Debian Codegraph @

src/window/castlewindow_form.inc

raw
1 {%MainUnit castlewindow.pas}
2 {
3 Copyright 2013-2024 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 (*CastleWindow backend using Lazarus LCL or Delphi FMX underneath.
18
19 *Should* work with all platforms,
20 all LCL widgetsets,
21 all Delphi FMX platforms.
22
23 Note that there are a few TODOs in this file, for some specific Delphi (FMX)
24 or FPC / Lazarus (LCL) backends. Things are not perfect on their end always,
25 there are platform-specific edge cases.
26 We still try to support all LCL and FMX widgetsets here, *but*
27 we focus our testing on platforms where we actually use this backend by default.
28 This means right now only:
29
30 - Delphi/Linux with FMX
31
32 Historically, it was useful also with some LCL backends (e.g. we depended on
33 this for FPC/macOS for a long time, before we implemented castlewindow_cocoa.inc).
34 And it may be useful with more platforms in the future, both LCL and FMX
35 (e.g. Delphi/macOS will likely depend on this too).
36
37 - LCL TODO: Mouse look still stutters awfully on both Carbon and GTK2.
38 ProcessTasks helps (without it, mouse look would not work at all)
39 but doesn't completely fix the problem. Other CastleWindow backends
40 have smooth mouse look.
41
42 Note that Carbon is unused now (only Cocoa matters).
43 Needs retest with Cocoa.
44 *)
45
46 { How to implement calling CGE Update (and if needed Render) events continuously?
47
48 - When USE_TIMER defined, we will use TTimer with short Interval
49 to execute our processing regularly.
50
51 This seems a cleaner solution, thus preferred if possible.
52 Timer explicitly expresses "we want to run Update regularly,
53 no matter how busy application is" which is what we want.
54
55 And it means that all LCL/FMX functionality,
56 like Forms.Application.Run, is free to be used. Internally,
57 LCL/FMX is responsible for calling our timer event regularly, instead
58 of hanging indefinitely waiting for user input.
59
60 - When not USE_TIMER, we instead "control" the event loop more
61 carefully and manually insert our processing between LCL/FMX processing.
62
63 That is, we never let application sleep indefinitely inside
64 OS event processing (e.g. we'll never call LCL/FMX Forms.Application.Run).
65 We will always do LCL/FMX non-blocking event processing,
66 and follow it with calls to CGE Update / Render as needed.
67
68 Note: In the past we experimented with Application.OnIdle, but that's useless
69 for our purpose.
70 Idle is not executed regularly, it may not be executed at all when application
71 is busy doing something else.
72 Moreover, with Delphi FMX, there's no "add/remove
73 idle listener" API, instead we'd have to override Application.OnIdle.
74 So user cannot use Application.OnIdle for anything else.
75
76 Delphi (with FMX) situation:
77
78 - Timer is reliable on Windows. All our Delphi FMX and VCL components
79 use TTimer like this.
80
81 - On Linux, we *cannot* use timer.
82
83 Timer with FMXLinux fails badly when we do non-trivial work in each update,
84 like fps_game animations, or Spine dragon animations in play_animation.
85 Running "flying" in play_animation just makes the screen go black,
86 never updated. I was not able to debug it to the end -- the DoUpdate calls
87 are still executed by timer, but rendering just doesn't work,
88 even if we force doing DoRender from timer. It gets executed, but displayed
89 window is not refreshed. The same problem occurs for FMX-drawn controls
90 on form (like memo and buttons on CastleFmx).
91 The same problem occurs for GTK dialogs, like open dialog shown
92 by play_animation.
93
94 FPC (with LCL) situation:
95
96 (Possibly this is outdated comment!
97 FPC situation wasn't tested for quite some time now.
98 We don't really need CASTLE_WINDOW_FORM for FPC now, so we don't test it.)
99
100 - Carbon (macOS): Timer is the only reliable solution.
101
102 It is translated to Carbon timer.
103 It is the only way to receive continuous messages in some cases.
104
105 Otherwise such bugs can be observed (only on LCL-Carbon, not on LCL-GTK2):
106
107 - When trying to Walk using mouse dragging in castle-model-viewer, it doesn't
108 work smoothly: when you simply keep some mouse button pressed,
109 but don't move the mouse anymore (which should result in constant
110 movement forward/backward if you did it after dragging up/down),
111 then we don't get any events (so no movement, no redraw...).
112
113 - Using castle-model-viewer Navigation->Jump to viewpoint... doesn't work
114 smoothly, there is a visible delay when we don't receive messages
115 right after menu click, and so transtion is visible with some delay.
116
117 - Other platforms?
118 No decision, and practically it doesn't matter:
119 with FPC, at this point we have covered all platforms with native
120 TCastleWindow implementation, not depending on LCL and CASTLR_WINDOW_FORM.
121
122 TODO: Call FileMonitor.CheckChanges when user switches to application.
123 }
124 {$if defined(FPC) or (not defined(LINUX))}
125 {$define USE_TIMER}
126 {$endif}
127
128 {$ifdef read_interface_uses}
129 {$ifdef FPC}
130 // LCL
131 Interfaces, Forms, Dialogs, OpenGLContext, Menus, ExtCtrls,
132 Controls, FileUtil, Graphics, LCLType, CastleLCLUtils, Clipbrd, CustomTimer,
133 LCLVersion,
134 {$else}
135 UITypes, Types, Rtti,
136 // FMX
137 {$ifdef LINUX} FMX.Platform.Linux, {$endif}
138 FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
139 FMX.StdCtrls, FMX.Menus, FMX.Platform,
140 // CGE
141 Fmx.CastleInternalGLControl, CastleInternalDelphiUtils, CastleFmxUtils,
142 {$endif}
143 {$endif}
144
145 {$ifdef read_window_interface}
146 private
147 type
148 TFormMenuItem = {$ifndef FPC} FMX. {$endif} Menus.TMenuItem;
149
150 { Descendant of LCL TMenuItem used for our menu. }
151 TGoodMenuItem = class(TFormMenuItem)
152 {$ifndef FPC}
153 strict private
154 function GetCaption: String;
155 procedure SetCaption(const Value: String);
156 function GetChecked: Boolean;
157 procedure SetChecked(const Value: Boolean);
158 {$endif}
159 public
160 Window: TCastleWindow;
161 Entry: TMenuEntry;
162
163 {$ifdef FPC}
164 // only for LCL
165 { Capture IntfDoSelect, which is fired on GTK2
166 event 'select' on menu item, which we have to capture to call
167 ReleaseAllKeysAndMouse.
168
169 Just like in our gtk/castlewindow_gtk_menu.inc: capturing 'select' GTK2
170 event is the only way to capture when user opened menu bar.
171 And we need to capture it, to work with GTK2 and menu bar,
172 e.g. when you use Alt+F to reach "File" menu, do not keep "Alt" key in
173 the pressed state indefinitely (e.g. it would make camera keys non-working
174 after opening a file using Alt+F and recent files in castle-model-viewer).
175
176 This should be also harmless on other non-GTK2 widgetsets. }
177 procedure IntfDoSelect; override;
178 {$else}
179 { Use FMX Text under the hood. }
180 property Caption: String read GetCaption write SetCaption;
181
182 { Use FMX IsChecked under the hood. }
183 property Checked: Boolean read GetChecked write SetChecked;
184 {$endif}
185 end;
186
187 { Like TOpenGLControl but sets Invalidated:=true on Window,
188 so that Window knows when it's invalidated by the OS. }
189 TGoodOpenGLControl = class(TOpenGLControl)
190 public
191 Window: TCastleWindow;
192 procedure Invalidate; override;
193 {$ifdef FPC}
194 { Size in pixels, not scaled by anything.
195 This is trivial in LCL, defined just for compatibility
196 with FMX TOpenGLControl where it is not so trivial. }
197 function PixelsWidth: Integer;
198 function PixelsHeight: Integer;
199 { Scale of mouse coordinates. }
200 function MousePosScale: Single;
201 {$endif}
202 end;
203
204 var
205 Form: TForm;
206 OpenGLControl: TGoodOpenGLControl;
207 Menu: TMainMenu;
208 { TLCLKeyPressHandler is only necessary for LCL.
209 FMX has much more comfortable KeyDown (that gets both key code and char),
210 just like CGE KeyDown, so it's more straightforward to handle. }
211 {$ifdef FPC}
212 FKeyPressHandler: TLCLKeyPressHandler;
213 {$endif}
214
215 procedure MenuConvert(const MyMenu: TMenu; const AMenu: TFormMenuItem);
216 function MenuEntryConvert(const MyEntry: TMenuEntry): TGoodMenuItem;
217 procedure MainMenuConvert(const MyMenu: TMenu; const AMenu: TMainMenu);
218 class function CheckMenu(const Entry: TMenuEntry; out GoodMenuItem: TGoodMenuItem): boolean;
219
220 procedure MenuItemClick(Sender: TObject);
221 procedure MenuUpdateShortcut(Entry: TMenuItem);
222 procedure ProcessTasks;
223 procedure UpdateCursor;
224 procedure UpdateFullScreenForm;
225 {$ifdef FPC}
226 procedure KeyPressHandlerPress(Sender: TObject;
227 const Event: TInputPressRelease);
228 {$endif}
229
230 procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
231 procedure FormDeactivate(Sender: TObject);
232 procedure FormDropFiles(Sender: TObject; const FileNames: array of string);
233
234 procedure OpenGLControlPaint(Sender: TObject);
235 procedure OpenGLControlResize(Sender: TObject);
236 procedure OpenGLControlKeyDown(Sender: TObject; var Key: Word;
237 {$ifndef FPC} var KeyChar: WideChar; {$endif}
238 Shift: TShiftState);
239 {$ifdef FPC}
240 procedure OpenGLControlUTF8KeyPress(Sender: TObject; var UTF8Key: TUTF8Char);
241 {$endif}
242 procedure OpenGLControlKeyUp(Sender: TObject; var Key: Word;
243 {$ifndef FPC} var KeyChar: WideChar; {$endif}
244 Shift: TShiftState);
245 procedure OpenGLControlMouseDown(Sender: TObject; Button: TMouseButton;
246 Shift: TShiftState;
247 X, Y: {$ifdef FPC} Integer {$else} Single {$endif});
248 procedure OpenGLControlMouseUp(Sender: TObject; Button: TMouseButton;
249 Shift: TShiftState;
250 X, Y: {$ifdef FPC} Integer {$else} Single {$endif});
251 procedure OpenGLControlMouseMove(Sender: TObject; Shift: TShiftState;
252 X, Y: {$ifdef FPC} Integer {$else} Single {$endif});
253 procedure OpenGLControlMouseWheel(Sender: TObject; Shift: TShiftState;
254 WheelDelta: Integer; {$ifdef FPC} MousePos: TPoint; {$endif}
255 var Handled: Boolean);
256 function MousePosToCastle(
257 const X, Y: {$ifdef FPC} Integer {$else} Single {$endif}): TVector2;
258 {$endif read_window_interface}
259
260 {$ifdef read_application_interface}
261 private
262 {$ifdef USE_TIMER}
263 FTimer: TTimer;
264 procedure ApplicationTimer(Sender: TObject);
265 {$endif}
266 procedure ProcessTasks;
267 {$endif read_application_interface}
268
269 {$ifdef read_implementation}
270
271 { Return LCL or FMX Application singleton.
272 Just trivial "Application" in most code, but we need to avoid clashing with
273 CGE "Application" and take into account that LCL / FMX
274 have different units. }
275 function FormApplication: TApplication;
276 begin
277 Result := {$ifndef FPC} FMX. {$endif} Forms.Application;
278 end;
279
280 { TGoodMenuItem ---------------------------------------------------------------- }
281
282 {$ifdef FPC}
283 procedure TCastleWindow.TGoodMenuItem.IntfDoSelect;
284 begin
285 inherited;
286 Window.ReleaseAllKeysAndMouse;
287 end;
288 {$else}
289 function TCastleWindow.TGoodMenuItem.GetCaption: String;
290 begin
291 Result := Text;
292 end;
293
294 procedure TCastleWindow.TGoodMenuItem.SetCaption(const Value: String);
295 begin
296 Text := Value;
297 end;
298
299 function TCastleWindow.TGoodMenuItem.GetChecked: Boolean;
300 begin
301 Result := IsChecked;
302 end;
303
304 procedure TCastleWindow.TGoodMenuItem.SetChecked(const Value: Boolean);
305 begin
306 IsChecked := Value;
307 end;
308 {$endif}
309
310 { TGoodOpenGLControl --------------------------------------------------------- }
311
312 procedure TCastleWindow.TGoodOpenGLControl.Invalidate;
313
314 { TODO: In FMX, this is not called automatically when a system event
315 (e.g. when window is obscured and then revealed again) occurs.
316
317 Still, this is a useful method to react to.
318 When CGE knows to invalidate (because e.g. some UI called
319 VisibleChange, or we have AutoRedisplay) then TCastleWindow.Invalidate
320 is called, and in turn calls this method.
321
322 We should make sure to call DoRender soon:
323
324 - In FMX, "inherited" will invalidate the control
325 using FMX features, causing OpenGLControl.OnPaint soon.
326
327 So we actually don't depend on "Window.Invalidated" (own tracking
328 of invalidated).
329
330 - Unsure about LCL at this point, does it cause OpenGLControl.OnPaint
331 reliably on all backends.
332
333 So with LCL (FPC) we rely on own Window.Invalidated.
334 Window.Invalidated := true is set set here,
335 later DoRender will clear it.
336 }
337
338 begin
339 // track our own Invalidated state, although still cooperate with LCL invalidate
340 Window.Invalidated := true;
341 inherited;
342 end;
343
344 {$ifdef FPC}
345 function TCastleWindow.TGoodOpenGLControl.PixelsWidth: Integer;
346 begin
347 Result := Width;
348 end;
349
350 function TCastleWindow.TGoodOpenGLControl.PixelsHeight: Integer;
351 begin
352 Result := Height;
353 end;
354
355 function TCastleWindow.TGoodOpenGLControl.MousePosScale: Single;
356 begin
357 Result := 1;
358 end;
359 {$endif}
360
361 { TCastleWindow ------------------------------------------------------------------ }
362
363 procedure TCastleWindow.CreateBackend;
364 begin
365 end;
366
367 function TCastleWindow.MenuEntryConvert(const MyEntry: TMenuEntry): TGoodMenuItem;
368 begin
369 Result := TGoodMenuItem.Create(Form);
370 Result.Window := Self;
371 Result.OnClick := {$ifdef FPC}@{$endif} MenuItemClick;
372 { store connection both ways between LCL menu item <-> our menu entry }
373 Result.Entry := MyEntry;
374 MyEntry.Handle := Result;
375 if MyEntry is TMenuItem then
376 MenuUpdateShortcut(TMenuItem(MyEntry));
377 if MyEntry is TMenuEntryWithCaption then
378 begin
379 { set MenuItem.Caption and Enabled }
380 MenuUpdateCaption(TMenuEntryWithCaption(MyEntry));
381 MenuUpdateEnabled(TMenuEntryWithCaption(MyEntry));
382 if MyEntry is TMenuItemChecked then
383 begin
384 {$ifdef FPC}
385 Result.ShowAlwaysCheckable := true;
386 {$endif}
387 Result.RadioItem := MyEntry is TMenuItemRadio;
388 MenuUpdateChecked(TMenuItemChecked(MyEntry));
389 end;
390 end else
391 if MyEntry is TMenuSeparator then
392 { set Result.Caption - special for separator }
393 Result.Caption := '-';
394 { if we have submenu, do this recursively }
395 if MyEntry is TMenu then
396 MenuConvert(TMenu(MyEntry), Result);
397 end;
398
399 procedure TCastleWindow.MenuConvert(const MyMenu: TMenu;
400 const AMenu: TFormMenuItem);
401 var
402 I: Integer;
403 NewMenuChild: TFormMenuItem;
404 begin
405 for I := 0 to MyMenu.Count - 1 do
406 begin
407 NewMenuChild := MenuEntryConvert(MyMenu[I]);
408 AMenu.{$ifdef FPC}Add{$else}AddObject{$endif}(NewMenuChild);
409 end;
410 end;
411
412 procedure TCastleWindow.MainMenuConvert(
413 const MyMenu: TMenu; const AMenu: TMainMenu);
414 {$ifdef FPC}
415 begin
416 MenuConvert(MyMenu, AMenu.Items);
417 {$else}
418 var
419 I: Integer;
420 NewMenuChild: TFormMenuItem;
421 begin
422 for I := 0 to MyMenu.Count - 1 do
423 begin
424 NewMenuChild := MenuEntryConvert(MyMenu[I]);
425 AMenu.{$ifdef FPC}Add{$else}AddObject{$endif}(NewMenuChild);
426 end;
427 {$endif}
428 end;
429
430 procedure TCastleWindow.BackendMenuInitialize;
431 begin
432 Menu := TMainMenu.Create(Form);
433 { connet Menu with Form }
434 Menu.Parent := Form;
435 {$ifdef FPC} // in FMX, there's no need to assign main menu to any form property
436 Form.Menu := Menu;
437 {$endif}
438 MainMenuConvert(MainMenu, Menu);
439 end;
440
441 procedure TCastleWindow.BackendMenuFinalize;
442 begin
443 FreeAndNil(Menu);
444 MainMenu.ClearHandles;
445 end;
446
447 class function TCastleWindow.CheckMenu(const Entry: TMenuEntry; out GoodMenuItem: TGoodMenuItem): boolean;
448 begin
449 GoodMenuItem := TObject(Entry.Handle) as TGoodMenuItem;
450 Result := GoodMenuItem <> nil;
451
452 if (not Result) and
453 ((Entry.CorrectParentWindow = nil) or Entry.CorrectParentWindow.MainMenuVisible) then
454 WritelnWarning('Menu', 'Menu entry has Handle = nil (this means that corresponding LCL menu item object was not created, but it should)');
455 end;
456
457 procedure TCastleWindow.MenuUpdateShortcut(Entry: TMenuItem);
458
459 {$ifndef FPC}
460 { Convert FMX key code (Word) and shift state to TShortCut.
461 FMX doesn't have this function built-in,
462 but it is straightforward following
463 http://docwiki.embarcadero.com/RADStudio/Sydney/en/Representing_Keys_and_Shortcuts#Representing_Shortcuts }
464 function KeyToShortCut(const Key: Word; const Shift: TShiftState): TShortCut;
465 begin
466 Result := Key;
467 if ssShift in Shift then
468 Result := Result or scShift;
469 if ssCtrl in Shift then
470 Result := Result or scCtrl;
471 if ssAlt in Shift then
472 Result := Result or scAlt;
473 end;
474 {$endif}
475
476 var
477 KeyCode: Word;
478 Shift: TShiftState;
479 FormMenuItem: TGoodMenuItem;
480 begin
481 if not CheckMenu(Entry, FormMenuItem) then Exit;
482
483 { TODO: FMX Linux doesn't handle (pass to GTK?) "Home" shortcut it seems.
484 Or Page Up / Page Down.
485 It is displayed in menu OK, but FMX doesn't actually call menu item
486 when pressing home.
487 Testcase: castle-image-viewer. }
488
489 KeyFromCastle(Entry.Key, Entry.KeyString, Entry.Modifiers, KeyCode, Shift);
490 FormMenuItem.ShortCut := KeyToShortCut(KeyCode, Shift);
491 end;
492
493 procedure TCastleWindow.MenuUpdateCaption(Entry: TMenuEntryWithCaption);
494
495 function MenuCaptionFromCastle(const S: string): string;
496 begin
497 { We use _ for the same purpose as FMX / LCL use &: to mark mnemonics.
498
499 But we cannot just replace _ with &:
500
501 Double underscore should be converted to single underscore.
502 Only unpaired single underscore should be converted to &.
503
504 Moreover, single & shoule be doubled: to make it visible,
505 not as accelerator.
506
507 Note: FMX Linux has a bug, and it strips last _ from
508 '&foo with underscore : _' .
509 Probably FMX Linux code doesn't quote (double) the underscore and it gets
510 interpreted by GTK as accelerator?
511 Since underscore is GTK accelerator,
512 https://docs.gtk.org/gtk3/ctor.CheckMenuItem.new_with_mnemonic.html .
513 We have autotest that we pass it OK (single underscore) to FMX,
514 see TTestCastleStringUtils.TestSReplacePatternsMenu . }
515
516 Result := SReplacePatterns(S, ['__', '_', '&'], ['_', '&', '&&'], false);
517 end;
518
519 var
520 FormMenuItem: TGoodMenuItem;
521 begin
522 if not CheckMenu(Entry, FormMenuItem) then Exit;
523 FormMenuItem.Caption := MenuCaptionFromCastle(Entry.Caption);
524 end;
525
526 procedure TCastleWindow.MenuUpdateEnabled(Entry: TMenuEntryWithCaption);
527
528 procedure RefreshEnabled(MyMenu: TMenu);
529
530 procedure RefreshEnabledEntry(const MyEntry: TMenuEntry);
531 begin
532 if MyEntry is TMenuEntryWithCaption then
533 MenuUpdateEnabled(TMenuEntryWithCaption(MyEntry));
534 if MyEntry is TMenu then
535 RefreshEnabled(TMenu(MyEntry));
536 end;
537
538 var
539 I: Integer;
540 begin
541 for I := 0 to MyMenu.Count - 1 do
542 RefreshEnabledEntry(MyMenu[I]);
543 end;
544
545 var
546 FormMenuItem: TGoodMenuItem;
547 begin
548 { To apply MainMenu.Enabled: we would prefer to map MainMenu.Enabled
549 on LCL Menu.Items.Enabled, and just handle MainMenu.Enabled like
550 every other menu item. But LCL (at least GTK2 and Carbon) seems to
551 completely ignore Menu.Items.Enabled.
552
553 So to do make it work, we
554 1. Always combine MainMenu.Enabled with particular item's Enabled value
555 (in particular, this way BackendMenuInitialize applies it to every item).
556 2. At MenuUpdateEnabled for MainMenu (so when you change MainMenu.Enabled
557 value) we do a refresh (update enabled state) of all the menu items.
558
559 Note that we cannot just do MenuFinalize + MenuInitialize to implement
560 the 2nd step, because macOS (Carbon) reacts very badly to menu rebuilds.
561 There is a problem when you have a menu item with key shortcut,
562 and when this menu item is executed --- we destroy and create new menu
563 that also reacts to this shortcut. In this case, Carbon executes
564 the menu item again! Consider e.g. castle-model-viewer "File->Open" with
565 Ctrl+O shortcut, that after opening a new file rebuilds the menu
566 to update the "recent files" menu section. Consider also "Display->Raytrace"
567 with Ctrl+R shortcut, that after choosing options changes
568 the MainMenu.Enabled. If we would do a MenuFinalize + MenuInitialize
569 to easiy recreate LCL menu, we would see open dialog twice after Ctrl+O,
570 and raytrace dialog twice after Ctrl+R. So we don't do it.
571 In MenuInsert and MenuDelete and in this method, MenuUpdateEnabled,
572 we merely change the existing LCL menu instances.
573
574 This all could be considered LCL bug, anyway we have to work with it.
575 }
576
577 if Entry = MainMenu then
578 begin
579 RefreshEnabled(MainMenu);
580 Exit;
581 end;
582
583 if not CheckMenu(Entry, FormMenuItem) then Exit;
584 FormMenuItem.Enabled := Entry.Enabled and MainMenu.Enabled;
585 end;
586
587 procedure TCastleWindow.MenuUpdateChecked(Entry: TMenuItemChecked);
588 var
589 FormMenuItem: TGoodMenuItem;
590 begin
591 // TODO: LCL GTK2 backend only: All radio menu items are always on, reason unknown.
592
593 { TODO: FMX on Linux (not a problem elsewhere, in particular with FMX on Windows):
594 Sometimes it seems that checked menu item, after updating to "true",
595 is left with an empty checkbox box -- a state that actually should not be
596 possible through FMX API (it shows a checkbox possibility but it is "off",
597 and FMX doesn't have property like ShowAlwaysCheckable from LCL)
598 and moreover incorrect (we set it to "true", but it shows "false").
599 Testcase: window_menu, set to "Top", then set to "Top" again.
600 }
601
602 if not CheckMenu(Entry, FormMenuItem) then Exit;
603 FormMenuItem.Checked := Entry.Checked;
604 end;
605
606 function TCastleWindow.MenuUpdateCheckedFast: boolean;
607 begin
608 Result := true;
609 end;
610
611 procedure TCastleWindow.MenuInsert(const Parent: TMenu;
612 const ParentPosition: Integer; const Entry: TMenuEntry);
613
614 procedure InsertInMainMenu;
615 var
616 NewFormMenu: TFormMenuItem;
617 begin
618 NewFormMenu := MenuEntryConvert(Entry);
619 Menu.{$ifdef FPC}Items.Insert{$else}InsertObject{$endif}(ParentPosition, NewFormMenu);
620 end;
621
622 var
623 ParentFormMenu, NewFormMenu: TGoodMenuItem;
624 begin
625 if not CheckMenu(Parent, ParentFormMenu) then
626 begin
627 { Our main menu (Menu:TMainMenu) is not set as MainMenu.Handle,
628 because we use just standard FMX / LCL TMainMenu class,
629 not our TGoodMenuItem.
630 But we can handle it by a special case here. }
631 if Parent = MainMenu then
632 InsertInMainMenu;
633 Exit;
634 end;
635
636 NewFormMenu := MenuEntryConvert(Entry);
637 ParentFormMenu.{$ifdef FPC}Insert{$else}InsertObject{$endif}(ParentPosition, NewFormMenu);
638 end;
639
640 procedure TCastleWindow.MenuDelete(const Parent: TMenu;
641 const ParentPosition: Integer; const Entry: TMenuEntry);
642 var
643 FormMenuItem: TGoodMenuItem;
644 begin
645 if not CheckMenu(Entry, FormMenuItem) then Exit;
646 Entry.ClearHandles;
647
648 {$if defined(LCLCarbon) or defined(LCLCocoa)}
649 (*Workaround LCL on Carbon bug http://bugs.freepascal.org/view.php?id=20688 .
650 (assuming it's the same on Cocoa)
651
652 Symptoms:
653 Sometimes after menu changes we have a segfault in Carbon widgetset,
654 like our menu item reference was invalid.
655 Happens after various menu changes: rebuilding the menu, also fast changes
656 like MenuDelete (like when changing recent files submenu in castle-model-viewer).
657 It seems that Carbon doesn't like deleting a menu currently used.
658
659 Happens both when debugging and not debugging.
660 Using the file menu to choose a recent file to load from castle-model-viewer
661 is the most common case.
662
663 In Lazarus debuggger:
664 Project castle-model-viewer.app raised exception class 'External: EXC_BAD_ACCESS'.
665 In file './carbon/carbonlclintf.inc' at line 342:
666 end; {TCarbonWidgetSet.PromptUser}
667
668 When running from console:
669 TApplication.HandleException Access violation
670 Stack trace:
671 $0039566B CARBONAPP_COMMANDPROCESS, line 2872 of /Users/michalis/sources/lazarus/trunk/lcl/interfaces/./carbon/carbonint.pas
672
673 Most probably this is the same thing as reported on
674 http://bugs.freepascal.org/view.php?id=20688 .
675 Less likely, to http://bugs.freepascal.org/view.php?id=18908 ?
676
677 Workaround for now is just to not remove LCL menu items, only hide them.
678 This at least fixes the issue when we delete menu by MenuDelete
679 (as opposed to menu rebuild).
680 *)
681 FormMenuItem.Visible := false;
682 {$else}
683 FreeAndNil(FormMenuItem);
684 {$endif}
685 end;
686
687 procedure TCastleWindow.SwapBuffers;
688 begin
689 OpenGLControl.SwapBuffers;
690 end;
691
692 procedure TCastleWindow.OpenBackend;
693
694 procedure GetInitialMousePos;
695 var
696 {$ifdef FPC}
697 InitialMousePos: TPoint;
698 {$else}
699 InitialMousePos: TPointF;
700 MouseService: IFMXMouseService;
701 {$endif}
702 begin
703 {$ifdef FPC}
704 InitialMousePos := Mouse.CursorPos;
705 InitialMousePos := OpenGLControl.ScreenToControl(InitialMousePos);
706 {$else}
707 if not TPlatformServices.Current.SupportsPlatformService(IFMXMouseService, MouseService) then
708 Exit;
709 InitialMousePos := MouseService.GetMousePos;
710 //WritelnLog('Initial mouse position (screen coordinates): %f %f', [InitialMousePos.X, InitialMousePos.Y]);
711 InitialMousePos := Form.ScreenToClient(InitialMousePos);
712 //WritelnLog('Initial mouse position (form coordinates): %f %f', [InitialMousePos.X, InitialMousePos.Y]);
713 InitialMousePos := OpenGLControl.AbsoluteToLocal(InitialMousePos);
714 //WritelnLog('Initial mouse position (OpenGL control coordinates): %f %f', [InitialMousePos.X, InitialMousePos.Y]);
715 {$endif}
716 FMousePosition := MousePosToCastle(InitialMousePos.X, InitialMousePos.Y);
717 //WritelnLog('Initial mouse position (CGE coordinates): %s', [FMousePosition.ToString]);
718 end;
719
720 { Convert argument to assign to Form.Width / Height to make the result
721 be a size in pixels size (not some FMX scaled size). }
722 function FormSizeRequestPrecisely(const Form: TCustomForm; const PixelSize: Integer): Integer;
723 begin
724 Result := PixelSize;
725
726 // Without this, requesting window size like 200 actually gives you 200 scaled by window scale
727 // Testcase: multi_window with Delphi/Linux.
728 {$if defined(DELPHI) and defined(LINUX)}
729 if Form.Handle <> nil then
730 Result := Round(Result / TLinuxWindowHandle(Form.Handle).Scale);
731 {$endif}
732
733 { Note: We tried, but failed, to cope with FMX (Delphi) scaling also on Windows.
734 See castlewindow_form_fmx_scaling.md }
735 end;
736
737 begin
738 {$ifdef FPC}
739 FKeyPressHandler := TLCLKeyPressHandler.Create;
740 FKeyPressHandler.OnPress := @KeyPressHandlerPress;
741 {$endif}
742
743 {$ifdef FPC}
744 { We use FormApplication.CreateForm, not just "Form := TForm.CreateNew(nil)",
745 because we want our Form to be set as FormApplication.MainForm.
746
747 And there is no other way to set FormApplication.MainForm,
748 we have to use mechanism that "the first form created by Application.CreateForm
749 is set as main", see http://www.lazarus.freepascal.org/index.php?topic=14438.0
750 and LCL sources of TApplication.UpdateMainForm.
751 The "Forms.Application.MainForm" property is not directly settable.
752
753 And we need to have a main form, as that's the only way to capture (in form
754 close event) the macOS "ProjectName -> Quit" automatic menu item (see
755 http://bugs.freepascal.org/view.php?id=10983).
756
757 Note: This would be a problem if we used TForm descendant,
758 as then Forms.Application.CreateForm would search for a related resource.
759 Unless we set RequireDerivedFormResource to false (which actually
760 is the default RequireDerivedFormResource value for now, but the adviced
761 value is true).
762 Fortunately, the whole resource-searching is not used when we just
763 have a TForm class (see TCustomForm.Create in LCL), so that's not a problem. }
764
765 FormApplication.CreateForm(TForm, Form);
766 {$else}
767 { In FMX, we cannot use
768 FormApplication.CreateForm
769 as it doesn't create form immediately.
770 We'd have to follow with RealCreateForms,
771 https://docwiki.embarcadero.com/Libraries/Sydney/en/FMX.Forms.TApplication.RealCreateForms
772
773 But it is simpler to just use TForm.CreateNew.
774 We can assign MainForm later. }
775
776 Form := TForm.CreateNew(FormApplication);
777 FormApplication.MainForm := Form;
778 {$endif}
779
780 {$ifdef FPC}
781 // FMX: TODO
782 Form.OnDropFiles := @FormDropFiles;
783 {$endif}
784
785 Form.Top := Top;
786 Form.Left := Left;
787 { LCL note:
788 We would prefer to leave Form.AutoSize := true and allow form to adjust
789 to OpenGLControl.Width/Height. But it doesn't work with LCL. }
790 Form.Width := FormSizeRequestPrecisely(Form, Width);
791 Form.Height := FormSizeRequestPrecisely(Form, Height);
792 Form.Caption := GetWholeCaption; // SetCaption may also change it later
793
794 UpdateFullScreenForm;
795
796 Form.OnCloseQuery := {$ifdef FPC}@{$endif} FormCloseQuery;
797 { Note: I tried also using OpenGLControl.OnExit for this, seems to be quivalent
798 in our case. And, similarly, both methods still need manual workaround
799 to call ReleaseAllKeysAndMouse manually in MessageOK and similar methods
800 (otherwise: check e.g. window_events with Window.MessageOk from Update:
801 entering MessageOK *must* make ReleaseAllKeysAndMouse, otherwise it hangs.) }
802 Form.OnDeactivate := {$ifdef FPC}@{$endif} FormDeactivate;
803
804 { Do not make it owned by Form, instead we will free it explicitly.
805 This avoids problems in Invalidate, where we access OpenGLControl instance,
806 but we may be already in csDestroying state of Form (so it's owned components
807 are already freed).
808
809 Affects macOS with Carbon widgetset behavior when making castle-model-viewer
810 screenshot from command-line, like
811 ".../castle-model-viewer .../dynamic_world.x3dv --screenshot 0 output_2d_screenshot.png".
812
813 Alternatively we could check "not (csDestroying in Form.ComponentState)"
814 in Invalidate, but this feels cleaner. }
815
816 OpenGLControl := TGoodOpenGLControl.Create(nil);
817 OpenGLControl.Window := Self;
818 OpenGLControl.Parent := Form;
819 OpenGLControl.Align := {$ifdef FPC} alClient {$else} TAlignLayout.Client {$endif};
820 OpenGLControl.Width := Width;
821 OpenGLControl.Height := Height;
822 {$ifdef FPC} // TODO: FMX
823 OpenGLControl.Constraints.MinWidth := MinWidth;
824 OpenGLControl.Constraints.MinHeight := MinHeight;
825 OpenGLControl.Constraints.MaxWidth := MaxWidth;
826 OpenGLControl.Constraints.MaxHeight := MaxHeight;
827 {$endif}
828 OpenGLControl.TabStop := true;
829
830 {$ifdef FPC}
831 OpenGLControl.DoubleBuffered := DoubleBuffer;
832 OpenGLControl.StencilBits := StencilBits;
833 OpenGLControl.DepthBits := DepthBits;
834 OpenGLControl.AlphaBits := AlphaBits;
835 OpenGLControl.MultiSampling := MultiSampling;
836 {$else}
837 OpenGLControl.Requirements.DoubleBuffer := DoubleBuffer;
838 OpenGLControl.Requirements.StencilBits := StencilBits;
839 OpenGLControl.Requirements.DepthBits := DepthBits;
840 OpenGLControl.Requirements.AlphaBits := AlphaBits;
841 OpenGLControl.Requirements.MultiSampling := MultiSampling;
842 {$endif}
843
844 UpdateCursor; // SetCursor may call it also later
845
846 Form.ActiveControl := OpenGLControl;
847
848 if (MainMenu <> nil) and MainMenuVisible then
849 MenuInitialize;
850
851 Form.Visible :=
852 {$if not (defined(DELPHI) and defined(LINUX))}
853 Visible
854 {$else}
855 { For Delphi/Linux, we set Form.Visible always to true.
856 Otherwise the GDK resources are not created for hidden window,
857 and thus we cannot create OpenGL context there.
858 In effect our testcases (that create window with Visible:=false)
859 would fail on Delphi/Linux with
860 "Widget does not have GDK handle initialized yet". }
861 true
862 {$endif};
863
864 if FullScreen then
865 begin
866 FLeft := 0;
867 FTop := 0;
868 end;
869
870 { pass the actual OpenGLControl sizes (e.g. after accounting for MainMenu size
871 under GTK2 widgetset, actually under all widgetsets that do not have global
872 menu (like macOS), and after accounting for FullScreen).
873 DoResize is already implemented to handle such
874 call (from OpenBackend, before EventOpen was called) correctly. }
875 DoResize(
876 OpenGLControl.PixelsWidth,
877 OpenGLControl.PixelsHeight, false);
878
879 { Assign OpenGLControl.OnPaint *after* making Form visible.
880 If we would assign OpenGLControl.OnPaint earlier, then
881 Form.Visible := true would cause OpenGLControlPaint *before*
882 OpenGL context was created. }
883 OpenGLControl.OnPaint := {$ifdef FPC}@{$endif} OpenGLControlPaint;
884 OpenGLControl.OnResize := {$ifdef FPC}@{$endif} OpenGLControlResize;
885 OpenGLControl.OnKeyDown := {$ifdef FPC}@{$endif} OpenGLControlKeyDown;
886 {$ifdef FPC}
887 OpenGLControl.OnUTF8KeyPress := {$ifdef FPC}@{$endif} OpenGLControlUTF8KeyPress;
888 {$endif}
889 OpenGLControl.OnKeyUp := {$ifdef FPC}@{$endif} OpenGLControlKeyUp;
890 OpenGLControl.OnMouseDown := {$ifdef FPC}@{$endif} OpenGLControlMouseDown;
891 OpenGLControl.OnMouseUp := {$ifdef FPC}@{$endif} OpenGLControlMouseUp;
892 OpenGLControl.OnMouseMove := {$ifdef FPC}@{$endif} OpenGLControlMouseMove;
893 OpenGLControl.OnMouseWheel := {$ifdef FPC}@{$endif} OpenGLControlMouseWheel;
894
895 { Make sure we have OpenGL context created now, and send initial Invalidate
896 (it may not happen automatically, testcase: castle-image-viewer on Carbon).
897 TCastleWindow.OpenCore will call MakeCurrent next. }
898 OpenGLControl.HandleNeeded;
899 OpenGLControl.Invalidate;
900
901 Application.OpenWindowsAdd(Self);
902
903 GetInitialMousePos;
904
905 Container.Dpi := {$ifdef FPC} Screen {$else} OpenGLControl {$endif}.PixelsPerInch;
906 end;
907
908 const
909 BorderNone = {$ifdef FPC} Controls.bsNone {$else} TFmxFormBorderStyle.None {$endif};
910
911 procedure TCastleWindow.UpdateFullScreenForm;
912 begin
913 if FullScreen then
914 begin
915 { For Lazarus (LCL with FPC):
916 - Setting Form.WindowState to wsFullScreen is key to make form fullscreen.
917
918 For FMX (in Delphi):
919 - Setting Form.FullScreen := true (done later) it key.
920 For both Linux and Windows.
921 - Setting Form.BorderStyle to BorderNone actually breaks it on Linux,
922 making form non-full-screen (but borderless).
923 For Windows, it is not a problem.
924 Seems FMXLinux bug? Or at least inconsistency with FMX on Windows.
925 }
926 Form.BorderStyle := {$ifdef FPC} BorderNone {$else} TFmxFormBorderStyle.Sizeable {$endif};
927 Form.WindowState := {$ifdef FPC} wsFullScreen {$else} TWindowState.wsNormal {$endif};
928 end else
929 begin
930 if ResizeAllowed <> raAllowed then
931 Form.BorderStyle := {$ifdef FPC} bsSingle {$else} TFmxFormBorderStyle.Single {$endif}
932 else
933 Form.BorderStyle := {$ifdef FPC} bsSizeable {$else} TFmxFormBorderStyle.Sizeable {$endif};
934 Form.WindowState := {$ifdef FPC} wsNormal {$else} TWindowState.wsNormal {$endif};
935 end;
936
937 {$ifdef DELPHI}
938 Form.FullScreen := FullScreen;
939 {$endif}
940 end;
941
942 {$ifdef FPC}
943 procedure TCastleWindow.KeyPressHandlerPress(Sender: TObject;
944 const Event: TInputPressRelease);
945 begin
946 DoKeyDown(Event.Key, Event.KeyString);
947 end;
948 {$endif}
949
950 procedure TCastleWindow.UpdateFullScreenBackend;
951 begin
952 if FFullScreenBackend <> FFullScreenWanted then
953 begin
954 FFullScreenBackend := FFullScreenWanted;
955 if not Closed then
956 UpdateFullScreenForm;
957 end;
958 end;
959
960 procedure TCastleWindow.CloseBackend;
961 begin
962 { Make freeing of Form and OpenGLControl independent.
963 It seems that otherwise, when OpenGLControl.Parent is Form,
964 freeing Form will also free OpenGLControl - at least on FMX Linux. }
965 if OpenGLControl <> nil then
966 OpenGLControl.Parent := nil;
967
968 {$if not (defined(LCLCarbon) or defined(LCLCocoa))}
969 FreeAndNil(Form);
970 FreeAndNil(OpenGLControl);
971 {$else}
972 { Workaround LCL problem with both Carbon and Cocoa
973 https://github.com/castle-engine/castle-engine/issues/237
974 Freeing LCL form may fail with EAccessViolation. }
975 Form := nil; // causing memory leak, but at least not crash
976 OpenGLControl := nil;
977 {$endif}
978
979 { freeing the Form will automatically free other owned components }
980 Menu := nil;
981
982 { although Menu was already freed, but make sure we also change state,
983 like TCastleWindow.MenuInitialized and clear TMenuItem.Handle. }
984 MenuFinalize;
985
986 {$ifdef FPC}
987 FreeAndNil(FKeyPressHandler);
988 {$endif}
989 end;
990
991 procedure TCastleWindow.SetCaption(const Part: TCaptionPart; const Value: string);
992 begin
993 FCaption[Part] := Value;
994 if not Closed then Form.Caption := GetWholeCaption;
995 end;
996
997 procedure TCastleWindow.BackendMakeCurrent;
998 begin
999 OpenGLControl.MakeCurrent;
1000 end;
1001
1002 procedure TCastleWindow.UpdateCursor;
1003 begin
1004 { FPC (LCL) notes:
1005
1006 - OpenGLControl.Cursor is better than Form.Cursor for this,
1007 hiding the cursor would not work on Carbon with Form.Cursor.
1008
1009 Delphi (FMX) notes:
1010
1011 - Setting Form.Cursor := .. no effect.
1012 Tested on Delphi/Linux and Delphi/Win64, with Delphi 11.3.
1013
1014 - Using
1015
1016 var
1017 CursorService: IFMXCursorService;
1018 begin
1019 if not TPlatformServices.Current.SupportsPlatformService(IFMXCursorService, CursorService) then
1020 Exit;
1021 CursorService.SetCursor(CursorFromCastle(InternalCursor));
1022 end;
1023
1024 On Delphi/Linux with Delphi 11.3:
1025 It changes the cursor only temporarily -- until next mouse move.
1026 So we're not supposed to use this, as I understand -- FMX is internally
1027 I guess using IFMXCursorService to set the value from
1028 OpenGLControl.Cursor.
1029
1030 On Delphi/Win64 with Delphi 11.3:
1031 Seems to do nothing.
1032
1033 - OpenGLControl.Cursor := .. :
1034
1035 Is reliable, on Delphi/Linux, with Delphi 11.3.
1036
1037 Doesn't work Delphi/Win64 with Delphi 11.3.
1038
1039 So really no solution works for Delphi/Win64 with Delphi 11.3...
1040 We just ignore it, as Windows users shall not use this backend,
1041 they shall use better CASTLE_WINDOW_WINAPI.
1042 }
1043
1044 OpenGLControl.Cursor := CursorFromCastle(InternalCursor);
1045 end;
1046
1047 procedure TCastleWindow.SetCursor(const Value: TMouseCursor);
1048 begin
1049 if FCursor <> Value then
1050 begin
1051 FCursor := Value;
1052 if not Closed then
1053 UpdateCursor;
1054 end;
1055 end;
1056
1057 function TCastleWindow.RedirectKeyDownToMenuClick: boolean;
1058 begin
1059 Result := false;
1060 end;
1061
1062 procedure TCastleWindow.SetMousePosition(const Value: TVector2);
1063
1064 { Convert window position from the CGE convention to window system
1065 convention where (0,0) is left-top.
1066 This reverses LeftTopToCastle. }
1067 function CastleToLeftTop(const V: TVector2): TVector2;
1068 begin
1069 Result.X := V.X;
1070 Result.Y := FRealHeight / OpenGLControl.MousePosScale - 1 - V.Y;
1071 end;
1072
1073 var
1074 { LCL takes int mouse positions, Delphi (FMX) takes float mouse positions. }
1075 P: {$ifdef FPC} TVector2Integer {$else} TVector2 {$endif};
1076 Pt: {$ifdef FPC} TPoint {$else} TPointF {$endif};
1077 begin
1078 if not Closed then
1079 begin
1080
1081 { Do not set Mouse.CursorPos to the same value, to make sure we don't cause
1082 unnecessary OnMotion on some systems while actual MousePosition didn't change. }
1083 if TVector2.PerfectlyEquals(Value, FMousePosition) then Exit;
1084
1085 //WritelnLog('New mouse position (CGE coordinates): %f %f', [Value.X, Value.Y]);
1086
1087 P := {$ifdef FPC} CastleToLeftTopInt {$else} CastleToLeftTop {$endif}
1088 (Value / OpenGLControl.MousePosScale);
1089
1090 {$ifdef FPC}
1091 { LCL version: use Mouse.CursorPos .}
1092 Pt := Point(P.X, P.Y);
1093 Pt := OpenGLControl.ControlToScreen(Pt);
1094 Mouse.CursorPos := Pt;
1095
1096 {$else}
1097 { FMX version.
1098 It seems there's no cross-platform solution for this in FMX.
1099 It has IFMXMouseService but only with GetMousePos, not setter.
1100 So we just do platform-specific call in FmxSetMousePos,
1101 for now implemented only for Linux (GTK 3). }
1102
1103 Pt := PointF(P.X, P.Y);
1104 //WritelnLog('New mouse position (OpenGL control coordinates): %f %f', [Pt.X, Pt.Y]);
1105 Pt := OpenGLControl.LocalToAbsolute(Pt);
1106 //WritelnLog('New mouse position (form coordinates): %f %f', [Pt.X, Pt.Y]);
1107 Pt := Form.ClientToScreen(Pt);
1108 //WritelnLog('New mouse position (screen coordinates): %f %f', [Pt.X, Pt.Y]);
1109
1110 {$ifdef LINUX}
1111 if Form.Handle = nil then
1112 begin
1113 WritelnWarning('Cannot set mouse position, form has no Handle');
1114 Exit;
1115 end;
1116 if TLinuxWindowHandle(Form.Handle).NativeHandle = nil then
1117 begin
1118 WritelnWarning('Cannot set mouse position, form has no NativeHandle');
1119 Exit;
1120 end;
1121 FmxSetMousePos(TLinuxWindowHandle(Form.Handle).NativeHandle, Pt);
1122 {$else}
1123 WritelnWarning('Setting mouse position not implemented for this platform with Delphi and CASTLE_WINDOW_FORM');
1124 {$endif}
1125
1126 {$endif}
1127 end;
1128 end;
1129
1130 procedure TCastleWindow.MenuItemClick(Sender: TObject);
1131 var
1132 Entry: TMenuEntry;
1133 begin
1134 Entry := (Sender as TGoodMenuItem).Entry;
1135 if Entry is TMenuItem then
1136 begin
1137 { It seems that checked menu item is always automatically swapped,
1138 at least with LCL-GTK2. So manually revert it to original setting,
1139 as we don't want this (DoMenuClick will change Checked as necessary). }
1140 if Entry is TMenuItemChecked then
1141 MenuUpdateChecked(TMenuItemChecked(Entry));
1142 DoMenuClick(TMenuItem(Entry));
1143 end;
1144 end;
1145
1146 procedure TCastleWindow.FormCloseQuery(Sender: TObject;
1147 var CanClose: Boolean);
1148 begin
1149 DoCloseQuery;
1150 CanClose := false; // DoCloseQuery will call Close when needed
1151 end;
1152
1153 procedure TCastleWindow.FormDeactivate(Sender: TObject);
1154 begin
1155 ReleaseAllKeysAndMouse;
1156 end;
1157
1158 procedure TCastleWindow.OpenGLControlPaint(Sender: TObject);
1159 begin
1160 DoRender;
1161 end;
1162
1163 procedure TCastleWindow.OpenGLControlResize(Sender: TObject);
1164 begin
1165 DoResize(
1166 OpenGLControl.PixelsWidth,
1167 OpenGLControl.PixelsHeight, false);
1168
1169 (*
1170 TODO: The issue is now solved in a different way, to effectively
1171 always behave as if AutoRedisplay=true.
1172 It seems that calling either Invalidate or even DoRender from
1173 TCastleWindow.OpenGLControlResize is sometimes not effective -- the context
1174 doesn't get redrawn, even though logs show it is executed.
1175
1176 Testcase: AutoRedisplay:=false in some
1177 TCastleWindow application *not* doing something in each update that
1178 already causes redisplay each frame (like updating FPS on label).
1179 Then maximize / restore it (e.g. by Alt+F10 in GNOME) repeatedly.
1180 On Delphi/Linux.
1181
1182 {$ifndef FPC}
1183 { When using FMX TOpenGLControl, our Invalidate is not automatically
1184 called by the system when we should be redrawn.
1185 So we have to call it manually.
1186
1187 Testcase this is needed: set AutoRedisplay:=false in some
1188 TCastleWindow application *not* doing something in each update that
1189 already causes redisplay each frame (like updating FPS on label).
1190 Then resize this window.
1191 Without this code, the window would not be redrawn to show new size.
1192 On Delphi/Linux.
1193 }
1194
1195 Invalidate;
1196
1197 //DoRender;
1198 {$endif}
1199 *)
1200 end;
1201
1202 procedure TCastleWindow.OpenGLControlKeyDown(Sender: TObject;
1203 var Key: Word; {$ifndef FPC} var KeyChar: WideChar; {$endif}
1204 Shift: TShiftState);
1205 {$ifdef FPC}
1206 begin
1207 FKeyPressHandler.KeyDown(Key, Shift);
1208 {$else}
1209 var
1210 CastleKey: TKey;
1211 CastleKeyString: String;
1212 begin
1213 FmxKeysToCastle(Key, KeyChar, Shift, CastleKey, CastleKeyString);
1214
1215 if (CastleKey <> keyNone) or (CastleKeyString <> '') then
1216 DoKeyDown(CastleKey, CastleKeyString);
1217 {$endif}
1218 end;
1219
1220 {$ifdef FPC}
1221 procedure TCastleWindow.OpenGLControlUTF8KeyPress(Sender: TObject;
1222 var UTF8Key: TUTF8Char);
1223 begin
1224 FKeyPressHandler.UTF8KeyPress(UTF8Key);
1225 end;
1226 {$endif}
1227
1228 procedure TCastleWindow.OpenGLControlKeyUp(Sender: TObject; var Key: Word;
1229 {$ifndef FPC} var KeyChar: WideChar; {$endif}
1230 Shift: TShiftState);
1231 var
1232 CastleKey: TKey;
1233 {$ifndef FPC}
1234 CastleKeyString: String;
1235 {$endif}
1236 begin
1237 {$ifdef FPC}
1238 FKeyPressHandler.BeforeKeyUp(Key, Shift);
1239 CastleKey := KeyToCastle(Key, Shift);
1240 {$else}
1241
1242 { Note that KeyUp seems to have additional issue with FMXLinux,
1243 not fixed in this code:
1244
1245 When the key is held (so we expect to receive multiple KeyDown
1246 for one KeyUp), FMXLinux sends additional KeyUp before each KeyDown.
1247 So for code, it seems as if user is pressing and releasing the key.
1248 We cannot easily workaround it on CGE side.
1249 To track keys being held, we advise to check Pressed[keyXxx] in Update
1250 methods, instead of relying on KeyDown/KeyUp. }
1251
1252 { In principle, FmxKeysToCastle does something similar to
1253 "CastleKey := KeyToCastle(Key, Shift)" in FPC.
1254 But we have to use it with Delphi, to apply some FMXLinux-specific fixes.
1255 We actually ignore the resulting CastleKeyString now. }
1256
1257 FmxKeysToCastle(Key, KeyChar, Shift, CastleKey, CastleKeyString);
1258 {$endif}
1259
1260 if CastleKey <> keyNone then
1261 DoKeyUp(CastleKey);
1262 end;
1263
1264 procedure TCastleWindow.OpenGLControlMouseDown(Sender: TObject;
1265 Button: TMouseButton; Shift: TShiftState;
1266 X, Y: {$ifdef FPC} Integer {$else} Single {$endif});
1267 var
1268 MyButton: TCastleMouseButton;
1269 begin
1270 if MouseButtonToCastle(Button, MyButton) then
1271 DoMouseDown(MousePosToCastle(X, Y), MyButton, 0);
1272 end;
1273
1274 procedure TCastleWindow.OpenGLControlMouseUp(Sender: TObject;
1275 Button: TMouseButton; Shift: TShiftState;
1276 X, Y: {$ifdef FPC} Integer {$else} Single {$endif});
1277 var
1278 MyButton: TCastleMouseButton;
1279 begin
1280 if MouseButtonToCastle(Button, MyButton) then
1281 DoMouseUp(MousePosToCastle(X, Y), MyButton, 0);
1282 end;
1283
1284 procedure TCastleWindow.ProcessTasks;
1285 begin
1286 { Use ApplicationProperties.LimitFPS (if non-zero, by default 100)
1287 to avoid performing too many updates per second. }
1288 if (ApplicationProperties.LimitFPS <= 0) or
1289 (Fps.UpdateStartTime.ElapsedTime > 1 / ApplicationProperties.LimitFPS) then
1290 begin
1291 { Note that calling here ApplicationProperties._Update/_UpdateEnd
1292 may be too often, in case multiple TCastleWindow are open. }
1293 ApplicationProperties._Update;
1294 DoUpdate;
1295 ApplicationProperties._UpdateEnd;
1296
1297 {$ifdef FPC}
1298
1299 { Manually using Invalidated flag to call DoRender
1300 doesn't seem needed with Delphi/Linux,
1301 so we don't do it to conserve resources.
1302 On Delphi/Linux, DoRender is called from OpenGLControlPaint.
1303
1304 For FPC/LCL, we rely on own Invalidated tracking,
1305 and apply Invalidated here.
1306 Note that DoRender will clear the Invalidated flag
1307 (unless AutoRedisplay). }
1308
1309 if Invalidated then
1310 DoRender;
1311
1312 {$else}
1313
1314 { Original intention: Implement AutoRedisplay,
1315 for FMX this is the only place causing render each frame.
1316
1317 The "if AutoRedisplay then Invalidate;" done by TCastleWindow.DoRender
1318 doesn't have a desired effect on FMX (at least on Linux),
1319 it seems TOpenGLControl.Invalidate inside OnPaint is ignored.
1320 And we ignore own Window.Invalidated tracking with FMX.
1321 So we redo it here.
1322
1323 Testcase: edit_test, but with TCastleEdit deliberately
1324 not doing VisibleChanged each frame.
1325 Without the code below: Window would not be redrawn there
1326 with blinking cursor, so it would ignore AutoRedisplay=true. }
1327
1328 { TODO: Later intention: behave as if AutoRedisplay was always true.
1329 Reason: Only then we get proper redisplay on maximize / restore of the window
1330 with Delphi/Linux. }
1331
1332 //if AutoRedisplay then
1333 Invalidate;
1334 {$endif}
1335 end;
1336 end;
1337
1338 procedure TCastleWindow.Invalidate;
1339 begin
1340 if not Closed then
1341 OpenGLControl.Invalidate;
1342 end;
1343
1344 procedure TCastleWindow.OpenGLControlMouseMove(Sender: TObject;
1345 Shift: TShiftState;
1346 X, Y: {$ifdef FPC} Integer {$else} Single {$endif});
1347 begin
1348 DoMotion(InputMotion(MousePosition, MousePosToCastle(X, Y),
1349 MousePressed, 0));
1350
1351 {$ifdef FPC}
1352 { On LCL, we need to call ProcessTasks often,
1353 as Forms.Application.ProcessMessages in LCL may process ~100 OS events in one call.
1354 This means that LCL Forms.Application.ProcessMessages is quite blocked
1355 when user moves mouse a lot (e.g. doing mouse look in games).
1356 We ensure processing by manually calling ProcessTasks often.
1357
1358 With Delphi FMX, we don't need to do this, and actually we shouldn't
1359 -- it was causing perceived FPS drops when we were moving the mouse.
1360 Testcase:
1361 - moving with mouse Examine mode in play_animation
1362 - rotating around in fps_game }
1363 ProcessTasks;
1364 {$endif}
1365 end;
1366
1367 procedure TCastleWindow.OpenGLControlMouseWheel(Sender: TObject;
1368 Shift: TShiftState; WheelDelta: Integer;
1369 {$ifdef FPC} MousePos: TPoint; {$endif}
1370 var Handled: Boolean);
1371 begin
1372 DoMouseWheel(WheelDelta/120, true);
1373 end;
1374
1375 { TCastleWindow dialogs ---------------------------------------------------------- }
1376
1377 function TCastleWindow.BackendFileDialog(const Title: string; var FileName: string;
1378 OpenDialog: boolean; FileFilters: TFileFilterList): boolean;
1379 var
1380 // In FMX, TSaveDialog descends from TOpenDialog
1381 Dialog: {$ifdef FPC} TFileDialog {$else} TOpenDialog {$endif};
1382 ExpandedFileName: string;
1383 begin
1384 if OpenDialog then
1385 Dialog := TOpenDialog.Create(nil)
1386 else
1387 Dialog := TSaveDialog.Create(nil);
1388 try
1389 Dialog.Title := Title;
1390 if FileName = '' then
1391 Dialog.InitialDir := GetCurrentDir
1392 else
1393 begin
1394 ExpandedFileName := ExpandFileName(FileName);
1395 Dialog.InitialDir := ExtractFilePath(ExpandedFileName);
1396 Dialog.FileName := ExtractFileName(ExpandedFileName);
1397 end;
1398 FileFiltersToDialog(FileFilters, Dialog);
1399 ReleaseAllKeysAndMouse; // do it manually
1400 Result := Dialog.Execute;
1401 if Result then
1402 FileName := Dialog.FileName;
1403 finally FreeAndNil(Dialog) end;
1404 end;
1405
1406 function TCastleWindow.ColorDialog(var Color: TCastleColor): boolean;
1407 {$ifdef FPC}
1408 var
1409 Dialog: TColorDialog;
1410 ColorByte: TVector3Byte;
1411 begin
1412 Dialog := TColorDialog.Create(nil);
1413 try
1414 ColorByte := Vector3Byte(Color.RGB);
1415 Dialog.Color := RGBToColor(ColorByte.X, ColorByte.Y, ColorByte.Z);
1416 ReleaseAllKeysAndMouse; // do it manually
1417 Result := Dialog.Execute;
1418 if Result then
1419 begin
1420 RedGreenBlue(Dialog.Color, ColorByte.X, ColorByte.Y, ColorByte.Z);
1421 Color := Vector4(Vector3(ColorByte), Color.W);
1422 end;
1423 finally FreeAndNil(Dialog) end;
1424 {$else}
1425 begin
1426 WritelnWarning('TODO: ColorDialog not implemented with TCastleWindow backend on FMX');
1427 Result := false;
1428 {$endif}
1429 end;
1430
1431 procedure TCastleWindow.MessageOK(const S: string; const MessageType: TWindowMessageType);
1432 const
1433 MessageTypeCastleToLCL: array [TWindowMessageType] of TMsgDlgType = (
1434 TMsgDlgType.mtInformation,
1435 TMsgDlgType.mtWarning,
1436 TMsgDlgType.mtConfirmation,
1437 TMsgDlgType.mtError,
1438 TMsgDlgType.mtCustom
1439 );
1440 begin
1441 ReleaseAllKeysAndMouse; // do it manually
1442 MessageDlg(S, MessageTypeCastleToLCL[MessageType], [TMsgDlgBtn.mbOK], 0);
1443 end;
1444
1445 function TCastleWindow.MessageYesNo(const S: string;
1446 const MessageType: TWindowMessageType): boolean;
1447 begin
1448 ReleaseAllKeysAndMouse; // do it manually
1449 Result := MessageDlg(S, TMsgDlgType.mtConfirmation,
1450 [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0) = mrYes;
1451 end;
1452
1453 procedure TCastleWindow.FormDropFiles(Sender: TObject; const FileNames: array of string);
1454 begin
1455 DoDropFiles(FileNames);
1456 end;
1457
1458 procedure TCastleWindow.BackendInsideUpdate;
1459 begin
1460 {$if defined(FPC)}
1461 FKeyPressHandler.Flush; // finish any pending key presses
1462 {$else}
1463 OpenGLControl.Update; // on FMX, we need to call TOpenGLControl.Update
1464 {$endif}
1465 end;
1466
1467 function TCastleWindow.MousePosToCastle(
1468 const X, Y: {$ifdef FPC} Integer {$else} Single {$endif}): TVector2;
1469 begin
1470 Result := LeftTopToCastle(
1471 X * OpenGLControl.MousePosScale,
1472 Y * OpenGLControl.MousePosScale);
1473 end;
1474
1475 { TFormsClipboard ----------------------------------------------------------- }
1476
1477 type
1478 { Easy API for LCL or FMX clipboard. }
1479 TFormsClipboard = class(TCastleClipboard)
1480 protected
1481 function GetAsText: string; override;
1482 procedure SetAsText(const Value: string); override;
1483 end;
1484
1485 function TFormsClipboard.GetAsText: string;
1486 {$ifdef FPC}
1487 begin
1488 Result := Clipbrd.Clipboard.AsText;
1489 {$else}
1490 var
1491 ClipboardService: IFMXClipboardService;
1492 Value: TValue;
1493 begin
1494 if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, ClipboardService) then
1495 begin
1496 Value := ClipboardService.GetClipboard;
1497 if not Value.TryAsType(Result) then
1498 Result := '';
1499 end;
1500 {$endif}
1501 end;
1502
1503 procedure TFormsClipboard.SetAsText(const Value: string);
1504 {$ifdef FPC}
1505 begin
1506 Clipbrd.Clipboard.AsText := Value;
1507 {$else}
1508 var
1509 ClipboardService: IFMXClipboardService;
1510 begin
1511 if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, ClipboardService) then
1512 begin
1513 ClipboardService.SetClipboard(Value);
1514 end;
1515 {$endif}
1516 end;
1517
1518 { TCastleApplication ---------------------------------------------------------- }
1519
1520 procedure TCastleApplication.CreateBackend;
1521 begin
1522 RegisterClipboard(TFormsClipboard.Create);
1523
1524 {$ifdef FPC}
1525 { Do not install LCL handler for ExceptProc, we want to use our own handler
1526 in CastleUtils. }
1527 FormApplication.CaptureExceptions := false;
1528 {$else}
1529 { We tested assigning on Delphi FMX
1530 FormApplication.OnException := DoNothingOnException;
1531 to a callback that does nothing.
1532 But this was bad: exceptions still didn't reach TCastleWindow
1533 (testcase: deliberate exception from simple_3d_demo)
1534 and CtrlC handling was worse (first CtrlC was ignored -- though later tests
1535 suggest it can happen anyway, regardless of FormApplication.OnException).
1536 So don't tweak this for Delphi FMX. }
1537 {$endif}
1538
1539 FormApplication.Initialize;
1540
1541 {$ifdef USE_TIMER}
1542 FTimer := TTimer.Create(Self);
1543 FTimer.Interval := 1;
1544 FTimer.OnTimer := {$ifdef FPC}@{$endif} ApplicationTimer;
1545 FTimer.Enabled := true;
1546 {$endif USE_TIMER}
1547 end;
1548
1549 procedure TCastleApplication.DestroyBackend;
1550 begin
1551 {$ifdef USE_TIMER}
1552 FreeAndNil(FTimer);
1553 {$endif}
1554 end;
1555
1556 {$ifdef USE_TIMER}
1557 procedure TCastleApplication.ApplicationTimer(Sender: TObject);
1558 begin
1559 ApplicationProperties._Update;
1560 { Call Update events on all windows. }
1561 FOpenWindows.DoUpdate;
1562 ApplicationProperties._UpdateEnd;
1563 end;
1564 {$endif}
1565
1566 function TCastleApplication.ProcessMessage(WaitForMessage, WaitToLimitFPS: boolean): boolean;
1567
1568 function CheckTerminated: Boolean;
1569 begin
1570 Result :=
1571 { Check our "Terminated" (from TCustomApplication):
1572
1573 - This way we honor "Application.Terminate" calls
1574 from CGE applications, like fps_game main menu "Quit" button.
1575 Which is necessary regardless of USE_TIMER.
1576
1577 - And we honor "Terminate" calls done by TCastleApplication
1578 itself when last open window is closed.
1579 }
1580 Terminated
1581 or
1582 { It seems we don't need to check FormApplication.Terminated at all now.
1583 Unless some LCL widgetset sets FormApplication.Terminated directly,
1584 e.g. maybe Cocoa application menu "Quit" sets FormApplication.Terminated?
1585
1586 Note that such widgetset would interrupt its own FormApplication.Run
1587 anyway. So us checking here "FormApplication.Terminated" matters only
1588 if
1589 1. USE_TIMER is not defined in this case,
1590 2. or user code uses CGE "Application.ProcessMessage" directly.
1591 }
1592 FormApplication.Terminated;
1593 end;
1594
1595 var
1596 I: Integer;
1597 begin
1598 if CheckTerminated then
1599 Exit(false);
1600
1601 { When not USE_TIMER, we cannot wait for message, as it would mean we
1602 can hang indefinitely. }
1603 {$ifndef USE_TIMER}
1604 WaitForMessage := false;
1605 {$endif}
1606
1607 { TODO: take WaitToLimitFPS into account }
1608
1609 if WaitForMessage then
1610 begin
1611 { TODO: We never call Fps.InternalSleeping, so Fps.WasSleeping
1612 will be always false.
1613
1614 This may result in confusing Fps.ToString in case
1615 - AutoRedisplay is false (since otherwise we render each frame)
1616 - and USE_TIMER is defined (since otherwise we never have WaitForMessage=true)
1617
1618 This doesn't seem to matter for any practical application of this. }
1619
1620 { HandleMessage will call timer events, so no need for ProcessTasks
1621 hack in this case. }
1622 FormApplication.HandleMessage;
1623 Result := not CheckTerminated;
1624 end else
1625 begin
1626 FormApplication.ProcessMessages;
1627 Result := not CheckTerminated;
1628
1629 {$ifndef USE_TIMER}
1630 if Result then
1631 ProcessTasks;
1632 {$endif}
1633 end;
1634 end;
1635
1636 procedure TCastleApplication.ProcessTasks;
1637 var
1638 I: Integer;
1639 begin
1640 for I := 0 to OpenWindowsCount - 1 do
1641 OpenWindows[I].ProcessTasks;
1642 end;
1643
1644 function TCastleApplication.ProcessAllMessages: boolean;
1645 begin
1646 // Result := not FormApplication.Terminated;
1647 // while Result do
1648 Result := ProcessMessage(false, false);
1649 end;
1650
1651 procedure TCastleApplication.Run;
1652 begin
1653 if OpenWindowsCount = 0 then Exit;
1654
1655 {$ifdef USE_TIMER}
1656 { LCL Cocoa really must call here FormApplication.Run.
1657
1658 It cannot just call our ProcessMessage
1659 (which makes FormApplication.ProcessMessage) in a loop.
1660 That is because on some LCL widgetsets, you really need to run
1661 FormApplication.Run, see e.g. Carbon that does special stuff inside
1662 TCarbonWidgetSet.AppRun inside lcl/interfaces/carbon/carbonobject.inc.
1663 Without this, global menu on Carbon is always blocked.
1664
1665 This causes necessary Cocoa problems:
1666
1667 - Our TCastleWindow interface
1668 promises that it's not necessary to call Run, it should be always
1669 equivalent to call just ProcessMessage in a loop.
1670 For Cocoa with CASTLE_WINDOW_FORM, this cannot be true.
1671
1672 Other platforms with USE_TIMER call FormApplication.Run here
1673 as this is most straightforward.
1674 It maps to AppService.Run in FMX, so specific platforms
1675 may benefit from having FormApplication.Run call instead of loop
1676 over ProcessMessage.
1677 }
1678 FormApplication.Run;
1679 {$else}
1680 while ProcessMessage(false, false) do ;
1681 {$endif}
1682 end;
1683
1684 procedure TCastleApplication.BackendTerminate;
1685 begin
1686 {$ifdef USE_TIMER}
1687
1688 { TODO: This line makes sense, for USE_TIMER,
1689 to break FormApplication.Run when user code runs "Application.Terminate".
1690 Or when last window is closed (by Alt+F4,
1691 or clicking on "X" button on window frame).
1692 Testcase: "fps_game" "Quit" menu button, or "fps_game" click on "X" button.
1693
1694 But it causes crash with "fps_game" "Quit" menu button
1695 -- reproduced with Delphi 11.3 on Win32 and Win64,
1696 when compiled with CASTLE_WINDOW_FORM for Windows.
1697 Backtrace uncertain, stack trace seems somewhat currupted.
1698 Maybe this fails when called from CloseAllOpenWindows,
1699 maybe from TCastleApplication destructor,
1700 but workaround by "if not (csDestroying in ComponentState)"
1701 doesn't help. }
1702 FormApplication.Terminate; // break also FormApplication.Run
1703
1704 {$endif}
1705 end;
1706
1707 function TCastleApplication.ScreenWidth: integer;
1708 begin
1709 { TODO: On FMX (Delphi) and Windows, this doesn't return correct size in pixels.
1710 We tried, but failed, to fix it:
1711 See castlewindow_form_fmx_scaling.md }
1712
1713 Result := Round(Screen.Width); // Round for FMX
1714 end;
1715
1716 function TCastleApplication.ScreenHeight: integer;
1717 begin
1718 Result := Round(Screen.Height); // Round for FMX
1719 end;
1720
1721 function TCastleApplication.BackendName: string;
1722 begin
1723 Result := 'Form';
1724 end;
1725
1726 { TWindowContainer ----------------------------------------------------------- }
1727
1728 function TWindowContainer.SettingMousePositionCausesMotion: Boolean;
1729 begin
1730 { Delphi/Linux, using
1731 https://docs.gtk.org/gdk3/method.Device.warp.html for SetMousePosition,
1732 says
1733
1734 """
1735 Warping the pointer creates events as if the user had moved
1736 the mouse instantaneously to the destination.
1737 """
1738
1739 So it does generate Motion events.
1740 }
1741 Result := true;
1742 end;
1743
1744 {$endif read_implementation}