os_osx.mm 107 KB

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