-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathterp.py.save
executable file
·3503 lines (3218 loc) · 113 KB
/
terp.py.save
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
#!/usr/bin/python
##############################################################################
#
# TERP: a Text-mode ERP Client
# Copyright (C) 2010 by Almacom (Thailand) Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from optparse import OptionParser
import curses
import curses.textpad
import sys
import time
import xmlrpclib
import xml.etree.ElementTree
import pdb
import traceback
import re
import ConfigParser
import os
import locale
locale.setlocale(locale.LC_ALL,"")
parser=OptionParser()
parser.add_option("-H","--host",dest="host",help="host name",metavar="HOST",default="127.0.0.1")
parser.add_option("-P","--port",dest="port",help="port number",metavar="PORT",type="int",default=8069)
parser.add_option("-d","--db",dest="dbname",help="database",metavar="DB")
parser.add_option("-u","--uid",dest="uid",help="user ID",metavar="UID",type="int",default=1)
parser.add_option("-p","--passwd",dest="passwd",help="user password",metavar="PASSWD",default="admin")
parser.add_option("--pref",action="store_true",dest="user_pref",help="edit user preferences",default=False)
parser.add_option("--debug",action="store_true",dest="debug",help="debug mode",default=False)
(opts,args)=parser.parse_args()
if opts.debug:
def ex_info(type,value,tb):
traceback.print_exception(type,value,tb)
pdb.pm()
sys.excepthook=ex_info
rpc_obj=xmlrpclib.ServerProxy("http://%s:%d/xmlrpc/object"%(opts.host,opts.port))
rpc_wiz=xmlrpclib.ServerProxy("http://%s:%d/xmlrpc/wizard"%(opts.host,opts.port))
dbname=opts.dbname
if not dbname:
raise Exception("Missing dbname")
uid=opts.uid
passwd=opts.passwd
screen=None
root_panel=None
log_file=file("/tmp/terp.log","a")
dbg_mode=0
color_pairs={
"base_color": [1,"white,blue"],
"selection_color": [2,"black,white"],
"tabpanel_color": [3,"black,cyan"],
"statuspanel_color": [4,"black,cyan"],
"command_color": [5,"yellow,blue"],
"separator_color": [6,"cyan,blue"],
"button_color": [7,"green,blue"],
"scrollbar_color": [8,"white,blue"],
"notebook_color": [9,"white,blue"],
"fieldlabel_color": [10,"white,blue"],
"header_color": [11,"white,blue"],
}
def log(*args):
if not log_file:
return
s=s.encode('ascii','replace')
msg=" ".join([unicode(a).encode('ascii','replace') for a in args])
log_file.write(msg+"\n")
log_file.flush()
def rpc_obj_exec(*args):
try:
return rpc_obj.execute(dbname,uid,passwd,*args)
except Exception,e:
raise Exception("rpc_obj_exec failed: %s %s %s %s\n%s"%(dbname,uid,passwd,unicode(args),unicode(e)))
def rpc_obj_exec_wkf(*args):
try:
return rpc_obj.exec_workflow(dbname,uid,passwd,*args)
except Exception,e:
raise Exception("rpc_obj_exec_wkf failed: %s %s %s %s\n%s"%(dbname,uid,passwd,unicode(args),unicode(e)))
def set_trace():
curses.nocbreak()
screen.keypad(0)
curses.echo()
curses.endwin()
pdb.set_trace()
class Widget(object):
def on_unfocus(self,arg,source):
pass
def on_cursor_move(self,arg,source):
pass
def __init__(self):
self.x=None
self.y=None
self.w=None
self.h=None
self.maxw=None
self.maxh=None
self.extw=None
self.update_maxw=True
self.update_maxh=True
user self.borders=[0,0,0,0]
self.padding=[0,0,0,0]
self.valign="top"
self.halign="left"
self.cx=None
self.cy=None
self.states_f={}
self.view_attrs={}
self.states_v=None
self.attrs_v={}
self.colspan=1
self.colspan_follow=0
self.rowspan=1
self.parent=None
self.window=None
self.win_x=None
self.win_y=None
self.listeners={
"keypress": [],
"unfocus": [],
"cursor_move": [],
}
self.add_event_listener("unfocus",self.on_unfocus)
self.add_event_listener("cursor_move",self.on_cursor_move)
self.record=None
self.name=None
self.field=None
self.invisible=False
self.readonly=False
self.update_readonly=True
self.can_focus=False
self.has_focus=False
self.update_can_focus=False
self.view_wg=None
self.color=0
self.string=None
def to_s(self,d=0):
s=" "*d
s+=" "+self.__class__.__name__
for name in dir(self):
if name.startswith("_"):
continue
if not name in ("x","y","maxw","maxh","h","w","can_focus","has_focus","borders","padding","seps","string","cx","cy","colspan","col","readonly","required","invisible"):
continue
val=getattr(self,name)
if callable(val):
continue
s+=" %s=%s"%(name,unicode(val))
for name,val in self.view_attrs.items():
s+=" %s=%s"%(name,unicode(val))
return s
def draw(self):
raise Exception("method not implemented")
def refresh(self):
pass
def get_tabindex(self):
if self.can_focus:
return [self]
else:
return []
def add_event_listener(self,type,listener):
self.listeners[type].append(listener)
def process_event(self,event,param,source):
processed=False
for listener in self.listeners.get(event,[]):
if listener(param,source):
processed=True
if processed:
return True
if self.parent:
self.parent.process_event(event,param,source)
def clear_focus(self):
if self.has_focus:
self.has_focus=False
self.process_event("unfocus",None,self)
def set_focus(self):
self.has_focus=self.can_focus
if self.has_focus:
return self
return None
def get_focus(self):
return self.has_focus and self or None
def set_cursor(self):
self.move_cursor(self.y,self.x)
def init_attrs(self):
if self.field:
if "string" in self.field:
self.string=self.field["string"]
if "select" in self.field:
val=self.field['select']
if type(val)!=type(1):
val=1
sel_fields=self.view_wg.parent.select_fields
sel_fields[self.name]=max(val,sel_fields.get(self.name,0))
if "string" in self.view_attrs:
self.string=self.view_attrs["string"]
if "colspan" in self.view_attrs:
self.colspan=int(self.view_attrs["colspan"])
if "col" in self.view_attrs:
self.col=int(self.view_attrs["col"])
if "select" in self.view_attrs:
val=eval(self.view_attrs['select'])
if type(val)!=type(1):
val=1
sel_fields=self.view_wg.parent.select_fields
sel_fields[self.name]=max(val,sel_fields.get(self.name,0))
def update_attrs(self):
new_attrs={}
if self.field:
for attr in ("readonly","required","domain"):
if attr in self.field:
new_attrs[attr]=self.field[attr]
if "states" in self.field:
state=self.eval_expr("state")
vals=self.field["states"].get(state,[])
for attr,val in vals:
new_attrs[attr]=val
for attr in ('readonly','required','invisible'):
if attr in self.view_attrs:
res=self.eval_expr(self.view_attrs[attr])
if res:
new_attrs[attr]=True
if "domain" in self.view_attrs:
new_attrs["domain"]=self.eval_expr(self.view_attrs["domain"]) or []
if "context" in self.view_attrs:
expr=self.view_attrs["context"]
if expr[0]=="{":
new_attrs["context"]=self.eval_expr(expr)
else:
ctx={}
for expr_ in expr.split(","):
var,val=expr_.split("=")
ctx[var]=self.eval_expr(val) or {}
new_attrs["context"]=ctx
if "states" in self.view_attrs:
states=self.view_attrs["states"].split(",")
state=self.eval_expr("state")
if not state in states:
new_attrs["invisible"]=1
if "attrs" in self.view_attrs:
if self.record:
attrs=self.eval_expr(self.view_attrs["attrs"])
for attr,dom in attrs.items():
eval_dom=True
for (name,op,param) in dom:
val=self.record.get_val(name)
if op=="=":
res=val==param
elif op in ("!=","<>"):
res=val!=param
elif op=="in":
res=val in param
elif op=="not in":
res=not val in param
else:
raise Exception('invalid operation in domain: %s'%op)
if not res:
eval_dom=False
break
if eval_dom:
new_attrs[attr]=True
for attr,val in new_attrs.items():
if not attr in ("readonly","required","invisible","domain","context"):
continue
if attr=="readonly" and not self.update_readonly:
continue
setattr(self,attr,val)
if self.update_can_focus:
self.can_focus=not self.readonly
def on_record_change(self):
self.update_attrs()
def on_field_change(self):
pass
def set_record(self,record):
self.record=record
record.add_event_listener("record_change",self.on_record_change)
if self.name:
record.add_event_listener("field_change_"+self.name,self.on_field_change)
def eval_expr(self,expr):
class Env(dict):
def __init__(self,wg):
self.__wg=wg
def __getitem__(self,name):
if name=="True":
return True
elif name=="False":
return False
elif name=="parent":
return Env(self.__wg.view_wg.parent)
elif name=="context":
return self.__wg.view_wg.parent.context
rec=self.__wg.record
if not rec:
return False
if not name in rec.fields:
return False
val=rec.get_val(name)
if rec.fields[name]['type']=='many2one' and val:
val=val[0]
return val
def __getattr__(self,name):
if name=="__wg":
return self.__dict__["__wg"]
return self[name]
return eval(expr,Env(self))
def move_cursor(self,y,x):
self.process_event("cursor_move",(y,x),self)
screen.move(self.win_y+y,self.win_x+x)
class Panel(Widget):
def __init__(self):
super(Panel,self).__init__()
self._childs=[]
def add(self,wg):
wg.parent=self
self._childs.append(wg)
def remove(self,wg):
self._childs.remove(wg)
def to_s(self,d=0):
s=super(Panel,self).to_s(d)
for c in self._childs:
s+="\n"+c.to_s(d+1)
return s
def _vis_childs(self):
for c in self._childs:
if c.invisible:
continue
yield c
def compute(self,h,w,y,x):
self._compute_pass1()
self.h=h
self.w=w
self.y=y
self.x=x
self._compute_pass2()
def draw(self):
for c in self._vis_childs():
c.draw()
def refresh(self):
for c in self._vis_childs():
c.refresh()
def get_tabindex(self):
ind=super(Panel,self).get_tabindex()
for wg in self._vis_childs():
ind+=wg.get_tabindex()
return ind
def clear_focus(self):
super(Panel,self).clear_focus()
for wg in self._childs:
wg.clear_focus()
def set_focus(self):
res=super(Panel,self).set_focus()
if res:
return res
for wg in self._childs:
res=wg.set_focus()
if res:
return res
def get_focus(self):
wg_f=super(Panel,self).get_focus()
if wg_f:
return wg_f
for wg in self._childs:
wg_f=wg.get_focus()
if wg_f:
return wg_f
return None
class ScrollPanel(Panel):
def __init__(self):
super(ScrollPanel,self).__init__()
self.y0=0
def _compute_pass1(self):
if self._childs:
wg=self._childs[0]
wg._compute_pass1()
else:
wg=None
if self.update_maxw:
self.maxw=wg and wg.maxw or 1
if self.maxw!=-1:
self.maxw+=self.borders[1]+self.borders[3]+1
if self.update_maxh:
self.maxh=wg and wg.maxh or 1
if self.maxh!=-1:
self.maxh+=self.borders[0]+self.borders[2]
def _compute_pass2(self):
if not self._childs:
return
wg=self._childs[0]
w=self.w-self.borders[1]-self.borders[3]-1
h=self.h-self.borders[0]-self.borders[2]
wg.y=0
wg.x=0
wg.w=w
if wg.maxh==-1:
wg.h=h
else:
wg.h=wg.maxh
wg.window=curses.newpad(wg.h+1,wg.w) # XXX: python-curses bug? should not need h+1 (can't write in bottom-right corner of window)
wg.window.bkgd(get_col_attr('base_color'))
wg.win_y=self.win_y+self.y+self.borders[0]-self.y0
wg.win_x=self.win_x+self.x+self.borders[3]
wg._compute_pass2()
def draw(self):
win=self.window
for wg in self._childs:
wg.window.clear()
wg.draw()
if self.borders[0]:
curses.textpad.rectangle(win,self.y,self.x,self.y+self.h-1,self.x+self.w-1)
h_total=self.h-self.borders[0]-self.borders[2]
if wg.h:
h0=(h_total*self.y0+wg.h-1)/wg.h
h1=h_total*min(self.y0+h_total,wg.h)/wg.h
else:
h0=0
h1=h_total
if not (h0==0 and h1==h_total):
win.attron(get_col_attr("scrollbar_color"))
win.vline(self.y+self.borders[0],self.x+self.w-1-self.borders[1],curses.ACS_VLINE,h_total)
win.vline(self.y+self.borders[0]+h0,self.x+self.w-1-self.borders[1],curses.ACS_CKBOARD,h1-h0)
win.attroff(get_col_attr("scrollbar_color"))
def refresh(self):
wg=self._childs[0]
y0=self.win_y+self.y+self.borders[0]
x0=self.win_x+self.x+self.borders[3]
y1=y0+min(self.h-self.borders[2]-self.borders[0],wg.h)-1
x1=x0+min(self.w-self.borders[1]-self.borders[3],wg.w)-1
if y1>=y0 and x1>=x0:
wg.window.refresh(self.y0,0,y0,x0,y1,x1)
wg.refresh()
def on_cursor_move(self,arg,source):
if not self._childs:
return
wg=self._childs[0]
if source.window!=wg.window:
return
y,x=arg
if y<self.y0:
self.y0=y
root_panel.compute()
root_panel.draw()
root_panel.refresh()
return True
elif y>self.y0+self.h-self.borders[0]-self.borders[2]-1:
self.y0=y-(self.h-self.borders[0]-self.borders[2]-1)
root_panel.compute()
root_panel.draw()
root_panel.refresh()
return True
class DeckPanel(Panel):
def on_keypress(self,k,source):
if k==curses.KEY_RIGHT:
if source==self:
chs=[wg for wg in self._vis_childs()]
i=chs.index(self.cur_wg)
i=(i+1)%len(chs)
self.cur_wg=chs[i]
root_panel.compute()
root_panel.draw()
root_panel.refresh()
root_panel.set_cursor()
elif k==curses.KEY_LEFT:
if source==self:
chs=[wg for wg in self._vis_childs()]
i=chs.index(self.cur_wg)
i=(i-1)%len(chs)
self.cur_wg=chs[i]
root_panel.compute()
root_panel.draw()
root_panel.refresh()
root_panel.set_cursor()
def __init__(self):
super(DeckPanel,self).__init__()
self.cur_wg=None
self.add_event_listener("keypress",self.on_keypress)
def add(self,wg):
super(DeckPanel,self).add(wg)
if self.cur_wg==None:
self.cur_wg=wg
def set_cur_wg(self,wg):
self.cur_wg=wg
def remove(self,wg):
i=self._childs.index(wg)
self._childs.pop(i)
if wg==self.cur_wg:
if self._childs:
self.cur_wg=self._childs[i%len(self._childs)]
else:
self.cur_wg=None
def _compute_pass1(self):
if not self.cur_wg:
return
self.cur_wg._compute_pass1()
if self.update_maxw:
maxw=self.cur_wg.maxw
if maxw==-1:
self.maxw=-1
else:
self.maxw=maxw+self.borders[1]+self.borders[3]+self.padding[1]+self.padding[3]
if self.update_maxh:
maxh=self.cur_wg.maxh
if maxh==-1:
self.maxh=-1
else:
self.maxh=maxh+self.borders[0]+self.borders[2]+self.padding[0]+self.padding[2]
def _compute_pass2(self):
w=self.w-self.borders[1]-self.borders[3]-self.padding[1]-self.padding[3]
h=self.h-self.borders[0]-self.borders[2]-self.padding[0]-self.padding[2]
wg=self.cur_wg
if wg.maxw==-1:
wg.w=w
else:
wg.w=min(w,wg.maxw)
if wg.maxh==-1:
wg.h=h
else:
wg.h=min(h,wg.maxh)
wg.y=self.y+self.borders[0]+self.padding[0]
wg.x=self.x+self.borders[3]+self.padding[3]
wg.window=self.window
wg.win_y=self.win_y
wg.win_x=self.win_x
wg._compute_pass2()
def draw(self):
win=self.window
if self.borders[0]:
curses.textpad.rectangle(win,self.y,self.x,self.y+self.h-1,self.x+self.w-1)
if self.cur_wg:
self.cur_wg.draw()
def refresh(self):
if self.cur_wg:
self.cur_wg.refresh()
def set_focus(self):
wg_f=Widget.set_focus(self)
if wg_f:
return wg_f
if not self.cur_wg:
return None
return self.cur_wg.set_focus()
def get_tabindex(self):
ind=Widget.get_tabindex(self)
if self.cur_wg:
ind+=self.cur_wg.get_tabindex()
return ind
class TabPanel(DeckPanel):
def __init__(self):
super(TabPanel,self).__init__()
self.padding=[1,0,0,0]
self.can_focus=True
def on_keypress(k,source):
if k==ord('c'):
if source==self:
self.remove(self.cur_wg)
root_panel.draw()
root_panel.refresh()
root_panel.set_cursor()
self.add_event_listener("keypress",on_keypress)
def compute_tabs(self):
x=self.x
self.tab_x=[]
for wg in self._childs:
self.tab_x.append(x)
x+=len(wg.name)+3
def _compute_pass2(self):
super(TabPanel,self)._compute_pass2()
self.compute_tabs()
def draw(self):
win=self.window
i=0
col=get_col_attr("tabpanel_color")
win.addstr(self.y,self.x," "*self.w,col) # XXX: use separate window for this?
for wg in self._childs:
x=self.tab_x[i]
s="%d "%(i+1)
win.addstr(self.y,x,s,(wg==self.cur_wg and get_col_attr("selection_color") or col|curses.A_BOLD))
x+=2
s="%s "%wg.name
win.addstr(self.y,x,s,wg==self.cur_wg and get_col_attr("selection_color") or col)
i+=1
super(TabPanel,self).draw()
def set_cursor(self):
if not self.cur_wg:
return
i=self._childs.index(self.cur_wg)
x=self.tab_x[i]
self.move_cursor(self.y,x)
class Notebook(DeckPanel):
def __init__(self):
super(Notebook,self).__init__()
self.can_focus=True
self.tab_x=[]
self.borders=[1,1,1,1]
self.maxw=-1
self.update_maxw=False
def compute_tabs(self):
x=self.x+3
self.tab_x=[]
for wg in self._childs:
if wg.invisible:
continue
self.tab_x.append(x)
x+=len(wg.string)+3
def _compute_pass2(self):
super(Notebook,self)._compute_pass2()
self.compute_tabs()
def draw(self):
win=self.window
super(Notebook,self).draw()
i=0
for wg in self._childs:
if wg.invisible:
continue
x=self.tab_x[i]
if x+len(wg.string)+1>=80:
continue
if i==0:
win.addch(self.y,x-2,curses.ACS_RTEE)
else:
win.addch(self.y,x-2,curses.ACS_VLINE)
s=" "+wg.string+" "
if self.cur_wg==wg:
win.addstr(self.y,x-1,s,curses.A_BOLD)
else:
win.addstr(self.y,x-1,s,get_col_attr("notebook_color"))
if i==len(self._childs)-1:
win.addch(self.y,x+len(wg.string)+1,curses.ACS_LTEE)
i+=1
def set_cursor(self):
if not self.cur_wg:
return
chs=[wg for wg in self._vis_childs()]
i=chs.index(self.cur_wg)
x=self.tab_x[i]
if x<self.x+self.w:
self.move_cursor(self.y,x)
class Table(Panel):
def __init__(self):
super(Table,self).__init__()
self.col=0
self._childs=[]
self.num_rows=0
self.seps=[[(0,False)],[(0,False)]]
self.h_top=None
self.w_left=None
self._next_cx=0
self._next_cy=0
def add(self,wg):
if self._next_cx and self._next_cx+wg.colspan+wg.colspan_follow>self.col:
self._next_cy+=1
self._next_cx=0
if wg.colspan>self.col:
wg.colspan=self.col
wg.cy=self._next_cy
wg.cx=self._next_cx
wg.parent=self
self._childs.append(wg)
self._next_cx+=wg.colspan
self.num_rows=wg.cy+1
def pop(self):
wg=self._childs.pop()
self._next_cx-=wg.colspan
return wg
def insert_row(self,cy,row):
cx=0
for wg in row:
wg.cy=cy
wg.cx=cx
cx+=wg.colspan
if cx>self.col:
raise Exception("line too big")
pos=None
i=0
for wg in self._childs:
if wg.cy>=cy:
if pos==None:
pos=i
wg.cy+=1
i+=1
if pos==None:
pos=len(self._childs)
self._childs=self._childs[:pos]+row+self._childs[pos:]
for wg in row:
wg.parent=self
self.num_rows+=1
def delete_row(self,cy):
self._childs=[wg for wg in self._childs if wg.cy!=cy]
for wg in self._childs:
if wg.cy>cy:
wg.cy-=1
self.num_rows-=1
if self._next_cy==cy:
self._next_cx=0
if self._next_cy>0:
self._next_cy-=1
def newline(self):
self._next_cy+=1
self._next_cx=0
def _get_sep_size(self,type,i):
if type=="y":
seps=self.seps[0]
elif type=="x":
seps=self.seps[1]
else:
raise Exception("invalid separator type")
if i==0:
return 0
elif i-1<len(seps):
return seps[i-1][0]
else:
return seps[-1][0]
def _get_sep_style(self,type,i):
if type=="y":
seps=self.seps[0]
elif type=="x":
seps=self.seps[1]
else:
raise Exception("invalid separator type")
if i==0:
return False
elif i-1<len(seps):
return seps[i-1][1]
else:
return seps[-1][1]
def _total_sep_size(self,type):
if type=="y":
n=self.num_rows
elif type=="x":
n=self.col
else:
raise Exception("invalid separator type")
return sum([self._get_sep_size(type,i) for i in range(n)])
def _compute_pass1(self):
for widget in self._vis_childs():
if hasattr(widget,"_compute_pass1"):
widget._compute_pass1()
# 1. compute container max width
if self.update_maxw:
expand=False
for wg in self._vis_childs():
if wg.maxw==-1:
expand=True
break
if expand:
self.maxw=-1
else:
w_left=[0]
for i in range(1,self.col+1):
w_max=w_left[i-1]
for wg in self._vis_childs():
cr=wg.cx+wg.colspan
if cr!=i:
continue
w=w_left[wg.cx]+self._get_sep_size("x",wg.cx)+wg.maxw
if w>w_max:
w_max=w
w_left.append(w_max)
self.maxw=self.borders[3]+self.borders[1]+w_left[-1]
# 2. compute container max height
if self.update_maxh:
expand=False
for wg in self._vis_childs():
if wg.maxh==-1:
expand=True
break
if expand:
self.maxh=-1
else:
h_top=[0]
for i in range(1,self.num_rows+1):
h_max=h_top[i-1]
for wg in self._vis_childs():
cr=wg.cy+wg.rowspan
if cr!=i:
continue
h=h_top[wg.cy]+self._get_sep_size("y",wg.cy)+wg.maxh
if h>h_max:
h_max=h
h_top.append(h_max)
self.maxh=self.borders[2]+self.borders[0]+h_top[-1]
def _compute_pass2(self):
if not self._childs:
self.w=0
return
# 1. compute child widths
w_avail=self.w-self.borders[3]-self.borders[1]
for wg in self._vis_childs():
wg.w=0
w_left=[0]*(self.col+1)
w_rest=w_avail
use_extra=False
# allocate space fairly to every child
while w_rest>0:
w_alloc=w_rest-self._total_sep_size("x")
if w_alloc>self.col:
dw=w_alloc/self.col
else:
dw=1
incr=False
for wg in self._vis_childs():
maxw=wg.maxw
if maxw!=-1:
if use_extra and wg.extw:
maxw+=wg.extw
if not wg.w<maxw:
continue
dw_=min(dw,maxw-wg.w)
else:
dw_=dw
w=w_left[wg.cx]+self._get_sep_size("x",wg.cx)+wg.w+dw_
cr=wg.cx+wg.colspan
if w>w_left[cr]:
dwl=w-w_left[cr]
if dwl>w_rest:
continue
wg.w+=dw_
incr=True
for i in range(cr,self.col+1):
w_left[i]+=dwl
w_rest-=dwl
if w_rest==0:
break
else:
wg.w+=dw_
incr=True
if not incr:
if use_extra:
break
else:
use_extra=True
self.w_left=w_left
# add extra cell space to regions
for wg in self._vis_childs():
if wg.maxw!=-1 and wg.w==wg.maxw:
continue
w=w_left[wg.cx]+self._get_sep_size("x",wg.cx)+wg.w
cr=wg.cx+wg.colspan
if w<w_left[cr]:
dw=w_left[cr]-w
if wg.maxw!=-1:
dw=min(dw,wg.maxw-wg.w)
wg.w+=dw
# 2. compute child heights
h_avail=self.h-self.borders[2]-self.borders[0]
for wg in self._vis_childs():
wg.h=0
h_top=[0]*(self.num_rows+1)
h_rest=h_avail
# allocate space fairly to every child
while h_rest>0:
h_alloc=h_rest-self._total_sep_size("y")
if h_alloc>self.num_rows:
dh=h_alloc/self.num_rows
else:
dh=1
incr=False
for wg in self._vis_childs():
if wg.maxh!=-1:
if not wg.h<wg.maxh:
continue
dh_=min(dh,wg.maxh-wg.h)
else:
dh_=dh
h=h_top[wg.cy]+self._get_sep_size("y",wg.cy)+wg.h+dh_
cr=wg.cy+wg.rowspan
if h>h_top[cr]:
dht=h-h_top[cr]
if dht>h_rest:
continue
wg.h+=dh_
incr=True
for i in range(cr,self.num_rows+1):
h_top[i]+=dht
h_rest-=dht
if h_rest==0:
break
else:
wg.h+=dh_
incr=True
if not incr:
break
self.h_top=h_top
# add extra cell space to regions
for wg in self._vis_childs():
if wg.maxh!=-1 and wg.h==wg.maxh:
continue
h=h_top[wg.cy]+self._get_sep_size("y",wg.cy)+wg.h
cr=wg.cy+wg.rowspan
if h<h_top[cr]:
dh=h_top[cr]-h
if wg.maxh!=-1:
dh=min(dh,wg.maxh-wg.h)
wg.h+=dh
# 3. compute child positions
for wg in self._vis_childs():
if wg.valign=="top":
wg.y=self.y+self.borders[0]+self.h_top[wg.cy]+self._get_sep_size("y",wg.cy)
elif wg.valign=="bottom":
wg.y=self.y+self.borders[0]+self.h_top[wg.cy+wg.rowspan]-wg.h
else:
raise Exception("invalid valign: %s"%wg.valign)
if wg.halign=="left":
wg.x=self.x+self.borders[3]+w_left[wg.cx]+self._get_sep_size("x",wg.cx)
elif wg.halign=="right":
wg.x=self.x+self.borders[3]+w_left[wg.cx+wg.colspan]-wg.w
else:
raise Exception("invalid halign: %s"%wg.valign)
wg.window=self.window
wg.win_y=self.win_y