-
Notifications
You must be signed in to change notification settings - Fork 34
/
scenegraph.py
1776 lines (1437 loc) · 62.3 KB
/
scenegraph.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
#!/usr/bin/env python
from PySide import QtCore, QtGui
from functools import partial
import os
import re
import pysideuic
import xml.etree.ElementTree as xml
from cStringIO import StringIO
import simplejson as json
from SceneGraph import options
from SceneGraph import core
from SceneGraph import util
from SceneGraph.ui import settings
from SceneGraph.ui import models
from SceneGraph.ui import attributes
from SceneGraph.ui import graphics
log = core.log
SCENEGRAPH_UI = options.SCENEGRAPH_UI
def loadUiType(uiFile):
"""
Pyside lacks the "loadUiType" command, so we have to convert the ui file to py code in-memory first
and then execute it in a special frame to retrieve the form_class.
"""
parsed = xml.parse(uiFile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uiFile, 'r') as f:
o = StringIO()
frame = {}
pysideuic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
try:
exec pyc in frame
except ImportError as err:
log.warning('loadUi: %s' % err)
#Fetch the base_class and form class based on their type in the xml from designer
form_class = frame['Ui_%s'%form_class]
base_class = eval('QtGui.%s'%widget_class)
return form_class, base_class
#If you put the .ui file for this example elsewhere, just change this path.
form_class, base_class = loadUiType(SCENEGRAPH_UI)
class SceneGraphUI(form_class, base_class):
def __init__(self, parent=None, **kwargs):
super(SceneGraphUI, self).__init__(parent)
from SceneGraph.icn import icons
self.setupUi(self)
self.setDockNestingEnabled(True)
#self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.icons = icons.ICONS
self.fonts = dict()
self.view = None # GraphicsView
self.pmanager = None # Plugin manager UI
self.attr_manager = None # Attribute manager dialog
self.graph_attrs = None
# font prefs
self.font_family_ui = None
self.font_family_mono = None
self.font_family_nodes = None
self.font_size_ui = None
self.font_size_mono = None
# stylesheet
self.stylesheet_name = None
self.palette_style = None
self.font_style = None
# preferences
self.debug = kwargs.get('debug', False)
self.use_gl = kwargs.get('use_gl', False)
self.use_stylesheet = kwargs.get('use_stylesheet', True)
self.stylesheet = None # stylesheet manager
self.ignore_scene_prefs = False
self._show_private = False
self._valid_plugins = []
self.edge_type = kwargs.get('edge_type', 'bezier')
self.viewport_mode = kwargs.get('viewport_mode', 'smart')
self.render_fx = kwargs.get('render_fx', True)
self.antialiasing = 2
self.environment = kwargs.get('env', 'standalone')
# setup default user path
self._work_path = kwargs.get('start', options.SCENEGRAPH_USER_WORK_PATH)
self.status_timer = QtCore.QTimer()
self.autosave_inc = 30000
self.autosave_timer = QtCore.QTimer()
# stash temp selections here
self._selected_nodes = []
# undo stack
self.undo_stack = QtGui.QUndoStack(self)
# preferences
self.settings_file = os.path.join(options.SCENEGRAPH_PREFS_PATH, 'SceneGraph.ini')
self.qsettings = settings.Settings(self.settings_file, QtCore.QSettings.IniFormat, parent=self)
self.qsettings.setFallbacksEnabled(False)
# icon
self.setWindowIcon(QtGui.QIcon(os.path.join(options.SCENEGRAPH_ICON_PATH, 'graph_icon.png')))
# item views/models
self.tableView = models.TableView(self.sceneWidgetContents)
self.sceneScrollAreaLayout.addWidget(self.tableView)
self.tableModel = models.GraphTableModel(headers=['Node Type', 'Node'])
self.tableView.setModel(self.tableModel)
self.tableSelectionModel = self.tableView.selectionModel()
# nodes list model
self.nodesModel = models.NodesListModel()
self.nodeStatsList.setModel(self.nodesModel)
self.nodeListSelModel = self.nodeStatsList.selectionModel()
# edges list
self.edgesModel = models.EdgesListModel()
self.edgeStatsList.setModel(self.edgesModel)
self.edgeListSelModel = self.edgeStatsList.selectionModel()
# setup
self.initializeWorkPath(self._work_path)
# read settings first, so that user prefs will override defaults
self.readSettings(**kwargs)
self.initializeStylesheet()
self.initializeUI()
self.connectSignals()
self.resetStatus()
#- Attributes ----
@property
def handler(self):
"""
Return the current SceneEventHandler.
.. todo::: probably should take this out, useful for debugging mostly.
:returns: SceneEventHandler instance.
:rtype: SceneEventHandler
"""
return self.view.scene().handler
def eventFilter(self, obj, event):
"""
Install an event filter to filter key presses away from the parent.
"""
if event.type() == QtCore.QEvent.KeyPress:
#if event.key() == QtCore.Qt.Key_Delete:
if self.hasFocus():
return True
return False
else:
return super(SceneGraphUI, self).eventFilter(obj, event)
def initializeWorkPath(self, path=None):
"""
Setup the user work directory.
:param str path: user work path.
"""
if not path:
path = options.SCENEGRAPH_USER_WORK_PATH
if os.path.exists(path):
os.chdir(path)
return path
else:
if os.makedirs(path):
os.chdir(path)
return path
return
def initializeUI(self):
"""
Set up the main UI
"""
# build the graph
self.initializeGraphicsView()
self.initializePreferencesPane()
self.initializeRecentFilesMenu()
self.buildWindowTitle()
self.resetStatus()
# Qt application style menu
self.app_style_label.setHidden(True)
self.app_style_menu.setHidden(True)
# setup undo/redo
undo_action = self.view.scene().undo_stack.createUndoAction(self, "&Undo")
undo_action.setShortcuts(QtGui.QKeySequence.Undo)
redo_action = self.view.scene().undo_stack.createRedoAction(self, "&Redo")
redo_action.setShortcuts(QtGui.QKeySequence.Redo)
self.menu_edit.addAction(undo_action)
self.menu_edit.addAction(redo_action)
# validators for console widget
self.scene_posx.setValidator(QtGui.QDoubleValidator(-5000, 10000, 2, self.scene_posx))
self.scene_posy.setValidator(QtGui.QDoubleValidator(-5000, 10000, 2, self.scene_posy))
self.view_posx.setValidator(QtGui.QDoubleValidator(-5000, 10000, 2, self.view_posx))
self.view_posy.setValidator(QtGui.QDoubleValidator(-5000, 10000, 2, self.view_posy))
self.autosave_time_edit.setValidator(QtGui.QDoubleValidator(0, 1000, 2, self.autosave_time_edit))
self.consoleTextEdit.textChanged.connect(self.outputTextChangedAction)
self.toggleDebug()
def initializeStylesheet(self, paths=[], style='default', **kwargs):
"""
Setup the stylehsheet.
"""
overrides = dict(
font_family_ui = kwargs.get('font_family_ui', self.font_family_ui),
font_family_mono = kwargs.get('font_family_mono', self.font_family_mono),
font_size_ui = kwargs.get('font_size_ui', self.font_size_ui),
font_size_mono = kwargs.get('font_size_mono', self.font_size_mono),
stylesheet_name = kwargs.get('stylesheet_name', self.stylesheet_name),
palette_style = kwargs.get('palette_style', self.palette_style),
font_style = kwargs.get('font_style', self.font_style)
)
self.stylesheet.run(paths=paths)
style_data = self.stylesheet.style_data(style=style, **overrides)
if self.use_stylesheet:
self.setStyleSheet(style_data)
attr_editor = self.getAttributeEditorWidget()
if attr_editor:
attr_editor.setStyleSheet(style_data)
def initializeGraphicsView(self, filter=False):
"""
Initialize the graphics view/scen and graph objects.
"""
# initialize the Graph
self.graph = core.Graph()
self.network = self.graph.network
# add our custom GraphicsView object (gview is defined in the ui file)
self.view = graphics.GraphicsView(self.gview, ui=self, use_gl=self.use_gl, edge_type=self.edge_type)
self.gviewLayout.addWidget(self.view)
self.view.setSceneRect(-5000, -5000, 10000, 10000)
self.view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.network.graph['environment'] = self.environment
# disable plugins
if self._valid_plugins:
for plugin in self.graph.plug_mgr.node_types():
if plugin not in self._valid_plugins:
log.info('disabling plugin "%s"' % plugin)
self.graph.plug_mgr.node_types().get(plugin).update(enabled=False)
def connectSignals(self):
"""
Setup signals & slots.
"""
# timers
self.status_timer.timeout.connect(self.resetStatus)
self.autosave_timer.timeout.connect(self.autoSaveAction)
self.view.tabPressed.connect(partial(self.createTabMenu, self.view))
self.view.statusEvent.connect(self.updateConsole)
# Scene handler
self.view.selectionChanged.connect(self.nodesSelectedAction)
# file & ui menu
self.menu_file.aboutToShow.connect(self.initializeFileMenu)
self.menu_graph.aboutToShow.connect(self.initializeGraphMenu)
self.menu_window.aboutToShow.connect(self.initializeWindowMenu)
self.menu_debug.aboutToShow.connect(self.initializeDebugMenu)
self.menu_nodes.aboutToShow.connect(self.initializeNodesMenu)
self.action_new_graph.triggered.connect(self.resetGraph)
self.action_read_graph.triggered.connect(self.readGraph)
self.action_save_graph.triggered.connect(self.saveCurrentGraph)
self.action_save_graph_as.triggered.connect(self.saveGraphAs)
self.action_revert.triggered.connect(self.revertGraph)
self.action_show_all.triggered.connect(self.togglePrivate)
self.action_reset_scale.triggered.connect(self.resetScale)
self.action_restore_default_layout.triggered.connect(self.restoreDefaultSettings)
self.action_exit.triggered.connect(self.close)
self.action_save_layout.triggered.connect(self.saveLayoutAction)
self.action_plugins.triggered.connect(self.pluginManagerAction)
# debug menu
self.action_reset_dots.triggered.connect(self.resetDotsAction)
self.action_evaluate.triggered.connect(self.evaluateScene)
self.action_plugin_output.triggered.connect(self.evaluatePlugins)
self.action_update_nodes.triggered.connect(self.graphAttributesAction)
self.action_style_output.triggered.connect(self.stylesheetOutputAction)
# preferences
self.ignore_scene_prefs_check.toggled.connect(self.toggleIgnore)
self.action_debug_mode.triggered.connect(self.toggleDebug)
self.edge_type_menu.currentIndexChanged.connect(self.edgeTypeChangedAction)
self.viewport_mode_menu.currentIndexChanged.connect(self.toggleViewMode)
self.check_use_gl.toggled.connect(self.toggleOpenGLMode)
self.logging_level_menu.currentIndexChanged.connect(self.toggleLoggingLevel)
self.check_render_fx.toggled.connect(self.toggleEffectsRendering)
self.autosave_time_edit.editingFinished.connect(self.setAutosaveDelay)
self.app_style_menu.currentIndexChanged.connect(self.applicationStyleChanged)
self.ui_font_menu.currentIndexChanged.connect(self.stylesheetChangedAction)
self.mono_font_menu.currentIndexChanged.connect(self.stylesheetChangedAction)
self.node_font_menu.currentIndexChanged.connect(self.stylesheetChangedAction)
# styles
self.stylesheet_menu.currentIndexChanged.connect(self.stylesheetChangedAction)
self.palette_style_menu.currentIndexChanged.connect(self.stylesheetChangedAction)
self.font_style_menu.currentIndexChanged.connect(self.stylesheetChangedAction)
self.ui_fontsize_spinbox.valueChanged.connect(self.stylesheetChangedAction)
self.mono_fontsize_spinbox.valueChanged.connect(self.stylesheetChangedAction)
self.button_reset_fonts.clicked.connect(self.resetFontsAction)
# output tab buttons
self.tabWidget.currentChanged.connect(self.updateOutput)
self.tabWidget.currentChanged.connect(self.updateMetadata)
self.button_refresh.clicked.connect(self.updateOutput)
self.button_clear.clicked.connect(self.outputTextBrowser.clear)
self.consoleTabWidget.currentChanged.connect(self.updateStats)
# table view
self.tableSelectionModel.selectionChanged.connect(self.tableSelectionChangedAction)
self.nodeListSelModel.selectionChanged.connect(self.nodesModelChangedAction)
self.edgeListSelModel.selectionChanged.connect(self.edgesModelChangedAction)
# undo tab
self.undo_stack.cleanChanged.connect(self.buildWindowTitle)
self.button_undo_clean.clicked.connect(self.clearUndoStack)
self.button_console_clear.clicked.connect(self.consoleTextEdit.clear)
# status tips
self.action_new_graph.setStatusTip("Clear the graph")
self.action_read_graph.setStatusTip("Open a scene")
self.action_save_graph.setStatusTip("Save current graph")
self.action_save_graph_as.setStatusTip("Save current graph as")
self.action_revert.setStatusTip("Revert graph to last saved version")
self.action_show_all.setStatusTip("Show hidden node attributes")
#self.statusBar().messageChanged.connect(self.status_timer.start(4000))
def initializeFileMenu(self):
"""
Setup the file menu before it is drawn.
"""
current_scene = self.graph.getScene()
if not current_scene:
#self.action_save_graph.setEnabled(False)
self.action_revert.setEnabled(False)
# create the recent files menu
self.initializeRecentFilesMenu()
def initializeGraphMenu(self):
"""
Setup the graph menu before it is drawn.
"""
edge_type = 'bezier'
if self.view.scene().edge_type == 'bezier':
edge_type = 'polygon'
self.action_edge_type.setText('%s lines' % edge_type.title())
db_label = 'Debug on'
debug = os.getenv('SCENEGRAPH_DEBUG', False)
if debug in ['true', '1']:
debug = True
if debug in ['false', '0']:
debug = False
if debug:
db_label = 'Debug off'
show_msg = 'Show all attrbutes'
if self._show_private:
show_msg = 'Hide private attrbutes'
self.action_debug_mode.setText(db_label)
self.action_show_all.setText(show_msg)
def initializeWindowMenu(self):
"""
Set up the Window menu.
"""
restore_menu = self.menu_restore_layout
delete_menu = self.menu_delete_layout
restore_menu.clear()
delete_menu.clear()
layout_names = self.qsettings.get_layouts()
for layout in layout_names:
restore_action = restore_menu.addAction(layout)
restore_action.triggered.connect(partial(self.qsettings.restoreLayout, layout))
if layout != 'default':
delete_action = delete_menu.addAction(layout)
delete_action.triggered.connect(partial(self.qsettings.deleteLayout, layout))
def initializeDebugMenu(self):
"""
Set up the debug menu.
"""
has_dots = False
for node in self.view.scene().get_nodes():
if node.node_class == 'dot':
has_dots = True
self.action_reset_dots.setEnabled(has_dots)
def initializeNodesMenu(self):
"""
Set up the nodes menu.
"""
current_pos = QtGui.QCursor().pos()
color = False
attribute = False
scene = self.view.scene()
nodes = scene.selectedNodes()
if nodes:
color = True
attribute = True
self.createNodesMenu(self.menu_nodes, pos=current_pos, color=color, attribute=attribute)
def initializeRecentFilesMenu(self):
"""
Build a menu of recently opened scenes.
"""
recent_files = self.qsettings.getRecentFiles()
self.menu_recent_files.clear()
self.menu_recent_files.setEnabled(False)
if recent_files:
i = 0
# Recent files menu
for filename in reversed(recent_files):
if filename:
if i < self.qsettings._max_files:
file_action = QtGui.QAction(filename, self.menu_recent_files)
file_action.triggered.connect(partial(self.readGraph, filename))
self.menu_recent_files.addAction(file_action)
i+=1
self.menu_recent_files.setEnabled(True)
def initializePreferencesPane(self, **kwargs):
"""
Setup the preferences area.
"""
ignore_scene_prefs = kwargs.pop('ignore_scene_prefs', self.ignore_scene_prefs)
render_fx = kwargs.pop('render_fx', self.render_fx)
viewport_mode = kwargs.pop('viewport_mode', self.viewport_mode)
font_family_ui = kwargs.pop('font_family_ui', self.font_family_ui)
autosave_inc = kwargs.pop('autosave_inc', self.autosave_inc)
antialiasing = kwargs.pop('antialiasing', self.antialiasing)
font_size_mono = kwargs.pop('font_size_mono', self.font_size_mono)
stylesheet_name = kwargs.pop('stylesheet_name', self.stylesheet_name)
palette_style = kwargs.pop('palette_style', self.palette_style)
font_style = kwargs.pop('font_style', self.font_style)
font_size_ui = kwargs.pop('font_size_ui', self.font_size_ui)
edge_type = kwargs.pop('edge_type', self.edge_type)
font_family_nodes = kwargs.pop('font_family_nodes', self.font_family_nodes)
use_gl = kwargs.pop('use_gl', self.use_gl)
font_family_mono = kwargs.pop('font_family_mono', self.font_family_mono)
self.ignore_scene_prefs_check.blockSignals(True)
self.edge_type_menu.blockSignals(True)
self.edge_type_menu.blockSignals(True)
self.viewport_mode_menu.blockSignals(True)
self.check_use_gl.blockSignals(True)
self.logging_level_menu.blockSignals(True)
self.check_render_fx.blockSignals(True)
self.app_style_menu.blockSignals(True)
self.ui_font_menu.blockSignals(True)
self.mono_font_menu.blockSignals(True)
self.node_font_menu.blockSignals(True)
self.ui_fontsize_spinbox.blockSignals(True)
self.mono_fontsize_spinbox.blockSignals(True)
self.stylesheet_menu.blockSignals(True)
self.palette_style_menu.blockSignals(True)
self.font_style_menu.blockSignals(True)
# global preferences
self.ignore_scene_prefs_check.setChecked(ignore_scene_prefs)
self.edge_type_menu.clear()
self.viewport_mode_menu.clear()
self.logging_level_menu.clear()
# edge type menu
self.edge_type_menu.addItems(options.EDGE_TYPES)
self.edge_type_menu.setCurrentIndex(self.edge_type_menu.findText(edge_type))
# render FX
self.check_render_fx.setChecked(render_fx)
# build the viewport menu
for item in options.VIEWPORT_MODES.items():
label, mode = item[0], item[1]
self.viewport_mode_menu.addItem(label, str(mode))
self.viewport_mode_menu.setCurrentIndex(self.viewport_mode_menu.findText(viewport_mode))
# OpenGL check
GL_MODE = use_gl
if GL_MODE is None:
GL_MODE = False
self.check_use_gl.setChecked(GL_MODE)
# logging level
log_level_str = [x[0] for x in options.LOGGING_LEVELS.items() if x[1] == log.level][0]
# add current log levels to the menu
for item in options.LOGGING_LEVELS.items():
label, mode = item[0], item[1]
self.logging_level_menu.addItem(label.lower(), mode)
self.logging_level_menu.setCurrentIndex(self.logging_level_menu.findText(log_level_str.lower()))
# undo viewer
self.undoView = QtGui.QUndoView(self.tab_undo)
self.undoTabLayout.insertWidget(0,self.undoView)
self.undoView.setStack(self.undo_stack)
self.undoView.setCleanIcon(self.icons.get("arrow_curve_180_left"))
# autosave prefs
self.autosave_time_edit.setText(str(autosave_inc/1000))
# application style
app = QtGui.QApplication.instance()
current_style = app.style().metaObject().className()
current_style = current_style.split(':')[0]
app_styles = [current_style]
app_styles.extend(QtGui.QStyleFactory.keys())
app_styles = list(set(app_styles))
self.app_style_menu.clear()
self.app_style_menu.addItems(app_styles)
self.app_style_menu.setCurrentIndex(self.app_style_menu.findText(current_style))
# font/stylesheet preferences
self.ui_font_menu.clear()
self.mono_font_menu.clear()
self.stylesheet_menu.clear()
self.palette_style_menu.clear()
self.font_style_menu.clear()
# font menus
self.ui_font_menu.addItems(self.stylesheet.buildUIFontList())
self.mono_font_menu.addItems(self.stylesheet.buildMonospaceFontList())
self.node_font_menu.addItems(self.stylesheet.buildNodesFontList())
self.stylesheet_menu.addItems(self.stylesheet.qss_names)
self.palette_style_menu.addItems(self.stylesheet.palette_styles)
self.font_style_menu.addItems(self.stylesheet.font_styles)
self.ui_font_menu.setCurrentIndex(self.ui_font_menu.findText(font_family_ui))
self.mono_font_menu.setCurrentIndex(self.mono_font_menu.findText(font_family_mono))
self.node_font_menu.setCurrentIndex(self.node_font_menu.findText(font_family_nodes))
self.stylesheet_menu.setCurrentIndex(self.stylesheet_menu.findText(stylesheet_name))
self.palette_style_menu.setCurrentIndex(self.palette_style_menu.findText(palette_style))
self.font_style_menu.setCurrentIndex(self.font_style_menu.findText(font_style))
ui_font_size = float(re.sub('pt$', '', font_size_ui))
mono_font_size = float(re.sub('pt$', '', font_size_mono))
self.ui_fontsize_spinbox.setValue(ui_font_size)
self.mono_fontsize_spinbox.setValue(mono_font_size)
self.ignore_scene_prefs_check.blockSignals(False)
self.edge_type_menu.blockSignals(False)
self.viewport_mode_menu.blockSignals(False)
self.check_use_gl.blockSignals(False)
self.logging_level_menu.blockSignals(False)
self.check_render_fx.blockSignals(False)
self.app_style_menu.blockSignals(False)
self.ui_font_menu.blockSignals(False)
self.mono_font_menu.blockSignals(False)
self.node_font_menu.blockSignals(False)
self.ui_fontsize_spinbox.blockSignals(False)
self.mono_fontsize_spinbox.blockSignals(False)
self.stylesheet_menu.blockSignals(False)
self.palette_style_menu.blockSignals(False)
self.font_style_menu.blockSignals(False)
def buildWindowTitle(self):
"""
Build the window title
"""
title_str = 'Scene Graph'
if self.environment not in ['standalone']:
title_str = 'Scene Graph - %s' % self.environment.title()
if self.graph.getScene():
title_str = '%s: %s' % (title_str, self.graph.getScene())
# add an asterisk if the current stack is dirty (scene is changed)
if not self.undo_stack.isClean():
title_str = '%s*' % title_str
#self.autosave_timer.start(self.autosave_inc)
self.setWindowTitle(title_str)
def sizeHint(self):
return QtCore.QSize(800, 675)
#- Status & Messaging ------
def updateStatus(self, msg, level='info'):
"""
Send output to logger/statusbar
"""
if level == 'info':
self.statusBar().showMessage(self._getInfoStatus(msg))
log.info(msg)
if level == 'error':
self.statusBar().showMessage(self._getErrorStatus(msg))
log.error(msg)
if level == 'warning':
self.statusBar().showMessage(self._getWarningStatus(msg))
log.warning(msg)
self.status_timer.start(4000)
def resetStatus(self):
"""
Reset the status bar message.
"""
self.statusBar().showMessage('[SceneGraph]: ready')
def _getInfoStatus(self, msg):
return '[SceneGraph]: INFO: %s' % msg
def _getErrorStatus(self, val):
return '[SceneGraph]: ERROR: %s' % msg
def _getWarningStatus(self, val):
return '[SceneGraph]: WARNING: %s' % msg
#- Saving & Loading ------
def saveGraphAs(self, filename=None):
"""
Save the current graph to a json file. Pass the filename argument to override.
:param str filename: file path to save.
"""
import os
if not filename:
filename = os.path.join(os.getenv('HOME'), 'my_graph.json')
if self.graph.getScene():
filename = self.graph.getScene()
scenefile, filters = QtGui.QFileDialog.getSaveFileName(self, "Save graph file",
filename,
"JSON files (*.json)")
basename, fext = os.path.splitext(scenefile)
if not fext:
scenefile = '%s.json' % basename
self.undo_stack.setClean()
filename = str(os.path.normpath(scenefile))
self.updateStatus('saving current graph "%s"' % scenefile)
self.graph.write(scenefile)
#self.action_save_graph.setEnabled(True)
self.action_revert.setEnabled(True)
# remove autosave files
autosave_file = '%s~' % scenefile
if os.path.exists(autosave_file):
os.remove(autosave_file)
self.qsettings.addRecentFile(scenefile)
self.initializeRecentFilesMenu()
self.buildWindowTitle()
def saveCurrentGraph(self):
"""
Save the current graph file.
.. todo:::
- combine this with saveGraphAs
"""
if not self.graph.getScene():
filename = self.saveDialog()
if filename:
self.graph.setScene(filename)
else:
return
self.undo_stack.setClean()
filename = self.graph.getScene()
self.updateStatus('saving current graph "%s"' % filename)
self.graph.write(filename)
self.buildWindowTitle()
self.qsettings.addRecentFile(filename)
self.initializeRecentFilesMenu()
# remove autosave files
autosave_file = '%s~' % filename
if os.path.exists(autosave_file):
os.remove(autosave_file)
return self.graph.getScene()
def autoSaveAction(self):
"""
Save a temp file when the graph changes. Set to auto-fire when the autosave timer
timeouts.
"""
if self.undo_stack.isClean():
self.autosave_timer.start(self.autosave_inc)
return
if self.graph.getScene():
autosave = '%s~' % self.graph.getScene()
else:
# use the graph's autosave path
autosave = self.graph.autosave_path
self.graph.write(autosave, auto=True)
self.updateStatus('autosaving "%s"...' % autosave)
#self.undo_stack.setClean()
return autosave
def readGraph(self, filename=None):
"""
Read the current graph from a json file.
:param str filename: scene file to read.
"""
if filename is None:
filename = self.openDialog("Open graph file", path=self._work_path)
if not filename:
return
if not os.path.exists(filename):
log.error('filename %s does not exist' % filename)
return
# stash a string for recent files menu
recent_file = filename
# check for autosave file
filename = self.autoSaveCheck(filename)
self.resetGraph()
self.updateStatus('reading graph "%s"' % filename)
self.graph.read(filename)
#self.action_save_graph.setEnabled(True)
self.qsettings.addRecentFile(recent_file)
log.debug('adding recent file: "%s"' % filename)
self.buildWindowTitle()
self.view.scene().clearSelection()
self.undo_stack.setClean()
self.autosave_timer.start(self.autosave_inc)
self.clearUndoStack()
def autoSaveCheck(self, filename):
"""
Queries the user to choose to use a newer autosave version
of the given filename. If the user chooses the autosave file,
the autosave is copied over the current filename and removed.
:param str filename: file to check for autosave.
:returns: file to read.
:rtype: str
"""
autosave_file = '%s~' % filename
if os.path.exists(autosave_file):
if util.is_newer(autosave_file, filename):
use_autosave = self.promptDialog("Autosave exists", "Newer file exists: %s, use that?" % autosave_file)
if use_autosave:
try:
import shutil
shutil.copy(autosave_file, filename)
except:
pass
# remove the autosave file.
os.remove(autosave_file)
return filename
def revertGraph(self):
"""
Revert the current graph file.
"""
filename=self.graph.getScene()
if filename:
self.resetGraph()
self.readGraph(filename)
log.info('reverting graph: %s' % filename)
self.clearUndoStack()
def resetGraph(self):
"""
Clear the current graph.
"""
self.view.scene().initialize()
self.graph.reset()
#self.action_save_graph.setEnabled(False)
self.buildWindowTitle()
self.updateOutput()
self.clearUndoStack()
def resetScale(self):
self.view.resetMatrix()
def clearUndoStack(self):
"""
Reset the undo stack.
"""
self.undo_stack.clear()
def toggleViewMode(self):
"""
Update the GraphicsView update mode for performance.
"""
mode = self.viewport_mode_menu.currentText()
qmode = self.viewport_mode_menu.itemData(self.viewport_mode_menu.currentIndex())
self.view.viewport_mode = eval(qmode)
self.view.scene().update()
self.viewport_mode = mode
def toggleOpenGLMode(self, val):
"""
Toggle OpenGL mode and swap out viewports.
"""
self.use_gl = val
widget = self.view.viewport()
widget.deleteLater()
if self.use_gl:
from PySide import QtOpenGL
self.view.setViewport(QtOpenGL.QGLWidget(QtOpenGL.QGLFormat(QtOpenGL.QGL.SampleBuffers)))
log.info('initializing OpenGL renderer.')
else:
self.view.setViewport(QtGui.QWidget())
self.initializeStylesheet()
self.view.scene().update()
def toggleEffectsRendering(self, val):
"""
Toggle rendering of node effects.
.. todo::: this probably belongs in GraphicsView/Scene.
"""
self.render_fx = val
log.info('toggling effects %s' % ('on' if val else 'off'))
for node in self.view.scene().scenenodes.values():
if hasattr(node, '_render_effects'):
node._render_effects = self.render_fx
node.update()
self.view.scene().update()
def toggleLoggingLevel(self):
"""
Toggle the logging level.
"""
log.level = self.logging_level_menu.itemData(self.logging_level_menu.currentIndex())
print '# DEBUG: toggling log level: ', log.level
def toggleIgnore(self):
self.ignore_scene_prefs = self.ignore_scene_prefs_check.isChecked()
def toggleDebug(self):
"""
Set the debug environment variable and set widget
debug values to match.
"""
debug = os.getenv('SCENEGRAPH_DEBUG', False)
if debug in ['true', '1']:
debug = False
if debug in ['false', '0']:
debug = True
nodes = self.view.scene().get_nodes()
edge_widgets = self.view.scene().get_edges()
if nodes:
for widget in nodes:
widget.setDebug(debug)
if edge_widgets:
for ewidget in edge_widgets:
ewidget._debug = debug
self.debug = debug
self.view.scene().update()
self.view.scene().update()
os.environ['SCENEGRAPH_DEBUG'] = '1' if debug else '0'
def toggleEdgeTypes(self, edge_type):
"""
Toggle the edge types.
:params str edge_type: edge type (bezier or polygon)
"""
if edge_type != self.edge_type:
self.edge_type = edge_type
for edge in self.view.scene().get_edges():
edge.edge_type = self.edge_type
self.view.scene().update()
menu_text = self.edge_type_menu.currentText()
if menu_text != edge_type:
self.edge_type_menu.blockSignals(True)
self.edge_type_menu.setCurrentIndex(self.edge_type_menu.findText(edge_type))
self.edge_type_menu.blockSignals(False)
def togglePrivate(self):
"""
**Debug
"""
self._show_private = not self._show_private
ae = self.getAttributeEditorWidget()
if ae:
ae.setNodes(self.view.scene().selectedDagNodes(), clear=True)
def setAutosaveDelay(self):
"""
Update the autosave increment time.
Time is in seconds, so mult X 1000
"""
astime = int(self.autosave_time_edit.text())
log.info('updating autosave delay to: %d seconds.' % astime)
self.autosave_timer.stop()
self.autosave_inc = astime * 1000
self.autosave_timer.start(self.autosave_inc)
#- Actions ----
def edgeTypeChangedAction(self):
"""
Runs when the current edge type menu is changed.
"""
edge_type = self.edge_type_menu.currentText()
self.toggleEdgeTypes(edge_type)
def applicationStyleChanged(self, index):
"""
Sets the current application style.
"""
style_name = self.app_style_menu.currentText()
app = QtGui.QApplication.instance()
log.debug('setting application style: "%s"' % str(style_name))
app.setStyle(style_name)
self.initializeStylesheet()
def stylesheetChangedAction(self, index):
"""
Runs when the user updates a font/stylesheet pref.
"""
self.font_family_ui = str(self.ui_font_menu.currentText())
self.font_family_mono = str(self.mono_font_menu.currentText())
self.font_family_nodes = str(self.node_font_menu.currentText())
ui_fontsize = self.ui_fontsize_spinbox.value()
mono_fontsize = self.mono_fontsize_spinbox.value()