This file is indexed.

/usr/src/castle-game-engine-5.2.0/window/castlewindow_lcl.inc is in castle-game-engine-src 5.2.0-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
{
  Copyright 2013-2014 Michalis Kamburelis.

  This file is part of "Castle Game Engine".

  "Castle Game Engine" is free software; see the file COPYING.txt,
  included in this distribution, for details about the copyright.

  "Castle Game Engine" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  ----------------------------------------------------------------------------
}

(*CastleWindow backend using Lazarus LCL underneath.
  Should work with all LCL widgetsets, but was especially done and tested
  to use LCL Carbon widgetset under Mac OS X (since for other OSes
  we already have more native CastleWindow backends).

  TODO:
  - Mouse look still stutters awfully on both Carbon and GTK2.
    AggressiveUpdate helps (without it, mouse look would not work at all)
    but doesn't completely fix the problem. Other CastleWindow backends
    have smooth mouse look.

  Bugs on GTK2, not on Carbon:
  - All radio menu items are always on. Why?

  Bugs on Carbon, untested elsewhere:
  - When you switch FullScreen, at application exit there is an access violation
    in LCL. Seems harmless, so we just ignore it for now.
*)

{$ifdef read_interface_uses}
Interfaces, Forms, Dialogs, OpenGLContext, Menus,
Controls, FileUtil, Graphics, LCLType, CastleLCLUtils, Clipbrd, CustomTimer, LCLVersion,
{$endif}

{$ifdef read_window_interface}
private
  type
    { Descendant of LCL TMenuItem used for our menu. }
    TGoodMenuItem = class(Menus.TMenuItem)
    public
      Window: TCastleWindowCustom;
      Entry: TMenuEntry;

      { Capture IntfDoSelect, which is fired on GTK2
        event 'select' on menu item, which we have to capture to call
        ReleaseAllKeysAndMouse.

        Just like in our gtk/castlewindow_gtk_menu.inc: capturing 'select' GTK2
        event is the only way to capture when user opened menu bar.
        And we need to capture it, to work with GTK2 and menu bar,
        e.g. when you use Alt+F to reach "File" menu, do not keep "Alt" key in
        the pressed state indefinitely (e.g. it would make camera keys non-working
        after opening a file using Alt+F and recent files in view3dscene).

        This should be also harmless on other non-GTK2 widgetsets. }
      procedure IntfDoSelect; override;
    end;

    { Like TOpenGLControl but sets Invalidated:=true on Window,
      so that Window knows when it's invalidated by the OS. }
    TGoodOpenGLControl = class(TOpenGLControl)
    public
      Window: TCastleWindowCustom;
      procedure Invalidate; override;
    end;

  var
    Form: TForm;
    OpenGLControl: TGoodOpenGLControl;
    Menu: TMainMenu;

  procedure MenuCastleToLCL(const MyMenu: TMenu; const AMenu: Menus.TMenuItem);
  function MenuEntryCastleToLCL(const MyEntry: TMenuEntry): TGoodMenuItem;

  procedure MenuItemClick(Sender: TObject);
  procedure MenuUpdateShortcut(Entry: TMenuItem);
  procedure AggressiveUpdate;
  procedure UpdateFullScreen;

  procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
  procedure FormDeactivate(Sender: TObject);
  procedure FormDropFiles(Sender: TObject; const FileNames: array of string);

  procedure OpenGLControlPaint(Sender: TObject);
  procedure OpenGLControlResize(Sender: TObject);
  procedure OpenGLControlKeyDown(Sender: TObject; var Key: Word;
    Shift: TShiftState);
  procedure OpenGLControlKeyUp(Sender: TObject; var Key: Word;
    Shift: TShiftState);
  procedure OpenGLControlMouseDown(Sender: TObject; Button: Controls.TMouseButton;
    Shift: TShiftState; X, Y: Integer);
  procedure OpenGLControlMouseUp(Sender: TObject; Button: Controls.TMouseButton;
    Shift: TShiftState; X, Y: Integer);
  procedure OpenGLControlMouseMove(Sender: TObject; Shift: TShiftState; X,
    Y: Integer);
  procedure OpenGLControlMouseWheel(Sender: TObject; Shift: TShiftState;
    WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
{$endif read_window_interface}

{$ifdef read_application_interface}
private
  LastDoTimerTime: TMilisecTime;
  {$ifdef LCLCarbon}
  FTimer: TCustomTimer;
  procedure ApplicationTimer(Sender: TObject);
  {$endif LCLCarbon}
  procedure ApplicationIdle(Sender: TObject; var Done: Boolean);
{$endif read_application_interface}

{$ifdef read_implementation}

const
  MaxDesiredFPS = DefaultLimitFPS;

{ TGoodMenuItem ---------------------------------------------------------------- }

procedure TCastleWindowCustom.TGoodMenuItem.IntfDoSelect;
begin
  inherited;
  Window.ReleaseAllKeysAndMouse;
end;

{ TGoodOpenGLControl --------------------------------------------------------- }

procedure TCastleWindowCustom.TGoodOpenGLControl.Invalidate;
begin
  // track our own Invalidated state, although still cooperate with LCL invalidate
  Window.Invalidated := true;
  inherited;
end;

{ TCastleWindowCustom ------------------------------------------------------------------ }

procedure TCastleWindowCustom.CreateBackend;
begin
end;

function TCastleWindowCustom.MenuEntryCastleToLCL(const MyEntry: TMenuEntry): TGoodMenuItem;
begin
  Result := TGoodMenuItem.Create(Form);
  Result.Window := Self;
  Result.OnClick := @MenuItemClick;
  { store connection both ways between LCL menu item <-> our menu entry }
  Result.Entry := MyEntry;
  MyEntry.Handle := Result;
  if MyEntry is TMenuItem then
    MenuUpdateShortcut(TMenuItem(MyEntry));
  if MyEntry is TMenuEntryWithCaption then
  begin
    { set MenuItem.Caption and Enabled }
    MenuUpdateCaption(TMenuEntryWithCaption(MyEntry));
    MenuUpdateEnabled(TMenuEntryWithCaption(MyEntry));
    if MyEntry is TMenuItemChecked then
    begin
      Result.ShowAlwaysCheckable := true;
      Result.RadioItem := MyEntry is TMenuItemRadio;
      MenuUpdateChecked(TMenuItemChecked(MyEntry));
    end;
  end else
  if MyEntry is TMenuSeparator then
    { set Result.Caption - special for separator }
    Result.Caption := '-';
  { if we have submenu, do this recursively }
  if MyEntry is TMenu then
    MenuCastleToLCL(TMenu(MyEntry), Result);
end;

procedure TCastleWindowCustom.MenuCastleToLCL(const MyMenu: TMenu;
  const AMenu: Menus.TMenuItem);
var
  I: Integer;
begin
  for I := 0 to MyMenu.Count - 1 do
    AMenu.Add(MenuEntryCastleToLCL(MyMenu[I]));
end;

procedure TCastleWindowCustom.BackendMenuInitialize;
begin
  Menu := TMainMenu.Create(Form);
  { connet Menu with Form }
  Menu.Parent := Form;
  Form.Menu := Menu;
  MenuCastleToLCL(MainMenu, Menu.Items);
end;

procedure TCastleWindowCustom.BackendMenuFinalize;
begin
  FreeAndNil(Menu);
  MainMenu.ClearHandles;
end;

function CheckMenu(const Entry: TMenuEntry; out EntryLCL: Menus.TMenuItem): boolean;
begin
  EntryLCL := Menus.TMenuItem(Entry.Handle);
  Result := EntryLCL <> nil;
  if (not Result) and Log and
     ((Entry.CorrectParentWindow = nil) or Entry.CorrectParentWindow.MainMenuVisible) then
    WritelnLog('Menu', 'Warning: menu entry has Handle = nil (this means that corresponding LCL menu item object was not created, but it should)');
end;

procedure TCastleWindowCustom.MenuUpdateShortcut(Entry: TMenuItem);
var
  LazKey: Word;
  Shift: TShiftState;
  EntryLCL: Menus.TMenuItem;
begin
  if not CheckMenu(Entry, EntryLCL) then Exit;

  {$ifdef LCLCarbon}
  { Workaround yet another bug in LCL Carbon.
    When a menu item is disabled (because Entry.Enabled is false or
    MainMenu.Enabled is false), it turns out we have to disable it's shortcut.
    Otherwise pressing this shortcut can be captured and cause strange behavior
    later.

    view3dscene bugs (when this workaround not present) on Mac OS X:
    - Enter "Open Link" with Command+L. Press Command+O (that leads to disabled
      menu item, and doesn't do anything!). Nothing happens, dummy letter with
      Ord(CtrlO) is inserted, that's Ok. Then press Escape. And the dialog appears
      again... Somehow, the Command+O (pressed when it was disabled!) was captured,
      with delay, and caused weird double menu item activation.
    - Similarly, after Command+R, press Command+O before escaping.
      It causes the raytracing dialog to appear again after escaping.
  }
  if not EntryLCL.Enabled then
  begin
    EntryLCL.ShortCut := 0;
    Exit;
  end;
  {$endif}

  KeyCastleToLCL(Entry.Key, Entry.CharKey, Entry.Modifiers, LazKey, Shift);
  EntryLCL.ShortCut := KeyToShortCut(LazKey, Shift);
end;

procedure TCastleWindowCustom.MenuUpdateCaption(Entry: TMenuEntryWithCaption);

  function MenuCaptionCastleToLCL(const S: string): string;
  begin
    { We use _ for the same purpose as LCL uses &, to mark mnemonics.
      But we cannot just replace _ with &:
      Double underscore should be converted to single underscore.
      Only unpaired single underscore should be converted to &.
      Our SReplacePatterns guarantees correct behavior. }
    Result := SReplacePatterns(S, ['__', '_'], ['_', '&'], [soMatchCase]);
  end;

var
  EntryLCL: Menus.TMenuItem;
begin
  if not CheckMenu(Entry, EntryLCL) then Exit;
  EntryLCL.Caption := MenuCaptionCastleToLCL(Entry.Caption);
end;

procedure TCastleWindowCustom.MenuUpdateEnabled(Entry: TMenuEntryWithCaption);

  procedure RefreshEnabled(MyMenu: TMenu);

    procedure RefreshEnabledEntry(const MyEntry: TMenuEntry);
    begin
      if MyEntry is TMenuEntryWithCaption then
        MenuUpdateEnabled(TMenuEntryWithCaption(MyEntry));
      if MyEntry is TMenu then
        RefreshEnabled(TMenu(MyEntry));
    end;

  var
    I: Integer;
  begin
    for I := 0 to MyMenu.Count - 1 do
      RefreshEnabledEntry(MyMenu[I]);
  end;

var
  EntryLCL: Menus.TMenuItem;
begin
  { To apply MainMenu.Enabled: we would prefer to map MainMenu.Enabled
    on LCL Menu.Items.Enabled, and just handle MainMenu.Enabled like
    every other menu item. But LCL (at least GTK2 and Carbon) seems to
    completely ignore Menu.Items.Enabled.

    So to do make it work, we
    1. Always combine MainMenu.Enabled with particular item's Enabled value
       (in particular, this way BackendMenuInitialize applies it to every item).
    2. At MenuUpdateEnabled for MainMenu (so when you change MainMenu.Enabled
       value) we do a refresh (update enabled state) of all the menu items.

    Note that we cannot just do MenuFinalize + MenuInitialize to implement
    the 2nd step, because Mac OS X (Carbon) reacts very badly to menu rebuilds.
    There is a problem when you have a menu item with key shortcut,
    and when this menu item is executed --- we destroy and create new menu
    that also reacts to this shortcut. In this case, Carbon executes
    the menu item again! Consider e.g. view3dscene "File->Open" with
    Ctrl+O shortcut, that after opening a new file rebuilds the menu
    to update the "recent files" menu section. Consider also "Display->Raytrace"
    with Ctrl+R shortcut, that after choosing options changes
    the MainMenu.Enabled. If we would do a MenuFinalize + MenuInitialize
    to easiy recreate LCL menu, we would see open dialog twice after Ctrl+O,
    and raytrace dialog twice after Ctrl+R. So we don't do it.
    In MenuInsert and MenuDelete and in this method, MenuUpdateEnabled,
    we merely change the existing LCL menu instances.

    This all could be considered Carbon's bug, anyway we have to work with it.
  }

  if Entry = MainMenu then
  begin
    RefreshEnabled(MainMenu);
    Exit;
  end;

  if not CheckMenu(Entry, EntryLCL) then Exit;
  EntryLCL.Enabled := Entry.Enabled and MainMenu.Enabled;

  {$ifdef LCLCarbon}
  if Entry is TMenuItem then
    MenuUpdateShortcut(TMenuItem(Entry));
  {$endif}
end;

procedure TCastleWindowCustom.MenuUpdateChecked(Entry: TMenuItemChecked);
var
  EntryLCL: Menus.TMenuItem;
begin
  if not CheckMenu(Entry, EntryLCL) then Exit;
  EntryLCL.Checked := Entry.Checked;
end;

function TCastleWindowCustom.MenuUpdateCheckedFast: boolean;
begin
  Result := true;
end;

procedure TCastleWindowCustom.MenuInsert(const Parent: TMenu;
  const ParentPosition: Integer; const Entry: TMenuEntry);
var
  ParentLCL: Menus.TMenuItem;
begin
  if not CheckMenu(Parent, ParentLCL) then Exit;
  ParentLCL.Insert(ParentPosition, MenuEntryCastleToLCL(Entry));
end;

procedure TCastleWindowCustom.MenuDelete(const Parent: TMenu;
  const ParentPosition: Integer; const Entry: TMenuEntry);
var
  EntryLCL: Menus.TMenuItem;
begin
  if not CheckMenu(Entry, EntryLCL) then Exit;
  Entry.ClearHandles;

  {$ifdef LCLCarbon}
    (*Workaround LCL on Carbon bug http://bugs.freepascal.org/view.php?id=20688 .

      Symptoms:
      Sometimes after menu changes we have a segfault in Carbon widgetset,
      like our menu item reference was invalid.
      Happens after various menu changes: rebuilding the menu, also fast changes
      like MenuDelete (like when changing recent files submenu in view3dscene).
      It seems that Carbon doesn't like deleting a menu currently used.

      Happens both when debugging and not debugging.
      Using the file menu to choose a recent file to load from view3dscene
      is the most common case.

      In Lazarus debuggger:
        Project view3dscene.app raised exception class 'External: EXC_BAD_ACCESS'.
        In file './carbon/carbonlclintf.inc' at line 342:
        end; {TCarbonWidgetSet.PromptUser}

      When running from console:
        TApplication.HandleException Access violation
          Stack trace:
          $0039566B  CARBONAPP_COMMANDPROCESS,  line 2872 of /Users/michalis/sources/lazarus/trunk/lcl/interfaces/./carbon/carbonint.pas

      Most probably this is the same thing as reported on
      http://bugs.freepascal.org/view.php?id=20688  .
      Less likely, to http://bugs.freepascal.org/view.php?id=18908 ?

      Workaround for now is just to not remove LCL menu items, only hide them.
      This at least fixes the issue when we delete menu by MenuDelete
      (as opposed to menu rebuild).
    *)
    EntryLCL.Visible := false;
  {$else}
    FreeAndNil(EntryLCL);
  {$endif}
end;

procedure TCastleWindowCustom.SwapBuffers;
begin
  OpenGLControl.SwapBuffers;
end;

procedure TCastleWindowCustom.OpenBackend;
begin
  { We use Forms.Application.CreateForm, not just "Form := TForm.CreateNew(nil)",
    because we want our Form to be set as Forms.Application.MainForm.

    And there is no other way to set Forms.Application.MainForm,
    we have to use mechanism that "the first form created by Application.CreateForm
    is set as main", see http://www.lazarus.freepascal.org/index.php?topic=14438.0
    and LCL sources of TApplication.UpdateMainForm.
    The "Forms.Application.MainForm" property is not directly settable.

    And we need to have a main form, as that's the only way to capture (in form
    close event) the Mac OS X "ProjectName -> Quit" automatic menu item (see
    http://bugs.freepascal.org/view.php?id=10983).

    Note: This would be a problem if we used TForm descendant,
    as then Forms.Application.CreateForm would search for a related resource.
    Unless we set RequireDerivedFormResource to false (which actually
    is the default RequireDerivedFormResource value for now, but the adviced
    value is true).
    Fortunately, the whole resource-searching is not used when we just
    have a TForm class (see TCustomForm.Create in LCL), so that's not a problem. }

  Forms.Application.CreateForm(TForm, Form);
  Form.OnDropFiles := @FormDropFiles;

  Form.Top := Top;
  Form.Left := Left;
  { We would prefer to leave Form.AutoSize := true and allow form to adjust
    to OpenGLControl.Width/Height. But it doesn't work. }
  Form.Width := Width;
  Form.Height := Height;
  Form.Caption := GetWholeCaption; // SetCaption may also change it later
  Form.Cursor := CursorCastleToLCL[Cursor]; // SetCursor may also change it later

  UpdateFullScreen;

  Form.OnCloseQuery := @FormCloseQuery;
  { Note: I tried also using OpenGLControl.OnExit for this, seems to be quivalent
    in our case. And, similarly, both methods still need manual workaround
    to call ReleaseAllKeysAndMouse manually in MessageOK and similar methods
    (otherwise: check e.g. window_events with Window.MessageOk from Update:
    entering MessageOK *must* make ReleaseAllKeysAndMouse, otherwise it hangs.) }
  Form.OnDeactivate := @FormDeactivate;

  OpenGLControl := TGoodOpenGLControl.Create(Form);
  OpenGLControl.Window := Self;
  OpenGLControl.Parent := Form;
  OpenGLControl.Align := alClient;
  OpenGLControl.Width := Width;
  OpenGLControl.Height := Height;
  OpenGLControl.Constraints.MinWidth := MinWidth;
  OpenGLControl.Constraints.MinHeight := MinHeight;
  OpenGLControl.Constraints.MaxWidth := MaxWidth;
  OpenGLControl.Constraints.MaxHeight := MaxHeight;
  OpenGLControl.TabStop := true;

  OpenGLControl.DoubleBuffered := DoubleBuffer;
  {$if (LCL_FullVersion > 1001000)}
  OpenGLControl.StencilBits := StencilBits;
  OpenGLControl.DepthBits := DepthBits;
  OpenGLControl.AlphaBits := AlphaBits;
  OpenGLControl.MultiSampling := MultiSampling;
  {$else}
  {$warning Using LCL (Lazarus library) version before 1.1. OpenGL control doesn't have features to control stencil/alpha/multi-sampling etc.}
  {$endif}

  Form.ActiveControl := OpenGLControl;

  if (MainMenu <> nil) and MainMenuVisible then
    MenuInitialize;

  Form.Visible := Visible;

  if FullScreen then
  begin
    FLeft := 0;
    FTop := 0;
  end;

  { pass the actual OpenGLControl sizes (e.g. after accounting for MainMenu size
    under GTK2 widgetset, actually under all widgetsets that do not have global
    menu (like Mac OS X), and after accounting for FullScreen).
    DoResize is already implemented to handle such
    call (from OpenBackend, before EventOpen was called) correctly. }
  DoResize(OpenGLControl.Width, OpenGLControl.Height, false);

  { Assign OpenGLControl.OnPaint *after* making Form visible.
    If we would assign OpenGLControl.OnPaint earlier, then
    Form.Visible := true would cause OpenGLControlPaint *before*
    OpenGL context was created. }
  OpenGLControl.OnPaint := @OpenGLControlPaint;
  OpenGLControl.OnResize := @OpenGLControlResize;
  OpenGLControl.OnKeyDown := @OpenGLControlKeyDown;
  OpenGLControl.OnKeyUp := @OpenGLControlKeyUp;
  OpenGLControl.OnMouseDown := @OpenGLControlMouseDown;
  OpenGLControl.OnMouseUp := @OpenGLControlMouseUp;
  OpenGLControl.OnMouseMove := @OpenGLControlMouseMove;
  OpenGLControl.OnMouseWheel := @OpenGLControlMouseWheel;

  { Make sure we have OpenGL context created now, and send initial Invalidate
    (it may not happen automatically, testcase: glViewImage on Carbon).
    TCastleWindowCustom.OpenCore will call MakeCurrent next. }
  OpenGLControl.HandleNeeded;
  OpenGLControl.Invalidate;

  Application.OpenWindowsAdd(Self);
end;

const
  BorderNone = Controls.bsNone;

procedure TCastleWindowCustom.UpdateFullScreen;
begin
  if FullScreen then
  begin
    Form.BorderStyle := BorderNone;
    Form.WindowState := wsFullScreen;
  end else
  begin
    if ResizeAllowed <> raAllowed then
      Form.BorderStyle := bsSingle else
      Form.BorderStyle := bsSizeable;
    Form.WindowState := wsNormal;
  end;
end;

procedure TCastleWindowCustom.SetFullScreen(const Value: boolean);
begin
  if FFullScreen <> Value then
  begin
    FFullScreen := Value;
    if not Closed then
      UpdateFullScreen;
  end;
end;

procedure TCastleWindowCustom.CloseBackend;
begin
  FreeAndNil(Form);
  { freeing the Form will automatically free other owned components }
  OpenGLControl := nil;
  Menu := nil;

  { although Menu was already freed, but make sure we also change state,
    like TCastleWindowCustom.MenuInitialized and clear TMenuItem.Handle. }
  MenuFinalize;
end;

procedure TCastleWindowCustom.SetCaption(const Part: TCaptionPart; const Value: string);
begin
  FCaption[Part] := Value;
  if not Closed then Form.Caption := GetWholeCaption;
end;

procedure TCastleWindowCustom.BackendMakeCurrent;
begin
  OpenGLControl.MakeCurrent;
end;

procedure TCastleWindowCustom.SetCursor(const Value: TMouseCursor);
begin
  if FCursor <> Value then
  begin
    FCursor := Value;
    if not Closed then
      { Do not use Form.Cursor for this, e.g. hiding the cursor would not work
        then on Carbon. }
      OpenGLControl.Cursor := CursorCastleToLCL[Value];
  end;
end;

procedure TCastleWindowCustom.SetCustomCursor(const Value: TRGBAlphaImage);
begin
  { TODO }
  FCustomCursor := Value;
end;

function TCastleWindowCustom.RedirectKeyDownToMenuClick: boolean;
begin
  Result := false;
end;

procedure TCastleWindowCustom.SetMousePosition(const Value: TVector2Single);
begin
  if not Closed then
    Mouse.CursorPos := OpenGLControl.ControlToScreen(Point(
      Floor(Value[0]), Height - 1 - Floor(Value[1])));
end;

procedure TCastleWindowCustom.MenuItemClick(Sender: TObject);
var
  Entry: TMenuEntry;
begin
  Entry := (Sender as TGoodMenuItem).Entry;
  if Entry is TMenuItem then
  begin
    { It seems that checked menu item is always automatically swapped,
      at least with LCL-GTK2. So manually revert it to original setting,
      as we don't want this (DoMenuClick will change Checked as necessary). }
    if Entry is TMenuItemChecked then
      MenuUpdateChecked(TMenuItemChecked(Entry));
    DoMenuClick(TMenuItem(Entry));
  end;
end;

procedure TCastleWindowCustom.FormCloseQuery(Sender: TObject;
  var CanClose: Boolean);
begin
  DoCloseQuery;
  CanClose := false; // DoCloseQuery will call Close when needed
end;

procedure TCastleWindowCustom.FormDeactivate(Sender: TObject);
begin
  ReleaseAllKeysAndMouse;
end;

procedure TCastleWindowCustom.OpenGLControlPaint(Sender: TObject);
begin
  DoRender;
end;

procedure TCastleWindowCustom.OpenGLControlResize(Sender: TObject);
begin
  DoResize(OpenGLControl.Width, OpenGLControl.Height, false);
end;

procedure TCastleWindowCustom.OpenGLControlKeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
var
  MyKey: TKey;
  MyCharKey: char;
begin
  KeyLCLToCastle(Key, Shift, MyKey, MyCharKey);
  if (MyKey <> K_None) or (MyCharKey <> #0) then
    DoKeyDown(MyKey, MyCharKey);
end;

procedure TCastleWindowCustom.OpenGLControlKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var
  MyKey: TKey;
  MyCharKey: char;
begin
  KeyLCLToCastle(Key, Shift, MyKey, MyCharKey);
  if MyKey <> K_None then
    DoKeyUp(MyKey);
end;

procedure TCastleWindowCustom.OpenGLControlMouseDown(Sender: TObject;
  Button: Controls.TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  MyButton: CastleKeysMouse.TMouseButton;
begin
  if MouseButtonLCLToCastle(Button, MyButton) then
    DoMouseDown(Vector2Single(X, Height - 1 - Y), MyButton, 0);
end;

procedure TCastleWindowCustom.OpenGLControlMouseUp(Sender: TObject;
  Button: Controls.TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  MyButton: CastleKeysMouse.TMouseButton;
begin
  if MouseButtonLCLToCastle(Button, MyButton) then
    DoMouseUp(Vector2Single(X, Height - 1 - Y), MyButton, 0);
end;

{ Since LCL event loop may become clogged when dragging with mouse
  (like when using mouse look), force doing update and (if needed) redraw
  from time to time.
  See TCastleControl implementation for analogous AggressiveUpdate
  procedure with detailed discussion about why this is needed. }
procedure TCastleWindowCustom.AggressiveUpdate;
var
  DesiredFPS: Single;
begin
  if Application.LimitFPS <= 0 then
    DesiredFPS := MaxDesiredFPS else
    DesiredFPS := Min(MaxDesiredFPS, Application.LimitFPS);
  if Timer - Fps.UpdateStartTime > TimerFrequency / DesiredFPS then
  begin
    DoUpdate;

    { TODO:
      - TCastleApplication.OnIdle is not taken care of here.
        This takes care of calling OnUpdate for this window.
        Other windows (in case you have multiple TCastleWindow instances)
        will take care of themselves too, they all have separate Fps counter.
        But TCastleApplication.OnIdle is left not called.
      - OnTimer (both from Application and TCastleWindow)
        is not taken care of here.
    }

    if Invalidated then DoRender;
  end;
end;

procedure TCastleWindowCustom.Invalidate;
begin
  if not Closed then
    OpenGLControl.Invalidate;
end;

procedure TCastleWindowCustom.OpenGLControlMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
  DoMotion(InputMotion(MousePosition, Vector2Single(X, Height - 1 - Y),
    MousePressed, 0));
  AggressiveUpdate;
end;

procedure TCastleWindowCustom.OpenGLControlMouseWheel(Sender: TObject;
  Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint;
  var Handled: Boolean);
begin
  DoMouseWheel(WheelDelta/120, true);
end;

{ TCastleWindowCustom dialogs ---------------------------------------------------------- }

function TCastleWindowCustom.BackendFileDialog(const Title: string; var FileName: string;
  OpenDialog: boolean; FileFilters: TFileFilterList): boolean;
var
  Dialog: TFileDialog;
  ExpandedFileName: string;
begin
  if OpenDialog then
    Dialog := TOpenDialog.Create(nil) else
    Dialog := TSaveDialog.Create(nil);
  try
    Dialog.Title := Title;
    if FileName = '' then
      Dialog.InitialDir := SysToUTF8(GetCurrentDir) else
    begin
      ExpandedFileName := ExpandFileName(FileName);
      Dialog.InitialDir := SysToUTF8(ExtractFilePath(ExpandedFileName));
      Dialog.FileName := SysToUTF8(ExtractFileName(ExpandedFileName));
    end;
    FileFiltersToDialog(FileFilters, Dialog);
    ReleaseAllKeysAndMouse; // do it manually
    Result := Dialog.Execute;
    if Result then
      FileName := UTF8ToSys(Dialog.FileName);
  finally FreeAndNil(Dialog) end;
end;

function TCastleWindowCustom.ColorDialog(var Color: TVector3Single): boolean;
var
  Dialog: TColorDialog;
  ColorByte: TVector3Byte;
begin
  Dialog := TColorDialog.Create(nil);
  try
    ColorByte := Vector3Byte(Color);
    Dialog.Color := RGBToColor(ColorByte[0], ColorByte[1], ColorByte[2]);
    ReleaseAllKeysAndMouse; // do it manually
    Result := Dialog.Execute;
    if Result then
    begin
      RedGreenBlue(Dialog.Color, ColorByte[0], ColorByte[1], ColorByte[2]);
      Color := Vector3Single(ColorByte);
    end;
  finally FreeAndNil(Dialog) end;
end;

procedure TCastleWindowCustom.MessageOK(const S: string; const MessageType: TWindowMessageType);
const
  MessageTypeCastleToLCL: array [TWindowMessageType] of TMsgDlgType =
  (Dialogs.mtInformation, Dialogs.mtWarning, Dialogs.mtConfirmation, Dialogs.mtError, Dialogs.mtCustom);
begin
  ReleaseAllKeysAndMouse; // do it manually
  MessageDlg(S, MessageTypeCastleToLCL[MessageType], [mbOK], 0);
end;

function TCastleWindowCustom.MessageYesNo(const S: string;
  const MessageType: TWindowMessageType): boolean;
begin
  ReleaseAllKeysAndMouse; // do it manually
  Result := MessageDlg(S, mtConfirmation, mbYesNo, 0) = mrYes;
end;

procedure TCastleWindowCustom.FormDropFiles(Sender: TObject; const FileNames: array of string);
begin
  DoDropFiles(FileNames);
end;

{ TCastleApplication ---------------------------------------------------------- }

procedure TCastleApplication.CreateBackend;
begin
  { Do not install LCL handler for ExceptProc, we want to use our own handler
    in CastleUtils. }
  Forms.Application.CaptureExceptions := false;

  Forms.Application.Initialize;
  Forms.Application.AddOnIdleHandler(@ApplicationIdle);

  {$ifdef LCLCarbon}
  FTimer := TCustomTimer.Create(Self);
  FTimer.Interval := Round(1000 / MaxDesiredFPS);
  FTimer.OnTimer := @ApplicationTimer;
  FTimer.Enabled := true;
  {$endif LCLCarbon}
end;

procedure TCastleApplication.DestroyBackend;
begin
  Forms.Application.RemoveOnIdleHandler(@ApplicationIdle);
  {$ifdef LCLCarbon}
  FreeAndNil(FTimer);
  {$endif LCLCarbon}
end;

{$ifdef LCLCarbon}
{ Only for LCL Carbon: Using LCL timer (that is translated to Carbon timer)
  is the only way to receive continous messages in some cases.

  Otherwise such bugs can be observed (only on LCL-Carbon, not on LCL-GTK2):

  - When trying to Walk using mouse dragging in view3dscene, it doesn't
    work smoothly: when you simply keep some mouse button pressed,
    but don't move the mouse anymore (which should result in constant
    movement forward/backward if you did it after dragging up/down),
    then we don't get any events (so no movement, no redraw...).

  - Using view3dscene Navigation->Jump to viewpoint... doesn't work
    smoothly, there is a visible delay when we don't receive messages
    right after menu click, and so transtion is visible with some delay.
}
procedure TCastleApplication.ApplicationTimer(Sender: TObject);
var
  I: Integer;
begin
  for I := 0 to OpenWindowsCount - 1 do
    OpenWindows[I].AggressiveUpdate;
end;
{$endif LCLCarbon}

procedure TCastleApplication.ApplicationIdle(Sender: TObject; var Done: Boolean);
begin
  { Call Update and timer events of Application and all windows.
    Update events are handled by DoSelfUpdate and OpenWindows.DoUpdate.
    Timer events are handled by MaybeDoTimer, that in turn will call
    (when needed) DoSelfTimer and OpenWindows.DoTimer. }
  DoSelfUpdate;
  FOpenWindows.DoUpdate;
  MaybeDoTimer(LastDoTimerTime);

  { We need Done := false, otherwise the widgetset will hang waiting
    for next message. See ../components/castlecontrol.pas comments.

    Done := false also prevents other application idle handlers,
    but fortunately in this case we're the only thing interfacing with LCL,
    so that's not a problem. }
  Done := false;
end;

function TCastleApplication.ProcessMessage(WaitForMessage, WaitToLimitFPS: boolean): boolean;
var
  I: Integer;
begin
  if Forms.Application.Terminated then Exit(false);

  { TODO: take WaitToLimitFPS into account }

  if WaitForMessage then
  begin
    { HandleMessage will call ApplicationIdle, so no need for AggressiveUpdate
      hack in this case. }
    Forms.Application.HandleMessage;
    Result := not Forms.Application.Terminated;
  end else
  begin
    Forms.Application.ProcessMessages;
    Result := not Forms.Application.Terminated;

    { Without this, OnUpdate will not be called when application calls
      TCastleApplication.ProcessMessage in a loop, because LCL will not make
      ApplicationIdle calls from Forms.Application.ProcessMessages.

      Bugs observed when the below workaround is not used (on both LCL-Carbon and LCL-GTK2):
      - Arrow keys up/down do not work in CastleMessages window.
        E.g. view3dscene "OpenGL info".
        That's becaue UpdateMessg is never called.
        (Although this is now fixed anyway by above HandleMessage usage.)
      - Progress is not rendered smoothly.
        E.g. in fps_game, define -dTESTING_PROGRESS_DELAY, and notice that progress
        is not smoothly updated (if you don't move the mouse, since MouseMove
        already causes AggressiveUpdate).
    }
    if Result then
    begin
      for I := 0 to OpenWindowsCount - 1 do
        OpenWindows[I].AggressiveUpdate;
    end;
  end;
end;

function TCastleApplication.ProcessAllMessages: boolean;
begin
//  Result := not Forms.Application.Terminated;
//  while Result do
    Result := ProcessMessage(false, false);
end;

procedure TCastleApplication.Run;
begin
  if OpenWindowsCount = 0 then Exit;

  { Implementing Run by calling ProcessMessage in a loop (like below)
    is a valid and good implementation. Make sure your ProcessMessage
    honours WaitForMessage and WaitToLimitFPS = true,
    to avoid wasting CPU on "busy waiting". }
  // while ProcessMessage(true, true) do ;

  { We have to call here Forms.Application.Run, not just call our
    ProcessMessage (which makes Forms.Application.ProcessMessage) in a loop.
    That is because on some LCL widgetsets, you really need to run
    Forms.Application.Run, see e.g. Carbon that does special stuff inside
    TCarbonWidgetSet.AppRun inside lcl/interfaces/carbon/carbonobject.inc.
    Without this, global menu on Carbon is always blocked.

    TODO: that's unfortunate, as our TCastleWindowCustom interface
    promises that it's not necessary to call Run, it should be always
    equivalent to call just ProcessMessage in a loop.

    TODO: this makes Update/timer broken, they need our
    TCastleApplication.ProcessMessage to work. }

  Forms.Application.Run;
end;

procedure TCastleApplication.QuitWhenNoOpenWindows;
begin
  Forms.Application.Terminate; // break also Forms.Application.Run
end;

function TCastleApplication.ScreenWidth: integer;
begin
  Result := Screen.Width;
end;

function TCastleApplication.ScreenHeight: integer;
begin
  Result := Screen.Height;
end;

function TCastleApplication.BackendName: string;
begin
  Result := 'LCL';
end;

{ TCastleClipboard ----------------------------------------------------------- }

function TCastleClipboard.GetAsText: string;
begin
  Result := UTF8ToSys(Clipbrd.Clipboard.AsText);
end;

procedure TCastleClipboard.SetAsText(const Value: string);
begin
  Clipbrd.Clipboard.AsText := SysToUTF8(Value);
end;

{ TCastleWindow -------------------------------------------------------------- }

procedure TCastleWindow.NavigationInfoChanged;
begin
end;

{$endif read_implementation}