summaryrefslogtreecommitdiff
path: root/examples/blissPlot.py
blob: 71c1fd3034e02db4c643737b0593af2377334ac8 (plain)
1
2
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
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
467
468
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
# coding: utf-8


from __future__ import division, absolute_import, print_function, unicode_literals


import six

from silx.gui import qt, icons
from silx.gui.plot.actions import PlotAction, mode
from silx.gui.plot import PlotWindow, PlotWidget
from silx.gui.plot.Colors import rgba


class DrawModeAction(PlotAction):
    """Action that control drawing mode"""

    _MODES = {  # shape: (icon, text, tooltip
        'rectangle': ('shape-rectangle', 'Rectangle selection', 'Select a rectangular region'),
        'line': ('shape-diagonal', 'Line selection', 'Select a line'),
        'hline': ('shape-horizontal', 'H. line selection', 'Select a horizontal line'),
        'vline': ('shape-vertical', 'V. line selection', 'Select a vertical line'),
        'polygon': ('shape-polygon', 'Polygon selection', 'Select a polygon'),
    }

    def __init__(self, plot, parent=None):
        self._shape = 'polygon'
        self._label = None
        self._color = 'black'
        self._width = None
        icon, text, tooltip = self._MODES[self._shape]

        super(DrawModeAction, self).__init__(
            plot, icon=icon, text=text,
            tooltip=tooltip,
            triggered=self._actionTriggered,
            checkable=True, parent=parent)

        # Listen to mode change
        self.plot.sigInteractiveModeChanged.connect(self._modeChanged)
        # Init the state
        self._modeChanged(None)

    def _update(self):
        if self.isChecked():
            self._actionTriggered()

    def setShape(self, shape):
        self._shape = shape
        icon, text, tooltip = self._MODES[self._shape]
        self.setIcon(icons.getQIcon(icon))
        self.setText(text)
        self.setToolTip(tooltip)
        self._update()

    def getShape(self):
        return self._shape

    def setColor(self, color):
        self._color = rgba(color)
        self._update()

    def getColor(self):
        return qt.QColor.fromRgbF(*self._color)

    def setLabel(self, label):
        self._label = label
        self._update()

    def getLabel(self):
        return self._label

    def setWidth(self, width):
        self._width = width
        self._update()

    def getWidth(self):
        return self._width

    def _modeChanged(self, source):
        modeDict = self.plot.getInteractiveMode()
        old = self.blockSignals(True)
        self.setChecked(modeDict['mode'] == 'draw' and
                        modeDict['shape'] == self._shape and
                        modeDict['label'] == self._label)
        self.blockSignals(old)

    def _actionTriggered(self, checked=False):
        self.plot.setInteractiveMode('draw',
                                     source=self,
                                     shape=self._shape,
                                     color=self._color,
                                     label=self._label,
                                     width=self._width)


class ShapeSelector(qt.QObject):
    """Handles the selection of a single shape in a PlotWidget

    :param parent: QObject's parent
    """

    selectionChanged = qt.Signal(tuple)
    """Signal emitted whenever the selection has changed.
    
    It provides the selection.
    """

    selectionFinished = qt.Signal(tuple)
    """Signal emitted when selection is terminated.
    
    It provides the selection.
    """

    def __init__(self, parent=None):
        assert isinstance(parent, PlotWidget)
        super(ShapeSelector, self).__init__(parent)
        self._isSelectionRunning = False
        self._selection = ()
        self._itemId = "%s-%s" % (self.__class__.__name__, id(self))

        # Add a toolbar to plot
        self._toolbar = qt.QToolBar('Selection')
        self._modeAction = DrawModeAction(plot=parent)
        self._modeAction.setLabel(self._itemId)
        self._modeAction.setColor(rgba('red'))
        toolButton = qt.QToolButton()
        toolButton.setDefaultAction(self._modeAction)
        toolButton.setToolButtonStyle(qt.Qt.ToolButtonTextBesideIcon)
        self._toolbar.addWidget(toolButton)

    # Style

    def getColor(self):
        """Returns the color used for the selection shape

        :rtype: QColor
        """
        return self._modeAction.getColor()

    def setColor(self, color):
        """Set the color used for the selection shape

        :param color: The color to use for selection shape as
           either a color name, a QColor, a list of uint8 or float in [0, 1].
        """
        self._modeAction.setColor(color)
        self._updateShape()

    # Control selection

    def getSelection(self):
        """Returns selection control point coordinates

        Returns an empty tuple if there is no selection

        :return: Nx2 (x, y) coordinates or an empty tuple.
        """
        return tuple(zip(*self._selection))

    def _setSelection(self, x, y):
        """Set the selection shape control points.

        Use :meth:`reset` to remove the selection.

        :param x: X coordinates of control points
        :param y: Y coordinates of control points
        """
        selection = x, y
        if selection != self._selection:
            self._selection = selection
            self._updateShape()
            self.selectionChanged.emit(self.getSelection())

    def reset(self):
        """Clear the rectangle selection"""
        if self._selection:
            self._selection = ()
            self._updateShape()
            self.selectionChanged.emit(self.getSelection())

    def start(self, shape):
        """Start requiring user to select a rectangle

        :param str shape: The shape to select in:
            'rectangle', 'line', 'polygon', 'hline', 'vline'
        """
        plot = self.parent()
        if plot is None:
            raise RuntimeError('No plot to perform selection')

        self.stop()
        self.reset()

        assert shape in ('rectangle', 'line', 'polygon', 'hline', 'vline')

        self._modeAction.setShape(shape)
        self._modeAction.trigger()  # To set the interaction mode

        self._isSelectionRunning = True

        plot.sigPlotSignal.connect(self._handleDraw)

        self._toolbar.show()
        plot.addToolBar(qt.Qt.BottomToolBarArea, self._toolbar)

    def stop(self):
        """Stop shape selection"""
        if not self._isSelectionRunning:
            return

        plot = self.parent()
        if plot is None:
            return

        mode = plot.getInteractiveMode()
        if mode['mode'] == 'draw' and mode['label'] == self._itemId:
            plot.setInteractiveMode('zoom')  # This disconnects draw handler

        plot.sigPlotSignal.disconnect(self._handleDraw)

        plot.removeToolBar(self._toolbar)

        self._isSelectionRunning = False
        self.selectionFinished.emit(self.getSelection())

    def _handleDraw(self, event):
        """Handle shape drawing event"""
        if (event['event'] == 'drawingFinished' and
                event['parameters']['label'] == self._itemId):
            self._setSelection(event['xdata'], event['ydata'])
            self.stop()

    def _updateShape(self):
        """Update shape on the plot"""
        plot = self.parent()
        if plot is not None:
            if not self._selection:
                plot.remove(legend=self._itemId, kind='item')

            else:
                x, y = self._selection
                shape = self._modeAction.getShape()
                if shape == 'line':
                    shape = 'polylines'

                plot.addItem(x, y,
                             legend=self._itemId,
                             shape=shape,
                             color=rgba(self._modeAction.getColor()),
                             fill=False)



class PointsSelector(qt.QObject):
    """Handle selection of points in a PlotWidget"""

    selectionChanged = qt.Signal(tuple)
    """Signal emitted whenever the selection has changed.
    
    It provides the selection.
    """

    selectionFinished = qt.Signal(tuple)
    """Signal emitted when selection is terminated.
    
    It provides the selection.
    """


    def __init__(self, parent):
        assert isinstance(parent, PlotWidget)
        super(PointsSelector, self).__init__(parent)

        self._isSelectionRunning = False
        self._markersAndPos = []
        self._totalPoints = 0

    def getSelection(self):
        """Returns the selection"""
        return tuple(pos for _, pos in self._markersAndPos)

    def eventFilter(self, obj, event):
        """Event filter for plot hide and key event"""
        if event.type() == qt.QEvent.Hide:
            self.stop()

        elif event.type() == qt.QEvent.KeyPress:
            if event.key() in (qt.Qt.Key_Delete, qt.Qt.Key_Backspace) or (
                    event.key() == qt.Qt.Key_Z and event.modifiers() & qt.Qt.ControlModifier):
                if len(self._markersAndPos) > 0:
                    plot = self.parent()
                    if plot is not None:
                        legend, _ = self._markersAndPos.pop()
                        plot.remove(legend=legend, kind='marker')

                        self._updateStatusBar()
                        self.selectionChanged.emit(self.getSelection())
                        return True  # Stop further handling of those keys

            elif event.key() == qt.Qt.Key_Return:
                self.stop()
                return True  # Stop further handling of those keys

        return super(PointsSelector, self).eventFilter(obj, event)

    def start(self, nbPoints=1):
        """Start interactive selection of points

        :param int nbPoints: Number of points to select
        """
        self.stop()
        self.reset()

        plot = self.parent()
        if plot is None:
            raise RuntimeError('No plot to perform selection')

        self._totalPoints = nbPoints
        self._isSelectionRunning = True

        plot.setInteractiveMode(mode='zoom')
        self._handleInteractiveModeChanged(None)
        plot.sigInteractiveModeChanged.connect(
            self._handleInteractiveModeChanged)

        plot.installEventFilter(self)

        self._updateStatusBar()

    def stop(self):
        """Stop interactive point selection"""
        if not self._isSelectionRunning:
            return

        plot = self.parent()
        if plot is None:
            return

        plot.removeEventFilter(self)

        plot.sigInteractiveModeChanged.disconnect(
            self._handleInteractiveModeChanged)

        currentMode = plot.getInteractiveMode()
        if currentMode['mode'] == 'zoom':  # Stop handling mouse click
            plot.sigPlotSignal.disconnect(self._handleSelect)

        plot.statusBar().clearMessage()
        self._isSelectionRunning = False
        self.selectionFinished.emit(self.getSelection())

    def reset(self):
        """Reset selected points"""
        plot = self.parent()
        if plot is None:
            return

        for legend, _ in self._markersAndPos:
            plot.remove(legend=legend, kind='marker')
        self._markersAndPos = []
        self.selectionChanged.emit(self.getSelection())

    def _updateStatusBar(self):
        """Update status bar message"""
        plot = self.parent()
        if plot is None:
            return

        msg = 'Select %d/%d input points' % (len(self._markersAndPos),
                                             self._totalPoints)

        currentMode = plot.getInteractiveMode()
        if currentMode['mode'] != 'zoom':
            msg += ' (Use zoom mode to add/remove points)'

        plot.statusBar().showMessage(msg)

    def _handleSelect(self, event):
        """Handle mouse events"""
        if event['event'] == 'mouseClicked' and event['button'] == 'left':
            plot = self.parent()
            if plot is None:
                return

            x, y = event['x'], event['y']

            # Add marker
            legend = "sx.ginput %d" % len(self._markersAndPos)
            plot.addMarker(
                x, y,
                legend=legend,
                text='%d' % len(self._markersAndPos),
                color='red',
                draggable=False)

            self._markersAndPos.append((legend, (x, y)))
            self._updateStatusBar()
            if len(self._markersAndPos) >= self._totalPoints:
                self.stop()

    def _handleInteractiveModeChanged(self, source):
        """Handle change of interactive mode in the plot

        :param source: Objects that triggered the mode change
        """
        plot = self.parent()
        if plot is None:
            return

        mode = plot.getInteractiveMode()
        if mode['mode'] == 'zoom':  # Handle click events
            plot.sigPlotSignal.connect(self._handleSelect)
        else:  # Do not handle click event
            plot.sigPlotSignal.disconnect(self._handleSelect)
        self._updateStatusBar()


# TODO refactor to make a selection by composition rather than inheritance...
class BlissPlot(PlotWindow):
    """Plot with selection methods"""

    sigSelectionDone = qt.Signal(object)
    """Signal emitted when the selection is done
    
    It provides the list of selected points
    """

    def __init__(self, parent=None, **kwargs):
        super(BlissPlot, self).__init__(parent=parent, **kwargs)
        self._selectionColor = rgba('red')
        self._selectionMode = None
        self._markers = []
        self._pointNames = ()

    # Style

    def getColor(self):
        """Returns the color used for selection markers

        :rtype: QColor
        """
        return qt.QColor.fromRgbF(*self._selectionColor)

    def setColor(self, color):
        """Set the markers used for selection

        :param color: The color to use for selection markers as
           either a color name, a QColor, a list of uint8 or float in [0, 1].
        """
        self._selectionColor = rgba(color)
        self._updateMarkers()  # To apply color change

    # Marker helpers

    def _setSelectedPointMarker(self, x, y, index=None):
        """Add/Update a marker for a point

        :param float x: X coord in plot
        :param float y: Y coord in plot
        :param int index: Index of point in points names to set
        :return: corresponding marker legend
        :rtype: str
        """
        if index is None:
            index = len(self._markers)

        name = self._pointNames[index]
        legend = "BlissPlotSelection-%d" % index

        self.addMarker(
            x, y,
            legend=legend,
            text=name,
            color=self._selectionColor,
            draggable=self._selectionMode is not None)
        return legend

    def _updateMarkers(self):
        """Update all markers to sync color/draggable"""
        for index, (x, y) in enumerate(self.getSelectedPoints()):
            self._setSelectedPointMarker(x, y, index)

    # Selection mode control

    def startPointSelection(self, points=1):
        """Request the user to select a number of points

        :param points:
            The number of points the user need to select (default: 1)
            or a list of point names or a single name.
        :type points: Union[int, List[str], str]
        :return: A future to access the result
        :rtype: concurrent.futures.Future
        """
        self.stopSelection()
        self.resetSelection()

        if isinstance(points, six.string_types):
            points = [points]
        elif isinstance(points, int):
            points = [str(i) for i in range(points)]

        self._pointNames = points

        self._markers = []
        self._selectionMode = 'points'

        self.setInteractiveMode(mode='zoom')
        self._handleInteractiveModeChanged(None)
        self.sigInteractiveModeChanged.connect(
            self._handleInteractiveModeChanged)

    def stopSelection(self):
        """Stop current selection.

        Calling this method emits the selection through sigSelectionDone
        and does not clear the selection.
        """
        if self._selectionMode is not None:
            currentMode = self.getInteractiveMode()
            if currentMode['mode'] == 'zoom':  # Stop handling mouse click
                self.sigPlotSignal.disconnect(self._handleSelect)

            self.sigInteractiveModeChanged.disconnect(
                self._handleInteractiveModeChanged)

            self._selectionMode = None
            self.statusBar().showMessage('Selection done')

            self._updateMarkers()  # To make them not draggable

            self.sigSelectionDone.emit(self.getSelectedPoints())

    def getSelectedPoints(self):
        """Returns list of currently selected points

        :rtype: tuple
        """
        return tuple(self._getItem(kind='marker', legend=legend).getPosition()
                     for legend in self._markers)

    def resetSelection(self):
        """Clear current selection"""
        for legend in self._markers:
            self.remove(legend, kind='marker')
        self._markers = []

        if self._selectionMode is not None:
            self._updateStatusBar()
        else:
            self.statusBar().clearMessage()

    def _handleInteractiveModeChanged(self, source):
        """Handle change of interactive mode in the plot

        :param source: Objects that triggered the mode change
        """
        mode = self.getInteractiveMode()
        if mode['mode'] == 'zoom':  # Handle click events
            self.sigPlotSignal.connect(self._handleSelect)
        else:  # Do not handle click event
            self.sigPlotSignal.disconnect(self._handleSelect)
        self._updateStatusBar()

    def _handleSelect(self, event):
        """Handle mouse events"""
        if event['event'] == 'mouseClicked' and event['button'] == 'left':
            if len(self._markers) == len(self._pointNames):
                return

            x, y = event['x'], event['y']
            legend = self._setSelectedPointMarker(x, y, len(self._markers))
            self._markers.append(legend)
            self._updateStatusBar()

    def keyPressEvent(self, event):
        """Handle keys for undo/done actions"""
        if self._selectionMode is not None:
            if event.key() in (qt.Qt.Key_Delete, qt.Qt.Key_Backspace) or (
                    event.key() == qt.Qt.Key_Z and
                    event.modifiers() & qt.Qt.ControlModifier):
                if len(self._markers) > 0:
                    legend = self._markers.pop()
                    self.remove(legend, kind='marker')

                    self._updateStatusBar()
                    return  # Stop processing the event

            elif event.key() == qt.Qt.Key_Return:
                self.stopSelection()
                return  # Stop processing the event

        return super(BlissPlot, self).keyPressEvent(event)

    def _updateStatusBar(self):
        """Update status bar message"""
        if len(self._markers) < len(self._pointNames):
            name = self._pointNames[len(self._markers)]
            msg = 'Select point: %s (%d/%d)' % (
                name, len(self._markers), len(self._pointNames))
        else:
            msg = 'Selection ready. Press Enter to validate'

        currentMode = self.getInteractiveMode()
        if currentMode['mode'] != 'zoom':
            msg += ' (Use zoom mode to add/edit points)'

        self.statusBar().showMessage(msg)


if __name__ == '__main__':
    app = qt.QApplication([])

    #plot = BlissPlot()
    #plot.startPointSelection(('first', 'second', 'third'))

    def dumpChanged(selection):
        print('selectionChanged', selection)

    def dumpFinished(selection):
        print('selectionFinished', selection)

    plot = PlotWindow()
    selector = ShapeSelector(plot)
    #selector.start(shape='rectangle')
    selector.selectionChanged.connect(dumpChanged)
    selector.selectionFinished.connect(dumpFinished)
    plot.show()

    points = PointsSelector(plot)
    points.start(3)
    points.selectionChanged.connect(dumpChanged)
    points.selectionFinished.connect(dumpFinished)
    #app.exec_()