-
Notifications
You must be signed in to change notification settings - Fork 444
/
Copy pathgraphics_view.py
1726 lines (1450 loc) · 69.2 KB
/
graphics_view.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
# -*- coding: utf-8 -*-
#
# Copyright (C) 2014 GNS3 Technologies Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Graphical view on the scene where items are drawn.
"""
import logging
import os
from .qt import sip
import sys
from .qt import QtCore, QtGui, QtNetwork, QtWidgets, qpartial, qslot
from .items.node_item import NodeItem
from .dialogs.node_properties_dialog import NodePropertiesDialog
from .link import Link
from .node import Node
from .modules import MODULES
from .modules.module_error import ModuleError
from .modules.builtin import Builtin
from .settings import GRAPHICS_VIEW_SETTINGS
from .topology import Topology
from .template_manager import TemplateManager
from .dialogs.style_editor_dialog import StyleEditorDialog
from .dialogs.text_editor_dialog import TextEditorDialog
from .dialogs.symbol_selection_dialog import SymbolSelectionDialog
from .dialogs.idlepc_dialog import IdlePCDialog
from .dialogs.console_command_dialog import ConsoleCommandDialog
from .dialogs.file_editor_dialog import FileEditorDialog
from .dialogs.node_info_dialog import NodeInfoDialog
from .local_config import LocalConfig
from .progress import Progress
from .utils.server_select import server_select
from .compute_manager import ComputeManager
from .utils.get_icon import get_icon
# link items
from .items.link_item import LinkItem, SvgIconItem
from .items.ethernet_link_item import EthernetLinkItem
from .items.serial_link_item import SerialLinkItem
# other items
from .items.label_item import LabelItem
from .items.text_item import TextItem
from .items.shape_item import ShapeItem
from .items.drawing_item import DrawingItem
from .items.rectangle_item import RectangleItem
from .items.line_item import LineItem
from .items.ellipse_item import EllipseItem
from .items.image_item import ImageItem
from .items.logo_item import LogoItem
log = logging.getLogger(__name__)
class GraphicsView(QtWidgets.QGraphicsView):
"""
Graphics view that displays the scene.
:param parent: parent widget
"""
# Class-level constants for default colors
DEFAULT_DRAWING_GRID_COLOR = QtGui.QColor(208, 208, 208) # #D0D0D0
DEFAULT_NODE_GRID_COLOR = QtGui.QColor(190, 190, 190) # #BEBEBE
def __init__(self, parent):
# Our parent is the central widget which parent is the main window.
self._main_window = parent.parent()
super().__init__(parent)
self._settings = {}
self._loadSettings()
self._adding_link = False
self._adding_note = False
self._adding_rectangle = False
self._adding_ellipse = False
self._adding_line = False
self._newlink = None
self._dragging = False
self._grid_size = 75
self._drawing_grid_size = 25
self._drawing_grid_color = self.DEFAULT_DRAWING_GRID_COLOR
self._node_grid_color = self.DEFAULT_NODE_GRID_COLOR
self._last_mouse_position = None
self._topology = Topology.instance()
self._background_warning_msgbox = QtWidgets.QErrorMessage(self)
self._background_warning_msgbox.setWindowTitle("Layer position")
# set the scene
scene = QtWidgets.QGraphicsScene(parent=self)
width = self._settings["scene_width"]
height = self._settings["scene_height"]
self.setScene(scene)
self.setSceneSize(width, height)
# set the custom flags for this view
self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
self.setRenderHint(QtGui.QPainter.Antialiasing)
self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorViewCenter)
# default directories for QFileDialog
self._import_config_directory = QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.DocumentsLocation)
self._export_config_directory = QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.DocumentsLocation)
self._local_addresses = ['0.0.0.0', '127.0.0.1', 'localhost', '::1', '0:0:0:0:0:0:0:1', '::', QtNetwork.QHostInfo.localHostName()]
def setSceneSize(self, width, height):
self.scene().setSceneRect(-(width / 2), -(height / 2), width, height)
def setZoom(self, zoom):
"""
Sets zoom of the Graphics View
"""
if zoom:
factor = zoom / 100.
self.scale(factor, factor)
def setNodeGridSize(self, grid_size):
"""
Sets the grid size for nodes.
"""
self._grid_size = grid_size
def nodeGridSize(self):
"""
Returns the grid size for nodes.
:return: integer
"""
return self._grid_size
def setDrawingGridSize(self, grid_size):
"""
Sets the grid size for drawings
"""
self._drawing_grid_size = grid_size
def drawingGridSize(self):
"""
Returns the grid size for drawings
:return: integer
"""
return self._drawing_grid_size
def setEnabled(self, enabled):
if enabled is False:
self.reset()
item = QtWidgets.QGraphicsTextItem("Please create a project")
item.setPos(0, 0)
self.scene().addItem(item)
super().setEnabled(enabled)
self.toggleUiDeviceMenu()
def reset(self):
"""
Remove all the items from the scene and
reset the instances count.
"""
# reset the modules
for module in MODULES:
instance = module.instance()
instance.reset()
# reset instance IDs for
# nodes, links and ports
Node.reset()
Link.reset()
# reset the topology
self._topology.reset()
# clear the topology summary
self._main_window.uiTopologySummaryTreeWidget.clear()
# reset the lock button
self._main_window.uiLockAllAction.setChecked(False)
# clear all objects on the scene
self.scene().clear()
# reset zoom / scale
self.resetTransform()
def _loadSettings(self):
"""
Loads the settings from the persistent settings file.
"""
self._settings = LocalConfig.instance().loadSectionSettings(self.__class__.__name__, GRAPHICS_VIEW_SETTINGS)
def settings(self):
"""
Returns the graphics view settings.
:returns: settings dictionary
"""
return self._settings
def setSettings(self, new_settings):
"""
Set new graphics view settings.
:param new_settings: settings dictionary
"""
# save the settings
self._settings.update(new_settings)
LocalConfig.instance().saveSectionSettings(self.__class__.__name__, self._settings)
def addingLinkSlot(self, enabled):
"""
Slot to receive events from MainWindow
when a user has clicked on "Add a link" button.
:param enable: either the user is adding a link or not (boolean)
"""
if enabled:
self.setCursor(QtCore.Qt.CrossCursor)
else:
if self._newlink and self._newlink in self.scene().items():
self.scene().removeItem(self._newlink)
self._newlink = None
self.setCursor(QtCore.Qt.ArrowCursor)
self._adding_link = enabled
def addNote(self, state):
"""
Adds a note.
:param state: boolean
"""
if state:
self._adding_note = True
self.setCursor(QtCore.Qt.IBeamCursor)
else:
self._adding_note = False
self.setCursor(QtCore.Qt.ArrowCursor)
def addRectangle(self, state):
"""
Adds a rectangle.
:param state: boolean
"""
if state:
self._adding_rectangle = True
self.setCursor(QtCore.Qt.PointingHandCursor)
else:
self._adding_rectangle = False
self.setCursor(QtCore.Qt.ArrowCursor)
def addEllipse(self, state):
"""
Adds an ellipse.
:param state: boolean
"""
if state:
self._adding_ellipse = True
self.setCursor(QtCore.Qt.PointingHandCursor)
else:
self._adding_ellipse = False
self.setCursor(QtCore.Qt.ArrowCursor)
def addLine(self, state):
"""
Adds a line.
:param state: boolean
"""
if state:
self._adding_line = True
self.setCursor(QtCore.Qt.PointingHandCursor)
else:
self._adding_line = False
self.setCursor(QtCore.Qt.ArrowCursor)
def addImage(self, image_path):
"""
Adds an image.
:param image_path: path to the image
"""
image_item = ImageItem(image_path=image_path, project=self._topology.project())
image_item.create()
self.scene().addItem(image_item)
self._topology.addDrawing(image_item)
def addLogo(self, logo_path, logo_url):
logo_item = LogoItem(logo_path, logo_url, self._topology.project())
self.scene().addItem(logo_item)
def addLink(self, source_node, source_port, destination_node, destination_port, **link_data):
"""
Creates a Link instance representing a connection between 2 devices.
:param source_node: source Node instance
:param source_port: source Port instance
:param destination_node: destination Node instance
:param destination_port: destination Port instance
:param link_data: information about link from the API
:returns: Link
"""
link = Link(source_node, source_port, destination_node, destination_port, **link_data)
# connect the signals that let the graphics view knows about events such as
# a new link creation or deletion.
if self._topology.addLink(link):
source_node.addLink(link)
destination_node.addLink(link)
link.add_link_signal.connect(self.addLinkSlot)
link.delete_link_signal.connect(self.deleteLinkSlot)
if link.initialized():
self.addLinkSlot(link.id())
return link
def addLinkSlot(self, link_id):
"""
Slot to receive events from Link instances
when a link has been created.
:param link_id: link identifier
"""
link = self._topology.getLink(link_id)
if not link:
return
source_item = None
destination_item = None
source_port = link.sourcePort()
destination_port = link.destinationPort()
# find the correct source and destination node items
for item in self.scene().items():
if isinstance(item, NodeItem):
if item.node().id() == link.sourceNode().id():
source_item = item
if item.node().id() == link.destinationNode().id():
destination_item = item
if source_item and destination_item:
break
if not source_item or not destination_item:
log.error("Could not find a source or destination item for the link!")
self.deleteLinkSlot(link_id)
return
if link.sourcePort().linkType() == "Serial":
link_item = SerialLinkItem(source_item, source_port, destination_item, destination_port, link)
else:
link_item = EthernetLinkItem(source_item, source_port, destination_item, destination_port, link)
self.scene().addItem(link_item)
def deleteLinkSlot(self, link_id):
"""
Slot to receive events from Link instances
when a link has been deleted.
:param link_id: link identifier
"""
link = self._topology.getLink(link_id)
self._topology.removeLink(link)
def _userNodeLinking(self, event, item):
"""
Handles node linking by the user.
:param event: QMouseEvent instance
:param item: NodeItem instance
"""
# link addition code
if not self._newlink:
source_item = item
source_port = source_item.connectToPort(event.globalPos())
if not source_port:
return
if source_port.link() is not None:
QtWidgets.QMessageBox.warning(self, "Create link", "Can't create the link the port is not free")
return
if source_port.linkType() == "Serial":
self._newlink = SerialLinkItem(source_item, source_port, self.mapToScene(event.pos()), None, adding_flag=True)
else:
self._newlink = EthernetLinkItem(source_item, source_port, self.mapToScene(event.pos()), None, adding_flag=True)
self.scene().addItem(self._newlink)
else:
source_item = self._newlink.sourceItem()
source_port = self._newlink.sourcePort()
destination_item = item
destination_port = destination_item.connectToPort(event.globalPos())
if not destination_port:
return
if destination_port.link() is not None:
QtWidgets.QMessageBox.warning(self, "Create link", "Can't create the link the destination port is not free")
return
if self._newlink in self.scene().items():
self.scene().removeItem(self._newlink)
self._newlink = None
self.addLink(source_item.node(), source_port, destination_item.node(), destination_port)
def mousePressEvent(self, event):
"""
Handles all mouse press events.
:param event: QMouseEvent instance
"""
is_not_link = True
is_not_logo = True
item = self.itemAt(event.pos())
if item and sip.isdeleted(item):
return
elif not item:
self._main_window.uiStatusBar.clearMessage() # reset the status bar message when clicking on the scene
if item and (isinstance(item, LinkItem) or isinstance(item.parentItem(), LinkItem)):
is_not_link = False
if item and (isinstance(item, LogoItem) or isinstance(item.parentItem(), LogoItem)):
is_not_logo = False
else:
for it in self.scene().items():
if isinstance(it, LinkItem):
it.setHovered(False)
if (event.buttons() == QtCore.Qt.LeftButton and event.modifiers() == QtCore.Qt.ShiftModifier) or event.buttons() == QtCore.Qt.MidButton:
# checks to see if either the middle mouse is pressed
# or a combination of left mouse button and SHIT key are pressed to start dragging the view
self._last_mouse_position = self.mapFromGlobal(event.globalPos())
self._dragging = True
self.setCursor(QtCore.Qt.ClosedHandCursor)
return
if is_not_link and item and event.modifiers() == QtCore.Qt.ControlModifier and event.button() == QtCore.Qt.LeftButton and item and not self._adding_link:
# manual selection using CTRL
if item.isSelected():
item.setSelected(False)
else:
item.setSelected(True)
elif is_not_link and is_not_logo and event.button() == QtCore.Qt.RightButton and not self._adding_link:
pass #TODO: remove this without creating a bug...
elif is_not_link and self._adding_link and event.button() == QtCore.Qt.RightButton:
# send a escape key to the main window to cancel the link addition
key = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, QtCore.Qt.Key_Escape, QtCore.Qt.NoModifier)
QtWidgets.QApplication.sendEvent(self._main_window, key)
elif item and isinstance(item, NodeItem) and self._adding_link and event.button() == QtCore.Qt.LeftButton:
self._userNodeLinking(event, item)
#context_event = QtGui.QContextMenuEvent(QtGui.QContextMenuEvent.Mouse, event.pos())
#QtWidgets.QApplication.sendEvent(self, context_event)
elif event.button() == QtCore.Qt.LeftButton and self._adding_note:
pos = self.mapToScene(event.pos())
note = self.createDrawingItem("text", int(pos.x()), int(pos.y()), 2)
pos_x = note.pos().x()
pos_y = note.pos().y() - (note.boundingRect().height() / 2)
note.setPos(pos_x, pos_y)
note.editText()
self._main_window.uiAddNoteAction.setChecked(False)
self.setCursor(QtCore.Qt.ArrowCursor)
self._adding_note = False
elif event.button() == QtCore.Qt.LeftButton and self._adding_rectangle:
pos = self.mapToScene(event.pos())
self.createDrawingItem("rect", int(pos.x()), int(pos.y()), 1)
self._main_window.uiDrawRectangleAction.setChecked(False)
self.setCursor(QtCore.Qt.ArrowCursor)
self._adding_rectangle = False
elif event.button() == QtCore.Qt.LeftButton and self._adding_ellipse:
pos = self.mapToScene(event.pos())
self.createDrawingItem("ellipse", int(pos.x()), int(pos.y()), 1)
self._main_window.uiDrawEllipseAction.setChecked(False)
self.setCursor(QtCore.Qt.ArrowCursor)
self._adding_ellipse = False
elif event.button() == QtCore.Qt.LeftButton and self._adding_line:
pos = self.mapToScene(event.pos())
self.createDrawingItem("line", int(pos.x()), int(pos.y()), 1)
self._main_window.uiDrawLineAction.setChecked(False)
self.setCursor(QtCore.Qt.ArrowCursor)
self._adding_line = False
else:
super().mousePressEvent(event)
self.toggleUiDeviceMenu()
def contextMenuEvent(self, event):
"""
Handles all context menu events.
:param event: QContextMenuEvent instance
"""
is_not_link = True
is_not_logo = True
item = self.itemAt(event.pos())
if item and sip.isdeleted(item):
return
if item and (isinstance(item, LinkItem) or isinstance(item.parentItem(), LinkItem)):
is_not_link = False
if item and (isinstance(item, LogoItem) or isinstance(item.parentItem(), LogoItem)):
is_not_logo = False
else:
for it in self.scene().items():
if isinstance(it, LinkItem):
it.setHovered(False)
if is_not_link and is_not_logo and not self._adding_link:
if item and not sip.isdeleted(item):
# Prevent right clicking on a selected item from de-selecting all other items
if not item.isSelected():
if not event.modifiers() & QtCore.Qt.ControlModifier:
for it in self.scene().items():
it.setSelected(False)
item.setSelected(True)
self._showDeviceContextualMenu(event.globalPos())
# when more than one item is selected display the contextual menu even if mouse is not above an item
elif len(self.scene().selectedItems()) > 1:
self._showDeviceContextualMenu(event.globalPos())
#elif item and isinstance(item, NodeItem) and self._adding_link:
# self._userNodeLinking(event, item)
else:
super().contextMenuEvent(event)
def mouseReleaseEvent(self, event):
"""
Handles all mouse release events.
:param: QMouseEvent instance
"""
for item in self.scene().selectedItems():
if isinstance(item, NodeItem):
item.mouseRelease()
# If the left mouse button is not still pressed TOGETHER with the SHIFT key and neither is the middle button
# this means the user is no longer trying to drag the view
if self._dragging and not (event.buttons() == QtCore.Qt.LeftButton and event.modifiers() == QtCore.Qt.ShiftModifier) and not event.buttons() & QtCore.Qt.MidButton:
self._dragging = False
self.setCursor(QtCore.Qt.ArrowCursor)
else:
item = self.itemAt(event.pos())
if item is not None and not event.modifiers() & QtCore.Qt.ControlModifier:
item.setSelected(True)
super().mouseReleaseEvent(event)
self.toggleUiDeviceMenu()
def wheelEvent(self, event):
"""
Handles zoom in or out using the mouse wheel.
:param: QWheelEvent instance
"""
if event.modifiers() == QtCore.Qt.ControlModifier:
delta = event.angleDelta()
if delta is not None and delta.x() == 0:
# CTRL is pressed then use the mouse wheel to zoom in or out.
self.scaleView(pow(2.0, (delta.y()/2) / 240.0))
self._topology.project().setZoom(round(self.transform().m11() * 100))
self._topology.project().update()
else:
super().wheelEvent(event)
def scaleView(self, scale_factor):
"""
Scales the view (zoom in and out).
"""
factor = self.transform().scale(scale_factor, scale_factor).mapRect(QtCore.QRectF(0, 0, 1, 1)).width()
if factor < 0.10 or factor > 10:
return
self.scale(scale_factor, scale_factor)
self._main_window.uiStatusBar.showMessage("Zoom: {}%".format(round(self.transform().m11() * 100)), 5000)
def keyPressEvent(self, event):
"""
Handles all key press events for this view.
:param event: QKeyEvent
"""
if event.key() == QtCore.Qt.Key_Delete:
# check if we are editing an LabelItem instance, then send the delete key event to it
for item in self.scene().selectedItems():
if (isinstance(item, LabelItem) or isinstance(item, TextItem)) and item.hasFocus():
super().keyPressEvent(event)
return
self.deleteActionSlot()
super().keyPressEvent(event)
def mouseMoveEvent(self, event):
"""
Handles all mouse move events (mouse tracking has been enabled).
:param event: QMouseEvent instance
"""
if self._dragging:
# This if statement event checks to see if the user is dragging the scene
# if so it sets the value of the scene scroll bars based on the change between
# the previous and current mouse position
mapped_global_pos = self.mapFromGlobal(event.globalPos())
hBar = self.horizontalScrollBar()
vBar = self.verticalScrollBar()
delta = mapped_global_pos - self._last_mouse_position
hBar.setValue(hBar.value() + (delta.x() if QtWidgets.QApplication.isRightToLeft() else -delta.x()))
vBar.setValue(vBar.value() - delta.y())
self._last_mouse_position = mapped_global_pos
if self._adding_link and self._newlink and self._newlink in self.scene().items():
# update the mouse position when the user is adding a link.
self._newlink.setMousePoint(self.mapToScene(event.pos()))
event.ignore()
else:
item = self.itemAt(event.pos())
if item:
# show item coords in the status bar
coords = "X: {} Y: {} Z: {}".format(item.x(), item.y(), item.zValue())
self._main_window.uiStatusBar.showMessage(coords)
# force the children to redraw because of a problem with QGraphicsEffect
for item in self.scene().selectedItems():
for child in item.childItems():
child.update()
super().mouseMoveEvent(event)
def mouseDoubleClickEvent(self, event):
"""
Handles all mouse double click events.
:param event: QMouseEvent instance
"""
item = self.itemAt(event.pos())
if not self._adding_link:
if isinstance(item, NodeItem) and item.node().initialized():
item.setSelected(True)
if item.node().status() == Node.stopped or item.node().consoleType() == "none" or item.node().consoleType() is None:
self.configureSlot()
return
else:
if item.node().bringToFront():
return
self.consoleFromItems(self.scene().selectedItems())
return
elif isinstance(item, LabelItem) and isinstance(item.parentItem(), NodeItem):
if item.parentItem().node().initialized():
item.parentItem().setSelected(True)
self.changeHostnameActionSlot()
return
super().mouseDoubleClickEvent(event)
def configureSlot(self, items=None):
"""
Opens the node properties dialog.
"""
if not items:
items = []
for item in self.scene().selectedItems():
if isinstance(item, NodeItem) and item.node().initialized() and hasattr(item.node(), "configPage"):
items.append(item)
with Progress.instance().context(min_duration=0):
node_properties = NodePropertiesDialog(items, self._main_window)
node_properties.setModal(True)
node_properties.show()
node_properties.exec_()
def dragMoveEvent(self, event):
"""
Handles all drag move events.
:param event: QDragMoveEvent instance
"""
# check if what is dragged is handled by this view
if event.mimeData().hasFormat("text/uri-list") \
or event.mimeData().hasFormat("application/x-gns3-template"):
event.acceptProposedAction()
event.accept()
else:
event.ignore()
def dropEvent(self, event):
"""
Handles all drop events.
:param event: QDropEvent instance
"""
log.debug("Drop event received with mime data: {}".format(event.mimeData().formats()))
# check if what has been dropped is handled by this view
if event.mimeData().hasFormat("application/x-gns3-template"):
template_id = event.mimeData().data("application/x-gns3-template").data().decode()
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
if event.keyboardModifiers() == QtCore.Qt.ShiftModifier:
max_nodes_per_line = 10 # max number of nodes on a single line
offset = 100 # spacing between elements
integer, ok = QtWidgets.QInputDialog.getInt(self, "Nodes", "Number of nodes:", 2, 1, 100, 1)
if ok:
for node_number in range(integer):
x = event.pos().x() - (150 // 2) + (node_number % max_nodes_per_line) * offset
y = event.pos().y() - (70 // 2) + (node_number // max_nodes_per_line) * offset
if self.createNodeFromTemplateId(template_id, QtCore.QPoint(x, y)) is False:
event.ignore()
break
else:
if self.createNodeFromTemplateId(template_id, event.pos()) is False:
event.ignore()
elif event.mimeData().hasFormat("text/uri-list") and event.mimeData().hasUrls():
# This should not arrive but we received bug report with it...
if len(event.mimeData().urls()) == 0:
return
if len(event.mimeData().urls()) > 1:
QtWidgets.QMessageBox.critical(self, "Project files", "Please drop only one file")
return
path = event.mimeData().urls()[0].toLocalFile()
if os.path.isfile(path):
self._main_window.loadPath(path)
event.acceptProposedAction()
else:
event.ignore()
def _showDeviceContextualMenu(self, pos):
"""
Create and display the device contextual menu on the view.
:param pos: position where to display the menu
"""
menu = QtWidgets.QMenu()
self.populateDeviceContextualMenu(menu)
menu.exec_(pos)
menu.clear()
# Make sure to deselect all items.
# This is to prevent a bug on Windows
# see https://github.com/GNS3/gns3-gui/issues/2986
for it in self.scene().items():
it.setSelected(False)
def populateDeviceContextualMenu(self, menu):
"""
Adds device actions to the device contextual menu.
:param menu: QMenu instance
"""
items = self.scene().selectedItems()
if not items:
return
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "configPage"), items)):
# Action: Configure node
configure_action = QtWidgets.QAction("Configure", menu)
configure_action.setIcon(get_icon("configuration.svg"))
configure_action.triggered.connect(self.configureActionSlot)
menu.addAction(configure_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and item.node().console() is not None, items)):
console_action = QtWidgets.QAction("Console", menu)
console_action.setIcon(get_icon("console.svg"))
console_action.triggered.connect(self.consoleActionSlot)
menu.addAction(console_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "auxConsole"), items)):
aux_console_action = QtWidgets.QAction("Auxiliary console", menu)
aux_console_action.setIcon(get_icon("aux-console.svg"))
aux_console_action.triggered.connect(self.auxConsoleActionSlot)
menu.addAction(aux_console_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and not item.node().isAlwaysOn(), items)):
start_action = QtWidgets.QAction("Start", menu)
start_action.setIcon(get_icon("start.svg"))
start_action.triggered.connect(self.startActionSlot)
menu.addAction(start_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and not item.node().isAlwaysOn(), items)):
suspend_action = QtWidgets.QAction("Suspend", menu)
suspend_action.setIcon(get_icon("pause.svg"))
suspend_action.triggered.connect(self.suspendActionSlot)
menu.addAction(suspend_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and not item.node().isAlwaysOn(), items)):
stop_action = QtWidgets.QAction("Stop", menu)
stop_action.setIcon(get_icon("stop.svg"))
stop_action.triggered.connect(self.stopActionSlot)
menu.addAction(stop_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and not item.node().isAlwaysOn(), items)):
reload_action = QtWidgets.QAction("Reload", menu)
reload_action.setIcon(get_icon("reload.svg"))
reload_action.triggered.connect(self.reloadActionSlot)
menu.addAction(reload_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and item.node().console() is not None, items)):
console_edit_action = QtWidgets.QAction("Custom console", menu)
console_edit_action.setIcon(get_icon("console_edit.svg"))
console_edit_action.triggered.connect(self.customConsoleActionSlot)
menu.addAction(console_edit_action)
if True in list(map(lambda item: isinstance(item, NodeItem), items)):
# Action: Change hostname
change_hostname_action = QtWidgets.QAction("Change hostname", menu)
change_hostname_action.setIcon(get_icon("show-hostname.svg"))
change_hostname_action.triggered.connect(self.changeHostnameActionSlot)
menu.addAction(change_hostname_action)
if True in list(map(lambda item: isinstance(item, NodeItem), items)):
# Action: Change symbol
change_symbol_action = QtWidgets.QAction("Change symbol", menu)
change_symbol_action.setIcon(get_icon("node_conception.svg"))
change_symbol_action.triggered.connect(self.changeSymbolActionSlot)
menu.addAction(change_symbol_action)
if True in list(map(lambda item: isinstance(item, DrawingItem) or isinstance(item, NodeItem), items)):
duplicate_action = QtWidgets.QAction("Duplicate", menu)
duplicate_action.setIcon(get_icon("duplicate.svg"))
duplicate_action.triggered.connect(self.duplicateActionSlot)
menu.addAction(duplicate_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "info"), items)):
# Action: Show node information
show_node_info_action = QtWidgets.QAction("Show node information", menu)
show_node_info_action.setIcon(get_icon("help.svg"))
show_node_info_action.triggered.connect(self.showNodeInfoSlot)
menu.addAction(show_node_info_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "nodeDir"), items)):
# Action: Show in file manager
show_in_file_manager_action = QtWidgets.QAction("Show in file manager", menu)
show_in_file_manager_action.setIcon(get_icon("open.svg"))
show_in_file_manager_action.triggered.connect(self.showInFileManagerSlot)
menu.addAction(show_in_file_manager_action)
if not sys.platform.startswith("darwin") and True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "bringToFront"), items)):
# Action: bring console or window to front (Windows and Linux only)
bring_to_front_action = QtWidgets.QAction("Bring to front", menu)
bring_to_front_action.setIcon(get_icon("front.svg"))
bring_to_front_action.triggered.connect(self.bringToFrontSlot)
menu.addAction(bring_to_front_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and bool(item.node().configFiles()), items)):
import_config_action = QtWidgets.QAction("Import config", menu)
import_config_action.setIcon(get_icon("import.svg"))
import_config_action.triggered.connect(self.importConfigActionSlot)
menu.addAction(import_config_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and bool(item.node().configFiles()), items)):
export_config_action = QtWidgets.QAction("Export config", menu)
export_config_action.setIcon(get_icon("export.svg"))
export_config_action.triggered.connect(self.exportConfigActionSlot)
menu.addAction(export_config_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and bool(item.node().configTextFiles()), items)):
export_config_action = QtWidgets.QAction("Edit config", menu)
export_config_action.setIcon(get_icon("edit.svg"))
export_config_action.triggered.connect(self.editConfigActionSlot)
menu.addAction(export_config_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "idlepc"), items)):
idlepc_action = QtWidgets.QAction("Idle-PC", menu)
idlepc_action.setIcon(get_icon("calculate.svg"))
idlepc_action.triggered.connect(self.idlepcActionSlot)
menu.addAction(idlepc_action)
if True in list(map(lambda item: isinstance(item, NodeItem) and hasattr(item.node(), "idlepc"), items)):
auto_idlepc_action = QtWidgets.QAction("Auto Idle-PC", menu)
auto_idlepc_action.setIcon(get_icon("calculate.svg"))
auto_idlepc_action.triggered.connect(self.autoIdlepcActionSlot)
menu.addAction(auto_idlepc_action)
if True in list(map(lambda item: isinstance(item, LabelItem), items)):
text_edit_action = QtWidgets.QAction("Text edit", menu)
text_edit_action.setIcon(get_icon("show-hostname.svg"))
text_edit_action.triggered.connect(self.textEditActionSlot)
menu.addAction(text_edit_action)
if True in list(map(lambda item: isinstance(item, TextItem), items)):
text_edit_action = QtWidgets.QAction("Text edit", menu)
text_edit_action.setIcon(get_icon("edit.svg"))
text_edit_action.triggered.connect(self.textEditActionSlot)
menu.addAction(text_edit_action)
if True in list(map(lambda item: isinstance(item, ShapeItem) or isinstance(item, LineItem), items)):
style_action = QtWidgets.QAction("Style", menu)
style_action.setIcon(get_icon("node_conception.svg"))
style_action.triggered.connect(self.styleActionSlot)
menu.addAction(style_action)
if True in list(map(lambda item: isinstance(item, LabelItem), items)) and False in list(map(lambda item: item.parentItem() is None, items)):
# action only for port labels
reset_label_position_action = QtWidgets.QAction("Reset position", menu)
reset_label_position_action.setIcon(get_icon("reset.svg"))
reset_label_position_action.triggered.connect(self.resetLabelPositionActionSlot)
menu.addAction(reset_label_position_action)
# item must have no parent
if True in list(map(lambda item: item.parentItem() is None, items)):
if len(items) > 1:
horizontal_align_action = QtWidgets.QAction("Align horizontally", menu)
horizontal_align_action.setIcon(get_icon("horizontally.svg"))
horizontal_align_action.triggered.connect(self.horizontalAlignmentSlot)
menu.addAction(horizontal_align_action)
vertical_align_action = QtWidgets.QAction("Align vertically", menu)
vertical_align_action.setIcon(get_icon("vertically.svg"))
vertical_align_action.triggered.connect(self.verticalAlignmentSlot)
menu.addAction(vertical_align_action)
raise_layer_action = QtWidgets.QAction("Raise one layer", menu)
raise_layer_action.setIcon(get_icon("raise_z_value.svg"))
raise_layer_action.triggered.connect(self.raiseLayerActionSlot)
menu.addAction(raise_layer_action)
lower_layer_action = QtWidgets.QAction("Lower one layer", menu)
lower_layer_action.setIcon(get_icon("lower_z_value.svg"))
lower_layer_action.triggered.connect(self.lowerLayerActionSlot)
menu.addAction(lower_layer_action)
if len(items) > 1:
lock_action = QtWidgets.QAction("Lock or unlock items", menu)
lock_action.setIcon(get_icon("lock.svg"))
else:
item = items[0]
if item.flags() & QtWidgets.QGraphicsItem.ItemIsMovable:
lock_action = QtWidgets.QAction("Lock item", menu)
lock_action.setIcon(get_icon("lock.svg"))
else:
lock_action = QtWidgets.QAction("Unlock item", menu)
lock_action.setIcon(get_icon("unlock.svg"))
lock_action.triggered.connect(self.lockActionSlot)
menu.addAction(lock_action)
delete_action = QtWidgets.QAction("Delete", menu)
delete_action.setIcon(get_icon("delete.svg"))
delete_action.triggered.connect(self.deleteActionSlot)
menu.addAction(delete_action)
def startActionSlot(self):
"""
Slot to receive events from the start action in the
contextual menu.
"""
for item in self.scene().selectedItems():
if isinstance(item, NodeItem) and hasattr(item.node(), "start") and item.node().initialized():
item.node().start()
def stopActionSlot(self):
"""
Slot to receive events from the stop action in the
contextual menu.
"""
for item in self.scene().selectedItems():
if isinstance(item, NodeItem) and hasattr(item.node(), "stop") and item.node().initialized():
item.node().stop()
def suspendActionSlot(self):
"""
Slot to receive events from the suspend action in the
contextual menu.
"""
for item in self.scene().selectedItems():