os_osx.mm 75 KB

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