Debian Codegraph @

src/window/castlewindow_cocoa.inc

raw
1 {%MainUnit castlewindow.pas}
2 {
3 Copyright 2022-2024 Michalis Kamburelis, Jan Adamec, and GLPT, LCL contributors.
4
5 The Cocoa integration code is based on
6
7 - GLPT
8
9 The base code to create window with OpenGL context
10 comes from GLPT original, from https://github.com/daar/GLPT .
11 The fork from https://github.com/genericptr/GLPT was also useful.
12
13 Thank you go to all GLPT contributors, in particular:
14 - Darius Blaszyk (daar)
15 - Ryan Joseph (genericptr)
16
17 - LCL Cocoa widgetset
18
19 The code for alerts and file/color dialogs is based
20 on LCL Cocoa widgetset.
21 In many other cases we consulted LCL Cocoa widgetset code
22 to see "how to do something properly with Cocoa".
23
24 This file is part of "Castle Game Engine".
25
26 "Castle Game Engine" is free software; see the file COPYING.txt,
27 included in this distribution, for details about the copyright.
28
29 "Castle Game Engine" is distributed in the hope that it will be useful,
30 but WITHOUT ANY WARRANTY; without even the implied warranty of
31 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
32
33 ----------------------------------------------------------------------------
34 }
35
36 { TODO p1:
37 - fullscreen: should be on top of dock / menu (started but doesn't work, search for COCOA_FULL_SCREEN)
38 - hide / show mouse cursor (for mouse look) (started but doesn't work, NSCursor.hide/unhide)
39 - reposition mouse (for mouse look ) (started but doesn't work, see SetMousePosition)
40
41 TODO p2:
42 - use filters in FileDialog to highlight correct files
43 - avoid deprecated warnings at assembling
44 Assembling castlewindow
45 /Users/administrator/sources/castle-engine/castle-engine/examples/user_interface/test_all_state_events/castle-engine-output/compilation/x86_64-darwin/castlewindow.s:263336:10: warning: section "__datacoal_nt" is deprecated
46 .section __DATA, __datacoal_nt, coalesced
47 ^ ~~~~~~~~~~~~~~
48 /Users/administrator/sources/castle-engine/castle-engine/examples/user_interface/test_all_state_events/castle-engine-output/compilation/x86_64-darwin/castlewindow.s:263336:10: note: change section name to "__data"
49 .section __DATA, __datacoal_nt, coalesced
50 ^ ~~~~~~~~~~~~~~
51 /Users/administrator/sources/castle-engine/castle-engine/examples/user_interface/test_all_state_events/castle-engine-output/compilation/x86_64-darwin/castlewindow.s:263484:10: warning: section "__datacoal_nt" is deprecated
52 .section __DATA, __datacoal_nt, coalesced
53 ^ ~~~~~~~~~~~~~~
54 /Users/administrator/sources/castle-engine/castle-engine/examples/user_interface/test_all_state_events/castle-engine-output/compilation/x86_64-darwin/castlewindow.s:263484:10: note: change section name to "__data"
55 .section __DATA, __datacoal_nt, coalesced
56 ^ ~~~~~~~~~~~~~~
57 Unknown how to deal with it.
58 https://wiki.lazarus.freepascal.org/Mac_Installation_FAQ#Lazarus_reports_success.2C_but_there_are_errors.21
59 mentions it, without any answer except "ignore them"..
60 - entering modal message leaves the key pressed down, testcase: test_all_state_events, press Q
61 - hiding cursor doesn't work for unknown reason
62 - Call FileMonitor.CheckChanges when user switches to application.
63 }
64
65 {$ifdef read_interface_uses}
66 CocoaAll,
67 {$endif}
68
69 {$ifdef read_implementation_uses}
70 // for CGWarp... in SetMousePosition, unused for now
71 // CGRemoteOperation, CGGeometry,
72 {$endif}
73
74 {$ifdef read_window_interface}
75 private
76 ref: NSWindow;
77 GLcontext: NSOpenGLContext;
78 FMenuForcefullyDisabled: Boolean;
79 procedure FullScreenBegin;
80 procedure FullScreenEnd;
81 procedure SetMenuForcefullyDisabled(const Value: Boolean);
82 property MenuForcefullyDisabled: Boolean read FMenuForcefullyDisabled write SetMenuForcefullyDisabled;
83
84 { Show Cocoa modal message box.
85
86 Use Cocoa Sheet called NSAlert.
87 See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Sheets/Tasks/UsingAlertSheets.html#//apple_ref/doc/uid/20001045-BABFIBIA .
88 Based on Lazarus LCL lcl/interfaces/cocoa/cocoalclintf.inc ,
89 but greatly simplified.
90
91 @param(AlertStyle Pass NSCriticalAlertStyle or NSInformationalAlertStyle.
92 You can also use NSWarningAlertStyle, but Apple docs openly say it is
93 equivalent to NSInformationalAlertStyle, see
94 https://developer.apple.com/documentation/appkit/nsalertstyle.)
95
96 @param(ButtonCaptions Array of button captions.)
97
98 @param(ButtonResults Array of button result values. May have equal length as ButtonCaptions.)
99
100 @returns(The value from ButtonResults corresponding to the button that was pressed.
101 Returns -1 if application ended while the message was active.) }
102 function CocoaPromptUser(const DialogCaption: String;
103 const DialogMessage: String;
104 const AlertStyle: NSAlertStyle;
105 const ButtonCaptions: array of String;
106 const ButtonResults: array of NSInteger): NSInteger;
107
108 { Set Cocoa cursor following our FCursor value. }
109 procedure UpdateCursor;
110 {$endif read_window_interface}
111
112 {$ifdef read_application_interface}
113 private
114 CursorHidden: Boolean;
115 {$endif read_application_interface}
116
117 {$ifdef read_implementation}
118
119 {$I castlewindow_cocoa_menu.inc}
120 {$I castlewindow_cocoa_message.inc}
121 {$I castlewindow_cocoa_filedialog.inc}
122 {$I castlewindow_cocoa_colordialog.inc}
123
124 { Integration code from GLPT ------------------------------------------------- }
125
126 var
127 KeyCodeCocoaToCastle: array [0..127] of TKey = (
128 { 0 } keyA,
129 { 1 } keyS,
130 { 2 } keyD,
131 { 3 } keyF,
132 { 4 } keyH,
133 { 5 } keyG,
134 { 6 } keyZ,
135 { 7 } keyX,
136 { 8 } keyC,
137 { 9 } keyV,
138 { 10 } keyNone, // TODO, GLPT_SCANCODE_NONUSBACKSLASH, { GLPT_SCANCODE_NONUSBACKSLASH on ANSI and JIS keyboards (if this key would exist there), GLPT_SCANCODE_GRAVE on ISO. (The USB keyboard driver actually translates these usage codes to different virtual key codes depending on whether the keyboard is ISO/ANSI/JIS. That's why you have to help it identify the keyboard type when you plug in a PC USB keyboard. It's a historical thing - ADB keyboards are wired this way.) }
139 { 11 } keyB,
140 { 12 } keyQ,
141 { 13 } keyW,
142 { 14 } keyE,
143 { 15 } keyR,
144 { 16 } keyY,
145 { 17 } keyT,
146 { 18 } key1,
147 { 19 } key2,
148 { 20 } key3,
149 { 21 } key4,
150 { 22 } key6,
151 { 23 } key5,
152 { 24 } keyEqual,
153 { 25 } key9,
154 { 26 } key7,
155 { 27 } keyMinus,
156 { 28 } key8,
157 { 29 } key0,
158 { 30 } keyRightBracket,
159 { 31 } keyO,
160 { 32 } keyU,
161 { 33 } keyLeftBracket,
162 { 34 } keyI,
163 { 35 } keyP,
164 { 36 } keyEnter,
165 { 37 } keyL,
166 { 38 } keyJ,
167 { 39 } keyApostrophe,
168 { 40 } keyK,
169 { 41 } keySemicolon,
170 { 42 } keyBackslash,
171 { 43 } keyComma,
172 { 44 } keySlash,
173 { 45 } keyN,
174 { 46 } keyM,
175 { 47 } keyPeriod,
176 { 48 } keyTab,
177 { 49 } keySpace,
178 { 50 } keyNone, // TODO, GLPT_SCANCODE_GRAVE, { GLPT_SCANCODE_GRAVE on ANSI and JIS keyboards, GLPT_SCANCODE_NONUSBACKSLASH on ISO (see comment about virtual key code 10 above) }
179 { 51 } keyBackspace,
180 { 52 } keyNumpadEnter, { keyboard enter on portables }
181 { 53 } keyEscape,
182 { 54 } keyNone, // TODO, GLPT_SCANCODE_RGUI,
183 { 55 } keyNone, // TODO, GLPT_SCANCODE_GUI,
184 { 56 } keyShift, // left shift
185 { 57 } keyCapsLock,
186 { 58 } keyAlt, // left alt
187 { 59 } keyCtrl, // left ctrl
188 { 60 } keyShift, // right shift
189 { 61 } keyAlt, // right alt
190 { 62 } keyCtrl, // right ctrl
191 { 63 } keyNone, // TODO, GLPT_SCANCODE_RGUI, { fn on portables, acts as a hardware-level modifier already, so we don't generate events for it, also XK_Meta_R }
192 { 64 } keyNone, // TODO, GLPT_SCANCODE_F17,
193 { 65 } keyPeriod, // keyNumpadPeriod, but we don't have such specific key
194 { 66 } keyNone, { unknown (unused?) }
195 { 67 } keyNumpadMultiply,
196 { 68 } keyNone, { unknown (unused?) }
197 { 69 } keyNumpadPlus,
198 { 70 } keyNone, { unknown (unused?) }
199 { 71 } keyNone, // TODO, GLPT_SCANCODE_NUMLOCKCLEAR,
200 { 72 } keyNone, // TODO, GLPT_SCANCODE_VOLUMEUP,
201 { 73 } keyNone, // TODO, GLPT_SCANCODE_VOLUMEDOWN,
202 { 74 } keyNone, // TODO, GLPT_SCANCODE_MUTE,
203 { 75 } keyNumpadDivide,
204 { 76 } keyNumpadEnter, { keypad enter on external keyboards, fn-return on portables }
205 { 77 } keyNone, { unknown (unused?) }
206 { 78 } keyNumpadMinus,
207 { 79 } keyNone, // TODO, GLPT_SCANCODE_F18,
208 { 80 } keyNone, // TODO, GLPT_SCANCODE_F19,
209 { 81 } keyEqual, // keyNumpadEqual, but we don't have such specific key
210 { 82 } keyNumpad0,
211 { 83 } keyNumpad1,
212 { 84 } keyNumpad2,
213 { 85 } keyNumpad3,
214 { 86 } keyNumpad4,
215 { 87 } keyNumpad5,
216 { 88 } keyNumpad6,
217 { 89 } keyNumpad7,
218 { 90 } keyNone, { unknown (unused?) }
219 { 91 } keyNumpad8,
220 { 92 } keyNumpad9,
221 { 93 } keyNone, // TODO, GLPT_SCANCODE_INTERNATIONAL3, { Cosmo_USB2ADB.c says "Yen (JIS)" }
222 { 94 } keyNone, // TODO, GLPT_SCANCODE_INTERNATIONAL1, { Cosmo_USB2ADB.c says "Ro (JIS)" }
223 { 95 } keyComma, { Cosmo_USB2ADB.c says ", JIS only" } // keyNumpadComma, but we don't have such specific key
224 { 96 } keyF5,
225 { 97 } keyF6,
226 { 98 } keyF7,
227 { 99 } keyF3,
228 { 100 } keyF8,
229 { 101 } keyF9,
230 { 102 } keyNone, // TODO, GLPT_SCANCODE_LANG2, { Cosmo_USB2ADB.c says "Eisu" }
231 { 103 } keyF11,
232 { 104 } keyNone, // TODO, GLPT_SCANCODE_LANG1, { Cosmo_USB2ADB.c says "Kana" }
233 { 105 } keyPrintScreen, { On ADB keyboards, this key is labeled "F13/print screen". Problem: USB has different usage codes for these two functions. On Apple USB keyboards, the key is labeled "F13" and sends the F13 usage code (GLPT_SCANCODE_F13). I decided to use GLPT_SCANCODE_PRINTSCREEN here nevertheless since SDL applications are more likely to assume the presence of a print screen key than an F13 key. }
234 { 106 } keyNone, // TODO, GLPT_SCANCODE_F16,
235 { 107 } keyNone, // TODO, GLPT_SCANCODE_SCROLLLOCK, { F14/scroll lock, see comment about F13/print screen above }
236 { 108 } keyNone, { unknown (unused?) }
237 { 109 } keyF10,
238 { 110 } keyNone, // TODO, GLPT_SCANCODE_APPLICATION, { windows contextual menu key, fn-enter on portables }
239 { 111 } keyF12,
240 { 112 } keyNone, { unknown (unused?) }
241 { 113 } keyNone, // TODO, GLPT_SCANCODE_PAUSE, { F15/pause, see comment about F13/print screen above }
242 { 114 } keyInsert, { the key is actually labeled "help" on Apple keyboards, and works as such in Mac OS, but it sends the "insert" usage code even on Apple USB keyboards }
243 { 115 } keyHome,
244 { 116 } keyPageUp,
245 { 117 } keyDelete,
246 { 118 } keyF4,
247 { 119 } keyEnd,
248 { 120 } keyF2,
249 { 121 } keyPageDown,
250 { 122 } keyF1,
251 { 123 } keyArrowLeft,
252 { 124 } keyArrowRight,
253 { 125 } keyArrowDown,
254 { 126 } keyArrowUp,
255 { 127 } keyNone // TODO, GLPT_SCANCODE_POWER
256 );
257
258 {=============================================}
259 {@! ___BORDERLESS WINDOW___ }
260 {=============================================}
261
262 type
263 TBorderlessWindow = objcclass (NSWindow)
264 public
265 function initWithContentRect_styleMask_backing_defer (contentRect: NSRect; aStyle: NSUInteger; bufferingType: NSBackingStoreType; flag: ObjCBool): id; override;
266 function initWithContentRect(contentRect: NSRect): id; message 'initWithContentRect:';
267 function canBecomeKeyWindow: ObjCBool; override;
268 function canBecomeMainWindow: ObjCBool; override;
269 procedure setKeepFullScreenAlways (newValue: boolean); message 'setKeepFullScreenAlways:';
270 procedure dealloc; override;
271 private
272 keepFullScreenAlways: boolean;
273 procedure screenParametersChanged (notification: NSNotification); message 'screenParametersChanged:';
274 end;
275
276 function TBorderlessWindow.canBecomeKeyWindow: ObjCBool;
277 begin
278 result := true;
279 end;
280
281 function TBorderlessWindow.canBecomeMainWindow: ObjCBool;
282 begin
283 result := true;
284 end;
285
286 procedure TBorderlessWindow.setKeepFullScreenAlways (newValue: boolean);
287 begin
288 orderFrontRegardless;
289 keepFullScreenAlways := newValue;
290 if keepFullScreenAlways then
291 setFrame_display(screen.frame, true);
292 end;
293
294 procedure TBorderlessWindow.screenParametersChanged (notification: NSNotification);
295 begin
296 if keepFullScreenAlways then
297 setFrame_display(NSScreen.mainScreen.frame, true);
298 end;
299
300 procedure TBorderlessWindow.dealloc;
301 begin
302 NSNotificationCenter.defaultCenter.removeObserver(self);
303 inherited dealloc;
304 end;
305
306 function TBorderlessWindow.initWithContentRect_styleMask_backing_defer (contentRect: NSRect; aStyle: NSUInteger; bufferingType: NSBackingStoreType; flag: ObjCBool): id;
307 begin
308 result := inherited initWithContentRect_styleMask_backing_defer(contentRect, aStyle, bufferingType, flag);
309 if result <> nil then
310 NSNotificationCenter(NSNotificationCenter.defaultCenter).addObserver_selector_name_object(result, objcselector('screenParametersChanged:'), NSApplicationDidChangeScreenParametersNotification, nil);
311 end;
312
313 function TBorderlessWindow.initWithContentRect(contentRect: NSRect): id;
314 begin
315 result := initWithContentRect_styleMask_backing_defer(contentRect, NSBorderlessWindowMask, NSBackingStoreBuffered, false);
316 if result <> nil then
317 begin
318 result.setMovableByWindowBackground(false);
319 //result.setBackgroundColor(NSColor.clearColor);
320 //result.setOpaque(false);
321 result.setHasShadow(false);
322 result.setExcludedFromWindowsMenu(true);
323 self := result;
324 end;
325 end;
326
327 {=============================================}
328 {@! ___COCOA WINDOW___ }
329 {=============================================}
330
331 type
332 TCocoaWindow = objcclass (TBorderlessWindow)
333 private
334 ref: TCastleWindow;
335 WithinCloseBackend: Cardinal;
336 ScaleFactor: Single;
337 public
338 procedure close; override;
339 procedure becomeKeyWindow; override;
340 procedure resignKeyWindow; override;
341 procedure doCommandBySelector(aSelector: SEL); override;
342 end;
343
344 procedure TCocoaWindow.close;
345 begin
346 if WithinCloseBackend = 0 then
347 ref.DoCloseQuery;
348 inherited;
349 end;
350
351 procedure TCocoaWindow.doCommandBySelector(aSelector: SEL);
352 begin
353 // do nothing to prevent beeping
354 end;
355
356 procedure TCocoaWindow.becomeKeyWindow;
357 begin
358 inherited;
359 // ref.FKeyWindow := true; // we don't track such property now
360 end;
361
362 procedure TCocoaWindow.resignKeyWindow;
363 begin
364 inherited;
365 // ref.FKeyWindow := false;
366 end;
367
368 {=============================================}
369 {@! ___COCOA APP___ }
370 {=============================================}
371
372 type
373 TCocoaApp = objcclass (NSApplication)
374 procedure poll; message 'poll';
375 end;
376
377 type
378 TCocoaAppDelegate = objcclass (NSObject, NSApplicationDelegateProtocol)
379 procedure application_openFiles(sender: NSApplication; filenames: NSArray); message 'application:openFiles:';
380 end;
381
382 procedure TCocoaApp.poll;
383 var
384 win: TCastleWindow = nil;
385
386 procedure CheckMotionDragged(const MouseButton: TCastleMouseButton);
387 begin
388 if not (MouseButton in win.MousePressed) then
389 begin
390 WritelnWarning('Cocoa event indicated that %s should be pressed, but not registered as pressed yet', [
391 MouseButtonStr[MouseButton]
392 ]);
393 win.DoMouseDown(win.MousePosition, MouseButton, 0);
394 end;
395 end;
396
397 { Simulate pressing / release of modifiers (like shift, alt, ctrl) based on modifier flags.
398 These keys are not passed to regular key down / up keycodes.
399 See https://stackoverflow.com/questions/4640696/cocoa-nsevent-respond-to-the-shift-key
400 https://developer.apple.com/documentation/appkit/nseventmodifierflags?language=objc }
401 procedure UpdateModifiersPressed(const ModifierFlags: NSEventModifierFlags);
402 var
403 IsShift, IsAlt, IsCtrl: Boolean;
404 begin
405 IsShift := (ModifierFlags and NSShiftKeyMask) <> 0;
406 if IsShift <> win.Pressed[keyShift] then
407 if IsShift then
408 win.DoKeyDown(keyShift, '')
409 else
410 win.DoKeyUp(keyShift);
411
412 IsAlt := (ModifierFlags and NSAlternateKeyMask) <> 0;
413 if IsAlt <> win.Pressed[keyAlt] then
414 if IsAlt then
415 win.DoKeyDown(keyAlt, '')
416 else
417 win.DoKeyUp(keyAlt);
418
419 IsCtrl :=
420 //(ModifierFlags and NSControlKeyMask) <> 0;
421 (ModifierFlags and NSCommandKeyMask) <> 0; // treat Command key as Ctrl
422 if IsCtrl <> win.Pressed[keyCtrl] then
423 if IsCtrl then
424 win.DoKeyDown(keyCtrl, '')
425 else
426 win.DoKeyUp(keyCtrl);
427 end;
428
429 var
430 event: NSEvent;
431 pool: NSAutoreleasePool;
432 CastleMouseButton: TCastleMouseButton;
433 ScaleFactor: Single;
434 begin
435 pool := NSAutoreleasePool.alloc.init;
436 event := nextEventMatchingMask_untilDate_inMode_dequeue(NSAnyEventMask, {NSDate.distantPast}nil, NSDefaultRunLoopMode, true);
437 if event <> nil then
438 begin
439 //WritelnLog('Cocoa event ' + event.description.UTF8String);
440
441 if (event.window <> nil) and
442 { We need to check the class of event.window, as when clicking "minimize" / "zoom" in menu
443 we get events not related to this window.
444
445 Note: It seems we cannot use
446 (event.window is TCocoaWindow)
447 or even
448 (event.window.ClassType = TCocoaWindow)
449 with objcclass. Comparing ClassName.UTF8String seems like the only solution
450 (report if you know a cleaner approach).
451 }
452 (event.window.ClassName.UTF8String = 'TCocoaWindow') then
453 win := TCocoaWindow(event.window).ref;
454
455 if win <> nil then
456 begin
457 ScaleFactor := TCocoaWindow(event.window).ScaleFactor;
458 case event.type_ of
459 NSMouseMoved,
460 NSLeftMouseDragged,
461 NSRightMouseDragged,
462 NSOtherMouseDragged:
463 begin
464 case event.type_ of
465 NSLeftMouseDragged : CheckMotionDragged(buttonLeft);
466 NSRightMouseDragged: CheckMotionDragged(buttonRight);
467 NSOtherMouseDragged: CheckMotionDragged(buttonMiddle);
468 end;
469 win.DoMotion(InputMotion(win.MousePosition,
470 Vector2(event.locationInWindow.x*ScaleFactor, event.locationInWindow.y*ScaleFactor), win.MousePressed, 0));
471 end;
472 NSLeftMouseDown, NSRightMouseDown, NSOtherMouseDown:
473 begin
474 case event.type_ of
475 NSLeftMouseDown: CastleMouseButton := buttonLeft;
476 NSRightMouseDown: CastleMouseButton := buttonRight;
477 NSOtherMouseDown: CastleMouseButton := buttonMiddle;
478 else raise EInternalError.Create('Unexpected event.type_');
479 end;
480 win.DoMouseDown(Vector2(event.locationInWindow.x*ScaleFactor, event.locationInWindow.y*ScaleFactor),
481 CastleMouseButton, 0);
482 end;
483 NSLeftMouseUp, NSRightMouseUp, NSOtherMouseUp:
484 begin
485 case event.type_ of
486 NSLeftMouseUp: CastleMouseButton := buttonLeft;
487 NSRightMouseUp: CastleMouseButton := buttonRight;
488 NSOtherMouseUp: CastleMouseButton := buttonMiddle;
489 else raise EInternalError.Create('Unexpected event.type_');
490 end;
491 win.DoMouseUp(Vector2(event.locationInWindow.x*ScaleFactor, event.locationInWindow.y*ScaleFactor),
492 CastleMouseButton, 0);
493 end;
494 NSKeyDown:
495 begin
496 // UpdateModifiersPressed(event.modifierFlags); // not needed - NSFlagsChanged works well enough
497 win.DoKeyDown(KeyCodeCocoaToCastle[event.keycode], event.characters.UTF8String);
498 // TODO we could use event.isARepeat for our KeyRepeated, instead we always calculate it manually
499 end;
500 NSKeyUp:
501 begin
502 win.DoKeyUp(KeyCodeCocoaToCastle[event.keycode]);
503 // UpdateModifiersPressed(event.modifierFlags); // not needed - NSFlagsChanged works well enough
504 end;
505 NSFlagsChanged:
506 UpdateModifiersPressed(event.modifierFlags);
507 NSScrollWheel:
508 begin
509 if event.deltaX <> 0 then
510 win.DoMouseWheel(event.deltaX, false);
511 if event.deltaY <> 0 then
512 win.DoMouseWheel(event.deltaY, true);
513 end;
514 otherwise
515 ;
516 end;
517 end else
518 begin
519 { This is normal:
520 - at start Cocoa sends message
521 NSEvent: type=Kitdefined loc=(0,1080) time=608959.3 flags=0x40 win=0x0 winNum=0 ctxt=0x0 subtype=1 data1=627 data2=0
522 - when doing minimize / zoom, we get messages for window that is not TCocoaWindow
523 }
524 //WritelnWarning('Ignoring Cocoa event %s, window does not exist', [event.description.UTF8String]);
525 end;
526
527 sendEvent(event);
528 updateWindows;
529 end;
530 pool.release;
531 end;
532
533 procedure TCocoaAppDelegate.application_openFiles(sender: NSApplication; filenames: NSArray);
534 var
535 lFiles: array of string;
536 lNSStr: NSString;
537 I: Integer;
538 begin
539 SetLength(lFiles, filenames.count);
540 for I := 0 to filenames.count-1 do
541 begin
542 lNSStr := NSString(filenames.objectAtIndex(I));
543 lFiles[I] := lNSStr.UTF8String;
544 end;
545 if Application.MainWindow <> nil then
546 Application.MainWindow.DoDropFiles(lFiles);
547 end;
548
549 {=============================================}
550 {@! ___OPENGL VIEW___ }
551 {=============================================}
552
553 type
554 TOpenGLView = objcclass (NSView)
555 public
556 function initWithFrame(frameRect: NSRect): id; override;
557 procedure dealloc; override;
558 function isOpaque: ObjCBool; override;
559 procedure viewDidMoveToWindow; override;
560 procedure mouseEntered(theEvent: NSEvent); override;
561 procedure mouseExited(theEvent: NSEvent); override;
562 procedure doCommandBySelector(aSelector: SEL); override;
563 procedure updateTrackingAreas; override;
564 procedure keyDown(theEvent: NSEvent); override;
565 procedure drawRect(dirtyRect: NSRect); override;
566 procedure setFrameSize(newSize: NSSize); override;
567
568 { Realizes TCastleWindow.OnDropFiles, allows to handle dropping files. }
569 function performDragOperation(sender: NSDraggingInfoProtocol): ObjCBOOL; override;
570 function prepareForDragOperation(sender: NSDraggingInfoProtocol): ObjCBool; override;
571 function draggingEntered(sender: NSDraggingInfoProtocol): NSDragOperation; override;
572 private
573 openGLContext: NSOpenGLContext;
574 trackingArea: NSTrackingArea;
575
576 function defaultPixelFormat: NSOpenGLPixelFormat; message 'defaultPixelFormat';
577 function windowRef: TCastleWindow; message 'windowRef';
578 procedure frameChanged (sender: NSNotification); message 'frameChanged:';
579 procedure reshape(newSize: NSSize); message 'reshape:';
580 end;
581
582 // note: setValues_forParameter in RTL headers is parsed wrong
583 type
584 NSOpenGLContext_Fixed = objccategory external (NSOpenGLContext)
585 procedure setValues_forParameter_fixed (vals: pointer; param: NSOpenGLContextParameter); overload; message 'setValues:forParameter:';
586 end;
587
588 function TOpenGLView.windowRef: TCastleWindow;
589 begin
590 result := TCocoaWindow(window).ref;
591 end;
592
593 procedure TOpenGLView.updateTrackingAreas;
594 begin
595 if trackingArea <> nil then
596 removeTrackingArea(trackingArea);
597 trackingArea := NSTrackingArea.alloc.initWithRect_options_owner_userInfo(bounds, NSTrackingMouseEnteredAndExited + NSTrackingActiveAlways, self, nil).autorelease;
598 addTrackingArea(trackingArea);
599 end;
600
601 procedure TOpenGLView.keyDown(theEvent: NSEvent);
602 begin
603 // do nothing to prevent beeping
604 end;
605
606 procedure TOpenGLView.doCommandBySelector(aSelector: SEL);
607 begin
608 // do nothing to prevent beeping
609 end;
610
611 procedure TOpenGLView.mouseEntered(theEvent: NSEvent);
612 begin
613 windowRef.FFocused := true;
614 end;
615
616 procedure TOpenGLView.mouseExited(theEvent: NSEvent);
617 begin
618 windowRef.FFocused := false;
619 end;
620
621 procedure TOpenGLView.viewDidMoveToWindow;
622 var
623 swapInterval: integer = 1;
624 opacity: integer = 0;
625 begin
626 inherited viewDidMoveToWindow;
627
628 if openGLContext = nil then
629 begin
630 openGLContext := NSOpenGLContext.alloc.initWithFormat_shareContext(defaultPixelFormat, nil);
631 if openGLContext = nil then
632 raise EInternalError.Create('invalid NSOpenGLContext');
633 openGLContext.makeCurrentContext;
634 openGLContext.setView(self);
635
636 openGLContext.setValues_forParameter_fixed(@swapInterval, NSOpenGLCPSwapInterval);
637
638 if not isOpaque then
639 openGLContext.setValues_forParameter_fixed(@opacity, NSOpenGLCPSurfaceOpacity);
640 end;
641
642 if window = nil then
643 openGLContext.clearDrawable
644 else
645 reshape(bounds.size);
646 end;
647
648 procedure TOpenGLView.frameChanged (sender: NSNotification);
649 begin
650 if (openGLContext <> nil) and (window <> nil) and (windowRef <> nil) then
651 reshape(bounds.size);
652 end;
653
654 procedure TOpenGLView.drawRect(dirtyRect: NSRect);
655 begin
656 // This has to be done in Cocoa_SwapBuffers, at least on macOS 12
657 // openGLContext.flushBuffer;
658 end;
659
660 procedure TOpenGLView.reshape(newSize: NSSize);
661 var
662 ScaleFactor: Single;
663 BackingSize: NSSize;
664 begin
665 openGLContext.update;
666
667 { To be secure, check both window and windowRef.
668 When window=nil, accessing windowRef would be an error. }
669 if (window <> nil) and (windowRef <> nil) then
670 begin
671 { On high-resolution displays, the bounds.size needs to be scaled by
672 https://developer.apple.com/documentation/appkit/nswindow/1419459-backingscalefactor?language=objc
673 See also
674 https://developer.apple.com/documentation/appkit/nsviewlayercontentscaledelegate?language=objc
675 https://developer.apple.com/documentation/quartzcore/calayer/1410746-contentsscale?language=objc
676 (possibly we could use NSViewLayerContentScaleDelegate
677 to avoid such scaling on OpenGL control; for now this solution seems easier). }
678 if window.respondsToSelector( ObjCSelector('backingScaleFactor')) then // check if we are on OSX 10.7
679 begin
680 BackingSize := convertSizeToBacking(newSize);
681 ScaleFactor := BackingSize.width / newSize.width;
682 end
683 else
684 begin
685 if window.respondsToSelector( ObjCSelector('backingScaleFactor')) then
686 ScaleFactor := window.backingScaleFactor
687 else
688 if window.respondsToSelector( ObjCSelector('userSpaceScaleFactor')) then // for older OSX
689 {$warnings off}
690 // do not warn about userSpaceScaleFactor being deprecated, we only use it for older OS
691 ScaleFactor := window.userSpaceScaleFactor
692 {$warnings on}
693 else
694 ScaleFactor := 1;
695 BackingSize := NSMakeSize(newSize.width * ScaleFactor, newSize.height * ScaleFactor);
696 end;
697
698 if TCocoaWindow(window).ScaleFactor <> ScaleFactor then
699 begin
700 TCocoaWindow(window).ScaleFactor := ScaleFactor;
701 windowRef.Container.Dpi := ScaleFactor * DefaultDpi
702 end;
703
704 windowRef.DoResize(trunc(BackingSize.width), trunc(BackingSize.height), false);
705 end;
706 end;
707
708 procedure TOpenGLView.setFrameSize(newSize: NSSize);
709 begin
710 inherited setFrameSize(newSize);
711 reshape(newSize);
712 end;
713
714 function TOpenGLView.isOpaque: ObjCBool;
715 begin
716 // return false to make the view transparent
717 result := window.backgroundColor.alphaComponent > 0;
718 end;
719
720 function TOpenGLView.defaultPixelFormat: NSOpenGLPixelFormat;
721 function Inc (var i: integer): integer;
722 begin
723 i += 1;
724 result := i;
725 end;
726 const
727 NSOpenGLPFAOpenGLProfile = 99 { available in 10_7 };
728 const
729 NSOpenGLProfileVersionLegacy = $1000 { available in 10_7 };
730 NSOpenGLProfileVersion3_2Core = $3200 { available in 10_7 };
731 NSOpenGLProfileVersion4_1Core = $4100 { available in 10_10 };
732 var
733 attributes: array[0..32] of NSOpenGLPixelFormatAttribute;
734 i: integer = -1;
735 context: TCastleWindow;
736 begin
737 context := TCocoaWindow(window).ref;
738
739 { Request accelerated?
740 Does not seem necessary,
741 https://developer.apple.com/documentation/appkit/nsopenglpixelformat/1436213-opengl_pixel_format_attributes
742 says that accelerated is preferred anyway. }
743 // attributes[Inc(i)] := NSOpenGLPFAAccelerated;
744
745 if context.doubleBuffer then
746 attributes[Inc(i)] := NSOpenGLPFADoubleBuffer;
747 attributes[Inc(i)] := NSOpenGLPFAColorSize;
748 attributes[Inc(i)] := context.ColorBits;
749 attributes[Inc(i)] := NSOpenGLPFADepthSize;
750 attributes[Inc(i)] := context.DepthBits;
751 attributes[Inc(i)] := NSOpenGLPFAStencilSize;
752 attributes[Inc(i)] := context.StencilBits;
753 attributes[Inc(i)] := NSOpenGLPFAOpenGLProfile;
754 attributes[Inc(i)] := NSOpenGLProfileVersion3_2Core;
755 attributes[Inc(i)] := 0;
756
757 result := NSOpenGLPixelFormat.alloc.initWithAttributes(@attributes).autorelease;
758 if result = nil then
759 raise EInternalError.Create('invalid NSOpenGLPixelFormat');
760
761 { Make TGLFeatures.Create use a path that avoids accessing deprecated glGetString(GL_EXTENSIONS).
762
763 TODO: This should not be necessary, we should not change RequestCapabilities here.
764 It used to be a necessary hack with FPC GLExt unit:
765 But FPC GLExt unit will by default access deprecated glGetString(GL_EXTENSIONS),
766 this is for now the simplest way to prevent it. }
767 TGLFeatures.RequestCapabilities := rcForceModern;
768 end;
769
770 function TOpenGLView.initWithFrame(frameRect: NSRect): id;
771 begin
772 result := inherited initWithFrame(frameRect);
773 if result <> nil then
774 begin
775 // NSViewGlobalFrameDidChangeNotification is not needed when setFrameSize is overriden in our view. This notification is received far too often.
776 //NSNotificationCenter(NSNotificationCenter.defaultCenter).addObserver_selector_name_object(result, objcselector('frameChanged:'), NSViewGlobalFrameDidChangeNotification, result);
777 end;
778 end;
779
780 procedure TOpenGLView.dealloc;
781 begin
782 //NSNotificationCenter(NSNotificationCenter.defaultCenter).removeObserver_name_object(self, NSViewGlobalFrameDidChangeNotification, result);
783 NSNotificationCenter(NSNotificationCenter.defaultCenter).removeObserver_name_object(self, NSWindowDidChangeScreenNotification, nil);
784 NSNotificationCenter(NSNotificationCenter.defaultCenter).removeObserver_name_object(self, NSWindowDidChangeBackingPropertiesNotification, nil);
785
786 inherited dealloc;
787 end;
788
789 function TOpenGLView.draggingEntered(sender: NSDraggingInfoProtocol): NSDragOperation;
790 begin
791 // Result := NSDragOperationNone;
792 // Necessary to support drag-and-drop files on the application.
793 Result := sender.draggingSourceOperationMask();
794 end;
795
796 function TOpenGLView.prepareForDragOperation(sender: NSDraggingInfoProtocol): ObjCBool;
797 begin
798 { According to docs https://developer.apple.com/documentation/appkit/nsdraggingdestination/1416066-preparefordragoperation?language=objc ,
799 it is necessary to return true to support drag-and-drop files on the application.
800
801 In practice overriding prepareForDragOperation doesn't seem to do anything
802 - it is not necessary (overriding draggingEntered is enough),
803 - it doesn't make drag-and-drop possible without draggingEntered.
804
805 Still we override it, following the docs. }
806
807 Result := true;
808 end;
809
810 function TOpenGLView.performDragOperation(sender: NSDraggingInfoProtocol): ObjCBOOL;
811 { Based on LCL Cocoa widgetset }
812 var
813 draggedURLs: NSArray;
814 lFiles: array of string;
815 i: Integer;
816 pboard: NSPasteboard;
817 lNSStr: NSString;
818 CastleWindow: TCastleWindow;
819 begin
820 Result := False;
821 pboard := sender.draggingPasteboard();
822
823 // Multiple strings
824 draggedURLs := pboard.propertyListForType(NSFilenamesPboardType);
825 SetLength(lFiles, draggedURLs.count);
826 for i := 0 to draggedURLs.count-1 do
827 begin
828 lNSStr := NSString(draggedURLs.objectAtIndex(i));
829 lFiles[i] := lNSStr.UTF8String;
830 end;
831
832 CastleWindow := TCocoaWindow(window).ref;
833
834 if Length(lFiles) > 0 then
835 CastleWindow.DoDropFiles(lFiles);
836
837 Result := True;
838 end;
839
840 {=============================================}
841 {@! ___GLPT___ }
842 {=============================================}
843
844 { unused
845 procedure Cocoa_GetFrameBufferSize(win: TCastleWindow; out width, height: integer);
846 begin
847 width := trunc(win^.ref.contentView.bounds.size.width);
848 height:= trunc(win^.ref.contentView.bounds.size.height);
849 end;
850 }
851
852 { TCastleWindow ------------------------------------------------------------------ }
853
854 procedure TCastleWindow.CreateBackend;
855 begin
856 end;
857
858 procedure TCastleWindow.SwapBuffers;
859 begin
860 ref.contentView.display;
861 glcontext.flushBuffer;
862
863 { Without this workaround:
864
865 For unknown reason, changing title on Cocoa resets the cursor to arrow.
866 So change it back, if FCursor requires non-standard look.
867
868 Testcase: castle-model-viewer open
869 demo-models/sensors_pointing_device/touch_sensor_tests.x3dv ,
870 hover with mouse over pointing device sensor -- the cursor should remain
871 "hand", not be reset to "arrow". Note that castle-model-viewer uses
872 "Window.FpsShowOnCaption := true;" so indeed it changes caption every second.
873
874 Some other report:
875 https://stackoverflow.com/questions/52379148/cocoa-api-keeps-resetting-our-nscursor
876 (no solution there).
877
878 Doing UpdateCursor at the end of SetCaption unfortunately
879 doesn't fix the issue.
880
881 We do it only when FCursor is non-standard to avoid hyphothetical performance
882 cost (due to doing NSCursor.xxx.set_ call each frame) in the most common
883 situation (when Cursor is left as default), but actually tests show that
884 it is not costly at all, and without the test "if not (FCursor..."
885 the performance on macOS is the same.
886 }
887 if not (FCursor in [mcDefault, mcNone, mcForceNone, mcStandard]) then
888 UpdateCursor;
889 end;
890
891 { TODO:
892 This causes error from all examples:
893 EOpenGLError: End of TCastleWindow.DoRender
894 OpenGL error (1286): The command is trying to render to or read from the framebuffer while the currently bound framebuffer is not framebuffer complete (i.e. the return value from glCheckFramebufferStatus is not GL_FRAMEBUFFER_COMPLETE).
895 }
896 {.$define COCOA_FULL_SCREEN}
897
898 procedure TCastleWindow.FullScreenBegin;
899 {$ifdef COCOA_FULL_SCREEN}
900 var
901 FullScreenOptions: NSDictionary;
902 begin
903 { TODO: alternative:
904
905 if NSAppKitVersionNumber >= NSAppKitVersionNumber10_7 then
906 begin
907 if ref.collectionBehavior and (
908 NSWindowCollectionBehaviorFullScreenPrimary or
909 NSWindowCollectionBehaviorFullScreenAuxiliary
910 ) = 0 then
911 ref.setCollectionBehavior(ref.collectionBehavior or NSWindowCollectionBehaviorFullScreenPrimary);
912 ref.toggleFullScreen(nil);
913 end
914 }
915
916 { In Objective-C:
917 NSDictionary fullScreenOptions = [[NSDictionary dictionaryWithObject: [NSNumber numberWithBool: YES] forKey: NSFullScreenModeSetting] retain];
918 See https://thinkstack.wordpress.com/2015/12/19/full-screen-mode-for-cocoa-applications/
919 }
920 FullScreenOptions := NSDictionary.dictionaryWithObjectsAndKeys(
921 NSNumber.numberWithBool(true), NSFullScreenModeSetting,
922 nil);
923 FFullScreenBackend := ref.contentView.EnterFullScreenMode_withOptions(ref.screen, FullScreenOptions);
924 if not FFullScreenBackend then
925 WritelnWarning('Cannot enter full-screen mode');
926 {$else}
927 begin
928 {$endif COCOA_FULL_SCREEN}
929 end;
930
931 procedure TCastleWindow.FullScreenEnd;
932 begin
933 {$ifdef COCOA_FULL_SCREEN}
934 ref.contentView.ExitFullScreenModeWithOptions(nil);
935 {$endif COCOA_FULL_SCREEN}
936 end;
937
938 procedure TCastleWindow.OpenBackend;
939 const
940 NSWindowCollectionBehaviorFullScreenPrimary = 1 shl 7 { available in 10_7 };
941 NSWindowCollectionBehaviorFullScreenAuxiliary = 1 shl 8 { available in 10_7 };
942 var
943 window: TCocoaWindow;
944 openGLView: TOpenGLView;
945 windowFlags: NSUInteger = 0;
946 begin
947 if not FullScreen then
948 begin
949 windowFlags := NSTitledWindowMask + NSClosableWindowMask + NSMiniaturizableWindowMask + NSResizableWindowMask;
950 window := TCocoaWindow.alloc.initWithContentRect_styleMask_backing_defer(NSMakeRect(FLeft, FTop, FWidth, FHeight), windowFlags, NSBackingStoreBuffered, false);
951 window.setTitle(NSSTR(GetWholeCaption));
952 end else
953 begin
954 { Update position/size in case window is fullscreen }
955 FLeft := 0;
956 FTop := 0;
957 DoResize(Application.ScreenWidth, Application.ScreenHeight, false);
958
959 // windowFlags := NSBorderlessWindowMask;
960 // window := TCocoaWindow.alloc.initWithContentRect_styleMask_backing_defer(NSMakeRect(FLeft, FTop, FWidth, FHeight), windowFlags, NSBackingStoreBuffered, false);
961 window := TCocoaWindow.alloc.initWithContentRect(NSMakeRect(FLeft, FTop, FWidth, FHeight));
962 window.setKeepFullScreenAlways(true);
963 end;
964
965 window.ref := Self;
966 window.ScaleFactor := 1; // wil be detected during openGLView creation
967
968 openGLView := TOpenGLView.alloc.initWithFrame(window.contentView.bounds);
969 // makes drag-and-drop files on window work
970 openGLView.registerForDraggedTypes(NSArray.arrayWithObjects_count(@NSFilenamesPboardType, 1));
971 { It is critical to call this, in order to get the "real" resolution OpenGL
972 context (with our pixel corresponding to final device pixels).
973 Otherwise, with Retina monitors, we get OpenGL context with smaller pixel
974 size that is then stretched (on the macOS side) to the final size,
975 which is not what we want -- we want crisp rendering, we want to control
976 any eventual scaling on our side.
977
978 This wasnt necessary when compiling with old macOS SDK (on macOS 12.7.2).
979
980 With new macOS SDK (macOS 14.6, Xcode 15.4) this is necessary.
981
982 Docs on https://developer.apple.com/documentation/appkit/nsview/1414938-wantsbestresolutionopenglsurface?language=objc
983 say this is deprecated and defaults to Yes with new macOS SDK, but it seems
984 the docs are wrong.
985 LCL Cocoa TOpenGLControl also does this, see
986 https://gitlab.com/freepascal.org/lazarus/lazarus/-/blob/main/components/opengl/glcocoanscontext.pas?ref_type=heads . }
987 openGLView.setWantsBestResolutionOpenGLSurface(true);
988 window.setContentView(openGLView);
989 openGLView.release;
990
991 NSNotificationCenter(NSNotificationCenter.defaultCenter).addObserver_selector_name_object(openGLView, objcselector('frameChanged:'), NSWindowDidChangeScreenNotification, window);
992 NSNotificationCenter(NSNotificationCenter.defaultCenter).addObserver_selector_name_object(openGLView, objcselector('frameChanged:'), NSWindowDidChangeBackingPropertiesNotification, window);
993
994 if FullScreen then
995 FullScreenBegin;
996
997 window.makeFirstResponder(openGLView);
998
999 window.setCollectionBehavior(NSWindowCollectionBehaviorFullScreenPrimary);
1000 window.setAcceptsMouseMovedEvents(true);
1001 window.makeKeyAndOrderFront(nil);
1002
1003 openGLView.reshape(openGLView.bounds.size);
1004
1005 glcontext := openGLView.openGLContext;
1006 ref := window;
1007
1008 Application.OpenWindowsAdd(Self);
1009
1010 // TODO
1011 // GetInitialCursorPos;
1012 // UpdateCursor;
1013 end;
1014
1015 procedure TCastleWindow.CloseBackend;
1016 var
1017 CocoaWindow: TCocoaWindow;
1018 begin
1019 if ref <> nil then
1020 begin
1021 CocoaWindow := TCocoaWindow(ref);
1022 Inc(CocoaWindow.WithinCloseBackend); // avoids infinite loop at closing
1023 CocoaWindow.close;
1024 Dec(CocoaWindow.WithinCloseBackend);
1025 ref := nil;
1026 end;
1027 end;
1028
1029 procedure TCastleWindow.SetCaption(const Part: TCaptionPart; const Value: String);
1030 begin
1031 FCaption[Part] := Value;
1032 if not Closed then
1033 ref.setTitle(NSSTR(GetWholeCaption));
1034 end;
1035
1036 procedure TCastleWindow.BackendMakeCurrent;
1037 begin
1038 glcontext.makeCurrentContext;
1039 end;
1040
1041 procedure TCastleWindow.UpdateCursor;
1042 var
1043 WantsCursorHidden: Boolean;
1044 begin
1045 if not Closed then
1046 begin
1047 { To implement mcNone, mcForceNone we need to hide/unhide the cursor.
1048 The calls to hide/unhide in Cocoa must be balanced, following docs,
1049 so we use CursorHidden to know when they are actually necessary to call. }
1050 WantsCursorHidden := FCursor in [mcNone, mcForceNone];
1051 if Application.CursorHidden <> WantsCursorHidden then
1052 begin
1053 Application.CursorHidden := WantsCursorHidden;
1054 // TODO: hiding cursor doesn't work for unknown reason
1055 if Application.CursorHidden then
1056 NSCursor.hide()
1057 else
1058 NSCursor.unhide();
1059 end;
1060
1061 // Set Cocoa (global) cursor, see https://developer.apple.com/documentation/appkit/nscursor
1062 case FCursor of
1063 mcDefault, mcStandard:
1064 NSCursor.arrowCursor.set_;
1065 mcNone, mcForceNone:
1066 { do nothing here, without any warning };
1067 mcText:
1068 NSCursor.IBeamCursor.set_;
1069 mcHand:
1070 NSCursor.openHandCursor.set_;
1071 mcResizeHorizontal:
1072 NSCursor.resizeLeftRightCursor.set_;
1073 mcResizeVertical:
1074 NSCursor.resizeUpDownCursor.set_;
1075 mcResizeLeft:
1076 NSCursor.resizeLeftCursor.set_;
1077 mcResizeRight:
1078 NSCursor.resizeRightCursor.set_;
1079 mcResizeTop:
1080 NSCursor.resizeUpCursor.set_;
1081 mcResizeBottom:
1082 NSCursor.resizeDownCursor.set_;
1083 else
1084 begin
1085 NSCursor.arrowCursor.set_;
1086 WritelnWarning('Cursor %d not implemented on Cocoa', [Ord(FCursor)]);
1087 end;
1088 end;
1089 end;
1090 end;
1091
1092 procedure TCastleWindow.SetCursor(const Value: TMouseCursor);
1093 begin
1094 if FCursor <> Value then
1095 begin
1096 FCursor := Value;
1097 UpdateCursor;
1098 end;
1099 end;
1100
1101 function TCastleWindow.RedirectKeyDownToMenuClick: boolean;
1102 begin
1103 Result := { TODO } true;
1104 end;
1105
1106 procedure TCastleWindow.SetMousePosition(const Value: TVector2);
1107 begin
1108 end;
1109 (* TODO: Unfortunately none of the options below make any effect.
1110
1111 var
1112 PointWindowCoords, PointScreenCoords: NSPoint;
1113 CgPointScreenCoords: CGPoint;
1114 begin
1115 if not Closed then
1116 begin
1117 PointWindowCoords := NSMakePoint(Value.X, Value.Y);
1118 PointScreenCoords := ref.convertBaseToScreen(PointWindowCoords);
1119
1120 { Beware, it seems MacOsAll and CGGeometry both define CGPoint }
1121 CgPointScreenCoords := CGGeometry.CGPoint(
1122 //CGPointMake(PointScreenCoords.X, Application.ScreenHeight - PointScreenCoords.Y)
1123 NSPointToCGPoint(PointScreenCoords)
1124 );
1125
1126 { Seems that CGXxx function is the only way to do this:
1127 https://developer.apple.com/documentation/coregraphics/1456387-cgwarpmousecursorposition?language=objc }
1128 CGWarpMouseCursorPosition(CgPointScreenCoords);
1129
1130 Writeln('warping to ', CgPointScreenCoords.X:1:2, ' ', CgPointScreenCoords.Y:1:2);
1131 end;
1132 end;
1133 *)
1134
1135 procedure TCastleWindow.UpdateFullScreenBackend;
1136 begin
1137 if FFullScreenBackend <> FFullScreenWanted then
1138 begin
1139 if not Closed then
1140 begin
1141 if FFullScreenWanted then
1142 FullScreenBegin
1143 else
1144 FullScreenEnd;
1145 end else
1146 FFullScreenBackend := FFullScreenWanted;
1147 end;
1148 end;
1149
1150 procedure TCastleWindow.BackendInsideUpdate;
1151 begin
1152 end;
1153
1154 { TCocoaClipboard ----------------------------------------------------------- }
1155
1156 { Clipboard operations using Cocoa }
1157
1158 type
1159 TCocoaClipboard = class(TCastleClipboard)
1160 protected
1161 function GetAsText: String; override;
1162 procedure SetAsText(const Value: String); override;
1163 end;
1164
1165 function TCocoaClipboard.GetAsText: String;
1166 var
1167 Pasteboard: NSPasteboard;
1168 Text: NSString;
1169 begin
1170 Result := '';
1171
1172 Pasteboard := NSPasteboard.generalPasteboard;
1173 if Pasteboard <> nil then
1174 begin
1175 Text := Pasteboard.stringForType(NSPasteboardTypeString);
1176 if Text <> nil then
1177 Result := PChar(Text.UTF8String);
1178 end;
1179 end;
1180
1181 procedure TCocoaClipboard.SetAsText(const Value: String);
1182 var
1183 Pasteboard: NSPasteboard;
1184 begin
1185 Pasteboard := NSPasteboard.generalPasteboard;
1186 if Pasteboard <> nil then
1187 begin
1188 Pasteboard.clearContents;
1189 Pasteboard.setString_forType(NSSTR(Value), NSPasteboardTypeString);
1190 end;
1191 end;
1192
1193 { TCastleApplication ---------------------------------------------------------- }
1194
1195 procedure TCastleApplication.CreateBackend;
1196
1197 procedure SetupMainMenu;
1198
1199 procedure AddMenu(menu: NSMenu);
1200 var
1201 menuItem: NSMenuItem;
1202 begin
1203 menuItem := NSMenuItem.alloc.initWithTitle_action_keyEquivalent(menu.title, nil, NSSTR('')).autorelease;
1204 menuItem.setSubmenu(menu);
1205 NSApp.mainMenu.addItem(menuItem);
1206 end;
1207
1208 var
1209 mainMenu: NSMenu;
1210 appleMenu: NSMenu;
1211 //windowMenu: NSMenu;
1212 begin
1213 // main menu
1214 mainMenu := NSMenu.alloc.init.autorelease;
1215 NSApp.setMainMenu(mainMenu);
1216
1217 // apple menu
1218 appleMenu := NSMenu.alloc.initWithTitle(NSSTR('')).autorelease;
1219 appleMenu.addItemWithTitle_action_keyEquivalent(NSSTR('Quit ' + ApplicationName), objcselector('terminate:'), NSSTR('q'));
1220
1221 AddMenu(appleMenu);
1222
1223 { This is consistent with some Apple applications,
1224 but it would mix with TCastleWindow.MainMenu and be surprisingly uneditable for developer.
1225
1226 // window menu
1227 windowMenu := NSMenu.alloc.initWithTitle(NSSTR('Window')).autorelease;
1228 windowMenu.addItemWithTitle_action_keyEquivalent(NSSTR('Minimize'), objcselector('performMiniaturize:'), NSSTR('m'));
1229 windowMenu.addItemWithTitle_action_keyEquivalent(NSSTR('Zoom'), objcselector('performZoom:'), NSSTR(''));
1230
1231 AddMenu(windowMenu);
1232 }
1233 end;
1234
1235 var
1236 pool: NSAutoreleasePool;
1237 app: TCocoaApp;
1238 delegate: TCocoaAppDelegate;
1239 begin
1240 // https://hero.handmade.network/forums/code-discussion/t/1409-main_game_loop_on_os_x
1241
1242 pool := NSAutoreleasePool.alloc.init;
1243
1244 app := TCocoaApp(TCocoaApp.sharedApplication);
1245
1246 delegate := TCocoaAppDelegate.alloc.init;
1247 app.setDelegate(delegate);
1248
1249 RegisterClipboard(TCocoaClipboard.Create);
1250
1251 NSApp.setActivationPolicy(NSApplicationActivationPolicyRegular);
1252 NSApp.activateIgnoringOtherApps(true);
1253
1254 if NSApp.mainMenu = nil then
1255 SetupMainMenu;
1256 app.finishLaunching;
1257
1258 pool.release;
1259 end;
1260
1261 procedure TCastleApplication.DestroyBackend;
1262 begin
1263 // This is deprecated, and seems to do nothing for us, we call this when windows are already closed.
1264 // NSApp.terminate(nil);
1265 end;
1266
1267 function TCastleApplication.ProcessMessage(WaitForMessage, WaitToLimitFPS: boolean): boolean;
1268 begin
1269 if Terminated then Exit(false);
1270
1271 { TODO: honor WaitForMessage }
1272
1273 // note: do we really need to call on main thread? isn't the first thread "main"?
1274 //TCocoaApp(TCocoaApp.sharedApplication).poll;
1275 NSApp.performSelectorOnMainThread_withObject_waitUntilDone(objcselector('poll'), nil, true);
1276 if Terminated then Exit(false);
1277
1278 { TODO: UpdateAndRenderEverything should be called only if no message was in the queue.
1279
1280 This follows castlewindow_winsystem.inc approach, and works very good
1281 to prevent doing Update / Render when we're clogged with events
1282 (typically happens when walking with mouse look, then we're clogged
1283 with mouse move events). }
1284
1285 UpdateAndRenderEverything;
1286 Result := not Terminated;
1287
1288 { TODO:
1289 if (not WasAnyMessage) and
1290 (not Terminated) and
1291 (not WaitForMessage) and
1292 WaitToLimitFPS then
1293 DoLimitFPS;
1294 }
1295 end;
1296
1297 function TCastleApplication.ProcessAllMessages: boolean;
1298 begin
1299 { This implementation is valid for start: }
1300 Result := ProcessMessage(false, false);
1301
1302 { In general, ProcessAllMessages should make sure that all messages
1303 are handled, calling "ProcessMessage(false, false)" as long as some
1304 message exists in window system queue.
1305 Then it should call UpdateAndRenderEverything.
1306 See the GTK backend for example. }
1307 end;
1308
1309 procedure TCastleApplication.Run;
1310 begin
1311 if OpenWindowsCount = 0 then Exit;
1312
1313 { Implementing Run by calling ProcessMessage in a loop (like below)
1314 is a valid and good implementation. Make sure your ProcessMessage
1315 honours WaitForMessage and WaitToLimitFPS = true,
1316 to avoid wasting CPU on "busy waiting". }
1317 while ProcessMessage(true, true) do ;
1318 end;
1319
1320 procedure TCastleApplication.BackendTerminate;
1321 begin
1322 end;
1323
1324 function TCastleApplication.ScreenWidth: integer;
1325 var
1326 screenFrame: NSRect;
1327 begin
1328 screenFrame := NSScreen.mainScreen.frame;
1329 Result := trunc(NSMaxX(screenFrame)) - trunc(NSMinX(screenFrame));
1330 end;
1331
1332 function TCastleApplication.ScreenHeight: integer;
1333 var
1334 screenFrame: NSRect;
1335 begin
1336 screenFrame := NSScreen.mainScreen.frame;
1337 Result := trunc(NSMaxY(screenFrame)) - trunc(NSMinY(screenFrame));
1338 end;
1339
1340 function TCastleApplication.BackendName: String;
1341 begin
1342 Result := 'Cocoa';
1343 end;
1344
1345 { TWindowContainer ----------------------------------------------------------- }
1346
1347 function TWindowContainer.SettingMousePositionCausesMotion: Boolean;
1348 begin
1349 { You should check, using window_events example, what is the correct value
1350 (press "5", see if OnMotion is generated). }
1351 Result := true;
1352 end;
1353
1354 {$endif read_implementation}