toolchaineditor.py 41.7 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
39
40
41
42
43

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
44
from PyQt5.QtGui import QTransform
45
from PyQt5.QtGui import QIcon
46

47
from PyQt5.QtWidgets import QHBoxLayout
48
from PyQt5.QtWidgets import QFormLayout
49
from PyQt5.QtWidgets import QWidget
50
51
52
53
from PyQt5.QtWidgets import QGraphicsView
from PyQt5.QtWidgets import QGraphicsItem
from PyQt5.QtWidgets import QGraphicsPathItem
from PyQt5.QtWidgets import QGraphicsObject
54
from PyQt5.QtWidgets import QToolBar
55
56
57
58
59
60
61
62
63
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

from ..backend.asset import Asset
64
from ..backend.asset import AssetType
65
from ..backend.assetmodel import AssetModel
66
from ..decorators import frozen
Samuel GAIST's avatar
Samuel GAIST committed
67

68
from .editor import AbstractAssetEditor
69
from .drawing_space import DrawingSpace
70
71
from ..backend.resourcemodels import AlgorithmResourceModel
from ..backend.resourcemodels import DatasetResourceModel
72
73


74
class BasePin(QGraphicsObject):
75
76
    """Base class for pin graphics"""

77
78
    dataChanged = pyqtSignal()

79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    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())

109
    def mousePressEvent(self, event):
110
        """Painting connection initiated"""
111
112
113
114
115

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

    def mouseMoveEvent(self, event):
116
        """Painting connection in progress"""
117

118
119
120
121
122
123
124
125
126
127
128
129
        # 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()

130
131
132
133
        mouse_position = self.mapToScene(event.pos())
        self.new_connection.set_new_connection_pins_coordinates(self, mouse_position)

    def mouseReleaseEvent(self, event):
134
        """Painting connection ended - validation required"""
135
136
137
138
139
140

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

141
        if isinstance(target, BasePin):
142

143
144
145
            if isinstance(self, OutputPin):
                start = self
                end = target
146
            else:
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
                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

163
164
165
166
                if end.block_object.synchronized_channel is None:
                    end.block_object.synchronized_channel = connection_settings[
                        "channel"
                    ]
167
168
169
170
171
172
173
174
175
176
177
178
                # 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
                )
179
180
181

                self.dataChanged.emit()

182
183
                self.block_object.toolchain.connections.append(connection)
                self.block_object.toolchain.scene.addItem(connection)
184

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
    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)
        y = (
            self.block_object.height
210
            + self.block_object.inputs.index(self.pin) * self.block_object.pin_height
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        )

        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)
        y = (
            self.block_object.height
232
            + self.block_object.outputs.index(self.pin) * self.block_object.pin_height
233
234
235
236
237
238
239
        )

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


class Connection(QGraphicsPathItem):
240
    def __init__(self, style):
241
242
243

        super().__init__()

244
245
246
247
248
249
250
        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
251

252
        self.connection_color = []
253
254
255
256
257
258
259
260

        self.set_style(style)

    def set_style(self, config):

        # Highlight
        self.setAcceptHoverEvents(True)

261
262
        # Geometry and color settings
        self.connection_color = config["color"]
263

264
        self.connection_pen = QPen()
265
        self.connection_pen.setColor(QColor(*self.connection_color))
266
        self.connection_pen.setWidth(config["width"])
267

268
269
270
271
272
    def drawCubicBezierCurve(self):

        self.setPen(self.connection_pen)

        path = QPainterPath()
273
274
275
276
277
278
        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
279
        second_middle_point_y = (
280
            self.end_pin_center_point.y() - self.start_pin_center_point.y()
281
282
283
        ) / 4.0
        control_point = QPointF(middle_point_x, middle_point_y)
        second_control_point = QPointF(middle_point_x, second_middle_point_y)
284
        path.moveTo(self.start_pin_center_point)
285
        path.cubicTo(
286
287
288
            self.start_pin_center_point + control_point,
            self.end_pin_center_point - second_control_point,
            self.end_pin_center_point,
289
290
291
292
        )

        self.setPath(path)

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
    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()

316
317
318
319
320
321
322
323
324
325
326
327
328
    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:
329
330
            if connection.end_block == end.block_object and connection.end_pin == end:
                return False
331
332
333

        return True

334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
    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"]

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

        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

        self.start_pin = self.start_block.pins["outputs"][self.start_pin_name]
        self.end_pin = self.end_block.pins["inputs"][self.end_pin_name]

        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)

369

370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
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)
        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 = []
        if block.type == BlockType.DATASETS.name:
            layout.addRow(self.tr("Channel:"), no_dataset_channel_label)
        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)

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

        return {
            "name": self.name_lineedit.text(),
            "channel": self.channel_combobox.currentText(),
        }

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


448
449
450
451
452
453
454
class BlockType(Enum):
    """All possible block types"""

    BLOCKS = "blocks"
    ANALYZERS = "analyzers"
    DATASETS = "datasets"

455
456
457
458
459
460
461
    @classmethod
    def from_name(cls, name):
        try:
            return cls[name]
        except ValueError:
            raise ValueError("{} is not a valid block type".format(name))

462
463
464
465

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

466
    dataChanged = pyqtSignal()
467
468
    blockMoved = pyqtSignal()

469
    def __init__(self, block_type, style, connection_style):
470
471
472
        super().__init__()

        # Block information
473
474
        self.type = block_type
        self.name = ""
475

476
        if self.type == BlockType.DATASETS.name:
477
478
            self.inputs = None
        else:
479
480
481
            self.inputs = []

        if self.type == BlockType.ANALYZERS.name:
482
483
            self.outputs = None
        else:
484
485
486
            self.outputs = []

        self.synchronized_channel = None
487
488

        self.style = style
489
        self.connection_style = connection_style
490

491
        self.position = QPointF(0, 0)
492
493
494
495
496
        self.pins = dict()
        self.pins["inputs"] = dict()
        self.pins["outputs"] = dict()

        self.set_style(style)
497
498
499

    def load(self, toolchain, block_details):
        self.toolchain = toolchain
500
501
502

        if "name" in block_details:
            self.name = block_details["name"]
503
504
505
506
507
508
509
510
511
512
513

        if self.type != BlockType.DATASETS.name:
            self.inputs = block_details["inputs"]

        if self.type != BlockType.ANALYZERS.name:
            self.outputs = block_details["outputs"]

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

        self.set_style(self.style)
514
515
516
517
518
519
520
521
522
523
524
        self.create_pins()

    def create_pins(self):

        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

525
526
                input_pin.dataChanged.connect(self.dataChanged)

527
528
529
530
531
532
533
        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

534
535
                output_pin.dataChanged.connect(self.dataChanged)

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
    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)
        text_width = metrics.boundingRect(self.name).width() + 14

555
        if self.inputs is not None and len(self.inputs) > 0:
556
557
558
559
560
561
            self.max_inputs_width = (
                metrics.boundingRect(max(self.inputs, key=len)).width() + 14
            )
        else:
            self.max_inputs_width = 14

562
        if self.outputs is not None and len(self.outputs) > 0:
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
            self.max_outputs_width = (
                metrics.boundingRect(max(self.outputs, key=len)).width() + 14
            )
        else:
            self.max_outputs_width = 14

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

        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)
579
580
581
582
583
584

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

        self.background_brush.setColor(self.background_color_blocks)
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

        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)
        text_height = metrics.boundingRect(self.name).height() + 14

        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

629
630
631
632
        if max_pin_height == 0:
            self.custom_width = 55
            self.height = 55

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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
        rect = QRect(
            0,
            -text_height,
            self.custom_width,
            text_height + self.height + max_pin_height * self.pin_height,
        )
        rect = QRectF(rect)
        return rect

    def draw_pins_name(self, painter, _type, data):
        """Paint pin with name"""
        offset = 0
        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)

681
682
        self.position = self.scenePos()

683
        self.blockMoved.emit()
684
        self.dataChanged.emit()
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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
    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"]:
                self.name = value["name"]
                block_updated = True
            if (
                self.synchronized_channel != value["channel"]
                and self.type != BlockType.DATASETS.name
            ):
                self.synchronized_channel = value["channel"]
                block_updated = True

        if block_updated:
            # Update blocks
            block_item = {}
            block_item["inputs"] = self.inputs
            block_item["outputs"] = self.outputs
            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

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

788
789
790
791
    def paint(self, painter, option, widget):
        """Paint the block"""

        # Design tools
792
793
794
795
796
        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)

797
798
799
800
801
802
803
804
805
806
807
808
        painter.setBrush(self.background_brush)
        painter.setPen(self.border_pen)

        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

809
810
811
812
813
814
815
        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)

816
817
818
819
        if max_pin_height == 0:
            self.custom_width = 55
            self.height = 55

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
        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())
        text_width = metrics.boundingRect(self.name).width() + 14
        text_height = metrics.boundingRect(self.name).height() + 14
        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
        if self.inputs is not None:
            self.draw_pins_name(painter, "input", self.inputs)
        if self.outputs is not None:
            self.draw_pins_name(painter, "output", self.outputs)


848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
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
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()

    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)


892
893
class Toolchain(QWidget):
    """Toolchain designer"""
894

895
896
    dataChanged = pyqtSignal()

897
898
899
900
901
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.json_object = {}

902
903
904
905
906
907
908
909
910
        with open("beat/editor/widgets/space_nodes_config.json") as json_file:
            config_data = json.load(json_file)

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

911
912
        self.view = ToolchainView(self)
        self.view.setScene(self.scene)
913
914
915

        self.toolbar = QToolBar()

916
917
918
919
920
921
922
923
924
        self.dataset_button = QPushButton()
        self.dataset_button.setToolTip("Dataset")
        self.dataset_button.setIcon(QIcon("beat/editor/widgets/dataset_icon.png"))
        self.dataset_edit_menu = QMenu(self)

        self.block_button = QPushButton()
        self.block_button.setToolTip("Block")
        self.block_button.setIcon(QIcon("beat/editor/widgets/block_icon.png"))
        self.block_edit_menu = QMenu(self)
925

926
927
928
929
930
931
932
933
        self.analyzer_button = QPushButton()
        self.analyzer_button.setToolTip("Analyzer")
        self.analyzer_button.setIcon(QIcon("beat/editor/widgets/analyzer_icon.png"))
        self.analyzer_edit_menu = QMenu(self)

        self.toolbar.addWidget(self.dataset_button)
        self.toolbar.addWidget(self.block_button)
        self.toolbar.addWidget(self.analyzer_button)
934
935
936
937
938

        self.toolbar.setOrientation(Qt.Vertical)

        layout = QHBoxLayout(self)
        layout.addWidget(self.toolbar)
939
        layout.addWidget(self.view)
940

941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
    def update_channel_path(self, block, old_channel, new_channel):
        # check if current block is synchronized on old_channel
        for connection in self.connections:
            if (
                block.name == connection.start_block_name
                and connection.channel == old_channel
            ):
                # update connection channel
                connection.channel = new_channel

                self.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.json_object.get("representation", {}).get(
                    "channel_colors"
                )
                connection.load(self, connection_settings, channel_colors)
                self.scene.addItem(connection)

    def button_item_selected(self, block_type, name):
        inputs = []
        outputs = []

        if block_type == BlockType.DATASETS.name:
            inputs = None
            name_split = name.split("/")
            database_name = name_split[0] + "/" + name_split[1]
            asset = Asset(self.prefix_path, AssetType.DATABASE, database_name)
            for protocol in asset.declaration["protocols"]:
                if protocol["name"] == name_split[2]:
                    for _set in protocol["sets"]:
                        if _set["name"] == name_split[3]:
                            for key in _set["outputs"].keys():
                                outputs.append(key)
        else:
            if block_type == BlockType.ANALYZERS.name:
                outputs = None
            asset = Asset(self.prefix_path, AssetType.ALGORITHM, name)
            declaration = asset.declaration
            for group in declaration["groups"]:
                if "inputs" in group:
                    for key in group["inputs"].keys():
                        inputs.append(key)
                if "outputs" in group:
                    for key in group["outputs"].keys():
                        outputs.append(key)

        block_item = {}
        block_item["inputs"] = inputs
        block_item["outputs"] = outputs
        init_name_count = 0
        init_name = self.tr("CHANGE_ME")
        for block in self.blocks:
            if block.name.find(init_name) > -1:
                init_name_count += 1
1006
1007
1008
1009
        new_block_name = init_name + "_" + str(init_name_count)
        block_item["name"] = new_block_name

        self.web_representation["channel_colors"][new_block_name] = "#000000"
1010
1011
1012

        block = Block(block_type, self.block_config, self.connection_config)
        block.load(self, block_item)
1013

1014
        block.dataChanged.connect(self.dataChanged)
1015
        block.dataChanged.emit()
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
        self.blocks.append(block)
        self.scene.addItem(block)

    def set_prefix_databases_algorithms_lists(
        self, prefix_path, dataset_list, algorithm_list, analyzer_list
    ):
        self.prefix_path = prefix_path

        for dataset_name in dataset_list:
            self.dataset_edit_menu.addAction(
                self.tr(dataset_name),
                partial(
                    self.button_item_selected, BlockType.DATASETS.name, dataset_name
                ),
            )

        for algorithm_name in algorithm_list:
            self.block_edit_menu.addAction(
                self.tr(algorithm_name),
                partial(
                    self.button_item_selected, BlockType.BLOCKS.name, algorithm_name
                ),
            )

        for analyzer_name in analyzer_list:
            self.analyzer_edit_menu.addAction(
                self.tr(analyzer_name),
                partial(
                    self.button_item_selected, BlockType.ANALYZERS.name, analyzer_name
                ),
            )

        self.dataset_button.setMenu(self.dataset_edit_menu)
        self.block_button.setMenu(self.block_edit_menu)
        self.analyzer_button.setMenu(self.analyzer_edit_menu)
1051

1052
1053
1054
1055
    def clear_space(self):
        self.scene.clear()
        self.scene.items().clear()
        self.blocks = []
1056
        self.connections = []
1057
        self.channels = []
1058
1059
1060
1061
1062
1063

    def load(self, json_object):
        """Parse the json in parameter and generates a graph"""

        self.json_object = json_object

1064
1065
        self.web_representation = self.json_object.get("representation")
        self.editor_gui = self.json_object.get("editor_gui")
1066

1067
        self.clear_space()
1068

1069
1070
        # Get datasets, blocks, analyzers
        for block_type in BlockType:
1071
            for block_item in self.json_object.get(block_type.value, {}):
1072
                block = Block(
1073
                    block_type.name, self.block_config, self.connection_config
1074
                )
1075
                block.load(self, block_item)
1076
1077
1078
1079
1080
1081
1082
1083
                # Place blocks (x,y) if information is given
                if self.editor_gui is not None:
                    if block.name in self.editor_gui:
                        block.setPos(
                            self.editor_gui[block.name]["x"],
                            self.editor_gui[block.name]["y"],
                        )
                        block.position = block.scenePos()
1084
                block.dataChanged.connect(self.dataChanged)
1085
1086
1087
1088
                self.blocks.append(block)
                self.scene.addItem(block)

        # Display connections
1089
1090
1091
1092
        connections = self.json_object.get("connections", [])
        channel_colors = self.json_object.get("representation", {}).get(
            "channel_colors"
        )
1093

1094
        for connection_item in connections:
1095
1096
            connection = Connection(self.connection_config)
            connection.load(self, connection_item, channel_colors)
1097
            self.connections.append(connection)
1098
            self.scene.addItem(connection)
1099
1100
1101
1102

    def dump(self):
        """Returns the json used to load the widget"""

1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
        data = {}

        if self.web_representation is not None:
            data["representation"] = self.web_representation

        data["editor_gui"] = {}

        for block_type in BlockType:
            block_type_list = []
            for block in self.blocks:
                block_data = {}
                if block_type == BlockType.from_name(block.type):
                    block_data["name"] = block.name
                    if block.synchronized_channel is not None:
                        block_data["synchronized_channel"] = block.synchronized_channel
                    if block.inputs is not None:
                        block_data["inputs"] = block.inputs
                    if block.outputs is not None:
                        block_data["outputs"] = block.outputs

                    block_type_list.append(block_data)
                data["editor_gui"][block.name] = {
                    "x": block.position.x(),
                    "y": block.position.y(),
                }
            data[block_type.value] = block_type_list

        connection_list = []
        for connection in self.connections:
            connection_data = {}
            connection_data["channel"] = connection.channel
            connection_data["from"] = (
                connection.start_block_name + "." + connection.start_pin_name
            )
            connection_data["to"] = (
                connection.end_block_name + "." + connection.end_pin_name
            )
            connection_list.append(connection_data)

        data["connections"] = connection_list

        return data
1145
1146


Samuel GAIST's avatar
Samuel GAIST committed
1147
@frozen
1148
1149
class ToolchainEditor(AbstractAssetEditor):
    def __init__(self, parent=None):
1150
        super().__init__(AssetType.TOOLCHAIN, parent)
Samuel GAIST's avatar
Samuel GAIST committed
1151
        self.setObjectName(self.__class__.__name__)
1152
1153
        self.set_title(self.tr("Toolchain"))

1154
1155
1156
1157
1158
        self.toolchain_model = AssetModel()
        self.toolchain_model.asset_type = AssetType.TOOLCHAIN

        self.toolchain = Toolchain()
        self.layout().addWidget(self.toolchain, 2)
1159
1160
        self.layout().addStretch()

1161
1162
1163
1164
        self.algorithm_list = []
        self.analyzer_list = []
        self.dataset_list = []

1165
        self.toolchain.dataChanged.connect(self.dataChanged)
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
        self.contextChanged.connect(self.__onContextChanged)

    @pyqtSlot()
    def __onContextChanged(self):
        algorithm_model = AlgorithmResourceModel()
        algorithm_model.setAnalyzerEnabled(False)
        dataset_model = DatasetResourceModel()

        self.dataset_list = [
            dataset_model.index(i, 0).data() for i in range(dataset_model.rowCount())
        ]
        self.algorithm_list = [
            algorithm_model.index(i, 0).data()
            for i in range(algorithm_model.rowCount())
        ]
        algorithm_model.setAnalyzerEnabled(True)
        self.analyzer_list = [
            algorithm_model.index(i, 0).data()
            for i in range(algorithm_model.rowCount())
        ]

        self.toolchain.set_prefix_databases_algorithms_lists(
            self.prefix_path, self.dataset_list, self.algorithm_list, self.analyzer_list
        )
1190

1191
1192
    def _load_json(self, json_object):
        """Load the json object passed as parameter"""
1193

1194
        self.toolchain.load(json_object)
1195
1196
1197

    def _dump_json(self):
        """Returns the json representation of the asset"""
1198

1199
        return self.toolchain.dump()