Repository navigation
Expand file tree
/
Copy pathRegistryBase.py
More file actions
2138 lines (1942 loc) · 79.1 KB
/
Copy pathRegistryBase.py
File metadata and controls
2138 lines (1942 loc) · 79.1 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
'''Info Header Start
Name : RegistryBase
Author : Dan@DAN-4090
Saveorigin : FNSTools_PRIV.toe
Saveversion : 2025.33070
Info Header End'''
CustomParHelper: CustomParHelper = (next((d for d in me.docked if 'ExtUtils' in d.tags), None) or next((c for c in me.parent().children if 'ExtUtils' in c.tags), None)).mod('CustomParHelper').CustomParHelper # import
###
from TDStoreTools import StorageManager
class _RegistryToolPageMixin:
"""The tool-facing 'Registry' page: bound proxy pars on the parent tool,
bind repair, and the host-cloning contract attrs (CLONE_EXPR)."""
# --- tool-facing 'Registry' page (bound proxy pars on the parent tool) ---
TOOL_PAGE_NAME = 'Registry'
TOOL_PAGE_PREFIX = None # subclass sets a short unique prefix, e.g. 'Tb'
TOOL_PAGE_LABEL = None # section header label; defaults to REGISTRY_NAME
TOOL_PAGE_PARS = () # host Registration par names to proxy
# In-project host cloning. Subclasses set the guarded clone expression
# hosts carry; masters are depth-1 packages of the toolkit root, so it
# resolves through the root's FNS shortcut --
# CLONE_EXPR = "op.FNS.op('XRegistry') if hasattr(op, 'FNS') else None"
# With it set, the base provides _healHostClones and StampHost.
CLONE_EXPR = None
def _ensureToolRegistryPage(self):
"""Standardized 'Registry' page on the host's PARENT tool: key
Registration pars mirrored onto the tool, so registration is
configured on the tool itself without opening the host. The TOOL
pars are the bind MASTERS -- they hold and persist the values with
the tool -- and the host's Registration pars BIND to them, following
whatever the tool ships with. Prefixed par names let multiple
registries (toolbar + navbar) share the one page. Created
programmatically on every successful registration -- the whole fleet
standardizes itself, and drop-to-register stamps inherit it with
zero per-tool work."""
if not self.TOOL_PAGE_PREFIX or not self.TOOL_PAGE_PARS:
return
if self._is_sys_global() or self._isUnderSysOrUi():
return
# A depth-1 RAW MASTER never proxies Registration pars onto its
# parent: that parent is the toolkit root, and decorating it
# re-creates the per-tool par surface the restructure removed
# (observed as dangling Cf* binds after every reload).
parent = self.ownerComp.parent()
if parent is not None and parent is getattr(op, 'FNS', None):
return
# Opt-out for shippers: Promotepars off = no proxy page on the tool
# (and an existing section is withdrawn). Missing par = on.
if not self._parBool('Promotepars', True):
self._removeToolRegistryPage()
return
tool = self.ownerComp.parent()
if tool is None or not tool.valid or tool.path == '/':
return
page = next((pg for pg in tool.customPages if pg.name == self.TOOL_PAGE_NAME), None)
if page is None:
page = tool.appendCustomPage(self.TOOL_PAGE_NAME)
self._orderToolRegistryPage(tool)
# A Page is an index: after the sort the object above names whatever
# page now sits at its old slot (About, on a tool that had one), and
# every append below landed there (TDCollab, 2026-10-13). Look it up
# by name again.
page = next((pg for pg in tool.customPages if pg.name == self.TOOL_PAGE_NAME), page)
head_name = self.TOOL_PAGE_PREFIX + 'section'
hpar = getattr(tool.par, head_name, None)
if hpar is None:
page.appendHeader(head_name,
label=self.TOOL_PAGE_LABEL or self.REGISTRY_NAME)
else:
self._reclaimToolPar(hpar, page)
appenders = {'Toggle': page.appendToggle, 'Pulse': page.appendPulse,
'Str': page.appendStr, 'Int': page.appendInt,
'Float': page.appendFloat, 'Menu': page.appendMenu}
for name in self._toolPageParNames():
src = getattr(self.ownerComp.par, name, None)
if src is None:
continue
tname = self.TOOL_PAGE_PREFIX + name.lower()
# host value BEFORE any bind changes -- it seeds a fresh tool par
try:
cur = src.eval() if src.style != 'Pulse' else None
except Exception:
cur = None
tpar = getattr(tool.par, tname, None)
if tpar is not None:
self._reclaimToolPar(tpar, page)
if tpar is None:
append = appenders.get(src.style)
if append is None:
continue
try:
tpar = append(tname, label=src.label)[0]
except Exception as e:
debug(f'{self.REGISTRY_NAME}: tool page par {tname}: {e}')
continue
tpar.help = src.help
if src.style == 'Menu':
tpar.menuNames = src.menuNames
tpar.menuLabels = src.menuLabels
if src.style in ('Int', 'Float'):
tpar.normMin, tpar.normMax = src.normMin, src.normMax
if src.readOnly:
tpar.readOnly = True
try:
tpar.default = src.default
except Exception:
pass
if cur is not None:
tpar.val = cur
elif tpar.mode == ParMode.BIND:
# migrate from the earlier (reversed) direction: the tool par
# becomes the master, seeded with the live value
try:
tpar.mode = ParMode.CONSTANT
if cur is not None:
tpar.val = cur
except Exception:
pass
# keep presentation in sync with the host par -- labels were once
# copied only at creation, so a corrected host label never reached
# the tools that had already been promoted
try:
if tpar.label != src.label:
tpar.label = src.label
if tpar.help != src.help:
tpar.help = src.help
except Exception:
pass
# the HOST par follows the tool par
try:
expr = f"parent().par.{tname}"
if src.bindExpr != expr or src.mode != ParMode.BIND:
src.bindExpr = expr
src.mode = ParMode.BIND
except Exception as e:
debug(f'{self.REGISTRY_NAME}: host bind {name}: {e}')
self._orderToolSection(tool)
def _reclaimToolPar(self, tpar, page):
"""Move a section par back onto the Registry page. TD relocates a
destroyed page's pars onto another page instead of destroying them,
so after any page churn our pars can be stranded on About/Version
Ctrl -- ensure() heals that instead of skipping them as 'existing'."""
try:
if tpar.page != page:
tpar.page = page
except Exception as e:
debug(f'{self.REGISTRY_NAME}: reclaim {tpar.name}: {e}')
def _toolPageParNames(self):
"""TOOL_PAGE_PARS with Unregister slotted in beside Register.
Deliberately NOT added to each subclass's tuple: the registry ext file
is copied per tool (~15 of them on disk), while RegistryBase is synced
from ONE shared file by 100 of the 102 live hosts. Adding it here is a
single edit that reaches the whole fleet. Slotted next to Register
rather than appended so _orderToolSection puts the two buttons side by
side instead of stranding Unregister at the end of the section.
"""
names = list(self.TOOL_PAGE_PARS)
if self.UNREGISTER_PAR in names or 'Register' not in names:
return names
names.insert(names.index('Register') + 1, self.UNREGISTER_PAR)
return names
def _sectionParNames(self):
return ([self.TOOL_PAGE_PREFIX + 'section'] +
[self.TOOL_PAGE_PREFIX + n.lower() for n in self._toolPageParNames()])
def _orderToolSection(self, tool):
"""Keep this registry's section contiguous and in declared order on
the Registry page (reclaimed strays land wherever TD appends them)."""
try:
ours = [getattr(tool.par, n, None) for n in self._sectionParNames()]
ours = [p for p in ours if p is not None]
orders = [p.order for p in ours]
if len(ours) < 2 or orders == sorted(orders):
return
base = min(orders)
for i, p in enumerate(ours):
p.order = base + i * 0.001
except Exception as e:
debug(f'{self.REGISTRY_NAME}: section ordering: {e}')
# meta pages the Registry page must come BEFORE
TOOL_PAGE_BEFORE = ('About', 'Common', 'Version Ctrl')
def _orderToolRegistryPage(self, tool):
"""Keep the Registry page ahead of the meta pages: the tool's own
pages first, then Registry, then About / Common / Version Ctrl."""
try:
names = [pg.name for pg in tool.customPages]
if self.TOOL_PAGE_NAME not in names:
return
metas = [n for n in names if n in self.TOOL_PAGE_BEFORE]
rest = [n for n in names
if n != self.TOOL_PAGE_NAME and n not in self.TOOL_PAGE_BEFORE]
desired = rest + [self.TOOL_PAGE_NAME] + metas
if names != desired and hasattr(tool, 'sortCustomPages'):
tool.sortCustomPages(*desired)
except Exception as e:
debug(f'{self.REGISTRY_NAME}: Registry page ordering: {e}')
def onParPromotepars(self, _par, _val, _prev):
"""Toggle the tool-facing Registry page on the fly. Turning it off
unbinds the host pars first (their masters are about to go away)."""
ext = self._hostExtFromPar(_par)
if ext._parBool('Promotepars', True):
ext._ensureToolRegistryPage()
else:
for pg in ext.ownerComp.customPages:
if pg.name != ext.HOST_PAGE_NAME:
continue
for p in pg.pars:
try:
if p.mode == ParMode.BIND:
p.mode = ParMode.CONSTANT
except Exception:
pass
ext._removeToolRegistryPage()
def _repairDanglingHostBinds(self):
"""Registration pars bound to a tool Registry page that no longer
exists (page removed, host copied somewhere without one) raise on
every eval and would kill extension init. Fall back to CONSTANT --
the par's constant slot still holds its pre-bind value."""
page = next((pg for pg in self.ownerComp.customPages
if pg.name == self.HOST_PAGE_NAME), None)
if page is None:
return
for p in page.pars:
try:
if p.mode != ParMode.BIND:
continue
master = None
try:
master = p.bindMaster
except Exception:
master = None
if master is None:
p.mode = ParMode.CONSTANT
continue
if p.style != 'Pulse':
p.eval()
except Exception:
try:
p.mode = ParMode.CONSTANT
except Exception:
pass
def _removeToolRegistryPage(self):
"""Drop this registry's section from the tool's Registry page (and
the page itself once no section remains)."""
if not self.TOOL_PAGE_PREFIX:
return
tool = self.ownerComp.parent()
if tool is None or not tool.valid:
return
# destroy by exact name wherever the pars sit -- page churn can have
# stranded them on another page (TD relocates, never destroys, the
# pars of a destroyed page)
for pname in self._sectionParNames():
p = getattr(tool.par, pname, None)
if p is not None:
try:
p.destroy()
except Exception:
pass
for page in list(tool.customPages):
if page.name == self.TOOL_PAGE_NAME and not list(page.pars):
try:
page.destroy()
except Exception:
pass
class _RegistryHostMixin:
"""Host auto-registration: the Registration page, register/unregister,
status, and the host-side parameter surface."""
# --- host auto-registration (Registration page) ---
def _isUnderSysOrUi(self):
path = self.ownerComp.path
return path == '/sys' or path.startswith('/sys/') or path == '/ui' or path.startswith('/ui/')
def _hostComp(self):
"""COMP to register as the pane owner. Defaults to parent (..)."""
comp_par = getattr(self.ownerComp.par, 'Comp', None)
if comp_par is None:
# Back-compat with older Panel parameter name.
comp_par = getattr(self.ownerComp.par, 'Panel', None)
if comp_par is not None:
comp = comp_par.eval()
if comp:
return comp
parent = self.ownerComp.parent()
if parent and parent.path not in ('/',):
return parent
return None
def _isAutoRegister(self):
if hasattr(self.ownerComp.par, 'Autoregister'):
return bool(self.ownerComp.par.Autoregister.eval())
return False
def _parBool(self, name, default=False):
if hasattr(self.ownerComp.par, name):
return bool(getattr(self.ownerComp.par, name).eval())
return default
def _hostRecallFlags(self):
"""Orthogonal recall flags from the Registration page."""
return {
'set_owner': self._parBool('Setowner', True),
'change_type': self._parBool('Changetype', True),
'maximize': self._parBool('Maximize', False),
'tear_away': self._parBool('Tearaway', False),
'float': self._parBool('Float', False),
'open_parameters': self._parBool('Openparameters', False),
}
def _hostCallbackDat(self):
if hasattr(self.ownerComp.par, 'Callback'):
cb = self.ownerComp.par.Callback.eval()
if cb is not None:
return cb
return None
def _hostCanonicalName(self):
name = ''
if hasattr(self.ownerComp.par, 'Canonicalname'):
name = str(self.ownerComp.par.Canonicalname.eval() or '').strip()
if name:
return name
host = self._hostComp()
return host.name if host else ''
# The docs site. MUST match build_manifest.DOCS_SITE: packaging derives
# the manifest's help_url with the same rule, and the two cannot import
# each other (this ships inside tools; that runs at release). Change
# both or neither.
HELP_SITE = 'https://functionstore.tools/docs'
def _packageHelpUrl(self, comp):
"""The docs page for the package enclosing `comp`, or ''.
The manifest's landed rule (build_manifest._helpUrl, measured
2026-08-26: derivation from the package name did 100% of the work
fleet-wide): FNS_About.Helpurl on the package is the ONE override,
else derive HELP_SITE/<name lowercased, _ -> ->/. Shipped tools
derive unconditionally -- the site build refuses a catalogued
package without a docs page, so every shipped package has one."""
pkg = self._enclosingPackage(comp)
if pkg is None:
return ''
fa = pkg.op('FNS_About')
if fa is not None:
p = getattr(fa.par, 'Helpurl', None)
if p is not None and str(p.eval()).strip():
return str(p.eval()).strip()
return '%s/%s/' % (self.HELP_SITE, pkg.name.lower().replace('_', '-'))
def _enclosingPackage(self, comp):
"""The depth-1 toolkit package holding `comp`, or None."""
root = getattr(op, 'FNS', None)
if root is None or comp is None:
return None
c = comp
while c is not None:
parent = c.parent()
if parent is root:
return c
c = parent
return None
def _registryApi(self):
"""Live registry that owns the panebar menu (prefer global /sys copy)."""
if self._is_sys_global():
return self
global_reg = self._global_registry()
if global_reg and global_reg.valid and global_reg.extensionsReady:
if hasattr(global_reg.ext, self.EXT_NAME):
return getattr(global_reg.ext, self.EXT_NAME)
return self
UNREGISTER_PAR = 'Unregister'
def _ensureCanonicalFollowsOwner(self):
"""A host whose constant Canonicalname merely repeats its owner's name
gets the parent().name expression instead (same value, no
registration change). Hand-authored names that differ are left
alone, as are masters, the /sys global and anything under /ui."""
if self._is_sys_global() or self._isUnderSysOrUi():
return
par = self.ownerComp.par['Canonicalname']
owner = self.ownerComp.parent()
if par is None or owner is None or owner is getattr(op, 'FNS', None):
return
try:
if par.mode != ParMode.CONSTANT or str(par.val).strip() != owner.name:
return
par.expr = self.CANONICAL_FOLLOWS_OWNER_EXPR
par.mode = ParMode.EXPRESSION
except Exception as e:
debug(f'{self.REGISTRY_NAME}: canonical follows owner: {e}')
def _ensureUnregisterPar(self):
"""Give every host an Unregister button, next to Register.
Registration was only reversible by turning Autoregister OFF, which is
a setting rather than an action -- nothing on the page said "take this
back out", so the way to undo a registration was undiscoverable.
Created in code because the Registration page is authored per COMP and
there are 102 hosts, while this file is shared. It lands on whatever
page Register lives on and takes the slot right after it, so it heals
into the correct place no matter how a given registry ordered its page.
"""
if self._is_sys_global():
return
if getattr(self.ownerComp.par, self.UNREGISTER_PAR, None) is not None:
return
reg = getattr(self.ownerComp.par, 'Register', None)
if reg is None:
return # not a host-publisher layout
try:
par = reg.page.appendPulse(self.UNREGISTER_PAR, label='Unregister')[0]
par.order = reg.order + 0.5 # between Register and Regstatus
par.help = ("Take this tool's contribution back out of the registry "
"and turn Autoregister off, so it stays out. Register "
"puts it back.")
except Exception as e:
debug(f'{self.REGISTRY_NAME}: could not create {self.UNREGISTER_PAR}: {e}')
def onParUnregister(self, _par):
self._hostExtFromPar(_par)._unregisterHost()
def _unregisterHost(self):
"""Withdraw this host's contribution and keep it withdrawn.
Autoregister goes off as PART of the action, not as a side effect worth
hiding: without it the next heal tick calls _applyHostRegistration and
puts the entry straight back, so the button would flicker and read as
doing nothing at all.
"""
par = getattr(self.ownerComp.par, 'Autoregister', None)
if par is not None:
try:
# may be BOUND to the tool's Registry page -- writing through is
# correct (the tool par is the master and must agree), but a
# dangling bind raises, so it must not take the unregister down
par.val = False
except Exception as e:
debug(f'{self.REGISTRY_NAME}: clearing Autoregister: {e}')
# NOT _clearHostRegistration: that trusts stored['HostCanonical'], which
# is local bookkeeping and drifts. Force-registering (the Register pulse)
# with Autoregister off leaves a live entry while a later
# _applyHostRegistration blanks the stored name, so the clear returns
# early and removes NOTHING -- measured: entry live, host owns it, and
# the button still reported "Unregistered" with the widget on screen.
# An explicit user action asks what this host actually owns instead.
api = self._registryApi()
removed = []
for name in (self.stored['HostCanonical'], self._hostCanonicalName()):
if not name or name in removed:
continue
if self._unregisterOwnedMenuName(name, api=api):
removed.append(name)
self.stored['HostCanonical'] = ''
# 'Idle' is what _applyHostRegistration writes a frame later when the
# Autoregister callback lands, and it is accurate -- not registered,
# autoregister off. An earlier attempt to re-assert 'Unregistered' after
# that callback via a delayed run() dropped the project from 60fps to 2,
# so the status is left to settle on its own.
self._setRegStatus('Unregistered' if removed else 'Not registered')
PRESAVE_HEAL_PAR = 'Presaveheal'
PRESAVE_HEAL_HELP = (
'Before each project save, re-check this registry: update entries '
'whose component moved, drop entries whose component is gone, and '
'republish a host that initialised before the global registry '
'existed. Off skips the sweep for this registry only.')
def _ensurePresaveHealPar(self):
"""Surface the pre-save heal switch on the in-project MASTER only.
The pre-save exec (/FNSTools/registry_presave_exec) reads this toggle
per registry before healing; hosts and the /sys global never carry the
decision. Created in code so every install self-heals the par."""
if self.ownerComp is not self._masterComp():
return
existing = getattr(self.ownerComp.par, self.PRESAVE_HEAL_PAR, None)
if existing is not None:
# Re-asserted rather than skipped. The par shipped before the
# help text did, and `help` is not a nicety here: it is the
# tooltip AND the description build_manifest.Parameters() puts
# on the docs page, so an early return would leave every
# already-installed registry permanently undocumented.
if not (existing.help or '').strip():
existing.help = self.PRESAVE_HEAL_HELP
return
try:
page = next((p for p in self.ownerComp.customPages
if p.name == self.HOST_PAGE_NAME), None) \
or self.ownerComp.appendCustomPage(self.HOST_PAGE_NAME)
p = page.appendToggle(self.PRESAVE_HEAL_PAR, label='Pre-Save Heal')[0]
p.startSection = True
p.default = True
p.val = True
p.help = self.PRESAVE_HEAL_HELP
except Exception as e:
debug(f'{self.REGISTRY_NAME}: could not create {self.PRESAVE_HEAL_PAR}: {e}')
def _setRegStatus(self, status):
if hasattr(self.ownerComp.par, 'Regstatus'):
self.ownerComp.par.Regstatus.val = status
# Registered/Error transitions are the interesting ones; Idle/Skipped
# states fire for every host copy at startup and stay at DEBUG.
_lvl = 'INFO' if str(status).startswith(('Registered', 'Error')) else 'DEBUG'
self.fnsLog(f'{self.REGISTRY_NAME} [{self.ownerComp.path}]: {status}', level=_lvl)
def _hostMenuOrder(self):
"""Read Registration Menuorder par; None means default append."""
if not hasattr(self.ownerComp.par, 'Menuorder'):
return None
return self._normalizeMenuOrder(self.ownerComp.par.Menuorder.eval())
def _applyHostRegistration(self, force=False):
"""Register or unregister the host COMP based on Auto-register + location.
force=True (Register pulse) registers even when Auto-register is off.
"""
if self._is_sys_global():
# Global /sys copy is infrastructure — never auto-registers a host.
self._setRegStatus('Idle (global)')
return
if self._isUnderSysOrUi():
self._clearHostRegistration()
self._setRegStatus('Skipped (/sys or /ui)')
return
if not force and not self._isAutoRegister():
self._clearHostRegistration()
self._setRegStatus('Idle')
return
host = self._hostComp()
if not host:
if not force:
self._clearHostRegistration()
self._setRegStatus('Error: no host COMP')
return
canonical = self._hostCanonicalName()
if not canonical:
if not force:
self._clearHostRegistration()
self._setRegStatus('Error: empty canonical name')
return
pane_type = self.ownerComp.par.Panetype.eval() if hasattr(self.ownerComp.par, 'Panetype') else 'PANEL'
flags = self._hostRecallFlags()
callback = self._hostCallbackDat()
err = self._validateHostForPaneType(host, pane_type)
if err:
if not force:
self._clearHostRegistration()
self._setRegStatus(f'Error: {err}')
return
prev = self.stored['HostCanonical']
api = self._registryApi()
# Only drop prev if THIS registry owns that global entry.
# Copied host templates inherit HostCanonical from the source and must
# not unregister the template's live menu name (e.g. project1 -> button1).
if prev and prev != canonical:
self._unregisterOwnedMenuName(prev, api=api)
api.RegisterPanel(
host, canonical, pane_type=pane_type,
set_owner=flags['set_owner'],
change_type=flags['change_type'],
maximize=flags['maximize'],
tear_away=flags['tear_away'],
float_pane=flags['float'],
open_parameters=flags['open_parameters'],
callback=callback,
source_registry=self.ownerComp,
menu_order=self._hostMenuOrder(),
)
self.stored['HostCanonical'] = canonical
self._setRegStatus(f'Registered: {canonical} -> {host.path}')
self._ensureToolRegistryPage()
def _ownsGlobalMenuName(self, canonical, api=None):
"""True if the global menu entry for canonical was published by this registry."""
if not canonical:
return False
api = api or self._registryApi()
if api is None:
return False
try:
info = api.stored['PaneRegistry'].get(canonical)
except Exception:
info = None
if not info:
return False
src_id = info.get('source_registry_id')
if src_id is not None:
try:
if int(src_id) == int(self.ownerComp.id):
return True
except Exception:
pass
return info.get('source_registry') == self.ownerComp.path
def _unregisterOwnedMenuName(self, canonical, api=None):
"""Unregister a menu name only when this host registry owns it."""
if not canonical:
return False
api = api or self._registryApi()
if api is None:
return False
if not self._ownsGlobalMenuName(canonical, api=api):
return False
api.UnregisterPanel(canonical)
return True
def _clearHostRegistration(self):
prev = self.stored['HostCanonical']
if not prev:
return
api = self._registryApi()
self._unregisterOwnedMenuName(prev, api=api)
self.stored['HostCanonical'] = ''
def _hostExtFromPar(self, _par):
"""Resolve the registry extension that owns this parameter.
CustomParHelper keeps a class-level EXT_SELF, so with a shipped
registry plus a /sys global copy the wrong instance can receive
callbacks. Always go through the parameter's owner.
"""
owner = _par.owner if _par is not None else self.ownerComp
if owner and owner.valid and owner.extensionsReady:
if hasattr(owner.ext, self.EXT_NAME):
return getattr(owner.ext, self.EXT_NAME)
return self
class _RegistryGlobalMixin:
"""Global registry lifecycle: /sys promotion, version arbitration,
merge and destroy. Pkgversion governs; Version is the fallback."""
# --- global registry lifecycle ---
SYS_HOME = 'FNS_Registries'
def _sys_comp(self, create=False):
"""Home of the promoted globals: /sys/FNS_Registries.
One container keeps the FNS globals out of TD's own /sys furniture
and gives the installer a single place to look. Global OP shortcuts
resolve from any depth, so nesting costs consumers nothing.
Only the promotion path passes create=True -- every read stays
side-effect free, so merely asking the question never grows a
container in a project that has no registries.
"""
sys_root = op('/sys')
if sys_root is None:
return None
home = sys_root.op(self.SYS_HOME)
if home is None and create:
home = sys_root.create(baseCOMP, self.SYS_HOME)
home.color = (0.35, 0.45, 0.55)
anchor = sys_root.op('TDDialogs') or sys_root.op('TDResources')
if anchor:
home.nodeX = anchor.nodeX
home.nodeY = anchor.nodeY - 300
self.fnsLog(f'{self.REGISTRY_NAME}: created global registry home {home.path}')
return home
def _isLegacySysCopy(self, registry_comp=None):
"""A copy promoted straight into /sys, before the FNS_Registries home."""
comp = registry_comp or self.ownerComp
sys_root = op('/sys')
return bool(sys_root and comp and comp.valid
and comp.parent() == sys_root and comp is not self._sys_comp())
def _is_in_sys(self, registry_comp=None):
comp = registry_comp or self.ownerComp
sys_comp = self._sys_comp()
return bool(sys_comp and comp and comp.valid and comp.parent() == sys_comp)
def _global_registry(self):
if hasattr(op, self.SHORTCUT):
reg = getattr(op, self.SHORTCUT)
if reg and reg.valid and self._is_global_registry(reg):
return reg
for child in self._find_sys_registries():
if self._is_global_registry(child):
return child
return None
def _installGlobalRegistry(self):
if self._is_sys_global(self.ownerComp):
self.ownerComp.par.opshortcut = self.SHORTCUT
# A freshly promoted global REPLACED its predecessor, killing
# any sync chains scheduled against the old copy -- without a
# settle sync of its own, registrations merged into this copy
# never reach the surface (observed: two toolbar buttons on
# open, all nineteen after one manual sync).
if hasattr(self, '_syncSurface'):
run('args[0].valid and args[0].ext.%s._syncSurface()'
% self.EXT_NAME,
self.ownerComp, delayFrames=90, delayRef=op.TDResources)
try:
self._armRegistryWatch()
except Exception:
pass
return
global_registry = self._global_registry()
if global_registry and global_registry != self.ownerComp:
# a global still parked directly in /sys predates the
# FNS_Registries home: relocate it even at an equal version,
# so the two homes never both hold a live global
relocating = not self._is_in_sys(global_registry)
if not relocating and self._check_version_against(global_registry):
return
self._replace_global_registry(global_registry, force=relocating)
return
if not self._reconcile_parked_sys_registries():
return
self._become_global_registry()
def _release_shipped_shortcut(self):
if self._is_in_sys():
return
if hasattr(self.ownerComp.par, 'opshortcut'):
self.ownerComp.par.opshortcut = ''
def _is_global_registry(self, registry_comp):
return self._has_global_shortcut(registry_comp)
def _is_sys_global(self, registry_comp=None):
comp = registry_comp or self.ownerComp
return self._is_in_sys(comp) and self._is_global_registry(comp)
def _has_global_shortcut(self, registry_comp):
if not registry_comp or not registry_comp.valid:
return False
if hasattr(op, self.SHORTCUT) and getattr(op, self.SHORTCUT) == registry_comp:
return True
if hasattr(registry_comp.par, 'opshortcut'):
return registry_comp.par.opshortcut.eval() == self.SHORTCUT
return False
def _find_parked_sys_registries(self):
return [child for child in self._find_sys_registries()
if child != self.ownerComp and not self._is_global_registry(child)]
def _reconcile_parked_sys_registries(self):
parked = self._find_parked_sys_registries()
if not parked:
return True
winner = parked[0]
for reg in parked[1:]:
new_winner = self._compare_versions(reg, winner)
if new_winner == reg:
self._merge_into_registry(reg, winner)
winner.destroy()
winner = reg
else:
self._merge_into_registry(winner, reg)
reg.destroy()
# a winner still parked in the pre-container /sys is never promoted
# where it stands -- absorb it instead, so promotion always lands
# in the FNS_Registries home
if self._is_in_sys(winner) and self._compare_versions(winner, self.ownerComp) == winner:
self._merge_into_registry(winner, self.ownerComp)
self._promote_to_global(winner)
return False
self._merge_pane_registry_from(winner)
winner.destroy()
return True
def _merge_into_registry(self, target_registry, source_registry):
if target_registry == source_registry:
return
if hasattr(target_registry, 'ext') and hasattr(target_registry.ext, self.EXT_NAME):
getattr(target_registry.ext, self.EXT_NAME)._merge_pane_registry_from(source_registry)
def _compare_versions(self, comp_a, comp_b):
"""Whichever of the two should own the shortcut.
Newest wins, always -- and silently. Ties go to the incumbent. This is
never allowed to ask: it runs during project load, once per registry copy,
so a prompt here is a stack of modal dialogs across startup."""
ver_a = self._parse_version(self._get_version(comp_a))
ver_b = self._parse_version(self._get_version(comp_b))
if ver_a is None and ver_b is None:
return comp_b if self._is_in_sys(comp_b) else comp_a
if ver_a is None:
return comp_b
if ver_b is None:
return comp_a
return comp_a if ver_a > ver_b else comp_b
def _promote_to_global(self, registry_comp):
if not registry_comp or not registry_comp.valid:
return
registry_comp.par.opshortcut = self.SHORTCUT
if hasattr(registry_comp, 'ext') and hasattr(registry_comp.ext, self.EXT_NAME):
ext = getattr(registry_comp.ext, self.EXT_NAME)
ext._neutralizeHostParameters()
ext._syncSurface()
# The copy's own postInit ran BEFORE the shortcut existed (host
# branch), so the healing watch was never armed there. Arm it now
# that the comp is the sys-global -- without this, a first-compile
# success promotes a global with no heal loop.
ext._armRegistryWatch()
def _destroy_other_globals(self, keep=None):
keep = keep or self.ownerComp
security_counter = 10
while security_counter:
security_counter -= 1
for candidate in self._find_sys_registries():
if candidate == keep:
continue
if self._is_global_registry(candidate):
candidate.destroy()
def _find_sys_registries(self):
"""Every promoted copy: the FNS_Registries home, plus any pre-container
copy still parked directly in /sys (where older builds promoted)."""
found = []
home = self._sys_comp()
if home:
found.extend(home.findChildren(name=self.REGISTRY_NAME + '*', depth=1))
sys_root = op('/sys')
if sys_root:
for child in sys_root.findChildren(name=self.REGISTRY_NAME + '*', depth=1):
if child not in found:
found.append(child)
return found
def _retryGlobalExtensionInit(self, registry_comp, attempts_left=20):
"""Re-init /sys copy when ExtUtils dock lagged behind first extension compile."""
if not registry_comp or not registry_comp.valid:
return
has_ext = (
hasattr(registry_comp, 'ext')
and hasattr(registry_comp.ext, self.EXT_NAME)
)
if has_ext:
if self.ownerComp and self.ownerComp.valid:
self._merge_into_registry(registry_comp, self.ownerComp)
self._promote_to_global(registry_comp)
return
ext_dat = registry_comp.op(self.EXT_NAME)
docked_n = len(ext_dat.docked) if ext_dat else -1
eu = next((c for c in registry_comp.children if 'ExtUtils' in c.tags), None)
debug(
f'{self.REGISTRY_NAME}: retry global ext init attempts={attempts_left} '
f'docked={docked_n} eu={eu.path if eu else None}'
)
if hasattr(registry_comp.par, 'reinitextensions'):
registry_comp.par.reinitextensions.pulse()
if attempts_left > 0:
run(
lambda c=registry_comp, n=attempts_left - 1: self._retryGlobalExtensionInit(c, n),
delayFrames=3,
)
def _become_global_registry(self):
if self._is_in_sys():
self._destroy_other_globals()
self.ownerComp.par.opshortcut = self.SHORTCUT
self._syncSurface()
self._armRegistryWatch()
return
sys_comp = self._sys_comp(create=True)
if not sys_comp:
debug(f'{self.REGISTRY_NAME}: /sys not found, cannot become global registry.')
return
if not self._reconcile_parked_sys_registries():
return
self._destroy_other_globals()
self.fnsLog(f'{self.REGISTRY_NAME}: installing global registry copy into /sys from {self.ownerComp.path}')
new_registry = sys_comp.copy(self.ownerComp, name=self.REGISTRY_NAME)
new_registry.allowCooking = True
# The /sys global is STANDALONE: the copy inherits whatever clone
# binding the master carries (dev masters are clone-bound for
# hot-propagation), but a global cloned to an in-project master
# dangles the moment an update destroys and reloads that master.
# Promotion is the handover; from here the global owns itself.
try:
new_registry.par.clone = ''
new_registry.par.enablecloning = False
except Exception:
pass
# one tidy column inside the home: each new global drops below the
# highest sibling, spaced by its own height so tall copies never overlap
sibs = [c for c in sys_comp.children if c is not new_registry]
if sibs:
step = ((int(new_registry.nodeHeight) + 100 + 199) // 200) * 200
new_registry.nodeX = int(min(c.nodeX for c in sibs))
new_registry.nodeY = int(min(c.nodeY for c in sibs)) - step
else:
new_registry.nodeX = 0
new_registry.nodeY = 0
# The copy's extension initializes DURING copy() (initextonstart),
# before it has our shortcut or data -- hand both over explicitly.
if hasattr(new_registry, 'ext') and hasattr(new_registry.ext, self.EXT_NAME):
self._merge_into_registry(new_registry, self.ownerComp)
else:
# Extension often fails first compile: me.docked empty until network cooks.
# Sibling ExtUtils already exists — import fallback + delayed reinit recovers.
new_registry.store('post_update', True)
new_registry.store('PaneRegistry', dict(self.stored['PaneRegistry']))
run(lambda c=new_registry: self._retryGlobalExtensionInit(c), delayFrames=1)
self._promote_to_global(new_registry)
self._release_shipped_shortcut()
self._dropParallelTable()
if self._isLegacySysCopy():
# we WERE the pre-container global; the home copy carries our
# data now, so the old parking spot is litter -- clear it a few
# frames out, never from inside our own init
self.fnsLog(f'{self.REGISTRY_NAME}: retiring pre-container copy '
f'{self.ownerComp.path}')
run('args[0].valid and args[0].destroy()', self.ownerComp,
delayFrames=5, delayRef=op.TDResources)
return new_registry
def _replace_global_registry(self, old_registry, force=False):
if not force and self._check_version_against(old_registry):
return
# The incumbent is the LIVE table; whatever this master still holds
# is history. Same-name entries must come from the incumbent, or a
# stale order/side/visibility rides into the new global and the
# republish sweep skips the host because its entry "exists"
# (Hub and Palette masters carried such tables, 2026-09-10).
self._merge_pane_registry_from(old_registry, prefer_other=True)
if self._is_global_registry(old_registry):
old_registry.destroy()
self._become_global_registry()
def _merge_pane_registry_from(self, other_registry, prefer_other=False):
"""Fold another copy's entries into ours. Names we lack are always
taken; with prefer_other the other copy also wins same-name entries
(the takeover case, where the other copy is the live global)."""
other_data = self._get_pane_registry_data(other_registry)
for name, info in other_data.items():
if prefer_other or name not in self.stored['PaneRegistry']:
try:
info = dict(info)
info['action'] = self._normalize_action(info.get('action'))
except (TypeError, AttributeError):
pass
self.stored['PaneRegistry'][name] = info
def _dropParallelTable(self):
"""A master or host that is NOT the global keeps no entry table.
Registrations delegate to the global, so a table here is either
history from before the global existed or a copy's inheritance --
and on the next takeover it would shadow the live entries. Cleared
only while a separate global is live: with no /sys, this COMP IS the
API and its table is the real one."""
if self._is_sys_global():
return
glob = self._global_registry()
if glob is None or glob == self.ownerComp:
return
if self.stored['PaneRegistry']:
self.stored['PaneRegistry'].clear()
def _get_pane_registry_data(self, registry_comp):
if hasattr(registry_comp, 'ext') and hasattr(registry_comp.ext, self.EXT_NAME):