roi_selection_widget.py 10.6 KB
Newer Older
Valentin Valls's avatar
Valentin Valls committed
1
2
3
4
# -*- coding: utf-8 -*-
#
# This file is part of the bliss project
#
Benoit Formet's avatar
Benoit Formet committed
5
# Copyright (c) 2015-2020 Beamline Control Unit, ESRF
Valentin Valls's avatar
Valentin Valls committed
6
7
8
9
10
11
# Distributed under the GNU LGPLv3. See LICENSE for more info.

"""
Provide a RoiSelectionWidget
"""

12
import typing
13
14
15
import logging
import functools
import re
16

Valentin Valls's avatar
Valentin Valls committed
17
from silx.gui import qt
18
from silx.gui import icons
Valentin Valls's avatar
Valentin Valls committed
19
20
21
from silx.gui.plot.tools.roi import RegionOfInterestManager
from silx.gui.plot.tools.roi import RegionOfInterestTableWidget
from silx.gui.plot.items.roi import RectangleROI
22
from silx.gui.plot.items.roi import RegionOfInterest
23
from silx.gui.plot.tools.roi import RoiModeSelectorAction
Valentin Valls's avatar
Valentin Valls committed
24
25


26
27
28
_logger = logging.getLogger(__name__)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class _AutoHideToolBar(qt.QToolBar):
    """A toolbar which hide itself if no actions are visible"""

    def actionEvent(self, event):
        if event.type() == qt.QEvent.ActionChanged:
            self._updateVisibility()
        return qt.QToolBar.actionEvent(self, event)

    def _updateVisibility(self):
        visible = False
        for action in self.actions():
            if action.isVisible():
                visible = True
                break
        self.setVisible(visible)


46
47
48
49
50
51
52
53
54
55
56
class _RegionOfInterestManagerWithContextMenu(RegionOfInterestManager):

    sigRoiContextMenuRequested = qt.Signal(object, qt.QMenu)

    def _feedContextMenu(self, menu):
        RegionOfInterestManager._feedContextMenu(self, menu)
        roi = self.getCurrentRoi()
        if roi is not None:
            if roi.isEditable():
                self.sigRoiContextMenuRequested.emit(roi, menu)

57
58
59
60
61
62
    def getRoiByName(self, name):
        for r in self.getRois():
            if r.getName() == name:
                return r
        return None

63

64
class RoiSelectionWidget(qt.QWidget):
Valentin Valls's avatar
Valentin Valls committed
65
66
67

    selectionFinished = qt.Signal(object)

68
    def __init__(self, plot, parent=None, kinds: typing.List[RegionOfInterest] = None):
69
        qt.QWidget.__init__(self, parent)
Valentin Valls's avatar
Valentin Valls committed
70
71
72
73
74
75
        # TODO: destroy on close
        self.plot = plot

        mode = plot.getInteractiveMode()["mode"]
        self.__previousMode = mode

76
        self.roiManager = _RegionOfInterestManagerWithContextMenu(plot)
77
78
        self.roiManager.setColor("pink")
        self.roiManager.sigRoiAdded.connect(self.__roiAdded)
79
        self.roiManager.sigRoiContextMenuRequested.connect(self.roiContextMenuRequested)
80
        self.roiManager.sigCurrentRoiChanged.connect(self.__currentRoiChanged)
Valentin Valls's avatar
Valentin Valls committed
81
        self.table = RegionOfInterestTableWidget()
82

83
84
85
86
87
        self.table.setSelectionBehavior(qt.QAbstractItemView.SelectRows)
        self.table.setSelectionMode(qt.QAbstractItemView.SingleSelection)
        selectionModel = self.table.selectionModel()
        selectionModel.currentRowChanged.connect(self.__currentRowChanged)

88
89
        # Hide coords
        horizontalHeader = self.table.horizontalHeader()
90
        horizontalHeader.setSectionResizeMode(0, qt.QHeaderView.Stretch)
91
92
        horizontalHeader.hideSection(1)  # is editable
        horizontalHeader.hideSection(3)  # coords
93
        self.table.setRegionOfInterestManager(self.roiManager)
Valentin Valls's avatar
Valentin Valls committed
94

95
96
97
        if kinds is None:
            kinds = [RectangleROI]

98
99
        self.roiToolbar = qt.QToolBar(self)

100
        cloneAction = qt.QAction(self.roiManager)
101
102
103
104
105
        cloneAction.setText("Duplicate")
        cloneAction.setToolTip("Duplicate selected ROI")
        icon = icons.getQIcon("flint:icons/roi-duplicate")
        cloneAction.setIcon(icon)
        cloneAction.setEnabled(False)
106
        cloneAction.triggered.connect(self.cloneCurrentRoiRequested)
107
        self.__cloneAction = cloneAction
108
109
110

        renameAction = qt.QAction(self.roiManager)
        renameAction.setText("Rename")
111
112
113
114
        renameAction.setToolTip("Rename selected ROI")
        icon = icons.getQIcon("flint:icons/roi-rename")
        renameAction.setIcon(icon)
        renameAction.setEnabled(False)
115
        renameAction.triggered.connect(self.renameCurrentRoiRequested)
116
        self.__renameAction = renameAction
117
118
119

        self.roiToolbar.addAction(cloneAction)
        self.roiToolbar.addAction(renameAction)
120
121
122
123
124
125
126
127
128
        self.roiToolbar.addSeparator()

        firstAction = None
        for roiKind in kinds:
            action = self.roiManager.getInteractionModeAction(roiKind)
            action.setSingleShot(True)
            self.roiToolbar.addAction(action)
            if firstAction is None:
                firstAction = action
129

130
131
132
133
        applyAction = qt.QAction(self.roiManager)
        applyAction.setText("Apply")
        applyAction.triggered.connect(self.on_apply)
        applyAction.setObjectName("roi-apply-selection")
134
135
136
137
138
139
140
141
142
        self.addAction(applyAction)

        self.applyButton = qt.QPushButton(self)
        self.applyButton.setFixedHeight(40)
        self.applyButton.setText("Apply this ROIs")
        icon = icons.getQIcon("flint:icons/roi-save")
        self.applyButton.setIcon(icon)
        self.applyButton.clicked.connect(self.on_apply)
        self.applyButton.setIconSize(qt.QSize(24, 24))
143
144
145
146
147
148
149
150
151
152
153
154

        roiEditToolbar = _AutoHideToolBar(self)
        modeSelectorAction = RoiModeSelectorAction(self)
        modeSelectorAction.setRoiManager(self.roiManager)
        roiEditToolbar.addAction(modeSelectorAction)
        self.roiEditToolbar = roiEditToolbar

        layout = qt.QVBoxLayout(self)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.roiToolbar)
        layout.addWidget(self.roiEditToolbar)
Valentin Valls's avatar
Valentin Valls committed
155
        layout.addWidget(self.table)
156
        layout.addWidget(self.applyButton)
Valentin Valls's avatar
Valentin Valls committed
157

158
159
        if firstAction is not None:
            firstAction.trigger()
160

161
162
163
164
165
166
167
168
169
170
171
    def __currentRowChanged(self, current, previous):
        model = self.table.model()
        index = model.index(current.row(), 0)
        name = model.data(index)
        roi = self.roiManager.getRoiByName(name)
        self.roiManager.setCurrentRoi(roi)

    def __currentRoiChanged(self, roi):
        selectionModel = self.table.selectionModel()
        if roi is None:
            selectionModel.clear()
172
            enabled = False
173
174
175
176
177
178
179
180
181
182
183
184
185
186
        else:
            name = roi.getName()
            model = self.table.model()
            for row in range(model.rowCount()):
                index = model.index(row, 0)
                if model.data(index) == name:
                    selectionModel.reset()
                    mode = (
                        qt.QItemSelectionModel.Clear
                        | qt.QItemSelectionModel.Rows
                        | qt.QItemSelectionModel.Current
                        | qt.QItemSelectionModel.Select
                    )
                    selectionModel.select(index, mode)
187
                    enabled = True
188
189
190
                    break
            else:
                selectionModel.clear()
191
192
193
194
                enabled = False

        self.__cloneAction.setEnabled(enabled)
        self.__renameAction.setEnabled(enabled)
195

Valentin Valls's avatar
Valentin Valls committed
196
    def on_apply(self):
197
        self.selectionFinished.emit(self.roiManager.getRois())
Valentin Valls's avatar
Valentin Valls committed
198
199
        self.clear()

200
201
202
203
    def roiContextMenuRequested(self, roi, menu: qt.QMenu):
        menu.addSeparator()

        cloneAction = qt.QAction(menu)
204
        cloneAction.setText("Duplicate %s" % roi.getName())
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
        callback = functools.partial(self.cloneRoiRequested, roi)
        cloneAction.triggered.connect(callback)
        menu.addAction(cloneAction)

        renameAction = qt.QAction(menu)
        renameAction.setText("Rename %s" % roi.getName())
        callback = functools.partial(self.renameRoiRequested, roi)
        renameAction.triggered.connect(callback)
        menu.addAction(renameAction)

    def renameRoiRequested(self, roi):
        name = roi.getName()
        result = qt.QInputDialog.getText(
            self, "Rename ROI name", "ROI name", qt.QLineEdit.Normal, name
        )
        if result[1]:
            newName = result[0]
            if newName == name:
                return
            if self.isAlreadyUsed(newName):
                qt.QMessageBox.warning(
                    self, "Action cancelled", f"ROI name '{newName}' already used."
                )
                return
            roi.setName(newName)

    def __splitTrailingNumber(self, name):
        m = re.search(r"^(.*?)(\d+)$", name)
        if m is None:
            return name, 1
        groups = m.groups()
        return groups[0], int(groups[1])

    def cloneRoiRequested(self, roi):
        name = roi.getName()
        basename, number = self.__splitTrailingNumber(name)
        for _ in range(50):
            number = number + 1
            name = f"{basename}{number}"
            if not self.isAlreadyUsed(name):
                break

        result = qt.QInputDialog.getText(
            self, "Clone ROI", "ROI name", qt.QLineEdit.Normal, name
        )
        if result[1]:
            if self.isAlreadyUsed(name):
                qt.QMessageBox.warning(
                    self, "Action cancelled", f"ROI name '{name}' already used."
                )
                return

            try:
                newRoi = roi.clone()
            except Exception:
                _logger.error("Error while cloning ROI", exc_info=True)
                return

            newName = result[0]
            newRoi.setName(newName)
            self.roiManager.addRoi(newRoi)

    def isAlreadyUsed(self, name):
        for r in self.roiManager.getRois():
            if r.getName() == name:
                return True
        return False

    def cloneCurrentRoiRequested(self):
        roi = self.roiManager.getCurrentRoi()
        if roi is None:
            return
        self.cloneRoiRequested(roi)

    def renameCurrentRoiRequested(self):
        roi = self.roiManager.getCurrentRoi()
        if roi is None:
            return
        self.renameRoiRequested(roi)

Valentin Valls's avatar
Valentin Valls committed
285
    def clear(self):
286
        self.roiManager.clear()
Valentin Valls's avatar
Valentin Valls committed
287
288
289
290
291
292
        try:
            self.plot.setInteractiveMode(self.__previousMode)
        except Exception:
            # In case the mode is not supported
            pass

293
294
295
296
297
298
299
300
301
302
    def searchForFreeName(self, roi):
        """Returns a new name for a ROI.

        The name is picked in order to match roi_counters and
        roi2spectrum_counters. It was decided to allow to have the same sub
        names for both Lima devices.

        As this module is generic, it would be better to move this code in more
        specific place.
        """
303
        rois = self.roiManager.getRois()
304
305
306
307
308
309
310
311
312
        roiNames = set([r.getName() for r in rois])

        for i in range(1, 1000):
            name = f"roi{i}"
            if name not in roiNames:
                return name
        return "roi666.666"

    def __roiAdded(self, roi):
313
314
        roi.setSelectable(True)
        roi.setEditable(True)
Valentin Valls's avatar
Valentin Valls committed
315
        if not roi.getName():
316
317
            name = self.searchForFreeName(roi)
            roi.setName(name)
Valentin Valls's avatar
Valentin Valls committed
318
319

    def add_roi(self, roi):
320
        self.roiManager.addRoi(roi)