xstack 2.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,692 @@
1
+ import typing
2
+ import logging
3
+ import functools
4
+ import qtility
5
+ from Qt import QtWidgets, QtGui, QtCore
6
+
7
+ from . import resources
8
+ from . import options
9
+ from . import config
10
+ from . import tree
11
+ from . import settings
12
+ from . import runner
13
+ from . import log_view
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ # --------------------------------------------------------------------------------------
19
+ # noinspection PyUnresolvedReferences
20
+ class AppWidget(QtWidgets.QWidget):
21
+ """
22
+ This is the main widget that brings together the tree view and the options
23
+ view
24
+
25
+ Args:
26
+ app_config: This is a class that inherits from xstack_app.AppConfig. You can
27
+ use this to tailor how this application presents information and terminology
28
+ """
29
+
30
+ build_started = QtCore.Signal()
31
+ build_complete = QtCore.Signal()
32
+
33
+ # ----------------------------------------------------------------------------------
34
+ def __init__(self, app_config=None, allow_threading=True, parent: QtWidgets.QWidget = None):
35
+ super().__init__(parent=parent)
36
+
37
+ # -- Store the stack
38
+ self.stack = None
39
+ self.allow_threading = allow_threading
40
+ self.run_thread = None
41
+
42
+ # -- Store the app config
43
+ self.app_config = app_config or config.AppConfig
44
+
45
+ # -- These are properties used in full mode
46
+ self.tree_widget = None
47
+ self.editor_widget = None
48
+ self.splitter = None
49
+
50
+ # -- These are for our menu system
51
+ self.menu_bar = None
52
+ self.progress_bar = QtWidgets.QProgressBar(self)
53
+ self.progress_bar.setRange(0, 100)
54
+ self.progress_bar.setVisible(False)
55
+
56
+ # -- Set the layout
57
+ self.setLayout(
58
+ qtility.layouts.slimify(
59
+ QtWidgets.QVBoxLayout(),
60
+ ),
61
+ )
62
+
63
+ # -- The content is split into tabs: the stack itself, and the log. The
64
+ # -- tabs are made once, and only the stack tab is rebuilt when the
65
+ # -- active stack changes, so the log survives switching stacks. The
66
+ # -- progress bar sits below the tabs so it shows on either.
67
+ self.tab_widget = QtWidgets.QTabWidget(self)
68
+ self.tab_widget.setDocumentMode(True)
69
+ self.tab_widget.setTabBarAutoHide(True)
70
+ self.layout().addWidget(self.tab_widget)
71
+ self.layout().addWidget(self.progress_bar)
72
+
73
+ self.stack_page = QtWidgets.QWidget(self)
74
+ self.stack_page.setLayout(
75
+ qtility.layouts.slimify(
76
+ QtWidgets.QVBoxLayout(),
77
+ ),
78
+ )
79
+ self.tab_widget.addTab(self.stack_page, self.app_config.label)
80
+
81
+ self.log_view = None
82
+
83
+ if self.app_config.show_log_tab:
84
+ self.log_view = log_view.LogView(
85
+ logger_names=self.app_config.log_logger_names,
86
+ parent=self,
87
+ )
88
+ self.log_view.counts_changed.connect(self.update_log_tab_title)
89
+ self.log_view.build_failed.connect(self.on_logged_build_failed)
90
+ self.tab_widget.addTab(self.log_view, "Log")
91
+
92
+ # -- Add the splash widget whilst we're not seeing any rigs
93
+ self.add_splash()
94
+
95
+ # -- Construct the menu on startup
96
+ self.build_menu()
97
+
98
+ self.build_started.connect(self.on_build_started)
99
+ self.build_complete.connect(self.on_build_complete)
100
+
101
+ def build(self, build_up_to=None, build_only=None, build_below=None, validate_only=False):
102
+ """
103
+ This will trigger a threaded build of the stack
104
+
105
+ Args:
106
+ build_below: This will trigger a build of only components within this
107
+ component and below
108
+ validate_only: This will trigger a validation pass only
109
+ """
110
+ self.build_started.emit()
111
+ if self.allow_threading:
112
+ self.run_thread = runner.ThreadedRun(
113
+ stack=self.stack,
114
+ build_up_to=build_up_to,
115
+ build_below=build_below,
116
+ build_only=build_only,
117
+ validate_only=validate_only,
118
+ )
119
+ self.run_thread.build_progressed.connect(self.update_progressbar)
120
+ self.run_thread.finished.connect(self.build_complete.emit)
121
+ self.run_thread.start()
122
+
123
+ else:
124
+ # -- Only listen to the stack for the duration of this build, so
125
+ # -- repeated builds do not stack up connections
126
+ stack = self.stack
127
+ stack.build_progressed.connect(self.update_progressbar)
128
+ stack.build_failed.connect(self.on_build_failed)
129
+
130
+ try:
131
+ stack.build(
132
+ build_up_to=build_up_to,
133
+ build_below=build_below,
134
+ build_only=build_only,
135
+ validate_only=validate_only,
136
+ )
137
+
138
+ finally:
139
+ stack.build_progressed.disconnect(self.update_progressbar)
140
+ stack.build_failed.disconnect(self.on_build_failed)
141
+ self.build_complete.emit()
142
+
143
+ def update_progressbar(self, percentage):
144
+ """
145
+ This will update the progress bar value with the given percentage
146
+
147
+ Args:
148
+ percentage: The percentage value to update
149
+ """
150
+ self.progress_bar.setValue(percentage)
151
+ self.progress_bar.setFormat(f"Running : {int(percentage)}%")
152
+
153
+ def on_build_started(self):
154
+ """
155
+ This event is called with the build of the stack is initiated.
156
+ """
157
+ self.progress_bar.setValue(0)
158
+ self.progress_bar.setVisible(True)
159
+ self.menu_bar.setEnabled(False)
160
+ self.editor_widget.setVisible(False)
161
+
162
+ def on_build_complete(self):
163
+ """
164
+ This event is called when the build is complete
165
+ """
166
+ self.progress_bar.setVisible(False)
167
+ self.menu_bar.setEnabled(True)
168
+ self.editor_widget.setVisible(True)
169
+
170
+ def on_build_failed(self, component=None, details: str = ""):
171
+ """
172
+ This event is called when a build started from this widget fails. It
173
+ selects the component that failed, if there is one, so the user can see
174
+ it straight away. It is not called for threaded builds.
175
+
176
+ Args:
177
+ component: The component which failed or was invalid, or None
178
+ details: The reason for the failure
179
+ """
180
+ if component and self.tree_widget:
181
+ self.tree_widget.select_component(component)
182
+
183
+ # ----------------------------------------------------------------------------------
184
+ def on_logged_build_failed(self):
185
+ """
186
+ This event is called when the log tab sees a build fail, whichever way
187
+ the build was started. It brings the log to the front, unless the user
188
+ has turned that off in the preferences.
189
+ """
190
+ if self.log_view and self.app_config.get_setting("switch_to_log_on_failure"):
191
+ self.tab_widget.setCurrentWidget(self.log_view)
192
+
193
+ # ----------------------------------------------------------------------------------
194
+ def update_log_tab_title(self, warnings: int, errors: int):
195
+ """
196
+ Shows the number of warnings and errors in the title of the log tab, so
197
+ they are visible from the stack tab.
198
+ """
199
+ counts = []
200
+
201
+ if warnings:
202
+ counts.append(f"{warnings} warning{'s' if warnings > 1 else ''}")
203
+
204
+ if errors:
205
+ counts.append(f"{errors} error{'s' if errors > 1 else ''}")
206
+
207
+ title = "Log"
208
+ if counts:
209
+ title = f"Log ({', '.join(counts)})"
210
+
211
+ self.tab_widget.setTabText(self.tab_widget.indexOf(self.log_view), title)
212
+
213
+ # ----------------------------------------------------------------------------------
214
+ def show_component_in_log(self, component):
215
+ """
216
+ Brings the log tab to the front, scrolled to the given component's part
217
+ of the latest build's report.
218
+ """
219
+ if not self.log_view:
220
+ return
221
+
222
+ if self.log_view.show_component(component):
223
+ self.tab_widget.setCurrentWidget(self.log_view)
224
+
225
+ # ----------------------------------------------------------------------------------
226
+ def stack_layout(self) -> QtWidgets.QVBoxLayout:
227
+ """
228
+ Returns the layout of the stack tab. Subclasses which add widgets to the
229
+ stack's view should add them here rather than to the widget's own
230
+ layout, which holds the tabs.
231
+ """
232
+ return self.stack_page.layout()
233
+
234
+ # ----------------------------------------------------------------------------------
235
+ def add_splash(self):
236
+ """
237
+ Adds a splash widget into the layout
238
+ """
239
+ # -- Add the splash image to the background whilst its blank
240
+ splash = QtWidgets.QLabel(parent=self)
241
+ self.stack_layout().addWidget(splash)
242
+ splash.setPixmap(
243
+ QtGui.QPixmap(
244
+ self.app_config.icon,
245
+ ),
246
+ )
247
+ splash.setAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignHCenter )
248
+ return splash
249
+
250
+ # ----------------------------------------------------------------------------------
251
+ def additional_menus(self) -> typing.List:
252
+ """
253
+ This function may be re-implemented when subclassing to request the addition
254
+ of further menu items
255
+
256
+ When re-implementing you should return a list of QMenu's you want to add
257
+ to the app widgets titlebar
258
+ :return:
259
+ """
260
+ return list()
261
+
262
+ # ----------------------------------------------------------------------------------
263
+ def edit_menu_actions(self) -> typing.Dict[str, typing.Callable]:
264
+ """
265
+ This function may be re-implemented when subclassing to add entries to
266
+ the Edit menu, below Preferences.
267
+
268
+ When re-implementing you should return a dictionary of menu labels to
269
+ the callables they trigger
270
+ """
271
+ return dict()
272
+
273
+ # ----------------------------------------------------------------------------------
274
+ def set_active_stack(self, stack: typing.Optional["xstack.Stack"]):
275
+ """
276
+ This function will rebuild the layout of the tool based on the stack we expect
277
+ to be showing as the currently active stack
278
+ """
279
+ # -- Empty the current layout
280
+ qtility.layouts.empty(
281
+ self.stack_layout(),
282
+ )
283
+
284
+ # -- The log captures the builds of whichever stack is showing
285
+ if self.log_view:
286
+ self.log_view.watch_stack(stack)
287
+
288
+ # -- Always update self.stack so listeners and downstream code
289
+ # -- (e.g. subclasses' set_active_stack overrides) see the new
290
+ # -- state. Previously this assignment was skipped on the
291
+ # -- ``stack is None`` branch, leaving self.stack pointing at a
292
+ # -- now-stale previous stack.
293
+ self.stack = stack
294
+
295
+ # -- If we have not been given a stack, we clear the layout and
296
+ # -- rebuild the menu
297
+ if not stack:
298
+ self.tree_widget = None
299
+ self.editor_widget = None
300
+ self.splitter = None
301
+
302
+ self.add_splash()
303
+ self.build_menu()
304
+
305
+ return
306
+
307
+ # -- We have been given a stack, so rebuild the layout.
308
+ self.build_layout()
309
+
310
+ # ----------------------------------------------------------------------------------
311
+ def build_menu(self):
312
+ """
313
+ This will regenerate the tool menu
314
+ """
315
+ # -- We do not hard code the term "stack" into the App. This is because the
316
+ # -- stack library will be used for many purposes, and in most cases the user
317
+ # -- will want to tailor the terminology. Therefore we get the label from
318
+ # -- the app configuration class.
319
+ stack_label = self.app_config.label
320
+
321
+ # -- Create a new menu bar
322
+ self.menu_bar = QtWidgets.QMenuBar(parent=self)
323
+
324
+ # -- Add the stacks menu to the menu
325
+ stacks_menu = QtWidgets.QMenu("File", parent=self)
326
+
327
+ # -- We always expose the new stack option regardless of what is in the scene
328
+ new_stack_action = stacks_menu.addAction(
329
+ QtGui.QIcon(self.app_config.icon),
330
+ f"New {stack_label}",
331
+ )
332
+
333
+ new_stack_action.triggered.connect(
334
+ functools.partial(
335
+ self.create_new_stack,
336
+ )
337
+ )
338
+ stacks_menu.addSeparator()
339
+
340
+ import_stack_action = stacks_menu.addAction(
341
+ QtGui.QIcon(self.app_config.open_icon),
342
+ f"Open {stack_label} File",
343
+ )
344
+
345
+ import_stack_action.triggered.connect(
346
+ functools.partial(
347
+ self.open,
348
+ )
349
+ )
350
+
351
+ export_stack_action = stacks_menu.addAction(
352
+ QtGui.QIcon(self.app_config.save_icon),
353
+ f"Save {stack_label} File",
354
+ )
355
+ export_stack_action.triggered.connect(
356
+ functools.partial(
357
+ self.export_stack,
358
+ )
359
+ )
360
+ stacks_menu.addSeparator()
361
+
362
+ self.menu_bar.addMenu(stacks_menu)
363
+
364
+ # -- Create the settings menu
365
+ settings_menu = QtWidgets.QMenu("Edit", parent=self)
366
+
367
+ settings_editor_action = settings_menu.addAction(f"Preferences")
368
+ settings_editor_action.triggered.connect(
369
+ functools.partial(
370
+ settings.show_settings,
371
+ self.app_config,
372
+ ),
373
+ )
374
+
375
+ # -- Add any entries the application adds to the Edit menu
376
+ edit_actions = self.edit_menu_actions()
377
+
378
+ if edit_actions:
379
+ settings_menu.addSeparator()
380
+
381
+ for label, function in edit_actions.items():
382
+ edit_action = settings_menu.addAction(label)
383
+ edit_action.triggered.connect(
384
+ functools.partial(
385
+ function,
386
+ )
387
+ )
388
+
389
+ self.menu_bar.addMenu(settings_menu)
390
+
391
+ for additional_menu in self.additional_menus():
392
+ self.menu_bar.addMenu(additional_menu)
393
+
394
+ # -- Finally, apply the menu bar
395
+ self.layout().setMenuBar(self.menu_bar)
396
+
397
+
398
+ # -- If we're asked not to show the menu then lets immediately
399
+ # -- exit.
400
+ self.menu_bar.setVisible(self.app_config.show_menu_bar)
401
+
402
+ # ----------------------------------------------------------------------------------
403
+ def build_layout(self):
404
+ """
405
+ This will build the overall content of the tool
406
+ """
407
+ # -- Empty the current layout
408
+ qtility.layouts.empty(
409
+ self.stack_layout(),
410
+ )
411
+
412
+ self.flexible_layout = QtWidgets.QVBoxLayout()
413
+ self.stack_layout().addLayout(self.flexible_layout)
414
+
415
+ self.splitter = QtWidgets.QSplitter()
416
+ self.flexible_layout.addWidget(self.splitter)
417
+
418
+ tree_class = self.app_config.tree_widget or tree.BuildTreeWidget
419
+ self.tree_widget = tree_class(self.stack, self.app_config, app=self)
420
+ self.splitter.addWidget(self.tree_widget)
421
+ self.tree_widget.is_updated.connect(self.propagate_component_selection)
422
+ self.tree_widget.currentItemChanged.connect(self.propagate_component_selection)
423
+
424
+ self.editor_widget = options.ComponentEditor(
425
+ read_only_name=self.app_config.read_only_structure,
426
+ parent=self,
427
+ )
428
+ self.splitter.addWidget(self.editor_widget)
429
+
430
+ # -- The tree draws labels directly from the components, so a repaint is
431
+ # -- enough to show a name changed in the editor
432
+ self.editor_widget.label_changed.connect(self.tree_widget.viewport().update)
433
+
434
+ self.flexible_layout.setStretch(0, 1)
435
+ self.flexible_layout.setStretch(1, 0)
436
+
437
+ self.set_layout_orientation()
438
+
439
+ if self.app_config.splitter_bias is not None:
440
+ orientation = self.splitter.orientation()
441
+
442
+ if orientation == QtCore.Qt.Vertical:
443
+ scope = self.height()
444
+ else:
445
+ scope = self.width()
446
+
447
+ tree_size = scope * self.app_config.splitter_bias
448
+ option_size = scope - tree_size
449
+
450
+ self.splitter.setSizes([tree_size, option_size])
451
+
452
+ # ----------------------------------------------------------------------------------
453
+ def set_layout_orientation(self):
454
+ """
455
+ We adjust the layout of the tool based on whether its wide or tall - as
456
+ different users like to work in different states.
457
+ """
458
+
459
+ if not self.tree_widget:
460
+ return
461
+
462
+ force_vertical = False
463
+ force_horizontal = False
464
+
465
+ if not self.app_config.get_setting("auto_adjust_orientation"):
466
+
467
+ if self.app_config.get_setting("use_vertical_alignment"):
468
+ force_vertical = True
469
+
470
+ else:
471
+ force_horizontal = True
472
+
473
+ if self.app_config.forced_orientation == "vertical":
474
+ force_vertical = True
475
+ force_horizontal = False
476
+
477
+ if self.app_config.forced_orientation == "horizontal":
478
+ force_vertical = False
479
+ force_horizontal = True
480
+
481
+ widget_is_wide = self.rect().width() > self.rect().height()
482
+ use_horizontal_alignment = widget_is_wide
483
+
484
+ if force_horizontal:
485
+ use_horizontal_alignment = True
486
+
487
+ if force_vertical:
488
+ use_horizontal_alignment = False
489
+
490
+ if use_horizontal_alignment:
491
+ self.flexible_layout.setDirection(QtWidgets.QBoxLayout.LeftToRight)
492
+ self.splitter.setOrientation(QtCore.Qt.Horizontal)
493
+ else:
494
+ self.flexible_layout.setDirection(QtWidgets.QBoxLayout.TopToBottom)
495
+ self.splitter.setOrientation(QtCore.Qt.Vertical)
496
+
497
+ # ----------------------------------------------------------------------------------
498
+ def create_new_stack(self):
499
+ """
500
+ This will take the user through the flow of generating a new stack
501
+
502
+ :return:
503
+ """
504
+ stack_label = self.app_config.label
505
+
506
+ name = qtility.request.text(
507
+ title=f"New {stack_label}",
508
+ message=f"Please provide a name for the {stack_label}",
509
+ parent=self,
510
+ )
511
+
512
+ if not name:
513
+ return None
514
+
515
+ new_stack = self.app_config.stack_class(
516
+ label=name,
517
+ component_paths=self.app_config.component_paths,
518
+ )
519
+
520
+ self.switch_stack(new_stack)
521
+ self.build_menu()
522
+
523
+ return new_stack
524
+
525
+ # ----------------------------------------------------------------------------------
526
+ def switch_stack(self, stack: "xstack.Stack"):
527
+ """
528
+ Makes the given stack the one shown by the tool. The new stack and open
529
+ flows both come through here, so re-implement this (rather than
530
+ set_active_stack) to tie into switching stacks.
531
+
532
+ Args:
533
+ stack: The stack to show
534
+ """
535
+ self.set_active_stack(stack)
536
+
537
+ # ----------------------------------------------------------------------------------
538
+ def load_stack_file(self, filepath: str) -> "xstack.Stack":
539
+ """
540
+ Returns the stack to show for the given stack file. By default this is a
541
+ new stack loaded from the file. Re-implement this to load the file into
542
+ an existing stack instead.
543
+
544
+ Args:
545
+ filepath: The json file to load
546
+ """
547
+ return self.app_config.stack_class.open(
548
+ data=filepath,
549
+ component_paths=self.app_config.component_paths,
550
+ )
551
+
552
+ # ----------------------------------------------------------------------------------
553
+ def open(self, filepath=None, silent=False):
554
+ """
555
+ This defines the user flow for importing stack data. Returns the filepath
556
+ that was opened, or None if the user cancelled.
557
+ """
558
+
559
+ stack_label = self.app_config.label
560
+
561
+ if not silent:
562
+ confirmation = qtility.request.confirmation(
563
+ title=f"Import {stack_label}",
564
+ message=(
565
+ f"Importing a {stack_label} will clear any current {stack_label} data. "
566
+ "Are you sure you want to continue?"
567
+ ),
568
+ parent=self,
569
+ )
570
+
571
+ if not confirmation:
572
+ return None
573
+
574
+ if not filepath:
575
+ filepath = qtility.request.filepath(
576
+ title=f"Import {stack_label}",
577
+ filter_="*.json (*.json)",
578
+ parent=self,
579
+ save=False,
580
+ )
581
+
582
+ if not filepath:
583
+ return None
584
+
585
+ try:
586
+ new_stack = self.load_stack_file(filepath)
587
+
588
+ except (OSError, ValueError):
589
+ log.exception(f"Failed to open {filepath}")
590
+ return None
591
+
592
+ if not new_stack:
593
+ return None
594
+
595
+ self.switch_stack(new_stack)
596
+
597
+ return filepath
598
+
599
+ # ----------------------------------------------------------------------------------
600
+ def export_stack(self, additional_data=None):
601
+ """
602
+ Exports the current stack to a stack file
603
+ """
604
+ stack_label = self.app_config.label
605
+
606
+ filepath = qtility.request.filepath(
607
+ title=f"Export {stack_label}",
608
+ filter_="*.json (*.json)",
609
+ save=True,
610
+ parent=self,
611
+ )
612
+
613
+ if not filepath:
614
+ return
615
+
616
+ self.stack.save(
617
+ filepath,
618
+ additional_data=additional_data,
619
+ )
620
+
621
+ # ----------------------------------------------------------------------------------
622
+ def propagate_component_selection(self, *args, **kwargs):
623
+ """
624
+ We use this as a pass-through mechanism, so that when a component is selected
625
+ in the tree view we call the set_component in the editor panel.
626
+ """
627
+ component = self.tree_widget.current_component()
628
+ self.editor_widget.set_component(component)
629
+
630
+ # ----------------------------------------------------------------------------------
631
+ # noinspection PyPep8Naming
632
+ def resizeEvent(self, event):
633
+ """
634
+ Wen the window is resized check out layout orientation
635
+ """
636
+ super().resizeEvent(event)
637
+ self.set_layout_orientation()
638
+
639
+
640
+ # --------------------------------------------------------------------------------------
641
+ # noinspection PyUnresolvedReferences
642
+ class AppWindow(qtility.windows.MemorableWindow):
643
+
644
+ def __init__(self, app_config=None, allow_threading=True, storage_identifier="xstack", *args, **kwargs):
645
+ super().__init__(storage_identifier=storage_identifier, *args, **kwargs)
646
+
647
+ self.app_config = app_config or config.AppConfig
648
+
649
+ # -- Set the window properties
650
+ self.setObjectName(self.app_config.label)
651
+ self.setWindowTitle(self.app_config.label)
652
+
653
+ if self.app_config.icon:
654
+ self.setWindowIcon(
655
+ QtGui.QIcon(
656
+ self.app_config.icon,
657
+ ),
658
+ )
659
+
660
+ widget = self.app_config.app_widget or AppWidget
661
+ self.core = widget(
662
+ app_config=app_config,
663
+ allow_threading=allow_threading,
664
+ parent=self,
665
+ )
666
+ self.setCentralWidget(self.core)
667
+
668
+
669
+ # ------------------------------------------------------------------------------
670
+ # noinspection PyUnresolvedReferences,PyUnusedLocal
671
+ def launch(app_config=None, blocking: bool = True, load_file: str = None, run_on_launch: bool = False, allow_threading=True, active_stack=None, storage_identifier="xstack", *args, **kwargs):
672
+ """
673
+ This function should be called to invoke the app ui
674
+ """
675
+ q_app = qtility.app.get()
676
+
677
+ w = AppWindow(app_config=app_config, allow_threading=allow_threading, storage_identifier=storage_identifier, *args, **kwargs)
678
+ w.show()
679
+
680
+ if load_file:
681
+ w.core.open(filepath=load_file, silent=True)
682
+
683
+ if active_stack:
684
+ w.core.set_active_stack(active_stack)
685
+
686
+ if run_on_launch and w.core.stack:
687
+ w.core.build()
688
+
689
+ if blocking:
690
+ q_app.exec_()
691
+
692
+ return w