os_osx.mm 105 KB

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