-
Notifications
You must be signed in to change notification settings - Fork 7
/
cd_kv_dlg.py
2067 lines (1884 loc) · 98.2 KB
/
cd_kv_dlg.py
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
''' Lib for Plugin
Authors:
Andrey Kvichansky (kvichans on github.com)
Version:
'1.1.01 2019-07-01'
Content
See github.com/kvichans/cuda_kv_dlg/wiki
ToDo: (see end of file)
'''
import sys, os, tempfile, json, re
from time import perf_counter
import cudatext as app
from cudatext import ed
import cudax_lib as apx
from .cd_kv_base import * # as part of this plugin
VERSION = re.split('Version:', __doc__)[1].split("'")[1]
VERSION_V, \
VERSION_D = VERSION.split(' ')
version = lambda: VERSION_V
_ = None
try:
_ = get_translation(__file__) # I18N
except:pass
pass; _log4mod = -1 #LOG_FREE # Order log in the module
pass; from pprint import pformat
pass; pfw=lambda d,w=150:pformat(d,width=w)
_TYPE_ABBRS = {
'labl': 'label'
,'lilb': 'linklabel'
,'edit': 'edit'
,'edtp': 'edit_pwd'
,'sped': 'spinedit'
,'memo': 'memo'
,'bttn': 'button'
,'rdio': 'radio'
,'chck': 'check'
,'chbt': 'checkbutton'
,'chgp': 'checkgroup'
,'rdgp': 'radiogroup'
,'cmbx': 'combo'
,'cmbr': 'combo_ro'
,'libx': 'listbox'
,'clbx': 'checklistbox'
,'livw': 'listview'
,'clvw': 'checklistview'
,'tabs': 'tabs'
,'clpn': 'colorpanel'
,'imag': 'image'
,'flbx': 'filter_listbox'
,'flvw': 'filter_listview'
,'bvel': 'bevel'
,'panl': 'panel'
,'grop': 'group'
,'splt': 'splitter'
,'pags': 'pages'
,'trvw': 'treeview'
,'edtr': 'editor'
,'stbr': 'statusbar'
,'btex': 'button_ex'
}
_TYPE_WITH_VALUE = {
'edit'
,'edit_pwd'
,'spinedit'
,'memo'
,'radio'
,'check'
,'checkbutton'
,'checkgroup'
,'radiogroup'
,'combo'
,'combo_ro'
,'listbox'
,'checklistbox'
,'listview'
,'checklistview'
,'tabs'
,'filter_listbox'
,'filter_listview'
,'pages'
# ,'grop'
# ,'splt'
# ,'pags'
# ,'trvw'
# ,'edtr'
# ,'stbr'
# ,'btex'
}
_ATTR_ABBRS = {
'cols' : 'columns'
,'au' : 'autosize'
,'ali' : 'align'
,'sto' : 'tab_stop'
,'tor' : 'tab_order'
,'thint': 'texthint'
}
_ATTR_TP_ABBRS = {**_ATTR_ABBRS, 'tp':'type'}
#_ATTR_TP_ABBRS = upd_dict(_ATTR_ABBRS, {'tp':'type'})
_LIVE_ATTRS = {'r', 'b', 'x', 'y', 'w', 'h', 'val', 'columns', 'cols', 'cols_ws', 'items'}
_LIVE_CALC_ATTRS= {'r', 'b'}
CB_HIDE = lambda ag,name,d='':None # Control callback to hide dlg
CBP_WODATA = lambda cb_user: lambda ag,name,d='':cb_user(ag,name) # Callback-proxy to skip data
ALI_CL = app.ALIGN_CLIENT
ALI_LF = app.ALIGN_LEFT
ALI_RT = app.ALIGN_RIGHT
ALI_TP = app.ALIGN_TOP
ALI_BT = app.ALIGN_BOTTOM
SCROLL_W= app.app_proc(app.PROC_GET_GUI_HEIGHT, 'scrollbar')
pair_list_to_dict = lambda pair_lst: {p[0]:p[1] for p in pair_lst if p}
class DlgAg:
# See github.com/kvichans/cuda_kv_dlg/wiki
@staticmethod
def version(): return VERSION_V
###############
## Creators
###############
def __del__(self):
_dlg_proc(self.did, app.DLG_FREE) if self.did else 0
def __init__(self, ctrls, form, vals=None, fid=None, opts=None):
""" Create dialog """
pass; log4fun=0 # Order log in the function
# Fields
self._retval= None # Last event src-cid or user pointed val to return from show()
self._hidden= True # State of form
self._dockto= '' # State of form
self._modal = None # State of form
self._onetime = False # Free form data on hide
self._skip_free = False # To ban to free form data
self.locks = 0 # Lock counter to batch updates
self.opts = opts.copy() if opts else {}
ctrl_to_meta= self.opts.get('ctrl_to_meta', 'by_os')
self._c2m = ctrl_to_meta=='need' or \
ctrl_to_meta=='by_os' and \
'mac'==get_desktop_environment() # Need to translate 'Ctrl+' to 'Meta+' in hint,...
self.did = app.dlg_proc(0, app.DLG_CREATE)
self.ctrls = None # Mem-attrs of all controls {cid:{k:v}}
self.form = None # Mem-attrs of form {k:v}
self._setup(ctrls, form, vals, fid)
self.gen_repro_code()
#def __init__
def show(self, on_exit=None, modal=True, onetime=True):
""" Show the dialog
on_exit Call the function after dlg was hidden
modal Show as modal or nonmodal
onetime Free resources (if True) after or wait next show() (if False)
Return (if modal): (retval, vals)
retval Value of param ag.hide(retval) or None
vals Last live val properties of all controls
"""
pass; log4fun=0 # Order log in the function
pass; log__('modal, self._dockto, onetime, ed={}', (modal, self._dockto, onetime, ed) ,__=(log4fun,)) if _log4mod>=0 else 0
if not self.did:
raise ValueError('Dialog data is already destroyed (see "onetime" parameter)')
self._modal = modal if not self._dockto else False
self._retval = None
self._hidden = False
self._onetime = onetime
ed_caller = ed if self._modal else None
def when_close():
pass; log__("self.fattr('p')={}",self.fattr('p') ,__=(log4fun,)) if _log4mod>=0 else 0
if not self.fattr('p'): # Not docked
_form_acts('save', did=self.did
,key4store=self.opts.get('form data key')) \
if self.opts.get('restore_position', True) else 0
for cid in self.opts.get('store_col_widths', []):
self._cols_serv('save-ws', cid=cid)
if callable(on_exit):
on_exit(self)
vals = self.vals(live=True) if self._modal else None
if onetime:
if self._modal:
_dlg_proc(self.did, app.DLG_FREE)
else:
app.timer_proc(app.TIMER_START_ONE, lambda tag:app.dlg_proc(int(tag)
, app.DLG_FREE)
,200 ,tag= str(self.did)
)
self.did = 0
ed_to_focus = self.opts.get('on_exit_focus_to_ed', ed_caller)
pass; log__('ed_to_focus={}',ed_to_focus ,__=(log4fun,)) if _log4mod>=0 else 0
if ed_to_focus:
ed_to_focus.focus()
elif not self._modal:
ed.focus()
self._modal = None
return (self._retval, vals)
#def when_close
if self._modal:
pass; log__('as modal' ,__=(log4fun,)) if _log4mod>=0 else 0
# self._modal = True
app.dlg_proc(self.did, app.DLG_SHOW_MODAL)
return when_close()
# Nonmodal
app.dlg_proc(self.did, app.DLG_PROP_SET
,prop=dict(on_close=lambda idd, idc=0, data='':
when_close()))
pass; log__('as nonmodal' ,__=(log4fun,)) if _log4mod>=0 else 0
# self._modal = False
app.dlg_proc(self.did, app.DLG_SHOW_NONMODAL)
self.activate()
return (None, None)
#def show
###############
## Getters
###############
def focused(self, live=True):
if not live: return self.form.get('fid')
form = _dlg_proc(self.did, app.DLG_PROP_GET)
c_ind = form.get('focused')
c_pr = _dlg_proc(self.did, app.DLG_CTL_PROP_GET, index=c_ind)
return c_pr['name'] if c_pr else None
#def focused
def fattr(self, attr, defv=None, live=True):
""" Return one form property """
if attr in ('focused', 'fid'): return self.focused(live)
pr = _dlg_proc(self.did, app.DLG_PROP_GET) if live else self.form
return pr.get(attr, defv)
#def fattr
def fattrs(self, attrs=None, live=True):
""" Return form properties """
pr = _dlg_proc(self.did, app.DLG_PROP_GET) if live else self.form
return pr if not attrs else \
{attr:(self.focused(live) if attr in ('focused', 'fid') else pr.get(attr))
for attr in attrs}
#def fattrs
def _cattr(self, lpr, cid, attr, attr_=None, defv=None):
attr_ = attr_ if attr_ else _ATTR_TP_ABBRS.get(attr, attr)
pass; #log("cid, attr, attr_={}",(cid, attr, attr_))
pass; #log("lpr={}",(lpr))
if attr not in lpr and \
attr_ not in lpr and \
attr not in _LIVE_CALC_ATTRS: # Only into mem
mpr = self.ctrls[cid]
if attr in mpr: return mpr[attr ]
if attr_ in mpr: return mpr[attr_]
pass; #log("cid, defv={}",(cid,defv))
return defv
if attr=='r':
return lpr['x'] + lpr['w']
if attr=='b':
return lpr['y'] + lpr['h']
rsp = lpr.get(attr, lpr.get(attr_, defv))
if attr=='val' and rsp:
return self._take_val( cid , rsp, defv)
if attr in ('cols_ws'): pass # See cattr/cattrs
if attr in ('items', 'columns', 'cols') and rsp:
return self._take_it_cl(cid, attr, rsp, defv)
pass; #log("name, rsp={}",(name, rsp))
return rsp
#def _cattr
def cattr(self, name, attr, defv=None, live=True):
""" Return the attribute of the control.
If no the attribute return defv.
Take attribute value from screen (live) or from last settings (not live).
"""
if name not in self.ctrls: raise ValueError(f'Unknown name: {name}')
if attr=='cols_ws':
return self._cols_serv('get-ws', name, live=live)
attr_ = _ATTR_TP_ABBRS.get(attr, attr)
mpr = self.ctrls[name]
if not live:
return mpr.get(attr, mpr.get(attr_, defv))
else:# live:
# Some attrs not changable - return mem-value (if is)
if attr not in _LIVE_ATTRS and attr in mpr: return mpr[attr ]
if attr_ not in _LIVE_ATTRS and attr_ in mpr: return mpr[attr_]
lpr = _dlg_proc(self.did, app.DLG_CTL_PROP_GET, name=name)
rsp = self._cattr(lpr, name, attr, attr_)
return rsp
#def cattr
def cattrs(self, name, attrs=None, live=True):
""" Return the control attributes """
pass; log4fun=1 # Order log in the function
if name not in self.ctrls: raise ValueError(f'Unknown name: {name}')
mpr = self.ctrls[name]
if not live:
attrs = attrs if attrs else mpr
return {attr: self.cattr(name, attr, live=live) if attr=='cols_ws' else
mpr.get(attr)
for attr in attrs
}
elif attrs:# and live
# Are all attrs not changable? - return mem-values (if is)
rsp_attrs = {}
for attr in attrs:
attr_ = _ATTR_TP_ABBRS.get(attr, attr)
if attr not in _LIVE_ATTRS and attr in mpr:
rsp_attrs[attr ] = attr
elif attr_ not in _LIVE_ATTRS and attr_ in mpr:
rsp_attrs[attr ] = attr_
else:
rsp_attrs = None
break#for
pass; #log("rsp_attrs={}",(rsp_attrs))
if rsp_attrs:
return {attr: mpr.get(rsp_attrs[attr]) for attr in rsp_attrs}
lpr = _dlg_proc(self.did, app.DLG_CTL_PROP_GET, name=name)
attrs = attrs if attrs else list(lpr.keys())
return {attr: self.cattr(name, attr, live=live) if attr=='cols_ws' else
self._cattr(lpr, name, attr)
for attr in attrs
}
#def cattrs
def val(self, name, live=True):
""" Return the control val property """
return self.cattr(name, 'val', defv=None, live=live)
def vals(self, names=None, live=True):
""" Return val property for the controls
or (if names==None) for all controls with val
"""
names = names \
if names else \
[cid for (cid,cfg) in self.ctrls.items()
if cfg['type'] in _TYPE_WITH_VALUE]
return {cid: self.cattr(cid, 'val', defv=None, live=live)
for cid in names}
###############
## Updaters
###############
def reset(self, ctrls, form, vals=None, fid=None, opts=None):
pass; log4fun=0 # Order log in the function
_form_acts('save', did=self.did
,key4store=self.opts.get('form data key')) \
if self.opts.get('restore_position', True) else 0
app.dlg_proc(self.did, app.DLG_CTL_DELETE_ALL)
self.opts = opts.copy() if opts else {}
self._setup(ctrls, form, vals, fid)
return []
#def reset
def _lock(self, how):
pass; #print(f'_lock: how={how} self.locks={self.locks}')
pass; #return
if False:pass
elif how=='+':
if self.locks==0:
app.dlg_proc(self.did, app.DLG_LOCK)
self.locks += 1
elif how=='-':
self.locks = max(0, self.locks-1)
if self.locks==0:
app.dlg_proc(self.did, app.DLG_UNLOCK)
elif how=='.':
if self.locks >0:
app.dlg_proc(self.did, app.DLG_UNLOCK)
self.locks = 0
#def _lock
def update(self, upds=None, ctrls=[], form={}, vals={}, fid='', retval=None, opts=None):
""" Update most of dlg props
upds dict(ctrls=, form=, vals=, fid=)
ctrls [(name, {k:v})] or {name:{k:v}}
form {k:v}
vals {name:v}
fid name
Or list of such dicts
retval Value to "show()" return if form will be hidden during the update
"""
pass; log4fun=0 # Order log in the function
if upds is None and (ctrls or form or vals or fid):
upds = dict(ctrls=ctrls.copy(), form=form.copy(), vals=vals.copy())
if fid:
upds['fid'] = fid
pass; log__("upds, retval, opts={}",(upds, retval, opts) ,__=(log4fun,)) if _log4mod>=0 else 0
# if self._hidden:
# pass; log__('skip as hidden' ,__=(log4fun,)) if _log4mod>=0 else 0
# return
if upds is None: # To hide/close
pass; #log__('to hide' ,__=(log4fun,)) if _log4mod>=0 else 0
if retval is not None and self._retval is None:
self._retval = retval
if self._skip_free:
self._skip_free = False
return
app.dlg_proc(self.did, app.DLG_HIDE)
self._hidden = True
return
if upds is False:
pass; #log__('to stop ev' ,__=(log4fun,)) if _log4mod>=0 else 0
return False # False to cancel the current event
if upds in ([], {}):
return
if likeslist(upds): # Allow to use list of upd data
pass; #log__('many upds' ,__=(log4fun,)) if _log4mod>=0 else 0
shown = not self._hidden
self._lock('+')
for upd in upds:
self.update(upd, retval=retval, opts=opts)
if shown and self._hidden: break # hide is called on update
self._lock('-')
return
self._lock('+')
cupds = upds.get('ctrls', [])
cupds = pair_list_to_dict(cupds) if likeslist(cupds) else cupds
pass; log__('cupds={}',(cupds) ,__=(log4fun,)) if _log4mod>=0 else 0
vals = upds.get('vals', {})
form = upds.get('form', {})
DlgAg._check_data(self.ctrls, cupds, form, vals, upds.get('fid'))
if False:pass
elif vals and not cupds: # Allow to update only val in some controls
cupds = { cid_ : {'val':val} for cid_, val in vals.items()}
pass; #log("+vals-cupds cupds={}",(cupds))
elif vals and cupds:
for cid_, val in vals.items():
if cid_ not in cupds:
cupds[cid_] = {'val':val} # Merge vals to cupds
else:
cupds[cid_]['val'] = val # NB! Prefer val from vals but not from cupds
for cid_, cfg in cupds.items():
cfg['tp'] = self.ctrls[cid_]['tp'] # Type is stable
cfg['type'] = self.ctrls[cid_]['type'] # Type is stable
skip_form_upd = opts and opts.get('_skip_form_upd' , False)
skip_ctrls_upd = opts and opts.get('_skip_ctrls_upd', False)
if form:
self.form.update(form) if not skip_form_upd else 0
pass; #log('form={}',(self.fattrs(live=F)))
pass; #log('form={}',(self.fattrs()))
pass; #log('form={}',(form))
_dlg_proc(self.did, app.DLG_PROP_SET
,prop=form)
if cupds:
for cid, new_cfg in cupds.items():
pass; #log__('cid, new_cfg={}',(cid, new_cfg) ,__=(log4fun,)) if _log4mod>=0 else 0
cfg = self.ctrls[cid]
pass; #log__('cfg={}',(cfg) ,__=(log4fun,)) if _log4mod>=0 else 0
cfg.update(new_cfg) if not skip_ctrls_upd else 0
pass; #log__('cfg={}',(cfg) ,__=(log4fun,)) if _log4mod>=0 else 0
c_prop = self._prepare_control_prop(cid, new_cfg, {'ctrls':cupds})
pass; #log('c_prop={}',(c_prop)) if new_ctrl['type']=='listview' else None
pass; log__('c_prop={}',(c_prop) ,__=(log4fun,)) if _log4mod>=0 else 0
_dlg_proc(self.did, app.DLG_CTL_PROP_SET
,name=cid
,prop=c_prop
)
if 'fid' in upds or 'fid' in form:
fid = upds.get('fid', form.get('fid'))
self.form['fid']= fid
app.dlg_proc(self.did, app.DLG_CTL_FOCUS
,name=fid)
self._lock('-')
#def update
@staticmethod
def _check_data(mem_ctrls, ctrls, form, vals, fid):
# Check cid/tid/fid in (ctrls, form, vals, fid) to exist into mem_ctrls
if 'skip checks'!='skip checks': return
if likeslist(ctrls):
cids = [cid_cnt[0] for cid_cnt in ctrls if cid_cnt]
cids_d = [cid for cid in cids if cids.count(cid)>1]
if cids_d:
raise ValueError(f'Repeated names: {set(cids_d)}')
no_tids = {cnt['tid']
for cnt in ctrls
if cnt and 'tid' in cnt and
cnt['tid'] not in mem_ctrls}
if no_tids:
raise ValueError(f'No name for tid: {no_tids}')
if 'fid' in form and form['fid'] not in mem_ctrls:
raise ValueError(f('No name for form[fid]: {}', form['fid']))
no_vals = {cid
for cid in vals
if cid not in mem_ctrls} if vals else None
if no_vals:
raise ValueError(f'No name for val: {no_vals}')
if fid is not None and fid not in mem_ctrls:
raise ValueError(f'No name for fid: {fid}')
#def _check_data
def _setup(self, ctrls, form, vals=None, fid=None):
""" Arrange and fill all: controls attrs, form attrs, focus.
Params
ctrls [(name, {k:v})] or {name:{k:v}}
NB! Only from 3.7 Python saves key sequence for dict.
The sequence is important for tab-order of controls.
form {k:v}
vals {name:v}
fid name
"""
pass; log4fun=0 # Order log in the function
#NOTE: DlgAg init
self.ctrls = pair_list_to_dict(ctrls) if likeslist(ctrls) else ctrls.copy()
self.form = form.copy()
fid = fid if fid else form.get('fid', form.get('focused')) # focused?
DlgAg._check_data(self.ctrls, ctrls, form, vals, fid)
if vals:
for cid, val in vals.items():
self.ctrls[cid]['val'] = val
# Create controls
for cid, ccfg in self.ctrls.items():
tp = ccfg.get('tp', ccfg.get('type'))
if not tp:
raise ValueError(f'No type/tp for name: {cid}')
ccfg['tp'] = tp
ccfg['type'] = _TYPE_ABBRS.get(tp, tp)
pass; #log("tp,type={}",(tp,ccfg['type']))
# Create control
_dlg_proc(self.did, DLG_CTL_ADD_SET
,name=ccfg['type']
,prop=self._prepare_control_prop(cid, ccfg))
#for cid, ccfg
# Prepare form
fpr = self.form
fpr['topmost'] = True
wait_resize = 'auto_stretch_col' in self.opts # Agent will stretch column(s)
# Prepare callbacks
def get_proxy_cb(u_callbk, event):
def form_callbk(idd, key=-1, data=''):
pass; #log("event,wait_resize={}",(event,wait_resize))
if wait_resize and event=='on_resize':
self.update(self._on_resize()
,opts={'_skip_ctrls_upd':True}) # Agent acts: stretch column(s), ...
self._skip_free = (event=='on_resize') # Ban to close dlg by some events (on_resize,...)
upds = u_callbk(self, key, data)
if event=='on_close_query': # No upd, only bool about form close
return upds
# rsp = self.update(upds) # :(
# self._lock('.') # :(
# return rsp # :(
return self.update(upds)
return form_callbk
if wait_resize and 'on_resize' not in fpr:
fpr['on_resize'] = lambda ag,k,d:[] # Empty user callback
for on_key in [k for k in fpr if k[:3]=='on_' and callable(fpr[k])]:
fpr[on_key] = get_proxy_cb(fpr[on_key], on_key)
self._prepare_anchors() # a,aid -> a_*,sp_*
for cid in self.opts.get('store_col_widths', []):
self._cols_serv('restore-ws', cid=cid)
self._prepare_frame() # frame, border, on_resize
if fid:
fpr['fid'] = fid # Save in mem
app.dlg_proc(self.did, app.DLG_CTL_FOCUS, name=fid) # Push to live
#def _setup
def _on_resize(self):
pass; #log("",())
cupd = {}
if 'auto_stretch_col' in self.opts:
for cid, stch in self.opts['auto_stretch_col'].items():
if cid not in self.ctrls: continue
ctrl_w = self.cattr(cid, 'w')
if cid in self.opts.get('auto_start_col_width_on_min', []) and \
ctrl_w==self.cattr(cid, 'w', live=False):
# Min width - restore mem col width
col_ws = self.cattr(cid, 'cols_ws', live=False)
pass; #log("mem ws={}",(col_ws))
else:
cols = self.cattr(cid, 'cols', live=False)
cols = cols if cols else self.cattr(cid, 'cols')
min_cw = cols[stch].get('mi', 20)
min_cw = min_cw if min_cw else 20
col_ws = self.cattr(cid, 'cols_ws')
extra = ctrl_w - len(col_ws) - SCROLL_W - sum(col_ws)
pass; #log("w,SCROLL_W,extra,stch,ws[stch]={}",(ctrl_w,SCROLL_W,extra,stch,col_ws[stch]))
col_ws[stch]= max(min_cw, col_ws[stch] + extra)
pass; #log("calc ws={}",(col_ws))
cupd[cid] = dict(cols_ws=col_ws)
pass; #log("ws={}",(col_ws))
pass; #log("cupd={}",(cupd))
return {'ctrls':cupd} if cupd else []
#def _on_resize
def _prepare_frame(self, fpr=None):
fpr = self.form if fpr is None else fpr
w0,h0 = fpr['w'],fpr['h']
pass; #log("fpr['on_resize']={}",(fpr['on_resize']))
if callable(fpr.get('on_resize')) and 'resize' not in fpr.get('frame', ''):
fpr['frame'] = fpr.get('frame', '') + 'resize'
if False:pass
elif 'frame' not in fpr and 'border' not in fpr:
fpr['border'] = app.DBORDER_DIALOG
elif 'border' in fpr:
pass
elif 'no' in fpr['frame']:
fpr['border'] = app.DBORDER_NONE
elif 'resize' in fpr['frame'] and ('full-cap' in fpr['frame'] or 'min-max' in fpr['frame']):
fpr['border'] = app.DBORDER_SIZE
elif 'resize' in fpr['frame']:
fpr['border'] = app.DBORDER_TOOLSIZE
elif 'full-cap' in fpr['frame'] or 'min-max' in fpr['frame']:
fpr['border'] = app.DBORDER_SINGLE
pass; #log("fpr['border']={}",(fpr['border'], get_const_name(fpr['border'], 'DBORDER_')))
if fpr.get('border') in (app.DBORDER_SIZE, app.DBORDER_TOOLSIZE):
fpr['w_min'] = fpr.get('w_min', w0)
fpr['h_min'] = fpr.get('h_min', h0)
fpr.pop('resize', None)
# Restore prev pos/sizes
fpr = _form_acts('move', fprs=fpr # Move and (maybe) resize
, key4store=self.opts.get('form data key')) \
if self.opts.get('restore_position', True) else fpr
pass; #log("fpr['on_resize']={}",(fpr['on_resize']))
pass; #log("fpr={}",(fpr))
if 'on_resize' in fpr and (fpr['w'],fpr['h']) != (w0,h0):
pass; #log("fpr['on_resize']={}",(fpr['on_resize']))
def on_show(idd,idc='',data=''):
self.form['on_resize'](self)
return []
fpr['on_show'] = on_show
_dlg_proc(self.did, app.DLG_PROP_SET, prop=fpr.copy()) # Push to live
#def _prepare_frame
def _prepare_control_prop(self, cid, ccfg, opts={}):
pass; log4fun=0 # Order log in the function
Self = self.__class__
pass; log__('cid, ccfg={}',(cid, ccfg) ,__=(log4fun,)) if _log4mod>=0 else 0
EXTRA_C_ATTRS = ['tp','r','b','tid','a','aid']
tp = ccfg['type']
pass; log__('cid, ccfg={}',(cid, ccfg) ,__=(log4fun,)) if _log4mod>=0 else 0
Self._preprocessor(ccfg, tp) # sto -> tab_stop,... EXTRA_C_ATTRS
pass; log__('cid, ccfg={}',(cid, ccfg) ,__=(log4fun,)) if _log4mod>=0 else 0
c_pr = {k:v for (k,v) in ccfg.items()
if k not in ['items', 'val', 'columns', 'cols', 'cols_ws']
+EXTRA_C_ATTRS and
(k[:3]!='on_' or k=='on')}
c_pr['name'] = cid
pass; log__('cid, ccfg={}',(cid, ccfg) ,__=(log4fun,)) if _log4mod>=0 else 0
c_pr = self._prepare_vl_it_cl(c_pr, ccfg, cid, opts) #if k in ['items', 'val', 'cols']
c_pr.update(
self._prep_pos_attrs(ccfg, cid, opts.get('ctrls')) # r,b,tid -> x,y,w,h
)
pass; log__('c_pr={}',(c_pr) ,__=(log4fun,)) if _log4mod>=0 else 0
# Remove deprecated
for attr in ('props',):
c_pr.pop(attr, None)
if self._c2m and 'hint' in c_pr:
c_pr['hint'] = c_pr['hint'].replace('Ctrl+', 'Meta+')
# Prepare callbacks
def get_proxy_cb(u_callbk, event):
def ctrl_callbk(idd, idc, data):
pass; #log('ev,idc,cid,data={}',(event,idc,cid,data))
# if tp in ('listview',) and type(data) in (tuple, list):
if tp in ('listview',) and likeslist(data):
if not data[1]: return # Skip event "selection loss"
# Crutch for Linux! Wait fix in core
event_val = app.dlg_proc(idd, app.DLG_CTL_PROP_GET, index=idc)['val']
if event_val!=data[0]:
app.dlg_proc( idd, app.DLG_CTL_PROP_SET, index=idc, prop={'val':data[0]})
upds = u_callbk(self, cid, data)
rsp = self.update(upds, retval=cid)
self._lock('.')
return rsp
# return self.update(upds, retval=cid)
#def ctrl_callbk
return ctrl_callbk
#def get_proxy_cb
for on_key in [k for k in ccfg if k[:3]=='on_' and callable(ccfg[k])]:
if tp!='button':
c_pr['act'] = True
c_pr[on_key] = get_proxy_cb(ccfg[on_key], on_key)
#for on_key
return c_pr
#def _prepare_control_prop
def _prep_pos_attrs(self, cnt, cid, ctrls4cid=None):
pass; log4fun=0 # Order log in the function
ctrls4cid = ctrls4cid if ctrls4cid else self.ctrls
reflect = self.opts.get('negative_coords_reflect', False)
pass; log__('cid, reflect, cnt={}',(cid, reflect, cnt) ,__=(log4fun,)) if _log4mod>=0 else 0
prP = {}
cnt_ty = ctrls4cid[cid].get('tp', ctrls4cid[cid].get('type'))
cnt_ty = _TYPE_ABBRS.get(cnt_ty, cnt_ty)
if cnt_ty in ('label', 'linklabel'
,'combo', 'combo_ro'
) \
or 'h' not in cnt and \
cnt_ty in ('button', 'checkbutton'
,'edit', 'spinedit'
,'check', 'radio'
,'filter_listbox', 'filter_listview'
):
# OS specific control height
cnt['h'] = _get_gui_height(cnt_ty) # Some types kill 'h'
prP['_ready_h'] = True # Skip scaling
pass; #log('cnt={}',(cnt)) if cnt_ty=='checkbutton' else 0
if 'tid' in cnt:
assert cnt['tid'] in ctrls4cid
# cid for horz-align text
bas_cnt = ctrls4cid[ cnt['tid']]
bas_ty = bas_cnt.get('tp', bas_cnt.get('type'))
bas_ty = _TYPE_ABBRS.get(bas_ty, bas_ty)
t = bas_cnt.get('y', 0) + _fit_top_by_env(cnt_ty, bas_ty)
cnt['y'] = t # 'tid' kills 'y'
if reflect and (
cnt.get('x', 0)<0 or
cnt.get('r', 0)<0 or
cnt.get('y', 0)<0 or
cnt.get('b', 0)<0 ): #NOTE: reflect
def do_reflect(cnt_, k, pval):
if 0>cnt_.get(k, 0):
pass; log__('cid, k, pval, cnt_={}',(cid, k, pval, cnt_) ,__=(log4fun,)) if _log4mod>=0 else 0
cnt_[k] = pval + cnt_[k]
pass; log__('cnt_={}',(cnt_) ,__=(log4fun,)) if _log4mod>=0 else 0
pass; #log('cid,cnt={}',(cid,cnt))
prnt = cnt.get('p', self.form)
prnt = self.ctrls[prnt] if likesstr(prnt) else prnt ##?? Only form/[panel/]ctrl
prnt_w = prnt.get('w', self.form.get('w', 0)) ##?? Only form/[panel/]ctrl
prnt_h = prnt.get('h', self.form.get('h', 0)) ##?? Only form/[panel/]ctrl
pass; log__('prnt={}',(prnt) ,__=(log4fun,)) if _log4mod>=0 else 0
pass; log__('prnt_w,prnt_h={}',(prnt_w,prnt_h) ,__=(log4fun,)) if _log4mod>=0 else 0
pass; log__('cnt={}',(cnt) ,__=(log4fun,)) if _log4mod>=0 else 0
pass; #log('cnt={}',({k:v for k,v in cnt.items() if k in [('x','r','w')]}))
do_reflect(cnt, 'x', prnt_w)
do_reflect(cnt, 'r', prnt_w)
do_reflect(cnt, 'y', prnt_h)
do_reflect(cnt, 'b', prnt_h)
pass; #log('cnt={}',({k:v for k,v in cnt.items() if k in [('x','r','w')]}))
pass; log__('cnt={}',(cnt) ,__=(log4fun,)) if _log4mod>=0 else 0
def calt_third(kasx, kasr, kasw, src, trg):
# Use d[kasw] = d[kasr] - d[kasx]
# to copy val from src to trg
# Skip kasr if it is redundant
if False:pass
elif kasx in src and kasw in src: # x,w or y,h is enough
trg[kasx] = src[kasx]
trg[kasw] = src[kasw]
elif kasr in src and kasw in src: # r,w or b,h to calc
trg[kasx] = src[kasr] - src[kasw]
trg[kasw] = src[kasw]
elif kasx in src and kasr in src: # x,r or y,b to calc
trg[kasx] = src[kasx]
trg[kasw] = src[kasr] - src[kasx]
return trg
#def calt_third
pass; #log('cnt={}',cnt)#({k:cnt[k] for k in cnt if k in [('x','r','w')]}))
pass; #log('prP={}',prP)#({k:prP[k] for k in prP if k in [('x','r','w')]}))
prP = calt_third('x', 'r', 'w', cnt, prP)
prP = calt_third('y', 'b', 'h', cnt, prP)
pass; #log('prP={}',prP)#({k:prP[k] for k in prP if k in [('x','r','w')]}))
pass; #log__('cid, prP={}',(cid, prP) ,__=(log4fun,)) if _log4mod>=0 else 0
return prP
#def _prep_pos_attrs
def _prepare_vl_it_cl(self, c_pr, cfg_ctrl, cid, opts={}):
pass; log4fun=0 # Order log in the function
pass; log__('c_pr={}',(c_pr) ,__=(log4fun,)) if _log4mod>=0 else 0
pass; log__('cfg_ctrl={}',(cfg_ctrl) ,__=(log4fun,)) if _log4mod>=0 else 0
pass; log__('opts={}',(opts) ,__=(log4fun,)) if _log4mod>=0 else 0
tp = cfg_ctrl['type']
if 'val' in cfg_ctrl and opts.get('prepare val', True):
in_val = cfg_ctrl['val']
def list_to_list01(lst):
return list(('1' if v=='1' or v is True else '0')
for v in lst)
if False:pass
elif tp=='memo':
# For memo: "\t"-separated lines (in lines "\t" must be replaced to chr(3))
pass; log__("tp,in_val={}",(tp,in_val) ,__=(log4fun,)) if _log4mod>=0 else 0
if likeslist(in_val):
in_val = '\t'.join([v.replace('\t', chr(3)) for v in in_val])
else:
in_val = in_val.replace('\t', chr(3)).replace('\r\n','\n').replace('\r','\n').replace('\n','\t')
pass; log__("tp,in_val={}",(tp,in_val) ,__=(log4fun,)) if _log4mod>=0 else 0
elif tp=='checkgroup' and likeslist(in_val):
# For checkgroup: ","-separated checks (values "0"/"1")
in_val = ','.join(list_to_list01(in_val))
elif tp in ['checklistbox', 'checklistview'] and likeslist(in_val):
# For checklistbox, checklistview: index+";"+checks
in_val = ';'.join( (str(in_val[0]), ','.join(list_to_list01(in_val[1])) ) )
elif tp in ['listbox', 'combo_ro'] and 'ivals' in cfg_ctrl and cfg_ctrl['ivals']:
ivals = cfg_ctrl['ivals']
in_val = ivals.index(in_val) if in_val in ivals else -1
c_pr['val'] = in_val
if 'items' in cfg_ctrl and opts.get('prepare items', True):
items = cfg_ctrl['items']
pass; log__("tp,items={}",(tp,items) ,__=(log4fun,)) if _log4mod>=0 else 0
if likesstr(items):
pass
elif tp in ['listview', 'checklistview']:
# For listview, checklistview: "\t"-separated items.
# first item is column headers: title1+"="+size1 + "\r" + title2+"="+size2 + "\r" +...
# other items are data: cell1+"\r"+cell2+"\r"+...
# ([(hd,wd)], [[cells],[cells],])
items = '\t'.join(['\r'.join(['='.join((hd,str(sz))) for hd,sz in items[0]])]
+['\r'.join(row) for row in items[1]]
)
else:
# For combo, combo_ro, listbox, checkgroup, radiogroup, checklistbox: "\t"-separated lines
items = '\t'.join(items)
pass; log__("items={}",(items) ,__=(log4fun,)) if _log4mod>=0 else 0
c_pr['items'] = items
if ('cols' in cfg_ctrl or 'columns' in cfg_ctrl or 'cols_ws' in cfg_ctrl) and opts.get('prepare cols', True):
cols = cfg_ctrl.get('cols', cfg_ctrl.get('columns'))
cols = cols if cols else self.cattr(cid, 'cols')
cfg_ctrl['columns'] = cols
if likesstr(cols):
pass
else:
if 'cols_ws' in cfg_ctrl:
cols_ws = cfg_ctrl['cols_ws']
pass; #log("cols_ws={}",(cols_ws))
if len(cols_ws)!=len(cols): raise ValueError('Inconsistent attribures: cols/columns and cols_ws')
for n,w in enumerate(cols_ws):
cols[n]['wd'] = w
# For listview, checklistview:
# "\t"-separated of
# "\r"-separated
# Name, Width, Min Width, Max Width, Alignment (str), Autosize('0'/'1'), Visible('0'/'1')
pass; #log('cols={}',(cols))
str_sc = lambda n: str(_os_scale('scale', {'w':n})['w'])
cols = '\t'.join(['\r'.join([ cd[ 'hd']
,str_sc(cd.get('wd' ,0))
,str_sc(cd.get('mi' ,0))
,str_sc(cd.get('ma' ,0))
, cd.get('al','')
,'1' if cd.get('au',False) else '0'
,'1' if cd.get('vi',True ) else '0'
])
for cd in cols]
)
pass; #log('cols={}',repr(cols))
c_pr['columns'] = cols
return c_pr
#def _prepare_vl_it_cl
def _take_val(self, name, liv_val, defv=None):
pass; log4fun=0 # Order log in the function
pass; log__("name, liv_val={}",(name, liv_val) ,__=(log4fun,)) if _log4mod>=0 else 0
tp = self.ctrls[name]['type']
old_val = self.ctrls[name].get('val', defv)
new_val = liv_val
ivals = self.ctrls[name].get('ivals')
if False:pass
elif tp=='memo':
# For memo: "\t"-separated lines (in lines "\t" must be replaced to chr(3))
if likeslist(old_val):
# new_val = [v.replace(chr(3), '\t') for v in liv_val.split('\t')]
new_val = [v.replace(chr(2), '\t') ##!! Wait core fix
.replace(chr(3), '\t') for v in liv_val.split('\t')]
#liv_val = '\t'.join([v.replace('\t', chr(3)) for v in old_val])
else:
new_val = liv_val.replace('\t','\n').replace(chr(3), '\t')
#liv_val = old_val.replace('\t', chr(3)).replace('\r\n','\n').replace('\r','\n').replace('\n','\t')
elif tp=='checkgroup' and likeslist(old_val):
# For checkgroup: ","-separated checks (values "0"/"1")
new_val = liv_val.split(',')
#in_val = ','.join(in_val)
elif tp in ['checklistbox', 'checklistview'] and likeslist(old_val):
new_val = liv_val.split(';')
new_val = (new_val[0], new_val[1].split(','))
#liv_val = ';'.join(old_val[0], ','.join(old_val[1]))
elif tp in ['listbox', 'combo_ro'] and ivals:
new_val = int(new_val)
new_val = ivals[new_val] if 0<=new_val<len(ivals) else None
elif isinstance(old_val, bool):
new_val = liv_val=='1'
elif tp=='listview':
new_val = -1 if liv_val=='' else int(liv_val)
elif old_val is not None:
pass; #log('name,old_val,liv_val={}',(name,old_val,liv_val))
new_val = type(old_val)(liv_val)
return new_val
#def _take_val
def _take_it_cl(self, cid, attr, liv_val, defv=None):
tp = self.ctrls[cid]['type']
old_val = self.ctrls[cid].get(attr, defv)
pass; #log('cid, attr, isinstance(old_val, str)={}',(cid, attr, isinstance(old_val, str)))
if likesstr(old_val):
# No need parsing - config was by string
return liv_val
new_val = liv_val
if attr=='items':
if tp in ['listview', 'checklistview']:
# For listview, checklistview: "\t"-separated items.
# first item is column headers: title1+"="+size1 + "\r" + title2+"="+size2 + "\r" +...
# other items are data: cell1+"\r"+cell2+"\r"+...
# ([(hd,wd)], [[cells],[cells],])
header_rows = new_val.split('\t')
new_val =[[h.split('=') for h in header_rows[0].split('\r')]
,[r.split('\r') for r in header_rows[1:]]
]
else:
# For combo, combo_ro, listbox, checkgroup, radiogroup, checklistbox: "\t"-separated lines
new_val = new_val.split('\t')
if attr in ('columns', 'cols'):
# For listview, checklistview:
# "\t"-separated of
# "\r"-separated
# Name, Width, Min Width, Max Width, Alignment (str), Autosize('0'/'1'), Visible('0'/'1')
# [{nm:str, wd:num, mi:num, ma:num, al:str, au:bool, vi:bool}]
pass; #log('new_val={}',repr(new_val))
new_val= [ci.split('\r') for ci in new_val.split('\t')]
pass; #log('new_val={}',repr(new_val))
int_sc = lambda s: _os_scale('unscale', {'w':int(s)})['w']
new_val= [ dict(hd= ci[0]
,wd=int_sc(ci[1])
,mi=int_sc(ci[2])
,ma=int_sc(ci[3])
,al= ci[4]
,au='1'== ci[5]
,vi='1'== ci[6]
) for ci in new_val]
pass; #log('new_val={}',(new_val))
return new_val
#def _take_it_cl
@staticmethod
def _preprocessor(cnt, tp):
pass; log4fun=0 # Order log in the function
pass; log__('tp,cnt={}',(tp,cnt) ,__=(log4fun,)) if _log4mod>=0 else 0
# on -> on_???
if 'on' in cnt:
if False:pass
elif tp in ('listview', 'treeview'):
cnt['on_select'] = cnt['on']
elif tp in ('linklabel'):
cnt['on_click'] = cnt['on']
else:
cnt['on_change'] = cnt['on']
# Joins
if 'sp_lr' in cnt:
cnt['sp_l'] = cnt['sp_r'] = cnt['sp_lr']
if 'sp_lrt' in cnt:
cnt['sp_l'] = cnt['sp_r'] = cnt['sp_t'] = cnt['sp_lrt']
if 'sp_lrb' in cnt:
cnt['sp_l'] = cnt['sp_r'] = cnt['sp_b'] = cnt['sp_lrb']