-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathApus.Engine.UIWidgets.pas
1983 lines (1784 loc) · 63.3 KB
/
Apus.Engine.UIWidgets.pas
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
// -----------------------------------------------------
// Standard widget classes
//
// Author: Ivan Polyacov, Apus Software ([email protected])
// This file is licensed under the terms of BSD-3 license (see license.txt)
// This file is a part of the Apus Game Engine (http://apus-software.com/engine/)
// ------------------------------------------------------
unit Apus.Engine.UIWidgets;
interface
uses Types, Apus.Common, Apus.AnimatedValues,
Apus.Engine.API, Apus.Engine.Types, Apus.Engine.UITypes;
{$WRITEABLECONST ON}
{$IFDEF CPUARM} {$R-} {$ENDIF}
const
// Константы окна (дефолтное поведение, можно менять)
wcFrameBorder:integer=5; // Ширина рамки окна
wcTitleHeight:integer=24; // Высота заголовка окна
// Window area flags
wcLeftFrame = 1;
wcTopFrame = 2;
wcRightFrame = 4;
wcBottomFrame = 8;
wcHeader = 16; // area that can be used to drag and move the window
wcClient = 32; // client part of the window
type
// Элемент с ограничениями размера
TUIFlexControl=class(TUIElement)
minWidth,minHeight:integer;
maxWidth,maxHeight:integer;
end;
TUISplitter=class(TUIElement)
canResize:boolean; // true - allow resizing neighbour elements
constructor CreateH(height:single;parent:TUIElement;color:cardinal=0); overload;
constructor CreateH(innerHeight,marginH,marginV:single;parent:TUIElement;color:cardinal=0); overload;
constructor CreateV(width:single;parent:TUIElement;color:cardinal=0); overload;
constructor CreateV(innerWidth,marginH,marginV:single;parent:TUIElement;color:cardinal=0); overload;
end;
// Just a static image
TUIImage=class(TUIElement)
src:string; // can be "file:xxx" "event:xxx", "proc:XXXXXXXX" etc...
constructor Create(width,height:single;imgname:string;parent_:TUIElement;source:string='');
procedure SetRenderProc(proc:pointer); // sugar for use "proc:XXX" src for the default style
end;
// Скроллер для тачскрина - размещается независимо либо поверх другого элемента, который он и скроллит
// It captures mouse drag events, but passes clicks through
TUIScrollArea=class(TUIElement)
fullWidth,fullHeight:single; // full content area
direction:TUIScrollDirection;
constructor Create(width,height,fullW,fullH:single;dir:TUIScrollDirection;parent_:TUIElement);
procedure onMouseMove; override;
procedure onMouseButtons(button:byte;state:boolean); override;
procedure onTimer; override;
protected
speedX,speedY:single;
lastTime:cardinal;
isHooked:boolean;
end;
// Окошко хинта
// обычно создается незаполненным или неполностью заполненным,
// создающий код либо отрисовщик могут дополнить или использовать значения по умолчанию
TUIHint=class(TUIImage)
simpleText:string; // текст надписи
active:boolean; // если true - значит хинт активный, не кэшируется и содержит вложенные эл-ты
created:int64; // момент создания (в мс.)
adjusted:boolean; // отрисовщик может использовать это для корректировки параметров хинта
hiding:boolean; // hint is currently hiding
constructor Create(x,y:single;text:string;parent_:TUIElement);
destructor Destroy; override;
procedure Hide;
procedure onMouseButtons(button:byte;state:boolean); override;
procedure onTimer; override;
end;
TUILabel=class(TUIElement)
align:TTextAlignment;
autoSize:boolean; // render should adjust element size to match caption
verticalOffset:integer; // сдвиг текста вверх
constructor Create(width,height:single;labelname,text:string;color_:cardinal;bFont:TFontHandle;parent_:TUIElement); overload;
constructor Create(width,height:single;labelname,text:string;parent_:TUIElement;font:TFontHandle=0;color_:cardinal=clDefault); overload;
constructor CreateCentered(width,height:single;labelname,text:string;parent_:TUIElement;font:TFontHandle=0;color_:cardinal=clDefault);
constructor CreateRight(width,height:single;labelname,text:string;parent_:TUIElement;font:TFontHandle=0;color_:cardinal=clDefault);
procedure CaptionWidthIs(width:single);
end;
// Тип кнопок
TButtonStyle=(bsNormal, // обычная кнопка
bsSwitch, // кнопка-переключатель (фиксирующаяся в нажатом положении)
bsCheckbox); // кнопка-надпись (чекбокс)
TUIButton=class(TUIElement)
default:boolean; // кнопка по умолчанию (влияет только на отрисовку, но не на поведение!!!)
pressed:boolean; // кнопка вдавлена
pending:boolean; // состояние временной недоступности (не реагирует на нажатия)
autoPendingTime:integer; // время (в мс) на которое кнопка переводится в состояние pending при нажатии (0 - не переводится)
btnStyle:TButtonStyle; // тип кнопки (влияет как на отрисовку, так и на поведение)
group:integer; // Группа переключателей
onClick:TProcedure;
onClickEvent:string;
{ class var onClickSender:TUIButton;
class var active:TUIButton; // link to the active button (can be used in click handlers)}
constructor Create(width,height:single;btnName,btnCaption:string;btnFont:TFontHandle;parent_:TUIElement); overload;
constructor Create(width,height:single;btnName,btnCaption:string;parent_:TUIElement); overload;
constructor Create(width,height:single;btnCaption:string;parent_:TUIElement); overload;
constructor CreateSwitch(width,height:single;btnName,btnCaption:string;group:integer;
btnFont:TFontHandle;parent_:TUIElement;pressed:boolean=false); overload;
constructor CreateSwitch(width,height:single;btnName,btnCaption:string;parent_:TUIElement;pressed:boolean=false); overload;
constructor CreateSwitch(width,height:single;btnCaption:string;parent_:TUIElement;pressed:boolean=false); overload;
constructor CreateGroupSwitch(width,height:single;btnCaption:string;parent_:TUIElement;pressed:boolean=false); overload;
destructor Destroy; override;
procedure onMouseButtons(button:byte;state:boolean); override;
procedure onMouseMove; override;
function onKey(keycode:byte;pressed:boolean;shiftstate:byte):boolean; override;
function onHotKey(keycode:byte;shiftstate:byte):boolean; override;
procedure onTimer; override; // отжимает кнопку по таймеру
procedure SetPressed(pr:boolean); virtual;
procedure MakeSwitches(sameGroup:boolean=true;clickHandler:TProcedure=nil); // make all sibling buttons with the same size - switches
procedure Click; virtual; // simulate click
class function GetSwitchIndex(parent:TUIElement):integer;
class function Sender:TUIButton;
protected
procedure DoClick;
procedure CheckGroup;
procedure FireClickEvent;
private
lastPressed,pendingUntil:int64;
lastOver:boolean; // was under mouse when onMouseMove was called last time
end;
TUICheckBox=class(TUIButton)
checked:boolean;
constructor Create(width,height:single;btnName,caption:string;parent_:TUIElement;
checked:boolean=false;btnFont:TFontHandle=0); overload;
procedure SetPressed(pr:boolean); override;
end;
TUIRadioButton=class(TUICheckbox)
constructor Create(width,height:single;btnName,caption:string;
parent_:TUIElement;checked:boolean=false;btnFont:TFontHandle=0); overload;
end;
// Рамка
TUIFrame=class(TUIElement)
constructor Create(width,height:single;depth,style_:integer;parent_:TUIElement);
procedure SetBorderWidth(w:integer); virtual;
protected
borderWidth:integer; // ширина рамки
end;
// Basic window
TUIWindow=class(TUIImage)
header:integer; // Высота заголовка
autoBringToFront:boolean; // автоматически переносить окно на передний план при клике по нему или любому вложенному эл-ту
moveable:boolean; // окно можно перемещать
resizeable:boolean; // окно можно растягивать
minW,minH,maxW,maxH:integer; // максимальные и минимальные размеры (для растягивающихся окон)
constructor Create(innerWidth,innerHeight:single;sizeable:boolean;wndName,wndCaption:string;wndFont:TFontHandle;parent_:TUIElement);
// Возвращает флаги типа области в указанной точке (к-ты экранные (в пикселях)
// а также курсор, который нужно заюзать для этой области
// Эту ф-цию нужно переопределить для создания окон специальной формы или поведения
function GetAreaType(x,y:integer;out cur:NativeInt):integer; virtual;
procedure onMouseMove; override;
procedure onMouseButtons(button:byte;state:boolean); override;
procedure onLostFocus; override;
procedure Resize(newWidth,newHeight:single); override;
class function IsWindow:boolean; override;
private
hooked:boolean;
area:integer; // тип области под курсором
end;
// Разновидность окна: окно со скином
// ключевые особенности: имеет фиксированный размер и зачастую непрямоугольную форму,
// а также фон в виде картинки
// такое окно создается с дефолтными параметрами и должно далее настраиваться извне
TUISkinnedWindow=class(TUIWindow)
dragRegion:TRegion; // область, за которую можно таскать окно (если не задана - то за любую точку)
background:pointer; // некий указатель на фон окна (т.к. вопросы отрисовки в этом модуле не затрагиваются)
constructor Create(wndName,wndCaption:string;wndFont:TFontHandle;parent_:TUIElement;canmove:boolean=true);
destructor Destroy; override;
function GetAreaType(x,y:integer;out cur:NativeInt):integer; override; // x,y - screen space coordinates
end;
TUIEditBox=class(TUIElement)
realText:WideString; // real text value of the edit box
completion:WideString; // grayed background text, if it is not empty and enter is pressed, then it is set to realText
defaultText:WideString; // grayed background text, displayed if realText is empty
cursorPos:integer; // cursor position (cursor is located after the character with given index, 1-based)
maxLength:integer; // max allowed length
password:boolean; // is it password field? if true, all characters are displayed as '*'
noBorder:boolean; // deprecated
selStart,selCount:integer; //
cursorTimer:int64; // time offset for cursor blinking
needPos:integer; // pixel position feedback from the drawer
msSelect:boolean; // mouse selection mode is ON
protection:byte; // xor all characters with this value
offset:integer; // shift text right by this number of pixels
constructor Create(width,height:single;boxName:string;boxFont:TFontHandle;color_:cardinal;parent_:TUIElement); overload;
constructor Create(width,height:single;text:string;parent:TUIElement;name:string=''); overload;
procedure onChar(ch:char;scancode:byte); override;
procedure onUniChar(ch:WideChar;scancode:byte); override;
function onKey(keycode:byte;pressed:boolean;shiftstate:byte):boolean; override;
procedure onMouseButtons(button:byte;state:boolean); override;
procedure onMouseMove; override;
procedure SetFocus; override;
procedure onLostFocus; override;
procedure SelectAll; virtual;
private
savedText:WideString;
lastClickTime:int64;
msSelStart:integer; // после символа с этим номером находится точка начала выделения мышью
procedure AdjustState;
function GetText:String8;
procedure SetText(s:String8);
public
property text:String8 read GetText write SetText; // Current value in UTF-8 encoding
end;
// Полоса прокрутки
TUIScrollBar=class(TUIElement)
private
rValue:TAnimatedValue;
sliderRect:TRect;
function GetValue:single;
procedure SetValue(v:single);
function GetAnimating:boolean;
procedure SetPageSize(pageSize:single);
function GetStep:single;
procedure CheckAutoHide;
public
horizontal:boolean; // orientation
isInteger:boolean; // should value be always integer
min,max:single; // range
pagesize:single; // slider size (within range)
step:single; // add/subtract this amount with mouse scroll or similar events
sliderUnder:boolean; // mouse is over slider
sliderStart,sliderEnd:single; // relative position of slider (in 0..1 range)
autoHide:boolean; // hide if pagesize>=range
constructor Create(width,height:single;barName:string;parent_:TUIElement); overload;
constructor Create(width,height:single;min,max,pageSize,value:single;parent:TUIElement;barName:string=''); overload;
function GetScroller:IScroller;
function SetRange(newMin,newMax,newPageSize:single):TUIScrollBar;
// Переместить ползунок в указанную позицию
procedure MoveTo(val:single;smooth:boolean=false); virtual;
procedure MoveRel(delta:single;smooth:boolean=false); virtual;
// Связать значение с внешней переменной
procedure Link(elem:TUIElement); virtual;
// Сигналы от этих кнопок будут использоваться для перемещения ползунка
procedure UseButtons(lessBtn,moreBtn:string);
procedure CalcSliderPos(minSize:single=0.5); // minimal slider size (relative to width)
procedure onTimer; override;
procedure onMouseMove; override;
procedure onMouseButtons(button:byte;state:boolean); override;
procedure onMouseScroll(value:integer); override;
procedure onLostFocus; override;
property value:single read GetValue write SetValue;
property isAnimating:boolean read GetAnimating;
protected
linkedControl:TUIElement;
delta:integer; // смещение точки курсора относительно точки начала ползунка (если hooked)
moving:boolean;
scroller:TObject;
end;
TUIListBox=class(TUIElement)
lines:StringArr;
tags:array of cardinal;
hints:StringArr; // each element may have its own hint
lineHeight:single; // in self CS
selectedLine:integer; // index of selected line (or -1)
hoverLine:integer; // index of line under mouse (or -1)
autoSelectMode:boolean; // when true, hover line is automatically selected
bgColor,bgHoverColor,bgSelColor,textColor,hoverTextColor,selTextColor:cardinal; // цвета отрисовки
constructor Create(width,height:single;lHeight:single;listName:string;font_:TFontHandle;parent:TUIElement);
destructor Destroy; override;
procedure AddLine(line:string;tag:cardinal=0;hint:string=''); virtual;
procedure SetLine(index:integer;line:string;tag:cardinal=0;hint:string=''); virtual;
procedure ClearLines;
procedure SetLines(newLines:StringArr); virtual;
procedure SelectLine(line:integer); virtual;
procedure onMouseMove; override;
procedure onMouseButtons(button:byte;state:boolean); override;
procedure UpdateScroller;
end;
// Выпадающий список
TUIComboBox=class(TUIButton)
items,hints:WStringArr;
tags:IntArray;
defaultText:WideString;
fCurItem,fCurTag:integer;
// pop up elements
frame:TUIFrame;
popup:TUIListBox;
maxlines:integer; // max lines to show without scrolling
constructor Create(width,height:single;bFont:TFontHandle;list:WStringArr;parent_:TUIElement;name:string=''); overload;
constructor Create(width,height:single;parent_:TUIElement;name:string); overload;
procedure AddItem(item:WideString;tag:cardinal=0;hint:WideString=''); virtual;
procedure SetItem(index:integer;item:WideString;tag:cardinal=0;hint:string=''); virtual;
procedure ClearItems;
procedure onDropDown; virtual;
procedure onMouseButtons(button:byte;state:boolean); override;
procedure onTimer; override; // трюк: используется для слежения за всплывающим списком, чтобы не заморачиваться с сигналами
procedure SetCurItem(item:integer); virtual;
procedure SetCurItemByText(value:string16); virtual;
procedure SetCurItemByTag(tag:integer); virtual;
protected
function GetText:string16;
public
property curItem:integer read fCurItem write SetCurItem;
property curTag:integer read fCurTag write SetCurItemByTag;
property text:string16 read GetText;
end;
implementation
uses SysUtils, Apus.Types, Apus.CrossPlatform, Apus.EventMan, Apus.Geom2D, Apus.Clipboard;
type
TScrollBarInterface=class(TInterfacedObject, IScroller)
owner:TUIScrollBar;
constructor Create(owner:TUIScrollbar);
function GetElement:TUIElement;
procedure SetRange(min,max:single);
procedure SetValue(v:single);
procedure SetStep(step:single);
procedure SetPageSize(pageSize:single);
procedure MoveRel(delta:single;smooth:boolean);
function GetValue:single;
function GetStep:single;
function GetPageSize:single;
end;
var
comboPop:TUIComboBox; // если существует выпавший комбобокс (а он может быть только один) - он тут
{ TUISpacer }
constructor TUISplitter.CreateH(innerHeight,marginH,marginV:single;parent:TUIElement;color:cardinal);
begin
inherited Create(-1,innerHeight+marginV*2,parent);
SetPaddings(marginH,marginV,marginH,marginV);
if color<>0 then
SetStyle('inner-fill',IntToHex(color,8));
end;
constructor TUISplitter.CreateH(height:single;parent:TUIElement;color:cardinal);
begin
CreateH(height,0,0,parent,color);
end;
constructor TUISplitter.CreateV(innerWidth,marginH,marginV:single;parent:TUIElement;color:cardinal);
begin
inherited Create(innerWidth+marginH*2,-1,parent);
SetPaddings(marginH,marginV,marginH,marginV);
if color<>0 then
SetStyle('inner-fill',IntToHex(color,8));
end;
constructor TUISplitter.CreateV(width:single;parent:TUIElement;color:cardinal);
begin
CreateV(width,0,0,parent,color);
end;
{ TUIimage }
constructor TUIimage.Create(width,height:single;imgname:string;parent_:TUIElement;source:string='');
begin
inherited Create(width,height,parent_,imgName);
src:=source;
shape:=shapeEmpty;
end;
procedure TUIImage.SetRenderProc(proc:pointer);
begin
styleClass:=0;
src:='proc:'+FormatHex(UIntPtr(proc));
end;
{ TUIButton }
procedure TUIButton.Click;
begin
onMouseButtons(1,true);
onMouseButtons(1,false);
end;
constructor TUIButton.Create(width,height:single;btnName,btnCaption:string;btnFont:TFontHandle;parent_:TUIElement);
var
i:integer;
begin
inherited Create(width,height,parent_,btnName);
shape:=shapeFull;
font:=BtnFont;
btnStyle:=bsNormal;
group:=0;
caption:=BtnCaption;
default:=true; // make it default unless there is another sibling button
if parent<>nil then
if parent.children<>nil then
for i:=0 to high(parent.children) do
if parent.children[i] is TUIButton then
default:=false;
pressed:=false;
pending:=false;
autoPendingTime:=0;
CanHaveFocus:=false;
sendSignals:=ssMajor;
//CheckAndSetFocus;
lastPressed:=0;
end;
// Without font
constructor TUIButton.Create(width,height:single;btnName,btnCaption:string; parent_:TUIElement);
begin
Create(width,height,btnName,btnCaption,0,parent_);
end;
constructor TUIButton.Create(width,height:single;btnCaption:string;parent_:TUIElement);
begin
Create(width,height,'',btnCaption,0,parent_);
end;
constructor TUIButton.CreateSwitch(width,height:single;btnName,btnCaption:string;
group:integer;btnFont:TFontHandle;parent_:TUIElement;pressed:boolean=false);
begin
Create(width,height,btnName,btnCaption,btnFont,parent_);
btnStyle:=bsSwitch;
self.group:=group;
SetPressed(pressed);
CheckGroup;
end;
constructor TUIButton.CreateSwitch(width,height:single;btnName,btnCaption:string;
parent_:TUIElement;pressed:boolean=false);
begin
Create(width,height,btnName,btnCaption,0,parent_);
btnStyle:=bsSwitch;
SetPressed(pressed);
CheckGroup;
end;
constructor TUIButton.CreateSwitch(width,height:single;btnCaption:string;parent_:TUIElement;pressed:boolean=false);
begin
CreateSwitch(width,height,'',btnCaption,parent_,pressed);
end;
constructor TUIButton.CreateGroupSwitch(width,height:single;btnCaption:string;parent_:TUIElement;pressed:boolean=false);
begin
CreateSwitch(width,height,'',btnCaption,1,0,parent_,pressed);
end;
// Check if there are other pressed buttons in the same group and unpress them
procedure TUIButton.CheckGroup;
var
i:integer;
begin
if (parent=nil) or (group=0) then exit;
for i:=0 to length(parent.children)-1 do
if (parent.children[i]<>self) and
(parent.children[i] is TUIButton) and
(TUIButton(parent.children[i]).group=group) then begin
if pressed and TUIButton(parent.children[i]).pressed then
TUIButton(parent.children[i]).SetPressed(false);
end;
end;
destructor TUIButton.Destroy;
begin
inherited;
end;
procedure TUIButton.DoClick;
var
i:integer;
begin
// Toggle switch button
TUIElement.sender:=self;
if btnStyle<>bsNormal then begin
if group=0 then SetPressed(not pressed)
else begin
ASSERT(parent<>nil);
for i:=0 to length(parent.children)-1 do
if (parent.children[i] is TUIButton) and ((parent.children[i] as TUIButton).group=group) then
(parent.children[i] as TUIButton).SetPressed(false);
SetPressed(true);
end;
if (sendSignals<>ssNone) and
(pressed or (btnStyle=bsCheckbox)) then begin
Signal('UI\'+name+'\Click',byte(pressed));
Signal('UI\Button\Down\'+name,TTag(self));
FireClickEvent;
if onClickEvent<>'' then Signal(onClickEvent,TTag(self));
end;
end else begin
if pending then exit;
// Защита от двойных кликов
if (sendSignals<>ssNone) and (MyTickCount>lastPressed+50) then begin
Signal('UI\'+name+'\Click',byte(pressed));
Signal('UI\Button\Click\'+name,TTag(self));
if Assigned(onClick) then begin
game.RunAsync(@onClick);
end;
if onClickEvent<>'' then Signal(onClickEvent,TTag(self));
lastPressed:=MyTickCount;
end;
end;
end;
procedure TUIButton.FireClickEvent;
begin
if not Assigned(onClick) then exit;
TUIElement.sender:=self;
onClick;
end;
class function TUIButton.GetSwitchIndex(parent:TUIElement):integer;
var
e:TUIElement;
begin
result:=-1;
for e in parent.children do
if e is TUIButton then
with TUIButton(e) do
if group>0 then begin
inc(result);
if pressed then exit;
end;
result:=-1;
end;
function TUIButton.onHotKey(keycode,shiftstate:byte):boolean;
var
i:integer;
begin
result:=false;
if btnStyle=bsNormal then begin
SetPressed(true);
DoClick;
timer:=150;
result:=true;
end else begin
// don't click on button if it has no effect: i.e. it is pressed and there are other group buttons
if pressed and (parent<>nil) and (group<>0) then
for i:=0 to high(parent.children) do
if (parent.children[i]<>self) and (parent.children[i] is TUIButton) and
((parent.children[i] as TUIButton).group=group) then exit;
DoClick;
result:=true;
end;
end;
function TUIButton.onKey(keycode:byte;pressed:boolean;shiftstate:byte):boolean;
begin
result:=inherited onKey(keycode,pressed,shiftstate);
if pressed and (keycode in [VK_RETURN,VK_SPACE]) then begin // Enter
onHotKey(keycode,shiftstate);
result:=false;
end;
end;
procedure TUIButton.onMouseButtons(button:byte;state:boolean);
begin
if not enabled then begin
Signal('UI\'+name+'\ClickDisabled',button);
exit;
end;
// Regular button
if (button=1) and (btnStyle=bsNormal) then begin
if not pressed and state then SetPressed(true); // нажать
if pressed and not state then begin // отпустить и среагировать
DoClick;
SetPressed(false);
end;
end;
// Special button
if (button=1) and (btnStyle<>bsNormal) and state then DoClick;
inherited;
end;
procedure TUIButton.onMouseMove;
begin
inherited;
if not lastover and (undermouse=self) then
Signal('UI\Button\Over\'+name);
if lastover and (undermouse<>self) then
Signal('UI\Button\Out\'+name);
if btnStyle=bsNormal then begin
if pressed and (underMouse<>self) then
SetPressed(false);
end;
lastover:=undermouse=self;
end;
procedure TUIButton.onTimer;
begin
if btnStyle=bsNormal then begin
SetPressed(false);
end;
end;
class function TUIButton.Sender:TUIButton;
begin
result:=TUIElement.sender as TUIButton;
end;
procedure TUIButton.SetPressed(pr:boolean);
begin
pressed:=pr;
if linkedValue<>nil then
PBoolean(linkedValue)^:=pressed;
if (sendSignals<>ssNone) then begin
if btnStyle<>bsNormal then begin
Signal('UI\Button\Toggle\'+name,UIntPtr(self));
Signal('UI\'+name+'\Toggle');
end else begin
if pr then Signal('UI\Button\Down\'+name,UIntPtr(self))
else Signal('UI\Button\Up\'+name,UIntPtr(self));
end;
end;
end;
procedure TUIButton.MakeSwitches(sameGroup:boolean=true;clickHandler:Apus.Types.TProcedure=nil); // make all sibling buttons with the same size - switches
var
i:integer;
b:TUIButton;
first:boolean;
begin
if parent=nil then exit;
first:=true;
for i:=0 to high(parent.children) do begin
if not (parent.children[i] is TUIButton) then continue;
b:=TUIButton(parent.children[i]);
if not b.visible then continue;
if abs(b.size.x-size.x)+abs(b.size.y-size.y)>=1 then continue;
b.btnStyle:=bsSwitch;
if @clickHandler<>nil then b.onClick:=@clickHandler;
if sameGroup then begin
b.group:=1;
if first then begin
b.pressed:=true;
first:=false;
end;
end else
b.group:=i+1;
end;
end;
{ TUICheckBox }
constructor TUICheckBox.Create(width,height:single;btnName,caption:string;
parent_:TUIElement;checked:boolean;btnFont:TFontHandle);
begin
inherited Create(width,height,btnName,caption,parent_);
btnStyle:=bsCheckbox;
self.checked:=checked;
self.pressed:=checked;
if btnFont>0 then font:=btnFont;
end;
{ TUIRadioBox }
constructor TUIRadioButton.Create(width,height:single;btnName,caption:string;
parent_:TUIElement;checked:boolean;btnFont:TFontHandle);
var
i:integer;
begin
inherited Create(width,height,btnName,caption,parent_);
btnStyle:=bsCheckbox;
group:=1;
if btnFont>0 then font:=btnFont;
// Ensure there is at least one checked sibling
self.checked:=true;
for i:=0 to high(parent.children) do
if (parent.children[i]<>self) and (parent.children[i] is TUIRadioButton) then
if TUIRadioButton(parent.children[i]).checked and
(TUIRadioButton(parent.children[i]).group=group) then self.checked:=false;
if checked then DoClick;
end;
procedure TUICheckBox.SetPressed(pr:boolean);
begin
inherited;
checked:=pressed;
end;
{ TUILabel }
procedure TUILabel.CaptionWidthIs(width:single);
var
oldW,dW:single;
begin
width:=width/globalScale;
oldW:=size.x;
ResizeClient(width,clientHeight);
dW:=size.x-oldW;
case align of
taCenter: position.x:=position.x+dW/2;
taRight: position.x:=position.x+dW;
end;
end;
constructor TUILabel.Create(width,height:single;labelname,text:string;color_,bFont:TFontHandle;
parent_: TUIElement);
begin
inherited Create(width,height,parent_,labelName);
shape:=shapeFull;
if color_<>clDefault then color:=color_;
if bFont<>0 then font:=bFont;
align:=taLeft;
sendSignals:=ssMajor;
verticalOffset:=0;
caption:=text;
end;
constructor TUILabel.CreateCentered(width,height:single;labelname,text:string;
parent_:TUIElement;font:TFontHandle=0;color_:cardinal=clDefault);
begin
Create(width,height,labelName,text,color_,font,parent_);
align:=taCenter;
end;
constructor TUILabel.Create(width,height:single;labelname,text:string;
parent_:TUIElement;font:TFontHandle=0;color_:cardinal=clDefault);
begin
Create(width,height,labelName,text,color_,font,parent_);
align:=taLeft;
end;
constructor TUILabel.CreateRight(width,height:single;labelname,text:string;
parent_:TUIElement;font:TFontHandle=0;color_:cardinal=clDefault);
begin
Create(width,height,labelName,text,color_,font,parent_);
align:=taRight;
end;
{ TUIWindow }
constructor TUIWindow.Create(innerWidth,innerHeight:single;sizeable:boolean;wndName,
wndCaption:string;wndFont:TFontHandle;parent_:TUIElement);
var
deltaX,deltaY:integer;
begin
resizeable:=sizeable;
if resizeable then begin
deltaX:=wcFrameBorder; deltay:=wcFrameBorder;
end else begin
deltaX:=2; deltay:=2;
end;
inherited Create(innerWidth+deltaX*2,innerHeight+deltay+wcTitleHeight,wndName,parent_);
padding.Left:=deltaX; padding.Top:=wcTitleHeight;
padding.Right:=deltaX; padding.Bottom:=deltaY;
shape:=shapeFull;
caption:=wndCaption;
font:=wndFont;
header:=wcTitleHeight;
autoBringToFront:=true;
canhavefocus:=false;
moveable:=true;
minW:=32; minH:=32;
maxW:=1600; maxH:=1200;
color:=$FFBCB8B0;
area:=0;
order:=100; // выше чем прочие элементы.
end;
function TUIWindow.GetAreaType(x,y:integer;out cur:NativeInt):integer;
var
c:byte;
r:TRect;
begin
result:=0; cur:=CursorID.Default;
r:=GetPosOnScreen;
if (x<r.left) or (y<r.top) or (x>=r.Right) or (y>=r.Bottom) then exit;
dec(x,r.Left);
dec(y,r.Top);
if resizeable then begin
if x<wcFrameBorder then inc(result,wcLeftFrame);
if y<wcFrameBorder then inc(result,wcTopFrame);
if x+wcFrameBorder>=r.Width then inc(result,wcRightFrame);
if y+wcFrameBorder>=r.Height then inc(result,wcBottomFrame);
if (result=0) and (y<header) then inc(result,wcHeader);
end else begin
if y<header then inc(result,wcHeader);
end;
if result=0 then inc(result,wcClient);
c:=0;
if result and (wcLeftFrame+wcRightFrame)>0 then inc(c);
if result and (wcTopFrame+wcBottomFrame)>0 then inc(c,2);
case c of
1:cur:=CursorID.ResizeW;
2:cur:=CursorID.ResizeH;
3:cur:=CursorID.ResizeHW;
end;
end;
procedure TUIWindow.onLostFocus;
begin
hooked:=false;
end;
procedure TUIWindow.onMouseButtons(button:byte;state:boolean);
var
pnt:TPoint;
begin
inherited;
if (button=1) and not (area in [0,wcClient]) then begin
if not hooked and state then hooked:=true;
if hooked and not state then begin
hooked:=false;
// Don't allow window center to be moved outside screen
pnt:=GetPosOnScreen.CenterPoint;
/// TODO: implement action
end;
end;
end;
procedure TUIWindow.onMouseMove;
var
iScale:single;
dx,dy:single;
begin
if hooked then begin
iScale:=scale/globalScale; // pixels to parent's space scale
dx:=(curMouseX-oldMouseX)*iScale;
dy:=(curMouseY-oldMouseY)*iScale;
// Drag
if area=wcHeader then begin
position:=PointAdd(position, Point2s(dx,dy));
end;
// Resize
if area and wcRightFrame>0 then Resize(size.x+dx,-1);
if area and wcBottomFrame>0 then Resize(-1,size.y+dy);
if area and wcLeftFrame>0 then begin Resize(size.x-dx,-1); position.x:=position.x-dx; end;
if area and wcTopFrame>0 then begin Resize(-1,size.y-dy); position.y:=position.y-dy; end;
end;
inherited;
area:=GetAreaType(curMouseX,curMouseY,cursor);
if area in [0,wcClient] then hooked:=false;
end;
procedure TUIWindow.Resize(newWidth,newHeight:single);
begin
if newwidth<>-1 then begin
if newwidth<minW then newwidth:=minW;
if (newwidth>maxW) and (maxW>0) then newwidth:=maxW;
end;
if newheight<>-1 then begin
if newheight<minH then newheight:=minH;
if (newheight>maxH) and (maxH>0) then newheight:=maxH;
end;
inherited;
end;
class function TUIWindow.IsWindow:boolean;
begin
result:=true;
end;
{ TUIEditBox }
procedure TUIEditBox.AdjustState;
begin
if cursorpos>length(realtext) then cursorpos:=length(realtext);
if selstart>length(realtext) then selstart:=length(realtext);
if selstart+selcount>length(realtext)+1 then selcount:=length(realtext)-selstart+1;
end;
constructor TUIEditBox.Create(width,height:single;boxName:string;
boxFont:TFontHandle;color_:cardinal;parent_:TUIElement);
begin
inherited Create(width,height,parent_,boxName);
shape:=shapeFull;
cursor:=CursorID.Input;
realtext:='';
selstart:=0;
selcount:=0;
cursorpos:=0;
font:=boxFont;
maxlength:=240;
password:=false;
if (color_<>clDefault) then color:=color_;
protection:=0;
needPos:=-1;
offset:=0;
canhavefocus:=true; //CheckAndSetFocus;
sendSignals:=ssAll;
completion:='';
defaultText:='';
lastClickTime:=0;
end;
constructor TUIEditBox.Create(width,height:single;text:string;parent:TUIElement;name:string);
begin
Create(width,height,name,0,clDefault,parent);
self.text:=text;
end;
function TUIEditBox.GetText:String8;
begin
result:=Str8(realtext);
end;
procedure TUIEditBox.SetText(s:String8);
begin
realtext:=DecodeUTF8(s);
if cursorpos>length(realtext) then cursorpos:=length(realtext);
end;
procedure TUIEditBox.onChar(ch:char;scancode:byte);
begin
inherited;
end;
procedure TUIEditBox.onUniChar(ch:WideChar;scancode:byte);
var
oldText:WideString;
begin
oldText:=realText;
AdjustState;
cursortimer:=mytickcount;
TUIElement.sender:=self;
if (ch=#13) and (sendSignals<>ssNone) then begin
if (completion<>'') and (realText<>completion) then begin
realText:=completion;
completion:='';
cursorpos:=length(realtext);
selcount:=0;
Signal('UI\'+name+'\AutoCompletion',0);
Signal('UI\Editbox\AutoCompletion\'+name,0);
end else begin
Signal('UI\'+name+'\Enter',0);
Signal('UI\Editbox\Enter\'+name,0);
end;
end;
if (ch=#27) and (sendSignals<>ssNone) then Signal('UI\'+name+'\Escape',0);
if (ch>=#32) and (selcount>0) then begin
delete(realtext,selstart,selcount);
insert(ch,realtext,selstart);
selcount:=0;
cursorpos:=selstart;
exit;
end;
if (length(realtext)<maxlength) and (ch>=#32) then begin
inc(cursorpos);
insert(ch,realtext,cursorpos);
end;
if (sendSignals=ssAll) and (oldText<>realText) then begin
savedText:=oldText;
Signal('UI\'+name+'\changed',0);
end;
end;
function TUIEditBox.onKey(keycode:byte;pressed:boolean;shiftstate:byte):boolean;
procedure ClipCopy(cut:boolean=false);
var
str:string;
begin
if password or (protection<>0) then exit;
str:=copy(realtext,selstart,selcount);
CopyStrToClipboard(str);
if cut then begin
delete(realtext,selstart,selcount); selcount:=0; cursorpos:=selstart-1;
end;
end;
procedure ClipPaste;
var
str:string;
wst:WideString;
begin
wst:=PasteStrFromClipboardW;
if wst<>'' then begin
if selcount>0 then begin
delete(realtext,selstart,selcount);
cursorpos:=selstart-1;
end else
selstart:=cursorpos+1;
insert(wst,realtext,cursorpos+1);
selcount:=length(str);
if length(realtext)>maxlength then setLength(realtext,maxlength);