os_osx.mm 102 KB

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