forked from apoguita/Py4GW
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSettings.py.bak
More file actions
1572 lines (1375 loc) · 65.3 KB
/
Copy pathSettings.py.bak
File metadata and controls
1572 lines (1375 loc) · 65.3 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
"""
Settings — Account-Level Key Cache for the Py4GW settings database.
The Settings class maintains in-memory caches for the Widget, Keys (per-account),
and Globals tables. Every get/set/delete operation reads from or writes to cache
rather than hitting the database.
On each throttle period (1000 ms), dirty cache entries are flushed to the database
in a single transaction. This reduces the per-operation open→execute→commit→close
cycle to one DB read on first access (or account change) and one DB write per
throttle tick.
**commit parameter semantics (changed)**:
For cache-backed operations (current account, globals) the ``commit``
parameter is accepted but ignored — all writes are staged in cache and
persisted on the next throttle flush. For direct-DB fallback paths
(non-current accounts) ``commit`` is still honoured.
Return values: methods that return a database row ID may return 0 for
newly-created entries that have not yet been flushed to disk.
**Account identification**:
The current account is identified by email (via Player.GetAccountEmail())
and/or HWND (via Py4GW.Console.get_gw_window_handle()). Account change
detection checks both values and invalidates the account cache on mismatch.
"""
from dataclasses import dataclass
from typing import Any, Optional, cast
from .Account import Account
from .DBMgr import DBMgr
from Py4GWCoreLib.py4gwcorelib_src.Timer import ThrottledTimer
class WidgetSettings:
"""Widget-bound convenience wrapper over Settings."""
def __init__(self, settings_db: 'Settings', widget_key: str, widget_name: Optional[str], description: Optional[str]) -> None:
self._settings_db = settings_db
self.widget_key = str(widget_key).strip()
self.widget_name = widget_name
self.description = description
def Ensure(self, commit: bool = True) -> int:
return self._settings_db.EnsureWidget(self.widget_key, self.widget_name, self.description, commit=commit)
def EnsureKey(self, section: str, key: str, key_type: str, default: Any, commit: bool = True) -> int:
self.Ensure(commit=commit)
existing = self._settings_db.GetCurrentAccountEntry(self.widget_key, section, key, commit=commit)
if existing is not None:
return int(existing['ID'])
return self.SetKey(section, key, key_type, default, commit=commit)
def EnsureBool(self, section: str, key: str, default: bool = False, commit: bool = True) -> int:
return self.EnsureKey(section, key, 'bool', default, commit=commit)
def EnsureInt(self, section: str, key: str, default: int = 0, commit: bool = True) -> int:
return self.EnsureKey(section, key, 'int', default, commit=commit)
def EnsureFloat(self, section: str, key: str, default: float = 0.0, commit: bool = True) -> int:
return self.EnsureKey(section, key, 'float', default, commit=commit)
def EnsureStr(self, section: str, key: str, default: str = '', commit: bool = True) -> int:
return self.EnsureKey(section, key, 'str', default, commit=commit)
def GetKey(self, section: str, key: str, key_type: str, default: Any, commit: bool = True) -> Any:
return self._settings_db.GetCurrentAccountValue(
self.widget_key,
section,
key,
key_type,
default,
widget_name=self.widget_name,
description=self.description,
commit=commit,
)
def GetBool(self, section: str, key: str, default: bool = False, commit: bool = True) -> bool:
return bool(self.GetKey(section, key, 'bool', default, commit=commit))
def GetInt(self, section: str, key: str, default: int = 0, commit: bool = True) -> int:
return int(self.GetKey(section, key, 'int', default, commit=commit))
def GetFloat(self, section: str, key: str, default: float = 0.0, commit: bool = True) -> float:
return float(self.GetKey(section, key, 'float', default, commit=commit))
def GetStr(self, section: str, key: str, default: str = '', commit: bool = True) -> str:
return str(self.GetKey(section, key, 'str', default, commit=commit))
def SetKey(self, section: str, key: str, key_type: str, value: Any, commit: bool = True) -> int:
return self._settings_db.SetCurrentAccountValue(
self.widget_key,
section,
key,
key_type,
value,
widget_name=self.widget_name,
description=self.description,
commit=commit,
)
def SetBool(self, section: str, key: str, value: bool, commit: bool = True) -> int:
return self.SetKey(section, key, 'bool', value, commit=commit)
def SetInt(self, section: str, key: str, value: int, commit: bool = True) -> int:
return self.SetKey(section, key, 'int', value, commit=commit)
def SetFloat(self, section: str, key: str, value: float, commit: bool = True) -> int:
return self.SetKey(section, key, 'float', value, commit=commit)
def SetStr(self, section: str, key: str, value: str, commit: bool = True) -> int:
return self.SetKey(section, key, 'str', value, commit=commit)
def DeleteKey(self, section: str, key: str, commit: bool = True) -> int:
email = self._settings_db._get_current_account_email()
if not email:
return 0
return self._settings_db.DeleteAccountValueByEmail(self.widget_key, email, section, key, commit=commit)
def GetSection(self, section: str, commit: bool = True) -> list[dict]:
email = self._settings_db._get_current_account_email()
if not email:
return []
account_id = Account().GetAccountKey(email, commit=commit)
if account_id is None:
return []
return self._settings_db.GetAccountSection(self.widget_key, account_id, section, commit=commit)
def GetGlobalKey(self, section: str, key: str, key_type: str, default: Any, commit: bool = True) -> Any:
return self._settings_db.GetGlobalValue(
self.widget_key,
section,
key,
key_type,
default,
widget_name=self.widget_name,
description=self.description,
commit=commit,
)
def EnsureGlobalKey(self, section: str, key: str, key_type: str, default: Any, commit: bool = True) -> int:
self.Ensure(commit=commit)
existing = self._settings_db.GetGlobalEntry(self.widget_key, section, key, commit=commit)
if existing is not None:
return int(existing['ID'])
return self.SetGlobalKey(section, key, key_type, default, commit=commit)
def EnsureGlobalBool(self, section: str, key: str, default: bool = False, commit: bool = True) -> int:
return self.EnsureGlobalKey(section, key, 'bool', default, commit=commit)
def EnsureGlobalInt(self, section: str, key: str, default: int = 0, commit: bool = True) -> int:
return self.EnsureGlobalKey(section, key, 'int', default, commit=commit)
def EnsureGlobalFloat(self, section: str, key: str, default: float = 0.0, commit: bool = True) -> int:
return self.EnsureGlobalKey(section, key, 'float', default, commit=commit)
def EnsureGlobalStr(self, section: str, key: str, default: str = '', commit: bool = True) -> int:
return self.EnsureGlobalKey(section, key, 'str', default, commit=commit)
def GetGlobalBool(self, section: str, key: str, default: bool = False, commit: bool = True) -> bool:
return bool(self.GetGlobalKey(section, key, 'bool', default, commit=commit))
def GetGlobalInt(self, section: str, key: str, default: int = 0, commit: bool = True) -> int:
return int(self.GetGlobalKey(section, key, 'int', default, commit=commit))
def GetGlobalFloat(self, section: str, key: str, default: float = 0.0, commit: bool = True) -> float:
return float(self.GetGlobalKey(section, key, 'float', default, commit=commit))
def GetGlobalStr(self, section: str, key: str, default: str = '', commit: bool = True) -> str:
return str(self.GetGlobalKey(section, key, 'str', default, commit=commit))
def SetGlobalKey(self, section: str, key: str, key_type: str, value: Any, commit: bool = True) -> int:
return self._settings_db.SetGlobalValue(
self.widget_key,
section,
key,
key_type,
value,
widget_name=self.widget_name,
description=self.description,
commit=commit,
)
def SetGlobalBool(self, section: str, key: str, value: bool, commit: bool = True) -> int:
return self.SetGlobalKey(section, key, 'bool', value, commit=commit)
def SetGlobalInt(self, section: str, key: str, value: int, commit: bool = True) -> int:
return self.SetGlobalKey(section, key, 'int', value, commit=commit)
def SetGlobalFloat(self, section: str, key: str, value: float, commit: bool = True) -> int:
return self.SetGlobalKey(section, key, 'float', value, commit=commit)
def SetGlobalStr(self, section: str, key: str, value: str, commit: bool = True) -> int:
return self.SetGlobalKey(section, key, 'str', value, commit=commit)
def DeleteGlobalKey(self, section: str, key: str, commit: bool = True) -> int:
return self._settings_db.DeleteGlobalValue(self.widget_key, section, key, commit=commit)
@dataclass
class WindowState:
initialized: bool = False
x_pos: int = 0
y_pos: int = 0
width: int = 0
height: int = 0
collapsed: bool = False
begin_called: bool = False
begin_returned_true: bool = False
@dataclass
class _CacheEntry:
"""Single cache entry for the account-key or global-key cache."""
value: str # serialized value (as stored in DB)
key_type: str # 'bool'|'int'|'float'|'str'
dirty: bool = False
deleted: bool = False
db_id: int = 0 # Keys.ID or Globals.ID (0 = not yet in DB)
class Settings(DBMgr):
"""Persistence helpers for the Py4GW settings database.
Maintains in-memory account-level and global caches. All get/set/delete
operations for the current account and global scope hit the cache; the
database is only touched on the throttle boundary (every 1000 ms) via a
PyCallback frame callback.
Public API is unchanged — all method signatures, return types, and the
WidgetSettings wrapper remain identical.
"""
DATABASE_NAME = 'Py4GW_Settings'
WIDGET_TABLE = 'Widget'
GLOBALS_TABLE = 'Globals'
KEYS_TABLE = 'Keys'
_callback_name = 'Settings.FlushDirtyCache'
_settings_instance: Optional['Settings'] = None
def __new__(cls) -> 'Settings':
if cls._settings_instance is not None:
return cls._settings_instance
instance = cast('Settings', super().__new__(cls, cls.DATABASE_NAME))
cls._settings_instance = instance
return instance
@classmethod
def Instance(cls) -> 'Settings':
return cls()
def __init__(self) -> None:
super().__init__(self.DATABASE_NAME)
if getattr(self, '_settings_initialized', False):
return
# In-memory window state (unchanged from original)
self._window_states: dict[str, WindowState] = {}
# --- Cache dictionaries ---
self._account_cache: dict[tuple[str, str, str], _CacheEntry] = {} # (widget_key, section, key) → _CacheEntry
# (widget_key, section, key) → _CacheEntry
self._global_cache: dict[tuple[str, str, str], _CacheEntry] = {}
self._widget_cache: dict[str, int] = {} # widget_key → widget_id
self._widget_id_cache: dict[int, str] = {}
self._widget_info_cache: dict[str, tuple[str, Optional[str]]] = {}
self._dirty_account_keys: set[tuple[str, str, str]] = set()
self._dirty_global_keys: set[tuple[str, str, str]] = set()
self._widget_cache_loaded: bool = False
self._global_cache_loaded: bool = False
self._account_cache_loaded: bool = False
# --- Widget metadata forwarding ---
# widget_name/description received from callers; forwarded to EnsureWidget during flush
self._widget_metadata: dict[str, tuple[Optional[str], Optional[str]]] = {}
# --- Account identification ---
self._cached_email: str = ''
self._cached_hwnd: int = 0
self._cached_account_id: Optional[int] = None
# --- Flush machinery ---
self._flush_timer = ThrottledTimer(1000)
self._refresh_timer = ThrottledTimer(1000)
self._flush_failure_count: int = 0 # circuit breaker for persistent errors
# --- Guarded callback registration (tolerates missing Py4GW runtime) ---
try:
self._register_flush_callback()
except ImportError:
pass
self._settings_initialized = True
# ------------------------------------------------------------------
# Callback management
# ------------------------------------------------------------------
def _register_flush_callback(self) -> None:
"""Register the flush callback on Phase.Data / Context.Update (mirrors IniManager)."""
import PyCallback
PyCallback.PyCallback.Register(
self._callback_name,
PyCallback.Phase.Data,
self._flush_callback,
priority=99,
context=PyCallback.Context.Update,
)
@classmethod
def enable(cls) -> None:
"""Re-register the flush callback (e.g., after disable())."""
try:
cls.Instance()._register_flush_callback()
except ImportError:
pass
@classmethod
def disable(cls) -> None:
"""Remove the flush callback (for testing/shutdown)."""
try:
import PyCallback
PyCallback.PyCallback.RemoveByName(cls._callback_name)
except ImportError:
pass
def _flush_callback(self, *args, **kwargs) -> None:
"""Frame callback: flush on flush-throttle, refresh on refresh-throttle."""
if self._flush_timer.IsExpired():
if self._has_pending_flush() and self._flush_dirty():
self._refresh_cache_from_disk()
self._refresh_timer.Reset()
self._flush_timer.Reset()
if self._refresh_timer.IsExpired():
#if not self._has_pending_flush():
# self._refresh_cache_from_disk()
self._refresh_timer.Reset()
# ------------------------------------------------------------------
# Cache population
# ------------------------------------------------------------------
def _ensure_cache_populated(self) -> None:
"""Populate caches on first access by running one disk refresh."""
if self._widget_cache_loaded and self._global_cache_loaded and self._account_cache_loaded:
return
self._refresh_cache_from_disk()
return
email = self._get_current_account_email()
# M5: Only call native HWND method on first access; HWND doesn't change frame-to-frame.
hwnd = self._cached_hwnd if self._cached_hwnd != 0 else self._get_current_account_hwnd()
# Detect account change (email OR meaningful hwnd change)
# S5: Only clear on HWND change when both old and new are non-zero.
# A 0→N transition (window just created) should NOT invalidate the cache.
email_changed = email != self._cached_email
hwnd_changed = hwnd != self._cached_hwnd
if email_changed or (hwnd_changed and self._cached_hwnd != 0 and hwnd != 0):
self._account_cache.clear()
self._dirty_account_keys.clear()
self._cached_account_id = None
self._account_cache_loaded = False
self._cached_email = email
self._cached_hwnd = hwnd
# Populate widget cache (loaded once, never invalidated)
if not self._widget_cache_loaded:
try:
widget_rows = self.Select(self.WIDGET_TABLE)
for row in widget_rows:
wk = self._normalize_text(row['Key'] or '')
if wk:
wid = int(row['ID'])
self._widget_cache[wk] = wid
self._widget_id_cache[wid] = wk
self._widget_info_cache[wk] = (
self._normalize_text(row['Name'] or wk),
row['Description'],
)
except Exception:
pass
self._widget_cache_loaded = True
# Populate account cache (Keys table)
if not self._account_cache_loaded:
account_id: Optional[int] = None
# Try email first
if email:
try:
account_id = Account().GetAccountKey(email)
except Exception:
pass
# Fall back to HWND
if account_id is None and hwnd:
try:
rows = Account().Select(Account.ACCOUNT_TABLE, where={'HWND': hwnd}, limit=1)
if rows:
account_id = int(rows[0]['ID'])
except Exception:
pass
self._cached_account_id = account_id
if account_id is not None and self._widget_cache:
try:
keys_rows = self.Select(self.KEYS_TABLE, where={'AccountID': account_id})
for row in keys_rows:
wkey = self._widget_id_cache.get(int(row['WidgetID']))
if wkey is None:
continue
cache_key = (
wkey,
self._normalize_text(row['Section'] or ''),
self._normalize_text(row['Key'] or ''),
)
self._account_cache[cache_key] = _CacheEntry(
value=row['Value'] or '',
key_type=row['KeyType'] or 'str',
dirty=False,
deleted=False,
db_id=int(row['ID']),
)
except Exception:
pass
self._account_cache_loaded = True
# Populate global cache (Globals table — loaded once, never invalidated)
if not self._global_cache_loaded and self._widget_cache:
try:
global_rows = self.Select(self.GLOBALS_TABLE)
for row in global_rows:
wkey = self._widget_id_cache.get(int(row['WidgetID']))
if wkey is None:
continue
cache_key = (
wkey,
self._normalize_text(row['Section'] or ''),
self._normalize_text(row['Key'] or ''),
)
self._global_cache[cache_key] = _CacheEntry(
value=row['Value'] or '',
key_type=row['KeyType'] or 'str',
dirty=False,
deleted=False,
db_id=int(row['ID']),
)
except Exception:
pass
self._global_cache_loaded = True
def _resolve_current_account_id(self, email: str, hwnd: int) -> Optional[int]:
account_id: Optional[int] = None
if email:
try:
account_id = Account().GetAccountKey(email)
except Exception:
pass
if account_id is None and hwnd:
try:
rows = Account().Select(Account.ACCOUNT_TABLE, where={'HWND': hwnd}, limit=1)
if rows:
account_id = int(rows[0]['ID'])
except Exception:
pass
return account_id
def _refresh_cache_from_disk(self) -> None:
"""Refresh widget/global/current-account caches from disk."""
email = self._get_current_account_email()
hwnd = self._get_current_account_hwnd()
email_changed = email != self._cached_email
hwnd_changed = hwnd != self._cached_hwnd
if email_changed or (hwnd_changed and self._cached_hwnd != 0 and hwnd != 0):
self._account_cache.clear()
self._dirty_account_keys.clear()
self._cached_account_id = None
self._account_cache_loaded = False
self._cached_email = email
self._cached_hwnd = hwnd
try:
widget_rows = self.Select(self.WIDGET_TABLE)
widget_cache: dict[str, int] = {}
widget_id_cache: dict[int, str] = {}
widget_info_cache: dict[str, tuple[str, Optional[str]]] = {}
for row in widget_rows:
wk = self._normalize_text(row['Key'] or '')
if not wk:
continue
wid = int(row['ID'])
widget_cache[wk] = wid
widget_id_cache[wid] = wk
widget_info_cache[wk] = (
self._normalize_text(row['Name'] or wk),
row['Description'],
)
self._widget_cache = widget_cache
self._widget_id_cache = widget_id_cache
self._widget_info_cache = widget_info_cache
self._widget_cache_loaded = True
except Exception:
pass
self._cached_account_id = self._resolve_current_account_id(email, hwnd)
try:
global_cache: dict[tuple[str, str, str], _CacheEntry] = {}
if self._widget_cache:
global_rows = self.Select(self.GLOBALS_TABLE)
for row in global_rows:
wkey = self._widget_id_cache.get(int(row['WidgetID']))
if wkey is None:
continue
cache_key = (
wkey,
self._normalize_text(row['Section'] or ''),
self._normalize_text(row['Key'] or ''),
)
global_cache[cache_key] = _CacheEntry(
value=row['Value'] or '',
key_type=row['KeyType'] or 'str',
dirty=False,
deleted=False,
db_id=int(row['ID']),
)
self._global_cache = global_cache
self._global_cache_loaded = True
except Exception:
pass
try:
account_cache: dict[tuple[str, str, str], _CacheEntry] = {}
if self._cached_account_id is not None and self._widget_cache:
keys_rows = self.Select(self.KEYS_TABLE, where={'AccountID': self._cached_account_id})
for row in keys_rows:
wkey = self._widget_id_cache.get(int(row['WidgetID']))
if wkey is None:
continue
cache_key = (
wkey,
self._normalize_text(row['Section'] or ''),
self._normalize_text(row['Key'] or ''),
)
account_cache[cache_key] = _CacheEntry(
value=row['Value'] or '',
key_type=row['KeyType'] or 'str',
dirty=False,
deleted=False,
db_id=int(row['ID']),
)
self._account_cache = account_cache
self._account_cache_loaded = True
except Exception:
pass
def _resolve_widget_key(self, widget_id: int) -> Optional[str]:
"""Reverse-lookup widget_key from widget_id using _widget_cache."""
return self._widget_id_cache.get(int(widget_id))
def _resolve_widget_id(self, widget_key: str, commit: bool = False) -> int:
"""Resolve widget_id from widget_key, using cache first, then direct DB."""
wid = self._widget_cache.get(widget_key)
if wid is not None:
return wid
# Fall back to direct DB (widget-table methods stay direct)
wid = self.EnsureWidget(widget_key, commit=commit)
if wid:
resolved = int(wid)
self._widget_cache[widget_key] = resolved
self._widget_id_cache[resolved] = widget_key
return int(wid) if wid else 0
# ------------------------------------------------------------------
# Widget metadata tracking (minimal — forwarded to EnsureWidget at flush)
# ------------------------------------------------------------------
def _store_widget_metadata(
self, widget_key: str, widget_name: Optional[str], description: Optional[str]
) -> None:
"""Record widget metadata for forwarding to EnsureWidget during flush."""
if widget_name is not None or description is not None:
nwk = self._normalize_text(widget_key)
normalized_name = self._normalize_text(widget_name) if widget_name is not None else None
known = self._widget_info_cache.get(nwk)
if known is not None:
known_name, known_description = known
name_matches = normalized_name is None or normalized_name == known_name
description_matches = description is None or description == known_description
if name_matches and description_matches:
return
pending = self._widget_metadata.get(nwk)
if pending is not None:
pending_name, pending_description = pending
name_matches = normalized_name is None or normalized_name == pending_name
description_matches = description is None or description == pending_description
if name_matches and description_matches:
return
was_idle = not self._has_pending_flush()
effective_name = normalized_name
if effective_name is None:
if pending is not None and pending[0] is not None:
effective_name = pending[0]
elif known is not None:
effective_name = known[0]
else:
effective_name = nwk
effective_description = description
if effective_description is None:
if pending is not None:
effective_description = pending[1]
elif known is not None:
effective_description = known[1]
self._widget_metadata[nwk] = (effective_name, effective_description)
if was_idle:
self._flush_timer.Reset()
def _mark_dirty(
self,
cache_key: tuple[str, str, str],
entry: _CacheEntry,
dirty_keys: set[tuple[str, str, str]],
) -> None:
was_idle = not self._has_pending_flush()
entry.dirty = True
dirty_keys.add(cache_key)
if was_idle:
self._flush_timer.Reset()
def _has_pending_flush(self) -> bool:
if self._widget_metadata:
print(f"Pending widget metadata: {self._widget_metadata}")
if self._dirty_account_keys:
print(f"Pending account keys: {self._dirty_account_keys}")
if self._dirty_global_keys:
print(f"Pending global keys: {self._dirty_global_keys}")
return bool(self._widget_metadata or self._dirty_account_keys or self._dirty_global_keys)
# ------------------------------------------------------------------
# Flush
# ------------------------------------------------------------------
def _flush_dirty(self) -> bool:
"""Flush all dirty cache entries in a single transaction.
Pipeline:
1. Forward accumulated widget metadata to EnsureWidget.
2. For each dirty account-cache entry: DELETE/UPDATE/INSERT as needed.
3. Same for global-cache entries.
4. Single BeginTransaction/EndTransaction wrapping all operations.
Uses a local dedup dict for widget_id resolution to avoid redundant
EnsureWidget calls. Includes a circuit breaker: 3 consecutive flush
failures → clear all dirty flags to prevent infinite error loops.
"""
# Forward widget metadata (before the dirty check — metadata may be the only change)
# S3: EnsureWidget handles both widget existence and metadata; skip redundant _resolve_widget_id.
# Circuit breaker: after 3 consecutive failures, clear dirty flags to break error loop
if self._flush_failure_count >= 3:
for entry in self._account_cache.values():
entry.dirty = False
for entry in self._global_cache.values():
entry.dirty = False
self._dirty_account_keys.clear()
self._dirty_global_keys.clear()
self._widget_metadata.clear()
self._flush_failure_count = 0
self._flush_timer.Reset()
return False
# Local dedup dict for widget_id lookups within this flush
flush_widget_ids: dict[str, int] = {}
def _get_widget_id(wkey: str) -> int:
if wkey not in flush_widget_ids:
flush_widget_ids[wkey] = self._resolve_widget_id(wkey, commit=False)
return flush_widget_ids[wkey]
self.BeginTransaction()
try:
for widget_key, (name, desc) in list(self._widget_metadata.items()):
if name is None and desc is None:
continue
wid = self.EnsureWidget(widget_key, name=name, description=desc, commit=False)
if wid:
resolved = int(wid)
self._widget_cache[widget_key] = resolved
self._widget_id_cache[resolved] = widget_key
self._widget_info_cache[widget_key] = (
self._normalize_text(name or widget_key),
desc,
)
flush_widget_ids[widget_key] = resolved
# --- Flush account cache (Keys table) ---
processed_account_keys: list[tuple[str, str, str]] = []
for cache_key in list(self._dirty_account_keys):
entry = self._account_cache.get(cache_key)
if entry is None:
processed_account_keys.append(cache_key)
continue
widget_key, section, key = cache_key
if entry.deleted:
if entry.db_id != 0:
self.Delete(self.KEYS_TABLE, where={'ID': entry.db_id}, commit=False)
# Optimisation: db_id==0 entries were never persisted — just remove
del self._account_cache[cache_key]
processed_account_keys.append(cache_key)
continue
widget_id = _get_widget_id(widget_key)
if entry.db_id != 0:
self.Update(
self.KEYS_TABLE,
{'KeyType': entry.key_type, 'Value': entry.value},
where={'ID': entry.db_id},
commit=False,
)
else:
if self._cached_account_id is None:
self._cached_account_id = self._resolve_current_account_id(
self._get_current_account_email(),
self._get_current_account_hwnd(),
)
if self._cached_account_id is None:
continue
new_id = self.Insert(
self.KEYS_TABLE,
['WidgetID', 'AccountID', 'Section', 'Key', 'KeyType', 'Value'],
[widget_id, self._cached_account_id, section, key, entry.key_type, entry.value],
commit=False,
)
entry.db_id = int(new_id)
entry.dirty = False
processed_account_keys.append(cache_key)
# --- Flush global cache (Globals table) ---
processed_global_keys: list[tuple[str, str, str]] = []
for cache_key in list(self._dirty_global_keys):
entry = self._global_cache.get(cache_key)
if entry is None:
processed_global_keys.append(cache_key)
continue
widget_key, section, key = cache_key
if entry.deleted:
if entry.db_id != 0:
self.Delete(self.GLOBALS_TABLE, where={'ID': entry.db_id}, commit=False)
del self._global_cache[cache_key]
processed_global_keys.append(cache_key)
continue
widget_id = _get_widget_id(widget_key)
if entry.db_id != 0:
self.Update(
self.GLOBALS_TABLE,
{'KeyType': entry.key_type, 'Value': entry.value},
where={'ID': entry.db_id},
commit=False,
)
else:
new_id = self.Insert(
self.GLOBALS_TABLE,
['WidgetID', 'Section', 'Key', 'KeyType', 'Value'],
[widget_id, section, key, entry.key_type, entry.value],
commit=False,
)
entry.db_id = int(new_id)
entry.dirty = False
processed_global_keys.append(cache_key)
self.EndTransaction('COMMIT')
for cache_key in processed_account_keys:
self._dirty_account_keys.discard(cache_key)
for cache_key in processed_global_keys:
self._dirty_global_keys.discard(cache_key)
self._widget_metadata.clear()
self._flush_failure_count = 0 # reset on success
return True
except Exception:
self._flush_failure_count += 1
try:
self.EndTransaction('ROLLBACK')
except Exception:
pass
raise
# ------------------------------------------------------------------
# Account identification helpers
# ------------------------------------------------------------------
def _get_current_account_hwnd(self) -> int:
"""Return the current game window handle, or 0 if unavailable."""
try:
import Py4GW
return int(Py4GW.Console.get_gw_window_handle() or 0)
except Exception:
return 0
# ------------------------------------------------------------------
# Unchanged helpers
# ------------------------------------------------------------------
def ForWidget(self, widget_key: str, widget_name: Optional[str] = None, description: Optional[str] = None) -> WidgetSettings:
return WidgetSettings(self, widget_key, widget_name, description)
def _get_window_state(self, widget_key: str) -> WindowState:
normalized_widget_key = self._normalize_text(widget_key)
state = self._window_states.get(normalized_widget_key)
if state is None:
state = WindowState()
self._window_states[normalized_widget_key] = state
return state
def _normalize_text(self, value: str) -> str:
return str(value).strip()
def _normalize_key_type(self, key_type: str) -> str:
normalized = str(key_type).strip().lower()
if normalized not in {'bool', 'int', 'float', 'str'}:
raise ValueError(f"Unsupported key type '{key_type}'. Expected one of: bool, int, float, str.")
return normalized
def _serialize_value(self, value: Any, key_type: str) -> str:
normalized = self._normalize_key_type(key_type)
if normalized == 'bool':
return '1' if bool(value) else '0'
if normalized == 'int':
return str(int(value))
if normalized == 'float':
return str(float(value))
return str(value)
def _deserialize_value(self, value: str, key_type: str) -> Any:
normalized = self._normalize_key_type(key_type)
if normalized == 'bool':
return str(value).strip().lower() in {'1', 'true', 'yes', 'on'}
if normalized == 'int':
return int(value)
if normalized == 'float':
return float(value)
return str(value)
def _get_current_account_email(self) -> str:
from ..Player import Player
return str(Player.GetAccountEmail() or '').strip()
# ------------------------------------------------------------------
# Window config (unchanged — transparently benefits from cache)
# ------------------------------------------------------------------
def begin_window_config(self, widget_key: str) -> None:
import PyImGui
if not widget_key:
return
state = self._get_window_state(widget_key)
state.begin_called = True
state.begin_returned_true = False
if state.initialized:
return
settings = self.ForWidget(widget_key)
state.x_pos = settings.GetInt('Window config', 'x', default=0)
state.y_pos = settings.GetInt('Window config', 'y', default=0)
state.width = settings.GetInt('Window config', 'width', default=0)
state.height = settings.GetInt('Window config', 'height', default=0)
state.collapsed = settings.GetBool('Window config', 'collapsed', default=False)
PyImGui.set_next_window_pos(state.x_pos, state.y_pos)
if state.width > 0 and state.height > 0:
PyImGui.set_next_window_size(state.width, state.height)
PyImGui.set_next_window_collapsed(state.collapsed, 0)
state.initialized = True
def mark_begin_success(self, widget_key: str) -> None:
if not widget_key:
return
self._get_window_state(widget_key).begin_returned_true = True
def track_window_collapsed(self, widget_key: str, begin_result: bool) -> None:
if not widget_key:
return
state = self._get_window_state(widget_key)
new_collapsed = not begin_result
if new_collapsed == state.collapsed:
return
state.collapsed = new_collapsed
self.ForWidget(widget_key).SetBool('Window config', 'collapsed', state.collapsed)
def end_window_config(self, widget_key: str) -> None:
import PyImGui
if not widget_key:
return
state = self._get_window_state(widget_key)
if not state.begin_called or not state.begin_returned_true:
state.begin_called = False
state.begin_returned_true = False
return
end_pos = PyImGui.get_window_pos()
end_size = PyImGui.get_window_size()
new_x = int(end_pos[0])
new_y = int(end_pos[1])
new_width = int(end_size[0])
new_height = int(end_size[1])
settings = self.ForWidget(widget_key)
if new_x != state.x_pos:
state.x_pos = new_x
settings.SetInt('Window config', 'x', state.x_pos)
if new_y != state.y_pos:
state.y_pos = new_y
settings.SetInt('Window config', 'y', state.y_pos)
if new_width != state.width:
state.width = new_width
settings.SetInt('Window config', 'width', state.width)
if new_height != state.height:
state.height = new_height
settings.SetInt('Window config', 'height', state.height)
state.begin_called = False
state.begin_returned_true = False
# ------------------------------------------------------------------
# Widget-table methods (unchanged — direct DB, no cache)
# ------------------------------------------------------------------
def _get_widget_row(self, widget_key: str, commit: bool = True) -> Optional[dict]:
return self.GetFirstEntry(self.WIDGET_TABLE, 'Key', self._normalize_text(widget_key), commit=commit)
def _get_global_row(self, widget_id: int, section: str, key: str, commit: bool = True) -> Optional[dict]:
rows = self.Select(
self.GLOBALS_TABLE,
where={
'WidgetID': int(widget_id),
'Section': self._normalize_text(section),
'Key': self._normalize_text(key),
},
limit=1,
commit=commit,
)
return rows[0] if rows else None
def _get_account_row(self, widget_id: int, account_id: int, section: str, key: str, commit: bool = True) -> Optional[dict]:
rows = self.Select(
self.KEYS_TABLE,
where={
'WidgetID': int(widget_id),
'AccountID': int(account_id),
'Section': self._normalize_text(section),
'Key': self._normalize_text(key),
},
limit=1,
commit=commit,
)
return rows[0] if rows else None
def RegisterWidget(self, widget_key: str, name: str, description: Optional[str] = None, commit: bool = True) -> int:
nwk = self._normalize_text(widget_key)
existing = self._get_widget_row(widget_key, commit=commit)
if existing is not None:
wid = int(existing['ID'])
self._widget_cache[nwk] = wid # M3: keep widget cache in sync
self._widget_id_cache[wid] = nwk
self._widget_info_cache[nwk] = (
self._normalize_text(existing['Name'] or nwk),
existing.get('Description'),
)