-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWidgets.py
2337 lines (2145 loc) · 106 KB
/
Widgets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This is a GUI toolkit for SDL that I made mainly for my own use, but feel free to use it in your project if you want.
|
How to use:
First, construct a 'Frame' class instance. Then, initialize each widget you want to use, and add the class object to the
frame via the 'Frame.add_widget' method. Note that radio buttons are a bit special, as you have to first create a
'RadioGroup' instance, then create radio buttons for the group with the 'RadioGroup.create_radio_button' method. After
that, you can pass the 'RadioGroup' object to the 'Frame.add_widget' method like a normal widget.
Every game tick, make sure to pass user events to the frame by calling the 'Frame.update' method and passing a
'Mouse.Cursor' object and a list of 'pygame.event.Event' objects as parameters. You should initialize a 'Mouse.Cursor'
object at the beginning of your code, and continuously call its 'mouse_enter', 'mouse_leave', 'reset_scroll',
'push_scroll', 'set_button_state', 'set_pos', and 'reset_z_index' methods at the correct times in the game-loop. The
list should contain all keyboard-related events that has appeared since the last time 'Frame.update' was called. This
can easily be achieved by declaring an empty list, then looping through the event queue every frame and appending
keyboard-related events to the end of the list, then clearing the list after passing it to the 'Frame.update' method.
After that, you can "blit" the frame to the display surface using the frame's 'image' and 'rect'
attributes.
As widgets solely rely on the data you pass to it to handle user events, make sure to correctly update the data you're
passing to the 'Frame.update' method to ensure widgets respond to hovers, clicks, scroll events, key-presses, and window
events correctly.
'UI_Demo.py' is a UI that demonstrates how to use this module. It was created for testing purposes during
development, but I'm sure it'll also help you on getting started.
|
Notes:
1. This module also needs 'Global.py', 'Mouse.py', and 'Time.py' to work. Include them in your project if you want to
use this module.
2. Since this module needs access to window events, Pygame version >= 2.0.1 is required.
3. Apart from the 'Pygame' module, this file also requires the 'Pyperclip' module to be installed in order to access the
clipboard. Make sure to install it with 'pip install pyperclip' if you don't already have it.
"""
from Global import *
import math
import Mouse
import Time
import os
import pygame
import pyperclip
os.environ["SDL_IME_SHOW_UI"] = "1" # Enable showing the IME candidate list.
class BaseWidget(pygame.sprite.Sprite):
def __init__(self, widget_name: str = "!base_widget"):
"""Base class for all widgets."""
super().__init__()
self.widget_name = widget_name
self.parent = None
def update(self, mouse_obj: Mouse.Cursor, keyboard_events: List[pygame.event.Event]) -> None:
pass
def get_widget_name(self) -> str:
return self.widget_name
def set_parent(self, parent_widget) -> None:
self.parent = parent_widget
def has_parent(self) -> bool:
return self.parent is not None
class AnimatedSurface(BaseWidget):
def __init__(self,
x: Union[int, float],
y: Union[int, float],
surface: pygame.Surface,
callback: Optional[Callable[[], None]],
widen_amount: int = 60,
widget_name: str = "!animated_surf"):
"""Animates a static surface image to dilate on mouse-hover and shrink on mouse-leave. When clicked, the surface
flashes and calls the callback function given at initialization."""
super().__init__(widget_name)
# region Sprite Data
self.real_x = x # The x and y position without resize offset.
self.real_y = y
self.x = self.real_x
self.y = self.real_y
self.original_surface = surface
self.original_width, self.original_height = self.original_surface.get_size()
self.image = self.original_surface.copy()
self.current_width = self.original_width
self.current_height = self.original_height
self.max_width = self.original_width + widen_amount
self.min_width = self.original_width
self.aspect_ratio = self.original_height / self.original_width
# endregion
# region Flash Animation Data
self.brightness = 1
self.max_brightness = 100
self.brighten_step = 330
self.flash_state = "idle" # Literal["idle", "brighten", "darken"]
self.flash_timer = Time.Time()
# endregion
# region Resize Animation Data
self.difference = self.max_width - self.min_width
self.reducing_fraction = 0.2
self.resize_state = "small" # Literal["small", "large", "dilating", "shrinking"]
self.delta_timer = Time.Time()
self.delta_timer.reset_timer()
# endregion
self.lock = True
self.mouse_down = False
self.callback_func = callback # Stores the reference to the function to call when clicked.
self.rect = pygame.Rect(self.x, self.y, self.original_width, self.original_height)
self.mask = pygame.mask.from_surface(self.image)
def update(self, mouse_obj: Mouse.Cursor, keyboard_events: List[pygame.event.Event]) -> None:
# region Tick Size
collide = pygame.sprite.collide_mask(self, mouse_obj)
if collide is None:
if not mouse_obj.get_button_state(1):
# Cancel click if mouse is released after being dragged off the button.
self.mouse_down = False
self.lock = True
self.change_size("decrease")
else:
if mouse_obj.get_button_state(1) and (not self.lock):
self.mouse_down = True
elif (not mouse_obj.get_button_state(1)) and self.mouse_down:
self.mouse_down = False
if self.callback_func is not None:
self.flash_timer.reset_timer()
self.flash_state = "brighten" # Start flash animation.
self.callback_func() # Fire button-click event.
if not mouse_obj.get_button_state(1):
self.lock = False
self.change_size("increase")
# endregion
# region Tick Brightness
delta_time = self.flash_timer.get_time()
self.flash_timer.reset_timer()
if self.flash_state != "idle":
if self.flash_state == "brighten":
self.brightness += self.brighten_step * delta_time
if self.brightness >= self.max_brightness:
self.brightness = self.max_brightness
self.flash_state = "darken"
elif self.flash_state == "darken":
self.brightness -= self.brighten_step * delta_time
if self.brightness <= 1:
self.brightness = 1
self.flash_state = "idle"
# Obtain the button surface that is at the correct size, but not brightened.
if self.resize_state == "small":
# Copy from original surface if resizing is not needed.
self.image = self.original_surface.copy()
elif self.resize_state == "large":
# Scale original surface to max size.
self.image = pygame.transform.scale(self.original_surface,
(self.max_width, self.max_width * self.aspect_ratio))
# If button is currently changing size, the surface will already be the un-brightened version.
self.image.fill((self.brightness,) * 3, special_flags=pygame.BLEND_RGB_ADD)
# endregion
def set_size(self, new_size: float) -> None:
self.current_width = round(new_size)
self.current_height = round(self.current_width * self.aspect_ratio)
offset_x = round((self.original_width - self.current_width) / 2)
offset_y = round((self.original_height - self.current_height) / 2)
self.x = self.real_x + offset_x
self.y = self.real_y + offset_y
self.image = pygame.transform.scale(self.original_surface, (self.current_width, self.current_height))
self.rect = pygame.Rect(self.x, self.y, self.current_width, self.current_height)
self.mask = pygame.mask.from_surface(self.image)
def calc_physics(self, delta_time: float, direction: Literal["increase", "decrease"]) -> float:
self.difference *= math.pow(self.reducing_fraction, delta_time)
if self.resize_state == "dilating" and direction == "decrease" or \
self.resize_state == "shrinking" and direction == "increase":
self.difference = self.max_width - self.min_width - self.difference
self.resize_state = "shrinking" if self.resize_state == "dilating" else "dilating"
new_width = None
if direction == "increase":
new_width = self.max_width - self.difference
elif direction == "decrease":
new_width = self.min_width + self.difference
if round(new_width) == self.min_width and direction == "decrease":
self.resize_state = "small"
self.difference = self.max_width - self.min_width
elif round(new_width) == self.max_width and direction == "increase":
self.resize_state = "large"
self.difference = self.max_width - self.min_width
return new_width
def change_size(self, direction: Literal["increase", "decrease"]) -> None:
if (self.resize_state, direction) in (("small", "decrease"), ("large", "increase")):
self.delta_timer.reset_timer()
return None
if self.resize_state == "small":
self.resize_state = "dilating"
elif self.resize_state == "large":
self.resize_state = "shrinking"
self.set_size(self.calc_physics(self.delta_timer.get_time(), direction))
self.delta_timer.reset_timer()
@staticmethod
def calc_size(y_pos: int, og_width: int, og_height: int, widen_amount: int = 60) -> Tuple[float, float]:
"""Returns the top and bottom y coordinates of the button when it is at its max size."""
aspect_ratio = og_height / og_width
max_width = og_width + widen_amount
min_height = og_width * aspect_ratio
max_height = max_width * aspect_ratio
min_top_y = y_pos - (max_height - min_height) / 2
max_bottom_y = min_top_y + max_height
return min_top_y, max_bottom_y
class Button(AnimatedSurface):
def __init__(self,
x: Union[int, float],
y: Union[int, float],
width: int,
height: int,
border: int,
fg: Tuple[int, int, int],
bg: Tuple[int, int, int],
font: pygame.font.Font,
text: str,
callback: Optional[Callable[[], None]],
widen_amount: int = 60,
widget_name: str = "!button"):
"""Similar to AnimatedSurface, except it accepts a font object and a string in order to create the surface
dynamically. The shape of the button is a two-cornered rounded rect."""
button_surf = pygame.Surface((width, height), flags=pygame.SRCALPHA)
button_surf.fill((0, 0, 0, 0))
draw_button(button_surf, 0, 0, width, height, border, fg, bg, font, text)
super().__init__(x, y, button_surf, callback, widen_amount, widget_name)
class Label(BaseWidget):
def __init__(self,
x: Union[int, float],
y: Union[int, float],
text: Union[str, List[str]],
fg: Tuple[int, int, int],
width: int,
font: pygame.font.Font,
align: Literal["left", "center", "right"] = "center",
no_wrap: bool = False,
widget_name: str = "!label"):
"""Accepts text to be displayed, width in pixels, and a font object. The text will be word-wrapped to guarantee
that it fits the requested width."""
super().__init__(widget_name)
self.x = x
self.y = y
self.text_lines = text if no_wrap else word_wrap_text(text, width, font)
self.line_height = font.size("█")[1]
self.rect = pygame.Rect(self.x, self.y, width, self.line_height * len(self.text_lines))
self.image = pygame.Surface((self.rect.width, self.rect.height), flags=pygame.SRCALPHA)
self.image.fill((0, 0, 0, 0))
for index, line in enumerate(self.text_lines):
size = font.size(line)
surface = font.render(line, True, fg)
if align == "left":
x = 0
elif align == "center":
x = width / 2 - size[0] / 2
else:
x = width - size[0]
self.image.blit(surface, (x, index * self.line_height))
def update_position(self, x: Union[int, float], y: Union[int, float]) -> None:
self.x = x
self.y = y
self.rect = pygame.Rect(self.x, self.y, self.rect.width, self.rect.height)
def get_size(self) -> Tuple[int, int]:
return self.rect.size
class SplitLabel(BaseWidget):
def __init__(self, x: Union[int, float], y: Union[int, float], lines: Tuple[str, str], wrap_widths: Tuple[int, int],
font: pygame.font.Font, fg: Tuple[int, int, int], bg: Tuple[int, int, int], radius: int, padding: int,
widget_name: str = "!split_label"):
"""Appears as a rounded rect with a line of word-wrapped text on either side horizontally. Great for displaying
tables with two columns."""
super().__init__(widget_name)
self.x = x
self.y = y
self.width = 2 * radius + sum(wrap_widths) + padding
self.wrapped_lines: List[Label] = []
self.wrapped_lines.append(Label(radius, radius, lines[0], fg, wrap_widths[0], font, align="left"))
label = Label(0, radius, lines[1], fg, wrap_widths[1], font, align="right")
label.update_position(self.width - radius - label.get_size()[0], radius)
self.wrapped_lines.append(label)
self.height = 2 * radius + max(line.get_size()[1] for line in self.wrapped_lines)
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
self.image = pygame.Surface((self.width, self.height), flags=pygame.SRCALPHA)
self.image.fill((0, 0, 0, 0))
draw_rounded_rect(self.image, (0, 0), (self.width, self.height), radius, bg)
for line in self.wrapped_lines:
self.image.blit(line.image, line.rect)
class ParagraphRect(BaseWidget):
def __init__(self, x: Union[int, float], y: Union[int, float], width: int, radius: int, padding: int,
fg: Tuple[int, int, int], bg: Tuple[int, int, int], heading: str, body: str,
heading_font: pygame.font.Font, body_font: pygame.font.Font, widget_name: str = "!p_rect"):
"""Displays a heading and a word-wrapped paragraph in a rounded rect."""
super().__init__(widget_name)
self.x = x
self.y = y
self.width = width
heading_label = Label(padding, padding, heading, fg, self.width - 2 * padding, heading_font,
align="left")
body_label = Label(padding, heading_label.rect.bottom + padding, body, fg, self.width - 2 * padding,
body_font, align="left")
self.height = body_label.rect.bottom + padding
self.image = pygame.Surface((self.width, self.height), flags=pygame.SRCALPHA)
self.image.fill((0, 0, 0, 0))
draw_rounded_rect(self.image, (0, 0), (self.width, self.height), radius, bg)
self.image.blit(heading_label.image, heading_label.rect)
self.image.blit(body_label.image, body_label.rect)
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
def get_size(self) -> Tuple[int, int]:
return self.width, self.height
class Checkbox(BaseWidget):
def __init__(self,
x: Union[int, float],
y: Union[int, float],
label_text: str,
button_length: int,
border_radius: int,
text_color: Tuple[int, int, int],
bg: Tuple[int, int, int],
width: int,
font: pygame.font.Font,
padding: int,
border: int,
widget_name: str = "!checkbox"):
"""A simple checkbox with rounded corners both on the button and the surrounding rect. The caption text will be
word-wrapped to fit the requested width."""
super().__init__(widget_name)
self.x = x
self.y = y
self.button_length = button_length
self.button_radius = border_radius
self.text_lines = word_wrap_text(label_text, width - padding * 3 - self.button_length, font)
self.line_height = font.size("█")[1]
self.checked = False
self.image = pygame.Surface((width,
padding * 2 + self.line_height * len(self.text_lines)), flags=pygame.SRCALPHA)
self.image.fill((0, 0, 0, 0))
draw_rounded_rect(self.image, (0, 0), self.image.get_size(), self.button_radius, bg)
for index, text in enumerate(self.text_lines):
surface = font.render(text, True, text_color)
self.image.blit(surface, (padding * 2 + self.button_length, padding + self.line_height * index))
self.rect = pygame.Rect(self.x, self.y, *self.image.get_size())
self.__button = Box(padding, padding, self.button_length, self.button_radius, border)
def update(self, mouse_obj: Mouse.Cursor, keyboard_events: List[pygame.event.Event]) -> None:
abs_pos = mouse_obj.get_pos()
rel_mouse = mouse_obj.copy()
rel_mouse.set_pos(abs_pos[0] - self.x, abs_pos[1] - self.y)
self.__button.update(rel_mouse)
self.image.blit(self.__button.image, self.__button.rect)
def get_data(self) -> bool:
return self.__button.get_data()
def get_size(self) -> Tuple[int, int]:
return self.image.get_size()
class Box(pygame.sprite.Sprite):
def __init__(self,
x: Union[int, float],
y: Union[int, float],
length: int,
radius: int,
border: int):
super().__init__()
self.x = x
self.y = y
self.length = length
self.radius = radius
self.border = border
self.lock = True
self.mouse_down = False
self.checked = False
self.image = pygame.Surface((length, length))
self.image.set_colorkey(TRANSPARENT)
self.normal_color = GREY3
self.active_color = CYAN
self.current_color = self.normal_color
self.render_surface()
self.rect = pygame.Rect(self.x, self.y, length, length)
self.mask = pygame.mask.from_surface(self.image)
def render_surface(self) -> None:
self.image.fill(TRANSPARENT)
draw_rounded_rect(self.image, (0, 0), (self.length, self.length), self.radius, BLACK)
draw_rounded_rect(self.image,
(self.border, self.border),
(self.length - self.border * 2, self.length - self.border * 2),
self.radius - self.border,
self.current_color)
if self.checked:
pygame.draw.lines(self.image, BLACK, False, ((5, self.length / 2 + 3),
(self.length / 2 - 5, self.length - 5),
(self.length - 5, 5)), 3)
def update(self, mouse_obj: Mouse.Cursor) -> None:
collide = pygame.sprite.collide_mask(self, mouse_obj)
if collide is None:
if not mouse_obj.get_button_state(1):
self.mouse_down = False
self.lock = True
self.current_color = self.normal_color
else:
if mouse_obj.get_button_state(1) and (not self.lock):
self.mouse_down = True
elif (not mouse_obj.get_button_state(1)) and self.mouse_down:
self.mouse_down = False
self.checked = not self.checked
if not mouse_obj.get_button_state(1):
self.lock = False
self.current_color = self.active_color
self.render_surface() # Mask and rect updates are not needed, since the shape of the surface stays the same.
def get_data(self) -> bool:
return self.checked
class RadioGroup:
def __init__(self, default: int = 0):
"""Used for managing a group of radio buttons. Create all needed radio buttons with the 'create_radio_button'
method, then add this class instance to a frame when done."""
super().__init__()
self.default = default
self.counter_id = 0
self.selected_id = default
self.children = []
def create_radio_button(self,
x: Union[int, float],
y: Union[int, float],
label_text: str,
button_length: int,
border_radius: int,
selected_radius: int,
text_color: Tuple[int, int, int],
bg: Tuple[int, int, int],
width: int,
font: pygame.font.Font,
padding: int,
border: int,
widget_name: str = "!radio_button") -> None:
radio_button = RadioButton(self.counter_id, self.update_selection, self.counter_id == self.default, x, y,
label_text, button_length, border_radius, selected_radius, text_color, bg, width,
font, padding, border, widget_name)
self.children.append(radio_button)
self.counter_id += 1
def update_selection(self, new_id: int) -> None:
self.selected_id = new_id
for index, radio_button in enumerate(self.children):
if index != self.selected_id:
radio_button.unselect()
def get_children(self) -> list:
return self.children
def get_button_num(self) -> int:
return len(self.children)
def get_selected(self) -> int:
return self.selected_id
class RadioButton(Checkbox):
def __init__(self,
radio_id: int,
callback: Callable[[int], None],
selected: bool,
x: Union[int, float],
y: Union[int, float],
label_text: str,
button_length: int,
border_radius: int,
selected_radius: int,
text_color: Tuple[int, int, int],
bg: Tuple[int, int, int],
width: int,
font: pygame.font.Font,
padding: int,
border: int,
widget_name: str = "!radio_button"):
"""A simple radio button widget. When a radio button is selected, all other radio-buttons in the same group will
be unselected. The radio button which is selected by default is determined by the 'default' parameter passed to
the RadioGroup class."""
super().__init__(x, y, label_text, button_length, border_radius, text_color, bg, width, font, padding, border,
widget_name)
self.id = radio_id
self.button_radius = round(button_length / 2)
self.__button = Circle(padding, padding, self.button_radius, border, selected_radius, radio_id, callback,
selected)
def update(self, mouse_obj: Mouse.Cursor, keyboard_events: List[pygame.event.Event]) -> None:
abs_pos = mouse_obj.get_pos()
rel_mouse = mouse_obj.copy()
rel_mouse.set_pos(abs_pos[0] - self.x, abs_pos[1] - self.y)
self.__button.update(rel_mouse)
self.image.blit(self.__button.image, self.__button.rect)
def unselect(self) -> None:
self.__button.unselect()
def get_size(self) -> Tuple[int, int]:
return self.image.get_size()
class Circle(pygame.sprite.Sprite):
def __init__(self,
x: Union[int, float],
y: Union[int, float],
radius: int,
border: int,
selected_radius: int,
radio_id: int,
on_click: Callable[[int], None],
selected: bool = False):
super().__init__()
self.id = radio_id
self.x = x
self.y = y
self.radius = radius
self.border = border
self.selected_radius = selected_radius
self.callback = on_click
self.normal_color = GREY3
self.active_color = CYAN
self.current_color = self.normal_color
self.selected = selected
self.lock = True
self.mouse_down = False
self.image = pygame.Surface((radius * 2, radius * 2))
self.image.set_colorkey(TRANSPARENT)
self.image.fill(TRANSPARENT)
pygame.draw.circle(self.image, BLACK, (radius, radius), radius, 0)
pygame.draw.circle(self.image, self.current_color, (radius, radius), radius - border, 0)
self.rect = pygame.Rect(self.x, self.y, radius, radius)
self.mask = pygame.mask.from_surface(self.image)
def update(self, mouse_obj: Mouse.Cursor) -> None:
collide = pygame.sprite.collide_mask(self, mouse_obj)
if collide is None:
if not mouse_obj.get_button_state(1):
self.mouse_down = False
self.lock = True
self.current_color = self.normal_color
else:
if mouse_obj.get_button_state(1) and (not self.lock):
self.mouse_down = True
elif (not mouse_obj.get_button_state(1)) and self.mouse_down:
self.mouse_down = False
self.selected = True
self.callback(self.id)
if not mouse_obj.get_button_state(1):
self.lock = False
self.current_color = self.active_color
pygame.draw.circle(self.image, self.current_color, (self.radius, self.radius), self.radius - self.border, 0)
if self.selected:
pygame.draw.circle(self.image, BLACK, (self.radius, self.radius), self.selected_radius, 0)
def unselect(self) -> None:
self.selected = False
class Entry(BaseWidget):
def __init__(self,
x: Union[int, float],
y: Union[int, float],
width: int,
height: int,
padding: int,
font: pygame.font.Font,
fg: Tuple[int, int, int],
widget_name: str = "!entry"):
"""A simple text-box widget. Behaves virtually identical to the text-box widget of win32gui. Its copy-pasting
functionality relies on the 'Pyperclip' module, so make sure to have it installed. Note that the environment
variable 'SDL_IME_SHOW_UI' must be set to 1 for this widget to function correctly. This is done automatically
when the module is imported."""
super().__init__(widget_name)
self.x = x
self.y = y
self.original_width = width
self.height = height
self.padding = padding
self.font = font
self.fg = fg
self.border_thickness = 2
self.text_input = False
self.shift = False
self.selecting = False
self.start_select = True
self.normal_border = BLACK
self.active_border = BLUE
self.current_border = self.normal_border
self.block_select = False
self.drag_pos = None
self.drag_pos_recorded = False
self.dnd_start_x = -1
self.dnd_distance = 0
self.dnd_x_recorded = False
self.real_x = 0
self.real_y = 0
self.lock = True
self.mouse_down = False
self.text_canvas = EntryText(width - padding * 2, height - padding * 2, self.font, fg)
self.ime_canvas = None
self.caret_restore_pos = -1
# (start sticky keys, start timer, has reset repeat, repeat timer)
self.sticky_keys = {pygame.K_LEFT: [False,
Time.Time(),
False,
Time.Time(),
lambda: self.text_canvas.change_caret_pos("l")],
pygame.K_RIGHT: [False,
Time.Time(),
False,
Time.Time(),
lambda: self.text_canvas.change_caret_pos("r")],
pygame.K_BACKSPACE: [False,
Time.Time(),
False,
Time.Time(),
self.text_canvas.backspace],
pygame.K_DELETE: [False,
Time.Time(),
False,
Time.Time(),
self.text_canvas.delete]}
self.start_delay = 0.5
self.repeat_delay = 0.1
self.scroll_hit_box = 30
self.image = pygame.Surface((self.original_width, self.height))
self.rect = pygame.Rect(self.x, self.y, self.original_width, self.height)
def render_text_canvas(self) -> None:
self.image.fill((0, 0, 0, 0))
pygame.draw.rect(self.image, self.current_border, [0, 0, self.original_width, self.height], 0)
pygame.draw.rect(self.image,
WHITE,
[self.border_thickness,
self.border_thickness,
self.original_width - self.border_thickness * 2,
self.height - self.border_thickness * 2],
0)
self.image.blit(source=self.text_canvas.get_surface(),
dest=(self.padding, self.padding),
area=self.text_canvas.get_view_rect())
def update_real_pos(self, real_pos: Tuple[Union[int, float], Union[int, float]]) -> None:
self.real_x, self.real_y = real_pos
def update(self, mouse_obj: Mouse.Cursor, keyboard_events: List[pygame.event.Event]) -> Tuple[bool, bool, bool]:
collide = pygame.sprite.collide_rect(self, mouse_obj)
if collide:
if mouse_obj.get_button_state(1):
if (not self.lock) and (self.ime_canvas is None):
self.mouse_down = True
self.text_input = True
self.text_canvas.focus_get()
self.parent.raise_widget_layer(self.widget_name)
else:
self.mouse_down = False
self.lock = False
self.current_border = self.active_border
if (not self.text_canvas.dnd_event_ongoing()) and self.block_select:
self.block_select = False
else:
if mouse_obj.get_button_state(1):
self.mouse_down = True
if self.lock:
self.stop_focus()
else:
self.mouse_down = False
self.lock = True
self.current_border = self.normal_border
if (not self.text_canvas.dnd_event_ongoing()) and self.block_select:
self.block_select = False
abs_pos = mouse_obj.get_pos()
rel_mouse = mouse_obj.copy()
rel_mouse.set_pos(abs_pos[0] - (self.x + self.padding), abs_pos[1] - (self.y + self.padding))
for event in keyboard_events:
if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
if event.mod & pygame.KMOD_SHIFT:
self.shift = True
else:
if self.shift:
self.shift = False
if not self.start_select:
self.text_canvas.end_selection()
self.start_select = True
elif self.text_canvas.selection_event_ongoing():
# Special case for handling a text selection event that was initiated by a HOME or END
# key-press.
self.text_canvas.end_selection()
if event.type == pygame.WINDOWFOCUSLOST:
self.stop_focus()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_TAB:
self.text_canvas.add_text("\t".expandtabs(tabsize=4))
elif event.key in (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_BACKSPACE, pygame.K_DELETE):
if not self.sticky_keys[event.key][0]:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
if self.shift and self.start_select and \
(not self.text_canvas.selection_event_ongoing()):
# The last one in the boolean expression is to make sure a selection event won't be
# triggered again if it has already been initiated by a HOME or END key-press.
self.text_canvas.start_selection()
self.start_select = False
self.sticky_keys[event.key][4]()
self.sticky_keys[event.key][0] = True
self.sticky_keys[event.key][1].reset_timer()
elif event.key == pygame.K_HOME:
self.text_canvas.caret_home(self.shift)
elif event.key == pygame.K_END:
self.text_canvas.caret_end(self.shift)
elif event.key == pygame.K_RETURN:
if self.ime_canvas is not None:
self.stop_ime_input()
elif event.mod & pygame.KMOD_CTRL:
if event.key == pygame.K_c:
self.text_canvas.copy_text()
elif event.key == pygame.K_v:
self.paste_text()
elif event.key == pygame.K_a:
self.text_canvas.select_all()
elif event.key == pygame.K_x:
if self.text_canvas.copy_text():
self.text_canvas.backspace()
elif event.key == pygame.K_z:
if self.shift:
self.text_canvas.redo()
else:
self.text_canvas.undo()
elif event.key == pygame.K_y:
self.text_canvas.redo()
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT, pygame.K_BACKSPACE, pygame.K_DELETE):
self.sticky_keys[event.key][0] = False
self.sticky_keys[event.key][2] = False
elif event.type == pygame.TEXTINPUT:
self.text_canvas.add_text(event.text)
elif event.type == pygame.TEXTEDITING:
if self.ime_canvas is None and self.text_canvas.has_focus() and event.text:
self.caret_restore_pos = self.text_canvas.get_caret_index()
self.text_canvas.focus_lose(False)
self.ime_canvas = EntryText(self.original_width - self.padding * 2,
self.height - self.padding * 2,
self.font,
self.fg)
self.ime_canvas.focus_get()
if self.ime_canvas is not None:
self.ime_canvas.ime_update_text(event.text, event.start)
width_diff = (self.padding
+ self.text_canvas.get_x()
+ self.text_canvas.calc_location_width()
- self.text_canvas.get_caret_width()
+ self.ime_canvas.calc_text_size(self.ime_canvas.get_text())[0]
+ self.ime_canvas.get_caret_width()) - self.original_width
if width_diff > 0:
# (self.original_width + width_diff, self.height)
self.image = pygame.Surface((self.original_width + width_diff, self.height),
flags=pygame.SRCALPHA)
else:
self.image = pygame.Surface((self.original_width, self.height))
text_rect = pygame.Rect(self.real_x + self.padding + self.text_canvas.get_x()
+ self.text_canvas.calc_location_width()
- self.text_canvas.get_caret_width() + self.ime_canvas.calc_ime_x_pos(),
self.real_y + self.height - self.padding,
0,
0)
# It is unclear what effect the size of the rect has on the IME candidate list.
pygame.key.set_text_input_rect(self.parent.calc_resized_ime_rect(text_rect))
if not self.ime_canvas.get_text():
self.stop_ime_input()
for key in self.sticky_keys.values():
if key[0]:
if key[1].get_time() > self.start_delay and (not key[2]):
key[2] = True
key[3].reset_timer()
if key[2]:
delta_time = key[3].get_time()
if delta_time > self.repeat_delay:
compensation = delta_time - self.repeat_delay
key[4]()
if compensation > self.repeat_delay:
for i in range(math.floor(compensation / self.repeat_delay)):
key[4]()
compensation %= self.repeat_delay
key[3].force_elapsed_time(compensation)
if mouse_obj.get_button_state(1):
if self.drag_pos_recorded and self.text_canvas.mouse_collision(self.drag_pos):
if mouse_obj.get_pos()[0] < self.x + self.scroll_hit_box:
self.text_canvas.move_view_by_pos("r")
elif mouse_obj.get_pos()[0] > self.x + (self.original_width - self.scroll_hit_box):
self.text_canvas.move_view_by_pos("l")
if self.text_canvas.mouse_collision(rel_mouse):
if not self.drag_pos_recorded:
self.drag_pos_recorded = True
self.drag_pos = rel_mouse.copy()
self.text_canvas.update_caret_pos(rel_mouse.get_pos())
if not self.dnd_x_recorded:
self.dnd_x_recorded = True
self.dnd_start_x = rel_mouse.get_pos()[0]
if self.text_canvas.text_block_selected() and (not self.text_canvas.dnd_event_ongoing()):
if abs(rel_mouse.get_pos()[0] - self.dnd_start_x) > self.dnd_distance:
self.text_canvas.start_dnd_event(rel_mouse)
if not self.block_select:
self.block_select = True
if (not self.selecting) and \
(not self.text_canvas.dnd_event_ongoing()) and \
(not self.text_canvas.selection_rect_collide(rel_mouse.get_pos())):
self.text_canvas.start_selection()
self.selecting = True
else:
if self.text_canvas.mouse_collision(rel_mouse):
if self.dnd_start_x != -1 and self.text_canvas.text_block_selected():
if self.text_canvas.selection_rect_collide(rel_mouse.get_pos()):
if abs(rel_mouse.get_pos()[0] - self.dnd_start_x) <= self.dnd_distance:
# Unselect text
self.text_canvas.cancel_dnd_event()
self.text_canvas.start_selection()
self.text_canvas.end_selection()
if self.text_canvas.dnd_event_ongoing():
self.text_canvas.end_dnd_event()
if self.selecting:
self.selecting = False
if not mouse_obj.has_left():
self.text_canvas.update_caret_pos(rel_mouse.get_pos())
self.text_canvas.end_selection()
self.drag_pos_recorded = False
self.drag_pos = None
self.dnd_x_recorded = False
self.dnd_start_x = -1
self.text_canvas.update(False)
self.render_text_canvas()
if self.ime_canvas is not None:
self.ime_canvas.update(True)
self.image.blit(self.ime_canvas.get_surface(),
(self.padding
+ self.text_canvas.get_x()
+ self.text_canvas.calc_location_width()
- self.text_canvas.get_caret_width(),
self.padding))
return collide, self.block_select, self.text_input
def stop_focus(self) -> None:
if self.ime_canvas is not None:
# The IME text will be deleted.
self.stop_ime_input()
self.text_canvas.focus_lose()
self.text_input = False
def stop_ime_input(self):
self.image = pygame.Surface((self.original_width, self.height))
self.ime_canvas = None
self.text_canvas.focus_get()
self.text_canvas.set_caret_index(self.caret_restore_pos)
self.caret_restore_pos = -1
def paste_text(self) -> None:
try:
text = pyperclip.paste()
except pyperclip.PyperclipException:
return None
if text:
# The paste will be ignored if the Entry does not have keyboard focus.
self.text_canvas.add_text("".join(c for c in text if c.isprintable()))
def set_auto_typed_text(self, text: str) -> None:
"""Does the equivalent of clicking the entry, typing the text given, then pressing Ctrl+A."""
self.text_input = True
self.text_canvas.focus_get()
self.parent.raise_widget_layer(self.widget_name)
self.text_canvas.add_text(text)
self.text_canvas.select_all()
def get_pos(self) -> Tuple[int, int]:
return self.x, self.y
def get_entry_content(self) -> str:
return self.text_canvas.get_text()
class EntryText:
def __init__(self, width: int, height: int, font: pygame.font.Font, text_color: Tuple[int, int, int]):
self.font = font
self.text_color = text_color
self.scroll_padding = 5
self.x = 0
self.y = 0
self.view_width = width
self.view_height = height
self.caret_width = 2
self.caret_height = height - 4
self.caret_surf = pygame.Surface((self.caret_width, self.caret_height))
self.caret_surf.fill(BLACK)
self.caret_timer = Time.Time()
self.caret_delay = 0.5
self.scroll_amount = 70
self.scroll_time = 0
self.scroll_timer = Time.Time()
self.scroll_timer.reset_timer()
self.display_caret = True
self.focus = False
self.surface = pygame.Surface((self.caret_width, self.view_height))
self.surface.fill(WHITE)
self.text = ""
self.undo_history = [""]
self.redo_history = []
self.caret_index = 0
self.select_start = -1
self.select_end = -1
self.selecting = False
self.select_rect = None
self.dnd_event = False
def record_undo(self) -> None:
self.undo_history.append(self.text)
def undo(self) -> None:
if len(self.undo_history) and self.focus:
temp = self.text
while len(self.undo_history) and temp == self.text:
temp = self.undo_history.pop()
self.redo_history.append(temp)
self.text = temp
if self.caret_index > len(self.text):
self.caret_index = len(self.text)
current_width = self.calc_location_width()
if current_width < self.view_width:
self.x = 0
elif self.x + current_width < self.view_width:
self.move_view_by_caret("l")
def redo(self) -> None:
if len(self.redo_history) and self.focus:
temp = self.text
while len(self.redo_history) and temp == self.text:
temp = self.redo_history.pop()
self.undo_history.append(temp)
self.text = temp
if self.caret_index > len(self.text):
self.caret_index = len(self.text)
current_width = self.calc_location_width()
if current_width < self.view_width:
self.x = 0
elif self.x + current_width < self.view_width:
self.move_view_by_caret("l")
def text_block_selected(self) -> bool:
# Returns True if a block of text has already been selected, and the selection event has ENDED.
return self.select_start != -1 and self.select_end != -1 and (not self.selecting)
def selection_event_ongoing(self) -> bool:
# Returns True if a selection event is *currently* ongoing.
# (e.g. the shift key is still held down, or the left mouse button is still held down)
return self.selecting
def selection_rect_collide(self, position: Tuple[int, int]) -> bool:
if (self.select_rect is not None) and (self.select_start != -1 and self.select_end != -1):
rect = pygame.Rect(self.select_rect.x + self.x, self.select_rect.y, *self.select_rect.size)
return rect.collidepoint(*position)
else:
return False
def start_dnd_event(self, mouse_obj: Mouse.Cursor) -> None:
if not self.dnd_event:
if self.selection_rect_collide(mouse_obj.get_pos()) and \
(self.select_start != -1 and self.select_end != -1) and \
(not self.selecting):
self.dnd_event = True
def end_dnd_event(self) -> None:
if self.dnd_event and (self.select_start != -1 and self.select_end != -1) and (not self.selecting):
self.dnd_event = False
if self.select_start <= self.caret_index <= self.select_end:
self.select_start = -1
self.select_end = -1
self.select_rect = None
return None
selection = self.text[self.select_start:self.select_end]
before_sel = self.text[:self.select_start]
after_sel = self.text[self.select_end:]
self.text = before_sel + after_sel
if self.caret_index > self.select_end:
temp_caret_idx = self.caret_index - len(selection)