ViewBox.py 47.6 KB
Newer Older
1
from pyqtgraph.Qt import QtGui, QtCore
Luke Campagnola's avatar
Luke Campagnola committed
2
from pyqtgraph.python2_3 import sortList
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import numpy as np
from pyqtgraph.Point import Point
import pyqtgraph.functions as fn
from .. ItemGroup import ItemGroup
from .. GraphicsWidget import GraphicsWidget
from pyqtgraph.GraphicsScene import GraphicsScene
import pyqtgraph
import weakref
from copy import deepcopy

__all__ = ['ViewBox']


class ChildGroup(ItemGroup):
    
    sigItemsChanged = QtCore.Signal()
    
    def itemChange(self, change, value):
        ret = ItemGroup.itemChange(self, change, value)
        if change == self.ItemChildAddedChange or change == self.ItemChildRemovedChange:
            self.sigItemsChanged.emit()
        
        return ret


class ViewBox(GraphicsWidget):
    """
Luke Campagnola's avatar
Luke Campagnola committed
30
31
    **Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>`
    
32
    Box that allows internal scaling/panning of children by mouse drag. 
Luke Campagnola's avatar
Luke Campagnola committed
33
34
35
36
37
38
39
40
41
    This class is usually created automatically as part of a :class:`PlotItem <pyqtgraph.PlotItem>` or :class:`Canvas <pyqtgraph.canvas.Canvas>` or with :func:`GraphicsLayout.addViewBox() <pyqtgraph.GraphicsLayout.addViewBox>`.
    
    Features:
    
        - Scaling contents by mouse or auto-scale when contents change
        - View linking--multiple views display the same data ranges
        - Configurable by context menu
        - Item coordinate mapping methods
    
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    Not really compatible with GraphicsView having the same functionality.
    """
    
    sigYRangeChanged = QtCore.Signal(object, object)
    sigXRangeChanged = QtCore.Signal(object, object)
    sigRangeChangedManually = QtCore.Signal(object)
    sigRangeChanged = QtCore.Signal(object, object)
    #sigActionPositionChanged = QtCore.Signal(object)
    sigStateChanged = QtCore.Signal(object)
    
    ## mouse modes
    PanMode = 3
    RectMode = 1
    
    ## axes
    XAxis = 0
    YAxis = 1
    XYAxes = 2
    
    ## for linking views together
    NamedViews = weakref.WeakValueDictionary()   # name: ViewBox
    AllViews = weakref.WeakKeyDictionary()       # ViewBox: None
    
65
    def __init__(self, parent=None, border=None, lockAspect=False, enableMouse=True, invertY=False, enableMenu=True, name=None):
Luke Campagnola's avatar
Luke Campagnola committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        """
        =============  =============================================================
        **Arguments**
        *parent*       (QGraphicsWidget) Optional parent widget
        *border*       (QPen) Do draw a border around the view, give any 
                       single argument accepted by :func:`mkPen <pyqtgraph.mkPen>`
        *lockAspect*   (False or float) The aspect ratio to lock the view 
                       coorinates to. (or False to allow the ratio to change)
        *enableMouse*  (bool) Whether mouse can be used to scale/pan the view 
        *invertY*      (bool) See :func:`invertY <pyqtgraph.ViewBox.invertY>`
        =============  =============================================================
        """
        
        
        
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
        GraphicsWidget.__init__(self, parent)
        self.name = None
        self.linksBlocked = False
        self.addedItems = []
        #self.gView = view
        #self.showGrid = showGrid
        
        self.state = {
            
            ## separating targetRange and viewRange allows the view to be resized
            ## while keeping all previously viewed contents visible
            'targetRange': [[0,1], [0,1]],   ## child coord. range visible [[xmin, xmax], [ymin, ymax]]
            'viewRange': [[0,1], [0,1]],     ## actual range viewed
        
            'yInverted': invertY,
            'aspectLocked': False,    ## False if aspect is unlocked, otherwise float specifies the locked ratio.
            'autoRange': [True, True],  ## False if auto range is disabled, 
                                          ## otherwise float gives the fraction of data that is visible
99
100
            'autoPan': [False, False],         ## whether to only pan (do not change scaling) when auto-range is enabled
            'autoVisibleOnly': [False, False], ## whether to auto-range only to the visible portion of a plot 
101
102
            'linkedViews': [None, None],  ## may be None, "viewName", or weakref.ref(view)
                                          ## a name string indicates that the view *should* link to another, but no view with that name exists yet.
103
104
105
            
            'mouseEnabled': [enableMouse, enableMouse],
            'mouseMode': ViewBox.PanMode if pyqtgraph.getConfigOption('leftButtonPan') else ViewBox.RectMode,  
106
            'enableMenu': enableMenu,
107
            'wheelScaleFactor': -1.0 / 8.0,
108
109

            'background': None,
110
111
112
113
114
115
116
        }
        
        
        self.setFlag(self.ItemClipsChildrenToShape)
        self.setFlag(self.ItemIsFocusable, True)  ## so we can receive key presses
        
        ## childGroup is required so that ViewBox has local coordinates similar to device coordinates.
117
        ## this is a workaround for a Qt + OpenGL bug that causes improper clipping
118
119
120
121
        ## https://bugreports.qt.nokia.com/browse/QTBUG-23723
        self.childGroup = ChildGroup(self)
        self.childGroup.sigItemsChanged.connect(self.itemsChanged)
        
122
123
124
125
126
127
        self.background = QtGui.QGraphicsRectItem(self.rect())
        self.background.setParentItem(self)
        self.background.setZValue(-1e6)
        self.background.setPen(fn.mkPen(None))
        self.updateBackground()
        
128
129
130
131
132
        #self.useLeftButtonPan = pyqtgraph.getConfigOption('leftButtonPan') # normally use left button to pan
        # this also enables capture of keyPressEvents.
        
        ## Make scale box that is shown when dragging on the view
        self.rbScaleBox = QtGui.QGraphicsRectItem(0, 0, 1, 1)
133
        self.rbScaleBox.setPen(fn.mkPen((255,255,100), width=1))
134
135
        self.rbScaleBox.setBrush(fn.mkBrush(255,255,0,100))
        self.rbScaleBox.hide()
136
        self.addItem(self.rbScaleBox)
137
138
139
140
141
142
143
144
145
        
        self.axHistory = [] # maintain a history of zoom locations
        self.axHistoryPointer = -1 # pointer into the history. Allows forward/backward movement, not just "undo"
        
        self.setZValue(-100)
        self.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding))
        
        self.setAspectLocked(lockAspect)
        
Luke Campagnola's avatar
Luke Campagnola committed
146
        self.border = fn.mkPen(border)
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        self.menu = ViewBoxMenu(self)
        
        self.register(name)
        if name is None:
            self.updateViewLists()
        
    def register(self, name):
        """
        Add this ViewBox to the registered list of views. 
        *name* will appear in the drop-down lists for axis linking in all other views.
        The same can be accomplished by initializing the ViewBox with the *name* attribute.
        """
        ViewBox.AllViews[self] = None
        if self.name is not None:
            del ViewBox.NamedViews[self.name]
        self.name = name
        if name is not None:
            ViewBox.NamedViews[name] = self
            ViewBox.updateAllViewLists()
Luke Campagnola's avatar
Luke Campagnola committed
166
            sid = id(self)
167
            self.destroyed.connect(lambda: ViewBox.forgetView(sid, name) if ViewBox is not None else None)
168
            #self.destroyed.connect(self.unregister)
169
170

    def unregister(self):
Luke Campagnola's avatar
Luke Campagnola committed
171
172
173
        """
        Remove this ViewBox forom the list of linkable views. (see :func:`register() <pyqtgraph.ViewBox.register>`)
        """
174
175
176
177
178
179
180
181
182
183
184
185
        del ViewBox.AllViews[self]
        if self.name is not None:
            del ViewBox.NamedViews[self.name]

    def close(self):
        self.unregister()

    def implements(self, interface):
        return interface == 'ViewBox'
        
        
    def getState(self, copy=True):
186
187
        """Return the current state of the ViewBox. 
        Linked views are always converted to view names in the returned state."""
188
        state = self.state.copy()
189
190
191
192
193
194
195
196
197
        views = []
        for v in state['linkedViews']:
            if isinstance(v, weakref.ref):
                v = v()
            if v is None or isinstance(v, basestring):
                views.append(v)
            else:
                views.append(v.name)
        state['linkedViews'] = views
198
        if copy:
199
            return deepcopy(state)
200
        else:
201
            return state
202
203
        
    def setState(self, state):
204
205
        """Restore the state of this ViewBox.
        (see also getState)"""
206
207
208
209
210
211
212
213
214
215
216
        state = state.copy()
        self.setXLink(state['linkedViews'][0])
        self.setYLink(state['linkedViews'][1])
        del state['linkedViews']
        
        self.state.update(state)
        self.updateMatrix()
        self.sigStateChanged.emit(self)


    def setMouseMode(self, mode):
Luke Campagnola's avatar
Luke Campagnola committed
217
218
219
220
221
        """
        Set the mouse interaction mode. *mode* must be either ViewBox.PanMode or ViewBox.RectMode.
        In PanMode, the left mouse button pans the view and the right button scales.
        In RectMode, the left button draws a rectangle which updates the visible region (this mode is more suitable for single-button mice)
        """
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
        if mode not in [ViewBox.PanMode, ViewBox.RectMode]:
            raise Exception("Mode must be ViewBox.PanMode or ViewBox.RectMode")
        self.state['mouseMode'] = mode
        self.sigStateChanged.emit(self)

    #def toggleLeftAction(self, act):  ## for backward compatibility
        #if act.text() is 'pan':
            #self.setLeftButtonAction('pan')
        #elif act.text() is 'zoom':
            #self.setLeftButtonAction('rect')

    def setLeftButtonAction(self, mode='rect'):  ## for backward compatibility
        if mode.lower() == 'rect':
            self.setMouseMode(ViewBox.RectMode)
        elif mode.lower() == 'pan':
            self.setMouseMode(ViewBox.PanMode)
        else:
            raise Exception('graphicsItems:ViewBox:setLeftButtonAction: unknown mode = %s (Options are "pan" and "rect")' % mode)
            
    def innerSceneItem(self):
        return self.childGroup
    
    def setMouseEnabled(self, x=None, y=None):
Luke Campagnola's avatar
Luke Campagnola committed
245
246
247
248
        """
        Set whether each axis is enabled for mouse interaction. *x*, *y* arguments must be True or False.
        This allows the user to pan/scale one axis of the view while leaving the other axis unchanged.
        """
249
250
251
252
253
254
255
256
        if x is not None:
            self.state['mouseEnabled'][0] = x
        if y is not None:
            self.state['mouseEnabled'][1] = y
        self.sigStateChanged.emit(self)
            
    def mouseEnabled(self):
        return self.state['mouseEnabled'][:]
257
258
259
260
261
262
263
        
    def setMenuEnabled(self, enableMenu=True):
        self.state['enableMenu'] = enableMenu
        self.sigStateChanged.emit(self)

    def menuEnabled(self):
        return self.state.get('enableMenu', True)       
264
    
265
    def addItem(self, item, ignoreBounds=False):
Luke Campagnola's avatar
Luke Campagnola committed
266
267
268
269
        """
        Add a QGraphicsItem to this view. The view will include this item when determining how to set its range
        automatically unless *ignoreBounds* is True.
        """
270
271
272
        if item.zValue() < self.zValue():
            item.setZValue(self.zValue()+1)
        item.setParentItem(self.childGroup)
273
274
        if not ignoreBounds:
            self.addedItems.append(item)
275
276
277
278
        self.updateAutoRange()
        #print "addItem:", item, item.boundingRect()
        
    def removeItem(self, item):
Luke Campagnola's avatar
Luke Campagnola committed
279
        """Remove an item from this view."""
Luke Campagnola's avatar
Luke Campagnola committed
280
281
282
283
        try:
            self.addedItems.remove(item)
        except:
            pass
284
285
286
287
288
        self.scene().removeItem(item)
        self.updateAutoRange()

    def resizeEvent(self, ev):
        #self.setRange(self.range, padding=0)
Luke Campagnola's avatar
Luke Campagnola committed
289
        #self.updateAutoRange()
290
291
        self.updateMatrix()
        self.sigStateChanged.emit(self)
292
        self.background.setRect(self.rect())
293
294
        #self.linkedXChanged()
        #self.linkedYChanged()
295
296
        
    def viewRange(self):
Luke Campagnola's avatar
Luke Campagnola committed
297
        """Return a the view's visible range as a list: [[xmin, xmax], [ymin, ymax]]"""
298
299
300
301
302
303
304
305
306
        return [x[:] for x in self.state['viewRange']]  ## return copy

    def viewRect(self):
        """Return a QRectF bounding the region visible within the ViewBox"""
        try:
            vr0 = self.state['viewRange'][0]
            vr1 = self.state['viewRange'][1]
            return QtCore.QRectF(vr0[0], vr1[0], vr0[1]-vr0[0], vr1[1] - vr1[0])
        except:
307
            print("make qrectf failed:", self.state['viewRange'])
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
            raise
    
    #def viewportTransform(self):
        ##return self.itemTransform(self.childGroup)[0]
        #return self.childGroup.itemTransform(self)[0]
    
    def targetRange(self):
        return [x[:] for x in self.state['targetRange']]  ## return copy
    
    def targetRect(self):  
        """
        Return the region which has been requested to be visible. 
        (this is not necessarily the same as the region that is *actually* visible--
        resizing and aspect ratio constraints can cause targetRect() and viewRect() to differ)
        """
        try:
            tr0 = self.state['targetRange'][0]
            tr1 = self.state['targetRange'][1]
            return QtCore.QRectF(tr0[0], tr1[0], tr0[1]-tr0[0], tr1[1] - tr1[0])
        except:
328
            print("make qrectf failed:", self.state['targetRange'])
329
330
331
332
333
334
335
            raise

    def setRange(self, rect=None, xRange=None, yRange=None, padding=0.02, update=True, disableAutoRange=True):
        """
        Set the visible range of the ViewBox.
        Must specify at least one of *range*, *xRange*, or *yRange*. 
        
Luke Campagnola's avatar
Luke Campagnola committed
336
337
338
339
340
341
342
343
        ============= =====================================================================
        **Arguments**
        *rect*        (QRectF) The full range that should be visible in the view box.
        *xRange*      (min,max) The range that should be visible along the x-axis.
        *yRange*      (min,max) The range that should be visible along the y-axis.
        *padding*     (float) Expand the view by a fraction of the requested range. 
                      By default, this value is 0.02 (2%)
        ============= =====================================================================
344
345
346
347
348
349
350
351
352
353
354
355
        
        """
        changes = {}
        
        if rect is not None:
            changes = {0: [rect.left(), rect.right()], 1: [rect.top(), rect.bottom()]}
        if xRange is not None:
            changes[0] = xRange
        if yRange is not None:
            changes[1] = yRange

        if len(changes) == 0:
356
            print(rect)
Luke Campagnola's avatar
Luke Campagnola committed
357
            raise Exception("Must specify at least one of rect, xRange, or yRange. (gave rect=%s)" % str(type(rect)))
358
359
        
        changed = [False, False]
360
        for ax, range in changes.items():
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
            mn = min(range)
            mx = max(range)
            if mn == mx:   ## If we requested 0 range, try to preserve previous scale. Otherwise just pick an arbitrary scale.
                dy = self.state['viewRange'][ax][1] - self.state['viewRange'][ax][0]
                if dy == 0:
                    dy = 1
                mn -= dy*0.5
                mx += dy*0.5
                padding = 0.0
            if any(np.isnan([mn, mx])) or any(np.isinf([mn, mx])):
                raise Exception("Not setting range [%s, %s]" % (str(mn), str(mx)))
                
            p = (mx-mn) * padding
            mn -= p
            mx += p
            
            if self.state['targetRange'][ax] != [mn, mx]:
                self.state['targetRange'][ax] = [mn, mx]
                changed[ax] = True
            
        if any(changed) and disableAutoRange:
            if all(changed):
                ax = ViewBox.XYAxes
            elif changed[0]:
                ax = ViewBox.XAxis
            elif changed[1]:
                ax = ViewBox.YAxis
            self.enableAutoRange(ax, False)
                
                
        self.sigStateChanged.emit(self)
        
        if update:
            self.updateMatrix(changed)
            
396
        for ax, range in changes.items():
397
            link = self.linkedView(ax)
398
399
400
            if link is not None:
                link.linkedViewChanged(self, ax)

401
402
403
404
        if changed[0] and self.state['autoVisibleOnly'][1]:
            self.updateAutoRange()
        elif changed[1] and self.state['autoVisibleOnly'][0]:
            self.updateAutoRange()
405
406
            
    def setYRange(self, min, max, padding=0.02, update=True):
Luke Campagnola's avatar
Luke Campagnola committed
407
408
409
410
        """
        Set the visible Y range of the view to [*min*, *max*]. 
        The *padding* argument causes the range to be set larger by the fraction specified.
        """
411
412
413
        self.setRange(yRange=[min, max], update=update, padding=padding)
        
    def setXRange(self, min, max, padding=0.02, update=True):
Luke Campagnola's avatar
Luke Campagnola committed
414
415
416
417
        """
        Set the visible X range of the view to [*min*, *max*]. 
        The *padding* argument causes the range to be set larger by the fraction specified.
        """
418
419
        self.setRange(xRange=[min, max], update=update, padding=padding)

Luke Campagnola's avatar
Luke Campagnola committed
420
    def autoRange(self, padding=0.02, item=None):
421
422
        """
        Set the range of the view box to make all children visible.
Luke Campagnola's avatar
Luke Campagnola committed
423
424
        Note that this is not the same as enableAutoRange, which causes the view to 
        automatically auto-range whenever its contents are changed.
425
        """
Luke Campagnola's avatar
Luke Campagnola committed
426
427
428
429
430
        if item is None:
            bounds = self.childrenBoundingRect()
        else:
            bounds = self.mapFromItemToView(item, item.boundingRect()).boundingRect()
            
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
        if bounds is not None:
            self.setRange(bounds, padding=padding)
            
            
    def scaleBy(self, s, center=None):
        """
        Scale by *s* around given center point (or center of view).
        *s* may be a Point or tuple (x, y)
        """
        scale = Point(s)
        if self.state['aspectLocked'] is not False:
            scale[0] = self.state['aspectLocked'] * scale[1]

        vr = self.targetRect()
        if center is None:
            center = Point(vr.center())
        else:
            center = Point(center)
        tl = center + (vr.topLeft()-center) * scale
        br = center + (vr.bottomRight()-center) * scale
        self.setRange(QtCore.QRectF(tl, br), padding=0)
        
    def translateBy(self, t):
        """
        Translate the view by *t*, which may be a Point or tuple (x, y).
        """
        t = Point(t)
        #if viewCoords:  ## scale from pixels
            #o = self.mapToView(Point(0,0))
            #t = self.mapToView(t) - o
        
        vr = self.targetRect()
        self.setRange(vr.translated(t), padding=0)
        
    def enableAutoRange(self, axis=None, enable=True):
        """
Luke Campagnola's avatar
Luke Campagnola committed
467
468
        Enable (or disable) auto-range for *axis*, which may be ViewBox.XAxis, ViewBox.YAxis, or ViewBox.XYAxes for both
        (if *axis* is omitted, both axes will be changed).
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
        When enabled, the axis will automatically rescale when items are added/removed or change their shape.
        The argument *enable* may optionally be a float (0.0-1.0) which indicates the fraction of the data that should
        be visible (this only works with items implementing a dataRange method, such as PlotDataItem).
        """
        #print "autorange:", axis, enable
        #if not enable:
            #import traceback
            #traceback.print_stack()
        if enable is True:
            enable = 1.0
        
        if axis is None:
            axis = ViewBox.XYAxes
        
        if axis == ViewBox.XYAxes or axis == 'xy':
            self.state['autoRange'][0] = enable
            self.state['autoRange'][1] = enable
        elif axis == ViewBox.XAxis or axis == 'x':
            self.state['autoRange'][0] = enable
        elif axis == ViewBox.YAxis or axis == 'y':
            self.state['autoRange'][1] = enable
        else:
            raise Exception('axis argument must be ViewBox.XAxis, ViewBox.YAxis, or ViewBox.XYAxes.')
        
        if enable:
            self.updateAutoRange()
        self.sigStateChanged.emit(self)

    def disableAutoRange(self, axis=None):
Luke Campagnola's avatar
Luke Campagnola committed
498
        """Disables auto-range. (See enableAutoRange)"""
499
500
501
502
503
        self.enableAutoRange(axis, enable=False)

    def autoRangeEnabled(self):
        return self.state['autoRange'][:]

504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
    def setAutoPan(self, x=None, y=None):
        if x is not None:
            self.state['autoPan'][0] = x
        if y is not None:
            self.state['autoPan'][1] = y
        if None not in [x,y]:
            self.updateAutoRange()

    def setAutoVisible(self, x=None, y=None):
        if x is not None:
            self.state['autoVisibleOnly'][0] = x
            if x is True:
                self.state['autoVisibleOnly'][1] = False
        if y is not None:
            self.state['autoVisibleOnly'][1] = y
            if y is True:
                self.state['autoVisibleOnly'][0] = False
        
        if x is not None or y is not None:
            self.updateAutoRange()

525
    def updateAutoRange(self):
526
        targetRect = self.viewRange()
527
528
529
530
531
532
533
        if not any(self.state['autoRange']):
            return
            
        fractionVisible = self.state['autoRange'][:]
        for i in [0,1]:
            if type(fractionVisible[i]) is bool:
                fractionVisible[i] = 1.0
534

535
        childRange = None
536
537
538
539
540

        order = [0,1]
        if self.state['autoVisibleOnly'][0] is True:
            order = [1,0]

541
        args = {}
542
543
544
545
546
547
        for ax in order:
            if self.state['autoRange'][ax] is False:
                continue
            if self.state['autoVisibleOnly'][ax]:
                oRange = [None, None]
                oRange[ax] = targetRect[1-ax]
548
                childRange = self.childrenBounds(frac=fractionVisible, orthoRange=oRange)
549
550
                
            else:
551
552
553
554
555
556
                if childRange is None:
                    childRange = self.childrenBounds(frac=fractionVisible)
            
            ## Make corrections to range
            xr = childRange[ax]
            if xr is not None:
557
                if self.state['autoPan'][0]:
558
559
                    x = sum(xr) * 0.5
                    #x = childRect.center().x()
560
                    w2 = (targetRect[0][1]-targetRect[0][0]) / 2.
561
562
563
                    #childRect.setLeft(x-w2)
                    #childRect.setRight(x+w2)
                    childRange[ax] = [x-w2, x+w2]
564
                else:
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
                    #wp = childRect.width() * 0.02
                    wp = (xr[1] - xr[0]) * 0.02
                    #childRect = childRect.adjusted(-wp, 0, wp, 0)
                    childRange[ax][0] -= wp
                    childRange[ax][1] += wp
                #targetRect[ax][0] = childRect.left()
                #targetRect[ax][1] = childRect.right()
                targetRect[ax] = childRange[ax]
                args['xRange' if ax == 0 else 'yRange'] = targetRect[ax]
            #else:
                ### Make corrections to Y range
                #if self.state['autoPan'][1]:
                    #y = childRect.center().y()
                    #h2 = (targetRect[1][1]-targetRect[1][0]) / 2.
                    #childRect.setTop(y-h2)
                    #childRect.setBottom(y+h2)
                #else:
                    #hp = childRect.height() * 0.02
                    #childRect = childRect.adjusted(0, -hp, 0, hp)
584
                    
585
586
587
588
589
                #targetRect[1][0] = childRect.top()
                #targetRect[1][1] = childRect.bottom()
                #args['yRange'] = targetRect[1]
        if len(args) == 0:
            return
590
591
592
593
        args['padding'] = 0
        args['disableAutoRange'] = False
        #self.setRange(xRange=targetRect[0], yRange=targetRect[1], padding=0, disableAutoRange=False)
        self.setRange(**args)
594
595
        
    def setXLink(self, view):
Luke Campagnola's avatar
Luke Campagnola committed
596
        """Link this view's X axis to another view. (see LinkView)"""
597
598
599
        self.linkView(self.XAxis, view)
        
    def setYLink(self, view):
Luke Campagnola's avatar
Luke Campagnola committed
600
        """Link this view's Y axis to another view. (see LinkView)"""
601
602
603
604
605
606
607
608
609
610
611
612
        self.linkView(self.YAxis, view)
        
        
    def linkView(self, axis, view):
        """
        Link X or Y axes of two views and unlink any previously connected axes. *axis* must be ViewBox.XAxis or ViewBox.YAxis.
        If view is None, the axis is left unlinked.
        """
        if isinstance(view, basestring):
            if view == '':
                view = None
            else:
613
                view = ViewBox.NamedViews.get(view, view)  ## convert view name to ViewBox if possible
614
615
616
617
618
619
620
621
622
623
624
625
626

        if hasattr(view, 'implements') and view.implements('ViewBoxWrapper'):
            view = view.getViewBox()

        ## used to connect/disconnect signals between a pair of views
        if axis == ViewBox.XAxis:
            signal = 'sigXRangeChanged'
            slot = self.linkedXChanged
        else:
            signal = 'sigYRangeChanged'
            slot = self.linkedYChanged


627
        oldLink = self.linkedView(axis)
628
        if oldLink is not None:
629
630
631
632
633
            try:
                getattr(oldLink, signal).disconnect(slot)
            except TypeError:
                ## This can occur if the view has been deleted already
                pass
634
635
            
        
636
637
638
639
        if view is None or isinstance(view, basestring):
            self.state['linkedViews'][axis] = view
        else:
            self.state['linkedViews'][axis] = weakref.ref(view)
640
            getattr(view, signal).connect(slot)
641
            if view.autoRangeEnabled()[axis] is not False:
642
643
644
645
646
647
648
649
650
651
652
653
                self.enableAutoRange(axis, False)
                slot()
            else:
                if self.autoRangeEnabled()[axis] is False:
                    slot()
            
        self.sigStateChanged.emit(self)
        
    def blockLink(self, b):
        self.linksBlocked = b  ## prevents recursive plot-change propagation

    def linkedXChanged(self):
654
        ## called when x range of linked view has changed
655
        view = self.linkedView(0)
656
657
658
        self.linkedViewChanged(view, ViewBox.XAxis)

    def linkedYChanged(self):
659
        ## called when y range of linked view has changed
660
        view = self.linkedView(1)
661
662
        self.linkedViewChanged(view, ViewBox.YAxis)
        
663
664
665
666
667
668
669
670
    def linkedView(self, ax):
        ## Return the linked view for axis *ax*.
        ## this method _always_ returns either a ViewBox or None.
        v = self.state['linkedViews'][ax]
        if v is None or isinstance(v, basestring):
            return None
        else:
            return v()  ## dereference weakref pointer. If the reference is dead, this returns None
671
672

    def linkedViewChanged(self, view, axis):
673
        if self.linksBlocked or view is None:
674
675
676
677
678
            return
        
        vr = view.viewRect()
        vg = view.screenGeometry()
        sg = self.screenGeometry()
679
680
        if vg is None or sg is None:
            return
681
682
683
684
        
        view.blockLink(True)
        try:
            if axis == ViewBox.XAxis:
685
686
687
688
689
690
691
692
693
                overlap = min(sg.right(), vg.right()) - max(sg.left(), vg.left())
                if overlap < min(vg.width()/3, sg.width()/3):  ## if less than 1/3 of views overlap, 
                                                               ## then just replicate the view
                    x1 = vr.left()
                    x2 = vr.right()
                else:  ## views overlap; line them up
                    upp = float(vr.width()) / vg.width()
                    x1 = vr.left() + (sg.x()-vg.x()) * upp
                    x2 = x1 + sg.width() * upp
694
695
696
                self.enableAutoRange(ViewBox.XAxis, False)
                self.setXRange(x1, x2, padding=0)
            else:
697
698
699
                overlap = min(sg.bottom(), vg.bottom()) - max(sg.top(), vg.top())
                if overlap < min(vg.height()/3, sg.height()/3):  ## if less than 1/3 of views overlap, 
                                                               ## then just replicate the view
700
701
                    y1 = vr.top()
                    y2 = vr.bottom()
702
703
                else:  ## views overlap; line them up
                    upp = float(vr.height()) / vg.height()
704
705
                    y2 = vr.bottom() - (sg.y()-vg.y()) * upp
                    y1 = y2 - sg.height() * upp
706
                self.enableAutoRange(ViewBox.YAxis, False)
707
                self.setYRange(y1, y2, padding=0)
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
        finally:
            view.blockLink(False)
        
        
    def screenGeometry(self):
        """return the screen geometry of the viewbox"""
        v = self.getViewWidget()
        if v is None:
            return None
        b = self.sceneBoundingRect()
        wr = v.mapFromScene(b).boundingRect()
        pos = v.mapToGlobal(v.pos())
        wr.adjust(pos.x(), pos.y(), pos.x(), pos.y())
        return wr
        
    

    def itemsChanged(self):
        ## called when items are added/removed from self.childGroup
        self.updateAutoRange()
        
    def itemBoundsChanged(self, item):
        self.updateAutoRange()

    def invertY(self, b=True):
        """
        By default, the positive y-axis points upward on the screen. Use invertY(True) to reverse the y-axis.
        """
        self.state['yInverted'] = b
737
        self.updateMatrix(changed=(False, True))
738
        self.sigStateChanged.emit(self)
739
740
741

    def yInverted(self):
        return self.state['yInverted']
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
        
    def setAspectLocked(self, lock=True, ratio=1):
        """
        If the aspect ratio is locked, view scaling must always preserve the aspect ratio.
        By default, the ratio is set to 1; x and y both have the same scaling.
        This ratio can be overridden (width/height), or use None to lock in the current ratio.
        """
        if not lock:
            self.state['aspectLocked'] = False
        else:
            vr = self.viewRect()
            currentRatio = vr.width() / vr.height()
            if ratio is None:
                ratio = currentRatio
            self.state['aspectLocked'] = ratio
            if ratio != currentRatio:  ## If this would change the current range, do that now
                #self.setRange(0, self.state['viewRange'][0][0], self.state['viewRange'][0][1])
                self.updateMatrix()
        self.sigStateChanged.emit(self)
        
    def childTransform(self):
        """
        Return the transform that maps from child(item in the childGroup) coordinates to local coordinates.
        (This maps from inside the viewbox to outside)
        """ 
        m = self.childGroup.transform()
        #m1 = QtGui.QTransform()
        #m1.translate(self.childGroup.pos().x(), self.childGroup.pos().y())
        return m #*m1

    def mapToView(self, obj):
        """Maps from the local coordinates of the ViewBox to the coordinate system displayed inside the ViewBox"""
Luke Campagnola's avatar
Luke Campagnola committed
774
        m = fn.invertQTransform(self.childTransform())
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
        return m.map(obj)

    def mapFromView(self, obj):
        """Maps from the coordinate system displayed inside the ViewBox to the local coordinates of the ViewBox"""
        m = self.childTransform()
        return m.map(obj)

    def mapSceneToView(self, obj):
        """Maps from scene coordinates to the coordinate system displayed inside the ViewBox"""
        return self.mapToView(self.mapFromScene(obj))

    def mapViewToScene(self, obj):
        """Maps from the coordinate system displayed inside the ViewBox to scene coordinates"""
        return self.mapToScene(self.mapFromView(obj))
    
    def mapFromItemToView(self, item, obj):
Luke Campagnola's avatar
Luke Campagnola committed
791
        """Maps *obj* from the local coordinate system of *item* to the view coordinates"""
Luke Campagnola's avatar
Luke Campagnola committed
792
793
        return self.childGroup.mapFromItem(item, obj)
        #return self.mapSceneToView(item.mapToScene(obj))
794
795

    def mapFromViewToItem(self, item, obj):
Luke Campagnola's avatar
Luke Campagnola committed
796
        """Maps *obj* from view coordinates to the local coordinate system of *item*."""
Luke Campagnola's avatar
Luke Campagnola committed
797
798
        return self.childGroup.mapToItem(item, obj)
        #return item.mapFromScene(self.mapViewToScene(obj))
799

Luke Campagnola's avatar
Luke Campagnola committed
800
801
802
803
804
805
806
807
808
809
810
811
812
    def mapViewToDevice(self, obj):
        return self.mapToDevice(self.mapFromView(obj))
        
    def mapDeviceToView(self, obj):
        return self.mapToView(self.mapFromDevice(obj))
        
    def viewPixelSize(self):
        """Return the (width, height) of a screen pixel in view coordinates."""
        o = self.mapToView(Point(0,0))
        px, py = [Point(self.mapToView(v) - o) for v in self.pixelVectors()]
        return (px.length(), py.length())
        
        
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
    def itemBoundingRect(self, item):
        """Return the bounding rect of the item in view coordinates"""
        return self.mapSceneToView(item.sceneBoundingRect()).boundingRect()
    
    #def viewScale(self):
        #vr = self.viewRect()
        ##print "viewScale:", self.range
        #xd = vr.width()
        #yd = vr.height()
        #if xd == 0 or yd == 0:
            #print "Warning: 0 range in view:", xd, yd
            #return np.array([1,1])
        
        ##cs = self.canvas().size()
        #cs = self.boundingRect()
        #scale = np.array([cs.width() / xd, cs.height() / yd])
        ##print "view scale:", scale
        #return scale

    def wheelEvent(self, ev, axis=None):
        mask = np.array(self.state['mouseEnabled'], dtype=np.float)
        if axis is not None and axis >= 0 and axis < len(mask):
            mv = mask[axis]
            mask[:] = 0
            mask[axis] = mv
        s = ((mask * 0.02) + 1) ** (ev.delta() * self.state['wheelScaleFactor']) # actual scaling factor
        
Luke Campagnola's avatar
Luke Campagnola committed
840
        center = Point(fn.invertQTransform(self.childGroup.transform()).map(ev.pos()))
841
842
843
844
845
846
847
848
        #center = ev.pos()
        
        self.scaleBy(s, center)
        self.sigRangeChangedManually.emit(self.state['mouseEnabled'])
        ev.accept()

        
    def mouseClickEvent(self, ev):
849
        if ev.button() == QtCore.Qt.RightButton and self.menuEnabled():
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
            ev.accept()
            self.raiseContextMenu(ev)
    
    def raiseContextMenu(self, ev):
        #print "viewbox.raiseContextMenu called."
        
        #menu = self.getMenu(ev)
        menu = self.getMenu(ev)
        self.scene().addParentContextMenus(self, menu, ev)
        #print "2:", [str(a.text()) for a in self.menu.actions()]
        pos = ev.screenPos()
        #pos2 = ev.scenePos()
        #print "3:", [str(a.text()) for a in self.menu.actions()]
        #self.sigActionPositionChanged.emit(pos2)

        menu.popup(QtCore.QPoint(pos.x(), pos.y()))
        #print "4:", [str(a.text()) for a in self.menu.actions()]
        
    def getMenu(self, ev):
        self._menuCopy = self.menu.copy()  ## temporary storage to prevent menu disappearing
        return self._menuCopy
        
    def getContextMenus(self, event):
873
874
875
876
        if self.menuEnabled():
            return self.menu.subMenus()
        else:
            return None
877
878
879
        #return [self.getMenu(event)]
        

Luke Campagnola's avatar
Luke Campagnola committed
880
881
    def mouseDragEvent(self, ev, axis=None):
        ## if axis is specified, event will only affect that axis.
882
883
884
885
886
887
888
889
890
        ev.accept()  ## we accept all buttons
        
        pos = ev.pos()
        lastPos = ev.lastPos()
        dif = pos - lastPos
        dif = dif * -1

        ## Ignore axes if mouse is disabled
        mask = np.array(self.state['mouseEnabled'], dtype=np.float)
Luke Campagnola's avatar
Luke Campagnola committed
891
892
        if axis is not None:
            mask[1-axis] = 0.0
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922

        ## Scale or translate based on mouse button
        if ev.button() & (QtCore.Qt.LeftButton | QtCore.Qt.MidButton):
            if self.state['mouseMode'] == ViewBox.RectMode:
                if ev.isFinish():  ## This is the final move in the drag; change the view scale now
                    #print "finish"
                    self.rbScaleBox.hide()
                    #ax = QtCore.QRectF(Point(self.pressPos), Point(self.mousePos))
                    ax = QtCore.QRectF(Point(ev.buttonDownPos(ev.button())), Point(pos))
                    ax = self.childGroup.mapRectFromParent(ax)
                    self.showAxRect(ax)
                    self.axHistoryPointer += 1
                    self.axHistory = self.axHistory[:self.axHistoryPointer] + [ax]
                else:
                    ## update shape of scale box
                    self.updateScaleBox(ev.buttonDownPos(), ev.pos())
            else:
                tr = dif*mask
                tr = self.mapToView(tr) - self.mapToView(Point(0,0))
                self.translateBy(tr)
                self.sigRangeChangedManually.emit(self.state['mouseEnabled'])
        elif ev.button() & QtCore.Qt.RightButton:
            #print "vb.rightDrag"
            if self.state['aspectLocked'] is not False:
                mask[0] = 0
            
            dif = ev.screenPos() - ev.lastScreenPos()
            dif = np.array([dif.x(), dif.y()])
            dif[0] *= -1
            s = ((mask * 0.02) + 1) ** dif
Luke Campagnola's avatar
Luke Campagnola committed
923
924
925
926
927
            
            tr = self.childGroup.transform()
            tr = fn.invertQTransform(tr)
            
            center = Point(tr.map(ev.buttonDownPos(QtCore.Qt.RightButton)))
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
            self.scaleBy(s, center)
            self.sigRangeChangedManually.emit(self.state['mouseEnabled'])

    def keyPressEvent(self, ev):
        """
        This routine should capture key presses in the current view box.
        Key presses are used only when mouse mode is RectMode
        The following events are implemented:
        ctrl-A : zooms out to the default "full" view of the plot
        ctrl-+ : moves forward in the zooming stack (if it exists)
        ctrl-- : moves backward in the zooming stack (if it exists)
         
        """
        #print ev.key()
        #print 'I intercepted a key press, but did not accept it'
        
        ## not implemented yet ?
        #self.keypress.sigkeyPressEvent.emit()
        
        ev.accept()
        if ev.text() == '-':
            self.scaleHistory(-1)
        elif ev.text() in ['+', '=']:
            self.scaleHistory(1)
        elif ev.key() == QtCore.Qt.Key_Backspace:
            self.scaleHistory(len(self.axHistory))
        else:
            ev.ignore()

    def scaleHistory(self, d):
        ptr = max(0, min(len(self.axHistory)-1, self.axHistoryPointer+d))
        if ptr != self.axHistoryPointer:
            self.axHistoryPointer = ptr
            self.showAxRect(self.axHistory[ptr])
            

    def updateScaleBox(self, p1, p2):
        r = QtCore.QRectF(p1, p2)
        r = self.childGroup.mapRectFromParent(r)
        self.rbScaleBox.setPos(r.topLeft())
        self.rbScaleBox.resetTransform()
        self.rbScaleBox.scale(r.width(), r.height())
        self.rbScaleBox.show()

    def showAxRect(self, ax):
        self.setRange(ax.normalized()) # be sure w, h are correct coordinates
        self.sigRangeChangedManually.emit(self.state['mouseEnabled'])

    #def mouseRect(self):
        #vs = self.viewScale()
        #vr = self.state['viewRange']
        ## Convert positions from screen (view) pixel coordinates to axis coordinates 
        #ax = QtCore.QRectF(self.pressPos[0]/vs[0]+vr[0][0], -(self.pressPos[1]/vs[1]-vr[1][1]),
            #(self.mousePos[0]-self.pressPos[0])/vs[0], -(self.mousePos[1]-self.pressPos[1])/vs[1])
        #return(ax)

    def allChildren(self, item=None):
        """Return a list of all children and grandchildren of this ViewBox"""
        if item is None:
            item = self.childGroup
        
        children = [item]
        for ch in item.childItems():
            children.extend(self.allChildren(ch))
        return children
        
        
995
996
    
    def childrenBounds(self, frac=None, orthoRange=(None,None)):
997
998
999
1000
        """Return the bounding range of all children.
        [[xmin, xmax], [ymin, ymax]]
        Values may be None if there are no specific bounds for an axis.
        """