-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui_controls.py
2070 lines (1736 loc) · 73.2 KB
/
ui_controls.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
import os
import types
import weakref
import pygame
from functools import lru_cache
from draw_utils import *
__all__ = ['BaseControl', 'Layout', 'DrawingBoard','MainMenu', 'HorizontalLayout', 'VerticalLayout', 'ColorCell', 'Spacer', 'ToolPanel', 'StatusBar', 'VerticalLine', 'YesNoDialog',
'HorizontalLine', 'SliderCtrl', 'SpriteSheetCtrl', 'SpritePreview', 'Label', 'ButtonCtrl', 'SpriteSheet', 'FileDialog', 'ROI', 'TextEntry']
def save_to_conf(f):
def wrapped(*args, **kwargs):
self = args[0]
value = args[1]
res = f(*args, **kwargs)
if self._conf is not None:
if self._name is not None:
if isinstance(value, pygame.Color):
value = (value.r, value.g, value.b)
setattr(self._conf, "%s_%s" % (self._name, f.__name__), value)
return res
return wrapped
def load_from_conf(f):
def wrapped(*args, **kwargs):
self = args[0]
res = f(*args, **kwargs)
if self._conf is not None and self._name is not None:
res2 = getattr(self._conf, "%s_%s" % (self._name, f.__name__), None)
if res2 is not None:
return res2
return res
return wrapped
def makes_dirty(f):
def wrapped(*args, **kwargs):
res = f(*args, **kwargs)
self = args[0]
self._dirty=True
return res
return wrapped
class Region():
(
ALIGN_LEFT,
ALIGN_CENTER,
*_) = range(2)
def __init__(self, x, y, width, height, *args, **kwargs):
super().__init__(*args, **kwargs)
self._x = x
self._y = y
self._width = width
self._height = height
self._layout = None
self._parent = None
self._layer = 1
def move_infront_of(self, region):
self._layer = region._layer + 1
@property
def right(self):
return self.width + self.x
@right.setter
def right(self, value):
self.x = value - self.width
@property
def top(self):
return self.y
@top.setter
def top(self, value):
self.y = value
@property
def bottom(self):
return self.y + self.height
@property
def y(self):
return self._y
@property
def x(self):
return self._x
@x.setter
def x(self, val):
self._x = val
@y.setter
def y(self, value):
self._y = value
@bottom.setter
def bottom(self, value):
self.y = value-self.width
@property
def height(self):
return self._height
@property
def width(self):
return self._width
@property
def centerx(self):
return self.x + self.width // 2
@property
def centery(self):
return self.y + self.height // 2
def show(self):
self._visible = True
def hide(self):
self._visible = False
@property
def layout(self):
if self._layout is None:
return None
return self._layout()
@layout.setter
def layout(self, layout):
if layout is not None:
self._layout = weakref.ref(layout)
else:
self._layout = None
@property
def parent(self):
if callable(self._parent):
return self._parent()
return None
def _set_parent(self, parent):
if parent is not None:
self._parent = weakref.ref(parent)
else:
self._parent = None
class BaseGrid():
def __init__(self, cols, rows, *args, **kwargs):
super().__init__(*args, **kwargs)
self._rows = rows
self._cols = cols
def grid_index(self, col, row):
if row > (self._rows-1):
raise ValueError('row < self._rows-1')
if col > (self._cols-1):
raise ValueError('col < self._cols-1')
return row + self._rows * col
def index_to_cell(self, idx):
col = idx % self._cols
row = idx // self._cols
return col, row
@property
def rows(self):
return self._rows
@property
def cols(self):
return self._cols
def has_cell(self, col, row):
""" check if row, col is a valid cell
"""
return self._cols < col and self._rows < row
@property
def cell_count(self):
""" get cells count (same as len(self))
"""
return self._cols * self._rows
class BaseControl(Region):
""" Base class for all UI controls
"""
DRAG_MODE_BODY = 999
def __init__(self, x, y, width=8, height=8, color=None, conf=None, *args, **kwargs):
super().__init__(x, y, width, height, *args, **kwargs)
self._app = None
self._conf = conf
self._name = None
self._verbose = True
self._color = COLOR_FOREGROUND if color is None else color
self._visible = True
self._selected = False
self._drop_shadow = True
self._selectable = False
self._dirty = True # sometimes used
self._on_click_cb = None
self._on_doubleclick_cb = None
self._on_drag_move_cb = None
self._on_keypress_cb = None
@property
def selected(self):
return self._selected
@selected.setter
def selected(self, value):
if not isinstance(value, bool):
raise ValueError("selected value must be boolean")
self._selected = value
@property
def drop_shadow(self):
return self._drop_shadow
@drop_shadow.setter
def drop_shadow(self, drop):
self._drop_shadow = bool(drop)
@property
def name(self):
""" a control is assigned a name if it's referenced by an application object
field, i.e. app.control1 else is None
note: helpful for auto-saving control values in a conf file
"""
return self._name
@property
def color(self):
return self._color
@color.setter
def color(self, color):
if isinstance(color, pygame.Color):
color = (color.r, color.g, color.b)
self._color = color
@property
def app(self):
""" reference to application object
"""
return self._app
def on_drag_move(self, f_cb):
self._on_drag_move_cb = types.MethodType(f_cb, self)
on_drag_move = property(fset=on_drag_move)
def on_click(self, f_cb):
""" property to assign on click callback """
self._on_click_cb = types.MethodType(f_cb, self)
on_click = property(fset=on_click)
def on_doubleclick(self, f_cb):
""" property to assign on doubleclick callback """
self._on_doubleclick_cb = types.MethodType(f_cb, self)
on_doubleclick = property(fset=on_doubleclick)
def on_keypress(self, f_cb):
""" property to assign on doubleclick callback """
self._on_keypress_cb = types.MethodType(f_cb, self)
on_keypress = property(fset=on_keypress)
def click_test(self, click_x, click_y):
""" default method to see if a control is clicked """
return self.pick_box(self.x, self.y, self.right, self.bottom, click_x, click_y)
def drag_test(self, click_x, click_y):
""" default method to see if a control is dragged via mouse """
if self.pick_box(self.x, self.y, self.right, self.bottom, click_x, click_y):
res = self.DRAG_MODE_BODY
return res
return None
def drag_move(self, mode, x, y, x_rel, y_rel, app, button):
if self._on_drag_move_cb is not None:
self._on_drag_move_cb(mode, x, y, x_rel, y_rel, app, button)
def key_pressed(self, key, app):
if self._on_keypress_cb is not None:
self._on_keypress_cb( key, app)
def clicked(self, click_x, click_y, button, app):
""" is called if a control is clicked
override it to create your own click handler
"""
if self._on_click_cb is not None:
return self._on_click_cb(click_x, click_y, button, app)
return True
def doubleclicked(self, click_x, click_y, button, app):
if callable(self._on_doubleclick_cb):
return self._on_doubleclick_cb(click_x, click_y, button, app)
return True
@staticmethod
def pick_box(x1, y1, x2, y2, x, y):
""" test if box defined by x1, y1, x2, y2 can be
clicked at x, y (commonly mouse position)
"""
return x>=x1 and y>=y1 and x<=x2 and y<=y2
@staticmethod
def pick_circle(c_x, c_y, radius, x, y):
""" test if circle defined by c_x, c_y, and radius can be
clicked at x, y (commonly mouse position)
"""
return (x-c_x)**2 + (y-c_y)**2 <= radius**2
@staticmethod
def pick_point(px, py, x, y, size=2):
""" test if a vertex define by px, py, and size
can be clicked or dragged at x, y (commonly mouse position)
"""
return abs(x-px)<=size and abs(y-py)<=size
def __repr__(self):
return "<{.__class__.__name__}@{:x}>".format(self, id(self))
def __str__(self):
return "<{0.__class__.__name__}{1}:x={0.x:d},y={0.y:d}>".format(self, "" if self.name is None else "'"+self.name+"'")
class Layout(Region):
def __init__(self, x=None, y=None, spacing=None, *args, **kwargs):
super().__init__(x, y, 0, 0, *args, **kwargs)
self._items = []
self._index = 0
self._spacing = spacing
self._is_sorted = False
@Region.height.setter
def height(self, val):
self._height = val
if self.layout is not None:
self.layout._re_align()
@Region.width.setter
def width(self, val):
self._width = val
if self.layout is not None:
self.layout._re_align()
def add(self, val):
if not isinstance(val, (BaseControl, Layout)):
raise ValueError("You can only store controls and layouts here")
if val in self._items:
raise ValueError("The item is already in the layout")
if val.layout and val.layout is not self:
val.layout.remove(val)
if self.parent is not None:
val._set_parent(self.parent)
if self._y is None:
self._y = val.y
if self._x is None:
self._x = val.x
self._items.append(val)
val.layout = self
self._is_sorted = False
return val
def remove(self, val):
self._items.remove(val)
val.layout = None
return val
@property
def spacing(self):
return self._spacing
@Region.y.setter
def y(self, val):
for item in self._items:
if item.y is not None:
item.y += (val-self._y)
self._y = val
@Region.x.setter
def x(self, val):
for item in self._items:
if item.x is not None:
item.x += (val-self._x)
self._x = val
def _re_align(self):
pass
def __iter__(self):
self._iter = self._make_iter()
return self
def _make_iter(self):
""" iterating over a layout only yields controls
"""
if not self._is_sorted:
self._items = sorted(self._items, key=lambda item: item._layer)
self._is_sorted = True
for item in self._items:
if isinstance(item, BaseControl):
if hasattr(item, "_controls"):
yield item
if item._visible:
for ctrl in item._controls:
yield ctrl
else:
continue
else:
yield item
else:
for val in item:
yield val
def __next__(self):
return next(self._iter)
class SpriteSheet(BaseGrid):
""" generic sprite sheet
"""
_sprite_imgs = {}
def __init__(self, image_fn, sprite_size, cols=None, rows=None, colorkey=None, scale=None, sprite_info_fn=None, darker=None):
self._image_basename = os.path.basename(image_fn)
self._image_fn = image_fn
if not self._image_fn in self.__class__._sprite_imgs:
print("Loading:", image_fn)
img = pygame.image.load( image_fn )
img = img.convert()
self.__class__._sprite_imgs[self._image_fn] = img
else:
img = self.__class__._sprite_imgs[self._image_fn]
self._darker = darker
self._sprite_info_fn = sprite_info_fn
if cols is None:
im_size_w, im_size_h = img.get_size()
cols = im_size_w//sprite_size[0]
rows = im_size_h // sprite_size[1]
super().__init__(cols, rows)
self._colorkey = colorkey
self._image = img
self._sprites = []
self._sprite_size = sprite_size
self._scale = scale
self._rebuild_sprites()
@property
def image(self):
return self._image
def _rebuild_sprites(self):
if self._colorkey is None:
self._image.set_colorkey(self._image.get_at((0,0)))
sprite_w, sprite_h = self._sprite_size
if self._darker is not None:
darken = pygame.Surface(self._image.get_size()).convert()
darken.fill((self._darker, self._darker, self._darker))
self._image = self._image.copy()
self._image.blit(darken, (0,0), special_flags=pygame.BLEND_RGB_SUB)
if self._scale is not None:
size = self._image.get_size()
sprite_w = int(sprite_w * self._scale)
sprite_h = int(sprite_h * self._scale)
self._image = pygame.transform.scale(self._image, ( int(size[0]*self._scale), int(size[1]*self._scale) ) )
for row in range(self._rows):
for col in range(self._cols):
self._sprites.append( self._image.subsurface((col*sprite_w, row*sprite_h, sprite_w, sprite_h)) )
def __getitem__(self, idx):
#print(self, '__getitem__', idx, self._sprites)
return self._sprites[idx]
def render_sprites(self, surf, spriteids_list, x, y):
cur_y = y
sprite_w, sprite_h = self[0].get_size()
for scanline in spriteids_list:
cur_x = x
for sprite_no in scanline:
if sprite_no is not None:
surf.blit(self._sprites[sprite_no], (cur_x, cur_y))
cur_x += sprite_w
cur_y += sprite_h
return (cur_x-x, cur_y-y) # size of the sprites area
class VerticalLayout(Layout):
def __init__(self, x=None, y=None, spacing=2):
super().__init__(x, y, spacing)
def add(self, item):
super().add(item)
self._re_align()
return item
def _re_align(self):
self._height = 0
for item in self._items:
item.y = self.y + self._height
self._height += item.height + self.spacing
if isinstance(item, Layout):
self._height += item.spacing
if self.x is not None:
item.x = self.x
if self.width<item.width:
self.width = item.width
super()._re_align()
class GridLayout(Layout, BaseGrid):
""" arrange controls in a grid
param alignment: 0 - left aligned, 1 - items are centered in cells
"""
def __init__(self, cols, rows, x=None, y=None, spacing=2, alignment=0):
super().__init__(x, y, spacing, cols, rows)
self._grid=[[0]*cols for _ in range(rows)]
for row in range(rows):
for col in range(cols):
self._grid[row][col] = dict(width=0, height=0, item=None)
self._alignment = alignment
def add(self, item, cell_pos):
col, row = cell_pos
super().add(item)
grid_cell = self._grid[row][col]
grid_cell['item']=item
self._re_align()
return item
def _re_align(self):
self._height = 0
self._width = 0
col_widths = [0] * self._cols
for col in range(self._cols):
for row in range(self._rows):
cell = self._grid[row][col]
item = cell["item"]
if item is None:
continue
if item.width > col_widths[col]:
col_widths[col] = item.width
for row in range(self._rows):
cell_height = 0
#print('start of the loop, cell_height:', cell_height)
item_left=0
for col in range(self._cols):
cell = self._grid[row][col]
item = cell["item"]
if item is None:
continue
if self._alignment==0:
item.x = self.x + item_left
else:
item.x = self.x + item_left + (col_widths[col] - item.width)//2
item_left += col_widths[col] + self.spacing
if isinstance(item, Layout):
item_left += item.spacing
if cell_height < item.height:
cell_height = item.height
#print("bubble gum 2")
item.y = self.y + self._height
h_incr = cell_height + self.spacing
#print('h_incr:', h_incr, "cell_height:", cell_height, "self.spacing:", self.spacing)
self._height += h_incr
if self._width<item_left:
self._width=item_left
if isinstance(item, Layout):
self._height += item.spacing
super()._re_align()
class Spacer(Layout):
def __init__(self, spacing):
super().__init__(None, None, spacing)
def add(self, val):
raise ValueError("Can't add items to spacer")
@Region.y.setter
def y(self, val):
pass
@Region.x.setter
def x(self, val):
pass
class HorizontalLayout(Layout):
def __init__(self, x=None, y=None, spacing=0, *args, **kwargs):
#print('HorizontalLayout __init__:', args, kwargs)
super().__init__(x, y, spacing, *args, **kwargs)
self._width = 0
def add(self, item):
super().add(item)
self._re_align()
return item
def _re_align(self):
super()._re_align()
self._width = 0
for i, item in enumerate(self._items, start=1):
if self.x is None:
break
item.x = self.x + self._width
self._width += item.width + (self.spacing if i<len(self._items) else 0)
if isinstance(item, Layout):
self._width += item.spacing
if self.y is not None:
item.y = self.y
if self.height<item.height:
self.height = item.height
class DrawingBoard(BaseControl, BaseGrid):
""" Display pixel grid for sprite editing """
DRAW_GRID_AT_ZOOM = 5
MAX_ZOOM = 32
COLOR_GRID_TINT = (33,32,29)
def __init__(self, size, color=COLOR_GRID, zoom=4, max_width=None, **kwargs):
super().__init__(0, 0, 0, 0, color, cols=size[0], rows=size[1], **kwargs)
if max_width is not None:
for z in range(1,self.MAX_ZOOM+1):
self._zoom = z
if self.width>=max_width:
break
else:
self._zoom = zoom
self._max_width = max_width
self.size = size
self._onion_skin = None
self._on_painted_cb = None
def on_painted(self, f_cb):
""" property to assign on painted callback """
self._on_painted_cb = types.MethodType(f_cb, self)
on_painted = property(fset=on_painted)
@property
def size(self):
return self._size
@size.setter
@makes_dirty
@save_to_conf
def size(self, value):
if not isinstance(value, (list, tuple)):
raise TypeError('size val has to be list or tuple :P')
self._size = value
self._grid_image = pygame.Surface(self._size).convert()
self._grid_image.fill( self._color )
self._cols = self._size[0]
self._rows = self._size[1]
@makes_dirty
def set_image(self, surf, where=(0,0)):
self._grid_image.blit(surf, where)
@property
def cell_width(self):
return self._zoom
@property
def cell_height(self):
return self._zoom
@makes_dirty
def set_onion_skin(self, surf):
self._onion_skin = surf
def cell_at_pos(self, x, y, boundry_checks=True):
""" get col, row and specified position x, y
"""
cell_col = (x - self._x) // self.cell_width
cell_row = (y - self._y) // self.cell_height
if boundry_checks and (cell_col<0 or cell_row<0 or cell_col>(self._cols-1) or cell_row>(self._rows-1)):
return None
return cell_col, cell_row
def get_cellcolor_at_pos(self, x, y):
res = self.cell_at_pos(x, y)
if res is None:
return None
cell_col, cell_row = res
return self._grid_image.get_at((cell_col, cell_row))
@makes_dirty
def set_cellcolor_at_pos(self, x, y, value):
res = self.cell_at_pos(x, y)
if res is None:
return None
cell_col, cell_row = res
self._grid_image.set_at( (cell_col, cell_row), value )
@makes_dirty
def line(self, x1, y1, x2, y2, color):
p1 = self.cell_at_pos(x1, y1, False)
p2 = self.cell_at_pos(x2, y2, False)
if p1 is None or p2 is None:
return None
pygame.draw.line(self._grid_image, color, p1, p2)
@makes_dirty
def set_grid_image(self, new_img):
self.size = new_img.get_size()
self._grid_image = new_img.copy()
@property
def grid_image(self):
return self._grid_image
@lru_cache(maxsize=3)
def _make_grid_s(self, size):
grid_surf = pygame.Surface(size)
#grid_surf.fill(self.COLOR_WHITE)
s = pygame.PixelArray(grid_surf)
s[::self._zoom, 1::2] = self.COLOR_GRID_TINT
s[1::2, ::self._zoom] = self.COLOR_GRID_TINT
s.close()
return grid_surf
@makes_dirty
def flood_fill_at_pos(self, x,y,value):
res = self.cell_at_pos(x, y)
if res is None:
return None
cell_col, cell_row = res
flood_fill(self._grid_image, cell_col, cell_row, value)
@staticmethod
@lru_cache(maxsize=5)
def _new_image(size):
res = pygame.Surface(size)
return res
@property
def image(self):
if self._dirty:
self._image = self._new_image((self.width, self.height))
if self._onion_skin is not None:
new_im = self._grid_image.copy()
new_im.set_colorkey(self._grid_image.get_at((0,0)))
im = pygame.transform.average_surfaces( [ new_im, new_im, self._onion_skin ])
im.blit(new_im, (0,0), special_flags=0)
else:
im = self._grid_image
pygame.transform.scale(im, (self.width, self.height), self._image)
if self._zoom > self.DRAW_GRID_AT_ZOOM:
grid_surf = self._make_grid_s( (self.width, self.height) )
self._image.blit(grid_surf, (0,0),special_flags=pygame.BLEND_SUB)
#self._image.blit(grid_surf, (0,0),special_flags=pygame.BLEND_MAX)
pygame.draw.rect(self._image, COLOR_GRID_CELL, (0, 0, self.width, self.height), width=1)
if self._on_painted_cb is not None:
self._on_painted_cb(self._grid_image, self.app)
self._dirty = False
return self._image
@Region.width.getter
def width(self):
return self._zoom * self._cols
@Region.height.getter
def height(self):
return self._zoom * self._rows
@property
def zoom(self):
return self._zoom
@zoom.setter
@makes_dirty
def zoom(self, zoom):
if not isinstance(zoom, int):
raise TypeError('zoom has to be int')
if zoom<1 or zoom > 32:
raise ValueError('zoom has to be > 1 and <= 32')
self._zoom = zoom
def draw(self, surf):
surf.blit(self.image, (self._x, self._y))
class MainMenu(BaseControl):
def __init__(self, height=18, margin=5, spacing=0, color=COLOR_FOREGROUND, *args, **kwargs):
self._margin = margin
self._spacing = spacing
self._controls = HorizontalLayout(spacing=self._spacing)
self._controls._set_parent(self)
super().__init__(0, 0, 8, height, color, **kwargs)
self._drop_shadow = False
self._menus = {}
self._controls.x = self.x+margin
self._controls.y = self.y+margin
self._selected_menu = None
self._on_menu_item_cb = None
self._selectable = True
def on_menu_item(self, f_cb):
""" property to assign on when menu item is clicked or
pushed by keyboard callback
"""
self._on_menu_item_cb = types.MethodType(f_cb, self)
on_menu_item = property(fset=on_menu_item)
def _hide_items(self, menu):
for item_ctrl in menu["items"]:
item_ctrl.hide()
def _show_items(self, menu):
for item_ctrl in menu["items"]:
item_ctrl.show()
def _menu_item_click(self, *args, **kwargs):
menu = kwargs["menu"]
item_name = kwargs["item_name"]
if self._on_menu_item_cb is not None:
self._on_menu_item_cb(menu['name'], item_name, self.app)
def _hide_invisible(self):
for c_menu in self._menus.values():
if c_menu is self._selected_menu:
self._show_items( c_menu )
else:
self._hide_items( c_menu )
def _menu_click(self, *args, **kwargs):
menu = kwargs["menu"]
self._selected_menu = menu
self._hide_invisible()
@BaseControl.selected.setter
def selected(self, selected):
print(self, 'selected:', selected)
self._selected = selected
if not selected:
self._selected_menu = None
self._hide_invisible()
def add_menu_item(self, group_name, item_name):
menu = self._menus.get(group_name, None)
if menu is None:
menu = {}
menu["name"] = group_name
menu["layout"] = self._controls.add(VerticalLayout(spacing=5))
menu["label"] = menu["layout"].add( Label( menu["name"] ) )
menu["layout"].add( Spacer(5) )
menu["label"].on_click = lambda *args, **kwargs: self._menu_click(*args, **kwargs, menu=menu)
menu["items"] = []
self._menus[group_name] = menu
if item_name=="--":
menu_item = menu["layout"].add( HorizontalLine(menu["layout"].width, 1, mode=0) )
else:
menu_item = menu["layout"].add( Label(item_name) )
for ctrl in menu["items"]:
if isinstance(ctrl, HorizontalLine):
ctrl._width = menu["layout"].width
menu_item.on_click = lambda *args, **kwargs: self._menu_item_click(*args, **kwargs, menu=menu, item_name=item_name)
menu_item.hide()
menu["items"] += [menu_item]
def remove_menu_item(self, group_name, item_name):
pass
#return self._controls.remove( value )
@Region.width.getter
def width(self):
if self.app is not None:
return self.app.screen_width
return self._width
def draw(self, surf):
draw_panel(surf, self.x, self.y, self.width, self.height, self._color)
for menu in self._menus.values():
if menu is self._selected_menu:
layout = menu["layout"]
draw_panel(surf, layout.x-4, layout.y+self.height, layout.width+4*2, layout.height-self.height, darker(COLOR_FOREGROUND, 0.1))
highlight = pygame.Surface((menu["label"].width, self.height-2))
highlight.fill((35,45,37))
surf.blit(highlight, (menu["label"].x, self.y+2), special_flags=pygame.BLEND_RGB_ADD)
class ColorCell(BaseControl):
def __init__(self, width, height, color, *args, **kwargs):
super().__init__(0, 0, width, height, *args, **kwargs)
self._color = color
self._border_color = COLOR_BORDER
@BaseControl.color.getter
def color(self):
return self._color
@color.setter
def color(self, color):
if isinstance(color, pygame.Color):
color = (color.r, color.g, color.b)
self._color = color
def draw(self, surf):
pygame.draw.rect(surf, self._color, (self.x, self.y, self.width, self.height))
pygame.draw.rect(surf, self._border_color, (self.x, self.y, self.width, self.height), width=1)
class ROI(BaseControl):
(DRAG_MODE_V1,
DRAG_MODE_V2,
DRAG_MODE_V3,
DRAG_MODE_V4,
DRAG_MODE_E1,
DRAG_MODE_E2,
DRAG_MODE_E3,
DRAG_MODE_E4) = range(1, 9)
def __init__(self, width, height, *args, **kwargs):
super().__init__(0, 0, width, height, *args, **kwargs)
self._drop_shadow = False
self._controls = Layout(self.x, self.y)
self._label = self._controls.add(Label(""))
self._label.x += 5
self._label.y += 5
self._label._visible = False
def pick_edge_hor(self, x, y, length, thinkness, pick_x, pick_y):
dx = pick_x - x
dy = pick_y - y
return dx >= 0 and dx <= length and abs(dy)<=thinkness
def pick_edge_vert(self, x, y, length, thinkness, pick_x, pick_y):
dx = pick_x - x
dy = pick_y - y
return dy>=0 and dy<=length and abs(dx)<=thinkness
def drag_test(self, x, y):
if self.pick_point(self.x, self.y, x, y, size=3):
return self.DRAG_MODE_V1
elif self.pick_point(self.right, self.y, x, y, size=3):
return self.DRAG_MODE_V2
elif self.pick_point(self.right, self.bottom, x, y, size=3):
return self.DRAG_MODE_V3
elif self.pick_point(self.x, self.bottom, x, y, size=3):
return self.DRAG_MODE_V4
elif self.pick_edge_hor(self.x, self.y, self.width, 3, x, y):
return self.DRAG_MODE_E1
elif self.pick_edge_hor(self.x, self.bottom, self.width, 3, x, y):
return self.DRAG_MODE_E3
elif self.pick_edge_vert(self.x, self.y, self.height, 3, x, y):
return self.DRAG_MODE_E4
elif self.pick_edge_vert(self.right, self.y, self.height, 3, x, y):
return self.DRAG_MODE_E2
def drag_move(self, mode, x, y, x_rel, y_rel, app, button):
super().drag_move(mode, x, y, x_rel, y_rel, app, button)
if button==pygame.BUTTON_LEFT:
if mode==self.DRAG_MODE_V1:
self.x = x
self.y = y
self.width-=x_rel
self.height-=y_rel
elif mode==self.DRAG_MODE_V2:
self.width+=x_rel
self.y = y
self.height-=y_rel
elif mode==self.DRAG_MODE_V3:
self.width+=x_rel
self.height+=y_rel
elif mode==self.DRAG_MODE_V4:
self.x = x
self.width-=x_rel
self.height+=y_rel
elif mode in (self.DRAG_MODE_E1, self.DRAG_MODE_E2, self.DRAG_MODE_E3, self.DRAG_MODE_E4):
self.x += x_rel
self.y += y_rel
if self.width<=0:
self.x+=self.width
self.width = 1
if self.height<=0:
self.y+=self.height
self.height=1
@property
def roi(self):
return (self.x, self.y, self.width, self.height)
@Region.x.getter