parameterwidget.py 30 KB
Newer Older
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
# vim: set fileencoding=utf-8 :
###############################################################################
#                                                                             #
# Copyright (c) 2019 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.editor module of the BEAT platform.           #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform is distributed in the hope that it will be useful, but    #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################

Samuel GAIST's avatar
Samuel GAIST committed
26
27
from enum import Enum
from enum import unique
28

Samuel GAIST's avatar
Samuel GAIST committed
29
import numpy as np
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

from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QComboBox
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QDialogButtonBox
from PyQt5.QtWidgets import QFormLayout
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QInputDialog
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QListWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QRadioButton
from PyQt5.QtWidgets import QStackedWidget
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget

from ..utils import dataformat_basetypes
from .spinboxes import NumpySpinBox


@unique
class InputType(Enum):
    """All possible assets available on the BEAT platform"""

    UNKNOWN = None
    INT8 = np.int8
    INT16 = np.int16
    INT32 = np.int32
    INT64 = np.int64
    UINT8 = np.uint8
    UINT16 = np.uint16
    UINT32 = np.uint32
    UINT64 = np.uint64
    FLOAT32 = np.float32
    FLOAT64 = np.float64
    BOOL = np.bool
    STRING = np.str

    def __init__(self, np_type):
        super().__init__()
        self.np_type = np_type

    @property
    def numpy_info(self):
        info = None
78
79

        if self is InputType.UNKNOWN:
Samuel GAIST's avatar
Samuel GAIST committed
80
            raise RuntimeError("Invalid type")
81
        elif np.issubdtype(self.np_type, np.floating):
82
83
84
85
            info = np.finfo(self.np_type)
        elif np.issubdtype(self.np_type, np.integer):
            info = np.iinfo(self.np_type)
        else:
86
            raise RuntimeError(f"No information available for {self}")
87
88
89

        return info

90
91
92
93
94
95
96
97
    @staticmethod
    def numerical_types():
        return [
            item
            for item in InputType
            if item not in [InputType.UNKNOWN, InputType.BOOL, InputType.STRING]
        ]

98

99
100
101
102
103
104
105
106
class StackedWidget(QStackedWidget):
    """Subclass that will use the current widget height to adjust the stack
    size.

    This allows to keep a compact widget.
    """

    def __init__(self, parent=None):
107
        super().__init__(parent)
108
109
110
111
112
113

    def sizeHint(self):
        """Returns a size hint based on the current widget in place of the
        biggest of all widgets added.
        """

114
        size = super().size()
115
116
117
118
119
120
121
122
123
        current_size_hint = self.currentWidget().sizeHint()
        size.setHeight(current_size_hint.height())
        return size

    def minimumSizeHint(self):
        """Returns a minimum size hint base on the current widget in place of
        the biggest of all widgets added.
        """

124
        size = super().size()
125
126
127
128
129
        current_size_hint = self.currentWidget().minimumSizeHint()
        size.setHeight(current_size_hint.height())
        return size


130
class NumericalChoiceDialog(QDialog):
131
132
133
134
135
136
137
138
139
    """Dialog to retrieve a value to to add to a choice list"""

    def __init__(self, selected_type, parent=None):
        """Constructor

        :param selected_type: current basetype
        :param parent QWidget: parent widget
        """

140
        super().__init__(parent)
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

        self.setWindowTitle(self.tr("Input"))
        self.label = QLabel(self.tr("New Choice:"))
        self.spinbox = NumpySpinBox(selected_type.np_type)

        layout = QVBoxLayout(self)
        layout.addWidget(self.label)
        layout.addWidget(self.spinbox)

        # OK and Cancel buttons
        self.buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self
        )
        layout.addWidget(self.buttons)

        # Signals/Slots connection
        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

160
161
162
    def value(self):
        """Returns the value selected"""

163
        return self.spinbox.value
164

165
166
167
168
169
170
171
172
    @staticmethod
    def getChoiceValue(selected_type, parent=None):
        """Static method to create the dialog and return qdialog accepted/spinbox value

        :param selected_type: current basetype
        :param parent QWidget: parent widget
        """

173
        dialog = NumericalChoiceDialog(selected_type, parent)
174
175
176
177
        result = dialog.exec_()
        value = None

        if result == QDialog.Accepted:
178
            value = dialog.value()
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

        return (value, result)


class BoolSetupWidget(QWidget):
    """Editor to setup a boolean parameter"""

    dataChanged = pyqtSignal()

    def __init__(self, parent=None):
        """Constructor

        :param parent QWidget: parent widget
        """

194
        super().__init__(parent)
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

        # Member variables
        # Added self for auto-exclusion to work correctly
        self.true_button = QRadioButton(self.tr("True"), self)
        self.true_button.setChecked(True)
        self.false_button = QRadioButton(self.tr("False"), self)

        # Layouts
        radio_buttons_layout = QVBoxLayout()
        radio_buttons_layout.addWidget(self.true_button)
        radio_buttons_layout.addWidget(self.false_button)
        radio_buttons_layout.addStretch(1)

        layout = QFormLayout(self)
        layout.addRow(self.tr("Default"), radio_buttons_layout)

        # Signals
        self.true_button.toggled.connect(self.dataChanged)
        self.false_button.toggled.connect(self.dataChanged)

    def load(self, data):
        """Load the json object passed as parameter"""

218
219
        self.reset()

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        default = data.get("default", True)
        if default:
            self.true_button.setChecked(True)
        else:
            self.false_button.setChecked(True)

    def dump(self):
        """Returns the json representation of this editor"""

        return {"default": self.true_button.isChecked()}

    def reset(self):
        """Reset editor to default values"""

        self.true_button.setChecked(True)


class StringSetupWidget(QWidget):
    """Editor to setup a string parameter"""

    dataChanged = pyqtSignal()
241
    editorChanged = pyqtSignal()
242
243
244
245
246
247
248

    def __init__(self, parent=None):
        """Constructor

        :param parent QWidget: parent widget
        """

249
        super().__init__(parent)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265

        # Member variables
        self.single_button = QRadioButton(self.tr("Single"), self)
        self.single_button.setChecked(True)
        self.choices_button = QRadioButton(self.tr("Choices"), self)

        # Layouts
        radio_buttons_layout = QHBoxLayout()
        radio_buttons_layout.addWidget(self.single_button)
        radio_buttons_layout.addWidget(self.choices_button)
        radio_buttons_layout.addStretch(1)

        layout = QVBoxLayout(self)
        layout.addLayout(radio_buttons_layout)

        # single items
266
        self.single_default_lineedit = QLineEdit()
267
268
269
270
271
272
273
274
275
276
277
278

        # choices items
        self.choices_default_combobox = QComboBox()
        self.choices_listwidget = QListWidget()
        self.add_button = QPushButton(self.tr("+"))
        self.remove_button = QPushButton(self.tr("-"))

        # Widgets to be stacked
        self.single_conf_widget = QWidget()
        self.choices_conf_widget = QWidget()

        # Stacked widget
279
        self.stacked_widget = StackedWidget()
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
        self.stacked_widget.addWidget(self.single_conf_widget)
        self.stacked_widget.addWidget(self.choices_conf_widget)

        self.__setup_single_ui()
        self.__setup_choices_ui()

        layout.addWidget(self.stacked_widget)

        # Signals
        self.single_button.toggled.connect(
            lambda: self.stacked_widget.setCurrentWidget(self.single_conf_widget)
        )
        self.choices_button.toggled.connect(
            lambda: self.stacked_widget.setCurrentWidget(self.choices_conf_widget)
        )

        self.add_button.clicked.connect(self.__onChoiceAddClicked)
        self.remove_button.clicked.connect(self.__onChoiceRemoveClicked)

        self.single_button.toggled.connect(self.dataChanged)
        self.choices_button.toggled.connect(self.dataChanged)
301
        self.single_default_lineedit.textChanged.connect(self.dataChanged)
302
303
304
305
306
        self.choices_default_combobox.currentIndexChanged.connect(self.dataChanged)
        choices_model = self.choices_listwidget.model()
        choices_model.rowsInserted.connect(self.dataChanged)
        choices_model.rowsRemoved.connect(self.dataChanged)

307
308
309
        self.stacked_widget.currentChanged.connect(lambda: self.adjustSize())
        self.stacked_widget.currentChanged.connect(self.editorChanged)

310
311
312
    def load(self, data):
        """Load the json object passed as parameter"""

313
314
        self.reset()

315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
        choices = data.get("choice", [])
        default = data.get("default", "")

        if "choice" in data:
            # Check there are no duplicates
            if len(choices) != len(set(choices)):
                raise RuntimeError("Invalid duplicate choice")
            else:
                if default not in choices:
                    raise RuntimeError("Invalid default choice")
                else:
                    self.choices_button.setChecked(True)
                    self.choices_listwidget.addItems(choices)
                    self.choices_default_combobox.addItems(choices)
                    index = self.choices_default_combobox.findText(
                        default, Qt.MatchFixedString
                    )
                    if index >= 0:
                        self.choices_default_combobox.setCurrentIndex(index)
                    else:
                        raise RuntimeError("Invalid default value")
        else:
            self.single_button.setChecked(True)
338
            self.single_default_lineedit.setText(default)
339
340
341
342
343
344
345

    def dump(self):
        """Returns the json representation of the editor"""

        data = {}

        if self.single_button.isChecked():
346
            data["default"] = self.single_default_lineedit.text()
347
348
349
350
351
352
353
354
355
356
357
358
359
        else:
            data["default"] = self.choices_default_combobox.currentText()
            data["choice"] = [
                str(self.choices_listwidget.item(i).text())
                for i in range(self.choices_listwidget.count())
            ]

        return data

    def reset(self):
        """Reset the editor to its default state"""

        self.single_button.setChecked(True)
360
        self.single_default_lineedit.clear()
361
362
363
364
365
366
        self.choices_listwidget.clear()
        self.choices_default_combobox.clear()

    def __setup_single_ui(self):

        layout = QFormLayout()
367
        layout.addRow(self.tr("Default:"), self.single_default_lineedit)
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
        self.single_conf_widget.setLayout(layout)

    def __setup_choices_ui(self):

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(self.add_button)
        buttons_layout.addWidget(self.remove_button)
        buttons_layout.addStretch(1)

        choices_layout = QVBoxLayout()
        choices_layout.addWidget(self.choices_listwidget)
        choices_layout.addLayout(buttons_layout)

        layout = QFormLayout()
        layout.addRow(self.tr("Default:"), self.choices_default_combobox)
        layout.addRow(self.tr("Choices:"), choices_layout)

        self.choices_conf_widget.setLayout(layout)

    @pyqtSlot()
    def __onChoiceAddClicked(self):
        input_value = None
        ok = False

        input_value, ok = QInputDialog.getText(
            self, self.tr("Input"), self.tr("New Choice:"), QLineEdit.Normal, ""
        )
        if ok:
            if (
                len(
                    self.choices_listwidget.findItems(str(input_value), Qt.MatchExactly)
                )
                == 0
            ):
                self.choices_listwidget.addItem(str(input_value))
                self.choices_default_combobox.addItem(str(input_value))

    @pyqtSlot()
    def __onChoiceRemoveClicked(self):
        choices = self.choices_listwidget.selectedItems()
        for choice in choices:
            self.choices_default_combobox.removeItem(
                self.choices_listwidget.row(choice)
            )
            self.choices_listwidget.takeItem(self.choices_listwidget.row(choice))


class NumericalSetupWidget(QWidget):
    """Editor to setup a numerical parameter"""

    dataChanged = pyqtSignal()
419
    editorChanged = pyqtSignal()
420
421
422
423
424
425
426
427

    def __init__(self, selected_type, parent=None):
        """Constructor

        :param selected_type InputType: input type to edit
        :param parent QWidget: parent widget
        """

428
        super().__init__(parent)
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

        # Class variables
        self.current_type = selected_type

        # Member variables
        self.single_button = QRadioButton(self.tr("Single"), self)
        self.single_button.setChecked(True)
        self.choices_button = QRadioButton(self.tr("Choices"), self)
        self.range_button = QRadioButton(self.tr("Range"), self)

        # Layouts
        radio_buttons_layout = QHBoxLayout()
        radio_buttons_layout.addWidget(self.single_button)
        radio_buttons_layout.addWidget(self.choices_button)
        radio_buttons_layout.addWidget(self.range_button)
        radio_buttons_layout.addStretch(1)

        layout = QVBoxLayout(self)
        layout.addLayout(radio_buttons_layout)

        min_value = self.current_type.numpy_info.min
        max_value = self.current_type.numpy_info.max

        # single items
        self.single_default_spinbox = NumpySpinBox(self.current_type.np_type)
        self.single_default_spinbox.setMinimum(min_value)
        self.single_default_spinbox.setMaximum(max_value)

        # choices items
        self.choices_default_combobox = QComboBox()
        self.choices_listwidget = QListWidget()
        self.add_button = QPushButton(self.tr("+"))
        self.remove_button = QPushButton(self.tr("-"))

        # range items
        self.range_minimum_spinbox = NumpySpinBox(self.current_type.np_type)
        self.range_maximum_spinbox = NumpySpinBox(self.current_type.np_type)
        self.range_default_spinbox = NumpySpinBox(self.current_type.np_type)

        # free bounds
        self.range_minimum_spinbox.setMinimum(min_value)
        self.range_maximum_spinbox.setMaximum(max_value)

        self.range_minimum_spinbox.setValue(-10)
        self.range_maximum_spinbox.setValue(10)

        # restricted bounds
        self.restrict_range()

        # Widgets to be stacked
        self.single_conf_widget = QWidget()
        self.choices_conf_widget = QWidget()
        self.range_conf_widget = QWidget()

        # Stacked widget
484
        self.stacked_widget = StackedWidget(self)
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
        self.stacked_widget.addWidget(self.single_conf_widget)
        self.stacked_widget.addWidget(self.choices_conf_widget)
        self.stacked_widget.addWidget(self.range_conf_widget)

        self.__setup_single_ui()
        self.__setup_choices_ui()
        self.__setup_range_ui()

        layout.addWidget(self.stacked_widget)

        # Signals
        self.single_button.toggled.connect(
            lambda: self.stacked_widget.setCurrentWidget(self.single_conf_widget)
        )
        self.choices_button.toggled.connect(
            lambda: self.stacked_widget.setCurrentWidget(self.choices_conf_widget)
        )
        self.range_button.toggled.connect(
            lambda: self.stacked_widget.setCurrentWidget(self.range_conf_widget)
        )

        self.add_button.clicked.connect(self.__onChoiceAddClicked)
        self.remove_button.clicked.connect(self.__onChoiceRemoveClicked)

        self.range_minimum_spinbox.valueChanged.connect(self.restrict_range_from_min)
        self.range_maximum_spinbox.valueChanged.connect(self.restrict_range_from_max)

        self.single_button.toggled.connect(self.dataChanged)
        self.choices_button.toggled.connect(self.dataChanged)
        self.range_button.toggled.connect(self.dataChanged)
        self.single_default_spinbox.valueChanged.connect(self.dataChanged)
        self.choices_default_combobox.currentIndexChanged.connect(self.dataChanged)
        choices_model = self.choices_listwidget.model()
        choices_model.rowsInserted.connect(self.dataChanged)
        choices_model.rowsRemoved.connect(self.dataChanged)
        self.range_default_spinbox.valueChanged.connect(self.dataChanged)
        self.range_minimum_spinbox.valueChanged.connect(self.dataChanged)
        self.range_maximum_spinbox.valueChanged.connect(self.dataChanged)
523
524
        self.stacked_widget.currentChanged.connect(lambda: self.adjustSize())
        self.stacked_widget.currentChanged.connect(self.editorChanged)
525
526
527
528

    def load(self, data):
        """Load the json object passed as parameter"""

529
530
        self.reset(self.current_type)

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
        choices = data.get("choice", [])
        str_choices = [str(item) for item in choices]
        range_values = data.get("range", [-10, 10])
        minimum = range_values[0]
        maximum = range_values[1]
        default = data.get("default", 0)

        if "choice" in data:
            # Check there are no duplicates
            if len(str_choices) != len(set(str_choices)):
                raise RuntimeError("Invalid duplicate choice")
            else:
                if default not in choices:
                    raise RuntimeError("Invalid default choice")
                else:
                    self.choices_button.setChecked(True)
                    self.choices_listwidget.addItems(str_choices)
                    self.choices_default_combobox.addItems(str_choices)
                    index = self.choices_default_combobox.findText(
                        str(default), Qt.MatchFixedString
                    )
                    if index >= 0:
                        self.choices_default_combobox.setCurrentIndex(index)
                    else:
                        raise RuntimeError("Invalid default value")
        elif "range" in data:
            if len(range_values) != len(set(range_values)):
                raise RuntimeError("Invalid duplicate range")
            else:
                if minimum <= default <= maximum:
                    self.range_button.setChecked(True)
                    self.range_maximum_spinbox.setValue(maximum)
                    self.range_minimum_spinbox.setValue(minimum)
                    self.range_default_spinbox.setValue(default)
                else:
                    raise RuntimeError("Invalid default or min/max range")
        else:
            self.single_button.setChecked(True)
            self.single_default_spinbox.setValue(default)

    def dump(self):
        """Returns the json representation of this editor"""

        data = {}
        numpy_type = self.current_type.np_type

        if self.choices_button.isChecked():
            if len(self.choices_default_combobox.currentText()) == 0:
                data["default"] = 0
            else:
                try:
                    data["default"] = numpy_type(
                        self.choices_default_combobox.currentText()
                    )
                except OverflowError:
                    raise RuntimeError("Invalid default value: OverflowError")

            if self.choices_listwidget.count() == 0:
                data["choice"] = []
            else:
                data["choice"] = [
                    numpy_type(self.choices_listwidget.item(i).text())
                    for i in range(self.choices_listwidget.count())
                ]
        elif self.range_button.isChecked():
596
            data["default"] = self.range_default_spinbox.value
597
            data["range"] = [
598
599
                self.range_minimum_spinbox.value,
                self.range_maximum_spinbox.value,
600
601
            ]
        else:
602
            data["default"] = self.single_default_spinbox.value
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

        return data

    def reset(self, selected_type):
        """Reset editor to default values"""

        self.current_type = selected_type

        # reset single state
        self.single_button.setChecked(True)
        self.single_default_spinbox.setNumpyType(self.current_type.np_type)

        # reset choices state
        self.choices_listwidget.clear()
        self.choices_default_combobox.clear()

        # reset range state
        self.range_default_spinbox.setNumpyType(self.current_type.np_type)
        self.range_minimum_spinbox.setNumpyType(self.current_type.np_type)
        self.range_maximum_spinbox.setNumpyType(self.current_type.np_type)

        self.range_minimum_spinbox.setValue(-10)
        self.range_maximum_spinbox.setValue(10)

        # restricted bounds
        self.restrict_range()

    def restrict_set_bounds(self, min_value, max_value, default_value):
        """Ensure that the values entered are in the correct bounds as well as
        ensure that a range is really a range.
        """

635
636
637
        min_value = self.range_minimum_spinbox.value
        max_value = self.range_maximum_spinbox.value
        default_value = self.range_default_spinbox.value
638
639
640
641
642
643
644
645
646
647
648
649
650

        self.range_minimum_spinbox.setMaximum(max_value)
        self.range_maximum_spinbox.setMinimum(min_value)
        self.range_default_spinbox.setMinimum(min_value)
        self.range_default_spinbox.setMaximum(max_value)

        # update default value when out of bounds
        if default_value < min_value:
            self.range_default_spinbox.setValue(min_value)
        if default_value > max_value:
            self.range_default_spinbox.setValue(max_value)

    def restrict_range(self):
651
652
653
        min_value = self.range_minimum_spinbox.value
        max_value = self.range_maximum_spinbox.value
        default_value = self.range_default_spinbox.value
654
655
656
657

        self.restrict_set_bounds(min_value, max_value, default_value)

    def restrict_range_from_min(self):
658
659
660
        min_value = self.range_minimum_spinbox.value
        max_value = self.range_maximum_spinbox.value
        default_value = self.range_default_spinbox.value
661
662
663
664
665
666
667
668
669

        if min_value == max_value:
            self.range_maximum_spinbox.setMinimum(min_value)
            self.range_maximum_spinbox.setValue(min_value + 1)
            self.range_default_spinbox.setMaximum(min_value + 1)
        else:
            self.restrict_set_bounds(min_value, max_value, default_value)

    def restrict_range_from_max(self):
670
671
672
        min_value = self.range_minimum_spinbox.value
        max_value = self.range_maximum_spinbox.value
        default_value = self.range_default_spinbox.value
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718

        if min_value == max_value:
            self.range_minimum_spinbox.setMaximum(max_value)
            self.range_minimum_spinbox.setValue(max_value - 1)
            self.range_default_spinbox.setMinimum(max_value - 1)
        else:
            self.restrict_set_bounds(min_value, max_value, default_value)

    def __setup_single_ui(self):

        layout = QFormLayout()
        layout.addRow(self.tr("Default:"), self.single_default_spinbox)
        self.single_conf_widget.setLayout(layout)

    def __setup_choices_ui(self):

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(self.add_button)
        buttons_layout.addWidget(self.remove_button)
        buttons_layout.addStretch(1)

        choices_layout = QVBoxLayout()
        choices_layout.addWidget(self.choices_listwidget)
        choices_layout.addLayout(buttons_layout)

        layout = QFormLayout()
        layout.addRow(self.tr("Default:"), self.choices_default_combobox)
        layout.addRow(self.tr("Choices:"), choices_layout)

        self.choices_conf_widget.setLayout(layout)

    def __setup_range_ui(self):

        layout = QFormLayout()
        layout.addRow(self.tr("Default:"), self.range_default_spinbox)
        layout.addRow(self.tr("Minimum:"), self.range_minimum_spinbox)
        layout.addRow(self.tr("Maximum:"), self.range_maximum_spinbox)

        self.range_conf_widget.setLayout(layout)

    @pyqtSlot()
    def __onChoiceAddClicked(self):

        input_value = None
        ok = False

719
        input_value, ok = NumericalChoiceDialog.getChoiceValue(self.current_type)
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752

        if ok:
            if (
                len(
                    self.choices_listwidget.findItems(str(input_value), Qt.MatchExactly)
                )
                == 0
            ):
                self.choices_listwidget.addItem(str(input_value))
                self.choices_default_combobox.addItem(str(input_value))

    @pyqtSlot()
    def __onChoiceRemoveClicked(self):

        choices = self.choices_listwidget.selectedItems()
        for choice in choices:
            self.choices_default_combobox.removeItem(
                self.choices_listwidget.row(choice)
            )
            self.choices_listwidget.takeItem(self.choices_listwidget.row(choice))


class ParameterWidget(QWidget):
    """Widget representing a parameter"""

    dataChanged = pyqtSignal()

    def __init__(self, parent=None):
        """Constructor

        :param parent QWidget: parent widget
        """

753
        super().__init__(parent)
754
755
756
757
758
759
760
761
762
763
764
765
766

        unwanted_basetypes = {"complex64", "complex128"}
        basetypes = [
            base_type
            for base_type in dataformat_basetypes()
            if base_type not in unwanted_basetypes
        ]

        # Member variables
        self.description_lineedit = QLineEdit()
        self.basetype_comboxbox = QComboBox()
        self.basetype_comboxbox.addItems(basetypes)
        self.selected_type = InputType[basetypes[0].upper()]
767
        self.setup_stackedwidget = StackedWidget()
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

        # Stacked widgets
        self.numerical_setup_widget = NumericalSetupWidget(self.selected_type)
        self.string_setup_widget = StringSetupWidget(self)
        self.bool_setup_widget = BoolSetupWidget(self)

        self.setup_stackedwidget.addWidget(self.numerical_setup_widget)
        self.setup_stackedwidget.addWidget(self.string_setup_widget)
        self.setup_stackedwidget.addWidget(self.bool_setup_widget)

        layout = QFormLayout(self)
        layout.addRow(self.tr("Description:"), self.description_lineedit)
        layout.addRow(self.tr("Type:"), self.basetype_comboxbox)
        layout.addRow(self.tr("Setup:"), self.setup_stackedwidget)

        # Signal/Slots connections
        self.description_lineedit.textChanged.connect(self.dataChanged)

        self.basetype_comboxbox.currentIndexChanged.connect(self.__onTypeWidgetChanged)
        self.setup_stackedwidget.currentChanged.connect(self.dataChanged)
788
        self.setup_stackedwidget.currentChanged.connect(lambda: self.adjustSize())
789
790

        self.numerical_setup_widget.dataChanged.connect(self.dataChanged)
791
792
        self.numerical_setup_widget.editorChanged.connect(lambda: self.adjustSize())

793
        self.string_setup_widget.dataChanged.connect(self.dataChanged)
794
795
        self.string_setup_widget.editorChanged.connect(lambda: self.adjustSize())

796
797
798
799
800
801
        self.bool_setup_widget.dataChanged.connect(self.dataChanged)

    @pyqtSlot()
    def __onTypeWidgetChanged(self):
        self.selected_type = InputType[self.basetype_comboxbox.currentText().upper()]

802
        selected_widget = None
803
804
        if self.selected_type == InputType.BOOL:
            self.bool_setup_widget.reset()
805
            selected_widget = self.bool_setup_widget
806
807
        elif self.selected_type == InputType.STRING:
            self.string_setup_widget.reset()
808
            selected_widget = self.string_setup_widget
809
810
        else:
            self.numerical_setup_widget.reset(self.selected_type)
811
812
813
            selected_widget = self.numerical_setup_widget

        self.setup_stackedwidget.setCurrentWidget(selected_widget)
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855

    def dump(self):
        """Returns the json representation of this editor"""

        data = self.setup_stackedwidget.currentWidget().dump()
        description = self.description_lineedit.text()
        if description:
            data["description"] = description
        data["type"] = self.selected_type.name.lower()

        return data

    def load(self, data):
        """Load the json object passed as parameter"""

        data = data.copy()
        description = data.get("description", "")
        selected_type = data.get("type", None)
        default = data.get("default", None)

        if selected_type is None:
            raise RuntimeError("Invalid parameter with no type")
        if default is None:
            raise RuntimeError("Invalid parameter with no default")

        index = self.basetype_comboxbox.findText(selected_type, Qt.MatchFixedString)
        if index == -1:
            raise RuntimeError("Invalid parameter type value")

        self.basetype_comboxbox.setCurrentIndex(index)
        self.selected_type = InputType[selected_type.upper()]
        self.description_lineedit.setText(description)

        data.pop("type")
        data.pop("description", None)

        if self.selected_type == InputType.BOOL:
            self.bool_setup_widget.load(data)
        elif self.selected_type == InputType.STRING:
            self.string_setup_widget.load(data)
        else:
            self.numerical_setup_widget.load(data)