Debian Codegraph @

src/ui/castleuicontrols_userinterface.inc

raw
1 {%MainUnit castleuicontrols.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 //type
20
21 { Basic user-interface class. All UI controls derive from this class,
22 overriding chosen methods to react to some events.
23
24 Every control can have children controls, see @link(Controls) and @link(ControlsCount).
25 Parent control is recorded inside the @link(Parent). A control
26 may only be a child of one other control --- that is, you cannot
27 insert to the UI hierarchy the same control multiple times.
28
29 Control may handle mouse/keyboard input, see @link(Press) and @link(Release)
30 methods.
31
32 Various methods return Boolean signalling if the input event is "handled".
33 Input events that are handled are not passed to subsequent controls.
34 This way we avoid 2 controls from reacting to the same mouse click,
35 key press etc. Return @true if something was done as a result of given input.
36
37 Every control also has a position and size and takes some rectangular space
38 on the container.
39
40 The position is controlled using a @link(Translation) that works relative
41 to the currently set anchors. You can change the position, adjusting
42 also anchor, using an utility method @link(Anchor): one overloaded version
43 of @link(Anchor) changes the horizontal position and anchors
44 (@link(HorizontalAnchorSelf), @link(HorizontalAnchorParent), @link(Translation Translation.X)),
45 the other overloaded version changes vertical position and anchors
46 (@link(VerticalAnchorSelf), @link(VerticalAnchorParent), @link(Translation Translation.Y)).
47 You can also change each individual property mentioned above.
48
49 The size is controlled using the @link(Width), @link(WidthFraction),
50 @link(Height), @link(HeightFraction), @link(FullSize), or @link(AutoSizeToChildren)
51 properties.
52
53 The size (before UI scaling is applied) can be queried using
54 @link(EffectiveWidth) and @link(EffectiveHeight) methods.
55 The rectangle where the control is visible (during rendering,
56 after applying UI scaling) can be queried using @link(RenderRect)
57 and @link(RenderRectWithBorder) methods.
58
59 Note that some descendants perform auto-sizing,
60 that is: their effective size follows some natural property of the control.
61 For example, @link(TCastleLabel) size by default follows the @link(TCastleLabel.Caption)
62 value, and ignores the explicit size set in @link(Width) and @link(Height).
63 You can turn off auto-sizing by @link(TCastleLabel.AutoSize),
64 to manually control the size using @link(Width) and @link(Height).
65
66 All the coordinates passed here should follow the Castle Game Engine
67 convention that (0, 0) is left-bottom window corner. }
68 TCastleUserInterface = class(TCastleComponent)
69 strict private
70 type
71 TEnumerator = record
72 private
73 FList: TInternalChildrenControls;
74 FPosition: Integer;
75 function GetCurrent: TCastleUserInterface; inline;
76 public
77 constructor Create(const AList: TInternalChildrenControls);
78 function MoveNext: Boolean; inline;
79 property Current: TCastleUserInterface read GetCurrent;
80 end;
81 var
82 FOnVisibleChange: TCastleUserInterfaceChangeEvent;
83 FContainer: TCastleContainer;
84 FLastSeenUIScale: Single;
85 FCursor: TMouseCursor;
86 {$ifdef FPC}
87 FOnCursorChange: TNotifyEvent;
88 FHasHorizontalAnchor: boolean;
89 FHasVerticalAnchor: boolean;
90 {$endif}
91 FExclusiveEvents: boolean;
92 FOnUpdate: TUiUpdateEvent;
93 FOnPress: TUiPressReleaseEvent;
94 FOnRelease: TUiPressReleaseEvent;
95 FOnMotion: TUiMotionEvent;
96 FVisible: Boolean;
97 FDisableContextOpenClose: Cardinal;
98 FFocused: boolean;
99 FGLInitialized: boolean;
100 FExists: boolean;
101 FControls: TInternalChildrenControls;
102 FLeft: Single;
103 FBottom: Single;
104 FHorizontalAnchorSelf, FHorizontalAnchorParent: THorizontalPosition;
105 FTranslation: TVector2;
106 FVerticalAnchorSelf, FVerticalAnchorParent: TVerticalPosition;
107 FEnableUIScaling: boolean;
108 FKeepInFront, FCapturesEvents: boolean;
109 FWidth, FHeight: Single;
110 FWidthFraction, FHeightFraction: Single;
111 FFullSize: boolean;
112 FBorder: TBorder;
113 FBorderColor: TCastleColor;
114 FAutoSizeToChildren: Boolean;
115 FAutoSizeToChildrenPaddingRight: Single;
116 FAutoSizeToChildrenPaddingTop: Single;
117 FSizeFromChildrenValid: Boolean;
118 FSizeFromChildrenWidth, FSizeFromChildrenHeight: Single;
119 FCachedRectWithoutAnchors: TFloatRectangle;
120 FUseCachedRectWithoutAnchors: Cardinal; // <> 0 if we should use FCachedRectWithoutAnchors
121 FInsideRectWithoutAnchors: Boolean;
122 FCulling: Boolean;
123 FClipChildren: Boolean;
124 FOnRender, FOnInternalMouseEnter, FOnInternalMouseLeave: TUiNotifyEvent;
125 FCustomTheme: TCastleTheme;
126 FCustomThemeObserver: TFreeNotificationObserver;
127 FTooltipControl: TCastleUserInterface;
128 FTooltipControlObserver: TFreeNotificationObserver;
129 FEditorSelectOnHover: Boolean;
130
131 procedure SerializeChildrenAdd(const C: TComponent);
132 procedure SerializeChildrenClear;
133 procedure SerializeChildrenEnumerate(const Proc: TGetChildProc);
134 procedure BorderChange(Sender: TObject);
135 procedure SetExists(const Value: boolean);
136 function GetControls(const I: Integer): TCastleUserInterface;
137 procedure SetControls(const I: Integer; const Item: TCastleUserInterface);
138 procedure CreateControls;
139 procedure SetAutoSizeToChildren(const Value: Boolean);
140 procedure SetAutoSizeToChildrenPaddingRight(const Value: Single);
141 procedure SetAutoSizeToChildrenPaddingTop(const Value: Single);
142
143 { This takes care of some internal quirks with saving Left property
144 correctly. (Because TComponent doesn't declare, but saves/loads a "magic"
145 property named Left during streaming. This is used to place non-visual
146 components on the form. Our Left is completely independent from this.) }
147 procedure ReadRealLeft(Reader: TReader);
148 procedure WriteRealLeft(Writer: TWriter);
149
150 procedure ReadLeft(Reader: TReader);
151 procedure ReadTop(Reader: TReader);
152 procedure WriteLeft(Writer: TWriter);
153 procedure WriteTop(Writer: TWriter);
154
155 { Support for deprecated properties }
156 procedure SetLeft(const Value: Single);
157 procedure SetBottom(const Value: Single);
158 function GetHorizontalAnchorDelta: Single;
159 function GetVerticalAnchorDelta: Single;
160 procedure SetHorizontalAnchorDelta(const Value: Single);
161 procedure SetVerticalAnchorDelta(const Value: Single);
162
163 procedure SetHorizontalAnchorSelf(const Value: THorizontalPosition);
164 procedure SetHorizontalAnchorParent(const Value: THorizontalPosition);
165 procedure SetVerticalAnchorSelf(const Value: TVerticalPosition);
166 procedure SetVerticalAnchorParent(const Value: TVerticalPosition);
167 procedure SetEnableUIScaling(const Value: boolean);
168 procedure SetTranslation(const Value: TVector2);
169
170 procedure SetFullSize(const Value: boolean);
171 procedure SetBorderColor(const Value: TCastleColor);
172 procedure SetWidthFraction(const Value: Single);
173 procedure SetHeightFraction(const Value: Single);
174 procedure SetCulling(const Value: Boolean);
175 procedure SetClipChildren(const Value: Boolean);
176 procedure SetWidth(const Value: Single);
177 procedure SetHeight(const Value: Single);
178 procedure SetCustomTheme(const Value: TCastleTheme);
179 procedure CustomThemeFreeNotification(const Sender: TFreeNotificationObserver);
180 procedure SetTooltipControl(const Value: TCastleUserInterface);
181 procedure TooltipControlFreeNotification(const Sender: TFreeNotificationObserver);
182
183 { Position and size of this control, assuming it exists,
184 in the local coordinates (relative to the parent 2D control,
185 although without anchors applied).
186
187 The implementation in this class follows the algorithm
188 documented at @link(EffectiveRect).
189
190 @unorderedList(
191 @item(@bold(This must ignore)
192 the current value of the @link(Exists) method
193 and @link(Exists) property, that is: the result of this function
194 assumes that control does exist.)
195
196 @item(@bold(This must ignore) the anchors. Their effect is applied
197 outside of this method, in RectWithAnchors.)
198
199 @item(@bold(This must take into account) UI scaling.
200 This method must calculate a result already multiplied by @link(UIScale).
201 )
202 )
203
204 @italic(Why float-based coordinates?)
205
206 Using the float-based rectangles and coordinates is better than integer
207 in case you use UI scaling (@link(TCastleContainer.UIScaling)).
208 It may sound counter-intuitive, but calculating everything using
209 floats results in more precision and better speed
210 (because we avoid various rounding in the middle of calculations).
211 Without UI scaling, it doesn't matter, use whichever ones are more
212 comfortable.
213
214 Using the float-based coordinates is also natural for animations. }
215 function RectWithoutAnchors: TFloatRectangle;
216 { Like @link(RectWithoutAnchors), but may be temporarily cached.
217 Inside TCastleUserInterface implementation, always use this instead
218 of calling RectWithoutAnchors. }
219 function FastRectWithoutAnchors: TFloatRectangle;
220 { Like @link(RectWithoutAnchors) but with anchors effect applied. }
221 function RectWithAnchors(
222 const CalculateEvenWithoutContainer: boolean = false): TFloatRectangle;
223 { How to translate local coordinates to the container.
224 Looks at our and parent's anchors (@link(Translation)) and positon (Left, Bottom).
225
226 As such it is useful to modify the children UI control position.
227
228 If you use UI scaling, this works in final coordinates
229 (after scaling, real pixels on screen). }
230 function LocalToContainerTranslation: TVector2;
231 { Like LocalToContainerTranslation but also add additional shift because of our Border. }
232 function LocalToContainerTranslationShiftBorder: TVector2;
233
234 procedure SetCursor(const Value: TMouseCursor);
235 //procedure SetParent(const Value: TCastleUserInterface);
236 private
237 FParent: TCastleUserInterface;
238 FLastSeenContainerWidth, FLastSeenContainerHeight: Integer;
239
240 { Show Name and ClassName for debug/log purposes. }
241 function DebugName: String;
242
243 { Recalculate UIScale property value, call UIScaleChanged if needed. }
244 procedure CheckUIScaleChanged;
245 { Recalculate FLastSeenContainerWidth/Height, call Resize if needed. }
246 procedure CheckResize;
247
248 protected
249 procedure Loaded; override;
250
251 { Call RecursiveRender on all children.
252 @exclude }
253 procedure InternalRenderLoop(const ViewportRect: TRectangle); virtual;
254
255 { Show and hide UI used to render tooltip (may come from user TooltipControl or some internal component).
256 @exclude }
257 procedure InternalSetTooltipExists(const Value: Boolean); virtual;
258
259 { Container sizes.
260 @groupBegin }
261 function ContainerWidth: Cardinal; virtual; deprecated 'arrange UI using anchors, FullSize and friends; if you really need container size, use "Container.UnscaledWidth" or "Container.PixelsWidth" after checking "Container <> nil"';
262 function ContainerHeight: Cardinal; virtual; deprecated 'arrange UI using anchors, FullSize and friends; if you really need container size, use "Container.UnscaledHeight" or "Container.PixelsHeight" after checking "Container <> nil"';
263 function ContainerRect: TRectangle; virtual; deprecated 'arrange UI using anchors, FullSize and friends; if you really need container size, use "Container.UnscaledRect" or "Container.PixelsRect" after checking "Container <> nil"';
264 function ContainerSizeKnown: boolean; virtual; deprecated 'arrange UI using anchors, FullSize and friends; if you really need container size, use "Container.UnscaledWidth/Height" or "Container.PixelsWidth/Height" after checking "Container <> nil"';
265 { @groupEnd }
266
267 {$ifdef FPC}
268 { Called when @link(Cursor) changed.
269 In TCastleUserInterface class, just calls OnCursorChange. }
270 procedure DoCursorChange; virtual;
271 deprecated 'better override VisibleChange and watch for chCursor in Changes';
272 {$endif}
273
274 procedure DefineProperties(Filer: TFiler); override;
275
276 procedure UIScaleChanged; virtual;
277
278 //procedure DoCursorChange; override;
279
280 { Controls that have a preferred size should override this.
281 By default this contains values derived from
282 @link(Width), @link(WidthFraction),
283 @link(Height), @link(HeightFraction), with @link(Border) subtracted.
284
285 Note that the arguments should be already scaled, i.e. multiplied by UIScale,
286 i.e. expressed in final device pixels.
287
288 Note that the returned PreferredWidth and PreferredHeight
289 must not include the space for @link(Border). Border size will be
290 added later. }
291 procedure PreferredSize(var PreferredWidth, PreferredHeight: Single); virtual;
292
293 { Called right before calculating size.
294 This is your only chance to adjust e.g. children size,
295 if you need them to be synchronized with something,
296 and you may use @link(AutoSizeToChildren).
297
298 In most use-cases, you rather adjust preferred size by overriding
299 @link(PreferredSize). }
300 procedure BeforeSizing; virtual;
301
302 procedure DoInternalMouseEnter; virtual;
303 procedure DoInternalMouseLeave; virtual;
304
305 { Theme that should be used by this control.
306 Either CustomTheme or global @link(Theme). }
307 function Theme: TCastleTheme;
308 public
309 const
310 DefaultWidth = 100.0;
311 DefaultHeight = 100.0;
312
313 constructor Create(AOwner: TComponent); override;
314 destructor Destroy; override;
315 procedure CustomSerialization(const SerializationProcess: TSerializationProcess); override;
316 function PropertySections(const PropertyName: String): TPropertySections; override;
317 procedure DesignerInfo(const SList: TStrings); override;
318 procedure DesignerWarnings(const SList: TStrings); override;
319 function GetEnumerator: TEnumerator;
320 procedure InternalSetContainer(const Value: TCastleContainer); virtual;
321
322 (*Override this method to react to user pressing a key, mouse button or mouse wheel.
323 Return @true if the event was handled,
324 which prevents from passing this event to other UI controls.
325
326 When implementing in descendants it is best to override it like this:
327
328 @longCode(#
329 function TMyControl.Press(const Event: TInputPressRelease): boolean;
330 begin
331 Result := inherited;
332 if Result then Exit; // exit if ancestor already handled this event
333
334 if Event.IsKey(keyEnter) then
335 begin
336 // do something in reaction to Enter key
337 ...
338 // let engine know that this input event was handled
339 Exit(true);
340 end;
341
342 if Event.IsMouseButton(buttonLeft) then
343 begin
344 // do something in reaction to left mouse button press
345 ...
346 // let engine know that this input event was handled
347 Exit(true);
348 end;
349 end;
350 #)
351
352 These events are generated for all UI controls, whether they are considered
353 "interactive" or not.
354 These events are generated for non-interactive controls
355 like @link(TCastleRectangleControl) or @link(TCastleLabel) as well.
356 For example, these events ignore the @link(TCastleButton.Enabled) state,
357 they are generated always (see https://github.com/castle-engine/castle-engine/issues/413 ).
358 Use instead @link(TCastleButton.OnClick) to detect clicks on a button in a way that honors
359 the @link(TCastleButton.Enabled) state.
360
361 When a control returns @true from @link(Press), it means it starts to "capture"
362 subsequent mouse events: subsequent mouse moves and release will be send
363 to this control even if mouse will move outside of this control.
364
365 The events Press and Release are passed to the parent only
366 after the children had a chance to process this event.
367 Overriding them makes sense if you draw something that "looks clickable"
368 in @link(TCastleUserInterface.Render), which is the standard place you should draw stuff.
369 For example our TCastleButton draws there.
370
371 In contrast, the events PreviewPress and PreviewRelease are passed first to
372 the parent control, before children have a chance to process this event.
373 In partcular, overriding them makes sense if you draw something that "looks clickable"
374 in @link(TCastleUserInterface.RenderOverChildren).
375 *)
376 function Press(const Event: TInputPressRelease): boolean; virtual;
377
378 { Override this method to react to user releasing a key, mouse button.
379 Return @true if the event was handled,
380 which prevents from passing this event to other UI controls.
381
382 This is counterpart to @link(Press) method.
383 See @link(Press) for more details.
384
385 Note: We'd like this method to also be called when user releases
386 a mouse wheel. But currently releasing of the mouse wheel
387 is not reported now by any backend.
388 Only releasing of keys and mouse buttons is reported.
389
390 @seealso Press }
391 function Release(const Event: TInputPressRelease): boolean; virtual;
392
393 { Similar to @link(Press) but allows the parent control to preview
394 the event before it is passed to children UI controls.
395
396 @seealso Press }
397 function PreviewPress(const Event: TInputPressRelease): boolean; virtual;
398
399 { Similar to @link(Release) but allows the parent control to preview
400 the event before it is passed to children UI controls.
401
402 @seealso Press }
403 function PreviewRelease(const Event: TInputPressRelease): boolean; virtual;
404
405 { Motion of mouse or touch. }
406 function Motion(const Event: TInputMotion): boolean; virtual;
407
408 { Rotation detected by 3D sensor.
409 Used for example by 3Dconnexion devices.
410
411 @param X X axis (tilt forward/backwards)
412 @param Y Y axis (rotate)
413 @param Z Z axis (tilt sidewards)
414 @param Angle Angle of rotation (in radians)
415 @param(SecondsPassed The time passed since last SensorRotation call.
416 This is necessary because some sensors, e.g. 3Dconnexion,
417 may *not* reported as often as normal @link(Update) calls.) }
418 function SensorRotation(const X, Y, Z, Angle: Double; const SecondsPassed: Single): boolean; virtual;
419
420 { Translation detected by 3D sensor.
421 Used for example by 3Dconnexion devices.
422
423 @param X X axis (move left/right)
424 @param Y Y axis (move up/down)
425 @param Z Z axis (move forward/backwards)
426 @param Length Length of the vector consisting of the above
427 @param(SecondsPassed The time passed since last SensorRotation call.
428 This is necessary because some sensors, e.g. 3Dconnexion,
429 may *not* reported as often as normal @link(Update) calls.) }
430 function SensorTranslation(const X, Y, Z, Length: Double; const SecondsPassed: Single): boolean; virtual;
431
432 { Axis movement detected by joystick.
433
434 @param JoyID ID of joystick with pressed button
435 @param Axis Number of moved axis }
436 function JoyAxisMove(const JoyID, Axis: Byte): boolean; virtual;
437 deprecated 'use event Joysticks.OnAxisMove, or just observe Joysticks[0].Axis';
438
439 { Joystick button pressed.
440
441 @param JoyID ID of joystick with pressed button
442 @param Button Number of pressed button }
443 function JoyButtonPress(const JoyID, Button: Byte): boolean; virtual;
444 deprecated 'use Joysticks.OnButtonDown or Joysticks.OnButtonPress';
445
446 { Control may do here anything that must be continuously repeated.
447 E.g. camera handles here falling down due to gravity,
448 rotating model in Examine mode, and many more.
449
450 @param(SecondsPassed Should be calculated like TFramesPerSecond.SecondsPassed,
451 and usually it's in fact just taken from TCastleWindow.Fps.SecondsPassed.)
452
453 This method may be used, among many other things, to continuously
454 react to the fact that user pressed some key (or mouse button).
455 For example, if holding some key should move some 3D object,
456 you should do something like:
457
458 @longCode(#
459 if HandleInput then
460 begin
461 if Container.Pressed[keyArrowRight] then
462 begin
463 Transform.Position := Transform.Position + Vector3(SecondsPassed * 10, 0, 0);
464 HandleInput := false;
465 end;
466 end;
467 #)
468
469 Instead of directly using a key code, consider also
470 using TInputShortcut that makes the input key nicely configurable.
471 See engine tutorial about handling inputs.
472
473 Multiplying movement by SecondsPassed makes your
474 operation frame-rate independent. Object will move by 10
475 units in a second, regardless of how many FPS your game has.
476
477 The code related to HandleInput is important if you write
478 a generally-useful control that should nicely cooperate with all other
479 controls, even when placed on top of them or under them.
480 The correct approach is to only look at pressed keys/mouse buttons
481 if HandleInput is @true. Moreover, if you did check
482 that HandleInput is @true, and you did actually handle some keys,
483 then you have to set @code(HandleInput := false).
484 This will prevent the other controls (behind the current control)
485 from handling the keys (they will get HandleInput = @false).
486 And this is important to avoid doubly-processing the same key press,
487 e.g. if two controls react to the same key, only the one on top should
488 process it.
489
490 Note that to handle a single press / release (like "switch
491 light on when pressing a key") you should rather
492 use @link(Press) and @link(Release) methods. Use this method
493 only for continuous handling (like "holding this key makes
494 the light brighter and brighter").
495
496 To understand why such HandleInput approach is needed,
497 realize that the "Update" events are called
498 differently than simple mouse and key events like "Press" and "Release".
499 "Press" and "Release" events
500 return whether the event was somehow "handled", and the container
501 passes them only to the controls under the mouse (decided by
502 @link(TCastleUserInterface.CapturesEventsAtPosition)). And as soon as some control says it "handled"
503 the event, other controls (even if under the mouse) will not
504 receive the event.
505
506 This approach is not suitable for Update events. Some controls
507 need to do the Update job all the time,
508 regardless of whether the control is under the mouse and regardless
509 of what other controls already did. So all controls (well,
510 all controls that exist, in case of TCastleUserInterface,
511 see TCastleUserInterface.Exists) receive Update calls.
512
513 So the "handled" status is passed through HandleInput.
514 If a control is not under the mouse, it will receive HandleInput
515 = @false. If a control is under the mouse, it will receive HandleInput
516 = @true as long as no other control on top of it didn't already
517 change it to @false. }
518 procedure Update(const SecondsPassed: Single;
519 var HandleInput: boolean); virtual;
520
521 { Called always when something important inside this control (or it's children)
522 changed. To be more precise, this is called when something mentioned among
523 the @link(TCastleUserInterfaceChange) enumerated items changed.
524
525 This is always called with Changes <> [] (non-empty set). }
526 procedure VisibleChange(const Changes: TCastleUserInterfaceChanges;
527 const ChangeInitiatedByChildren: boolean = false); overload; virtual;
528
529 { Called always when something important inside this control (or it's children)
530 changed. See @link(VisibleChange) for details about when and how this is called.
531
532 Be careful when handling this event. Various changes may cause this,
533 so be prepared to handle it at any moment, even in the middle when UI control
534 is changing. It may also occur very often.
535 It's usually safest to only set a boolean flag like
536 "something should be recalculated" when this event happens,
537 and do the actual recalculation later. }
538 property OnVisibleChange: TCastleUserInterfaceChangeEvent
539 read FOnVisibleChange write FOnVisibleChange;
540
541 { Allow window containing this control to suspend waiting for user input.
542 Typically you want to override this to return @false when you do
543 something in the overridden @link(Update) method.
544
545 In this class, this simply returns always @true.
546
547 @seeAlso TCastleWindow.AllowSuspendForInput }
548 function AllowSuspendForInput: boolean; virtual;
549
550 { Event called when the container (component or window with OpenGL context)
551 size changes.
552
553 You can resize/reposition your component here
554 to react to parent size changes.
555 This is called only when the rendering context of the container
556 is initialized, so you can be sure that this is called only between
557 GLContextOpen and GLContextClose.
558
559 We also call this once when inserting into the controls list
560 (like @link(TCastleWindow.Controls) or
561 @link(TCastleControl.Controls) or inside parent TCastleUserInterface),
562 if inserting into the container/parent
563 with already initialized OpenGL context. If inserting into the container/parent
564 without OpenGL context initialized, it will be called later,
565 when OpenGL context will get initialized, right after GLContextOpen.
566
567 In other words, this is always called to let the control know
568 the size of the container, if and only if the OpenGL context is
569 initialized. }
570 procedure Resize; virtual;
571
572 { Container of this control. When adding control to container's Controls
573 list (like TCastleWindow.Controls) container will automatically
574 set itself here, and when removing from container this will be changed
575 back to @nil.
576
577 May be @nil if this control is not yet inserted into any container. }
578 property Container: TCastleContainer read FContainer;
579
580 {$ifdef FPC}
581 { Event called when the @link(Cursor) property changes.
582 This event is, in normal circumstances, used by the Container,
583 so you should not use it in your own programs. }
584 property OnCursorChange: TNotifyEvent
585 read FOnCursorChange write FOnCursorChange;
586 deprecated 'use OnVisibleChange (or override VisibleChange) and watch for Changes that include chCursor';
587 {$endif}
588
589 { Should we disable further mouse / keys handling for events that
590 we already handled in this control. If @true, then our events will
591 return @true for mouse and key events handled.
592
593 This means that events will not be simultaneously handled by both this
594 control and some other (or camera or normal window callbacks),
595 which is usually more sensible, but sometimes somewhat limiting. }
596 property ExclusiveEvents: boolean
597 read FExclusiveEvents write FExclusiveEvents default true;
598 {$ifdef FPC} deprecated 'do not use this; supporting this property was complicated and had no real benefit; everything now works as if ExclusiveEvents=true, always'; {$endif}
599
600 property Controls [const Index: Integer]: TCastleUserInterface read GetControls write SetControls;
601 function ControlsCount: Integer;
602
603 { Add child control, at the front of other children. }
604 procedure InsertFront(const NewItem: TCastleUserInterface); overload;
605 procedure InsertFrontIfNotExists(const NewItem: TCastleUserInterface);
606 procedure InsertFront(const NewItems: TCastleUserInterfaceList); overload;
607
608 { Add child control, at the back of other children. }
609 procedure InsertBack(const NewItem: TCastleUserInterface); overload;
610 procedure InsertBackIfNotExists(const NewItem: TCastleUserInterface);
611 procedure InsertBack(const NewItems: TCastleUserInterfaceList); overload;
612
613 { Add child control at specified position.
614 It is usually easier to use @link(InsertFront) or @link(InsertBack),
615 if possible. }
616 procedure InsertControl(const Index: Integer; const NewItem: TCastleUserInterface);
617
618 { Remove control added by @link(InsertFront) or @link(InsertBack).
619
620 Note that this method @italic(does not) free the Item instance.
621 This method merely removes Item from our controls,
622 so that Item is no longer rendered as part of this parent.
623 It is still the caller's responsibility to make sure the Item is freed
624 at some point.
625
626 See https://castle-engine.io/modern_pascal_introduction.html#_freeing_classes
627 for description how to free instances in Pascal.
628 As TCastleUserInterface descends from TComponent, a simple and proper solution
629 is often just to create it with some "owner" (like @link(TCastleView.FreeAtStop) or @link(Application))
630 that will take care of freeing it. }
631 procedure RemoveControl(const Item: TCastleUserInterface);
632
633 { Index of child control, or -1 if not present. }
634 function IndexOfControl(const Item: TCastleUserInterface): Integer;
635
636 { Remove all child controls added by @link(InsertFront) or @link(InsertBack).
637
638 Note that, just like @link(RemoveControl), this method @italic(does not) free
639 the children controls. This method merely removes children controls,
640 so they are no longer rendered as part of the parent.
641 It is still the caller's responsibility to make sure the children controls
642 are freed at some point.
643
644 See https://castle-engine.io/modern_pascal_introduction.html#_freeing_classes
645 for description how to free instances in Pascal.
646 As TCastleUserInterface descends from TComponent, a simple and proper solution
647 is often just to create it with some "owner" (like @link(TCastleView.FreeAtStop) or @link(Application))
648 that will take care of freeing it. }
649 procedure ClearControls;
650
651 {$ifdef FPC}
652 property GetExists: Boolean read FExists; deprecated 'use Exists';
653 {$endif}
654
655 { Does this control capture events under this container position.
656 The default implementation simply checks whether Position
657 is inside @link(RenderRect).
658 It also checks whether @link(CapturesEvents) is @true.
659
660 Always treated like @false when Exists returns @false,
661 so the implementation of this method only needs to make checks assuming that
662 Exists = @true. }
663 function CapturesEventsAtPosition(const Position: TVector2): boolean; virtual;
664
665 { Prepare your resources, right before drawing.
666 Called only when @link(Exists) and GLInitialized.
667
668 @bold(Do not explicitly call this method.)
669 Instead, render controls by adding them to the
670 @link(TCastleContainer.Controls) list, or render them explicitly
671 (for off-screen rendering) by @link(TCastleContainer.RenderControl).
672 }
673 procedure BeforeRender; virtual;
674
675 { Render a control. Called only when @link(Exists) and render context is initialized.
676
677 @bold(Do not call this method.) It will be automatically called by the engine
678 when needed. It will be called when UI is part of @link(TCastleContainer.Controls) list
679 or rendered (e.g. for off-screen rendering) by @link(TCastleContainer.RenderControl).
680
681 You should only override this method.
682
683 See https://castle-engine.io/manual_2d_ui_custom_drawn.php for examples
684 what you can put here.
685
686 You can depend on some OpenGL state being set before calling this method.
687 You can depend on it being set, and you can carelessly change it.
688 This state we set:
689
690 @unorderedList(
691 @item(Viewport is set to include whole container.)
692
693 @item(Depth test is off.)
694
695 @item(For ancient fixed-function pipeline (see @link(TGLFeatures.RequestCapabilities)):
696
697 @unorderedList(
698 @item(The 2D orthographic projection is always set at the beginning.
699 Useful for 2D controls.)
700
701 @item(The modelview matrix is set to identity. The matrix mode
702 is always modelview.)
703
704 @item(The raster position is set to (0,0).
705 The (deprecated) WindowPos is also set to (0,0).)
706
707 @item(Texturing, lighting, fog is off.)
708 )
709 )
710 )
711
712 Beware that GLSL @link(TRenderContext.CurrentProgram RenderContext.CurrentProgram)
713 has undefined value when this is called.
714 You should always set it, before making direct OpenGL drawing calls
715 (all the engine drawing routines do it already, this is only a concern
716 if you make direct OpenGL / OpenGLES calls). }
717 procedure Render; virtual;
718
719 { Render a control contents @italic(over the children controls).
720 This is analogous to @link(Render), but it executes after children are drawn.
721 You should usually prefer to override @link(Render) instead of this method,
722 as the convention is that the parent is underneath children.
723
724 You should only override this method (do not call it, it will be called by the engine).
725
726 See https://castle-engine.io/manual_2d_ui_custom_drawn.php for examples
727 what you can put here. }
728 procedure RenderOverChildren; virtual;
729
730 { Render a tooltip of this control. If you want to have tooltip for
731 this control detected, you have to override TooltipExists.
732 Then the TooltipRender will be called.
733
734 TooltipRender is called in the same way as @link(Render).
735 TooltipRender is always called as a last (front-most) control.
736 Argument TooltipPosition is the left-bottom (in screen space, regardless of UIScaling)
737 suggested position of the tooltip.
738
739 It is simplest to descend from TCastleUserInterfaceFont,
740 that implements simple @link(TCastleUserInterfaceFont.Tooltip) property
741 and overrides these two methods as necessary.
742
743 @groupBegin }
744 function TooltipExists: Boolean; virtual; deprecated 'use TooltipControl to customize tooltip look';
745 procedure TooltipRender(const TooltipPosition: TVector2); virtual; deprecated 'use TooltipControl to customize tooltip look';
746 { @groupEnd }
747
748 { Initialize your OpenGL resources.
749
750 This is called when OpenGL context of the container is created,
751 or when the control is added to the already existing context.
752 In other words, this is the moment when you can initialize
753 OpenGL resources, like display lists, VBOs, OpenGL texture names, etc.
754
755 As an exception, this is called regardless of the Exists value.
756 This way a control can prepare it's resources, regardless if it exists now. }
757 procedure GLContextOpen; virtual;
758
759 { Destroy your OpenGL resources.
760
761 Called when OpenGL context of the container is destroyed.
762 Also called when controls is removed from the container
763 @code(Controls) list. Also called from the destructor.
764
765 You should release here any resources that are tied to the
766 OpenGL context. In particular, the ones created in GLContextOpen.
767
768 As an exception, this is called regardless of the Exists value.
769 This way a control can release it's resources, regardless if it exists now. }
770 procedure GLContextClose; virtual;
771
772 property GLInitialized: boolean read FGLInitialized default false;
773
774 { @exclude
775 This is dirty internal hack, and will be removed one day.
776 Please don't use this.
777
778 When non-zero, control will not receive GLContextOpen and
779 GLContextClose events when it is added/removed from the
780 @link(TCastleContainer.Controls) list.
781
782 This can be useful as an optimization, to keep the OpenGL resources
783 created even for controls that are not present on the
784 @link(TCastleContainer.Controls) list. @italic(This must used
785 very, very carefully), as bad things will happen if the actual OpenGL
786 context will be destroyed while the control keeps the OpenGL resources
787 (because it had DisableContextOpenClose > 0). The control will then
788 remain having incorrect OpenGL resource handles, and will try to use them,
789 causing OpenGL errors or at least weird display artifacts.
790
791 Most of the time, when you think of using this, you should instead
792 use the @link(TCastleUserInterface.Exists) property. This allows you to keep the control
793 of the @link(TCastleContainer.Controls) list, and it will be receive
794 GLContextOpen and GLContextClose events as usual, but will not exist
795 for all other purposes.
796
797 Using this mechanism is only sensible if you want to reliably hide a control,
798 but also allow readding it to the @link(TCastleContainer.Controls) list,
799 and then you want to show it again. This is useful for CastleInternalWindowModes,
800 that must push (and then pop) the controls, but then allows the caller
801 to modify the controls list. And some games, e.g. castle1, add back
802 some (but not all) of the just-hidden controls. For example the TCastleNotifications
803 instance is added back, to be visible even in the menu mode.
804 This means that CastleInternalWindowModes cannot just modify the TCastleContainer.Exists
805 value, leaving the control on the @link(TCastleContainer.Controls) list:
806 it would leave the TCastleUserInterface existing many times on the @link(TCastleContainer.Controls)
807 list, with the undefined TCastleContainer.Exists value. }
808 property DisableContextOpenClose: Cardinal
809 read FDisableContextOpenClose write FDisableContextOpenClose;
810
811 { Called when this control becomes or stops being focused,
812 that is: under the mouse cursor and will receive events.
813
814 This updates Focused property.
815 This also calls OnInternalMouseEnter / OnInternalMouseLeave. }
816 procedure SetFocused(const Value: boolean); virtual;
817
818 { See @link(SetFocused). }
819 property Focused: boolean read FFocused write SetFocused;
820
821 { Visual parent control. This control is rendered within the parent,
822 and it's anchors and coordinates are relative to the parent.
823 Parent may be @nil, which means that the @link(Container)
824 (if set) is our direct parent.
825
826 Note that this property doesn't have a setter, as it could be confusing:
827 the order in which children are inserted into parent sometimes matters,
828 for back-and-front order. If you want to change the parent, you can
829 use code like this:
830
831 @longCode(#
832 if Control.Parent <> nil then
833 Control.Parent.RemoveControl(Control);
834 if NewParent <> nil then
835 NewParent.InsertFront(Control); // or InsertBack, as InsertControl...
836 #) }
837 property Parent: TCastleUserInterface read FParent {write SetParent};
838
839 { Control position and size.
840 Use this to base other controls size/position on this control's
841 calculated size/position.
842
843 The algorithm that determines control position and size is like this:
844
845 @unorderedList(
846 @item(
847 When @link(AutoSizeToChildren) is @true:
848
849 The control size is adjusted to children, to surround them.
850 @link(Left) and @link(Bottom) and our anchors still matter,
851 but our @link(Width) and @link(Height) do not matter.
852 See the @link(AutoSizeToChildren) documentation for details.
853 )
854
855 @item(
856 Otherwise, when @link(FullSize) is @true:
857
858 The control always fills the whole parent.
859 If the control is added directly to the container,
860 it will fill the whole container (TCastleWindow or TCastleControl).
861 )
862 @item(
863 Otherwise (when @link(FullSize) and @link(AutoSizeToChildren)
864 are both @false):
865
866 The position and size of the control is determined by
867 the @link(Left), @link(Bottom), @link(Width), @link(Height) properties.
868
869 Moreover, @link(WidthFraction), if non-zero, specifies the control width
870 as a fraction of the parent width. E.g. WidthFraction = 1.0 means that width
871 equals parent, 0.5 means it's half the width of the parent etc.
872 In this case the explicit @link(Width) is ignored.
873
874 Similarly you can use @link(HeightFraction) to express height as a fraction of parent.
875 When @link(HeightFraction) is not zero, then
876 the explicit @link(Height) is ignored.
877
878 If at least one of the resulting sizes is zero, the rectangle is empty
879 (it is @link(TFloatRectangle.Empty)).
880 )
881 )
882
883 The above describes the size of the @italic(content and border, summed).
884 The content itself may be a little smaller, when the @link(Border) is
885 used. The size of the "content itself" is returned
886 only by @code(RenderRect) (in already-scaled coordinates,
887 i.e. using final device pixels).
888
889 The anchors (see @link(Anchor)) also affect the final position of the control.
890
891 Note that some descendants do @italic(auto-sizing) by default.
892 This means that some of these properties may be ignored,
893 and instead the calculated size (EffectiveWidth, EffectiveHeight)
894 depends on some core values of the control.
895
896 For example:
897
898 @unorderedList(
899 @item TCastleImageControl adjusts to image (unless you set @link(TCastleImageControl.Stretch) to @true),
900 @item TCastleLabel adjusts to caption (unless you set @link(TCastleLabel.AutoSize) to @false),
901 @item TCastleButton adjusts to caption and icon (unless you set @link(TCastleButton.AutoSize) to @false),
902 @item TCastleVerticalGroup adjusts to children sizes,
903 @item ... and so on.
904 )
905
906 Consult the documentation of each descendant for the exact
907 specification of the size behavior.
908
909 This method returns the rectangle in local coordinates
910 (relative to the parent 2D control).
911 The returned rectangle size includes the border size.
912 The returned rectangle size uses "unscaled" coordinates,
913 which means that they correspond to the sizes you set e.g. in
914 @link(TCastleUserInterface.Width),
915 @link(TCastleUserInterface.Height), and translation units you use with
916 e.g. @link(TCastleUserInterface.Anchor).
917
918 If you're looking for a way to query the size of the control
919 in final scaled coordinates (in real device pixels), and not relative
920 to the parent position, use @link(RenderRect)
921 or @link(RenderRectWithBorder) instead.
922
923 This method ignores the current value of the @link(Exists) method
924 and @link(Exists) property, that is: the result of this function
925 assumes that control does exist.
926
927 @seealso TCastleUserInterface.EffectiveWidth
928 @seealso TCastleUserInterface.EffectiveHeight
929 }
930 function EffectiveRect: TFloatRectangle;
931
932 { Calculated width of the control, without UI scaling.
933 Useful if you want to base other controls size/position on this control
934 calculated size.
935
936 Unlike the @link(Width) property,
937 this is the @italic(effective) size, not the desired size.
938 So this is already processed by any auto-sizing mechanism
939 (e.g. TCastleImageControl may adjust it's own size to the underlying image,
940 depending on settings), it is changed by @link(FullSize) and so on.
941
942 It is always equal to just @code(EffectiveRect.Width).
943 It is 0 when EffectiveRect is empty.
944
945 @seealso EffectiveRect }
946 function EffectiveWidth: Single;
947
948 { Calculated height of the control, without UI scaling.
949 Useful if you want to base other controls size/position on this control
950 calculated size.
951
952 Unlike the @link(Height) property,
953 this is the @italic(effective) size, not the desired size.
954 So this is already processed by any auto-sizing mechanism
955 (e.g. TCastleImageControl may adjust it's own size to the underlying image,
956 depending on settings), it is changed by @link(FullSize) and so on.
957
958 It is always equal to just @code(EffectiveRect.Height).
959 It is 0 when EffectiveRect is empty.
960
961 @seealso EffectiveRect }
962 function EffectiveHeight: Single;
963
964 { @link(EffectiveWidth) without @link(Border) size. }
965 function EffectiveWidthForChildren: Single;
966 { @link(EffectiveHeight) without @link(Border) size. }
967 function EffectiveHeightForChildren: Single;
968
969 function CalculatedWidth: Cardinal; deprecated 'use EffectiveWidth';
970 function CalculatedHeight: Cardinal; deprecated 'use EffectiveHeight';
971 function CalculatedRect: TRectangle; deprecated 'use EffectiveRect';
972
973 { Position and size of this control, assuming it exists, in container
974 coordinates (in final device pixels).
975 The primary use of this is inside @link(Render).
976 A proper UI control should adjust to draw precisely in this rectangle. }
977 function RenderRect: TFloatRectangle;
978 function RenderRectWithBorder: TFloatRectangle;
979
980 function ScreenRect: TRectangle; deprecated 'use RenderRect';
981
982 { Convert position relative to container (in final device coordinates, without UI scaling, by default)
983 into position relative to this UI control (in coordinates with UI scaling).
984 Useful e.g. to convert mouse/touch position from
985 @link(TInputPressRelease.Position) into position useful for children
986 of this UI control.
987
988 The exact definition is that using the result of this to set our child
989 @link(Translation), assuming the child is anchored to the left-bottom (the default state)
990 and child has Left = Bottom = 0, sets child position exactly to
991 the indicated point on the container.
992
993 @param(ContainerPositionScaled
994 If @true (default) then the container position (the ContainerPosition parameter)
995 is assumed to be in final device pixels,
996 i.e. the window area in X is from 0 to @link(TCastleContainer.Width),
997 in Y from 0 and @link(TCastleContainer.Height).
998 This is useful when the parameter comes e.g. from @link(TInputPressRelease.Position).
999
1000 If @false then the container position (the ContainerPosition parameter)
1001 is assumed to be in unscaled device pixels,
1002 i.e. the window area in X is from 0 to @link(TCastleContainer.UnscaledWidth),
1003 in Y from 0 and @link(TCastleContainer.UnscaledHeight).
1004 )
1005 }
1006 function ContainerToLocalPosition(ContainerPosition: TVector2;
1007 const ContainerPositionScaled: Boolean = true): TVector2;
1008
1009 { Convert position relative to this UI control (in coordinates with UI scaling)
1010 into relative to container (in final device coordinates, without UI scaling, by default).
1011 Reverses @link(ContainerToLocalPosition).
1012
1013 @param(ContainerPositionScaled
1014 If @true (default) then the container position (the result of this method)
1015 is assumed to be in final device pixels,
1016 i.e. the window area in X is from 0 to @link(TCastleContainer.Width),
1017 in Y from 0 and @link(TCastleContainer.Height).
1018
1019 If @false then the container position (the result of this method)
1020 is assumed to be in unscaled device pixels,
1021 i.e. the window area in X is from 0 to @link(TCastleContainer.UnscaledWidth),
1022 in Y from 0 and @link(TCastleContainer.UnscaledHeight).
1023 )
1024 }
1025 function LocalToContainerPosition(const LocalPosition: TVector2;
1026 const ContainerPositionScaled: Boolean = true): TVector2;
1027
1028 { Rectangle filling the parent control (or container), in local coordinates.
1029 Since this is in local coordinates, the returned rectangle Left and Bottom
1030 are always zero, unless parent has Border (the returned rectangle
1031 is shrunk by Parent.Border).
1032 This is already scaled by UI scaling. }
1033 function ParentRect: TFloatRectangle;
1034
1035 { Adjust position to align us with the parent horizontally.
1036 The resulting @link(EffectiveRect) and @link(RenderRect) and @link(RenderRectWithBorder)
1037 will immediately reflect the new position.
1038
1039 Note that position set here (anchors, @link(Translation))
1040 are ignored when @link(FullSize) is set to true.
1041 In case of @link(FullSize), the control fills the parent perfectly.
1042
1043 This utility method sets @link(HorizontalAnchorSelf), @link(HorizontalAnchorParent),
1044 @link(Translation Translation.X). }
1045 procedure Anchor(const AHorizontalAnchor: THorizontalPosition;
1046 const TranslationX: Single = 0); overload;
1047
1048 { Adjust position to align us with the parent horizontally.
1049 The resulting @link(EffectiveRect) and @link(RenderRect) and @link(RenderRectWithBorder)
1050 will immediately reflect the new position.
1051
1052 Note that position set here (anchors, @link(Translation))
1053 are ignored when @link(FullSize) is set to true.
1054 In case of @link(FullSize), the control fills the parent perfectly.
1055
1056 This utility method sets @link(HorizontalAnchorSelf), @link(HorizontalAnchorParent),
1057 @link(Translation Translation.X). }
1058 procedure Anchor(
1059 const AHorizontalAnchorSelf, AHorizontalAnchorParent: THorizontalPosition;
1060 const TranslationX: Single = 0); overload;
1061
1062 { Adjust position to align us to the parent vertically.
1063 The resulting @link(EffectiveRect) and @link(RenderRect) and @link(RenderRectWithBorder)
1064 will immediately reflect the new position.
1065
1066 Note that position set here (anchors, @link(Translation))
1067 are ignored when @link(FullSize) is set to true.
1068 In case of @link(FullSize), the control fills the parent perfectly.
1069
1070 This utility method sets @link(VerticalAnchorSelf), @link(VerticalAnchorParent),
1071 @link(Translation Translation.Y). }
1072 procedure Anchor(const AVerticalAnchor: TVerticalPosition;
1073 const TranslationY: Single = 0); overload;
1074
1075 { Adjust position to align us to the parent vertically.
1076 The resulting @link(EffectiveRect) and @link(RenderRect) and @link(RenderRectWithBorder)
1077 will immediately reflect the new position.
1078
1079 Note that position set here (anchors, @link(Translation))
1080 are ignored when @link(FullSize) is set to true.
1081 In case of @link(FullSize), the control fills the parent perfectly.
1082
1083 This utility method sets @link(VerticalAnchorSelf), @link(VerticalAnchorParent),
1084 @link(Translation Translation.Y). }
1085 procedure Anchor(
1086 const AVerticalAnchorSelf, AVerticalAnchorParent: TVerticalPosition;
1087 const TranslationY: Single = 0); overload;
1088
1089 {$warnings off} // using deprecated TPositionRelative in deprecated
1090
1091 { Immediately position the control with respect to the parent
1092 by adjusting @link(Left).
1093 Deprecated, use @link(Align) with THorizontalPosition. }
1094 procedure AlignHorizontal(
1095 const ControlPosition: TPositionRelative = prMiddle;
1096 const ContainerPosition: TPositionRelative = prMiddle;
1097 const X: Single = 0); deprecated 'use Anchor';
1098
1099 { Immediately position the control with respect to the parent
1100 by adjusting @link(Left).
1101
1102 Note that using @link(Anchor) is often more comfortable than this method,
1103 since you only need to set anchor once (for example, right after creating
1104 the control). In contract, adjusting position using this method
1105 will typically need to be repeated at each window on resize,
1106 like in @link(TCastleWindow.OnResize). }
1107 procedure Align(
1108 const ControlPosition: THorizontalPosition;
1109 const ContainerPosition: THorizontalPosition;
1110 const X: Single = 0); overload; deprecated 'use Anchor';
1111
1112 { Immediately position the control with respect to the parent
1113 by adjusting @link(Bottom).
1114 Deprecated, use @link(Align) with TVerticalPosition. }
1115 procedure AlignVertical(
1116 const ControlPosition: TPositionRelative = prMiddle;
1117 const ContainerPosition: TPositionRelative = prMiddle;
1118 const Y: Single = 0); deprecated 'use Anchor';
1119
1120 { Immediately position the control with respect to the parent
1121 by adjusting @link(Bottom).
1122
1123 Note that using @link(Anchor) is often more comfortable than this method,
1124 since you only need to set anchor once (for example, right after creating
1125 the control). In contract, adjusting position using this method
1126 will typically need to be repeated at each window on resize,
1127 like in @link(TCastleWindow.OnResize). }
1128 procedure Align(
1129 const ControlPosition: TVerticalPosition;
1130 const ContainerPosition: TVerticalPosition;
1131 const Y: Single = 0); overload; deprecated 'use Anchor';
1132
1133 {$warnings on}
1134
1135 { Immediately center the control within the parent,
1136 both horizontally and vertically.
1137
1138 Note that using @link(Anchor) is often more comfortable than this method,
1139 since you only need to set anchor once. For example, right after creating
1140 the control call @code(Anchor(hpMiddle); Anchor(vpMiddle);).
1141 In contrast, adjusting position using this method
1142 will typically need to be repeated at each window on resize,
1143 like in @link(TCastleWindow.OnResize). }
1144 procedure Center; deprecated 'use Anchor(hpMiddle); Anchor(vpMiddle); to reliably center the control';
1145
1146 { UI scale of this control, derived from container
1147 (see @link(TCastleContainer.UIScaling) and @link(EnableUIScaling)). }
1148 function UIScale: Single; virtual;
1149
1150 { Override this to prevent resizing some dimension in CGE editor. }
1151 procedure EditorAllowResize(out ResizeWidth, ResizeHeight: Boolean;
1152 out Reason: String); virtual;
1153
1154 {$ifdef FPC}
1155 property FloatWidth: Single read FWidth write SetWidth stored false;
1156 deprecated 'use Width';
1157 property FloatHeight: Single read FHeight write SetHeight stored false;
1158 deprecated 'use Height';
1159 {$endif}
1160
1161 { Position of the control, relative to the anchor at parent
1162 (by default, relative to left-bottom corner of the parent). }
1163 property AnchorDelta: TVector2 read FTranslation write SetTranslation;
1164 {$ifdef FPC}deprecated 'use Translation';{$endif}
1165
1166 { Position of the control, relative to the anchor at parent
1167 (by default, relative to left-bottom corner of the parent). }
1168 property Translation: TVector2 read FTranslation write SetTranslation;
1169
1170 { Keep the control in front of other controls (with KeepInFront=@false)
1171 when inserting.
1172
1173 TODO: Do not change this property while the control is already
1174 a child of something. }
1175 property KeepInFront: boolean read FKeepInFront write FKeepInFront
1176 default false;
1177
1178 { Color of the @link(Border), by default completely transparent black. }
1179 property BorderColor: TCastleColor read FBorderColor write SetBorderColor;
1180
1181 {$ifdef FPC}
1182 property HasHorizontalAnchor: boolean
1183 read FHasHorizontalAnchor write FHasHorizontalAnchor stored false;
1184 deprecated 'this property does not do anything anymore, anchors are always active';
1185 property HasVerticalAnchor: boolean
1186 read FHasVerticalAnchor write FHasVerticalAnchor stored false;
1187 deprecated 'this property does not do anything anymore, anchors are always active';
1188 {$endif}
1189
1190 { Delta between our border and parent.
1191 @seealso Anchor }
1192 property HorizontalAnchorDelta: Single
1193 read GetHorizontalAnchorDelta write SetHorizontalAnchorDelta {$ifdef FPC}default 0{$endif};
1194 {$ifdef FPC}deprecated 'use Translation.X';{$endif}
1195 { Delta between our border and parent.
1196 @seealso Anchor }
1197 property VerticalAnchorDelta: Single
1198 read GetVerticalAnchorDelta write SetVerticalAnchorDelta {$ifdef FPC}default 0{$endif};
1199 {$ifdef FPC}deprecated 'use Translation.Y';{$endif}
1200
1201 { Is the control possibly visible.
1202 This is always @true when @link(Culling) is @false (the default). }
1203 property Visible: Boolean read FVisible;
1204
1205 { Enable or disable UI scaling for this particular control.
1206 See more about UI scaling on @link(TCastleContainer.UIScaling) and
1207 @link(TCastleUserInterface.UIScale). Setting this to @false forces
1208 @link(TCastleUserInterface.UIScale) to always return 1.0.
1209
1210 Note that this does not work recursively, i.e. it does not affect
1211 the children of this control. Setting this to @false does not prevent
1212 UI scaling on children (you have to turn it off explicitly for children too,
1213 if you need to disable UI scaling recursively).
1214
1215 @italic(The use-cases for changing this property to "false" are very rare.
1216 Usually you should use UI scaling for 100% of your UI.) }
1217 property EnableUIScaling: boolean
1218 read FEnableUIScaling write SetEnableUIScaling default true;
1219
1220 { Capture input events (keyboard, mouse, joystick).
1221 If @false, then the methods like @link(Press) and @link(Release) will never be called,
1222 and @link(Update) will always be called with HandleInput = @false.
1223 The control will never behave like focused.
1224
1225 The only exception is when this control is set as @link(TCastleContainer.ForceCaptureInput).
1226 In this case, the control will receive inputs.
1227 In other words, @link(TCastleContainer.ForceCaptureInput) overrides
1228 the intent of this property.
1229
1230 @italic(This property may be replaced by something like
1231 "CaptureInput" or just universal "Enabled" in the future.) }
1232 property CapturesEvents: boolean read FCapturesEvents write FCapturesEvents
1233 default true;
1234
1235 { Called when control starts being under the mouse cursor and will receive events.
1236 See @link(SetFocused), this is called when @link(Focused) changes from @false to @true.
1237
1238 This is called "Internal" now, because we do not guarantee it's 100%
1239 always paired with @link(OnInternalMouseLeave). A different approach to this may
1240 be done in the future releases. }
1241 property OnInternalMouseEnter: TUiNotifyEvent
1242 read FOnInternalMouseEnter write FOnInternalMouseEnter;
1243
1244 { Called when control stops being under the mouse cursor and will receive events.
1245 See @link(SetFocused), this is called when @link(Focused) changes from @true to @false.
1246
1247 This is called "Internal" now, because we do not guarantee it's 100%
1248 always paired with @link(OnInternalMouseEnter). A different approach to this may
1249 be done in the future releases. }
1250 property OnInternalMouseLeave: TUiNotifyEvent
1251 read FOnInternalMouseLeave write FOnInternalMouseLeave;
1252
1253 { Is the @link(FullSize) actually active.
1254 Checks @link(FullSize) and not @link(AutoSizeToChildren),
1255 i.e. it accounts that AutoSizeToChildren overrides FullSize
1256 (since they cannot both work at the same time). }
1257 function EffectiveFullSize: Boolean;
1258
1259 { Renders control's children, assuming various tests like culling passed.
1260 @exclude }
1261 procedure InternalRecursiveRender(const ViewportRect: TRectangle);
1262 published
1263 { Mouse cursor over this control.
1264 When user moves mouse over the Container, the currently focused
1265 (topmost under the cursor) control determines the mouse cursor look. }
1266 property Cursor: TMouseCursor read FCursor write SetCursor default mcDefault;
1267
1268 { Event that occurs continuously on each control.
1269 See @link(Update) for details. }
1270 property OnUpdate: TUiUpdateEvent read FOnUpdate write FOnUpdate;
1271
1272 { An input (key, mouse button, mouse wheel) was pressed.
1273 See @link(Press) for details. }
1274 property OnPress: TUiPressReleaseEvent read FOnPress write FOnPress;
1275
1276 { An input (key, mouse button, mouse wheel) was released.
1277 See @link(Release) for details. }
1278 property OnRelease: TUiPressReleaseEvent read FOnRelease write FOnRelease;
1279
1280 { Pointer (mouse or finger) moved.
1281 See @link(Motion) for details. }
1282 property OnMotion: TUiMotionEvent read FOnMotion write FOnMotion;
1283
1284 { Control is being displayed.
1285 See @link(Render) for details.
1286 This event it called @italic(after) the @link(Render) method
1287 of this control finished but before we started rendering children. }
1288 property OnRender: TUiNotifyEvent read FOnRender write FOnRender;
1289
1290 { Not existing control is not visible, it doesn't receive input
1291 and generally doesn't exist from the point of view of user.
1292 This is mostly equivalent to just removing this control from parent list.
1293
1294 Non-existing controls still receive
1295 @link(GLContextOpen), @link(GLContextClose), @link(Resize) events. }
1296 property Exists: boolean read FExists write SetExists default true;
1297
1298 { Position from the left side of the parent control.
1299
1300 It's usually better to use anchors instead of this property.
1301 For example, instead of setting @code(Control.Left := 10),
1302 you can call @code(Control.Anchor(hpLeft, 10)),
1303 or just change @link(Translation Translation.X).
1304
1305 Note that the effects of this property and @link(Translation Translation.X)
1306 are summed, if you set both.
1307 We advise to leave @link(Left) as zero and just use anchors in new code. }
1308 property Left: Single read FLeft write SetLeft stored false {$ifdef FPC}default 0{$endif};
1309 {$ifdef FPC}deprecated 'use Translation.X';{$endif}
1310
1311 { Position from the bottom side of the parent control.
1312
1313 It's usually better to use anchors instead of this property.
1314 For example, instead of setting @code(Control.Bottom := 10),
1315 you can call @code(Control.Anchor(vpBottom, 10)),
1316 or just change @link(Translation Translation.Y).
1317
1318 Note that the effects of this property and @link(Translation Translation.Y)
1319 are summed, if you set both.
1320 We advise to leave @link(Bottom) as zero and just use anchors in new code. }
1321 property Bottom: Single read FBottom write SetBottom {$ifdef FPC}default 0{$endif};
1322 {$ifdef FPC}deprecated 'use Translation.Y';{$endif}
1323
1324 { When @name, the control will always fill the whole parent area.
1325 @seealso TCastleUserInterface.EffectiveRect
1326 @seealso TCastleUserInterface.EffectiveWidth
1327 @seealso TCastleUserInterface.EffectiveHeight }
1328 property FullSize: boolean read FFullSize write SetFullSize default false;
1329
1330 { These properties determine the control size.
1331 See the @link(EffectiveRect) documentation for details how the size
1332 is calculated.
1333
1334 @seealso TCastleUserInterface.EffectiveRect
1335 @seealso TCastleUserInterface.EffectiveWidth
1336 @seealso TCastleUserInterface.EffectiveHeight
1337 @groupBegin }
1338 property Width: Single read FWidth write SetWidth {$ifdef FPC}default DefaultWidth{$endif};
1339 property Height: Single read FHeight write SetHeight {$ifdef FPC}default DefaultHeight{$endif};
1340 property WidthFraction: Single read FWidthFraction write SetWidthFraction {$ifdef FPC}default 0.0{$endif};
1341 property HeightFraction: Single read FHeightFraction write SetHeightFraction {$ifdef FPC}default 0.0{$endif};
1342 { @groupEnd }
1343
1344 { Adjust size to encompass all the children.
1345 The properties @link(FullSize), @link(Width), @link(Height)
1346 are ignored in this case.
1347 Our @link(Left) and @link(Bottom) still matter.
1348
1349 Our size is adjusted to all existing children sizes and positions.
1350
1351 We add @link(AutoSizeToChildrenPaddingTop) to the resulting height,
1352 and @link(AutoSizeToChildrenPaddingRight) to the resulting width.
1353 }
1354 property AutoSizeToChildren: Boolean
1355 read FAutoSizeToChildren write SetAutoSizeToChildren default false;
1356
1357 { Padding added when @link(AutoSizeToChildren) is used.
1358 TODO: Should be AutoSizeToChildrenPaddingHorizontal, there's nothing that makes it specific
1359 to "right" or "left" side now. }
1360 property AutoSizeToChildrenPaddingRight: Single
1361 read FAutoSizeToChildrenPaddingRight
1362 write SetAutoSizeToChildrenPaddingRight {$ifdef FPC}default 0{$endif};
1363 { Padding added when @link(AutoSizeToChildren) is used.
1364 TODO: Should be AutoSizeToChildrenPaddingVertical, there's nothing that makes it specific
1365 to "top" or "bottom" side now. }
1366 property AutoSizeToChildrenPaddingTop: Single
1367 read FAutoSizeToChildrenPaddingTop
1368 write SetAutoSizeToChildrenPaddingTop {$ifdef FPC}default 0{$endif};
1369
1370 { Which @bold(our) border to align with parent.
1371 @seealso Anchor }
1372 property HorizontalAnchorSelf: THorizontalPosition
1373 read FHorizontalAnchorSelf write SetHorizontalAnchorSelf default hpLeft;
1374 { Which @bold(parent) border is aligned to our @link(HorizontalAnchorSelf) border.
1375 @seealso Anchor }
1376 property HorizontalAnchorParent: THorizontalPosition
1377 read FHorizontalAnchorParent write SetHorizontalAnchorParent default hpLeft;
1378
1379 { Which @bold(our) border to align with parent.
1380 @seealso Anchor }
1381 property VerticalAnchorSelf: TVerticalPosition
1382 read FVerticalAnchorSelf write SetVerticalAnchorSelf default vpBottom;
1383 { Which @bold(parent) border is aligned to our @link(VerticalAnchorSelf) border.
1384 @seealso Anchor }
1385 property VerticalAnchorParent: TVerticalPosition
1386 read FVerticalAnchorParent write SetVerticalAnchorParent default vpBottom;
1387
1388 { Optimize rendering and event processing
1389 by checking whether the control can be visible.
1390 The visibility is checked by looking at container rectangle,
1391 and all possible clipping parents
1392 (set by @link(TCastleScrollView), or any other control with
1393 @link(ClipChildren)).
1394
1395 This is useful for UI controls that have expensive rendering or other events
1396 (e.g. they do something non-trivial in @link(Render) or @link(RenderOverChildren),
1397 or they include a lot of children controls).
1398 And they may be placed off-screen,
1399 or they may be outside of a parent with clipping,
1400 which is often the case when the parent is @link(TCastleScrollView). }
1401 property Culling: Boolean read FCulling write SetCulling default false;
1402
1403 { Clip the rendering of children.
1404
1405 By default this is @false and so the control
1406 can draw outside of it's designated rectangle (@link(RenderRect)).
1407 Although all the standard UI controls are carefully implemented
1408 such that their @link(Render) and @link(RenderOverChildren)
1409 draw only within their @link(RenderRect).
1410 But it is easy to place children controls outside of this rectangle.
1411
1412 When this property is @true, the rendering is clipped,
1413 so the "overflowing" parts are never visible.
1414 This affects both @link(Render) and @link(RenderOverChildren)
1415 of this control, as well as all children rendering. }
1416 property ClipChildren: Boolean read FClipChildren write SetClipChildren default false;
1417
1418 { Border (by default transparent) of the control.
1419 Border adds a space from the control content
1420 (drawn within @link(RenderRect)) to the control rectangle
1421 (returned by @link(RenderRectWithBorder)) (scaled), or @link(EffectiveRect)
1422 (unscaled) and friends).
1423
1424 It is transparent by default, but you can change it by @link(BorderColor).
1425
1426 Border works always, regardless of @link(FullSize) or @link(AutoSizeToChildren).
1427
1428 One obvious use-case is to use this for visual space
1429 (empty space or a colorful frame, separating this control from the rest).
1430
1431 Another use-case is to reserve a predictable space
1432 for as additional (sibling) control within the same parent.
1433 E.g. you can set FullSize=true and Border.Top=100,
1434 and this way there is always a strip with Height=100 at the top
1435 of the parent, where you can insert another control (with Height=100,
1436 anchored to the top). }
1437 property Border: TBorder read FBorder;
1438
1439 { Use a custom instance of TCastleTheme to determine the look of this control. }
1440 property CustomTheme: TCastleTheme read FCustomTheme write SetCustomTheme;
1441
1442 { If set, the indicated control will act as a tooltip:
1443 we will make it existing when we should show the tooltip for this control,
1444 we will make it no longer existing when the tooltip for this should be hidden.
1445 Initially the TooltipControl should usually have @link(Exists)=false,
1446 because you usually do not want to show it until we start showing it as a tooltip.
1447
1448 If TooltipControl is assigned then TCastleUserInterfaceFont
1449 no longer does tooltip rendering.
1450 The @link(TCastleUserInterfaceFont.Tooltip) text is ignored.
1451
1452 The visual parent of TooltipControl can be whatever is comfortable.
1453 That is, it is OK to make TooltipControl parent of this control,
1454 and it is OK not to: you can as well place TooltipControl as e.g. parent of container
1455 or design root. }
1456 property TooltipControl: TCastleUserInterface read FTooltipControl write SetTooltipControl;
1457
1458 { Select the UI (hover, select on click) at design-time when the mouse
1459 is over rectangle of this UI. This affects operation in the editor,
1460 and when using the inspector (press F8 at run-time, when the application
1461 is build in debug mode).
1462
1463 It's by default @true and it makes most sense to leave it @true for
1464 the majority of components. However some components are not only invisible,
1465 but also "user doesn't expect to select them by hovering". E.g. TCastleNavigation,
1466 or DesignHud in examples/fps_game. It is more intuitive for user then that such
1467 component doesn't obscure things underneath.
1468
1469 Note that hovering over children of UI with EditorSelectOnHover will still select them.
1470 This is good e.g. for DesignHud in examples/fps_game. }
1471 property EditorSelectOnHover: Boolean read FEditorSelectOnHover write FEditorSelectOnHover default true;
1472
1473 {$define read_interface_class}
1474 {$I auto_generated_persistent_vectors/tcastleuserinterface_persistent_vectors.inc}
1475 {$undef read_interface_class}
1476 end;
1477
1478 TCastleUserInterfaceClass = class of TCastleUserInterface;
1479
1480 {$endif read_interface}
1481
1482 {$ifdef read_implementation}
1483
1484 { TCastleUserInterface.TEnumerator ------------------------------------------------- }
1485
1486 function TCastleUserInterface.TEnumerator.GetCurrent: TCastleUserInterface;
1487 begin
1488 Result := FList[FPosition];
1489 end;
1490
1491 constructor TCastleUserInterface.TEnumerator.Create(const AList: TInternalChildrenControls);
1492 begin
1493 // inherited Create;
1494 FList := AList;
1495 FPosition := -1;
1496 end;
1497
1498 function TCastleUserInterface.TEnumerator.MoveNext: Boolean;
1499 begin
1500 Inc(FPosition);
1501 { Note that FList may be nil, as TCastleUserInterface.FControls may be nil when empty. }
1502 Result := (FList <> nil) and (FPosition < FList.Count);
1503 end;
1504
1505 { TCastleUserInterface ----------------------------------------------------------------- }
1506
1507 constructor TCastleUserInterface.Create(AOwner: TComponent);
1508 begin
1509 inherited;
1510 FExclusiveEvents := true;
1511 FCursor := mcDefault;
1512 FVisible := true;
1513 FExists := true;
1514 FEnableUIScaling := true;
1515 FCapturesEvents := true;
1516 FWidth := DefaultWidth;
1517 FHeight := DefaultHeight;
1518 FBorder := TBorder.Create(nil);
1519 FBorder.SetSubComponent(true);
1520 FBorder.OnChange := {$ifdef FPC}@{$endif} BorderChange;
1521 FLastSeenUIScale := 1.0;
1522 FEditorSelectOnHover := true;
1523
1524 FCustomThemeObserver := TFreeNotificationObserver.Create(Self);
1525 FCustomThemeObserver.OnFreeNotification := {$ifdef FPC}@{$endif} CustomThemeFreeNotification;
1526
1527 FTooltipControlObserver := TFreeNotificationObserver.Create(Self);
1528 FTooltipControlObserver.OnFreeNotification := {$ifdef FPC}@{$endif} TooltipControlFreeNotification;
1529
1530 {$define read_implementation_constructor}
1531 {$I auto_generated_persistent_vectors/tcastleuserinterface_persistent_vectors.inc}
1532 {$undef read_implementation_constructor}
1533 end;
1534
1535 function TCastleUserInterface.Press(const Event: TInputPressRelease): boolean;
1536 begin
1537 Result := false;
1538 if Assigned(OnPress) then
1539 OnPress(Self, Event, Result);
1540 end;
1541
1542 function TCastleUserInterface.Release(const Event: TInputPressRelease): boolean;
1543 begin
1544 Result := false;
1545 if Assigned(OnRelease) then
1546 OnRelease(Self, Event, Result);
1547 end;
1548
1549 function TCastleUserInterface.PreviewPress(const Event: TInputPressRelease): boolean;
1550 begin
1551 Result := false;
1552 end;
1553
1554 function TCastleUserInterface.PreviewRelease(const Event: TInputPressRelease): boolean;
1555 begin
1556 Result := false;
1557 end;
1558
1559 function TCastleUserInterface.Motion(const Event: TInputMotion): boolean;
1560 begin
1561 Result := false;
1562 if Assigned(OnMotion) then
1563 OnMotion(Self, Event, Result);
1564 end;
1565
1566 function TCastleUserInterface.SensorRotation(const X, Y, Z, Angle: Double; const SecondsPassed: Single): boolean;
1567 begin
1568 Result := false;
1569 end;
1570
1571 function TCastleUserInterface.SensorTranslation(const X, Y, Z, Length: Double; const SecondsPassed: Single): boolean;
1572 begin
1573 Result := false;
1574 end;
1575
1576 function TCastleUserInterface.JoyAxisMove(const JoyID, Axis: Byte): boolean;
1577 begin
1578 Result := False;
1579 end;
1580
1581 function TCastleUserInterface.JoyButtonPress(const JoyID, Button: Byte): boolean;
1582 begin
1583 Result := False;
1584 end;
1585
1586 procedure TCastleUserInterface.Update(const SecondsPassed: Single;
1587 var HandleInput: boolean);
1588 begin
1589 if Assigned(OnUpdate) then
1590 OnUpdate(Self, SecondsPassed, HandleInput);
1591 end;
1592
1593 procedure TCastleUserInterface.VisibleChange(const Changes: TCastleUserInterfaceChanges;
1594 const ChangeInitiatedByChildren: boolean);
1595 begin
1596 Assert(Changes <> [], 'Never call VisibleChange with an empty set');
1597
1598 { Debug:
1599 Writeln(ClassName, '.VisibleChange: [',
1600 Iff(chRender in Changes, 'chRender, ' , ''),
1601 Iff(chRectangle in Changes, 'chRectangle, ', ''),
1602 Iff(chCursor in Changes, 'chCursor, ' , ''),
1603 Iff(chCamera in Changes, 'chCamera, ' , ''),
1604 Iff(chExists in Changes, 'chExists, ' , ''),
1605 Iff(chChildren in Changes, 'chChildren, ' , ''),
1606 ']'
1607 ); }
1608
1609 if Container <> nil then
1610 Container.ControlsVisibleChange(Self, Changes, ChangeInitiatedByChildren);
1611 if Assigned(OnVisibleChange) then
1612 OnVisibleChange(Self, Changes, ChangeInitiatedByChildren);
1613 if Parent <> nil then
1614 Parent.VisibleChange(Changes, true);
1615 if [chRectangle, chChildren, chChildrenExists] * Changes <> [] then
1616 FSizeFromChildrenValid := false;
1617 end;
1618
1619 function TCastleUserInterface.AllowSuspendForInput: boolean;
1620 begin
1621 Result := true;
1622 end;
1623
1624 procedure TCastleUserInterface.Resize;
1625 begin
1626 end;
1627
1628 function TCastleUserInterface.ContainerWidth: Cardinal;
1629 begin
1630 {$warnings off} // using deprecated to implement deprecated
1631 if ContainerSizeKnown then
1632 {$warnings on}
1633 Result := Container.PixelsWidth
1634 else
1635 Result := 0;
1636 end;
1637
1638 function TCastleUserInterface.ContainerHeight: Cardinal;
1639 begin
1640 {$warnings off} // using deprecated to implement deprecated
1641 if ContainerSizeKnown then
1642 {$warnings on}
1643 Result := Container.PixelsHeight
1644 else
1645 Result := 0;
1646 end;
1647
1648 function TCastleUserInterface.ContainerRect: TRectangle;
1649 begin
1650 {$warnings off} // using deprecated to implement deprecated
1651 if ContainerSizeKnown then
1652 {$warnings on}
1653 Result := Container.PixelsRect
1654 else
1655 Result := TRectangle.Empty;
1656 end;
1657
1658 function TCastleUserInterface.ContainerSizeKnown: boolean;
1659 begin
1660 { Note that ContainerSizeKnown is calculated looking at current Container,
1661 without waiting for Resize. This way it works even before
1662 we receive Resize method, which may happen to be useful:
1663 if you insert some TCastleUserInterface to a window before it's open,
1664 and then you do something inside OnOpen that wants to render
1665 this viewport (which may happen if you simply initialize a progress bar
1666 without any predefined loading_image). TCastleUserInterface did not receive
1667 a Resize in this case yet (it will receive it from OnResize,
1668 which happens after OnOpen).
1669
1670 See castle_game_engine/tests/testcontainer.pas for cases
1671 when this is really needed. }
1672
1673 Result := (Container <> nil) and
1674 (not (csDestroying in Container.ComponentState)) and
1675 Container.GLInitialized;
1676 end;
1677
1678 procedure TCastleUserInterface.SetCursor(const Value: TMouseCursor);
1679 begin
1680 if Value <> FCursor then
1681 begin
1682 FCursor := Value;
1683 VisibleChange([chCursor]);
1684 {$ifdef FPC}
1685 {$warnings off} // keep deprecated method working
1686 DoCursorChange;
1687 {$warnings on}
1688 {$endif}
1689 end;
1690 end;
1691
1692 {
1693 procedure TCastleUserInterface.SetParent(const Value: TCastleTransform);
1694 begin
1695 if Parent <> Value then
1696 begin
1697 if Parent <> nil then
1698 Parent.RemoveControl(Self);
1699 FParent := Value;
1700 if Value <> nil then
1701 Value.InsertFront(Self);
1702 end;
1703 end;
1704 }
1705
1706 {$ifdef FPC}
1707 procedure TCastleUserInterface.DoCursorChange;
1708 begin
1709 {$warnings off} // keep deprecated event working
1710 if Assigned(OnCursorChange) then OnCursorChange(Self);
1711 {$warnings on}
1712 end;
1713 {$endif FPC}
1714
1715 destructor TCastleUserInterface.Destroy;
1716 begin
1717 GLContextClose;
1718 FreeAndNil(FControls);
1719 FreeAndNil(FBorder);
1720
1721 {$define read_implementation_destructor}
1722 {$I auto_generated_persistent_vectors/tcastleuserinterface_persistent_vectors.inc}
1723 {$undef read_implementation_destructor}
1724 inherited;
1725 end;
1726
1727 procedure TCastleUserInterface.CustomSerialization(const SerializationProcess: TSerializationProcess);
1728 var
1729 OldDelta: Single;
1730 begin
1731 inherited;
1732 SerializationProcess.ReadWriteList('Children',
1733 {$ifdef FPC}@{$endif}SerializeChildrenEnumerate,
1734 {$ifdef FPC}@{$endif}SerializeChildrenAdd,
1735 {$ifdef FPC}@{$endif}SerializeChildrenClear);
1736
1737 OldDelta := 0;
1738 SerializationProcess.ReadWriteSingle('HorizontalAnchorDelta', OldDelta, false);
1739 if OldDelta <> 0 then
1740 begin
1741 Translation := Vector2(OldDelta, Translation.Y);
1742 // too verbose for now, we have lots of designs with old names
1743 // WritelnWarning('Upgrading deprecated HorizontalAnchorDelta to Translation.X on component "%s"', [
1744 // Name
1745 // ]);
1746 end;
1747
1748 OldDelta := 0;
1749 SerializationProcess.ReadWriteSingle('VerticalAnchorDelta', OldDelta, false);
1750 if OldDelta <> 0 then
1751 begin
1752 Translation := Vector2(Translation.X, OldDelta);
1753 // too verbose for now, we have lots of designs with old names
1754 // WritelnWarning('Upgrading deprecated VerticalAnchorDelta to Translation.Y on component "%s"', [
1755 // Name
1756 // ]);
1757 end;
1758 end;
1759
1760 procedure TCastleUserInterface.SerializeChildrenEnumerate(const Proc: TGetChildProc);
1761 var
1762 I: Integer;
1763 begin
1764 if FControls <> nil then
1765 for I := 0 to FControls.Count - 1 do
1766 { Do not save SubComponents, like TCastleScrollView.ScrollArea.
1767 They are saved separately, as published properties.
1768 Also do not save csTransient components, like loaded TCastleDesign
1769 child, or TCastleCheckbox children. They are automatically managed
1770 by the parent, and they should not be saved in normal fashion. }
1771 if [csSubComponent, csTransient] * FControls[I].ComponentStyle = [] then
1772 Proc(FControls[I]);
1773 end;
1774
1775 procedure TCastleUserInterface.SerializeChildrenAdd(const C: TComponent);
1776 begin
1777 InsertFront(C as TCastleUserInterface);
1778 end;
1779
1780 procedure TCastleUserInterface.SerializeChildrenClear;
1781 var
1782 I: Integer;
1783 begin
1784 if FControls <> nil then
1785 for I := FControls.Count - 1 downto 0 do // downto, as list may shrink during loop
1786 if FControls[I].ComponentStyle * [csSubComponent, csTransient] = [] then
1787 FControls[I].Free; // will remove itself from children list
1788 end;
1789
1790 procedure TCastleUserInterface.CreateControls;
1791 begin
1792 if FControls = nil then
1793 begin
1794 FControls := TInternalChildrenControls.Create(Self);
1795 FControls.Container := Container;
1796 end;
1797 end;
1798
1799 procedure TCastleUserInterface.InsertFront(const NewItem: TCastleUserInterface);
1800 begin
1801 CreateControls;
1802 FControls.InsertFront(NewItem);
1803 end;
1804
1805 procedure TCastleUserInterface.InsertFrontIfNotExists(const NewItem: TCastleUserInterface);
1806 begin
1807 CreateControls;
1808 FControls.InsertFrontIfNotExists(NewItem);
1809 end;
1810
1811 procedure TCastleUserInterface.InsertFront(const NewItems: TCastleUserInterfaceList);
1812 begin
1813 CreateControls;
1814 FControls.InsertFront(NewItems);
1815 end;
1816
1817 procedure TCastleUserInterface.InsertBack(const NewItem: TCastleUserInterface);
1818 begin
1819 CreateControls;
1820 FControls.InsertBack(NewItem);
1821 end;
1822
1823 procedure TCastleUserInterface.InsertBackIfNotExists(const NewItem: TCastleUserInterface);
1824 begin
1825 CreateControls;
1826 FControls.InsertBackIfNotExists(NewItem);
1827 end;
1828
1829 procedure TCastleUserInterface.InsertBack(const NewItems: TCastleUserInterfaceList);
1830 begin
1831 CreateControls;
1832 FControls.InsertBack(NewItems);
1833 end;
1834
1835 procedure TCastleUserInterface.InsertControl(const Index: Integer; const NewItem: TCastleUserInterface);
1836 begin
1837 CreateControls;
1838 FControls.Insert(Index, NewItem);
1839 end;
1840
1841 procedure TCastleUserInterface.RemoveControl(const Item: TCastleUserInterface);
1842 begin
1843 if FControls <> nil then
1844 FControls.Remove(Item);
1845 end;
1846
1847 function TCastleUserInterface.IndexOfControl(const Item: TCastleUserInterface
1848 ): Integer;
1849 begin
1850 if FControls <> nil then
1851 Result := FControls.IndexOf(Item)
1852 else
1853 Result := -1;
1854 end;
1855
1856 procedure TCastleUserInterface.ClearControls;
1857 begin
1858 if FControls <> nil then
1859 FControls.Clear;
1860 end;
1861
1862 function TCastleUserInterface.GetControls(const I: Integer): TCastleUserInterface;
1863 begin
1864 Result := FControls[I];
1865 end;
1866
1867 procedure TCastleUserInterface.SetControls(const I: Integer; const Item: TCastleUserInterface);
1868 begin
1869 FControls[I] := Item;
1870 end;
1871
1872 function TCastleUserInterface.ControlsCount: Integer;
1873 begin
1874 if FControls <> nil then
1875 Result := FControls.Count else
1876 Result := 0;
1877 end;
1878
1879 procedure TCastleUserInterface.InternalSetContainer(const Value: TCastleContainer);
1880 var
1881 I: Integer;
1882 begin
1883 FContainer := Value;
1884 if FControls <> nil then
1885 begin
1886 FControls.Container := Value;
1887 for I := 0 to FControls.Count - 1 do
1888 FControls[I].InternalSetContainer(Value);
1889 end;
1890 end;
1891
1892 procedure TCastleUserInterface.SetEnableUIScaling(const Value: boolean);
1893 begin
1894 if FEnableUIScaling <> Value then
1895 begin
1896 FEnableUIScaling := Value;
1897 CheckUIScaleChanged;
1898 end;
1899 end;
1900
1901 procedure TCastleUserInterface.UIScaleChanged;
1902 begin
1903 end;
1904
1905 { No point in doing anything? We should propagate it to to parent like T3D?
1906 procedure TCastleUserInterface.DoCursorChange;
1907 begin
1908 inherited;
1909 if FControls <> nil then
1910 for I := 0 to FControls.Count - 1 do
1911 FControls[I].DoCursorChange;
1912 end;
1913 }
1914
1915 function TCastleUserInterface.CapturesEventsAtPosition(const Position: TVector2): boolean;
1916 var
1917 SR: TFloatRectangle;
1918 begin
1919 if not CapturesEvents then
1920 Exit(false);
1921
1922 SR := RenderRect;
1923 {$warnings off} // using deprecated ContainerWidth/Height now
1924 Result := SR.Contains(Position) or
1925 { if the control covers the whole Container, it *always* captures events,
1926 even when mouse position is unknown yet, or outside the window. }
1927 (ContainerSizeKnown and
1928 (SR.Left <= 0) and
1929 (SR.Bottom <= 0) and
1930 (SR.Width >= ContainerWidth) and
1931 (SR.Height >= ContainerHeight));
1932 {$warnings on}
1933 end;
1934
1935 function TCastleUserInterface.TooltipExists: boolean;
1936 begin
1937 Result := TooltipControl <> nil;
1938 end;
1939
1940 function TCastleUserInterface.UIScale: Single;
1941 begin
1942 Result := FLastSeenUIScale;
1943 end;
1944
1945 procedure TCastleUserInterface.CheckUIScaleChanged;
1946 var
1947 NewUIScale: Single;
1948 begin
1949 if (Container <> nil) and EnableUIScaling then
1950 NewUIScale := Container.UIScale
1951 else
1952 NewUIScale := 1;
1953 if FLastSeenUIScale <> NewUIScale then
1954 begin
1955 FLastSeenUIScale := NewUIScale;
1956 UIScaleChanged;
1957 end;
1958 end;
1959
1960 procedure TCastleUserInterface.CheckResize;
1961 var
1962 NewContainerWidth, NewContainerHeight: Integer;
1963 begin
1964 if Container <> nil then
1965 begin
1966 NewContainerWidth := Container.PixelsWidth;
1967 NewContainerHeight := Container.PixelsHeight;
1968 end else
1969 begin
1970 NewContainerWidth := 0;
1971 NewContainerHeight := 0;
1972 end;
1973 if (FLastSeenContainerWidth <> NewContainerWidth) or
1974 (FLastSeenContainerHeight <> NewContainerHeight) then
1975 begin
1976 FLastSeenContainerWidth := NewContainerWidth;
1977 FLastSeenContainerHeight := NewContainerHeight;
1978 Resize;
1979 end;
1980 end;
1981
1982 function TCastleUserInterface.DebugName: String;
1983 begin
1984 if Name <> '' then
1985 Result := '"' + Name + '" (' + ClassName + ')'
1986 else
1987 Result := '<unnamed> (' + ClassName + ')';
1988 end;
1989
1990 procedure TCastleUserInterface.BeforeRender;
1991 begin
1992 end;
1993
1994 procedure TCastleUserInterface.Render;
1995 begin
1996 end;
1997
1998 procedure TCastleUserInterface.RenderOverChildren;
1999 begin
2000 end;
2001
2002 procedure TCastleUserInterface.InternalRecursiveRender(const ViewportRect: TRectangle);
2003
2004 { Draw 4 borders.
2005 RectBorder is equal to Self.RenderRectWithBorder,
2006 but it is already calculated by the caller. }
2007 procedure DrawBorder(const RectBorder: TFloatRectangle);
2008
2009 procedure DrawBorderRectangle(const R: TFloatRectangle);
2010 begin
2011 if not R.IsEmpty then
2012 DrawRectangle(R, BorderColor);
2013 end;
2014
2015 var
2016 RectLeftRightBorders: TFloatRectangle;
2017 begin
2018 if FBorderColor[3] = 0 then Exit; // early exit in a common case
2019 { RenderControlPrepare necessary, since TCastleViewport could have
2020 changed RenderContext.Viewport. }
2021 TCastleContainer.RenderControlPrepare(ViewportRect);
2022
2023 DrawBorderRectangle(RectBorder.TopPart(Border.TotalTop * UIScale));
2024 DrawBorderRectangle(RectBorder.BottomPart(Border.TotalBottom * UIScale));
2025
2026 { Draw left and right borders from a smaller rectangle.
2027 This way we do not overdraw border corners, which is important
2028 in case BorderColor[3] is e.g. 0.5. Drawing corner twice would
2029 make it seem more opaque.
2030 Unfortunately artifacts are visible (the right part is visibly
2031 shifted by ~1 pixel to the right), so we don't do it always now. }
2032 RectLeftRightBorders := RectBorder.
2033 RemoveTop(Border.TotalTop * UIScale).
2034 RemoveBottom(Border.TotalBottom * UIScale);
2035 DrawBorderRectangle(RectLeftRightBorders.RightPart(Border.TotalRight * UIScale));
2036 DrawBorderRectangle(RectLeftRightBorders.LeftPart(Border.TotalLeft * UIScale));
2037 end;
2038
2039 procedure CacheRectBegin;
2040 begin
2041 // the calculation inside will use Rect a number of times, make it faster
2042 if FUseCachedRectWithoutAnchors = 0 then
2043 FCachedRectWithoutAnchors := RectWithoutAnchors;
2044 Inc(FUseCachedRectWithoutAnchors);
2045 end;
2046
2047 procedure CacheRectEnd;
2048 begin
2049 Dec(FUseCachedRectWithoutAnchors);
2050 end;
2051
2052 function ClippingRect: TFloatRectangle;
2053 var
2054 ResultInt, ScissorRect: TRectangle;
2055 begin
2056 {$warnings off} // using deprecated ContainerRect
2057 ResultInt := ContainerRect;
2058 {$warnings on}
2059 if RenderContext.FinalScissor(ScissorRect) then
2060 ResultInt := ResultInt * ScissorRect;
2061 Result := FloatRectangle(ResultInt);
2062 end;
2063
2064 var
2065 Scissor: TScissor;
2066
2067 procedure ClipChildrenBegin;
2068 begin
2069 if ClipChildren then
2070 begin
2071 Scissor := TScissor.Create;
2072 Scissor.Rect := RenderRect.Round;
2073 Scissor.Enabled := true;
2074 end else
2075 Scissor := nil;
2076 end;
2077
2078 procedure ClipChildrenEnd;
2079 begin
2080 if Scissor <> nil then
2081 begin
2082 Scissor.Enabled := false;
2083 FreeAndNil(Scissor);
2084 end;
2085 end;
2086
2087 var
2088 R: TFloatRectangle;
2089 begin
2090 if Exists then
2091 begin
2092 { Usually, CheckUIScaleChanged and CheckResize are called from TCastleContainer.EventBeforeRender,
2093 and that's enough. But in case control is not FVisible, they will not be called.
2094 Which is a problem, because control may become visible (RenderRectWithBorder below may change)
2095 exactly as an effect of CheckUIScaleChanged or CheckResize.
2096 See https://github.com/castle-engine/castle-engine/issues/458 .
2097 So in this special case, we do these calls here. }
2098 if Culling and not FVisible then
2099 begin
2100 CheckUIScaleChanged;
2101 CheckResize;
2102 end;
2103
2104 CacheRectBegin;
2105
2106 R := RenderRectWithBorder;
2107
2108 FVisible := (not Culling) or ClippingRect.Collides(R);
2109 if FVisible then
2110 begin
2111 DrawBorder(R);
2112
2113 ClipChildrenBegin;
2114
2115 { We check GLInitialized, because it may happen that a control
2116 did not receive GLContextOpen yet, in case we cause some rendering
2117 during TCastleContainer.EventOpen (e.g. because some TCastleUserInterface.GLContextOpen
2118 calls Window.Screenshot, so everything is rendered
2119 before even the rest of controls received TCastleUserInterface.GLContextOpen).
2120 See castle_game_engine/tests/testcontainer.pas . }
2121
2122 if GLInitialized then
2123 begin
2124 TCastleContainer.RenderControlPrepare(ViewportRect);
2125 Render;
2126
2127 if Assigned(OnRender) then
2128 begin
2129 TCastleContainer.RenderControlPrepare(ViewportRect);
2130 OnRender(Self);
2131 end;
2132 end;
2133
2134 InternalRenderLoop(ViewportRect);
2135
2136 if GLInitialized then
2137 begin
2138 TCastleContainer.RenderControlPrepare(ViewportRect);
2139 RenderOverChildren;
2140 end;
2141
2142 ClipChildrenEnd;
2143 end;
2144
2145 CacheRectEnd;
2146 end;
2147 end;
2148
2149 procedure TCastleUserInterface.InternalRenderLoop(const ViewportRect: TRectangle);
2150 var
2151 I: Integer;
2152 begin
2153 for I := 0 to ControlsCount - 1 do
2154 Controls[I].InternalRecursiveRender(ViewportRect);
2155 end;
2156
2157 procedure TCastleUserInterface.TooltipRender(const TooltipPosition: TVector2);
2158 begin
2159 end;
2160
2161 procedure TCastleUserInterface.GLContextOpen;
2162 begin
2163 FGLInitialized := true;
2164 end;
2165
2166 procedure TCastleUserInterface.GLContextClose;
2167 begin
2168 FGLInitialized := false;
2169 end;
2170
2171 procedure TCastleUserInterface.DoInternalMouseEnter;
2172 begin
2173 if Assigned(OnInternalMouseEnter) then
2174 OnInternalMouseEnter(Self);
2175 end;
2176
2177 procedure TCastleUserInterface.DoInternalMouseLeave;
2178 begin
2179 if Assigned(OnInternalMouseLeave) then
2180 OnInternalMouseLeave(Self);
2181 end;
2182
2183 procedure TCastleUserInterface.SetFocused(const Value: boolean);
2184 var
2185 OldValue: Boolean;
2186 begin
2187 OldValue := FFocused;
2188 FFocused := Value;
2189 if (not OldValue) and Value then
2190 DoInternalMouseEnter
2191 else
2192 if OldValue and (not Value) then
2193 DoInternalMouseLeave;
2194 end;
2195
2196 procedure TCastleUserInterface.SetExists(const Value: boolean);
2197 begin
2198 if FExists <> Value then
2199 begin
2200 FExists := Value;
2201 VisibleChange([chExists]);
2202 if Parent <> nil then
2203 Parent.VisibleChange([chChildrenExists]);
2204 end;
2205 end;
2206
2207 procedure TCastleUserInterface.BorderChange(Sender: TObject);
2208 begin
2209 VisibleChange([chRectangle]);
2210 end;
2211
2212 { We store Left property value in file under "TUIControlPos_Real_Left" name,
2213 to avoid clashing with TComponent magic "left" property name.
2214 The idea how to do this is taken from TComponent's own implementation
2215 of it's "left" magic property (rtl/objpas/classes/compon.inc). }
2216
2217 procedure TCastleUserInterface.ReadRealLeft(Reader: TReader);
2218 begin
2219 FLeft := Reader.ReadSingle;
2220 end;
2221
2222 procedure TCastleUserInterface.WriteRealLeft(Writer: TWriter);
2223 begin
2224 Writer.WriteSingle(FLeft);
2225 end;
2226
2227 procedure TCastleUserInterface.ReadLeft(Reader: TReader);
2228 var
2229 D: Int32;
2230 begin
2231 D := DesignInfo;
2232 LongRec(D).Lo:=Reader.ReadInteger;
2233 DesignInfo := D;
2234 end;
2235
2236 procedure TCastleUserInterface.ReadTop(Reader: TReader);
2237 var
2238 D: Int32;
2239 begin
2240 D := DesignInfo;
2241 LongRec(D).Hi:=Reader.ReadInteger;
2242 DesignInfo := D;
2243 end;
2244
2245 procedure TCastleUserInterface.WriteLeft(Writer: TWriter);
2246 begin
2247 Writer.WriteInteger(LongRec(DesignInfo).Lo);
2248 end;
2249
2250 procedure TCastleUserInterface.WriteTop(Writer: TWriter);
2251 begin
2252 Writer.WriteInteger(LongRec(DesignInfo).Hi);
2253 end;
2254
2255 procedure TCastleUserInterface.DefineProperties(Filer: TFiler);
2256 Var Ancestor : TComponent;
2257 Temp : Int32;
2258 begin
2259 { Don't call inherited that defines magic left/top.
2260 This would make reading design-time "left" broken, it seems that our
2261 declaration of Left with "stored false" would then prevent the design-time
2262 Left from ever loading.
2263
2264 Instead, we'll save design-time "Left" below, under a special name. }
2265
2266 Filer.DefineProperty('TUIControlPos_RealLeft',
2267 {$ifdef FPC}@{$endif} ReadRealLeft,
2268 {$ifdef FPC}@{$endif} WriteRealLeft,
2269 FLeft <> 0);
2270
2271 // TODO: unfinished tests
2272 (*
2273 Filer.DefineProperty('Controls',
2274 {$ifdef FPC}@{$endif} ReadControls,
2275 {$ifdef FPC}@{$endif} WriteControls,
2276 ControlsCount <> 0);
2277 *)
2278
2279 { Code from fpc/trunk/rtl/objpas/classes/compon.inc }
2280 Temp:=0;
2281 Ancestor:=TComponent(Filer.Ancestor);
2282 If Assigned(Ancestor) then Temp:=Ancestor.DesignInfo;
2283 Filer.Defineproperty('TUIControlPos_Design_Left',
2284 {$ifdef FPC}@{$endif} readleft,
2285 {$ifdef FPC}@{$endif} writeleft,
2286 (longrec(DesignInfo).Lo<>Longrec(temp).Lo));
2287 Filer.Defineproperty('TUIControlPos_Design_Top',
2288 {$ifdef FPC}@{$endif} readtop,
2289 {$ifdef FPC}@{$endif} writetop,
2290 (longrec(DesignInfo).Hi<>Longrec(temp).Hi));
2291 end;
2292
2293 function TCastleUserInterface.PropertySections(
2294 const PropertyName: String): TPropertySections;
2295 begin
2296 if PropertyName = 'Exists' then
2297 Result := [psBasic]
2298 else if PropertyName = 'FullSize' then
2299 Result := [psBasic, psLayout]
2300 else if (PropertyName = 'Width') or
2301 (PropertyName = 'Height') or
2302 (PropertyName = 'HeightFraction') or
2303 (PropertyName = 'WidthFraction') or
2304 (PropertyName = 'AutoSizeToChildren') or
2305 (PropertyName = 'AutoSizeToChildrenPaddingTop') or
2306 (PropertyName = 'AutoSizeToChildrenPaddingRight') or
2307 (PropertyName = 'TranslationPersistent') or
2308 (PropertyName = 'HorizontalAnchorSelf') or
2309 (PropertyName = 'HorizontalAnchorParent') or
2310 (PropertyName = 'VerticalAnchorSelf') or
2311 (PropertyName = 'VerticalAnchorParent') or
2312 // (PropertyName = 'Left') or // deprecated
2313 // (PropertyName = 'Bottom') or // deprecated
2314 (PropertyName = 'Border') or
2315 (PropertyName = 'BorderColorPersistent') then
2316 Result := [psLayout]
2317 else
2318 Result := inherited PropertySections(PropertyName);
2319 end;
2320
2321 procedure TCastleUserInterface.SetLeft(const Value: Single);
2322 begin
2323 if FLeft <> Value then
2324 begin
2325 FLeft := Value;
2326 VisibleChange([chRectangle]);
2327 end;
2328 end;
2329
2330 procedure TCastleUserInterface.SetBottom(const Value: Single);
2331 begin
2332 if FBottom <> Value then
2333 begin
2334 FBottom := Value;
2335 VisibleChange([chRectangle]);
2336 end;
2337 end;
2338
2339 {$warnings off} // using deprecated in deprecated
2340
2341 procedure TCastleUserInterface.Align(
2342 const ControlPosition: THorizontalPosition;
2343 const ContainerPosition: THorizontalPosition;
2344 const X: Single = 0);
2345 begin
2346 Left := FastRectWithoutAnchors.AlignCore(ControlPosition, ParentRect, ContainerPosition, X);
2347 end;
2348
2349 procedure TCastleUserInterface.Align(
2350 const ControlPosition: TVerticalPosition;
2351 const ContainerPosition: TVerticalPosition;
2352 const Y: Single = 0);
2353 begin
2354 Bottom := FastRectWithoutAnchors.AlignCore(ControlPosition, ParentRect, ContainerPosition, Y);
2355 end;
2356
2357 procedure TCastleUserInterface.AlignHorizontal(
2358 const ControlPosition: TPositionRelative;
2359 const ContainerPosition: TPositionRelative;
2360 const X: Single);
2361 begin
2362 Align(
2363 THorizontalPosition(ControlPosition),
2364 THorizontalPosition(ContainerPosition), X);
2365 end;
2366
2367 procedure TCastleUserInterface.AlignVertical(
2368 const ControlPosition: TPositionRelative;
2369 const ContainerPosition: TPositionRelative;
2370 const Y: Single);
2371 begin
2372 Align(
2373 TVerticalPosition(ControlPosition),
2374 TVerticalPosition(ContainerPosition), Y);
2375 end;
2376
2377 procedure TCastleUserInterface.Center;
2378 begin
2379 Align(hpMiddle, hpMiddle);
2380 Align(vpMiddle, vpMiddle);
2381 end;
2382
2383 {$warnings on}
2384
2385 procedure TCastleUserInterface.BeforeSizing;
2386 begin
2387 end;
2388
2389 procedure TCastleUserInterface.PreferredSize(var PreferredWidth, PreferredHeight: Single);
2390 begin
2391 // nothing to be done here
2392 end;
2393
2394 function TCastleUserInterface.RectWithoutAnchors: TFloatRectangle;
2395
2396 procedure UpdateSizeFromChildren;
2397 var
2398 I: Integer;
2399 C: TCastleUserInterface;
2400 ChildRect: TFloatRectangle;
2401 begin
2402 if FSizeFromChildrenValid then Exit;
2403 FSizeFromChildrenValid := true;
2404 FSizeFromChildrenWidth := 0;
2405 FSizeFromChildrenHeight := 0;
2406
2407 for I := 0 to ControlsCount - 1 do
2408 begin
2409 C := Controls[I];
2410 if not C.Exists then Continue;
2411
2412 { Calculate ChildRect.
2413 We cannot use C.EffectiveRect or C.RectWithAnchors now,
2414 as they would query ParentRect, thus recursively asking for our
2415 current size.
2416 Although FSizeFromChildrenValid would prevent from entering an infinite
2417 loop, it would be still unreliable to use such result. }
2418 ChildRect := C.FastRectWithoutAnchors.ScaleAround0(1 / UIScale);
2419 if ChildRect.IsEmpty then
2420 Continue;
2421
2422 { We had 2, much more complicated and more limited, implementations of this :)
2423 Note that the instruction below makes sense both for both when
2424 C.HorizontalAnchorSelf = C.HorizontalAnchorParent = hpLeft and when
2425 C.HorizontalAnchorSelf = C.HorizontalAnchorParent = hpRight.
2426 }
2427
2428 MaxVar(FSizeFromChildrenWidth , ChildRect.Left + ChildRect.Width + Abs(C.Translation.X) + FBorder.TotalWidth);
2429 MaxVar(FSizeFromChildrenHeight, ChildRect.Bottom + ChildRect.Height + Abs(C.Translation.Y) + FBorder.TotalHeight);
2430 end;
2431
2432 FSizeFromChildrenWidth := FSizeFromChildrenWidth + AutoSizeToChildrenPaddingRight;
2433 FSizeFromChildrenHeight := FSizeFromChildrenHeight + AutoSizeToChildrenPaddingTop;
2434 end;
2435
2436 var
2437 PR: TFloatRectangle;
2438 W, H, BorderW, BorderH: Single;
2439 begin
2440 if FInsideRectWithoutAnchors then
2441 begin
2442 WriteLnWarning('UI control ' + DebugName + ' encountered an endless loop when trying to calculate it''s size. This means that UI child size depends on the parent (e.g. using FullSize or WidthFraction or HeightFraction),' + ' while at the same time UI parent size depends on the child (e.g. using AutoSizeToChildren).');
2443 Exit(TFloatRectangle.Empty);
2444 end;
2445 FInsideRectWithoutAnchors := true;
2446
2447 BeforeSizing;
2448
2449 if AutoSizeToChildren then
2450 begin
2451 UpdateSizeFromChildren;
2452 if (FSizeFromChildrenWidth <= 0) or
2453 (FSizeFromChildrenHeight <= 0) then
2454 Result := TFloatRectangle.Empty
2455 else
2456 {$warnings off} // using deprecated Left, Bottom to keep them working
2457 Result := FloatRectangle(Left, Bottom, FSizeFromChildrenWidth, FSizeFromChildrenHeight).
2458 ScaleAround0(UIScale);
2459 {$warnings on}
2460 end else
2461 if FullSize then
2462 begin
2463 Result := ParentRect;
2464 end else
2465 begin
2466 W := Width * UIScale;
2467 H := Height * UIScale;
2468 if (WidthFraction <> 0) or (HeightFraction <> 0) then
2469 begin
2470 PR := ParentRect;
2471 if WidthFraction <> 0 then
2472 W := WidthFraction * PR.Width;
2473 if HeightFraction <> 0 then
2474 H := HeightFraction * PR.Height;
2475 end;
2476
2477 // subtract Border from W, H
2478 BorderW := Border.TotalWidth * UIScale;
2479 BorderH := Border.TotalHeight * UIScale;
2480 W := W - BorderW;
2481 H := H - BorderH;
2482
2483 PreferredSize(W, H);
2484
2485 // add Border around Result
2486 W := W + BorderW;
2487 H := H + BorderH;
2488
2489 if (W > 0) and (H > 0) then
2490 begin
2491 {$warnings off} // using deprecated Left, Bottom to keep them working
2492 Result := FloatRectangle(Left * UIScale, Bottom * UIScale, W, H);
2493 {$warnings on}
2494 //Result.Left := Result.Left - FBorder.TotalLeft * UIScale; // no need to
2495 //Result.Bottom := Result.Bottom - FBorder.TotalBottom * UIScale; // no need to
2496 end else
2497 Result := TFloatRectangle.Empty;
2498 end;
2499
2500 FInsideRectWithoutAnchors := false;
2501 end;
2502
2503 function TCastleUserInterface.EffectiveRect: TFloatRectangle;
2504 begin
2505 Result := RectWithAnchors(true).ScaleAround0(1 / UIScale);
2506 end;
2507
2508 function TCastleUserInterface.EffectiveWidth: Single;
2509 var
2510 R: TFloatRectangle;
2511 begin
2512 { Naive implementation:
2513 Result := EffectiveRect.Width; }
2514
2515 { Optimized implementation, knowing that RectWithAnchors(true) does not
2516 change RectWithoutAnchors.Width:
2517 Result := RectWithoutAnchors.ScaleAround0(1 / UIScale).Width; }
2518
2519 { Optimized implementation: }
2520 R := FastRectWithoutAnchors;
2521 if R.IsEmpty then
2522 Result := 0
2523 else
2524 begin
2525 Result := R.Width / UIScale;
2526 //Assert(Result = EffectiveRect.Width);
2527 end;
2528 end;
2529
2530 function TCastleUserInterface.EffectiveHeight: Single;
2531 var
2532 R: TFloatRectangle;
2533 begin
2534 R := FastRectWithoutAnchors;
2535 if R.IsEmpty then
2536 Result := 0
2537 else
2538 begin
2539 Result := R.Height / UIScale;
2540 //Assert(Result = EffectiveRect.Height);
2541 end;
2542 end;
2543
2544 function TCastleUserInterface.CalculatedWidth: Cardinal;
2545 begin
2546 Result := Round(EffectiveWidth);
2547 end;
2548
2549 function TCastleUserInterface.CalculatedHeight: Cardinal;
2550 begin
2551 Result := Round(EffectiveHeight);
2552 end;
2553
2554 function TCastleUserInterface.CalculatedRect: TRectangle;
2555 begin
2556 Result := EffectiveRect.Round;
2557 end;
2558
2559 function TCastleUserInterface.FastRectWithoutAnchors: TFloatRectangle;
2560 begin
2561 if FUseCachedRectWithoutAnchors <> 0 then
2562 Result := FCachedRectWithoutAnchors
2563 else
2564 Result := RectWithoutAnchors;
2565 end;
2566
2567 function TCastleUserInterface.EffectiveFullSize: Boolean;
2568 begin
2569 Result := FullSize and not AutoSizeToChildren;
2570 end;
2571
2572 function TCastleUserInterface.RectWithAnchors(const CalculateEvenWithoutContainer: boolean): TFloatRectangle;
2573 var
2574 PR: TFloatRectangle;
2575 begin
2576 {$warnings off} // using deprecated ContainerSizeKnown for now
2577 if (not ContainerSizeKnown) and
2578 (not CalculateEvenWithoutContainer) then
2579 { Don't call virtual Rect in this state, Rect implementations
2580 typically assume that ParentRect is sensible.
2581 This is crucial, various programs will crash without it. }
2582 Exit(TFloatRectangle.Empty);
2583 {$warnings on}
2584
2585 Result := FastRectWithoutAnchors;
2586
2587 { apply my Anchors and parent Border }
2588 if not EffectiveFullSize then
2589 begin
2590 PR := ParentRect;
2591 Result.Left := Result.Left +
2592 Result.AlignCore(HorizontalAnchorSelf, PR, HorizontalAnchorParent,
2593 UIScale * Translation.X);
2594 Result.Bottom := Result.Bottom +
2595 Result.AlignCore(VerticalAnchorSelf, PR, VerticalAnchorParent,
2596 UIScale * Translation.Y);
2597 end;
2598 end;
2599
2600 function TCastleUserInterface.RenderRectWithBorder: TFloatRectangle;
2601 var
2602 T: TVector2;
2603 begin
2604 Result := RectWithAnchors;
2605 { transform local to container }
2606 if Parent <> nil then
2607 begin
2608 T := Parent.LocalToContainerTranslation;
2609 Result.Left := Result.Left + T[0];
2610 Result.Bottom := Result.Bottom + T[1];
2611 end;
2612 end;
2613
2614 function TCastleUserInterface.RenderRect: TFloatRectangle;
2615 begin
2616 Result := RenderRectWithBorder;
2617 if FBorder.Exists then // optimize common case
2618 Result := Result.
2619 RemoveTop (FBorder.TotalTop * UIScale).
2620 RemoveRight (FBorder.TotalRight * UIScale).
2621 RemoveBottom(FBorder.TotalBottom * UIScale).
2622 RemoveLeft (FBorder.TotalLeft * UIScale);
2623 end;
2624
2625 function TCastleUserInterface.ScreenRect: TRectangle;
2626 begin
2627 Result := RenderRect.Round;
2628 end;
2629
2630 function TCastleUserInterface.LocalToContainerTranslation: TVector2;
2631 var
2632 RA: TFloatRectangle;
2633 begin
2634 if Parent <> nil then
2635 Result := Parent.LocalToContainerTranslation
2636 else
2637 Result := TVector2.Zero;
2638
2639 RA := RectWithAnchors;
2640 Result.X := Result.X + RA.Left;
2641 Result.Y := Result.Y + RA.Bottom;
2642 end;
2643
2644 function TCastleUserInterface.LocalToContainerTranslationShiftBorder: TVector2;
2645 begin
2646 Result := LocalToContainerTranslation;
2647 if FBorder.Exists then // optimize common case
2648 begin
2649 Result.X := Result.X + FBorder.TotalLeft * UIScale;
2650 Result.Y := Result.Y + FBorder.TotalBottom * UIScale;
2651 end;
2652 end;
2653
2654 function TCastleUserInterface.ContainerToLocalPosition(ContainerPosition: TVector2;
2655 const ContainerPositionScaled: Boolean): TVector2;
2656 begin
2657 { LocalToContainerTranslationShiftBorder is always in scaled coordinates.
2658 So to implement ContainerPositionScaled = false, we need to multiply by UIScale,
2659 only to later divide by it...
2660 This should be cleaned up. But then, more routines like RectWithAnchors,
2661 ParentRect will require an alternative "unscaled" variant,
2662 or we should just use "unscaled" coordinates more throughout the internal code. }
2663 if not ContainerPositionScaled then
2664 ContainerPosition := ContainerPosition * UIScale;
2665 Result := (ContainerPosition - LocalToContainerTranslationShiftBorder) / UIScale;
2666 end;
2667
2668 function TCastleUserInterface.LocalToContainerPosition(const LocalPosition: TVector2;
2669 const ContainerPositionScaled: Boolean): TVector2;
2670 begin
2671 Result := LocalPosition * UIScale + LocalToContainerTranslationShiftBorder;
2672 if not ContainerPositionScaled then
2673 Result := Result / UIScale;
2674 end;
2675
2676 function TCastleUserInterface.ParentRect: TFloatRectangle;
2677 begin
2678 if Parent <> nil then
2679 begin
2680 Result := Parent.FastRectWithoutAnchors;
2681 Result.Left := 0;
2682 Result.Bottom := 0;
2683
2684 if Parent.FBorder.Exists then // optimize common case
2685 Result := Result.
2686 RemoveTop (Parent.FBorder.TotalTop * UIScale).
2687 RemoveRight (Parent.FBorder.TotalRight * UIScale).
2688 RemoveBottom(Parent.FBorder.TotalBottom * UIScale).
2689 RemoveLeft (Parent.FBorder.TotalLeft * UIScale);
2690 end else
2691 {$warnings off} // using deprecated ContainerRect
2692 Result := FloatRectangle(ContainerRect);
2693 {$warnings on}
2694 end;
2695
2696 procedure TCastleUserInterface.SetHorizontalAnchorSelf(const Value: THorizontalPosition);
2697 begin
2698 if FHorizontalAnchorSelf <> Value then
2699 begin
2700 FHorizontalAnchorSelf := Value;
2701 VisibleChange([chRectangle]);
2702 end;
2703 end;
2704
2705 procedure TCastleUserInterface.SetHorizontalAnchorParent(const Value: THorizontalPosition);
2706 begin
2707 if FHorizontalAnchorParent <> Value then
2708 begin
2709 FHorizontalAnchorParent := Value;
2710 VisibleChange([chRectangle]);
2711 end;
2712 end;
2713
2714 procedure TCastleUserInterface.SetTranslation(const Value: TVector2);
2715 begin
2716 if not TVector2.PerfectlyEquals(FTranslation, Value) then
2717 begin
2718 FTranslation := Value;
2719 VisibleChange([chRectangle]);
2720 end;
2721 end;
2722
2723 function TCastleUserInterface.GetHorizontalAnchorDelta: Single;
2724 begin
2725 Result := Translation.X;
2726 end;
2727
2728 function TCastleUserInterface.GetVerticalAnchorDelta: Single;
2729 begin
2730 Result := Translation.Y;
2731 end;
2732
2733 procedure TCastleUserInterface.SetHorizontalAnchorDelta(const Value: Single);
2734 begin
2735 Translation := Vector2(Value, Translation.Y);
2736 end;
2737
2738 procedure TCastleUserInterface.SetVerticalAnchorDelta(const Value: Single);
2739 begin
2740 Translation := Vector2(Translation.X, Value);
2741 end;
2742
2743 procedure TCastleUserInterface.SetVerticalAnchorSelf(const Value: TVerticalPosition);
2744 begin
2745 if FVerticalAnchorSelf <> Value then
2746 begin
2747 FVerticalAnchorSelf := Value;
2748 VisibleChange([chRectangle]);
2749 end;
2750 end;
2751
2752 procedure TCastleUserInterface.SetVerticalAnchorParent(const Value: TVerticalPosition);
2753 begin
2754 if FVerticalAnchorParent <> Value then
2755 begin
2756 FVerticalAnchorParent := Value;
2757 VisibleChange([chRectangle]);
2758 end;
2759 end;
2760
2761 procedure TCastleUserInterface.Anchor(const AHorizontalAnchor: THorizontalPosition;
2762 const TranslationX: Single);
2763 begin
2764 HorizontalAnchorSelf := AHorizontalAnchor;
2765 HorizontalAnchorParent := AHorizontalAnchor;
2766 Translation := Vector2(TranslationX, Translation.Y);
2767 end;
2768
2769 procedure TCastleUserInterface.Anchor(
2770 const AHorizontalAnchorSelf, AHorizontalAnchorParent: THorizontalPosition;
2771 const TranslationX: Single);
2772 begin
2773 HorizontalAnchorSelf := AHorizontalAnchorSelf;
2774 HorizontalAnchorParent := AHorizontalAnchorParent;
2775 Translation := Vector2(TranslationX, Translation.Y);
2776 end;
2777
2778 procedure TCastleUserInterface.Anchor(const AVerticalAnchor: TVerticalPosition;
2779 const TranslationY: Single);
2780 begin
2781 VerticalAnchorSelf := AVerticalAnchor;
2782 VerticalAnchorParent := AVerticalAnchor;
2783 Translation := Vector2(Translation.X, TranslationY);
2784 end;
2785
2786 procedure TCastleUserInterface.Anchor(
2787 const AVerticalAnchorSelf, AVerticalAnchorParent: TVerticalPosition;
2788 const TranslationY: Single);
2789 begin
2790 VerticalAnchorSelf := AVerticalAnchorSelf;
2791 VerticalAnchorParent := AVerticalAnchorParent;
2792 Translation := Vector2(Translation.X, TranslationY);
2793 end;
2794
2795 procedure TCastleUserInterface.SetWidth(const Value: Single);
2796 begin
2797 if FWidth <> Value then
2798 begin
2799 FWidth := Value;
2800 VisibleChange([chRectangle]);
2801 end;
2802 end;
2803
2804 procedure TCastleUserInterface.SetHeight(const Value: Single);
2805 begin
2806 if FHeight <> Value then
2807 begin
2808 FHeight := Value;
2809 VisibleChange([chRectangle]);
2810 end;
2811 end;
2812
2813 procedure TCastleUserInterface.SetWidthFraction(const Value: Single);
2814 begin
2815 if FWidthFraction <> Value then
2816 begin
2817 FWidthFraction := Value;
2818 VisibleChange([chRectangle]);
2819 end;
2820 end;
2821
2822 procedure TCastleUserInterface.SetHeightFraction(const Value: Single);
2823 begin
2824 if FHeightFraction <> Value then
2825 begin
2826 FHeightFraction := Value;
2827 VisibleChange([chRectangle]);
2828 end;
2829 end;
2830
2831 procedure TCastleUserInterface.SetFullSize(const Value: boolean);
2832 begin
2833 if FFullSize <> Value then
2834 begin
2835 FFullSize := Value;
2836 VisibleChange([chRectangle]);
2837 end;
2838 end;
2839
2840 procedure TCastleUserInterface.SetBorderColor(const Value: TCastleColor);
2841 begin
2842 if not TCastleColor.PerfectlyEquals(FBorderColor, Value) then
2843 begin
2844 FBorderColor := Value;
2845 VisibleChange([chRender]);
2846 end;
2847 end;
2848
2849 procedure TCastleUserInterface.SetAutoSizeToChildren(const Value: Boolean);
2850 begin
2851 if FAutoSizeToChildren <> Value then
2852 begin
2853 FAutoSizeToChildren := Value;
2854 FSizeFromChildrenValid := false;
2855 end;
2856 end;
2857
2858 procedure TCastleUserInterface.SetAutoSizeToChildrenPaddingRight(const Value: Single);
2859 begin
2860 if FAutoSizeToChildrenPaddingRight <> Value then
2861 begin
2862 FAutoSizeToChildrenPaddingRight := Value;
2863 FSizeFromChildrenValid := false;
2864 end;
2865 end;
2866
2867 procedure TCastleUserInterface.SetAutoSizeToChildrenPaddingTop(const Value: Single);
2868 begin
2869 if FAutoSizeToChildrenPaddingTop <> Value then
2870 begin
2871 FAutoSizeToChildrenPaddingTop := Value;
2872 FSizeFromChildrenValid := false;
2873 end;
2874 end;
2875
2876 procedure TCastleUserInterface.SetCulling(const Value: Boolean);
2877 begin
2878 if FCulling <> Value then
2879 begin
2880 FCulling := Value;
2881 if not Value then
2882 FVisible := true; // Visible is always true when Culling is false
2883 VisibleChange([chRender]);
2884 end;
2885 end;
2886
2887 procedure TCastleUserInterface.SetCustomTheme(const Value: TCastleTheme);
2888 begin
2889 if FCustomTheme <> Value then
2890 begin
2891 FCustomThemeObserver.Observed := Value;
2892 FCustomTheme := Value;
2893 VisibleChange([chRender]);
2894 end;
2895 end;
2896
2897 procedure TCastleUserInterface.CustomThemeFreeNotification(
2898 const Sender: TFreeNotificationObserver);
2899 begin
2900 CustomTheme := nil;
2901 end;
2902
2903 function TCastleUserInterface.Theme: TCastleTheme;
2904 begin
2905 if CustomTheme <> nil then
2906 Result := CustomTheme
2907 else
2908 Result := CastleUIControls.Theme;
2909 end;
2910
2911 procedure TCastleUserInterface.SetTooltipControl(const Value: TCastleUserInterface);
2912 begin
2913 if FTooltipControl <> Value then
2914 begin
2915 FTooltipControlObserver.Observed := Value;
2916 FTooltipControl := Value;
2917 VisibleChange([chRender]);
2918 end;
2919 end;
2920
2921 procedure TCastleUserInterface.TooltipControlFreeNotification(
2922 const Sender: TFreeNotificationObserver);
2923 begin
2924 TooltipControl := nil;
2925 end;
2926
2927 procedure TCastleUserInterface.SetClipChildren(const Value: Boolean);
2928 begin
2929 if FClipChildren <> Value then
2930 begin
2931 FClipChildren := Value;
2932 VisibleChange([chRender]);
2933 end;
2934 end;
2935
2936 procedure TCastleUserInterface.EditorAllowResize(
2937 out ResizeWidth, ResizeHeight: Boolean; out Reason: String);
2938 begin
2939 ResizeWidth := true;
2940 ResizeHeight := true;
2941 Reason := '';
2942
2943 if AutoSizeToChildren then
2944 begin
2945 ResizeWidth := false;
2946 ResizeHeight := false;
2947 Reason := SAppendPart(Reason, NL, 'Turn off "AutoSizeToChildren" to change size.');
2948 end;
2949
2950 if FullSize then
2951 begin
2952 ResizeWidth := false;
2953 ResizeHeight := false;
2954 Reason := SAppendPart(Reason, NL, 'Turn off "FullSize" to change size.');
2955 end;
2956
2957 if WidthFraction <> 0 then
2958 begin
2959 ResizeWidth := false;
2960 Reason := SAppendPart(Reason, NL, 'Set "WidthFraction" to 0 to be able to freely change "Width".');
2961 end;
2962
2963 if HeightFraction <> 0 then
2964 begin
2965 ResizeHeight := false;
2966 Reason := SAppendPart(Reason, NL, 'Set "HeightFraction" to 0 to be able to freely change "Height".');
2967 end;
2968 end;
2969
2970 function TCastleUserInterface.EffectiveHeightForChildren: Single;
2971 begin
2972 Result := Max(0, EffectiveHeight - Border.TotalHeight);
2973 end;
2974
2975 function TCastleUserInterface.EffectiveWidthForChildren: Single;
2976 begin
2977 Result := Max(0, EffectiveWidth - Border.TotalWidth);
2978 end;
2979
2980 function TCastleUserInterface.GetEnumerator: TEnumerator;
2981 begin
2982 Result := TEnumerator.Create(FControls);
2983 end;
2984
2985 procedure TCastleUserInterface.Loaded;
2986 begin
2987 inherited;
2988
2989 {$warnings off} // using deprecated to warn about it
2990 if Left <> 0 then
2991 WritelnWarning('Left is deprecated (on TCastleUserInterface "%s"). Instead: Add it to Translation.X', [
2992 Name
2993 ]);
2994 if Bottom <> 0 then
2995 WritelnWarning('Bottom is deprecated (on TCastleUserInterface "%s"). Instead: Add it to Translation.Y', [
2996 Name
2997 ]);
2998 {$warnings on}
2999 end;
3000
3001 procedure TCastleUserInterface.InternalSetTooltipExists(const Value: Boolean);
3002 begin
3003 if TooltipControl <> nil then
3004 TooltipControl.Exists := Value;
3005 end;
3006
3007 procedure TCastleUserInterface.DesignerInfo(const SList: TStrings);
3008 var
3009 RR: TFloatRectangle;
3010 AllowResizeWidth, AllowResizeHeight: Boolean;
3011 ReasonCannotResize: String;
3012 begin
3013 inherited;
3014 RR := RenderRectWithBorder;
3015 if RR.IsEmpty then
3016 begin
3017 SList.Add('Size: Empty');
3018 end else
3019 begin
3020 SList.Add(Format(
3021 'Effective size: %f x %f', [
3022 EffectiveWidth,
3023 EffectiveHeight
3024 ]));
3025 SList.Add(Format('Render rectangle (scaled and with anchors):' + NL +
3026 ' Left x Bottom: %f x %f' + NL +
3027 ' Size: %f x %f', [
3028 RR.Left,
3029 RR.Bottom,
3030 RR.Width,
3031 RR.Height
3032 ]));
3033
3034 EditorAllowResize(
3035 { out } AllowResizeWidth,
3036 { out } AllowResizeHeight,
3037 { out } ReasonCannotResize);
3038 if not (AllowResizeWidth and AllowResizeHeight) then
3039 begin
3040 SList.Add('Cannot be resized at design-time because of:' + NL + ReasonCannotResize);
3041 end;
3042 end;
3043 end;
3044
3045 procedure TCastleUserInterface.DesignerWarnings(const SList: TStrings);
3046 begin
3047 inherited;
3048 if (Parent <> nil) and
3049 (not Parent.RenderRect.Contains(RenderRectWithBorder)) then
3050 SList.Add('The rectangle occupied by this control is outside of the parent rectangle. The events (like mouse clicks) may not reach this control. You must always fit child control inside the parent.');
3051 end;
3052
3053 {$define read_implementation_methods}
3054 {$I auto_generated_persistent_vectors/tcastleuserinterface_persistent_vectors.inc}
3055 {$undef read_implementation_methods}
3056
3057 {$endif read_implementation}