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
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
# 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/.           #
#                                                                             #
###############################################################################

import numpy as np

from enum import Enum, unique

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
79
80
81
82

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

        return info

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

99

100
101
102
103
104
105
106
107
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):
108
        super().__init__(parent)
109
110
111
112
113
114

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

115
        size = super().size()
116
117
118
119
120
121
122
123
124
        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.
        """

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


131
class NumericalChoiceDialog(QDialog):
132
133
134
135
136
137
138
139
140
    """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
        """

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

        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)

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

164
        return self.spinbox.value
165

166
167
168
169
170
171
172
173
    @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
        """

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

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

        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
        """

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

        # 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"""

219
220
        self.reset()

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
        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()
242
    editorChanged = pyqtSignal()
243
244
245
246
247
248
249

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

        :param parent QWidget: parent widget
        """

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

        # 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
267
        self.single_default_lineedit = QLineEdit()
268
269
270
271
272
273
274
275
276
277
278
279

        # 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
280
        self.stacked_widget = StackedWidget()
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
        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)
302
        self.single_default_lineedit.textChanged.connect(self.dataChanged)
303
304
305
306
307
        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)

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

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

314
315
        self.reset()

316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        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)
339
            self.single_default_lineedit.setText(default)
340
341
342
343
344
345
346

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

        data = {}

        if self.single_button.isChecked():
347
            data["default"] = self.single_default_lineedit.text()
348
349
350
351
352
353
354
355
356
357
358
359
360
        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)
361
        self.single_default_lineedit.clear()
362
363
364
365
366
367
        self.choices_listwidget.clear()
        self.choices_default_combobox.clear()

    def __setup_single_ui(self):

        layout = QFormLayout()
368
        layout.addRow(self.tr("Default:"), self.single_default_lineedit)
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
        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()
420
    editorChanged = pyqtSignal()
421
422
423
424
425
426
427
428

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

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

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

        # 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
485
        self.stacked_widget = StackedWidget(self)
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
        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)
524
525
        self.stacked_widget.currentChanged.connect(lambda: self.adjustSize())
        self.stacked_widget.currentChanged.connect(self.editorChanged)
526
527
528
529

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

530
531
        self.reset(self.current_type)

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
        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():
597
            data["default"] = self.range_default_spinbox.value
598
            data["range"] = [
599
600
                self.range_minimum_spinbox.value,
                self.range_maximum_spinbox.value,
601
602
            ]
        else:
603
            data["default"] = self.single_default_spinbox.value
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

        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.
        """

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

        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):
652
653
654
        min_value = self.range_minimum_spinbox.value
        max_value = self.range_maximum_spinbox.value
        default_value = self.range_default_spinbox.value
655
656
657
658

        self.restrict_set_bounds(min_value, max_value, default_value)

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

        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):
671
672
673
        min_value = self.range_minimum_spinbox.value
        max_value = self.range_maximum_spinbox.value
        default_value = self.range_default_spinbox.value
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
719

        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

720
        input_value, ok = NumericalChoiceDialog.getChoiceValue(self.current_type)
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
753

        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
        """

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

        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()]
768
        self.setup_stackedwidget = StackedWidget()
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788

        # 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)
789
        self.setup_stackedwidget.currentChanged.connect(lambda: self.adjustSize())
790
791

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

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

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

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

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

        self.setup_stackedwidget.setCurrentWidget(selected_widget)
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
856

    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)