cocoa_window.m 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071
  1. //========================================================================
  2. // GLFW 3.5 macOS - www.glfw.org
  3. //------------------------------------------------------------------------
  4. // Copyright (c) 2009-2019 Camilla Löwy <[email protected]>
  5. //
  6. // This software is provided 'as-is', without any express or implied
  7. // warranty. In no event will the authors be held liable for any damages
  8. // arising from the use of this software.
  9. //
  10. // Permission is granted to anyone to use this software for any purpose,
  11. // including commercial applications, and to alter it and redistribute it
  12. // freely, subject to the following restrictions:
  13. //
  14. // 1. The origin of this software must not be misrepresented; you must not
  15. // claim that you wrote the original software. If you use this software
  16. // in a product, an acknowledgment in the product documentation would
  17. // be appreciated but is not required.
  18. //
  19. // 2. Altered source versions must be plainly marked as such, and must not
  20. // be misrepresented as being the original software.
  21. //
  22. // 3. This notice may not be removed or altered from any source
  23. // distribution.
  24. //
  25. //========================================================================
  26. #include "internal.h"
  27. #if defined(_GLFW_COCOA)
  28. #include <float.h>
  29. #include <string.h>
  30. #include <assert.h>
  31. // HACK: This enum value is missing from framework headers on OS X 10.11 despite
  32. // having been (according to documentation) added in Mac OS X 10.7
  33. #define NSWindowCollectionBehaviorFullScreenNone (1 << 9)
  34. // Returns whether the cursor is in the content area of the specified window
  35. //
  36. static GLFWbool cursorInContentArea(_GLFWwindow* window)
  37. {
  38. const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream];
  39. return [window->ns.view mouse:pos inRect:[window->ns.view frame]];
  40. }
  41. // Hides the cursor if not already hidden
  42. //
  43. static void hideCursor(_GLFWwindow* window)
  44. {
  45. if (!_glfw.ns.cursorHidden)
  46. {
  47. [NSCursor hide];
  48. _glfw.ns.cursorHidden = GLFW_TRUE;
  49. }
  50. }
  51. // Shows the cursor if not already shown
  52. //
  53. static void showCursor(_GLFWwindow* window)
  54. {
  55. if (_glfw.ns.cursorHidden)
  56. {
  57. [NSCursor unhide];
  58. _glfw.ns.cursorHidden = GLFW_FALSE;
  59. }
  60. }
  61. // Updates the cursor image according to its cursor mode
  62. //
  63. static void updateCursorImage(_GLFWwindow* window)
  64. {
  65. if (window->cursorMode == GLFW_CURSOR_NORMAL)
  66. {
  67. showCursor(window);
  68. if (window->cursor)
  69. [(NSCursor*) window->cursor->ns.object set];
  70. else
  71. [[NSCursor arrowCursor] set];
  72. }
  73. else
  74. hideCursor(window);
  75. }
  76. // Apply chosen cursor mode to a focused window
  77. //
  78. static void updateCursorMode(_GLFWwindow* window)
  79. {
  80. if (window->cursorMode == GLFW_CURSOR_DISABLED)
  81. {
  82. _glfw.ns.disabledCursorWindow = window;
  83. _glfwGetCursorPosCocoa(window,
  84. &_glfw.ns.restoreCursorPosX,
  85. &_glfw.ns.restoreCursorPosY);
  86. _glfwCenterCursorInContentArea(window);
  87. CGAssociateMouseAndMouseCursorPosition(false);
  88. }
  89. else if (_glfw.ns.disabledCursorWindow == window)
  90. {
  91. _glfw.ns.disabledCursorWindow = NULL;
  92. _glfwSetCursorPosCocoa(window,
  93. _glfw.ns.restoreCursorPosX,
  94. _glfw.ns.restoreCursorPosY);
  95. // NOTE: The matching CGAssociateMouseAndMouseCursorPosition call is
  96. // made in _glfwSetCursorPosCocoa as part of a workaround
  97. }
  98. if (cursorInContentArea(window))
  99. updateCursorImage(window);
  100. }
  101. // Make the specified window and its video mode active on its monitor
  102. //
  103. static void acquireMonitor(_GLFWwindow* window)
  104. {
  105. _glfwSetVideoModeCocoa(window->monitor, &window->videoMode);
  106. const CGRect bounds = CGDisplayBounds(window->monitor->ns.displayID);
  107. const NSRect frame = NSMakeRect(bounds.origin.x,
  108. _glfwTransformYCocoa(bounds.origin.y + bounds.size.height - 1),
  109. bounds.size.width,
  110. bounds.size.height);
  111. [window->ns.object setFrame:frame display:YES];
  112. _glfwInputMonitorWindow(window->monitor, window);
  113. }
  114. // Remove the window and restore the original video mode
  115. //
  116. static void releaseMonitor(_GLFWwindow* window)
  117. {
  118. if (window->monitor->window != window)
  119. return;
  120. _glfwInputMonitorWindow(window->monitor, NULL);
  121. _glfwRestoreVideoModeCocoa(window->monitor);
  122. }
  123. // Translates macOS key modifiers into GLFW ones
  124. //
  125. static int translateFlags(NSUInteger flags)
  126. {
  127. int mods = 0;
  128. if (flags & NSEventModifierFlagShift)
  129. mods |= GLFW_MOD_SHIFT;
  130. if (flags & NSEventModifierFlagControl)
  131. mods |= GLFW_MOD_CONTROL;
  132. if (flags & NSEventModifierFlagOption)
  133. mods |= GLFW_MOD_ALT;
  134. if (flags & NSEventModifierFlagCommand)
  135. mods |= GLFW_MOD_SUPER;
  136. if (flags & NSEventModifierFlagCapsLock)
  137. mods |= GLFW_MOD_CAPS_LOCK;
  138. return mods;
  139. }
  140. // Translates a macOS keycode to a GLFW keycode
  141. //
  142. static int translateKey(unsigned int key)
  143. {
  144. if (key >= sizeof(_glfw.ns.keycodes) / sizeof(_glfw.ns.keycodes[0]))
  145. return GLFW_KEY_UNKNOWN;
  146. return _glfw.ns.keycodes[key];
  147. }
  148. // Translate a GLFW keycode to a Cocoa modifier flag
  149. //
  150. static NSUInteger translateKeyToModifierFlag(int key)
  151. {
  152. switch (key)
  153. {
  154. case GLFW_KEY_LEFT_SHIFT:
  155. case GLFW_KEY_RIGHT_SHIFT:
  156. return NSEventModifierFlagShift;
  157. case GLFW_KEY_LEFT_CONTROL:
  158. case GLFW_KEY_RIGHT_CONTROL:
  159. return NSEventModifierFlagControl;
  160. case GLFW_KEY_LEFT_ALT:
  161. case GLFW_KEY_RIGHT_ALT:
  162. return NSEventModifierFlagOption;
  163. case GLFW_KEY_LEFT_SUPER:
  164. case GLFW_KEY_RIGHT_SUPER:
  165. return NSEventModifierFlagCommand;
  166. case GLFW_KEY_CAPS_LOCK:
  167. return NSEventModifierFlagCapsLock;
  168. }
  169. return 0;
  170. }
  171. // Defines a constant for empty ranges in NSTextInputClient
  172. //
  173. static const NSRange kEmptyRange = { NSNotFound, 0 };
  174. //------------------------------------------------------------------------
  175. // Delegate for window related notifications
  176. //------------------------------------------------------------------------
  177. @interface GLFWWindowDelegate : NSObject
  178. {
  179. _GLFWwindow* window;
  180. }
  181. - (instancetype)initWithGlfwWindow:(_GLFWwindow *)initWindow;
  182. @end
  183. @implementation GLFWWindowDelegate
  184. - (instancetype)initWithGlfwWindow:(_GLFWwindow *)initWindow
  185. {
  186. self = [super init];
  187. if (self != nil)
  188. window = initWindow;
  189. return self;
  190. }
  191. - (BOOL)windowShouldClose:(id)sender
  192. {
  193. _glfwInputWindowCloseRequest(window);
  194. return NO;
  195. }
  196. - (void)windowDidResize:(NSNotification *)notification
  197. {
  198. if (window->context.source == GLFW_NATIVE_CONTEXT_API)
  199. [window->context.nsgl.object update];
  200. if (_glfw.ns.disabledCursorWindow == window)
  201. _glfwCenterCursorInContentArea(window);
  202. const int maximized = [window->ns.object isZoomed];
  203. if (window->ns.maximized != maximized)
  204. {
  205. window->ns.maximized = maximized;
  206. _glfwInputWindowMaximize(window, maximized);
  207. }
  208. const NSRect contentRect = [window->ns.view frame];
  209. const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect];
  210. if (fbRect.size.width != window->ns.fbWidth ||
  211. fbRect.size.height != window->ns.fbHeight)
  212. {
  213. window->ns.fbWidth = fbRect.size.width;
  214. window->ns.fbHeight = fbRect.size.height;
  215. _glfwInputFramebufferSize(window, fbRect.size.width, fbRect.size.height);
  216. }
  217. if (contentRect.size.width != window->ns.width ||
  218. contentRect.size.height != window->ns.height)
  219. {
  220. window->ns.width = contentRect.size.width;
  221. window->ns.height = contentRect.size.height;
  222. _glfwInputWindowSize(window, contentRect.size.width, contentRect.size.height);
  223. }
  224. }
  225. - (void)windowDidMove:(NSNotification *)notification
  226. {
  227. if (window->context.source == GLFW_NATIVE_CONTEXT_API)
  228. [window->context.nsgl.object update];
  229. if (_glfw.ns.disabledCursorWindow == window)
  230. _glfwCenterCursorInContentArea(window);
  231. int x, y;
  232. _glfwGetWindowPosCocoa(window, &x, &y);
  233. _glfwInputWindowPos(window, x, y);
  234. }
  235. - (void)windowDidMiniaturize:(NSNotification *)notification
  236. {
  237. if (window->monitor)
  238. releaseMonitor(window);
  239. _glfwInputWindowIconify(window, GLFW_TRUE);
  240. }
  241. - (void)windowDidDeminiaturize:(NSNotification *)notification
  242. {
  243. if (window->monitor)
  244. acquireMonitor(window);
  245. _glfwInputWindowIconify(window, GLFW_FALSE);
  246. }
  247. - (void)windowDidBecomeKey:(NSNotification *)notification
  248. {
  249. if (_glfw.ns.disabledCursorWindow == window)
  250. _glfwCenterCursorInContentArea(window);
  251. _glfwInputWindowFocus(window, GLFW_TRUE);
  252. updateCursorMode(window);
  253. }
  254. - (void)windowDidResignKey:(NSNotification *)notification
  255. {
  256. if (window->monitor && window->autoIconify)
  257. _glfwIconifyWindowCocoa(window);
  258. _glfwInputWindowFocus(window, GLFW_FALSE);
  259. }
  260. - (void)windowDidChangeOcclusionState:(NSNotification* )notification
  261. {
  262. if ([window->ns.object respondsToSelector:@selector(occlusionState)])
  263. {
  264. if ([window->ns.object occlusionState] & NSWindowOcclusionStateVisible)
  265. window->ns.occluded = GLFW_FALSE;
  266. else
  267. window->ns.occluded = GLFW_TRUE;
  268. }
  269. }
  270. @end
  271. //------------------------------------------------------------------------
  272. // Content view class for the GLFW window
  273. //------------------------------------------------------------------------
  274. @interface GLFWContentView : NSView <NSTextInputClient>
  275. {
  276. _GLFWwindow* window;
  277. NSTrackingArea* trackingArea;
  278. NSMutableAttributedString* markedText;
  279. }
  280. - (instancetype)initWithGlfwWindow:(_GLFWwindow *)initWindow;
  281. @end
  282. @implementation GLFWContentView
  283. - (instancetype)initWithGlfwWindow:(_GLFWwindow *)initWindow
  284. {
  285. self = [super init];
  286. if (self != nil)
  287. {
  288. window = initWindow;
  289. trackingArea = nil;
  290. markedText = [[NSMutableAttributedString alloc] init];
  291. [self updateTrackingAreas];
  292. [self registerForDraggedTypes:@[NSPasteboardTypeURL]];
  293. }
  294. return self;
  295. }
  296. - (void)dealloc
  297. {
  298. [trackingArea release];
  299. [markedText release];
  300. [super dealloc];
  301. }
  302. - (BOOL)isOpaque
  303. {
  304. return [window->ns.object isOpaque];
  305. }
  306. - (BOOL)canBecomeKeyView
  307. {
  308. return YES;
  309. }
  310. - (BOOL)acceptsFirstResponder
  311. {
  312. return YES;
  313. }
  314. - (BOOL)wantsUpdateLayer
  315. {
  316. return YES;
  317. }
  318. - (void)updateLayer
  319. {
  320. if (window->context.source == GLFW_NATIVE_CONTEXT_API)
  321. [window->context.nsgl.object update];
  322. _glfwInputWindowDamage(window);
  323. }
  324. - (void)cursorUpdate:(NSEvent *)event
  325. {
  326. updateCursorImage(window);
  327. }
  328. - (BOOL)acceptsFirstMouse:(NSEvent *)event
  329. {
  330. return YES;
  331. }
  332. - (void)mouseDown:(NSEvent *)event
  333. {
  334. _glfwInputMouseClick(window,
  335. GLFW_MOUSE_BUTTON_LEFT,
  336. GLFW_PRESS,
  337. translateFlags([event modifierFlags]));
  338. }
  339. - (void)mouseDragged:(NSEvent *)event
  340. {
  341. [self mouseMoved:event];
  342. }
  343. - (void)mouseUp:(NSEvent *)event
  344. {
  345. _glfwInputMouseClick(window,
  346. GLFW_MOUSE_BUTTON_LEFT,
  347. GLFW_RELEASE,
  348. translateFlags([event modifierFlags]));
  349. }
  350. - (void)mouseMoved:(NSEvent *)event
  351. {
  352. if (window->cursorMode == GLFW_CURSOR_DISABLED)
  353. {
  354. const double dx = [event deltaX] - window->ns.cursorWarpDeltaX;
  355. const double dy = [event deltaY] - window->ns.cursorWarpDeltaY;
  356. _glfwInputCursorPos(window,
  357. window->virtualCursorPosX + dx,
  358. window->virtualCursorPosY + dy);
  359. }
  360. else
  361. {
  362. const NSRect contentRect = [window->ns.view frame];
  363. // NOTE: The returned location uses base 0,1 not 0,0
  364. const NSPoint pos = [event locationInWindow];
  365. _glfwInputCursorPos(window, pos.x, contentRect.size.height - pos.y);
  366. }
  367. window->ns.cursorWarpDeltaX = 0;
  368. window->ns.cursorWarpDeltaY = 0;
  369. }
  370. - (void)rightMouseDown:(NSEvent *)event
  371. {
  372. _glfwInputMouseClick(window,
  373. GLFW_MOUSE_BUTTON_RIGHT,
  374. GLFW_PRESS,
  375. translateFlags([event modifierFlags]));
  376. }
  377. - (void)rightMouseDragged:(NSEvent *)event
  378. {
  379. [self mouseMoved:event];
  380. }
  381. - (void)rightMouseUp:(NSEvent *)event
  382. {
  383. _glfwInputMouseClick(window,
  384. GLFW_MOUSE_BUTTON_RIGHT,
  385. GLFW_RELEASE,
  386. translateFlags([event modifierFlags]));
  387. }
  388. - (void)otherMouseDown:(NSEvent *)event
  389. {
  390. _glfwInputMouseClick(window,
  391. (int) [event buttonNumber],
  392. GLFW_PRESS,
  393. translateFlags([event modifierFlags]));
  394. }
  395. - (void)otherMouseDragged:(NSEvent *)event
  396. {
  397. [self mouseMoved:event];
  398. }
  399. - (void)otherMouseUp:(NSEvent *)event
  400. {
  401. _glfwInputMouseClick(window,
  402. (int) [event buttonNumber],
  403. GLFW_RELEASE,
  404. translateFlags([event modifierFlags]));
  405. }
  406. - (void)mouseExited:(NSEvent *)event
  407. {
  408. if (window->cursorMode == GLFW_CURSOR_HIDDEN)
  409. showCursor(window);
  410. _glfwInputCursorEnter(window, GLFW_FALSE);
  411. }
  412. - (void)mouseEntered:(NSEvent *)event
  413. {
  414. if (window->cursorMode == GLFW_CURSOR_HIDDEN)
  415. hideCursor(window);
  416. _glfwInputCursorEnter(window, GLFW_TRUE);
  417. }
  418. - (void)viewDidChangeBackingProperties
  419. {
  420. const NSRect contentRect = [window->ns.view frame];
  421. const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect];
  422. const float xscale = fbRect.size.width / contentRect.size.width;
  423. const float yscale = fbRect.size.height / contentRect.size.height;
  424. if (xscale != window->ns.xscale || yscale != window->ns.yscale)
  425. {
  426. if (window->ns.scaleFramebuffer && window->ns.layer)
  427. [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]];
  428. window->ns.xscale = xscale;
  429. window->ns.yscale = yscale;
  430. _glfwInputWindowContentScale(window, xscale, yscale);
  431. }
  432. if (fbRect.size.width != window->ns.fbWidth ||
  433. fbRect.size.height != window->ns.fbHeight)
  434. {
  435. window->ns.fbWidth = fbRect.size.width;
  436. window->ns.fbHeight = fbRect.size.height;
  437. _glfwInputFramebufferSize(window, fbRect.size.width, fbRect.size.height);
  438. }
  439. }
  440. - (void)drawRect:(NSRect)rect
  441. {
  442. _glfwInputWindowDamage(window);
  443. }
  444. - (void)updateTrackingAreas
  445. {
  446. if (trackingArea != nil)
  447. {
  448. [self removeTrackingArea:trackingArea];
  449. [trackingArea release];
  450. }
  451. const NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited |
  452. NSTrackingActiveInKeyWindow |
  453. NSTrackingEnabledDuringMouseDrag |
  454. NSTrackingCursorUpdate |
  455. NSTrackingInVisibleRect |
  456. NSTrackingAssumeInside;
  457. trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds]
  458. options:options
  459. owner:self
  460. userInfo:nil];
  461. [self addTrackingArea:trackingArea];
  462. [super updateTrackingAreas];
  463. }
  464. - (void)keyDown:(NSEvent *)event
  465. {
  466. const int key = translateKey([event keyCode]);
  467. const int mods = translateFlags([event modifierFlags]);
  468. _glfwInputKey(window, key, [event keyCode], GLFW_PRESS, mods);
  469. [self interpretKeyEvents:@[event]];
  470. }
  471. - (void)flagsChanged:(NSEvent *)event
  472. {
  473. int action;
  474. const unsigned int modifierFlags =
  475. [event modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
  476. const int key = translateKey([event keyCode]);
  477. const int mods = translateFlags(modifierFlags);
  478. const NSUInteger keyFlag = translateKeyToModifierFlag(key);
  479. if (keyFlag & modifierFlags)
  480. {
  481. if (window->keys[key] == GLFW_PRESS)
  482. action = GLFW_RELEASE;
  483. else
  484. action = GLFW_PRESS;
  485. }
  486. else
  487. action = GLFW_RELEASE;
  488. _glfwInputKey(window, key, [event keyCode], action, mods);
  489. }
  490. - (void)keyUp:(NSEvent *)event
  491. {
  492. const int key = translateKey([event keyCode]);
  493. const int mods = translateFlags([event modifierFlags]);
  494. _glfwInputKey(window, key, [event keyCode], GLFW_RELEASE, mods);
  495. }
  496. - (void)scrollWheel:(NSEvent *)event
  497. {
  498. double deltaX = [event scrollingDeltaX];
  499. double deltaY = [event scrollingDeltaY];
  500. if ([event hasPreciseScrollingDeltas])
  501. {
  502. deltaX *= 0.1;
  503. deltaY *= 0.1;
  504. }
  505. if (fabs(deltaX) > 0.0 || fabs(deltaY) > 0.0)
  506. _glfwInputScroll(window, deltaX, deltaY);
  507. }
  508. - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
  509. {
  510. // HACK: We don't know what to say here because we don't know what the
  511. // application wants to do with the paths
  512. return NSDragOperationGeneric;
  513. }
  514. - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
  515. {
  516. const NSRect contentRect = [window->ns.view frame];
  517. // NOTE: The returned location uses base 0,1 not 0,0
  518. const NSPoint pos = [sender draggingLocation];
  519. _glfwInputCursorPos(window, pos.x, contentRect.size.height - pos.y);
  520. NSPasteboard* pasteboard = [sender draggingPasteboard];
  521. NSDictionary* options = @{NSPasteboardURLReadingFileURLsOnlyKey:@YES};
  522. NSArray* urls = [pasteboard readObjectsForClasses:@[[NSURL class]]
  523. options:options];
  524. const NSUInteger count = [urls count];
  525. if (count)
  526. {
  527. char** paths = _glfw_calloc(count, sizeof(char*));
  528. for (NSUInteger i = 0; i < count; i++)
  529. paths[i] = _glfw_strdup([urls[i] fileSystemRepresentation]);
  530. _glfwInputDrop(window, (int) count, (const char**) paths);
  531. for (NSUInteger i = 0; i < count; i++)
  532. _glfw_free(paths[i]);
  533. _glfw_free(paths);
  534. }
  535. return YES;
  536. }
  537. - (BOOL)hasMarkedText
  538. {
  539. return [markedText length] > 0;
  540. }
  541. - (NSRange)markedRange
  542. {
  543. if ([markedText length] > 0)
  544. return NSMakeRange(0, [markedText length] - 1);
  545. else
  546. return kEmptyRange;
  547. }
  548. - (NSRange)selectedRange
  549. {
  550. return kEmptyRange;
  551. }
  552. - (void)setMarkedText:(id)string
  553. selectedRange:(NSRange)selectedRange
  554. replacementRange:(NSRange)replacementRange
  555. {
  556. [markedText release];
  557. if ([string isKindOfClass:[NSAttributedString class]])
  558. markedText = [[NSMutableAttributedString alloc] initWithAttributedString:string];
  559. else
  560. markedText = [[NSMutableAttributedString alloc] initWithString:string];
  561. }
  562. - (void)unmarkText
  563. {
  564. [[markedText mutableString] setString:@""];
  565. }
  566. - (NSArray*)validAttributesForMarkedText
  567. {
  568. return [NSArray array];
  569. }
  570. - (NSAttributedString*)attributedSubstringForProposedRange:(NSRange)range
  571. actualRange:(NSRangePointer)actualRange
  572. {
  573. return nil;
  574. }
  575. - (NSUInteger)characterIndexForPoint:(NSPoint)point
  576. {
  577. return 0;
  578. }
  579. - (NSRect)firstRectForCharacterRange:(NSRange)range
  580. actualRange:(NSRangePointer)actualRange
  581. {
  582. const NSRect frame = [window->ns.view frame];
  583. return NSMakeRect(frame.origin.x, frame.origin.y, 0.0, 0.0);
  584. }
  585. - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
  586. {
  587. NSString* characters;
  588. NSEvent* event = [NSApp currentEvent];
  589. const int mods = translateFlags([event modifierFlags]);
  590. const int plain = !(mods & GLFW_MOD_SUPER);
  591. if ([string isKindOfClass:[NSAttributedString class]])
  592. characters = [string string];
  593. else
  594. characters = (NSString*) string;
  595. NSRange range = NSMakeRange(0, [characters length]);
  596. while (range.length)
  597. {
  598. uint32_t codepoint = 0;
  599. if ([characters getBytes:&codepoint
  600. maxLength:sizeof(codepoint)
  601. usedLength:NULL
  602. encoding:NSUTF32StringEncoding
  603. options:0
  604. range:range
  605. remainingRange:&range])
  606. {
  607. if (codepoint >= 0xf700 && codepoint <= 0xf7ff)
  608. continue;
  609. _glfwInputChar(window, codepoint, mods, plain);
  610. }
  611. }
  612. }
  613. - (void)doCommandBySelector:(SEL)selector
  614. {
  615. }
  616. @end
  617. //------------------------------------------------------------------------
  618. // GLFW window class
  619. //------------------------------------------------------------------------
  620. @interface GLFWWindow : NSWindow {}
  621. @end
  622. @implementation GLFWWindow
  623. - (BOOL)canBecomeKeyWindow
  624. {
  625. // Required for NSWindowStyleMaskBorderless windows
  626. return YES;
  627. }
  628. - (BOOL)canBecomeMainWindow
  629. {
  630. return YES;
  631. }
  632. @end
  633. // Create the Cocoa window
  634. //
  635. static GLFWbool createNativeWindow(_GLFWwindow* window,
  636. const _GLFWwndconfig* wndconfig,
  637. const _GLFWfbconfig* fbconfig)
  638. {
  639. window->ns.delegate = [[GLFWWindowDelegate alloc] initWithGlfwWindow:window];
  640. if (window->ns.delegate == nil)
  641. {
  642. _glfwInputError(GLFW_PLATFORM_ERROR,
  643. "Cocoa: Failed to create window delegate");
  644. return GLFW_FALSE;
  645. }
  646. NSRect contentRect;
  647. if (window->monitor)
  648. {
  649. GLFWvidmode mode;
  650. int xpos, ypos;
  651. _glfwGetVideoModeCocoa(window->monitor, &mode);
  652. _glfwGetMonitorPosCocoa(window->monitor, &xpos, &ypos);
  653. contentRect = NSMakeRect(xpos, ypos, mode.width, mode.height);
  654. }
  655. else
  656. {
  657. if (wndconfig->xpos == GLFW_ANY_POSITION ||
  658. wndconfig->ypos == GLFW_ANY_POSITION)
  659. {
  660. contentRect = NSMakeRect(0, 0, wndconfig->width, wndconfig->height);
  661. }
  662. else
  663. {
  664. const int xpos = wndconfig->xpos;
  665. const int ypos = _glfwTransformYCocoa(wndconfig->ypos + wndconfig->height - 1);
  666. contentRect = NSMakeRect(xpos, ypos, wndconfig->width, wndconfig->height);
  667. }
  668. }
  669. NSUInteger styleMask = NSWindowStyleMaskMiniaturizable;
  670. if (window->monitor || !window->decorated)
  671. styleMask |= NSWindowStyleMaskBorderless;
  672. else
  673. {
  674. styleMask |= (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable);
  675. if (window->resizable)
  676. styleMask |= NSWindowStyleMaskResizable;
  677. }
  678. window->ns.object = [[GLFWWindow alloc]
  679. initWithContentRect:contentRect
  680. styleMask:styleMask
  681. backing:NSBackingStoreBuffered
  682. defer:NO];
  683. if (window->ns.object == nil)
  684. {
  685. _glfwInputError(GLFW_PLATFORM_ERROR, "Cocoa: Failed to create window");
  686. return GLFW_FALSE;
  687. }
  688. if (window->monitor)
  689. [window->ns.object setLevel:NSMainMenuWindowLevel + 1];
  690. else
  691. {
  692. if (wndconfig->xpos == GLFW_ANY_POSITION ||
  693. wndconfig->ypos == GLFW_ANY_POSITION)
  694. {
  695. [(NSWindow*) window->ns.object center];
  696. _glfw.ns.cascadePoint =
  697. NSPointToCGPoint([window->ns.object cascadeTopLeftFromPoint:
  698. NSPointFromCGPoint(_glfw.ns.cascadePoint)]);
  699. }
  700. if (wndconfig->resizable)
  701. {
  702. const NSWindowCollectionBehavior behavior =
  703. NSWindowCollectionBehaviorFullScreenPrimary |
  704. NSWindowCollectionBehaviorManaged;
  705. [window->ns.object setCollectionBehavior:behavior];
  706. }
  707. else
  708. {
  709. const NSWindowCollectionBehavior behavior =
  710. NSWindowCollectionBehaviorFullScreenNone;
  711. [window->ns.object setCollectionBehavior:behavior];
  712. }
  713. if (wndconfig->floating)
  714. [window->ns.object setLevel:NSFloatingWindowLevel];
  715. if (wndconfig->maximized)
  716. [window->ns.object zoom:nil];
  717. }
  718. if (strlen(wndconfig->ns.frameName))
  719. [window->ns.object setFrameAutosaveName:@(wndconfig->ns.frameName)];
  720. window->ns.view = [[GLFWContentView alloc] initWithGlfwWindow:window];
  721. window->ns.scaleFramebuffer = wndconfig->scaleFramebuffer;
  722. if (fbconfig->transparent)
  723. {
  724. [window->ns.object setOpaque:NO];
  725. [window->ns.object setHasShadow:NO];
  726. [window->ns.object setBackgroundColor:[NSColor clearColor]];
  727. }
  728. [window->ns.object setContentView:window->ns.view];
  729. [window->ns.object makeFirstResponder:window->ns.view];
  730. [window->ns.object setTitle:@(wndconfig->title)];
  731. [window->ns.object setDelegate:window->ns.delegate];
  732. [window->ns.object setAcceptsMouseMovedEvents:YES];
  733. [window->ns.object setRestorable:NO];
  734. #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200
  735. if ([window->ns.object respondsToSelector:@selector(setTabbingMode:)])
  736. [window->ns.object setTabbingMode:NSWindowTabbingModeDisallowed];
  737. #endif
  738. _glfwGetWindowSizeCocoa(window, &window->ns.width, &window->ns.height);
  739. _glfwGetFramebufferSizeCocoa(window, &window->ns.fbWidth, &window->ns.fbHeight);
  740. return GLFW_TRUE;
  741. }
  742. //////////////////////////////////////////////////////////////////////////
  743. ////// GLFW internal API //////
  744. //////////////////////////////////////////////////////////////////////////
  745. // Transforms a y-coordinate between the CG display and NS screen spaces
  746. //
  747. float _glfwTransformYCocoa(float y)
  748. {
  749. return CGDisplayBounds(CGMainDisplayID()).size.height - y - 1;
  750. }
  751. //////////////////////////////////////////////////////////////////////////
  752. ////// GLFW platform API //////
  753. //////////////////////////////////////////////////////////////////////////
  754. GLFWbool _glfwCreateWindowCocoa(_GLFWwindow* window,
  755. const _GLFWwndconfig* wndconfig,
  756. const _GLFWctxconfig* ctxconfig,
  757. const _GLFWfbconfig* fbconfig)
  758. {
  759. @autoreleasepool {
  760. if (!createNativeWindow(window, wndconfig, fbconfig))
  761. return GLFW_FALSE;
  762. if (ctxconfig->client != GLFW_NO_API)
  763. {
  764. if (ctxconfig->source == GLFW_NATIVE_CONTEXT_API)
  765. {
  766. if (!_glfwInitNSGL())
  767. return GLFW_FALSE;
  768. if (!_glfwCreateContextNSGL(window, ctxconfig, fbconfig))
  769. return GLFW_FALSE;
  770. }
  771. else if (ctxconfig->source == GLFW_EGL_CONTEXT_API)
  772. {
  773. // EGL implementation on macOS use CALayer* EGLNativeWindowType so we
  774. // need to get the layer for EGL window surface creation.
  775. [window->ns.view setWantsLayer:YES];
  776. window->ns.layer = [window->ns.view layer];
  777. if (!_glfwInitEGL())
  778. return GLFW_FALSE;
  779. if (!_glfwCreateContextEGL(window, ctxconfig, fbconfig))
  780. return GLFW_FALSE;
  781. }
  782. else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API)
  783. {
  784. if (!_glfwInitOSMesa())
  785. return GLFW_FALSE;
  786. if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig))
  787. return GLFW_FALSE;
  788. }
  789. if (!_glfwRefreshContextAttribs(window, ctxconfig))
  790. return GLFW_FALSE;
  791. }
  792. if (wndconfig->mousePassthrough)
  793. _glfwSetWindowMousePassthroughCocoa(window, GLFW_TRUE);
  794. if (window->monitor)
  795. {
  796. _glfwShowWindowCocoa(window);
  797. _glfwFocusWindowCocoa(window);
  798. acquireMonitor(window);
  799. if (wndconfig->centerCursor)
  800. _glfwCenterCursorInContentArea(window);
  801. }
  802. else
  803. {
  804. if (wndconfig->visible)
  805. {
  806. _glfwShowWindowCocoa(window);
  807. if (wndconfig->focused)
  808. _glfwFocusWindowCocoa(window);
  809. }
  810. }
  811. return GLFW_TRUE;
  812. } // autoreleasepool
  813. }
  814. void _glfwDestroyWindowCocoa(_GLFWwindow* window)
  815. {
  816. @autoreleasepool {
  817. if (_glfw.ns.disabledCursorWindow == window)
  818. _glfw.ns.disabledCursorWindow = NULL;
  819. [window->ns.object orderOut:nil];
  820. if (window->monitor)
  821. releaseMonitor(window);
  822. if (window->context.destroy)
  823. window->context.destroy(window);
  824. [window->ns.object setDelegate:nil];
  825. [window->ns.delegate release];
  826. window->ns.delegate = nil;
  827. [window->ns.view release];
  828. window->ns.view = nil;
  829. [window->ns.object close];
  830. window->ns.object = nil;
  831. // HACK: Allow Cocoa to catch up before returning
  832. _glfwPollEventsCocoa();
  833. } // autoreleasepool
  834. }
  835. void _glfwSetWindowTitleCocoa(_GLFWwindow* window, const char* title)
  836. {
  837. @autoreleasepool {
  838. NSString* string = @(title);
  839. [window->ns.object setTitle:string];
  840. // HACK: Set the miniwindow title explicitly as setTitle: doesn't update it
  841. // if the window lacks NSWindowStyleMaskTitled
  842. [window->ns.object setMiniwindowTitle:string];
  843. } // autoreleasepool
  844. }
  845. void _glfwSetWindowIconCocoa(_GLFWwindow* window,
  846. int count, const GLFWimage* images)
  847. {
  848. _glfwInputError(GLFW_FEATURE_UNAVAILABLE,
  849. "Cocoa: Regular windows do not have icons on macOS");
  850. }
  851. void _glfwGetWindowPosCocoa(_GLFWwindow* window, int* xpos, int* ypos)
  852. {
  853. @autoreleasepool {
  854. const NSRect contentRect =
  855. [window->ns.object contentRectForFrameRect:[window->ns.object frame]];
  856. if (xpos)
  857. *xpos = contentRect.origin.x;
  858. if (ypos)
  859. *ypos = _glfwTransformYCocoa(contentRect.origin.y + contentRect.size.height - 1);
  860. } // autoreleasepool
  861. }
  862. void _glfwSetWindowPosCocoa(_GLFWwindow* window, int x, int y)
  863. {
  864. @autoreleasepool {
  865. const NSRect contentRect = [window->ns.view frame];
  866. const NSRect dummyRect = NSMakeRect(x, _glfwTransformYCocoa(y + contentRect.size.height - 1), 0, 0);
  867. const NSRect frameRect = [window->ns.object frameRectForContentRect:dummyRect];
  868. [window->ns.object setFrameOrigin:frameRect.origin];
  869. } // autoreleasepool
  870. }
  871. void _glfwGetWindowSizeCocoa(_GLFWwindow* window, int* width, int* height)
  872. {
  873. @autoreleasepool {
  874. const NSRect contentRect = [window->ns.view frame];
  875. if (width)
  876. *width = contentRect.size.width;
  877. if (height)
  878. *height = contentRect.size.height;
  879. } // autoreleasepool
  880. }
  881. void _glfwSetWindowSizeCocoa(_GLFWwindow* window, int width, int height)
  882. {
  883. @autoreleasepool {
  884. if (window->monitor)
  885. {
  886. if (window->monitor->window == window)
  887. acquireMonitor(window);
  888. }
  889. else
  890. {
  891. NSRect contentRect =
  892. [window->ns.object contentRectForFrameRect:[window->ns.object frame]];
  893. contentRect.origin.y += contentRect.size.height - height;
  894. contentRect.size = NSMakeSize(width, height);
  895. [window->ns.object setFrame:[window->ns.object frameRectForContentRect:contentRect]
  896. display:YES];
  897. }
  898. } // autoreleasepool
  899. }
  900. void _glfwSetWindowSizeLimitsCocoa(_GLFWwindow* window,
  901. int minwidth, int minheight,
  902. int maxwidth, int maxheight)
  903. {
  904. @autoreleasepool {
  905. if (minwidth == GLFW_DONT_CARE || minheight == GLFW_DONT_CARE)
  906. [window->ns.object setContentMinSize:NSMakeSize(0, 0)];
  907. else
  908. [window->ns.object setContentMinSize:NSMakeSize(minwidth, minheight)];
  909. if (maxwidth == GLFW_DONT_CARE || maxheight == GLFW_DONT_CARE)
  910. [window->ns.object setContentMaxSize:NSMakeSize(DBL_MAX, DBL_MAX)];
  911. else
  912. [window->ns.object setContentMaxSize:NSMakeSize(maxwidth, maxheight)];
  913. } // autoreleasepool
  914. }
  915. void _glfwSetWindowAspectRatioCocoa(_GLFWwindow* window, int numer, int denom)
  916. {
  917. @autoreleasepool {
  918. if (numer == GLFW_DONT_CARE || denom == GLFW_DONT_CARE)
  919. [window->ns.object setResizeIncrements:NSMakeSize(1.0, 1.0)];
  920. else
  921. [window->ns.object setContentAspectRatio:NSMakeSize(numer, denom)];
  922. } // autoreleasepool
  923. }
  924. void _glfwGetFramebufferSizeCocoa(_GLFWwindow* window, int* width, int* height)
  925. {
  926. @autoreleasepool {
  927. const NSRect contentRect = [window->ns.view frame];
  928. const NSRect fbRect = [window->ns.view convertRectToBacking:contentRect];
  929. if (width)
  930. *width = (int) fbRect.size.width;
  931. if (height)
  932. *height = (int) fbRect.size.height;
  933. } // autoreleasepool
  934. }
  935. void _glfwGetWindowFrameSizeCocoa(_GLFWwindow* window,
  936. int* left, int* top,
  937. int* right, int* bottom)
  938. {
  939. @autoreleasepool {
  940. const NSRect contentRect = [window->ns.view frame];
  941. const NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect];
  942. if (left)
  943. *left = contentRect.origin.x - frameRect.origin.x;
  944. if (top)
  945. *top = frameRect.origin.y + frameRect.size.height -
  946. contentRect.origin.y - contentRect.size.height;
  947. if (right)
  948. *right = frameRect.origin.x + frameRect.size.width -
  949. contentRect.origin.x - contentRect.size.width;
  950. if (bottom)
  951. *bottom = contentRect.origin.y - frameRect.origin.y;
  952. } // autoreleasepool
  953. }
  954. void _glfwGetWindowContentScaleCocoa(_GLFWwindow* window,
  955. float* xscale, float* yscale)
  956. {
  957. @autoreleasepool {
  958. const NSRect points = [window->ns.view frame];
  959. const NSRect pixels = [window->ns.view convertRectToBacking:points];
  960. if (xscale)
  961. *xscale = (float) (pixels.size.width / points.size.width);
  962. if (yscale)
  963. *yscale = (float) (pixels.size.height / points.size.height);
  964. } // autoreleasepool
  965. }
  966. void _glfwIconifyWindowCocoa(_GLFWwindow* window)
  967. {
  968. @autoreleasepool {
  969. [window->ns.object miniaturize:nil];
  970. } // autoreleasepool
  971. }
  972. void _glfwRestoreWindowCocoa(_GLFWwindow* window)
  973. {
  974. @autoreleasepool {
  975. if ([window->ns.object isMiniaturized])
  976. [window->ns.object deminiaturize:nil];
  977. else if ([window->ns.object isZoomed])
  978. [window->ns.object zoom:nil];
  979. } // autoreleasepool
  980. }
  981. void _glfwMaximizeWindowCocoa(_GLFWwindow* window)
  982. {
  983. @autoreleasepool {
  984. if (![window->ns.object isZoomed])
  985. [window->ns.object zoom:nil];
  986. } // autoreleasepool
  987. }
  988. void _glfwShowWindowCocoa(_GLFWwindow* window)
  989. {
  990. @autoreleasepool {
  991. [window->ns.object orderFront:nil];
  992. } // autoreleasepool
  993. }
  994. void _glfwHideWindowCocoa(_GLFWwindow* window)
  995. {
  996. @autoreleasepool {
  997. [window->ns.object orderOut:nil];
  998. } // autoreleasepool
  999. }
  1000. void _glfwRequestWindowAttentionCocoa(_GLFWwindow* window)
  1001. {
  1002. @autoreleasepool {
  1003. [NSApp requestUserAttention:NSInformationalRequest];
  1004. } // autoreleasepool
  1005. }
  1006. void _glfwFocusWindowCocoa(_GLFWwindow* window)
  1007. {
  1008. @autoreleasepool {
  1009. // Make us the active application
  1010. // HACK: This is here to prevent applications using only hidden windows from
  1011. // being activated, but should probably not be done every time any
  1012. // window is shown
  1013. [NSApp activateIgnoringOtherApps:YES];
  1014. [window->ns.object makeKeyAndOrderFront:nil];
  1015. } // autoreleasepool
  1016. }
  1017. void _glfwSetWindowMonitorCocoa(_GLFWwindow* window,
  1018. _GLFWmonitor* monitor,
  1019. int xpos, int ypos,
  1020. int width, int height,
  1021. int refreshRate)
  1022. {
  1023. @autoreleasepool {
  1024. if (window->monitor == monitor)
  1025. {
  1026. if (monitor)
  1027. {
  1028. if (monitor->window == window)
  1029. acquireMonitor(window);
  1030. }
  1031. else
  1032. {
  1033. const NSRect contentRect =
  1034. NSMakeRect(xpos, _glfwTransformYCocoa(ypos + height - 1), width, height);
  1035. const NSUInteger styleMask = [window->ns.object styleMask];
  1036. const NSRect frameRect =
  1037. [window->ns.object frameRectForContentRect:contentRect
  1038. styleMask:styleMask];
  1039. [window->ns.object setFrame:frameRect display:YES];
  1040. }
  1041. return;
  1042. }
  1043. if (window->monitor)
  1044. releaseMonitor(window);
  1045. _glfwInputWindowMonitor(window, monitor);
  1046. // HACK: Allow the state cached in Cocoa to catch up to reality
  1047. // TODO: Solve this in a less terrible way
  1048. _glfwPollEventsCocoa();
  1049. NSUInteger styleMask = [window->ns.object styleMask];
  1050. if (window->monitor)
  1051. {
  1052. styleMask &= ~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable);
  1053. styleMask |= NSWindowStyleMaskBorderless;
  1054. }
  1055. else
  1056. {
  1057. if (window->decorated)
  1058. {
  1059. styleMask &= ~NSWindowStyleMaskBorderless;
  1060. styleMask |= (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable);
  1061. }
  1062. if (window->resizable)
  1063. styleMask |= NSWindowStyleMaskResizable;
  1064. else
  1065. styleMask &= ~NSWindowStyleMaskResizable;
  1066. }
  1067. [window->ns.object setStyleMask:styleMask];
  1068. // HACK: Changing the style mask can cause the first responder to be cleared
  1069. [window->ns.object makeFirstResponder:window->ns.view];
  1070. if (window->monitor)
  1071. {
  1072. [window->ns.object setLevel:NSMainMenuWindowLevel + 1];
  1073. [window->ns.object setHasShadow:NO];
  1074. acquireMonitor(window);
  1075. }
  1076. else
  1077. {
  1078. NSRect contentRect = NSMakeRect(xpos, _glfwTransformYCocoa(ypos + height - 1),
  1079. width, height);
  1080. NSRect frameRect = [window->ns.object frameRectForContentRect:contentRect
  1081. styleMask:styleMask];
  1082. [window->ns.object setFrame:frameRect display:YES];
  1083. if (window->numer != GLFW_DONT_CARE &&
  1084. window->denom != GLFW_DONT_CARE)
  1085. {
  1086. [window->ns.object setContentAspectRatio:NSMakeSize(window->numer,
  1087. window->denom)];
  1088. }
  1089. if (window->minwidth != GLFW_DONT_CARE &&
  1090. window->minheight != GLFW_DONT_CARE)
  1091. {
  1092. [window->ns.object setContentMinSize:NSMakeSize(window->minwidth,
  1093. window->minheight)];
  1094. }
  1095. if (window->maxwidth != GLFW_DONT_CARE &&
  1096. window->maxheight != GLFW_DONT_CARE)
  1097. {
  1098. [window->ns.object setContentMaxSize:NSMakeSize(window->maxwidth,
  1099. window->maxheight)];
  1100. }
  1101. if (window->floating)
  1102. [window->ns.object setLevel:NSFloatingWindowLevel];
  1103. else
  1104. [window->ns.object setLevel:NSNormalWindowLevel];
  1105. if (window->resizable)
  1106. {
  1107. const NSWindowCollectionBehavior behavior =
  1108. NSWindowCollectionBehaviorFullScreenPrimary |
  1109. NSWindowCollectionBehaviorManaged;
  1110. [window->ns.object setCollectionBehavior:behavior];
  1111. }
  1112. else
  1113. {
  1114. const NSWindowCollectionBehavior behavior =
  1115. NSWindowCollectionBehaviorFullScreenNone;
  1116. [window->ns.object setCollectionBehavior:behavior];
  1117. }
  1118. [window->ns.object setHasShadow:YES];
  1119. // HACK: Clearing NSWindowStyleMaskTitled resets and disables the window
  1120. // title property but the miniwindow title property is unaffected
  1121. [window->ns.object setTitle:[window->ns.object miniwindowTitle]];
  1122. }
  1123. } // autoreleasepool
  1124. }
  1125. GLFWbool _glfwWindowFocusedCocoa(_GLFWwindow* window)
  1126. {
  1127. @autoreleasepool {
  1128. return [window->ns.object isKeyWindow];
  1129. } // autoreleasepool
  1130. }
  1131. GLFWbool _glfwWindowIconifiedCocoa(_GLFWwindow* window)
  1132. {
  1133. @autoreleasepool {
  1134. return [window->ns.object isMiniaturized];
  1135. } // autoreleasepool
  1136. }
  1137. GLFWbool _glfwWindowVisibleCocoa(_GLFWwindow* window)
  1138. {
  1139. @autoreleasepool {
  1140. return [window->ns.object isVisible];
  1141. } // autoreleasepool
  1142. }
  1143. GLFWbool _glfwWindowMaximizedCocoa(_GLFWwindow* window)
  1144. {
  1145. @autoreleasepool {
  1146. if (window->resizable)
  1147. return [window->ns.object isZoomed];
  1148. else
  1149. return GLFW_FALSE;
  1150. } // autoreleasepool
  1151. }
  1152. GLFWbool _glfwWindowHoveredCocoa(_GLFWwindow* window)
  1153. {
  1154. @autoreleasepool {
  1155. const NSPoint point = [NSEvent mouseLocation];
  1156. if ([NSWindow windowNumberAtPoint:point belowWindowWithWindowNumber:0] !=
  1157. [window->ns.object windowNumber])
  1158. {
  1159. return GLFW_FALSE;
  1160. }
  1161. return NSMouseInRect(point,
  1162. [window->ns.object convertRectToScreen:[window->ns.view frame]], NO);
  1163. } // autoreleasepool
  1164. }
  1165. GLFWbool _glfwFramebufferTransparentCocoa(_GLFWwindow* window)
  1166. {
  1167. @autoreleasepool {
  1168. return ![window->ns.object isOpaque] && ![window->ns.view isOpaque];
  1169. } // autoreleasepool
  1170. }
  1171. void _glfwSetWindowResizableCocoa(_GLFWwindow* window, GLFWbool enabled)
  1172. {
  1173. @autoreleasepool {
  1174. const NSUInteger styleMask = [window->ns.object styleMask];
  1175. if (enabled)
  1176. {
  1177. [window->ns.object setStyleMask:(styleMask | NSWindowStyleMaskResizable)];
  1178. const NSWindowCollectionBehavior behavior =
  1179. NSWindowCollectionBehaviorFullScreenPrimary |
  1180. NSWindowCollectionBehaviorManaged;
  1181. [window->ns.object setCollectionBehavior:behavior];
  1182. }
  1183. else
  1184. {
  1185. [window->ns.object setStyleMask:(styleMask & ~NSWindowStyleMaskResizable)];
  1186. const NSWindowCollectionBehavior behavior =
  1187. NSWindowCollectionBehaviorFullScreenNone;
  1188. [window->ns.object setCollectionBehavior:behavior];
  1189. }
  1190. } // autoreleasepool
  1191. }
  1192. void _glfwSetWindowDecoratedCocoa(_GLFWwindow* window, GLFWbool enabled)
  1193. {
  1194. @autoreleasepool {
  1195. NSUInteger styleMask = [window->ns.object styleMask];
  1196. if (enabled)
  1197. {
  1198. styleMask |= (NSWindowStyleMaskTitled | NSWindowStyleMaskClosable);
  1199. styleMask &= ~NSWindowStyleMaskBorderless;
  1200. }
  1201. else
  1202. {
  1203. styleMask |= NSWindowStyleMaskBorderless;
  1204. styleMask &= ~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable);
  1205. }
  1206. [window->ns.object setStyleMask:styleMask];
  1207. [window->ns.object makeFirstResponder:window->ns.view];
  1208. } // autoreleasepool
  1209. }
  1210. void _glfwSetWindowFloatingCocoa(_GLFWwindow* window, GLFWbool enabled)
  1211. {
  1212. @autoreleasepool {
  1213. if (enabled)
  1214. [window->ns.object setLevel:NSFloatingWindowLevel];
  1215. else
  1216. [window->ns.object setLevel:NSNormalWindowLevel];
  1217. } // autoreleasepool
  1218. }
  1219. void _glfwSetWindowMousePassthroughCocoa(_GLFWwindow* window, GLFWbool enabled)
  1220. {
  1221. @autoreleasepool {
  1222. [window->ns.object setIgnoresMouseEvents:enabled];
  1223. }
  1224. }
  1225. float _glfwGetWindowOpacityCocoa(_GLFWwindow* window)
  1226. {
  1227. @autoreleasepool {
  1228. return (float) [window->ns.object alphaValue];
  1229. } // autoreleasepool
  1230. }
  1231. void _glfwSetWindowOpacityCocoa(_GLFWwindow* window, float opacity)
  1232. {
  1233. @autoreleasepool {
  1234. [window->ns.object setAlphaValue:opacity];
  1235. } // autoreleasepool
  1236. }
  1237. void _glfwSetRawMouseMotionCocoa(_GLFWwindow *window, GLFWbool enabled)
  1238. {
  1239. _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
  1240. "Cocoa: Raw mouse motion not yet implemented");
  1241. }
  1242. GLFWbool _glfwRawMouseMotionSupportedCocoa(void)
  1243. {
  1244. return GLFW_FALSE;
  1245. }
  1246. void _glfwPollEventsCocoa(void)
  1247. {
  1248. @autoreleasepool {
  1249. for (;;)
  1250. {
  1251. NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny
  1252. untilDate:[NSDate distantPast]
  1253. inMode:NSDefaultRunLoopMode
  1254. dequeue:YES];
  1255. if (event == nil)
  1256. break;
  1257. [NSApp sendEvent:event];
  1258. }
  1259. } // autoreleasepool
  1260. }
  1261. void _glfwWaitEventsCocoa(void)
  1262. {
  1263. @autoreleasepool {
  1264. // I wanted to pass NO to dequeue:, and rely on PollEvents to
  1265. // dequeue and send. For reasons not at all clear to me, passing
  1266. // NO to dequeue: causes this method never to return.
  1267. NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny
  1268. untilDate:[NSDate distantFuture]
  1269. inMode:NSDefaultRunLoopMode
  1270. dequeue:YES];
  1271. [NSApp sendEvent:event];
  1272. _glfwPollEventsCocoa();
  1273. } // autoreleasepool
  1274. }
  1275. void _glfwWaitEventsTimeoutCocoa(double timeout)
  1276. {
  1277. @autoreleasepool {
  1278. NSDate* date = [NSDate dateWithTimeIntervalSinceNow:timeout];
  1279. NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny
  1280. untilDate:date
  1281. inMode:NSDefaultRunLoopMode
  1282. dequeue:YES];
  1283. if (event)
  1284. [NSApp sendEvent:event];
  1285. _glfwPollEventsCocoa();
  1286. } // autoreleasepool
  1287. }
  1288. void _glfwPostEmptyEventCocoa(void)
  1289. {
  1290. @autoreleasepool {
  1291. NSEvent* event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined
  1292. location:NSMakePoint(0, 0)
  1293. modifierFlags:0
  1294. timestamp:0
  1295. windowNumber:0
  1296. context:nil
  1297. subtype:0
  1298. data1:0
  1299. data2:0];
  1300. [NSApp postEvent:event atStart:YES];
  1301. } // autoreleasepool
  1302. }
  1303. void _glfwGetCursorPosCocoa(_GLFWwindow* window, double* xpos, double* ypos)
  1304. {
  1305. @autoreleasepool {
  1306. const NSRect contentRect = [window->ns.view frame];
  1307. // NOTE: The returned location uses base 0,1 not 0,0
  1308. const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream];
  1309. if (xpos)
  1310. *xpos = pos.x;
  1311. if (ypos)
  1312. *ypos = contentRect.size.height - pos.y;
  1313. } // autoreleasepool
  1314. }
  1315. void _glfwSetCursorPosCocoa(_GLFWwindow* window, double x, double y)
  1316. {
  1317. @autoreleasepool {
  1318. updateCursorImage(window);
  1319. const NSRect contentRect = [window->ns.view frame];
  1320. // NOTE: The returned location uses base 0,1 not 0,0
  1321. const NSPoint pos = [window->ns.object mouseLocationOutsideOfEventStream];
  1322. window->ns.cursorWarpDeltaX += x - pos.x;
  1323. window->ns.cursorWarpDeltaY += y - contentRect.size.height + pos.y;
  1324. if (window->monitor)
  1325. {
  1326. CGDisplayMoveCursorToPoint(window->monitor->ns.displayID,
  1327. CGPointMake(x, y));
  1328. }
  1329. else
  1330. {
  1331. const NSRect localRect = NSMakeRect(x, contentRect.size.height - y - 1, 0, 0);
  1332. const NSRect globalRect = [window->ns.object convertRectToScreen:localRect];
  1333. const NSPoint globalPoint = globalRect.origin;
  1334. CGWarpMouseCursorPosition(CGPointMake(globalPoint.x,
  1335. _glfwTransformYCocoa(globalPoint.y)));
  1336. }
  1337. // HACK: Calling this right after setting the cursor position prevents macOS
  1338. // from freezing the cursor for a fraction of a second afterwards
  1339. if (window->cursorMode != GLFW_CURSOR_DISABLED)
  1340. CGAssociateMouseAndMouseCursorPosition(true);
  1341. } // autoreleasepool
  1342. }
  1343. void _glfwSetCursorModeCocoa(_GLFWwindow* window, int mode)
  1344. {
  1345. @autoreleasepool {
  1346. if (mode == GLFW_CURSOR_CAPTURED)
  1347. {
  1348. _glfwInputError(GLFW_FEATURE_UNIMPLEMENTED,
  1349. "Cocoa: Captured cursor mode not yet implemented");
  1350. }
  1351. if (_glfwWindowFocusedCocoa(window))
  1352. updateCursorMode(window);
  1353. } // autoreleasepool
  1354. }
  1355. const char* _glfwGetScancodeNameCocoa(int scancode)
  1356. {
  1357. @autoreleasepool {
  1358. if (scancode < 0 || scancode > 0xff)
  1359. {
  1360. _glfwInputError(GLFW_INVALID_VALUE, "Invalid scancode %i", scancode);
  1361. return NULL;
  1362. }
  1363. const int key = _glfw.ns.keycodes[scancode];
  1364. if (key == GLFW_KEY_UNKNOWN)
  1365. return NULL;
  1366. UInt32 deadKeyState = 0;
  1367. UniChar characters[4];
  1368. UniCharCount characterCount = 0;
  1369. if (UCKeyTranslate([(NSData*) _glfw.ns.unicodeData bytes],
  1370. scancode,
  1371. kUCKeyActionDisplay,
  1372. 0,
  1373. LMGetKbdType(),
  1374. kUCKeyTranslateNoDeadKeysBit,
  1375. &deadKeyState,
  1376. sizeof(characters) / sizeof(characters[0]),
  1377. &characterCount,
  1378. characters) != noErr)
  1379. {
  1380. return NULL;
  1381. }
  1382. if (!characterCount)
  1383. return NULL;
  1384. CFStringRef string = CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
  1385. characters,
  1386. characterCount,
  1387. kCFAllocatorNull);
  1388. CFStringGetCString(string,
  1389. _glfw.ns.keynames[key],
  1390. sizeof(_glfw.ns.keynames[key]),
  1391. kCFStringEncodingUTF8);
  1392. CFRelease(string);
  1393. return _glfw.ns.keynames[key];
  1394. } // autoreleasepool
  1395. }
  1396. int _glfwGetKeyScancodeCocoa(int key)
  1397. {
  1398. return _glfw.ns.scancodes[key];
  1399. }
  1400. GLFWbool _glfwCreateCursorCocoa(_GLFWcursor* cursor,
  1401. const GLFWimage* image,
  1402. int xhot, int yhot)
  1403. {
  1404. @autoreleasepool {
  1405. NSImage* native;
  1406. NSBitmapImageRep* rep;
  1407. rep = [[NSBitmapImageRep alloc]
  1408. initWithBitmapDataPlanes:NULL
  1409. pixelsWide:image->width
  1410. pixelsHigh:image->height
  1411. bitsPerSample:8
  1412. samplesPerPixel:4
  1413. hasAlpha:YES
  1414. isPlanar:NO
  1415. colorSpaceName:NSCalibratedRGBColorSpace
  1416. bitmapFormat:NSBitmapFormatAlphaNonpremultiplied
  1417. bytesPerRow:image->width * 4
  1418. bitsPerPixel:32];
  1419. if (rep == nil)
  1420. return GLFW_FALSE;
  1421. memcpy([rep bitmapData], image->pixels, image->width * image->height * 4);
  1422. native = [[NSImage alloc] initWithSize:NSMakeSize(image->width, image->height)];
  1423. [native addRepresentation:rep];
  1424. cursor->ns.object = [[NSCursor alloc] initWithImage:native
  1425. hotSpot:NSMakePoint(xhot, yhot)];
  1426. [native release];
  1427. [rep release];
  1428. if (cursor->ns.object == nil)
  1429. return GLFW_FALSE;
  1430. return GLFW_TRUE;
  1431. } // autoreleasepool
  1432. }
  1433. GLFWbool _glfwCreateStandardCursorCocoa(_GLFWcursor* cursor, int shape)
  1434. {
  1435. @autoreleasepool {
  1436. SEL cursorSelector = NULL;
  1437. // HACK: Try to use a private message
  1438. switch (shape)
  1439. {
  1440. case GLFW_RESIZE_EW_CURSOR:
  1441. cursorSelector = NSSelectorFromString(@"_windowResizeEastWestCursor");
  1442. break;
  1443. case GLFW_RESIZE_NS_CURSOR:
  1444. cursorSelector = NSSelectorFromString(@"_windowResizeNorthSouthCursor");
  1445. break;
  1446. case GLFW_RESIZE_NWSE_CURSOR:
  1447. cursorSelector = NSSelectorFromString(@"_windowResizeNorthWestSouthEastCursor");
  1448. break;
  1449. case GLFW_RESIZE_NESW_CURSOR:
  1450. cursorSelector = NSSelectorFromString(@"_windowResizeNorthEastSouthWestCursor");
  1451. break;
  1452. }
  1453. if (cursorSelector && [NSCursor respondsToSelector:cursorSelector])
  1454. {
  1455. id object = [NSCursor performSelector:cursorSelector];
  1456. if ([object isKindOfClass:[NSCursor class]])
  1457. cursor->ns.object = object;
  1458. }
  1459. if (!cursor->ns.object)
  1460. {
  1461. switch (shape)
  1462. {
  1463. case GLFW_ARROW_CURSOR:
  1464. cursor->ns.object = [NSCursor arrowCursor];
  1465. break;
  1466. case GLFW_IBEAM_CURSOR:
  1467. cursor->ns.object = [NSCursor IBeamCursor];
  1468. break;
  1469. case GLFW_CROSSHAIR_CURSOR:
  1470. cursor->ns.object = [NSCursor crosshairCursor];
  1471. break;
  1472. case GLFW_POINTING_HAND_CURSOR:
  1473. cursor->ns.object = [NSCursor pointingHandCursor];
  1474. break;
  1475. case GLFW_RESIZE_EW_CURSOR:
  1476. cursor->ns.object = [NSCursor resizeLeftRightCursor];
  1477. break;
  1478. case GLFW_RESIZE_NS_CURSOR:
  1479. cursor->ns.object = [NSCursor resizeUpDownCursor];
  1480. break;
  1481. case GLFW_RESIZE_ALL_CURSOR:
  1482. cursor->ns.object = [NSCursor closedHandCursor];
  1483. break;
  1484. case GLFW_NOT_ALLOWED_CURSOR:
  1485. cursor->ns.object = [NSCursor operationNotAllowedCursor];
  1486. break;
  1487. }
  1488. }
  1489. if (!cursor->ns.object)
  1490. {
  1491. _glfwInputError(GLFW_CURSOR_UNAVAILABLE,
  1492. "Cocoa: Standard cursor shape unavailable");
  1493. return GLFW_FALSE;
  1494. }
  1495. [cursor->ns.object retain];
  1496. return GLFW_TRUE;
  1497. } // autoreleasepool
  1498. }
  1499. void _glfwDestroyCursorCocoa(_GLFWcursor* cursor)
  1500. {
  1501. @autoreleasepool {
  1502. if (cursor->ns.object)
  1503. [(NSCursor*) cursor->ns.object release];
  1504. } // autoreleasepool
  1505. }
  1506. void _glfwSetCursorCocoa(_GLFWwindow* window, _GLFWcursor* cursor)
  1507. {
  1508. @autoreleasepool {
  1509. if (cursorInContentArea(window))
  1510. updateCursorImage(window);
  1511. } // autoreleasepool
  1512. }
  1513. void _glfwSetClipboardStringCocoa(const char* string)
  1514. {
  1515. @autoreleasepool {
  1516. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  1517. [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
  1518. [pasteboard setString:@(string) forType:NSPasteboardTypeString];
  1519. } // autoreleasepool
  1520. }
  1521. const char* _glfwGetClipboardStringCocoa(void)
  1522. {
  1523. @autoreleasepool {
  1524. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  1525. if (![[pasteboard types] containsObject:NSPasteboardTypeString])
  1526. {
  1527. _glfwInputError(GLFW_FORMAT_UNAVAILABLE,
  1528. "Cocoa: Failed to retrieve string from pasteboard");
  1529. return NULL;
  1530. }
  1531. NSString* object = [pasteboard stringForType:NSPasteboardTypeString];
  1532. if (!object)
  1533. {
  1534. _glfwInputError(GLFW_PLATFORM_ERROR,
  1535. "Cocoa: Failed to retrieve object from pasteboard");
  1536. return NULL;
  1537. }
  1538. _glfw_free(_glfw.ns.clipboardString);
  1539. _glfw.ns.clipboardString = _glfw_strdup([object UTF8String]);
  1540. return _glfw.ns.clipboardString;
  1541. } // autoreleasepool
  1542. }
  1543. EGLenum _glfwGetEGLPlatformCocoa(EGLint** attribs)
  1544. {
  1545. if (_glfw.egl.ANGLE_platform_angle)
  1546. {
  1547. int type = 0;
  1548. if (_glfw.egl.ANGLE_platform_angle_opengl)
  1549. {
  1550. if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_OPENGL)
  1551. type = EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE;
  1552. }
  1553. if (_glfw.egl.ANGLE_platform_angle_metal)
  1554. {
  1555. if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_METAL)
  1556. type = EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE;
  1557. }
  1558. if (type)
  1559. {
  1560. *attribs = _glfw_calloc(3, sizeof(EGLint));
  1561. (*attribs)[0] = EGL_PLATFORM_ANGLE_TYPE_ANGLE;
  1562. (*attribs)[1] = type;
  1563. (*attribs)[2] = EGL_NONE;
  1564. return EGL_PLATFORM_ANGLE_ANGLE;
  1565. }
  1566. }
  1567. return 0;
  1568. }
  1569. EGLNativeDisplayType _glfwGetEGLNativeDisplayCocoa(void)
  1570. {
  1571. return EGL_DEFAULT_DISPLAY;
  1572. }
  1573. EGLNativeWindowType _glfwGetEGLNativeWindowCocoa(_GLFWwindow* window)
  1574. {
  1575. return window->ns.layer;
  1576. }
  1577. void _glfwGetRequiredInstanceExtensionsCocoa(char** extensions)
  1578. {
  1579. if (_glfw.vk.KHR_surface && _glfw.vk.EXT_metal_surface)
  1580. {
  1581. extensions[0] = "VK_KHR_surface";
  1582. extensions[1] = "VK_EXT_metal_surface";
  1583. }
  1584. else if (_glfw.vk.KHR_surface && _glfw.vk.MVK_macos_surface)
  1585. {
  1586. extensions[0] = "VK_KHR_surface";
  1587. extensions[1] = "VK_MVK_macos_surface";
  1588. }
  1589. }
  1590. GLFWbool _glfwGetPhysicalDevicePresentationSupportCocoa(VkInstance instance,
  1591. VkPhysicalDevice device,
  1592. uint32_t queuefamily)
  1593. {
  1594. return GLFW_TRUE;
  1595. }
  1596. VkResult _glfwCreateWindowSurfaceCocoa(VkInstance instance,
  1597. _GLFWwindow* window,
  1598. const VkAllocationCallbacks* allocator,
  1599. VkSurfaceKHR* surface)
  1600. {
  1601. @autoreleasepool {
  1602. // HACK: Dynamically load Core Animation to avoid adding an extra
  1603. // dependency for the majority who don't use MoltenVK
  1604. NSBundle* bundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/QuartzCore.framework"];
  1605. if (!bundle)
  1606. {
  1607. _glfwInputError(GLFW_PLATFORM_ERROR,
  1608. "Cocoa: Failed to find QuartzCore.framework");
  1609. return VK_ERROR_EXTENSION_NOT_PRESENT;
  1610. }
  1611. // NOTE: Create the layer here as makeBackingLayer should not return nil
  1612. window->ns.layer = [[bundle classNamed:@"CAMetalLayer"] layer];
  1613. if (!window->ns.layer)
  1614. {
  1615. _glfwInputError(GLFW_PLATFORM_ERROR,
  1616. "Cocoa: Failed to create layer for view");
  1617. return VK_ERROR_EXTENSION_NOT_PRESENT;
  1618. }
  1619. if (window->ns.scaleFramebuffer)
  1620. [window->ns.layer setContentsScale:[window->ns.object backingScaleFactor]];
  1621. [window->ns.view setLayer:window->ns.layer];
  1622. [window->ns.view setWantsLayer:YES];
  1623. VkResult err;
  1624. if (_glfw.vk.EXT_metal_surface)
  1625. {
  1626. VkMetalSurfaceCreateInfoEXT sci;
  1627. PFN_vkCreateMetalSurfaceEXT vkCreateMetalSurfaceEXT;
  1628. vkCreateMetalSurfaceEXT = (PFN_vkCreateMetalSurfaceEXT)
  1629. vkGetInstanceProcAddr(instance, "vkCreateMetalSurfaceEXT");
  1630. if (!vkCreateMetalSurfaceEXT)
  1631. {
  1632. _glfwInputError(GLFW_API_UNAVAILABLE,
  1633. "Cocoa: Vulkan instance missing VK_EXT_metal_surface extension");
  1634. return VK_ERROR_EXTENSION_NOT_PRESENT;
  1635. }
  1636. memset(&sci, 0, sizeof(sci));
  1637. sci.sType = VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT;
  1638. sci.pLayer = window->ns.layer;
  1639. err = vkCreateMetalSurfaceEXT(instance, &sci, allocator, surface);
  1640. }
  1641. else
  1642. {
  1643. VkMacOSSurfaceCreateInfoMVK sci;
  1644. PFN_vkCreateMacOSSurfaceMVK vkCreateMacOSSurfaceMVK;
  1645. vkCreateMacOSSurfaceMVK = (PFN_vkCreateMacOSSurfaceMVK)
  1646. vkGetInstanceProcAddr(instance, "vkCreateMacOSSurfaceMVK");
  1647. if (!vkCreateMacOSSurfaceMVK)
  1648. {
  1649. _glfwInputError(GLFW_API_UNAVAILABLE,
  1650. "Cocoa: Vulkan instance missing VK_MVK_macos_surface extension");
  1651. return VK_ERROR_EXTENSION_NOT_PRESENT;
  1652. }
  1653. memset(&sci, 0, sizeof(sci));
  1654. sci.sType = VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK;
  1655. sci.pView = window->ns.view;
  1656. err = vkCreateMacOSSurfaceMVK(instance, &sci, allocator, surface);
  1657. }
  1658. if (err)
  1659. {
  1660. _glfwInputError(GLFW_PLATFORM_ERROR,
  1661. "Cocoa: Failed to create Vulkan surface: %s",
  1662. _glfwGetVulkanResultString(err));
  1663. }
  1664. return err;
  1665. } // autoreleasepool
  1666. }
  1667. //////////////////////////////////////////////////////////////////////////
  1668. ////// GLFW native API //////
  1669. //////////////////////////////////////////////////////////////////////////
  1670. GLFWAPI id glfwGetCocoaWindow(GLFWwindow* handle)
  1671. {
  1672. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  1673. if (_glfw.platform.platformID != GLFW_PLATFORM_COCOA)
  1674. {
  1675. _glfwInputError(GLFW_PLATFORM_UNAVAILABLE,
  1676. "Cocoa: Platform not initialized");
  1677. return nil;
  1678. }
  1679. _GLFWwindow* window = (_GLFWwindow*) handle;
  1680. assert(window != NULL);
  1681. return window->ns.object;
  1682. }
  1683. GLFWAPI id glfwGetCocoaView(GLFWwindow* handle)
  1684. {
  1685. _GLFW_REQUIRE_INIT_OR_RETURN(nil);
  1686. if (_glfw.platform.platformID != GLFW_PLATFORM_COCOA)
  1687. {
  1688. _glfwInputError(GLFW_PLATFORM_UNAVAILABLE,
  1689. "Cocoa: Platform not initialized");
  1690. return nil;
  1691. }
  1692. _GLFWwindow* window = (_GLFWwindow*) handle;
  1693. assert(window != NULL);
  1694. return window->ns.view;
  1695. }
  1696. #endif // _GLFW_COCOA