Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1279 lines (1043 loc) · 50.3 KB
/
Copy pathmain.py
File metadata and controls
1279 lines (1043 loc) · 50.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pygame
import sys
import json
import os
import sqlite3
from datetime import datetime
import importlib.util
# ==========================================
# 0. 数据库与用户鉴权 (SQLite)
# ==========================================
DB_PATH = "system.db"
def init_db():
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
role TEXT NOT NULL -- 'admin' 或 'user'
)
''')
cursor.execute("INSERT OR IGNORE INTO users (username, password, role) VALUES ('admin', '123456', 'admin')")
cursor.execute("INSERT OR IGNORE INTO users (username, password, role) VALUES ('user', '123456', 'user')")
conn.commit()
conn.close()
def verify_login(username, password):
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("SELECT role FROM users WHERE username=? AND password=?", (username, password))
result = cursor.fetchone()
conn.close()
return result[0] if result else None
init_db()
# ==========================================
# 1. 全局配置与状态定义
# ==========================================
SYSTEM_CONFIG = {
"bg_color": (0, 128, 128)
}
STATE_BOOT = "BOOT"
STATE_LOGIN = "LOGIN"
STATE_DESKTOP = "DESKTOP"
current_state = STATE_BOOT
current_user = None
current_role = None
pygame.init()
WIDTH, HEIGHT = 900, 700
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame Retro Desktop System")
def set_system_resolution(new_w, new_h):
global WIDTH, HEIGHT, screen, taskbar
WIDTH, HEIGHT = new_w, new_h
screen = pygame.display.set_mode((WIDTH, HEIGHT))
taskbar.rect.y = HEIGHT - TASKBAR_HEIGHT
taskbar.start_btn_rect.y = HEIGHT - TASKBAR_HEIGHT + 2
for win in wm.windows:
win.rect.x = min(win.rect.x, WIDTH - win.rect.w)
win.rect.y = min(win.rect.y, HEIGHT - TASKBAR_HEIGHT - win.rect.h)
def lerp(start, end, factor=0.25):
return start + (end - start) * factor
def get_chinese_font(size=14):
font_paths = [
"/System/Library/Fonts/PingFang.ttc",
"/System/Library/Fonts/Hiragino Sans GB.ttc",
"C:/Windows/Fonts/simsun.ttc",
"C:/Windows/Fonts/msyh.ttc"
]
for path in font_paths:
if os.path.exists(path):
return pygame.font.Font(path, size)
return pygame.font.SysFont("arial", size)
font = get_chinese_font(14)
font_small = get_chinese_font(12)
font_large = get_chinese_font(26)
COLOR_BG = (0, 128, 128)
COLOR_WIN_BG = (192, 192, 192)
COLOR_TITLE_ACTIVE = (0, 0, 128)
COLOR_TITLE_INACTIVE = (128, 128, 128)
COLOR_WHITE = (255, 255, 255)
COLOR_DARK = (128, 128, 128)
COLOR_BLACK = (0, 0, 0)
COLOR_HOVER = (0, 0, 128)
COLOR_PROGRESS = (0, 0, 128)
COLOR_SELECTION = (0, 120, 215, 100)
TASKBAR_HEIGHT = 30
TOOLBAR_HEIGHT = 20 # 工具栏默认高度
# 默认兼容菜单栏配置
DEFAULT_MENU_BAR = [
{
"label": "文件",
"submenu": [
{"label": "新建", "action": "menu_file_new"},
{"label": "打开", "action": "menu_file_open"},
{"label": "保存", "action": "menu_file_save"},
{"label": "退出", "action": "menu_file_exit"}
]
},
{
"label": "编辑",
"submenu": [
{"label": "撤销", "action": "menu_edit_undo"},
{"label": "剪切", "action": "menu_edit_cut"},
{"label": "复制", "action": "menu_edit_copy"},
{"label": "粘贴", "action": "menu_edit_paste"}
]
},
{
"label": "帮助",
"submenu": [
{"label": "查看帮助", "action": "menu_help_view"},
{"label": "关于", "action": "menu_help_about"}
]
}
]
# ==========================================
# 2. 桌面鼠标框选组件
# ==========================================
class SelectionBox:
def __init__(self):
self.active = False
self.start_pos = (0, 0)
self.current_pos = (0, 0)
def start(self, pos):
self.active = True
self.start_pos = pos
self.current_pos = pos
def update(self, pos):
if self.active:
self.current_pos = pos
def stop(self):
self.active = False
def draw(self, surface):
if not self.active:
return
x = min(self.start_pos[0], self.current_pos[0])
y = min(self.start_pos[1], self.current_pos[1])
w = abs(self.start_pos[0] - self.current_pos[0])
h = abs(self.start_pos[1] - self.current_pos[1])
if w > 0 and h > 0:
select_surf = pygame.Surface((w, h), pygame.SRCALPHA)
select_surf.fill(COLOR_SELECTION)
surface.blit(select_surf, (x, y))
pygame.draw.rect(surface, (0, 120, 215), (x, y, w, h), 1)
# ==========================================
# 3. 多级上下文右键与开始菜单
# ==========================================
class Menu:
ITEM_HEIGHT = 24
MENU_WIDTH = 130
def __init__(self, items, x, y, is_root=True, upward=False):
self.items = items
self.is_root = is_root
self.upward = upward
self.active_sub_index = None
self.sub_menu = None
self.target_h = len(items) * self.ITEM_HEIGHT + 4
self.current_h = 0.0
calc_y = y - self.target_h if upward else y
calc_x = min(x, WIDTH - self.MENU_WIDTH)
calc_y = max(0, min(calc_y, HEIGHT - self.target_h))
self.rect = pygame.Rect(calc_x, calc_y, self.MENU_WIDTH, self.target_h)
def draw(self, surface):
self.current_h = lerp(self.current_h, self.target_h, 0.3)
if self.upward:
anim_y = self.rect.bottom - self.current_h
anim_rect = pygame.Rect(self.rect.x, anim_y, self.MENU_WIDTH, self.current_h)
else:
anim_rect = pygame.Rect(self.rect.x, self.rect.y, self.MENU_WIDTH, self.current_h)
old_clip = surface.get_clip()
surface.set_clip(anim_rect.clip(old_clip))
pygame.draw.rect(surface, COLOR_WIN_BG, anim_rect)
pygame.draw.line(surface, COLOR_WHITE, anim_rect.topleft, anim_rect.topright)
pygame.draw.line(surface, COLOR_WHITE, anim_rect.topleft, anim_rect.bottomleft)
pygame.draw.line(surface, COLOR_BLACK, anim_rect.bottomleft, anim_rect.bottomright)
pygame.draw.line(surface, COLOR_BLACK, anim_rect.topright, anim_rect.bottomright)
mx, my = pygame.mouse.get_pos()
for i, item in enumerate(self.items):
item_rect = pygame.Rect(self.rect.x + 2, self.rect.y + 2 + i * self.ITEM_HEIGHT, self.rect.w - 4,
self.ITEM_HEIGHT)
if item_rect.collidepoint(mx, my):
if self.active_sub_index != i:
self.active_sub_index = i
if "submenu" in item and item["submenu"]:
sub_x = self.rect.right
if sub_x + self.MENU_WIDTH > WIDTH:
sub_x = self.rect.x - self.MENU_WIDTH
sub_y = item_rect.y
self.sub_menu = Menu(item["submenu"], sub_x, sub_y, is_root=False, upward=False)
else:
self.sub_menu = None
is_hovered = item_rect.collidepoint(mx, my) or (self.active_sub_index == i)
if is_hovered:
pygame.draw.rect(surface, COLOR_HOVER, item_rect)
txt = font.render(item["label"], True, COLOR_WHITE)
else:
txt = font.render(item["label"], True, COLOR_BLACK)
surface.blit(txt, (item_rect.x + 8, item_rect.y + 4))
if "submenu" in item and item["submenu"]:
arrow_color = COLOR_WHITE if is_hovered else COLOR_BLACK
arrow_txt = font_small.render("▶", True, arrow_color)
surface.blit(arrow_txt, (item_rect.right - 14, item_rect.y + 5))
surface.set_clip(old_clip)
if self.sub_menu:
self.sub_menu.draw(surface)
def handle_event(self, event, action_handler, on_close):
if self.sub_menu and self.sub_menu.handle_event(event, action_handler, on_close):
return True
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mx, my = event.pos
for i, item in enumerate(self.items):
item_rect = pygame.Rect(self.rect.x + 2, self.rect.y + 2 + i * self.ITEM_HEIGHT, self.rect.w - 4,
self.ITEM_HEIGHT)
if item_rect.collidepoint(mx, my):
if "submenu" in item and item["submenu"]:
return True
action = item.get("action")
if action and action_handler:
action_handler(action)
on_close()
return True
if not self.rect.collidepoint(mx, my) and self.is_root:
on_close()
return False
# ==========================================
# 4. 完整通用 UI 控件库
# ==========================================
class UIElement:
def __init__(self, x=0, y=0, w=0, h=0, align="left"):
self.rel_x = x
self.rel_y = y
self.base_w = w
self.rect = pygame.Rect(x, y, w, h)
self.id = ""
self.align = align
def update_layout(self, container_w, container_h):
if self.align == "right":
self.rect.x = container_w - self.rel_x - self.rect.w
elif self.align == "fill":
self.rect.x = self.rel_x
self.rect.w = max(20, container_w - self.rel_x * 2)
else:
self.rect.x = self.rel_x
self.rect.y = self.rel_y
def draw(self, surface, abs_x, abs_y):
pass
def handle_event(self, event, abs_x, abs_y):
return False
class Label(UIElement):
def __init__(self, text, x, y, align="left"):
super().__init__(x, y, 0, 0, align)
self.text = text
def draw(self, surface, abs_x, abs_y):
txt = font.render(self.text, True, COLOR_BLACK)
surface.blit(txt, (abs_x + self.rect.x, abs_y + self.rect.y))
class Button(UIElement):
def __init__(self, text, x, y, w=80, h=25, callback=None, align="left"):
super().__init__(x, y, w, h, align)
self.text = text
self.callback = callback
self.is_pressed = False
def draw(self, surface, abs_x, abs_y):
r = pygame.Rect(abs_x + self.rect.x, abs_y + self.rect.y, self.rect.w, self.rect.h)
pygame.draw.rect(surface, COLOR_WIN_BG, r)
if self.is_pressed:
pygame.draw.rect(surface, COLOR_DARK, r, 1)
else:
pygame.draw.line(surface, COLOR_WHITE, r.topleft, r.topright)
pygame.draw.line(surface, COLOR_WHITE, r.topleft, r.bottomleft)
pygame.draw.line(surface, COLOR_BLACK, r.bottomleft, r.bottomright)
pygame.draw.line(surface, COLOR_BLACK, r.topright, r.bottomright)
txt = font.render(self.text, True, COLOR_BLACK)
txt_rect = txt.get_rect(center=r.center)
surface.blit(txt, txt_rect)
def handle_event(self, event, abs_x, abs_y):
r = pygame.Rect(abs_x + self.rect.x, abs_y + self.rect.y, self.rect.w, self.rect.h)
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and r.collidepoint(event.pos):
self.is_pressed = True
return True
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
if self.is_pressed:
self.is_pressed = False
if r.collidepoint(event.pos) and self.callback:
self.callback()
return True
return False
class CheckBox(UIElement):
def __init__(self, text, x, y, checked=False, align="left"):
super().__init__(x, y, 140, 18, align)
self.text = text
self.checked = checked
def draw(self, surface, abs_x, abs_y):
rx, ry = abs_x + self.rect.x, abs_y + self.rect.y
box_r = pygame.Rect(rx, ry + 2, 14, 14)
pygame.draw.rect(surface, COLOR_WHITE, box_r)
pygame.draw.line(surface, COLOR_DARK, box_r.topleft, box_r.topright)
pygame.draw.line(surface, COLOR_DARK, box_r.topleft, box_r.bottomleft)
pygame.draw.line(surface, COLOR_BLACK, box_r.topright, box_r.bottomright)
if self.checked:
txt_v = font_small.render("✓", True, COLOR_BLACK)
surface.blit(txt_v, (box_r.x + 2, box_r.y - 1))
txt = font.render(self.text, True, COLOR_BLACK)
surface.blit(txt, (rx + 20, ry))
def handle_event(self, event, abs_x, abs_y):
r = pygame.Rect(abs_x + self.rect.x, abs_y + self.rect.y, self.rect.w, self.rect.h)
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and r.collidepoint(event.pos):
self.checked = not self.checked
return True
return False
class RadioGroup(UIElement):
def __init__(self, options, x, y, selected_index=0, align="left"):
super().__init__(x, y, 120, len(options) * 22, align)
self.options = options
self.selected_index = selected_index
def draw(self, surface, abs_x, abs_y):
rx, ry = abs_x + self.rect.x, abs_y + self.rect.y
for i, opt in enumerate(self.options):
cy = ry + i * 22 + 8
pygame.draw.circle(surface, COLOR_WHITE, (rx + 8, cy), 6)
pygame.draw.circle(surface, COLOR_DARK, (rx + 8, cy), 6, 1)
if i == self.selected_index:
pygame.draw.circle(surface, COLOR_BLACK, (rx + 8, cy), 3)
txt = font.render(opt, True, COLOR_BLACK)
surface.blit(txt, (rx + 20, cy - 7))
def handle_event(self, event, abs_x, abs_y):
rx, ry = abs_x + self.rect.x, abs_y + self.rect.y
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for i in range(len(self.options)):
r = pygame.Rect(rx, ry + i * 22, self.rect.w, 20)
if r.collidepoint(event.pos):
self.selected_index = i
return True
return False
class TextBox(UIElement):
def __init__(self, text, x, y, w=150, h=22, is_password=False, align="left"):
super().__init__(x, y, w, h, align)
self.text = text
self.is_focused = False
self.is_password = is_password
def draw(self, surface, abs_x, abs_y):
r = pygame.Rect(abs_x + self.rect.x, abs_y + self.rect.y, self.rect.w, self.rect.h)
pygame.draw.rect(surface, COLOR_WHITE, r)
pygame.draw.line(surface, COLOR_DARK, r.topleft, r.topright)
pygame.draw.line(surface, COLOR_DARK, r.topleft, r.bottomleft)
disp_txt = "*" * len(self.text) if self.is_password else self.text
txt = font.render(disp_txt + ("|" if self.is_focused else ""), True, COLOR_BLACK)
surface.blit(txt, (r.x + 5, r.y + 3))
def handle_event(self, event, abs_x, abs_y):
r = pygame.Rect(abs_x + self.rect.x, abs_y + self.rect.y, self.rect.w, self.rect.h)
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self.is_focused = r.collidepoint(event.pos)
return self.is_focused
if self.is_focused and event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
self.text = self.text[:-1]
elif len(event.unicode) > 0 and event.unicode.isprintable():
self.text += event.unicode
return True
return False
class ProgressBar(UIElement):
def __init__(self, x, y, w=200, h=20, progress=0.0, align="left"):
super().__init__(x, y, w, h, align)
self.progress = progress
def draw(self, surface, abs_x, abs_y):
r = pygame.Rect(abs_x + self.rect.x, abs_y + self.rect.y, self.rect.w, self.rect.h)
pygame.draw.rect(surface, COLOR_WIN_BG, r)
pygame.draw.rect(surface, COLOR_DARK, r, 1)
fill_w = int((self.rect.w - 4) * min(1.0, max(0.0, self.progress)))
if fill_w > 0:
pygame.draw.rect(surface, COLOR_PROGRESS, (r.x + 2, r.y + 2, fill_w, self.rect.h - 4))
class ComboBox(UIElement):
def __init__(self, options, x, y, w=120, h=22, align="left"):
super().__init__(x, y, w, h, align)
self.options = options
self.selected_index = 0
self.is_open = False
def draw(self, surface, abs_x, abs_y):
r = pygame.Rect(abs_x + self.rect.x, abs_y + self.rect.y, self.rect.w, self.rect.h)
pygame.draw.rect(surface, COLOR_WHITE, r)
pygame.draw.rect(surface, COLOR_BLACK, r, 1)
txt = font.render(self.options[self.selected_index], True, COLOR_BLACK)
surface.blit(txt, (r.x + 5, r.y + 3))
btn_r = pygame.Rect(r.right - 18, r.y + 2, 16, r.h - 4)
pygame.draw.rect(surface, COLOR_WIN_BG, btn_r)
pygame.draw.rect(surface, COLOR_DARK, btn_r, 1)
pygame.draw.polygon(surface, COLOR_BLACK,
[(btn_r.x + 4, btn_r.y + 6), (btn_r.x + 12, btn_r.y + 6), (btn_r.x + 8, btn_r.y + 11)])
def draw_overlay(self, surface, abs_x, abs_y):
if not self.is_open: return
rx, ry = abs_x + self.rect.x, abs_y + self.rect.y
for i, opt in enumerate(self.options):
item_r = pygame.Rect(rx, ry + self.rect.h + i * self.rect.h, self.rect.w, self.rect.h)
pygame.draw.rect(surface, COLOR_HOVER if i == self.selected_index else COLOR_WIN_BG, item_r)
pygame.draw.rect(surface, COLOR_DARK, item_r, 1)
txt = font.render(opt, True, COLOR_WHITE if i == self.selected_index else COLOR_BLACK)
surface.blit(txt, (item_r.x + 5, item_r.y + 3))
def handle_event(self, event, abs_x, abs_y):
rx, ry = abs_x + self.rect.x, abs_y + self.rect.y
r = pygame.Rect(rx, ry, self.rect.w, self.rect.h)
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if r.collidepoint(event.pos):
self.is_open = not self.is_open
return True
elif self.is_open:
for i in range(len(self.options)):
item_r = pygame.Rect(rx, ry + self.rect.h + i * self.rect.h, self.rect.w, self.rect.h)
if item_r.collidepoint(event.pos):
self.selected_index = i
self.is_open = False
return True
self.is_open = False
return False
# ==========================================
# 5. 系统弹窗组件 (MessageBox)
# ==========================================
class MessageBox:
@staticmethod
def show_info(wm, title, message):
MessageBox._dialog(wm, title, f"ℹ️ {message}", ["确定"])
@staticmethod
def show_warning(wm, title, message):
MessageBox._dialog(wm, title, f"⚠️ {message}", ["确定"])
@staticmethod
def show_error(wm, title, message):
MessageBox._dialog(wm, title, f"❌ {message}", ["确定"])
@staticmethod
def show_yes_no(wm, title, message, on_yes=None):
def cb_yes():
if on_yes: on_yes()
MessageBox._dialog(wm, title, message, ["是", "否"], [cb_yes, None])
@staticmethod
def show_input(wm, title, prompt, on_submit=None):
win = Window(title, WIDTH // 2 - 110, HEIGHT // 2 - 60, 220, 130)
win.add_child(Label(prompt, 15, 10))
tb = TextBox("", 15, 35, 190, 24, align="fill")
win.add_child(tb)
def submit():
if on_submit: on_submit(tb.text)
win.is_closed = True
win.add_child(Button("确定", 30, 70, 70, 25, callback=submit))
win.add_child(Button("取消", 120, 70, 70, 25, callback=lambda: setattr(win, 'is_closed', True)))
wm.add_window(win)
@staticmethod
def _dialog(wm, title, msg, btns, cbs=None):
win = Window(title, WIDTH // 2 - 120, HEIGHT // 2 - 50, 240, 100)
win.add_child(Label(msg, 20, 15))
for i, b_text in enumerate(btns):
cb_func = cbs[i] if cbs and i < len(cbs) else None
def click_handler(f=cb_func):
if f: f()
win.is_closed = True
btn_x = 40 + i * 90 if len(btns) > 1 else 85
win.add_child(Button(b_text, btn_x, 50, 65, 25, callback=click_handler))
wm.add_window(win)
# ==========================================
# 6. 窗口容器 & 窗口管理器(平滑动画)
# ==========================================
class Window:
MIN_WIDTH = 150
MIN_HEIGHT = 100
def __init__(self, title, x, y, w, h, context_menu_data=None, menu_bar_data=None):
self.title = title
self.rect = pygame.Rect(x, y, w, h)
self.display_rect = pygame.Rect(x, y, w, h).copy()
self.is_closed = False
self.is_minimized = False
self.is_maximized = False
self.normal_rect = pygame.Rect(x, y, w, h)
self.children = []
self.context_menu_data = context_menu_data or []
# 工具栏数据 (如未提供,自动降级为默认菜单)
self.menu_bar_data = menu_bar_data if menu_bar_data is not None else DEFAULT_MENU_BAR
self.active_menu = None
self.is_dragging = False
self.drag_offset = (0, 0)
self.is_resizing = False
self.resize_start_size = (w, h)
self.resize_start_pos = (0, 0)
def add_child(self, child: UIElement):
self.children.append(child)
self.update_children_layout()
def update_children_layout(self):
# 内部元素根据坐标偏移自适应 (顶栏 22 + 工具栏 TOOLBAR_HEIGHT)
top_offset = 22 + (TOOLBAR_HEIGHT if self.menu_bar_data else 0)
for child in self.children:
child.update_layout(self.rect.w, self.rect.h - top_offset)
@property
def title_bar_rect(self):
return pygame.Rect(self.rect.x, self.rect.y, self.rect.width, 22)
@property
def tool_bar_rect(self):
return pygame.Rect(self.rect.x, self.rect.y + 22, self.rect.width, TOOLBAR_HEIGHT)
@property
def close_btn_rect(self):
return pygame.Rect(self.rect.right - 18, self.rect.y + 3, 15, 15)
@property
def max_btn_rect(self):
return pygame.Rect(self.rect.right - 36, self.rect.y + 3, 15, 15)
@property
def min_btn_rect(self):
return pygame.Rect(self.rect.right - 54, self.rect.y + 3, 15, 15)
@property
def resize_grip_rect(self):
return pygame.Rect(self.rect.right - 8, self.rect.bottom - 8, 8, 8)
def update_anim(self):
if self.is_dragging or self.is_resizing:
self.display_rect = pygame.Rect(self.rect)
return
factor = 0.25
if self.is_minimized:
target_x = self.rect.x
target_y = HEIGHT - TASKBAR_HEIGHT
target_w = self.rect.w
target_h = 0
else:
target_x, target_y = self.rect.x, self.rect.y
target_w, target_h = self.rect.w, self.rect.h
self.display_rect.x = lerp(self.display_rect.x, target_x, factor)
self.display_rect.y = lerp(self.display_rect.y, target_y, factor)
self.display_rect.w = lerp(self.display_rect.w, target_w, factor)
self.display_rect.h = lerp(self.display_rect.h, target_h, factor)
def toggle_maximize(self):
if self.is_maximized:
self.rect = pygame.Rect(self.normal_rect)
self.is_maximized = False
else:
self.normal_rect = pygame.Rect(self.rect)
self.rect = pygame.Rect(0, 0, WIDTH, HEIGHT - TASKBAR_HEIGHT)
self.is_maximized = True
self.update_children_layout()
def draw(self, surface, is_active):
if self.is_closed: return
self.update_anim()
if self.display_rect.h < 5: return
x, y, w, h = self.display_rect.x, self.display_rect.y, self.display_rect.w, self.display_rect.h
win_rect = pygame.Rect(x, y, w, h)
pygame.draw.rect(surface, COLOR_WIN_BG, win_rect)
pygame.draw.line(surface, COLOR_WHITE, (x, y), (x + w - 1, y))
pygame.draw.line(surface, COLOR_WHITE, (x, y), (x, y + h - 1))
pygame.draw.line(surface, COLOR_BLACK, (x, y + h - 1), (x + w - 1, y + h - 1))
pygame.draw.line(surface, COLOR_BLACK, (x + w - 1, y), (x + w - 1, y + h - 1))
# 渲染标题栏
tb_h = min(22, h)
title_bar_rect = pygame.Rect(x, y, w, tb_h)
t_color = COLOR_TITLE_ACTIVE if is_active else COLOR_TITLE_INACTIVE
pygame.draw.rect(surface, t_color, title_bar_rect)
if h > 15:
title_txt = font.render(self.title, True, COLOR_WHITE)
surface.blit(title_txt, (x + 5, y + 3))
cb = pygame.Rect(x + w - 18, y + 3, 15, 15)
mb = pygame.Rect(x + w - 36, y + 3, 15, 15)
nb = pygame.Rect(x + w - 54, y + 3, 15, 15)
pygame.draw.rect(surface, COLOR_WIN_BG, cb)
pygame.draw.rect(surface, COLOR_BLACK, cb, 1)
surface.blit(font_small.render("✕", True, COLOR_BLACK), (cb.x + 3, cb.y + 1))
pygame.draw.rect(surface, COLOR_WIN_BG, mb)
pygame.draw.rect(surface, COLOR_BLACK, mb, 1)
max_icon = "❐" if self.is_maximized else "□"
surface.blit(font_small.render(max_icon, True, COLOR_BLACK), (mb.x + 3, mb.y + 1))
pygame.draw.rect(surface, COLOR_WIN_BG, nb)
pygame.draw.rect(surface, COLOR_BLACK, nb, 1)
surface.blit(font_small.render("_", True, COLOR_BLACK), (nb.x + 4, nb.y - 1))
content_start_y = y + 22
# 渲染顶部工具栏 (如果存在)
if self.menu_bar_data and h > 35:
tbar_rect = pygame.Rect(x + 2, y + 22, w - 4, TOOLBAR_HEIGHT)
pygame.draw.rect(surface, COLOR_WIN_BG, tbar_rect)
pygame.draw.line(surface, COLOR_DARK, (x + 2, y + 22 + TOOLBAR_HEIGHT),
(x + w - 2, y + 22 + TOOLBAR_HEIGHT))
menu_x = x + 6
for item in self.menu_bar_data:
txt = font.render(item["label"], True, COLOR_BLACK)
tw = txt.get_width() + 12
item_rect = pygame.Rect(menu_x, y + 23, tw, TOOLBAR_HEIGHT - 2)
mx, my = pygame.mouse.get_pos()
if item_rect.collidepoint(mx, my):
pygame.draw.rect(surface, COLOR_HOVER, item_rect)
txt = font.render(item["label"], True, COLOR_WHITE)
surface.blit(txt, (menu_x + 6, y + 25))
menu_x += tw
content_start_y += TOOLBAR_HEIGHT
# 渲染窗口内容
if h > (content_start_y - y):
content_rect = pygame.Rect(x + 2, content_start_y, max(0, w - 4), max(0, h - (content_start_y - y) - 2))
old_clip = surface.get_clip()
surface.set_clip(content_rect.clip(old_clip))
for child in self.children:
child.draw(surface, x, content_start_y)
surface.set_clip(old_clip)
for child in self.children:
if hasattr(child, 'draw_overlay'):
child.draw_overlay(surface, x, content_start_y)
if not self.is_maximized:
rg = pygame.Rect(x + w - 8, y + h - 8, 8, 8)
pygame.draw.line(surface, COLOR_DARK, (rg.x + 6, rg.y + 1), (rg.x + 1, rg.y + 6))
pygame.draw.line(surface, COLOR_WHITE, (rg.x + 7, rg.y + 2), (rg.x + 2, rg.y + 7))
# 渲染激活的下拉菜单(顶层覆盖)
if self.active_menu:
self.active_menu.draw(surface)
def close_active_menu(self):
self.active_menu = None
def handle_event(self, event, is_top_window):
if self.is_closed or self.is_minimized: return False
# 优先响应弹出式工具栏菜单
if self.active_menu:
if self.active_menu.handle_event(event, handle_menu_action, self.close_active_menu):
return True
content_y = self.rect.y + 22 + (TOOLBAR_HEIGHT if self.menu_bar_data else 0)
if is_top_window:
for child in reversed(self.children):
if child.handle_event(event, self.rect.x, content_y):
return True
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
mx, my = event.pos
if self.close_btn_rect.collidepoint(event.pos):
self.is_closed = True
return True
if self.max_btn_rect.collidepoint(event.pos):
self.toggle_maximize()
return True
if self.min_btn_rect.collidepoint(event.pos):
self.is_minimized = True
return True
# 点击工具栏触发下拉多级菜单
if self.menu_bar_data and self.tool_bar_rect.collidepoint(mx, my):
menu_x = self.rect.x + 6
for item in self.menu_bar_data:
tw = font.render(item["label"], True, COLOR_BLACK).get_width() + 12
item_rect = pygame.Rect(menu_x, self.rect.y + 23, tw, TOOLBAR_HEIGHT - 2)
if item_rect.collidepoint(mx, my):
if "submenu" in item:
self.active_menu = Menu(item["submenu"], item_rect.x, item_rect.bottom)
return True
menu_x += tw
if not self.is_maximized and self.resize_grip_rect.collidepoint(event.pos):
self.is_resizing = True
self.resize_start_size = (self.rect.w, self.rect.h)
self.resize_start_pos = event.pos
return True
if self.title_bar_rect.collidepoint(event.pos):
if not self.is_maximized:
self.is_dragging = True
self.drag_offset = (self.rect.x - event.pos[0], self.rect.y - event.pos[1])
return True
if self.rect.collidepoint(event.pos):
return True
elif event.type == pygame.MOUSEBUTTONUP:
self.is_dragging = False
self.is_resizing = False
elif event.type == pygame.MOUSEMOTION:
if self.is_dragging:
self.rect.x = event.pos[0] + self.drag_offset[0]
self.rect.y = event.pos[1] + self.drag_offset[1]
return True
elif self.is_resizing:
dx = event.pos[0] - self.resize_start_pos[0]
dy = event.pos[1] - self.resize_start_pos[1]
self.rect.w = max(self.MIN_WIDTH, self.resize_start_size[0] + dx)
self.rect.h = max(self.MIN_HEIGHT, self.resize_start_size[1] + dy)
self.update_children_layout()
return True
return False
# ==========================================
# 7. 任务栏(显示自适应 Tab 及当前登录账号角色)
# ==========================================
class Taskbar:
def __init__(self, screen_w, screen_h, start_menu_data):
self.rect = pygame.Rect(0, screen_h - TASKBAR_HEIGHT, screen_w, TASKBAR_HEIGHT)
self.start_btn_rect = pygame.Rect(2, screen_h - TASKBAR_HEIGHT + 2, 60, TASKBAR_HEIGHT - 4)
self.start_menu_data = start_menu_data
self.start_menu = None
self.app_buttons = []
def draw(self, surface, windows, active_window, user_name, user_role):
pygame.draw.rect(surface, COLOR_WIN_BG, self.rect)
pygame.draw.line(surface, COLOR_WHITE, self.rect.topleft, self.rect.topright)
is_open = self.start_menu is not None
pygame.draw.rect(surface, COLOR_WIN_BG, self.start_btn_rect)
if is_open:
pygame.draw.rect(surface, COLOR_DARK, self.start_btn_rect, 1)
else:
pygame.draw.line(surface, COLOR_WHITE, self.start_btn_rect.topleft, self.start_btn_rect.topright)
pygame.draw.line(surface, COLOR_WHITE, self.start_btn_rect.topleft, self.start_btn_rect.bottomleft)
pygame.draw.line(surface, COLOR_BLACK, self.start_btn_rect.bottomleft, self.start_btn_rect.bottomright)
pygame.draw.line(surface, COLOR_BLACK, self.start_btn_rect.topright, self.start_btn_rect.bottomright)
start_txt = font.render("开始", True, COLOR_BLACK)
surface.blit(start_txt, (self.start_btn_rect.x + 16, self.start_btn_rect.y + 5))
self.app_buttons.clear()
start_x = self.start_btn_rect.right + 10
btn_h = TASKBAR_HEIGHT - 6
open_windows = [w for w in windows if not w.is_closed]
count = len(open_windows)
role_str = "管理员" if user_role == "admin" else "普通用户"
user_info = font_small.render(f"[{role_str}] {user_name}", True, COLOR_BLACK)
surface.blit(user_info, (start_x, self.rect.y + 8))
start_x += user_info.get_width() + 15
if count > 0:
time_box_left = WIDTH - 75
available_w = time_box_left - start_x - 10
gap = 4
max_btn_w, min_btn_w = 110, 30
calc_w = (available_w - (count - 1) * gap) // count
btn_w = max(min_btn_w, min(max_btn_w, calc_w))
for win in open_windows:
btn_rect = pygame.Rect(start_x, self.rect.y + 3, btn_w, btn_h)
self.app_buttons.append((btn_rect, win))
is_active = (win == active_window) and (not win.is_minimized)
pygame.draw.rect(surface, COLOR_WIN_BG, btn_rect)
if is_active:
pygame.draw.rect(surface, COLOR_DARK, btn_rect, 1)
else:
pygame.draw.line(surface, COLOR_WHITE, btn_rect.topleft, btn_rect.topright)
pygame.draw.line(surface, COLOR_WHITE, btn_rect.topleft, btn_rect.bottomleft)
pygame.draw.line(surface, COLOR_BLACK, btn_rect.bottomleft, btn_rect.bottomright)
pygame.draw.line(surface, COLOR_BLACK, btn_rect.topright, btn_rect.bottomright)
max_chars = max(1, (btn_w - 12) // 10)
title_str = win.title[:max(1, max_chars - 1)] + ".." if len(win.title) > max_chars else win.title
if btn_w >= 35:
txt_color = COLOR_BLACK if not is_active else COLOR_HOVER
txt = font_small.render(title_str, True, txt_color)
surface.blit(txt, (btn_rect.x + 6, btn_rect.y + 5))
start_x += btn_w + gap
now_str = datetime.now().strftime("%H:%M:%S")
time_txt = font.render(now_str, True, COLOR_BLACK)
time_box = pygame.Rect(WIDTH - 75, self.rect.y + 4, 70, TASKBAR_HEIGHT - 8)
pygame.draw.rect(surface, COLOR_WIN_BG, time_box)
pygame.draw.line(surface, COLOR_DARK, time_box.topleft, time_box.topright)
pygame.draw.line(surface, COLOR_DARK, time_box.topleft, time_box.bottomleft)
pygame.draw.line(surface, COLOR_WHITE, time_box.bottomleft, time_box.bottomright)
surface.blit(time_txt, (time_box.x + 8, time_box.y + 4))
if self.start_menu:
self.start_menu.draw(surface)
def handle_event(self, event, action_handler, wm):
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if self.start_btn_rect.collidepoint(event.pos):
if self.start_menu:
self.start_menu = None
else:
self.start_menu = Menu(self.start_menu_data, x=2, y=self.rect.top, upward=True)
return True
for btn_rect, win in self.app_buttons:
if btn_rect.collidepoint(event.pos):
if win.is_minimized:
win.is_minimized = False
wm.bring_to_front(win)
else:
if wm.get_top_window() == win:
win.is_minimized = True
else:
wm.bring_to_front(win)
return True
if self.start_menu and self.start_menu.handle_event(event, action_handler, self.close_menu):
return True
if event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP) and self.rect.collidepoint(event.pos):
return True
return False
def close_menu(self):
self.start_menu = None
# ==========================================
# 8. 应用与 JSON 依赖构建器
# ==========================================
def load_app_from_folder(app_folder_name, wm_ref, x_offset=0, y_offset=0):
app_dir = os.path.join("apps", app_folder_name)
ui_path = os.path.join(app_dir, "ui_config.json")
code_path = os.path.join(app_dir, "main.py")
if not os.path.exists(ui_path):
print(f"配置文件缺失: {ui_path}")
return None
with open(ui_path, "r", encoding="utf-8") as f:
win_data = json.load(f)
win = Window(
title=win_data.get("title", app_folder_name),
x=win_data.get("x", 100) + x_offset,
y=win_data.get("y", 100) + y_offset,
w=win_data.get("w", 300),
h=win_data.get("h", 200),
context_menu_data=win_data.get("context_menu", []),
menu_bar_data=win_data.get("menu_bar", DEFAULT_MENU_BAR) # 兼容未提供菜单的应用
)
for child_data in win_data.get("children", []):
c_type = child_data.get("type")
cx, cy = child_data.get("x", 0), child_data.get("y", 0)
cid = child_data.get("id", "")
align = child_data.get("align", "left")
element = None
if c_type == "label":
element = Label(child_data.get("text", ""), cx, cy, align=align)
elif c_type == "button":
element = Button(child_data.get("text", "按钮"), cx, cy, child_data.get("w", 80), child_data.get("h", 25),
align=align)
elif c_type == "checkbox":
element = CheckBox(child_data.get("text", ""), cx, cy, child_data.get("checked", False), align=align)
elif c_type == "radio":
element = RadioGroup(child_data.get("options", []), cx, cy, child_data.get("selected_index", 0),
align=align)
elif c_type == "textbox":
element = TextBox(child_data.get("text", ""), cx, cy, child_data.get("w", 120), child_data.get("h", 22),
align=align)
elif c_type == "progressbar":
element = ProgressBar(cx, cy, child_data.get("w", 150), child_data.get("h", 18),
child_data.get("progress", 0.0), align=align)
elif c_type == "combobox":
element = ComboBox(child_data.get("options", []), cx, cy, child_data.get("w", 120), child_data.get("h", 22),
align=align)
if element:
element.id = cid
win.add_child(element)
if os.path.exists(code_path):
try:
module_name = f"apps.{app_folder_name}.main"
spec = importlib.util.spec_from_file_location(module_name, code_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
if hasattr(mod, "App"):
win.app_instance = mod.App(win, wm_ref)
except Exception as e:
print(f"加载应用逻辑失败 [{app_folder_name}]: {e}")
wm_ref.add_window(win)
return win