Debian Codegraph @

src/delphi/castleinternalfmxutils_linux.inc

raw
1 {%MainUnit castleinternalfmxutils.pas}
2 {
3 Copyright 2022-2023 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { Implementation of CastleInternalFmxUtils (initialize OpenGL context in FMX,
18 code shared between FMX TOpenGLControl and FMX TCastleControl)
19 for Linux. }
20
21 uses
22 SysUtils,
23 { Needed for TCustomForm used by XWindowHandle }
24 FMX.Forms,
25 CTypes,
26 CastleInternalContextEgl, CastleLog, CastleUtils;
27
28 {$I castleinternalfmxutils_gtk3.inc}
29
30 { internal routines --------------------------------------------------------- }
31
32 procedure PassSignalToOtherWidget(const SignalName: AnsiString;
33 const OtherWidget: Pointer; const Event: Pointer);
34 var
35 SignalEmitArgs: array[0..2] of TGValue;
36 ReturnValue: TGValue;
37 SignalInt: CUInt;
38 begin
39 SignalInt := g_signal_lookup(PAnsiChar(SignalName), G_TYPE_FROM_INSTANCE(OtherWidget));
40 if SignalInt = 0 then
41 raise Exception.CreateFmt('Signal "%s" on target not found', [SignalName]);
42
43 { Initialize GValue list.
44 - 1st item must be instance to which we send signal,
45 - then params of that signal (just Event),
46 - then finish (leave uinitialized GValue,
47 "uinitialized" == filled with zeroes for glib).
48
49 Note that we have to fill initially values with zeroes, otherwise
50 it could be mistaken with initialized value with some garbage and cause
51 valid glib warnings/errors. }
52 FillChar(SignalEmitArgs, SizeOf(SignalEmitArgs), 0);
53 g_value_init(@SignalEmitArgs[0], G_TYPE_OBJECT);
54 g_value_set_instance(@SignalEmitArgs[0], OtherWidget);
55 g_value_init(@SignalEmitArgs[1], G_TYPE_POINTER);
56 g_value_set_pointer(@SignalEmitArgs[1], Event);
57
58 { Initialie ReturnValue (GValue). Despite docs,
59 g_signal_emitv cannot get nil as return value. }
60 FillChar(ReturnValue, SizeOf(ReturnValue), 0);
61 g_value_init(@ReturnValue, G_TYPE_BOOLEAN);
62 g_value_set_boolean(@ReturnValue, false);
63
64 g_signal_emitv(@SignalEmitArgs, SignalInt, 0, @ReturnValue);
65
66 g_value_unset(@SignalEmitArgs[0]);
67 g_value_unset(@SignalEmitArgs[1]);
68 g_value_unset(@ReturnValue);
69 end;
70
71 function signal_button_press_event(AGLAreaGtk: Pointer; Event: PGdkEventAny;
72 Data: Pointer): gboolean; cdecl;
73 begin
74 { Pass the signal to FMX control,
75 which will make FMX callbacks,
76 and then TCastleWindow (in case of CASTLE_WINDOW_FORM)
77 or TCastleControl will handle the event from FMX. }
78 PassSignalToOtherWidget('button_press_event', Data, Event);
79 Result := false;
80 end;
81
82 function signal_button_release_event(AGLAreaGtk: Pointer; Event: PGdkEventAny;
83 Data: Pointer): gboolean; cdecl;
84 begin
85 PassSignalToOtherWidget('button_release_event', Data, Event);
86 Result := false;
87 end;
88
89 function signal_motion_notify_event(AGLAreaGtk: Pointer; Event: PGdkEventAny;
90 Data: Pointer): gboolean; cdecl;
91 begin
92 { We need own motion_notify_event otherwise events do not reach
93 FMX after you clicked (when mouse events are grabbed),
94 regardless of button_press_event return value. }
95 PassSignalToOtherWidget('motion_notify_event', Data, Event);
96 Result := false;
97 end;
98
99 function signal_scroll_event(AGLAreaGtk: Pointer; Event: PGdkEventAny;
100 Data: Pointer): gboolean; cdecl;
101 begin
102 PassSignalToOtherWidget('scroll_event', Data, Event);
103 Result := false;
104 end;
105
106 { TFmxOpenGLUtility ---------------------------------------------------------- }
107
108 (*
109 // Note: This wasn't needed in the end, so we never finished or tested it.
110 // Keeping it here -- as it may make sense again.
111
112 function TFmxOpenGLUtility.HandlePossible: Boolean;
113 var
114 LinuxFormHandle: TLinuxWindowHandle;
115 begin
116 Result := false;
117
118 if (Control.Root <> nil) and
119 (Control.Root is TCustomForm) then
120 begin
121 LinuxFormHandle := TLinuxWindowHandle(TCustomForm(Control.Root).Handle);
122 if LinuxFormHandle <> nil then
123 Exit(true);
124 end;
125 end;
126 *)
127
128 procedure TFmxOpenGLUtility.ContextAdjustEarly(const PlatformContext: TGLContext);
129
130 { Get XWindow handle (to pass to EGL) from GTK widget. }
131 function XHandleFromGtkWidget(const GtkWnd: Pointer): Pointer;
132 var
133 GdkWnd: Pointer;
134 begin
135 GdkWnd := gtk_widget_get_window(GtkWnd);
136 if GdkWnd = nil then
137 raise Exception.Create('Widget does not have GDK handle initialized yet');
138
139 Result := gdk_x11_window_get_xid(GdkWnd);
140 if Result = nil then
141 raise Exception.Create('Widget does not have X11 handle initialized yet');
142 end;
143
144 var
145 EglContext: TGLContextEgl;
146 XHandle: Pointer;
147 begin
148 if GLAreaGtk = nil then
149 raise Exception.Create('Native GTK area not ready when calling ContextAdjustEarly');
150 XHandle := XHandleFromGtkWidget(GLAreaGtk);
151 EglContext := PlatformContext as TGLContextEgl;
152 EglContext.WndPtr := XHandle;
153 Assert(EglContext.WndPtr <> nil); // XHandleFromGtkWidget already checks this and made exception if problem
154 end;
155
156 { If @true, there's a reasonable chance that everything necessary
157 for GetLinuxHandle is already initialized. }
158 function GetLinuxHandlePossible(const Control: TPresentedControl): Boolean;
159 begin
160 Result :=
161 (Control <> nil) and
162 (Control.Root is TCustomForm) and // also checks Control.Root <> nil
163 (TCustomForm(Control.Root).Handle <> nil);
164 end;
165
166 function GetLinuxHandle(const Control: TPresentedControl): TLinuxWindowHandle;
167 var
168 Form: TCustomForm;
169 begin
170 if Control.Root = nil then
171 raise Exception.CreateFmt('Control %s does not have root', [Control.ClassName]);
172 if not (Control.Root is TCustomForm) then
173 raise Exception.CreateFmt('Control %s root is not TCastleForm, but is %s', [
174 Control.ClassName,
175 (Control.Root as TObject).ClassName
176 ]);
177 Form := Control.Root as TCustomForm;
178
179 (*
180 Old version, assuming Control.Parent is form (which is only sometimes true):
181 if Control.Parent = nil then
182 raise Exception.CreateFmt('Parent of %s must be set', [Control.ClassName]);
183 // This actually also tests Parent <> nil, but previous check makes better error message
184 if not (Control.Parent is TCustomForm) then
185 raise Exception.CreateFmt('Parent of %s must be form', [Control.ClassName]);
186 Form := Control.Parent as TCustomForm;
187 *)
188
189 Result := TLinuxWindowHandle(Form.Handle);
190 if Result = nil then
191 raise Exception.CreateFmt('Form of %s does not have TLinuxHandle initialized yet', [Control.ClassName]);
192 end;
193
194 function GetControlRect(const Control: TPresentedControl; const Scale: Single): TVector4Integer;
195 begin
196 Result := Vector4Integer(
197 Round(Control.Position.X * Scale),
198 Round(Control.Position.Y * Scale),
199 Round(Control.Size.Width * Scale),
200 Round(Control.Size.Height * Scale)
201 );
202 end;
203
204 procedure TFmxOpenGLUtility.HandleNeeded;
205 var
206 LinuxHandle: TLinuxWindowHandle;
207 DrawingAreaParentAsFixed: Pointer;
208 DrawingAreaParentClassName: AnsiString;
209 begin
210 { Use GLAreaInitialized, instead of check GLAreaGtk <> nil,
211 to avoid repeating this when some check below raises exception
212 and GLAreaGtk would always remain nil. }
213 if GLAreaInitialized then
214 Exit;
215 GLAreaInitialized := true;
216
217 WritelnLog('FMX OpenGL', 'Creating context and GLAreaGtk widget');
218
219 LinuxHandle := GetLinuxHandle(Control);
220
221 if LinuxHandle.NativeHandle = nil then
222 raise Exception.CreateFmt('Form of %s does not have GTK NativeHandle initialized yet', [Control.ClassName]);
223 if LinuxHandle.NativeDrawingArea = nil then
224 raise Exception.CreateFmt('Form of %s does not have GTK NativeDrawingArea initialized yet', [Control.ClassName]);
225
226 { Tests show that parent of is GtkFixed,
227 this makes things easy for us to insert GLAreaGtk later. }
228 DrawingAreaParent := gtk_widget_get_parent(LinuxHandle.NativeDrawingArea);
229 if DrawingAreaParent = nil then
230 raise Exception.Create('FMX drawing area in GTK has no parent');
231
232 DrawingAreaParentClassName := G_OBJECT_TYPE_NAME(DrawingAreaParent);
233 if DrawingAreaParentClassName <> 'GtkFixed' then
234 WritelnWarning('FMX drawing area has parent with unexpected class "%s". We will try to continue it and cast it to GtkFixed', [
235 DrawingAreaParentClassName
236 ]);
237
238 DrawingAreaParentAsFixed := g_type_check_instance_cast(DrawingAreaParent, gtk_fixed_get_type);
239
240 { Note: We tested alternative solution
241 GLAreaGtk := LinuxHandle.NativeDrawingArea;
242 which seems to make sense when GLAreaGtk should just fill the whole window,
243 like for TCastleWindow. But it causes blinking. }
244
245 { Initialization of variables and checks are done.
246 Now actually create GLAreaGtk, if things look sensible. }
247
248 GLAreaGtk := gtk_drawing_area_new;
249
250 { Add a refcount to GLAreaGtk, and later HandleRelease will do g_object_unref.
251
252 This way HandleRelease is more robust: in case the GTK window of the form
253 was already destroyed at the moment of HandleRelease call,
254 the GLAreaGtk remains valid (it would be invalid
255 without this g_object_ref call). So we can call gtk_widget_destroy
256 safely on it.
257
258 Otherwise, gtk_widget_destroy(GLAreaGtk) in HandleRelease could cause
259 GTK errors, that argument is not a widget, sometimes: when the form
260 was already freed.
261
262 Testcase: CastleFmx with explicit "FreeAndNil(TestCgeControl)" in main program file. }
263 g_object_ref(GLAreaGtk);
264
265 { connect signal handlers to GLAreaGtk }
266 { What events to catch ? It must cover all signal_yyy_event functions that we
267 will connect. This must be called before X Window is created. }
268 gtk_widget_set_events(GLAreaGtk,
269 // GDK_EXPOSURE_MASK {for expose_event} or
270 GDK_BUTTON_PRESS_MASK {for button_press_event} or
271 GDK_BUTTON_RELEASE_MASK {for button_release_event} or
272 GDK_POINTER_MOTION_MASK {for motion_notify_event}
273 );
274 g_signal_connect(GLAreaGtk, 'button_press_event', @signal_button_press_event,
275 LinuxHandle.NativeDrawingArea);
276 g_signal_connect(GLAreaGtk, 'button_release_event', @signal_button_release_event,
277 LinuxHandle.NativeDrawingArea);
278 g_signal_connect(GLAreaGtk, 'motion_notify_event', @signal_motion_notify_event,
279 LinuxHandle.NativeDrawingArea);
280 g_signal_connect(GLAreaGtk, 'scroll_event', @signal_scroll_event,
281 LinuxHandle.NativeDrawingArea);
282
283 // Do this using gtk_fixed_put instead:
284 //gtk_container_add(DrawingAreaParentAsFixed, GLAreaGtk);
285 GLAreaRect := GetControlRect(Control, LinuxHandle.Scale);
286 gtk_fixed_put(DrawingAreaParentAsFixed, GLAreaGtk, GLAreaRect.X, GLAreaRect.Y);
287 gtk_widget_set_size_request(GLAreaGtk, GLAreaRect.Z, GLAreaRect.W);
288 gtk_widget_show(GLAreaGtk);
289
290 { Debugging what are some Gtk classes, to reverse-engineer what FMXLinux
291 is doing inside it's closed library:
292 WritelnLog('LinuxHandle.NativeHandle type ' + G_OBJECT_TYPE_NAME(LinuxHandle.NativeHandle));
293 WritelnLog('LinuxHandle.NativeDrawingArea type ' + G_OBJECT_TYPE_NAME(LinuxHandle.NativeDrawingArea));
294 WritelnLog('GLAreaGtk type ' + G_OBJECT_TYPE_NAME(GLAreaGtk));
295 }
296
297 if Assigned(OnHandleAfterCreateEvent) then
298 OnHandleAfterCreateEvent();
299 end;
300
301 procedure TFmxOpenGLUtility.Update;
302 var
303 NewRect: TVector4Integer;
304 begin
305 // abort if HandleNeeded not yet called (or not successful)
306 if GLAreaGtk = nil then
307 Exit;
308
309 NewRect := GetControlRect(Control, Scale);
310 if not TVector4Integer.Equals(NewRect, GLAreaRect) then
311 begin
312 gtk_fixed_move(DrawingAreaParent, GLAreaGtk, NewRect.X, NewRect.Y);
313 gtk_widget_set_size_request(GLAreaGtk, NewRect.Z, NewRect.W);
314 GLAreaRect := NewRect;
315 end;
316 end;
317
318 procedure TFmxOpenGLUtility.HandleRelease;
319 begin
320 if GLAreaGtk <> nil then
321 begin
322 WritelnLog('FMX OpenGL', 'Destroying context and GLAreaGtk widget');
323 if Assigned(OnHandleBeforeDestroyEvent) then
324 OnHandleBeforeDestroyEvent();
325 gtk_widget_destroy(GLAreaGtk);
326 g_object_unref(GLAreaGtk);
327
328 GLAreaGtk := nil;
329 GLAreaInitialized := false;
330 DrawingAreaParent := nil;
331 end;
332 end;
333
334 function TFmxOpenGLUtility.Scale: Single;
335 var
336 LinuxHandle: TLinuxWindowHandle;
337 begin
338 { Note that we check GetLinuxHandlePossible, not "GLAreaGtk <> nil".
339 This way we can get scale before the OpenGL context was initialized.
340
341 This way castlewindow_form.inc code doesn't need to care that
342 FGLUtility.Scale may change after form creation,
343 and thus PixelWidth/Height could change without causing OnResize event.
344
345 Testcase: multi_window.
346 }
347 if GetLinuxHandlePossible(Control) then
348 begin
349 LinuxHandle := GetLinuxHandle(Control);
350 Result := LinuxHandle.Scale;
351 end else
352 Result := 1;
353 end;