Debian Codegraph @

src/window/gtk/castlewindow_gtk_menu.inc

raw
1 {%MainUnit ../castlewindow.pas}
2 {
3 Copyright 2004-2022 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 function TCastleWindow.RedirectKeyDownToMenuClick: boolean;
18 begin
19 Result := false;
20 end;
21
22 procedure signal_menu_item_activate(AMenuItemGtk: PGtkMenuItem;
23 data: gpointer); cdecl; forward;
24
25 procedure gtk_check_menu_item_set_draw_as_radio(
26 check_menu_item:PGtkCheckMenuItem; draw_as_radio:gboolean);
27 cdecl; external gtklib;
28
29 function gtk_check_menu_item_get_draw_as_radio(
30 check_menu_item:PGtkCheckMenuItem):gboolean;
31 cdecl; external gtklib;
32
33 function signal_menu_bar_activation(AGtkMenuBar: PGtkMenuBar;
34 Event: PGdkEventButton; UserData: gpointer): gboolean; cdecl;
35 var
36 Window: TCastleWindow absolute UserData;
37 begin
38 { For reasons of using MenuRecreateForbidden, see signal_menu_item_select
39 comments. }
40 Inc(Window.MenuRecreateForbidden);
41 try
42 Window.ReleaseAllKeysAndMouse;
43 finally
44 Dec(Window.MenuRecreateForbidden);
45 end;
46
47 Result := gfalse;
48 end;
49
50 { This is the only event I found that can be used in GTK 2 to
51 "sniff" when menu is open. See ReleaseAllKeysAndMouse
52 for comments why it's important to sniff it.
53
54 Note that in GTK 2 even when menu is open, key up will correctly
55 be called when you release keys over item in main menu bar
56 (i.e. if your MainMenu contains directly TMenuItem).
57 In this case key up is just passed to our WindowGtk.
58 But this is of course only a special case, in general
59 we still must take care ourselves to call ReleaseAllKeysAndMouse
60 when needed. That's why proc below is needed.
61
62 Note that we use MenuRecreateForbidden here, to prevent modification
63 of menu from within ReleaseAllKeysAndMouse. Reason: menu recreate actually
64 destroys and recreates GTK resources for this menu, and this causes
65 GTK to SEGFAULT right after calling this callback.
66 Not surprising --- we just destroyed the very resource that received focus...
67
68 Menu recreate calls could happen when some KeyUp
69 message will cause e.g. TWindowState.SetStandardState. For example,
70 this happens in castle-model-viewer when KeyUp may produce message to KeySensor about
71 key release, and this may produce ChangedAll on TCastleScene, which produces
72 CastleWindowProgress run...
73
74 MenuRecreateForbidden is not an ideal solution, menu should be eventually
75 recreated at some later point, TODO... For now this works Ok,
76 as TWindowState.SetStandardState only changes Enabled to false and later back
77 to true, so actually recreating menu is not needed. }
78
79 function signal_menu_item_select(AItem: PGtkItem;
80 UserData: gpointer): gboolean; cdecl;
81 var
82 Window: TCastleWindow absolute UserData;
83 begin
84 Inc(Window.MenuRecreateForbidden);
85 try
86 Window.ReleaseAllKeysAndMouse;
87 finally
88 Dec(Window.MenuRecreateForbidden);
89 end;
90
91 Result := gfalse;
92 end;
93
94 { Block signal_menu_item_activate on this menu item.
95 Useful inside signal_menu_item_activate, see there for comments.
96
97 Note: MenuItemBlock/Unblock were changed in CASTLE_WINDOW_GTK_2
98 to use g_signal_handlers_block/unblock_by_func instead of
99 gtk_signal_handler_block/unblock_by_func. Although it should be
100 perfectly correct to use gtk_signal_handler_xxx functions still in GTK_2,
101 this caused some warnings printed by gtk:
102 after doing gtk_signal_handler_block_by_func,
103 next unblocking of this signal and any subsequent blocking and unblocking
104 were writing
105 (castle-model-viewer:4151): Gtk-WARNING **: unable to find signal handler for
106 object(GtkCheckMenuItem:0x8358538) with func(0x80ec484) and data(0x6)
107 (but indeed 0x8358538 and 0x80ec484 and 0x6 were exactly parameters
108 of blocked signal ! In other words, it seems that blocking signal by
109 gtk_signal_handler_block_by_func is doing something wrong that
110 causes all subsequent block/unblock of this signal to display
111 this strange warning.
112 Switching to g_signal_handlers_block/unblock_xxx solves the problem,
113 no warnings are displayed and everything works OK. }
114 procedure MenuItemBlock(MenuItemGtk: PGtkMenuItem; MenuItem: TMenuItem);
115 begin
116 g_signal_handlers_block_by_func( GTK_OBJECT(MenuItemGtk),
117 @signal_menu_item_activate, Pointer(PtrUInt(MenuItem.SmallId)));
118 end;
119
120 { Unblock signal_menu_item_activate from this menu item.
121 Useful inside signal_menu_item_activate, see there for comments. }
122 procedure MenuItemUnblock(MenuItemGtk: PGtkMenuItem; MenuItem: TMenuItem);
123 begin
124 g_signal_handlers_unblock_by_func( GTK_OBJECT(MenuItemGtk),
125 @signal_menu_item_activate, Pointer(PtrUInt(MenuItem.SmallId)));
126 end;
127
128 { Initialize MainMenu.Handle (to GtkMenuBar) and insert it to window_vbox.
129
130 It will not clear the previous value of MainMenu.Handle,
131 it does not try to remove previous MainMenu.Handle from window_vbox
132 etc. --- you have to take care of that yourself. This simply assumes
133 that window_vbox is empty and current value of MainMenu.Handle
134 is clear. }
135
136 procedure TCastleWindow.BackendMenuInitialize;
137
138 { Install GTK menu accelerator (key shortcut) from given MenuItem. }
139 procedure InstallGtkAccelerator(const Item: PGtkMenuItem;
140 const MenuItem: TMenuItem);
141 var
142 Key: TKey;
143 CharKey: Char;
144 Modifiers: TModifierKeys;
145 gdk_keyval: GUint;
146 modifier_type: TGdkModifierType;
147 begin
148 Key := MenuItem.Key;
149 if Length(MenuItem.KeyString) = 1 then
150 CharKey := MenuItem.KeyString[1]
151 else
152 CharKey := #0;
153 Modifiers := MenuItem.Modifiers;
154
155 { Calculate GDK keyval gdk_keyval and modifier_type.
156 (Look for possible gdk_keyval values in gdk/gdkkeysyms.h header
157 (e.g. /usr/include/gtk-1.2/gdk/gdkkeysyms.h on my system)). }
158 modifier_type := 0;
159 case CharKey of
160 CtrlA .. CtrlZ:
161 { I could handle here specially three keys:
162 CharBackspace: gdk_keyval := GDK_KEY_BackSpace;
163 CharTab: gdk_keyval := GDK_KEY_Tab;
164 CharEnter: gdk_keyval := GDK_KEY_Return;
165 but it would be bad idea --- I would have no way to specify
166 then actual Ctrl+H, Ctrl+I, Ctrl+M shortcuts.
167 (While Backspace, Tab, Enter can always be specified by TKey
168 constants keyBackSpace, keyTab, keyEnter).
169 }
170 begin
171 gdk_keyval := GDK_KEY_A + Ord(CharKey) - Ord(CtrlA);
172 modifier_type := GDK_CONTROL_MASK;
173 end;
174
175 CharEscape: gdk_keyval := GDK_KEY_Escape;
176 '0' .. '9': gdk_keyval := GDK_KEY_0 + Ord(CharKey) - Ord('0');
177 'a' .. 'z': gdk_keyval := GDK_KEY_A + Ord(CharKey) - Ord('a');
178 'A' .. 'Z':
179 begin
180 gdk_keyval := GDK_KEY_A + Ord(CharKey) - Ord('A');
181 modifier_type := GDK_SHIFT_MASK;
182 end;
183 '?': gdk_keyval := GDK_KEY_question;
184 else
185 case Key of
186 keyBackSpace: gdk_keyval := GDK_KEY_BackSpace;
187 keyTab: gdk_keyval := GDK_KEY_Tab;
188 keyEnter: gdk_keyval := GDK_KEY_Return;
189
190 { This is not proper translation: keyXxx constants do not make
191 difference between left/right Ctrl/Shift/Alt,
192 while GDK_KEY_Xxx constants do.
193
194 Some solution would be to make two accelerators for one
195 menu item -- TODO when this will be useful. }
196 keyShift: gdk_keyval := GDK_KEY_Shift_L;
197 keyCtrl: gdk_keyval := GDK_KEY_Control_L;
198 keyAlt: gdk_keyval := GDK_KEY_Alt_L;
199
200 keyEscape: gdk_keyval := GDK_KEY_Escape;
201 keySpace: gdk_keyval := GDK_KEY_Space;
202 keyPageUp: gdk_keyval := GDK_KEY_Page_Up;
203 keyPageDown: gdk_keyval := GDK_KEY_Page_Down;
204 keyEnd: gdk_keyval := GDK_KEY_End;
205 keyHome: gdk_keyval := GDK_KEY_Home;
206 keyArrowLeft: gdk_keyval := GDK_KEY_Left;
207 keyArrowUp: gdk_keyval := GDK_KEY_Up;
208 keyArrowRight: gdk_keyval := GDK_KEY_Right;
209 keyArrowDown: gdk_keyval := GDK_KEY_Down;
210 keyInsert: gdk_keyval := GDK_KEY_Insert;
211 keyDelete: gdk_keyval := GDK_KEY_Delete;
212
213 keyNumpadPlus: gdk_keyval := GDK_KEY_Plus;
214 keyNumpadMinus: gdk_keyval := GDK_KEY_Minus;
215
216 key0 .. key9: gdk_keyval := GDK_KEY_0 + Ord(Key) - Ord(key0);
217 keyA .. keyZ: gdk_keyval := GDK_KEY_A + Ord(Key) - Ord(keyA);
218
219 keyF1 : gdk_keyval := GDK_KEY_F1;
220 keyF2 : gdk_keyval := GDK_KEY_F2;
221 keyF3 : gdk_keyval := GDK_KEY_F3;
222 keyF4 : gdk_keyval := GDK_KEY_F4;
223 keyF5 : gdk_keyval := GDK_KEY_F5;
224 keyF6 : gdk_keyval := GDK_KEY_F6;
225 keyF7 : gdk_keyval := GDK_KEY_F7;
226 keyF8 : gdk_keyval := GDK_KEY_F8;
227 keyF9 : gdk_keyval := GDK_KEY_F9;
228 keyF10: gdk_keyval := GDK_KEY_F10;
229 keyF11: gdk_keyval := GDK_KEY_F11;
230 keyF12: gdk_keyval := GDK_KEY_F12;
231
232 keyComma: gdk_keyval := GDK_KEY_Comma;
233 keyPeriod: gdk_keyval := GDK_KEY_Period;
234 else Exit;
235 end;
236 end;
237
238 if mkShift in Modifiers then
239 modifier_type := modifier_type or GDK_SHIFT_MASK;
240 if mkCtrl in Modifiers then
241 modifier_type := modifier_type or GDK_CONTROL_MASK;
242 if mkAlt in Modifiers then
243 modifier_type := modifier_type or GDK_MOD1_MASK;
244
245 gtk_widget_add_accelerator(PGtkWidget(Item), 'activate', window_accel_group,
246 gdk_keyval, modifier_type, GTK_ACCEL_VISIBLE);
247 end;
248
249 { Assuming MainMenu <> nil, builds appropriate GtkMenuBar.
250 Signals signal_menu_item_activate and signal_menu_bar_activation are
251 registered. Everything that should be shown is shown.
252 You just have to insert MainMenu.Handle in your window. }
253 procedure MakeMainMenu;
254
255 function MenuEntryToGtkMenuItem(Entry: TMenuEntry): PGtkMenuItem;
256
257 { Returns fresh gtk_menu_new() }
258 function NewGtkMenu(): PGtkMenu;
259 begin
260 Result := PGtkMenu(gtk_menu_new());
261 { Do not show ! No "gtk_widget_show(GTK_WIDGET(Result));",
262 you do not want to show GtkMenu (it will be automatically
263 shown when user selects it with a mouse click etc.) }
264 end;
265
266 var
267 SubMenu: PGtkMenu;
268 I: Integer;
269 EntryItem: TMenuItem;
270 EntryChecked: TMenuItemChecked;
271 EntryMenu: TMenu;
272 begin
273 if Entry is TMenuItem then
274 begin
275 EntryItem := TMenuItem(Entry);
276 if EntryItem is TMenuItemChecked then
277 begin
278 EntryChecked := TMenuItemChecked(EntryItem);
279 Result := PGtkMenuItem(gtk_check_menu_item_new_with_mnemonic(
280 PChar(EntryItem.Caption)));
281 gtk_check_menu_item_set_active(PGtkCheckMenuItem(Result),
282 EntryChecked.Checked);
283 gtk_check_menu_item_set_show_toggle(PGtkCheckMenuItem(Result), gtrue);
284
285 { To implement TMenuItemRadio I use normal GTK check menu items
286 and just make them look like radio items.
287
288 That's because we implement radio behavior (radio groups,
289 turning Checked on and turning Checked off of the rest)
290 ourselves. So there's no need to map our groups to GTK radio
291 groups (even though they follow the same design...).
292 But in GTK "at each instant exactly one of the radio menu
293 items from a group is selected." So I cannot just create
294 radio items carelessly, I have to set their groups correctly.
295
296 So it's easier for me just to use normal check menu items
297 and only make them look like radios. }
298 gtk_check_menu_item_set_draw_as_radio(
299 PGtkCheckMenuItem(Result), Entry is TMenuItemRadio);
300 end else
301 Result := PGtkMenuItem(gtk_menu_item_new_with_mnemonic(
302 PChar(EntryItem.Caption)));
303
304 gtk_object_set_user_data(GTK_OBJECT(Result), Pointer(Self));
305 gtk_signal_connect(GTK_OBJECT(Result), 'activate',
306 GTK_SIGNAL_FUNC(@signal_menu_item_activate),
307 Pointer(PtrUInt(EntryItem.SmallId)));
308
309 InstallGtkAccelerator(Result, EntryItem);
310 end else
311 if Entry is TMenuSeparator then
312 begin
313 { gtk_menu_item_new() creates a separator menu item, this can be found
314 in GTK FAQ. }
315 Result := PGtkMenuItem(gtk_menu_item_new());
316 end else
317 if Entry is TMenu then
318 begin
319 EntryMenu := TMenu(Entry);
320 Result := PGtkMenuItem(gtk_menu_item_new_with_mnemonic(
321 PChar(EntryMenu.Caption)));
322
323 SubMenu := NewGtkMenu();
324
325 for i := 0 to EntryMenu.Count - 1 do
326 gtk_menu_append(GTK_WIDGET(SubMenu),
327 GTK_WIDGET( MenuEntryToGtkMenuItem(EntryMenu.Entries[i]) ));
328
329 gtk_menu_item_set_submenu(Result, GTK_WIDGET(SubMenu));
330 end else
331 raise EInternalError.Create('Not implemented TMenuEntry subclass');
332
333 Entry.Handle := Result;
334
335 if Entry is TMenuEntryWithCaption then
336 MenuUpdateEnabled(TMenuEntryWithCaption(Entry));
337
338 gtk_signal_connect(GTK_OBJECT(Result), 'select',
339 GTK_SIGNAL_FUNC(@signal_menu_item_select), Self);
340
341 gtk_widget_show(GTK_WIDGET(Result));
342 end;
343
344 var
345 I: Integer;
346 begin
347 MainMenu.Handle := PGtkMenuBar(gtk_menu_bar_new());
348
349 MenuUpdateEnabled(MainMenu);
350
351 gtk_widget_show(GTK_WIDGET(MainMenu.Handle));
352 for I := 0 to MainMenu.Count - 1 do
353 { Don't put TMenuSeparator in menu bar because that would look ugly. }
354 if not (MainMenu.Entries[I] is TMenuSeparator) then
355 gtk_menu_bar_append(GTK_WIDGET(MainMenu.Handle),
356 GTK_WIDGET( MenuEntryToGtkMenuItem(MainMenu.Entries[I]) ));
357
358 { How to catch the moment when the menu bar is opened/selected/clicked
359 etc. by the user ? It should be caught when user enters menu by clicking
360 on menu bar or pressing some menu key (like F10 in GTK 2).
361
362 There is no way do this nicely in GTK 1 ?
363 So I'm using threre very non-elegant soltuion to catch button-press-event.
364 GTK 1 does not allow user to enter menu by F10 or some other key like that. }
365 gtk_signal_connect(GTK_OBJECT(MainMenu.Handle), 'button-press-event',
366 GTK_SIGNAL_FUNC(@signal_menu_bar_activation), Self);
367 end;
368
369 begin
370 if MenuRecreateForbidden <> 0 then Exit;
371
372 MakeMainMenu;
373 gtk_box_pack_start(PGtkBox(window_vbox), GTK_WIDGET(MainMenu.Handle),
374 gfalse, gfalse, 0);
375 end;
376
377 procedure TCastleWindow.BackendMenuFinalize;
378 begin
379 if MenuRecreateForbidden <> 0 then Exit;
380
381 { According to GTK docs (at gtk_container_remove),
382 the simplest way to remove GtkMenuBar (in MainMenu.Handle)
383 from window_vbox is to simply do gtk_widget_destroy on MainMenu.Handle.
384 This will take care of removing MainMenu.Handle appropriately. }
385 gtk_widget_destroy(GTK_WIDGET(MainMenu.Handle));
386
387 MainMenu.ClearHandles;
388 end;
389
390 { GTK >= 2.16 already includes "gtk_menu_item_set_label":
391 http://library.gnome.org/devel/gtk/2.21/GtkMenuItem.html#gtk-menu-item-set-label
392 But we cannot use GTK 2.16 (e.g. Debian stable still only has
393 GTK 2.12 on 2010-05).
394
395 So we implement it ourselves, following ideas from
396 http://mail.gnome.org/archives/gtk-app-devel-list/2003-October/msg00171.html
397 http://mail.gnome.org/archives/gtk-app-devel-list/2003-October/msg00180.html }
398 procedure gtk_menu_item_set_label(EntryGtk: PGtkMenuItem; Caption: PChar);
399 var
400 LabelGtk: PGtkWidget;
401 begin
402 LabelGtk := gtk_bin_get_child(PGtkBin(EntryGtk));
403 if (LabelGtk <> nil) and GTK_IS_LABEL(LabelGtk) then
404 gtk_label_set_text_with_mnemonic(PGtkLabel(LabelGtk), Caption);
405 end;
406
407 { Extract PGtkWidget corresponding to given Entry.
408 Returns @false (and does log warning, and sets EntryGtk to nil) if failed. }
409 function CheckEntryGtk(Entry: TMenuEntryWithCaption; out EntryGtk: PGtkWidget): boolean;
410 begin
411 EntryGtk := PGtkWidget(Entry.Handle);
412 Result := EntryGtk <> nil;
413 if (not Result) and
414 ((Entry.CorrectParentWindow = nil) or Entry.CorrectParentWindow.MainMenuVisible) then
415 WritelnWarning('Menu', 'Menu entry "' + Entry.Caption + '" has Handle = nil (this means that corresponding GTK menu item object was not created, but it should)');
416 end;
417
418 procedure TCastleWindow.MenuUpdateCaption(Entry: TMenuEntryWithCaption);
419 var
420 EntryGtk: PGtkWidget;
421 begin
422 if not CheckEntryGtk(Entry, EntryGtk) then Exit;
423
424 { MainMenu is a little special: it's Caption is ignored,
425 and it's not really a GtkMenuItem so gtk_menu_item_set_label call
426 would be invalid. }
427 if Entry <> MainMenu then
428 gtk_menu_item_set_label(PGtkMenuItem(EntryGtk), PChar(Entry.Caption));
429 end;
430
431 procedure TCastleWindow.MenuUpdateEnabled(Entry: TMenuEntryWithCaption);
432 var
433 EntryGtk: PGtkWidget;
434 begin
435 if not CheckEntryGtk(Entry, EntryGtk) then Exit;
436
437 gtk_widget_set_sensitive(PGtkWidget(EntryGtk), Entry.Enabled);
438 end;
439
440 procedure TCastleWindow.MenuUpdateChecked(Entry: TMenuItemChecked);
441 var
442 EntryGtk: PGtkWidget;
443 begin
444 if not CheckEntryGtk(Entry, EntryGtk) then Exit;
445
446 { Use MenuItemBlock, otherwise gtk_check_menu_item_set_active will
447 call signal_menu_item_activate (which is pointless, and breaks
448 assertion there). }
449 MenuItemBlock(PGtkMenuItem(EntryGtk), Entry);
450 try
451 gtk_check_menu_item_set_active(PGtkCheckMenuItem(EntryGtk), Entry.Checked);
452 finally
453 MenuItemUnblock(PGtkMenuItem(EntryGtk), Entry);
454 end;
455 end;
456
457 function TCastleWindow.MenuUpdateCheckedFast: boolean;
458 begin
459 Result := true;
460 end;
461
462 procedure TCastleWindow.MenuInsert(const Parent: TMenu;
463 const ParentPosition: Integer; const Entry: TMenuEntry);
464 begin
465 { TODO: unoptimal }
466 MenuFinalize;
467 MenuInitialize;
468 end;
469
470 procedure TCastleWindow.MenuDelete(const Parent: TMenu;
471 const ParentPosition: Integer; const Entry: TMenuEntry);
472 begin
473 { TODO: unoptimal }
474 MenuFinalize;
475 MenuInitialize;
476 end;