os_osx.mm 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144
  1. /*************************************************************************/
  2. /* os_osx.mm */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "os_osx.h"
  31. #include "dir_access_osx.h"
  32. #include "drivers/gles2/rasterizer_instance_gles2.h"
  33. #include "main/main.h"
  34. #include "os/keyboard.h"
  35. #include "print_string.h"
  36. #include "scene/resources/texture.h"
  37. #include "sem_osx.h"
  38. #include "servers/physics/physics_server_sw.h"
  39. #include "servers/visual/visual_server_raster.h"
  40. #include "servers/visual/visual_server_wrap_mt.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 <fcntl.h>
  51. #include <libproc.h>
  52. #include <stdio.h>
  53. #include <stdlib.h>
  54. #include <sys/stat.h>
  55. #include <sys/types.h>
  56. #include <unistd.h>
  57. //uses portions of glfw
  58. //========================================================================
  59. // GLFW 3.0 - www.glfw.org
  60. //------------------------------------------------------------------------
  61. // Copyright (c) 2002-2006 Marcus Geelnard
  62. // Copyright (c) 2006-2010 Camilla Berglund <elmindreda@elmindreda.org>
  63. //
  64. // This software is provided 'as-is', without any express or implied
  65. // warranty. In no event will the authors be held liable for any damages
  66. // arising from the use of this software.
  67. //
  68. // Permission is granted to anyone to use this software for any purpose,
  69. // including commercial applications, and to alter it and redistribute it
  70. // freely, subject to the following restrictions:
  71. //
  72. // 1. The origin of this software must not be misrepresented; you must not
  73. // claim that you wrote the original software. If you use this software
  74. // in a product, an acknowledgment in the product documentation would
  75. // be appreciated but is not required.
  76. //
  77. // 2. Altered source versions must be plainly marked as such, and must not
  78. // be misrepresented as being the original software.
  79. //
  80. // 3. This notice may not be removed or altered from any source
  81. // distribution.
  82. //
  83. //========================================================================
  84. #if MAC_OS_X_VERSION_MAX_ALLOWED < 101200
  85. #define NSWindowStyleMaskBorderless NSBorderlessWindowMask
  86. #endif
  87. static NSRect convertRectToBacking(NSRect contentRect) {
  88. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  89. if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
  90. return [OS_OSX::singleton->window_view convertRectToBacking:contentRect];
  91. else
  92. #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/
  93. return contentRect;
  94. }
  95. static InputModifierState translateFlags(NSUInteger flags) {
  96. InputModifierState mod;
  97. mod.shift = (flags & NSShiftKeyMask);
  98. mod.control = (flags & NSControlKeyMask);
  99. mod.alt = (flags & NSAlternateKeyMask);
  100. mod.meta = (flags & NSCommandKeyMask);
  101. return mod;
  102. }
  103. static int mouse_x = 0;
  104. static int mouse_y = 0;
  105. static int prev_mouse_x = 0;
  106. static int prev_mouse_y = 0;
  107. static int button_mask = 0;
  108. static bool mouse_down_control = false;
  109. @interface GodotApplication : NSApplication
  110. @end
  111. @implementation GodotApplication
  112. // From http://cocoadev.com/index.pl?GameKeyboardHandlingAlmost
  113. // This works around an AppKit bug, where key up events while holding
  114. // down the command key don't get sent to the key window.
  115. - (void)sendEvent:(NSEvent *)event {
  116. if ([event type] == NSKeyUp && ([event modifierFlags] & NSCommandKeyMask))
  117. [[self keyWindow] sendEvent:event];
  118. else
  119. [super sendEvent:event];
  120. }
  121. @end
  122. @interface GodotApplicationDelegate : NSObject
  123. - (void)forceUnbundledWindowActivationHackStep1;
  124. - (void)forceUnbundledWindowActivationHackStep2;
  125. - (void)forceUnbundledWindowActivationHackStep3;
  126. @end
  127. @implementation GodotApplicationDelegate
  128. - (void)forceUnbundledWindowActivationHackStep1 {
  129. // Step1: Switch focus to macOS Dock.
  130. // Required to perform step 2, TransformProcessType will fail if app is already the in focus.
  131. for (NSRunningApplication *app in [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.dock"]) {
  132. [app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  133. break;
  134. }
  135. [self performSelector:@selector(forceUnbundledWindowActivationHackStep2) withObject:nil afterDelay:0.02];
  136. }
  137. - (void)forceUnbundledWindowActivationHackStep2 {
  138. // Step 2: Register app as foreground process.
  139. ProcessSerialNumber psn = { 0, kCurrentProcess };
  140. (void)TransformProcessType(&psn, kProcessTransformToForegroundApplication);
  141. [self performSelector:@selector(forceUnbundledWindowActivationHackStep3) withObject:nil afterDelay:0.02];
  142. }
  143. - (void)forceUnbundledWindowActivationHackStep3 {
  144. // Step 3: Switch focus back to app window.
  145. [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateIgnoringOtherApps];
  146. }
  147. - (void)applicationDidFinishLaunching:(NSNotification *)notice {
  148. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  149. if (nsappname == nil) {
  150. // 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).
  151. [self performSelector:@selector(forceUnbundledWindowActivationHackStep1) withObject:nil afterDelay:0.02];
  152. }
  153. }
  154. - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
  155. if (OS_OSX::singleton->get_main_loop())
  156. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  157. return NSTerminateCancel;
  158. }
  159. - (void)applicationDidHide:(NSNotification *)notification {
  160. /*
  161. _Godotwindow* window;
  162. for (window = _Godot.windowListHead; window; window = window->next)
  163. _GodotInputWindowVisibility(window, GL_FALSE);
  164. */
  165. }
  166. - (void)applicationDidUnhide:(NSNotification *)notification {
  167. /*
  168. _Godotwindow* window;
  169. for (window = _Godot.windowListHead; window; window = window->next)
  170. {
  171. if ([window_object isVisible])
  172. _GodotInputWindowVisibility(window, GL_TRUE);
  173. }
  174. */
  175. }
  176. - (void)applicationDidChangeScreenParameters:(NSNotification *)notification {
  177. //_GodotInputMonitorChange();
  178. }
  179. @end
  180. @interface GodotWindowDelegate : NSObject {
  181. //_Godotwindow* window;
  182. }
  183. @end
  184. @implementation GodotWindowDelegate
  185. - (BOOL)windowShouldClose:(id)sender {
  186. //_GodotInputWindowCloseRequest(window);
  187. if (OS_OSX::singleton->get_main_loop())
  188. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  189. return NO;
  190. }
  191. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  192. - (void)windowDidEnterFullScreen:(NSNotification *)notification {
  193. OS_OSX::singleton->zoomed = true;
  194. }
  195. - (void)windowDidExitFullScreen:(NSNotification *)notification {
  196. OS_OSX::singleton->zoomed = false;
  197. }
  198. #endif // MAC_OS_X_VERSION_MAX_ALLOWED
  199. - (void)windowDidChangeBackingProperties:(NSNotification *)notification {
  200. if (!OS_OSX::singleton)
  201. return;
  202. NSWindow *window = (NSWindow *)[notification object];
  203. CGFloat newBackingScaleFactor = [window backingScaleFactor];
  204. CGFloat oldBackingScaleFactor = [[[notification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
  205. if (newBackingScaleFactor != oldBackingScaleFactor) {
  206. //Set new display scale and window size
  207. OS_OSX::singleton->display_scale = newBackingScaleFactor;
  208. const NSRect contentRect = [OS_OSX::singleton->window_view frame];
  209. const NSRect fbRect = contentRect; //convertRectToBacking(contentRect);
  210. OS_OSX::singleton->window_size.width = fbRect.size.width * OS_OSX::singleton->display_scale;
  211. OS_OSX::singleton->window_size.height = fbRect.size.height * OS_OSX::singleton->display_scale;
  212. //Update context
  213. if (OS_OSX::singleton->main_loop) {
  214. //Force window resize event
  215. [self windowDidResize:notification];
  216. }
  217. }
  218. }
  219. - (void)windowDidResize:(NSNotification *)notification {
  220. [OS_OSX::singleton->context update];
  221. const NSRect contentRect = [OS_OSX::singleton->window_view frame];
  222. const NSRect fbRect = contentRect; //convertRectToBacking(contentRect);
  223. OS_OSX::singleton->window_size.width = fbRect.size.width * OS_OSX::singleton->display_scale;
  224. OS_OSX::singleton->window_size.height = fbRect.size.height * OS_OSX::singleton->display_scale;
  225. if (OS_OSX::singleton->main_loop) {
  226. Main::force_redraw();
  227. //Event retrieval blocks until resize is over. Call Main::iteration() directly.
  228. Main::iteration();
  229. }
  230. //_GodotInputFramebufferSize(window, fbRect.size.width, fbRect.size.height);
  231. //_GodotInputWindowSize(window, contentRect.size.width, contentRect.size.height);
  232. //_GodotInputWindowDamage(window);
  233. //if (window->cursorMode == Godot_CURSOR_DISABLED)
  234. // centerCursor(window);
  235. }
  236. - (void)windowDidMove:(NSNotification *)notification {
  237. //[window->nsgl.context update];
  238. //int x, y;
  239. //_GodotPlatformGetWindowPos(window, &x, &y);
  240. //_GodotInputWindowPos(window, x, y);
  241. //if (window->cursorMode == Godot_CURSOR_DISABLED)
  242. // centerCursor(window);
  243. }
  244. - (void)windowDidBecomeKey:(NSNotification *)notification {
  245. //_GodotInputWindowFocus(window, GL_TRUE);
  246. //_GodotPlatformSetCursorMode(window, window->cursorMode);
  247. if (OS_OSX::singleton->get_main_loop())
  248. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  249. }
  250. - (void)windowDidResignKey:(NSNotification *)notification {
  251. //_GodotInputWindowFocus(window, GL_FALSE);
  252. //_GodotPlatformSetCursorMode(window, Godot_CURSOR_NORMAL);
  253. if (OS_OSX::singleton->get_main_loop())
  254. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  255. }
  256. - (void)windowDidMiniaturize:(NSNotification *)notification {
  257. OS_OSX::singleton->wm_minimized(true);
  258. if (OS_OSX::singleton->get_main_loop())
  259. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  260. };
  261. - (void)windowDidDeminiaturize:(NSNotification *)notification {
  262. OS_OSX::singleton->wm_minimized(false);
  263. if (OS_OSX::singleton->get_main_loop())
  264. OS_OSX::singleton->get_main_loop()->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  265. };
  266. @end
  267. @interface GodotContentView : NSView {
  268. NSTrackingArea *trackingArea;
  269. }
  270. @end
  271. @implementation GodotContentView
  272. + (void)initialize {
  273. if (self == [GodotContentView class]) {
  274. /*
  275. if (_glfw.ns.cursor == nil) {
  276. NSImage* data = [[NSImage alloc] initWithSize:NSMakeSize(1, 1)];
  277. _glfw.ns.cursor = [[NSCursor alloc] initWithImage:data hotSpot:NSZeroPoint];
  278. [data release];
  279. }
  280. */
  281. }
  282. }
  283. - (id)init {
  284. self = [super init];
  285. trackingArea = nil;
  286. [self updateTrackingAreas];
  287. [self registerForDraggedTypes:[NSArray arrayWithObject:NSFilenamesPboardType]];
  288. return self;
  289. }
  290. - (void)dealloc {
  291. [trackingArea release];
  292. [super dealloc];
  293. }
  294. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  295. return NSDragOperationCopy;
  296. }
  297. - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
  298. return NSDragOperationCopy;
  299. }
  300. - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  301. NSPasteboard *pboard = [sender draggingPasteboard];
  302. NSArray *filenames = [pboard propertyListForType:NSFilenamesPboardType];
  303. Vector<String> files;
  304. for (int i = 0; i < filenames.count; i++) {
  305. NSString *ns = [filenames objectAtIndex:i];
  306. char *utfs = strdup([ns UTF8String]);
  307. String ret;
  308. ret.parse_utf8(utfs);
  309. free(utfs);
  310. files.push_back(ret);
  311. }
  312. if (files.size()) {
  313. OS_OSX::singleton->main_loop->drop_files(files, 0);
  314. OS_OSX::singleton->move_window_to_foreground();
  315. }
  316. return NO;
  317. }
  318. - (BOOL)isOpaque {
  319. return YES;
  320. }
  321. - (BOOL)canBecomeKeyView {
  322. return YES;
  323. }
  324. - (BOOL)acceptsFirstResponder {
  325. return YES;
  326. }
  327. - (void)cursorUpdate:(NSEvent *)event {
  328. //setModeCursor(window, window->cursorMode);
  329. }
  330. static void _mouseDownEvent(NSEvent *event, int index, int mask, bool pressed) {
  331. if (pressed) {
  332. button_mask |= mask;
  333. } else {
  334. button_mask &= ~mask;
  335. }
  336. InputEvent ev;
  337. ev.type = InputEvent::MOUSE_BUTTON;
  338. ev.mouse_button.button_index = index;
  339. ev.mouse_button.pressed = pressed;
  340. ev.mouse_button.x = mouse_x;
  341. ev.mouse_button.y = mouse_y;
  342. ev.mouse_button.global_x = mouse_x;
  343. ev.mouse_button.global_y = mouse_y;
  344. ev.mouse_button.button_mask = button_mask;
  345. if (index == BUTTON_LEFT && pressed) {
  346. ev.mouse_button.doubleclick = [event clickCount] == 2;
  347. }
  348. ev.mouse_button.mod = translateFlags([event modifierFlags]);
  349. OS_OSX::singleton->push_input(ev);
  350. }
  351. - (void)mouseDown:(NSEvent *)event {
  352. if (([event modifierFlags] & NSControlKeyMask)) {
  353. mouse_down_control = true;
  354. _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, true);
  355. } else {
  356. mouse_down_control = false;
  357. _mouseDownEvent(event, BUTTON_LEFT, BUTTON_MASK_LEFT, true);
  358. }
  359. }
  360. - (void)mouseDragged:(NSEvent *)event {
  361. [self mouseMoved:event];
  362. }
  363. - (void)mouseUp:(NSEvent *)event {
  364. if (mouse_down_control) {
  365. _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, false);
  366. } else {
  367. _mouseDownEvent(event, BUTTON_LEFT, BUTTON_MASK_LEFT, false);
  368. }
  369. }
  370. - (void)mouseMoved:(NSEvent *)event {
  371. InputEvent ev;
  372. ev.type = InputEvent::MOUSE_MOTION;
  373. ev.mouse_motion.button_mask = button_mask;
  374. prev_mouse_x = mouse_x;
  375. prev_mouse_y = mouse_y;
  376. const NSRect contentRect = [OS_OSX::singleton->window_view frame];
  377. const NSPoint p = [event locationInWindow];
  378. mouse_x = p.x * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
  379. mouse_y = (contentRect.size.height - p.y) * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
  380. ev.mouse_motion.x = mouse_x;
  381. ev.mouse_motion.y = mouse_y;
  382. ev.mouse_motion.global_x = mouse_x;
  383. ev.mouse_motion.global_y = mouse_y;
  384. ev.mouse_motion.relative_x = ([event deltaX]) * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
  385. ev.mouse_motion.relative_y = ([event deltaY]) * OS_OSX::singleton->_mouse_scale([[event window] backingScaleFactor]);
  386. ev.mouse_motion.mod = translateFlags([event modifierFlags]);
  387. OS_OSX::singleton->input->set_mouse_pos(Point2(mouse_x, mouse_y));
  388. OS_OSX::singleton->push_input(ev);
  389. /*
  390. if (window->cursorMode == GLFW_CURSOR_DISABLED)
  391. _glfwInputCursorMotion(window, [event deltaX], [event deltaY]);
  392. else {
  393. const NSRect contentRect = [window->ns.view frame];
  394. const NSPoint p = [event locationInWindow];
  395. _glfwInputCursorMotion(window, p.x, contentRect.size.height - p.y);
  396. }
  397. */
  398. }
  399. - (void)rightMouseDown:(NSEvent *)event {
  400. _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, true);
  401. }
  402. - (void)rightMouseDragged:(NSEvent *)event {
  403. [self mouseMoved:event];
  404. }
  405. - (void)rightMouseUp:(NSEvent *)event {
  406. _mouseDownEvent(event, BUTTON_RIGHT, BUTTON_MASK_RIGHT, false);
  407. }
  408. - (void)otherMouseDown:(NSEvent *)event {
  409. if ((int)[event buttonNumber] != 2)
  410. return;
  411. _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, true);
  412. }
  413. - (void)otherMouseDragged:(NSEvent *)event {
  414. [self mouseMoved:event];
  415. }
  416. - (void)otherMouseUp:(NSEvent *)event {
  417. if ((int)[event buttonNumber] != 2)
  418. return;
  419. _mouseDownEvent(event, BUTTON_MIDDLE, BUTTON_MASK_MIDDLE, false);
  420. }
  421. - (void)mouseExited:(NSEvent *)event {
  422. if (!OS_OSX::singleton)
  423. return;
  424. if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
  425. OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
  426. //_glfwInputCursorEnter(window, GL_FALSE);
  427. }
  428. - (void)mouseEntered:(NSEvent *)event {
  429. //_glfwInputCursorEnter(window, GL_TRUE);
  430. if (!OS_OSX::singleton)
  431. return;
  432. if (OS_OSX::singleton->main_loop && OS_OSX::singleton->mouse_mode != OS::MOUSE_MODE_CAPTURED)
  433. OS_OSX::singleton->main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
  434. if (OS_OSX::singleton->input) {
  435. OS_OSX::singleton->cursor_shape = OS::CURSOR_MAX;
  436. OS_OSX::singleton->set_cursor_shape(OS::CURSOR_ARROW);
  437. }
  438. }
  439. - (void)viewDidChangeBackingProperties {
  440. /*
  441. const NSRect contentRect = [window->ns.view frame];
  442. const NSRect fbRect = convertRectToBacking(window, contentRect);
  443. _glfwInputFramebufferSize(window, fbRect.size.width, fbRect.size.height);
  444. */
  445. }
  446. - (void)updateTrackingAreas {
  447. if (trackingArea != nil) {
  448. [self removeTrackingArea:trackingArea];
  449. [trackingArea release];
  450. }
  451. NSTrackingAreaOptions options =
  452. NSTrackingMouseEnteredAndExited |
  453. NSTrackingActiveInKeyWindow |
  454. NSTrackingCursorUpdate |
  455. NSTrackingInVisibleRect;
  456. trackingArea = [[NSTrackingArea alloc]
  457. initWithRect:[self bounds]
  458. options:options
  459. owner:self
  460. userInfo:nil];
  461. [self addTrackingArea:trackingArea];
  462. [super updateTrackingAreas];
  463. }
  464. // Translates a OS X keycode to a Godot keycode
  465. //
  466. static int translateKey(unsigned int key) {
  467. // Keyboard symbol translation table
  468. static const unsigned int table[128] = {
  469. /* 00 */ KEY_A,
  470. /* 01 */ KEY_S,
  471. /* 02 */ KEY_D,
  472. /* 03 */ KEY_F,
  473. /* 04 */ KEY_H,
  474. /* 05 */ KEY_G,
  475. /* 06 */ KEY_Z,
  476. /* 07 */ KEY_X,
  477. /* 08 */ KEY_C,
  478. /* 09 */ KEY_V,
  479. /* 0a */ KEY_UNKNOWN,
  480. /* 0b */ KEY_B,
  481. /* 0c */ KEY_Q,
  482. /* 0d */ KEY_W,
  483. /* 0e */ KEY_E,
  484. /* 0f */ KEY_R,
  485. /* 10 */ KEY_Y,
  486. /* 11 */ KEY_T,
  487. /* 12 */ KEY_1,
  488. /* 13 */ KEY_2,
  489. /* 14 */ KEY_3,
  490. /* 15 */ KEY_4,
  491. /* 16 */ KEY_6,
  492. /* 17 */ KEY_5,
  493. /* 18 */ KEY_EQUAL,
  494. /* 19 */ KEY_9,
  495. /* 1a */ KEY_7,
  496. /* 1b */ KEY_MINUS,
  497. /* 1c */ KEY_8,
  498. /* 1d */ KEY_0,
  499. /* 1e */ KEY_BRACERIGHT,
  500. /* 1f */ KEY_O,
  501. /* 20 */ KEY_U,
  502. /* 21 */ KEY_BRACELEFT,
  503. /* 22 */ KEY_I,
  504. /* 23 */ KEY_P,
  505. /* 24 */ KEY_RETURN,
  506. /* 25 */ KEY_L,
  507. /* 26 */ KEY_J,
  508. /* 27 */ KEY_APOSTROPHE,
  509. /* 28 */ KEY_K,
  510. /* 29 */ KEY_SEMICOLON,
  511. /* 2a */ KEY_BACKSLASH,
  512. /* 2b */ KEY_COMMA,
  513. /* 2c */ KEY_SLASH,
  514. /* 2d */ KEY_N,
  515. /* 2e */ KEY_M,
  516. /* 2f */ KEY_PERIOD,
  517. /* 30 */ KEY_TAB,
  518. /* 31 */ KEY_SPACE,
  519. /* 32 */ KEY_QUOTELEFT,
  520. /* 33 */ KEY_BACKSPACE,
  521. /* 34 */ KEY_UNKNOWN,
  522. /* 35 */ KEY_ESCAPE,
  523. /* 36 */ KEY_META,
  524. /* 37 */ KEY_META,
  525. /* 38 */ KEY_SHIFT,
  526. /* 39 */ KEY_CAPSLOCK,
  527. /* 3a */ KEY_ALT,
  528. /* 3b */ KEY_CONTROL,
  529. /* 3c */ KEY_SHIFT,
  530. /* 3d */ KEY_ALT,
  531. /* 3e */ KEY_CONTROL,
  532. /* 3f */ KEY_UNKNOWN, /* Function */
  533. /* 40 */ KEY_UNKNOWN,
  534. /* 41 */ KEY_KP_PERIOD,
  535. /* 42 */ KEY_UNKNOWN,
  536. /* 43 */ KEY_KP_MULTIPLY,
  537. /* 44 */ KEY_UNKNOWN,
  538. /* 45 */ KEY_KP_ADD,
  539. /* 46 */ KEY_UNKNOWN,
  540. /* 47 */ KEY_NUMLOCK, /* Really KeypadClear... */
  541. /* 48 */ KEY_UNKNOWN, /* VolumeUp */
  542. /* 49 */ KEY_UNKNOWN, /* VolumeDown */
  543. /* 4a */ KEY_UNKNOWN, /* Mute */
  544. /* 4b */ KEY_KP_DIVIDE,
  545. /* 4c */ KEY_ENTER,
  546. /* 4d */ KEY_UNKNOWN,
  547. /* 4e */ KEY_KP_SUBTRACT,
  548. /* 4f */ KEY_UNKNOWN,
  549. /* 50 */ KEY_UNKNOWN,
  550. /* 51 */ KEY_EQUAL, //wtf equal?
  551. /* 52 */ KEY_KP_0,
  552. /* 53 */ KEY_KP_1,
  553. /* 54 */ KEY_KP_2,
  554. /* 55 */ KEY_KP_3,
  555. /* 56 */ KEY_KP_4,
  556. /* 57 */ KEY_KP_5,
  557. /* 58 */ KEY_KP_6,
  558. /* 59 */ KEY_KP_7,
  559. /* 5a */ KEY_UNKNOWN,
  560. /* 5b */ KEY_KP_8,
  561. /* 5c */ KEY_KP_9,
  562. /* 5d */ KEY_UNKNOWN,
  563. /* 5e */ KEY_UNKNOWN,
  564. /* 5f */ KEY_UNKNOWN,
  565. /* 60 */ KEY_F5,
  566. /* 61 */ KEY_F6,
  567. /* 62 */ KEY_F7,
  568. /* 63 */ KEY_F3,
  569. /* 64 */ KEY_F8,
  570. /* 65 */ KEY_F9,
  571. /* 66 */ KEY_UNKNOWN,
  572. /* 67 */ KEY_F11,
  573. /* 68 */ KEY_UNKNOWN,
  574. /* 69 */ KEY_F13,
  575. /* 6a */ KEY_F16,
  576. /* 6b */ KEY_F14,
  577. /* 6c */ KEY_UNKNOWN,
  578. /* 6d */ KEY_F10,
  579. /* 6e */ KEY_UNKNOWN,
  580. /* 6f */ KEY_F12,
  581. /* 70 */ KEY_UNKNOWN,
  582. /* 71 */ KEY_F15,
  583. /* 72 */ KEY_INSERT, /* Really Help... */
  584. /* 73 */ KEY_HOME,
  585. /* 74 */ KEY_PAGEUP,
  586. /* 75 */ KEY_DELETE,
  587. /* 76 */ KEY_F4,
  588. /* 77 */ KEY_END,
  589. /* 78 */ KEY_F2,
  590. /* 79 */ KEY_PAGEDOWN,
  591. /* 7a */ KEY_F1,
  592. /* 7b */ KEY_LEFT,
  593. /* 7c */ KEY_RIGHT,
  594. /* 7d */ KEY_DOWN,
  595. /* 7e */ KEY_UP,
  596. /* 7f */ KEY_UNKNOWN,
  597. };
  598. if (key >= 128)
  599. return KEY_UNKNOWN;
  600. return table[key];
  601. }
  602. - (void)keyDown:(NSEvent *)event {
  603. InputEvent ev;
  604. ev.type = InputEvent::KEY;
  605. ev.key.pressed = true;
  606. ev.key.mod = translateFlags([event modifierFlags]);
  607. ev.key.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode]));
  608. ev.key.echo = [event isARepeat];
  609. NSString *characters = [event characters];
  610. NSUInteger i, length = [characters length];
  611. if (length > 0 && keycode_has_unicode(ev.key.scancode)) {
  612. for (i = 0; i < length; i++) {
  613. ev.key.unicode = [characters characterAtIndex:i];
  614. OS_OSX::singleton->push_input(ev);
  615. ev.key.scancode = 0;
  616. }
  617. } else {
  618. OS_OSX::singleton->push_input(ev);
  619. }
  620. }
  621. - (void)flagsChanged:(NSEvent *)event {
  622. InputEvent ev;
  623. int key = [event keyCode];
  624. int mod = [event modifierFlags];
  625. ev.type = InputEvent::KEY;
  626. if (key == 0x36 || key == 0x37) {
  627. if (mod & NSCommandKeyMask) {
  628. mod &= ~NSCommandKeyMask;
  629. ev.key.pressed = true;
  630. } else {
  631. ev.key.pressed = false;
  632. }
  633. } else if (key == 0x38 || key == 0x3c) {
  634. if (mod & NSShiftKeyMask) {
  635. mod &= ~NSShiftKeyMask;
  636. ev.key.pressed = true;
  637. } else {
  638. ev.key.pressed = false;
  639. }
  640. } else if (key == 0x3a || key == 0x3d) {
  641. if (mod & NSAlternateKeyMask) {
  642. mod &= ~NSAlternateKeyMask;
  643. ev.key.pressed = true;
  644. } else {
  645. ev.key.pressed = false;
  646. }
  647. } else if (key == 0x3b || key == 0x3e) {
  648. if (mod & NSControlKeyMask) {
  649. mod &= ~NSControlKeyMask;
  650. ev.key.pressed = true;
  651. } else {
  652. ev.key.pressed = false;
  653. }
  654. } else {
  655. return;
  656. }
  657. ev.key.mod = translateFlags(mod);
  658. ev.key.scancode = latin_keyboard_keycode_convert(translateKey(key));
  659. OS_OSX::singleton->push_input(ev);
  660. }
  661. - (void)keyUp:(NSEvent *)event {
  662. InputEvent ev;
  663. ev.type = InputEvent::KEY;
  664. ev.key.pressed = false;
  665. ev.key.mod = translateFlags([event modifierFlags]);
  666. ev.key.scancode = latin_keyboard_keycode_convert(translateKey([event keyCode]));
  667. OS_OSX::singleton->push_input(ev);
  668. /*
  669. const int key = translateKey([event keyCode]);
  670. const int mods = translateFlags([event modifierFlags]);
  671. _glfwInputKey(window, key, [event keyCode], GLFW_RELEASE, mods);
  672. */
  673. }
  674. inline void sendScrollEvent(int button, double factor) {
  675. InputEvent ev;
  676. ev.type = InputEvent::MOUSE_BUTTON;
  677. ev.mouse_button.button_index = button;
  678. ev.mouse_button.factor = factor;
  679. ev.mouse_button.pressed = true;
  680. ev.mouse_button.x = mouse_x;
  681. ev.mouse_button.y = mouse_y;
  682. ev.mouse_button.global_x = mouse_x;
  683. ev.mouse_button.global_y = mouse_y;
  684. ev.mouse_button.button_mask = button_mask;
  685. OS_OSX::singleton->push_input(ev);
  686. ev.mouse_button.pressed = false;
  687. OS_OSX::singleton->push_input(ev);
  688. }
  689. - (void)scrollWheel:(NSEvent *)event {
  690. double deltaX, deltaY;
  691. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  692. if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6) {
  693. deltaX = [event scrollingDeltaX];
  694. deltaY = [event scrollingDeltaY];
  695. if ([event hasPreciseScrollingDeltas]) {
  696. deltaX *= 0.03;
  697. deltaY *= 0.03;
  698. }
  699. } else
  700. #endif // MAC_OS_X_VERSION_MAX_ALLOWED
  701. {
  702. deltaX = [event deltaX];
  703. deltaY = [event deltaY];
  704. }
  705. if (fabs(deltaX)) {
  706. sendScrollEvent(0 > deltaX ? BUTTON_WHEEL_RIGHT : BUTTON_WHEEL_LEFT, fabs(deltaX * 0.3));
  707. }
  708. if (fabs(deltaY)) {
  709. sendScrollEvent(0 < deltaY ? BUTTON_WHEEL_UP : BUTTON_WHEEL_DOWN, fabs(deltaY * 0.3));
  710. }
  711. }
  712. @end
  713. @interface GodotWindow : NSWindow {
  714. }
  715. @end
  716. @implementation GodotWindow
  717. - (BOOL)canBecomeKeyWindow {
  718. // Required for NSBorderlessWindowMask windows
  719. return YES;
  720. }
  721. @end
  722. int OS_OSX::get_video_driver_count() const {
  723. return 1;
  724. }
  725. const char *OS_OSX::get_video_driver_name(int p_driver) const {
  726. return "GLES2";
  727. }
  728. OS::VideoMode OS_OSX::get_default_video_mode() const {
  729. VideoMode vm;
  730. vm.width = 1024;
  731. vm.height = 600;
  732. vm.fullscreen = false;
  733. vm.resizable = true;
  734. return vm;
  735. }
  736. void OS_OSX::initialize_core() {
  737. crash_handler.initialize();
  738. OS_Unix::initialize_core();
  739. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_RESOURCES);
  740. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_USERDATA);
  741. DirAccess::make_default<DirAccessOSX>(DirAccess::ACCESS_FILESYSTEM);
  742. SemaphoreOSX::make_default();
  743. }
  744. static bool keyboard_layout_dirty = true;
  745. static void keyboard_layout_changed(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef user_info) {
  746. keyboard_layout_dirty = true;
  747. }
  748. static bool displays_arrangement_dirty = true;
  749. static void displays_arrangement_changed(CGDirectDisplayID display_id, CGDisplayChangeSummaryFlags flags, void *user_info) {
  750. displays_arrangement_dirty = true;
  751. }
  752. void OS_OSX::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  753. /*** OSX INITIALIZATION ***/
  754. /*** OSX INITIALIZATION ***/
  755. /*** OSX INITIALIZATION ***/
  756. keyboard_layout_dirty = true;
  757. displays_arrangement_dirty = true;
  758. // Register to be notified on keyboard layout changes
  759. CFNotificationCenterAddObserver(CFNotificationCenterGetDistributedCenter(),
  760. NULL, keyboard_layout_changed,
  761. kTISNotifySelectedKeyboardInputSourceChanged, NULL,
  762. CFNotificationSuspensionBehaviorDeliverImmediately);
  763. // Register to be notified on displays arrangement changes
  764. CGDisplayRegisterReconfigurationCallback(displays_arrangement_changed, NULL);
  765. if (is_hidpi_allowed() && [[NSScreen mainScreen] respondsToSelector:@selector(backingScaleFactor)]) {
  766. for (NSScreen *screen in [NSScreen screens]) {
  767. float s = [screen backingScaleFactor];
  768. if (s > display_scale) {
  769. display_scale = s;
  770. }
  771. }
  772. }
  773. window_delegate = [[GodotWindowDelegate alloc] init];
  774. // Don't use accumulation buffer support; it's not accelerated
  775. // Aux buffers probably aren't accelerated either
  776. unsigned int styleMask;
  777. if (p_desired.borderless_window) {
  778. styleMask = NSWindowStyleMaskBorderless;
  779. } else {
  780. styleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | (p_desired.resizable ? NSResizableWindowMask : 0);
  781. }
  782. window_object = [[GodotWindow alloc]
  783. initWithContentRect:NSMakeRect(0, 0, p_desired.width, p_desired.height)
  784. styleMask:styleMask
  785. backing:NSBackingStoreBuffered
  786. defer:NO];
  787. ERR_FAIL_COND(window_object == nil);
  788. window_view = [[GodotContentView alloc] init];
  789. window_size.width = p_desired.width * display_scale;
  790. window_size.height = p_desired.height * display_scale;
  791. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  792. if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6 && display_scale > 1) {
  793. [window_view setWantsBestResolutionOpenGLSurface:YES];
  794. //if (current_videomode.resizable)
  795. [window_object setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
  796. } else {
  797. [window_view setWantsBestResolutionOpenGLSurface:NO];
  798. }
  799. #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/
  800. //[window_object setTitle:[NSString stringWithUTF8String:"GodotEnginies"]];
  801. [window_object setContentView:window_view];
  802. [window_object setDelegate:window_delegate];
  803. [window_object setAcceptsMouseMovedEvents:YES];
  804. [window_object center];
  805. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  806. if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
  807. [window_object setRestorable:NO];
  808. #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/
  809. unsigned int attributeCount = 0;
  810. // OS X needs non-zero color size, so set resonable values
  811. int colorBits = 32;
  812. // Fail if a robustness strategy was requested
  813. #define ADD_ATTR(x) \
  814. { attributes[attributeCount++] = x; }
  815. #define ADD_ATTR2(x, y) \
  816. { \
  817. ADD_ATTR(x); \
  818. ADD_ATTR(y); \
  819. }
  820. // Arbitrary array size here
  821. NSOpenGLPixelFormatAttribute attributes[40];
  822. ADD_ATTR(NSOpenGLPFADoubleBuffer);
  823. ADD_ATTR(NSOpenGLPFAClosestPolicy);
  824. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  825. if (false /* use gl3*/)
  826. ADD_ATTR2(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core);
  827. #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/
  828. ADD_ATTR2(NSOpenGLPFAColorSize, colorBits);
  829. /*
  830. if (fbconfig->alphaBits > 0)
  831. ADD_ATTR2(NSOpenGLPFAAlphaSize, fbconfig->alphaBits);
  832. */
  833. ADD_ATTR2(NSOpenGLPFADepthSize, 24);
  834. ADD_ATTR2(NSOpenGLPFAStencilSize, 8);
  835. /*
  836. if (fbconfig->stereo)
  837. ADD_ATTR(NSOpenGLPFAStereo);
  838. */
  839. /*
  840. if (fbconfig->samples > 0) {
  841. ADD_ATTR2(NSOpenGLPFASampleBuffers, 1);
  842. ADD_ATTR2(NSOpenGLPFASamples, fbconfig->samples);
  843. }
  844. */
  845. // NOTE: All NSOpenGLPixelFormats on the relevant cards support sRGB
  846. // frambuffer, so there's no need (and no way) to request it
  847. ADD_ATTR(0);
  848. #undef ADD_ATTR
  849. #undef ADD_ATTR2
  850. pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attributes];
  851. ERR_FAIL_COND(pixelFormat == nil);
  852. context = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:nil];
  853. ERR_FAIL_COND(context == nil);
  854. [context setView:window_view];
  855. [context makeCurrentContext];
  856. [NSApp activateIgnoringOtherApps:YES];
  857. [window_object makeKeyAndOrderFront:nil];
  858. if (p_desired.fullscreen)
  859. zoomed = true;
  860. /*** END OSX INITIALIZATION ***/
  861. /*** END OSX INITIALIZATION ***/
  862. /*** END OSX INITIALIZATION ***/
  863. bool use_gl2 = p_video_driver != 1;
  864. AudioDriverManagerSW::add_driver(&audio_driver_osx);
  865. rasterizer = instance_RasterizerGLES2();
  866. visual_server = memnew(VisualServerRaster(rasterizer));
  867. if (get_render_thread_mode() != RENDER_THREAD_UNSAFE) {
  868. visual_server = memnew(VisualServerWrapMT(visual_server, get_render_thread_mode() == RENDER_SEPARATE_THREAD));
  869. }
  870. visual_server->init();
  871. AudioDriverManagerSW::initialize(p_audio_driver);
  872. sample_manager = memnew(SampleManagerMallocSW);
  873. audio_server = memnew(AudioServerSW(sample_manager));
  874. audio_server->set_mixer_params(AudioMixerSW::INTERPOLATION_LINEAR, false);
  875. audio_server->init();
  876. spatial_sound_server = memnew(SpatialSoundServerSW);
  877. spatial_sound_server->init();
  878. spatial_sound_2d_server = memnew(SpatialSound2DServerSW);
  879. spatial_sound_2d_server->init();
  880. physics_server = memnew(PhysicsServerSW);
  881. physics_server->init();
  882. //physics_2d_server = memnew( Physics2DServerSW );
  883. physics_2d_server = Physics2DServerWrapMT::init_server<Physics2DServerSW>();
  884. physics_2d_server->init();
  885. input = memnew(InputDefault);
  886. joystick_osx = memnew(JoystickOSX);
  887. _ensure_data_dir();
  888. restore_rect = Rect2(get_window_position(), get_window_size());
  889. }
  890. void OS_OSX::finalize() {
  891. CFNotificationCenterRemoveObserver(CFNotificationCenterGetDistributedCenter(), NULL, kTISNotifySelectedKeyboardInputSourceChanged, NULL);
  892. CGDisplayRemoveReconfigurationCallback(displays_arrangement_changed, NULL);
  893. delete_main_loop();
  894. spatial_sound_server->finish();
  895. memdelete(spatial_sound_server);
  896. spatial_sound_2d_server->finish();
  897. memdelete(spatial_sound_2d_server);
  898. memdelete(joystick_osx);
  899. memdelete(input);
  900. memdelete(sample_manager);
  901. audio_server->finish();
  902. memdelete(audio_server);
  903. visual_server->finish();
  904. memdelete(visual_server);
  905. memdelete(rasterizer);
  906. physics_server->finish();
  907. memdelete(physics_server);
  908. physics_2d_server->finish();
  909. memdelete(physics_2d_server);
  910. }
  911. void OS_OSX::set_main_loop(MainLoop *p_main_loop) {
  912. main_loop = p_main_loop;
  913. input->set_main_loop(p_main_loop);
  914. }
  915. void OS_OSX::delete_main_loop() {
  916. if (!main_loop)
  917. return;
  918. memdelete(main_loop);
  919. main_loop = NULL;
  920. }
  921. String OS_OSX::get_name() {
  922. return "OSX";
  923. }
  924. void OS_OSX::print_error(const char *p_function, const char *p_file, int p_line, const char *p_code, const char *p_rationale, ErrorType p_type) {
  925. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
  926. if (!_print_error_enabled)
  927. return;
  928. const char *err_details;
  929. if (p_rationale && p_rationale[0])
  930. err_details = p_rationale;
  931. else
  932. err_details = p_code;
  933. switch (p_type) {
  934. case ERR_ERROR:
  935. os_log_error(OS_LOG_DEFAULT, "ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.", p_function, err_details, p_file, p_line);
  936. print("\E[1;31mERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  937. print("\E[0;31m At: %s:%i.\E[0m\n", p_file, p_line);
  938. break;
  939. case ERR_WARNING:
  940. os_log_info(OS_LOG_DEFAULT, "WARNING: %{public}s: %{public}s\nAt: %{public}s:%i.", p_function, err_details, p_file, p_line);
  941. print("\E[1;33mWARNING: %s: \E[0m\E[1m%s\n", p_function, err_details);
  942. print("\E[0;33m At: %s:%i.\E[0m\n", p_file, p_line);
  943. break;
  944. case ERR_SCRIPT:
  945. os_log_error(OS_LOG_DEFAULT, "SCRIPT ERROR: %{public}s: %{public}s\nAt: %{public}s:%i.", p_function, err_details, p_file, p_line);
  946. print("\E[1;35mSCRIPT ERROR: %s: \E[0m\E[1m%s\n", p_function, err_details);
  947. print("\E[0;35m At: %s:%i.\E[0m\n", p_file, p_line);
  948. break;
  949. }
  950. #else
  951. OS_Unix::print_error(p_function, p_file, p_line, p_code, p_rationale, p_type);
  952. #endif
  953. }
  954. void OS_OSX::alert(const String &p_alert, const String &p_title) {
  955. // Set OS X-compliant variables
  956. NSAlert *window = [[NSAlert alloc] init];
  957. NSString *ns_title = [NSString stringWithUTF8String:p_title.utf8().get_data()];
  958. NSString *ns_alert = [NSString stringWithUTF8String:p_alert.utf8().get_data()];
  959. [window addButtonWithTitle:@"OK"];
  960. [window setMessageText:ns_title];
  961. [window setInformativeText:ns_alert];
  962. [window setAlertStyle:NSWarningAlertStyle];
  963. // Display it, then release
  964. [window runModal];
  965. [window release];
  966. }
  967. void OS_OSX::set_cursor_shape(CursorShape p_shape) {
  968. if (cursor_shape == p_shape)
  969. return;
  970. if (mouse_mode != MOUSE_MODE_VISIBLE) {
  971. cursor_shape = p_shape;
  972. return;
  973. }
  974. if (cursors[p_shape] != NULL) {
  975. [cursors[p_shape] set];
  976. } else {
  977. switch (p_shape) {
  978. case CURSOR_ARROW: [[NSCursor arrowCursor] set]; break;
  979. case CURSOR_IBEAM: [[NSCursor IBeamCursor] set]; break;
  980. case CURSOR_POINTING_HAND: [[NSCursor pointingHandCursor] set]; break;
  981. case CURSOR_CROSS: [[NSCursor crosshairCursor] set]; break;
  982. case CURSOR_WAIT: [[NSCursor arrowCursor] set]; break;
  983. case CURSOR_BUSY: [[NSCursor arrowCursor] set]; break;
  984. case CURSOR_DRAG: [[NSCursor closedHandCursor] set]; break;
  985. case CURSOR_CAN_DROP: [[NSCursor openHandCursor] set]; break;
  986. case CURSOR_FORBIDDEN: [[NSCursor arrowCursor] set]; break;
  987. case CURSOR_VSIZE: [[NSCursor resizeUpDownCursor] set]; break;
  988. case CURSOR_HSIZE: [[NSCursor resizeLeftRightCursor] set]; break;
  989. case CURSOR_BDIAGSIZE: [[NSCursor arrowCursor] set]; break;
  990. case CURSOR_FDIAGSIZE: [[NSCursor arrowCursor] set]; break;
  991. case CURSOR_MOVE: [[NSCursor arrowCursor] set]; break;
  992. case CURSOR_VSPLIT: [[NSCursor resizeUpDownCursor] set]; break;
  993. case CURSOR_HSPLIT: [[NSCursor resizeLeftRightCursor] set]; break;
  994. case CURSOR_HELP: [[NSCursor arrowCursor] set]; break;
  995. default: {
  996. };
  997. }
  998. }
  999. cursor_shape = p_shape;
  1000. }
  1001. void OS_OSX::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  1002. if (p_cursor.is_valid()) {
  1003. Ref<ImageTexture> texture = p_cursor;
  1004. Ref<AtlasTexture> atlas_texture = p_cursor;
  1005. Size2 texture_size;
  1006. Rect2 atlas_rect;
  1007. if (!texture.is_valid() && atlas_texture.is_valid()) {
  1008. texture = atlas_texture->get_atlas();
  1009. atlas_rect.size.width = texture->get_width();
  1010. atlas_rect.size.height = texture->get_height();
  1011. atlas_rect.pos.x = atlas_texture->get_region().pos.x;
  1012. atlas_rect.pos.y = atlas_texture->get_region().pos.y;
  1013. texture_size.width = atlas_texture->get_region().size.x;
  1014. texture_size.height = atlas_texture->get_region().size.y;
  1015. } else if (texture.is_valid()) {
  1016. texture_size.width = texture->get_width();
  1017. texture_size.height = texture->get_height();
  1018. }
  1019. ERR_FAIL_COND(!texture.is_valid());
  1020. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  1021. Image image = texture->get_data();
  1022. NSBitmapImageRep *imgrep = [[NSBitmapImageRep alloc]
  1023. initWithBitmapDataPlanes:NULL
  1024. pixelsWide:int(texture_size.width)
  1025. pixelsHigh:int(texture_size.height)
  1026. bitsPerSample:8
  1027. samplesPerPixel:4
  1028. hasAlpha:YES
  1029. isPlanar:NO
  1030. colorSpaceName:NSDeviceRGBColorSpace
  1031. bytesPerRow:int(texture_size.width) * 4
  1032. bitsPerPixel:32];
  1033. ERR_FAIL_COND(imgrep == nil);
  1034. uint8_t *pixels = [imgrep bitmapData];
  1035. int len = int(texture_size.width * texture_size.height);
  1036. DVector<uint8_t> data = image.get_data();
  1037. DVector<uint8_t>::Read r = data.read();
  1038. /* Premultiply the alpha channel */
  1039. for (int i = 0; i < len; i++) {
  1040. int row_index = floor(i / texture_size.width) + atlas_rect.pos.y;
  1041. int column_index = (i % int(texture_size.width)) + atlas_rect.pos.x;
  1042. if (atlas_texture.is_valid()) {
  1043. column_index = MIN(column_index, atlas_rect.size.width - 1);
  1044. row_index = MIN(row_index, atlas_rect.size.height - 1);
  1045. }
  1046. uint32_t color = image.get_pixel(column_index, row_index).to_ARGB32();
  1047. uint8_t alpha = (color >> 24) & 0xFF;
  1048. pixels[i * 4 + 0] = ((color >> 16) & 0xFF) * alpha / 255;
  1049. pixels[i * 4 + 1] = ((color >> 8) & 0xFF) * alpha / 255;
  1050. pixels[i * 4 + 2] = ((color)&0xFF) * alpha / 255;
  1051. pixels[i * 4 + 3] = alpha;
  1052. }
  1053. NSImage *nsimage = [[NSImage alloc] initWithSize:NSMakeSize(texture_size.width, texture_size.height)];
  1054. [nsimage addRepresentation:imgrep];
  1055. [cursors[p_shape] release];
  1056. NSCursor *cursor = [[NSCursor alloc] initWithImage:nsimage hotSpot:NSMakePoint(p_hotspot.x, p_hotspot.y)];
  1057. cursors[p_shape] = cursor;
  1058. if (p_shape == CURSOR_ARROW) {
  1059. if (mouse_mode == MOUSE_MODE_VISIBLE) {
  1060. [cursor set];
  1061. }
  1062. }
  1063. [imgrep release];
  1064. [nsimage release];
  1065. }
  1066. }
  1067. void OS_OSX::set_mouse_show(bool p_show) {
  1068. }
  1069. void OS_OSX::set_mouse_grab(bool p_grab) {
  1070. }
  1071. bool OS_OSX::is_mouse_grab_enabled() const {
  1072. return mouse_grab;
  1073. }
  1074. void OS_OSX::warp_mouse_pos(const Point2 &p_to) {
  1075. //copied from windows impl with osx native calls
  1076. if (mouse_mode == MOUSE_MODE_CAPTURED) {
  1077. mouse_x = p_to.x;
  1078. mouse_y = p_to.y;
  1079. } else {
  1080. //set OS position
  1081. //local point in window coords
  1082. const NSRect contentRect = [window_view frame];
  1083. NSRect pointInWindowRect = NSMakeRect(p_to.x / display_scale, contentRect.size.height - (p_to.y / display_scale) - 1, 0, 0);
  1084. NSPoint pointOnScreen = [[window_view window] convertRectToScreen:pointInWindowRect].origin;
  1085. //point in scren coords
  1086. CGPoint lMouseWarpPos = { pointOnScreen.x, CGDisplayBounds(CGMainDisplayID()).size.height - pointOnScreen.y };
  1087. //do the warping
  1088. CGEventSourceRef lEventRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
  1089. CGEventSourceSetLocalEventsSuppressionInterval(lEventRef, 0.0);
  1090. CGAssociateMouseAndMouseCursorPosition(false);
  1091. CGWarpMouseCursorPosition(lMouseWarpPos);
  1092. CGAssociateMouseAndMouseCursorPosition(true);
  1093. }
  1094. }
  1095. Point2 OS_OSX::get_mouse_pos() const {
  1096. return Vector2(mouse_x, mouse_y);
  1097. }
  1098. int OS_OSX::get_mouse_button_state() const {
  1099. return button_mask;
  1100. }
  1101. void OS_OSX::set_window_title(const String &p_title) {
  1102. title = p_title;
  1103. [window_object setTitle:[NSString stringWithUTF8String:p_title.utf8().get_data()]];
  1104. }
  1105. void OS_OSX::set_icon(const Image &p_icon) {
  1106. Image img = p_icon;
  1107. img.convert(Image::FORMAT_RGBA);
  1108. NSBitmapImageRep *imgrep = [[[NSBitmapImageRep alloc]
  1109. initWithBitmapDataPlanes:NULL
  1110. pixelsWide:p_icon.get_width()
  1111. pixelsHigh:p_icon.get_height()
  1112. bitsPerSample:8
  1113. samplesPerPixel:4
  1114. hasAlpha:YES
  1115. isPlanar:NO
  1116. colorSpaceName:NSDeviceRGBColorSpace
  1117. bytesPerRow:p_icon.get_width() * 4
  1118. bitsPerPixel:32] autorelease];
  1119. ERR_FAIL_COND(imgrep == nil);
  1120. uint8_t *pixels = [imgrep bitmapData];
  1121. int len = img.get_width() * img.get_height();
  1122. DVector<uint8_t> data = img.get_data();
  1123. DVector<uint8_t>::Read r = data.read();
  1124. /* Premultiply the alpha channel */
  1125. for (int i = 0; i < len; i++) {
  1126. uint8_t alpha = r[i * 4 + 3];
  1127. pixels[i * 4 + 0] = (uint8_t)(((uint16_t)r[i * 4 + 0] * alpha) / 255);
  1128. pixels[i * 4 + 1] = (uint8_t)(((uint16_t)r[i * 4 + 1] * alpha) / 255);
  1129. pixels[i * 4 + 2] = (uint8_t)(((uint16_t)r[i * 4 + 2] * alpha) / 255);
  1130. pixels[i * 4 + 3] = alpha;
  1131. }
  1132. NSImage *nsimg = [[[NSImage alloc] initWithSize:NSMakeSize(img.get_width(), img.get_height())] autorelease];
  1133. ERR_FAIL_COND(nsimg == nil);
  1134. [nsimg addRepresentation:imgrep];
  1135. [NSApp setApplicationIconImage:nsimg];
  1136. }
  1137. MainLoop *OS_OSX::get_main_loop() const {
  1138. return main_loop;
  1139. }
  1140. bool OS_OSX::can_draw() const {
  1141. return true;
  1142. }
  1143. void OS_OSX::set_clipboard(const String &p_text) {
  1144. NSArray *types = [NSArray arrayWithObjects:NSStringPboardType, nil];
  1145. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1146. [pasteboard declareTypes:types owner:nil];
  1147. [pasteboard setString:[NSString stringWithUTF8String:p_text.utf8().get_data()]
  1148. forType:NSStringPboardType];
  1149. }
  1150. String OS_OSX::get_clipboard() const {
  1151. NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  1152. if (![[pasteboard types] containsObject:NSStringPboardType]) {
  1153. return "";
  1154. }
  1155. NSString *object = [pasteboard stringForType:NSStringPboardType];
  1156. if (!object) {
  1157. return "";
  1158. }
  1159. char *utfs = strdup([object UTF8String]);
  1160. String ret;
  1161. ret.parse_utf8(utfs);
  1162. free(utfs);
  1163. return ret;
  1164. }
  1165. void OS_OSX::release_rendering_thread() {
  1166. [NSOpenGLContext clearCurrentContext];
  1167. }
  1168. void OS_OSX::make_rendering_thread() {
  1169. [context makeCurrentContext];
  1170. }
  1171. Error OS_OSX::shell_open(String p_uri) {
  1172. NSString *string = [NSString stringWithUTF8String:p_uri.utf8().get_data()];
  1173. NSURL *uri = [[NSURL alloc] initWithString:string];
  1174. // Escape special characters in filenames
  1175. if (!uri || !uri.scheme || [uri.scheme isEqual:@"file"]) {
  1176. uri = [[NSURL alloc] initWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  1177. }
  1178. [[NSWorkspace sharedWorkspace] openURL:uri];
  1179. return OK;
  1180. }
  1181. String OS_OSX::get_locale() const {
  1182. NSString *locale_code = [[NSLocale preferredLanguages] objectAtIndex:0];
  1183. return [locale_code UTF8String];
  1184. }
  1185. void OS_OSX::swap_buffers() {
  1186. [context flushBuffer];
  1187. }
  1188. void OS_OSX::wm_minimized(bool p_minimized) {
  1189. minimized = p_minimized;
  1190. };
  1191. void OS_OSX::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  1192. }
  1193. OS::VideoMode OS_OSX::get_video_mode(int p_screen) const {
  1194. VideoMode vm;
  1195. vm.width = window_size.width;
  1196. vm.height = window_size.height;
  1197. return vm;
  1198. }
  1199. void OS_OSX::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  1200. }
  1201. int OS_OSX::get_screen_count() const {
  1202. NSArray *screenArray = [NSScreen screens];
  1203. return [screenArray count];
  1204. };
  1205. // Returns the native top-left screen coordinate of the smallest rectangle
  1206. // that encompasses all screens. Needed in get_screen_position(),
  1207. // get_window_position, and set_window_position()
  1208. // to convert between OS X native screen coordinates and the ones expected by Godot
  1209. Point2 OS_OSX::get_screens_origin() const {
  1210. static Point2 origin;
  1211. if (displays_arrangement_dirty) {
  1212. origin = Point2();
  1213. for (int i = 0; i < get_screen_count(); i++) {
  1214. Point2 position = get_native_screen_position(i);
  1215. if (position.x < origin.x) {
  1216. origin.x = position.x;
  1217. }
  1218. if (position.y > origin.y) {
  1219. origin.y = position.y;
  1220. }
  1221. }
  1222. displays_arrangement_dirty = false;
  1223. }
  1224. return origin;
  1225. }
  1226. static int get_screen_index(NSScreen *screen) {
  1227. const NSUInteger index = [[NSScreen screens] indexOfObject:screen];
  1228. return index == NSNotFound ? 0 : index;
  1229. }
  1230. int OS_OSX::get_current_screen() const {
  1231. if (window_object) {
  1232. return get_screen_index([window_object screen]);
  1233. } else {
  1234. return get_screen_index([NSScreen mainScreen]);
  1235. }
  1236. };
  1237. void OS_OSX::set_current_screen(int p_screen) {
  1238. Vector2 wpos = get_window_position() - get_screen_position(get_current_screen());
  1239. set_window_position(wpos + get_screen_position(p_screen));
  1240. };
  1241. Point2 OS_OSX::get_native_screen_position(int p_screen) const {
  1242. NSArray *screenArray = [NSScreen screens];
  1243. if (p_screen < [screenArray count]) {
  1244. float displayScale = 1.0;
  1245. if (display_scale > 1.0 && [[screenArray objectAtIndex:p_screen] respondsToSelector:@selector(backingScaleFactor)]) {
  1246. displayScale = [[screenArray objectAtIndex:p_screen] backingScaleFactor];
  1247. }
  1248. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1249. // Return the top-left corner of the screen, for OS X the y starts at the bottom
  1250. return Point2(nsrect.origin.x, nsrect.origin.y + nsrect.size.height) * displayScale;
  1251. }
  1252. return Point2();
  1253. }
  1254. Point2 OS_OSX::get_screen_position(int p_screen) const {
  1255. Point2 position = get_native_screen_position(p_screen) - get_screens_origin();
  1256. // OS X native y-coordinate relative to get_screens_origin() is negative,
  1257. // Godot expects a positive value
  1258. position.y *= -1;
  1259. return position;
  1260. }
  1261. int OS_OSX::get_screen_dpi(int p_screen) const {
  1262. NSArray *screenArray = [NSScreen screens];
  1263. if (p_screen < [screenArray count]) {
  1264. float displayScale = 1.0;
  1265. if (display_scale > 1.0 && [[screenArray objectAtIndex:p_screen] respondsToSelector:@selector(backingScaleFactor)]) {
  1266. displayScale = [[screenArray objectAtIndex:p_screen] backingScaleFactor];
  1267. }
  1268. NSDictionary *description = [[screenArray objectAtIndex:p_screen] deviceDescription];
  1269. NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
  1270. CGSize displayPhysicalSize = CGDisplayScreenSize(
  1271. [[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
  1272. return (displayPixelSize.width * 25.4f / displayPhysicalSize.width) * displayScale;
  1273. }
  1274. return 72;
  1275. }
  1276. Size2 OS_OSX::get_screen_size(int p_screen) const {
  1277. NSArray *screenArray = [NSScreen screens];
  1278. if (p_screen < [screenArray count]) {
  1279. float displayScale = 1.0;
  1280. if (display_scale > 1.0 && [[screenArray objectAtIndex:p_screen] respondsToSelector:@selector(backingScaleFactor)]) {
  1281. displayScale = [[screenArray objectAtIndex:p_screen] backingScaleFactor];
  1282. }
  1283. // Note: Use frame to get the whole screen size
  1284. NSRect nsrect = [[screenArray objectAtIndex:p_screen] frame];
  1285. return Size2(nsrect.size.width, nsrect.size.height) * displayScale;
  1286. }
  1287. return Size2();
  1288. }
  1289. Point2 OS_OSX::get_native_window_position() const {
  1290. NSRect nsrect = [window_object frame];
  1291. Point2 pos;
  1292. // Return the position of the top-left corner, for OS X the y starts at the bottom
  1293. pos.x = nsrect.origin.x * display_scale;
  1294. pos.y = (nsrect.origin.y + nsrect.size.height) * display_scale;
  1295. return pos;
  1296. };
  1297. Point2 OS_OSX::get_window_position() const {
  1298. Point2 position = get_native_window_position() - get_screens_origin();
  1299. // OS X native y-coordinate relative to get_screens_origin() is negative,
  1300. // Godot expects a positive value
  1301. position.y *= -1;
  1302. return position;
  1303. }
  1304. void OS_OSX::_update_window() {
  1305. bool borderless_full = false;
  1306. if (get_borderless_window()) {
  1307. NSRect frameRect = [window_object frame];
  1308. NSRect screenRect = [[window_object screen] frame];
  1309. // Check if our window covers up the screen
  1310. if (frameRect.origin.x <= screenRect.origin.x && frameRect.origin.y <= frameRect.origin.y &&
  1311. frameRect.size.width >= screenRect.size.width && frameRect.size.height >= screenRect.size.height) {
  1312. borderless_full = true;
  1313. }
  1314. }
  1315. if (borderless_full) {
  1316. // If the window covers up the screen set the level to above the main menu and hide on deactivate
  1317. [window_object setLevel:NSMainMenuWindowLevel + 1];
  1318. [window_object setHidesOnDeactivate:YES];
  1319. } else {
  1320. // Reset these when our window is not a borderless window that covers up the screen
  1321. [window_object setLevel:NSNormalWindowLevel];
  1322. [window_object setHidesOnDeactivate:NO];
  1323. }
  1324. }
  1325. void OS_OSX::set_native_window_position(const Point2 &p_position) {
  1326. NSPoint pos;
  1327. pos.x = p_position.x / display_scale;
  1328. pos.y = p_position.y / display_scale;
  1329. [window_object setFrameTopLeftPoint:pos];
  1330. _update_window();
  1331. };
  1332. void OS_OSX::set_window_position(const Point2 &p_position) {
  1333. Point2 position = p_position;
  1334. // OS X native y-coordinate relative to get_screens_origin() is negative,
  1335. // Godot passes a positive value
  1336. position.y *= -1;
  1337. set_native_window_position(get_screens_origin() + position);
  1338. };
  1339. Size2 OS_OSX::get_window_size() const {
  1340. return window_size;
  1341. };
  1342. Size2 OS_OSX::get_real_window_size() const {
  1343. NSRect frame = [window_object frame];
  1344. return Size2(frame.size.width, frame.size.height);
  1345. }
  1346. void OS_OSX::set_window_size(const Size2 p_size) {
  1347. Size2 size = p_size;
  1348. if (get_borderless_window() == false) {
  1349. // NSRect used by setFrame includes the title bar, so add it to our size.y
  1350. CGFloat menuBarHeight = [[[NSApplication sharedApplication] mainMenu] menuBarHeight];
  1351. if (menuBarHeight != 0.f) {
  1352. size.y += menuBarHeight;
  1353. #if MAC_OS_X_VERSION_MAX_ALLOWED <= 101104
  1354. } else {
  1355. size.y += [[NSStatusBar systemStatusBar] thickness];
  1356. #endif
  1357. }
  1358. }
  1359. NSRect frame = [window_object frame];
  1360. [window_object setFrame:NSMakeRect(frame.origin.x, frame.origin.y, size.x, size.y) display:YES];
  1361. _update_window();
  1362. };
  1363. void OS_OSX::set_window_fullscreen(bool p_enabled) {
  1364. if (zoomed != p_enabled) {
  1365. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  1366. [window_object toggleFullScreen:nil];
  1367. #else
  1368. [window_object performZoom:nil];
  1369. #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/
  1370. }
  1371. zoomed = p_enabled;
  1372. };
  1373. bool OS_OSX::is_window_fullscreen() const {
  1374. #if MAC_OS_X_VERSION_MAX_ALLOWED < 1070
  1375. if ([window_object respondsToSelector:@selector(isZoomed)])
  1376. return [window_object isZoomed];
  1377. #endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/
  1378. return zoomed;
  1379. };
  1380. void OS_OSX::set_window_resizable(bool p_enabled) {
  1381. if (p_enabled)
  1382. [window_object setStyleMask:[window_object styleMask] | NSResizableWindowMask];
  1383. else
  1384. [window_object setStyleMask:[window_object styleMask] & ~NSResizableWindowMask];
  1385. };
  1386. bool OS_OSX::is_window_resizable() const {
  1387. return [window_object styleMask] & NSResizableWindowMask;
  1388. };
  1389. void OS_OSX::set_window_minimized(bool p_enabled) {
  1390. if (p_enabled)
  1391. [window_object performMiniaturize:nil];
  1392. else
  1393. [window_object deminiaturize:nil];
  1394. };
  1395. bool OS_OSX::is_window_minimized() const {
  1396. if ([window_object respondsToSelector:@selector(isMiniaturized)])
  1397. return [window_object isMiniaturized];
  1398. return minimized;
  1399. };
  1400. void OS_OSX::set_window_maximized(bool p_enabled) {
  1401. if (p_enabled) {
  1402. restore_rect = Rect2(get_window_position(), get_window_size());
  1403. [window_object setFrame:[[[NSScreen screens] objectAtIndex:get_current_screen()] visibleFrame] display:YES];
  1404. } else {
  1405. set_window_size(restore_rect.size);
  1406. set_window_position(restore_rect.pos);
  1407. };
  1408. maximized = p_enabled;
  1409. };
  1410. bool OS_OSX::is_window_maximized() const {
  1411. // don't know
  1412. return maximized;
  1413. };
  1414. void OS_OSX::move_window_to_foreground() {
  1415. [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
  1416. [window_object makeKeyAndOrderFront:nil];
  1417. }
  1418. void OS_OSX::set_window_always_on_top(bool p_enabled) {
  1419. if (is_window_always_on_top() == p_enabled)
  1420. return;
  1421. if (p_enabled)
  1422. [window_object setLevel:NSFloatingWindowLevel];
  1423. else
  1424. [window_object setLevel:NSNormalWindowLevel];
  1425. }
  1426. bool OS_OSX::is_window_always_on_top() const {
  1427. return [window_object level] == NSFloatingWindowLevel;
  1428. }
  1429. void OS_OSX::request_attention() {
  1430. [NSApp requestUserAttention:NSCriticalRequest];
  1431. }
  1432. void OS_OSX::set_borderless_window(int p_borderless) {
  1433. // OrderOut prevents a lose focus bug with the window
  1434. [window_object orderOut:nil];
  1435. if (p_borderless) {
  1436. [window_object setStyleMask:NSWindowStyleMaskBorderless];
  1437. } else {
  1438. [window_object setStyleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask];
  1439. // Force update of the window styles
  1440. NSRect frameRect = [window_object frame];
  1441. [window_object setFrame:NSMakeRect(frameRect.origin.x, frameRect.origin.y, frameRect.size.width + 1, frameRect.size.height) display:NO];
  1442. [window_object setFrame:frameRect display:NO];
  1443. // Restore the window title
  1444. [window_object setTitle:[NSString stringWithUTF8String:title.utf8().get_data()]];
  1445. }
  1446. _update_window();
  1447. [window_object makeKeyAndOrderFront:nil];
  1448. }
  1449. bool OS_OSX::get_borderless_window() {
  1450. return [window_object styleMask] == NSWindowStyleMaskBorderless;
  1451. }
  1452. String OS_OSX::get_executable_path() const {
  1453. int ret;
  1454. pid_t pid;
  1455. char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
  1456. pid = getpid();
  1457. ret = proc_pidpath(pid, pathbuf, sizeof(pathbuf));
  1458. if (ret <= 0) {
  1459. return OS::get_executable_path();
  1460. } else {
  1461. String path;
  1462. path.parse_utf8(pathbuf);
  1463. return path;
  1464. }
  1465. }
  1466. // Returns string representation of keys, if they are printable.
  1467. //
  1468. static NSString *createStringForKeys(const CGKeyCode *keyCode, int length) {
  1469. TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
  1470. if (!currentKeyboard)
  1471. return nil;
  1472. CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
  1473. if (!layoutData)
  1474. return nil;
  1475. const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
  1476. OSStatus err;
  1477. CFMutableStringRef output = CFStringCreateMutable(NULL, 0);
  1478. for (int i = 0; i < length; ++i) {
  1479. UInt32 keysDown = 0;
  1480. UniChar chars[4];
  1481. UniCharCount realLength;
  1482. err = UCKeyTranslate(keyboardLayout,
  1483. keyCode[i],
  1484. kUCKeyActionDisplay,
  1485. 0,
  1486. LMGetKbdType(),
  1487. kUCKeyTranslateNoDeadKeysBit,
  1488. &keysDown,
  1489. sizeof(chars) / sizeof(chars[0]),
  1490. &realLength,
  1491. chars);
  1492. if (err != noErr) {
  1493. CFRelease(output);
  1494. return nil;
  1495. }
  1496. CFStringAppendCharacters(output, chars, 1);
  1497. }
  1498. //CFStringUppercase(output, NULL);
  1499. return (NSString *)output;
  1500. }
  1501. OS::LatinKeyboardVariant OS_OSX::get_latin_keyboard_variant() const {
  1502. static LatinKeyboardVariant layout = LATIN_KEYBOARD_QWERTY;
  1503. if (keyboard_layout_dirty) {
  1504. layout = LATIN_KEYBOARD_QWERTY;
  1505. CGKeyCode keys[] = { kVK_ANSI_Q, kVK_ANSI_W, kVK_ANSI_E, kVK_ANSI_R, kVK_ANSI_T, kVK_ANSI_Y };
  1506. NSString *test = createStringForKeys(keys, 6);
  1507. if ([test isEqualToString:@"qwertz"]) {
  1508. layout = LATIN_KEYBOARD_QWERTZ;
  1509. } else if ([test isEqualToString:@"azerty"]) {
  1510. layout = LATIN_KEYBOARD_AZERTY;
  1511. } else if ([test isEqualToString:@"qzerty"]) {
  1512. layout = LATIN_KEYBOARD_QZERTY;
  1513. } else if ([test isEqualToString:@"',.pyf"]) {
  1514. layout = LATIN_KEYBOARD_DVORAK;
  1515. } else if ([test isEqualToString:@"xvlcwk"]) {
  1516. layout = LATIN_KEYBOARD_NEO;
  1517. } else if ([test isEqualToString:@"qwfpgj"]) {
  1518. layout = LATIN_KEYBOARD_COLEMAK;
  1519. }
  1520. [test release];
  1521. keyboard_layout_dirty = false;
  1522. return layout;
  1523. }
  1524. return layout;
  1525. }
  1526. void OS_OSX::process_events() {
  1527. while (true) {
  1528. NSEvent *event = [NSApp
  1529. nextEventMatchingMask:NSAnyEventMask
  1530. untilDate:[NSDate distantPast]
  1531. inMode:NSDefaultRunLoopMode
  1532. dequeue:YES];
  1533. if (event == nil)
  1534. break;
  1535. [NSApp sendEvent:event];
  1536. }
  1537. [autoreleasePool drain];
  1538. autoreleasePool = [[NSAutoreleasePool alloc] init];
  1539. }
  1540. void OS_OSX::push_input(const InputEvent &p_event) {
  1541. InputEvent ev = p_event;
  1542. ev.ID = last_id++;
  1543. input->parse_input_event(ev);
  1544. }
  1545. void OS_OSX::run() {
  1546. force_quit = false;
  1547. if (!main_loop)
  1548. return;
  1549. main_loop->init();
  1550. if (zoomed) {
  1551. zoomed = false;
  1552. set_window_fullscreen(true);
  1553. }
  1554. //uint64_t last_ticks=get_ticks_usec();
  1555. //int frames=0;
  1556. //uint64_t frame=0;
  1557. while (!force_quit) {
  1558. process_events(); // get rid of pending events
  1559. last_id = joystick_osx->process_joysticks(last_id);
  1560. if (Main::iteration() == true)
  1561. break;
  1562. };
  1563. main_loop->finish();
  1564. }
  1565. void OS_OSX::set_mouse_mode(MouseMode p_mode) {
  1566. if (p_mode == mouse_mode)
  1567. return;
  1568. if (p_mode == MOUSE_MODE_CAPTURED) {
  1569. // Apple Docs state that the display parameter is not used.
  1570. // "This parameter is not used. By default, you may pass kCGDirectMainDisplay."
  1571. // https://developer.apple.com/library/mac/documentation/graphicsimaging/reference/Quartz_Services_Ref/Reference/reference.html
  1572. CGDisplayHideCursor(kCGDirectMainDisplay);
  1573. CGAssociateMouseAndMouseCursorPosition(false);
  1574. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  1575. CGDisplayHideCursor(kCGDirectMainDisplay);
  1576. CGAssociateMouseAndMouseCursorPosition(true);
  1577. } else {
  1578. CGDisplayShowCursor(kCGDirectMainDisplay);
  1579. CGAssociateMouseAndMouseCursorPosition(true);
  1580. }
  1581. mouse_mode = p_mode;
  1582. }
  1583. OS::MouseMode OS_OSX::get_mouse_mode() const {
  1584. return mouse_mode;
  1585. }
  1586. String OS_OSX::get_joy_guid(int p_device) const {
  1587. return input->get_joy_guid_remapped(p_device);
  1588. }
  1589. Error OS_OSX::move_path_to_trash(String p_dir) {
  1590. NSFileManager *fm = [NSFileManager defaultManager];
  1591. NSURL *url = [NSURL fileURLWithPath:@(p_dir.utf8().get_data())];
  1592. NSError *err;
  1593. if (![fm trashItemAtURL:url resultingItemURL:nil error:&err]) {
  1594. ERR_PRINTS("trashItemAtURL error: " + String(err.localizedDescription.UTF8String));
  1595. return FAILED;
  1596. }
  1597. return OK;
  1598. }
  1599. void OS_OSX::set_use_vsync(bool p_enable) {
  1600. CGLContextObj ctx = CGLGetCurrentContext();
  1601. if (ctx) {
  1602. GLint swapInterval = p_enable ? 1 : 0;
  1603. CGLSetParameter(ctx, kCGLCPSwapInterval, &swapInterval);
  1604. }
  1605. }
  1606. bool OS_OSX::is_vsync_enabled() const {
  1607. GLint swapInterval = 0;
  1608. CGLContextObj ctx = CGLGetCurrentContext();
  1609. if (ctx) {
  1610. CGLGetParameter(ctx, kCGLCPSwapInterval, &swapInterval);
  1611. }
  1612. return swapInterval ? true : false;
  1613. }
  1614. OS_OSX *OS_OSX::singleton = NULL;
  1615. OS_OSX::OS_OSX() {
  1616. mouse_mode = OS::MOUSE_MODE_VISIBLE;
  1617. main_loop = NULL;
  1618. singleton = this;
  1619. autoreleasePool = [[NSAutoreleasePool alloc] init];
  1620. eventSource = CGEventSourceCreate(kCGEventSourceStateHIDSystemState);
  1621. ERR_FAIL_COND(!eventSource);
  1622. CGEventSourceSetLocalEventsSuppressionInterval(eventSource, 0.0);
  1623. /*
  1624. if (pthread_key_create(&_Godot.nsgl.current, NULL) != 0) {
  1625. _GodotInputError(Godot_PLATFORM_ERROR,
  1626. "NSGL: Failed to create context TLS");
  1627. return GL_FALSE;
  1628. }
  1629. */
  1630. framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl"));
  1631. ERR_FAIL_COND(!framework);
  1632. // Implicitly create shared NSApplication instance
  1633. [GodotApplication sharedApplication];
  1634. // In case we are unbundled, make us a proper UI application
  1635. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  1636. // Menu bar setup must go between sharedApplication above and
  1637. // finishLaunching below, in order to properly emulate the behavior
  1638. // of NSApplicationMain
  1639. NSMenuItem *menu_item;
  1640. NSString *title;
  1641. NSString *nsappname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
  1642. if (nsappname == nil)
  1643. nsappname = [[NSProcessInfo processInfo] processName];
  1644. // Setup Apple menu
  1645. NSMenu *apple_menu = [[NSMenu alloc] initWithTitle:@""];
  1646. title = [NSString stringWithFormat:NSLocalizedString(@"About %@", nil), nsappname];
  1647. [apple_menu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
  1648. [apple_menu addItem:[NSMenuItem separatorItem]];
  1649. NSMenu *services = [[NSMenu alloc] initWithTitle:@""];
  1650. menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Services", nil) action:nil keyEquivalent:@""];
  1651. [apple_menu setSubmenu:services forItem:menu_item];
  1652. [NSApp setServicesMenu:services];
  1653. [services release];
  1654. [apple_menu addItem:[NSMenuItem separatorItem]];
  1655. title = [NSString stringWithFormat:NSLocalizedString(@"Hide %@", nil), nsappname];
  1656. [apple_menu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];
  1657. menu_item = [apple_menu addItemWithTitle:NSLocalizedString(@"Hide Others", nil) action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
  1658. [menu_item setKeyEquivalentModifierMask:(NSAlternateKeyMask | NSCommandKeyMask)];
  1659. [apple_menu addItemWithTitle:NSLocalizedString(@"Show all", nil) action:@selector(unhideAllApplications:) keyEquivalent:@""];
  1660. [apple_menu addItem:[NSMenuItem separatorItem]];
  1661. title = [NSString stringWithFormat:NSLocalizedString(@"Quit %@", nil), nsappname];
  1662. [apple_menu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
  1663. // Setup menu bar
  1664. NSMenu *main_menu = [[NSMenu alloc] initWithTitle:@""];
  1665. menu_item = [main_menu addItemWithTitle:@"" action:nil keyEquivalent:@""];
  1666. [main_menu setSubmenu:apple_menu forItem:menu_item];
  1667. [NSApp setMainMenu:main_menu];
  1668. [main_menu release];
  1669. [apple_menu release];
  1670. [NSApp finishLaunching];
  1671. delegate = [[GodotApplicationDelegate alloc] init];
  1672. ERR_FAIL_COND(!delegate);
  1673. [NSApp setDelegate:delegate];
  1674. last_id = 1;
  1675. cursor_shape = CURSOR_ARROW;
  1676. maximized = false;
  1677. minimized = false;
  1678. window_size = Vector2(1024, 600);
  1679. zoomed = false;
  1680. display_scale = 1.0;
  1681. }
  1682. void OS_OSX::disable_crash_handler() {
  1683. crash_handler.disable();
  1684. }
  1685. bool OS_OSX::is_disable_crash_handler() const {
  1686. return crash_handler.is_disabled();
  1687. }