-
Notifications
You must be signed in to change notification settings - Fork 6
/
widgets.py
533 lines (436 loc) · 19.2 KB
/
widgets.py
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
from typing import Union
from qtpy.QtCore import Qt, QObject, Signal, QTimer
from qtpy.QtWidgets import (
QWidget,
QLabel,
QComboBox,
QSpinBox,
QLineEdit,
QPushButton
)
from superqt import QLabeledSlider, QLabeledDoubleSlider
from qtpy.QtWidgets import QFormLayout, QHBoxLayout, QGridLayout, QGroupBox
from abc import ABC, abstractmethod
from dataclasses import replace
from napari_live_recording.common import ROI
from enum import Enum
from typing import Dict, List, Tuple
class Timer(QTimer):
pass
class WidgetEnum(Enum):
ComboBox = 0,
SpinBox = 1,
DoubleSpinBox = 2,
LabeledSlider = 3,
LineEdit = 4
class LocalWidget(ABC):
def __init__(self, internalWidget : QWidget, name: str, unit: str = "", orientation: str = "left") -> None:
"""Common widget constructor.
Args:
internalWidget (QWidget): widget to construct the form layout.
name (str): parameter label description.
unit (str, optional): parameter unit measure. Defaults to "".
orientation (str, optional): label orientation on the layout. Defaults to "left".
"""
super().__init__()
self.__name = name
self.__unit = unit
labelStr = (self.__name + " (" + self.__unit + ")" if self.__unit != "" else self.__name)
self.label = QLabel(labelStr)
self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.widget = internalWidget
@property
def isEnabled(self) -> bool:
"""Widget is enabled for editing (True) or not (False).
"""
return self.widget.isEnabled()
@isEnabled.setter
def isEnabled(self, enable : bool) -> None:
"""Sets widget enabled for editing (True) or not (False).
"""
self.widget.setEnabled(enable)
@abstractmethod
def changeWidgetSettings(self, newParam) -> None:
"""Common widget update parameter abstract method.
"""
pass
@property
@abstractmethod
def value(self) -> None:
"""Widget current value.
"""
pass
@value.setter
@abstractmethod
def value(self, value: Union[str, int, float]) -> None:
"""Widget value setter.
"""
pass
@property
@abstractmethod
def signals(self) -> Dict[str, Signal]:
"""Common widget method to expose signals to the device.
"""
pass
class ComboBox(LocalWidget):
def __init__(self, param : List[str], name : str, unit : str = "", orientation: str = "left") -> None:
"""ComboBox widget.
Args:
param (List[str]): List of parameters added to the ComboBox.
name (str): parameter label description.
unit (str, optional): parameter unit measure. Defaults to "".
orientation (str, optional): label orientation on the layout. Defaults to "left".
"""
self.combobox = QComboBox()
self.combobox.addItems(param)
super().__init__(self.combobox, name, unit, orientation)
def changeWidgetSettings(self, newParam: List[str]) -> None:
"""ComboBox update widget parameter method. Old List of items is deleted.
Args:
newParam (List[str]): new List of parameters to add to the ComboBox.
"""
self.combobox.clear()
self.combobox.addItems(newParam)
@property
def value(self) -> Tuple[str, int]:
"""Returns a Tuple containing the ComboBox current text and index.
"""
return (self.combobox.currentText(), self.combobox.currentIndex())
@value.setter
def value(self, value: int) -> None:
"""Sets the ComboBox current showed value (based on elements indeces).
Args:
value (int): index of value to show on the ComboBox.
"""
self.combobox.setCurrentIndex(value)
@property
def signals(self) -> Dict[str, Signal]:
"""Returns a dictionary of signals available for the ComboBox widget.
Exposed signals are:
- currentIndexChanged,
- currentTextChanged
Returns:
Dict: Dict of signals (key: function name, value: function objects).
"""
return {
"currentIndexChanged" : self.combobox.currentIndexChanged,
"currentTextChanged" : self.combobox.currentTextChanged
}
class LabeledSlider(LocalWidget):
def __init__(self, param: Union[Tuple[int, int, int], Tuple[float, float, float]], name: str, unit: str = "", orientation: str = "left") -> None:
"""Slider widget.
Args:
param (Tuple[int, int, int])): parameters for spinbox settings: (<minimum_value>, <maximum_value>, <starting_value>)
name (str): parameter label description.
unit (str, optional): parameter unit measure. Defaults to "".
orientation (str, optional): label orientation on the layout. Defaults to "left".
"""
if any(type(param) == float):
self.__slider = QLabeledDoubleSlider(Qt.Horizontal)
else:
self.__slider = QLabeledSlider(Qt.Horizontal)
self.__slider.setRange(param[0], param[1])
self.__slider.setValue(param[2])
super().__init__(self.__slider, name, unit, orientation)
def changeWidgetSettings(self, newParam : Tuple[int, int, int]) -> None:
"""Slider update widget parameter method.
Args:
newParam (Tuple[int, int, int]): new parameters for SpinBox settings: (<minimum_value>, <maximum_value>, <starting_value>)
"""
self.__slider.setRange(newParam[0], newParam[1])
self.__slider.setValue(newParam[2])
@property
def value(self) -> int:
"""Returns the Slider current value.
"""
return self.__slider.value()
@value.setter
def value(self, value: int) -> None:
"""Sets the DoubleSpinBox current value to show on the widget.
Args:
value (float): value to set.
"""
self.__slider.setValue(value)
@property
def signals(self) -> Dict[str, Signal]:
"""Returns a dictionary of signals available for the SpinBox widget.
Exposed signals are:
- valueChanged
Returns:
Dict: Dict of signals (key: function name, value: function objects).
"""
return {
"valueChanged" : self.__slider.valueChanged
}
class LineEdit(LocalWidget):
def __init__(self, param: str, name: str, unit: str = "", orientation: str = "left") -> None:
"""LineEdit widget.
Args:
param (str): line edit contents
name (str): parameter label description.
unit (str, optional): parameter unit measure. Defaults to "".
orientation (str, optional): label orientation on the layout. Defaults to "left".
editable (bool, optional): sets the LineEdit to be editable. Defaults to False.
"""
self.__lineEdit = QLineEdit(param)
super().__init__(self.__lineEdit, name, unit, orientation)
def changeWidgetSettings(self, newParam : str) -> None:
"""Updates LineEdit text contents.
Args:
newParam (str): new string for LineEdit.
"""
self.__lineEdit.setText(newParam)
@property
def value(self) -> str:
"""Returns the LineEdit current text.
"""
return self.__lineEdit.text()
@value.setter
def value(self, value: str) -> None:
"""Sets the LineEdit current text to show on the widget.
Args:
value (str): string to set.
"""
self.__lineEdit.setText(value)
@property
def signals(self) -> Dict[str, Signal]:
"""Returns a dictionary of signals available for the LineEdit widget.
Exposed signals are:
- textChanged,
- textEdited
Returns:
Dict: Dict of signals (key: function name, value: function objects).
"""
return {
"textChanged" : self.__lineEdit.textChanged,
"textEdited" : self.__lineEdit.textEdited
}
class CameraSelection(QObject):
newCameraRequested = Signal(str, str, str)
def __init__(self) -> None:
"""Camera selection widget. It includes the following widgets:
- a ComboBox for camera selection based on strings to identify each camera type;
- a LineEdit for camera ID or serial number input
- a QPushButton to add the camera
Widget grid layout:
|(0,0-1) ComboBox |(0,2) QPushButton|
|(1,0) LineEdit|Line Edit(1,1) |(1,2) |
The QPushButton remains disabled as long as no camera is selected (first index is highlited).
"""
super(CameraSelection, self).__init__()
self.group = QGroupBox()
self.camerasComboBox = ComboBox([], "Interface")
self.nameLineEdit = LineEdit(param="MyCamera", name="Camera name")
self.idLineEdit = LineEdit(param="0", name="Camera ID/SN", orientation="right")
self.addButton = QPushButton("Add camera")
self.addButton.setEnabled(False)
# create widget layout
self.camerasComboBox.signals["currentIndexChanged"].connect(self._setAddEnabled)
self.addButton.clicked.connect(lambda: self.newCameraRequested.emit(self.camerasComboBox.value[0], self.nameLineEdit.value, self.idLineEdit.value))
self.formLayout = QFormLayout()
self.formLayout.addRow(self.camerasComboBox.label, self.camerasComboBox.widget)
self.formLayout.addRow(self.nameLineEdit.label, self.nameLineEdit.widget)
self.formLayout.addRow(self.idLineEdit.label, self.idLineEdit.widget)
self.formLayout.addRow(self.addButton)
self.group.setLayout(self.formLayout)
self.group.setFlat(True)
def setAvailableCameras(self, cameras: List[str]) -> None:
"""Sets the ComboBox with the List of available camera devices.
Args:
cameras (List[str]): List of available camera devices.
"""
# we need to extend the List of available cameras with a selection text
cameras.insert(0, "Select device")
self.camerasComboBox.changeWidgetSettings(cameras)
self.camerasComboBox.isEnabled = True
def _setAddEnabled(self, idx: int):
"""Private method serving as an enable/disable mechanism for the Add button widget.
This is done to avoid the first index, the "Select device" string, to be considered
as a valid camera device (which is not).
"""
if idx > 0:
self.addButton.setEnabled(True)
else:
self.addButton.setEnabled(False)
class RecordHandling(QObject):
recordRequested = Signal(int)
def __init__(self) -> None:
"""Recording Handling widget. Includes QPushButtons which allow to handle the following operations:
- live viewing;
- recording to output file;
- single frame snap;
- album stacking snap.
Widget layout:
|(0,0) QPushButton (Snap) |(0,1) QPushButton (Album)| |
|(1,0-1) QPushButton (Live) |
|(2,0) QSpinBox (Record size) |(2,1) QPushButton (Record) |
"""
QObject.__init__(self)
self.group = QGroupBox()
self.layout = QGridLayout()
self.snap = QPushButton("Snap")
self.album = QPushButton("Album")
self.live = QPushButton("Live")
# the live button is implemented as a toggle button
self.live.setCheckable(True)
self.recordSpinBox = QSpinBox()
self.recordSpinBox.lineEdit().setAlignment(Qt.AlignmentFlag.AlignCenter)
# todo: this is currently hardcoded
# maybe should find a way to initialize
# from outside the instance?
self.recordSpinBox.setRange(1, 5000)
self.recordSpinBox.setValue(100)
self.record = QPushButton("Record")
self.layout.addWidget(self.snap, 0, 0)
self.layout.addWidget(self.album, 0, 1)
self.layout.addWidget(self.live, 1, 0, 1, 2)
self.layout.addWidget(self.recordSpinBox, 2, 0)
self.layout.addWidget(self.record, 2, 1)
self.group.setLayout(self.layout)
# whenever the live button is toggled,
# the other pushbutton must be enabled/disabled
# in order to avoid undefined behaviors
# when grabbing frames from the device
self.live.toggled.connect(self._handleLiveToggled)
def setWidgetsEnabling(self, isEnabled : bool) -> None:
""" Enables/Disables all record handling widgets. """
self.snap.setEnabled(isEnabled)
self.album.setEnabled(isEnabled)
self.live.setEnabled(isEnabled)
self.record.setEnabled(isEnabled)
self.recordSpinBox.setEnabled(isEnabled)
def _handleLiveToggled(self, status: bool) -> None:
"""Enables/Disables pushbuttons when the live button is toggled.
Args:
status (bool): new live button status.
"""
self.snap.setEnabled(not status)
self.album.setEnabled(not status)
self.record.setEnabled(not status)
@property
def recordSize(self) -> int:
"""Returns the record size currently indicated in the QSpinBox widget.
"""
return self.recordSpinBox.value()
@property
def signals(self) -> Dict[str, Signal]:
"""Returns a dictionary of signals available for the RecordHandling widget.
Exposed signals are:
- snapRequested,
- albumRequested,
- liveRequested,
- recordRequested
Returns:
Dict: Dict of signals (key: function name, value: function objects).
"""
return {
"snapRequested" : self.snap.clicked,
"albumRequested" : self.album.clicked,
"liveRequested" : self.live.toggled,
"recordRequested" : self.record.clicked,
}
class ROIHandling(QWidget):
changeROIRequested = Signal(ROI)
fullROIRequested = Signal(ROI)
def __init__(self, sensorShape : ROI) -> None:
"""ROI Handling widget. Defines a set of non-custom widgets to set the Region Of Interest of the device.
This widget is common for all devices.
"""
QWidget.__init__(self)
self.sensorFullROI = replace(sensorShape)
self.offsetXLabel = QLabel("Offset X (px)")
self.offsetXLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.offsetXSpinBox = QSpinBox()
self.offsetXSpinBox.lineEdit().setAlignment(Qt.AlignmentFlag.AlignCenter)
self.offsetXSpinBox.setRange(0, self.sensorFullROI.width)
self.offsetXSpinBox.setSingleStep(self.sensorFullROI.ofs_x_step)
self.offsetXSpinBox.setValue(0)
self.offsetYLabel = QLabel("Offset Y (px)", )
self.offsetYLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.offsetYSpinBox = QSpinBox()
self.offsetYSpinBox.lineEdit().setAlignment(Qt.AlignmentFlag.AlignCenter)
self.offsetYSpinBox.setRange(0, self.sensorFullROI.height)
self.offsetYSpinBox.setSingleStep(self.sensorFullROI.ofs_y_step)
self.offsetYSpinBox.setValue(0)
self.widthLabel = QLabel("Width (px)")
self.widthLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.widthSpinBox = QSpinBox()
self.widthSpinBox.lineEdit().setAlignment(Qt.AlignmentFlag.AlignCenter)
self.widthSpinBox.setRange(0, self.sensorFullROI.width)
self.widthSpinBox.setSingleStep(self.sensorFullROI.width_step)
self.widthSpinBox.setValue(self.sensorFullROI.width)
self.heightLabel = QLabel("Height (px)")
self.heightLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.heightSpinBox = QSpinBox()
self.heightSpinBox.lineEdit().setAlignment(Qt.AlignmentFlag.AlignCenter)
self.heightSpinBox.setRange(0, self.sensorFullROI.height)
self.heightSpinBox.setSingleStep(self.sensorFullROI.height_step)
self.heightSpinBox.setValue(self.sensorFullROI.height)
self.changeROIButton = QPushButton("Set ROI")
self.fullROIButton = QPushButton("Full frame")
layout = QGridLayout()
layout.addWidget(self.offsetXLabel, 0, 0)
layout.addWidget(self.offsetXSpinBox, 0, 1)
layout.addWidget(self.offsetYSpinBox, 0, 2)
layout.addWidget(self.offsetYLabel, 0, 3)
layout.addWidget(self.widthLabel, 1, 0)
layout.addWidget(self.widthSpinBox, 1, 1)
layout.addWidget(self.heightSpinBox, 1, 2)
layout.addWidget(self.heightLabel, 1, 3)
layout.addWidget(self.changeROIButton, 2, 0, 1, 2)
layout.addWidget(self.fullROIButton, 2, 2, 1, 2)
# "clicked" signals are connected to private slots.
# These slots expose the signals available to the user
# to process the new ROI information if necessary.
self.changeROIButton.clicked.connect(self._onROIChanged)
self.fullROIButton.clicked.connect(self._onFullROI)
self.setLayout(layout)
def changeWidgetSettings(self, settings : ROI):
"""ROI handling update widget settings method.
This method is useful whenever the ROI values are changed based
on some device requirements and adapted.
Args:
settings (ROI): new ROI settings to change the widget values and steps.
"""
self.offsetXSpinBox.setSingleStep(settings.ofs_x_step)
self.offsetXSpinBox.setValue(settings.offset_x)
self.offsetYSpinBox.setSingleStep(settings.ofs_y_step)
self.offsetYSpinBox.setValue(settings.offset_y)
self.widthSpinBox.setSingleStep(settings.width_step)
self.widthSpinBox.setValue(settings.width)
self.heightSpinBox.setSingleStep(settings.height_step)
self.heightSpinBox.setValue(settings.height)
def _onROIChanged(self) -> None:
"""Private slot for ROI changed button pressed. Exposes a signal with the updated ROI settings.
"""
# read the current SpinBoxes status
newRoi = ROI(
offset_x=self.offsetXSpinBox.value(),
ofs_x_step=self.offsetXSpinBox.singleStep(),
offset_y=self.offsetYSpinBox.value(),
ofs_y_step=self.offsetXSpinBox.singleStep(),
width=self.widthSpinBox.value(),
width_step=self.widthSpinBox.singleStep(),
height=self.heightSpinBox.value(),
height_step=self.heightSpinBox.singleStep()
)
self.changeROIRequested.emit(newRoi)
def _onFullROI(self) -> None:
"""Private slot for full ROI button pressed. Exposes a signal with the full ROI settings.
It also returns the widget settings to their original value.
"""
self.changeWidgetSettings(self.sensorFullROI)
self.fullROIRequested.emit(replace(self.sensorFullROI))
@property
def signals(self) -> Dict[str, Signal]:
"""Returns a dictionary of signals available for the ROIHandling widget.
Exposed signals are:
- changeROIRequested,
- fullROIRequested,
Returns:
Dict: Dict of signals (key: function name, value: function objects).
"""
return {
"changeROIRequested" : self.changeROIRequested,
"fullROIRequested" : self.fullROIRequested,
}