Debian Codegraph @

src/ui/castleuicontrols_view.inc

raw
1 {%MainUnit castleuicontrols.pas}
2 {
3 Copyright 2015-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 { "View" represents the current state of your application user interface.
22 See also https://castle-engine.io/views
23 for an overview of using TCastleView.
24
25 In a given container (like a window), in the simple case only one TCastleView is @italic(current) at a given time,
26 and it can be get or set using the @link(TCastleContainer.View) property.
27 In more complex cases, you can use @link(TCastleContainer.PushView) and @link(TCastleContainer.PopView)
28 to build a stack of views, and in effect multiple views are active at the same time.
29 All of the views on stack are @italic(started), but only the top-most is @italic(resumed).
30
31 Each TCastleView has @link(Start) and @link(Stop)
32 methods that you can override to perform work when view becomes
33 part of the current view stack, or stops being part of it.
34
35 You can also override @link(Resume) and @link(Pause) methods,
36 to perform work when the view becomes the top-most view or is no longer
37 the top-most view. The distinction becomes important once you play
38 around with pushing/popping view.
39
40 To define view user interface:
41
42 @orderedList(
43 @item(It is simplest to set @link(DesignUrl)
44 to the design file you created using @url(https://castle-engine.io/manual_editor.php CGE editor).
45 Such user interface controls will be created right before @link(Start)
46 and destroyed right after @link(Stop) (so the view UI always "resets"
47 when view starts).)
48
49 @item(You can always create more UI controls and add them to the view at any point.
50 The view is a @link(TCastleUserInterface) descendant and you can add UI to it
51 just by using @link(TCastleUserInterface.InsertFront).
52
53 UI children can be added anytime you want, e.g. in @link(Start) or in overridden
54 constructor.
55
56 UI children can be removed or destroyed anytime you want as well.
57 You can use @link(FreeAtStop) as an owner for anything you want to be automatically
58 destroyed at @link(Stop).)
59 )
60
61 Current view is placed on the list of container controls.
62 This way view is notified about UI events, and can react to them.
63 Note that our children will handle events @italic(before) the view itself
64 is notified about them, following @link(TCastleUserInterface) events behavior.
65 This way view can:
66
67 @unorderedList(
68 @item(React to @link(TCastleUserInterface.Press Press),
69 @link(TCastleUserInterface.Release Release) of keys or mouse buttons,)
70
71 @item(do something continuos in @link(TCastleUserInterface.Update Update).)
72 )
73
74 See the TCastleUserInterface class for a lot of useful methods that you can
75 override in your view descendants to capture various events. }
76 TCastleView = class(TCastleUserInterface)
77 private
78 type
79 TDesignOwner = class(TComponent)
80 protected
81 ParentView: TCastleView;
82 procedure Notification(AComponent: TComponent; Operation: TOperation); override;
83 procedure ValidateRename(AComponent: TComponent; const CurName, NewName: String); override;
84 end;
85
86 var
87 FStartContainer: TCastleContainer;
88 FStartContainerObserver: TFreeNotificationObserver;
89 FInterceptInput, FFreeWhenStopped: boolean;
90 FFreeAtStop: TComponent;
91 FWaitingForRender: TNotifyEventList;
92 FCallBeforeUpdate: TNotifyEventList;
93
94 { Design* private fields }
95 FDesignUrl: String;
96 FDesignLoaded: TCastleUserInterface;
97 FDesignLoadedOwner: TDesignOwner;
98 FDesignPreload: Boolean;
99 FDesignPreloadedSerialized: TCastleComponentFactory;
100 FDesignPreloaded: TCastleUserInterface;
101 FDesignPreloadedOwner: TComponent;
102
103 procedure InternalStart(const AContainer: TCastleContainer);
104 procedure InternalStop;
105 procedure StartContainerFreeNotification(const Sender: TFreeNotificationObserver);
106 { Stop yourself and remove from FViewStack, if present there. }
107 procedure StopIfStarted;
108
109 { Design* private routines }
110 procedure SetDesignUrl(const Value: String);
111 procedure SetDesignPreload(const Value: Boolean);
112 procedure LoadDesign;
113 procedure UnLoadDesign;
114 procedure PreloadDesign;
115 procedure UnPreloadDesign;
116
117 { Set the published field corresponding to ReferenceName (usually equal to AComponent.Name).
118 If Enable=true: set it to AComponent.
119 If Enable=false: set it to nil. }
120 procedure SetNameReference(const AComponent: TComponent; const ReferenceName: String; const Enable: Boolean);
121
122 class function GetCurrent: TCastleView; static;
123 class procedure SetCurrent(const Value: TCastleView); static;
124 class function GetCurrentTop: TCastleView; static;
125 class function GetStateStack(const Index: Integer): TCastleView; static;
126
127 { Container in which view is started (if view is started)
128 or on which we predict it will be started (if view is not started yet).
129
130 If view is not started yet,
131 this is
132 @link(TCastleApplication.MainWindow Application.MainWindow)
133 if you use CastleWindow or
134 @link(TCastleControl.MainControl) if you use CastleControl.
135
136 When the view has started, then @link(Container) property (from
137 ancestor, see TCastleUserInterface.Container) is equal to this. }
138 function PredictedContainer: TCastleContainer;
139 protected
140 { The container size is always known: we assume that view will be part
141 of PredictedContainer, if the view not yet started.
142
143 So the view knows container size, regardless if we are between Start / Stop,
144 regardless if the TCastleView is already added to some TCastleContainer.Children.
145 This makes all other routines, like ParentRect, EffectiveRect, EffectiveWidth,
146 EffectiveHeight also work. }
147 function ContainerWidth: Cardinal; override;
148 function ContainerHeight: Cardinal; override;
149 function ContainerRect: TRectangle; override;
150 function ContainerSizeKnown: boolean; override;
151
152 function StateContainer: TCastleContainer; deprecated 'use Container to get the container in which we are already started, use PredictedContainer if the state is not yet started';
153
154 { The container in which the view works.
155
156 This is just like @link(Container) property (from
157 ancestor, see TCastleUserInterface.Container) but it is
158 already assigned even during @link(Start) and @link(Stop).
159
160 This method @italic(deliberately hides the ancestor @link(TCastleUserInterface.Container)
161 method).
162 This way it will work always, in particular also during @link(Start) method.
163 This allows you to do code like this in overridden @link(Start) method:
164
165 @longCode(# Container.OverrideCursor := mcNone; #) }
166 function Container: TCastleContainer;
167
168 { Assign this component as owner for your controls,
169 to make them freed right after nearest @link(Stop).
170
171 This component is created on-demand (whenever you access it)
172 and always destroyed right after running view @link(Stop) method.
173
174 The idea is that you can assign it as @italic(owner) (1st parameter to the constructor
175 of @code(TComponent) class or any classes descending from @code(TComponent),
176 this includes all CGE components) of something, like this:
177
178 @longCode(#
179 MyInstance := TSomeComponent.Create(FreeAtStop);
180 #)
181
182 And in effect, you know that @code(MyInstance) will be freed after the view stops.
183 So you don't need to worry about it anymore, in particular you don't need to do
184 @code(FreeAndNil(MyInstance)) in the state @link(Stop). }
185 function FreeAtStop: TComponent;
186 public
187 { When @true, view operations will send a log to CastleLog. }
188 class var Log: boolean;
189
190 { Create an instance of the view.
191 You willl typically create one instance of each view class
192 (like TViewMain, TViewPlay) at the application initialization
193 (e.g. in Application.OnInitialize callback), like
194
195 @longCode(#
196 ViewMainMenu := TViewMainMenu.Create(Application);
197 ViewPlay := TViewPlay.Create(Application);
198 #)
199
200 Later you switch between views using @link(TCastleContainer.View) or
201 @link(TCastleContainer.PushView) or
202 @link(TCastleContainer.PopView),
203 like this:
204
205 @longCode(#
206 Container.View := ViewMain;
207 #)
208
209 See https://castle-engine.io/views and numerous engine examples.
210 }
211 constructor Create(AOwner: TComponent); override;
212 destructor Destroy; override;
213
214 { Create the instance TCastleView that will be automatically freed when
215 the view is stopped.
216 This allows alternative usage of views (as opposed to the ones described in @link(Create)
217 docs), where you create short-lived instances of view classes.
218 Use it like this:
219
220 @longCode(#
221 Container.View := TViewMain.CreateUntilStopped;
222 #)
223
224 The advantages:
225
226 @unorderedList(
227 @item(You don't need to worry
228 that some view field value will "survive" with an invalid value after
229 @link(Stop). So you don't need to clear everything in @link(Stop)
230 or initialize everything in @link(Start), instead you can depend
231 that @link(Start) happens only once right after the constructor,
232 so the instance fields are clear.)
233
234 @item(You avoid having global variables, keeping singletons of each view class.
235 So the code is a little safer.)
236
237 @item(You can reintroduce your own constructor to require some parameters,
238 instead of exposing view parameters as public fields/properties.)
239 )
240
241 The disadvantage is that you cannot store in view fields anything
242 that should "survive" the view @link(Stop).
243 You can instead use "class variables" in view class, or any global variable.
244 }
245 constructor CreateUntilStopped;
246
247 { Executed when view becomes active, it's now part of the view stack.
248
249 Started view is part of the ViewStack, and will soon become
250 running (top-most on the stack). When the view is set to be current,
251 by @code(Container.View := MyView), this happens:
252
253 @orderedList(
254 @item(MyView is pushed as the top-most view on view stack.)
255 @item(MyView.Start is called.)
256 @item(MyView is added to the @link(TCastleContainer.Controls) list
257 (using the container where you set @link(TCastleContainer.PushView),
258 @link(TCastleContainer.View)).
259 This also means that the view methods GLContextOpen and Resize are called
260 (as for all normal TCastleUserInterface instances).)
261 @item(MyStar.Resume is called.)
262 ) }
263 procedure Start; virtual;
264
265 { Executed when view is no longer active, no longer part of view stack.
266
267 When the view stops becoming active, this happens:
268
269 @orderedList(
270 @item(MyView.Pause is called.)
271 @item(MyView is removed from the
272 @code(TCastleContainer.Controls) list
273 (using the container to which we were added).
274 So the view method GLContextClose is called
275 (as for all normal TCastleUserInterface instances).)
276 @item(MyView.Stop is called.)
277 @item(MyView is removed from the on view stack.)
278 )
279
280 This is always called to finalize the started view.
281 When the view is destroyed, it's @link(Pause) and @link(Stop)
282 are called too, so you can use this method to reliably finalize whatever
283 you initialized in @link(Start). }
284 procedure Stop; virtual;
285
286 { Executed when view is now the top-most view. See @link(Start) and @link(Stop)
287 docs about view lifecycle methods.
288 This is called after @link(Start), it is also called
289 when you pop another view, making this view the top-most. }
290 procedure Resume; virtual;
291
292 { Executed when view is no longer the top-most view. See @link(Start) and @link(Stop)
293 docs about view lifecycle methods.
294 This is called before @link(Stop), it is also called
295 when another view is pushed over this view, so this stops
296 being the the top-most view. }
297 procedure Pause; virtual;
298
299 procedure Finish; virtual; deprecated 'use Stop';
300
301 { View is right now part of the view stack, which means
302 it's between @link(Start) and @link(Stop) calls.
303 The view is added to the stack before the @link(Start) call,
304 and removed after the @link(Stop) call, so this returns @true
305 during all the methods --- @link(Start), @link(Resume), @link(Pause), @link(Stop). }
306 function Active: boolean;
307
308 { Prevents passing mouse/keyboard events to the UI views underneath.
309
310 More precisely, when this property is @true, then the
311 @link(Press), @link(Release) and @link(Motion) events are marked as
312 "handled" in this UI view. This means that they will not be processed
313 further, by UI controls under this view, in particular by UI views
314 that are underneath this view in @italic(view stack) (created
315 by @link(Push) method). They will also not be passed to final container
316 (TCastleWindow, TCastleControl) callbacks like
317 TCastleWindow.OnPress (as these callbacks are always used at the end,
318 when nothing else handled the event).
319
320 Note that setting this to @true means that calling @code(inherited)
321 from your @link(Press) overridden implementation will always return @true,
322 as if the ancestor handled all the items. For this reason,
323 in such case you should not immediately Exit when @code(inherited) is @true.
324 You should just ignore the ancestor result, like this:
325
326 @longCode(#
327 function TMyView.Press(const Event: TInputPressRelease): Boolean;
328 begin
329 Result := inherited;
330 // ignore the ancestor result, as we use InterceptInput, so ancestor always returns true
331 // if Result the Exit;
332
333 if Event.IsMouseButton(buttonLeft) then
334 begin
335 ...
336 Exit(true);
337 end;
338 end;
339 #)
340 }
341 property InterceptInput: boolean read FInterceptInput write FInterceptInput
342 default false;
343
344 function Press(const Event: TInputPressRelease): boolean; override;
345 function Release(const Event: TInputPressRelease): boolean; override;
346 function Motion(const Event: TInputMotion): boolean; override;
347 procedure Update(const SecondsPassed: Single;
348 var HandleInput: boolean); override;
349 procedure Render; override;
350 function UIScale: Single; override;
351
352 { Load and show a user interface from a .castle-user-interface file,
353 designed in Castle Game Engine Editor.
354
355 This is an utility method, loading a UI in a typical way into the TCastleView.
356 It is not the only way to load a .castle-user-interface file,
357 a more general approach is to use @link(UserInterfaceLoad) from
358 @link(CastleComponentSerialize) unit, and manually call InsertFront
359 to add it to the view UI.
360
361 The loaded UI is returned under the @code(Ui) parameter,
362 unless you use an overloaded version that omits this parameter.
363
364 It is owned by @code(UiOwner), which is useful to find the components
365 by name, like
366 @longCode(#
367 ButtonQuit := UiOwner.FindRequiredComponent('ButtonQuit') as TCastleButton;
368 #)
369
370 The UiOwner, in turn, is owned by the FinalOwner.
371 You typically use this method inside overridden @link(Start),
372 and as FinalOwner you pass @link(FreeAtStop) -- this way the user interface
373 is freed when the view is stopped.
374 }
375 procedure InsertUserInterface(const ADesignUrl: String;
376 const FinalOwner: TComponent;
377 out Ui: TCastleUserInterface; out UiOwner: TComponent); overload; deprecated 'instead of this, set DesignUrl in constructor';
378 procedure InsertUserInterface(const ADesignUrl: String;
379 const FinalOwner: TComponent; out UiOwner: TComponent); overload; deprecated 'instead of this, set DesignUrl in constructor';
380
381 { Wait until the render event happens (to redraw current view),
382 and then call Event.
383
384 The scheduled Event will be called at the @link(Update) time.
385
386 If the view stopped before the scheduled events fired,
387 then the remaining events are ignored.
388 That is, the scheduled events are cleared every time you start the view.
389
390 One use-case of this is to show a loading view,
391 where you load things, but also update the loading progress from time to time.
392 Be careful in this case to not call this @italic(too often),
393 as then your loading time will be tied to rendering time.
394 For example, when the monitor refresh rate is 60, and the "vertical sync"
395 is "on", then the render events happen at most 60 times per second.
396 So if you call WaitForRenderAndCall too often during loading,
397 you may spend more time waiting for render event (each WaitForRenderAndCall
398 taking 1/60 of second) than doing actual loading. }
399 procedure WaitForRenderAndCall(const Event: TNotifyEvent);
400
401 { Load a designed user interface (from .castle-user-interface file)
402 when this view is started.
403 You typically set this property in overridden constructor, and in effect
404 the given design file will be loaded right before @link(Start) and it will be freed
405 right after @link(Stop).
406
407 Typical use-case looks like this:
408
409 @longCode(#
410 constructor TViewPlay.Create(AOwner: TComponent);
411 begin
412 inherited;
413 DesignUrl := 'castle-data:/gameviewplay.castle-user-interface';
414 // DesignPreload := true; // to make future "Container.View := ViewPlay" faster
415 end;
416 #)
417
418 The published fields of this class,
419 if they have equal name to any component in the design,
420 are automatically initialized to the instance of this component.
421 (And they will be set to @nil when the design is destroyed, typically at @link(Stop).)
422
423 You can also modify this property when the view has already started
424 (after @link(Start) and before @link(Stop)) in which case
425 the previous design will be freed and new one will be loaded immediately.
426
427 Set this to empty string (default) to mean "no design should be loaded".
428
429 Note that this is not the only way to load a .castle-user-interface file.
430 A more general approach is to use @link(UserInterfaceLoad),
431 and call @link(InsertFront) to add it to the view UI.
432 Using this property just adds some comfortable automatic behavior
433 (design is freed at stop, published fields of view are set,
434 you can use comfortable @link(DesignPreload)).
435
436 @seealso DesignPreload
437 }
438 property DesignUrl: String read FDesignUrl write SetDesignUrl;
439
440 { Preload the design file (specified in @link(DesignUrl)) as soon as possible,
441 making starting the view much faster.
442 Using this property means that we "preload" the design file,
443 to cache the referenced images / TCastleScene instances etc. as soon as possible,
444 to make the future loading of this design (when view starts) very quick.
445
446 Typically you set this property in overridden TCastleView constructor,
447 right after (or before, it doesn't matter) setting DesignUrl.
448 It will mean that constructor takes a longer time (which typically means
449 that Application.OnInitialize takes a longer time) but in exchange
450 future starting of the view (when you do e.g. @code(Container.View := ViewXxx)
451 or @code(Container.PushView(ViewXxx)) will be much faster.
452
453 No functional difference should be visible, regardless of the @link(DesignPreload)
454 value. Internally the designed component is added/removed from view at the same time.
455 So think of this property as pure optimization -- you decide whether to slow down
456 the view constructor, or view start.
457
458 @seealso DesignUrl }
459 property DesignPreload: Boolean read FDesignPreload write SetDesignPreload default false;
460
461 { When the DesignUrl is set, and the view is started, you can use this method to find
462 loaded components. Like this:
463
464 @longCode(#
465 MyButton := DesignedComponent('MyButton') as TCastleButton;
466 #)
467
468 This method is seldom useful now.
469 The published fields of the view are automatically initialized when
470 loading / unloading design using @link(DesignUrl).
471 There's no need to use DesignedComponent for them.
472
473 @seealso DesignUrl }
474 function DesignedComponent(const ComponentName: String): TComponent;
475 //deprecated 'published view fields are automatically initialized now, no need to use this method';
476 // do not deprecate -- there are valid use-cases for it, sometimes it's easier to enumerate strings by code
477
478 { TODO: This doesn't work with FPC 3.2.0, see implementation comments.
479 It is also not that useful -- unlike Unity "GameObject.GetComponent<T>(): T",
480 in this case T would not be used as searching criteria, so it would
481 be just another way to express "as" cast. }
482 // generic function DesignedComponent<T: TComponent>(const ComponentName: String): T; overload;
483
484 class property Current: TCastleView read GetCurrent write SetCurrent; {$ifdef FPC}deprecated 'use Container.View';{$endif}
485 class property CurrentTop: TCastleView read GetCurrentTop; {$ifdef FPC}deprecated 'use Container.FrontView';{$endif}
486 class procedure Push(const NewState: TCastleView); deprecated 'use Container.PushView';
487 class procedure Pop; overload; deprecated 'use Container.PopView';
488 class procedure Pop(const CurrentTopMostState: TCastleView); overload; deprecated 'use Container.PopView';
489 class function StateStackCount: Integer; deprecated 'use Container.ViewStackCount';
490 class property StateStack [const Index: Integer]: TCastleView read GetStateStack; {$ifdef FPC}deprecated 'use Container.ViewStack';{$endif}
491 published
492 { TCastleView control makes most sense when it is FullSize,
493 filling the whole window.
494
495 This way it always captures events on the whole container.
496 And the child controls (anchored to this)
497 behave like anchored to the whole container. }
498 property FullSize default true;
499 end;
500
501 TCastleViewList = class({$ifdef FPC}specialize{$endif} TObjectList<TCastleView>);
502
503 {$endif read_interface}
504
505 {$ifdef read_implementation}
506
507 procedure ErrorDesignLoaded;
508 begin
509 raise Exception.Create('DesignedComponent can only be used if the desing was loaded, which means that TCastleView has started and DesignUrl is not empty');
510 end;
511
512 function RequireMainContainer: TCastleContainer;
513 begin
514 Result := GetMainContainer;
515 if Result = nil then
516 raise Exception.Create('Assign Application.MainWindow (if you use CastleWindow) or TCastleControl.MainControl (if you use CastleControl) before starting TCastleView');
517 end;
518
519 { TCastleComponentFactoryHelper ------------------------------------------------- }
520
521 type
522 { Helper methods extending TCastleComponentFactory.
523 Do not use TCastleComponentFactoryHelper from CastleViewport,
524 to not complicate unit dependencies. }
525 TCastleComponentFactoryHelper = class helper for TCastleComponentFactory
526 { Instantiate component.
527 Using this is equivalent to using global @link(UserInterfaceLoad),
528 but it is much faster if you want to instantiate the same file many times. }
529 function UserInterfaceLoad(const Owner: TComponent): TCastleUserInterface;
530 end;
531
532 function TCastleComponentFactoryHelper.UserInterfaceLoad(const Owner: TComponent): TCastleUserInterface;
533 begin
534 Result := ComponentLoad(Owner) as TCastleUserInterface;
535 end;
536
537 { TCastleView.TDesignOwner --------------------------------------------------------------- }
538
539 procedure TCastleView.TDesignOwner.Notification(AComponent: TComponent; Operation: TOperation);
540 begin
541 { TComponent.InsertComponent and TComponent.RemoveComponent are called on FDesignLoadedOwner
542 and they do Notification.
543 Rely on it to set field name.
544
545 Note that opInsert in practice doesn't do anything, as the component will have no name
546 at creation. It will be fixed by ValidateRename. }
547 case Operation of
548 opInsert: ParentView.SetNameReference(AComponent, AComponent.Name, true);
549 opRemove: ParentView.SetNameReference(AComponent, AComponent.Name, false);
550 else ;
551 end;
552 inherited;
553 end;
554
555 procedure TCastleView.TDesignOwner.ValidateRename(AComponent: TComponent; const CurName, NewName: String);
556 begin
557 inherited;
558 ParentView.SetNameReference(AComponent, CurName, false);
559 ParentView.SetNameReference(AComponent, NewName, true);
560 end;
561
562 { TCastleView --------------------------------------------------------------------- }
563
564 function TCastleView.FreeAtStop: TComponent;
565 begin
566 if FFreeAtStop = nil then
567 FFreeAtStop := TComponent.Create(Self);
568 Result := FFreeAtStop;
569 end;
570
571 procedure TCastleView.InternalStart(const AContainer: TCastleContainer);
572 var
573 TimeStart: TCastleProfilerTime;
574 begin
575 TimeStart := Profiler.Start('Started view ' + Name + ': ' + ClassName);
576
577 FWaitingForRender.Clear;
578 FCallBeforeUpdate.Clear;
579
580 { typically, the Start method will initialize some stuff,
581 making the 1st SecondsPassed non-representatively large. }
582 AContainer.Fps.ZeroNextSecondsPassed;
583
584 FStartContainer := AContainer;
585 FStartContainerObserver.Observed := FStartContainer;
586
587 LoadDesign;
588
589 Start;
590 { actually insert, this will also call GLContextOpen and Resize.
591 However, check first that we're still the current view,
592 to safeguard from the fact that Start changed view
593 (like the loading view, that changes to play view immediately in start). }
594 if AContainer.FViewStack.IndexOf(Self) <> -1 then
595 AContainer.Controls.InsertFront(Self);
596
597 Profiler.Stop(TimeStart, Log);
598 end;
599
600 procedure TCastleView.InternalStop;
601 begin
602 // when container is csDestroying, the FStartContainer.Controls may be invalid
603 if not (csDestroying in FStartContainer.ComponentState) then
604 FStartContainer.Controls.Remove(Self);
605
606 Stop;
607
608 {$warnings off}
609 Finish;
610 {$warnings on}
611
612 UnLoadDesign;
613
614 FStartContainer := nil;
615 FStartContainerObserver.Observed := nil;
616 FreeAndNil(FFreeAtStop);
617
618 if Log then
619 WritelnLog('TCastleView', 'Stopped: ' + Name + ': ' + ClassName);
620 end;
621
622 procedure TCastleView.StartContainerFreeNotification(
623 const Sender: TFreeNotificationObserver);
624 begin
625 { If FStartContainer is being freed, we need to stop now.
626 Otherwise later, InternalStop would surely fail, as it would try
627 to access invalid FStartContainer reference.
628 See https://github.com/castle-engine/castle-engine/issues/307 . }
629 StopIfStarted;
630
631 { Through InternalStop, above always sets FStartContainer to nil }
632 Assert(FStartContainer = nil);
633 end;
634
635 function TCastleView.Container: TCastleContainer;
636 begin
637 Result := PredictedContainer;
638 end;
639
640 function TCastleView.StateContainer: TCastleContainer;
641 begin
642 Result := PredictedContainer;
643 end;
644
645 function TCastleView.PredictedContainer: TCastleContainer;
646 begin
647 if FStartContainer <> nil then
648 { between Start and Stop, be sure to return the same thing
649 from PredictedContainer method. Also makes it working when Application
650 is nil when destroying view from CastleWindow finalization. }
651 Result := FStartContainer
652 else
653 begin
654 Result := GetMainContainer;
655 if Result = nil then
656 raise Exception.Create('Assign Application.MainWindow (if you use CastleWindow) or TCastleControl.MainControl (if you use CastleControl) before starting TCastleView');
657 end;
658 end;
659
660 constructor TCastleView.Create(AOwner: TComponent);
661 begin
662 inherited;
663 FullSize := true;
664 FWaitingForRender := TNotifyEventList.Create;
665 FCallBeforeUpdate := TNotifyEventList.Create;
666 FStartContainerObserver := TFreeNotificationObserver.Create(Self);
667 FStartContainerObserver.OnFreeNotification := {$ifdef FPC}@{$endif}StartContainerFreeNotification;
668 end;
669
670 constructor TCastleView.CreateUntilStopped;
671 begin
672 Create(nil);
673 FFreeWhenStopped := true;
674 end;
675
676 procedure TCastleView.StopIfStarted;
677 var
678 SavedContainer: TCastleContainer;
679 begin
680 if (FStartContainer <> nil) and
681 (FStartContainer.FViewStack <> nil) and
682 (FStartContainer.FViewStack.IndexOf(Self) <> -1) then
683 begin
684 SavedContainer := FStartContainer;
685
686 if SavedContainer.FViewStack.Last = Self then
687 Pause;
688 InternalStop; // this clears FStartContainer
689 SavedContainer.FViewStack.Remove(Self);
690 { deallocate empty FViewStack. Doing this here allows to deallocate
691 FViewStack only once all views finished gracefully. }
692 if SavedContainer.FViewStack.Count = 0 then
693 FreeAndNil(SavedContainer.FViewStack);
694 end;
695 end;
696
697 destructor TCastleView.Destroy;
698 begin
699 StopIfStarted;
700 UnLoadDesign;
701 UnPreloadDesign;
702 FreeAndNil(FWaitingForRender);
703 FreeAndNil(FCallBeforeUpdate);
704 inherited;
705 end;
706
707 procedure TCastleView.Resume;
708 begin
709 if Log then
710 WritelnLog('TCastleView', 'Resuming: ' + Name + ': ' + ClassName);
711 end;
712
713 procedure TCastleView.Pause;
714 begin
715 if Log then
716 WritelnLog('TCastleView', 'Paused: ' + Name + ': ' + ClassName);
717 end;
718
719 procedure TCastleView.Start;
720 begin
721 { Do not place here any logic, to make sure TCastleView works reliably even when
722 descendant doesn't have "inherited" call.
723 While we don't guarantee that our classes generally work OK in such situations
724 (you should always call "inherited" unless documented otherwise),
725 but in this special case we try to make it so, otherwise sometimes hard-to-debug
726 errors occur. }
727 end;
728
729 procedure TCastleView.Stop;
730 begin
731 { Do not place here any logic, to make sure TCastleView works reliably even when
732 descendant doesn't have "inherited" call.
733 Same as in Start. }
734 end;
735
736 procedure TCastleView.Finish;
737 begin
738 end;
739
740 function TCastleView.Active: boolean;
741 begin
742 Result := FStartContainer <> nil;
743 end;
744
745 function TCastleView.Press(const Event: TInputPressRelease): boolean;
746 begin
747 Result := inherited;
748 Result := Result or InterceptInput;
749 end;
750
751 function TCastleView.Release(const Event: TInputPressRelease): boolean;
752 begin
753 Result := inherited;
754 Result := Result or InterceptInput;
755 end;
756
757 function TCastleView.Motion(const Event: TInputMotion): boolean;
758 begin
759 Result := inherited;
760 Result := Result or InterceptInput;
761 end;
762
763 procedure TCastleView.Update(const SecondsPassed: Single;
764 var HandleInput: boolean);
765 begin
766 inherited;
767
768 { do not allow controls underneath to handle input }
769 if InterceptInput then
770 HandleInput := false;
771
772 if FCallBeforeUpdate.Count <> 0 then // optimize away common case
773 begin
774 { In case of using CreateUntilStopped view, you cannot change view
775 in the middle of FCallBeforeUpdate.ExecuteAll,
776 as it would free the array that is being iterated over. }
777 if FFreeWhenStopped then Inc(FStartContainer.FDisableStackChange);
778 try
779 FCallBeforeUpdate.ExecuteAll(Self);
780 FCallBeforeUpdate.Clear;
781 finally
782 if FFreeWhenStopped then Dec(FStartContainer.FDisableStackChange);
783 end;
784 end;
785 end;
786
787 procedure TCastleView.InsertUserInterface(const ADesignUrl: String;
788 const FinalOwner: TComponent;
789 out Ui: TCastleUserInterface; out UiOwner: TComponent);
790 begin
791 UiOwner := TComponent.Create(FinalOwner);
792 Ui := UserInterfaceLoad(ADesignUrl, UiOwner);
793 InsertFront(Ui);
794 end;
795
796 procedure TCastleView.InsertUserInterface(const ADesignUrl: String;
797 const FinalOwner: TComponent; out UiOwner: TComponent);
798 var
799 Ui: TCastleUserInterface;
800 begin
801 {$warnings off} // using deprecated in deprecated
802 InsertUserInterface(ADesignUrl, FinalOwner, Ui, UiOwner);
803 {$warnings on}
804 // ignore the returned Ui reference
805 end;
806
807 procedure TCastleView.Render;
808 begin
809 inherited;
810 FCallBeforeUpdate.AddRange(FWaitingForRender);
811 FWaitingForRender.Clear;
812 end;
813
814 procedure TCastleView.WaitForRenderAndCall(const Event: TNotifyEvent);
815 begin
816 FWaitingForRender.Add(Event);
817 end;
818
819 procedure TCastleView.LoadDesign;
820 begin
821 if DesignUrl <> '' then
822 begin
823 FDesignLoadedOwner := TDesignOwner.Create(nil);
824 FDesignLoadedOwner.ParentView := Self;
825 if FDesignPreloadedSerialized <> nil then
826 FDesignLoaded := FDesignPreloadedSerialized.UserInterfaceLoad(FDesignLoadedOwner)
827 else
828 FDesignLoaded := UserInterfaceLoad(DesignUrl, FDesignLoadedOwner);
829 InsertFront(FDesignLoaded);
830 end;
831 end;
832
833 procedure TCastleView.UnLoadDesign;
834 begin
835 FreeAndNil(FDesignLoadedOwner);
836 FDesignLoaded := nil; // freeing FDesignLoadedOwner must have freed this too
837 end;
838
839 procedure TCastleView.PreloadDesign;
840 begin
841 if DesignUrl <> '' then
842 begin
843 // load FDesignPreloadedSerialized to be able to faster load design, without parsing JSON
844 FDesignPreloadedSerialized := TCastleComponentFactory.Create(nil);
845 FDesignPreloadedSerialized.Url :=DesignUrl;
846 // load FDesignPreloaded to cache all that's possible,
847 // like images used inside TCastleImageControl or TCastleScene.
848 FDesignPreloadedOwner := TComponent.Create(nil);
849 FDesignPreloaded := FDesignPreloadedSerialized.UserInterfaceLoad(FDesignPreloadedOwner);
850 end;
851 end;
852
853 procedure TCastleView.UnPreloadDesign;
854 begin
855 { Note that it doesn't matter whether this FDesignPreloaded was used to load
856 currently created FDesignLoaded or not.
857 So FDesignLoaded* and FDesignPreloadedxx* are completely independent.
858 This makes it easier to think about them. }
859 FreeAndNil(FDesignPreloadedOwner);
860 FDesignPreloaded := nil;// freeing FDesignPreloadedOwner must have freed this too
861 FreeAndNil(FDesignPreloadedSerialized);
862 end;
863
864 procedure TCastleView.SetDesignUrl(const Value: String);
865 begin
866 if FDesignUrl <> Value then
867 begin
868 UnLoadDesign;
869 UnPreloadDesign;
870 FDesignUrl := Value;
871 if DesignPreload then
872 PreloadDesign; // do this before LoadDesign, as LoadDesign may use it
873 if Active then
874 LoadDesign;
875 end;
876 end;
877
878 procedure TCastleView.SetDesignPreload(const Value: Boolean);
879 begin
880 if FDesignPreload <> Value then
881 begin
882 UnPreloadDesign;
883 FDesignPreload := Value;
884 if FDesignPreload then
885 PreloadDesign;
886 end;
887 end;
888
889 (*
890 { FPC 3.2.0 error:
891 Error: function header doesn't match the previous declaration "DesignedComponent$1(const AnsiString):T;"
892 Error: Found declaration: DesignedComponent$1(const AnsiString):T;
893 }
894 generic function TCastleView.DesignedComponent<T: TComponent>(const ComponentName: String): T;
895 begin
896 if FDesignLoaded = nil then
897 ErrorDesignLoaded;
898 Result := FDesignLoaded.FindRequiredComponent(ComponentName) as T;
899 end;
900
901 { FPC 3.2.0 error:
902 Error: Global Generic template references static symtable
903 This works OK in a smaller testcase. }
904 generic function TCastleView.DesignedComponent<T>(const ComponentName: String): T;
905 begin
906 if FDesignLoaded = nil then
907 ErrorDesignLoaded;
908 // Dirty typecast to TClass needed, otherwise we get error
909 // Error: Class or interface type expected, but got "T"
910 // The error is valid -- which is why our first option was generic with constraints
911 // <T: TComponent> yet it failed.
912 Result := FDesignLoaded.FindRequiredComponent(ComponentName) as TClass(T);
913 end;
914 *)
915
916 function TCastleView.DesignedComponent(const ComponentName: String): TComponent;
917 begin
918 if FDesignLoaded = nil then
919 ErrorDesignLoaded;
920 Result := FDesignLoadedOwner.FindRequiredComponent(ComponentName);
921 end;
922
923 function TCastleView.ContainerWidth: Cardinal;
924 begin
925 Result := PredictedContainer.PixelsWidth;
926 end;
927
928 function TCastleView.ContainerHeight: Cardinal;
929 begin
930 Result := PredictedContainer.PixelsHeight;
931 end;
932
933 function TCastleView.ContainerRect: TRectangle;
934 begin
935 Result := PredictedContainer.PixelsRect;
936 end;
937
938 function TCastleView.ContainerSizeKnown: boolean;
939 begin
940 Result := true;
941 end;
942
943 function TCastleView.UIScale: Single;
944 begin
945 if EnableUIScaling then
946 Result := PredictedContainer.UIScale
947 else
948 Result := 1.0;
949 end;
950
951 class function TCastleView.GetCurrent: TCastleView;
952 begin
953 Result := RequireMainContainer.View;
954 end;
955
956 class function TCastleView.GetCurrentTop: TCastleView;
957 begin
958 Result := RequireMainContainer.FrontView;
959 end;
960
961 class procedure TCastleView.SetCurrent(const Value: TCastleView);
962 begin
963 RequireMainContainer.View := Value;
964 end;
965
966 class procedure TCastleView.Push(const NewState: TCastleView);
967 begin
968 RequireMainContainer.PushView(NewState);
969 end;
970
971 class procedure TCastleView.Pop;
972 begin
973 RequireMainContainer.PopView;
974 end;
975
976 class procedure TCastleView.Pop(const CurrentTopMostState: TCastleView);
977 begin
978 RequireMainContainer.PopView(CurrentTopMostState);
979 end;
980
981 class function TCastleView.StateStackCount: Integer;
982 begin
983 Result := RequireMainContainer.ViewStackCount;
984 end;
985
986 class function TCastleView.GetStateStack(const Index: Integer): TCastleView;
987 begin
988 Result := RequireMainContainer.ViewStack[Index];
989 end;
990
991 procedure TCastleView.SetNameReference(const AComponent: TComponent; const ReferenceName: String; const Enable: Boolean);
992 var
993 FieldAddr: ^TComponent;
994 begin
995 if ReferenceName = '' then
996 Exit;
997 FieldAddr := FieldAddress(ReferenceName);
998 if FieldAddr <> nil then
999 begin
1000 if Enable then
1001 FieldAddr^ := AComponent
1002 else
1003 FieldAddr^ := nil;
1004 end;
1005 end;
1006
1007 {$endif read_implementation}