os_osx.mm 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426
  1. /*************************************************************************/
  2. /* os_osx.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "os_osx.h"
  31. #include "dir_access_osx.h"
  32. #include "drivers/gles3/rasterizer_gles3.h"
  33. #include "main/main.h"
  34. #include "os/keyboard.h"
  35. #include "print_string.h"
  36. #include "sem_osx.h"
  37. #include "servers/visual/visual_server_raster.h"
  38. #include "version_generated.gen.h"
  39. #include <mach-o/dyld.h>
  40. #include <Carbon/Carbon.h>
  41. #import <Cocoa/Cocoa.h>
  42. #include <IOKit/IOCFPlugIn.h>
  43. #include <IOKit/IOKitLib.h>
  44. #include <IOKit/hid/IOHIDKeys.h>
  45. #include <IOKit/hid/IOHIDLib.h>
  46. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
  47. #include <os/log.h>
  48. #endif
  49. #include <dlfcn.h>
  50. #include <fcntl.h>
  51. #include <libproc.h>
  52. #include <stdio.h>
  53. #include <stdlib.h>
  54. #include <sys/stat.h>
  55. #include <sys/types.h>
  56. #include <unistd.h>
  57. #if MAC_OS_X_VERSION_MAX_ALLOWED < 101200
  58. #define NSEventMaskAny NSAnyEventMask
  59. #define NSEventTypeKeyDown NSKeyDown
  60. #define NSEventTypeKeyUp NSKeyUp
  61. #define NSEventModifierFlagShift NSShiftKeyMask
  62. #define NSEventModifierFlagCommand NSCommandKeyMask
  63. #define NSEventModifierFlagControl NSControlKeyMask
  64. #define NSEventModifierFlagOption NSAlternateKeyMask
  65. #define NSWindowStyleMaskTitled NSTitledWindowMask
  66. #define NSWindowStyleMaskResizable NSResizableWindowMask
  67. #define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
  68. #define NSWindowStyleMaskClosable NSClosableWindowMask
  69. #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
  70. #endif
  71. static NSRect convertRectToBacking(NSRect contentRect) {
  72. return [OS_OSX::singleton->window_view convertRectToBacking:contentRect];
  73. }
  74. static void get_key_modifier_state(unsigned int p_osx_state, Ref<InputEventWithModifiers> state) {
  75. state->set_shift((p_osx_state & NSEventModifierFlagShift));
  76. state->set_control((p_osx_state & NSEventModifierFlagControl));
  77. state->set_alt((p_osx_state & NSEventModifierFlagOption));
  78. state->set_metakey((p_osx_state & NSEventModifierFlagCommand));
  79. }
  80. static void push_to_key_event_buffer(const OS_OSX::KeyEvent &p_event) {
  81. Vector<OS_OSX::KeyEvent> &buffer = OS_OSX::singleton->key_event_buffer;
  82. if (OS_OSX::singleton->key_event_pos >= buffer.size()) {
  83. buffer.resize(1 + OS_OSX::singleton->key_event_pos);
  84. }
  85. buffer[OS_OSX::singleton->key_event_pos++] = p_event;
  86. }
  87. static int mouse_x = 0;
  88. static int mouse_y = 0;
  89. static int prev_mouse_x = 0;
  90. static int prev_mouse_y = 0;
  91. static int button_mask = 0;
  92. static bool mouse_down_control = false;
  93. static Vector2 get_mouse_pos(NSEvent *event) {
  94. const NSRect contentRect = [OS_OSX::singleton->window_view frame];
  95. const NSPoint p = [event locationInWindow];
  96. mouse_x = p.x * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
  97. mouse_y = (contentRect.size.height - p.y) * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
  98. return Vector2(mouse_x, mouse_y);
  99. }
  100. @interface GodotApplication : NSApplication
  101. @end
  102. @implementation GodotApplication
  103. - (void)sendEvent:(NSEvent *)event {
  104. // special case handling of command-period, which is traditionally a special
  105. // shortcut in macOS and doesn't arrive at our regular keyDown handler.
  106. if ([event type] == NSEventTypeKeyDown) {
  107. if (([event modifierFlags] & NSEventModifierFlagCommand) && [event keyCode] == 0x2f) {
  108. Ref<InputEventKey> k;
  109. k.instance();
  110. get_key_modifier_state([event modifierFlags], k);
  111. k->set_pressed(true);
  112. k->set_scancode(KEY_PERIOD);
  113. k->set_echo([event isARepeat]);
  114. OS_OSX::singleton->push_input(k);
  115. }
  116. }
  117. // From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
  118. // This works around an AppKit bug, where key up events while holding
  119. // down the command key don't get sent to the key window.
  120. if ([event type] == NSEventTypeKeyUp && ([event modifierFlags] & NSEventModifierFlagCommand))
  121. [[self keyWindow] sendEvent:event];
  122. else
  123. [super sendEvent:event];
  124. }
  125. @end
  126. @interface GodotApplicationDelegate : NSObject
  127. - (void)forceUnbundledWindowActivationHackStep1;
  128. - (void)forceUnbundledWindowActivationHackStep2;
  129. - (void)forceUnbundledWindowActivationHackStep3;
  130. @end
  131. @implementation GodotApplicationDelegate
  132. - (void)forceUnbundledWindowActivationHackStep1 {
  133. // Step1: Switch focus to macOS Dock.
  134. // Required to perform step 2, TransformProcessType will fail if app is already the in focus.
  135. for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.dock"]) {
  136. [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  137. break;
  138. }
  139. [self performSelector:@selector(forceUnbundledWindowActivationHackStep2) withObject:nil afterDelay:0.02];
  140. }
  141. - (void)forceUnbundledWindowActivationHackStep2 {
  142. // Step 2: Register app as foreground process.
  143. ProcessSerialNumber psn = { 0, kCurrentProcess };
  144. (void)TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  145. [self performSelector:@selector(forceUnbundledWindowActivationHackStep3) withObject:nil afterDelay:0.02];
  146. }
  147. - (void)forceUnbundledWindowActivationHackStep3 {
  148. // Step 3: Switch focus back to app window.
  149. [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  150. }
  151. - (void)applicationDidFinishLaunching:(NSNotification *)notice {
  152. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  153. if (nsappname == nil) {
  154. // If executable is not a bundled, macOS WindowServer won't register and activate app window correctly (menu and title bar are grayed out and input ignored).
  155. [self performSelector:@selector(forceUnbundledWindowActivationHackStep1) withObject:nil afterDelay:0.02];
  156. }
  157. }
  158. - (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
  159. // Note: called before main loop init!
  160. char *utfs = strdup([filename UTF8String]);
  161. OS_OSX::singleton->open_with_filename.parse_utf8(utfs);
  162. return YES;
  163. }
  164. - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
  165. if (OS_OSX::singleton->get_main_loop())
  166. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  167. return NSTerminateCancel;
  168. }
  169. - (void)applicationDidHide:(NSNotification *)notification {
  170. /*
  171. _Godotwindow* window;
  172. for (window = _Godot.windowListHead; window; window = window->next)
  173. _GodotInputWindowVisibility(window, GL_FALSE);
  174. */
  175. }
  176. - (void)applicationDidUnhide:(NSNotification *)notification {
  177. /*
  178. _Godotwindow* window;
  179. for (window = _Godot.windowListHead; window; window = window->next) {
  180. if ([window_object isVisible])
  181. _GodotInputWindowVisibility(window, GL_TRUE);
  182. }
  183. */
  184. }
  185. - (void)applicationDidChangeScreenParameters:(NSNotification *)notification {
  186. //_GodotInputMonitorChange();
  187. }
  188. - (void)showAbout:(id)sender {
  189. if (OS_OSX::singleton->get_main_loop())
  190. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_ABOUT);
  191. }
  192. @end
  193. @interface GodotWindowDelegate : NSObject {
  194. //_Godotwindow* window;
  195. }
  196. @end
  197. @implementation GodotWindowDelegate
  198. - (BOOL)windowShouldClose:(id)sender {
  199. //_GodotInputWindowCloseRequest(window);
  200. if (OS_OSX::singleton->get_main_loop())
  201. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  202. return NO;
  203. }
  204. - (void)windowDidEnterFullScreen:(NSNotification *)notification {
  205. OS_OSX::singleton->zoomed = true;
  206. }
  207. - (void)windowDidExitFullScreen:(NSNotification *)notification {
  208. OS_OSX::singleton->zoomed = false;
  209. }
  210. - (void)windowDidChangeBackingProperties:(NSNotification *)notification {
  211. if (!OS_OSX::singleton)
  212. return;
  213. NSWindow *window = (NSWindow *)[notification object];
  214. CGFloat newBackingScaleFactor = [window backingScaleFactor];
  215. CGFloat oldBackingScaleFactor = [[[notification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
  216. [OS_OSX::singleton->window_view setWantsBestResolutionOpenGLSurface:YES];
  217. if (newBackingScaleFactor != oldBackingScaleFactor) {
  218. //Set new display scale and window size
  219. float newDisplayScale = OS_OSX::singleton->is_hidpi_allowed() ? newBackingScaleFactor : 1.0;
  220. const NSRect contentRect = [OS_OSX::singleton->window_view frame];
  221. const NSRect fbRect = contentRect; //convertRectToBacking(contentRect);
  222. OS_OSX::singleton->window_size.width = fbRect.size.width * newDisplayScale;
  223. OS_OSX::singleton->window_size.height = fbRect.size.height * newDisplayScale;
  224. //Update context
  225. if (OS_OSX::singleton->main_loop) {
  226. [OS_OSX::singleton->context update];
  227. //Force window resize ???
  228. NSRect frame = [OS_OSX::singleton->window_object frame];
  229. [OS_OSX::singleton->window_object setFrame:NSMakeRect(frame.origin.x, frame.origin.y, 1, 1) display:YES];
  230. [OS_OSX::singleton->window_object setFrame:frame display:YES];
  231. }
  232. }
  233. }
  234. - (void)windowDidResize:(NSNotification *)notification {
  235. [OS_OSX::singleton->context update];
  236. const NSRect contentRect = [OS_OSX::singleton->window_view frame];
  237. const NSRect fbRect = contentRect; //convertRectToBacking(contentRect);
  238. float displayScale = OS_OSX::singleton->_display_scale();
  239. OS_OSX::singleton->window_size.width = fbRect.size.width * displayScale;
  240. OS_OSX::singleton->window_size.height = fbRect.size.height * displayScale;
  241. if (OS_OSX::singleton->main_loop) {
  242. Main::force_redraw();
  243. //Event retrieval blocks until resize is over. Call Main::iteration() directly.
  244. Main::iteration();
  245. }
  246. /*
  247. _GodotInputFramebufferSize(window, fbRect.size.width, fbRect.size.height);
  248. _GodotInputWindowSize(window, contentRect.size.width, contentRect.size.height);
  249. _GodotInputWindowDamage(window);
  250. if (window->cursorMode == Godot_CURSOR_DISABLED)
  251. centerCursor(window);
  252. */
  253. }
  254. - (void)windowDidMove:(NSNotification *)notification {
  255. /*
  256. [window->nsgl.context update];
  257. int x, y;
  258. _GodotPlatformGetWindowPos(window, &x, &y);
  259. _GodotInputWindowPos(window, x, y);
  260. if (window->cursorMode == Godot_CURSOR_DISABLED)
  261. centerCursor(window);
  262. */
  263. }
  264. - (void)windowDidBecomeKey:(NSNotification *)notification {
  265. //_GodotInputWindowFocus(window, GL_TRUE);
  266. //_GodotPlatformSetCursorMode(window, window->cursorMode);
  267. if (OS_OSX::singleton->get_main_loop())
  268. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  269. }
  270. - (void)windowDidResignKey:(NSNotification *)notification {
  271. //_GodotInputWindowFocus(window, GL_FALSE);
  272. //_GodotPlatformSetCursorMode(window, Godot_CURSOR_NORMAL);
  273. if (OS_OSX::singleton->get_main_loop())
  274. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  275. }
  276. - (void)windowDidMiniaturize:(NSNotification *)notification {
  277. OS_OSX::singleton->wm_minimized(true);
  278. if (OS_OSX::singleton->get_main_loop())
  279. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  280. };
  281. - (void)windowDidDeminiaturize:(NSNotification *)notification {
  282. OS_OSX::singleton->wm_minimized(false);
  283. if (OS_OSX::singleton->get_main_loop())
  284. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  285. };
  286. @end
  287. @interface GodotContentView : NSView <NSTextInputClient> {
  288. NSTrackingArea *trackingArea;
  289. NSMutableAttributedString *markedText;
  290. bool imeMode;
  291. }
  292. - (void)cancelComposition;
  293. @end
  294. @implementation GodotContentView
  295. + (void)initialize {
  296. if (self == [GodotContentView class]) {
  297. // nothing left to do here at the moment..
  298. }
  299. }
  300. - (id)init {
  301. self = [super init];
  302. trackingArea = nil;
  303. imeMode = false;
  304. [self updateTrackingAreas];
  305. [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
  306. markedText = [[NSMutableAttributedString alloc] init];
  307. return self;
  308. }
  309. - (void)dealloc {
  310. [trackingArea release];
  311. [markedText release];
  312. [super dealloc];
  313. }
  314. static const NSRange kEmptyRange = { NSNotFound, 0 };
  315. - (BOOL)hasMarkedText {
  316. return (markedText.length > 0);
  317. }
  318. - (NSRange)markedRange {
  319. return (markedText.length > 0) ? NSMakeRange(0, markedText.length - 1) : kEmptyRange;
  320. }
  321. - (NSRange)selectedRange {
  322. return kEmptyRange;
  323. }
  324. - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange {
  325. if ([aString isKindOfClass:[NSAttributedString class]]) {
  326. [markedText initWithAttributedString:aString];
  327. } else {
  328. [markedText initWithString:aString];
  329. }
  330. if (OS_OSX::singleton->im_callback) {
  331. imeMode = true;
  332. String ret;
  333. ret.parse_utf8([[markedText mutableString] UTF8String]);
  334. OS_OSX::singleton->im_callback(OS_OSX::singleton->im_target, ret, Point2(selectedRange.location, selectedRange.length));
  335. }
  336. }
  337. - (void)doCommandBySelector:(SEL)aSelector {
  338. if ([self respondsToSelector:aSelector])
  339. [self performSelector:aSelector];
  340. }
  341. - (void)unmarkText {
  342. imeMode = false;
  343. [[markedText mutableString] setString:@""];
  344. if (OS_OSX::singleton->im_callback)
  345. OS_OSX::singleton->im_callback(OS_OSX::singleton->im_target, "", Point2());
  346. }
  347. - (NSArray *)validAttributesForMarkedText {
  348. return [NSArray array];
  349. }
  350. - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
  351. return nil;
  352. }
  353. - (NSUInteger)characterIndexForPoint:(NSPoint)aPoint {
  354. return 0;
  355. }
  356. - (NSRect)firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange {
  357. const NSRect contentRect = [OS_OSX::singleton->window_view frame];
  358. float displayScale = OS_OSX::singleton->_display_scale();
  359. NSRect pointInWindowRect = NSMakeRect(OS_OSX::singleton->im_position.x / displayScale, contentRect.size.height - (OS_OSX::singleton->im_position.y / displayScale) - 1, 0, 0);
  360. NSPoint pointOnScreen = [[OS_OSX::singleton->window_view window] convertRectToScreen:pointInWindowRect].origin;
  361. return NSMakeRect(pointOnScreen.x, pointOnScreen.y, 0, 0);
  362. }
  363. - (void)cancelComposition {
  364. [self unmarkText];
  365. NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
  366. [currentInputContext discardMarkedText];
  367. }
  368. - (void)insertText:(id)aString {
  369. [self insertText:aString replacementRange:NSMakeRange(0, 0)];
  370. }
  371. - (void)insertText:(id)aString replacementRange:(NSRange)replacementRange {
  372. NSEvent *event = [NSApp currentEvent];
  373. NSString *characters;
  374. if ([aString isKindOfClass:[NSAttributedString class]]) {
  375. characters = [aString string];
  376. } else {
  377. characters = (NSString *)aString;
  378. }
  379. NSUInteger i, length = [characters length];
  380. NSCharacterSet *ctrlChars = [NSCharacterSet controlCharacterSet];
  381. NSCharacterSet *wsnlChars = [NSCharacterSet whitespaceAndNewlineCharacterSet];
  382. if ([characters rangeOfCharacterFromSet:ctrlChars].length && [characters rangeOfCharacterFromSet:wsnlChars].length == 0) {
  383. NSTextInputContext *currentInputContext = [NSTextInputContext currentInputContext];
  384. [currentInputContext discardMarkedText];
  385. [self cancelComposition];
  386. return;
  387. }
  388. for (i = 0; i < length; i++) {
  389. const unichar codepoint = [characters characterAtIndex:i];
  390. if ((codepoint & 0xFF00) == 0xF700)
  391. continue;
  392. OS_OSX::KeyEvent ke;
  393. ke.osx_state = [event modifierFlags];
  394. ke.pressed = true;
  395. ke.echo = false;
  396. ke.scancode = 0;
  397. ke.unicode = codepoint;
  398. push_to_key_event_buffer(ke);
  399. }
  400. [self cancelComposition];
  401. }
  402. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  403. return NSDragOperationCopy;
  404. }
  405. - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
  406. return NSDragOperationCopy;
  407. }
  408. - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  409. NSPasteboard *pboard = [sender draggingPasteboard];
  410. NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
  411. Vector<String> files;
  412. for (int i = 0; i < filenames.count; i++) {
  413. NSString *ns = [filenames objectAtIndex:i];
  414. char *utfs = strdup([ns UTF8String]);
  415. String ret;
  416. ret.parse_utf8(utfs);
  417. free(utfs);
  418. files.push_back(ret);
  419. }
  420. if (files.size()) {
  421. OS_OSX::singleton->main_loop->drop_files(files, 0);
  422. OS_OSX::singleton->move_window_to_foreground();
  423. }
  424. return NO;
  425. }
  426. - (BOOL)isOpaque {
  427. return YES;
  428. }
  429. - (BOOL)canBecomeKeyView {
  430. return YES;
  431. }
  432. - (BOOL)acceptsFirstResponder {
  433. return YES;
  434. }
  435. - (void)cursorUpdate:(NSEvent *)event {
  436. OS::CursorShape p_shape = OS_OSX::singleton->cursor_shape;
  437. OS_OSX::singleton->cursor_shape = OS::CURSOR_MAX;
  438. OS_OSX::singleton->set_cursor_shape(p_shape);
  439. }
  440. static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) {
  441. if (pressed) {
  442. button_mask |= mask;
  443. } else {
  444. button_mask &= ~mask;
  445. }
  446. Ref<InputEventMouseButton> mb;
  447. mb.instance();
  448. get_key_modifier_state([event modifierFlags], mb);
  449. mb->set_button_index(index);
  450. mb->set_pressed(pressed);
  451. mb->set_position(Vector2(mouse_x, mouse_y));
  452. mb->set_global_position(Vector2(mouse_x, mouse_y));
  453. mb->set_button_mask(button_mask);
  454. if (index == BUTTON_LEFT && pressed) {
  455. mb->set_doubleclick([event clickCount] == 2);
  456. }
  457. OS_OSX::singleton->push_input(mb);
  458. }
  459. - (void)mouseDown:(NSEvent *)event {
  460. if (([event modifierFlags] & NSEventModifierFlagControl)) {
  461. mouse_down_control = true;
  462. _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, true);
  463. } else {
  464. mouse_down_control = false;
  465. _mouseDownEvent(event, BUTTON_LEFT, BUTTON_MASK_LEFT, true);
  466. }
  467. }
  468. - (void)mouseDragged:(NSEvent *)event {
  469. [self mouseMoved:event];
  470. }
  471. - (void)mouseUp:(NSEvent *)event {
  472. if (mouse_down_control) {
  473. _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, false);
  474. } else {
  475. _mouseDownEvent(event, BUTTON_LEFT, BUTTON_MASK_LEFT, false);
  476. }
  477. }
  478. - (void)mouseMoved:(NSEvent *)event {
  479. Ref<InputEventMouseMotion> mm;
  480. mm.instance();
  481. mm->set_button_mask(button_mask);
  482. prev_mouse_x = mouse_x;
  483. prev_mouse_y = mouse_y;
  484. const Vector2 pos = get_mouse_pos(event);
  485. mm->set_position(pos);
  486. mm->set_global_position(pos);
  487. Vector2 relativeMotion = Vector2();
  488. relativeMotion.x = [event deltaX] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
  489. relativeMotion.y = [event deltaY] * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
  490. mm->set_relative(relativeMotion);
  491. get_key_modifier_state([event modifierFlags], mm);
  492. OS_OSX::singleton->input->set_mouse_position(Point2(mouse_x, mouse_y));
  493. OS_OSX::singleton->push_input(mm);
  494. }
  495. - (void)rightMouseDown:(NSEvent *)event {
  496. _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, true);
  497. }
  498. - (void)rightMouseDragged:(NSEvent *)event {
  499. [self mouseMoved:event];
  500. }
  501. - (void)rightMouseUp:(NSEvent *)event {
  502. _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, false);
  503. }
  504. - (void)otherMouseDown:(NSEvent *)event {
  505. if ((int)[event buttonNumber] != 2)
  506. return;
  507. _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, true);
  508. }
  509. - (void)otherMouseDragged:(NSEvent *)event {
  510. [self mouseMoved:event];
  511. }
  512. - (void)otherMouseUp:(NSEvent *)event {
  513. if ((int)[event buttonNumber] != 2)
  514. return;
  515. _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, false);
  516. }
  517. - (void)mouseExited:(NSEvent *)event {
  518. if (!OS_OSX::singleton)
  519. return;
  520. if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
  521. OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
  522. if (OS_OSX::singleton->input)
  523. OS_OSX::singleton->input->set_mouse_in_window(false);
  524. }
  525. - (void)mouseEntered:(NSEvent *)event {
  526. if (!OS_OSX::singleton)
  527. return;
  528. if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
  529. OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
  530. if (OS_OSX::singleton->input)
  531. OS_OSX::singleton->input->set_mouse_in_window(true);
  532. OS::CursorShape p_shape = OS_OSX::singleton->cursor_shape;
  533. OS_OSX::singleton->cursor_shape = OS::CURSOR_MAX;
  534. OS_OSX::singleton->set_cursor_shape(p_shape);
  535. }
  536. - (void)magnifyWithEvent:(NSEvent *)event {
  537. Ref<InputEventMagnifyGesture> ev;
  538. ev.instance();
  539. get_key_modifier_state([event modifierFlags], ev);
  540. ev->set_position(get_mouse_pos(event));
  541. ev->set_factor([event magnification] + 1.0);
  542. OS_OSX::singleton->push_input(ev);
  543. }
  544. - (void)viewDidChangeBackingProperties {
  545. // nothing left to do here
  546. }
  547. - (void)updateTrackingAreas {
  548. if (trackingArea != nil) {
  549. [self removeTrackingArea:trackingArea];
  550. [trackingArea release];
  551. }
  552. NSTrackingAreaOptions options =
  553. NSTrackingMouseEnteredAndExited |
  554. NSTrackingActiveInKeyWindow |
  555. NSTrackingCursorUpdate |
  556. NSTrackingInVisibleRect;
  557. trackingArea = [[NSTrackingArea alloc]
  558. initWithRect:[self bounds]
  559. options:options
  560. owner:self
  561. userInfo:nil];
  562. [self addTrackingArea:trackingArea];
  563. [super updateTrackingAreas];
  564. }
  565. // Translates a OS X keycode to a Godot keycode
  566. //
  567. static int translateKey(unsigned int key) {
  568. // Keyboard symbol translation table
  569. static const unsigned int table[128] = {
  570. /* 00 */ KEY_A,
  571. /* 01 */ KEY_S,
  572. /* 02 */ KEY_D,
  573. /* 03 */ KEY_F,
  574. /* 04 */ KEY_H,
  575. /* 05 */ KEY_G,
  576. /* 06 */ KEY_Z,
  577. /* 07 */ KEY_X,
  578. /* 08 */ KEY_C,
  579. /* 09 */ KEY_V,
  580. /* 0a */ KEY_UNKNOWN,
  581. /* 0b */ KEY_B,
  582. /* 0c */ KEY_Q,
  583. /* 0d */ KEY_W,
  584. /* 0e */ KEY_E,
  585. /* 0f */ KEY_R,
  586. /* 10 */ KEY_Y,
  587. /* 11 */ KEY_T,
  588. /* 12 */ KEY_1,
  589. /* 13 */ KEY_2,
  590. /* 14 */ KEY_3,
  591. /* 15 */ KEY_4,
  592. /* 16 */ KEY_6,
  593. /* 17 */ KEY_5,
  594. /* 18 */ KEY_EQUAL,
  595. /* 19 */ KEY_9,
  596. /* 1a */ KEY_7,
  597. /* 1b */ KEY_MINUS,
  598. /* 1c */ KEY_8,
  599. /* 1d */ KEY_0,
  600. /* 1e */ KEY_BRACERIGHT,
  601. /* 1f */ KEY_O,
  602. /* 20 */ KEY_U,
  603. /* 21 */ KEY_BRACELEFT,
  604. /* 22 */ KEY_I,
  605. /* 23 */ KEY_P,
  606. /* 24 */ KEY_ENTER,
  607. /* 25 */ KEY_L,
  608. /* 26 */ KEY_J,
  609. /* 27 */ KEY_APOSTROPHE,
  610. /* 28 */ KEY_K,
  611. /* 29 */ KEY_SEMICOLON,
  612. /* 2a */ KEY_BACKSLASH,
  613. /* 2b */ KEY_COMMA,
  614. /* 2c */ KEY_SLASH,
  615. /* 2d */ KEY_N,
  616. /* 2e */ KEY_M,
  617. /* 2f */ KEY_PERIOD,
  618. /* 30 */ KEY_TAB,
  619. /* 31 */ KEY_SPACE,
  620. /* 32 */ KEY_QUOTELEFT,
  621. /* 33 */ KEY_BACKSPACE,
  622. /* 34 */ KEY_UNKNOWN,
  623. /* 35 */ KEY_ESCAPE,
  624. /* 36 */ KEY_META,
  625. /* 37 */ KEY_META,
  626. /* 38 */ KEY_SHIFT,
  627. /* 39 */ KEY_CAPSLOCK,
  628. /* 3a */ KEY_ALT,
  629. /* 3b */ KEY_CONTROL,
  630. /* 3c */ KEY_SHIFT,
  631. /* 3d */ KEY_ALT,
  632. /* 3e */ KEY_CONTROL,
  633. /* 3f */ KEY_UNKNOWN, /* Function */
  634. /* 40 */ KEY_UNKNOWN,
  635. /* 41 */ KEY_KP_PERIOD,
  636. /* 42 */ KEY_UNKNOWN,
  637. /* 43 */ KEY_KP_MULTIPLY,
  638. /* 44 */ KEY_UNKNOWN,
  639. /* 45 */ KEY_KP_ADD,
  640. /* 46 */ KEY_UNKNOWN,
  641. /* 47 */ KEY_NUMLOCK, /* Really KeypadClear... */
  642. /* 48 */ KEY_UNKNOWN, /* VolumeUp */
  643. /* 49 */ KEY_UNKNOWN, /* VolumeDown */
  644. /* 4a */ KEY_UNKNOWN, /* Mute */
  645. /* 4b */ KEY_KP_DIVIDE,
  646. /* 4c */ KEY_KP_ENTER,
  647. /* 4d */ KEY_UNKNOWN,
  648. /* 4e */ KEY_KP_SUBTRACT,
  649. /* 4f */ KEY_UNKNOWN,
  650. /* 50 */ KEY_UNKNOWN,
  651. /* 51 */ KEY_EQUAL, //wtf equal?
  652. /* 52 */ KEY_KP_0,
  653. /* 53 */ KEY_KP_1,
  654. /* 54 */ KEY_KP_2,
  655. /* 55 */ KEY_KP_3,
  656. /* 56 */ KEY_KP_4,
  657. /* 57 */ KEY_KP_5,
  658. /* 58 */ KEY_KP_6,
  659. /* 59 */ KEY_KP_7,
  660. /* 5a */ KEY_UNKNOWN,
  661. /* 5b */ KEY_KP_8,
  662. /* 5c */ KEY_KP_9,
  663. /* 5d */ KEY_UNKNOWN,
  664. /* 5e */ KEY_UNKNOWN,
  665. /* 5f */ KEY_UNKNOWN,
  666. /* 60 */ KEY_F5,
  667. /* 61 */ KEY_F6,
  668. /* 62 */ KEY_F7,
  669. /* 63 */ KEY_F3,
  670. /* 64 */ KEY_F8,
  671. /* 65 */ KEY_F9,
  672. /* 66 */ KEY_UNKNOWN,
  673. /* 67 */ KEY_F11,
  674. /* 68 */ KEY_UNKNOWN,
  675. /* 69 */ KEY_F13,
  676. /* 6a */ KEY_F16,
  677. /* 6b */ KEY_F14,
  678. /* 6c */ KEY_UNKNOWN,
  679. /* 6d */ KEY_F10,
  680. /* 6e */ KEY_UNKNOWN,
  681. /* 6f */ KEY_F12,
  682. /* 70 */ KEY_UNKNOWN,
  683. /* 71 */ KEY_F15,
  684. /* 72 */ KEY_INSERT, /* Really Help... */
  685. /* 73 */ KEY_HOME,
  686. /* 74 */ KEY_PAGEUP,
  687. /* 75 */ KEY_DELETE,
  688. /* 76 */ KEY_F4,
  689. /* 77 */ KEY_END,
  690. /* 78 */ KEY_F2,
  691. /* 79 */ KEY_PAGEDOWN,
  692. /* 7a */ KEY_F1,
  693. /* 7b */ KEY_LEFT,
  694. /* 7c */ KEY_RIGHT,
  695. /* 7d */ KEY_DOWN,
  696. /* 7e */ KEY_UP,
  697. /* 7f */ KEY_UNKNOWN,
  698. };
  699. if (key >= 128)
  700. return KEY_UNKNOWN;
  701. return table[key];
  702. }
  703. - (void)keyDown:(NSEvent *)event {
  704. //disable raw input in IME mode
  705. if (!imeMode) {
  706. OS_OSX::KeyEvent ke;
  707. ke.osx_state = [event modifierFlags];
  708. ke.pressed = true;
  709. ke.echo = [event isARepeat];
  710. ke.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode]));
  711. ke.unicode = 0;
  712. push_to_key_event_buffer(ke);
  713. }
  714. if ((OS_OSX::singleton->im_position.x != 0) && (OS_OSX::singleton->im_position.y != 0))
  715. [self interpretKeyEvents:[NSArray arrayWithObject:event]];
  716. }
  717. - (void)flagsChanged:(NSEvent *)event {
  718. if (!imeMode) {
  719. OS_OSX::KeyEvent ke;
  720. ke.echo = false;
  721. int key = [event keyCode];
  722. int mod = [event modifierFlags];
  723. if (key == 0x36 || key == 0x37) {
  724. if (mod & NSEventModifierFlagCommand) {
  725. mod &= ~NSEventModifierFlagCommand;
  726. ke.pressed = true;
  727. } else {
  728. ke.pressed = false;
  729. }
  730. } else if (key == 0x38 || key == 0x3c) {
  731. if (mod & NSEventModifierFlagShift) {
  732. mod &= ~NSEventModifierFlagShift;
  733. ke.pressed = true;
  734. } else {
  735. ke.pressed = false;
  736. }
  737. } else if (key == 0x3a || key == 0x3d) {
  738. if (mod & NSEventModifierFlagOption) {
  739. mod &= ~NSEventModifierFlagOption;
  740. ke.pressed = true;
  741. } else {
  742. ke.pressed = false;
  743. }
  744. } else if (key == 0x3b || key == 0x3e) {
  745. if (mod & NSEventModifierFlagControl) {
  746. mod &= ~NSEventModifierFlagControl;
  747. ke.pressed = true;
  748. } else {
  749. ke.pressed = false;
  750. }
  751. } else {
  752. return;
  753. }
  754. ke.osx_state = mod;
  755. ke.scancode = latin_keyboard_keycode_convert(translateKey(key));
  756. ke.unicode = 0;
  757. push_to_key_event_buffer(ke);
  758. }
  759. }
  760. - (void)keyUp:(NSEvent *)event {
  761. if (!imeMode) {
  762. OS_OSX::KeyEvent ke;
  763. ke.osx_state = [event modifierFlags];
  764. ke.pressed = false;
  765. ke.echo = false;
  766. ke.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode]));
  767. ke.unicode = 0;
  768. push_to_key_event_buffer(ke);
  769. }
  770. }
  771. inline void sendScrollEvent(int button, double factor, int modifierFlags) {
  772. Ref<InputEventMouseButton> sc;
  773. sc.instance();
  774. get_key_modifier_state(modifierFlags, sc);
  775. sc->set_button_index(button);
  776. sc->set_factor(factor);
  777. sc->set_pressed(true);
  778. Vector2 mouse_pos = Vector2(mouse_x, mouse_y);
  779. sc->set_position(mouse_pos);
  780. sc->set_global_position(mouse_pos);
  781. sc->set_button_mask(button_mask);
  782. OS_OSX::singleton->push_input(sc);
  783. sc->set_pressed(false);
  784. OS_OSX::singleton->push_input(sc);
  785. }
  786. inline void sendPanEvent(double dx, double dy, int modifierFlags) {
  787. Ref<InputEventPanGesture> pg;
  788. pg.instance();
  789. get_key_modifier_state(modifierFlags, pg);
  790. Vector2 mouse_pos = Vector2(mouse_x, mouse_y);
  791. pg->set_position(mouse_pos);
  792. pg->set_delta(Vector2(-dx, -dy));
  793. OS_OSX::singleton->push_input(pg);
  794. }
  795. - (void)scrollWheel:(NSEvent *)event {
  796. double deltaX, deltaY;
  797. deltaX = [event scrollingDeltaX];
  798. deltaY = [event scrollingDeltaY];
  799. if ([event hasPreciseScrollingDeltas]) {
  800. deltaX *= 0.03;
  801. deltaY *= 0.03;
  802. }
  803. if ([event phase] != NSEventPhaseNone || [event momentumPhase] != NSEventPhaseNone) {
  804. sendPanEvent(deltaX, deltaY, [event modifierFlags]);
  805. } else {
  806. if (fabs(deltaX)) {
  807. sendScrollEvent(0 > deltaX ? BUTTON_WHEEL_RIGHT : BUTTON_WHEEL_LEFT, fabs(deltaX * 0.3), [event modifierFlags]);
  808. }
  809. if (fabs(deltaY)) {
  810. sendScrollEvent(0 < deltaY ? BUTTON_WHEEL_UP : BUTTON_WHEEL_DOWN, fabs(deltaY * 0.3), [event modifierFlags]);
  811. }
  812. }
  813. }
  814. @end
  815. @interface GodotWindow : NSWindow {
  816. }
  817. @end
  818. @implementation GodotWindow
  819. - (BOOL)canBecomeKeyWindow {
  820. // Required for NSBorderlessWindowMask windows
  821. return YES;
  822. }
  823. @end
  824. void OS_OSX::set_ime_intermediate_text_callback(ImeCallback p_callback, void *p_inp) {
  825. im_callback = p_callback;
  826. im_target = p_inp;
  827. if (!im_callback) {
  828. [window_view cancelComposition];
  829. }
  830. }
  831. void OS_OSX::set_ime_position(const Point2 &p_pos) {
  832. im_position = p_pos;
  833. }
  834. int OS_OSX::get_video_driver_count() const {
  835. return 1;
  836. }
  837. const char *OS_OSX::get_video_driver_name(int p_driver) const {
  838. return "GLES3";
  839. }
  840. void OS_OSX::initialize_core() {
  841. crash_handler.initialize();
  842. OS_Unix::initialize_core();
  843. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_RESOURCES);
  844. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_USERDATA);
  845. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_FILESYSTEM);
  846. SemaphoreOSX::make_default();
  847. }
  848. static bool keyboard_layout_dirty = true;
  849. static void keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info) {
  850. keyboard_layout_dirty = true;
  851. }
  852. static bool displays_arrangement_dirty = true;
  853. static void displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info) {
  854. displays_arrangement_dirty = true;
  855. }
  856. Error OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  857. /*** OSX INITIALIZATION ***/
  858. /*** OSX INITIALIZATION ***/
  859. /*** OSX INITIALIZATION ***/
  860. keyboard_layout_dirty = true;
  861. displays_arrangement_dirty = true;
  862. // Register to be notified on keyboard layout changes
  863. CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
  864. NULL, keyboard_layout_changed,
  865. kTISNotifySelectedKeyboardInputSourceChanged, NULL,
  866. CFNotificationSuspensionBehaviorDeliverImmediately);
  867. // Register to be notified on displays arrangement changes
  868. CGDisplayRegisterReconfigurationCallback(displays_arrangement_changed, NULL);
  869. window_delegate = [[GodotWindowDelegate alloc] init];
  870. // Don't use accumulation buffer support; it's not accelerated
  871. // Aux buffers probably aren't accelerated either
  872. unsigned int styleMask;
  873. if (p_desired.borderless_window) {
  874. styleMask = NSWindowStyleMaskBorderless;
  875. } else {
  876. styleMask = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | (p_desired.resizable ? NSWindowStyleMaskResizable : 0);
  877. }
  878. window_object = [[GodotWindow alloc]
  879. initWithContentRect:NSMakeRect(0, 0, p_desired.width, p_desired.height)
  880. styleMask:styleMask
  881. backing:NSBackingStoreBuffered
  882. defer:NO];
  883. ERR_FAIL_COND_V(window_object == nil, ERR_UNAVAILABLE);
  884. window_view = [[GodotContentView alloc] init];
  885. float displayScale = 1.0;
  886. if (is_hidpi_allowed()) {
  887. // note that mainScreen is not screen #0 but the one with the keyboard focus.
  888. NSScreen *screen = [NSScreen mainScreen];
  889. if ([screen respondsToSelector:@selector(backingScaleFactor)]) {
  890. displayScale = fmax(displayScale, [screen backingScaleFactor]);
  891. }
  892. }
  893. window_size.width = p_desired.width * displayScale;
  894. window_size.height = p_desired.height * displayScale;
  895. if (displayScale > 1.0) {
  896. [window_view setWantsBestResolutionOpenGLSurface:YES];
  897. //if (current_videomode.resizable)
  898. [window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  899. }
  900. //[window_object setTitle:[NSString stringWithUTF8String:"GodotEnginies"]];
  901. [window_object setContentView:window_view];
  902. [window_object setDelegate:window_delegate];
  903. [window_object setAcceptsMouseMovedEvents:YES];
  904. [window_object center];
  905. [window_object setRestorable:NO];
  906. unsigned int attributeCount = 0;
  907. // OS X needs non-zero color size, so set reasonable values
  908. int colorBits = 32;
  909. // Fail if a robustness strategy was requested
  910. #define ADD_ATTR(x) \
  911. { attributes[attributeCount++] = x; }
  912. #define ADD_ATTR2(x, y) \
  913. { \
  914. ADD_ATTR(x); \
  915. ADD_ATTR(y); \
  916. }
  917. // Arbitrary array size here
  918. NSOpenGLPixelFormatAttribute attributes[40];
  919. ADD_ATTR(NSOpenGLPFADoubleBuffer);
  920. ADD_ATTR(NSOpenGLPFAClosestPolicy);
  921. //we now need OpenGL 3 or better, maybe even change this to 3_3Core ?
  922. ADD_ATTR2(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core);
  923. ADD_ATTR2(NSOpenGLPFAColorSize, colorBits);
  924. /*
  925. if (fbconfig->alphaBits > 0)
  926. ADD_ATTR2(NSOpenGLPFAAlphaSize, fbconfig->alphaBits);
  927. */
  928. ADD_ATTR2(NSOpenGLPFADepthSize, 24);
  929. ADD_ATTR2(NSOpenGLPFAStencilSize, 8);
  930. /*
  931. if (fbconfig->stereo)
  932. ADD_ATTR(NSOpenGLPFAStereo);
  933. */
  934. /*
  935. if (fbconfig->samples > 0) {
  936. ADD_ATTR2(NSOpenGLPFASampleBuffers, 1);
  937. ADD_ATTR2(NSOpenGLPFASamples, fbconfig->samples);
  938. }
  939. */
  940. // NOTE: All NSOpenGLPixelFormats on the relevant cards support sRGB
  941. // framebuffer, so there's no need (and no way) to request it
  942. ADD_ATTR(0);
  943. #undef ADD_ATTR
  944. #undef ADD_ATTR2
  945. pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
  946. ERR_FAIL_COND_V(pixelFormat == nil, ERR_UNAVAILABLE);
  947. context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
  948. ERR_FAIL_COND_V(context == nil, ERR_UNAVAILABLE);
  949. [context setView:window_view];
  950. [context makeCurrentContext];
  951. set_use_vsync(p_desired.use_vsync);
  952. [NSApp activateIgnoringOtherApps:YES];
  953. _update_window();
  954. [window_object makeKeyAndOrderFront:nil];
  955. if (p_desired.fullscreen)
  956. zoomed = true;
  957. /*** END OSX INITIALIZATION ***/
  958. bool use_gl2 = p_video_driver != 1;
  959. AudioDriverManager::add_driver(&audio_driver);
  960. // only opengl support here...
  961. RasterizerGLES3::register_config();
  962. RasterizerGLES3::make_current();
  963. visual_server = memnew(VisualServerRaster);
  964. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  965. visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
  966. }
  967. visual_server->init();
  968. AudioDriverManager::initialize(p_audio_driver);
  969. input = memnew(InputDefault);
  970. joypad_osx = memnew(JoypadOSX);
  971. power_manager = memnew(power_osx);
  972. _ensure_user_data_dir();
  973. restore_rect = Rect2(get_window_position(), get_window_size());
  974. return OK;
  975. }
  976. void OS_OSX::finalize() {
  977. CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL);
  978. CGDisplayRemoveReconfigurationCallback(displays_arrangement_changed, NULL);
  979. delete_main_loop();
  980. memdelete(joypad_osx);
  981. memdelete(input);
  982. visual_server->finish();
  983. memdelete(visual_server);
  984. //memdelete(rasterizer);
  985. }
  986. void OS_OSX::set_main_loop(MainLoop *p_main_loop) {
  987. main_loop = p_main_loop;
  988. input->set_main_loop(p_main_loop);
  989. }
  990. void OS_OSX::delete_main_loop() {
  991. if (!main_loop)
  992. return;
  993. memdelete(main_loop);
  994. main_loop = NULL;
  995. }
  996. String OS_OSX::get_name() {
  997. return "OSX";
  998. }
  999. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
  1000. class OSXTerminalLogger : public StdLogger {
  1001. public:
  1002. virtual void log_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type = ERR_ERROR) {
  1003. if (!should_log(true)) {
  1004. return;
  1005. }
  1006. const char *err_details;
  1007. if (p_rationale && p_rationale[0])
  1008. err_details = p_rationale;
  1009. else
  1010. err_details = p_code;
  1011. switch (p_type) {
  1012. case ERR_WARNING:
  1013. if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_12) {
  1014. os_log_info(OS_LOG_DEFAULT,
  1015. "WARNING: %{public}s: %{public}s\nAt: %{public}s:%i.",
  1016. p_function, err_details, p_file, p_line);
  1017. }
  1018. logf_error("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n", p_function,
  1019. err_details);
  1020. logf_error("\E[0;33m At: %s:%i.\E[0m\n", p_file, p_line);
  1021. break;
  1022. case ERR_SCRIPT:
  1023. if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_12) {
  1024. os_log_error(OS_LOG_DEFAULT,
  1025. "SCRIPT ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
  1026. p_function, err_details, p_file, p_line);
  1027. }
  1028. logf_error("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n", p_function,
  1029. err_details);
  1030. logf_error("\E[0;35m At: %s:%i.\E[0m\n", p_file, p_line);
  1031. break;
  1032. case ERR_SHADER:
  1033. if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_12) {
  1034. os_log_error(OS_LOG_DEFAULT,
  1035. "SHADER ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
  1036. p_function, err_details, p_file, p_line);
  1037. }
  1038. logf_error("\E[1;36mSHADER ERROR: %s: \E[0m\E[1m%s\n", p_function,
  1039. err_details);
  1040. logf_error("\E[0;36m At: %s:%i.\E[0m\n", p_file, p_line);
  1041. break;
  1042. case ERR_ERROR:
  1043. default:
  1044. if (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_12) {
  1045. os_log_error(OS_LOG_DEFAULT,
  1046. "ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.",
  1047. p_function, err_details, p_file, p_line);
  1048. }
  1049. logf_error("\E[1;31mERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  1050. logf_error("\E[0;31m At: %s:%i.\E[0m\n", p_file, p_line);
  1051. break;
  1052. }
  1053. }
  1054. };
  1055. #else
  1056. typedef UnixTerminalLogger OSXTerminalLogger;
  1057. #endif
  1058. void OS_OSX::alert(const String &p_alert, const String &p_title) {
  1059. // Set OS X-compliant variables
  1060. NSAlert *window = [[NSAlert alloc] init];
  1061. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  1062. NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
  1063. [window addButtonWithTitle:@"OK"];
  1064. [window setMessageText:ns_title];
  1065. [window setInformativeText:ns_alert];
  1066. [window setAlertStyle:NSWarningAlertStyle];
  1067. // Display it, then release
  1068. [window runModal];
  1069. [window release];
  1070. }
  1071. Error OS_OSX::open_dynamic_library(const String p_path, void *&p_library_handle, bool p_also_set_library_path) {
  1072. String path = p_path;
  1073. if (!FileAccess::exists(path)) {
  1074. //this code exists so gdnative can load .dylib files from within the executable path
  1075. path = get_executable_path().get_base_dir().plus_file(p_path.get_file());
  1076. }
  1077. if (!FileAccess::exists(path)) {
  1078. //this code exists so gdnative can load .dylib files from a standard macOS location
  1079. path = get_executable_path().get_base_dir().plus_file("../Frameworks").plus_file(p_path.get_file());
  1080. }
  1081. p_library_handle = dlopen(path.utf8().get_data(), RTLD_NOW);
  1082. if (!p_library_handle) {
  1083. ERR_EXPLAIN("Can't open dynamic library: " + p_path + ". Error: " + dlerror());
  1084. ERR_FAIL_V(ERR_CANT_OPEN);
  1085. }
  1086. return OK;
  1087. }
  1088. void OS_OSX::set_cursor_shape(CursorShape p_shape) {
  1089. if (cursor_shape == p_shape)
  1090. return;
  1091. if (cursors[p_shape] != NULL) {
  1092. [cursors[p_shape] set];
  1093. } else {
  1094. switch (p_shape) {
  1095. case CURSOR_ARROW: [[NSCursor arrowCursor] set]; break;
  1096. case CURSOR_IBEAM: [[NSCursor IBeamCursor] set]; break;
  1097. case CURSOR_POINTING_HAND: [[NSCursor pointingHandCursor] set]; break;
  1098. case CURSOR_CROSS: [[NSCursor crosshairCursor] set]; break;
  1099. case CURSOR_WAIT: [[NSCursor arrowCursor] set]; break;
  1100. case CURSOR_BUSY: [[NSCursor arrowCursor] set]; break;
  1101. case CURSOR_DRAG: [[NSCursor closedHandCursor] set]; break;
  1102. case CURSOR_CAN_DROP: [[NSCursor openHandCursor] set]; break;
  1103. case CURSOR_FORBIDDEN: [[NSCursor arrowCursor] set]; break;
  1104. case CURSOR_VSIZE: [[NSCursor resizeUpDownCursor] set]; break;
  1105. case CURSOR_HSIZE: [[NSCursor resizeLeftRightCursor] set]; break;
  1106. case CURSOR_BDIAGSIZE: [[NSCursor arrowCursor] set]; break;
  1107. case CURSOR_FDIAGSIZE: [[NSCursor arrowCursor] set]; break;
  1108. case CURSOR_MOVE: [[NSCursor arrowCursor] set]; break;
  1109. case CURSOR_VSPLIT: [[NSCursor resizeUpDownCursor] set]; break;
  1110. case CURSOR_HSPLIT: [[NSCursor resizeLeftRightCursor] set]; break;
  1111. case CURSOR_HELP: [[NSCursor arrowCursor] set]; break;
  1112. default: {};
  1113. }
  1114. }
  1115. cursor_shape = p_shape;
  1116. }
  1117. void OS_OSX::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  1118. if (p_cursor.is_valid()) {
  1119. Ref<Texture> texture = p_cursor;
  1120. Ref<Image> image = texture->get_data();
  1121. int image_size = 32 * 32;
  1122. ERR_FAIL_COND(texture->get_width() != 32 || texture->get_height() != 32);
  1123. NSBitmapImageRep *imgrep = [[[NSBitmapImageRep alloc]
  1124. initWithBitmapDataPlanes:NULL
  1125. pixelsWide:image->get_width()
  1126. pixelsHigh:image->get_height()
  1127. bitsPerSample:8
  1128. samplesPerPixel:4
  1129. hasAlpha:YES
  1130. isPlanar:NO
  1131. colorSpaceName:NSDeviceRGBColorSpace
  1132. bytesPerRow:image->get_width() * 4
  1133. bitsPerPixel:32] autorelease];
  1134. ERR_FAIL_COND(imgrep == nil);
  1135. uint8_t *pixels = [imgrep bitmapData];
  1136. int len = image->get_width() * image->get_height();
  1137. PoolVector<uint8_t> data = image->get_data();
  1138. PoolVector<uint8_t>::Read r = data.read();
  1139. /* Premultiply the alpha channel */
  1140. for (int i = 0; i < len; i++) {
  1141. uint8_t alpha = r[i * 4 + 3];
  1142. pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
  1143. pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
  1144. pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
  1145. pixels[i * 4 + 3] = alpha;
  1146. }
  1147. NSImage *nsimage = [[[NSImage alloc] initWithSize:NSMakeSize(image->get_width(), image->get_height())] autorelease];
  1148. [nsimage addRepresentation:imgrep];
  1149. NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
  1150. cursors[p_shape] = cursor;
  1151. if (p_shape == CURSOR_ARROW) {
  1152. [cursor set];
  1153. }
  1154. }
  1155. }
  1156. void OS_OSX::set_mouse_show(bool p_show) {
  1157. }
  1158. void OS_OSX::set_mouse_grab(bool p_grab) {
  1159. }
  1160. bool OS_OSX::is_mouse_grab_enabled() const {
  1161. return mouse_grab;
  1162. }
  1163. void OS_OSX::warp_mouse_position(const Point2 &p_to) {
  1164. //copied from windows impl with osx native calls
  1165. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1166. mouse_x = p_to.x;
  1167. mouse_y = p_to.y;
  1168. } else { //set OS position
  1169. //local point in window coords
  1170. const NSRect contentRect = [window_view frame];
  1171. float displayScale = _display_scale();
  1172. NSRect pointInWindowRect = NSMakeRect(p_to.x / displayScale, contentRect.size.height - (p_to.y / displayScale) - 1, 0, 0);
  1173. NSPoint pointOnScreen = [[window_view window] convertRectToScreen:pointInWindowRect].origin;
  1174. //point in scren coords
  1175. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  1176. //do the warping
  1177. CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
  1178. CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0);
  1179. CGAssociateMouseAndMouseCursorPosition(false);
  1180. CGWarpMouseCursorPosition(lMouseWarpPos);
  1181. CGAssociateMouseAndMouseCursorPosition(true);
  1182. }
  1183. }
  1184. Point2 OS_OSX::get_mouse_position() const {
  1185. return Vector2(mouse_x, mouse_y);
  1186. }
  1187. int OS_OSX::get_mouse_button_state() const {
  1188. return button_mask;
  1189. }
  1190. void OS_OSX::set_window_title(const String &p_title) {
  1191. title = p_title;
  1192. [window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
  1193. }
  1194. void OS_OSX::set_icon(const Ref<Image> &p_icon) {
  1195. Ref<Image> img = p_icon;
  1196. img = img->duplicate();
  1197. img->convert(Image::FORMAT_RGBA8);
  1198. NSBitmapImageRep *imgrep = [[[NSBitmapImageRep alloc]
  1199. initWithBitmapDataPlanes:NULL
  1200. pixelsWide:img->get_width()
  1201. pixelsHigh:img->get_height()
  1202. bitsPerSample:8
  1203. samplesPerPixel:4
  1204. hasAlpha:YES
  1205. isPlanar:NO
  1206. colorSpaceName:NSDeviceRGBColorSpace
  1207. bytesPerRow:img->get_width() * 4
  1208. bitsPerPixel:32] autorelease];
  1209. ERR_FAIL_COND(imgrep == nil);
  1210. uint8_t *pixels = [imgrep bitmapData];
  1211. int len = img->get_width() * img->get_height();
  1212. PoolVector<uint8_t> data = img->get_data();
  1213. PoolVector<uint8_t>::Read r = data.read();
  1214. /* Premultiply the alpha channel */
  1215. for (int i = 0; i < len; i++) {
  1216. uint8_t alpha = r[i * 4 + 3];
  1217. pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
  1218. pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
  1219. pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
  1220. pixels[i * 4 + 3] = alpha;
  1221. }
  1222. NSImage *nsimg = [[[NSImage alloc] initWithSize:NSMakeSize(img->get_width(), img->get_height())] autorelease];
  1223. ERR_FAIL_COND(nsimg == nil);
  1224. [nsimg addRepresentation:imgrep];
  1225. [NSApp setApplicationIconImage:nsimg];
  1226. }
  1227. MainLoop *OS_OSX::get_main_loop() const {
  1228. return main_loop;
  1229. }
  1230. String OS_OSX::get_config_path() const {
  1231. if (has_environment("XDG_CONFIG_HOME")) {
  1232. return get_environment("XDG_CONFIG_HOME");
  1233. } else if (has_environment("HOME")) {
  1234. return get_environment("HOME").plus_file("Library/Application Support");
  1235. } else {
  1236. return ".";
  1237. }
  1238. }
  1239. String OS_OSX::get_data_path() const {
  1240. if (has_environment("XDG_DATA_HOME")) {
  1241. return get_environment("XDG_DATA_HOME");
  1242. } else {
  1243. return get_config_path();
  1244. }
  1245. }
  1246. String OS_OSX::get_cache_path() const {
  1247. if (has_environment("XDG_CACHE_HOME")) {
  1248. return get_environment("XDG_CACHE_HOME");
  1249. } else if (has_environment("HOME")) {
  1250. return get_environment("HOME").plus_file("Library/Caches");
  1251. } else {
  1252. return get_config_path();
  1253. }
  1254. }
  1255. // Get properly capitalized engine name for system paths
  1256. String OS_OSX::get_godot_dir_name() const {
  1257. return String(VERSION_SHORT_NAME).capitalize();
  1258. }
  1259. String OS_OSX::get_system_dir(SystemDir p_dir) const {
  1260. NSSearchPathDirectory id = 0;
  1261. switch (p_dir) {
  1262. case SYSTEM_DIR_DESKTOP: {
  1263. id = NSDesktopDirectory;
  1264. } break;
  1265. case SYSTEM_DIR_DOCUMENTS: {
  1266. id = NSDocumentDirectory;
  1267. } break;
  1268. case SYSTEM_DIR_DOWNLOADS: {
  1269. id = NSDownloadsDirectory;
  1270. } break;
  1271. case SYSTEM_DIR_MOVIES: {
  1272. id = NSMoviesDirectory;
  1273. } break;
  1274. case SYSTEM_DIR_MUSIC: {
  1275. id = NSMusicDirectory;
  1276. } break;
  1277. case SYSTEM_DIR_PICTURES: {
  1278. id = NSPicturesDirectory;
  1279. } break;
  1280. }
  1281. String ret;
  1282. if (id) {
  1283. NSArray *paths = NSSearchPathForDirectoriesInDomains(id, NSUserDomainMask, YES);
  1284. if (paths && [paths count] >= 1) {
  1285. char *utfs = strdup([[paths firstObject] UTF8String]);
  1286. ret.parse_utf8(utfs);
  1287. free(utfs);
  1288. }
  1289. }
  1290. return ret;
  1291. }
  1292. bool OS_OSX::can_draw() const {
  1293. return true;
  1294. }
  1295. void OS_OSX::set_clipboard(const String &p_text) {
  1296. NSArray *types = [NSArray arrayWithObjects:NSStringPboardType, nil];
  1297. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1298. [pasteboard declareTypes:types owner:nil];
  1299. [pasteboard setString:[NSString stringWithUTF8String:p_text.utf8().get_data()]
  1300. forType:NSStringPboardType];
  1301. }
  1302. String OS_OSX::get_clipboard() const {
  1303. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1304. if (![[pasteboard types] containsObject:NSStringPboardType]) {
  1305. return "";
  1306. }
  1307. NSString *object = [pasteboard stringForType:NSStringPboardType];
  1308. if (!object) {
  1309. return "";
  1310. }
  1311. char *utfs = strdup([object UTF8String]);
  1312. String ret;
  1313. ret.parse_utf8(utfs);
  1314. free(utfs);
  1315. return ret;
  1316. }
  1317. void OS_OSX::release_rendering_thread() {
  1318. [NSOpenGLContext clearCurrentContext];
  1319. }
  1320. void OS_OSX::make_rendering_thread() {
  1321. [context makeCurrentContext];
  1322. }
  1323. Error OS_OSX::shell_open(String p_uri) {
  1324. [[NSWorkspace sharedWorkspace] openURL:[[NSURL alloc] initWithString:[[NSString stringWithUTF8String:p_uri.utf8().get_data()] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]];
  1325. return OK;
  1326. }
  1327. String OS_OSX::get_locale() const {
  1328. NSString *locale_code = [[NSLocale currentLocale] localeIdentifier];
  1329. return [locale_code UTF8String];
  1330. }
  1331. void OS_OSX::swap_buffers() {
  1332. [context flushBuffer];
  1333. }
  1334. void OS_OSX::wm_minimized(bool p_minimized) {
  1335. minimized = p_minimized;
  1336. };
  1337. void OS_OSX::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  1338. }
  1339. OS::VideoMode OS_OSX::get_video_mode(int p_screen) const {
  1340. VideoMode vm;
  1341. vm.width = window_size.width;
  1342. vm.height = window_size.height;
  1343. return vm;
  1344. }
  1345. void OS_OSX::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  1346. }
  1347. int OS_OSX::get_screen_count() const {
  1348. NSArray *screenArray = [NSScreen screens];
  1349. return [screenArray count];
  1350. };
  1351. // Returns the native top-left screen coordinate of the smallest rectangle
  1352. // that encompasses all screens. Needed in get_screen_position(),
  1353. // get_window_position, and set_window_position()
  1354. // to convert between OS X native screen coordinates and the ones expected by Godot
  1355. Point2 OS_OSX::get_screens_origin() const {
  1356. static Point2 origin;
  1357. if (displays_arrangement_dirty) {
  1358. origin = Point2();
  1359. for (int i = 0; i < get_screen_count(); i++) {
  1360. Point2 position = get_native_screen_position(i);
  1361. if (position.x < origin.x) {
  1362. origin.x = position.x;
  1363. }
  1364. if (position.y > origin.y) {
  1365. origin.y = position.y;
  1366. }
  1367. }
  1368. displays_arrangement_dirty = false;
  1369. }
  1370. return origin;
  1371. }
  1372. static int get_screen_index(NSScreen *screen) {
  1373. const NSUInteger index = [[NSScreen screens] indexOfObject:screen];
  1374. return index == NSNotFound ? 0 : index;
  1375. }
  1376. int OS_OSX::get_current_screen() const {
  1377. if (window_object) {
  1378. return get_screen_index([window_object screen]);
  1379. } else {
  1380. return get_screen_index([NSScreen mainScreen]);
  1381. }
  1382. };
  1383. void OS_OSX::set_current_screen(int p_screen) {
  1384. Vector2 wpos = get_window_position() - get_screen_position(get_current_screen());
  1385. set_window_position(wpos + get_screen_position(p_screen));
  1386. };
  1387. Point2 OS_OSX::get_native_screen_position(int p_screen) const {
  1388. if (p_screen == -1) {
  1389. p_screen = get_current_screen();
  1390. }
  1391. NSArray *screenArray = [NSScreen screens];
  1392. if (p_screen < [screenArray count]) {
  1393. float display_scale = _display_scale([screenArray objectAtIndex:p_screen]);
  1394. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1395. // Return the top-left corner of the screen, for OS X the y starts at the bottom
  1396. return Point2(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * display_scale;
  1397. }
  1398. return Point2();
  1399. }
  1400. Point2 OS_OSX::get_screen_position(int p_screen) const {
  1401. Point2 position = get_native_screen_position(p_screen) - get_screens_origin();
  1402. // OS X native y-coordinate relative to get_screens_origin() is negative,
  1403. // Godot expects a positive value
  1404. position.y *= -1;
  1405. return position;
  1406. }
  1407. int OS_OSX::get_screen_dpi(int p_screen) const {
  1408. if (p_screen == -1) {
  1409. p_screen = get_current_screen();
  1410. }
  1411. NSArray *screenArray = [NSScreen screens];
  1412. if (p_screen < [screenArray count]) {
  1413. float displayScale = _display_scale([screenArray objectAtIndex:p_screen]);
  1414. NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
  1415. NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
  1416. CGSize displayPhysicalSize = CGDisplayScreenSize(
  1417. [[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
  1418. return (displayPixelSize.width * 25.4f / displayPhysicalSize.width) * displayScale;
  1419. }
  1420. return 72;
  1421. }
  1422. Size2 OS_OSX::get_screen_size(int p_screen) const {
  1423. if (p_screen == -1) {
  1424. p_screen = get_current_screen();
  1425. }
  1426. NSArray *screenArray = [NSScreen screens];
  1427. if (p_screen < [screenArray count]) {
  1428. float displayScale = _display_scale([screenArray objectAtIndex:p_screen]);
  1429. // Note: Use frame to get the whole screen size
  1430. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1431. return Size2(nsrect.size.width, nsrect.size.height) * displayScale;
  1432. }
  1433. return Size2();
  1434. }
  1435. void OS_OSX::_update_window() {
  1436. bool borderless_full = false;
  1437. if (get_borderless_window()) {
  1438. NSRect frameRect = [window_object frame];
  1439. NSRect screenRect = [[window_object screen] frame];
  1440. // Check if our window covers up the screen
  1441. if (frameRect.origin.x <= screenRect.origin.x && frameRect.origin.y <= frameRect.origin.y &&
  1442. frameRect.size.width >= screenRect.size.width && frameRect.size.height >= screenRect.size.height) {
  1443. borderless_full = true;
  1444. }
  1445. }
  1446. if (borderless_full) {
  1447. // If the window covers up the screen set the level to above the main menu and hide on deactivate
  1448. [window_object setLevel:NSMainMenuWindowLevel + 1];
  1449. [window_object setHidesOnDeactivate:YES];
  1450. } else {
  1451. // Reset these when our window is not a borderless window that covers up the screen
  1452. [window_object setLevel:NSNormalWindowLevel];
  1453. [window_object setHidesOnDeactivate:NO];
  1454. }
  1455. }
  1456. float OS_OSX::_display_scale() const {
  1457. if (window_object) {
  1458. return _display_scale([window_object screen]);
  1459. } else {
  1460. return _display_scale([NSScreen mainScreen]);
  1461. }
  1462. }
  1463. float OS_OSX::_display_scale(id screen) const {
  1464. if (is_hidpi_allowed()) {
  1465. if ([screen respondsToSelector:@selector(backingScaleFactor)]) {
  1466. return fmax(1.0, [screen backingScaleFactor]);
  1467. }
  1468. }
  1469. return 1.0;
  1470. }
  1471. Point2 OS_OSX::get_native_window_position() const {
  1472. NSRect nsrect = [window_object frame];
  1473. Point2 pos;
  1474. float display_scale = _display_scale();
  1475. // Return the position of the top-left corner, for OS X the y starts at the bottom
  1476. pos.x = nsrect.origin.x * display_scale;
  1477. pos.y = (nsrect.origin.y + nsrect.size.height) * display_scale;
  1478. return pos;
  1479. };
  1480. Point2 OS_OSX::get_window_position() const {
  1481. Point2 position = get_native_window_position() - get_screens_origin();
  1482. // OS X native y-coordinate relative to get_screens_origin() is negative,
  1483. // Godot expects a positive value
  1484. position.y *= -1;
  1485. return position;
  1486. }
  1487. void OS_OSX::set_native_window_position(const Point2 &p_position) {
  1488. NSPoint pos;
  1489. float displayScale = _display_scale();
  1490. pos.x = p_position.x / displayScale;
  1491. pos.y = p_position.y / displayScale;
  1492. [window_object setFrameTopLeftPoint:pos];
  1493. _update_window();
  1494. };
  1495. void OS_OSX::set_window_position(const Point2 &p_position) {
  1496. Point2 position = p_position;
  1497. // OS X native y-coordinate relative to get_screens_origin() is negative,
  1498. // Godot passes a positive value
  1499. position.y *= -1;
  1500. set_native_window_position(get_screens_origin() + position);
  1501. };
  1502. Size2 OS_OSX::get_window_size() const {
  1503. return window_size;
  1504. };
  1505. Size2 OS_OSX::get_real_window_size() const {
  1506. NSRect frame = [window_object frame];
  1507. return Size2(frame.size.width, frame.size.height);
  1508. }
  1509. void OS_OSX::set_window_size(const Size2 p_size) {
  1510. Size2 size = p_size;
  1511. if (get_borderless_window() == false) {
  1512. // NSRect used by setFrame includes the title bar, so add it to our size.y
  1513. CGFloat menuBarHeight = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
  1514. if (menuBarHeight != 0.f) {
  1515. size.y += menuBarHeight;
  1516. } else {
  1517. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
  1518. if (floor(NSAppKitVersionNumber) < NSAppKitVersionNumber10_12) {
  1519. #else
  1520. {
  1521. #endif
  1522. size.y += [[NSStatusBar systemStatusBar] thickness];
  1523. }
  1524. }
  1525. }
  1526. NSRect frame = [window_object frame];
  1527. [window_object setFrame:NSMakeRect(frame.origin.x, frame.origin.y, size.x, size.y) display:YES];
  1528. _update_window();
  1529. };
  1530. void OS_OSX::set_window_fullscreen(bool p_enabled) {
  1531. if (zoomed != p_enabled) {
  1532. [window_object toggleFullScreen:nil];
  1533. }
  1534. zoomed = p_enabled;
  1535. };
  1536. bool OS_OSX::is_window_fullscreen() const {
  1537. return zoomed;
  1538. };
  1539. void OS_OSX::set_window_resizable(bool p_enabled) {
  1540. if (p_enabled)
  1541. [window_object setStyleMask:[window_object styleMask] | NSWindowStyleMaskResizable];
  1542. else
  1543. [window_object setStyleMask:[window_object styleMask] & ~NSWindowStyleMaskResizable];
  1544. };
  1545. bool OS_OSX::is_window_resizable() const {
  1546. return [window_object styleMask] & NSWindowStyleMaskResizable;
  1547. };
  1548. void OS_OSX::set_window_minimized(bool p_enabled) {
  1549. if (p_enabled)
  1550. [window_object performMiniaturize:nil];
  1551. else
  1552. [window_object deminiaturize:nil];
  1553. };
  1554. bool OS_OSX::is_window_minimized() const {
  1555. if ([window_object respondsToSelector:@selector(isMiniaturized)])
  1556. return [window_object isMiniaturized];
  1557. return minimized;
  1558. };
  1559. void OS_OSX::set_window_maximized(bool p_enabled) {
  1560. if (p_enabled) {
  1561. restore_rect = Rect2(get_window_position(), get_window_size());
  1562. [window_object setFrame:[[[NSScreen screens] objectAtIndex:get_current_screen()] visibleFrame] display:YES];
  1563. } else {
  1564. set_window_size(restore_rect.size);
  1565. set_window_position(restore_rect.position);
  1566. };
  1567. maximized = p_enabled;
  1568. };
  1569. bool OS_OSX::is_window_maximized() const {
  1570. // don't know
  1571. return maximized;
  1572. };
  1573. void OS_OSX::move_window_to_foreground() {
  1574. [window_object orderFrontRegardless];
  1575. }
  1576. void OS_OSX::set_window_always_on_top(bool p_enabled) {
  1577. if (is_window_always_on_top() == p_enabled)
  1578. return;
  1579. if (p_enabled)
  1580. [window_object setLevel:NSFloatingWindowLevel];
  1581. else
  1582. [window_object setLevel:NSNormalWindowLevel];
  1583. }
  1584. bool OS_OSX::is_window_always_on_top() const {
  1585. return [window_object level] == NSFloatingWindowLevel;
  1586. }
  1587. void OS_OSX::request_attention() {
  1588. [NSApp requestUserAttention:NSCriticalRequest];
  1589. }
  1590. void OS_OSX::set_borderless_window(bool p_borderless) {
  1591. // OrderOut prevents a lose focus bug with the window
  1592. [window_object orderOut:nil];
  1593. if (p_borderless) {
  1594. [window_object setStyleMask:NSWindowStyleMaskBorderless];
  1595. } else {
  1596. [window_object setStyleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable];
  1597. // Force update of the window styles
  1598. NSRect frameRect = [window_object frame];
  1599. [window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  1600. [window_object setFrame:frameRect display:NO];
  1601. // Restore the window title
  1602. [window_object setTitle:[NSString stringWithUTF8String:title.utf8().get_data()]];
  1603. }
  1604. _update_window();
  1605. [window_object makeKeyAndOrderFront:nil];
  1606. }
  1607. bool OS_OSX::get_borderless_window() {
  1608. return [window_object styleMask] == NSWindowStyleMaskBorderless;
  1609. }
  1610. String OS_OSX::get_executable_path() const {
  1611. int ret;
  1612. pid_t pid;
  1613. char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
  1614. pid = getpid();
  1615. ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
  1616. if (ret <= 0) {
  1617. return OS::get_executable_path();
  1618. } else {
  1619. String path;
  1620. path.parse_utf8(pathbuf);
  1621. return path;
  1622. }
  1623. }
  1624. // Returns string representation of keys, if they are printable.
  1625. //
  1626. static NSString *createStringForKeys(const CGKeyCode *keyCode, int length) {
  1627. TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
  1628. if (!currentKeyboard)
  1629. return nil;
  1630. CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
  1631. if (!layoutData)
  1632. return nil;
  1633. const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
  1634. OSStatus err;
  1635. CFMutableStringRef output = CFStringCreateMutable(NULL, 0);
  1636. for (int i = 0; i < length; ++i) {
  1637. UInt32 keysDown = 0;
  1638. UniChar chars[4];
  1639. UniCharCount realLength;
  1640. err = UCKeyTranslate(keyboardLayout,
  1641. keyCode[i],
  1642. kUCKeyActionDisplay,
  1643. 0,
  1644. LMGetKbdType(),
  1645. kUCKeyTranslateNoDeadKeysBit,
  1646. &keysDown,
  1647. sizeof(chars) / sizeof(chars[0]),
  1648. &realLength,
  1649. chars);
  1650. if (err != noErr) {
  1651. CFRelease(output);
  1652. return nil;
  1653. }
  1654. CFStringAppendCharacters(output, chars, 1);
  1655. }
  1656. //CFStringUppercase(output, NULL);
  1657. return (NSString *)output;
  1658. }
  1659. OS::LatinKeyboardVariant OS_OSX::get_latin_keyboard_variant() const {
  1660. static LatinKeyboardVariant layout = LATIN_KEYBOARD_QWERTY;
  1661. if (keyboard_layout_dirty) {
  1662. layout = LATIN_KEYBOARD_QWERTY;
  1663. CGKeyCode keys[] = { kVK_ANSI_Q, kVK_ANSI_W, kVK_ANSI_E, kVK_ANSI_R, kVK_ANSI_T, kVK_ANSI_Y };
  1664. NSString *test = createStringForKeys(keys, 6);
  1665. if ([test isEqualToString:@"qwertz"]) {
  1666. layout = LATIN_KEYBOARD_QWERTZ;
  1667. } else if ([test isEqualToString:@"azerty"]) {
  1668. layout = LATIN_KEYBOARD_AZERTY;
  1669. } else if ([test isEqualToString:@"qzerty"]) {
  1670. layout = LATIN_KEYBOARD_QZERTY;
  1671. } else if ([test isEqualToString:@"',.pyf"]) {
  1672. layout = LATIN_KEYBOARD_DVORAK;
  1673. } else if ([test isEqualToString:@"xvlcwk"]) {
  1674. layout = LATIN_KEYBOARD_NEO;
  1675. } else if ([test isEqualToString:@"qwfpgj"]) {
  1676. layout = LATIN_KEYBOARD_COLEMAK;
  1677. }
  1678. [test release];
  1679. keyboard_layout_dirty = false;
  1680. return layout;
  1681. }
  1682. return layout;
  1683. }
  1684. void OS_OSX::process_events() {
  1685. while (true) {
  1686. NSEvent *event = [NSApp
  1687. nextEventMatchingMask:NSEventMaskAny
  1688. untilDate:[NSDate distantPast]
  1689. inMode:NSDefaultRunLoopMode
  1690. dequeue:YES];
  1691. if (event == nil)
  1692. break;
  1693. [NSApp sendEvent:event];
  1694. }
  1695. process_key_events();
  1696. [autoreleasePool drain];
  1697. autoreleasePool = [[NSAutoreleasePool alloc] init];
  1698. }
  1699. void OS_OSX::process_key_events() {
  1700. Ref<InputEventKey> k;
  1701. for (int i = 0; i < key_event_pos; i++) {
  1702. KeyEvent &ke = key_event_buffer[i];
  1703. if ((i == 0 && ke.scancode == 0) || (i > 0 && key_event_buffer[i - 1].scancode == 0)) {
  1704. k.instance();
  1705. get_key_modifier_state(ke.osx_state, k);
  1706. k->set_pressed(ke.pressed);
  1707. k->set_echo(ke.echo);
  1708. k->set_scancode(0);
  1709. k->set_unicode(ke.unicode);
  1710. push_input(k);
  1711. }
  1712. if (ke.scancode != 0) {
  1713. k.instance();
  1714. get_key_modifier_state(ke.osx_state, k);
  1715. k->set_pressed(ke.pressed);
  1716. k->set_echo(ke.echo);
  1717. k->set_scancode(ke.scancode);
  1718. if (i + 1 < key_event_pos && key_event_buffer[i + 1].scancode == 0) {
  1719. k->set_unicode(key_event_buffer[i + 1].unicode);
  1720. }
  1721. push_input(k);
  1722. }
  1723. }
  1724. key_event_pos = 0;
  1725. }
  1726. void OS_OSX::push_input(const Ref<InputEvent> &p_event) {
  1727. Ref<InputEvent> ev = p_event;
  1728. input->parse_input_event(ev);
  1729. }
  1730. void OS_OSX::force_process_input() {
  1731. process_events(); // get rid of pending events
  1732. joypad_osx->process_joypads();
  1733. }
  1734. void OS_OSX::run() {
  1735. force_quit = false;
  1736. if (!main_loop)
  1737. return;
  1738. main_loop->init();
  1739. if (zoomed) {
  1740. zoomed = false;
  1741. set_window_fullscreen(true);
  1742. }
  1743. //uint64_t last_ticks=get_ticks_usec();
  1744. //int frames=0;
  1745. //uint64_t frame=0;
  1746. while (!force_quit) {
  1747. process_events(); // get rid of pending events
  1748. joypad_osx->process_joypads();
  1749. if (Main::iteration() == true)
  1750. break;
  1751. };
  1752. main_loop->finish();
  1753. }
  1754. void OS_OSX::set_mouse_mode(MouseMode p_mode) {
  1755. if (p_mode == mouse_mode)
  1756. return;
  1757. if (p_mode == MOUSE_MODE_CAPTURED) {
  1758. // Apple Docs state that the display parameter is not used.
  1759. // "This parameter is not used. By default, you may pass kCGDirectMainDisplay."
  1760. // https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/Quartz_Services_Ref/Reference/reference.html
  1761. CGDisplayHideCursor(kCGDirectMainDisplay);
  1762. CGAssociateMouseAndMouseCursorPosition(false);
  1763. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  1764. CGDisplayHideCursor(kCGDirectMainDisplay);
  1765. CGAssociateMouseAndMouseCursorPosition(true);
  1766. } else {
  1767. CGDisplayShowCursor(kCGDirectMainDisplay);
  1768. CGAssociateMouseAndMouseCursorPosition(true);
  1769. }
  1770. mouse_mode = p_mode;
  1771. }
  1772. OS::MouseMode OS_OSX::get_mouse_mode() const {
  1773. return mouse_mode;
  1774. }
  1775. String OS_OSX::get_joy_guid(int p_device) const {
  1776. return input->get_joy_guid_remapped(p_device);
  1777. }
  1778. OS::PowerState OS_OSX::get_power_state() {
  1779. return power_manager->get_power_state();
  1780. }
  1781. int OS_OSX::get_power_seconds_left() {
  1782. return power_manager->get_power_seconds_left();
  1783. }
  1784. int OS_OSX::get_power_percent_left() {
  1785. return power_manager->get_power_percent_left();
  1786. }
  1787. Error OS_OSX::move_to_trash(const String &p_path) {
  1788. NSFileManager *fm = [NSFileManager defaultManager];
  1789. NSURL *url = [NSURL fileURLWithPath:@(p_path.utf8().get_data())];
  1790. NSError *err;
  1791. if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
  1792. ERR_PRINTS("trashItemAtURL error: " + String(err.localizedDescription.UTF8String));
  1793. return FAILED;
  1794. }
  1795. return OK;
  1796. }
  1797. void OS_OSX::_set_use_vsync(bool p_enable) {
  1798. CGLContextObj ctx = CGLGetCurrentContext();
  1799. if (ctx) {
  1800. GLint swapInterval = p_enable ? 1 : 0;
  1801. CGLSetParameter(ctx, kCGLCPSwapInterval, &swapInterval);
  1802. }
  1803. }
  1804. /*
  1805. bool OS_OSX::is_vsync_enabled() const {
  1806. GLint swapInterval = 0;
  1807. CGLContextObj ctx = CGLGetCurrentContext();
  1808. if (ctx) {
  1809. CGLGetParameter(ctx, kCGLCPSwapInterval, &swapInterval);
  1810. }
  1811. return swapInterval ? true : false;
  1812. }
  1813. */
  1814. OS_OSX *OS_OSX::singleton = NULL;
  1815. OS_OSX::OS_OSX() {
  1816. key_event_pos = 0;
  1817. mouse_mode = OS::MOUSE_MODE_VISIBLE;
  1818. main_loop = NULL;
  1819. singleton = this;
  1820. im_position = Point2();
  1821. im_callback = NULL;
  1822. im_target = NULL;
  1823. autoreleasePool = [[NSAutoreleasePool alloc] init];
  1824. eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
  1825. ERR_FAIL_COND(!eventSource);
  1826. CGEventSourceSetLocalEventsSuppressionInterval(eventSource, 0.0);
  1827. /*
  1828. if (pthread_key_create(&_Godot.nsgl.current, NULL) != 0) {
  1829. _GodotInputError(Godot_PLATFORM_ERROR, "NSGL: Failed to create context TLS");
  1830. return GL_FALSE;
  1831. }
  1832. */
  1833. framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
  1834. ERR_FAIL_COND(!framework);
  1835. // Implicitly create shared NSApplication instance
  1836. [GodotApplication sharedApplication];
  1837. // In case we are unbundled, make us a proper UI application
  1838. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  1839. // Menu bar setup must go between sharedApplication above and
  1840. // finishLaunching below, in order to properly emulate the behavior
  1841. // of NSApplicationMain
  1842. NSMenuItem *menu_item;
  1843. NSString *title;
  1844. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  1845. if (nsappname == nil)
  1846. nsappname = [[NSProcessInfo processInfo] processName];
  1847. // Setup Apple menu
  1848. NSMenu *apple_menu = [[NSMenu alloc] initWithTitle:@""];
  1849. title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
  1850. [apple_menu addItemWithTitle:title action:@selector(showAbout:) keyEquivalent:@""];
  1851. [apple_menu addItem:[NSMenuItem separatorItem]];
  1852. NSMenu *services = [[NSMenu alloc] initWithTitle:@""];
  1853. menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
  1854. [apple_menu setSubmenu:services forItem:menu_item];
  1855. [NSApp setServicesMenu:services];
  1856. [services release];
  1857. [apple_menu addItem:[NSMenuItem separatorItem]];
  1858. title = [NSString stringWithFormat:NSLocalizedString(@"Hide %@", nil), nsappname];
  1859. [apple_menu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
  1860. menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Hide Others", nil) action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
  1861. [menu_item setKeyEquivalentModifierMask:(NSEventModifierFlagOption | NSEventModifierFlagCommand)];
  1862. [apple_menu addItemWithTitle:NSLocalizedString(@"Show all", nil) action:@selector(unhideAllApplications:) keyEquivalent:@""];
  1863. [apple_menu addItem:[NSMenuItem separatorItem]];
  1864. title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
  1865. [apple_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
  1866. // Setup menu bar
  1867. NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
  1868. menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
  1869. [main_menu setSubmenu:apple_menu forItem:menu_item];
  1870. [NSApp setMainMenu:main_menu];
  1871. [main_menu release];
  1872. [apple_menu release];
  1873. [NSApp finishLaunching];
  1874. delegate = [[GodotApplicationDelegate alloc] init];
  1875. ERR_FAIL_COND(!delegate);
  1876. [NSApp setDelegate:delegate];
  1877. cursor_shape = CURSOR_ARROW;
  1878. maximized = false;
  1879. minimized = false;
  1880. window_size = Vector2(1024, 600);
  1881. zoomed = false;
  1882. Vector<Logger *> loggers;
  1883. loggers.push_back(memnew(OSXTerminalLogger));
  1884. _set_logger(memnew(CompositeLogger(loggers)));
  1885. //process application:openFile: event
  1886. while (true) {
  1887. NSEvent *event = [NSApp
  1888. nextEventMatchingMask:NSEventMaskAny
  1889. untilDate:[NSDate distantPast]
  1890. inMode:NSDefaultRunLoopMode
  1891. dequeue:YES];
  1892. if (event == nil)
  1893. break;
  1894. [NSApp sendEvent:event];
  1895. }
  1896. }
  1897. bool OS_OSX::_check_internal_feature_support(const String &p_feature) {
  1898. return p_feature == "pc" || p_feature == "s3tc";
  1899. }
  1900. void OS_OSX::disable_crash_handler() {
  1901. crash_handler.disable();
  1902. }
  1903. bool OS_OSX::is_disable_crash_handler() const {
  1904. return crash_handler.is_disabled();
  1905. }