toolchaineditor.py 70.2 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/.           #
#                                                                             #
###############################################################################

26
27
28
import simplejson as json

from enum import Enum
29
from functools import partial
30

31
32
33
34
35
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QRect
from PyQt5.QtCore import QRectF
from PyQt5.QtCore import QPointF
from PyQt5.QtCore import pyqtSignal
36
from PyQt5.QtCore import pyqtSlot
37
38
from PyQt5.QtCore import QFile
from PyQt5.QtCore import QIODevice
39
40
41
42
43
44
45

from PyQt5.QtGui import QColor
from PyQt5.QtGui import QBrush
from PyQt5.QtGui import QPen
from PyQt5.QtGui import QFont
from PyQt5.QtGui import QFontMetrics
from PyQt5.QtGui import QPainterPath
46
from PyQt5.QtGui import QTransform
47
from PyQt5.QtGui import QIcon
48

49
from PyQt5.QtWidgets import QHBoxLayout
50
from PyQt5.QtWidgets import QVBoxLayout
51
from PyQt5.QtWidgets import QFormLayout
52
from PyQt5.QtWidgets import QWidget
53
54
55
56
from PyQt5.QtWidgets import QGraphicsView
from PyQt5.QtWidgets import QGraphicsItem
from PyQt5.QtWidgets import QGraphicsPathItem
from PyQt5.QtWidgets import QGraphicsObject
57
from PyQt5.QtWidgets import QToolBar
58
59
60
61
62
63
64
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWidgets import QDialogButtonBox
from PyQt5.QtWidgets import QComboBox
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QMenu
from PyQt5.QtWidgets import QLineEdit
65
from PyQt5.QtWidgets import QMessageBox
66
from PyQt5.QtWidgets import QColorDialog
67
from PyQt5.QtWidgets import QListWidget
68

69
70
from beat.backend.python.algorithm import Algorithm

71
from ..backend.asset import Asset
72
from ..backend.asset import AssetType
73
from ..backend.assetmodel import AssetModel
74
from ..decorators import frozen
Samuel GAIST's avatar
Samuel GAIST committed
75

76
from .editor import AbstractAssetEditor
77
from .drawing_space import DrawingSpace
78
79
from ..backend.resourcemodels import AlgorithmResourceModel
from ..backend.resourcemodels import DatasetResourceModel
80
81


82
class BasePin(QGraphicsObject):
83
84
    """Base class for pin graphics"""

85
86
    dataChanged = pyqtSignal()

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
    def __init__(self, parent, pin, block, pin_brush, pin_pen):

        super().__init__(parent=parent)

        # Highlight
        self.setAcceptHoverEvents(True)

        # Storage
        self.pin_type = None
        self.pin = pin
        self.block = block
        self.brush = pin_brush
        self.pen = pin_pen
        self.block_object = parent

    def shape(self):
        """Define the circle shape of a Pin object"""

        path = QPainterPath()
        path.addRect(self.boundingRect())
        return path

    def paint(self, painter, option, widget):
        """Paint the Pin"""

        painter.setBrush(self.brush)
        painter.setPen(self.pen)

        painter.drawEllipse(self.boundingRect())

117
    def mousePressEvent(self, event):
118
        """Painting connection initiated"""
119
120
121
122
123

        self.new_connection = Connection(self.block_object.connection_style)
        self.block_object.scene().addItem(self.new_connection)

    def mouseMoveEvent(self, event):
124
        """Painting connection in progress"""
125

126
127
128
129
130
131
132
133
134
135
136
137
        # Only one single connection allowed from input pin
        if isinstance(self, InputPin):
            # Check if connection exist and remove if it does
            for connection in self.block_object.toolchain.connections:
                if (
                    connection.end_block == self.block_object
                    and connection.end_pin == self
                ):
                    self.block_object.toolchain.connections.remove(connection)
                    self.block_object.scene().removeItem(connection)
                    self.dataChanged.emit()

138
139
140
141
        mouse_position = self.mapToScene(event.pos())
        self.new_connection.set_new_connection_pins_coordinates(self, mouse_position)

    def mouseReleaseEvent(self, event):
142
        """Painting connection ended - validation required"""
143
144
145
146
147
148

        self.block_object.scene().removeItem(self.new_connection)
        target = self.block_object.scene().itemAt(
            event.scenePos().toPoint(), QTransform()
        )

149
        if isinstance(target, BasePin):
150

151
152
153
            if isinstance(self, OutputPin):
                start = self
                end = target
154
            else:
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
                start = target
                end = self

            if Connection(self.block_object.connection_style).check_validity(
                start, end
            ):

                # Find the corresponding channel
                connection_settings = {}
                if start.block_object.type == BlockType.DATASETS.name:
                    connection_settings["channel"] = start.block_object.name
                else:
                    connection_settings[
                        "channel"
                    ] = start.block_object.synchronized_channel

171
172
173
174
                if end.block_object.synchronized_channel is None:
                    end.block_object.synchronized_channel = connection_settings[
                        "channel"
                    ]
175
176
177
178
179
180
181
182
183
184
185
186
                # Create the connection
                connection_settings["from"] = start.block + "." + start.pin
                connection_settings["to"] = end.block + "." + end.pin

                channel_colors = self.block_object.toolchain.json_object[
                    "representation"
                ]["channel_colors"]

                connection = Connection(self.block_object.connection_style)
                connection.load(
                    self.block_object.toolchain, connection_settings, channel_colors
                )
187
188
189

                self.dataChanged.emit()

190
191
                self.block_object.toolchain.connections.append(connection)
                self.block_object.toolchain.scene.addItem(connection)
192

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    def get_center_point(self):
        """Get the center coordinates of the Pin(x,y)"""

        rect = self.boundingRect()
        pin_center_point = QPointF(
            rect.x() + rect.width() / 2.0, rect.y() + rect.height() / 2.0
        )

        return self.mapToScene(pin_center_point)


class InputPin(BasePin):
    def __init__(self, parent, pin, block, pin_brush, pin_pen):

        super().__init__(parent, pin, block, pin_brush, pin_pen)

    def boundingRect(self):
        """Bounding rect around pin object"""

        height = self.block_object.height / 2.0
        width = height

        x = -(width / 2.0)
216
217

        if self.block_object.type == BlockType.LOOPS.name:
218
            _idx = None
219
220
221
222
223
224
            if self.pin in self.block_object.processor_inputs:
                _idx = self.block_object.processor_inputs.index(self.pin)
            elif self.pin in self.block_object.evaluator_inputs:
                _idx = self.block_object.evaluator_inputs.index(self.pin) + len(
                    self.block_object.processor_inputs
                )
225
226
227
228
            if _idx is not None:
                y = self.block_object.height + _idx * self.block_object.pin_height
            else:
                y = self.block_object.height
229
230
231
232
233
234
        else:
            y = (
                self.block_object.height
                + self.block_object.inputs.index(self.pin)
                * self.block_object.pin_height
            )
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

        rect = QRectF(QRect(x, y, width, height))
        return rect


class OutputPin(BasePin):
    def __init__(self, parent, pin, block, pin_brush, pin_pen):

        super().__init__(parent, pin, block, pin_brush, pin_pen)

    def boundingRect(self):
        """ bounding rect width by height.
        """

        height = self.block_object.height / 2.0
        width = height

        x = self.block_object.custom_width - (width / 2.0)
253
        if self.block_object.type == BlockType.LOOPS.name:
254
            _idx = None
255
256
257
258
259
260
261
            if self.pin in self.block_object.processor_outputs:
                _idx = self.block_object.processor_outputs.index(self.pin)
            elif self.pin in self.block_object.evaluator_outputs:
                _idx = self.block_object.evaluator_outputs.index(self.pin) + len(
                    self.block_object.processor_outputs
                )

262
263
264
265
            if _idx is not None:
                y = self.block_object.height + _idx * self.block_object.pin_height
            else:
                y = self.block_object.height
266
267
268
269
270
271
        else:
            y = (
                self.block_object.height
                + self.block_object.outputs.index(self.pin)
                * self.block_object.pin_height
            )
272
273
274
275
276
277

        rect = QRectF(QRect(x, y, width, height))
        return rect


class Connection(QGraphicsPathItem):
278
    def __init__(self, style):
279
280
281

        super().__init__()

282
283
284
285
286
287
288
        self.start_block_name = None
        self.start_pin_name = None
        self.start_pin_center_point = None
        self.end_block_name = None
        self.end_pin_name = None
        self.end_pin_center_point = None
        self.channel = None
289

290
        self.connection_color = []
291
292
293

        self.set_style(style)

294
295
296
297
298
299
300
301
302
303
304
    def itemChange(self, change, value):
        if change == self.ItemSelectedChange:
            if value:
                color = QColor("red")
            else:
                color = QColor(*self.connection_color)
            pen = self.pen()
            pen.setColor(color)
            self.setPen(pen)
        return QGraphicsItem.itemChange(self, change, value)

305
306
307
308
    def set_style(self, config):

        # Highlight
        self.setAcceptHoverEvents(True)
309
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
310

311
312
        # Geometry and color settings
        self.connection_color = config["color"]
313

314
        self.connection_pen = QPen()
315
        self.connection_pen.setColor(QColor(*self.connection_color))
316
        self.connection_pen.setWidth(config["width"])
317

318
319
320
321
322
    def drawCubicBezierCurve(self):

        self.setPen(self.connection_pen)

        path = QPainterPath()
323
324
325
326
327
328
        middle_point_x = (
            self.end_pin_center_point.x() - self.start_pin_center_point.x()
        ) / 2.0
        middle_point_y = (
            self.end_pin_center_point.y() - self.start_pin_center_point.y()
        ) / 2.0
329
        second_middle_point_y = (
330
            self.end_pin_center_point.y() - self.start_pin_center_point.y()
331
332
333
        ) / 4.0
        control_point = QPointF(middle_point_x, middle_point_y)
        second_control_point = QPointF(middle_point_x, second_middle_point_y)
334
        path.moveTo(self.start_pin_center_point)
335
        path.cubicTo(
336
337
338
            self.start_pin_center_point + control_point,
            self.end_pin_center_point - second_control_point,
            self.end_pin_center_point,
339
340
341
342
        )

        self.setPath(path)

343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    def set_moved_block_pins_coordinates(self):
        self.start_pin_center_point = self.start_pin.get_center_point()
        self.end_pin_center_point = self.end_pin.get_center_point()

        self.drawCubicBezierCurve()

    def set_new_connection_pins_coordinates(self, selected_pin, mouse_position):

        if isinstance(selected_pin, OutputPin):
            self.start_block_name = selected_pin.block
            self.start_pin_name = selected_pin.pin
            self.start_pin = selected_pin
            self.start_pin_center_point = self.start_pin.get_center_point()
            self.end_pin_center_point = mouse_position
        if isinstance(selected_pin, InputPin):
            self.end_block_name = selected_pin.block
            self.end_pin_name = selected_pin.pin
            self.end_pin = selected_pin
            self.end_pin_center_point = self.end_pin.get_center_point()
            self.start_pin_center_point = mouse_position

        self.drawCubicBezierCurve()

366
367
368
369
370
371
372
373
374
375
376
377
378
    def check_validity(self, start, end):

        # remove input-input and output-output connection
        if type(start) == type(end):
            return False

        # remove connection to same block object
        if start.block_object == end.block_object:
            return False

        # check if end block pin is free
        toolchain = end.block_object.toolchain
        for connection in toolchain.connections:
379
380
            if connection.end_block == end.block_object and connection.end_pin == end:
                return False
381
382
383

        return True

384
385
386
387
388
389
390
391
    def load(self, toolchain, connection_details, channel_colors):

        self.start_block_name = connection_details["from"].split(".")[0]
        self.start_pin_name = connection_details["from"].split(".")[1]
        self.end_block_name = connection_details["to"].split(".")[0]
        self.end_pin_name = connection_details["to"].split(".")[1]
        self.channel = connection_details["channel"]

392
        if self.channel is None:
393
394
395
396
397
398
399
400
401
402
            warning = QMessageBox()
            warning.setIcon(QMessageBox.Warning)
            warning.setWindowTitle(toolchain.tr("Connection creation"))
            warning.setInformativeText(
                toolchain.tr("No dataset synchronization channel connection found!")
            )
            warning.setStandardButtons(QMessageBox.Ok)
            warning.exec_()

        else:
403
404
405
406
            if self.channel not in channel_colors:
                toolchain.web_representation["channel_colors"][self.channel] = "#000000"
                channel_colors = toolchain.web_representation["channel_colors"]

407
408
409
410
411
412
413
414
            hexadecimal = channel_colors[self.channel].lstrip("#")
            hlen = len(hexadecimal)
            self.connection_color = list(
                int(hexadecimal[i : i + hlen // 3], 16)
                for i in range(0, hlen, hlen // 3)
            )
            self.connection_color.append(255)
            self.connection_pen.setColor(QColor(*self.connection_color))
415
416
417
418
419
420
421
422
423

        self.blocks = toolchain.blocks

        for block in self.blocks:
            if block.name == self.start_block_name:
                self.start_block = block
            elif block.name == self.end_block_name:
                self.end_block = block

424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
        if self.start_block.type == BlockType.LOOPS.name:
            if self.start_pin_name in self.start_block.pins["outputs"]["processor"]:
                self.start_pin = self.start_block.pins["outputs"]["processor"][
                    self.start_pin_name
                ]
            else:
                self.start_pin = self.start_block.pins["outputs"]["evaluator"][
                    self.start_pin_name
                ]
        else:
            self.start_pin = self.start_block.pins["outputs"][self.start_pin_name]

        if self.end_block.type == BlockType.LOOPS.name:
            if self.end_pin_name in self.end_block.pins["inputs"]["processor"]:
                self.end_pin = self.end_block.pins["inputs"]["processor"][
                    self.end_pin_name
                ]
            else:
                self.end_pin = self.end_block.pins["inputs"]["evaluator"][
                    self.end_pin_name
                ]
        else:
            self.end_pin = self.end_block.pins["inputs"][self.end_pin_name]
447
448
449
450
451
452
453
454
455

        self.start_pin_center_point = self.start_pin.get_center_point()
        self.end_pin_center_point = self.end_pin.get_center_point()

        self.drawCubicBezierCurve()

        self.start_block.blockMoved.connect(self.set_moved_block_pins_coordinates)
        self.end_block.blockMoved.connect(self.set_moved_block_pins_coordinates)

456

457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
class LoopWidget(QDialog):
    """Class holder for the various libraries"""

    dataChanged = pyqtSignal()

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

        super().__init__(parent)

        self.setMinimumHeight(200)

        # Layouts
        layout = QHBoxLayout(self)

        self.sequential_loop_processor_listwidget = QListWidget()
        self.autonomous_loop_processor_listwidget = QListWidget()
        self.sequential_loop_evaluator_listwidget = QListWidget()
        self.autonomous_loop_evaluator_listwidget = QListWidget()

        # QVBoxLayout for available lists
        sequential_loop_processor_listwidget_layout = QVBoxLayout()
        sequential_loop_processor_listwidget_layout.addWidget(
            QLabel(self.tr("Sequential Loop Processor"))
        )
        sequential_loop_processor_listwidget_layout.addWidget(
            self.sequential_loop_processor_listwidget
        )

        autonomous_loop_processor_listwidget_layout = QVBoxLayout()
        autonomous_loop_processor_listwidget_layout.addWidget(
            QLabel(self.tr("Autonomous Loop Processor"))
        )
        autonomous_loop_processor_listwidget_layout.addWidget(
            self.autonomous_loop_processor_listwidget
        )

        sequential_loop_evaluator_listwidget_layout = QVBoxLayout()
        sequential_loop_evaluator_listwidget_layout.addWidget(
            QLabel(self.tr("Sequential Loop Evaluator"))
        )
        sequential_loop_evaluator_listwidget_layout.addWidget(
            self.sequential_loop_evaluator_listwidget
        )

        autonomous_loop_evaluator_listwidget_layout = QVBoxLayout()
        autonomous_loop_evaluator_listwidget_layout.addWidget(
            QLabel(self.tr("Autonomous Loop Evaluator"))
        )
        autonomous_loop_evaluator_listwidget_layout.addWidget(
            self.autonomous_loop_evaluator_listwidget
        )

        # Layouts Design
        layout.addLayout(sequential_loop_processor_listwidget_layout)
        layout.addLayout(autonomous_loop_processor_listwidget_layout)
        layout.addLayout(sequential_loop_evaluator_listwidget_layout)
        layout.addLayout(autonomous_loop_evaluator_listwidget_layout)

    def set_sequential_loop_processor_list(self, _list):
        self.sequential_loop_processor_list = _list
        self.sequential_loop_processor_listwidget.addItems(_list)

    def set_autonomous_loop_processor_list(self, _list):
        self.autonomous_loop_processor_list = _list
        self.autonomous_loop_processor_listwidget.addItems(_list)

    def set_sequential_loop_evaluator_list(self, _list):
        self.sequential_loop_evaluator_list = _list
        self.sequential_loop_evaluator_listwidget.addItems(_list)

    def set_autonomous_loop_evaluator_list(self, _list):
        self.autonomous_loop_evaluator_list = _list
        self.autonomous_loop_evaluator_listwidget.addItems(_list)

    def get_processor_evaluator_loops(self):
        selected_loops = {}

        selected_sequential_loop_processor = (
            self.sequential_loop_processor_listwidget.selectedItems()
        )
        selected_autonomous_loop_processor = (
            self.autonomous_loop_processor_listwidget.selectedItems()
        )
        selected_sequential_loop_evaluator = (
            self.sequential_loop_evaluator_listwidget.selectedItems()
        )
        selected_autonomous_loop_evaluator = (
            self.autonomous_loop_evaluator_listwidget.selectedItems()
        )

        sequential_loop_processor = None
        if selected_sequential_loop_processor:
            sequential_loop_processor = selected_sequential_loop_processor[0].text()

        autonomous_loop_processor = None
        if selected_autonomous_loop_processor:
            autonomous_loop_processor = selected_autonomous_loop_processor[0].text()

        sequential_loop_evaluator = None
        if selected_sequential_loop_evaluator:
            sequential_loop_evaluator = selected_sequential_loop_evaluator[0].text()

        autonomous_loop_evaluator = None
        if selected_autonomous_loop_evaluator:
            autonomous_loop_evaluator = selected_autonomous_loop_evaluator[0].text()

        selected_loops["sequential_loop_processor"] = sequential_loop_processor
        selected_loops["autonomous_loop_processor"] = autonomous_loop_processor
        selected_loops["sequential_loop_evaluator"] = sequential_loop_evaluator
        selected_loops["autonomous_loop_evaluator"] = autonomous_loop_evaluator

        return selected_loops


class LoopDialog(QDialog):
    """Dialog to edit a block"""

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

        :param block: current block
        :param parent QWidget: parent widget
        """

        super().__init__(parent)
        self.setWindowTitle(self.tr("Add Loop"))

        layout = QVBoxLayout(self)

        # Layouts Widget
        self.loop_widget = LoopWidget()
        layout.addWidget(self.loop_widget)

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

    def value(self):
        """Returns the value selected"""

        return self.loop_widget.get_processor_evaluator_loops()

    def set_lists(
        self,
        sequential_loop_processor_list,
        autonomous_loop_processor_list,
        sequential_loop_evaluator_list,
        autonomous_loop_evaluator_list,
    ):

        self.loop_widget.set_sequential_loop_processor_list(
            sequential_loop_processor_list
        )
        self.loop_widget.set_autonomous_loop_processor_list(
            autonomous_loop_processor_list
        )
        self.loop_widget.set_sequential_loop_evaluator_list(
            sequential_loop_evaluator_list
        )
        self.loop_widget.set_autonomous_loop_evaluator_list(
            autonomous_loop_evaluator_list
        )

    @staticmethod
    def getLoops(
        toolchain,
        sequential_loop_processor_list,
        autonomous_loop_processor_list,
        sequential_loop_evaluator_list,
        autonomous_loop_evaluator_list,
        parent=None,
    ):
        """Static method to create the dialog and return qdialog accepted/spinbox value

        :param block: current block
        :param parent QWidget: parent widget
        """

        dialog = LoopDialog(toolchain, parent)
        dialog.set_lists(
            sequential_loop_processor_list,
            autonomous_loop_processor_list,
            sequential_loop_evaluator_list,
            autonomous_loop_evaluator_list,
        )
        result = dialog.exec_()
        value = None

        if result == QDialog.Accepted:
            value = dialog.value()

        return (value, result)


659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
class BlockEditionDialog(QDialog):
    """Dialog to edit a block"""

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

        :param block: current block
        :param parent QWidget: parent widget
        """

        super().__init__(parent)

        toolchain = block.toolchain
        self.setWindowTitle(self.tr("Block Edition"))
        self.name_lineedit = QLineEdit(block.name)
674
        self.color = "#000000"
675
676
677
678
679
680
681
682
        self.channel_combobox = QComboBox()
        no_channel_label = QLabel(self.tr("No input connections yet!"))
        no_dataset_channel_label = QLabel(self.tr("No synchronization for datasets"))

        layout = QFormLayout(self)
        layout.addRow(self.tr("Name:"), self.name_lineedit)

        channels = []
683

684
        if block.type == BlockType.DATASETS.name:
685
686
687
            channel_color_button = QPushButton("Channel color", self)
            channel_color_button.setToolTip("Opens color dialog")
            channel_color_button.clicked.connect(self.on_color_click)
688
            layout.addRow(self.tr("Channel:"), no_dataset_channel_label)
689
            layout.addRow(self.tr("Channel color:"), channel_color_button)
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
        elif block.synchronized_channel is None:
            layout.addRow(self.tr("Channel:"), no_channel_label)
        else:
            for connection in toolchain.connections:
                if connection.end_block == block and connection.channel not in channels:
                    channels.append(connection.channel)
            self.channel_combobox.addItems(channels)
            # set current channel if exists
            index = self.channel_combobox.findText(
                str(block.synchronized_channel), Qt.MatchFixedString
            )
            if index >= 0:
                self.channel_combobox.setCurrentIndex(index)

            layout.addRow(self.tr("Channel:"), self.channel_combobox)

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

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

717
718
719
720
721
722
723
724
725
726
    @pyqtSlot()
    def on_color_click(self):
        self.colorDialog()

    def colorDialog(self):
        color = QColorDialog.getColor()

        if color.isValid():
            self.color = color.name().capitalize()

727
728
729
730
731
732
    def value(self):
        """Returns the value selected"""

        return {
            "name": self.name_lineedit.text(),
            "channel": self.channel_combobox.currentText(),
733
            "color": self.color,
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
        }

    @staticmethod
    def getNewBlockSettings(block, parent=None):
        """Static method to create the dialog and return qdialog accepted/spinbox value

        :param block: current block
        :param parent QWidget: parent widget
        """

        dialog = BlockEditionDialog(block, parent)
        result = dialog.exec_()
        value = None

        if result == QDialog.Accepted:
            value = dialog.value()

        return (value, result)


754
755
756
757
758
759
class BlockType(Enum):
    """All possible block types"""

    BLOCKS = "blocks"
    ANALYZERS = "analyzers"
    DATASETS = "datasets"
760
    LOOPS = "loops"
761

762
763
764
765
766
767
768
    @classmethod
    def from_name(cls, name):
        try:
            return cls[name]
        except ValueError:
            raise ValueError("{} is not a valid block type".format(name))

769
770
771
772

class Block(QGraphicsObject):
    """Block item"""

773
    dataChanged = pyqtSignal()
774
775
    blockMoved = pyqtSignal()

776
    def __init__(self, block_type, style, connection_style):
777
778
779
        super().__init__()

        # Block information
780
781
        self.type = block_type
        self.name = ""
782

783
784
785
786
787
        if self.type == BlockType.LOOPS.name:
            self.processor_inputs = []
            self.processor_outputs = []
            self.evaluator_inputs = []
            self.evaluator_outputs = []
788
        else:
789
790
791
792
            if self.type == BlockType.DATASETS.name:
                self.inputs = None
            else:
                self.inputs = []
793

794
795
796
797
            if self.type == BlockType.ANALYZERS.name:
                self.outputs = None
            else:
                self.outputs = []
798
799

        self.synchronized_channel = None
800
801

        self.style = style
802
        self.connection_style = connection_style
803

804
        self.position = QPointF(0, 0)
805
806
807
808
        self.pins = dict()
        self.pins["inputs"] = dict()
        self.pins["outputs"] = dict()

809
810
811
812
813
814
        if self.type == BlockType.LOOPS.name:
            self.pins["inputs"]["processor"] = dict()
            self.pins["outputs"]["processor"] = dict()
            self.pins["inputs"]["evaluator"] = dict()
            self.pins["outputs"]["evaluator"] = dict()

815
        self.set_style(style)
816
817
818

    def load(self, toolchain, block_details):
        self.toolchain = toolchain
819
820
821

        if "name" in block_details:
            self.name = block_details["name"]
822

823
824
825
826
827
828
829
830
831
832
833
        if self.type == BlockType.LOOPS.name:
            self.processor_inputs = block_details["processor_inputs"]
            self.processor_outputs = block_details["processor_outputs"]
            self.evaluator_inputs = block_details["evaluator_inputs"]
            self.evaluator_outputs = block_details["evaluator_outputs"]
        else:
            if (
                self.type != BlockType.DATASETS.name
                and self.type != BlockType.LOOPS.name
            ):
                self.inputs = block_details["inputs"]
834

835
836
837
838
839
            if (
                self.type != BlockType.ANALYZERS.name
                and self.type != BlockType.LOOPS.name
            ):
                self.outputs = block_details["outputs"]
840
841
842
843
844

        if "synchronized_channel" in block_details:
            self.synchronized_channel = block_details["synchronized_channel"]

        self.set_style(self.style)
845
846
847
848
        self.create_pins()

    def create_pins(self):

849
850
        if self.type == BlockType.LOOPS.name:
            for pin_name in self.processor_inputs:
851
852
853
                input_pin = InputPin(
                    self, pin_name, self.name, self.pin_brush, self.pin_pen
                )
854
                self.pins["inputs"]["processor"][pin_name] = input_pin
855

856
857
                input_pin.dataChanged.connect(self.dataChanged)

858
            for pin_name in self.processor_outputs:
859
860
861
                output_pin = OutputPin(
                    self, pin_name, self.name, self.pin_brush, self.pin_pen
                )
862
                self.pins["outputs"]["processor"][pin_name] = output_pin
863

864
865
                output_pin.dataChanged.connect(self.dataChanged)

866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
            for pin_name in self.evaluator_inputs:
                input_pin = InputPin(
                    self, pin_name, self.name, self.pin_brush, self.pin_pen
                )
                self.pins["inputs"]["evaluator"][pin_name] = input_pin

                input_pin.dataChanged.connect(self.dataChanged)

            for pin_name in self.evaluator_outputs:
                output_pin = OutputPin(
                    self, pin_name, self.name, self.pin_brush, self.pin_pen
                )
                self.pins["outputs"]["evaluator"][pin_name] = output_pin

                output_pin.dataChanged.connect(self.dataChanged)
        else:
            if self.inputs is not None:
                for pin_name in self.inputs:
                    input_pin = InputPin(
                        self, pin_name, self.name, self.pin_brush, self.pin_pen
                    )
                    self.pins["inputs"][pin_name] = input_pin

                    input_pin.dataChanged.connect(self.dataChanged)

            if self.outputs is not None:
                for pin_name in self.outputs:
                    output_pin = OutputPin(
                        self, pin_name, self.name, self.pin_brush, self.pin_pen
                    )
                    self.pins["outputs"][pin_name] = output_pin

                    output_pin.dataChanged.connect(self.dataChanged)

900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
    def set_style(self, config):

        self.setAcceptHoverEvents(True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemIsMovable)

        # Geometry settings
        self.width = config["width"]
        self.height = config["height"]
        self.border = config["border"]
        self.radius = config["radius"]
        self.pin_height = config["pin_height"]

        self.text_font = QFont(config["font"], config["font_size"], QFont.Bold)
        self.pin_font = QFont(config["pin_font"], config["pin_font_size"], QFont.Normal)

        metrics = QFontMetrics(self.text_font)
917
        text_width = metrics.boundingRect(self.name).width() + 24
918

919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
        if self.type == BlockType.LOOPS.name:
            if len(self.processor_inputs) > 0:
                self.max_processor_inputs_width = (
                    metrics.boundingRect(max(self.processor_inputs, key=len)).width()
                    + 24
                )
            else:
                self.max_processor_inputs_width = 24

            if len(self.evaluator_inputs) > 0:
                self.max_evaluator_inputs_width = (
                    metrics.boundingRect(max(self.evaluator_inputs, key=len)).width()
                    + 24
                )
            else:
                self.max_evaluator_inputs_width = 24

            self.max_inputs_width = max(
                self.max_processor_inputs_width, self.max_evaluator_inputs_width
938
939
            )

940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
            if len(self.processor_outputs) > 0:
                self.max_processor_outputs_width = (
                    metrics.boundingRect(max(self.processor_outputs, key=len)).width()
                    + 24
                )
            else:
                self.max_processor_outputs_width = 24

            if len(self.evaluator_outputs) > 0:
                self.max_evaluator_outputs_width = (
                    metrics.boundingRect(max(self.evaluator_outputs, key=len)).width()
                    + 24
                )
            else:
                self.max_evaluator_outputs_width = 24

            self.max_outputs_width = max(
                self.max_processor_outputs_width, self.max_evaluator_outputs_width
958
959
            )
        else:
960
961
962
963
964
965
966
967
968
969
970
971
972
            if self.inputs is not None and len(self.inputs) > 0:
                self.max_inputs_width = (
                    metrics.boundingRect(max(self.inputs, key=len)).width() + 24
                )
            else:
                self.max_inputs_width = 24

            if self.outputs is not None and len(self.outputs) > 0:
                self.max_outputs_width = (
                    metrics.boundingRect(max(self.outputs, key=len)).width() + 24
                )
            else:
                self.max_outputs_width = 24
973
974
975
976
977

        self.custom_width = max(
            self.max_outputs_width + self.max_inputs_width, text_width
        )

978
979
        self.custom_height = self.height

980
981
982
983
984
985
        self.center = QPointF()
        self.center.setX(self.custom_width / 2.0)
        self.center.setY(self.height / 2.0)

        self.background_brush = QBrush()
        self.background_brush.setStyle(Qt.SolidPattern)
986
987
988
989

        self.background_color_datasets = QColor(*config["background_color_datasets"])
        self.background_color_analyzers = QColor(*config["background_color_analyzers"])
        self.background_color_blocks = QColor(*config["background_color_blocks"])
990
        self.background_color_loops = QColor(*config["background_color_loops"])
991
992

        self.background_brush.setColor(self.background_color_blocks)
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025

        self.background_pen = QPen()
        self.background_pen.setStyle(Qt.SolidLine)
        self.background_pen.setWidth(0)
        self.background_pen.setColor(QColor(*config["background_color"]))

        self.border_pen = QPen()
        self.border_pen.setStyle(Qt.SolidLine)
        self.border_pen.setWidth(self.border)
        self.border_pen.setColor(QColor(*config["border_color"]))

        self.selection_border_pen = QPen()
        self.selection_border_pen.setStyle(Qt.SolidLine)
        self.selection_border_pen.setWidth(self.border)
        self.selection_border_pen.setColor(QColor(*config["selection_border_color"]))

        self.text_pen = QPen()
        self.text_pen.setStyle(Qt.SolidLine)
        self.text_pen.setColor(QColor(*config["text_color"]))

        self._pin_brush = QBrush()
        self._pin_brush.setStyle(Qt.SolidPattern)

        self.pin_pen = QPen()
        self.pin_pen.setStyle(Qt.SolidLine)

        self.pin_brush = QBrush()
        self.pin_brush.setStyle(Qt.SolidPattern)
        self.pin_brush.setColor(QColor(*config["pin_color"]))

    def boundingRect(self):
        """Bounding rect of the block object width by height"""
        metrics = QFontMetrics(self.text_font)
1026
        text_height = metrics.boundingRect(self.name).height() + 24
1027

1028
1029
1030
1031
1032
        if self.type == BlockType.LOOPS.name:
            max_pin_height = max(
                len(self.processor_inputs) + len(self.evaluator_inputs),
                len(self.processor_outputs) + len(self.evaluator_outputs),
            )
1033
        else:
1034
1035
1036
1037
1038
1039
1040
1041
            if self.inputs is not None and self.outputs is not None:
                max_pin_height = max(len(self.inputs), len(self.outputs))
            elif self.inputs is not None and self.outputs is None:
                max_pin_height = len(self.inputs)
            elif self.inputs is None and self.outputs is not None:
                max_pin_height = len(self.outputs)
            else:
                max_pin_height = 0
1042

1043
1044
1045
1046
        if max_pin_height == 0:
            self.custom_width = 55
            self.height = 55

1047
1048
        self.custom_height = (
            text_height + self.height + max_pin_height * self.pin_height
1049
        )
1050
        rect = QRect(0, -text_height, self.custom_width, self.custom_height)
1051
1052
1053
        rect = QRectF(rect)
        return rect

1054
    def draw_pins_name(self, painter, _type, data, offset):
1055
        """Paint pin with name"""
1056
        offset = offset * self.pin_height
1057
1058
1059
1060
1061
1062
1063
        if offset != 0:
            # add processor/evaluator separator line
            painter.setPen(self.pin_pen)
            separator_height = self.height - self.radius + offset
            painter.drawLine(
                self.border, separator_height, self.custom_width, separator_height
            )
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
        for pin_name in data:
            # Pin rect
            painter.setBrush(self.background_brush)
            painter.setPen(self.background_pen)
            painter.setFont(self.pin_font)

            coord_x = self.border / 2
            alignement = Qt.AlignLeft

            max_width = self.max_inputs_width
            if _type == "output":
                coord_x = self.custom_width - self.max_outputs_width - self.border / 2
                max_width = self.max_outputs_width
                alignement = Qt.AlignRight

            rect = QRect(
                coord_x, self.height - self.radius + offset, max_width, self.pin_height
            )

            textRect = QRect(
                rect.left() + self.radius,
                rect.top() + self.radius,
                rect.width() - 2 * self.radius,
                rect.height(),
            )

            painter.setPen(self.pin_pen)
            painter.drawText(textRect, alignement, pin_name)

            offset += self.pin_height

    def mouseMoveEvent(self, event):
        """Update connections due to new block position"""

        super(Block, self).mouseMoveEvent(event)

1100
1101
        self.position = self.scenePos()

1102
        self.blockMoved.emit()
1103
        self.dataChanged.emit()
1104

1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
    def mouseDoubleClickEvent(self, event):
        """Update block information"""
        value = None
        ok = False
        block_updated = False

        value, ok = BlockEditionDialog.getNewBlockSettings(self)

        old_name = self.name
        old_channel = self.synchronized_channel

        if ok:
            if self.name != value["name"]:
1118
                old_name = self.name
1119
                self.name = value["name"]
1120
1121
1122
1123
1124
1125
1126
                if self.type == BlockType.DATASETS.name:
                    self.toolchain.web_representation["channel_colors"][
                        self.name
                    ] = self.toolchain.web_representation["channel_colors"].pop(
                        old_name
                    )

1127
1128
1129
1130
1131
1132
1133
                block_updated = True
            if (
                self.synchronized_channel != value["channel"]
                and self.type != BlockType.DATASETS.name
            ):
                self.synchronized_channel = value["channel"]
                block_updated = True
1134
1135
1136
1137
1138
            if self.type == BlockType.DATASETS.name:
                self.toolchain.web_representation["channel_colors"][self.name] = value[
                    "color"
                ]
                block_updated = True
1139
1140
1141

        if block_updated:
            block_item = {}
1142
1143
1144
            if self.type == BlockType.LOOPS.name:
                block_item["processor_inputs"] = self.processor_inputs
                block_item["processor_outputs"] = self.processor_outputs
1145
                block_item["evaluator_inputs"] = self.evaluator_inputs
1146
1147
1148
1149
1150
                block_item["evaluator_outputs"] = self.evaluator_outputs
            # Update blocks
            else:
                block_item["inputs"] = self.inputs
                block_item["outputs"] = self.outputs
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
            block_item["name"] = self.name
            block_item["synchronized_channel"] = self.synchronized_channel

            self.toolchain.blocks.remove(self)
            self.scene().removeItem(self)

            self.load(self.toolchain, block_item)
            self.dataChanged.connect(self.toolchain.dataChanged)
            self.toolchain.blocks.append(self)
            self.toolchain.scene.addItem(self)

            # if type is dataset: update sync channels everywhere
            if self.type == BlockType.DATASETS.name:
                for block in self.toolchain.blocks:
                    if (
                        block.type != BlockType.DATASETS.name
                        and block.synchronized_channel == old_name
                    ):
                        block.synchronized_channel = self.name

            # Update connections
            for connection in self.toolchain.connections:
                # Name update
                if connection.start_block_name == old_name:
                    connection.start_block_name = self.name
                if connection.end_block_name == old_name:
                    connection.end_block_name = self.name
                if connection.channel == old_name:
                    connection.channel = self.name

1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
                # color update
                self.toolchain.scene.removeItem(connection)

                # Find the corresponding channel
                connection_settings = {}
                connection_settings["channel"] = connection.channel
                # Create the connection
                connection_settings["from"] = (
                    connection.start_block_name + "." + connection.start_pin_name
                )
                connection_settings["to"] = (
                    connection.end_block_name + "." + connection.end_pin_name
                )

                channel_colors = self.toolchain.json_object.get(
                    "representation", {}
                ).get("channel_colors")
                connection.load(self.toolchain, connection_settings, channel_colors)

                self.toolchain.scene.addItem(connection)

1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
            # Complete toolchain channel update from current block
            if old_channel != self.synchronized_channel:
                self.toolchain.update_channel_path(
                    self, old_channel, self.synchronized_channel
                )

            # Update representation
            web_representation = self.toolchain.web_representation
            for key, value in web_representation.items():
                for sub_key, sub_value in web_representation[key].items():
                    if sub_key == old_name:
                        # blocks and channel_colors
                        new_sub_key = sub_key.replace(old_name, self.name)
                        web_representation[key][new_sub_key] = web_representation[
                            key
                        ].pop(sub_key)
                    elif "/" in sub_key:
                        # connections
                        new_sub_key = sub_key
                        left_part = sub_key.split("/")[0]
                        right_part = sub_key.split("/")[1]

                        if left_part.split(".")[0] == old_name:
                            new_sub_key = (
                                self.name
                                + "."
                                + left_part.split(".")[1]
                                + "/"
                                + right_part
                            )
                        if right_part.split(".")[0] == old_name:
                            new_sub_key = (
                                left_part
                                + "/"
                                + self.name
                                + "."
                                + right_part.split(".")[1]
                            )
                        if new_sub_key != sub_key:
                            web_representation[key][new_sub_key] = web_representation[
                                key
                            ].pop(sub_key)

            self.dataChanged.emit()

1247
1248
1249
1250
    def paint(self, painter, option, widget):
        """Paint the block"""

        # Design tools
1251
1252
1253
1254
        if self.type == BlockType.DATASETS.name:
            self.background_brush.setColor(self.background_color_datasets)
        elif self.type == BlockType.ANALYZERS.name:
            self.background_brush.setColor(self.background_color_analyzers)
1255
1256
        elif self.type == BlockType.LOOPS.name:
            self.background_brush.setColor(self.background_color_loops)
1257

1258
1259
1260
        painter.setBrush(self.background_brush)
        painter.setPen(self.border_pen)

1261
1262
1263
1264
1265
        if self.type == BlockType.LOOPS.name:
            max_pin_height = max(
                len(self.processor_inputs) + len(self.evaluator_inputs),
                len(self.processor_outputs) + len(self.evaluator_outputs),
            )
1266
        else:
1267
1268
1269
1270
1271
1272
1273
1274
            if self.inputs is not None and self.outputs is not None:
                max_pin_height = max(len(self.inputs), len(self.outputs))
            elif self.inputs is not None and self.outputs is None:
                max_pin_height = len(self.inputs)
            elif self.inputs is None and self.outputs is not None:
                max_pin_height = len(self.outputs)
            else:
                max_pin_height = 0
1275

1276
1277
1278
1279
1280
1281
1282
        if self.isSelected():
            self.selection_border_pen.setWidth(3)
            painter.setPen(self.selection_border_pen)
        else:
            self.border_pen.setWidth(0)
            painter.setPen(self.border_pen)

1283
1284
1285
1286
        if max_pin_height == 0:
            self.custom_width = 55
            self.height = 55

1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
        painter.drawRoundedRect(
            0,
            0,
            self.custom_width,
            self.height + max_pin_height * self.pin_height,
            self.radius,
            self.radius,
        )

        # Block name
        painter.setPen(self.text_pen)
        painter.setFont(self.text_font)

        metrics = QFontMetrics(painter.font())
1301
1302
        text_width = metrics.boundingRect(self.name).width() + 24
        text_height = metrics.boundingRect(self.name).height() + 24
1303
1304
1305
1306
1307
1308
        margin = (text_width - self.custom_width) * 0.5
        text_rect = QRect(-margin, -text_height, text_width, text_height)

        painter.drawText(text_rect, Qt.AlignCenter, self.name)

        # Pin
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
        if self.type == BlockType.LOOPS.name:
            self.draw_pins_name(painter, "input", self.processor_inputs, 0)
            self.draw_pins_name(
                painter, "input", self.evaluator_inputs, len(self.processor_inputs)
            )
            self.draw_pins_name(painter, "output", self.processor_outputs, 0)
            self.draw_pins_name(
                painter, "output", self.evaluator_outputs, len(self.processor_outputs)
            )
        else:
            if self.inputs is not None:
                self.draw_pins_name(painter, "input", self.inputs, 0)
            if self.outputs is not None:
                self.draw_pins_name(painter, "output", self.outputs, 0)
1323
1324


1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
class ToolchainView(QGraphicsView):
    def __init__(self, toolchain):
        super().__init__()

        self.toolchain = toolchain

    def wheelEvent(self, event):
        """In/Out zoom view using the mouse wheel"""

        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        factor = (event.angleDelta().y() / 120) * 0.1
        self.scale(1 + factor, 1 + factor)

    def keyPressEvent(self, event):
        """Focus on the toolchain when F key pressed"""
        if event.key() == Qt.Key_F:
            self.custom_focus()
1342
        if event.key() == Qt.Key_Backspace or event.key() == Qt.Key_Delete:
1343
            self.delete_blocks()
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369

    def custom_focus(self):
        """Custom focus on toolchain"""

        selected_blocks = self.scene().selectedItems()
        if selected_blocks:
            x_list = []
            y_list = []
            width_list = []
            height_list = []
            for block in selected_blocks:
                x_list.append(block.scenePos().x())
                y_list.append(block.scenePos().y())
                width_list.append(block.boundingRect().width())
                height_list.append(block.boundingRect().height())
                min_x = min(x_list)
                min_y = min(y_list) + block.boundingRect().y()
                max_width = max(x_list) + max(width_list) - min_x
                max_height = max(y_list) + max(height_list) - min_y
            rect = QRectF(QRect(min_x, min_y, max_width, max_height))
            toolchain_focus = rect
        else:
            toolchain_focus = self.scene().itemsBoundingRect()

        self.fitInView(toolchain_focus, Qt.KeepAspectRatio)

1370
1371
    def delete_blocks(self):
        """Custom deletion on toolchain"""
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382

        selected_items = self.scene().selectedItems()
        if selected_items:
            for item in selected_items:
                if isinstance(item, Connection):
                    self.toolchain.connections.remove(item)
                    self.scene().removeItem(item)
                    self.toolchain.dataChanged.emit()
                elif isinstance(item, Block):
                    num_connections = 0
                    for connection in self.toolchain.connections:
1383
                        if (
1384
1385
                            item.name == connection.start_block_name
                            or item.name == connection.end_block_name
1386
                        ):
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
                            num_connections += 1
                    if num_connections > 0:
                        warning = QMessageBox()
                        warning.setIcon(QMessageBox.Warning)
                        warning.setWindowTitle(self.tr("Deleting connected block"))
                        warning.setInformativeText(
                            self.tr("You can't delete a connected block!")
                        )
                        warning.setStandardButtons(QMessageBox.Ok)
                        warning.exec_()
                    else:
                        if item.type == BlockType.DATASETS.name:
                            if (
                                item.name
                                in self.toolchain.web_representation["channel_colors"]
                            ):
                                self.toolchain.web_representation["channel_colors"].pop(
                                    item.name
                                )
                        self.toolchain.web_representation["blocks"].pop(item.name)

                        self.toolchain.blocks.remove(item)
                        self.scene().removeItem(item)
                        self.toolchain.dataChanged.emit()
1411

1412

1413
1414
class Toolchain(QWidget):
    """Toolchain designer"""
1415

1416
1417
    dataChanged = pyqtSignal()

1418
1419
1420
1421
1422
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.json_object = {}

1423
1424
1425
1426
1427
        self.sequential_loop_processor_list = []
        self.autonomous_loop_processor_list = []
        self.sequential_loop_evaluator_list = []
        self.autonomous_loop_evaluator_list = []

1428
        config_data = {}
1429
        _file = QFile(":/resources/toolchain_style_config")
1430
1431
        if _file.open(QFile.ReadOnly | QIODevice.Text):
            config_data = json.loads(_file.readAll().data().decode("utf-8"))
1432
1433
1434
1435
1436
1437
1438

        self.scene_config = config_data["drawing_space_config"]
        self.scene = DrawingSpace(self.scene_config)

        self.block_config = config_data["block_config"]
        self.connection_config = config_data["connection_config"]

1439
1440
        self.view = ToolchainView(self)
        self.view.setScene(self.scene)
1441
1442
1443

        self.toolbar = QToolBar()

1444
1445
        self.loop_button = QPushButton()
        self.loop_button.setToolTip("Loop")
1446
        self.loop_button.setIcon(QIcon(":/resources/loop"))
1447
        self.loop_button.clicked.connect(self.add_loop_block)
1448

1449
1450
        self.dataset_button = QPushButton()
        self.dataset_button.setToolTip("Dataset")
1451
        self.dataset_button.setIcon(QIcon(":/resources/dataset"))
1452
1453
1454
1455
        self.dataset_edit_menu = QMenu(self)

        self.block_button = QPushButton()
        self.block_button.setToolTip("Block")
1456
        self.block_button.setIcon(QIcon(":/resources/block"))
1457
        self.block_edit_menu = QMenu(self)
1458

1459
1460
        self.analyzer_button = QPushButton()
        self.analyzer_button.setToolTip("Analyzer")
1461
        self.analyzer_button.setIcon(QIcon(":/resources/analyzer"))
1462
1463
1464
1465
1466
        self.analyzer_edit_menu = QMenu(self)

        self.toolbar.addWidget(self.dataset_button)
        self.toolbar.addWidget(self.block_button)
        self.toolbar.addWidget(self.analyzer_button)
1467
        self.toolbar.addWidget(self.loop_button)
1468
1469
1470
1471
1472

        self.toolbar.setOrientation(Qt.Vertical)

        layout = QHBoxLayout(self)
        layout.addWidget(self.toolbar)
1473
        layout.addWidget(self.view)
1474

1475
1476
1477
1478
1479
1480
1481
1482
1483
    def add_loop_block(self):
        loops, ok = LoopDialog.getLoops(
            self,
            self.sequential_loop_processor_list,
            self.autonomous_loop_processor_list,
            self.sequential_loop_evaluator_list,
            self.autonomous_loop_evaluator_list,
        )

1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
        if ok:
            sequential_loop_processor = loops["sequential_loop_processor"]
            autonomous_loop_processor = loops["autonomous_loop_processor"]
            sequential_loop_evaluator = loops["sequential_loop_evaluator"]
            autonomous_loop_evaluator = loops["autonomous_loop_evaluator"]

            if sequential_loop_processor is None and autonomous_loop_processor is None:
                raise ValueError("No processor selected!")
            elif (
                sequential_loop_evaluator is None and autonomous_loop_evaluator is None
            ):
                raise ValueError("No evaluator selected!")
            elif (
                sequential_loop_processor is not None
                and autonomous_loop_processor is not None
            ):
                raise ValueError("Two processors selected!")
            elif (
                sequential_loop_evaluator is not None
                and autonomous_loop_evaluator is not None
            ):
                raise ValueError("Two evaluators selected!")
1506
            else:
1507
1508
                processor_asset = None
                evaluator_asset = None
1509

1510
1511
1512
1513
                processor_inputs = []
                processor_outputs = []
                evaluator_inputs = []
                evaluator_outputs = []
1514

1515
1516
1517
1518
1519
1520
1521
1522
                if sequential_loop_processor is not None:
                    processor_asset = Asset(
                        self.prefix_path, AssetType.ALGORITHM, sequential_loop_processor
                    )
                else:
                    processor_asset = Asset(
                        self.prefix_path, AssetType.ALGORITHM, autonomous_loop_processor
                    )
1523

1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562