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.
xstack/app/runner.py ADDED
@@ -0,0 +1,35 @@
1
+ from Qt import QtCore, QtWidgets
2
+
3
+
4
+ class ThreadedRun(QtCore.QThread):
5
+ """
6
+ This is a Qt thread which can run the given stack to allow the ui to not
7
+ be blocked.
8
+ """
9
+
10
+ # -- This will emit a Qt threading safe signal as the stack
11
+ # -- progresses through its build
12
+ build_progressed = QtCore.Signal(float)
13
+
14
+ def __init__(self, stack, build_up_to=None, build_below=None, build_only=None, validate_only=False, *args, **kwargs):
15
+ super().__init__(*args, **kwargs)
16
+ self.stack = stack
17
+ self.build_up_to = build_up_to
18
+ self.build_below = build_below
19
+ self.build_only = build_only
20
+ self.validate_only = validate_only
21
+
22
+ self.finished.connect(self.disconnect_signals)
23
+
24
+ def run(self):
25
+ self.stack.build_progressed.connect(self.build_progressed.emit)
26
+
27
+ self.stack.build(
28
+ build_up_to=self.build_up_to,
29
+ build_below=self.build_below,
30
+ build_only=self.build_only,
31
+ validate_only=self.validate_only,
32
+ )
33
+
34
+ def disconnect_signals(self):
35
+ self.stack.build_progressed.disconnect(self.build_progressed.emit)
xstack/app/settings.py ADDED
@@ -0,0 +1,89 @@
1
+ import string
2
+ import functools
3
+ import qtility
4
+ from Qt import QtWidgets, QtGui
5
+
6
+ from . import resources
7
+
8
+
9
+
10
+ # --------------------------------------------------------------------------------------
11
+ class SettingsWidget(QtWidgets.QWidget):
12
+
13
+ # ----------------------------------------------------------------------------------
14
+ def __init__(self, app_config, parent=None):
15
+ super().__init__(parent=parent)
16
+
17
+ self.app_config = app_config
18
+
19
+ self.setLayout(
20
+ QtWidgets.QVBoxLayout(),
21
+ )
22
+
23
+ for setting_name, setting_value in self.app_config.all_settings().items():
24
+
25
+ widget = qtility.derive.qwidget(
26
+ value=setting_value,
27
+ )
28
+
29
+ # -- Hook up a connection such that when this option ui changes we
30
+ # -- reflect that change into the component
31
+ qtility.derive.connect(
32
+ widget,
33
+ functools.partial(
34
+ self.store_setting_change,
35
+ widget,
36
+ setting_name,
37
+ ),
38
+ )
39
+ self.layout().addLayout(
40
+ qtility.widgets.addLabel(
41
+ widget,
42
+ string.capwords(setting_name.replace('_', ' ')),
43
+ 150,
44
+ slim=False,
45
+ ),
46
+ )
47
+
48
+ # -- Always add in a spacer to push all the widgets up to the top
49
+ self.layout().addSpacerItem(
50
+ QtWidgets.QSpacerItem(
51
+ 10,
52
+ 0,
53
+ QtWidgets.QSizePolicy.Expanding,
54
+ QtWidgets.QSizePolicy.Expanding,
55
+ ),
56
+ )
57
+
58
+ # ----------------------------------------------------------------------------------
59
+ def store_setting_change(self, widget, option_name, *args, **kwargs):
60
+ self.app_config.store_setting(
61
+ option_name,
62
+ qtility.derive.value(widget),
63
+ )
64
+
65
+
66
+ # --------------------------------------------------------------------------------------
67
+ class SettingsWindow(QtWidgets.QMainWindow):
68
+
69
+ def __init__(self, app_config, parent=None):
70
+ super().__init__(parent=parent)
71
+
72
+ self.setWindowTitle("Aniseed Preferences")
73
+ self.setWindowIcon(
74
+ QtGui.QIcon(
75
+ resources.get("icon.png")
76
+ )
77
+ )
78
+ self.setCentralWidget(
79
+ SettingsWidget(
80
+ app_config=app_config,
81
+ parent=parent,
82
+ ),
83
+ )
84
+
85
+
86
+ # --------------------------------------------------------------------------------------
87
+ def show_settings(app_config):
88
+ window = SettingsWindow(app_config, parent=qtility.windows.application())
89
+ window.show()
xstack/app/tree.py ADDED
@@ -0,0 +1,582 @@
1
+ import typing
2
+ import logging
3
+ import qtility
4
+ from Qt import QtWidgets, QtCore, QtGui
5
+
6
+ from . import dialogs
7
+ from . import delegate
8
+ from . import menu
9
+
10
+ log = logging.getLogger(__name__)
11
+
12
+
13
+ # --------------------------------------------------------------------------------------
14
+ # noinspection PyUnresolvedReferences,PyPep8Naming
15
+ class BuildTreeWidget(QtWidgets.QTreeWidget):
16
+ """
17
+ The tree view is the heart of the stacking tool - exposing the build order to the
18
+ user and allowing the user to add, remove and move components.
19
+ """
20
+ is_updated = QtCore.Signal()
21
+
22
+ # -- The context menu class. Subclasses can replace it to tailor the menu
23
+ menu_class = menu.TreeMenu
24
+
25
+ # ----------------------------------------------------------------------------------
26
+ def __init__(self, stack: "xstack.Stack", app_config, app: QtWidgets.QWidget = None):
27
+ super().__init__(parent=app)
28
+
29
+ self.app = app
30
+ self.app_config = app_config
31
+ self.add_component_window = None
32
+ self.switch_component_window = None
33
+ self.allow_interaction = True
34
+
35
+ # -- Declare the settings to allow us to correctly handle drag and
36
+ # -- drop events. A read only structure cannot be re-ordered.
37
+ if self.app_config.read_only_structure:
38
+ self.setAcceptDrops(False)
39
+ self.setDragEnabled(False)
40
+ self.setDragDropMode(QtWidgets.QAbstractItemView.NoDragDrop)
41
+
42
+ else:
43
+ self.setAcceptDrops(True)
44
+ self.setDragEnabled(True)
45
+ self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
46
+
47
+ # -- Ensure we dont sort, as the order of the items is specifically
48
+ # -- important
49
+ self.setSortingEnabled(False)
50
+
51
+ # -- We turn on mouse tracking so we can deal with hover events
52
+ self.setMouseTracking(True)
53
+
54
+ # -- We're not using columns, so we dont need a header
55
+ self.setHeaderHidden(True)
56
+
57
+ # -- Double clicking an item renames it, so we dont want it to
58
+ # -- also expand/collapse the item
59
+ self.setExpandsOnDoubleClick(False)
60
+
61
+ # -- We use a custom delegate to draw our items to allow us complete
62
+ # -- control over how our items are visualised.
63
+ self.setItemDelegateForColumn(
64
+ 0,
65
+ delegate.ComponentItemDelegate(stack, self.app_config),
66
+ )
67
+
68
+ # -- Store a reference to the stack
69
+ self.stack: "xstack.Stack" = stack
70
+
71
+ # -- Store a reference to the root item
72
+ self._root_item = None
73
+ #
74
+ # # -- This is where we store a mapping of uuid's to widgetitems
75
+ # self._item_lookup = dict()
76
+
77
+ # -- Tracker for if we're building
78
+ self.is_building = False
79
+
80
+ if self.app_config.stack_background:
81
+
82
+ path = self.app_config.stack_background.replace("\\", "/")
83
+
84
+ self.setStyleSheet(
85
+ (
86
+ "QTreeView {"
87
+ f"background-image: url({path});"
88
+ "background-position: center;"
89
+ "background-repeat: no-repeat;"
90
+ "}"
91
+ ),
92
+ )
93
+
94
+ # -- Now we're done, lets populate the tree
95
+ self.populate()
96
+
97
+ self.stack.hierarchy_changed.connect(self.populate)
98
+ self.stack.component_added.connect(self.populate)
99
+ self.stack.component_removed.connect(self.populate)
100
+ self.app.build_started.connect(self.disable_interaction)
101
+ self.app.build_complete.connect(self.enable_interaction)
102
+ self.stack.build_progressed.connect(self.on_build_updated)
103
+ self.itemDoubleClicked.connect(self.on_item_double_clicked)
104
+
105
+ # ----------------------------------------------------------------------------------
106
+ def describe(self):
107
+ for component in self.stack.components():
108
+ component.describe()
109
+
110
+ # ----------------------------------------------------------------------------------
111
+ def disable_interaction(self):
112
+ self.allow_interaction = False
113
+
114
+ def enable_interaction(self):
115
+ self.allow_interaction = True
116
+
117
+ def on_build_updated(self, *args, **kwargs):
118
+ self.viewport().update()
119
+
120
+ # ----------------------------------------------------------------------------------
121
+ def populate(self, *args, remember_collapse_state: bool = True, **kwargs):
122
+ """
123
+ This will clear out the tree and rebuild it. The current component (if any)
124
+ is selected again once the tree has been rebuilt.
125
+
126
+ Args:
127
+ remember_collapse_state: If True, any component items which were collapsed
128
+ before the rebuild are collapsed again afterwards. New items are
129
+ always expanded.
130
+ """
131
+ # -- Remember what was selected so we can restore it after the rebuild
132
+ current_component = self.current_component()
133
+
134
+ # -- Remember which items were collapsed, as re-ordering or adding components
135
+ # -- triggers a rebuild and we do not want to lose the users layout
136
+ collapsed_uuids = set()
137
+
138
+ if remember_collapse_state:
139
+ collapsed_uuids = self._collapsed_component_uuids()
140
+
141
+ # -- Clear the current entries
142
+ self.clear()
143
+
144
+ # -- If we do not have a stack then there is nothing else we need
145
+ # -- to do
146
+ if not self.stack:
147
+ return
148
+
149
+ label = self.app_config.header_label or self.app_config.label
150
+
151
+ # -- Declare the root item
152
+ if self.app_config.show_tree_header:
153
+ self._root_item = QtWidgets.QTreeWidgetItem(
154
+ [label],
155
+ )
156
+ else:
157
+ self._root_item = self.invisibleRootItem()
158
+
159
+ self.insertTopLevelItems(0, [self._root_item])
160
+
161
+ for root_component in self.stack.root_components:
162
+ root_item = self._create_item(root_component)
163
+ self._root_item.addChild(root_item)
164
+ self.generate_child_items(root_item)
165
+ root_item.setExpanded(True)
166
+ self._root_item.setExpanded(True)
167
+
168
+ # -- Restore the collapse state of any items which existed before the rebuild
169
+ for item in self._all_items():
170
+ item_component = getattr(item, "component", None)
171
+
172
+ if item_component and item_component.uuid() in collapsed_uuids:
173
+ item.setExpanded(False)
174
+
175
+ if current_component:
176
+ self.select_component(current_component)
177
+
178
+ # ----------------------------------------------------------------------------------
179
+ def select_component(self, component: "xstack.Component"):
180
+ """
181
+ Makes the item representing the given component the current item
182
+ """
183
+ if not component:
184
+ return
185
+
186
+ for item in self._all_items():
187
+ item_component = getattr(item, "component", None)
188
+
189
+ if item_component and item_component.uuid() == component.uuid():
190
+ self.setCurrentItem(item)
191
+ self.scrollToItem(item)
192
+ return
193
+
194
+ # ----------------------------------------------------------------------------------
195
+ def _all_items(self) -> list:
196
+ """
197
+ Returns every item in the tree, breadth first.
198
+
199
+ We walk the items directly rather than using a QTreeWidgetItemIterator,
200
+ as PySide can leave an iterator registered with the tree after we are
201
+ done with it, and Qt then crashes updating it when items are moved
202
+ """
203
+ all_items = list()
204
+
205
+ items = [
206
+ self.topLevelItem(i)
207
+ for i in range(self.topLevelItemCount())
208
+ ]
209
+
210
+ while items:
211
+ item = items.pop(0)
212
+ all_items.append(item)
213
+
214
+ items.extend(
215
+ item.child(i)
216
+ for i in range(item.childCount())
217
+ )
218
+
219
+ return all_items
220
+
221
+ # ----------------------------------------------------------------------------------
222
+ def _collapsed_component_uuids(self) -> set:
223
+ """
224
+ Returns the uuids of all the components whose items are currently collapsed
225
+ """
226
+ return {
227
+ item.component.uuid()
228
+ for item in self._all_items()
229
+ if getattr(item, "component", None) and not item.isExpanded()
230
+ }
231
+
232
+ def generate_child_items(self, item):
233
+ for child_component in item.component.children:
234
+ child_item = self._create_item(child_component)
235
+ item.addChild(child_item)
236
+ self.generate_child_items(child_item)
237
+ item.setExpanded(True)
238
+
239
+ # ----------------------------------------------------------------------------------
240
+ def current_component(self) -> typing.Optional["xstack.Component"]:
241
+ """
242
+ Returns the component for the currently active item
243
+ """
244
+ selected_item = self.currentItem()
245
+
246
+ if not selected_item:
247
+ return None
248
+
249
+ if not hasattr(selected_item, "component"):
250
+ return None
251
+
252
+ return selected_item.component
253
+
254
+ # ----------------------------------------------------------------------------------
255
+ @classmethod
256
+ def _create_item(cls, component: "xstack.Component") -> QtWidgets.QTreeWidgetItem:
257
+ """
258
+ This is a convenience function for create a consistent item in the tree view
259
+ """
260
+
261
+ if not component:
262
+ return None
263
+
264
+ # -- Build the item
265
+ item = QtWidgets.QTreeWidgetItem(
266
+ [f"{component.label()} ({component.identifier})"],
267
+ )
268
+ item.component = component
269
+
270
+ # -- If we have an icon, apply it
271
+ if component.icon:
272
+ item.setIcon(0, QtGui.QIcon(component.icon))
273
+
274
+ item.setData(
275
+ 0,
276
+ QtCore.Qt.DisplayRole,
277
+ component.uuid(),
278
+ )
279
+
280
+ return item
281
+
282
+ # ----------------------------------------------------------------------------------
283
+ def dropEvent(self, event: QtCore.QEvent):
284
+ """
285
+ Triggered on a drop event, this is where we check if we want to accept it and
286
+ allow the item to be reparented.
287
+ """
288
+ # -- We only want to allow events from within ourselves, and never
289
+ # -- when the structure is read only
290
+ if not isinstance(event.source(), self.__class__) or self.app_config.read_only_structure:
291
+ event.ignore()
292
+ return
293
+
294
+ # -- Get the item that is dropped, and the item its being dropped on to
295
+ item_being_dropped = self.currentItem()
296
+
297
+ super().dropEvent(event)
298
+
299
+ new_parent_item = item_being_dropped.parent()
300
+
301
+ # -- Get the corresponding components for these
302
+ child_component = item_being_dropped.component
303
+
304
+ if hasattr(new_parent_item, "component"):
305
+ parent_component = new_parent_item.component
306
+
307
+ else:
308
+ parent_component = None
309
+
310
+ if parent_component:
311
+ index = new_parent_item.indexOfChild(item_being_dropped)
312
+
313
+ else:
314
+ index = None
315
+
316
+ child_component.set_parent(parent_component, child_index=index)
317
+ self.populate()
318
+
319
+ # ----------------------------------------------------------------------------------
320
+ def mousePressEvent(self, event: QtCore.QEvent):
321
+ """
322
+ Tstackgered when a mouse is clicked in the view. This allows the users to edit
323
+ and manipulate the components
324
+ """
325
+ super().mousePressEvent(event)
326
+
327
+ if not self.allow_interaction:
328
+ return
329
+ if event.button() != QtCore.Qt.RightButton:
330
+ return
331
+
332
+ selected_item = self.itemAt(event.pos())
333
+
334
+ context_menu = self.menu_class(
335
+ item=selected_item,
336
+ app_config=self.app_config,
337
+ app=self.app,
338
+ parent=self,
339
+ )
340
+
341
+ # -- An app may leave nothing to offer, such as on empty space when
342
+ # -- the structure is read only
343
+ if context_menu.isEmpty():
344
+ return
345
+
346
+ if hasattr(context_menu, "exec_"):
347
+ context_menu.exec_(QtGui.QCursor().pos())
348
+ else:
349
+ context_menu.exec(QtGui.QCursor().pos())
350
+
351
+ # ----------------------------------------------------------------------------------
352
+ def save_component_settings(self, item):
353
+
354
+ component = item.component
355
+
356
+ filepath = qtility.request.filepath(
357
+ title="Save Config Settings",
358
+ filter_="*.json (*.json)",
359
+ save=True,
360
+ )
361
+
362
+ if not filepath:
363
+ return
364
+
365
+ component.save_settings(filepath)
366
+
367
+ # ----------------------------------------------------------------------------------
368
+ def load_component_settings(self, item):
369
+
370
+ component = item.component
371
+
372
+ filepath = qtility.request.filepath(
373
+ title="Load Config Settings",
374
+ filter_="*.json (*.json)",
375
+ save=False,
376
+ )
377
+
378
+ if not filepath:
379
+ return
380
+
381
+ component.load_settings(filepath=filepath)
382
+
383
+ # ----------------------------------------------------------------------------------
384
+ def import_subtree(self, item):
385
+ """
386
+ Load a JSON file and add its contents as children of the
387
+ right-clicked component. Regenerates UUIDs on load.
388
+ """
389
+ component = item.component
390
+
391
+ filepath = qtility.request.filepath(
392
+ title="Import as Children",
393
+ filter_="*.json (*.json)",
394
+ save=False,
395
+ )
396
+
397
+ if not filepath:
398
+ return
399
+
400
+ component.import_subtree(filepath=filepath)
401
+
402
+ # ----------------------------------------------------------------------------------
403
+ def toggle_enable(self, item):
404
+ component = item.component
405
+ component.set_enabled(not component.is_enabled())
406
+
407
+ # ----------------------------------------------------------------------------------
408
+ def duplicate_component(self, item):
409
+
410
+ component = item.component
411
+
412
+ dialog = dialogs.DuplicateComponentDialog(
413
+ component=component,
414
+ app_config=self.app_config,
415
+ parent=self,
416
+ )
417
+
418
+ result = dialog.exec_() if hasattr(dialog, "exec_") else dialog.exec()
419
+
420
+ if not result:
421
+ return
422
+
423
+ # -- Only search and replace when a search was given. An empty
424
+ # -- replace is allowed, and removes the matched text.
425
+ search_for = dialog.search_for() or None
426
+ replace_with = dialog.replace_with() if search_for else None
427
+
428
+ new_component = component.duplicate(
429
+ search_for=search_for,
430
+ replace_with=replace_with,
431
+ )
432
+
433
+ if not new_component:
434
+ return
435
+
436
+ # -- An explicitly entered name takes priority over the label the
437
+ # -- search and replace produced
438
+ if dialog.label() and dialog.label() != component.label():
439
+ new_component.set_label(dialog.label())
440
+
441
+ self.populate()
442
+
443
+ # -- Select the duplicate so the editor shows its inputs, options and outputs
444
+ self.select_component(new_component)
445
+
446
+ # ----------------------------------------------------------------------------------
447
+ def search_and_replace_component(self, item):
448
+
449
+ search_for = qtility.request.text(
450
+ title="Search For",
451
+ message=(
452
+ "Give the text you want to search for. Note that this will be converted "
453
+ "to a regular expression."
454
+ ),
455
+ text="",
456
+ )
457
+
458
+ if not search_for:
459
+ return None
460
+
461
+ replace_with = qtility.request.text(
462
+ title="Replace With",
463
+ message=(
464
+ "Give the text you want to replace with."
465
+ ),
466
+ text="",
467
+ )
468
+
469
+ if not replace_with:
470
+ return None
471
+
472
+ item.component.search_and_replace(
473
+ search_for=search_for,
474
+ replace_with=replace_with,
475
+ )
476
+
477
+ # ----------------------------------------------------------------------------------
478
+ def help_for_component(self, item):
479
+ item.component.help()
480
+
481
+ # ----------------------------------------------------------------------------------
482
+ @staticmethod
483
+ def _run_user_function(func):
484
+
485
+ # -- At this point, we're executing third party code, so we
486
+ # -- wrap this in a broad exception
487
+ # noinspection PyBroadException
488
+ try:
489
+ return func()
490
+
491
+ except Exception:
492
+ log.exception(f"Function failed to execute : {func}")
493
+
494
+ # ----------------------------------------------------------------------------------
495
+ def remove_component(self, item: QtWidgets.QListWidgetItem):
496
+ """
497
+ Removes a component from the stack
498
+ """
499
+ # -- Get the component
500
+ component = item.component
501
+
502
+ confirmation = qtility.request.confirmation(
503
+ title=f"Remove {self.app_config.component_label}",
504
+ message=f"Are you sure you want to remove {component.label()}",
505
+ parent=self,
506
+ )
507
+
508
+ if not confirmation:
509
+ return
510
+
511
+ # -- Remove the reference to it
512
+ item.component = None
513
+ self.stack.remove_component(component)
514
+
515
+ # -- Removing the component repopulates the tree, which may already
516
+ # -- have deleted this item
517
+ try:
518
+ item.parent().removeChild(item)
519
+
520
+ except RuntimeError:
521
+ pass
522
+
523
+ # ----------------------------------------------------------------------------------
524
+ def add_component(self, parent):
525
+ """
526
+ Adds the component with the given uuid to the stack
527
+ """
528
+ self.add_component_window = dialogs.AddComponentWidget(
529
+ stack=self.stack,
530
+ component_parent=parent,
531
+ app_config=self.app_config,
532
+ parent=self,
533
+ )
534
+ self.add_component_window.component_added.connect(self.populate)
535
+ self.add_component_window.show()
536
+
537
+ # ----------------------------------------------------------------------------------
538
+ def on_item_double_clicked(self, item: QtWidgets.QTreeWidgetItem, column: int):
539
+ """
540
+ Double clicking a component item starts the rename flow, unless the
541
+ structure is read only. Subclasses can re-implement this to give double
542
+ clicking another meaning.
543
+ """
544
+ if not self.allow_interaction:
545
+ return
546
+
547
+ if not getattr(item, "component", None):
548
+ return
549
+
550
+ if self.app_config.read_only_structure:
551
+ return
552
+
553
+ self.rename_component(item)
554
+
555
+ # ----------------------------------------------------------------------------------
556
+ def rename_component(self, item: QtWidgets.QListWidgetItem):
557
+
558
+ component = item.component
559
+
560
+ label = qtility.request.text(
561
+ title=f"New {self.app_config.component_label} Label",
562
+ message=f"Please provide a new label for this {self.app_config.component_label}",
563
+ text=component.label(),
564
+ parent=self
565
+ )
566
+
567
+ if not label or label == component.label():
568
+ return
569
+
570
+ component.set_label(label)
571
+
572
+ self.populate()
573
+
574
+ def switch_component_type(self, item: QtWidgets.QListWidgetItem):
575
+
576
+ self.switch_component_window = dialogs.SwitchComponentTypeDialog(
577
+ component=item.component,
578
+ app_config=self.app_config,
579
+ parent=self,
580
+ )
581
+ self.switch_component_window.component_switched.connect(self.populate)
582
+ self.switch_component_window.show()