Debian Codegraph @

src/ui/castlecontrols_button.inc

raw
1 {%MainUnit castlecontrols.pas}
2 {
3 Copyright 2010-2023 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18
19 { Possible image placement for a button, see @link(TCastleButton.ImageLayout). }
20 TCastleButtonImageLayout = (ilTop, ilBottom, ilLeft, ilRight);
21
22 { Clickable button.
23
24 This is TCastleUserInterface descendant, so to use it just add it to
25 the TCastleWindow.Controls or TCastleControl.Controls list.
26 You will also usually want to adjust position (TCastleButton.Left,
27 TCastleButton.Bottom), TCastleButton.Caption,
28 and assign TCastleButton.OnClick (or ovevrride TCastleButton.DoClick). }
29 TCastleButton = class(TCastleUserInterfaceFont)
30 strict private
31 FCalculatedSize: Boolean;
32 { The only method that can access these is PreferredSize.
33 Everything else should use
34 RenderRect, EffectiveWidth, EffectiveHeight or other methods.
35 This makes sure that FCalculatedSize is honored. }
36 FCalculatedPreferredWidth, FCalculatedPreferredHeight: Single;
37 TextWidth, TextHeight: Single;
38 FOnClick: TNotifyEvent;
39 FCaption: String;
40 FAutoSize, FAutoSizeWidth, FAutoSizeHeight: boolean;
41 FPressed: boolean;
42 FImage,
43 FCustomBackgroundPressed,
44 FCustomBackgroundDisabled,
45 FCustomBackgroundFocused,
46 FCustomBackgroundNormal: TCastleImagePersistent;
47 FCustomColorPressed,
48 FCustomColorDisabled,
49 FCustomColorFocused,
50 FCustomColorNormal: TCastleColor;
51 FCustomBackground: boolean;
52 FCustomTextColor: TCastleColor;
53 FCustomTextColorUse: boolean;
54 FToggle: boolean;
55 ClickStarted: boolean;
56 ClickStartedPosition: TVector2;
57 ClickStartedFinger: TFingerIndex;
58 FMinImageWidth: Single;
59 FMinImageHeight: Single;
60 FImageLayout: TCastleButtonImageLayout;
61 FMinWidth, FMinHeight: Single;
62 FImageMargin: Single;
63 FPaddingHorizontal, FPaddingVertical: Single;
64 FTintPressed, FTintDisabled, FTintFocused, FTintNormal: TCastleColor;
65 FEnabled: boolean;
66 FEnableParentDragging: boolean;
67 FTextAlignment: THorizontalPosition;
68 FAlignment: THorizontalPosition;
69 FVerticalAlignment: TVerticalPosition;
70 FLineSpacing: Single;
71 FHtml: boolean;
72 FCaptionTranslate: Boolean;
73 FImageScale: Single;
74 { Make sure FCalculatedSize is true and if necessary
75 calculate TextWidth, TextHeight, FCalculatedPreferredWidth/Height. }
76 procedure CalculateSizeIfNecessary;
77 procedure SetCaption(const Value: String);
78 procedure SetAutoSize(const Value: boolean);
79 procedure SetAutoSizeWidth(const Value: boolean);
80 procedure SetAutoSizeHeight(const Value: boolean);
81 procedure SetCustomColorDisabled(const AValue: TCastleColor);
82 procedure SetCustomColorFocused(const AValue: TCastleColor);
83 procedure SetCustomColorNormal(const AValue: TCastleColor);
84 procedure SetCustomColorPressed(const AValue: TCastleColor);
85 procedure SetImageLayout(const Value: TCastleButtonImageLayout);
86 procedure SetMinWidth(const Value: Single);
87 procedure SetMinHeight(const Value: Single);
88 procedure SetImageMargin(const Value: Single);
89 procedure SetEnabled(const Value: boolean);
90 procedure SetTextAlignment(const Value: THorizontalPosition);
91 procedure SetLineSpacing(const Value: Single);
92 procedure SetHtml(const Value: boolean);
93 function GetTextToRender: TRichText;
94 procedure SetPaddingHorizontal(const Value: Single);
95 procedure SetPaddingVertical(const Value: Single);
96 procedure CustomBackgroundImageChanged(Sender: TObject);
97 procedure ImageChanged(Sender: TObject);
98 procedure SetImageScale(const Value: Single);
99 procedure SetAlignment(const Value: THorizontalPosition);
100 procedure SetVerticalAlignment(const Value: TVerticalPosition);
101 protected
102 procedure SetPressed(const Value: boolean); virtual;
103 procedure UIScaleChanged; override;
104 procedure PreferredSize(var PreferredWidth, PreferredHeight: Single); override;
105 function GetInternalText: String; override;
106 procedure SetInternalText(const Value: String); override;
107 procedure TranslateProperties(const TranslatePropertyEvent: TTranslatePropertyEvent); override;
108 public
109 const
110 DefaultImageMargin = 10;
111 DefaultPaddingHorizontal = 10;
112 DefaultPaddingVertical = 10;
113 DefaultLineSpacing = 2;
114 DefaultTextAlignment = hpMiddle;
115
116 constructor Create(AOwner: TComponent); override;
117 destructor Destroy; override;
118 procedure Render; override;
119 function Press(const Event: TInputPressRelease): boolean; override;
120 function Release(const Event: TInputPressRelease): boolean; override;
121 function Motion(const Event: TInputMotion): boolean; override;
122 procedure FontChanged; override;
123 procedure Update(const SecondsPassed: Single; var HandleInput: boolean); override;
124
125 { Internal: set FCalculatedSize to false,
126 to make sure TextWidth, TextWidth and FCalculatedPreferredWidth/Height are recalculated
127 at next PreferredSize. } { }
128 procedure VisibleChange(const Changes: TCastleUserInterfaceChanges;
129 const ChangeInitiatedByChildren: boolean = false); override;
130 procedure EditorAllowResize(out ResizeWidth, ResizeHeight: Boolean;
131 out Reason: String); override;
132 function PropertySections(const PropertyName: String): TPropertySections; override;
133
134 { Called when user clicks the button. In this class, simply calls
135 OnClick callback. }
136 procedure DoClick; virtual;
137 procedure SetFocused(const Value: boolean); override;
138
139 { Color tint when button is pressed (regardless if enabled or disabled). Opaque white by default. }
140 property TintPressed : TCastleColor read FTintPressed write FTintPressed;
141 { Color tint when button is disabled (and not pressed). Opaque white by default. }
142 property TintDisabled: TCastleColor read FTintDisabled write FTintDisabled;
143 { Color tint when button is focused. Opaque white by default. }
144 property TintFocused : TCastleColor read FTintFocused write FTintFocused;
145 { Color tint when button is enabled, but neither pressed nor focused. Opaque white by default. }
146 property TintNormal : TCastleColor read FTintNormal write FTintNormal;
147
148 { Text color to use if @link(CustomTextColorUse) is @true.
149 Black by default, just like @code(Theme.TextColor). }
150 property CustomTextColor: TCastleColor read FCustomTextColor write FCustomTextColor;
151
152 { Button colors used when @link(CustomBackground) is @true,
153 but CustomBackgroundXxx images (like @link(CustomBackgroundNormal))
154 are left empty.
155
156 By default they are all transparent black, so actually the button
157 is completely transparent in this case.
158
159 They are affected by tint (see @link(TintPressed), @link(TintDisabled),
160 @link(TintFocused), @link(TintNormal)). The tint color is simply multiplied
161 component-wise with these colors. By default all tint colors are
162 opaque white, so the multiplication by tint actually doesn't change anything.
163 }
164 property CustomColorPressed: TCastleColor read FCustomColorPressed write SetCustomColorPressed;
165 property CustomColorDisabled: TCastleColor read FCustomColorDisabled write SetCustomColorDisabled;
166 property CustomColorFocused: TCastleColor read FCustomColorFocused write SetCustomColorFocused;
167 property CustomColorNormal: TCastleColor read FCustomColorNormal write SetCustomColorNormal;
168 published
169 { Auto-size routines (see @link(AutoSize)) may treat the image
170 like always having at least these minimal sizes.
171 Even if the @link(Image) is empty (@nil).
172 This is useful when you have a row of buttons (typical for toolbar),
173 and you want them to have the same height, and their captions
174 to be displayed at the same level, regardless of their images sizes. }
175 property MinImageWidth: Single read FMinImageWidth write FMinImageWidth {$ifdef FPC}default 0{$endif};
176 property MinImageHeight: Single read FMinImageHeight write FMinImageHeight {$ifdef FPC}default 0{$endif};
177
178 { For multi-line @link(Caption), the horizontal alignment of the lines. }
179 property TextAlignment: THorizontalPosition
180 read FTextAlignment write SetTextAlignment default DefaultTextAlignment;
181
182 { Horizontal alignment of the text+image within button area,
183 useful in case you don't use @link(AutoSize).
184
185 We align text+image within the available area inside the button
186 (which is determined by button size, without paddings determined by @link(PaddingHorizontal),
187 @link(PaddingVertical)). }
188 property Alignment: THorizontalPosition
189 read FAlignment write SetAlignment default hpMiddle;
190
191 { Vertical alignment of the text+image within button area,
192 useful in case you don't use @link(AutoSize).
193
194 We align text+image within the available area inside the button
195 (which is determined by button size, without paddings determined by @link(PaddingHorizontal),
196 @link(PaddingVertical)). }
197 property VerticalAlignment: TVerticalPosition
198 read FVerticalAlignment write SetVerticalAlignment default vpMiddle;
199
200 { For multi-line @link(Caption), the extra spacing between lines.
201 May also be negative to squeeze lines tighter. }
202 property LineSpacing: Single read FLineSpacing write SetLineSpacing
203 {$ifdef FPC}default DefaultLineSpacing{$endif};
204
205 { Enable HTML tags in the @link(Caption).
206 This allows to easily change colors or use bold, italic text.
207
208 See the example examples/fonts/html_text.lpr and
209 examples/fonts/html_text_demo.html for a demo of what HTML tags can do.
210 See @link(TCastleAbstractFont.PrintStrings) documentation for a list of support HTML markup.
211
212 Note that to see the bold/italic font variants in the HTML markup,
213 you need to set the font to be TCastleFontFamily with bold/italic variants.
214 See the example mentioned above, examples/fonts/html_text.lpr,
215 for a code how to do it. }
216 property Html: boolean read FHtml write SetHtml default false;
217
218 { Use custom background images. If @true, we use properties
219 @unorderedList(
220 @item @link(CustomBackgroundPressed) (or fallback on @link(CustomBackgroundNormal) if empty),
221 @item @link(CustomBackgroundDisabled) (or fallback on @link(CustomBackgroundNormal) if empty),
222 @item @link(CustomBackgroundFocused) (or fallback on @link(CustomBackgroundNormal) if empty),
223 @item(@link(CustomBackgroundNormal) (or fallback on solid color if empty,
224 see @link(CustomColorPressed),
225 see @link(CustomColorNormal) and so on).)
226 )
227
228 They are affected by tint (see @link(TintPressed), @link(TintDisabled),
229 @link(TintFocused), @link(TintNormal)).
230 }
231 property CustomBackground: boolean read FCustomBackground write FCustomBackground default false;
232
233 { Optional image displayed on the button. }
234 property Image: TCastleImagePersistent read FImage;
235
236 { Scaling of @link(Image). }
237 property ImageScale: Single read FImageScale write SetImageScale {$ifdef FPC}default 1.0{$endif};
238
239 { Background image on the pressed button. See @link(CustomBackground) for details. }
240 property CustomBackgroundPressed: TCastleImagePersistent read FCustomBackgroundPressed;
241 { Background image on the disabled button. See @link(CustomBackground) for details. }
242 property CustomBackgroundDisabled: TCastleImagePersistent read FCustomBackgroundDisabled;
243 { Background image on the focused button. See @link(CustomBackground) for details. }
244 property CustomBackgroundFocused: TCastleImagePersistent read FCustomBackgroundFocused;
245 { Background image on the normal button. See @link(CustomBackground) for details. }
246 property CustomBackgroundNormal: TCastleImagePersistent read FCustomBackgroundNormal;
247
248 { Should we use custom text color in @link(CustomTextColor)
249 instead of @code(Theme.TextColor) or @code(Theme.DisabledTextColor). }
250 property CustomTextColorUse: boolean read FCustomTextColorUse write FCustomTextColorUse default false;
251
252 { Horizontal distance between text or @link(Image) and the button border. }
253 property PaddingHorizontal: Single
254 read FPaddingHorizontal write SetPaddingHorizontal {$ifdef FPC}default DefaultPaddingHorizontal{$endif};
255
256 { Vertical distance between text or @link(Image) and the button border. }
257 property PaddingVertical: Single
258 read FPaddingVertical write SetPaddingVertical {$ifdef FPC}default DefaultPaddingVertical{$endif};
259
260 { When AutoSize is @true (the default) then button sizes are automatically
261 calculated when you change the @link(Caption) and @link(Image).
262 The calculated size takes into account the @link(Caption) text size (with current font),
263 and @link(Image) size, plus some margin to make it look nice.
264
265 Width is auto-calculated only when AutoSize and AutoSizeWidth
266 (otherwise we use @link(Width), @link(WidthFraction) and similar properties).
267 Likewise, Height is calculated only when AutoSize and AutoSizeHeight
268 (otherwise we use @link(Height), @link(HeightFraction) and similar properties).
269 This way you can turn off auto-sizing in only one dimension if you
270 want (and when you don't need such flexibility, leave
271 AutoSizeWidth = AutoSizeHeight = @true and control both by simple
272 AutoSize).
273
274 If needed, you can query the resulting button size with the standard
275 TCastleUserInterface methods like @link(TCastleUserInterface.EffectiveWidth) and
276 @link(TCastleUserInterface.EffectiveHeight). Note that they may not be available
277 before the button is actually added to the container,
278 and the container size is initialized (we need to know the size of container,
279 for UI scaling to determine the font size). }
280 property AutoSize: boolean read FAutoSize write SetAutoSize default true;
281 property AutoSizeWidth: boolean read FAutoSizeWidth write SetAutoSizeWidth default true;
282 property AutoSizeHeight: boolean read FAutoSizeHeight write SetAutoSizeHeight default true;
283
284 { When auto-size is in effect, these properties may force
285 a minimal width/height of the button. This is useful if you want
286 to use auto-size (to make sure that the content fits inside),
287 but you want to force filling some space. }
288 property MinWidth: Single read FMinWidth write SetMinWidth {$ifdef FPC}default 0{$endif};
289 property MinHeight: Single read FMinHeight write SetMinHeight {$ifdef FPC}default 0{$endif};
290
291 property OnClick: TNotifyEvent read FOnClick write FOnClick;
292
293 { Caption to display on the button.
294 The text may be multiline (use the LineEnding or NL constants to mark newlines). }
295 property Caption: String read FCaption write SetCaption;
296
297 { Should the @link(Caption) be localized (translated into other languages).
298 Determines if the property is enumerated by @link(TCastleComponent.TranslateProperties),
299 which affects the rest of localization routines. }
300 property CaptionTranslate: Boolean read FCaptionTranslate write FCaptionTranslate default true;
301
302 { Can the button be permanently pressed. Good for making a button
303 behave like a checkbox, that is indicate a boolean state.
304 When @link(Toggle) is @true, you can set the @link(Pressed) property,
305 and the clicks are visualized a little differently. }
306 property Toggle: boolean read FToggle write FToggle default false;
307
308 { Is the button pressed down. If @link(Toggle) is @true,
309 you can read and write this property to set the pressed state.
310
311 When not @link(Toggle), this property isn't really useful to you.
312 The pressed state is automatically managed then to visualize
313 user clicks. In this case, you can read this property,
314 but you cannot reliably set it. }
315 property Pressed: boolean read FPressed write SetPressed default false;
316
317 { Where the @link(Image) is drawn on a button. }
318 property ImageLayout: TCastleButtonImageLayout
319 read FImageLayout write SetImageLayout default ilLeft;
320
321 { Distance between text and @link(Image). Unused if @link(Image) not set. }
322 property ImageMargin: Single read FImageMargin write SetImageMargin
323 {$ifdef FPC}default DefaultImageMargin{$endif};
324
325 { Enabled button can be focused and clicked, is not grayed-out. }
326 property Enabled: boolean read FEnabled write SetEnabled default true;
327
328 { Enable to drag a parent control, for example to drag a TCastleScrollView
329 that contains this button. To do this, you need to turn on
330 TCastleScrollView.EnableDragging, and set EnableParentDragging=@true
331 on all buttons inside. In effect, buttons will cancel the click operation
332 once you start dragging, which allows the parent to handle
333 all the motion events for dragging. }
334 property EnableParentDragging: boolean
335 read FEnableParentDragging write FEnableParentDragging default false;
336
337 {$define read_interface_class}
338 {$I auto_generated_persistent_vectors/tcastlebutton_persistent_vectors.inc}
339 {$undef read_interface_class}
340 end;
341
342 {$endif read_interface}
343
344 {$ifdef read_implementation}
345
346 { TCastleButton --------------------------------------------------------------- }
347
348 constructor TCastleButton.Create(AOwner: TComponent);
349 begin
350 inherited;
351
352 FAutoSize := true;
353 FAutoSizeWidth := true;
354 FAutoSizeHeight := true;
355 FImageLayout := ilLeft;
356 FImageMargin := DefaultImageMargin;
357 FPaddingHorizontal := DefaultPaddingHorizontal;
358 FPaddingVertical := DefaultPaddingVertical;
359 FTintPressed := White;
360 FTintDisabled := White;
361 FTintFocused := White;
362 FTintNormal := White;
363 FEnabled := true;
364 FLineSpacing := DefaultLineSpacing;
365 FTextAlignment := DefaultTextAlignment;
366 FCustomTextColor := Black;
367 FCaptionTranslate := true;
368 FImageScale := 1.0;
369 FAlignment := hpMiddle;
370 FVerticalAlignment := vpMiddle;
371
372 FImage := TCastleImagePersistent.Create;
373 FImage.OnChange := {$ifdef FPC}@{$endif}ImageChanged;
374 FCustomBackgroundPressed := TCastleImagePersistent.Create;
375 FCustomBackgroundPressed.OnChange := {$ifdef FPC}@{$endif}CustomBackgroundImageChanged;
376 FCustomBackgroundDisabled := TCastleImagePersistent.Create;
377 FCustomBackgroundDisabled.OnChange := {$ifdef FPC}@{$endif}CustomBackgroundImageChanged;
378 FCustomBackgroundFocused := TCastleImagePersistent.Create;
379 FCustomBackgroundFocused.OnChange := {$ifdef FPC}@{$endif}CustomBackgroundImageChanged;
380 FCustomBackgroundNormal := TCastleImagePersistent.Create;
381 FCustomBackgroundNormal.OnChange := {$ifdef FPC}@{$endif}CustomBackgroundImageChanged;
382
383 {$define read_implementation_constructor}
384 {$I auto_generated_persistent_vectors/tcastlebutton_persistent_vectors.inc}
385 {$undef read_implementation_constructor}
386 end;
387
388 destructor TCastleButton.Destroy;
389 begin
390 FreeAndNil(FImage);
391 FreeAndNil(FCustomBackgroundPressed);
392 FreeAndNil(FCustomBackgroundDisabled);
393 FreeAndNil(FCustomBackgroundFocused);
394 FreeAndNil(FCustomBackgroundNormal);
395
396 {$define read_implementation_destructor}
397 {$I auto_generated_persistent_vectors/tcastlebutton_persistent_vectors.inc}
398 {$undef read_implementation_destructor}
399 inherited;
400 end;
401
402 procedure TCastleButton.Render;
403 var
404 TextLeft, TextBottom: Single;
405
406 procedure RenderText;
407 var
408 TextColor: TCastleColor;
409 TextX, LineSpacingScaled: Single;
410 TextToRender: TRichText;
411 begin
412 if Enabled then
413 TextColor := Theme.TextColor else
414 TextColor := Theme.DisabledTextColor;
415 if CustomTextColorUse then
416 TextColor := CustomTextColor;
417
418 if (not Html) and (CharsPos([#10, #13], Caption) = 0) then
419 begin
420 { fast case: single line, and no need to use TRichText in this case }
421 Font.Print(TextLeft, TextBottom, TextColor, Caption);
422 end else
423 begin
424 { calculate TextX }
425 case TextAlignment of
426 hpLeft : TextX := TextLeft;
427 hpMiddle: TextX := TextLeft + TextWidth / 2;
428 hpRight : TextX := TextLeft + TextWidth;
429 {$ifndef COMPILER_CASE_ANALYSIS}
430 else raise EInternalError.Create('TCastleButton.Render: TextAlignment?');
431 {$endif}
432 end;
433
434 LineSpacingScaled := UIScale * LineSpacing;
435 TextToRender := GetTextToRender;
436 try
437 TextToRender.Print(TextX, TextBottom,
438 TextColor, LineSpacingScaled, TextAlignment);
439 finally FreeAndNil(TextToRender) end;
440 end;
441 end;
442
443 var
444 ImgLeft, ImgBottom, ImgScreenWidth, ImgScreenHeight: Single;
445 Background: TThemeImage;
446 CustomBackgroundImage: TCastleImagePersistent;
447 SR: TFloatRectangle;
448 ImageMarginScaled: Single;
449 UseImage, UseText: boolean;
450 Tint, SolidColor: TCastleColor;
451 RectForTextAndImage: TFloatRectangle;
452 begin
453 inherited;
454
455 CalculateSizeIfNecessary;
456
457 ImageMarginScaled := ImageMargin * UIScale;
458
459 SR := RenderRect;
460
461 { calculate Tint }
462 if Pressed then
463 Tint := TintPressed else
464 if not Enabled then
465 Tint := TintDisabled else
466 if Focused then
467 Tint := TintFocused else
468 Tint := TintNormal;
469
470 { calculate CustomBackgroundImage }
471 CustomBackgroundImage := nil;
472 if CustomBackground then
473 begin
474 if Pressed then
475 CustomBackgroundImage := FCustomBackgroundPressed
476 else
477 if not Enabled then
478 CustomBackgroundImage := FCustomBackgroundDisabled
479 else
480 if Focused then
481 CustomBackgroundImage := FCustomBackgroundFocused
482 else
483 CustomBackgroundImage := FCustomBackgroundNormal;
484 { instead of CustomBackgroundDisabled/Pressed/Focused, use Normal, if available }
485 if CustomBackgroundImage.Empty then
486 CustomBackgroundImage := FCustomBackgroundNormal;
487 { render using CustomBackgroundImage, if any }
488 if not CustomBackgroundImage.Empty then
489 begin
490 CustomBackgroundImage.DrawUiBegin(UIScale);
491 CustomBackgroundImage.Color := CustomBackgroundImage.Color * Tint;
492 CustomBackgroundImage.Draw(SR);
493 CustomBackgroundImage.DrawUiEnd;
494 end else
495 begin
496 if Pressed then
497 SolidColor := FCustomColorPressed
498 else
499 if not Enabled then
500 SolidColor := FCustomColorDisabled
501 else
502 if Focused then
503 SolidColor := FCustomColorFocused
504 else
505 SolidColor := FCustomColorNormal;
506 if SolidColor[3] <> 0 then
507 DrawRectangle(SR, SolidColor * Tint);
508 end;
509 end else
510 begin
511 if Pressed then
512 Background := tiButtonPressed
513 else
514 if not Enabled then
515 Background := tiButtonDisabled
516 else
517 if Focused then
518 Background := tiButtonFocused
519 else
520 Background := tiButtonNormal;
521 Theme.Draw(SR, Background, UIScale, Tint);
522 end;
523
524 UseImage := not FImage.Empty;
525 if UseImage then
526 begin
527 ImgScreenWidth := FImageScale * UIScale * FImage.Width;
528 ImgScreenHeight := FImageScale * UIScale * FImage.Height;
529 end else
530 begin
531 { Not really necessary,
532 but silence FPC 3.3.1 warnings that these are not initialized later. }
533 ImgScreenWidth := 0;
534 ImgScreenHeight := 0;
535 end;
536
537 { rectangle where we should display the text+image }
538 RectForTextAndImage := SR.Grow(
539 -PaddingHorizontal * UIScale,
540 -PaddingVertical * UIScale);
541
542 UseText := (Length(Caption) > 0);
543
544 if UseText then
545 begin
546 case Alignment of
547 hpLeft :
548 begin
549 TextLeft := RectForTextAndImage.Left;
550 Check(not (UseImage and (ImageLayout in [ilLeft, ilRight])), 'TODO: Alignment combined with this ImageLayout not implemented');
551 end;
552 hpRight:
553 begin
554 TextLeft := RectForTextAndImage.Right - TextWidth;
555 Check(not (UseImage and (ImageLayout in [ilLeft, ilRight])), 'TODO: Alignment combined with this ImageLayout not implemented');
556 end;
557 hpMiddle:
558 begin
559 TextLeft := RectForTextAndImage.Left + (RectForTextAndImage.Width - TextWidth) / 2;
560 if UseImage and (ImageLayout = ilLeft) then
561 TextLeft := TextLeft + ((ImgScreenWidth + ImageMarginScaled) / 2) else
562 if UseImage and (ImageLayout = ilRight) then
563 TextLeft := TextLeft - ((ImgScreenWidth + ImageMarginScaled) / 2);
564 end;
565 {$ifndef COMPILER_CASE_ANALYSIS}
566 else raise EInternalError.Create('TCastleButton.Render: Alignment?');
567 {$endif}
568 end;
569
570 case VerticalAlignment of
571 vpBottom:
572 begin
573 TextBottom := RectForTextAndImage.Bottom;
574 Check(not (UseImage and (ImageLayout in [ilBottom, ilTop])), 'TODO: Alignment combined with this ImageLayout not implemented');
575 end;
576 vpTop:
577 begin
578 TextBottom := RectForTextAndImage.Top - TextHeight;
579 Check(not (UseImage and (ImageLayout in [ilBottom, ilTop])), 'TODO: Alignment combined with this ImageLayout not implemented');
580 end;
581 vpMiddle:
582 begin
583 TextBottom := RectForTextAndImage.Bottom + (RectForTextAndImage.Height - TextHeight) / 2;
584 if UseImage and (ImageLayout = ilBottom) then
585 TextBottom := TextBottom + ((ImgScreenHeight + ImageMarginScaled) / 2) else
586 if UseImage and (ImageLayout = ilTop) then
587 TextBottom := TextBottom - ((ImgScreenHeight + ImageMarginScaled) / 2);
588 TextBottom := TextBottom + Font.DescenderHeight;
589 end;
590 {$ifndef COMPILER_CASE_ANALYSIS}
591 else raise EInternalError.Create('TCastleButton.Render: Alignment?');
592 {$endif}
593 end;
594
595 RenderText;
596 end else
597 begin
598 { Not really necessary,
599 but silence FPC 3.3.1 warnings that these are not initialized later. }
600 TextLeft := 0;
601 TextBottom := 0;
602 end;
603
604 if UseImage then
605 begin
606 ImgLeft := SR.Left + (SR.Width - ImgScreenWidth) / 2;
607 ImgBottom := SR.Bottom + (SR.Height - ImgScreenHeight) / 2;
608 if UseText then
609 begin
610 case ImageLayout of
611 ilLeft : ImgLeft := TextLeft - ImgScreenWidth - ImageMarginScaled;
612 ilRight : ImgLeft := TextLeft + TextWidth + ImageMarginScaled;
613 else ;
614 end;
615 case ImageLayout of
616 ilBottom : ImgBottom := TextBottom - ImgScreenHeight - ImageMarginScaled;
617 ilTop : ImgBottom := TextBottom + TextHeight + ImageMarginScaled;
618 else ;
619 end;
620 end;
621 FImage.DrawUiBegin(UIScale);
622 FImage.Draw(FloatRectangle(ImgLeft, ImgBottom, ImgScreenWidth, ImgScreenHeight));
623 FImage.DrawUiEnd;
624 end;
625 end;
626
627 function TCastleButton.Press(const Event: TInputPressRelease): boolean;
628 begin
629 Result := inherited;
630 if Result or (Event.EventType <> itMouseButton) then Exit;
631
632 if Enabled then
633 begin
634 Result := true;
635
636 if not Toggle then
637 begin
638 FPressed := true;
639 { We base our Render on Pressed value. }
640 VisibleChange([chRender]);
641 end;
642 // regardless of Toggle value, set ClickStarted, to be able to reach OnClick.
643 ClickStarted := true;
644 ClickStartedPosition := Event.Position;
645 ClickStartedFinger := Event.FingerIndex;
646 end;
647 end;
648
649 function TCastleButton.Release(const Event: TInputPressRelease): boolean;
650 begin
651 Result := inherited;
652 if Result or (Event.EventType <> itMouseButton) then Exit;
653
654 if ClickStarted and (ClickStartedFinger = Event.FingerIndex) then
655 begin
656 Result := true;
657
658 if not Toggle then FPressed := false;
659 ClickStarted := false;
660 { We base our Render on Pressed value. }
661 VisibleChange([chRender]);
662
663 { This is normal behavior of buttons: to click them, you have to make
664 mouse down on the button, and then release mouse while still over
665 the button.
666
667 We have to check CapturesEventsAtPosition, since (because we keep "focus"
668 on this button, if mouse down was on this) we *always* get release event
669 (even if mouse position is no longer over this button).
670
671 This is consistent with behaviors of other toolkits.
672 It means that if the user does mouse down over the button,
673 moves mouse out from the control, then moves it back inside,
674 then does mouse up -> it counts as a "click". }
675 if Enabled and CapturesEventsAtPosition(Event.Position) then
676 DoClick;
677 end;
678 end;
679
680 function TCastleButton.Motion(const Event: TInputMotion): boolean;
681
682 { Similar to Release implementation, but never calls DoClick. }
683 procedure CancelDragging;
684 begin
685 if not Toggle then FPressed := false;
686 ClickStarted := false;
687 { We base our Render on Pressed value. }
688 VisibleChange([chRender]);
689 { Without ReleaseCapture, the parent (like TCastleScrollView) would still
690 not receive the following motion events. }
691 Container.ReleaseCapture(Self);
692 end;
693
694 const
695 DistanceToHijackDragging = 20;
696 begin
697 Result := inherited;
698 if Result then Exit;
699
700 if ClickStarted and
701 (ClickStartedFinger = Event.FingerIndex) then
702 begin
703 if EnableParentDragging and
704 (PointsDistanceSqr(ClickStartedPosition, Event.Position) >
705 { scaling with UIScale is helpful. Scaling with physical size
706 would probably be even better, for mobiles. }
707 Sqr(DistanceToHijackDragging * UIScale)) then
708 begin
709 CancelDragging;
710 Exit(false); // drag not handled, pass to parent
711 end;
712
713 // drag handled, don't pass to others.
714 Exit(true);
715 end;
716 end;
717
718 procedure TCastleButton.Update(const SecondsPassed: Single;
719 var HandleInput: boolean);
720 begin
721 inherited;
722
723 if ClickStarted and HandleInput then
724 begin
725 // don't let others, like TCastleWalkNavigation, handle drag input to move.
726 // Testcase: physics_3d_demo, clicking on button should not cause accidental move.
727 HandleInput := false;
728 end;
729 end;
730
731 procedure TCastleButton.DoClick;
732 begin
733 if Assigned(OnClick) then
734 OnClick(Self);
735 end;
736
737 procedure TCastleButton.SetCaption(const Value: String);
738 begin
739 if Value <> FCaption then
740 begin
741 FCaption := Value;
742 { Note that actually recalculating size is deferred to CalculateSizeIfNecessary,
743 which will be called from Render or PreferredSize.
744 This way we will not recalculate button size e.g. when merely loading the design
745 from castle-user-interface file (which would be wasteful, as Container is not
746 assigned then, so Container.DefaultFont is unknown and calculation would likely
747 use a different font and be overridden anyway from FontChanged). }
748 VisibleChange([chRectangle]);
749 end;
750 end;
751
752 procedure TCastleButton.SetAutoSize(const Value: boolean);
753 begin
754 if Value <> FAutoSize then
755 begin
756 FAutoSize := Value;
757 VisibleChange([chRectangle]);
758 end;
759 end;
760
761 procedure TCastleButton.SetAutoSizeWidth(const Value: boolean);
762 begin
763 if Value <> FAutoSizeWidth then
764 begin
765 FAutoSizeWidth := Value;
766 VisibleChange([chRectangle]);
767 end;
768 end;
769
770 procedure TCastleButton.SetAutoSizeHeight(const Value: boolean);
771 begin
772 if Value <> FAutoSizeHeight then
773 begin
774 FAutoSizeHeight := Value;
775 VisibleChange([chRectangle]);
776 end;
777 end;
778
779 procedure TCastleButton.SetCustomColorDisabled(
780 const AValue: TCastleColor);
781 begin
782 if not TCastleColor.PerfectlyEquals(FCustomColorDisabled, AValue) then
783 begin
784 FCustomColorDisabled := AValue;
785 VisibleChange([chRender]);
786 end;
787 end;
788
789 procedure TCastleButton.SetCustomColorFocused(
790 const AValue: TCastleColor);
791 begin
792 if not TCastleColor.PerfectlyEquals(FCustomColorFocused, AValue) then
793 begin
794 FCustomColorFocused := AValue;
795 VisibleChange([chRender]);
796 end;
797 end;
798
799 procedure TCastleButton.SetCustomColorNormal(
800 const AValue: TCastleColor);
801 begin
802 if not TCastleColor.PerfectlyEquals(FCustomColorNormal, AValue) then
803 begin
804 FCustomColorNormal := AValue;
805 VisibleChange([chRender]);
806 end;
807 end;
808
809 procedure TCastleButton.SetCustomColorPressed(
810 const AValue: TCastleColor);
811 begin
812 if not TCastleColor.PerfectlyEquals(FCustomColorPressed, AValue) then
813 begin
814 FCustomColorPressed := AValue;
815 VisibleChange([chRender]);
816 end;
817 end;
818
819 procedure TCastleButton.FontChanged;
820 begin
821 inherited;
822 end;
823
824 procedure TCastleButton.CustomBackgroundImageChanged(Sender: TObject);
825 begin
826 VisibleChange([chRender]);
827 end;
828
829 procedure TCastleButton.ImageChanged(Sender: TObject);
830 begin
831 // this must do more than CustomBackgroundImageChanged, as changing Image affects button size
832 VisibleChange([chRectangle]);
833 end;
834
835 function TCastleButton.GetTextToRender: TRichText;
836 begin
837 Result := TRichText.Create(Font, Caption, Html);
838 end;
839
840 procedure TCastleButton.UIScaleChanged;
841 begin
842 inherited;
843 VisibleChange([chRectangle]);
844 end;
845
846 procedure TCastleButton.SetFocused(const Value: boolean);
847 begin
848 if Value <> Focused then
849 begin
850 if not Value then
851 begin
852 if not Toggle then FPressed := false;
853 ClickStarted := false;
854 end;
855
856 { We base our Render on Pressed and Focused value. }
857 VisibleChange([chRender]);
858 end;
859
860 inherited;
861 end;
862
863 procedure TCastleButton.SetTextAlignment(const Value: THorizontalPosition);
864 begin
865 if FTextAlignment <> Value then
866 begin
867 FTextAlignment := Value;
868 VisibleChange([chRender]);
869 end;
870 end;
871
872 procedure TCastleButton.SetLineSpacing(const Value: Single);
873 begin
874 if FLineSpacing <> Value then
875 begin
876 FLineSpacing := Value;
877 VisibleChange([chRectangle]);
878 end;
879 end;
880
881 procedure TCastleButton.SetPaddingHorizontal(const Value: Single);
882 begin
883 if FPaddingHorizontal <> Value then
884 begin
885 FPaddingHorizontal := Value;
886 VisibleChange([chRectangle]);
887 end;
888 end;
889
890 procedure TCastleButton.SetPaddingVertical(const Value: Single);
891 begin
892 if FPaddingVertical <> Value then
893 begin
894 FPaddingVertical := Value;
895 VisibleChange([chRectangle]);
896 end;
897 end;
898
899 procedure TCastleButton.SetHtml(const Value: boolean);
900 begin
901 if FHtml <> Value then
902 begin
903 FHtml := Value;
904 VisibleChange([chRectangle]);
905 end;
906 end;
907
908 procedure TCastleButton.SetPressed(const Value: boolean);
909 begin
910 if FPressed <> Value then
911 begin
912 { Allow to change Pressed always.
913 This is necessary for correct deserialization,
914 where Pressed may be deserialized
915 before Toggle is deserialized. }
916 // if not Toggle then
917 // raise Exception.Create('You cannot modify TCastleButton.Pressed value when Toggle is false');
918 FPressed := Value;
919 VisibleChange([chRender]);
920 end;
921 end;
922
923 procedure TCastleButton.SetImageLayout(const Value: TCastleButtonImageLayout);
924 begin
925 if FImageLayout <> Value then
926 begin
927 FImageLayout := Value;
928 VisibleChange([chRectangle]);
929 end;
930 end;
931
932 procedure TCastleButton.SetImageScale(const Value: Single);
933 begin
934 if FImageScale <> Value then
935 begin
936 FImageScale := Value;
937 VisibleChange([chRectangle]);
938 end;
939 end;
940
941 procedure TCastleButton.SetMinWidth(const Value: Single);
942 begin
943 if FMinWidth <> Value then
944 begin
945 FMinWidth := Value;
946 VisibleChange([chRectangle]);
947 end;
948 end;
949
950 procedure TCastleButton.SetMinHeight(const Value: Single);
951 begin
952 if FMinHeight <> Value then
953 begin
954 FMinHeight := Value;
955 VisibleChange([chRectangle]);
956 end;
957 end;
958
959 procedure TCastleButton.SetImageMargin(const Value: Single);
960 begin
961 if FImageMargin <> Value then
962 begin
963 FImageMargin := Value;
964 VisibleChange([chRectangle]);
965 end;
966 end;
967
968 procedure TCastleButton.SetEnabled(const Value: boolean);
969 begin
970 if FEnabled <> Value then
971 begin
972 FEnabled := Value;
973 VisibleChange([chRender]);
974 end;
975 end;
976
977 procedure TCastleButton.CalculateSizeIfNecessary;
978
979 procedure CalculateTextSize;
980 var
981 LineSpacingScaled: Single;
982 TextToRender: TRichText;
983 begin
984 if Font <> nil then
985 begin
986 if (not Html) and (CharsPos([#10, #13], Caption) = 0) then
987 begin
988 { fast case: single line, and no need to use TRichText in this case }
989 TextWidth := Font.TextWidth(Caption);
990 TextHeight := Font.Height;
991 end else
992 begin
993 LineSpacingScaled := UIScale * LineSpacing;
994 TextToRender := GetTextToRender;
995 try
996 TextWidth := TextToRender.Width;
997 TextHeight := TextToRender.Count * (Font.Height + LineSpacingScaled);
998 finally FreeAndNil(TextToRender) end;
999 end;
1000 end;
1001 end;
1002
1003 procedure CalculatePreferredSize;
1004 var
1005 ImgSize: Single;
1006 MinWidthScaled, MinHeightScaled,
1007 ImageMarginScaled,
1008 PaddingHorizontalScaled, PaddingVerticalScaled: Single;
1009 begin
1010 PaddingHorizontalScaled := PaddingHorizontal * UIScale;
1011 PaddingVerticalScaled := PaddingVertical * UIScale;
1012 ImageMarginScaled := ImageMargin * UIScale;
1013 MinWidthScaled := MinWidth * UIScale;
1014 MinHeightScaled := MinHeight * UIScale;
1015
1016 FCalculatedPreferredWidth := TextWidth + PaddingHorizontalScaled * 2;
1017 FCalculatedPreferredHeight := TextHeight + PaddingVerticalScaled * 2;
1018
1019 if (not FImage.Empty) or
1020 (MinImageWidth <> 0) or
1021 (MinImageHeight <> 0) then
1022 begin
1023 if not FImage.Empty then
1024 ImgSize := Max(FImage.Width, MinImageWidth) else
1025 ImgSize := MinImageWidth;
1026 ImgSize := FImageScale * ImgSize * UIScale;
1027 case ImageLayout of
1028 ilLeft, ilRight: FCalculatedPreferredWidth := FCalculatedPreferredWidth + ImgSize + ImageMarginScaled;
1029 ilTop, ilBottom: FCalculatedPreferredWidth := Max(FCalculatedPreferredWidth, ImgSize + PaddingHorizontalScaled * 2);
1030 end;
1031
1032 if not FImage.Empty then
1033 ImgSize := Max(FImage.Height, MinImageHeight) else
1034 ImgSize := MinImageHeight;
1035 ImgSize := FImageScale * ImgSize * UIScale;
1036 case ImageLayout of
1037 ilLeft, ilRight: FCalculatedPreferredHeight := Max(FCalculatedPreferredHeight, ImgSize + PaddingVerticalScaled * 2);
1038 ilTop, ilBottom: FCalculatedPreferredHeight := FCalculatedPreferredHeight + ImgSize + ImageMarginScaled;
1039 end;
1040 end;
1041
1042 { at the end apply MinXxx properties }
1043 MaxVar(FCalculatedPreferredWidth, MinWidthScaled);
1044 MaxVar(FCalculatedPreferredHeight, MinHeightScaled);
1045 end;
1046
1047 begin
1048 if not FCalculatedSize then
1049 begin
1050 FCalculatedSize := true;
1051 CalculateTextSize;
1052 CalculatePreferredSize;
1053 end;
1054 end;
1055
1056 procedure TCastleButton.PreferredSize(var PreferredWidth, PreferredHeight: Single);
1057 begin
1058 inherited;
1059
1060 CalculateSizeIfNecessary;
1061 Assert(FCalculatedSize);
1062
1063 if AutoSize and AutoSizeWidth then
1064 PreferredWidth := FCalculatedPreferredWidth;
1065 if AutoSize and AutoSizeHeight then
1066 PreferredHeight := FCalculatedPreferredHeight;
1067 end;
1068
1069 procedure TCastleButton.EditorAllowResize(
1070 out ResizeWidth, ResizeHeight: Boolean; out Reason: String);
1071 begin
1072 inherited;
1073 if AutoSize and AutoSizeWidth then
1074 begin
1075 ResizeWidth := false;
1076 Reason := SAppendPart(Reason, NL, 'Turn off "TCastleButton.AutoSize" or "TCastleButton.AutoSizeWidth" to change width.');
1077 end;
1078 if AutoSize and AutoSizeHeight then
1079 begin
1080 ResizeHeight := false;
1081 Reason := SAppendPart(Reason, NL, 'Turn off "TCastleButton.AutoSize" or "TCastleButton.AutoSizeHeight" to change height.');
1082 end;
1083 end;
1084
1085 procedure TCastleButton.VisibleChange(const Changes: TCastleUserInterfaceChanges;
1086 const ChangeInitiatedByChildren: boolean = false);
1087 begin
1088 inherited;
1089 // react to SetWidth, SetHeight etc.
1090 if [chRectangle, chChildren] * Changes <> [] then
1091 FCalculatedSize := false;
1092 end;
1093
1094 function TCastleButton.GetInternalText: String;
1095 begin
1096 Result := Caption;
1097 end;
1098
1099 procedure TCastleButton.SetInternalText(const Value: String);
1100 begin
1101 Caption := Value;
1102 end;
1103
1104 function TCastleButton.PropertySections(
1105 const PropertyName: String): TPropertySections;
1106 begin
1107 if (PropertyName = 'Caption') or
1108 (PropertyName = 'TextAlignment') or
1109 (PropertyName = 'Alignment') or
1110 (PropertyName = 'VerticalAlignment') or
1111 (PropertyName = 'LineSpacing') or
1112 (PropertyName = 'Html') or
1113 (PropertyName = 'TintPressed') or
1114 (PropertyName = 'TintDisabled') or
1115 (PropertyName = 'TintFocused') or
1116 (PropertyName = 'TintNormal') or
1117 (PropertyName = 'Image') or
1118 (PropertyName = 'ImageScale') or
1119 (PropertyName = 'ImageLayout') or
1120 (PropertyName = 'ImageMargin') or
1121 (PropertyName = 'CustomTextColorUse') or
1122 (PropertyName = 'CustomTextColorPersistent') or
1123 (PropertyName = 'Toggle') or
1124 (PropertyName = 'Pressed') or
1125 (PropertyName = 'Enabled') then
1126 Result := [psBasic]
1127 else if (PropertyName = 'AutoSize') or
1128 (PropertyName = 'AutoSizeWidth') or
1129 (PropertyName = 'AutoSizeHeight') or
1130 (PropertyName = 'PaddingHorizontal') or
1131 (PropertyName = 'PaddingVertical') then
1132 Result := [psBasic, psLayout]
1133 else
1134 Result := inherited PropertySections(PropertyName);
1135 end;
1136
1137 procedure TCastleButton.TranslateProperties(
1138 const TranslatePropertyEvent: TTranslatePropertyEvent);
1139 var
1140 S: String;
1141 begin
1142 if CaptionTranslate and (Caption <> '') then
1143 begin
1144 S := Caption;
1145 TranslatePropertyEvent(Self, 'Caption', S);
1146 Caption := S;
1147 end;
1148 end;
1149
1150 procedure TCastleButton.SetAlignment(const Value: THorizontalPosition);
1151 begin
1152 if FAlignment <> Value then
1153 begin
1154 FAlignment := Value;
1155 VisibleChange([chRender]);
1156 end;
1157 end;
1158
1159 procedure TCastleButton.SetVerticalAlignment(const Value: TVerticalPosition);
1160 begin
1161 if FVerticalAlignment <> Value then
1162 begin
1163 FVerticalAlignment := Value;
1164 VisibleChange([chRender]);
1165 end;
1166 end;
1167
1168 {$define read_implementation_methods}
1169 {$I auto_generated_persistent_vectors/tcastlebutton_persistent_vectors.inc}
1170 {$undef read_implementation_methods}
1171
1172 {$endif read_implementation}