Repository navigation
Expand file tree
/
Copy pathApus.Engine.DefaultStyle.pas
More file actions
2040 lines (1949 loc) · 80 KB
/
Copy pathApus.Engine.DefaultStyle.pas
File metadata and controls
2040 lines (1949 loc) · 80 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Default UI style (0) inspired by CSS
//
// Copyright (C) 2022 Apus Software (ivan@apus-software.com)
// This file is licensed under the terms of BSD-3 license (see license.txt)
// This file is a part of the Apus Game Engine (https://github.com/Cooler2/ApusGameEngine)
unit Apus.Engine.DefaultStyle;
interface
uses Apus.Core, Apus.Engine.Types, Apus.Engine.API, Apus.Engine.UI, Apus.Engine.UITypes;
type
// Outer-shadow description stored in TStyleBox.shadow and drawn by DrawStyleBox
// when its Shadow layer is selected. ResolveStyleBox fills it from 'box-shadow';
// a custom drawer may adjust it on the resolved box before drawing. Distances
// are already in screen pixels.
TBoxShadow=record
color:cardinal; // 0 - none
dx,dy,blur,spread:single; // pixels
end;
// Rendering stage selected through DrawStyleBox's layers argument: Shadow is
// the outer box shadow, Background includes fills/shading/images, and Border is
// the outline. Select stages to compose a styled box with custom content.
{$SCOPEDENUMS ON}
TStyleBoxLayer=(Shadow,Background,Border);
{$SCOPEDENUMS OFF}
// Layer mask accepted by DrawStyleBox, e.g. [TStyleBoxLayer.Shadow]. Draw the
// shadow/background first, add custom content, then draw the border above it.
// Omitting the layers argument draws all stages in one call.
TStyleBoxLayers=set of TStyleBoxLayer;
// One background-image layer in TStyleBox.images[0..imageCount-1]. ResolveStyleBox
// supplies the base image and any state cross-fades; DrawStyleBox consumes them
// in its Background layer. Custom drawers may inspect or replace these entries.
// The record borrows tex: copying it does not acquire ownership, and textures
// supplied by the resolver must not be freed through this record.
TBoxImage=record
tex:TTexture;
tint:cardinal;
weight:single; // cross-fade weight (alpha multiplier)
end;
// Per-draw box description returned by either ResolveStyleBox overload for a
// custom element or named-part drawer. Resolve after updating element geometry
// and visual state, optionally adjust this value, then pass it to DrawStyleBox.
// ContentRect gives content bounds that reserve the widest border across states;
// use DrawElementBox when resolving, drawing and obtaining those bounds is enough.
// Colors/fills reflect current state weights; geometry is already in screen
// pixels. Texture references are borrowed and must stay valid through drawing.
// Re-resolve when the element's style, state, geometry or UI scale changes.
TStyleBox=record
rect:TRect; // screen bounds; Right and Bottom are exclusive
scale:single; // globalScale of the element
radii:TCornerRadii;
borderWidth:single;
reserve:single; // the widest border over the base and all state blocks
fill,border,shade:TBlendedFill; // 'fill', 'border-color', 'fill-shade' (over the fill)
shadow:TBoxShadow; // 'box-shadow'
outerBorder:boolean; // the border lies outside rect (list boxes)
// 'background-image' layers: the base and state cross-fades; 'background-size: stretch',
// 'background-position: top-left', 'background-offset-x/y'
images:array[0..3] of TBoxImage;
imageCount:integer;
imageStretch,imageTopLeft:boolean;
imageOfs:TVec2;
moveBlend:boolean; // the shape is not empty: copy over a transparent target (blMove)
function IsEmpty:boolean; // nothing to draw (the shadow aside)
function ContentRect:TRect; // rect deflated by reserve: does not move on hover/focus
end;
// The box of an element: base values blended toward its states (call after UpdateVisualState,
// which DrawUIElement does). The style only: the default drawer adds the look of a plain
// button (a default fill, a shade, derived state colors), this does not
procedure ResolveStyleBox(element:TUIElement; out box:TStyleBox); overload;
// The box of a part ('header { ... }') in rect, with the part states given by the drawer;
// keys come from the part block (no background images yet)
procedure ResolveStyleBox(element:TUIElement; const part:String8; const rect:TRect;
const weights:TElementStateWeights; out box:TStyleBox); overload;
// Draw a resolved box: the shadow, the background (fill, shade, images), the border
procedure DrawStyleBox(const box:TStyleBox;
layers:TStyleBoxLayers=[TStyleBoxLayer.Shadow..TStyleBoxLayer.Border]);
// Resolve and draw the box with the inner block; returns the content rect. One call for a
// simple drawer
function DrawElementBox(element:TUIElement):TRect;
type
// Result of ResolveEmboss, exposed so custom UI drawers can share the default
// disabled appearance of captions, checkbox marks and other content.
// A transient value describing the fully disabled appearance: draw the offset
// highlight first, then the main content. The caller handles state transitions
// and explicit style overrides. Highlight offsets are screen pixels.
TUIEmbossStyle=record
color,shadowColor:cardinal;
shadowX,shadowY:single;
dimRGB:boolean; // light content keeps its coverage when darkened
end;
// Per-draw caption description returned by ResolveUITextStyle so custom drawers
// can reuse the default typography, text effects and state transitions. Resolve
// after updating the element's visual state, optionally adjust font/color/align,
// then pass this value and a screen-space text anchor/baseline to WriteUIText.
// Offsets are already in screen pixels; the font handle is borrowed. Re-resolve
// when style, state or UI scale changes.
TUITextStyle=record
font:TFontHandle;
color:cardinal;
align:TTextAlignment;
options:cardinal;
shadowColor:cardinal;
shadowX,shadowY:single;
ofsX,ofsY:single; // screen pixels
hover,pressed,disabled:single; // transition progress
disabledEmboss:boolean;
emboss:TUIEmbossStyle; // derived from content color before disabled dimming
end;
// Compute fully disabled emboss parameters from the original content color.
// surfaceColor is an optional known opaque solid background (0 = unknown).
// Use ResolveUITextStyle when element styles and state transitions are also needed.
function ResolveEmboss(baseColor:cardinal;surfaceColor:cardinal=0):TUIEmbossStyle;
// Retain the standard skin/focus/transitions while optionally replacing caption.
procedure DrawDefaultUI(element:TUIElement;drawButtonCaption:boolean=true);
// Build TUITextStyle for a custom caption drawer from the element's current
// styles/state weights and the caller's defaults. UpdateVisualState first
// (the normal DrawUIElement path does this before calling the drawer).
function ResolveUITextStyle(element:TUIElement;defColor:cardinal;
defAlign:TTextAlignment=taLeft;defOptions:cardinal=0;
defHoverColor:cardinal=0;defDisabledColor:cardinal=0;defPressOfsY:single=0):TUITextStyle;
// Draw a resolved TUITextStyle, including its offsets and shadow. x is the
// alignment anchor and y the baseline in screen pixels; targetWidth controls
// text layout, for example justification. The caller supplies any clipping.
procedure WriteUIText(const style:TUITextStyle;x,y:single;const text:String8;targetWidth:integer=0);
var
defaultBtnColor:cardinal=$FFB0A0C0;
implementation
uses Apus.Images, SysUtils, Types, Apus.Tweenings,
Apus.Colors, Apus.EventMan, Apus.Geom2D,
Apus.Engine.UIWidgets, Apus.Engine.UIMenu, Apus.Engine.UITable,
Apus.Engine.UIRender,
Apus.Engine.Style, // ParseStyleColor/Number for compound values (text-shadow)
Apus.Lib, Apus.Utils, Apus.Strings, Apus.Threads;
var
hintImage,tickImage:TTexture;
//imgHash:TObjectMap; // hash of loaded images: filename -> TTexture
// shared by the render threads of all windows: guarded by imageLock (a leaf lock,
// images are loaded outside it)
imageLock:TLock;
unsupportedImageSources:Strings8; // already reported to the log
fillImageSrc:Strings8; // url() images of fills (ResolveFillImage)
fillImageTex:array of TTexture;
threadvar
blendModeChanged:boolean; // per render thread: windows draw in their own threads
type
// Drawer memo of an element (state transitions are in element.visualState)
TContext=class
skinned:boolean; // set by the box path: a background-image was drawn this frame
destructor Destroy; override;
// Resolve a 'background-image' value to a texture. 'file:' textures are loaded once
// and memoized (the context holds one reference each); 'tex:' ones are looked up
// every call and never owned (the creator of a named texture keeps it alive)
function GetImage(const src:String8):TTexture;
private
imgSrc:array of String8; // memo: source string -> texture (small, linear)
imgTex:array of TTexture; // one reference per entry, released in the destructor
end;
function PrepareContext(element:TUIElement):TContext;
begin
if element.styleContext<>nil then begin
if element.styleContext is TContext then exit(TContext(element.styleContext));
element.StyleContext.Free;
end;
result:=TContext.Create;
element.styleContext:=result;
end;
procedure SetProperBlendMode(element:TUIElement);
begin
if transpBgnd and (element.shape<>TUIShape.shapeEmpty) then begin
gfx.target.BlendMode(blMove);
blendModeChanged:=true;
end;
end;
procedure RestoreBlendMode;
begin
if blendModeChanged then begin
gfx.target.BlendMode(blAlpha);
blendModeChanged:=false;
end;
end;
// styleinfo="00000000 11111111 22222222 33333333" - list of colors (hex)
{ function GetStyleColor(control:TUIElement;index:integer=0):cardinal;
var
i,v:integer;
begin
result:=0;
for i:=1 to length(control.styleinfo) do begin
if control.styleinfo[i]<'0' then begin
dec(index);
if index<0 then exit;
continue;
end;
if index=0 then begin
v:=(ord(control.styleinfo[i]) and $1F)-$10;
if v<0 then inc(v,25);
result:=result shl 4+v;
end;
end;
end;}
// Light content must cover the bright copy underneath instead of letting it shine
// through the body of each stroke. Dark content keeps the accepted fading behavior.
function DimEmbossColor(baseColor:cardinal;lightContent:boolean):cardinal;
const DIM_FACTOR:single=0.45;
begin
if lightContent then result:=Color.ScaleRGB(baseColor,DIM_FACTOR)
else result:=Color.Scale(baseColor,DIM_FACTOR);
end;
function ResolveEmboss(baseColor:cardinal;surfaceColor:cardinal):TUIEmbossStyle;
var brightness,strength,alpha:single;
function SmoothStrength(value,lowValue,highValue:single):single;
begin
result:=Clamp((value-lowValue)/(highValue-lowValue),0,1);
result:=result*result*(3-2*result);
end;
begin
brightness:=Color.Lightness(baseColor)/255;
alpha:=0.18+0.17*SmoothStrength(brightness,0.25,0.75);
// On a light surface the white rim needs more contrast, even for dark text.
if surfaceColor shr 24=$FF then begin
strength:=SmoothStrength(Color.Lightness(surfaceColor)/255,0.65,0.85);
alpha:=Lerp(alpha,0.95,strength);
end;
result.dimRGB:=brightness>=0.5;
result.color:=DimEmbossColor(baseColor,result.dimRGB);
if result.dimRGB then
// Keep the rim visibly lighter than the gray strokes without a near-white highlight.
result.shadowColor:=Color.Brighten(result.color,48)
else
result.shadowColor:=Color.Scale($FFFFFFFF,alpha*(baseColor shr 24)/255);
result.shadowX:=1; result.shadowY:=1;
end;
// Resolve only a known solid surface. Images, gradients, shades and translucent
// layers keep the content-color fallback rather than guessing their displayed color.
function EmbossSurfaceColor(element:TUIElement):cardinal;
var
fill,shade:TBlendedFill;
image:String8;
plainButton:boolean;
begin
result:=0;
while element<>nil do begin
image:=element.GetStyleValue('background-image');
if (image<>'') and not SameText(image,'none') then exit;
plainButton:=(element is TUIButton) and not (element is TUICheckBox) and
not (element is TUIComboBox) and not (element is TUIMenuItem);
// The procedural button skin includes a default fill and gradient shade.
if plainButton and ((element.GetStyleValue('fill')='') or
(element.GetStyleValue('fill-shade')='')) then exit;
shade:=element.GetBlendedStyleFill('fill-shade',TFill.None);
if not shade.IsEmpty then exit;
fill:=element.GetBlendedStyleFill('fill',TFill.None);
if not fill.IsSingle then exit;
case fill.fill.kind of
fkNone:;
fkSolid:begin
if fill.fill.stops[0].color shr 24=$FF then exit(fill.fill.stops[0].color);
if fill.fill.stops[0].color shr 24<>0 then exit;
end;
else exit;
end;
element:=element.parent;
end;
end;
type
// Content (text) style of an element, resolved for its current state.
// Offsets are screen pixels (logical style units multiplied by globalScale).
TTextStyle=TUITextStyle;
// Resolve the content keys for the element's current state: font, color, text-align,
// text-decoration, text-shadow, text-offset-x/y. Colors and offsets are tweened through
// the state values (like the box path); align, decoration and shadow switch instantly.
// defHoverColor/defDisabledColor - drawer defaults for those states (0 = keep the base
// color); defPressOfsY - default caption shift while pressed (data can override it).
function ResolveTextStyle(element:TUIElement;context:TContext;defColor:cardinal;
defAlign:TTextAlignment=taLeft;defOptions:cardinal=0;
defHoverColor:cardinal=0;defDisabledColor:cardinal=0;defPressOfsY:single=0):TTextStyle;
var
scale,cv:single;
surfaceColor:cardinal;
st:String8;
parts:Strings8;
i,n:integer;
procedure BlendColor(const state:String8;v:single;defC:cardinal);
begin
if v<=0 then exit;
if defC=0 then defC:=result.color;
result.color:=Color.Mix(result.color,element.GetStateStyleColor(state,'color',defC),v);
end;
procedure BlendOffset(const state:String8;v,defY:single);
begin
if v<=0 then exit;
result.ofsX:=Lerp(result.ofsX,element.GetStateStyleNumber(state,'text-offset-x',result.ofsX),v);
result.ofsY:=Lerp(result.ofsY,element.GetStateStyleNumber(state,'text-offset-y',result.ofsY+defY),v);
end;
begin
scale:=element.globalScale;
result.font:=element.StyleFont;
result.hover:=element.StateWeight(TElementState.Hover);
result.pressed:=element.StateWeight(TElementState.Pressed);
result.disabled:=element.StateWeight(TElementState.Disabled);
cv:=element.StateWeight(TElementState.Checked);
result.options:=defOptions;
result.shadowColor:=0;
result.shadowX:=1; result.shadowY:=1;
// Base values (states are blended in, so the base must ignore them)
result.color:=element.GetBaseStyleColor('color',defColor);
result.ofsX:=element.GetBaseStyleNumber('text-offset-x');
result.ofsY:=element.GetBaseStyleNumber('text-offset-y');
// priority order (TElementState); 'checked' looks pressed by default
BlendColor('hover',result.hover,defHoverColor);
BlendColor('checked',cv,0);
BlendColor('pressed',result.pressed,0);
st:=element.GetStyleValue('disabled-effect');
if (st='') and (element is TUIButton) then st:='emboss';
result.disabledEmboss:=SameText(st,'emboss');
surfaceColor:=0;
if result.disabledEmboss and (result.disabled>0) then surfaceColor:=EmbossSurfaceColor(element);
result.emboss:=ResolveEmboss(result.color,surfaceColor);
if result.disabledEmboss then begin
defDisabledColor:=result.emboss.color;
if result.disabled>0 then begin
result.options:=result.options and not toWithShadow;
result.shadowColor:=Color.Scale(result.emboss.shadowColor,result.disabled);
result.shadowX:=result.emboss.shadowX;
result.shadowY:=result.emboss.shadowY;
end;
end;
BlendColor('disabled',result.disabled,defDisabledColor);
BlendOffset('hover',result.hover,0);
BlendOffset('checked',cv,defPressOfsY);
BlendOffset('pressed',result.pressed,defPressOfsY);
BlendOffset('disabled',result.disabled,0);
// Alignment: the style overrides the drawer's default (e.g. TUILabel.align)
result.align:=defAlign;
st:=element.GetStyleValue('text-align');
if st<>'' then
if SameText(st,'left') then result.align:=taLeft else
if SameText(st,'center') then result.align:=taCenter else
if SameText(st,'right') then result.align:=taRight else
if SameText(st,'justify') then result.align:=taJustify;
// Decoration
st:=element.GetStyleValue('text-decoration');
if SameText(st,'underline') then result.options:=result.options or toUnderline else
if SameText(st,'none') then result.options:=result.options and not toUnderline;
// Shadow: '<color> [dx dy]' or 'none'; an explicit shadow replaces the built-in one
st:=element.GetStyleValue('text-shadow');
if st<>'' then begin
result.options:=result.options and not toWithShadow;
result.shadowColor:=0; // explicit 'none' also suppresses automatic emboss
if not SameText(st,'none') then begin
parts:=st.Split(' ');
n:=0;
for i:=0 to high(parts) do
if parts[i].Trim<>'' then begin
parts[n]:=parts[i].Trim; inc(n);
end;
if n>0 then result.shadowColor:=ParseStyleColor(ExpandToken(parts[0]));
if n>=3 then begin
result.shadowX:=ParseStyleNumber(parts[1]);
result.shadowY:=ParseStyleNumber(parts[2]);
end;
end;
end;
result.ofsX:=result.ofsX*scale;
result.ofsY:=result.ofsY*scale;
// Automatic emboss is a one-screen-pixel relief at every DPI. Explicit text-shadow
// offsets retain their documented logical units.
if (st<>'') or not result.disabledEmboss then begin
result.shadowX:=result.shadowX*scale;
result.shadowY:=result.shadowY*scale;
end;
end;
// Anchor point matching ts.align inside a horizontal span (x2 = inclusive right edge)
function AlignAnchor(const ts:TTextStyle;x1,x2:integer):single;
begin
case ts.align of
taRight:result:=x2;
taCenter:result:=(x1+x2)/2;
else result:=x1;
end;
end;
// Draw text with a resolved content style: offsets, shadow layer and options included.
// x matches ts.align (left edge / center / right edge), y is the baseline.
procedure WriteStyled(const ts:TTextStyle;x,y:single;const st:String32;targetWidth:integer=0); overload;
begin
x:=x+ts.ofsX; y:=y+ts.ofsY;
if ts.shadowColor<>0 then
txt.WriteW(ts.font,x+ts.shadowX,y+ts.shadowY,ts.shadowColor,st,ts.align,ts.options,targetWidth);
txt.WriteW(ts.font,x,y,ts.color,st,ts.align,ts.options,targetWidth);
end;
procedure WriteStyled(const ts:TTextStyle;x,y:single;const st:String8;targetWidth:integer=0); overload;
begin
x:=x+ts.ofsX; y:=y+ts.ofsY;
if ts.shadowColor<>0 then
txt.Write(ts.font,x+ts.shadowX,y+ts.shadowY,ts.shadowColor,st,ts.align,ts.options,targetWidth);
txt.Write(ts.font,x,y,ts.color,st,ts.align,ts.options,targetWidth);
end;
// Resolve an image reference used by style values and TUIImage.src:
// tex:<name> - registered texture (TTexture.FindByName); weak reference: the
// creator of the texture keeps it alive, nothing to free
// file:<name> - image file via LoadImage: the first user loads it, later users share
// the same texture; the caller owns one reference (FreeImage when done)
// none or '' - no image (e.g. to cancel an image set by a named style)
// Returns nil if the reference can't be resolved (yet). An unsupported source is
// reported to the log once per distinct value.
function ResolveStyleImage(const src:String8):TTexture;
var
i:integer;
begin
result:=nil;
if (src='') or SameText(src,'none') then exit;
if src.StartsWith('tex:',true) then
result:=TTexture(TTexture.FindByName(copy(src,5,200)))
else
if src.StartsWith('file:',true) then
LoadImage(result,copy(src,6,200))
else begin
imageLock.Enter;
try
for i:=0 to high(unsupportedImageSources) do
if unsupportedImageSources[i]=src then exit;
i:=length(unsupportedImageSources);
SetLength(unsupportedImageSources,i+1);
unsupportedImageSources[i]:=src;
finally
imageLock.Leave;
end;
Log.Warn('Unsupported image source: '+src);
end;
end;
// StyleImageResolver for 'url(...)' fills: textures are resolved once and kept for the
// lifetime of the program (ramps are small and shared by many elements)
function ResolveFillImage(const src:String8):TObject;
var
i,n:integer;
tex:TTexture;
begin
imageLock.Enter;
try
for i:=0 to high(fillImageSrc) do
if fillImageSrc[i]=src then exit(fillImageTex[i]);
finally
imageLock.Leave;
end;
tex:=ResolveStyleImage(src); // may load a file: not under the lock
if tex=nil then exit(nil);
imageLock.Enter;
try
// another thread may have resolved it meanwhile: keep the first one
for i:=0 to high(fillImageSrc) do
if fillImageSrc[i]=src then begin
if src.StartsWith('file:',true) then FreeImage(tex); // our own reference
exit(fillImageTex[i]);
end;
n:=length(fillImageSrc);
SetLength(fillImageSrc,n+1);
SetLength(fillImageTex,n+1);
fillImageSrc[n]:=src;
fillImageTex[n]:=tex;
result:=tex;
finally
imageLock.Leave;
end;
end;
procedure DrawUIElement(element:TUIElement;x1,y1,x2,y2:integer;context:TContext);
var
ts:TTextStyle;
begin
if (element.caption<>'') and (element.ClassType=TUIElement) then begin
ts:=ResolveTextStyle(element,context,$FF808080,taCenter,toWithShadow);
WriteStyled(ts,AlignAnchor(ts,x1,x2),(y1+y2)/2,Str32(element.caption));
end;
end;
procedure BuildSimpleHint(hnt:TUIHint);
var
lines:Strings8;
i,h,iWidth,iHeight,dw,lw:integer;
font:TFontHandle;
begin
font:=hnt.StyleFont;
if font=0 then font:=defaultHintFont;
if font=0 then font:=txt.GetFont('Default',7);
with hnt do begin
// line breaks: '~' or a literal '\n' sequence -> a real newline char.
hnt.simpleText:=StringReplace(hnt.simpleText,'\n',#10,[rfReplaceAll]);
hnt.simpleText:=StringReplace(hnt.simpleText,'~',#10,[rfReplaceAll]);
lines:=hnt.simpleText.Split(#10);
h:=round(txt.Height(font)*1.5);
iHeight:=h*length(lines)+9;
iWidth:=0;
for i:=0 to high(lines) do begin
lw:=txt.Measure(font,lines[i],toComplexText).Width; // SML-aware width via the real layout path
if iWidth<lw then iWidth:=lw;
end;
dw:=txt.Width(font,'M');
inc(iWidth,4+dw);
if (hintImage=nil) or (hintImage.width<>iWidth) or (hintImage.height<>iHeight) then begin
Log.Debug('[Re]alloc hint image');
if HintImage<>nil then FreeImage(HintImage);
hintImage:=AllocImage(iWidth,iHeight,pfRenderTargetAlpha,aiTexture+aiRenderTarget,'UI_HintImage');
if hintImage=nil then
raise EError.Create('Failed to alloc hint image!');
end;
size.Init(iWidth/globalScale,iHeight/globalScale);
gfx.BeginPaint(hintImage);
try
gfx.target.Mask(true,true); // may potentially break drawing of the following elements
gfx.target.Clear(0,-1,-1);
draw.FillGradrect(0,0,iwidth-3,iheight-3,$FFFFFFD0,$FFE0E0A0,true);
draw.Rect(0,0,iwidth-3,iheight-3,$FF000000);
// shadow
draw.Line(1,iHeight-2,iwidth-2,iheight-2,$50000000);
draw.Line(iwidth-2,iheight-2,iwidth-2,0.5,$50000000);
draw.Line(2,iHeight-1,iwidth-1,iheight-1,$28000000);
draw.Line(iwidth-1,iheight-2,iwidth-1,1.5,$28000000);
gfx.target.UnMask;
// rich text: SML markup ({B}, {C=...}, ...) is honored; default color $D0000000 unless overridden by {C=...}
for i:=0 to high(lines) do
txt.Write(font,1+dw div 2,round(2+h div 7+(i+0.75)*h),$D0000000,lines[i],taLeft,toComplexText);
finally
gfx.EndPaint;
end;
end;
end;
procedure AdjustHint(scrX,scrY:integer;hnt:TUIHint);
var
pnt:TVec2;
remainer:single;
begin
with hnt do begin
adjusted:=true;
pnt.x:=scrX+(5+size.x)*globalscale; // right side in screen coordinates
pnt.y:=scrY+(12+size.y)*globalScale; // bottom in screen coordinates
// Adjust Y
remainer:=window.canvasHeight-pnt.y;
if remainer<0 then begin
position.y:=position.y-size.y;
end else
position.y:=position.y+12;
// Adjust X
remainer:=window.canvasWidth-pnt.x;
if remainer<0 then begin
pnt.x:=scrX+remainer;
pnt:=parent.TransformFromScreen(pnt);
position.x:=pnt.x;
end else
position.x:=position.x+5;
end;
end;
procedure DrawUIHint(control:TUIHint;x1,y1,x2,y2:integer);
var
v:integer;
c:cardinal;
savePos:TVec2;
begin
with control as TUIHint do begin
if pfRenderTargetAlpha=ipfNone then exit;
if not adjusted then begin
// initialize hint contents before the first draw
Log.Debug('InitHint '+inttohex(UIntPtr(control),SizeOf(UIntPtr)*2));
if not active then try
BuildSimpleHint(control as TUIHint);
except
on e:exception do begin
Log.Msg('Failed to build simple hint - deleted');
control.flags.visible:=false;
exit;
end;
end;
// adjust the on-screen position (so it is always visible)
savePos:=position;
AdjustHint(x1,y1,control as TUIHint);
savePos.Sub(position);
inc(x1,round(savepos.x));
inc(y1,round(savepos.y));
control.globalRect:=control.GetPosOnScreen;
x1:=control.globalRect.Left;
y1:=control.globalRect.Top;
end;
if not hiding then
v:=(CoreTime.Ticks-created)*2
else begin
v:=256-(CoreTime.Ticks-created) div 2;
if v<=0 then begin
{FreeImage(HintImage);
HintImage:=nil;}
control.flags.visible:=false;
exit;
end;
end;
if hintImage=nil then begin
Log.Force('Hint has no image! '+inttohex(UIntPtr(control),SizeOf(UIntPtr)*2));
exit;
end;
if v>256 then v:=256;
c:=Color.Scale(clNeutral,v/256);
gfx.clip.Nothing;
draw.Image(x1,y1,HintImage,c);
gfx.clip.Restore;
end;
end;
procedure DrawUILabel(control:TUILabel;x1,y1,x2,y2:integer;context:TContext);
var
mY,targetWidth:integer;
wst:String32;
r:TRect;
ts:TTextStyle;
begin
// control.align is the default: 'text-align' in the style overrides it
ts:=ResolveTextStyle(control,context,$FF808080,control.align);
with control do begin
r:=GetClientPosOnScreen;
gfx.clip.Rect(r);
mY:=round((r.top+r.bottom)*0.5+txt.Height(ts.font)*0.45)-verticalOffset;
wst:=Str32(caption);
if ts.align=taJustify then targetWidth:=r.Width
else targetWidth:=0;
WriteStyled(ts,AlignAnchor(ts,r.left,r.Right-1),mY,wst,targetWidth);
gfx.clip.Restore;
end;
end;
procedure DrawUICheckbox(element:TUICheckbox;x1,y1,x2,y2:integer);
const
TICK_IMAGE = '20 1F ((((~SSS(SSS^SSSESSSDSSS_SSSBSSS &A(*-+&@(*+$&>(%$)*&=(*-$)*&=(*+$+*&=(*+$+*&=(*$)+*&<(%&()*'+
'&<(*-&()*&<(*,&()/*&;(*-&(),*&<(*&()-*&<(*&().*&<(*+&()*&<(*+&()*&1(&(*&+(*.&(),*&0(*/++,*&)(*,&()+*&0(*-&().*'+
'&((*&))*&1(.&*)/*#*+&(),*&1(*+&))+*(*-&().*&3(*+&)),%&))*&5(*&*)*&)),*&5(*,&))+&()+*&7(*&.)/*&7(*,&,).*&9(*&,)*'+
'&:(*,&*)!\SSS*&;(*&))+*&<(*.$)-*&>(*$-*&?(*.%&:(';
var
col,vColor,baseCol,baseTick,lightColor:cardinal;
font:TFontHandle;
d,y,yy,fontH,size,captionLeft:integer;
v,ss,tt,alpha,lightX,lightY:single;
context:TContext;
ts:TTextStyle;
inTransition:boolean;
begin
context:=element.styleContext as TContext;
baseCol:=element.GetBaseStyleColor('border-color',$FF808080);
ts:=ResolveTextStyle(element,context,baseCol);
ts.align:=taLeft;
// Explicit disabled colors take precedence over automatic emboss dimming.
col:=element.GetBlendedStyleColor('border-color',baseCol);
if ts.disabledEmboss and (element.GetStateStyleValue('disabled','border-color')='') then
col:=Color.Mix(col,DimEmbossColor(col,ts.emboss.dimRGB),ts.disabled);
if element.classType=TUICheckBox then baseTick:=Color.Add(baseCol,$808080)
else baseTick:=baseCol;
baseTick:=element.GetBlendedStyleColor('tick-color',baseTick);
if ts.disabledEmboss and (element.GetStateStyleValue('disabled','tick-color')='') then
baseTick:=Color.Mix(baseTick,DimEmbossColor(baseTick,ts.emboss.dimRGB),ts.disabled);
// The indicator shares the caption's derived highlight, unless explicitly overridden.
lightColor:=0;
if ts.disabled>0 then begin
if ts.disabledEmboss then lightColor:=ts.emboss.shadowColor;
lightColor:=Color.Scale(element.GetStyleColor('border-light',lightColor),ts.disabled);
end;
lightX:=ts.emboss.shadowX;
lightY:=ts.emboss.shadowY;
font:=ts.font;
fontH:=txt.Height(font);
y:=y2-round((y2-y1+1-fontH)/2);
size:=round(fontH*1.2);
inc(x1,round(size*0.3));
d:=round(size*0.15);
//
inTransition:=(element.visualState<>nil) and element.visualState.Animating(TElementState.Checked);
if element.classType=TUICheckBox then begin
vColor:=baseTick;
if lightColor shr 24<>0 then
draw.RoundRect(x1+lightX,y-size+d+lightY,x1+size+lightX,y+d+lightY,size*0.24,element.globalScale,lightColor,0);
draw.RoundRect(x1,y-size+d,x1+size,y+d,size*0.24,element.globalScale,col,0);
if tickImage=nil then tickImage:=CreateImageFrom(TICK_IMAGE,1);
if element.checked or inTransition then begin
alpha:=1; ss:=1.1;
if inTransition then begin // transition
tt:=element.StateWeight(TElementState.Checked);
if element.checked then begin
// appear
alpha:=splines.easeOut(tt,0,1,0.5,1);
ss:=Spline(tt, 0.5,3, 1.1,-1);
end else begin
// dissolve
alpha:=tt;
end;
end;
if lightColor shr 24<>0 then
draw.Centered(x1+size*0.65+lightX,y-size*0.4+lightY,ss*size/tickImage.height,tickImage,Color.Scale(lightColor,alpha));
draw.Centered(x1+size*0.65,y-size*0.4,ss*size/tickImage.height,tickImage,Color.Scale(vColor,alpha));
end;
end;
if element.ClassType=TUIRadioButton then begin
yy:=y-size+d;
if lightColor shr 24<>0 then
draw.RoundRect(x1+lightX,yy+lightY,x1+size+lightX,yy+size+lightY,size*0.5+1,element.globalScale,lightColor,0);
draw.RoundRect(x1,yy,x1+size,yy+size,size*0.5+1,element.globalScale,col,0);
if element.checked or inTransition then begin
alpha:=1;
v:=size*0.24;
if inTransition then begin // transition
tt:=element.StateWeight(TElementState.Checked);
if element.checked then begin
// appear
alpha:=tt;
v:=size*Spline(tt, 0.4,-0.8, 0.24,0.8);
end else begin
// dissolve
alpha:=tt;
v:=size*(0.24+tt*0.2);
end;
end;
vColor:=Color.Scale(baseTick,alpha);
if lightColor shr 24<>0 then
draw.RoundRect(x1+v+lightX,yy+v+lightY,x1+size-v+lightX,yy+size-v+lightY,size*0.5+1-v,1,
Color.Scale(lightColor,alpha),Color.Scale(lightColor,alpha));
draw.RoundRect(x1+v,yy+v,x1+size-v,yy+size-v,size*0.5+1-v,1,vColor,vColor);
end;
end;
// Caption
inc(x1,round(size*1.5));
// The gap before the caption also reserves room for an upper-left highlight.
captionLeft:=x1;
if (ts.shadowColor shr 24<>0) and (ts.shadowX<0) then inc(captionLeft,round(ts.shadowX));
gfx.clip.Rect(Rect(captionLeft,y1,x2,y2));
WriteStyled(ts,x1,y,element.caption);
gfx.clip.Restore;
if FocusedElement=element then
draw.Rect(x1,y1,x2,y2,col xor $808080);
end;
procedure DrawUIButton(control:TUIButton;x1,y1,x2,y2:integer;context:TContext;drawCaption:boolean);
var
localRect:TRect2;
captionRect:TRect;
mY:integer;
c,c2:cardinal;
hv,av,dv:single;
wst:String32;
ts:TTextStyle;
begin
with control do begin
hv:=StateWeight(TElementState.Hover);
av:=Max(StateWeight(TElementState.Pressed),StateWeight(TElementState.Checked));
dv:=StateWeight(TElementState.Disabled);
// The box (fill / fill-shade / background-image, state-blended) is drawn by the common
// box path. Procedural look adds bevel frames on top of it; a skin has them baked in.
if not context.skinned then begin
c:=control.GetBaseStyleColor('border-light',$60000000);
c2:=control.GetBaseStyleColor('border-dark',$80FFFFFF);
draw.ShadedRect(x1,y1,x2,y2,1,c,c2); // outer frame
if av>=1 then { pressed, no inner frame }
else if dv<1 then begin // enabled
c:=Color.Mix(control.GetBaseStyleColor('border-light',$A0FFFFFF),
control.GetStateStyleColor('hover','border-light',$A0FFFFFF),hv);
c2:=Color.Mix(control.GetBaseStyleColor('border-dark',$70000000),
control.GetStateStyleColor('hover','border-dark',$70000000),hv);
draw.ShadedRect(x1+1,y1+1,x2-1,y2-1,1,c,c2);
end else begin // disabled
c:=control.GetStateStyleColor('disabled','border-light',$A0FFFFFF);
c2:=control.GetStateStyleColor('disabled','border-dark',$70000000);
draw.ShadedRect(x1+1,y1+1,x2-1,y2-1,1,c,c2);
end;
// focus ring (a skin expresses focus via ':focused { background-image }')
if (FocusedElement=control) or
(default and ((FocusedElement=nil) or not (FocusedElement is TUIButton))) then
draw.Rect(x1-1,y1-1,x2+1,y2+1,$80FFFF80);
end;
// The caption and child widgets share the same client-content displacement.
// Explicit text-offset values remain an additional caption-only adjustment.
if drawCaption and (caption<>'') and
not SameText(control.GetStyleValue('caption-display'),'none') then begin
gfx.clip.Rect(Rect(x1+2,y1+2,x2-2,y2-2));
ts:=ResolveTextStyle(control,context,clBlack,taCenter,0,$FF300000);
localRect:=GetRect;
localRect.MoveBy(-scroll.X,-scroll.Y);
captionRect:=TransformToScreen(localRect).Rounded;
mY:=round((captionRect.Top+captionRect.Bottom-1)*0.5+txt.Height(ts.font)*0.45);
wSt:=Str32(caption);
WriteStyled(ts,AlignAnchor(ts,captionRect.Left,captionRect.Right-1),mY,wst);
gfx.clip.Restore;
end;
end;
end;
// Menu line: the box (hover = the current line) is drawn by the common path. Caption on the
// left, shortcut on the right in 'shortcut-color' (the text color by default; the text color
// anyway while highlighted or disabled)
procedure DrawUIMenuItem(item:TUIMenuItem;context:TContext);
var
r:TRect;
ts:TTextStyle;
y:integer;
begin
ts:=ResolveTextStyle(item,context,clBlack,taLeft);
r:=item.GetClientPosOnScreen;
y:=round((r.Top+r.Bottom-1)*0.5+txt.Height(ts.font)*0.45);
gfx.clip.Rect(item.GetPosOnScreen);
WriteStyled(ts,AlignAnchor(ts,r.Left,r.Right-1),y,item.caption);
if item.shortcut<>'' then begin
ts.align:=taRight;
ts.font:=item.ShortcutFont; // smaller by default, on the same baseline
ts.color:=Color.Mix(item.GetStyleColor('shortcut-color',ts.color),ts.color,
Max(item.StateWeight(TElementState.Hover),item.StateWeight(TElementState.Disabled)));
WriteStyled(ts,r.Right-1,y,item.shortcut);
end;
gfx.clip.Restore;
end;
procedure DrawUIMenuSeparator(sep:TUIMenuSeparator;x1,y1,x2,y2:integer);
var
d,y:integer;
begin
d:=round(4*sep.globalScale);
y:=(y1+y2) div 2;
draw.Line(x1+d,y,x2-d,y,sep.GetStyleColor('line-color',$60000000));
end;
procedure DrawUIFrame(control:TUIFrame;x1,y1,x2,y2:integer);
var
c1,c2:cardinal;
i:integer;
begin
c1:=control.GetStyleColor('border-color',clBlack);
c2:=control.GetStyleColor('border-dark',0); // 0 = flat frame
for i:=0 to round(control.padding.Left)-1 do begin
if c2=0 then draw.Rect(x1+i,y1+i,x2-i,y2-i,c1)
else draw.ShadedRect(x1+i,y1+i,x2-i,y2-i,1,c1,c2);
end;
end;
procedure DrawUIImage(control:TUIImage;x1,y1,x2,y2:integer;context:TContext);
type
TImageDrawProc=procedure(img:TUIImage);
var
tex:TTexture;
proc:TImageDrawProc;
begin
with control do begin
if src<>'' then begin
// SRC = procesure address?
if src.StartsWith('proc:',true) then begin
proc:=pointer(Conv.HexToInt(copy(src,6,20)));
proc(control);
exit;
end;
// SRC = event (must be immediate)
if src.StartsWith('event:',true) then begin
Signal(copy(src,7,200),PtrUInt(control));
exit;
end;
// SRC = image reference: 'tex:<name>' or 'file:<name>'
tex:=context.GetImage(src);
if tex<>nil then begin
draw.Scaled(x1,y1,x2-1,y2-1,tex,control.GetStyleColor('tint',clWhite));
end;
end;
end;
end;
// Window chrome (header, frame, caption). A skinned window (background-image) has its
// chrome painted by the artist, so only the box path draws it.
procedure DrawUIWindow(element:TUIWindow;x1,y1,x2,y2:integer;context:TContext);
var
c:cardinal;
ty:integer;
col:cardinal;
ts:TTextStyle;
begin
if context.skinned then exit;
col:=element.GetStyleColor('fill',$FFB0B0C0);
ts:=ResolveTextStyle(element,context,$FFFFFFD0,taCenter);
if ts.shadowColor=0 then ts.shadowColor:=$B0000000; // classic title shadow
with element do begin
// body: the common box path already drew 'fill' when the style defines it;
// draw the default body only for a style without 'fill' (avoids double blending)
if element.GetStyleValue('fill')='' then draw.FillRect(x1,y1,x2,y2,col);
if boundToWindow then exit; // the app draws the caption row of an OS window frame
if element.IsActiveWindow then c:=$FF8080E0 // current window
else c:=$FFB0B0B0;
c:=Color.Mix(col,c,128);
if resizeable then begin
draw.FillRect(x1,y1,x2,y1+header-1,c);
draw.FillRect(x1,y1+header,x1+wcFrameBorder-1,y2,c);
draw.FillRect(x2-wcFrameBorder+1,y1+header,x2,y2,c);
draw.FillRect(x1+wcFrameBorder,y2-wcFrameBorder+1,x2-wcFrameBorder,y2,c);
draw.ShadedRect(x1+wcFrameBorder-1,y1+header-1,x2-wcFrameBorder+1,y2-wcFrameBorder+1,1,$80000000,$80FFFFFF);
end else begin
draw.FillRect(x1,y1,x2,y1+header-1,c);
draw.ShadedRect(x1+3,y1+header-1,x2-3,y1+header,1,$80000000,$80FFFFFF);
end;
draw.ShadedRect(x1,y1,x2,y2,2,$C0FFFFFF,$C0000000);
gfx.clip.Rect(Rect(x1+2,y1+2,x2-2,y1+header-2));
ty:=y1+round(header*0.7);
WriteStyled(ts,AlignAnchor(ts,x1,x2),ty,caption);
gfx.clip.Restore;
end;
end;
procedure DrawUIScrollbar(element:TUIScrollbar;x1,y1,x2,y2:integer);
var
col,trackColor:cardinal;
size,width:integer;
scale,trackWidth,sliderWidth,hoverWidth,sliderRadius,f,hv:single;
sStyle:string8;
context:TContext;
sliderVisible,alignEnd:boolean;
r:TRect2;
begin
size:=x2-x1; width:=y2-y1;
if not element.horizontal then Swap(size,width);
// Calculate parameters
element.CalcSliderPos(element.GetStyleNumber('min-size',0.75));
sliderVisible:=(element.sliderEnd>element.sliderStart) and (element.sliderEnd-element.sliderStart<1);
// Draw
context:=TContext(element.styleContext);
sStyle:=element.GetStyleValue('variant','flat');
col:=element.GetStyleColor('color',$FFA8B0BC); // slider color
scale:=element.globalScale;
if SameText(sStyle,'flat') then begin
// Flat style. The widths may grow under the mouse (':hover { slider-width }'), dragging keeps
// them grown; with 'slider-align:end' a narrow slider and track hug the far edge
hv:=element.StateWeight(TElementState.Hover);
if hooked=element then hv:=1;
trackWidth:=element.GetBaseStyleNumber('track-width',1);
trackWidth:=Lerp(trackWidth,element.GetStateStyleNumber('hover','track-width',trackWidth),hv);
sliderWidth:=element.GetBaseStyleNumber('slider-width',0.9);
hoverWidth:=element.GetStateStyleNumber('hover','slider-width',sliderWidth);
sliderWidth:=Lerp(sliderWidth,hoverWidth,hv);
alignEnd:=SameText(element.GetStyleValue('slider-align','center'),'end');
sliderRadius:=element.GetStyleNumber('radius',0)*width*sliderWidth;
// Draw track
trackColor:=element.GetBaseStyleColor('track-color',Color.Scale(col,0.5));
trackColor:=Color.Mix(trackColor,element.GetStateStyleColor('hover','track-color',trackColor),hv);
r.Init(x1,y1,x2,y2);
if alignEnd then f:=1-trackWidth else f:=(1-trackWidth)/2;
if element.horizontal then begin
r.y1:=Lerp(y1,y2,f);
r.y2:=Lerp(y1,y2,f+trackWidth);
end else begin
r.x1:=Lerp(x1,x2,f);
r.x2:=Lerp(x1,x2,f+trackWidth);
end;
draw.FillRect(r.x1,r.y1,r.x2,r.y2,trackColor);
// Draw slider
if sliderVisible then begin
// slider rect: at the end it keeps the far side of the widest slider
if alignEnd then f:=(1+Max(sliderWidth,hoverWidth))/2-sliderWidth
else f:=(1-sliderWidth)/2;
if element.horizontal then begin
r.x1:=Lerp(x1,x2,element.sliderStart);
r.y1:=Lerp(y1,y2,f);
r.x2:=Lerp(x1,x2,element.sliderEnd);
r.y2:=Lerp(y1,y2,f+sliderWidth);
end else begin
r.x1:=Lerp(x1,x2,f);
r.y1:=Lerp(y1,y2,element.sliderStart);
r.x2:=Lerp(x1,x2,f+sliderWidth);
r.y2:=Lerp(y1,y2,element.sliderEnd);
end;
// col
if hooked=element then
col:=element.GetStyleColor('active-color',Color.Add(col,$404040)) // pressed/dragging
else if element.sliderUnder then
col:=element.GetStateStyleColor('hover','color',Color.Add(col,$202020)); // hover col