toolchaineditor.py 22.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

30
31
32
33
34
35
36
37
38
39
40
41
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

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
42
43
44

from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget
45
46
47
48
from PyQt5.QtWidgets import QGraphicsView
from PyQt5.QtWidgets import QGraphicsItem
from PyQt5.QtWidgets import QGraphicsPathItem
from PyQt5.QtWidgets import QGraphicsObject
49

50
from ..backend.asset import AssetType
51
from ..backend.assetmodel import AssetModel
52
from ..decorators import frozen
Samuel GAIST's avatar
Samuel GAIST committed
53

54
from .editor import AbstractAssetEditor
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
from .drawing_space import DrawingSpace


class BasePin(QGraphicsItem):
    """Base class for pin graphics"""

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

    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
            + self.block_object.inputs.index(self.pin) * self.block_object.height
        )

        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
            + self.block_object.outputs.index(self.pin) * self.block_object.height
        )

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


class Connection(QGraphicsPathItem):
146
    def __init__(self, toolchain, connection_details, style, channel_colors):
147
148
149
150
151
152
153
154
155

        super().__init__()

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

156
157
158
159
160
161
162
        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)

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
        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.pointer = None

        self.set_style(style)

        self.drawCubicBezierCurve()

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

    def set_style(self, config):

        # Highlight
        self.setAcceptHoverEvents(True)

        # Geometry settings
        self.width = config["width"]
        self.color = config["color"]
191

192
        self.connection_pen = QPen()
193
        self.connection_pen.setColor(QColor(*self.connection_color))
194
        self.connection_pen.setWidth(config["width"])
195

196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    def drawCubicBezierCurve(self):

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

        path = QPainterPath()
        middle_point_x = (end_pin_center_point.x() - start_pin_center_point.x()) / 2.0
        middle_point_y = (end_pin_center_point.y() - start_pin_center_point.y()) / 2.0
        second_middle_point_y = (
            end_pin_center_point.y() - start_pin_center_point.y()
        ) / 4.0
        control_point = QPointF(middle_point_x, middle_point_y)
        second_control_point = QPointF(middle_point_x, second_middle_point_y)
        path.moveTo(start_pin_center_point)
        path.cubicTo(
            start_pin_center_point + control_point,
            end_pin_center_point - second_control_point,
            end_pin_center_point,
        )

        self.setPath(path)


class BlockType(Enum):
    """All possible block types"""

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

227
228
229
230
231
232
233
    @classmethod
    def from_name(cls, name):
        try:
            return cls[name]
        except ValueError:
            raise ValueError("{} is not a valid block type".format(name))

234
235
236
237

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

238
    dataChanged = pyqtSignal()
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
    blockMoved = pyqtSignal()

    def __init__(self, block_details, block_type, style):
        super().__init__()

        # Block information
        self.name = block_details["name"]
        if block_type == BlockType.DATASETS.name:
            self.inputs = None
        else:
            self.inputs = block_details["inputs"]
        if block_type == BlockType.ANALYZERS.name:
            self.outputs = None
        else:
            self.outputs = block_details["outputs"]

        if "synchronized_channel" in block_details:
            self.synchronized_channel = block_details["synchronized_channel"]
257
258
        else:
            self.synchronized_channel = None
259
260
261
        self.type = block_type
        self.style = style

262
        self.position = QPointF(0, 0)
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        self.pins = dict()
        self.pins["inputs"] = dict()
        self.pins["outputs"] = dict()

        self.set_style(style)
        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

        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

    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

        if self.inputs is not None:
            self.max_inputs_width = (
                metrics.boundingRect(max(self.inputs, key=len)).width() + 14
            )
        else:
            self.max_inputs_width = 14

        if self.outputs is not None:
            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)
329
330
331
332
333
334

        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)
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426

        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

        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)

427
428
        self.position = self.scenePos()

429
        self.blockMoved.emit()
430
        self.dataChanged.emit()
431
432
433
434
435

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

        # Design tools
436
437
438
439
440
        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)

441
442
443
444
445
446
447
448
449
450
451
452
        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

453
454
455
456
457
458
459
        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)

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


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


532
533
class Toolchain(QWidget):
    """Toolchain designer"""
534

535
536
    dataChanged = pyqtSignal()

537
538
539
540
541
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.json_object = {}

542
543
544
545
546
547
548
549
550
        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"]

551
552
        self.view = ToolchainView(self)
        self.view.setScene(self.scene)
553
        layout = QVBoxLayout(self)
554
        layout.addWidget(self.view)
555
556
557
558
559

    def clear_space(self):
        self.scene.clear()
        self.scene.items().clear()
        self.blocks = []
560
        self.connections = []
561
        self.channels = []
562
563
564
565
566
567

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

        self.json_object = json_object

568
569
570
571
572
        if "representation" in self.json_object:
            self.web_representation = self.json_object["representation"]
        else:
            self.web_representation = None

573
574
575
576
577
        if "editor_gui" in self.json_object:
            self.editor_gui = self.json_object["editor_gui"]
        else:
            self.editor_gui = None

578
        self.clear_space()
579

580
581
582
583
        # Get datasets, blocks, analyzers
        for block_type in BlockType:
            for block_item in self.json_object[block_type.value]:
                block = Block(block_item, block_type.name, self.block_config)
584
585
586
587
588
589
590
591
                # 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()
592
                block.dataChanged.connect(self.dataChanged)
593
594
595
596
597
                self.blocks.append(block)
                self.scene.addItem(block)

        # Display connections
        connections = self.json_object["connections"]
598
599
        channel_colors = self.json_object["representation"]["channel_colors"]

600
        for connection_item in connections:
601
602
603
            connection = Connection(
                self, connection_item, self.connection_config, channel_colors
            )
604
            self.connections.append(connection)
605
            self.scene.addItem(connection)
606
607
608
609

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

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
        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
652
653


Samuel GAIST's avatar
Samuel GAIST committed
654
@frozen
655
656
class ToolchainEditor(AbstractAssetEditor):
    def __init__(self, parent=None):
657
        super().__init__(AssetType.TOOLCHAIN, parent)
Samuel GAIST's avatar
Samuel GAIST committed
658
        self.setObjectName(self.__class__.__name__)
659
660
        self.set_title(self.tr("Toolchain"))

661
662
663
664
665
        self.toolchain_model = AssetModel()
        self.toolchain_model.asset_type = AssetType.TOOLCHAIN

        self.toolchain = Toolchain()
        self.layout().addWidget(self.toolchain, 2)
666
667
        self.layout().addStretch()

668
669
        self.toolchain.dataChanged.connect(self.dataChanged)

670
671
    def _load_json(self, json_object):
        """Load the json object passed as parameter"""
672

673
        self.toolchain.load(json_object)
674
675
676

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

678
        return self.toolchain.dump()