BsMacOSPlatform.mm 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #define BS_COCOA_INTERNALS 1
  4. #include "Private/MacOS/BsMacOSPlatform.h"
  5. #include "Private/MacOS/BsMacOSWindow.h"
  6. #include "Input/BsInputFwd.h"
  7. #include "Image/BsPixelData.h"
  8. #include "Image/BsColor.h"
  9. #include "RenderAPI/BsRenderWindow.h"
  10. #include "Private/MacOS/BsMacOSDropTarget.h"
  11. #include "String/BsUnicode.h"
  12. #include "BsCoreApplication.h"
  13. #import <Cocoa/Cocoa.h>
  14. #import <Carbon/Carbon.h>
  15. /** Application implementation that overrides the terminate logic with custom shutdown, and tracks Esc key presses. */
  16. @interface BSApplication : NSApplication
  17. -(void)terminate:(nullable id)sender;
  18. -(void)sendEvent:(NSEvent*)event;
  19. @end
  20. @implementation BSApplication
  21. -(void)terminate:(nullable id)sender
  22. {
  23. bs::gCoreApplication().quitRequested();
  24. }
  25. -(void)sendEvent:(NSEvent *)event
  26. {
  27. // Handle Esc key here, as it doesn't seem to be reported elsewhere
  28. if([event type] == NSEventTypeKeyDown)
  29. {
  30. if([event keyCode] == 53) // Escape key
  31. {
  32. bs::InputCommandType ic = bs::InputCommandType ::Escape;
  33. bs::MacOSPlatform::sendInputCommandEvent(ic);
  34. }
  35. }
  36. [super sendEvent:event];
  37. }
  38. @end
  39. /** Application delegate implementation that activates the application when it finishes launching. */
  40. @interface BSAppDelegate : NSObject<NSApplicationDelegate>
  41. @end
  42. @implementation BSAppDelegate : NSObject
  43. -(void)applicationDidFinishLaunching:(NSNotification *)notification
  44. {
  45. [NSApp activateIgnoringOtherApps:YES];
  46. }
  47. @end
  48. @class BSCursor;
  49. @class BSPlatform;
  50. namespace bs
  51. {
  52. /** Contains information about a modal window session. */
  53. struct ModalWindowInfo
  54. {
  55. UINT32 windowId;
  56. NSModalSession session;
  57. };
  58. struct Platform::Pimpl
  59. {
  60. BSAppDelegate* appDelegate = nil;
  61. Mutex windowMutex;
  62. CocoaWindow* mainWindow = nullptr;
  63. UnorderedMap<UINT32, CocoaWindow*> allWindows;
  64. Vector<ModalWindowInfo> modalWindows;
  65. BSPlatform* platformManager = nil;
  66. // Cursor
  67. BSCursor* cursorManager = nil;
  68. Mutex cursorMutex;
  69. bool cursorIsHidden = false;
  70. Vector2I cursorPos;
  71. // Clipboard
  72. Mutex clipboardMutex;
  73. WString cachedClipboardData;
  74. INT32 clipboardChangeCount = -1;
  75. };
  76. }
  77. /**
  78. * Contains cursor specific functionality. Encapsulated in objective C so its selectors can be triggered from other
  79. * threads.
  80. */
  81. @interface BSCursor : NSObject
  82. @property NSCursor* currentCursor;
  83. -(BSCursor*) initWithPlatformData:(bs::Platform::Pimpl*)platformData;
  84. -(bs::Vector2I) getPosition;
  85. -(void) setPosition:(const bs::Vector2I&) position;
  86. -(BOOL) clipCursor:(bs::Vector2I&) position;
  87. -(void) updateClipBounds:(NSWindow*) window;
  88. -(void) clipCursorToWindow:(NSValue*) windowValue;
  89. -(void) clipCursorToRect:(NSValue*) rectValue;
  90. -(void) clipCursorDisable;
  91. -(void) setCursor:(NSArray*) params;
  92. -(void) unregisterWindow:(NSWindow*) window;
  93. @end
  94. @implementation BSCursor
  95. {
  96. bs::Platform::Pimpl* platformData;
  97. bool cursorClipEnabled;
  98. bs::Rect2I cursorClipRect;
  99. NSWindow* cursorClipWindow;
  100. }
  101. - (BSCursor*)initWithPlatformData:(bs::Platform::Pimpl*)data
  102. {
  103. self = [super init];
  104. platformData = data;
  105. return self;
  106. }
  107. - (bs::Vector2I)getPosition
  108. {
  109. NSPoint point = [NSEvent mouseLocation];
  110. for (NSScreen* screen in [NSScreen screens])
  111. {
  112. NSRect frame = [screen frame];
  113. if (NSMouseInRect(point, frame, NO))
  114. bs::flipY(screen, point);
  115. }
  116. bs::Vector2I output;
  117. output.x = (int32_t)point.x;
  118. output.y = (int32_t)point.y;
  119. return output;
  120. }
  121. - (void)setPosition:(const bs::Vector2I&)position
  122. {
  123. NSPoint point = NSMakePoint(position.x, position.y);
  124. CGWarpMouseCursorPosition(point);
  125. Lock lock(platformData->cursorMutex);
  126. platformData->cursorPos = position;
  127. }
  128. - (BOOL)clipCursor:(bs::Vector2I&)position
  129. {
  130. if(!cursorClipEnabled)
  131. return false;
  132. int32_t clippedX = position.x - cursorClipRect.x;
  133. int32_t clippedY = position.y - cursorClipRect.y;
  134. if(clippedX < 0)
  135. clippedX = 0;
  136. else if(clippedX >= (int32_t)cursorClipRect.width)
  137. clippedX = cursorClipRect.width > 0 ? cursorClipRect.width - 1 : 0;
  138. if(clippedY < 0)
  139. clippedY = 0;
  140. else if(clippedY >= (int32_t)cursorClipRect.height)
  141. clippedY = cursorClipRect.height > 0 ? cursorClipRect.height - 1 : 0;
  142. clippedX += cursorClipRect.x;
  143. clippedY += cursorClipRect.y;
  144. if(clippedX != position.x || clippedY != position.y)
  145. {
  146. position.x = clippedX;
  147. position.y = clippedY;
  148. return true;
  149. }
  150. return false;
  151. }
  152. - (void)updateClipBounds:(NSWindow*)window
  153. {
  154. if(!cursorClipEnabled || cursorClipWindow != window)
  155. return;
  156. NSRect rect = [window contentRectForFrameRect:[window frame]];
  157. bs::flipY([window screen], rect);
  158. cursorClipRect.x = (int32_t)rect.origin.x;
  159. cursorClipRect.y = (int32_t)rect.origin.y;
  160. cursorClipRect.width = (uint32_t)rect.size.width;
  161. cursorClipRect.height = (uint32_t)rect.size.height;
  162. }
  163. - (void)clipCursorToWindow:(NSValue*)windowValue
  164. {
  165. bs::CocoaWindow* window;
  166. [windowValue getValue:&window];
  167. cursorClipEnabled = true;
  168. cursorClipWindow = window->_getPrivateData()->window;
  169. [self updateClipBounds:cursorClipWindow];
  170. bs::Vector2I pos = [self getPosition];
  171. if([self clipCursor:pos])
  172. [self setPosition:pos];
  173. }
  174. - (void)clipCursorToRect:(NSValue*)rectValue
  175. {
  176. bs::Rect2I rect;
  177. [rectValue getValue:&rect];
  178. cursorClipEnabled = true;
  179. cursorClipRect = rect;
  180. cursorClipWindow = nullptr;
  181. bs::Vector2I pos = [self getPosition];
  182. if([self clipCursor:pos])
  183. [self setPosition:pos];
  184. }
  185. - (void)clipCursorDisable
  186. {
  187. cursorClipEnabled = false;
  188. cursorClipWindow = nullptr;
  189. }
  190. - (void)setCursor:(NSArray*)params
  191. {
  192. NSCursor* cursor = params[0];
  193. NSValue* hotSpotValue = params[1];
  194. NSPoint hotSpot;
  195. [hotSpotValue getValue:&hotSpot];
  196. [self setCurrentCursor:cursor];
  197. for(auto& entry : platformData->allWindows)
  198. {
  199. NSWindow* window = entry.second->_getPrivateData()->window;
  200. [window invalidateCursorRectsForView:[window contentView]];
  201. }
  202. }
  203. - (void)unregisterWindow:(NSWindow*)window
  204. {
  205. if(cursorClipEnabled && cursorClipWindow == window)
  206. [self clipCursorDisable];
  207. }
  208. @end
  209. /** Contains platform specific functionality that is meant to be delayed executed from the sim thread, through Platform. */
  210. @interface BSPlatform : NSObject
  211. -(BSPlatform*) initWithPlatformData:(bs::Platform::Pimpl*)platformData;
  212. -(void) setCaptionNonClientAreas:(NSArray*) params;
  213. -(void) resetNonClientAreas:(NSValue*) windowIdValue;
  214. -(void) openFolder:(NSURL*) url;
  215. -(void) setClipboardText:(NSString*) text;
  216. -(NSString*) getClipboardText;
  217. -(int32_t) getClipboardChangeCount;
  218. @end
  219. @implementation BSPlatform
  220. {
  221. bs::Platform::Pimpl* mPlatformData;
  222. }
  223. - (BSPlatform*)initWithPlatformData:(bs::Platform::Pimpl*)platformData
  224. {
  225. self = [super init];
  226. mPlatformData = platformData;
  227. return self;
  228. }
  229. - (void)setCaptionNonClientAreas:(NSArray*)params
  230. {
  231. NSValue* windowIdValue = params[0];
  232. bs::UINT32 windowId;
  233. [windowIdValue getValue:&windowId];
  234. auto iterFind = mPlatformData->allWindows.find(windowId);
  235. if(iterFind == mPlatformData->allWindows.end())
  236. return;
  237. bs::CocoaWindow* window = iterFind->second;
  238. NSUInteger numEntries = [params count] - 1;
  239. bs::Vector<bs::Rect2I> areas;
  240. for(NSUInteger i = 0; i < numEntries; i++)
  241. {
  242. NSValue* value = params[i + 1];
  243. bs::Rect2I area;
  244. [value getValue:&area];
  245. areas.push_back(area);
  246. }
  247. window->_setDragZones(areas);
  248. }
  249. - (void)resetNonClientAreas:(NSValue*) windowIdValue
  250. {
  251. bs::UINT32 windowId;
  252. [windowIdValue getValue:&windowId];
  253. auto iterFind = mPlatformData->allWindows.find(windowId);
  254. if(iterFind == mPlatformData->allWindows.end())
  255. return;
  256. bs::CocoaWindow* window = iterFind->second;
  257. window->_setDragZones({});
  258. }
  259. - (void)openFolder:(NSURL*)url
  260. {
  261. [[NSWorkspace sharedWorkspace] openURL:url];
  262. }
  263. - (void) setClipboardText:(NSString*) text
  264. { @autoreleasepool {
  265. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  266. [pasteboard clearContents];
  267. NSArray* objects = [NSArray arrayWithObject:text];
  268. [pasteboard writeObjects:objects];
  269. }}
  270. - (NSString*) getClipboardText
  271. { @autoreleasepool {
  272. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  273. NSArray* classes = [NSArray arrayWithObjects:[NSString class], nil];
  274. NSDictionary* options = [NSDictionary dictionary];
  275. NSArray* items = [pasteboard readObjectsForClasses:classes options:options];
  276. if(!items || items.count == 0)
  277. return nil;
  278. return (NSString*) items[0];
  279. }}
  280. - (int32_t)getClipboardChangeCount
  281. {
  282. return (int32_t)[[NSPasteboard generalPasteboard] changeCount];
  283. }
  284. @end
  285. namespace bs
  286. {
  287. // Maps macOS keycodes to bs button codes
  288. static constexpr ButtonCode KeyCodeMapping[] =
  289. {
  290. /* 0 */ BC_A,
  291. /* 1 */ BC_S,
  292. /* 2 */ BC_D,
  293. /* 3 */ BC_F,
  294. /* 4 */ BC_H,
  295. /* 5 */ BC_G,
  296. /* 6 */ BC_Z,
  297. /* 7 */ BC_X,
  298. /* 8 */ BC_C,
  299. /* 9 */ BC_V,
  300. /* 10 */ BC_GRAVE,
  301. /* 11 */ BC_B,
  302. /* 12 */ BC_Q,
  303. /* 13 */ BC_W,
  304. /* 14 */ BC_E,
  305. /* 15 */ BC_R,
  306. /* 16 */ BC_Y,
  307. /* 17 */ BC_T,
  308. /* 18 */ BC_1,
  309. /* 19 */ BC_2,
  310. /* 20 */ BC_3,
  311. /* 21 */ BC_4,
  312. /* 22 */ BC_6,
  313. /* 23 */ BC_5,
  314. /* 24 */ BC_EQUALS,
  315. /* 25 */ BC_9,
  316. /* 26 */ BC_7,
  317. /* 27 */ BC_MINUS,
  318. /* 28 */ BC_8,
  319. /* 29 */ BC_0,
  320. /* 30 */ BC_RBRACKET,
  321. /* 31 */ BC_O,
  322. /* 32 */ BC_U,
  323. /* 33 */ BC_LBRACKET,
  324. /* 34 */ BC_I,
  325. /* 35 */ BC_P,
  326. /* 36 */ BC_RETURN,
  327. /* 37 */ BC_L,
  328. /* 38 */ BC_J,
  329. /* 39 */ BC_APOSTROPHE,
  330. /* 40 */ BC_K,
  331. /* 41 */ BC_SEMICOLON,
  332. /* 42 */ BC_BACKSLASH,
  333. /* 43 */ BC_COMMA,
  334. /* 44 */ BC_SLASH,
  335. /* 45 */ BC_N,
  336. /* 46 */ BC_M,
  337. /* 47 */ BC_PERIOD,
  338. /* 48 */ BC_TAB,
  339. /* 49 */ BC_SPACE,
  340. /* 50 */ BC_GRAVE,
  341. /* 51 */ BC_BACK,
  342. /* 52 */ BC_NUMPADENTER,
  343. /* 53 */ BC_ESCAPE,
  344. /* 54 */ BC_RWIN,
  345. /* 55 */ BC_LWIN,
  346. /* 56 */ BC_LSHIFT,
  347. /* 57 */ BC_CAPITAL,
  348. /* 58 */ BC_LMENU,
  349. /* 59 */ BC_LCONTROL,
  350. /* 60 */ BC_RSHIFT,
  351. /* 61 */ BC_RMENU,
  352. /* 62 */ BC_RCONTROL,
  353. /* 63 */ BC_RWIN,
  354. /* 64 */ BC_UNASSIGNED,
  355. /* 65 */ BC_DECIMAL,
  356. /* 66 */ BC_UNASSIGNED,
  357. /* 67 */ BC_MULTIPLY,
  358. /* 68 */ BC_UNASSIGNED,
  359. /* 69 */ BC_ADD,
  360. /* 70 */ BC_UNASSIGNED,
  361. /* 71 */ BC_NUMLOCK,
  362. /* 72 */ BC_VOLUMEUP,
  363. /* 73 */ BC_VOLUMEDOWN,
  364. /* 74 */ BC_MUTE,
  365. /* 75 */ BC_DIVIDE,
  366. /* 76 */ BC_NUMPADENTER,
  367. /* 77 */ BC_UNASSIGNED,
  368. /* 78 */ BC_SUBTRACT,
  369. /* 79 */ BC_UNASSIGNED,
  370. /* 80 */ BC_UNASSIGNED,
  371. /* 81 */ BC_NUMPADEQUALS,
  372. /* 82 */ BC_NUMPAD0,
  373. /* 83 */ BC_NUMPAD1,
  374. /* 84 */ BC_NUMPAD2,
  375. /* 85 */ BC_NUMPAD3,
  376. /* 86 */ BC_NUMPAD4,
  377. /* 87 */ BC_NUMPAD5,
  378. /* 88 */ BC_NUMPAD6,
  379. /* 89 */ BC_NUMPAD7,
  380. /* 90 */ BC_UNASSIGNED,
  381. /* 91 */ BC_NUMPAD8,
  382. /* 92 */ BC_NUMPAD9,
  383. /* 93 */ BC_CONVERT,
  384. /* 94 */ BC_NOCONVERT,
  385. /* 95 */ BC_NUMPADCOMMA,
  386. /* 96 */ BC_F5,
  387. /* 97 */ BC_F6,
  388. /* 98 */ BC_F7,
  389. /* 99 */ BC_F3,
  390. /* 100 */ BC_F8,
  391. /* 101 */ BC_F9,
  392. /* 102 */ BC_UNASSIGNED,
  393. /* 103 */ BC_F11,
  394. /* 104 */ BC_UNASSIGNED,
  395. /* 105 */ BC_UNASSIGNED,
  396. /* 106 */ BC_UNASSIGNED,
  397. /* 107 */ BC_SCROLL,
  398. /* 108 */ BC_UNASSIGNED,
  399. /* 109 */ BC_F10,
  400. /* 110 */ BC_UNASSIGNED,
  401. /* 111 */ BC_F12,
  402. /* 112 */ BC_UNASSIGNED,
  403. /* 113 */ BC_PAUSE,
  404. /* 114 */ BC_INSERT,
  405. /* 115 */ BC_HOME,
  406. /* 116 */ BC_PGUP,
  407. /* 117 */ BC_DELETE,
  408. /* 118 */ BC_F4,
  409. /* 119 */ BC_END,
  410. /* 120 */ BC_F2,
  411. /* 121 */ BC_PGDOWN,
  412. /* 122 */ BC_F1,
  413. /* 123 */ BC_LEFT,
  414. /* 124 */ BC_RIGHT,
  415. /* 125 */ BC_DOWN,
  416. /* 126 */ BC_UP,
  417. /* 127 */ BC_POWER
  418. };
  419. static UINT32 ButtonCodeToKeyCode[255];
  420. static void initKeyCodeMapping()
  421. {
  422. memset(ButtonCodeToKeyCode, 0, sizeof(ButtonCodeToKeyCode));
  423. UINT32 numKeyCodes = sizeof(KeyCodeMapping) / sizeof(KeyCodeMapping[0]);
  424. for(UINT32 i = 0; i < numKeyCodes; i++)
  425. ButtonCodeToKeyCode[KeyCodeMapping[i]] = i;
  426. }
  427. void flipY(NSScreen* screen, NSRect& rect)
  428. {
  429. NSRect screenFrame = [screen frame];
  430. rect.origin.y = screenFrame.size.height - (rect.origin.y + rect.size.height);
  431. }
  432. void flipY(NSScreen* screen, NSPoint &point)
  433. {
  434. NSRect screenFrame = [screen frame];
  435. point.y = screenFrame.size.height - point.y;
  436. }
  437. void flipYWindow(NSWindow* window, NSPoint &point)
  438. {
  439. NSRect windowFrame = [window frame];
  440. point.y = windowFrame.size.height - point.y;
  441. }
  442. /** Returns the name of the current application based on the information in the app. bundle. */
  443. static NSString* getAppName()
  444. {
  445. NSString* appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
  446. if (!appName)
  447. appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
  448. if (![appName length]) {
  449. appName = [[NSProcessInfo processInfo] processName];
  450. }
  451. return appName;
  452. }
  453. /** Creates the default menu for the application menu bar. */
  454. static void createApplicationMenu()
  455. { @autoreleasepool {
  456. NSMenu* mainMenu = [[NSMenu alloc] init];
  457. [NSApp setMainMenu:mainMenu];
  458. NSString* appName = getAppName();
  459. NSMenu* appleMenu = [[NSMenu alloc] initWithTitle:@""];
  460. NSString* aboutTitle = [@"About " stringByAppendingString:appName];
  461. [appleMenu addItemWithTitle:aboutTitle
  462. action:@selector(orderFrontStandardAboutPanel:)
  463. keyEquivalent:@""];
  464. [appleMenu addItem:[NSMenuItem separatorItem]];
  465. NSString* hideTitle = [@"Hide " stringByAppendingString:appName];
  466. [appleMenu addItemWithTitle:hideTitle action:@selector(hide:) keyEquivalent:@"h"];
  467. NSMenuItem* hideOthersMenuItem = [appleMenu
  468. addItemWithTitle:@"Hide Others"
  469. action:@selector(hideOtherApplications:)
  470. keyEquivalent:@"h"];
  471. [hideOthersMenuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
  472. [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
  473. [appleMenu addItem:[NSMenuItem separatorItem]];
  474. NSString* quitTitle = [@"Quit " stringByAppendingString:appName];
  475. [appleMenu addItemWithTitle:quitTitle action:@selector(terminate:) keyEquivalent:@"q"];
  476. NSMenuItem* appleMenuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
  477. [appleMenuItem setSubmenu:appleMenu];
  478. [[NSApp mainMenu] addItem:appleMenuItem];
  479. }}
  480. Event<void(const Vector2I &, const OSPointerButtonStates &)> Platform::onCursorMoved;
  481. Event<void(const Vector2I &, OSMouseButton button, const OSPointerButtonStates &)> Platform::onCursorButtonPressed;
  482. Event<void(const Vector2I &, OSMouseButton button, const OSPointerButtonStates &)> Platform::onCursorButtonReleased;
  483. Event<void(const Vector2I &, const OSPointerButtonStates &)> Platform::onCursorDoubleClick;
  484. Event<void(InputCommandType)> Platform::onInputCommand;
  485. Event<void(float)> Platform::onMouseWheelScrolled;
  486. Event<void(UINT32)> Platform::onCharInput;
  487. Event<void()> Platform::onMouseCaptureChanged;
  488. Platform::Pimpl* Platform::mData = bs_new<Platform::Pimpl>();
  489. Platform::~Platform()
  490. {
  491. }
  492. Vector2I Platform::getCursorPosition()
  493. {
  494. Lock lock(mData->cursorMutex);
  495. return mData->cursorPos;
  496. }
  497. void Platform::setCursorPosition(const Vector2I& screenPos)
  498. {
  499. [mData->cursorManager setPosition:screenPos];
  500. }
  501. void Platform::captureMouse(const RenderWindow& window)
  502. {
  503. // Do nothing
  504. }
  505. void Platform::releaseMouseCapture()
  506. {
  507. // Do nothing
  508. }
  509. bool Platform::isPointOverWindow(const RenderWindow& window, const Vector2I& screenPos)
  510. {
  511. CFArrayRef windowDicts = CGWindowListCopyWindowInfo(
  512. kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
  513. kCGNullWindowID);
  514. if(!windowDicts)
  515. return nil;
  516. CocoaWindow* cocoaWindow;
  517. window.getCustomAttribute("COCOA_WINDOW", &cocoaWindow);
  518. int32_t requestedWindowNumber = (int32_t)[cocoaWindow->_getPrivateData()->window windowNumber];
  519. CGPoint point = CGPointMake(screenPos.x, screenPos.y);
  520. CFIndex numEntries = CFArrayGetCount(windowDicts);
  521. for(CFIndex i = 0; i < numEntries; i++)
  522. {
  523. CFDictionaryRef dict = (CFDictionaryRef)CFArrayGetValueAtIndex(windowDicts, i);
  524. CFNumberRef layerRef = (CFNumberRef) CFDictionaryGetValue(dict, kCGWindowLayer);
  525. if(!layerRef)
  526. continue;
  527. // Ignore windows outside of layer 0, as those appear to be desktop elements
  528. int32_t layer;
  529. CFNumberGetValue(layerRef, kCFNumberIntType, &layer);
  530. // Layer 0 appear to be normal windows
  531. // Layer 8 appear to be modal windows
  532. // Layer 25 appear to be fullscreen windows
  533. // Note: This is based on experimentation, as no documentation about it exists
  534. if(layer != 0 && layer != 8 && layer != 25)
  535. continue;
  536. CFDictionaryRef boundsRef = (CFDictionaryRef)CFDictionaryGetValue(dict, kCGWindowBounds);
  537. CGRect rect;
  538. CGRectMakeWithDictionaryRepresentation(boundsRef, &rect);
  539. if(CGRectContainsPoint(rect, point))
  540. {
  541. // Windows are ordered front to back intrinsically, so the first one we are within bounds of is the one we want
  542. CFNumberRef windowNumRef = (CFNumberRef)CFDictionaryGetValue(dict, kCGWindowNumber);
  543. int32_t windowNumber;
  544. CFNumberGetValue(windowNumRef, kCGWindowIDCFNumberType, &windowNumber);
  545. return requestedWindowNumber == windowNumber;
  546. }
  547. }
  548. return false;
  549. }
  550. void Platform::hideCursor()
  551. {
  552. Lock lock(mData->cursorMutex);
  553. if(!mData->cursorIsHidden)
  554. {
  555. [NSCursor performSelectorOnMainThread:@selector(hide) withObject:nil waitUntilDone:NO];
  556. mData->cursorIsHidden = true;
  557. }
  558. }
  559. void Platform::showCursor()
  560. {
  561. Lock lock(mData->cursorMutex);
  562. if(mData->cursorIsHidden)
  563. {
  564. [NSCursor performSelectorOnMainThread:@selector(unhide) withObject:nil waitUntilDone:NO];
  565. mData->cursorIsHidden = false;
  566. }
  567. }
  568. bool Platform::isCursorHidden()
  569. {
  570. Lock lock(mData->cursorMutex);
  571. return mData->cursorIsHidden;
  572. }
  573. void Platform::clipCursorToWindow(const RenderWindow& window)
  574. {
  575. CocoaWindow* cocoaWindow;
  576. window.getCustomAttribute("COCOA_WINDOW", &cocoaWindow);
  577. [mData->cursorManager
  578. performSelectorOnMainThread:@selector(clipCursorToWindow:)
  579. withObject:[NSValue valueWithPointer:cocoaWindow]
  580. waitUntilDone:NO];
  581. }
  582. void Platform::clipCursorToRect(const Rect2I& screenRect)
  583. {
  584. [mData->cursorManager
  585. performSelectorOnMainThread:@selector(clipCursorToRect:)
  586. withObject:[NSValue value:&screenRect withObjCType:@encode(Rect2I)]
  587. waitUntilDone:NO];
  588. }
  589. void Platform::clipCursorDisable()
  590. {
  591. [mData->cursorManager
  592. performSelectorOnMainThread:@selector(clipCursorDisable)
  593. withObject:nil
  594. waitUntilDone:NO];
  595. }
  596. void Platform::setCursor(PixelData& pixelData, const Vector2I& hotSpot)
  597. { @autoreleasepool {
  598. NSImage* image = MacOSPlatform::createNSImage(pixelData);
  599. NSPoint point = NSMakePoint(hotSpot.x, hotSpot.y);
  600. NSCursor* cursor = [[NSCursor alloc] initWithImage:image hotSpot:point];
  601. NSArray* params = @[cursor, [NSValue valueWithPoint:point]];
  602. [mData->cursorManager
  603. performSelectorOnMainThread:@selector(setCursor:) withObject:params waitUntilDone:NO];
  604. }}
  605. void Platform::setIcon(const PixelData& pixelData)
  606. { @autoreleasepool {
  607. NSImage* image = MacOSPlatform::createNSImage(pixelData);
  608. [NSApp performSelectorOnMainThread:@selector(setApplicationIconImage:) withObject:image waitUntilDone:NO];
  609. }}
  610. void Platform::setCaptionNonClientAreas(const ct::RenderWindow& window, const Vector<Rect2I>& nonClientAreas)
  611. { @autoreleasepool {
  612. NSMutableArray* params = [[NSMutableArray alloc] init];
  613. UINT32 windowId;
  614. window.getCustomAttribute("WINDOW_ID", &windowId);
  615. NSValue* windowIdValue = [NSValue valueWithBytes:&windowId objCType:@encode(UINT32)];
  616. [params addObject:windowIdValue];
  617. for(auto& entry : nonClientAreas)
  618. [params addObject:[NSValue value:&entry withObjCType:@encode(bs::Rect2I)]];
  619. [mData->platformManager
  620. performSelectorOnMainThread:@selector(setCaptionNonClientAreas:)
  621. withObject:params
  622. waitUntilDone:NO];
  623. }}
  624. void Platform::setResizeNonClientAreas(const ct::RenderWindow& window, const Vector<NonClientResizeArea>& nonClientAreas)
  625. {
  626. // Do nothing, custom resize areas not needed on MacOS
  627. }
  628. void Platform::resetNonClientAreas(const ct::RenderWindow& window)
  629. {
  630. UINT32 windowId;
  631. window.getCustomAttribute("WINDOW_ID", &windowId);
  632. NSValue* windowIdValue = [NSValue valueWithBytes:&windowId objCType:@encode(UINT32)];
  633. [mData->platformManager
  634. performSelectorOnMainThread:@selector(resetNonClientAreas:)
  635. withObject:windowIdValue
  636. waitUntilDone:NO];
  637. }
  638. void Platform::sleep(UINT32 duration)
  639. {
  640. usleep(duration * 1000);
  641. }
  642. void Platform::copyToClipboard(const WString& string)
  643. { @autoreleasepool {
  644. String utf8String = UTF8::fromWide(string);
  645. NSString* text = [NSString stringWithUTF8String:utf8String.c_str()];
  646. [mData->platformManager performSelectorOnMainThread:@selector(setClipboardText:)
  647. withObject:text
  648. waitUntilDone:NO];
  649. }}
  650. WString Platform::copyFromClipboard()
  651. {
  652. Lock lock(mData->clipboardMutex);
  653. return mData->cachedClipboardData;
  654. }
  655. WString Platform::keyCodeToUnicode(UINT32 buttonCode)
  656. {
  657. UINT32 keyCode = ButtonCodeToKeyCode[buttonCode];
  658. TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
  659. if(!currentKeyboard)
  660. return L"";
  661. auto layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
  662. CFRelease(currentKeyboard);
  663. if(!layoutData)
  664. {
  665. currentKeyboard = TISCopyCurrentASCIICapableKeyboardInputSource();
  666. layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
  667. CFRelease(currentKeyboard);
  668. }
  669. if(!layoutData)
  670. return L"";
  671. auto keyLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(layoutData);
  672. UINT32 keysDown = 0;
  673. UniChar chars[4];
  674. UniCharCount length = 0;
  675. UCKeyTranslate(
  676. keyLayout,
  677. (unsigned short)keyCode,
  678. kUCKeyActionDisplay,
  679. 0,
  680. LMGetKbdType(),
  681. kUCKeyTranslateNoDeadKeysBit,
  682. &keysDown,
  683. sizeof(chars) / sizeof(chars[0]),
  684. &length,
  685. chars);
  686. U16String u16String((char16_t*)chars, (size_t)length);
  687. String utf8String = UTF8::fromUTF16(u16String);
  688. return UTF8::toWide(utf8String);
  689. }
  690. void Platform::openFolder(const Path& path)
  691. {
  692. String pathStr = path.toString();
  693. NSURL* url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:pathStr.c_str()]];
  694. [mData->platformManager
  695. performSelectorOnMainThread:@selector(openFolder:)
  696. withObject:url
  697. waitUntilDone:NO];
  698. }
  699. void Platform::_startUp()
  700. {
  701. initKeyCodeMapping();
  702. mData->appDelegate = [[BSAppDelegate alloc] init];
  703. mData->cursorManager = [[BSCursor alloc] initWithPlatformData:mData];
  704. mData->platformManager = [[BSPlatform alloc] initWithPlatformData:mData];
  705. [BSApplication sharedApplication];
  706. [NSApp setDelegate:mData->appDelegate];
  707. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  708. createApplicationMenu();
  709. [NSApp finishLaunching];
  710. }
  711. void Platform::_update()
  712. {
  713. CocoaDragAndDrop::update();
  714. {
  715. Lock lock(mData->cursorMutex);
  716. mData->cursorPos = [mData->cursorManager getPosition];
  717. }
  718. INT32 changeCount = [mData->platformManager getClipboardChangeCount];
  719. if(mData->clipboardChangeCount != changeCount)
  720. {
  721. NSString* string = [mData->platformManager getClipboardText];
  722. String utf8String;
  723. if(string)
  724. utf8String = [string UTF8String];
  725. {
  726. Lock lock(mData->clipboardMutex);
  727. mData->cachedClipboardData = UTF8::toWide(utf8String);
  728. }
  729. mData->clipboardChangeCount = changeCount;
  730. }
  731. _messagePump();
  732. }
  733. void Platform::_coreUpdate()
  734. {
  735. // Do nothing
  736. }
  737. void Platform::_shutDown()
  738. {
  739. // Do nothing
  740. }
  741. void Platform::_messagePump()
  742. { @autoreleasepool {
  743. while(true)
  744. {
  745. if(!mData->modalWindows.empty())
  746. {
  747. NSModalSession session = mData->modalWindows.back().session;
  748. [NSApp runModalSession:session];
  749. break;
  750. }
  751. else
  752. {
  753. NSEvent* event = [NSApp
  754. nextEventMatchingMask:NSEventMaskAny
  755. untilDate:[NSDate distantPast]
  756. inMode:NSDefaultRunLoopMode
  757. dequeue:YES];
  758. if (!event)
  759. break;
  760. [NSApp sendEvent:event];
  761. }
  762. }
  763. }}
  764. void MacOSPlatform::registerWindow(CocoaWindow* window)
  765. {
  766. // First window is assumed to be main
  767. if(!mData->mainWindow)
  768. mData->mainWindow = window;
  769. CocoaWindow::Pimpl* windowData = window->_getPrivateData();
  770. if(windowData->isModal)
  771. {
  772. ModalWindowInfo info = { window->_getWindowId(), windowData->modalSession };
  773. mData->modalWindows.push_back(info);
  774. }
  775. Lock lock(mData->windowMutex);
  776. mData->allWindows[window->_getWindowId()] = window;
  777. }
  778. void MacOSPlatform::unregisterWindow(CocoaWindow* window)
  779. {
  780. CocoaWindow::Pimpl* windowData = window->_getPrivateData();
  781. if(windowData->isModal)
  782. {
  783. UINT32 windowId = window->_getWindowId();
  784. auto iterFind = std::find_if(mData->modalWindows.begin(), mData->modalWindows.end(),
  785. [windowId](const ModalWindowInfo& x)
  786. {
  787. return x.windowId == windowId;
  788. });
  789. if(iterFind != mData->modalWindows.end())
  790. mData->modalWindows.erase(iterFind);
  791. }
  792. Lock lock(mData->windowMutex);
  793. mData->allWindows.erase(window->_getWindowId());
  794. [mData->cursorManager unregisterWindow:windowData->window];
  795. // Shut down app when the main window is closed
  796. if(mData->mainWindow == window)
  797. {
  798. bs::gCoreApplication().quitRequested();
  799. mData->mainWindow = nullptr;
  800. }
  801. }
  802. void MacOSPlatform::lockWindows()
  803. {
  804. mData->windowMutex.lock();
  805. }
  806. void MacOSPlatform::unlockWindows()
  807. {
  808. mData->windowMutex.unlock();
  809. }
  810. CocoaWindow* MacOSPlatform::getWindow(UINT32 windowId)
  811. {
  812. auto iterFind = mData->allWindows.find(windowId);
  813. if(iterFind == mData->allWindows.end())
  814. return nullptr;
  815. return iterFind->second;
  816. }
  817. NSImage* MacOSPlatform::createNSImage(const PixelData& data)
  818. {
  819. // Premultiply alpha
  820. Vector<Color> colors = data.getColors();
  821. for(auto& color : colors)
  822. {
  823. color.r *= color.a;
  824. color.g *= color.a;
  825. color.b *= color.a;
  826. }
  827. // Convert to RGBA
  828. SPtr<PixelData> rgbaData = PixelData::create(data.getWidth(), data.getHeight(), 1, PF_RGBA8);
  829. rgbaData->setColors(colors);
  830. @autoreleasepool
  831. {
  832. INT32 pitch = data.getWidth() * sizeof(UINT32);
  833. NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc]
  834. initWithBitmapDataPlanes:nullptr
  835. pixelsWide:data.getWidth()
  836. pixelsHigh:data.getHeight()
  837. bitsPerSample:8
  838. samplesPerPixel:4
  839. hasAlpha:YES
  840. isPlanar:NO
  841. colorSpaceName:NSDeviceRGBColorSpace
  842. bytesPerRow:pitch
  843. bitsPerPixel:32];
  844. unsigned char* pixels = [imageRep bitmapData];
  845. memcpy(pixels, rgbaData->getData(), data.getHeight() * pitch);
  846. NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(data.getWidth(), data.getHeight())];
  847. [image addRepresentation:imageRep];
  848. return image;
  849. }
  850. }
  851. void MacOSPlatform::sendInputCommandEvent(InputCommandType inputCommand)
  852. {
  853. onInputCommand(inputCommand);
  854. }
  855. void MacOSPlatform::sendCharInputEvent(UINT32 character)
  856. {
  857. onCharInput(character);
  858. }
  859. void MacOSPlatform::sendPointerButtonPressedEvent(
  860. const Vector2I& pos,
  861. OSMouseButton button,
  862. const OSPointerButtonStates& buttonStates)
  863. {
  864. onCursorButtonPressed(pos, button, buttonStates);
  865. }
  866. void MacOSPlatform::sendPointerButtonReleasedEvent(
  867. const Vector2I& pos,
  868. OSMouseButton button,
  869. const OSPointerButtonStates& buttonStates)
  870. {
  871. onCursorButtonReleased(pos, button, buttonStates);
  872. }
  873. void MacOSPlatform::sendPointerDoubleClickEvent(const Vector2I& pos, const OSPointerButtonStates& buttonStates)
  874. {
  875. onCursorDoubleClick(pos, buttonStates);
  876. }
  877. void MacOSPlatform::sendPointerMovedEvent(const Vector2I& pos, const OSPointerButtonStates& buttonStates)
  878. {
  879. onCursorMoved(pos, buttonStates);
  880. }
  881. void MacOSPlatform::sendMouseWheelScrollEvent(float delta)
  882. {
  883. onMouseWheelScrolled(delta);
  884. }
  885. void MacOSPlatform::notifyWindowEvent(bs::WindowEventType type, bs::UINT32 windowId)
  886. {
  887. CocoaWindow* window = nullptr;
  888. {
  889. auto iterFind = mData->allWindows.find(windowId);
  890. if(iterFind == mData->allWindows.end())
  891. return;
  892. window = iterFind->second;
  893. }
  894. auto renderWindow = (RenderWindow*)window->_getUserData();
  895. if(renderWindow == nullptr)
  896. {
  897. // If it's a render window we allow the client code to handle the message, otherwise we just destroy it
  898. if(type == WindowEventType::CloseRequested)
  899. window->_destroy();
  900. return;
  901. }
  902. renderWindow->_notifyWindowEvent(type);
  903. }
  904. NSCursor* MacOSPlatform::_getCurrentCursor()
  905. {
  906. return [mData->cursorManager currentCursor];
  907. }
  908. bool MacOSPlatform::_clipCursor(Vector2I& pos)
  909. {
  910. return [mData->cursorManager clipCursor:pos];
  911. }
  912. void MacOSPlatform::_updateClipBounds(NSWindow* window)
  913. {
  914. [mData->cursorManager updateClipBounds:window];
  915. }
  916. void MacOSPlatform::_setCursorPosition(const Vector2I& position)
  917. {
  918. [mData->cursorManager setPosition:position];
  919. }
  920. }