os_osx.mm 79 KB

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