Debian Codegraph @

src/window/castlewindowmenu.inc

raw
1 {%MainUnit castlewindow.pas}
2 {
3 Copyright 2004-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 menu bar. }
18
19 {$ifdef read_interface}
20 TMenu = class;
21
22 { A basic class representing basic menu building block.
23 This can be a separator, clickable menu item or something that
24 expands to submenu. }
25 TMenuEntry = class
26 private
27 { if CorrectParentWindow <> nil call CorrectParentWindow.Menu*. }
28 procedure MenuInitialize;
29 procedure MenuFinalize;
30 private
31 { Stuff internal for proper communication between menu and
32 TCastleWindow implementation. }
33
34 { ParentWindow to call MenuFinalize, MenuInitialize.
35
36 Used only on root menu item
37 (the one with ParentMenu = @nil). From TMenuEntry implementations,
38 you should use CorrectParentWindow, that looks for it recursively.
39 This way we only have to update it on SetMainMenu (no need to keep
40 it recursively updated in all TMenuEntry instances). }
41 ParentWindow: TCastleWindow;
42
43 { Internal handle of this menu item within CastleWindow backend.
44 This is used by CastleWindow backend implementation, to store the
45 internal resource corresponding to this menu entry.
46 The exact interpretation depends on CastleWindow backend,
47 and should not be messed with. }
48 Handle: Pointer;
49
50 FParentMenu: TMenu;
51 FParentMenuPosition: Cardinal;
52
53 function CorrectParentWindow: TCastleWindow;
54 protected
55 { Recursively clear TMenuEntry.Handle values. }
56 procedure ClearHandles; virtual;
57 public
58 { For optimization purposes, you may surround many menu changes
59 inside MenuUpdateBegin + MenuUpdateEnd calls.
60 Make sure window is not closed / opened between them.
61 @groupBegin }
62 procedure MenuUpdateBegin;
63 procedure MenuUpdateEnd;
64 { @groupEnd }
65
66 { This is the parent TMenu that has this item in it's Entries list.
67 @nil is there is not parent menu yet (e.g. because it's not assigned
68 yet, or because this is the main menu). }
69 property ParentMenu: TMenu read FParentMenu;
70
71 { Position on ParentMenu. Indexed from 0, so
72 ParentMenu.Entries[ParentMenuPosition] should be always equal to Self
73 (as long as ParentMenu <> @nil. }
74 property ParentMenuPosition: Cardinal read FParentMenuPosition;
75 end;
76
77 TMenuEntryList = {$ifdef FPC}specialize{$endif} TObjectList<TMenuEntry>;
78
79 TMenuEntryWithCaption = class(TMenuEntry)
80 private
81 FCaption: String;
82 procedure SetCaption(const Value: String);
83 private
84 FEnabled: boolean;
85 procedure SetEnabled(Value: boolean);
86 public
87 constructor Create(const ACaption: String);
88
89 { Caption of this menu entry. Will be shown to user.
90
91 To indicate that some letter of a caption is a mnemonic
92 for this menu item put '_' (underscore) char before this
93 letter. Depending on CastleWindow-backend-dependent,
94 mnemonics should allow user to easier activate this menu item
95 with keyboard (e.g. Alt+mnemonic to dropdown item in MainMenu).
96
97 You can put two consecutive underscore chars in Caption to
98 indicate that here Caption should display literally one underscore
99 character.
100
101 (Convention to mark mnemonics with '_' is just copied from gtk,
102 from gtk_label_new_with_mnemonic. So no, I didn't invent
103 another new convention here.)
104
105 It is undefined what will happen if you put underscore chars
106 before *two* or more letters in Caption.
107 I.e. you can't define multiple mnemonics for one menu item.
108 I.e. this will not crash your program,
109 but results may be CastleWindow-backend-dependent.
110
111 Just like in GTK toolkit gtk_label_new_with_mnemonic and
112 gtk_menu_item_new_with_mnemonic. }
113 property Caption: String read FCaption write SetCaption;
114
115 property Enabled: boolean read FEnabled write SetEnabled
116 default true;
117 end;
118
119 TMenuItemRadioGroup = class;
120
121 { TMenuEntry that contains a list of menu entries.
122 This is the basic class to represent a drop-down menu, a submenu etc. }
123 TMenu = class(TMenuEntryWithCaption)
124 private
125 FEntries: TMenuEntryList;
126 function GetEntries(Index: Integer): TMenuEntry;
127 protected
128 procedure ClearHandles; override;
129 public
130 constructor Create(const ACaption: String);
131 destructor Destroy; override;
132
133 { Items (entries) on the menu. Items are owned by this menu instance
134 (are automatically freed at destruction, at @link(Delete) and such). }
135 property Entries [Index: Integer]: TMenuEntry read GetEntries; default;
136 function Count: Integer;
137 procedure Insert(Index: Integer; Value: TMenuEntry);
138 { Add at the end. Same as Insert(@link(Count), Value). }
139 procedure Append(Value: TMenuEntry);
140 procedure Delete(Index: Integer);
141 procedure Clear;
142
143 { @deprecated Deprecated name for @link(Count). }
144 function EntriesCount: Integer; deprecated;
145 { @deprecated Deprecated name for @link(Delete). }
146 procedure EntryDelete(Index: Integer); deprecated;
147 { @deprecated Deprecated name for @link(Clear). }
148 procedure EntriesDeleteAll; deprecated;
149 { @deprecated Deprecated name for @link(Clear). }
150 procedure DeleteAll;
151
152 { Append a number of radio menu items.
153 This is a comfortable shortcut for an often task of adding
154 many TMenuItemRadio items that create a new radio group
155 (TMenuItemRadioGroup).
156
157 For each item of Items list, we'll add a new TMenuItemRadio instance.
158
159 @unorderedList(
160 @item(TMenuItemRadio.Caption will be set to the Items[I]
161 string. Additionally it will be quoted by SQuoteMenuEntryCaption
162 to avoid interpreting underscore characters (if QuoteCaption).)
163
164 @item(TMenuItemRadio.IntData will be set to BaseIntData + the number
165 of this item. (This is usually most comfortable,
166 you can handle this radio group by "case" with a range.))
167
168 @item(TMenuItemRadio.Group will be equal. More precisely:
169 along with creating the first TMenuItemRadio, we will also
170 create new TMenuItemRadioGroup. For the rest of TMenuItemRadio,
171 we'll assign this group.)
172
173 @item(TMenuItemRadio.Checked will be set to @true on only
174 one item: the one numbered SelectedIndex.
175 Pass SelectedIndex negative (or >= than items count)
176 to have no radio item checked by default.)
177
178 @item(TMenuItemRadio.AutoCheckedToggle will be set according
179 to ou parameter AAutoCheckedToggle.)
180 )
181
182 We return the newly created TMenuItemRadioGroup.
183 If Items is empty, this does nothing and returns @nil.
184 }
185 function AppendRadioGroup(const Items: array of string;
186 BaseIntData: Cardinal; SelectedIndex: Integer;
187 AAutoCheckedToggle: boolean; QuoteCaption: boolean = true): TMenuItemRadioGroup;
188 end;
189
190 { TMenuEntry that is a simple, clickable menu item.
191 User expects that something will happend when he clicks on TMenuItem.
192 You can also specify key shortcuts for this menu item. }
193 TMenuItem = class(TMenuEntryWithCaption)
194 private
195 FIntData: Integer;
196 FSmallId: Integer;
197
198 FKeyString: String;
199 FKey: TKey;
200 FModifiers: TModifierKeys;
201
202 function GetCharKey: Char;
203 procedure SetCharKey(const AValue: Char);
204 public
205 { An integer value, for any purpose you want. Useful to identify this item in
206 TCastleWindow.OnMenuClick callback. }
207 property IntData: Integer read FIntData write FIntData;
208
209 { Unique small identifier of this menu item.
210 This is initialized at creation of this object, to be unique among
211 all currently existing (created and not destroyed) TMenuItem instances.
212
213 The intention is that this SmallId should be the smallest possible value >= 0.
214 So it's not something like PtrUInt(Self).
215 This may be useful when you're constructing a menu
216 using some API --- you usually want to identify
217 your menu item by some unique id and you want this id to be small
218 (e.g. under WinAPI menu item's id must fit in 16 bit integer).
219
220 @seealso MenuItemFromSmallId }
221 property SmallId: Integer read FSmallId;
222
223 { Called when this menu item will be choosen by user (by clicking,
224 or pressing the matching key shortcut).
225
226 You can override this and return true if you handled the event.
227 If this will return false, CastleWindow will call EventMenuClick
228 (OnMenuClick).
229
230 When entering this method, current OpenGL context is set to
231 the context of the window that the clicked menu belongs to.
232
233 Default implementation of this method in this class always returns false. }
234 function DoClick: boolean; virtual;
235
236 { Key shortcut for this menu item.
237
238 When user presses indicated Key (if it's not keyNone)
239 or KeyString (if it's not '') then DoClick will be called
240 (which results in TCastleWindow.EventMenuClick,
241 and TCastleWindow.OnMenuClick,
242 if DoClick returns false).
243
244 Handling of menu key shortcuts is completely within the CastleWindow
245 (usually, it's even done by the underlying backend like GTK or WinAPI).
246 You will not get EventPress (OnPress) messages for keypresses that translate
247 to menu clicks. Although TCastleWindow.Pressed.Keys will be
248 still appropriately updated.
249
250 Note that Caption of this object should not contain
251 description of Key or KeyString. The backend will automatically show the
252 key description in an appropriate way.
253
254 You should use at most one of these properties, not both.
255 So either use Key or KeyString, and leave the other one at default
256 value (Key = keyNone, KeyString = '').
257
258 The KeyString values within range CtrlA..CtrlZ mean
259 that user must press the given letter with Ctrl modfier. This rule
260 includes some special chars like
261 @unorderedList(
262 @item KeyString = #8 (equal to CharBackSpace, also equal to CtrlH) or
263 @item KeyString = #9 (equal to CharTab, also equal to CtrlI) or
264 @item KeyString = #13 (equal to CharEnter, also equal to CtrlM).
265 )
266 The KeyString values above do @bold(not) mean the backspace or tab or enter
267 keys, they mean the combination of Ctrl key + respective letter.
268 If you want to have backspace/tab/enter keys to activate the menu item,
269 use Key = keyBackSpace, Key = keyTab or Key = keyEnter.
270
271 TODO: for now, this must be assigned before adding this menu item
272 to parent (actually, before the parent menu is added to window MainMenu)
273 to work reliably. Don't change this property afterwards.
274 Usually, you will set this property by an argument to the constructor.
275
276 @groupBegin }
277 property KeyString: String read FKeyString write FKeyString;
278 property Key: TKey read FKey write FKey default keyNone;
279 { @groupEnd }
280
281 {$ifdef FPC}
282 property CharKey: Char read GetCharKey write SetCharKey;
283 deprecated 'use KeyString';
284 {$endif}
285
286 { Modifiers (shift, ctrl and such) required to activate this menu item.
287 These have to be pressed along with @link(Key) or @link(KeyString).
288
289 Note that KeyString may already indicate some modifiers,
290 if it's one of the CtrlA ... CtrlZ then the Ctrl key is required
291 and if it's an uppercase letter then the Shift key is required.
292 There's no need to include this modifier in this property then.
293
294 TODO: for now, this must be assigned before adding this menu item
295 to parent (actually, before the parent menu is added to window MainMenu)
296 to work reliably. Don't change this property afterwards. }
297 property Modifiers: TModifierKeys read FModifiers write FModifiers;
298
299 { Returns as S the string that describes key shortcut
300 (@link(KeyString), @link(Key), @link(Modifiers)) and then returns true.
301 If KeyString = '' and Key = keyNone then returns false and
302 S is undefined. }
303 function KeyToString(out S: string): boolean;
304
305 function KeyMatches(const AKey: TKey; const AKeyString: String;
306 const AModifiers: TModifierKeys): boolean;
307
308 { Caption with optional key description (returned by KeyString)
309 appended. }
310 function CaptionWithKey: string;
311
312 constructor Create(const ACaption: String; AIntData: Integer); overload;
313 constructor Create(const ACaption: String; AIntData: Integer; AKeyString: String); overload;
314 constructor Create(const ACaption: String; AIntData: Integer; AKey: TKey); overload;
315
316 destructor Destroy; override;
317 end;
318
319 { TMenuEntry that acts as a visual separator (horizontal line
320 or something like that) between menu items. This is not clickable
321 by the user. Separators may be sometimes ignored in toplevel menus
322 (e.g. WinAPI does not allow separator in toplevel menu bar). }
323 TMenuSeparator = class(TMenuEntry)
324 end;
325
326 { TMenuItem that should visualize Checked state somehow to the user. }
327 TMenuItemChecked = class(TMenuItem)
328 private
329 FChecked: boolean;
330 FAutoCheckedToggle: boolean;
331 protected
332 { Called when Checked property is assigned. }
333 procedure SetChecked(Value: boolean); virtual;
334
335 { Called from DoClick when AutoCheckedToggle is @true.
336 It's supposed to actually implement the AutoCheckedToggle behavior.
337
338 Note that this is overriden ina a "dirty" way
339 (i.e. not calling "inherited") in TMenuItemRadio descendant. }
340 procedure DoAutoCheckedToggle; virtual;
341 public
342 property Checked: boolean read FChecked write SetChecked;
343
344 { If @true then each time user chooses this menu item,
345 @link(Checked) is changed to @code(not Checked). }
346 property AutoCheckedToggle: boolean read FAutoCheckedToggle
347 write FAutoCheckedToggle;
348
349 { Overriden to handle AutoCheckedToggle. In this class,
350 DoClick still returns false (like in ancestor class). }
351 function DoClick: boolean; override;
352
353 constructor Create(const ACaption: String; AIntData: Integer;
354 AChecked, AAutoCheckedToggle: boolean); overload;
355 constructor Create(const ACaption: String; AIntData: Integer; const AKeyString: String;
356 AChecked, AAutoCheckedToggle: boolean); overload;
357 constructor Create(const ACaption: String; AIntData: Integer; AKey: TKey;
358 AChecked, AAutoCheckedToggle: boolean); overload;
359 end;
360
361 { Menu radio item. Similar to TMenuItemChecked, but it belongs to a group and
362 within this group only one (or none) radio button can be checked.
363
364 Note that AutoCheckedToggle property has a little different
365 meaning in this class: whenever user will click on some item,
366 it will be automatically set to Checked = @true and the rest
367 of items within this group will be set to Checked = @false.
368
369 You can of course operate on Checked property explicitly,
370 setting it to @true or @false. }
371 TMenuItemRadio = class(TMenuItemChecked)
372 private
373 FGroup: TMenuItemRadioGroup;
374 procedure SetGroup(Value: TMenuItemRadioGroup);
375 procedure CreateCommon;
376 protected
377 procedure SetChecked(Value: boolean); override;
378 procedure DoAutoCheckedToggle; override;
379 public
380 constructor Create(const ACaption: String; AIntData: Integer;
381 AChecked, AAutoCheckedToggle: boolean); overload;
382 constructor Create(const ACaption: String; AIntData: Integer; const AKeyString: String;
383 AChecked, AAutoCheckedToggle: boolean); overload;
384 constructor Create(const ACaption: String; AIntData: Integer; AKey: TKey;
385 AChecked, AAutoCheckedToggle: boolean); overload;
386
387 destructor Destroy; override;
388
389 { The list of radio items within this group. This is never @nil.
390
391 Assigning this property is equivalent to adding yourself to the
392 wanted group. I.e. @code(Item.Group := NewGroup;)
393 is equivalent to NewGroup.Add(Item). }
394 property Group: TMenuItemRadioGroup read FGroup write SetGroup;
395 end;
396
397 { A group of radio buttons.
398
399 An instance of this object is always
400 created and destroyed automatically by TMenuItemRadio objects.
401 All TMenuItemRadio within the same group share the same
402 TMenuItemRadioGroup instance.
403
404 Never modify anything within this group using general TObjectList
405 properties. Instead always use methods defined here.
406 TODO: This should not descend from TObjectList<TMenuItemRadio> then,
407 it should contain it privately. }
408 TMenuItemRadioGroup = class({$ifdef FPC}specialize{$endif} TObjectList<TMenuItemRadio>)
409 private
410 FSelected: TMenuItemRadio;
411 procedure SetSelected(Value: TMenuItemRadio);
412 { Index of @link(Selected) menu item. -1 if Selected is @nil. }
413 function SelectedIndex: Integer;
414 public
415 { Adds an existing radio menu item to this group.
416 After this, Item.Group will point to this group object.
417
418 Note that Item.Checked may be changed to @false if there
419 already is a selected item in this group. If the added
420 item already has Item.Checked = @false then for sure
421 it will not be changed (SelectedIndex can be left as -1). }
422 procedure Add(Item: TMenuItemRadio); reintroduce;
423
424 procedure Remove(Item: TMenuItemRadio);
425
426 { This is the only currently Checked item.
427
428 It can be nil if no item is checked currently
429 (this can happen if you added all initial items with
430 Checked = @false, or if you later removed the checked item from the
431 group; we need a state to represent this situation, that's why
432 it's allowed for radio group to have none radio item chosen). }
433 property Selected: TMenuItemRadio read FSelected write SetSelected;
434
435 { Return previous (from @link(Selected)) menu item in this group.
436
437 If there's no previous item:
438
439 @unorderedList(
440 @item(When Cycle = @true, return the last item.)
441 @item(When Cycle = @false and there is no previous item,
442 but still @link(Selected) <> nil, return @link(Selected).)
443 )
444
445 Only when there's no @link(Selected) item, returns @false. }
446 function Previous(out Item: TMenuItemRadio; const Cycle: Boolean = false): Boolean;
447
448 { Return next (from @link(Selected)) menu item in this group.
449
450 If there's no next item:
451
452 @unorderedList(
453 @item(When Cycle = @true, return the first item.)
454 @item(When Cycle = @false and there is no next item,
455 but still @link(Selected) <> nil, return @link(Selected).)
456 )
457
458 Only when there's no @link(Selected) item, returns @false. }
459 function Next(out Item: TMenuItemRadio; const Cycle: Boolean = false): Boolean;
460
461 (* procedure DebugWriteln; *)
462 end;
463
464 { Menu item that toggles TCastleWindow.FullScreen.
465
466 This already has a nice caption, key shortcut (F11 on most platforms,
467 except macOS where it's Command+F11 (on LCL backend) or Ctrl+F11
468 (on other backends), since the bare F11 is reserved on macOS).
469 And it has a DoClick implementation that takes care of the actual job.
470
471 So you can just add it to your menu, and forget about it. }
472 TMenuItemToggleFullScreen = class(TMenuItemChecked)
473 constructor Create(const InitialFullScreen: boolean);
474 function DoClick: boolean; override;
475 end;
476
477 {$endif read_interface}
478
479 {$ifdef read_interface_2}
480
481 { Search for menu item with given SmallId.
482 SearchSmallId must be a SmallId of some existing (i.e. created and not
483 destroyed yet) TMenuItem. This function returns this TMenuItem. }
484 function MenuItemFromSmallId(SearchSmallId: Integer): TMenuItem;
485
486 { Returns S with each '__' replaced with single '_',
487 any other '_' removed.
488
489 In other words: with mnemonics (as defined by
490 @link(TMenuEntryWithCaption.Caption) removed. }
491 function SRemoveMnemonics(const S: string): string;
492
493 { Returns S with each underscore '_' replaced by two underscores, '__'.
494
495 In other words: S will not contain any mnemonics.
496 If you will assign S to @link(TMenuEntryWithCaption.Caption),
497 then this menu entry caption will display exactly S,
498 without any mnemonics. Single '_' in S will be displayed exactly
499 as single '_'. }
500 function SQuoteMenuEntryCaption(const S: string): string;
501
502 {$endif read_interface_2}
503
504 {$ifdef read_implementation}
505
506 { Implementation of these classes is NOT dependent on CastleWindow
507 implementation (i.e. it's not GTK or WinAPI specific).
508 That was the original idea of this unit. Once these classes
509 were even declared in a separate unit (that was not dependent on CastleWindow
510 unit).
511
512 Such separation makes implementation of these things simple --
513 it's not cluttered with GTK/WinAPI specific details.
514 }
515
516 { MenuItems global list ------------------------------------------------------------ }
517
518 var
519 { This list contains only TMenuItem objects (and some nils).
520 Position on this list is object's SmallId.
521 The current implementation of SmallId in this unit is a resource-eater
522 (MenuItems only grows !), it can be optimized in many ways.
523 But I don't do it because I don't need
524 it for now -- all my programs use a limited set of menu items, and usually
525 free those menu items right before exiting. So there's no need to optimize
526 this for them. }
527 FMenuItems: TMenuEntryList;
528
529 function MenuItems: TMenuEntryList;
530 begin
531 if (FMenuItems = nil) and not UnitFinalization then
532 FMenuItems := TMenuEntryList.Create(false);
533 Result := FMenuItems;
534 end;
535
536 { TMenuEntry ------------------------------------------------------------ }
537
538 function TMenuEntry.CorrectParentWindow: TCastleWindow;
539 begin
540 if ParentMenu = nil then
541 Result := ParentWindow else
542 Result := ParentMenu.CorrectParentWindow;
543 end;
544
545 procedure TMenuEntry.MenuInitialize;
546 var
547 P: TCastleWindow;
548 begin
549 P := CorrectParentWindow;
550 if P <> nil then P.MenuInitialize;
551 end;
552
553 procedure TMenuEntry.MenuFinalize;
554 var
555 P: TCastleWindow;
556 begin
557 P := CorrectParentWindow;
558 if P <> nil then P.MenuFinalize;
559 end;
560
561 procedure TMenuEntry.MenuUpdateBegin;
562 var
563 P: TCastleWindow;
564 begin
565 P := CorrectParentWindow;
566 if P <> nil then P.MenuUpdateBegin;
567 end;
568
569 procedure TMenuEntry.MenuUpdateEnd;
570 var
571 P: TCastleWindow;
572 begin
573 P := CorrectParentWindow;
574 if P <> nil then P.MenuUpdateEnd;
575 end;
576
577 procedure TMenuEntry.ClearHandles;
578 begin
579 Handle := nil;
580 end;
581
582 { TMenuEntryWithCaption ---------------------------------------- }
583
584 constructor TMenuEntryWithCaption.Create(const ACaption: String);
585 begin
586 inherited Create;
587 FCaption := ACaption;
588 FEnabled := true;
589 end;
590
591 procedure TMenuEntryWithCaption.SetCaption(const Value: String);
592 var
593 P: TCastleWindow;
594 begin
595 FCaption := Value;
596
597 P := CorrectParentWindow;
598 if (P <> nil) and (not P.Closed) then P.MenuUpdateCaption(Self);
599 end;
600
601 procedure TMenuEntryWithCaption.SetEnabled(Value: boolean);
602 var
603 P: TCastleWindow;
604 begin
605 if FEnabled <> Value then
606 begin
607 FEnabled := Value;
608
609 P := CorrectParentWindow;
610 if (P <> nil) and (not P.Closed) then P.MenuUpdateEnabled(Self);
611 end;
612 end;
613
614 { TMenu ------------------------------------------------------------ }
615
616 constructor TMenu.Create(const ACaption: String);
617 begin
618 inherited Create(ACaption);
619 FEntries := TMenuEntryList.Create(true);
620 end;
621
622 destructor TMenu.Destroy;
623 begin
624 FreeAndNil(FEntries);
625 inherited;
626 end;
627
628 function TMenu.GetEntries(Index: Integer): TMenuEntry;
629 begin
630 Result := FEntries[Index];
631 end;
632
633 function TMenu.EntriesCount: Integer;
634 begin
635 Result := Count;
636 end;
637
638 function TMenu.Count: Integer;
639 begin
640 Result := FEntries.Count;
641 end;
642
643 procedure TMenu.Insert(Index: Integer; Value: TMenuEntry);
644 var
645 I: Integer;
646 P: TCastleWindow;
647 begin
648 FEntries.Insert(Index, Value);
649
650 { update Value.FParentMenu }
651 Value.FParentMenu := Self;
652
653 { update changed FParentMenuPosition values (this includes
654 Value.FParentMenuPosition) }
655 for I := Index to Count - 1 do
656 FEntries[I].FParentMenuPosition := I;
657
658 P := CorrectParentWindow;
659 if (P <> nil) and (not P.Closed) then P.MenuInsert(Self, Index, Value);
660 end;
661
662 procedure TMenu.Append(Value: TMenuEntry);
663 begin
664 Insert(FEntries.Count, Value);
665 end;
666
667 procedure TMenu.EntryDelete(Index: Integer);
668 begin
669 Delete(Index);
670 end;
671
672 procedure TMenu.Delete(Index: Integer);
673 var
674 I: Integer;
675 Entry: TMenuEntry;
676 P: TCastleWindow;
677 begin
678 {$ifdef FPC}
679 Entry := FEntries.ExtractIndex(Index);
680 {$else}
681 Entry := FEntries.Extract(FEntries[Index]);
682 {$endif}
683
684 { update changed FParentMenuPosition values }
685 for I := Index to Count - 1 do
686 FEntries[I].FParentMenuPosition := I;
687
688 P := CorrectParentWindow;
689 if (P <> nil) and (not P.Closed) then P.MenuDelete(Self, Index, Entry);
690
691 FreeAndNil(Entry);
692 end;
693
694 procedure TMenu.EntriesDeleteAll;
695 begin
696 Clear;
697 end;
698
699 procedure TMenu.DeleteAll;
700 begin
701 Clear;
702 end;
703
704 procedure TMenu.Clear;
705 var
706 I: Integer;
707 begin
708 MenuUpdateBegin;
709 for I := Count - 1 downto 0 do
710 Delete(I);
711 MenuUpdateEnd;
712 end;
713
714 function TMenu.AppendRadioGroup(const Items: array of string;
715 BaseIntData: Cardinal; SelectedIndex: Integer;
716 AAutoCheckedToggle: boolean; QuoteCaption: boolean): TMenuItemRadioGroup;
717 var
718 Radio: TMenuItemRadio;
719 I: Integer;
720 S: string;
721 begin
722 Result := nil;
723 for I := 0 to High(Items) do
724 begin
725 S := Items[I];
726 if QuoteCaption then
727 S := SQuoteMenuEntryCaption(S);
728 Radio := TMenuItemRadio.Create(S,
729 Cardinal(I) + BaseIntData, I = SelectedIndex, AAutoCheckedToggle);
730 if Result = nil then
731 Result := Radio.Group else
732 Radio.Group := Result;
733 Append(Radio);
734 end;
735 end;
736
737 procedure TMenu.ClearHandles;
738 var
739 I: Integer;
740 begin
741 inherited;
742 for I := 0 to Count - 1 do
743 Entries[I].ClearHandles;
744 end;
745
746 { TMenuItem ------------------------------------------------------------ }
747
748 function TMenuItem.GetCharKey: Char;
749 begin
750 if Length(KeyString) = 1 then
751 Result := KeyString[1]
752 else
753 Result := #0;
754 end;
755
756 procedure TMenuItem.SetCharKey(const AValue: Char);
757 begin
758 if AValue = #0 then
759 KeyString := ''
760 else
761 KeyString := AValue;
762 end;
763
764 function TMenuItem.DoClick: boolean;
765 begin
766 Result := false;
767 end;
768
769 function TMenuItem.KeyToString(out S: string): boolean;
770 begin
771 Result := CastleWindow.KeyToString(KeyString, Key, Modifiers, S);
772 end;
773
774 function TMenuItem.KeyMatches(const AKey: TKey; const AKeyString: String;
775 const AModifiers: TModifierKeys): boolean;
776 begin
777 { AModifiers (currently pressed) must be a superset of required Modifiers. }
778 if not (AModifiers >= Modifiers) then
779 Exit(false);
780
781 { For CtrlH (= CharBackspace), *do not* match backspace key. }
782 if (Key = keyNone) and (KeyString = CharBackSpace) then
783 Result := (AKeyString = CharBackSpace) and not (AKey = keyBackSpace) else
784
785 if (Key = keyNone) and (KeyString = CharEnter) then
786 Result := (AKeyString = CharEnter) and not (AKey = keyEnter) else
787
788 if (Key = keyNone) and (KeyString = CharTab) then
789 Result := (AKeyString = CharTab) and not (AKey = keyTab) else
790
791 Result :=
792 ( (AKey <> keyNone) and (Key = AKey) ) or
793 ( (AKeyString <> '') and (KeyString = AKeyString) );
794 end;
795
796 function TMenuItem.CaptionWithKey: string;
797 var KeyStr: string;
798 begin
799 Result := Caption;
800 if KeyToString(KeyStr) then
801 Result := Result + ' [' + KeyStr + ']';
802 end;
803
804 constructor TMenuItem.Create(const ACaption: String; AIntData: Integer);
805 begin
806 inherited Create(ACaption);
807 FIntData := AIntData;
808
809 FSmallId := MenuItems.Count;
810 MenuItems.Add(Self);
811 end;
812
813 constructor TMenuItem.Create(const ACaption: String; AIntData: Integer;
814 AKeyString: String);
815 begin
816 // only for backward compatibility (when this parameter was Char) convert #0 to ''
817 if AKeyString = #0 then
818 AKeyString := '';
819
820 Create(ACaption, AIntData);
821 FKeyString := AKeyString;
822 end;
823
824 constructor TMenuItem.Create(const ACaption: String; AIntData: Integer;
825 AKey: TKey);
826 begin
827 Create(ACaption, AIntData);
828 FKey := AKey;
829 end;
830
831 destructor TMenuItem.Destroy;
832 begin
833 { We must set MenuItems[SmallId] so that MenuItemFromSmallId
834 will never try to dereference a non-existing object.
835 Note that we can't simply delete SmallId item from MenuItems
836 because that would shift all following objects (and made their SmallId
837 not corresponging to their index on MenuItems). }
838 MenuItems[SmallId] := nil;
839 inherited;
840 end;
841
842 function MenuItemFromSmallId(SearchSmallId: Integer): TMenuItem;
843 var MenuItem: TMenuItem;
844 i: Integer;
845 begin
846 for i := 0 to MenuItems.Count-1 do
847 begin
848 MenuItem := TMenuItem(MenuItems[i]);
849 if (MenuItem <> nil) and (MenuItem.SmallId = SearchSmallId) then
850 Exit(MenuItem);
851 end;
852
853 raise EInternalError.CreateFmt(
854 'MenuItemFromSmallId: SearchSmallId %d not found', [SearchSmallId]);
855 end;
856
857 { TMenuItemChecked ------------------------------------------------------------ }
858
859 procedure TMenuItemChecked.DoAutoCheckedToggle;
860 begin
861 Checked := not Checked;
862 end;
863
864 function TMenuItemChecked.DoClick: boolean;
865 begin
866 if inherited DoClick then Exit(true);
867
868 if AutoCheckedToggle then
869 DoAutoCheckedToggle;
870
871 Result := false;
872 end;
873
874 procedure TMenuItemChecked.SetChecked(Value: boolean);
875 var
876 P: TCastleWindow;
877 begin
878 if Value <> Checked then
879 begin
880 FChecked := Value;
881
882 P := CorrectParentWindow;
883 if (P <> nil) and (not P.Closed) then P.MenuUpdateChecked(Self);
884 end;
885 end;
886
887 constructor TMenuItemChecked.Create(const ACaption: String; AIntData: Integer;
888 AChecked, AAutoCheckedToggle: boolean);
889 begin
890 inherited Create(ACaption, AIntData);
891 FChecked := AChecked;
892 FAutoCheckedToggle := AAutoCheckedToggle;
893 end;
894
895 constructor TMenuItemChecked.Create(const ACaption: String; AIntData: Integer;
896 const AKeyString: String;
897 AChecked, AAutoCheckedToggle: boolean);
898 begin
899 inherited Create(ACaption, AIntData, AKeyString);
900 FChecked := AChecked;
901 FAutoCheckedToggle := AAutoCheckedToggle;
902 end;
903
904 constructor TMenuItemChecked.Create(const ACaption: String; AIntData: Integer;
905 AKey: TKey;
906 AChecked, AAutoCheckedToggle: boolean);
907 begin
908 inherited Create(ACaption, AIntData, AKey);
909 FChecked := AChecked;
910 FAutoCheckedToggle := AAutoCheckedToggle;
911 end;
912
913 { TMenuItemRadio ------------------------------------------------------------- }
914
915 constructor TMenuItemRadio.Create(const ACaption: String; AIntData: Integer;
916 AChecked, AAutoCheckedToggle: boolean);
917 begin
918 inherited;
919 CreateCommon;
920 end;
921
922 constructor TMenuItemRadio.Create(const ACaption: String; AIntData: Integer;
923 const AKeyString: String;
924 AChecked, AAutoCheckedToggle: boolean);
925 begin
926 inherited;
927 CreateCommon;
928 end;
929
930 constructor TMenuItemRadio.Create(const ACaption: String; AIntData: Integer;
931 AKey: TKey;
932 AChecked, AAutoCheckedToggle: boolean);
933 begin
934 inherited;
935 CreateCommon;
936 end;
937
938 procedure TMenuItemRadio.CreateCommon;
939 begin
940 FGroup := TMenuItemRadioGroup.Create(false);
941 FGroup.Add(Self);
942 end;
943
944 destructor TMenuItemRadio.Destroy;
945 begin
946 if FGroup.Count > 1 then
947 FGroup.Remove(Self) else
948 FreeAndNil(FGroup);
949
950 inherited;
951 end;
952
953 procedure TMenuItemRadio.SetGroup(Value: TMenuItemRadioGroup);
954 begin
955 Value.Add(Self);
956 end;
957
958 procedure TMenuItemRadio.SetChecked(Value: boolean);
959 begin
960 { MenuUpdateChecked inside inherited here is only for this menu item.
961 Later Group.SetSelected takes care to notify about the changes
962 the rest of the group. }
963 inherited;
964
965 if Group.Selected <> Self then
966 begin
967 if Checked then
968 Group.Selected := Self;
969 end else
970 begin
971 if not Checked then
972 Group.Selected := nil;
973 end;
974 end;
975
976 procedure TMenuItemRadio.DoAutoCheckedToggle;
977 begin
978 Group.Selected := Self;
979 end;
980
981 { TMenuItemRadioGroup -------------------------------------------------------- }
982
983 procedure TMenuItemRadioGroup.Add(Item: TMenuItemRadio);
984 begin
985 if Count = 0 then
986 begin
987 { Then this is the addition of the first radio item called from
988 TMenuItemRadio.CreateCommon. Handle this just by calling inherited. }
989 inherited Add(Item);
990 end else
991 begin
992 { Remove item from it's previous group }
993 if Item.FGroup.Count > 1 then
994 Item.FGroup.Remove(Item) else
995 SysUtils.FreeAndNil(Item.FGroup);
996
997 inherited Add(Item);
998
999 Item.FGroup := Self;
1000 end;
1001
1002 if Item.Checked then
1003 begin
1004 if Selected <> nil then
1005 Item.Checked := false else
1006 FSelected := Item;
1007 end;
1008 end;
1009
1010 procedure TMenuItemRadioGroup.Remove(Item: TMenuItemRadio);
1011 begin
1012 if Selected = Item then
1013 FSelected := nil;
1014 inherited Remove(Item);
1015 Item.FGroup := nil;
1016 end;
1017
1018 procedure TMenuItemRadioGroup.SetSelected(Value: TMenuItemRadio);
1019 var
1020 I: Integer;
1021 Item: TMenuItemRadio;
1022 CheckedFast, SelectedFound: boolean;
1023 P: TCastleWindow;
1024 begin
1025 { When count is 0, we have no items belonging to our group.
1026 So selected may only be nil.
1027
1028 This case is never used now: existing TMenuItemRadioGroup are always
1029 created when needed, and are automatically managed by TMenuItemRadio
1030 items, and are freed when there are no more items.
1031 So actually count is never 0, *for now*. We may allow creating
1032 and keeping empty TMenuItemRadioGroup at some point. }
1033 if Count = 0 then
1034 begin
1035 Assert(Value = nil, 'TMenuItemRadioGroup has no items, SetSelected may only be called with nil parameter');
1036 FSelected := nil;
1037 Exit;
1038 end;
1039
1040 P := Items[0].CorrectParentWindow;
1041 if (P <> nil) and P.Closed then P := nil;
1042
1043 { When not CheckedFast, then each SetChecked is expensive.
1044 So it's better to operate here on internal FChecked field
1045 and call MenuFinalize/MenuInitialize only once.
1046 When CheckedFast, don't do this, as using MenuFinalize/MenuInitialize
1047 would be slower then (and would recreate menu,
1048 e.g. hiding detached menus on GTK). }
1049 CheckedFast := (P = nil) or P.MenuUpdateCheckedFast;
1050
1051 if not CheckedFast then
1052 P.MenuFinalize;
1053
1054 FSelected := Value;
1055 if FSelected <> nil then
1056 begin
1057 SelectedFound := false;
1058
1059 for I := 0 to Count - 1 do
1060 begin
1061 Item := Items[I];
1062 Item.FChecked := Item = Selected;
1063 if Item.FChecked then
1064 SelectedFound := true;
1065 if CheckedFast then
1066 if P <> nil then P.MenuUpdateChecked(Item);
1067 end;
1068
1069 Assert(SelectedFound, 'Menu item set as TMenuItemRadioGroup.Selected is not part of this TMenuItemRadioGroup');
1070 end;
1071
1072 if not CheckedFast then
1073 P.MenuInitialize;
1074 end;
1075
1076 (*
1077 procedure TMenuItemRadioGroup.DebugWriteln;
1078 var
1079 I: Integer;
1080 begin
1081 Writeln('--------------------');
1082 for I := 0 to Count - 1 do
1083 begin
1084 Writeln(I, ': ', Items[I].Caption:20, ' ', Items[I].Checked);
1085 Assert(Items[I].Group = Self);
1086 Assert((not Items[I].Checked) or (Selected = Items[I]));
1087 end;
1088 Writeln('--------------------');
1089 end;
1090 *)
1091
1092 function TMenuItemRadioGroup.SelectedIndex: Integer;
1093 begin
1094 if Selected <> nil then
1095 begin
1096 Result := IndexOf(Selected);
1097 Assert(Result <> -1, 'Selected item of TMenuItemRadioGroup does not belong to this group');
1098 end else
1099 Result := -1;
1100 end;
1101
1102 function TMenuItemRadioGroup.Previous(out Item: TMenuItemRadio; const Cycle: Boolean): Boolean;
1103 var
1104 SI, NewIndex: Integer;
1105 begin
1106 SI := SelectedIndex;
1107 if SI <> -1 then
1108 begin
1109 if Cycle then
1110 NewIndex := ChangeIntCycle(SI, -1, Count - 1)
1111 else
1112 NewIndex := Max(SI - 1, 0);
1113 Item := Items[NewIndex];
1114 Result := true;
1115 end else
1116 begin
1117 Item := nil;
1118 Result := false;
1119 end;
1120 end;
1121
1122 function TMenuItemRadioGroup.Next(out Item: TMenuItemRadio; const Cycle: Boolean): Boolean;
1123 var
1124 SI, NewIndex: Integer;
1125 begin
1126 SI := SelectedIndex;
1127 if SI <> -1 then
1128 begin
1129 if Cycle then
1130 NewIndex := ChangeIntCycle(SI, +1, Count - 1)
1131 else
1132 NewIndex := Min(SI + 1, Count - 1);
1133 Item := Items[NewIndex];
1134 Result := true;
1135 end else
1136 begin
1137 Item := nil;
1138 Result := false;
1139 end;
1140 end;
1141
1142 { TMenuItemToggleFullScreen -------------------------------------------------- }
1143
1144 constructor TMenuItemToggleFullScreen.Create(const InitialFullScreen: boolean);
1145 begin
1146 inherited Create('_Full Screen', 0, keyF11, InitialFullScreen, true);
1147 {$ifdef DARWIN} Modifiers := [mkCtrl]; {$endif}
1148 end;
1149
1150 function TMenuItemToggleFullScreen.DoClick: boolean;
1151 begin
1152 Result := inherited;
1153 if not Result then
1154 begin
1155 with CorrectParentWindow do FullScreen := not FullScreen;
1156 Result := true;
1157 end;
1158 end;
1159
1160 { Some useful things ---------------------------------------- }
1161
1162 function SRemoveMnemonics(const S: string): string;
1163 var SPos, ResultPos: Integer;
1164 begin
1165 { I'm utlizing here the fact that Result for sure will be
1166 shorter or equal to S }
1167 SetLength(Result, Length(S));
1168
1169 ResultPos := 1;
1170 SPos := 1;
1171 while SPos <= Length(S) do
1172 begin
1173 if S[SPos] = '_' then
1174 begin
1175 if (SPos < Length(S)) and (S[SPos + 1] = '_') then
1176 begin
1177 Result[ResultPos] := '_';
1178 Inc(ResultPos);
1179 Inc(SPos, 2);
1180 end else
1181 begin
1182 Inc(SPos);
1183 end;
1184 end else
1185 begin
1186 Result[ResultPos] := S[SPos];
1187 Inc(ResultPos);
1188 Inc(SPos);
1189 end;
1190 end;
1191
1192 SetLength(Result, ResultPos - 1);
1193 end;
1194
1195 function SQuoteMenuEntryCaption(const S: string): string;
1196 begin
1197 Result := StringReplace(S, '_', '__', [rfReplaceAll]);
1198 end;
1199
1200 {$endif read_implementation}