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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
119
120
121
122
123
124
125
126
127
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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

FileChangeWatcher

Bases: QObject

Qt-based file watcher with rotation handling and debounce.

Source code in client/ayon_applications/ui/process_monitor.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
 94
 95
 96
 97
 98
 99
100
101
102
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
209
210
211
212
213
214
215
216
217
218
219
220
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
@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
197
198
199
200
201
202
203
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)

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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
class ProcessMonitorController(QtCore.QObject):
    """Controller that encapsulates data logic for ProcessMonitorWindow.

    Handles ApplicationManager, QThreadPool, and QTimers.

    """
    file_content = QtCore.Signal(str)
    cleanup_finished = QtCore.Signal()
    status_message_requested = QtCore.Signal(str)
    error = QtCore.Signal(str)

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

        self._file_watcher = FileChangeWatcher(self)
        self._file_watcher.changed.connect(self._on_file_changed)

        self._thread_pool = QThreadPool()

        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 stop_timers(self) -> None:
        """Stop all active timers."""
        if self._file_reload_timer.isActive():
            self._file_reload_timer.stop()

    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))

    # 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 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()

    # Cleanup operations
    def clean_inactive(self) -> None:
        """Clean all inactive processes in background thread."""
        worker = SimpleWorker(self._cleanup_inactive)
        self._thread_pool.start(worker)

    def delete_processes(self, process_hashes: set[str]) -> None:
        """Delete processes by hash in background thread.

        Args:
            process_hashes (set[str]): Hash of the processes to delete.

        """
        worker = SimpleWorker(self._delete_processes, process_hashes)
        self._thread_pool.start(worker)

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

    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)

    def _delete_processes(self, process_hashes: set[str]) -> None:
        if not process_hashes:
            self._on_error("No process hashes provided")
            return
        try:
            self.manager.delete_processes_info(process_hashes)
            self.status_message_requested.emit(
                f"Deleted {len(process_hashes)} selected processes."
            )
            self.cleanup_finished.emit()

        except Exception as exc:  # noqa: BLE001
            self._on_error(str(exc))

    def _cleanup_inactive(self) -> None:
        """Clean up inactive processes."""
        try:
            deleted_count = self.manager.delete_inactive_processes()
            self.status_message_requested.emit(
                f"Deleted {deleted_count} inactive processes."
            )
            self.cleanup_finished.emit()

        except Exception as exc:  # noqa: BLE001
            self._on_error(str(exc))

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

__init__(parent=None)

Initialize the controller.

Source code in client/ayon_applications/ui/process_monitor.py
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
def __init__(self, parent: Optional[QtCore.QObject] = None):
    """Initialize the controller."""
    super().__init__(parent)
    self.manager = ProcessManager()

    self._file_watcher = FileChangeWatcher(self)
    self._file_watcher.changed.connect(self._on_file_changed)

    self._thread_pool = QThreadPool()

    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
887
888
889
890
def clean_inactive(self) -> None:
    """Clean all inactive processes in background thread."""
    worker = SimpleWorker(self._cleanup_inactive)
    self._thread_pool.start(worker)

delete_processes(process_hashes)

Delete processes by hash in background thread.

Parameters:

Name Type Description Default
process_hashes set[str]

Hash of the processes to delete.

required
Source code in client/ayon_applications/ui/process_monitor.py
892
893
894
895
896
897
898
899
900
def delete_processes(self, process_hashes: set[str]) -> None:
    """Delete processes by hash in background thread.

    Args:
        process_hashes (set[str]): Hash of the processes to delete.

    """
    worker = SimpleWorker(self._delete_processes, process_hashes)
    self._thread_pool.start(worker)

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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
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))

shutdown()

Shutdown controller.

Stop timers and wait for workers.

Source code in client/ayon_applications/ui/process_monitor.py
874
875
876
877
878
879
880
881
882
883
884
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
863
864
865
866
867
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
848
849
850
851
852
853
854
855
856
857
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)

stop_file_reload()

Stop auto-reloading file content.

Source code in client/ayon_applications/ui/process_monitor.py
869
870
871
872
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
859
860
861
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
824
825
826
827
def stop_timers(self) -> None:
    """Stop all active timers."""
    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
 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
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.file_content.connect(self._on_file_content)
        self._controller.status_message_requested.connect(
            self._on_status_message
        )
        self._controller.cleanup_finished.connect(self._on_cleanup_finished)
        self._controller.error.connect(self._on_error)

        self._current_process = None

        self._setup_ui()

    def keyReleaseEvent(self, event) -> None:
        if (
            event.modifiers() == QtCore.Qt.NoModifier
            and event.key() == QtCore.Qt.Key_Delete
        ):
            self._delete_selected_process()
            event.accept()
            return
        super().keyReleaseEvent(event)

    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_proxy = QtCore.QSortFilterProxyModel()
        self._tree_proxy.setSourceModel(self._tree_model)
        self._tree_view = QtWidgets.QTreeView()
        self._tree_view.setModel(self._tree_proxy)
        self._tree_view.setSelectionMode(
            QtWidgets.QAbstractItemView.SelectionMode.ExtendedSelection
        )
        self._tree_view.setSortingEnabled(True)
        self._tree_view.sortByColumn(
            ProcessTreeModel.COLUMNS.CREATED, QtCore.Qt.DescendingOrder
        )
        self._tree_view.doubleClicked.connect(self._on_row_double_clicked)
        self._tree_delegate = ElideTextDelegate(self._tree_view)
        self._tree_view.setItemDelegate(self._tree_delegate)
        self._tree_model.processes_refreshed.connect(
            self._on_processes_refreshed
        )
        self._tree_model.error.connect(self._on_error)

        header = self._tree_view.header()
        header.setStretchLastSection(True)
        for col in range(len(self._tree_model.HEADERS)):
            header.setSectionResizeMode(
                col, QtWidgets.QHeaderView.ResizeMode.Interactive
            )
        for col, size in enumerate([165, 320, 55, 140, 140]):
            header.resizeSection(col, size)

        # 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)

        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)
        return toolbar_layout

    def _refresh_data(self) -> None:
        """Refresh the process table data in background thread."""
        self._tree_model.refresh()

    def _on_processes_refreshed(self, process_count: int) -> None:
        self._status_bar.showMessage(f"Loaded {process_count} processes")
        self._log.debug("Process tree updated with new data")

    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}")

    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():
            return

        item_type = index.data(ITEM_TYPE_ROLE)
        if item_type != MAIN_PROCESS_ITEM:
            return

        process_hash = index.data(PROCESS_HASH_ROLE)
        process = self._tree_model.get_process_by_hash(process_hash)
        if not process:
            return
        self._current_process = process
        self._load_output_content()
        if (
            self._auto_reload_checkbox.isChecked()
            and process.pid
            and not process.stopped
        ):
            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 not self._current_process.stopped
        ):
            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."""
        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._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."""
        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()
        hashes = set()
        for index in indexes:
            if index.data(ITEM_TYPE_ROLE) == MAIN_PROCESS_ITEM:
                hashes.add(index.data(PROCESS_HASH_ROLE))

        if not hashes:
            QtWidgets.QMessageBox.information(
                self,
                "No Valid Selection",
                "Cannot delete a descendant process from DB.",
            )
            return

        suffix = "" if len(hashes) == 1 else "es"
        question = (
            f"Delete {len(hashes)} process{suffix} and its output file?"
        )

        reply = QtWidgets.QMessageBox.question(
            self,
            "Confirm Deletion",
            question,
            QtWidgets.QMessageBox.StandardButton.Yes
            | QtWidgets.QMessageBox.StandardButton.No,
            QtWidgets.QMessageBox.StandardButton.No,
        )

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

        self._status_bar.showMessage("Deleting process...")

        self._controller.delete_processes(hashes)

    def _on_status_message(self, message: str) -> None:
        """Handle status message requests."""
        self._status_bar.showMessage(message)

    def _on_cleanup_finished(self) -> None:
        self._refresh_data()

    def showEvent(self, event: QtGui.QShowEvent) -> None:  # noqa: N802
        """Apply stylesheet when the window is shown."""
        self.setStyleSheet(load_stylesheet())
        super().showEvent(event)
        self._tree_model.start_workers()
        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)
        self._tree_model.stop_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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
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.file_content.connect(self._on_file_content)
    self._controller.status_message_requested.connect(
        self._on_status_message
    )
    self._controller.cleanup_finished.connect(self._on_cleanup_finished)
    self._controller.error.connect(self._on_error)

    self._current_process = None

    self._setup_ui()

closeEvent(event)

Clean up timers and threads when closing.

Source code in client/ayon_applications/ui/process_monitor.py
1319
1320
1321
1322
1323
1324
1325
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)
    self._tree_model.stop_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
1312
1313
1314
1315
1316
1317
def showEvent(self, event: QtGui.QShowEvent) -> None:  # noqa: N802
    """Apply stylesheet when the window is shown."""
    self.setStyleSheet(load_stylesheet())
    super().showEvent(event)
    self._tree_model.start_workers()
    self._refresh_data()

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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
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.
    """
    processes_refreshed = QtCore.Signal(int)
    error = QtCore.Signal(str)

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

    # Columns
    HEADERS = [
        "Name", "Executable", "PID", "Created", "Start Time", "Output File"
    ]
    COLUMNS = enum.IntEnum(  # type: ignore[misc]
        "columns",
        {
            name.replace(" ", "_").upper(): i
            for i, name in enumerate(HEADERS)
        },
    )
    _display_roles_mapping = {
        COLUMNS.NAME: PROCESS_NAME_ROLE,
        COLUMNS.EXECUTABLE: PROCESS_EXECUTABLE_ROLE,
        COLUMNS.PID: PROCESS_PID_ROLE,
        COLUMNS.CREATED: PROCESS_CREATED_ROLE,
        COLUMNS.START_TIME: PROCESS_START_TIME_ROLE,
        COLUMNS.OUTPUT_FILE: PROCESS_OUTPUT_FILE_ROLE,
    }

    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.setColumnCount(len(self.HEADERS))
        self.setHorizontalHeaderLabels(self.HEADERS)

        refresh_timer = QtCore.QTimer()
        refresh_timer.setInterval(100)
        refresh_timer.timeout.connect(self._refresh_timer_callback)

        self._generate_icons(size=self.ICON_SIZE)
        self._manager = manager

        self._process_by_hash: dict[str, ProcessInfo] = {}
        self._root_items_by_hash: dict[str, QtGui.QStandardItem] = {}
        self._descendant_items_by_hash: dict[str, QtGui.QStandardItem] = {}

        # Helper mappings to reliably cleanup cached items
        self._hashes_to_process: list[str] = []

        self._state = _ModelState()

        self._thread_pool = QThreadPool()
        self._refresh_timer = refresh_timer

    def start_workers(self):
        self._state.stopped = False
        self._refresh_timer.start()
        if not self._state.refresh_in_pool:
            self._state.refresh_in_pool = True
            self._thread_pool.start(self._refresh)

    def stop_workers(self):
        self._state.stopped = True
        self._refresh_timer.stop()
        self._thread_pool.waitForDone()

    def refresh(self) -> None:
        self._refresh_processes()

    def _refresh(self) -> None:
        self._state.refresh_in_pool = False
        start = time.time()

        self._refresh_processes()
        self._refresh_states()

        while True:
            if self._state.stopped:
                return

            if self._state.has_new_roots:
                break

            if time.time() - start > 5:
                break
            QtCore.QThread.msleep(100)

        if not self._state.refresh_in_pool:
            self._thread_pool.start(self._refresh)

    def _refresh_processes(self) -> None:
        # Avoid running of '_refresh_processes' multiple times
        # - this method can be triggered manually from 'refresh' and also from
        #   internal '_refresh' in a thread pool.
        if self._state.refreshing_processes:
            return

        self._state.refreshing_processes = True

        to_remove = set(self._root_items_by_hash)

        refresh_data = self._state.refresh_data
        new_items = []
        hashes_to_process = []
        processes = self._manager.get_all_process_info(invalidate=False)
        for process in processes:
            process_hash = process.hash
            if not process_hash:
                continue

            self._process_by_hash[process_hash] = process
            to_remove.discard(process_hash)

            if not process.stopped:
                hashes_to_process.append(process_hash)

            item = self._root_items_by_hash.get(process_hash)
            if item is not None:
                state = item.data(PROCESS_STATE_ROLE)
                new_state = self._get_process_state(process, state)
                if new_state != state:
                    refresh_data.set_process_state(process_hash, new_state)
                continue

            item = QtGui.QStandardItem()
            item.setEditable(False)
            item.setColumnCount(self.columnCount())
            new_items.append(item)

            self._fill_item_data(item, process, MAIN_PROCESS_ITEM)

            self._root_items_by_hash[process_hash] = item

        self._hashes_to_process = hashes_to_process

        refresh_data.set_items(new_items, to_remove)
        if new_items:
            self._state.has_new_roots = True

        self._state.refreshing_processes = False

    def _refresh_timer_callback(self):
        refresh_data = self._state.refresh_data
        if not refresh_data.new_changes:
            return

        (
            new_items,
            to_remove,
            descendants_to_update,
            states_to_set,
        ) = refresh_data.pop()
        if new_items:
            root_item = self.invisibleRootItem()
            root_item.appendRows(new_items)

        self._remove_root_items(to_remove)

        for process_hash, descendants in descendants_to_update.items():
            self._update_descendants(process_hash, descendants)

        for process_hash, state in states_to_set.items():
            item = self._root_items_by_hash.get(process_hash)
            process = self._process_by_hash.get(process_hash)
            if item is None or process is None:
                continue
            self._set_item_state(
                item,
                process,
                MAIN_PROCESS_ITEM,
                state=state
            )

    def _refresh_states(self) -> None:
        """Refresh descendants for all root processes."""
        self._state.has_new_roots = False

        refresh_data = self._state.refresh_data

        queue = deque(self._hashes_to_process)
        while queue:
            if self._state.stopped:
                return

            QtCore.QThread.msleep(1)

            process_hash = queue.popleft()
            process = self._process_by_hash.get(process_hash)
            if process is None:
                continue

            state = ProcessState.UNKNOWN
            try:
                is_running = self._manager.invalidate_process(process)
                state = (
                    ProcessState.RUNNING
                    if is_running
                    else ProcessState.STOPPED
                )

            except Exception as exc:
                self.error.emit(str(exc))

            refresh_data.set_process_state(process_hash, state)

            try:
                descendants = self._manager.get_descendant_processes(process)
            except Exception as exc:
                descendants = []
                self.error.emit(str(exc))

            refresh_data.set_descendants(process_hash, descendants)

    def _remove_root_items(self, process_hashes: set[str]) -> None:
        root_item = self.invisibleRootItem()
        for process_hash in process_hashes:
            item = self._root_items_by_hash.pop(process_hash, None)
            if item is None:
                continue
            for row in range(item.rowCount()):
                child = item.child(row, 0)
                child_hash = child.data(PROCESS_HASH_ROLE)
                self._descendant_items_by_hash.pop(child_hash)

            root_item.takeRow(item.row())
            self._process_by_hash.pop(process_hash)

    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._root_items_by_hash.get(parent_hash)
        parent_proc = self._process_by_hash.get(parent_hash)
        if parent_item is None:
            return

        descendants_by_hash = {
            proc.hash: proc
            for proc in descendants
        }
        for row in reversed(range(parent_item.rowCount())):
            item = parent_item.child(row)
            child_hash = item.data(PROCESS_HASH_ROLE)
            proc = descendants_by_hash.pop(child_hash, None)
            if proc is None:
                self._descendant_items_by_hash.pop(child_hash)
                parent_item.removeRow(item.row())
                continue

            if proc.stopped:
                self._set_item_state(
                    item, proc, DESCENDANT_PROCESS_ITEM
                )

        new_items: list[QtGui.QStandardItem] = []
        for child_proc in descendants_by_hash.values():
            item = QtGui.QStandardItem()
            item.setEditable(False)
            item.setColumnCount(self.columnCount())
            new_items.append(item)

            # Make descendant name slightly italic to hint hierarchy
            font = item.font()
            font.setItalic(True)
            item.setFont(font)

            self._fill_item_data(item, child_proc, DESCENDANT_PROCESS_ITEM)
            self._descendant_items_by_hash[child_proc.hash] = item

        if new_items:
            parent_item.appendRows(new_items)

        if parent_proc is not None:
            self._set_item_state(
                parent_item, parent_proc, MAIN_PROCESS_ITEM
            )

    def get_process_by_hash(self, process_hash: str) -> ProcessInfo | None:
        return self._process_by_hash.get(process_hash)

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if not index.isValid():
            return super().data(index, role)

        col = index.column()
        if role == QtCore.Qt.DecorationRole:
            if col != self.COLUMNS.NAME:
                return None

        if role == QtCore.Qt.DisplayRole:
            role = self._display_roles_mapping.get(col)
            if role is None:
                return ""

        if role >= QtCore.Qt.UserRole:
            index = index.sibling(index.row(), 0)

        return super().data(index, role)

    def flags(self, index):
        return super().flags(index.sibling(index.row(), 0))

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

        Args:
            state (int): Process state.

        Returns:
            QtGui.QIcon: Colored circle icon.

        """
        if state == ProcessState.RUNNING:
            return self._running_icon
        if state == ProcessState.CHILD_RUNNING:
            return self._child_running_icon
        if state == ProcessState.STOPPED:
            return self._stopped_icon
        return self._unknown_icon

    def _get_process_state(
        self, process: ProcessInfo, old_state: int | None
    ) -> int:
        """.

        Args:
            process (ProcessInfo): ProcessInfo object.
            old_state (int): Item type.

        Returns:
            int: Process state.

        """
        # If top-level process has children, prefer child-running state
        if not process.stopped:
            if old_state is None or old_state == ProcessState.UNKNOWN:
                return ProcessState.UNKNOWN
            return ProcessState.RUNNING

        if process.hash:
            parent_item = self._root_items_by_hash.get(process.hash)
            # Process has any descendant items, consider it child-running
            if parent_item is not None and parent_item.rowCount() > 0:
                return ProcessState.CHILD_RUNNING

        return ProcessState.STOPPED

    @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 _fill_item_data(
        self,
        item: QtGui.QStandardItem,
        process: ProcessInfo,
        item_type: int,
    ) -> None:
        executable = process.executable.as_posix()
        pid_value = "N/A"
        created_at = "N/A"
        start_time = "N/A"
        output_file = "N/A"
        if process.pid:
            pid_value = str(process.pid)

        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"
                created_arrow = arrow.get(process.created_at).to("local")
                created_at = created_arrow.strftime("%Y-%m-%d %H:%M:%S")

            except (ValueError, AttributeError):
                # If parsing fails, return the original string
                created_at = process.created_at

        if process.start_time:
            st_obj = arrow.get(process.start_time).to("local")
            start_time = st_obj.strftime("%Y-%m-%d %H:%M:%S")

        if process.output:
            output_file = str(process.output)

        item.setData(process.name, PROCESS_NAME_ROLE)
        item.setData(process.hash, PROCESS_HASH_ROLE)
        item.setData(executable, PROCESS_EXECUTABLE_ROLE)
        item.setData(pid_value, PROCESS_PID_ROLE)
        item.setData(created_at, PROCESS_CREATED_ROLE)
        item.setData(start_time, PROCESS_START_TIME_ROLE)
        item.setData(output_file, PROCESS_OUTPUT_FILE_ROLE)
        item.setData(item_type, ITEM_TYPE_ROLE)
        self._set_item_state(item, process, item_type)

    def _set_item_state(
        self,
        item: QtGui.QStandardItem,
        process: ProcessInfo,
        item_type: int,
        *,
        state: int | None = None,
    ) -> None:
        old_state = item.data(PROCESS_STATE_ROLE)

        if state is None:
            if item_type == DESCENDANT_PROCESS_ITEM:
                state = ProcessState.RUNNING
            else:
                state = self._get_process_state(process, old_state)

        if old_state == state:
            return

        icon = self._get_status_icon(state)

        item.setData(state, PROCESS_STATE_ROLE)
        item.setData(icon, QtCore.Qt.DecorationRole)

__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
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
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.setColumnCount(len(self.HEADERS))
    self.setHorizontalHeaderLabels(self.HEADERS)

    refresh_timer = QtCore.QTimer()
    refresh_timer.setInterval(100)
    refresh_timer.timeout.connect(self._refresh_timer_callback)

    self._generate_icons(size=self.ICON_SIZE)
    self._manager = manager

    self._process_by_hash: dict[str, ProcessInfo] = {}
    self._root_items_by_hash: dict[str, QtGui.QStandardItem] = {}
    self._descendant_items_by_hash: dict[str, QtGui.QStandardItem] = {}

    # Helper mappings to reliably cleanup cached items
    self._hashes_to_process: list[str] = []

    self._state = _ModelState()

    self._thread_pool = QThreadPool()
    self._refresh_timer = refresh_timer

RefreshData dataclass

Keep track of items to refresh in UI.

These data are collected in a thread and has to be propagated in main thread.

Source code in client/ayon_applications/ui/process_monitor.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
@dataclass
class RefreshData:
    """Keep track of items to refresh in UI.

    These data are collected in a thread and has to be propagated in main
        thread.

    """
    new_changes: bool = False
    _states_to_set: dict[str, int] = field(default_factory=dict)
    _root_items_to_remove: set[str] = field(default_factory=set)
    _new_root_items: list[QtGui.QStandardItem] = field(default_factory=list)
    _descendants_to_update: dict[str, list] = field(default_factory=dict)

    def set_items(
        self, new_items: list[QtGui.QStandardItem], to_remove: set[str]
    ) -> None:
        """Set new items and items to remove."""
        self._new_root_items = new_items
        self._root_items_to_remove = to_remove
        if new_items or to_remove:
            self.new_changes = True

    def set_process_state(self, process_hash: str, state: int) -> None:
        """Change status of process."""
        self._states_to_set[process_hash] = state
        self.new_changes = True

    def set_descendants(
        self, process_hash: str, descendants: list[ProcessInfo]
    ) -> None:
        self._descendants_to_update[process_hash] = descendants
        self.new_changes = True

    def pop(self) -> tuple[
        list[QtGui.QStandardItem],
        set[str],
        dict[str, list[ProcessInfo]],
        dict[str, int],
    ]:
        self._new_root_items, items = [], self._new_root_items
        self._root_items_to_remove, to_remove = (
            set(), self._root_items_to_remove
        )
        self._descendants_to_update, descendants_to_update = (
            {}, self._descendants_to_update
        )
        self._states_to_set, states_to_set = {}, self._states_to_set
        return items, to_remove, descendants_to_update, states_to_set

set_items(new_items, to_remove)

Set new items and items to remove.

Source code in client/ayon_applications/ui/process_monitor.py
252
253
254
255
256
257
258
259
def set_items(
    self, new_items: list[QtGui.QStandardItem], to_remove: set[str]
) -> None:
    """Set new items and items to remove."""
    self._new_root_items = new_items
    self._root_items_to_remove = to_remove
    if new_items or to_remove:
        self.new_changes = True

set_process_state(process_hash, state)

Change status of process.

Source code in client/ayon_applications/ui/process_monitor.py
261
262
263
264
def set_process_state(self, process_hash: str, state: int) -> None:
    """Change status of process."""
    self._states_to_set[process_hash] = state
    self.new_changes = True

main()

Helper function to debug the tool.

Source code in client/ayon_applications/ui/process_monitor.py
1328
1329
1330
1331
1332
1333
1334
1335
def main() -> None:
    """Helper function to debug the tool."""
    app = get_ayon_qt_app()

    window = ProcessMonitorWindow()
    window.show()

    app.exec_()