-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathSystem Monitor UI.py
More file actions
1342 lines (1157 loc) · 53.4 KB
/
System Monitor UI.py
File metadata and controls
1342 lines (1157 loc) · 53.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import random
from dataclasses import dataclass, asdict
from collections.abc import Callable
import Py4GW
import PyImGui
import Py4GW.UI as UI
from Py4GWCoreLib.py4gwcorelib_src.Timer import ThrottledTimer
from Py4GWCoreLib.py4gwcorelib_src.Color import Color, ColorPalette
MODULE_NAME = "System Monitor UI"
MODULE_ICON = "Textures/Module_Icons/Monitor Diagnostic.png"
update_throttle = ThrottledTimer(1000) # Throttle updates to at most once per second
_ui_main = UI.UI()
_ui_detail = UI.UI()
_ui_initialized = False
_ui_usage_rows: list[dict] = []
_ui_stack_click_map: dict[str, str] = {}
_ui_row_click_map: dict[str, str] = {}
_ui_summary_text = ""
_ui_filtered_text = ""
_ui_groups_note = (
"Grouped by normalized entry (display_token), sorted by included usage total. "
"Only source avg totals are shown here; percentiles remain in tooltip/details."
)
@dataclass
class ParsedMetricName:
"""Normalized representation of a profiler metric name.
The profiler emits one metric schema with multiple naming patterns:
pure dotted names (e.g. `Draw.Callback.Data.SharedMemory.Update`) and
dotted prefixes followed by path-like script names (e.g.
`Main.Callback.Update.Guild Wars\\Items & Loot/InventoryPlus.py`).
This dataclass stores both the raw tokenization and semantic fields used for
grouping (`phase`, `subject_token`, `operation_token`, `display_token`).
"""
raw_name: str
dot_tokens: list[str]
hierarchy_tokens: list[str]
semantic_hierarchy_tokens: list[str]
path_tokens: list[str]
path_tail_tokens: list[str]
all_tokens: list[str]
phase: str
dot_prefix_tokens: list[str]
path_tail: str
is_path_metric: bool
script_path: str
script_name: str
script_like: str
leaf_token: str
operation_token: str
subject_token: str
display_token: str
def to_dict(self) -> dict:
"""Return the parsed record as a plain dictionary."""
return asdict(self)
class ProfilerMetricNameCatalog:
"""Encapsulate profiler metric-name fetching, parsing, indexing, and lookup.
The class is designed to be portable: a caller can use it without relying on
any UI helpers. It can ingest data from either live Py4GW profiler metrics or
pasted console output, parse the naming patterns, and expose indexed/grouped
access to the normalized results.
Typical usage:
catalog = ProfilerMetricNameCatalog()
catalog.refresh_from_live()
# or catalog.load_console_dump(text)
rows = catalog.items
grouped = catalog.group_by_attr("subject_token")
"""
_METRIC_LINE_RE = re.compile(
r"""
^.*?\[print:\]\s*
(?P<name>.+?)
:\s+Min=
""",
re.VERBOSE,
)
_GENERIC_OPERATION_LEAVES = {
"update",
"draw",
"main",
"total",
"updateptr",
"updatecache",
}
def __init__(self) -> None:
"""Create an empty catalog with no loaded data and no indexes."""
self.raw_names: list[str] = []
self.items: list[ParsedMetricName] = []
self.stats_by_raw_name: dict[str, dict[str, float]] = {}
self.history_by_raw_name: dict[str, list[float]] = {}
self.by_raw_name: dict[str, ParsedMetricName] = {}
self.by_phase: dict[str, list[ParsedMetricName]] = {}
self.by_subject: dict[str, list[ParsedMetricName]] = {}
self.by_display: dict[str, list[ParsedMetricName]] = {}
self.by_script_path: dict[str, list[ParsedMetricName]] = {}
self.by_script_name: dict[str, list[ParsedMetricName]] = {}
self.by_operation: dict[str, list[ParsedMetricName]] = {}
self.by_semantic_key: dict[tuple[str, ...], list[ParsedMetricName]] = {}
def clear(self) -> None:
"""Remove loaded names, parsed items, and all indexes."""
self.raw_names.clear()
self.items.clear()
self.stats_by_raw_name.clear()
self.history_by_raw_name.clear()
self.by_raw_name.clear()
self.by_phase.clear()
self.by_subject.clear()
self.by_display.clear()
self.by_script_path.clear()
self.by_script_name.clear()
self.by_operation.clear()
self.by_semantic_key.clear()
def extract_metric_name_from_console_line(self, line: str) -> str | None:
"""Extract a raw metric name from a console print line.
Args:
line: Console output line that may contain a profiler metric print.
Returns:
The metric name if the line matches the profiler print format,
otherwise `None`.
"""
match = self._METRIC_LINE_RE.match(line.strip())
if not match:
return None
return match.group("name").strip()
def parse_name(self, name: str) -> ParsedMetricName:
"""Parse a single raw profiler metric name into semantic tokens.
Naming rules handled here:
- Common leading categories split by `.` (phase, callback buckets, etc.)
- Optional path-like tail split by `/` or `\\`
- Path metrics preserve full path (`script_path`) but expose a compact
filename leaf (`script_name`) for display
- Generic trailing operation markers (`Update`, `Draw`, `UpdatePtr`, ...)
are recognized so grouping can prefer the measured subject instead
Args:
name: Raw profiler metric name.
Returns:
ParsedMetricName: Normalized parsed representation.
"""
raw = name.strip()
dot_tokens = [t for t in raw.split(".") if t]
phase = dot_tokens[0] if dot_tokens else ""
path_start_idx = -1
for i, token in enumerate(dot_tokens):
if "/" in token or "\\" in token:
path_start_idx = i
break
is_path_metric = path_start_idx >= 0
if is_path_metric:
dot_prefix_tokens = dot_tokens[:path_start_idx]
path_tail = ".".join(dot_tokens[path_start_idx:])
else:
dot_prefix_tokens = dot_tokens[:-1] if len(dot_tokens) > 1 else []
path_tail = dot_tokens[-1] if dot_tokens else raw
path_tail_tokens = [t for t in re.split(r"[\\/]+", path_tail) if t]
path_tokens = [t for t in re.split(r"[\\/]+", raw) if t]
hierarchy_tokens = (dot_prefix_tokens + path_tail_tokens) if is_path_metric else list(dot_tokens)
all_tokens = [t for t in re.split(r"[./\\\\]+", raw) if t]
leaf_token = path_tail_tokens[-1] if (is_path_metric and path_tail_tokens) else (dot_tokens[-1] if dot_tokens else raw)
if is_path_metric:
script_like = path_tail
elif len(dot_tokens) >= 2:
script_like = dot_tokens[-2]
else:
script_like = leaf_token
script_path = path_tail if is_path_metric else ""
script_name = path_tail_tokens[-1] if (is_path_metric and path_tail_tokens) else script_like
operation_token = leaf_token
subject_token = script_name if is_path_metric else script_like
leaf_is_generic_operation = operation_token.lower() in self._GENERIC_OPERATION_LEAVES
if is_path_metric:
display_token = script_name
elif leaf_is_generic_operation:
display_token = subject_token
else:
display_token = leaf_token
semantic_hierarchy_tokens = list(hierarchy_tokens)
if semantic_hierarchy_tokens:
if is_path_metric:
semantic_hierarchy_tokens[-1] = script_name
elif leaf_is_generic_operation and len(semantic_hierarchy_tokens) >= 2:
semantic_hierarchy_tokens = semantic_hierarchy_tokens[:-1]
return ParsedMetricName(
raw_name=raw,
dot_tokens=dot_tokens,
hierarchy_tokens=hierarchy_tokens,
semantic_hierarchy_tokens=semantic_hierarchy_tokens,
path_tokens=path_tokens,
path_tail_tokens=path_tail_tokens,
all_tokens=all_tokens,
phase=phase,
dot_prefix_tokens=dot_prefix_tokens,
path_tail=path_tail,
is_path_metric=is_path_metric,
script_path=script_path,
script_name=script_name,
script_like=script_like,
leaf_token=leaf_token,
operation_token=operation_token,
subject_token=subject_token,
display_token=display_token,
)
def load_names(self, names: list[str]) -> list[ParsedMetricName]:
"""Load and parse raw metric names, replacing the catalog contents.
Args:
names: List of raw metric names.
Returns:
Parsed records in the same order as the input (after trimming empty
entries).
"""
self.clear()
self.raw_names = [n.strip() for n in names if n and n.strip()]
self.items = [self.parse_name(name) for name in self.raw_names]
self._rebuild_indexes()
return self.items
def load_console_dump(self, text: str) -> list[ParsedMetricName]:
"""Parse profiler metric names from pasted console output and store them.
Args:
text: Multiline console dump containing `[print:] ...: Min=...` rows.
Returns:
Parsed metric-name records extracted from the dump.
"""
names: list[str] = []
for line in text.splitlines():
name = self.extract_metric_name_from_console_line(line)
if name:
names.append(name)
return self.load_names(names)
def get_live_metric_names(self) -> list[str]:
"""Fetch live profiler metric names from Py4GW if available.
Returns:
List of raw metric names. Returns an empty list when Py4GW is not
available or the call fails.
"""
if Py4GW is None:
return []
try:
return list(Py4GW.Console.get_profiler_metric_names())
except Exception:
return []
def get_live_profiler_reports(self) -> list[tuple]:
"""Fetch live profiler report rows from Py4GW if available.
Returns:
A list of report tuples in the format expected from
`Py4GW.Console.get_profiler_reports()`, or an empty list on failure.
"""
if Py4GW is None:
return []
try:
return list(Py4GW.Console.get_profiler_reports())
except Exception:
return []
def refresh_from_live(self) -> list[ParsedMetricName]:
"""Fetch live metric names from Py4GW, parse them, and rebuild indexes.
Returns:
Parsed metric-name records for the live profiler set.
"""
parsed = self.load_names(self.get_live_metric_names())
self._load_stats_from_reports(self.get_live_profiler_reports())
return parsed
def get_live_profiler_history(self, name: str) -> list[float]:
"""Fetch a profiler history trace for a metric from Py4GW, if available."""
if Py4GW is None:
return []
try:
return [float(v) for v in Py4GW.Console.get_profiler_history(name)]
except Exception:
return []
def has_usage_stats(self) -> bool:
"""Return `True` when live profiler timing stats are available."""
return bool(self.stats_by_raw_name)
def clear_usage_stats(self) -> None:
"""Clear cached profiler timing stats while keeping parsed names/indexes."""
self.stats_by_raw_name.clear()
self.history_by_raw_name.clear()
Py4GW.Console.clear_profiler_history()
def get_stats(self, raw_name: str) -> dict[str, float] | None:
"""Return timing stats for a raw metric name, if available."""
return self.stats_by_raw_name.get(raw_name)
def get_history(self, raw_name: str, refresh: bool = False) -> list[float]:
"""Return cached profiler history for a raw metric name, optionally refreshing."""
if not refresh and raw_name in self.history_by_raw_name:
return self.history_by_raw_name[raw_name]
hist = self.get_live_profiler_history(raw_name)
self.history_by_raw_name[raw_name] = hist
return hist
def get(self, raw_name: str) -> ParsedMetricName | None:
"""Return the parsed record for an exact raw metric name, if present."""
return self.by_raw_name.get(raw_name)
def filter(self, predicate: Callable[[ParsedMetricName], bool]) -> list[ParsedMetricName]:
"""Return parsed items matching a predicate.
Args:
predicate: Function that receives a parsed record and returns `True`
when the record should be included.
Returns:
Matching parsed records.
"""
return [item for item in self.items if predicate(item)]
def filter_text(self, needle: str) -> list[ParsedMetricName]:
"""Return parsed items whose normalized fields contain a text fragment.
Args:
needle: Case-insensitive substring matched against raw name, phase,
display token, subject token, script path/name, and all tokens.
Returns:
Matching parsed records. Empty `needle` returns all items.
"""
if not needle:
return list(self.items)
n = needle.lower()
return self.filter(
lambda item: (
n in item.raw_name.lower()
or n in item.phase.lower()
or n in item.display_token.lower()
or n in item.subject_token.lower()
or n in item.script_name.lower()
or n in item.script_path.lower()
or any(n in tok.lower() for tok in item.all_tokens)
)
)
def group_by_attr(self, attr_name: str) -> dict[str, list[ParsedMetricName]]:
"""Group records by any attribute on `ParsedMetricName`.
Args:
attr_name: Name of a `ParsedMetricName` attribute (for example
`phase`, `subject_token`, `operation_token`, `script_path`).
Returns:
Mapping from attribute value (as string) to matching records.
"""
grouped: dict[str, list[ParsedMetricName]] = {}
for item in self.items:
value = getattr(item, attr_name, "")
grouped.setdefault(str(value), []).append(item)
return grouped
def group_by_semantic_prefix(self, depth: int) -> dict[tuple[str, ...], list[ParsedMetricName]]:
"""Group records by a prefix of `semantic_hierarchy_tokens`.
Args:
depth: Number of semantic hierarchy tokens to keep in the grouping
key. `0` groups all records together.
Returns:
Mapping from semantic token tuple prefix to matching records.
"""
depth = max(0, depth)
grouped: dict[tuple[str, ...], list[ParsedMetricName]] = {}
for item in self.items:
key = tuple(item.semantic_hierarchy_tokens[:depth])
grouped.setdefault(key, []).append(item)
return grouped
def summary_counts(self) -> dict[str, int]:
"""Return lightweight diagnostics about the loaded catalog.
Returns:
Counts for total records and distinct keys in core indexes.
"""
return {
"items": len(self.items),
"phases": len(self.by_phase),
"subjects": len(self.by_subject),
"displays": len(self.by_display),
"script_paths": len(self.by_script_path),
"script_names": len(self.by_script_name),
"operations": len(self.by_operation),
"semantic_keys": len(self.by_semantic_key),
}
def print_sample(self, limit: int = 20) -> None:
"""Print a sample of parsed records for manual verification.
Args:
limit: Maximum number of parsed records to print.
"""
for idx, item in enumerate(self.items[:limit], start=1):
print(f"[{idx}] {item.raw_name}")
print(f" phase : {item.phase}")
print(f" script_path : {item.script_path}")
print(f" script_name : {item.script_name}")
print(f" subject : {item.subject_token}")
print(f" operation : {item.operation_token}")
print(f" display : {item.display_token}")
print(f" semantic : {item.semantic_hierarchy_tokens}")
stats = self.stats_by_raw_name.get(item.raw_name)
if stats:
print(f" avg : {stats['avg']:.4f}ms")
if len(self.items) > limit:
print(f"... ({len(self.items) - limit} more)")
def build_usage_groups_by_display(
self,
items: list[ParsedMetricName] | None = None,
include_phases: set[str] | None = None,
) -> list[dict]:
"""Aggregate usage stats by normalized display token (leaf/entity label).
A single display group may contain metrics from multiple phases
(`Draw`, `Main`, `Update`). This method aggregates those phase-specific
average timings and returns rows sorted by the selected-phase total.
Args:
items: Optional subset of parsed items to aggregate. If omitted, all
catalog items are used.
include_phases: Optional phase filter controlling which phases
contribute to `selected_total_avg`. If omitted, `Draw`, `Main`,
and `Update` are all included.
Returns:
list[dict]: Aggregated usage rows with phase totals, member records,
and sort-ready totals.
"""
source_items = self.items if items is None else items
selected_phases = include_phases or {"Draw", "Main", "Update"}
grouped: dict[str, dict] = {}
for item in source_items:
row = grouped.get(item.display_token)
if row is None:
row = {
"display": item.display_token,
"subjects": set(),
"script_paths": set(),
"members": [],
"phase_stats": {
"Draw": {"min": 0.0, "avg": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0, "max": 0.0},
"Main": {"min": 0.0, "avg": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0, "max": 0.0},
"Update": {"min": 0.0, "avg": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0, "max": 0.0},
},
"selected_stats": {"min": 0.0, "avg": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0, "max": 0.0},
"all_stats": {"min": 0.0, "avg": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0, "max": 0.0},
}
grouped[item.display_token] = row
row["subjects"].add(item.subject_token)
if item.script_path:
row["script_paths"].add(item.script_path)
row["members"].append(item)
stats = self.stats_by_raw_name.get(item.raw_name)
if not stats:
continue
phase_key = item.phase if item.phase in ("Draw", "Main", "Update") else None
for metric_key in ("min", "avg", "p50", "p95", "p99", "max"):
value = stats[metric_key]
row["all_stats"][metric_key] += value
if item.phase in selected_phases:
row["selected_stats"][metric_key] += value
if phase_key is not None:
row["phase_stats"][phase_key][metric_key] += value
rows = list(grouped.values())
for row in rows:
row["subjects"] = sorted(row["subjects"])
row["script_paths"] = sorted(row["script_paths"])
row["members"].sort(
key=lambda m: self.stats_by_raw_name.get(m.raw_name, {}).get("avg", 0.0),
reverse=True,
)
rows.sort(key=lambda r: r["selected_stats"]["avg"], reverse=True)
return rows
def _load_stats_from_reports(self, reports: list[tuple]) -> None:
"""Load timing stats from profiler reports into a raw-name lookup map."""
self.stats_by_raw_name = {}
for row in reports:
try:
name, min_time, avg_time, p50, p95, p99, max_time = row
except Exception:
continue
self.stats_by_raw_name[str(name)] = {
"min": float(min_time),
"avg": float(avg_time),
"p50": float(p50),
"p95": float(p95),
"p99": float(p99),
"max": float(max_time),
}
def _rebuild_indexes(self) -> None:
"""Rebuild all lookup indexes from the current `items` list."""
self.by_raw_name = {item.raw_name: item for item in self.items}
self.by_phase = {}
self.by_subject = {}
self.by_display = {}
self.by_script_path = {}
self.by_script_name = {}
self.by_operation = {}
self.by_semantic_key = {}
for item in self.items:
self.by_phase.setdefault(item.phase, []).append(item)
self.by_subject.setdefault(item.subject_token, []).append(item)
self.by_display.setdefault(item.display_token, []).append(item)
if item.script_path:
self.by_script_path.setdefault(item.script_path, []).append(item)
self.by_script_name.setdefault(item.script_name, []).append(item)
self.by_operation.setdefault(item.operation_token, []).append(item)
self.by_semantic_key.setdefault(tuple(item.semantic_hierarchy_tokens), []).append(item)
# Lightweight viewer state (optional UI built on top of the catalog).
_initialized = False
_catalog = ProfilerMetricNameCatalog()
_ui_filter_text = ""
_ui_show_details = False
_ui_max_rows = 15
_ui_include_draw = True
_ui_include_main = True
_ui_include_update = True
_ui_selected_entry = ""
_ui_show_selected_window = True
_history_seconds_per_sample = 0.1
_history_tick_seconds = 5.0
_ui_entry_color_map: dict[str, str] = {}
_ui_palette_order: list[str] = []
def _ensure_loaded() -> None:
"""Initialize the viewer cache once from live metrics."""
global _initialized
if _initialized:
return
_initialized = True
_catalog.refresh_from_live()
def _auto_refresh_if_needed() -> None:
"""Refresh the shared catalog at most once per second using the throttle."""
if update_throttle.IsExpired():
_catalog.refresh_from_live()
update_throttle.Reset()
def _entry_palette_names() -> list[str]:
"""Return a randomized full-palette order using every ColorPalette entry."""
global _ui_palette_order
if _ui_palette_order:
return list(_ui_palette_order)
_ui_palette_order = [n.lower() for n in ColorPalette.ListColors()]
random.shuffle(_ui_palette_order)
return list(_ui_palette_order)
def _c4(name: str, alpha: float | None = None) -> tuple[float, float, float, float]:
"""Return a normalized color tuple from ColorPalette, optionally overriding alpha."""
c = ColorPalette.GetColor(name).copy()
if alpha is not None:
c = c.opacity(alpha)
return c.to_tuple_normalized()
def _c32(name: str, alpha: float | None = None) -> int:
"""Return packed ABGR color from ColorPalette, optionally overriding alpha."""
c = ColorPalette.GetColor(name).copy()
if alpha is not None:
c = c.opacity(alpha)
return c.to_color()
def _u32(color: int) -> int:
"""Normalize Python int color to unsigned ImU32 range for draw-list APIs."""
return int(color) & 0xFFFFFFFF
def _i32_color(color: int) -> int:
"""Convert color bits to signed 32-bit int for bindings that expose `int`."""
v = int(color) & 0xFFFFFFFF
return v if v <= 0x7FFFFFFF else v - 0x100000000
def _entry_color_name(key: str) -> str:
"""Deterministically map an entry label to a palette color name."""
mapped = _ui_entry_color_map.get(key)
if mapped:
return mapped
names = _entry_palette_names()
if not names:
return "dodger_blue"
h = 0
for ch in key:
h = (h * 131 + ord(ch)) & 0xFFFFFFFF
return names[h % len(names)]
def _entry_color4(key: str) -> tuple[float, float, float, float]:
"""Normalized color for a grouped entry, consistent across widgets."""
return _c4(_entry_color_name(key))
def _color_luminance(color_name: str) -> float:
"""Return perceptual luminance of a palette color (0..1)."""
c = ColorPalette.GetColor(color_name)
return (0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b) / 255.0
def _contrast_text_color32(fill_color_name: str) -> int:
"""Pick black/white text based on fill brightness."""
return _c32("black") if _color_luminance(fill_color_name) >= 0.60 else _c32("white")
def _reroll_entry_palette() -> None:
"""Randomize the full palette order again (uses every palette entry name)."""
global _ui_palette_order
_ui_palette_order = [n.lower() for n in ColorPalette.ListColors()]
random.shuffle(_ui_palette_order)
def _log_color_pool_and_assignments(rows: list[dict] | None = None) -> None:
"""Log all palette entries and current entry assignments (reuse diagnostics)."""
pool = _entry_palette_names()
print("=== Profiler UI Color Pool (full ColorPalette, randomized order) ===")
rgba_aliases: dict[tuple[int, int, int, int], list[str]] = {}
for i, name in enumerate(pool, start=1):
c = ColorPalette.GetColor(name)
rgba = c.to_tuple()
rgba_aliases.setdefault(rgba, []).append(name)
print(f"[{i:03d}] {name:<18} rgba={rgba} lum={_color_luminance(name):.3f}")
dup_alias_sets = [names for names in rgba_aliases.values() if len(names) > 1]
if dup_alias_sets:
print("=== Palette aliases sharing the same RGBA ===")
for names in dup_alias_sets:
print(" - " + ", ".join(names))
if rows is None:
return
print("=== Current Entry -> Color Assignment ===")
reverse: dict[str, list[str]] = {}
for row in rows:
display = str(row.get("display", ""))
if not display or display == "Others":
continue
color_name = _entry_color_name(display)
reverse.setdefault(color_name, []).append(display)
print(f"{display} -> {color_name}")
reused = {k: v for k, v in reverse.items() if len(v) > 1}
if reused:
print("=== Reused colors detected ===")
for color_name, displays in reused.items():
print(f"{color_name}: {', '.join(displays)}")
else:
print("No color reuse detected for visible entries.")
def _refresh_entry_color_assignments(rows: list[dict]) -> None:
"""Assign unique palette colors to visible rows before any reuse.
Colors are assigned in current row order (usually usage-descending), which
makes top consumers get the best visual distinction first.
"""
global _ui_entry_color_map
pool = _entry_palette_names()
if not pool:
_ui_entry_color_map = {}
return
new_map: dict[str, str] = {}
pool_len = len(pool)
for idx, row in enumerate(rows):
display = str(row.get("display", ""))
if not display or display == "Others":
continue
# Unique until pool exhaustion, then wrap.
new_map[display] = pool[idx % pool_len]
_ui_entry_color_map = new_map
def _phase_color_name(phase: str) -> str:
"""Map profiler phase names to palette color names."""
mapping = {
"Draw": "dodger_blue",
"Main": "gold",
"Update": "light_green",
}
return mapping.get(phase, "light_gray")
def _ui_draw_top_usage_stacked_bar(rows: list[dict]) -> str | None:
"""UI-native top usage stacked bar (no raw PyImGui draw calls)."""
global _ui_stack_click_map
_ui_stack_click_map = {}
if not rows:
return None
total_usage = sum(r["selected_stats"]["avg"] for r in rows)
if total_usage <= 0.0:
_ui_main.text("No usage totals available for stacked bar")
return None
_ui_main.get_content_region_avail("ui_stack_avail_w", "ui_stack_avail_h")
avail_w = float(_ui_main.vars("ui_stack_avail_w") or 0.0)
bar_w = max(220.0, avail_w)
bar_h = 22.0
_ui_main.get_cursor_screen_pos("ui_stack_start_x", "ui_stack_start_y")
start_x = float(_ui_main.vars("ui_stack_start_x") or 0.0)
start_y = float(_ui_main.vars("ui_stack_start_y") or 0.0)
_ui_main.text_colored("Usage Share", _c4("light_blue"))
_ui_main.same_line(0, -1)
_ui_main.text(f"(100% of included avg totals, frame total {total_usage:.3f}ms)")
_ui_main.dummy(float(int(bar_w)), float(int(bar_h)))
bg = _c32("gw_disabled")
border = _c32("dark_gray")
_ui_main.draw_list_add_rect_filled(
float(start_x),
float(start_y + 16),
float(start_x + bar_w),
float(start_y + 16 + bar_h),
_i32_color(bg),
0.0,
0,
)
_ui_main.draw_list_add_rect(start_x, start_y + 16, start_x + bar_w, start_y + 16 + bar_h, _i32_color(border), 0.0, 0, 1.5)
min_px = 14.0
visible_segments = []
others_rows = []
for row in rows:
width_px = (row["selected_stats"]["avg"] / total_usage) * bar_w
if width_px < min_px:
others_rows.append(row)
else:
visible_segments.append(row)
if others_rows:
others_total = sum(r["selected_stats"]["avg"] for r in others_rows)
visible_segments.append(
{
"display": "Others",
"selected_stats": {"avg": others_total},
"members": [m for r in others_rows for m in r["members"]],
"_others_rows": others_rows,
}
)
clicked_entry: str | None = None
offset = 0.0
inner_y1 = start_y + 17
inner_y2 = start_y + 16 + bar_h - 1
for idx, row in enumerate(visible_segments):
share = row["selected_stats"]["avg"] / total_usage
seg_w = (bar_w - offset) if idx == len(visible_segments) - 1 else max(1.0, share * bar_w)
x1 = start_x + offset
x2 = start_x + offset + seg_w
offset += seg_w
color_name = _entry_color_name(row["display"]) if row["display"] != "Others" else "dark_gray"
color = _c32(color_name)
_ui_main.draw_list_add_rect_filled(
float(x1),
float(inner_y1),
float(x2),
float(inner_y2),
1,
0.0,
0,
)
_ui_main.draw_list_add_rect(x1, inner_y1, x2, inner_y2, _i32_color(border), 0.0, 0, 1.0)
if seg_w > 60:
label = row["display"]
if len(label) > 18:
label = label[:15] + "..."
_ui_main.draw_list_add_text(x1 + 3, inner_y1 + 2, _i32_color(_contrast_text_color32(color_name)), label)
click_var = f"ui_stack_click_{idx}"
hover_var = f"ui_stack_hover_{idx}"
if _ui_main.vars(click_var) is None:
_ui_main.set_var(click_var, False)
if _ui_main.vars(hover_var) is None:
_ui_main.set_var(hover_var, False)
_ui_main.set_cursor_screen_pos(x1, inner_y1)
_ui_main.invisible_button(f"##usage_stack_{idx}", seg_w, max(1.0, inner_y2 - inner_y1), click_var)
if bool(_ui_main.vars(click_var)):
clicked_entry = "__others__" if row["display"] == "Others" else row["display"]
_ui_main.is_item_hovered(hover_var)
if bool(_ui_main.vars(hover_var)):
pct = share * 100.0
_ui_main.begin_tooltip()
_ui_main.text_colored(row["display"], _c4("gold"))
_ui_main.text(f"Included total avg: {row['selected_stats']['avg']:.3f}ms")
_ui_main.text(f"Usage share: {pct:.1f}%")
if row["display"] == "Others":
subrows = row.get("_others_rows", [])
_ui_main.separator()
_ui_main.text(f"Collapsed entries: {len(subrows)}")
for sub in subrows[:10]:
_ui_main.text(f" {sub['display']} ({sub['selected_stats']['avg']:.3f}ms)")
_ui_main.end_tooltip()
_ui_main.spacing()
return clicked_entry
def _ui_draw_usage_groups(rows: list[dict]) -> None:
"""UI-class rendering for usage-group table with source-parity structure."""
global _ui_row_click_map
_ui_row_click_map = {}
total_usage = sum(row["selected_stats"]["avg"] for row in rows)
flags = int(PyImGui.TableFlags.Borders | PyImGui.TableFlags.RowBg | PyImGui.TableFlags.SizingStretchProp)
_ui_main.begin_table("prof_usage_groups", 5, flags)
_ui_main.table_setup_column("Entry", int(PyImGui.TableColumnFlags.WidthStretch))
_ui_main.table_setup_column("Total", int(PyImGui.TableColumnFlags.WidthFixed), 100.0)
_ui_main.table_setup_column("% Usage", int(PyImGui.TableColumnFlags.WidthFixed), 70.0)
_ui_main.table_setup_column("Usage Bar", int(PyImGui.TableColumnFlags.WidthFixed), 140.0)
_ui_main.table_setup_column("Members", int(PyImGui.TableColumnFlags.WidthFixed), 60.0)
_ui_main.table_headers_row()
for idx, row in enumerate(rows[:_ui_max_rows]):
pct = (row["selected_stats"]["avg"] / total_usage) if total_usage > 0.0 else 0.0
click_var = f"ui_usage_row_click_{idx}"
hover_var = f"ui_usage_row_hover_{idx}"
_ui_row_click_map[click_var] = row["display"]
# Treat selectable var as per-frame click output.
_ui_main.set_var(click_var, False)
if _ui_main.vars(hover_var) is None:
_ui_main.set_var(hover_var, False)
_ui_main.table_next_row()
_ui_main.table_set_column_index(0)
_ui_main.selectable(
f"{row['display']}##usage_row",
click_var,
int(PyImGui.SelectableFlags.NoFlag),
0.0,
0.0,
)
_ui_main.is_item_hovered(hover_var)
if bool(_ui_main.vars(hover_var)):
_ui_main.begin_tooltip()
_ui_main.text_colored(row["display"], _c4("gold"))
_ui_main.text(f"Included total avg: {row['selected_stats']['avg']:.3f}ms")
_ui_main.text(f"Usage share: {pct * 100:.1f}%")
_ui_main.separator()
_ui_main.text(f"Subjects: {', '.join(row['subjects'][:6])}")
_ui_main.text(
f"Phase avgs: Draw={row['phase_stats']['Draw']['avg']:.3f} | "
f"Main={row['phase_stats']['Main']['avg']:.3f} | Update={row['phase_stats']['Update']['avg']:.3f}"
)
if row["script_paths"]:
_ui_main.text("Script paths:")
for sp in row["script_paths"][:6]:
_ui_main.text(f" {sp}")
_ui_main.separator()
_ui_main.text("Top members:")
for item in row["members"][:10]:
stats = _catalog.get_stats(item.raw_name)
if stats:
_ui_main.text(
f" {item.phase}: avg={stats['avg']:.3f} p50={stats['p50']:.3f} "
f"p95={stats['p95']:.3f} p99={stats['p99']:.3f} max={stats['max']:.3f}"
)
_ui_main.text(f" {item.raw_name}")
_ui_main.end_tooltip()
_ui_main.table_set_column_index(1)
_ui_main.text(f"{row['selected_stats']['avg']:.3f}")
_ui_main.table_set_column_index(2)
_ui_main.text(f"{pct * 100:.1f}%")
_ui_main.table_set_column_index(3)
_ui_main.push_style_color(int(PyImGui.ImGuiCol.PlotHistogram), _entry_color4(row["display"]))
_ui_main.push_style_color(int(PyImGui.ImGuiCol.FrameBg), _c4("gw_disabled"))
_ui_main.progress_bar(pct, -1.0, "")
_ui_main.pop_style_color(2)
_ui_main.table_set_column_index(4)
_ui_main.text(str(len(row["members"])))
_ui_main.end_table()
def _ui_draw_sparkline(
id_str: str,
values: list[float],
width: float = 0.0,
height: float = 42.0,
line_col: int | None = None,
fill_col: int | None = None,
) -> None:
"""Draw a simple sparkline/area chart using UI draw-list primitives."""
safe_id = re.sub(r"[^a-zA-Z0-9_]", "_", id_str)
avail_var_x = f"{safe_id}_avail_x"
avail_var_y = f"{safe_id}_avail_y"
cur_var_x = f"{safe_id}_cur_x"
cur_var_y = f"{safe_id}_cur_y"
hover_var = f"{safe_id}_hover"
txt_w_var = f"{safe_id}_txt_w"
txt_h_var = f"{safe_id}_txt_h"
_ui_detail.get_content_region_avail(avail_var_x, avail_var_y)
avail_w = float(_ui_detail.vars(avail_var_x) or 0.0)
w = max(120.0, avail_w if width <= 0 else width)
h = max(16.0, height)
_ui_detail.get_cursor_screen_pos(cur_var_x, cur_var_y)
x = float(_ui_detail.vars(cur_var_x) or 0.0)
y = float(_ui_detail.vars(cur_var_y) or 0.0)
_ui_detail.invisible_button(id_str, w, h)
draw_bg = _c32("gw_disabled")
draw_border = _c32("slate_gray")
draw_line = line_col if line_col is not None else _c32("dodger_blue")
draw_fill = fill_col if fill_col is not None else _c32("dark_blue", 0.22)
_ui_detail.draw_list_add_rect_filled(
float(x),
float(y),
float(x + w),
float(y + h),
_i32_color(draw_bg),
0.0,
0,
)
_ui_detail.draw_list_add_rect(x, y, x + w, y + h, _i32_color(draw_border), 0.0, 0, 1.0)
if not values:
return
if len(values) == 1:
yy = y + h * 0.5
_ui_detail.draw_list_add_line(x + 2, yy, x + w - 2, yy, _i32_color(draw_line), 2.0)
return
vmin = min(values)
vmax = max(values)
vrange = (vmax - vmin) if vmax > vmin else 1.0
inner_pad = 2.0
px_prev = x + inner_pad
py_prev = y + h - inner_pad - (((values[0] - vmin) / vrange) * (h - inner_pad * 2))
for i in range(1, len(values)):
t = i / (len(values) - 1)
px = x + inner_pad + t * (w - inner_pad * 2)
py = y + h - inner_pad - (((values[i] - vmin) / vrange) * (h - inner_pad * 2))
_ui_detail.draw_list_add_line(px_prev, py_prev, px, py, _i32_color(draw_line), 1.5)