-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1162 lines (1074 loc) · 43.5 KB
/
main.py
File metadata and controls
1162 lines (1074 loc) · 43.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
@Author: CalaMity-X
"""
"""
Visual HSP -> main.py
Copyright (C) 2025 CalaMityX
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 <https://gnu.ac.cn/licenses/>.
"""
import _thread
import sys
import easygui
import pygame
import json
import headers
from segment_edit import seg_edit_support as seg_edit
selElm="Select"
maxElmts=999
def isPointInArea(Point, StartPoint, W, H):
return StartPoint[0]<Point[0]<StartPoint[0]+W and StartPoint[1]<Point[1]<StartPoint[1]+H
class Variables:
def __init__(self):
self.vars = {}
def set_if_none(self, k, val):
if k in self.vars.keys(): return
self.vars[k] = val
print("Var set_if_none:",k,":",val)
def set(self,k,v):
self.vars[k] = v
def rm(self,k):
self.vars.pop(k)
def mnt(self,d:dict):
self.vars = d
def exp(self):
return self.vars
def contains(self,k):
return k in self.vars.keys()
def serialize(self):
return "\n\n".join(f"{k} = {v if isinstance(v,int) else '"'+str(v)+'"'}" for k,v in self.vars.items())
def default(self):
self.vars = {"def_num":-1, "def_str":""}
global_vars = Variables()
global_vars.default()
#create a default val
Types={
"WidgetSel":0x01,
}
Elm_Types={
"Button": "Button",
"ComBox": "ComBox",
"Lbl": "Label",
"Picture": "Picture",
"MesBox": "MesBox",
"Input": "Input"
}
Env={
"SelWdg":"",
"State":"Normal",
"ResizingObj": None,
"ExpandObj": -1,
"Selected": -1
}
atl=False
pygame.init()
x=1240
y=768
def_hs=(50,30)
wnd = pygame.display.set_mode((x,y))
pygame.display.set_caption("VisualHSP")
clock = pygame.time.Clock()
# set
widget_list_width = 100
pad=5
def ignore(*args): pass
csr=[0,0]
ignore(csr) # to ignore IDE warn
pygame.font.init()
widget_list=[]
font_path = "unifont-17.0.01.otf"
gf = pygame.font.Font(font_path,48,)
gfsm = pygame.font.Font(font_path,14,)
gfm = pygame.font.Font(font_path,24,)
gfs = pygame.font.Font(font_path,16,)
class TkDialogs:
@staticmethod
def askText(title,text,val) -> str:
return easygui.enterbox(text,title,val,False)
class BaseElmParams:
def __init__(self):
self.prm = self.get_default()
def get_default(self):
return {}
def getAll(self):
return self.prm
def set(self,Key,Val):
self.prm[Key] = Val
def get(self,Key,Df=None):
return self.prm[Key] if Key in self.prm.keys() else Df
def containsKey(self,Key):
return Key in self.prm.keys()
def gen_view(self):
return "\n".join([f"{k}: {v}" for k,v in self.prm.items()])
def mnt_all(self,p:dict):
self.prm = p
return
class ButtonParams(BaseElmParams):
def get_default(self):
return {
"Text": "Button",
"Action": "label",
"lVar": ""
}
def __init__(self):
super().__init__()
class LabelParams(BaseElmParams):
def get_default(self):
return {
"Text": "Label",
"Color": ""
}
def __init__(self):
super().__init__()
class PicParams(BaseElmParams):
def get_default(self):
return {
"Src": "example.jpg"
}
def __init__(self):
super().__init__()
class DefWndParams(BaseElmParams):
def get_default(self):
return {
"TopMost": False,
"CenterWindow": True,
"Background": "",
"BackgroundColor": "255,255,255",
"Bassmod_Enabled": False,
"Bassmod_File": "",
"RemoveMinimize": True,
"DefaultTextColor": "0,0,0",
"Title": "Wnd"
}
def __init__(self):
super().__init__()
class ComboxParams(BaseElmParams):
def __init__(self):
super().__init__()
def get_default(self):
return {
"SelectVarName": "def_num",
"OptionsVarName": "def_str",
"lVar": ""
}
class MesboxParams(BaseElmParams):
def __init__(self):
super().__init__()
def get_default(self):
return {
"MesVarName": "def_str",
"Editable": False,
"HideScroll": True,
"Center": True,
"lVar": ""
}
defParamForElmMap={
Elm_Types["Button"]: ButtonParams,
Elm_Types["Lbl"]: LabelParams,
Elm_Types["Picture"]: PicParams,
Elm_Types["ComBox"]: ComboxParams,
Elm_Types["MesBox"]: MesboxParams
}
""" Custom Segment (LABEL) """
custom_import_segment_name = ";;CustomHeader"
custom_draw_segment_name=";;CustomDraw"
custom_before_draw = ";;BeforeDraw"
ignored_segs = [custom_draw_segment_name,custom_before_draw,custom_import_segment_name]
class CustomSegment:
def __init__(self):
self.seg = {}
def default(self):
return {
"label": "stop",
"quit": headers.hsp_quit_lbl,
custom_import_segment_name: "",
custom_draw_segment_name: "",
custom_before_draw: ""
}
def objexp(self):
return self.seg
def mnt(self,a:dict):
self.seg = a
def export(self):
return "".join([f"\n*{k}\n{v}" if not k in ignored_segs else "" for k,v in self.seg.items()])
def getSingle(self,k,default=None):
return self.seg[k] if k in self.seg else default
def contains(self,k):
return k in self.seg
def init_key(self,k):
if not k in self.seg:
self.seg[k] = ""
global_segs = CustomSegment()
#init glb_segs
global_segs.mnt(global_segs.default())
class Clickable:
def __init__(self):
pass
def onclick(self):
pass
def getType(self):
return None
def getParam(self):
return None
def onrclick(self):
pass
def onmclick(self):
pass
class WidgetItem(Clickable):
def __init__(self, csr, text, prm=None):
super().__init__()
self.csr=csr
self.w=widget_list_width
self.h=36
self.text=text
self.prm = prm if prm else text
def mouseEv(self,vec):
return isPointInArea(vec,(self.csr),self.w,self.h)
def drw(self,c=(32,32,32)):
pygame.draw.rect(wnd,c,(*self.csr,self.w,self.h))
t=gfm.render(self.text,atl,(0xff,0xff,0xff))
wnd.blit(t,(self.csr[0]+2,self.csr[1]))
pygame.draw.line(wnd,(99,99,99),(self.csr[0],self.csr[1]-1),(self.csr[0]+self.w,self.csr[1]-1))
return 0
def pack(self,w=False,h=True):
return (self.csr[0]+(self.w if w else 0), self.csr[1]+(self.h if h else 0)) if self.drw() == 0 else 0
def onclick(self):
return self.getType()
def getType(self):
return Types["WidgetSel"]
def getParam(self):
return self.prm
def appendWdgL(Text):
global csr
widget_list.append(WidgetItem(csr,Elm_Types[Text] if Text != selElm else Text))
csr=widget_list[-1].pack()
appendWdgL(selElm)
appendWdgL("Button")
appendWdgL("Lbl")
appendWdgL("Picture")
appendWdgL("MesBox")
appendWdgL("ComBox")
# appendWdgL("Input")
def prg_magnet(val,base,step):
return base+step*((val-base)//step)
class Element: # Non-Clickable, will be handled in Dlbox:
def __init__(self, Text, Type, base_csr, w, h, pnt_csr, default_params=None):
if default_params is None:
default_params = BaseElmParams()
self.type=Type
self.txt=Text
self.csr=base_csr
self.w,self.h=w,h
self.pnt_csr=pnt_csr
self.params=default_params
def put(self,sel=False):
pygame.draw.rect(wnd,(0xff,0xff,0xff),(self.pnt_csr[0]+self.csr[0]-1,self.pnt_csr[1]+self.csr[1]-1,self.w+2,self.h+2))
pygame.draw.rect(wnd,(32,32,32) if not sel else (99,99,99),(self.pnt_csr[0]+self.csr[0],self.pnt_csr[1]+self.csr[1],self.w,self.h))
_=gfsm.render(self.txt,atl,(255,255,255))
wnd.blit(_,tuple(a+b for a,b in zip(self.pnt_csr,self.csr)))
# return (self.csr[0]+(self.w if mx else 0),self.csr[1]+(self.h if my else 0))
def isPointIn(self,vec):
sfx = self.pnt_csr[0]+self.csr[0]
sfy = self.pnt_csr[1]+self.csr[1]
w=self.w
h=self.h
return isPointInArea(vec,(sfx,sfy),w,h)
def serialize(self) -> str | None:
sx, sy= self.csr
w, h= self.w,self.h
if self.type==Elm_Types["Lbl"]:
clr=self.params.get("Color","")
c1,c2='',''
if clr:
c1 = f"color {clr}\n"
c2 = f"\ncolor {dlb.params.get("DefaultTextColor")}"
return f"pos {sx},{sy}\n{c1}mes \"{self.params.get("Text",Df="").replace("\"","\\\"")}\"{c2}"
elif self.type==Elm_Types["Button"]:
sec=self.params.get("Action",Df="undefined")
if not global_segs.contains(sec): global_segs.init_key(sec)
return f"pos {sx},{sy}\nobjsize {w},{h}\nbutton \"{self.params.get("Text",Df="Button(Invalid Text)")}\", *{sec}{f"\n{self.params.get("lVar")} = stat" if self.params.get("lVar") else ""}"
elif self.type==Elm_Types["Picture"]:
return f"pos {sx},{sy}\ncelload \"{self.params.get("Src","1.jpg")}\", 1\ncelput 1"
elif self.type==Elm_Types["ComBox"]:
# "SelectVarName": "def_str",
# "OptionsVarName": "def_str"
global_vars.set_if_none(self.params.get("SelectVarName", "unknown_ivar"), -1)
global_vars.set_if_none(self.params.get("OptionsVarName", "unknown_svar"), "")
return f"pos {sx},{sy}\nobjsize {w},{h}\ncombox {self.params.get("SelectVarName")},100,{self.params.get("OptionsVarName")}{f"\n{self.params.get("lVar")} = stat" if self.params.get("lVar") else ""}"
elif self.type==Elm_Types["MesBox"]:
hideSc = self.params.get("HideScroll",True)
center = self.params.get("Center", True)
global_vars.set_if_none(self.params.get("MesVarName", "unknown_ivar"), "")
return (f"pos {sx},{sy}\nobjsize {w},{h}\nmesbox {self.params.get("MesVarName")}, {w}, {h}, {"1" if self.params.get("Editable",False) else "2"}\n{f"{self.params.get("lVar")} = stat\n" if self.params.get("lVar") else ""}"
f"{"_=stat\n" if hideSc or center else "\n"}"
f"{"HideScroll _\n" if hideSc else "\n"}"
f"{"MakeCenter _\n" if center else "\n"}")
return "\n"
def exp_cfg(self):
return {
"Type": self.type,
"Params": self.params.getAll(),
"Pos": [*self.csr],
"Size": [self.w, self.h],
"DesAlt": self.txt
}
def imp_cfg(self,d:dict):
assert "Type" in d
assert "Params" in d
assert "Pos" in d
assert "Size" in d
assert "DesAlt" in d
self.type = d['Type']
self.params = defParamForElmMap[d['Type']]()
self.params.mnt_all(d['Params'])
self.csr = (*d["Pos"],)
self.txt = d['DesAlt']
self.w,self.h = d["Size"]
class Dlbox(Clickable):
def __init__(self, csr, unitL: int, unitVec: tuple[int, int]):
super().__init__()
self.csr=csr
self.unitL=unitL
# unitVec = [i+1 for i in unitVec]
self.ux,self.uy=[i+1 for i in unitVec]
self.w,self.h=self.ux*unitL,self.uy*unitL
self.elements=[]
self.temp=Element("Temp",Elm_Types['Lbl'],(0,0),*def_hs,self.csr)
self.params=DefWndParams()
self.expandMode=0
def resize(self):
self.w, self.h = self.ux * self.unitL, self.uy * self.unitL
def drw_bgrect(self):
# outl
pygame.draw.rect(wnd, (0xff, 0xff, 0xff), (*[i -1 for i in self.csr], self.w+2, self.h+2))
# bg
pygame.draw.rect(wnd,(24,24,24),(*self.csr,self.w,self.h))
# points
for x in range(self.ux):
for y in range(self.uy):
pygame.draw.rect(wnd,(64,64,64),(self.csr[0]+x*self.unitL-1,self.csr[1]+y*self.unitL-1,2,2))
return 0
def drw(self):
self.drw_bgrect()
for elId in range(len(self.elements)):
el = self.elements[elId]
assert isinstance(el,Element)
el.put(Env["Selected"] == elId)
def isInArea(self,vec):
return isPointInArea(vec,self.csr,self.w,self.h)
def onclick(self):
if (Env["State"] == "Normal"):
if not Env["SelWdg"] == selElm:
if len(self.elements)<=maxElmts:
Env["State"] = "Add"
else:
print("Max elmt cnt exc.")
else:
#slct
for elmIdx in range(len(self.elements)):
elmId=len(self.elements)-elmIdx-1
_=self.elements[elmId]
assert isinstance(_,Element)
if _.isPointIn(pygame.mouse.get_pos()):
Env["Selected"] = elmId
return
Env["Selected"] = -1
elif (Env["State"] == "Add"):
#Place first point
# gen default params
tp = Env["SelWdg"]
df = defParamForElmMap[tp]() if tp in defParamForElmMap else BaseElmParams()
mx, my = pygame.mouse.get_pos()
self.elements.append(Element(Env["SelWdg"], Env["SelWdg"],
(prg_magnet(mx - self.csr[0], 0, self.unitL),
prg_magnet(my - self.csr[1], 0, self.unitL)),
*def_hs, self.csr,default_params=df))
Env["State"] = "Expand"
Env["ExpandObj"] = -1
elif (Env["State"] == "Expand"):
Env["State"] = "Normal"
#End Exp
elif (Env["State"] == "Resize"):
#goto Expand Mode
Env["State"] = "Expand"
Env["ExpandObj"] = Env["ResizingObj"]
def tick(self):
if Env["State"] == "Add":
tv=pygame.mouse.get_pos()
ax = prg_magnet(tv[0]-self.csr[0],0,self.unitL)
ay = prg_magnet(tv[1]-self.csr[1],0,self.unitL)
self.temp.csr = (ax,ay)
self.temp.put()
elif Env["State"] == "Expand":
elm = self.elements[Env["ExpandObj"]]
assert isinstance(elm,Element)
mx,my=pygame.mouse.get_pos()
mx,my=mx-self.csr[0],my-self.csr[1]
fx,fy=[prg_magnet(v,0,self.unitL) for v in [mx,my]]
# ZeroSize,Non Allowed
ny=fy-elm.csr[1]
nx=fx-elm.csr[0]
if nx < self.unitL or ny < self.unitL:
nx=self.unitL
ny=self.unitL
elm.h,elm.w=ny,nx
#show size ard mse
text=f"{nx}x{ny}"
_=gfs.render(text,atl,(0xff,0xff,0xff))
nx,ny=pygame.mouse.get_pos()
wnd.blit(_,(nx+10,ny+10))
elif Env["State"] == "Resize":
tv = pygame.mouse.get_pos()
ax = prg_magnet(tv[0] - self.csr[0], 0, self.unitL)
ay = prg_magnet(tv[1] - self.csr[1], 0, self.unitL)
assert isinstance(Env["ResizingObj"], int)
assert Env["ResizingObj"] is not None and not isinstance(Env["ResizingObj"],str)
elm = self.elements[Env["ResizingObj"]]
elm.csr = (ax, ay)
def onrclick(self):
if Env["State"] == "Normal":
for elmIdx in range(len(self.elements)):
elmId = len(self.elements)-elmIdx-1
elm = self.elements[elmId]
assert isinstance(elm,Element)
if (elm.isPointIn(pygame.mouse.get_pos())):
print("Rclick obj id",elmId)
Env["ResizingObj"] = elmId
Env["State"] = "Resize"
(elm.w,elm.h) = def_hs
return
def onmclick(self):
if Env["State"] == "Normal":
for elmIdx in range(len(self.elements)):
elmId = len(self.elements) - elmIdx -1
elm = self.elements[elmId]
assert isinstance(elm,Element)
if (elm.isPointIn(pygame.mouse.get_pos())):
print("Mclick obj",elmId)
print("Delete obj",elmId)
self.elements.pop(elmId)
if elmId == Env["Selected"] or Env['Selected'] >= len(dlb.elements): Env["Selected"] = -1
return
def serialize(self): #Export
out=""
out+=f"width {self.w},{self.h}"
for i in self.elements:
assert isinstance(i,Element)
out+="\n"+i.serialize()
return out
def layout_exp_cfg(self): #Save
ex = []
for elm in self.elements:
assert isinstance(elm, Element)
ex.append(elm.exp_cfg())
return ex
def layout_imp_cfg(self, d:list[dict]): #Open
for el in d:
assert isinstance(el,dict)
new=Element("","",(0,0),0,0,self.csr,None)
new.imp_cfg(el)
self.elements.append(new)
def wnd_exp_cfg(self):
return self.params.getAll()
def wnd_imp_cfg(self,a:dict):
self.params.mnt_all(a)
def wnd_c_exp_cfg(self):
return {"xc":self.ux,"yc":self.uy,"unit":self.unitL}
def wnd_c_imp_cfg(self,d:dict):
assert "xc" in d and "yc" in d and "unit" in d
self.ux = d['xc']
self.uy = d['yc']
self.unitL = d['unit']
self.resize()
def exp_cfg(self):
return {"Elements":self.layout_exp_cfg(),"Wnd":self.wnd_exp_cfg(),"Size":self.wnd_c_exp_cfg()}
def imp_cfg(self,p:dict):
assert "Elements" in p and "Wnd" in p and "Size" in p
self.wnd_imp_cfg(p['Wnd'])
self.layout_imp_cfg(p['Elements'])
self.wnd_c_imp_cfg(p["Size"])
btm_list_height=50
class BmListItem: #Non-Clickable 2
def __init__(self,cld_csr,pnt_csr,id: int,w=30,h=btm_list_height-1):
self.csr = cld_csr
self.pnt_csr = pnt_csr
self.h=h
self.w=w
self.id=id
def drw(self,last=False):
(sx,sy) = tuple(ax+bx for ax,bx in zip(self.csr,self.pnt_csr))
pygame.draw.rect(wnd,(32,32,32)if Env["Selected"]!=self.id else (64,64,64),(sx,sy,self.w,self.h))
_=gfsm.render(str(self.id),atl,(0xff,0xff,0xff))
wnd.blit(_,(sx,sy))
if Env["State"]=="Expand":
if Env["ExpandObj"] == self.id or (Env["ExpandObj"] == -1 and self.id == len(dlb.elements)-1):
_ = gfsm.render("EX", atl, (0xff, 0xff, 0xff))
wnd.blit(_, (sx, sy+10))
if Env["State"]=="Resize":
if Env["ResizingObj"] == self.id:
_ = gfsm.render("RS", atl, (0xff, 0xff, 0xff))
wnd.blit(_, (sx, sy + 10))
if not last:
stp=tuple(a+b for a,b in zip(self.pnt_csr,self.csr))
pygame.draw.line(wnd,(99,99,99),(stp[0]+self.w-1,stp[1]), (stp[0]+self.w-1,y))
class BottomElmtsList(Clickable):
def __init__(self, csr):
super().__init__()
self.csr=csr
self.step=20
def drw(self):
pygame.draw.line(wnd,(0xff,0xff,0xff),(self.csr[0],self.csr[1]-1),(x,self.csr[1]-1))
#fill bg
pygame.draw.rect(wnd,(0,0,0),(*self.csr,x,btm_list_height))
step=self.step
cur=0
for elmId in range(len(dlb.elements)):
elm = dlb.elements[elmId]
assert isinstance(elm,Element)
BmListItem((cur,1),self.csr,elmId,w=step).drw(elmId == len(dlb.elements)-1)
cur+=step
#drw id
_=gfsm.render(str(elmId),atl,(0xff,0xff,0xff))
sx,sy=tuple(a+b for a,b in zip(dlb.csr,elm.csr))
wnd.blit(_,(sx+len(elm.txt)*8,sy)) #.txt not .type.
if show_attr:
#drw elm params
rx=0
txt=elm.params.gen_view()
for l in txt.split("\n"):
_=gfsm.render(l,atl,(0xff,0xff,0xff))
wnd.blit(_,(sx,sy+10+rx))
rx+=10
#drw elm params if selected
if elmId == Env["Selected"]:
# drw elm params
ry = 0
txt = elm.params.gen_view()
base_csr = (x-rpnl_wth+1, len(rpnl.clickable)*rpnl.step+1)
for l in txt.split("\n"):
_ = gfsm.render(l, atl, (0xff, 0xff, 0xff))
wnd.blit(_, (base_csr[0], base_csr[1] + 10 + ry))
ry += 10
def isInArea(self,vec):
return isPointInArea(vec,self.csr,x,btm_list_height)
def onclick(self):
mx,my=pygame.mouse.get_pos()
id=mx//self.step
print("Clicked index (calculated):",id)
if id<= len(dlb.elements)-1:
Env["Selected"]=id
def onmclick(self):
mx, my = pygame.mouse.get_pos()
id = mx // self.step
print("mClicked index (calculated):", id)
if id <= len(dlb.elements) - 1:
dlb.elements.pop(id)
if id == Env["Selected"] or Env['Selected'] >= len(dlb.elements): Env["Selected"] = -1
csr = (widget_list_width+pad,pad)
dlb = Dlbox(csr,10,(30,40))
csr = (0,y-btm_list_height)
btm_list = BottomElmtsList(csr)
Env['SelWdg'] = selElm
show_attr=False
csr=(0,600)
ignore(csr)
def mount_var(vf):
return vf.replace("<ShowAttr>",str(show_attr)).replace("<ATL>",str(atl))
from var_edit import var_editor_support as var_editor
def pg_block():
pygame.event.set_blocked([pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP, pygame.MOUSEMOTION])
def pg_end_block():
pygame.event.set_allowed([pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP, pygame.MOUSEMOTION])
pygame.event.clear()
class Menu(Clickable):
def __init__(self, csr, step=60):
super().__init__()
self.csr=csr
self.step=step
self.operations = [
"Save",
"Open",
"Export",
"About",
"Show Attr\n<ShowAttr>",
"Antialias\n<ATL>",
"WndSize",
"VarEditor",
"SegsEdit"
]
def drw(self):
rx=0
for z in self.operations:
pygame.draw.rect(wnd,(0xff,0xff,0xff),(self.csr[0]+rx,self.csr[1],self.step,menu_height))
pygame.draw.rect(wnd,(32,32,32),(self.csr[0]+rx+1,self.csr[1]+1,self.step-2,menu_height-2))
by=self.csr[1]
subst=0
rz = mount_var(z)
for l in rz.split("\n"):
_=gfsm.render(l,atl,(0xff,0xff,0xff))
wnd.blit(_,(self.csr[0]+rx,by+subst))
subst+=10
rx+=self.step
def isInArea(self,vec):
return isPointInArea(vec,self.csr,self.step * len(self.operations), menu_height)
def onclick(self):
global show_attr,atl
mx,my=pygame.mouse.get_pos()
rx=mx-self.csr[0]
ex=rx//self.step
if ex<= len(self.operations):
op=self.operations[ex].split("\n")[0]
print("Menu clk:",op)
else:
return
if (op=="About"):
_thread.start_new_thread(lambda:easygui.msgbox("Made By CalaMity-X\nAll Rights Reserved.", "About This Program", "Done"),())
elif (op=="Export"):
o=Utils.exportHSP()
easygui.textbox("Out:","Export",o)
elif (op=="Show Attr"):
show_attr = not show_attr
elif (op=="Antialias"):
atl = not atl
elif op=="Save":
o = dlb.exp_cfg()
v = global_vars.exp()
s = global_segs.objexp()
p = json.dumps({"WndCfg": o, "VarCfg": v, "SegCfg": s})
easygui.textbox("Save:","Save",p)
elif op=="Open":
i=TkDialogs.askText("Paste","Paste cfg here","")
if not i is None:
try:
d=json.loads(i)
dlb.elements=[]
assert "WndCfg" in d and "VarCfg" in d and "SegCfg" in d
dlb.imp_cfg(d['WndCfg'])
global_vars.mnt(d["VarCfg"])
global_segs.mnt(d["SegCfg"])
except BaseException as e:
easygui.msgbox("Failed to load: "+str(e),"Error")
elif op=="WndSize":
i=TkDialogs.askText("Size","Format: wc,hc","")
if i is None:return
nw,nh=[int(v) for v in i.split(",")]
dlb.ux=nw
dlb.uy=nh
dlb.resize()
elif op=="VarEditor":
pg_block()
recv = var_editor.main(data=global_vars.exp())
pg_end_block()
if not recv: return
global_vars.mnt(recv)
print("saved new vars")
elif op=="SegsEdit":
org = global_segs.objexp()
pg_block()
r=seg_edit.main(data=org)
pg_end_block()
if not r: return
global_segs.mnt(r)
print("saved new segs")
menu_height=30
csr=(widget_list_width,y-btm_list_height-menu_height)
sysmenu = Menu(csr,65)
rpnl_wth = 200
class RightPnlItem: #NonClickAble
def __init__(self,csr,pnt_csr,text,w,h):
self.pnt_csr=pnt_csr
self.csr=csr
self.text=text
self.w=w
self.h=h
def drw(self):
pygame.draw.rect(wnd,(32,32,32), (*tuple(a+b for a,b in zip(self.csr,self.pnt_csr)),self.w,self.h))
_=gfs.render(RightPnlAttrInflate(self.text),atl,(0xff,0xff,0xff))
wnd.blit(_,(tuple(a+b for a,b in zip(self.csr,self.pnt_csr))))
pygame.draw.line(wnd,(99,99,99),(self.pnt_csr[0]+self.csr[0],self.csr[1]+self.pnt_csr[1]+self.h-1),(self.pnt_csr[0]+self.csr[1]+self.w,self.csr[1]+self.pnt_csr[1]+self.h-1))
def RightPnlAttrInflate(st:str)->str:
return st.replace("<TopMost>",str(dlb.params.get("TopMost"))).replace("<CenterWnd>",str(dlb.params.get("CenterWindow"))).replace("<WndBG>",dlb.params.get("Background") if dlb.params.get("Background") != "" else "(Not Set)")\
.replace("<Bassmod_Enabled>",str(dlb.params.get("Bassmod_Enabled"))).replace("<Bassmod_File>",str(dlb.params.get("Bassmod_File") if dlb.params.get("Bassmod_File") else "(Not Set)"))\
.replace("<mb.editable>",f"{dlb.elements[Env["Selected"]].params.get("Editable","(None)") if Env['Selected'] < len(dlb.elements) and Env['Selected'] != -1 else "Error idx"}")\
.replace("<mb.hideScroll>",f"{dlb.elements[Env["Selected"]].params.get("HideScroll","(None)") if Env['Selected'] < len(dlb.elements) and Env['Selected'] != -1 else "Error idx"}") \
.replace("<mb.center>",f"{dlb.elements[Env["Selected"]].params.get("Center", "(None)") if Env['Selected'] < len(dlb.elements) and Env['Selected'] != -1 else "Error idx"}").replace("<WndBGC>",dlb.params.get("BackgroundColor"))\
.replace("<WndRemoveMinimize>",str(dlb.params.get("RemoveMinimize"))).replace("<DefaultTextColor>",dlb.params.get("DefaultTextColor")).replace("<wnd.title>",dlb.params.get("Title","(None)"))\
.replace("<lVar>",f"{dlb.elements[Env["Selected"]].params.get("lVar", "(None)") if Env['Selected'] < len(dlb.elements) and Env['Selected'] != -1 else "Error idx"}")
class RightPanel(Clickable):
def __init__(self, csr):
super().__init__()
self.csr=csr
self.w=rpnl_wth
self.h=y-btm_list_height-1
self.clickable=[]
self.step=30
self._const={
"btn.text": "Edit btn text",
"btn.action": "Edit btn action",
"lbl.text": "Edit label text",
"pic.src": "Edit Pic Src",
"alt":"Change Alt",
"wnd.topmost": "TopMost: <TopMost>",
"wnd.center": "CenterWnd: <CenterWnd>",
"cm.var": "Combo selection Var",
"cm.op": "Combo options Var",
"wnd.bg": "BG: <WndBG>",
"wnd.bm_bool": "Bassmod: <Bassmod_Enabled>",
"wnd.bm_file": "Bassmod_File: <Bassmod_File>",
"mb.var": "Mes Var",
"mb.editable": "Editable: <mb.editable>",
"mb.hideScroll": "HideScroll: <mb.hideScroll>",
"mb.center": "Center: <mb.center>",
"wnd.bgcolor": "BG Color: <WndBGC>",
"lbl.color": "Change Color",
"wnd.rm_mini": "Rm Minimize: <WndRemoveMinimize>",
"wnd.tcolor": "Def txt color: <DefaultTextColor>",
"wnd.title": "Title: <wnd.title>",
"uni.lvar": "lVar: <lVar>"
}
self.options={
Elm_Types["MesBox"]:[
self._const['uni.lvar'],
self._const['mb.var'],
self._const['mb.editable'],
self._const['mb.hideScroll'],
self._const['mb.center'],
],
Elm_Types["Button"]:[
self._const['uni.lvar'],
self._const['btn.text'],
self._const['btn.action'],
],
Elm_Types["Lbl"]:[
self._const['lbl.text'],
self._const['lbl.color']
],
Elm_Types["Picture"]:[
self._const['pic.src']
],
"Wnd":[
self._const['wnd.title'],
self._const['wnd.topmost'],
self._const['wnd.center'],
self._const['wnd.bg'],
self._const['wnd.bm_bool'],
self._const['wnd.bm_file'],
self._const['wnd.bgcolor'],
self._const['wnd.tcolor'],
self._const['wnd.rm_mini']
],
Elm_Types["ComBox"]:[
self._const['uni.lvar'],
self._const["cm.var"],
self._const['cm.op'],
]
}
def updateClickable(self):
self.clickable = []
if Env["Selected"] == -1:
[self.clickable.append(op) for op in self.options["Wnd"]]
return
curr = dlb.elements[Env["Selected"]] if Env["Selected"] != -1 and Env["Selected"] < len(dlb.elements) else None
if not curr: return
assert isinstance(curr, Element)
tp=curr.type
self.clickable.append(self._const['alt'])
if tp in self.options.keys():
[self.clickable.append(op) for op in self.options[tp]]
def drw_bgrect(self):
pygame.draw.rect(wnd,(0,0,0),(*self.csr,self.w,self.h))
pygame.draw.line(wnd,(0xff,0xff,0xff),(self.csr[0],0),(self.csr[0],self.h))
def drw(self):
self.drw_bgrect()
self.updateClickable()
ind_y=0
for elm in self.clickable:
RightPnlItem((1,ind_y),(self.csr[0]+1,self.csr[1]),elm,self.w-1,self.step).drw()
ind_y+=self.step
def getCurrSel(self,rel_y):
id=rel_y//self.step
if id>=len(self.clickable): return ""
cl=self.clickable[id]
# assert isinstance(cl, RightPnlItem)
return cl #.text
def onclick(self):
if Env["State"] == "Normal":
ax,ay = pygame.mouse.get_pos()
ry = ay - self.csr[1]
if ry<0: return
sel = self.getCurrSel(ry)
if not sel: return
print("clicked:",sel)
currid = Env["Selected"]
if Env["Selected"] != -1:
currObj = dlb.elements[currid]
assert isinstance(currObj, Element)
if sel == self._const['lbl.text']:
ol = TkDialogs.askText("Change Label's Text","Change text for widget id: "+str(currid),currObj.params.get("Text"))
if ol is None: return
print("got:",ol,"for",currid,", change it.")
currObj.params.set("Text",ol)
elif sel == self._const["btn.text"]:
ol = TkDialogs.askText("Change Button's Text","Change text for widget id: "+str(currid),currObj.params.get("Text"))
if ol is None: return
print("got:",ol,"for",currid,", change it.")
currObj.params.set("Text",ol)
elif sel == self._const["btn.action"]:
ol = TkDialogs.askText("Change Button's Action", "Change text for widget id: " + str(currid)+"\nButton action must be a valid label name, without \"*\"",
currObj.params.get("Action"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
currObj.params.set("Action", ol)
elif sel == self._const['alt']:
ol = TkDialogs.askText("Change Widget's Alt Name", "Change Alt for widget id: " + str(
currid) + "\nAlt will not appear in exported code!",
currObj.txt)
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
currObj.txt=ol
elif sel == self._const['cm.var']:
ol = TkDialogs.askText("Change Combox's Var", "Change Var for widget id: " + str(
currid) + "\nCombo var is the selection storage.",
currObj.params.get("SelectVarName"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
currObj.params.set("SelectVarName",ol)
elif sel == self._const['cm.op']:
ol = TkDialogs.askText("Change Combox's Options Var", "Change Options for widget id: " + str(
currid) + "\nThe var which saved combox's options",
currObj.params.get("OptionsVarName"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
currObj.params.set("OptionsVarName", ol)
elif sel == self._const['pic.src']:
ol = TkDialogs.askText("Change Pic's src", "Change pic src for widget id: " + str(
currid) + "\nfile path",
currObj.params.get("Src"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
currObj.params.set("Src", ol)
elif sel == self._const['mb.var']:
ol = TkDialogs.askText("Change Mesbox's var", "Change var for widget id: " + str(
currid) + "\nMesbox var storage",
currObj.params.get("MesVarName"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
currObj.params.set("MesVarName", ol)
elif sel == self._const['mb.editable']:
currObj.params.set("Editable",not currObj.params.get("Editable",True))
elif sel == self._const['mb.hideScroll']:
currObj.params.set("HideScroll",not currObj.params.get("HideScroll",False))
elif sel == self._const['mb.center']:
currObj.params.set("Center",not currObj.params.get("Center",False))
elif sel == self._const['lbl.color']:
ol = TkDialogs.askText("Change Label's color", "Change color for widget id: " + str(
currid) + "\n",
currObj.params.get("Color"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
currObj.params.set("Color", ol)
elif sel == self._const["uni.lvar"]:
ol = TkDialogs.askText("Change lVar", "Change lVar for widget id: " + str(
currid) + "\n",
currObj.params.get("lVar"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
currObj.params.set("lVar", ol)
else:
if sel == self._const['wnd.topmost']:
dlb.params.set("TopMost", not dlb.params.get("TopMost"))
elif sel == self._const['wnd.center']:
dlb.params.set("CenterWindow", not dlb.params.get("CenterWindow"))
elif sel == self._const['wnd.bg']:
ol = TkDialogs.askText("Change Wnd's bg", "Change pic src for wnd " + "\nfile path",
dlb.params.get("Background"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
dlb.params.set("Background", ol)
elif sel == self._const["wnd.bm_bool"]:
dlb.params.set("Bassmod_Enabled", not dlb.params.get("Bassmod_Enabled"))
elif sel == self._const['wnd.bm_file']:
ol = TkDialogs.askText("Change Wnd's bassmod file", "Support xm,mod,it etc." + "\nfile path",
dlb.params.get("Bassmod_File"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
dlb.params.set("Bassmod_File", ol)
elif sel == self._const['wnd.bgcolor']:
ol = TkDialogs.askText("Change Wnd's bg color", "format: r,g,b" + "\n",
dlb.params.get("BackgroundColor"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
dlb.params.set("BackgroundColor", ol)
elif sel == self._const['wnd.rm_mini']:
dlb.params.set("RemoveMinimize", not dlb.params.get("RemoveMinimize"))
elif sel == self._const['wnd.tcolor']:
ol = TkDialogs.askText("Change Wnd's default text color", "format: r,g,b" + "\n",
dlb.params.get("DefaultTextColor"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
dlb.params.set("DefaultTextColor", ol)
elif sel == self._const['wnd.title']:
ol = TkDialogs.askText("Change Wnd's title", "" + "\n",
dlb.params.get("Title"))
if ol is None: return
print("got:", ol, "for", currid, ", change it.")
dlb.params.set("Title", ol)
def isInArea(self,vec):
return isPointInArea(vec,self.csr,self.w,self.h)
csr=(x-rpnl_wth,0)
rpnl=RightPanel(csr)
#Clk list
clklist={
#order by num, top elm must at the beginning.
"Normal":[
btm_list,
rpnl,
sysmenu
],
"Always":[
dlb,
]
}
#drw list
drwlist=[