os_osx.mm 86 KB

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