-
Notifications
You must be signed in to change notification settings - Fork 69
/
interactions.py
2185 lines (1830 loc) · 76.3 KB
/
interactions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
191
192
193
194
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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
329
330
331
332
333
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
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
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
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
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
"""
=========================
User Interaction Handlers
=========================
User interaction handlers for a :class:`~.SchemeEditWidget`.
User interactions encapsulate the logic of user interactions with the
scheme document.
All interactions are subclasses of :class:`UserInteraction`.
"""
import typing
from typing import Optional, Any, Tuple, List, Set, Iterable, Sequence, Dict
import abc
import logging
from functools import reduce
from AnyQt.QtWidgets import (
QApplication, QGraphicsRectItem, QGraphicsSceneMouseEvent,
QGraphicsSceneContextMenuEvent, QWidget, QGraphicsItem,
QGraphicsSceneDragDropEvent, QMenu, QAction, QWidgetAction, QLabel
)
from AnyQt.QtGui import QPen, QBrush, QColor, QFontMetrics, QKeyEvent, QFont
from AnyQt.QtCore import (
Qt, QObject, QCoreApplication, QSizeF, QPointF, QRect, QRectF, QLineF,
QPoint, QMimeData,
)
from AnyQt.QtCore import pyqtSignal as Signal
from orangecanvas.document.commands import UndoCommand
from .usagestatistics import UsageStatistics
from ..registry.description import WidgetDescription, OutputSignal, InputSignal
from ..registry.qt import QtWidgetRegistry, tooltip_helper, whats_this_helper
from .. import scheme
from ..scheme import (
SchemeNode as Node, SchemeLink as Link, Scheme, WorkflowEvent,
compatible_channels
)
from ..canvas import items
from ..canvas.items import controlpoints
from ..gui.quickhelp import QuickHelpTipEvent
from . import commands
from .editlinksdialog import EditLinksDialog
from ..utils import unique
from ..utils.pkgmeta import EntryPoint, entry_points
if typing.TYPE_CHECKING:
from .schemeedit import SchemeEditWidget
A = typing.TypeVar("A")
#: Output/Input pair of a link
OIPair = Tuple[OutputSignal, InputSignal]
log = logging.getLogger(__name__)
def assert_not_none(optional):
# type: (Optional[A]) -> A
assert optional is not None
return optional
class UserInteraction(QObject):
"""
Base class for user interaction handlers.
Parameters
----------
document : :class:`~.SchemeEditWidget`
An scheme editor instance with which the user is interacting.
parent : :class:`QObject`, optional
A parent QObject
deleteOnEnd : bool, optional
Should the UserInteraction be deleted when it finishes (``True``
by default).
"""
# Cancel reason flags
#: No specified reason
NoReason = 0
#: User canceled the operation (e.g. pressing ESC)
UserCancelReason = 1
#: Another interaction was set
InteractionOverrideReason = 3
#: An internal error occurred
ErrorReason = 4
#: Other (unspecified) reason
OtherReason = 5
#: Emitted when the interaction is set on the scene.
started = Signal()
#: Emitted when the interaction finishes successfully.
finished = Signal()
#: Emitted when the interaction ends (canceled or finished)
ended = Signal()
#: Emitted when the interaction is canceled.
canceled = Signal([], [int])
def __init__(self, document, parent=None, deleteOnEnd=True):
# type: ('SchemeEditWidget', Optional[QObject], bool) -> None
super().__init__(parent)
self.document = document
self.scene = document.scene()
scheme_ = document.scheme()
assert scheme_ is not None
self.scheme = scheme_ # type: scheme.Scheme
self.suggestions = document.suggestions()
self.deleteOnEnd = deleteOnEnd
self.cancelOnEsc = False
self.__finished = False
self.__canceled = False
self.__cancelReason = self.NoReason
def start(self):
# type: () -> None
"""
Start the interaction. This is called by the :class:`CanvasScene` when
the interaction is installed.
.. note:: Must be called from subclass implementations.
"""
self.started.emit()
def end(self):
# type: () -> None
"""
Finish the interaction. Restore any leftover state in this method.
.. note:: This gets called from the default :func:`cancel`
implementation.
"""
self.__finished = True
if self.scene.user_interaction_handler is self:
self.scene.set_user_interaction_handler(None)
if self.__canceled:
self.canceled.emit()
self.canceled[int].emit(self.__cancelReason)
else:
self.finished.emit()
self.ended.emit()
if self.deleteOnEnd:
self.deleteLater()
def cancel(self, reason=OtherReason):
# type: (int) -> None
"""
Cancel the interaction with `reason`.
"""
self.__canceled = True
self.__cancelReason = reason
self.end()
def isFinished(self):
# type: () -> bool
"""
Is the interaction finished.
"""
return self.__finished
def isCanceled(self):
# type: () -> bool
"""
Was the interaction canceled.
"""
return self.__canceled
def cancelReason(self):
# type: () -> int
"""
Return the reason the interaction was canceled.
"""
return self.__cancelReason
def mousePressEvent(self, event):
# type: (QGraphicsSceneMouseEvent) -> bool
"""
Handle a `QGraphicsScene.mousePressEvent`.
"""
return False
def mouseMoveEvent(self, event):
# type: (QGraphicsSceneMouseEvent) -> bool
"""
Handle a `GraphicsScene.mouseMoveEvent`.
"""
return False
def mouseReleaseEvent(self, event):
# type: (QGraphicsSceneMouseEvent) -> bool
"""
Handle a `QGraphicsScene.mouseReleaseEvent`.
"""
return False
def mouseDoubleClickEvent(self, event):
# type: (QGraphicsSceneMouseEvent) -> bool
"""
Handle a `QGraphicsScene.mouseDoubleClickEvent`.
"""
return False
def keyPressEvent(self, event):
# type: (QKeyEvent) -> bool
"""
Handle a `QGraphicsScene.keyPressEvent`
"""
if self.cancelOnEsc and event.key() == Qt.Key_Escape:
self.cancel(self.UserCancelReason)
return False
def keyReleaseEvent(self, event):
# type: (QKeyEvent) -> bool
"""
Handle a `QGraphicsScene.keyPressEvent`
"""
return False
def contextMenuEvent(self, event):
# type: (QGraphicsSceneContextMenuEvent) -> bool
"""
Handle a `QGraphicsScene.contextMenuEvent`
"""
return False
def dragEnterEvent(self, event):
# type: (QGraphicsSceneDragDropEvent) -> bool
"""
Handle a `QGraphicsScene.dragEnterEvent`
.. versionadded:: 0.1.20
"""
return False
def dragMoveEvent(self, event):
# type: (QGraphicsSceneDragDropEvent) -> bool
"""
Handle a `QGraphicsScene.dragMoveEvent`
.. versionadded:: 0.1.20
"""
return False
def dragLeaveEvent(self, event):
# type: (QGraphicsSceneDragDropEvent) -> bool
"""
Handle a `QGraphicsScene.dragLeaveEvent`
.. versionadded:: 0.1.20
"""
return False
def dropEvent(self, event):
# type: (QGraphicsSceneDragDropEvent) -> bool
"""
Handle a `QGraphicsScene.dropEvent`
.. versionadded:: 0.1.20
"""
return False
class NoPossibleLinksError(ValueError):
pass
class UserCanceledError(ValueError):
pass
def reversed_arguments(func):
"""
Return a function with reversed argument order.
"""
def wrapped(*args):
return func(*reversed(args))
return wrapped
class NewLinkAction(UserInteraction):
"""
User drags a new link from an existing `NodeAnchorItem` to create
a connection between two existing nodes or to a new node if the release
is over an empty area, in which case a quick menu for new node selection
is presented to the user.
"""
# direction of the drag
FROM_SOURCE = 1
FROM_SINK = 2
def __init__(self, document, *args, **kwargs):
super().__init__(document, *args, **kwargs)
self.from_item = None # type: Optional[items.NodeItem]
self.from_signal = None # type: Optional[Union[InputSignal, OutputSignal]]
self.direction = 0 # type: int
self.showing_incompatible_widget = False # type: bool
# An `NodeItem` currently under the mouse as a possible
# link drop target.
self.current_target_item = None # type: Optional[items.NodeItem]
# A temporary `LinkItem` used while dragging.
self.tmp_link_item = None # type: Optional[items.LinkItem]
# An temporary `AnchorPoint` inserted into `current_target_item`
self.tmp_anchor_point = None # type: Optional[items.AnchorPoint]
# An `AnchorPoint` following the mouse cursor
self.cursor_anchor_point = None # type: Optional[items.AnchorPoint]
# An UndoCommand
self.macro = None # type: Optional[UndoCommand]
# Cache viable signals of currently hovered node
self.__target_compatible_signals: Sequence[Tuple[OutputSignal, InputSignal]] = []
self.cancelOnEsc = True
def remove_tmp_anchor(self):
# type: () -> None
"""
Remove a temporary anchor point from the current target item.
"""
assert self.current_target_item is not None
assert self.tmp_anchor_point is not None
if self.direction == self.FROM_SOURCE:
self.current_target_item.removeInputAnchor(self.tmp_anchor_point)
else:
self.current_target_item.removeOutputAnchor(self.tmp_anchor_point)
self.tmp_anchor_point = None
def update_tmp_anchor(self, item, scenePos):
# type: (items.NodeItem, QPointF) -> None
"""
If hovering over a new compatible channel, move it.
"""
assert self.tmp_anchor_point is not None
if self.direction == self.FROM_SOURCE:
signal = item.inputAnchorItem.signalAtPos(scenePos,
self.__target_compatible_signals)
else:
signal = item.outputAnchorItem.signalAtPos(scenePos,
self.__target_compatible_signals)
self.tmp_anchor_point.setSignal(signal)
def create_tmp_anchor(self, item, scenePos):
# type: (items.NodeItem, QPointF) -> None
"""
Create a new tmp anchor at the `item` (:class:`NodeItem`).
"""
assert self.tmp_anchor_point is None
if self.direction == self.FROM_SOURCE:
anchor = item.inputAnchorItem
signal = anchor.signalAtPos(scenePos,
self.__target_compatible_signals)
self.tmp_anchor_point = item.newInputAnchor(signal)
else:
anchor = item.outputAnchorItem
signal = anchor.signalAtPos(scenePos,
self.__target_compatible_signals)
self.tmp_anchor_point = item.newOutputAnchor(signal)
def __possible_connection_signal_pairs(
self, target_item: items.NodeItem
) -> Sequence[Tuple[OutputSignal, InputSignal]]:
"""
Return possible connection signal pairs between current
`self.from_item` and `target_item`.
"""
if self.from_item is None:
return []
node1 = self.scene.node_for_item(self.from_item)
node2 = self.scene.node_for_item(target_item)
if self.direction == self.FROM_SOURCE:
links = self.scheme.propose_links(node1, node2,
source_signal=self.from_signal)
else:
links = self.scheme.propose_links(node2, node1,
sink_signal=self.from_signal)
return [(s1, s2) for s1, s2, _ in links]
def can_connect(self, target_item):
# type: (items.NodeItem) -> bool
"""
Is the connection between `self.from_item` (item where the drag
started) and `target_item` possible.
"""
return bool(self.__possible_connection_signal_pairs(target_item))
def set_link_target_anchor(self, anchor):
# type: (items.AnchorPoint) -> None
"""
Set the temp line target anchor.
"""
assert self.tmp_link_item is not None
if self.direction == self.FROM_SOURCE:
self.tmp_link_item.setSinkItem(None, anchor=anchor)
else:
self.tmp_link_item.setSourceItem(None, anchor=anchor)
def target_node_item_at(self, pos):
# type: (QPointF) -> Optional[items.NodeItem]
"""
Return a suitable :class:`NodeItem` at position `pos` on which
a link can be dropped.
"""
# Test for a suitable `NodeAnchorItem` or `NodeItem` at pos.
if self.direction == self.FROM_SOURCE:
anchor_type = items.SinkAnchorItem
else:
anchor_type = items.SourceAnchorItem
item = self.scene.item_at(pos, (anchor_type, items.NodeItem))
if isinstance(item, anchor_type):
return item.parentNodeItem()
elif isinstance(item, items.NodeItem):
return item
else:
return None
def mousePressEvent(self, event):
# type: (QGraphicsSceneMouseEvent) -> bool
anchor_item = self.scene.item_at(
event.scenePos(), items.NodeAnchorItem
)
if anchor_item is not None and event.button() == Qt.LeftButton:
# Start a new link starting at item
self.from_item = anchor_item.parentNodeItem()
if isinstance(anchor_item, items.SourceAnchorItem):
self.direction = NewLinkAction.FROM_SOURCE
else:
self.direction = NewLinkAction.FROM_SINK
event.accept()
helpevent = QuickHelpTipEvent(
self.tr("Create a new link"),
self.tr('<h3>Create new link</h3>'
'<p>Drag a link to an existing node or release on '
'an empty spot to create a new node.</p>'
'<p>Hold Shift when releasing the mouse button to '
'edit connections.</p>'
# '<a href="help://orange-canvas/create-new-links">'
# 'More ...</a>'
)
)
QCoreApplication.postEvent(self.document, helpevent)
return True
else:
# Whoever put us in charge did not know what he was doing.
self.cancel(self.ErrorReason)
return False
def mouseMoveEvent(self, event):
# type: (QGraphicsSceneMouseEvent) -> bool
if self.tmp_link_item is None:
# On first mouse move event create the temp link item and
# initialize it to follow the `cursor_anchor_point`.
self.tmp_link_item = items.LinkItem()
# An anchor under the cursor for the duration of this action.
self.cursor_anchor_point = items.AnchorPoint()
self.cursor_anchor_point.setPos(event.scenePos())
# Set the `fixed` end of the temp link (where the drag started).
scenePos = event.scenePos()
if self.direction == self.FROM_SOURCE:
anchor = self.from_item.outputAnchorItem
else:
anchor = self.from_item.inputAnchorItem
anchor.setHovered(False)
anchor.setCompatibleSignals(None)
if anchor.anchorOpen():
signal = anchor.signalAtPos(scenePos)
anchor.setKeepAnchorOpen(signal)
else:
signal = None
self.from_signal = signal
if self.direction == self.FROM_SOURCE:
self.tmp_link_item.setSourceItem(self.from_item, signal)
else:
self.tmp_link_item.setSinkItem(self.from_item, signal)
self.set_link_target_anchor(self.cursor_anchor_point)
self.scene.addItem(self.tmp_link_item)
assert self.cursor_anchor_point is not None
# `NodeItem` at the cursor position
item = self.target_node_item_at(event.scenePos())
if self.current_target_item is not None and \
(item is None or item is not self.current_target_item):
# `current_target_item` is no longer under the mouse cursor
# (was replaced by another item or the the cursor was moved over
# an empty scene spot.
log.info("%r is no longer the target.", self.current_target_item)
if self.direction == self.FROM_SOURCE:
anchor = self.current_target_item.inputAnchorItem
else:
anchor = self.current_target_item.outputAnchorItem
if self.showing_incompatible_widget:
anchor.setIncompatible(False)
self.showing_incompatible_widget = False
else:
self.remove_tmp_anchor()
anchor.setHovered(False)
anchor.setCompatibleSignals(None)
self.current_target_item = None
if item is not None and item is not self.from_item:
# The mouse is over a node item (different from the starting node)
if self.current_target_item is item:
# Mouse is over the same item
scenePos = event.scenePos()
# Move to new potential anchor
if not self.showing_incompatible_widget:
self.update_tmp_anchor(item, scenePos)
else:
self.set_link_target_anchor(self.cursor_anchor_point)
elif self.can_connect(item):
# Mouse is over a new item
links = self.__possible_connection_signal_pairs(item)
log.info("%r is the new target.", item)
if self.direction == self.FROM_SOURCE:
self.__target_compatible_signals = [s2 for s1, s2 in links]
item.inputAnchorItem.setCompatibleSignals(
self.__target_compatible_signals)
item.inputAnchorItem.setHovered(True)
else:
self.__target_compatible_signals = [s1 for s1, s2 in links]
item.outputAnchorItem.setCompatibleSignals(
self.__target_compatible_signals)
item.outputAnchorItem.setHovered(True)
scenePos = event.scenePos()
self.create_tmp_anchor(item, scenePos)
self.set_link_target_anchor(
assert_not_none(self.tmp_anchor_point)
)
self.current_target_item = item
self.showing_incompatible_widget = False
else:
log.info("%r does not have compatible channels", item)
self.__target_compatible_signals = []
if self.direction == self.FROM_SOURCE:
anchor = item.inputAnchorItem
else:
anchor = item.outputAnchorItem
anchor.setCompatibleSignals(
self.__target_compatible_signals)
anchor.setHovered(True)
anchor.setIncompatible(True)
self.showing_incompatible_widget = True
self.set_link_target_anchor(self.cursor_anchor_point)
self.current_target_item = item
else:
self.showing_incompatible_widget = item is not None
self.__target_compatible_signals = []
self.set_link_target_anchor(self.cursor_anchor_point)
self.cursor_anchor_point.setPos(event.scenePos())
return True
def mouseReleaseEvent(self, event):
# type: (QGraphicsSceneMouseEvent) -> bool
if self.tmp_link_item is not None:
item = self.target_node_item_at(event.scenePos())
node = None # type: Optional[Node]
stack = self.document.undoStack()
self.macro = UndoCommand(self.tr("Add link"))
if item:
# If the release was over a node item then connect them
node = self.scene.node_for_item(item)
else:
# Release on an empty canvas part
# Show a quick menu popup for a new widget creation.
try:
node = self.create_new(event)
except Exception:
log.error("Failed to create a new node, ending.",
exc_info=True)
node = None
if node is not None:
commands.AddNodeCommand(self.scheme, node,
parent=self.macro)
if node is not None and not self.showing_incompatible_widget:
if self.direction == self.FROM_SOURCE:
source_node = self.scene.node_for_item(self.from_item)
source_signal = self.from_signal
sink_node = node
if item is not None and item.inputAnchorItem.anchorOpen():
sink_signal = item.inputAnchorItem.signalAtPos(
event.scenePos(),
self.__target_compatible_signals
)
else:
sink_signal = None
else:
source_node = node
if item is not None and item.outputAnchorItem.anchorOpen():
source_signal = item.outputAnchorItem.signalAtPos(
event.scenePos(),
self.__target_compatible_signals
)
else:
source_signal = None
sink_node = self.scene.node_for_item(self.from_item)
sink_signal = self.from_signal
self.suggestions.set_direction(self.direction)
self.connect_nodes(source_node, sink_node,
source_signal, sink_signal)
self.reset_open_anchor()
if not self.isCanceled() or not self.isFinished() and \
self.macro is not None:
# Push (commit) the add link/node action on the stack.
stack.push(self.macro)
self.end()
return True
else:
self.end()
return False
def create_new(self, event):
# type: (QGraphicsSceneMouseEvent) -> Optional[Node]
"""
Create and return a new node with a `QuickMenu`.
"""
pos = event.screenPos()
menu = self.document.quickMenu()
node = self.scene.node_for_item(self.from_item)
from_signal = self.from_signal
from_desc = node.description
def is_compatible(
source_signal: OutputSignal,
source: WidgetDescription,
sink: WidgetDescription,
sink_signal: InputSignal
) -> bool:
return any(scheme.compatible_channels(output, input)
for output
in ([source_signal] if source_signal else source.outputs)
for input
in ([sink_signal] if sink_signal else sink.inputs))
from_sink = self.direction == self.FROM_SINK
if from_sink:
# Reverse the argument order.
is_compatible = reversed_arguments(is_compatible)
suggestion_sort = self.suggestions.get_source_suggestions(from_desc.name)
else:
suggestion_sort = self.suggestions.get_sink_suggestions(from_desc.name)
def sort(left, right):
# list stores frequencies, so sign is flipped
return suggestion_sort[left] > suggestion_sort[right]
menu.setSortingFunc(sort)
def filter(index):
desc = index.data(QtWidgetRegistry.WIDGET_DESC_ROLE)
if isinstance(desc, WidgetDescription):
return is_compatible(from_signal, from_desc, desc, None)
else:
return False
menu.setFilterFunc(filter)
menu.triggerSearch()
try:
action = menu.exec(pos)
finally:
menu.setFilterFunc(None)
if action:
item = action.property("item")
desc = item.data(QtWidgetRegistry.WIDGET_DESC_ROLE)
pos = event.scenePos()
# a new widget should be placed so that the connection
# stays as it was
offset = 31 * (-1 if self.direction == self.FROM_SINK else
1 if self.direction == self.FROM_SOURCE else 0)
statistics = self.document.usageStatistics()
statistics.begin_extend_action(from_sink, node)
node = self.document.newNodeHelper(desc,
position=(pos.x() + offset,
pos.y()))
return node
else:
return None
def connect_nodes(
self, source_node: Node, sink_node: Node,
source_signal: Optional[OutputSignal] = None,
sink_signal: Optional[InputSignal] = None
) -> None:
"""
Connect `source_node` to `sink_node`. If there are more then one
equally weighted and non conflicting links possible present a
detailed dialog for link editing.
"""
UsageStatistics.set_sink_anchor_open(sink_signal is not None)
UsageStatistics.set_source_anchor_open(source_signal is not None)
try:
possible = self.scheme.propose_links(source_node, sink_node,
source_signal, sink_signal)
log.debug("proposed (weighted) links: %r",
[(s1.name, s2.name, w) for s1, s2, w in possible])
if not possible:
raise NoPossibleLinksError
source, sink, w = possible[0]
# just a list of signal tuples for now, will be converted
# to SchemeLinks later
links_to_add = [] # type: List[Link]
links_to_remove = [] # type: List[Link]
show_link_dialog = False
# Ambiguous new link request.
if len(possible) >= 2:
# Check for possible ties in the proposed link weights
_, _, w2 = possible[1]
if w == w2:
show_link_dialog = True
# Check for destructive action (i.e. would the new link
# replace a previous link) except for explicit only link
# candidates
if sink.single and w2 > 0 and \
self.scheme.find_links(sink_node=sink_node,
sink_channel=sink):
show_link_dialog = True
if show_link_dialog:
existing = self.scheme.find_links(source_node=source_node,
sink_node=sink_node)
if existing:
# edit_links will populate the view with existing links
initial_links = None
else:
initial_links = [(source, sink)]
try:
rstatus, links_to_add, links_to_remove = self.edit_links(
source_node, sink_node, initial_links
)
except Exception:
log.error("Failed to edit the links",
exc_info=True)
raise
if rstatus == EditLinksDialog.Rejected:
raise UserCanceledError
else:
# links_to_add now needs to be a list of actual SchemeLinks
links_to_add = [
scheme.SchemeLink(source_node, source, sink_node, sink)
]
links_to_add, links_to_remove = \
add_links_plan(self.scheme, links_to_add)
# Remove temp items before creating any new links
self.cleanup()
for link in links_to_remove:
commands.RemoveLinkCommand(self.scheme, link,
parent=self.macro)
for link in links_to_add:
# Check if the new requested link is a duplicate of an
# existing link
duplicate = self.scheme.find_links(
link.source_node, link.source_channel,
link.sink_node, link.sink_channel
)
if not duplicate:
commands.AddLinkCommand(self.scheme, link,
parent=self.macro)
except scheme.IncompatibleChannelTypeError:
log.info("Cannot connect: invalid channel types.")
self.cancel()
except scheme.SchemeTopologyError:
log.info("Cannot connect: connection creates a cycle.")
self.cancel()
except NoPossibleLinksError:
log.info("Cannot connect: no possible links.")
self.cancel()
except UserCanceledError:
log.info("User canceled a new link action.")
self.cancel(UserInteraction.UserCancelReason)
except Exception:
log.error("An error occurred during the creation of a new link.",
exc_info=True)
self.cancel()
def edit_links(
self,
source_node: Node,
sink_node: Node,
initial_links: 'Optional[List[OIPair]]' = None
) -> 'Tuple[int, List[Link], List[Link]]':
"""
Show and execute the `EditLinksDialog`.
Optional `initial_links` list can provide a list of initial
`(source, sink)` channel tuples to show in the view, otherwise
the dialog is populated with existing links in the scheme (passing
an empty list will disable all initial links).
"""
status, links_to_add_spec, links_to_remove_spec = \
edit_links(
self.scheme, source_node, sink_node, initial_links,
parent=self.document
)
if status == EditLinksDialog.Accepted:
links_to_add = [
scheme.SchemeLink(
source_node, source_channel,
sink_node, sink_channel
) for source_channel, sink_channel in links_to_add_spec
]
links_to_remove = list(reduce(
list.__iadd__, (
self.scheme.find_links(
source_node, source_channel,
sink_node, sink_channel
) for source_channel, sink_channel in links_to_remove_spec
),
[]
)) # type: List[Link]
conflicting = [conflicting_single_link(self.scheme, link)
for link in links_to_add]
conflicting = [link for link in conflicting if link is not None]
for link in conflicting:
if link not in links_to_remove:
links_to_remove.append(link)
return status, links_to_add, links_to_remove
else:
return status, [], []
def end(self):
# type: () -> None
self.cleanup()
self.reset_open_anchor()
# Remove the help tip set in mousePressEvent
self.macro = None
helpevent = QuickHelpTipEvent("", "")
QCoreApplication.postEvent(self.document, helpevent)
super().end()
def cancel(self, reason=UserInteraction.OtherReason):
# type: (int) -> None
self.cleanup()
self.reset_open_anchor()
super().cancel(reason)
def cleanup(self):
# type: () -> None
"""
Cleanup all temporary items in the scene that are left.
"""
if self.tmp_link_item:
self.tmp_link_item.setSinkItem(None)
self.tmp_link_item.setSourceItem(None)
if self.tmp_link_item.scene():
self.scene.removeItem(self.tmp_link_item)
self.tmp_link_item = None
if self.current_target_item:
if not self.showing_incompatible_widget:
self.remove_tmp_anchor()
else:
if self.direction == self.FROM_SOURCE:
anchor = self.current_target_item.inputAnchorItem
else:
anchor = self.current_target_item.outputAnchorItem
anchor.setIncompatible(False)
self.current_target_item = None
if self.cursor_anchor_point and self.cursor_anchor_point.scene():
self.scene.removeItem(self.cursor_anchor_point)
self.cursor_anchor_point = None
def reset_open_anchor(self):
"""
This isn't part of cleanup, because it should retain its value
until the link is created.
"""
if self.direction == self.FROM_SOURCE:
anchor = self.from_item.outputAnchorItem
else:
anchor = self.from_item.inputAnchorItem
anchor.setKeepAnchorOpen(None)
def edit_links(
scheme: Scheme,
source_node: Node,
sink_node: Node,
initial_links: 'Optional[List[OIPair]]' = None,
parent: 'Optional[QWidget]' = None
) -> 'Tuple[int, List[OIPair], List[OIPair]]':
"""
Show and execute the `EditLinksDialog`.
Optional `initial_links` list can provide a list of initial
`(source, sink)` channel tuples to show in the view, otherwise
the dialog is populated with existing links in the scheme (passing
an empty list will disable all initial links).
"""
log.info("Constructing a Link Editor dialog.")
dlg = EditLinksDialog(parent, windowTitle="Edit Links")
# all SchemeLinks between the two nodes.
links = scheme.find_links(source_node=source_node, sink_node=sink_node)
existing_links = [(link.source_channel, link.sink_channel)
for link in links]
if initial_links is None:
initial_links = list(existing_links)
dlg.setNodes(source_node, sink_node)
dlg.setLinks(initial_links)
log.info("Executing a Link Editor Dialog.")
rval = dlg.exec()
if rval == EditLinksDialog.Accepted:
edited_links = dlg.links()
# Differences
links_to_add = set(edited_links) - set(existing_links)
links_to_remove = set(existing_links) - set(edited_links)
return rval, list(links_to_add), list(links_to_remove)
else:
return rval, [], []
def add_links_plan(scheme, links, force_replace=False):
# type: (Scheme, Iterable[Link], bool) -> Tuple[List[Link], List[Link]]
"""
Return a plan for adding a list of links to the scheme.
"""
links_to_add = list(links)
links_to_remove = [conflicting_single_link(scheme, link)
for link in links]
links_to_remove = [link for link in links_to_remove if link is not None]
if not force_replace:
links_to_add, links_to_remove = remove_duplicates(links_to_add,
links_to_remove)
return links_to_add, links_to_remove
def conflicting_single_link(scheme, link):
# type: (Scheme, Link) -> Optional[Link]
"""
Find and return an existing link in `scheme` connected to the same
input channel as `link` if the channel has the 'single' flag.
If no such channel exists (or sink channel is not 'single')
return `None`.
"""
if link.sink_channel.single:
existing = scheme.find_links(
sink_node=link.sink_node,