Skip to content

process_monitor

Process Monitor UI for launched processes.

CatchTime

Context manager to measure execution time.

Source code in client/ayon_applications/ui/process_monitor.py
 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
class CatchTime:
    """Context manager to measure execution time."""
    def __enter__(self):
        """Start timing.

        Returns:
            CatchTime: self, with start time initialized.

        """
        self.start = perf_counter()
        return self

    def __exit__(
            self,
            type_: Optional[type[BaseException]],
            value: Optional[BaseException],
            traceback: Optional[TracebackType],
    ) -> Optional[bool]:
        """Stop timing and store elapsed time.

        Returns:
            Optional[bool]: None

        """
        self.time = perf_counter() - self.start
        self.readout = f"Time: {self.time:.3f} seconds"
        return None

__enter__()

Start timing.

Returns:

Name Type Description
CatchTime

self, with start time initialized.

Source code in client/ayon_applications/ui/process_monitor.py
 95
 96
 97
 98
 99
100
101
102
103
def __enter__(self):
    """Start timing.

    Returns:
        CatchTime: self, with start time initialized.

    """
    self.start = perf_counter()
    return self

__exit__(type_, value, traceback)

Stop timing and store elapsed time.

Returns:

Type Description
Optional[bool]

Optional[bool]: None

Source code in client/ayon_applications/ui/process_monitor.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def __exit__(
        self,
        type_: Optional[type[BaseException]],
        value: Optional[BaseException],
        traceback: Optional[TracebackType],
) -> Optional[bool]:
    """Stop timing and store elapsed time.

    Returns:
        Optional[bool]: None

    """
    self.time = perf_counter() - self.start
    self.readout = f"Time: {self.time:.3f} seconds"
    return None

CleanupWorker

Bases: QRunnable

Worker thread for cleanup operations.

Source code in client/ayon_applications/ui/process_monitor.py
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
class CleanupWorker(QRunnable):
    """Worker thread for cleanup operations."""

    def __init__(self,
                 manager: ProcessManager,
                 cleanup_type: str,
                 process_hash: Optional[str] = None) -> None:
        """Initialize the worker.

        Args:
            manager (ApplicationManager): Application manager instance.
            cleanup_type (str): Type of cleanup ("inactive" or "single").
            process_hash (Optional[str]): Hash of the process to delete
                if cleanup_type is "single".

        """
        super().__init__()
        self.signals = CleanupWorkerSignals()
        self.signature = f"{self.__class__.__name__} ({cleanup_type})"
        self._manager = manager
        self._cleanup_type = cleanup_type  # "inactive" or "single"
        self._process_hash = process_hash
        self._log = getLogger(self.signature)

    @Slot()
    def run(self) -> None:
        """Perform cleanup in background thread."""
        self._log.debug(
            "Starting cleanup of type: %s", self._cleanup_type)
        try:
            if self._cleanup_type == "inactive":
                self._cleanup_inactive()
            elif self._cleanup_type == "single":
                self._remove_selected()
        except Exception as e:  # noqa: BLE001
            self.signals.error.emit(str(e))

    def _cleanup_inactive(self) -> None:
        """Clean up inactive processes."""
        deleted_count = self._manager.delete_inactive_processes()
        self.signals.finished.emit(deleted_count)

    def _remove_selected(self) -> None:
        """Remove a single selected process."""
        if not self._process_hash:
            self.signals.error.emit("No process hash provided")
            return

        self._manager.delete_process_info(self._process_hash)
        self.signals.finished.emit(1)

__init__(manager, cleanup_type, process_hash=None)

Initialize the worker.

Parameters:

Name Type Description Default
manager ApplicationManager

Application manager instance.

required
cleanup_type str

Type of cleanup ("inactive" or "single").

required
process_hash Optional[str]

Hash of the process to delete if cleanup_type is "single".

None
Source code in client/ayon_applications/ui/process_monitor.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def __init__(self,
             manager: ProcessManager,
             cleanup_type: str,
             process_hash: Optional[str] = None) -> None:
    """Initialize the worker.

    Args:
        manager (ApplicationManager): Application manager instance.
        cleanup_type (str): Type of cleanup ("inactive" or "single").
        process_hash (Optional[str]): Hash of the process to delete
            if cleanup_type is "single".

    """
    super().__init__()
    self.signals = CleanupWorkerSignals()
    self.signature = f"{self.__class__.__name__} ({cleanup_type})"
    self._manager = manager
    self._cleanup_type = cleanup_type  # "inactive" or "single"
    self._process_hash = process_hash
    self._log = getLogger(self.signature)

run()

Perform cleanup in background thread.

Source code in client/ayon_applications/ui/process_monitor.py
271
272
273
274
275
276
277
278
279
280
281
282
@Slot()
def run(self) -> None:
    """Perform cleanup in background thread."""
    self._log.debug(
        "Starting cleanup of type: %s", self._cleanup_type)
    try:
        if self._cleanup_type == "inactive":
            self._cleanup_inactive()
        elif self._cleanup_type == "single":
            self._remove_selected()
    except Exception as e:  # noqa: BLE001
        self.signals.error.emit(str(e))

CleanupWorkerSignals

Bases: QObject

Signals for CleanupWorker.

Signals can be defined only in classes derived from QObject.

Source code in client/ayon_applications/ui/process_monitor.py
237
238
239
240
241
242
243
244
class CleanupWorkerSignals(QtCore.QObject):
    """Signals for CleanupWorker.

    Signals can be defined only in classes derived from QObject.
    """
    # Emits (deleted_processes, deleted_files)
    finished = QtCore.Signal(int)
    error = QtCore.Signal(str)

FileChangeWatcher

Bases: QObject

Qt-based file watcher with rotation handling and debounce.

Source code in client/ayon_applications/ui/process_monitor.py
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
class FileChangeWatcher(QtCore.QObject):
    """Qt-based file watcher with rotation handling and debounce."""
    changed = QtCore.Signal(object)  # emits Path (as object)

    def __init__(self, parent=None, debounce_ms: int = 150) -> None:
        super().__init__(parent)
        self._watcher = QtCore.QFileSystemWatcher(self)
        self._target: Optional[Path] = None

        # debounce timer to coalesce bursts of events
        # QFileSystemWatcher can emit multiple events for a single change
        self._debounce = QtCore.QTimer(self)
        self._debounce.setSingleShot(True)
        self._debounce.setInterval(debounce_ms)
        self._debounce.timeout.connect(self._emit_changed)

        self._watcher.fileChanged.connect(self._on_any_change)
        self._watcher.directoryChanged.connect(self._on_any_change)

    def set_target(self, file_path: Optional[Path]) -> None:
        """Start watching given file and its parent directory."""
        self.stop()
        self._target = file_path
        if not file_path:
            return

        # Clear watched paths
        for path in self._watcher.files():
            with contextlib.suppress(Exception):
                self._watcher.removePath(path)

        # Watch the file (if present)
        with contextlib.suppress(Exception):
            self._watcher.files()
            self._watcher.addPath(str(file_path))

    def stop(self) -> None:
        """Stop watching."""
        self._debounce.stop()
        files = self._watcher.files()
        if files:
            self._watcher.removePaths(files)
        dirs = self._watcher.directories()
        if dirs:
            self._watcher.removePaths(dirs)

    @QtCore.Slot(str)
    def _on_any_change(self, _path: str) -> None:
        """Handle file changes."""
        if not self._target:
            return
        # Debounce bursts of events.
        self._debounce.start()

    def _emit_changed(self) -> None:
        if self._target:
            self.changed.emit(self._target)

set_target(file_path)

Start watching given file and its parent directory.

Source code in client/ayon_applications/ui/process_monitor.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def set_target(self, file_path: Optional[Path]) -> None:
    """Start watching given file and its parent directory."""
    self.stop()
    self._target = file_path
    if not file_path:
        return

    # Clear watched paths
    for path in self._watcher.files():
        with contextlib.suppress(Exception):
            self._watcher.removePath(path)

    # Watch the file (if present)
    with contextlib.suppress(Exception):
        self._watcher.files()
        self._watcher.addPath(str(file_path))

stop()

Stop watching.

Source code in client/ayon_applications/ui/process_monitor.py
70
71
72
73
74
75
76
77
78
def stop(self) -> None:
    """Stop watching."""
    self._debounce.stop()
    files = self._watcher.files()
    if files:
        self._watcher.removePaths(files)
    dirs = self._watcher.directories()
    if dirs:
        self._watcher.removePaths(dirs)

FileContentWorker

Bases: QRunnable

Worker thread for loading file content.

Source code in client/ayon_applications/ui/process_monitor.py
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
class FileContentWorker(QRunnable):
    """Worker thread for loading file content."""

    def __init__(self, file_path: Path):
        """Initialize the worker.

        Args:
            file_path (Path): Path to the file to load.

        """
        super().__init__()
        self.signals = FileContentWorkerSignals()
        self.signature = self.__class__.__name__
        self._file_path = file_path
        self._log = getLogger(self.signature)

    @Slot()
    def run(self) -> None:
        """Load file content in background thread."""
        self._log.debug("Loading file content from %s", self._file_path)
        try:
            if not self._file_path or not Path(self._file_path).exists():
                self.signals.finished.emit("Output file not found")
                return

            content = Path(self._file_path).read_text(
                encoding="utf-8", errors="replace")
            self.signals.finished.emit(content)
        except Exception as e:  # noqa: BLE001
            self.signals.error.emit(f"Error reading file: {e}")

__init__(file_path)

Initialize the worker.

Parameters:

Name Type Description Default
file_path Path

Path to the file to load.

required
Source code in client/ayon_applications/ui/process_monitor.py
208
209
210
211
212
213
214
215
216
217
218
219
def __init__(self, file_path: Path):
    """Initialize the worker.

    Args:
        file_path (Path): Path to the file to load.

    """
    super().__init__()
    self.signals = FileContentWorkerSignals()
    self.signature = self.__class__.__name__
    self._file_path = file_path
    self._log = getLogger(self.signature)

run()

Load file content in background thread.

Source code in client/ayon_applications/ui/process_monitor.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
@Slot()
def run(self) -> None:
    """Load file content in background thread."""
    self._log.debug("Loading file content from %s", self._file_path)
    try:
        if not self._file_path or not Path(self._file_path).exists():
            self.signals.finished.emit("Output file not found")
            return

        content = Path(self._file_path).read_text(
            encoding="utf-8", errors="replace")
        self.signals.finished.emit(content)
    except Exception as e:  # noqa: BLE001
        self.signals.error.emit(f"Error reading file: {e}")

FileContentWorkerSignals

Bases: QObject

Signals for FileContentWorker.

Signals can be defined only in classes derived from QObject.

Source code in client/ayon_applications/ui/process_monitor.py
196
197
198
199
200
201
202
class FileContentWorkerSignals(QtCore.QObject):
    """Signals for FileContentWorker.

    Signals can be defined only in classes derived from QObject.
    """
    finished = QtCore.Signal(str)  # Emits file content
    error = QtCore.Signal(str)

ProcessDescendantsUpdateWorker

Bases: QRunnable

Worker thread for updating process descendants.

Source code in client/ayon_applications/ui/process_monitor.py
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
class ProcessDescendantsUpdateWorker(QRunnable):
    """Worker thread for updating process descendants."""

    def __init__(
            self,
            manager: ProcessManager,
            parent_pid: int,
            parent_hash: str):
        """Initialize the worker."""
        super().__init__()
        self.signals = ProcessDescendantsUpdateWorkerSignals()
        self.signature = self.__class__.__name__
        self._manager = manager
        self._parent_pid = parent_pid
        self._parent_hash = parent_hash
        self._log = getLogger(self.signature)

    @Slot()
    def run(self) -> None:
        """Update process descendants data in background thread."""
        with CatchTime() as timer:
            try:
                descendants = self._manager.get_descendant_processes_by_pid(
                    self._parent_pid)
                self.signals.finished.emit(self._parent_hash, descendants)
            except Exception as e:  # noqa: BLE001
                self.signals.error.emit(str(e))
        self._log.debug(
            "Descendants update from db completed in %s", timer.readout)

__init__(manager, parent_pid, parent_hash)

Initialize the worker.

Source code in client/ayon_applications/ui/process_monitor.py
135
136
137
138
139
140
141
142
143
144
145
146
147
def __init__(
        self,
        manager: ProcessManager,
        parent_pid: int,
        parent_hash: str):
    """Initialize the worker."""
    super().__init__()
    self.signals = ProcessDescendantsUpdateWorkerSignals()
    self.signature = self.__class__.__name__
    self._manager = manager
    self._parent_pid = parent_pid
    self._parent_hash = parent_hash
    self._log = getLogger(self.signature)

run()

Update process descendants data in background thread.

Source code in client/ayon_applications/ui/process_monitor.py
149
150
151
152
153
154
155
156
157
158
159
160
@Slot()
def run(self) -> None:
    """Update process descendants data in background thread."""
    with CatchTime() as timer:
        try:
            descendants = self._manager.get_descendant_processes_by_pid(
                self._parent_pid)
            self.signals.finished.emit(self._parent_hash, descendants)
        except Exception as e:  # noqa: BLE001
            self.signals.error.emit(str(e))
    self._log.debug(
        "Descendants update from db completed in %s", timer.readout)

ProcessDescendantsUpdateWorkerSignals

Bases: QObject

Signals for ProcessDescendantsUpdateWorker.

Signals can be defined only in classes derived from QObject.

Source code in client/ayon_applications/ui/process_monitor.py
122
123
124
125
126
127
128
129
class ProcessDescendantsUpdateWorkerSignals(QtCore.QObject):
    """Signals for ProcessDescendantsUpdateWorker.

    Signals can be defined only in classes derived from QObject.
    """
    # Emits (parent_hash, list[ProcessInfo])
    finished = QtCore.Signal(object, list)
    error = QtCore.Signal(str)

ProcessMonitorController

Bases: QObject

Controller that encapsulates data logic for ProcessMonitorWindow.

Handles ApplicationManager, QThreadPool, and QTimers.

Source code in client/ayon_applications/ui/process_monitor.py
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
class ProcessMonitorController(QtCore.QObject):
    """Controller that encapsulates data logic for ProcessMonitorWindow.

    Handles ApplicationManager, QThreadPool, and QTimers.

    """
    processes_refreshed = QtCore.Signal(list)
    file_content = QtCore.Signal(str)
    cleanup_finished = QtCore.Signal(int)
    error = QtCore.Signal(str)
    # New: descendants refreshed signal (parent_hash, descendants)
    descendants_refreshed = QtCore.Signal(object, list)

    def __init__(self, parent: Optional[QtCore.QObject] = None):
        """Initialize the controller."""
        super().__init__(parent)
        self.manager = ProcessManager()
        self._thread_pool = QThreadPool()
        self._file_watcher = FileChangeWatcher(self)
        self._file_watcher.changed.connect(self._on_file_changed)

        # Timers (created once)
        self._refresh_timer = QtCore.QTimer(self)
        self._refresh_timer.timeout.connect(self.refresh)
        self._refresh_timer.setInterval(5000)

        self._file_reload_timer = QtCore.QTimer(self)
        self._file_reload_timer.timeout.connect(self._on_file_reload_timeout)
        self._file_reload_timer.setSingleShot(False)
        self._file_reload_interval = 2000
        self._file_reload_target: Optional[Path] = None

    # Timer control
    def start_timers(self) -> None:
        """Start the refresh timer if not already active."""
        if not self._refresh_timer.isActive():
            self._refresh_timer.start()

    def stop_timers(self) -> None:
        """Stop all active timers."""
        if self._refresh_timer.isActive():
            self._refresh_timer.stop()
        if self._file_reload_timer.isActive():
            self._file_reload_timer.stop()

    # Refresh
    def refresh(self) -> None:
        """Refresh process data in background thread."""
        try:
            worker = ProcessRefreshWorker(self.manager)
            worker.signals.finished.connect(self._on_refresh_finished)
            worker.signals.error.connect(self._on_error)
            self._thread_pool.start(worker)
        except Exception as exc:  # noqa: BLE001
            self.error.emit(str(exc))

    def _on_refresh_finished(self, processes: list[ProcessInfo]) -> None:
        """Handle completion of process refresh.

        Args:
            processes (list[ProcessInfo]): List of refreshed processes.

        """
        self.processes_refreshed.emit(processes)

    def fetch_descendants(self, parent_process: ProcessInfo) -> None:
        """Fetch descendants of a given parent process in background thread.

        Args:
            parent_process (ProcessInfo): Parent process whose descendants
                to fetch.

        """
        if not parent_process.pid or not parent_process.hash:
            return
        try:
            worker = ProcessDescendantsUpdateWorker(
                self.manager, parent_process.pid, parent_process.hash)
            worker.signals.finished.connect(self._on_descendants_finished)
            worker.signals.error.connect(self._on_error)
            self._thread_pool.start(worker)
        except Exception as exc:  # noqa: BLE001
            self.error.emit(str(exc))

    def _on_descendants_finished(
            self,
            parent_hash: object,
            descendants: list[ProcessInfo]) -> None:
        """Handle completion of descendants fetch.

        Args:
            parent_hash (object): Hash of the parent process.
            descendants (list[ProcessInfo]): List of descendant processes.

        """
        # Re-emit to window
        try:
            self.descendants_refreshed.emit(str(parent_hash), descendants)
        except Exception as exc:  # noqa: BLE001
            self.error.emit(str(exc))

    def load_file_content(self, file_path: Optional[Path]) -> None:
        """Load file content in background thread.

        Args:
            file_path (Optional[Path]): Path to the file to load.

        """
        if not file_path:
            self.file_content.emit("No output file available")
            return
        try:
            worker = FileContentWorker(file_path)
            worker.signals.finished.connect(self._on_file_content_loaded)
            worker.signals.error.connect(self._on_error)
            self._thread_pool.start(worker)
        except Exception as exc:  # noqa: BLE001
            self.error.emit(str(exc))

    def _on_file_content_loaded(self, content: str) -> None:
        """Handle completion of file content loading."""
        self.file_content.emit(content)

    # Auto-reload control
    def start_file_watch(self, file_path: Path) -> None:
        """Start watching file for instant updates.

        Args:
            file_path (Path): Path to the file to watch.

        """
        self._file_watcher.set_target(file_path)
        # Also load immediately so UI updates without waiting for first event.
        self.load_file_content(file_path)

    def stop_file_watch(self) -> None:
        """Stop watching file."""
        self._file_watcher.stop()

    def start_file_reload(self, file_path: Path, interval: int = 2000) -> None:
        """Start auto-reloading file content at given interval."""
        self._file_reload_target = file_path
        self._file_reload_interval = interval
        self._file_reload_timer.start(self._file_reload_interval)

    def stop_file_reload(self) -> None:
        """Stop auto-reloading file content."""
        self._file_reload_timer.stop()
        self._file_reload_target = None

    def _on_file_reload_timeout(self) -> None:
        """Handle file reload timer timeout."""
        if self._file_reload_target:
            self.load_file_content(self._file_reload_target)

    @QtCore.Slot(object)
    def _on_file_changed(self, file_obj: object) -> None:
        """Instant update on file change."""
        file_path = Path(str(file_obj))
        self.load_file_content(file_path)

    # Cleanup operations
    def clean_inactive(self) -> None:
        """Clean all inactive processes in background thread."""
        try:
            worker = CleanupWorker(self.manager, "inactive")
            worker.signals.finished.connect(self._on_cleanup_finished)
            worker.signals.error.connect(self._on_error)
            self._thread_pool.start(worker)
        except Exception as exc:  # noqa: BLE001
            self.error.emit(str(exc))

    def delete_single(self, process_hash: str) -> None:
        """Delete a single process by its hash in background thread.

        Args:
            process_hash (str): Hash of the process to delete.

        """
        try:
            worker = CleanupWorker(self.manager, "single", process_hash)
            worker.signals.finished.connect(self._on_cleanup_finished)
            worker.signals.error.connect(self._on_error)
            self._thread_pool.start(worker)
        except Exception as exc:  # noqa: BLE001
            self.error.emit(str(exc))

    def _on_cleanup_finished(
            self, deleted_proc: int) -> None:
        """Handle completion of cleanup operation."""
        self.cleanup_finished.emit(deleted_proc)

    def _on_error(self, msg: str) -> None:
        """Handle errors from workers."""
        self.error.emit(msg)

    def shutdown(self) -> None:
        """Shutdown controller.

        Stop timers and wait for workers.

        """
        self.stop_timers()
        with contextlib.suppress(Exception):
            self.stop_file_watch()
        with contextlib.suppress(Exception):
            self._thread_pool.waitForDone()

__init__(parent=None)

Initialize the controller.

Source code in client/ayon_applications/ui/process_monitor.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
def __init__(self, parent: Optional[QtCore.QObject] = None):
    """Initialize the controller."""
    super().__init__(parent)
    self.manager = ProcessManager()
    self._thread_pool = QThreadPool()
    self._file_watcher = FileChangeWatcher(self)
    self._file_watcher.changed.connect(self._on_file_changed)

    # Timers (created once)
    self._refresh_timer = QtCore.QTimer(self)
    self._refresh_timer.timeout.connect(self.refresh)
    self._refresh_timer.setInterval(5000)

    self._file_reload_timer = QtCore.QTimer(self)
    self._file_reload_timer.timeout.connect(self._on_file_reload_timeout)
    self._file_reload_timer.setSingleShot(False)
    self._file_reload_interval = 2000
    self._file_reload_target: Optional[Path] = None

clean_inactive()

Clean all inactive processes in background thread.

Source code in client/ayon_applications/ui/process_monitor.py
864
865
866
867
868
869
870
871
872
def clean_inactive(self) -> None:
    """Clean all inactive processes in background thread."""
    try:
        worker = CleanupWorker(self.manager, "inactive")
        worker.signals.finished.connect(self._on_cleanup_finished)
        worker.signals.error.connect(self._on_error)
        self._thread_pool.start(worker)
    except Exception as exc:  # noqa: BLE001
        self.error.emit(str(exc))

delete_single(process_hash)

Delete a single process by its hash in background thread.

Parameters:

Name Type Description Default
process_hash str

Hash of the process to delete.

required
Source code in client/ayon_applications/ui/process_monitor.py
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def delete_single(self, process_hash: str) -> None:
    """Delete a single process by its hash in background thread.

    Args:
        process_hash (str): Hash of the process to delete.

    """
    try:
        worker = CleanupWorker(self.manager, "single", process_hash)
        worker.signals.finished.connect(self._on_cleanup_finished)
        worker.signals.error.connect(self._on_error)
        self._thread_pool.start(worker)
    except Exception as exc:  # noqa: BLE001
        self.error.emit(str(exc))

fetch_descendants(parent_process)

Fetch descendants of a given parent process in background thread.

Parameters:

Name Type Description Default
parent_process ProcessInfo

Parent process whose descendants to fetch.

required
Source code in client/ayon_applications/ui/process_monitor.py
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
def fetch_descendants(self, parent_process: ProcessInfo) -> None:
    """Fetch descendants of a given parent process in background thread.

    Args:
        parent_process (ProcessInfo): Parent process whose descendants
            to fetch.

    """
    if not parent_process.pid or not parent_process.hash:
        return
    try:
        worker = ProcessDescendantsUpdateWorker(
            self.manager, parent_process.pid, parent_process.hash)
        worker.signals.finished.connect(self._on_descendants_finished)
        worker.signals.error.connect(self._on_error)
        self._thread_pool.start(worker)
    except Exception as exc:  # noqa: BLE001
        self.error.emit(str(exc))

load_file_content(file_path)

Load file content in background thread.

Parameters:

Name Type Description Default
file_path Optional[Path]

Path to the file to load.

required
Source code in client/ayon_applications/ui/process_monitor.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
def load_file_content(self, file_path: Optional[Path]) -> None:
    """Load file content in background thread.

    Args:
        file_path (Optional[Path]): Path to the file to load.

    """
    if not file_path:
        self.file_content.emit("No output file available")
        return
    try:
        worker = FileContentWorker(file_path)
        worker.signals.finished.connect(self._on_file_content_loaded)
        worker.signals.error.connect(self._on_error)
        self._thread_pool.start(worker)
    except Exception as exc:  # noqa: BLE001
        self.error.emit(str(exc))

refresh()

Refresh process data in background thread.

Source code in client/ayon_applications/ui/process_monitor.py
748
749
750
751
752
753
754
755
756
def refresh(self) -> None:
    """Refresh process data in background thread."""
    try:
        worker = ProcessRefreshWorker(self.manager)
        worker.signals.finished.connect(self._on_refresh_finished)
        worker.signals.error.connect(self._on_error)
        self._thread_pool.start(worker)
    except Exception as exc:  # noqa: BLE001
        self.error.emit(str(exc))

shutdown()

Shutdown controller.

Stop timers and wait for workers.

Source code in client/ayon_applications/ui/process_monitor.py
898
899
900
901
902
903
904
905
906
907
908
def shutdown(self) -> None:
    """Shutdown controller.

    Stop timers and wait for workers.

    """
    self.stop_timers()
    with contextlib.suppress(Exception):
        self.stop_file_watch()
    with contextlib.suppress(Exception):
        self._thread_pool.waitForDone()

start_file_reload(file_path, interval=2000)

Start auto-reloading file content at given interval.

Source code in client/ayon_applications/ui/process_monitor.py
841
842
843
844
845
def start_file_reload(self, file_path: Path, interval: int = 2000) -> None:
    """Start auto-reloading file content at given interval."""
    self._file_reload_target = file_path
    self._file_reload_interval = interval
    self._file_reload_timer.start(self._file_reload_interval)

start_file_watch(file_path)

Start watching file for instant updates.

Parameters:

Name Type Description Default
file_path Path

Path to the file to watch.

required
Source code in client/ayon_applications/ui/process_monitor.py
826
827
828
829
830
831
832
833
834
835
def start_file_watch(self, file_path: Path) -> None:
    """Start watching file for instant updates.

    Args:
        file_path (Path): Path to the file to watch.

    """
    self._file_watcher.set_target(file_path)
    # Also load immediately so UI updates without waiting for first event.
    self.load_file_content(file_path)

start_timers()

Start the refresh timer if not already active.

Source code in client/ayon_applications/ui/process_monitor.py
735
736
737
738
def start_timers(self) -> None:
    """Start the refresh timer if not already active."""
    if not self._refresh_timer.isActive():
        self._refresh_timer.start()

stop_file_reload()

Stop auto-reloading file content.

Source code in client/ayon_applications/ui/process_monitor.py
847
848
849
850
def stop_file_reload(self) -> None:
    """Stop auto-reloading file content."""
    self._file_reload_timer.stop()
    self._file_reload_target = None

stop_file_watch()

Stop watching file.

Source code in client/ayon_applications/ui/process_monitor.py
837
838
839
def stop_file_watch(self) -> None:
    """Stop watching file."""
    self._file_watcher.stop()

stop_timers()

Stop all active timers.

Source code in client/ayon_applications/ui/process_monitor.py
740
741
742
743
744
745
def stop_timers(self) -> None:
    """Stop all active timers."""
    if self._refresh_timer.isActive():
        self._refresh_timer.stop()
    if self._file_reload_timer.isActive():
        self._file_reload_timer.stop()

ProcessMonitorWindow

Bases: QDialog

Main window for the Process Monitor application.

Source code in client/ayon_applications/ui/process_monitor.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
class ProcessMonitorWindow(QtWidgets.QDialog):
    """Main window for the Process Monitor application."""
    def __init__(self, parent=None):  # noqa: ANN001
        """Initialize the main window."""
        super().__init__(parent)
        self._log = getLogger(self.__class__.__name__)
        self.setWindowTitle("AYON Process Monitor")
        self.setMinimumSize(1000, 600)

        # Controller instance (owns manager, thread pool, timers)
        self._controller = ProcessMonitorController(self)

        # Connect controller signals to UI slots
        # ANSI to HTML converter
        self._ansi_converter = AnsiToHtmlConverter()

        self._controller.processes_refreshed.connect(
            self._on_processes_refreshed
        )
        self._controller.file_content.connect(self._on_file_content)
        self._controller.cleanup_finished.connect(self._on_cleanup_finished)
        self._controller.error.connect(self._on_error)
        # New: descendants
        self._controller.descendants_refreshed.connect(
            self._on_descendants_refreshed
        )

        self._current_process = None
        self._is_loading = False
        # Track last selection to restore across refreshes (including children)
        self._last_selected_hashes: set[str] = set()

        self._setup_ui()

    def _setup_ui(self) -> None:
        """Set up the user interface."""
        central_widget = self
        main_layout = QtWidgets.QVBoxLayout(central_widget)

        # Toolbar
        toolbar_layout = self._setup_toolbar_ui()

        main_layout.addLayout(toolbar_layout)

        splitter = QtWidgets.QSplitter(QtCore.Qt.Orientation.Vertical)

        # Process tree view
        self._setup_tree_view_ui()

        splitter.addWidget(self._tree_view)

        # Output area
        self._setup_output_ui()

        splitter.addWidget(self._output_widget)

        # Give the tree view slightly more space than the output pane
        splitter.setStretchFactor(0, 3)
        splitter.setStretchFactor(1, 2)

        main_layout.addWidget(splitter, 1)

        # Status bar
        self._status_bar = QtWidgets.QStatusBar()
        self._status_bar.setSizeGripEnabled(False)
        main_layout.addWidget(self._status_bar, 0)
        self._status_bar.showMessage("Ready")

    def _setup_output_ui(self) -> None:
        self._output_widget = QtWidgets.QWidget()
        output_layout = QtWidgets.QVBoxLayout(self._output_widget)

        output_label = QtWidgets.QLabel("Output Content:")
        output_label.setStyleSheet("font-weight: bold; margin-top: 10px;")

        # Use QTextEdit instead of QPlainTextEdit for HTML support
        self._output_text = QtWidgets.QTextEdit()
        self._output_text.setReadOnly(True)
        # Set monospace font for consistent output formatting
        font = QtGui.QFont("Noto Sans Mono, Courier New, monospace")
        font.setPointSize(9)
        self._output_text.setFont(font)
        self._output_text.setPlaceholderText(
            "Double-click a process row to view its output file content...")

        # Auto-reload checkbox
        self._auto_reload_checkbox = QtWidgets.QCheckBox(
            "Auto-reload output for running processes")
        self._auto_reload_checkbox.setChecked(True)
        self._auto_reload_checkbox.toggled.connect(
            self._on_auto_reload_toggled)

        output_layout.addWidget(output_label, 0)
        output_layout.addWidget(self._output_text, 1)
        output_layout.addWidget(self._auto_reload_checkbox, 0)

        # Ensure output widget expands and takes available space
        self._output_widget.setSizePolicy(
            QtWidgets.QSizePolicy.Policy.Expanding,
            QtWidgets.QSizePolicy.Policy.Expanding
        )
        self._output_text.setSizePolicy(
            QtWidgets.QSizePolicy.Policy.Expanding,
            QtWidgets.QSizePolicy.Policy.Expanding
        )

    def _setup_tree_view_ui(self) -> None:
        """Set up the process tree view UI."""
        self._tree_model = ProcessTreeModel(manager=self._controller.manager)
        self._tree_view = QtWidgets.QTreeView()
        self._tree_view.setModel(self._tree_model)
        self._tree_view.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
        self._tree_view.setSortingEnabled(True)
        self._tree_view.doubleClicked.connect(self._on_row_double_clicked)

        header = self._tree_view.header()
        header.setStretchLastSection(True)
        for i in range(len(self._tree_model.headers)):
            header.setSectionResizeMode(
                i, QtWidgets.QHeaderView.ResizeMode.ResizeToContents)

        # Make tree view expand to fill available space
        self._tree_view.setSizePolicy(
            QtWidgets.QSizePolicy.Policy.Expanding,
            QtWidgets.QSizePolicy.Policy.Expanding
        )

    def _setup_toolbar_ui(self) -> QtWidgets.QHBoxLayout:
        """Set up the toolbar UI.

        Returns:
            QtWidgets.QHBoxLayout: The toolbar layout.

        """
        toolbar_layout = QtWidgets.QHBoxLayout()

        self._refresh_btn = QtWidgets.QPushButton("Refresh Process List")
        self._refresh_btn.clicked.connect(self._refresh_data)

        self._clean_inactive_btn = QtWidgets.QPushButton("Clean Inactive")
        self._clean_inactive_btn.setToolTip(
            "Remove all inactive processes from database")
        self._clean_inactive_btn.clicked.connect(
            self._clean_inactive_processes)

        self._clean_selected_btn = QtWidgets.QPushButton("Delete Selected")
        self._clean_selected_btn.setToolTip(
            "Delete selected process from database and its output file")
        self._clean_selected_btn.clicked.connect(
            self._delete_selected_process)

        # Loading indicator
        self._loading_label = QtWidgets.QLabel("Loading...")
        self._loading_label.setVisible(False)

        toolbar_layout.addWidget(self._refresh_btn, 0)
        toolbar_layout.addWidget(self._clean_inactive_btn, 0)
        toolbar_layout.addWidget(self._clean_selected_btn, 0)
        toolbar_layout.addStretch(1)
        toolbar_layout.addWidget(self._loading_label, 0)
        return toolbar_layout

    def _set_loading_state(self, *, loading: bool) -> None:
        """Set the loading state of the UI.

        Args:
            loading (bool): True to show loading state, False to hide.

        """
        self._is_loading = loading
        self._loading_label.setVisible(loading)

        # Disable buttons during loading
        buttons = [
            self._refresh_btn,
            self._clean_inactive_btn,
            self._clean_selected_btn,
        ]
        for btn in buttons:
            btn.setEnabled(not loading)

    def _refresh_data(self) -> None:
        """Refresh the process table data in background thread."""
        self._set_loading_state(loading=True)
        self._controller.refresh()

    def _on_processes_refreshed(self, processes: list[ProcessInfo]) -> None:
        selection_model = self._tree_view.selectionModel()
        selected_hashes: set[str] = set()
        if selection_model.hasSelection():
            for index in selection_model.selectedRows():
                proc = self._tree_model.get_process_at_index(index)
                if proc and proc.hash:
                    selected_hashes.add(proc.hash)
        # remember for later (children restored after descendants load)
        self._last_selected_hashes = selected_hashes

        # Update the model with new processes
        self._tree_model.update_processes(processes)

        # Restore selection for any top-level rows we can now
        indexes_to_select = self._tree_model.find_indexes_by_hashes(
            selected_hashes)
        for idx in indexes_to_select:
            selection_model.select(
                idx,
                (
                    QtCore.QItemSelectionModel.SelectionFlag.Select
                    | QtCore.QItemSelectionModel.SelectionFlag.Rows
                ),
            )

        # Fetch descendants for each process with PID
        for proc in processes:
            if proc.pid:
                self._controller.fetch_descendants(proc)

        self._status_bar.showMessage(f"Loaded {len(processes)} processes")
        self._set_loading_state(loading=False)
        self._log.debug("Process tree updated with new data")

    def _on_descendants_refreshed(
            self,
            parent_hash: object,
            descendants: list[ProcessInfo]) -> None:
        """Handle updated descendants for a parent process.

        Args:
            parent_hash (object): Hash of the parent process.
            descendants (list[ProcessInfo]): List of descendant processes.

        """
        parent_hash_str = str(parent_hash)
        self._tree_model.update_descendants(parent_hash_str, descendants)
        # Expand parent row to show its children
        parent_index = self._tree_model.get_index_by_hash(parent_hash_str)
        if parent_index is not None:
            self._tree_view.setExpanded(parent_index, True)  # noqa: FBT003
        # Try to restore child selection if needed
        if self._last_selected_hashes:
            sel_model = self._tree_view.selectionModel()
            for idx in self._tree_model.find_indexes_by_hashes(
                    self._last_selected_hashes):
                sel_model.select(
                    idx,
                    (
                        QtCore.QItemSelectionModel.SelectionFlag.Select
                        | QtCore.QItemSelectionModel.SelectionFlag.Rows
                    ),
                )

    def _on_error(self, error_msg: str) -> None:
        """Handle refresh error.

        Args:
            error_msg (str): Error message to display.

        """
        self._status_bar.showMessage(f"Error: {error_msg}")
        self._set_loading_state(loading=False)

    def _on_row_double_clicked(self, index: QtCore.QModelIndex) -> None:
        """Handle double-click on a process row to load its output file.

        Args:
            index (QtCore.QModelIndex): Index of the clicked row.

        """
        if not index.isValid() or self._is_loading:
            return
        process = self._tree_model.get_process_at_index(index)
        if not process:
            return
        self._current_process = process
        self._load_output_content()
        if (
            self._auto_reload_checkbox.isChecked()
            and process.pid
            and process.active
        ):
            self._controller.stop_file_reload()
            self._controller.start_file_watch(process.output)
        else:
            self._controller.stop_file_watch()
            self._controller.stop_file_reload()

    def _load_output_content(self) -> None:
        """Load output file content in background thread."""
        if not self._current_process or not self._current_process.output:
            self._output_text.setPlainText("No output file available")
            return

        self._output_text.setPlainText("Loading file content...")

        self._controller.load_file_content(self._current_process.output)

    def _on_file_content(self, content: str) -> None:
        """Handle file content loaded.

        Args:
            content (str): Loaded file content.

        """
        sb = self._output_text.verticalScrollBar()
        # Detect whether user was at bottom before reload
        at_bottom = sb.value() == sb.maximum()
        prev_max = sb.maximum()
        prev_val = sb.value()
        ratio = (prev_val / prev_max) if prev_max > 0 else 1.0

        if not content:
            self._output_text.setPlainText("Output file is empty")
        else:
            html_content = self._ansi_converter.convert(content)
            self._output_text.setHtml(html_content)

        # Restore scroll after layout pass
        def restore_scroll() -> None:
            """Restore the scroll position to the bottom.

            If the user was at the bottom before reload, keep them at
            the bottom. Otherwise, maintain their relative position.

            This is done in a single-shot timer to ensure it runs
            after the layout has been updated.

            """
            if at_bottom:
                sb.setValue(sb.maximum())
            else:
                sb.setValue(int(ratio * sb.maximum()))
        QtCore.QTimer.singleShot(0, restore_scroll)

    def _on_auto_reload_toggled(self, checked: bool) -> None:  # noqa: FBT001
        """Handle auto-reload checkbox toggle."""
        if not checked:
            # self._controller.stop_file_reload()
            self._controller.stop_file_watch()
            self._controller.stop_file_reload()
        elif (self._current_process and
              self._current_process.pid and
              self._current_process.active):

            self._controller.stop_file_reload()
            self._controller.start_file_watch(self._current_process.output)
            # self._controller.start_file_reload(
            #     self._current_process.output, DEFAULT_RELOAD_INTERVAL)

    def _clean_inactive_processes(self) -> None:
        """Clean all inactive processes from a database."""
        if self._is_loading:
            return

        reply = QtWidgets.QMessageBox.question(
            self,
            "Confirm Cleanup",
            (
                "This will remove all inactive processes from the database "
                "and delete their output files. Continue?"
            ),
            (
                QtWidgets.QMessageBox.StandardButton.Yes
                | QtWidgets.QMessageBox.StandardButton.No
            ),
            QtWidgets.QMessageBox.StandardButton.No,
        )

        if reply != QtWidgets.QMessageBox.StandardButton.Yes:
            return

        self._set_loading_state(loading=True)
        self._status_bar.showMessage("Cleaning inactive processes...")

        self._controller.clean_inactive()

    def _delete_selected_process(self) -> None:
        """Delete the selected process from database and its output file."""
        if self._is_loading:
            return
        selection = self._tree_view.selectionModel()
        if not selection.hasSelection():
            QtWidgets.QMessageBox.information(
                self,
                "No Selection",
                "Please select a process to delete."
            )
            return
        indexes = selection.selectedRows()
        if not indexes:
            return
        process = self._tree_model.get_process_at_index(indexes[0])
        if not process:
            return
        reply = QtWidgets.QMessageBox.question(
            self,
            "Confirm Deletion",
            f"Delete process '{process.name}' "
            f"(PID: {process.pid}) and its output file?",
            QtWidgets.QMessageBox.StandardButton.Yes
            | QtWidgets.QMessageBox.StandardButton.No,
            QtWidgets.QMessageBox.StandardButton.No,
        )

        if reply != QtWidgets.QMessageBox.StandardButton.Yes:
            return

        self._set_loading_state(loading=True)
        self._status_bar.showMessage("Deleting process...")

        # Only top-level processes exist in DB -> require hash to delete
        if process.hash:
            self._controller.delete_single(process.hash)
        else:
            self._status_bar.showMessage(
                "Cannot delete a descendant process from DB")
            self._set_loading_state(loading=False)

    def _on_cleanup_finished(
            self,
            deleted_proc: int) -> None:
        """Handle completion of cleanup operation."""
        self._refresh_data()
        self._status_bar.showMessage(
            f"Deleted {deleted_proc} inactive processes.")

    def showEvent(self, event: QtGui.QShowEvent) -> None:  # noqa: N802
        """Apply stylesheet when the window is shown."""
        self.setStyleSheet(load_stylesheet())
        super().showEvent(event)
        self._controller.start_timers()
        self._refresh_data()

    def closeEvent(self, event: QtGui.QCloseEvent) -> None:  # noqa: N802
        """Clean up timers and threads when closing."""
        # Delegate shutdown to controller (stops timers and waits for workers)
        with contextlib.suppress(Exception):
            self._controller.shutdown()
        super().closeEvent(event)

__init__(parent=None)

Initialize the main window.

Source code in client/ayon_applications/ui/process_monitor.py
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
def __init__(self, parent=None):  # noqa: ANN001
    """Initialize the main window."""
    super().__init__(parent)
    self._log = getLogger(self.__class__.__name__)
    self.setWindowTitle("AYON Process Monitor")
    self.setMinimumSize(1000, 600)

    # Controller instance (owns manager, thread pool, timers)
    self._controller = ProcessMonitorController(self)

    # Connect controller signals to UI slots
    # ANSI to HTML converter
    self._ansi_converter = AnsiToHtmlConverter()

    self._controller.processes_refreshed.connect(
        self._on_processes_refreshed
    )
    self._controller.file_content.connect(self._on_file_content)
    self._controller.cleanup_finished.connect(self._on_cleanup_finished)
    self._controller.error.connect(self._on_error)
    # New: descendants
    self._controller.descendants_refreshed.connect(
        self._on_descendants_refreshed
    )

    self._current_process = None
    self._is_loading = False
    # Track last selection to restore across refreshes (including children)
    self._last_selected_hashes: set[str] = set()

    self._setup_ui()

closeEvent(event)

Clean up timers and threads when closing.

Source code in client/ayon_applications/ui/process_monitor.py
1344
1345
1346
1347
1348
1349
def closeEvent(self, event: QtGui.QCloseEvent) -> None:  # noqa: N802
    """Clean up timers and threads when closing."""
    # Delegate shutdown to controller (stops timers and waits for workers)
    with contextlib.suppress(Exception):
        self._controller.shutdown()
    super().closeEvent(event)

showEvent(event)

Apply stylesheet when the window is shown.

Source code in client/ayon_applications/ui/process_monitor.py
1337
1338
1339
1340
1341
1342
def showEvent(self, event: QtGui.QShowEvent) -> None:  # noqa: N802
    """Apply stylesheet when the window is shown."""
    self.setStyleSheet(load_stylesheet())
    super().showEvent(event)
    self._controller.start_timers()
    self._refresh_data()

ProcessRefreshWorker

Bases: QRunnable

Worker thread for refreshing process data from the database.

Source code in client/ayon_applications/ui/process_monitor.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
class ProcessRefreshWorker(QRunnable):
    """Worker thread for refreshing process data from the database."""

    def __init__(self, manager: ProcessManager):
        """Initialize the worker."""
        super().__init__()
        self.signals = ProcessRefreshWorkerSignals()
        self.signature = self.__class__.__name__
        self._manager = manager
        self._log = getLogger(self.signature)

    @Slot()
    def run(self) -> None:
        """Refresh process data in background thread."""
        with CatchTime() as timer:
            try:
                processes = self._manager.get_all_process_info()
                self.signals.finished.emit(processes)
            except Exception as e:  # noqa: BLE001
                self.signals.error.emit(str(e))
        self._log.debug(
            "Refresh from db completed in %s", timer.readout)

__init__(manager)

Initialize the worker.

Source code in client/ayon_applications/ui/process_monitor.py
175
176
177
178
179
180
181
def __init__(self, manager: ProcessManager):
    """Initialize the worker."""
    super().__init__()
    self.signals = ProcessRefreshWorkerSignals()
    self.signature = self.__class__.__name__
    self._manager = manager
    self._log = getLogger(self.signature)

run()

Refresh process data in background thread.

Source code in client/ayon_applications/ui/process_monitor.py
183
184
185
186
187
188
189
190
191
192
193
@Slot()
def run(self) -> None:
    """Refresh process data in background thread."""
    with CatchTime() as timer:
        try:
            processes = self._manager.get_all_process_info()
            self.signals.finished.emit(processes)
        except Exception as e:  # noqa: BLE001
            self.signals.error.emit(str(e))
    self._log.debug(
        "Refresh from db completed in %s", timer.readout)

ProcessRefreshWorkerSignals

Bases: QObject

Signals for ProcessRefreshWorker.

Signals can be defined only in classes derived from QObject.

Source code in client/ayon_applications/ui/process_monitor.py
163
164
165
166
167
168
169
class ProcessRefreshWorkerSignals(QtCore.QObject):
    """Signals for ProcessRefreshWorker.

    Signals can be defined only in classes derived from QObject.
    """
    finished = QtCore.Signal(list)  # Emits list of ProcessInfo
    error = QtCore.Signal(str)

ProcessTreeModel

Bases: QStandardItemModel

Model for displaying process information.

Each row represents a ProcessInfo. ProcessInfo objects are stored in Qt.UserRole on the first item of the row for easy retrieval.

Source code in client/ayon_applications/ui/process_monitor.py
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
class ProcessTreeModel(QtGui.QStandardItemModel):
    """Model for displaying process information.

    Each row represents a ProcessInfo. ProcessInfo objects are stored in
    Qt.UserRole on the first item of the row for easy retrieval.
    """

    _running_icon: QtGui.QIcon
    _stopped_icon: QtGui.QIcon
    _unknown_icon: QtGui.QIcon
    _child_running_icon: QtGui.QIcon
    ICON_SIZE = 12

    def __init__(
            self,
            manager: ProcessManager,
            parent: Optional[QtCore.QObject] = None,
            ) -> None:
        """Initialize the model.

        Args:
            manager (ProcessManager): Process manager
            parent (Optional[QtCore.QObject]): Parent QObject.

        """
        super().__init__(parent)
        self._generate_icons(size=self.ICON_SIZE)
        self._processes: list[ProcessInfo] = []
        self._manager = manager
        # map of top-level process hash to its first-column item
        self._top_item_by_hash: dict[str, QtGui.QStandardItem] = {}
        # Columns
        self.headers = [
            "Name", "Executable", "PID", "Status", "Created", "Start Time",
            "Output File", "Hash"
        ]
        self.columns = enum.IntEnum(  # type: ignore[misc]
            "columns",
            {
                name.replace(" ", "_").upper(): i
                for i, name in enumerate(self.headers)
            },
        )
        self.setColumnCount(len(self.headers))
        self.setHorizontalHeaderLabels(self.headers)

    def _status_icon(self, process: ProcessInfo) -> QtGui.QIcon:
        """Return a small colored circle icon representing process status.

        Args:
            process (ProcessInfo): ProcessInfo object.

        Returns:
            QtGui.QIcon: Colored circle icon.

        """
        # If top-level process has children, prefer child-running state
        if process.hash:
            parent_item = self._top_item_by_hash.get(process.hash)
            if parent_item is not None:
                for i in range(parent_item.rowCount()):
                    child = parent_item.child(i, self.columns.NAME)
                    if child is None:
                        continue
                    cproc: Optional[ProcessInfo] = child.data(
                        QtCore.Qt.ItemDataRole.UserRole)
                    if cproc and cproc.pid and cproc.active:
                        return self._child_running_icon

        if process.pid:
            return self._running_icon if process.active else self._stopped_icon
        return self._unknown_icon

    @classmethod
    def _generate_icons(cls, size: int = 12) -> None:
        """Generate static icons for process statuses.

        Args:
            size (int): Size of the icons in pixels.

        """
        if not hasattr(cls, "_running_icon"):
            cls._running_icon = cls._create_icon(
                QtGui.QColor(0, 180, 0), size)  # green = running
        if not hasattr(cls, "_stopped_icon"):
            cls._stopped_icon = cls._create_icon(
                QtGui.QColor(200, 0, 0), size)  # red = stopped
        if not hasattr(cls, "_unknown_icon"):
            cls._unknown_icon = cls._create_icon(
                QtGui.QColor(140, 140, 140), size)  # gray = unknown
        if not hasattr(cls, "_child_running_icon"):
            # yellow = some child running
            cls._child_running_icon = cls._create_icon(
                QtGui.QColor(200, 180, 0), size)

    @staticmethod
    def _create_icon(color: QtGui.QColor, size: int = 12) -> QtGui.QIcon:
        """Create a colored circle icon.

        Args:
            color (QtGui.QColor): Color of the circle.
            size (int): Size of the icon in pixels.

        Returns:
            QtGui.QIcon: Colored circle icon.

        """
        pix = QtGui.QPixmap(size, size)
        pix.fill(QtCore.Qt.GlobalColor.transparent)
        painter = QtGui.QPainter(pix)
        painter.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing)
        painter.setBrush(QtGui.QBrush(color))
        painter.setPen(QtCore.Qt.PenStyle.NoPen)
        painter.drawEllipse(1, 1, size - 2, size - 2)
        painter.end()
        return QtGui.QIcon(pix)

    def update_processes(self, processes: list[ProcessInfo]) -> None:
        """Replace current content with provided processes.

        Args:
            processes (list[ProcessInfo]): List of ProcessInfo objects.

        """
        self._processes = list(processes)
        root_item = self.invisibleRootItem()
        root_item.removeRows(0, root_item.rowCount())
        self._top_item_by_hash.clear()

        for process in self._processes:
            row_items: list[QtGui.QStandardItem] = []
            bg = self._data_background_role(process)
            for col in range(len(self.headers)):
                text = self._data_display_role(col, process)
                item = QtGui.QStandardItem(
                    str(text) if text is not None else ""
                )
                item.setEditable(False)
                # Store ProcessInfo in UserRole on the first column item
                if col == self.columns.NAME:
                    item.setData(process, QtCore.Qt.ItemDataRole.UserRole)
                    item.setIcon(self._status_icon(process))
                    if process.hash:
                        self._top_item_by_hash[process.hash] = item
                # Set background color for entire row via individual items
                if bg is not None:
                    item.setBackground(bg)
                row_items.append(item)
            root_item.appendRow(row_items)

    def update_descendants(
        self, parent_hash: str, descendants: list[ProcessInfo]
    ) -> None:
        """Update descendant processes under a given parent process.

        Args:
            parent_hash (str): Hash of the parent process.
            descendants (list[ProcessInfo]): List of descendant
                ProcessInfo objects.

        """
        parent_item = self._top_item_by_hash.get(parent_hash)
        if parent_item is None:
            return
        # remove previous children
        parent_item.removeRows(0, parent_item.rowCount())

        for child_proc in descendants:
            child_items: list[QtGui.QStandardItem] = []
            bg = self._data_background_role(child_proc)
            for col in range(len(self.headers)):
                text = self._data_display_role(col, child_proc)
                citem = QtGui.QStandardItem(
                    str(text) if text is not None else ""
                )
                citem.setEditable(False)
                if col == self.columns.NAME:
                    citem.setData(child_proc, QtCore.Qt.ItemDataRole.UserRole)
                    citem.setIcon(self._status_icon(child_proc))
                    # Make descendant name slightly italic to hint hierarchy
                    font = citem.font()
                    font.setItalic(True)
                    citem.setFont(font)
                if bg is not None:
                    citem.setBackground(bg)
                child_items.append(citem)
            parent_item.appendRow(child_items)

        # After updating children, refresh parent's icon
        # (parent ProcessInfo stored in UserRole)
        with contextlib.suppress(Exception):
            parent_proc: Optional[ProcessInfo] = parent_item.data(
                QtCore.Qt.ItemDataRole.UserRole
            )
            if parent_proc is not None:
                parent_item.setIcon(self._status_icon(parent_proc))

    def get_process_at_row(self, row: int) -> Optional[ProcessInfo]:
        """Get the ProcessInfo stored at the given row.

        Args:
            row (int): Row index.

        Returns:
            Optional[ProcessInfo]: ProcessInfo object or None if not found.

        """
        item = self.item(row, self.columns.NAME)
        return (
            None
            if item is None
            else item.data(QtCore.Qt.ItemDataRole.UserRole)
        )

    def get_process_at_index(
        self, index: QtCore.QModelIndex
    ) -> Optional[ProcessInfo]:
        """Get the ProcessInfo stored at the given index.

        Args:
            index (QtCore.QModelIndex): Model index.

        Returns:
            Optional[ProcessInfo]: ProcessInfo object or None if not found.

        """
        if not index.isValid():
            return None
        first_col_index = index.sibling(index.row(), self.columns.NAME)
        item = self.itemFromIndex(first_col_index)
        return None if item is None else item.data(
            QtCore.Qt.ItemDataRole.UserRole)

    def find_indexes_by_hashes(
        self, hashes: set[str]
    ) -> list[QtCore.QModelIndex]:
        """Find model indexes for processes matching given hashes.

        Args:
            hashes (set[str]): Set of process hashes to search for.

        Returns:
            list[QtCore.QModelIndex]: List of matching model indexes.

        """
        results: list[QtCore.QModelIndex] = []
        root = self.invisibleRootItem()
        for r in range(root.rowCount()):
            top_item = root.child(r, self.columns.NAME)
            if top_item is None:
                continue
            proc: Optional[ProcessInfo] = top_item.data(
                QtCore.Qt.ItemDataRole.UserRole
            )
            if proc and proc.hash and proc.hash in hashes:
                results.append(self.indexFromItem(top_item))
            # children
            for cr in range(top_item.rowCount()):
                child = top_item.child(cr, self.columns.NAME)
                if child is None:
                    continue
                cproc: Optional[ProcessInfo] = child.data(
                    QtCore.Qt.ItemDataRole.UserRole
                )
                if cproc and cproc.hash and cproc.hash in hashes:
                    results.append(self.indexFromItem(child))
        return results

    def get_index_by_hash(self, hash_: str) -> Optional[QtCore.QModelIndex]:
        """Get model index for process matching given hash.

        Args:
            hash_ (str): Process hash to search for.

        Returns:
            Optional[QtCore.QModelIndex]: Matching model index or None
                if not found.

        """
        item = self._top_item_by_hash.get(hash_)
        return self.indexFromItem(item) if item else None

    def _data_display_role(  # noqa: C901, PLR0911, PLR0912
        self, column: int, process: ProcessInfo
    ) -> Optional[str]:
        """Get display text for a given column and process.

        Args:
            column (int): Column index.
            process (ProcessInfo): ProcessInfo object.

        Returns:
            Optional[str]: Display text or None if column is invalid.

        """
        if column == self.columns.NAME:
            return process.name
        if column == self.columns.EXECUTABLE:
            return process.executable.as_posix() or "N/A"
        if column == self.columns.PID:
            return str(process.pid) if process.pid else "N/A"
        if column == self.columns.STATUS:
            if process.pid:
                return "Running" if process.active else "Stopped"
            return "Unknown"
        if column == self.columns.CREATED:
            if process.created_at:
                try:
                    # Parse the UTC timestamp from SQLite and convert
                    # to local timezone
                    # SQLite CURRENT_TIMESTAMP format is "YYYY-MM-DD HH:MM:SS"
                    utc_dt = datetime.strptime(  # noqa: DTZ007
                        process.created_at, "%Y-%m-%d %H:%M:%S"
                    )
                    # Assume it is UTC and convert to local timezone
                    utc_dt = utc_dt.replace(tzinfo=timezone.utc)
                    local_dt = utc_dt.astimezone()
                    return local_dt.strftime("%Y-%m-%d %H:%M:%S")
                except (ValueError, AttributeError):
                    # If parsing fails, return the original string
                    return process.created_at
            return "N/A"
        if column == self.columns.START_TIME:
            if process.start_time:
                try:
                    return datetime.fromtimestamp(
                        process.start_time,
                        tz=datetime.now().astimezone().tzinfo,
                    ).strftime("%Y-%m-%d %H:%M:%S")
                except (OSError, OverflowError, ValueError):
                    return str(process.start_time)
            return "N/A"
        if column == self.columns.OUTPUT_FILE:
            return str(process.output) if process.output else "N/A"
        if column == self.columns.HASH:
            with contextlib.suppress(Exception):
                return process.hash or self._manager.get_process_info_hash(
                    process
                )
            return "N/A"
        return None

    @staticmethod
    def _data_background_role(process: ProcessInfo) -> QtGui.QColor:
        if process.pid:
            is_running = process.active
            if is_running:
                return QtGui.QColor(200, 255, 200)  # Light green

            return QtGui.QColor(255, 200, 200)  # Light red
        return QtGui.QColor(240, 240, 240)  # Light gray

    def sort(  # noqa: C901
        self,
        column: int,
        order: QtCore.Qt.SortOrder = QtCore.Qt.SortOrder.AscendingOrder,
    ) -> None:
        """Sort the model based on a column and order.

        Args:
            column (int): Column index to sort by.
            order (QtCore.Qt.SortOrder): Sort order (Ascending or Descending).

        """
        if not self._processes:
            return
        reverse = order == QtCore.Qt.SortOrder.DescendingOrder

        def key_func(  # noqa: PLR0911
            process: ProcessInfo,
        ) -> Union[str, int, float]:
            """Key function for sorting based on column.

            Returns:
                Union[str, int]: Value to sort by.

            """
            if column == self.columns.NAME:
                return process.name or ""
            if column == self.columns.EXECUTABLE:
                return (
                    process.executable.as_posix() if process.executable else ""
                )
            if column == self.columns.PID:
                return process.pid or 0
            if column == self.columns.STATUS:
                return process.active
            if column == self.columns.CREATED:
                return process.created_at or ""
            if column == self.columns.START_TIME:
                return process.start_time or 0
            if column == self.columns.OUTPUT_FILE:
                return process.output.as_posix() if process.output else ""
            if column == self.columns.HASH:
                return process.hash or ""

            return ""

        sorted_processes = sorted(
            self._processes, key=key_func, reverse=reverse)
        self.update_processes(sorted_processes)

__init__(manager, parent=None)

Initialize the model.

Parameters:

Name Type Description Default
manager ProcessManager

Process manager

required
parent Optional[QObject]

Parent QObject.

None
Source code in client/ayon_applications/ui/process_monitor.py
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
def __init__(
        self,
        manager: ProcessManager,
        parent: Optional[QtCore.QObject] = None,
        ) -> None:
    """Initialize the model.

    Args:
        manager (ProcessManager): Process manager
        parent (Optional[QtCore.QObject]): Parent QObject.

    """
    super().__init__(parent)
    self._generate_icons(size=self.ICON_SIZE)
    self._processes: list[ProcessInfo] = []
    self._manager = manager
    # map of top-level process hash to its first-column item
    self._top_item_by_hash: dict[str, QtGui.QStandardItem] = {}
    # Columns
    self.headers = [
        "Name", "Executable", "PID", "Status", "Created", "Start Time",
        "Output File", "Hash"
    ]
    self.columns = enum.IntEnum(  # type: ignore[misc]
        "columns",
        {
            name.replace(" ", "_").upper(): i
            for i, name in enumerate(self.headers)
        },
    )
    self.setColumnCount(len(self.headers))
    self.setHorizontalHeaderLabels(self.headers)

find_indexes_by_hashes(hashes)

Find model indexes for processes matching given hashes.

Parameters:

Name Type Description Default
hashes set[str]

Set of process hashes to search for.

required

Returns:

Type Description
list[QModelIndex]

list[QtCore.QModelIndex]: List of matching model indexes.

Source code in client/ayon_applications/ui/process_monitor.py
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
def find_indexes_by_hashes(
    self, hashes: set[str]
) -> list[QtCore.QModelIndex]:
    """Find model indexes for processes matching given hashes.

    Args:
        hashes (set[str]): Set of process hashes to search for.

    Returns:
        list[QtCore.QModelIndex]: List of matching model indexes.

    """
    results: list[QtCore.QModelIndex] = []
    root = self.invisibleRootItem()
    for r in range(root.rowCount()):
        top_item = root.child(r, self.columns.NAME)
        if top_item is None:
            continue
        proc: Optional[ProcessInfo] = top_item.data(
            QtCore.Qt.ItemDataRole.UserRole
        )
        if proc and proc.hash and proc.hash in hashes:
            results.append(self.indexFromItem(top_item))
        # children
        for cr in range(top_item.rowCount()):
            child = top_item.child(cr, self.columns.NAME)
            if child is None:
                continue
            cproc: Optional[ProcessInfo] = child.data(
                QtCore.Qt.ItemDataRole.UserRole
            )
            if cproc and cproc.hash and cproc.hash in hashes:
                results.append(self.indexFromItem(child))
    return results

get_index_by_hash(hash_)

Get model index for process matching given hash.

Parameters:

Name Type Description Default
hash_ str

Process hash to search for.

required

Returns:

Type Description
Optional[QModelIndex]

Optional[QtCore.QModelIndex]: Matching model index or None if not found.

Source code in client/ayon_applications/ui/process_monitor.py
567
568
569
570
571
572
573
574
575
576
577
578
579
def get_index_by_hash(self, hash_: str) -> Optional[QtCore.QModelIndex]:
    """Get model index for process matching given hash.

    Args:
        hash_ (str): Process hash to search for.

    Returns:
        Optional[QtCore.QModelIndex]: Matching model index or None
            if not found.

    """
    item = self._top_item_by_hash.get(hash_)
    return self.indexFromItem(item) if item else None

get_process_at_index(index)

Get the ProcessInfo stored at the given index.

Parameters:

Name Type Description Default
index QModelIndex

Model index.

required

Returns:

Type Description
Optional[ProcessInfo]

Optional[ProcessInfo]: ProcessInfo object or None if not found.

Source code in client/ayon_applications/ui/process_monitor.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
def get_process_at_index(
    self, index: QtCore.QModelIndex
) -> Optional[ProcessInfo]:
    """Get the ProcessInfo stored at the given index.

    Args:
        index (QtCore.QModelIndex): Model index.

    Returns:
        Optional[ProcessInfo]: ProcessInfo object or None if not found.

    """
    if not index.isValid():
        return None
    first_col_index = index.sibling(index.row(), self.columns.NAME)
    item = self.itemFromIndex(first_col_index)
    return None if item is None else item.data(
        QtCore.Qt.ItemDataRole.UserRole)

get_process_at_row(row)

Get the ProcessInfo stored at the given row.

Parameters:

Name Type Description Default
row int

Row index.

required

Returns:

Type Description
Optional[ProcessInfo]

Optional[ProcessInfo]: ProcessInfo object or None if not found.

Source code in client/ayon_applications/ui/process_monitor.py
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def get_process_at_row(self, row: int) -> Optional[ProcessInfo]:
    """Get the ProcessInfo stored at the given row.

    Args:
        row (int): Row index.

    Returns:
        Optional[ProcessInfo]: ProcessInfo object or None if not found.

    """
    item = self.item(row, self.columns.NAME)
    return (
        None
        if item is None
        else item.data(QtCore.Qt.ItemDataRole.UserRole)
    )

sort(column, order=QtCore.Qt.SortOrder.AscendingOrder)

Sort the model based on a column and order.

Parameters:

Name Type Description Default
column int

Column index to sort by.

required
order SortOrder

Sort order (Ascending or Descending).

AscendingOrder
Source code in client/ayon_applications/ui/process_monitor.py
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
def sort(  # noqa: C901
    self,
    column: int,
    order: QtCore.Qt.SortOrder = QtCore.Qt.SortOrder.AscendingOrder,
) -> None:
    """Sort the model based on a column and order.

    Args:
        column (int): Column index to sort by.
        order (QtCore.Qt.SortOrder): Sort order (Ascending or Descending).

    """
    if not self._processes:
        return
    reverse = order == QtCore.Qt.SortOrder.DescendingOrder

    def key_func(  # noqa: PLR0911
        process: ProcessInfo,
    ) -> Union[str, int, float]:
        """Key function for sorting based on column.

        Returns:
            Union[str, int]: Value to sort by.

        """
        if column == self.columns.NAME:
            return process.name or ""
        if column == self.columns.EXECUTABLE:
            return (
                process.executable.as_posix() if process.executable else ""
            )
        if column == self.columns.PID:
            return process.pid or 0
        if column == self.columns.STATUS:
            return process.active
        if column == self.columns.CREATED:
            return process.created_at or ""
        if column == self.columns.START_TIME:
            return process.start_time or 0
        if column == self.columns.OUTPUT_FILE:
            return process.output.as_posix() if process.output else ""
        if column == self.columns.HASH:
            return process.hash or ""

        return ""

    sorted_processes = sorted(
        self._processes, key=key_func, reverse=reverse)
    self.update_processes(sorted_processes)

update_descendants(parent_hash, descendants)

Update descendant processes under a given parent process.

Parameters:

Name Type Description Default
parent_hash str

Hash of the parent process.

required
descendants list[ProcessInfo]

List of descendant ProcessInfo objects.

required
Source code in client/ayon_applications/ui/process_monitor.py
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
def update_descendants(
    self, parent_hash: str, descendants: list[ProcessInfo]
) -> None:
    """Update descendant processes under a given parent process.

    Args:
        parent_hash (str): Hash of the parent process.
        descendants (list[ProcessInfo]): List of descendant
            ProcessInfo objects.

    """
    parent_item = self._top_item_by_hash.get(parent_hash)
    if parent_item is None:
        return
    # remove previous children
    parent_item.removeRows(0, parent_item.rowCount())

    for child_proc in descendants:
        child_items: list[QtGui.QStandardItem] = []
        bg = self._data_background_role(child_proc)
        for col in range(len(self.headers)):
            text = self._data_display_role(col, child_proc)
            citem = QtGui.QStandardItem(
                str(text) if text is not None else ""
            )
            citem.setEditable(False)
            if col == self.columns.NAME:
                citem.setData(child_proc, QtCore.Qt.ItemDataRole.UserRole)
                citem.setIcon(self._status_icon(child_proc))
                # Make descendant name slightly italic to hint hierarchy
                font = citem.font()
                font.setItalic(True)
                citem.setFont(font)
            if bg is not None:
                citem.setBackground(bg)
            child_items.append(citem)
        parent_item.appendRow(child_items)

    # After updating children, refresh parent's icon
    # (parent ProcessInfo stored in UserRole)
    with contextlib.suppress(Exception):
        parent_proc: Optional[ProcessInfo] = parent_item.data(
            QtCore.Qt.ItemDataRole.UserRole
        )
        if parent_proc is not None:
            parent_item.setIcon(self._status_icon(parent_proc))

update_processes(processes)

Replace current content with provided processes.

Parameters:

Name Type Description Default
processes list[ProcessInfo]

List of ProcessInfo objects.

required
Source code in client/ayon_applications/ui/process_monitor.py
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
def update_processes(self, processes: list[ProcessInfo]) -> None:
    """Replace current content with provided processes.

    Args:
        processes (list[ProcessInfo]): List of ProcessInfo objects.

    """
    self._processes = list(processes)
    root_item = self.invisibleRootItem()
    root_item.removeRows(0, root_item.rowCount())
    self._top_item_by_hash.clear()

    for process in self._processes:
        row_items: list[QtGui.QStandardItem] = []
        bg = self._data_background_role(process)
        for col in range(len(self.headers)):
            text = self._data_display_role(col, process)
            item = QtGui.QStandardItem(
                str(text) if text is not None else ""
            )
            item.setEditable(False)
            # Store ProcessInfo in UserRole on the first column item
            if col == self.columns.NAME:
                item.setData(process, QtCore.Qt.ItemDataRole.UserRole)
                item.setIcon(self._status_icon(process))
                if process.hash:
                    self._top_item_by_hash[process.hash] = item
            # Set background color for entire row via individual items
            if bg is not None:
                item.setBackground(bg)
            row_items.append(item)
        root_item.appendRow(row_items)

main()

Helper function to debug the tool.

Source code in client/ayon_applications/ui/process_monitor.py
1352
1353
1354
1355
1356
1357
1358
1359
def main() -> None:
    """Helper function to debug the tool."""
    app = get_ayon_qt_app()

    window = ProcessMonitorWindow()
    window.show()

    app.exec_()