-
Notifications
You must be signed in to change notification settings - Fork 2
/
cd_plug_lib.py
2426 lines (2241 loc) · 115 KB
/
cd_plug_lib.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:
'2.1.17 2021-04-16'
Content
log Logger with timing
get_translation i18n
dlg_wrapper Wrapper for dlg_custom: pack/unpack values, h-align controls
ToDo: (see end of file)
'''
import sys, os, gettext, logging, inspect, time, collections, json, re, subprocess
from time import perf_counter
try:
import cudatext as app
from cudatext import ed
import cudax_lib as apx
except:
import sw as app
from sw import ed
from . import cudax_lib as apx
pass; # Logging
pass; from pprint import pformat
pass; import tempfile
odict = collections.OrderedDict
T,F,N = True, False, None
GAP = 5
c13,c10,c9 = chr(13),chr(10),chr(9)
REDUCTIONS = {'lb' :'label'
, 'ln-lb' :'linklabel'
, 'llb' :'linklabel'
, 'ed' :'edit' # ro_mono_brd
, 'ed_pw' :'edit_pwd'
, 'sp-ed' :'spinedit' # min_max_inc
, 'sed' :'spinedit' # min_max_inc
, 'me' :'memo' # ro_mono_brd
, 'bt' :'button' # def_bt
, 'rd' :'radio'
, 'ch' :'check'
, 'ch-bt' :'checkbutton'
, 'ch-b' :'checkbutton'
, 'chb' :'checkbutton'
, 'ch-gp' :'checkgroup'
, 'rd-gp' :'radiogroup'
, 'cb' :'combo'
, 'cb-ro' :'combo_ro'
, 'cb-r' :'combo_ro'
, 'cbr' :'combo_ro'
, 'lbx' :'listbox'
, 'ch-lbx' :'checklistbox'
, 'clx' :'checklistbox'
, 'lvw' :'listview'
, 'ch-lvw' :'checklistview'
, 'tabs' :'tabs'
, 'clr' :'colorpanel'
, 'im' :'image'
, 'f-lb' :'filter_listbox'
, 'f-lvw' :'filter_listview'
, 'fr' :'bevel'
, 'pn' :'panel'
, 'gr' :'group'
, 'sp' :'splitter'
, 'tvw' :'treeview'
, 'edr' :'editor'
, 'sb' :'statusbar'
, 'bte' :'button_ex'
# , 'fid' :'focused'
, 'cols' :'columns'
}
def f(s, *args, **kwargs):return s.format(*args, **kwargs)
def log(msg='', *args, **kwargs):
if args or kwargs:
msg = msg.format(*args, **kwargs)
if Tr.tr is None:
Tr.tr=Tr()
return Tr.tr.log(msg)
class Tr :
tr=None
""" Трассировщик.
Основной (единственный) метод: log(строка) - выводит указанную строку в лог.
Управляется через команды в строках для вывода.
Команды:
>> Увеличить сдвиг при выводе будущих строк (пока жив возвращенный объект)
(:) Начать замер нового вложенного периода, закончить когда умрет возвращенный объект
(== Начать замер нового вложенного периода
==> Вывести длительность последнего периода
==) Вывести длительность последнего периода и закончить его замер
=}} Отменить все замеры
Вызов log с командой >> (увеличить сдвиг) возвращает объект,
который при уничтожении уменьшит сдвиг
"""
sec_digs = 2 # Точность отображения секунд, кол-во дробных знаков
se_fmt = ''
mise_fmt = ''
homise_fmt = ''
def __init__(self, log_to_file=None) :
# Поля объекта
self.gap = '' # Отступ
self.tm = perf_counter() # Отметка времени о запуске
self.stms = [] # Отметки времени о начале замера спец.периода
if log_to_file:
logging.basicConfig( filename=log_to_file
,filemode='w'
,level=logging.DEBUG
,format='%(message)s'
,datefmt='%H:%M:%S'
,style='%')
else: # to stdout
logging.basicConfig( stream=sys.stdout
,level=logging.DEBUG
,format='%(message)s'
,datefmt='%H:%M:%S'
,style='%')
# Tr()
def __del__(self):
logging.shutdown()
class TrLiver :
cnt = 0
""" Автоматически сокращает gap при уничножении
Показывает время своей жизни"""
def __init__(self, tr, ops) :
# Поля объекта
self.tr = tr
self.ops= ops
self.tm = 0
self.nm = Tr.TrLiver.cnt
if '(:)' in self.ops :
# Начать замер нового интервала
self.tm = perf_counter()
def log(self, msg='') :
if '(:)' in self.ops :
msg = '{}(:)=[{}]{}'.format( self.nm, Tr.format_tm( perf_counter() - self.tm ), msg )
logging.debug( self.tr.format_msg(msg, ops='') )
def __del__(self) :
#pass; logging.debug('in del')
if '(:)' in self.ops :
msg = '{}(:)=[{}]'.format( self.nm, Tr.format_tm( perf_counter() - self.tm ) )
logging.debug( self.tr.format_msg(msg, ops='') )
if '>>' in self.ops :
self.tr.gap = self.tr.gap[:-1]
def log(self, msg='') :
if '(:)' in msg :
Tr.TrLiver.cnt += 1
msg = msg.replace( '(:)', '{}(:)'.format(Tr.TrLiver.cnt) )
logging.debug( self.format_msg(msg) )
if '>>' in msg :
self.gap = self.gap + c9
# Создаем объект, который при разрушении сократит gap
if '>>' in msg or '(:)' in msg:
return Tr.TrLiver(self,('>>' if '>>' in msg else '')+('(:)' if '(:)' in msg else ''))
# return Tr.TrLiver(self,iif('>>' in msg,'>>','')+iif('(:)' in msg,'(:)',''))
else :
return self
# Tr.log
# def format_msg(self, msg, dpth=2, ops='+fun:ln +wait==') :
def format_msg(self, msg, dpth=3, ops='+fun:ln +wait==') :
if '(==' in msg :
# Начать замер нового интервала
self.stms = self.stms + [perf_counter()]
msg = msg.replace( '(==', '(==[' + Tr.format_tm(0) + ']' )
if '###' in msg :
# Показать стек
st_inf = '\n###'
for fr in inspect.stack()[1+dpth:]:
try:
cls = fr[0].f_locals['self'].__class__.__name__ + '.'
except:
cls = ''
fun = (cls + fr[3]).replace('.__init__','()')
ln = fr[2]
st_inf += ' {}:{}'.format(fun, ln)
msg += st_inf
if '+fun:ln' in ops :
frCaller= inspect.stack()[dpth] # 0-format_msg, 1-Tr.log|Tr.TrLiver, 2-log, 3-need func
try:
cls = frCaller[0].f_locals['self'].__class__.__name__ + '.'
except:
cls = ''
fun = (cls + frCaller[3]).replace('.__init__','()')
ln = frCaller[2]
msg = '[{}]{}{}:{} '.format( Tr.format_tm( perf_counter() - self.tm ), self.gap, fun, ln ) + msg
else :
msg = '[{}]{}'.format( Tr.format_tm( perf_counter() - self.tm ), self.gap ) + msg
if '+wait==' in ops :
if ( '==)' in msg or '==>' in msg ) and len(self.stms)>0 :
# Закончить/продолжить замер последнего интервала и вывести его длительность
sign = '==)' if '==)' in msg else '==>'
# sign = icase( '==)' in msg, '==)', '==>' )
stm = '[{}]'.format( Tr.format_tm( perf_counter() - self.stms[-1] ) )
msg = msg.replace( sign, sign+stm )
if '==)' in msg :
del self.stms[-1]
if '=}}' in msg :
# Отменить все замеры
self.stms = []
return msg.replace('¬',c9).replace('¶',c10)
# Tr.format
@staticmethod
def format_tm(secs) :
""" Конвертация количества секунд в 12h34'56.78" """
if 0==len(Tr.se_fmt) :
Tr.se_fmt = '{:'+str(3+Tr.sec_digs)+'.'+str(Tr.sec_digs)+'f}"'
Tr.mise_fmt = "{:2d}'"+Tr.se_fmt
Tr.homise_fmt = "{:2d}h"+Tr.mise_fmt
h = int( secs / 3600 )
secs = secs % 3600
m = int( secs / 60 )
s = secs % 60
return Tr.se_fmt.format(s) \
if 0==h+m else \
Tr.mise_fmt.format(m,s) \
if 0==h else \
Tr.homise_fmt.format(h,m,s)
# return icase( 0==h+m, Tr.se_fmt.format(s)
# , 0==h, Tr.mise_fmt.format(m,s)
# , Tr.homise_fmt.format(h,m,s) )
# Tr.format_tm
# Tr
def get_desktop_environment():
#From http://stackoverflow.com/questions/2035657/what-is-my-current-desktop-environment
# and http://ubuntuforums.org/showthread.php?t=652320
# and http://ubuntuforums.org/showthread.php?t=652320
# and http://ubuntuforums.org/showthread.php?t=1139057
if sys.platform in ["win32", "cygwin"]:
return "win"
elif sys.platform == "darwin":
return "mac"
else: #Most likely either a POSIX system or something not much common
desktop_session = os.environ.get("DESKTOP_SESSION")
if desktop_session is not None: #easier to match if we doesn't have to deal with caracter cases
desktop_session = desktop_session.lower()
if desktop_session in ["gnome","unity", "cinnamon", "mate", "xfce4", "lxde", "fluxbox",
"blackbox", "openbox", "icewm", "jwm", "afterstep","trinity", "kde"]:
return desktop_session
## Special cases ##
# Canonical sets $DESKTOP_SESSION to Lubuntu rather than LXDE if using LXDE.
# There is no guarantee that they will not do the same with the other desktop environments.
elif "xfce" in desktop_session or desktop_session.startswith("xubuntu"):
return "xfce4"
elif desktop_session.startswith("ubuntu"):
return "unity"
elif desktop_session.startswith("lubuntu"):
return "lxde"
elif desktop_session.startswith("kubuntu"):
return "kde"
elif desktop_session.startswith("razor"): # e.g. razorkwin
return "razor-qt"
elif desktop_session.startswith("wmaker"): # e.g. wmaker-common
return "windowmaker"
if os.environ.get('KDE_FULL_SESSION') == 'true':
return "kde"
elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
if not "deprecated" in os.environ.get('GNOME_DESKTOP_SESSION_ID'):
return "gnome2"
#From http://ubuntuforums.org/showthread.php?t=652320
elif is_running("xfce-mcs-manage"):
return "xfce4"
elif is_running("ksmserver"):
return "kde"
return "unknown"
def is_running(process):
#From http://www.bloggerpolis.com/2011/05/how-to-check-if-a-process-is-running-using-python/
# and http://richarddingwall.name/2009/06/18/windows-equivalents-of-ps-and-kill-commands/
try: #Linux/Unix
s = subprocess.Popen(["ps", "axw"],stdout=subprocess.PIPE)
except: #Windows
s = subprocess.Popen(["tasklist", "/v"],stdout=subprocess.PIPE)
for x in s.stdout:
if re.search(process, str(x)):
return True
return False
ENV2FITS= {'win':
{'check' :-2
,'radio' :-2
,'edit' :-3
,'button' :-4
,'combo_ro' :-4
,'combo' :-3
,'checkbutton':-5
,'linklabel' : 0
,'spinedit' :-3
}
,'unity':
{'check' :-3
,'radio' :-3
,'edit' :-5
,'button' :-4
,'combo_ro' :-5
,'combo' :-6
,'checkbutton':-4
,'linklabel' : 0
,'spinedit' :-6
}
,'mac':
{'check' :-1
,'radio' :-1
,'edit' :-3
,'button' :-3
,'combo_ro' :-2
,'combo' :-3
,'checkbutton':-2
,'linklabel' : 0
,'spinedit' : 0 ##??
}
}
fit_top_by_env__cash = {}
def fit_top_by_env__clear():
global fit_top_by_env__cash
fit_top_by_env__cash = {}
def fit_top_by_env(what_tp, base_tp='label'):
""" Get "fitting" to add to top of first control to vertical align inside text with text into second control.
The fittings rely to platform: win, unix(kde,gnome,...), mac
"""
if what_tp==base_tp:
return 0
if (what_tp, base_tp) in fit_top_by_env__cash:
pass; #log('cashed what_tp, base_tp={}',(what_tp, base_tp))
return fit_top_by_env__cash[(what_tp, base_tp)]
env = get_desktop_environment()
pass; #env = 'mac'
fit4lb = ENV2FITS.get(env, ENV2FITS.get('win'))
fit = 0
if base_tp=='label':
fit = apx.get_opt('dlg_wrapper_fit_va_for_'+what_tp, fit4lb.get(what_tp, 0))
pass; #fit_o=fit
fit = _os_scale(app.DLG_PROP_GET, {'y':fit})['y']
pass; #log('what_tp,fit_o,fit,h={}',(what_tp,fit_o,fit,get_gui_height(what_tp)))
else:
fit = fit_top_by_env(what_tp) - fit_top_by_env(base_tp)
pass; #log('what_tp, base_tp, fit={}',(what_tp, base_tp, fit))
return fit_top_by_env__cash.setdefault((what_tp, base_tp), fit)
#def fit_top_by_env
def rgb_to_int(r,g,b):
return r | (g<<8) | (b<<16)
def dlg_wrapper(title, w, h, cnts, in_vals={}, focus_cid=None):
""" Wrapper for dlg_custom.
Params
title, w, h Title, Width, Height
cnts List of static control properties
[{cid:'*', tp:'*', t:1,l:1,w:1,r:1,b;1,h:1,tid:'cid', cap:'*', hint:'*', en:'0', props:'*', items:[*], act='0'}]
cid (opt)(str) C(ontrol)id. Need only for buttons and conrols with value (and for tid)
tp (str) Control types from wiki or short names
t (opt)(int) Top
tid (opt)(str) Ref to other control cid for horz-align text in both controls
l (int) Left
r,b,w,h (opt)(int) Position. w>>>r=l+w, h>>>b=t+h, b can be omitted
cap (str) Caption for labels and buttons
hint (opt)(str) Tooltip
en (opt)('0'|'1'|True|False) Enabled-state
props (opt)(str) See wiki
act (opt)('0'|'1'|True|False) Will close dlg when changed
items (str|list) String as in wiki. List structure by types:
[v1,v2,] For combo, combo_ro, listbox, checkgroup, radiogroup, checklistbox
(head, body) For listview, checklistview
head [(cap,width),(cap,width),]
body [[r0c0,r0c1,],[r1c0,r1c1,],[r2c0,r2c1,],]
in_vals Dict of start values for some controls
{'cid':val}
focus_cid (opt) Control cid for start focus
Return
btn_cid Clicked/changed control cid
{'cid':val} Dict of new values for the same (as in_vals) controls
Format of values is same too.
focus_cid Focused control cid
[cid] List of controls with changed values
Short names for types
lb label
ln-lb linklabel
ed edit
sp-ed spinedit
me memo
bt button
rd radio
ch check
ch-bt checkbutton
ch-gp checkgroup
rd-gp radiogroup
cb combo
cb-ro combo_ro
lbx listbox
ch-lbx checklistbox
lvw listview
ch-lvw checklistview
Example.
def ask_number(ask, def_val):
cnts=[dict( tp='lb',tid='v',l=3 ,w=70,cap=ask)
,dict(cid='v',tp='ed',t=3 ,l=73,w=70)
,dict(cid='!',tp='bt',t=45 ,l=3 ,w=70,cap='OK',props='1')
,dict(cid='-',tp='bt',t=45 ,l=73,w=70,cap='Cancel')]
vals={'v':def_val}
while True:
aid,vals,fid,chds=dlg_wrapper('Example',146,75,cnts,vals,'v')
if aid is None or btn=='-': return def_val
if not re.match(r'\d+$', vals['v']): continue
return vals['v']
"""
pass; #log('in_vals={}',pformat(in_vals, width=120))
cnts = [cnt for cnt in cnts if cnt.get('vis', True) in (True, '1')]
cid2i = {cnt['cid']:i for i,cnt in enumerate(cnts) if 'cid' in cnt}
if True:
# Checks
no_tids = {cnt['tid'] for cnt in cnts if 'tid' in cnt and cnt['tid'] not in cid2i}
if no_tids:
raise Exception(f('No cid(s) for tid(s): {}', no_tids))
no_vids = {cid for cid in in_vals if cid not in cid2i}
if no_vids:
raise Exception(f('No cid(s) for vals: {}', no_vids))
simpp = ['cap','hint'
,'props'
,'color'
,'font_name', 'font_size', 'font_color', 'font'
,'act'
,'en','vis'
#,'tag'
]
ctrls_l = []
for cnt in cnts:
tp = cnt['tp']
tp = REDUCTIONS.get(tp, tp)
if tp=='--':
# Horz-line
t = cnt.get('t')
l = cnt.get('l', 0) # def: from DlgLeft
r = cnt.get('r', l+cnt.get('w', w)) # def: to DlgRight
lst = ['type=label']
lst+= ['cap='+'—'*1000]
lst+= ['font_color='+str(rgb_to_int(185,185,185))]
lst+= ['pos={l},{t},{r},0'.format(l=l,t=t,r=r)]
ctrls_l+= [chr(1).join(lst)]
continue#for cnt
lst = ['type='+tp]
# Preprocessor
if 'props' in cnt:
pass
elif tp=='label' and cnt['cap'][0]=='>':
# cap='>smth' --> cap='smth', props='1' (r-align)
cnt['cap'] = cnt['cap'][1:]
cnt['props']= '1'
elif tp=='label' and cnt.get('ralign'):
cnt['props']= cnt.get('ralign')
elif tp=='button' and cnt.get('def_bt') in ('1', True):
cnt['props']= '1'
elif tp=='spinedit' and cnt.get('min_max_inc'):
cnt['props']= cnt.get('min_max_inc')
elif tp=='linklabel' and cnt.get('url'):
cnt['props']= cnt.get('url')
elif tp=='listview' and cnt.get('grid'):
cnt['props']= cnt.get('grid')
elif tp=='tabs' and cnt.get('at_botttom'):
cnt['props']= cnt.get('at_botttom')
elif tp=='colorpanel' and cnt.get('brdW_fillC_fontC_brdC'):
cnt['props']= cnt.get('brdW_fillC_fontC_brdC')
elif tp in ('edit', 'memo') and cnt.get('ro_mono_brd'):
cnt['props']= cnt.get('ro_mono_brd')
# # Simple props
# for k in ['cap', 'hint', 'props', 'font_name', 'font_size', 'font_color', 'font', 'name']:
# lst += [k+'='+str(cnt[k])]
if 'props' in cnt:
props = cnt.pop('props').split(',')
for p_i, p_s in enumerate(props):
lst += ['ex'+str(p_i)+'='+p_s]
# Position:
# t[op] or tid, l[eft] required
# w[idth] >>> r[ight ]=l+w
# h[eight] >>> b[ottom]=t+h
# b dont need for buttons, edit, labels
l = cnt['l']
t = cnt.get('t', 0)
if 'tid' in cnt:
# cid for horz-align text
bs_cnt = cnts[cid2i[cnt['tid']]]
bs_tp = bs_cnt['tp']
t = bs_cnt['t'] + fit_top_by_env(tp, REDUCTIONS.get(bs_tp, bs_tp))
r = cnt.get('r', l+cnt.get('w', 0))
b = cnt.get('b', t+cnt.get('h', 0))
lst += ['pos={l},{t},{r},{b}'.format(l=l,t=t,r=r,b=b)]
# if 'en' in cnt:
# val = cnt['en']
# lst += ['en='+('1' if val in [True, '1'] else '0')]
if 'items' in cnt:
items = cnt['items']
if isinstance(items, str):
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,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)
lst+= ['items='+items]
# Prepare val
if cnt.get('cid') in in_vals:
in_val = in_vals[cnt['cid']]
if False:pass
elif tp in ['check', 'radio', 'checkbutton'] and isinstance(in_val, bool):
# For check, radio, checkbutton: value "0"/"1"
in_val = '1' if in_val else '0'
elif tp=='memo':
# For memo: "\t"-separated lines (in lines "\t" must be replaced to chr(2))
if isinstance(in_val, list):
in_val = '\t'.join([v.replace('\t', chr(2)) for v in in_val])
else:
in_val = in_val.replace('\t', chr(2)).replace('\r\n','\n').replace('\r','\n').replace('\n','\t')
elif tp=='checkgroup' and isinstance(in_val, list):
# For checkgroup: ","-separated checks (values "0"/"1")
in_val = ','.join(in_val)
elif tp in ['checklistbox', 'checklistview'] and isinstance(in_val, tuple):
# For checklistbox, checklistview: index+";"+checks
in_val = ';'.join( (str(in_val[0]), ','.join( in_val[1]) ) )
lst+= ['val='+str(in_val)]
# if 'act' in cnt: # must be last in lst
# val = cnt['act']
# lst += ['act='+('1' if val in [True, '1'] else '0')]
# Simple props
for k in simpp:
if k in cnt:
v = cnt[k]
v = ('1' if v else '0') if isinstance(v, bool) else str(v)
lst += [k+'='+v]
pass; #log('lst={}',lst)
ctrls_l+= [chr(1).join(lst)]
#for cnt
pass; #log('ok ctrls_l={}',pformat(ctrls_l, width=120))
pass; #ctrls_fn=tempfile.gettempdir()+os.sep+'dlg_custom_ctrls.txt'
pass; #open(ctrls_fn, 'w', encoding='UTF-8').write('\n'.join(ctrls_l).replace('\r',''))
pass; #log(f(r'app.dlg_custom("{t}",{w},{h},open(r"{fn}",encoding="UTF-8").read(), {f})',t=title, w=w, h=h, fn=ctrls_fn, f=cid2i.get(focus_cid, -1)))
ans = app.dlg_custom(title, w, h, '\n'.join(ctrls_l), cid2i.get(focus_cid, -1))
if ans is None: return None, None, None, None # btn_cid, {cid:v}, focus_cid, [cid]
pass; #log('ans={})',ans)
btn_i, \
vals_ls = ans[0], ans[1].splitlines()
pass; #log('btn_i,vals_ls={})',(btn_i,vals_ls))
focus_cid = ''
if vals_ls[-1].startswith('focused='):
# From API 1.0.156 dlg_custom also returns index of active control
focus_n_s = vals_ls.pop()
focus_i = int(focus_n_s.split('=')[1])
focus_cid = cnts[focus_i].get('cid', '')
pass; #log('btn_i,vals_ls,focus_cid={})',(btn_i,vals_ls,focus_cid))
act_cid = cnts[btn_i]['cid']
# Parse output values
an_vals = {cid:vals_ls[cid2i[cid]] for cid in in_vals}
for cid in an_vals:
cnt = cnts[cid2i[cid]]
tp = cnt['tp']
tp = REDUCTIONS.get(tp, tp)
in_val = in_vals[cid]
an_val = an_vals[cid]
pass; #log('tp,in_val,an_val={})',(tp,in_val,an_val))
if False:pass
elif tp=='memo':
# For memo: "\t"-separated lines (in lines "\t" must be replaced to chr(2))
if isinstance(in_val, list):
an_val = [v.replace(chr(2), '\t') for v in an_val.split('\t')]
#in_val = '\t'.join([v.replace('\t', chr(2)) for v in in_val])
else:
an_val = an_val.replace('\t','\n').replace(chr(2), '\t')
#in_val = in_val.replace('\t', chr(2)).replace('\r\n','\n').replace('\r','\n').replace('\n','\t')
elif tp=='checkgroup' and isinstance(in_val, list):
# For checkgroup: ","-separated checks (values "0"/"1")
an_val = an_val.split(',')
#in_val = ','.join(in_val)
elif tp in ['checklistbox', 'checklistview'] and isinstance(in_val, tuple):
an_val = an_val.split(';')
an_val = (an_val[0], an_val[1].split(','))
#in_val = ';'.join(in_val[0], ','.join(in_val[1]))
elif isinstance(in_val, bool):
an_val = an_val=='1'
elif tp=='listview':
an_val = -1 if an_val=='' else int(an_val)
else:
an_val = type(in_val)(an_val)
pass; #log('type(in_val),an_val={})',(type(in_val),an_val))
an_vals[cid] = an_val
#for cid
chds = [cid for cid in in_vals if in_vals[cid]!=an_vals[cid]]
if focus_cid:
# If out focus points to button then will point to a unique changed control
focus_tp= cnts[cid2i[focus_cid]]['tp']
focus_tp= REDUCTIONS.get(focus_tp, focus_tp)
if focus_tp in ('button'):
focus_cid = '' if len(chds)!=1 else chds[0]
return act_cid \
, an_vals \
, focus_cid \
, chds
#def dlg_wrapper
DLG_CTL_ADD_SET = 26
DLG_PROC_I2S={
0:'DLG_CREATE'
,1:'DLG_FREE'
,5:'DLG_SHOW_MODAL'
,6:'DLG_SHOW_NONMODAL'
,7:'DLG_HIDE'
,8:'DLG_FOCUS'
,9:'DLG_SCALE'
,10:'DLG_PROP_GET'
,11:'DLG_PROP_SET'
,12:'DLG_DOCK'
,13:'DLG_UNDOCK'
,20:'DLG_CTL_COUNT'
,21:'DLG_CTL_ADD'
,26:'DLG_CTL_ADD_SET'
,22:'DLG_CTL_PROP_GET'
,23:'DLG_CTL_PROP_SET'
,24:'DLG_CTL_DELETE'
,25:'DLG_CTL_DELETE_ALL'
,30:'DLG_CTL_FOCUS'
,31:'DLG_CTL_FIND'
,32:'DLG_CTL_HANDLE'
}
_SCALED_KEYS = ('x', 'y', 'w', 'h'
, 'w_min', 'w_max', 'h_min', 'h_max'
, 'sp_l', 'sp_r', 'sp_t', 'sp_b', 'sp_a'
)
def _os_scale(id_action, prop=None, index=-1, index2=-1, name=''):
pass; #return prop
pass; #log('prop={}',({k:prop[k] for k in prop if k in ('x','y')}))
pass; #logb=name in ('tolx', 'tofi') and id_action==app.DLG_CTL_PROP_GET
pass; #log('name,prop={}',(name,{k:prop[k] for k in prop if k in ('h','_ready_h')})) if logb else 0
ppi = app.app_proc(app.PROC_GET_SYSTEM_PPI, '')
if ppi==96:
return prop
scale = ppi/96
pass; #log('id_dialog, id_action,scale={}',(id_dialog, DLG_PROC_I2S[id_action],scale))
if False:pass
elif id_action in (app.DLG_PROP_SET , app.DLG_PROP_GET
,app.DLG_CTL_PROP_SET , app.DLG_CTL_PROP_GET
,'scale', 'unscale'):
def scale_up(prop_dct):
for k in _SCALED_KEYS:
if k in prop_dct and '_ready_'+k not in prop_dct:
prop_dct[k] = round(prop_dct[k] * scale) # Scale!
def scale_dn(prop_dct):
for k in _SCALED_KEYS:
if k in prop_dct and '_ready_'+k not in prop_dct:
prop_dct[k] = round(prop_dct[k] / scale) # UnScale!
# pass; print('a={}, ?? pr={}'.format(DLG_PROC_I2S[id_action], {k:prop[k] for k in prop if k in _SCALED_KEYS or k=='name'}))
if False:pass
elif id_action==app.DLG_PROP_SET: scale_up(prop)
elif id_action==app.DLG_CTL_PROP_SET and -1!=index: scale_up(prop)
elif id_action==app.DLG_CTL_PROP_SET and ''!=name: scale_up(prop)
elif id_action==app.DLG_PROP_GET: scale_dn(prop)
elif id_action==app.DLG_CTL_PROP_GET and -1!=index: scale_dn(prop)
elif id_action==app.DLG_CTL_PROP_GET and ''!=name: scale_dn(prop)
elif id_action== 'scale': scale_up(prop)
elif id_action=='unscale': scale_dn(prop)
pass; #print('a={}, ok pr={}'.format(DLG_PROC_I2S[id_action], {k:prop[k] for k in prop if k in _SCALED_KEYS or k=='name'}))
pass; #log('name,prop={}',(name,{k:prop[k] for k in prop if k in ('h','_ready_h')})) if logb else 0
return prop
#def _os_scale
gui_height_cache= { 'button' :0
, 'label' :0
, 'linklabel' :0
, 'combo' :0
, 'combo_ro' :0
, 'edit' :0
, 'spinedit' :0
, 'check' :0
, 'radio' :0
, 'checkbutton' :0
, 'filter_listbox' :0
, 'filter_listview' :0
# , 'scrollbar' :0
}
def get_gui_height(ctrl_type):
""" Return real OS-specific height of some control
'button'
'label' 'linklabel'
'combo' 'combo_ro'
'edit' 'spinedit'
'check' 'radio' 'checkbutton'
'filter_listbox' 'filter_listview'
'scrollbar'
"""
global gui_height_cache
if 0 == gui_height_cache['button']:
for tpc in gui_height_cache:
gui_height_cache[tpc] = app.app_proc(app.PROC_GET_GUI_HEIGHT, tpc)
pass; #log('gui_height_cache={}',(gui_height_cache))
idd=app.dlg_proc( 0, app.DLG_CREATE)
for tpc in gui_height_cache:
idc=app.dlg_proc( idd, app.DLG_CTL_ADD, tpc)
pass; #log('tpc,idc={}',(tpc,idc))
prc = {'name':tpc, 'x':0, 'y':0, 'w':1, 'cap':tpc
, 'h':gui_height_cache[tpc]}
if tpc in ('combo' 'combo_ro'):
prc['items']='item0'
app.dlg_proc( idd, app.DLG_CTL_PROP_SET, index=idc, prop=prc)
app.dlg_proc( idd, app.DLG_PROP_SET, prop={'x':-1000, 'y':-1000, 'w':100, 'h':100})
app.dlg_proc( idd, app.DLG_SHOW_NONMODAL)
ppi = app.app_proc(app.PROC_GET_SYSTEM_PPI, '')
if ppi!=96:
# Try to scale height of controls
scale = ppi/96
for tpc in gui_height_cache:
prc = app.dlg_proc( idd, app.DLG_CTL_PROP_GET, name=tpc)
sc_h = round(prc['h'] * scale)
app.dlg_proc( idd, app.DLG_CTL_PROP_SET, name=tpc, prop=dict(h=sc_h))
for tpc in gui_height_cache:
prc = app.dlg_proc( idd, app.DLG_CTL_PROP_GET, name=tpc)
pass; #log('prc={}',(prc))
gui_height_cache[tpc] = prc['h']
app.dlg_proc( idd, app.DLG_FREE)
pass; #log('gui_height_cache={}',(gui_height_cache))
return gui_height_cache.get(ctrl_type, app.app_proc(app.PROC_GET_GUI_HEIGHT, ctrl_type))
#def get_gui_height
def dlg_proc_wpr(id_dialog, id_action, prop='', index=-1, index2=-1, name=''):
""" Wrapper on app.dlg_proc
1. To set/get dlg-props in scaled OS
2. New command DLG_CTL_ADD_SET to set props of created ctrl
3. Correct prop for ('label', 'button', 'checkbutton'): if no 'h' then set 'h' as OS default
"""
if id_action==app.DLG_SCALE:
return
# if id_dialog==0:
# print('idd=dlg_proc(0, {})'.format(DLG_PROC_I2S[id_action]))
# else:
# print('dlg_proc(idd, {}, index={}, name="{}", prop={}, index2={})'.format( DLG_PROC_I2S[id_action],
# index, name,
# '""' if type(prop)==str else prop,
## '""' if type(prop)==str else {k:prop[k] for k in prop if k not in ['on_change']},
# index2))
#print('#dlg_proc id_action='+str(id_action)+' prop='+repr(prop))
scale_on_set = id_action in (app.DLG_PROP_SET, app.DLG_CTL_PROP_SET)
scale_on_get = id_action in (app.DLG_PROP_GET, app.DLG_CTL_PROP_GET)
res = ''
if id_action==DLG_CTL_ADD_SET: # Join ADD and SET for a control
res = ctl_ind = \
app.dlg_proc(id_dialog, app.DLG_CTL_ADD, name, -1, -1, '') # type in name
# if name in ('label', 'button', 'checkbutton') and 'h' not in prop:
# prop['h'] = app.dlg_proc(id_dialog, app.DLG_CTL_PROP_GET, index=ctl_ind)['h']
_os_scale( app.DLG_CTL_PROP_SET, prop, ctl_ind, -1, '')
app.dlg_proc(id_dialog, app.DLG_CTL_PROP_SET, prop, ctl_ind, -1, '')
else:
_os_scale( id_action, prop, index, index2, name) if scale_on_set else 0
res = app.dlg_proc(id_dialog, id_action, prop, index, index2, name)
pass; #log('res={}',({k:res[k] for k in res if k in ('x','y')})) if id_action==app.DLG_PROP_GET else 0
_os_scale(id_action, res, index, index2, name) if scale_on_get else 0
return res
#def dlg_proc_wpr
LMBD_HIDE = lambda cid,ag:None
class BaseDlgAgent:
"""
Simple helper to use dlg_proc(). See wiki.freepascal.org/CudaText_API#dlg_proc
Main features:
- All controls are created once then some of them can be changed via callbacks (attribute 'call').
- The helper stores config version of form's and control's attributes.
So the helper can return two versions of attributes: configured and actual (live).
- Helper marshals complex data ('items' for type=list/combo/..., 'val' for type=memo)
- Helper can to save/restore form position and sizes to/from file "settings/forms data.json".
Key for saving is form's 'cap' (default) or a value in call BaseDlgAgent(..., option={'form data key':'smth'})
If value of 'form data key' is empty then helper doesnt save/restore.
Format of constructor
BaseDlgAgent(ctrls, form=None, focused=None)
ctrls [(name,{...})] To create controls with the names
All attributes from
wiki.freepascal.org/CudaText_API#Control_properties
excluded: name, callback
form {...} To configure form
All attributes from
wiki.freepascal.org/CudaText_API#Form_properties
focused name_to_focus To set focus
Format of callback for a control
def callname(name_of_event_control, agent):
# Reactions
return None # To hide form
return {} # To keep controls and form state
return {'ctrls': [(name,{...})] # To change controls with the names
,'form': {...} # To change form
,'focused':name_to_focus # To set focus
} # Any key ('ctrls','form','focused') can be ommited.
Callback cannot add new controls or change type values.
Useful methods of agent
- agent.cattr(name, '??', live=T) To get a control actual/configured attribute
- agent.cattrs(name, ['??'], live=T) To get dict of a control listed actual/configured attributes
- agent.fattr('??', live=T) To get actual/configured form attribute
- agent.fattrs(live=T, ['??']=None) To get actual/configured all/listed form attributes
Tricks
Automatically set some values for attributes
- 'act':True If 'call' set in a control (not 'button')
- 'w_min':w If 'resize' set in the form
- 'h_min':h If 'resize' set in the form
Example. Dialog with two buttons.
BaseDlgAgent(
ctrls=[('b1', dict(type='button', cap='Click', x=0, y= 0, w=100,
call=lambda name,ag:{'ctrls':[('b1',{'cap':'OK', 'w':70})]}
))
,('b2', dict(type='button', cap='Close', x=0, y=30, w=100,
call=lambda name,ag:None)
)]
, form=dict(cap='Two buttons', x=0, y=0, w=100, h=60)
, focused='b1'
).show()
"""
def activate(self):
""" Set focus to the form """
app.dlg_proc(self.id_dlg, app.DLG_FOCUS)
#def activate
def hide(self):
app.dlg_proc(self.id_dlg, app.DLG_HIDE)
#def hide
def show(self, callbk_on_exit=None):
""" Show the form """
ed_caller = ed
# app.dlg_proc(self.id_dlg, app.DLG_SCALE) #??
# pass; pr_ = dlg_proc_wpr(self.id_dlg, app.DLG_CTL_PROP_GET, name='edch')
# pass; log('exit,pr_={}',('edch', {k:v for k,v in pr_.items() if k in ('h','y')}))
app.dlg_proc(self.id_dlg, app.DLG_SHOW_MODAL)
# pass; pr_ = dlg_proc_wpr(self.id_dlg, app.DLG_CTL_PROP_GET, name='edch')
# pass; log('exit,pr_={}',('edch', {k:v for k,v in pr_.items() if k in ('h','y')}))
pass; #log('ok DLG_SHOW_MODAL',())
BaseDlgAgent._form_acts('save', id_dlg=self.id_dlg, key4store=self.opts.get('form data key'))
if callbk_on_exit: callbk_on_exit(self)
dlg_proc_wpr(self.id_dlg, app.DLG_FREE)
ed_to_fcs = ed_caller \
if 'on_exit_focus_to_ed' not in self.opts else \
self.opts['on_exit_focus_to_ed']
pass; #log('self.opts={}',(self.opts))
pass; #log('ed_to_fcs.get_filename()={}',(ed_to_fcs.get_filename()))
if ed_to_fcs:
ed_to_fcs.focus()
# pass; log('self.opts={}',(self.opts))
# self.opts['on_exit_focus_to_ed'].focus()
# else:
# ed_caller.focus()
#def show
def fattr(self, attr, live=True, defv=None):
""" Return one form property """
attr= 'focused' if attr=='fid' else attr
pr = dlg_proc_wpr(self.id_dlg
, app.DLG_PROP_GET) if live else self.form
pass; #log('pr={}',(pr))
rsp = pr.get(attr, defv)
if live and attr=='focused':
prf = dlg_proc_wpr(self.id_dlg, app.DLG_CTL_PROP_GET, index=rsp)
rsp = prf['name'] if prf else None
return rsp
#def fattr
def fattrs(self, live=True, attrs=None):
""" Return form properties """
pr = dlg_proc_wpr(self.id_dlg
, app.DLG_PROP_GET) if live else self.form
return pr if not attrs else {attr:pr.get(attr) for attr in attrs}
#def fattrs
def cattr(self, name, attr, live=True, defv=None):
""" Return one the control property """
live= False if attr in ('type',) else live # Unchangable
pr = dlg_proc_wpr(self.id_dlg
, app.DLG_CTL_PROP_GET
, name=name) if live else self.ctrls[name]
attr = REDUCTIONS.get(attr, attr)
if attr not in pr: return defv
rsp = pr[attr]
if not live: return rsp
if attr=='val': return self._take_val(name, rsp, defv)
return self._take_it_cl(name, attr, rsp, defv)
# return self._take_val(name, rsp, defv) if attr=='val' and live else rsp
#def cattr
def cattrs(self, name, attrs=None, live=True):
""" Return the control properties """
pr = dlg_proc_wpr(self.id_dlg
, app.DLG_CTL_PROP_GET
, name=name) if live else self.ctrls[name]
attrs = attrs if attrs else list(pr.keys())
pass; #log('pr={}',(pr))
rsp = {attr:pr.get(attr) for attr in attrs if attr not in ('val','on_change','callback')}
if 'val' in attrs:
rsp['val'] = self._take_val(name, pr.get('val')) if live else pr.get('val')
return rsp
#def cattrs
def chandle(self, name):
return app.dlg_proc(self.id_dlg, app.DLG_CTL_HANDLE, name=name)
def bind_do(self, names=None, gui2data=True):
names = names if names else self.binds.keys()
assert self.bindof
for name in names:
if name not in self.binds: continue
attr = 'val'
if gui2data:
self.bindof.__setattr__(self.binds[name], self.cattr(name, attr))
else:
val = self.bindof.__getattr(self.binds[name])
self.update({'ctrls':[(name, {attr:val})]})
#def bind_do
def __init__(self, ctrls, form=None, focused=None, options=None):
# Fields
self.opts = options if options else {}
self.id_dlg = dlg_proc_wpr(0, app.DLG_CREATE)
self.ctrls = None # Conf-attrs of all controls by name (may be with 'val')
self.form = None # Conf-attrs of form
# self.callof = self.opts.get('callof') # Object for callbacks
self.bindof = self.opts.get('bindof') # Object for bind control's values to object's fields
self.binds = {} # {name:'other obj field name'}
self._setup_base(ctrls, form, focused)
rtf = self.opts.get('gen_repro_to_file', False)
rtf_fn = rtf if isinstance(rtf, str) else 'repro_dlg_proc.py'
if rtf: self._gen_repro_code(tempfile.gettempdir()+os.sep+rtf_fn)
#def __init__
def _setup_base(self, ctrls, form, focused=None):
""" Arrange and fill all: controls attrs, form attrs, focus.
Params
ctrls [(id, {})]
form {}
focused id
"""
#NOTE: DlgAg init
self.ctrls = odict(ctrls)
self.form = form.copy() if form else {}
# if 'checks'=='checks':
# if focused and focused not in self.ctrls:
# raise Exception(f('Unknown focused: {}', focused))
# Create controls
for name, cfg_ctrl in ctrls:
assert 'type' in cfg_ctrl
# Create control
cfg_ctrl.pop('callback', None)
cfg_ctrl.pop('on_change', None)
ind_c = dlg_proc_wpr(self.id_dlg
, DLG_CTL_ADD_SET
, name=cfg_ctrl['type']