BsMacOSPlatform.mm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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. CocoaWindow* mainWindow = nullptr;
  62. UnorderedMap<UINT32, CocoaWindow*> allWindows;
  63. Vector<ModalWindowInfo> modalWindows;
  64. BSPlatform* platformManager = nil;
  65. // Cursor
  66. BSCursor* cursorManager = nil;
  67. Mutex cursorMutex;
  68. bool cursorIsHidden = false;
  69. Vector2I cursorPos;
  70. // Clipboard
  71. Mutex clipboardMutex;
  72. WString cachedClipboardData;
  73. INT32 clipboardChangeCount = -1;
  74. };
  75. }
  76. /**
  77. * Contains cursor specific functionality. Encapsulated in objective C so its selectors can be triggered from other
  78. * threads.
  79. */
  80. @interface BSCursor : NSObject
  81. @property NSCursor* currentCursor;
  82. -(BSCursor*) initWithPlatformData:(bs::Platform::Pimpl*)platformData;
  83. -(bs::Vector2I) getPosition;
  84. -(void) setPosition:(const bs::Vector2I&) position;
  85. -(BOOL) clipCursor:(bs::Vector2I&) position;
  86. -(void) updateClipBounds:(NSWindow*) window;
  87. -(void) clipCursorToWindow:(NSValue*) windowValue;
  88. -(void) clipCursorToRect:(NSValue*) rectValue;
  89. -(void) clipCursorDisable;
  90. -(void) setCursor:(NSArray*) params;
  91. -(void) unregisterWindow:(NSWindow*) window;
  92. @end
  93. @implementation BSCursor
  94. {
  95. bs::Platform::Pimpl* platformData;
  96. bool cursorClipEnabled;
  97. bs::Rect2I cursorClipRect;
  98. NSWindow* cursorClipWindow;
  99. }
  100. - (BSCursor*)initWithPlatformData:(bs::Platform::Pimpl*)data
  101. {
  102. self = [super init];
  103. platformData = data;
  104. return self;
  105. }
  106. - (bs::Vector2I)getPosition
  107. {
  108. NSPoint point = [NSEvent mouseLocation];
  109. for (NSScreen* screen in [NSScreen screens])
  110. {
  111. NSRect frame = [screen frame];
  112. if (NSMouseInRect(point, frame, NO))
  113. bs::flipY(screen, point);
  114. }
  115. bs::Vector2I output;
  116. output.x = (int32_t)point.x;
  117. output.y = (int32_t)point.y;
  118. return output;
  119. }
  120. - (void)setPosition:(const bs::Vector2I&)position
  121. {
  122. NSPoint point = NSMakePoint(position.x, position.y);
  123. CGWarpMouseCursorPosition(point);
  124. Lock lock(platformData->cursorMutex);
  125. platformData->cursorPos = position;
  126. }
  127. - (BOOL)clipCursor:(bs::Vector2I&)position
  128. {
  129. if(!cursorClipEnabled)
  130. return false;
  131. int32_t clippedX = position.x - cursorClipRect.x;
  132. int32_t clippedY = position.y - cursorClipRect.y;
  133. if(clippedX < 0)
  134. clippedX = 0;
  135. else if(clippedX >= (int32_t)cursorClipRect.width)
  136. clippedX = cursorClipRect.width > 0 ? cursorClipRect.width - 1 : 0;
  137. if(clippedY < 0)
  138. clippedY = 0;
  139. else if(clippedY >= (int32_t)cursorClipRect.height)
  140. clippedY = cursorClipRect.height > 0 ? cursorClipRect.height - 1 : 0;
  141. clippedX += cursorClipRect.x;
  142. clippedY += cursorClipRect.y;
  143. if(clippedX != position.x || clippedY != position.y)
  144. {
  145. position.x = clippedX;
  146. position.y = clippedY;
  147. return true;
  148. }
  149. return false;
  150. }
  151. - (void)updateClipBounds:(NSWindow*)window
  152. {
  153. if(!cursorClipEnabled || cursorClipWindow != window)
  154. return;
  155. NSRect rect = [window contentRectForFrameRect:[window frame]];
  156. bs::flipY([window screen], rect);
  157. cursorClipRect.x = (int32_t)rect.origin.x;
  158. cursorClipRect.y = (int32_t)rect.origin.y;
  159. cursorClipRect.width = (uint32_t)rect.size.width;
  160. cursorClipRect.height = (uint32_t)rect.size.height;
  161. }
  162. - (void)clipCursorToWindow:(NSValue*)windowValue
  163. {
  164. bs::CocoaWindow* window;
  165. [windowValue getValue:&window];
  166. cursorClipEnabled = true;
  167. cursorClipWindow = window->_getPrivateData()->window;
  168. [self updateClipBounds:cursorClipWindow];
  169. bs::Vector2I pos = [self getPosition];
  170. if([self clipCursor:pos])
  171. [self setPosition:pos];
  172. }
  173. - (void)clipCursorToRect:(NSValue*)rectValue
  174. {
  175. bs::Rect2I rect;
  176. [rectValue getValue:&rect];
  177. cursorClipEnabled = true;
  178. cursorClipRect = rect;
  179. cursorClipWindow = nullptr;
  180. bs::Vector2I pos = [self getPosition];
  181. if([self clipCursor:pos])
  182. [self setPosition:pos];
  183. }
  184. - (void)clipCursorDisable
  185. {
  186. cursorClipEnabled = false;
  187. cursorClipWindow = nullptr;
  188. }
  189. - (void)setCursor:(NSArray*)params
  190. {
  191. NSCursor* cursor = params[0];
  192. NSValue* hotSpotValue = params[1];
  193. NSPoint hotSpot;
  194. [hotSpotValue getValue:&hotSpot];
  195. [self setCurrentCursor:cursor];
  196. for(auto& entry : platformData->allWindows)
  197. {
  198. NSWindow* window = entry.second->_getPrivateData()->window;
  199. [window invalidateCursorRectsForView:[window contentView]];
  200. }
  201. }
  202. - (void)unregisterWindow:(NSWindow*)window
  203. {
  204. if(cursorClipEnabled && cursorClipWindow == window)
  205. [self clipCursorDisable];
  206. }
  207. @end
  208. /** Contains platform specific functionality that is meant to be delayed executed from the sim thread, through Platform. */
  209. @interface BSPlatform : NSObject
  210. -(BSPlatform*) initWithPlatformData:(bs::Platform::Pimpl*)platformData;
  211. -(void) setCaptionNonClientAreas:(NSArray*) params;
  212. -(void) resetNonClientAreas:(NSValue*) windowValue;
  213. -(void) openFolder:(NSURL*) url;
  214. -(void) setClipboardText:(NSString*) text;
  215. -(NSString*) getClipboardText;
  216. -(int32_t) getClipboardChangeCount;
  217. @end
  218. @implementation BSPlatform
  219. {
  220. bs::Platform::Pimpl* mPlatformData;
  221. }
  222. - (BSPlatform*)initWithPlatformData:(bs::Platform::Pimpl*)platformData
  223. {
  224. self = [super init];
  225. mPlatformData = platformData;
  226. return self;
  227. }
  228. - (void)setCaptionNonClientAreas:(NSArray*)params
  229. {
  230. NSValue* windowValue = params[0];
  231. bs::CocoaWindow* window = (bs::CocoaWindow*)[windowValue pointerValue];
  232. NSUInteger numEntries = [params count] - 1;
  233. bs::Vector<bs::Rect2I> areas;
  234. for(NSUInteger i = 0; i < numEntries; i++)
  235. {
  236. NSValue* value = params[i];
  237. bs::Rect2I area;
  238. [value getValue:&area];
  239. areas.push_back(area);
  240. }
  241. window->_setDragZones(areas);
  242. }
  243. - (void)resetNonClientAreas:(NSValue*) windowValue
  244. {
  245. bs::CocoaWindow* window = (bs::CocoaWindow*)[windowValue pointerValue];
  246. window->_setDragZones({});
  247. }
  248. - (void)openFolder:(NSURL*)url
  249. {
  250. [[NSWorkspace sharedWorkspace] openURL:url];
  251. }
  252. - (void) setClipboardText:(NSString*) text
  253. { @autoreleasepool {
  254. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  255. [pasteboard clearContents];
  256. NSArray* objects = [NSArray arrayWithObject:text];
  257. [pasteboard writeObjects:objects];
  258. }}
  259. - (NSString*) getClipboardText
  260. { @autoreleasepool {
  261. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  262. NSArray* classes = [NSArray arrayWithObjects:[NSString class], nil];
  263. NSDictionary* options = [NSDictionary dictionary];
  264. NSArray* items = [pasteboard readObjectsForClasses:classes options:options];
  265. if(!items || items.count == 0)
  266. return nil;
  267. return (NSString*) items[0];
  268. }}
  269. - (int32_t)getClipboardChangeCount
  270. {
  271. return (int32_t)[[NSPasteboard generalPasteboard] changeCount];
  272. }
  273. @end
  274. namespace bs
  275. {
  276. void flipY(NSScreen* screen, NSRect& rect)
  277. {
  278. NSRect screenFrame = [screen frame];
  279. rect.origin.y = screenFrame.size.height - (rect.origin.y + rect.size.height);
  280. }
  281. void flipY(NSScreen* screen, NSPoint &point)
  282. {
  283. NSRect screenFrame = [screen frame];
  284. point.y = screenFrame.size.height - point.y;
  285. }
  286. void flipYWindow(NSWindow* window, NSPoint &point)
  287. {
  288. NSRect windowFrame = [window frame];
  289. point.y = windowFrame.size.height - point.y;
  290. }
  291. /** Returns the name of the current application based on the information in the app. bundle. */
  292. static NSString* getAppName()
  293. {
  294. NSString* appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
  295. if (!appName)
  296. appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
  297. if (![appName length]) {
  298. appName = [[NSProcessInfo processInfo] processName];
  299. }
  300. return appName;
  301. }
  302. /** Creates the default menu for the application menu bar. */
  303. static void createApplicationMenu()
  304. { @autoreleasepool {
  305. NSMenu* mainMenu = [[NSMenu alloc] init];
  306. [NSApp setMainMenu:mainMenu];
  307. NSString* appName = getAppName();
  308. NSMenu* appleMenu = [[NSMenu alloc] initWithTitle:@""];
  309. NSString* aboutTitle = [@"About " stringByAppendingString:appName];
  310. [appleMenu addItemWithTitle:aboutTitle
  311. action:@selector(orderFrontStandardAboutPanel:)
  312. keyEquivalent:@""];
  313. [appleMenu addItem:[NSMenuItem separatorItem]];
  314. NSString* hideTitle = [@"Hide " stringByAppendingString:appName];
  315. [appleMenu addItemWithTitle:hideTitle action:@selector(hide:) keyEquivalent:@"h"];
  316. NSMenuItem* hideOthersMenuItem = [appleMenu
  317. addItemWithTitle:@"Hide Others"
  318. action:@selector(hideOtherApplications:)
  319. keyEquivalent:@"h"];
  320. [hideOthersMenuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];
  321. [appleMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
  322. [appleMenu addItem:[NSMenuItem separatorItem]];
  323. NSString* quitTitle = [@"Quit " stringByAppendingString:appName];
  324. [appleMenu addItemWithTitle:quitTitle action:@selector(terminate:) keyEquivalent:@"q"];
  325. NSMenuItem* appleMenuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
  326. [appleMenuItem setSubmenu:appleMenu];
  327. [[NSApp mainMenu] addItem:appleMenuItem];
  328. }}
  329. Event<void(const Vector2I &, const OSPointerButtonStates &)> Platform::onCursorMoved;
  330. Event<void(const Vector2I &, OSMouseButton button, const OSPointerButtonStates &)> Platform::onCursorButtonPressed;
  331. Event<void(const Vector2I &, OSMouseButton button, const OSPointerButtonStates &)> Platform::onCursorButtonReleased;
  332. Event<void(const Vector2I &, const OSPointerButtonStates &)> Platform::onCursorDoubleClick;
  333. Event<void(InputCommandType)> Platform::onInputCommand;
  334. Event<void(float)> Platform::onMouseWheelScrolled;
  335. Event<void(UINT32)> Platform::onCharInput;
  336. Event<void()> Platform::onMouseCaptureChanged;
  337. Platform::Pimpl* Platform::mData = bs_new<Platform::Pimpl>();
  338. Platform::~Platform()
  339. {
  340. }
  341. Vector2I Platform::getCursorPosition()
  342. {
  343. Lock lock(mData->cursorMutex);
  344. return mData->cursorPos;
  345. }
  346. void Platform::setCursorPosition(const Vector2I& screenPos)
  347. {
  348. [mData->cursorManager setPosition:screenPos];
  349. }
  350. void Platform::captureMouse(const RenderWindow& window)
  351. {
  352. // Do nothing
  353. }
  354. void Platform::releaseMouseCapture()
  355. {
  356. // Do nothing
  357. }
  358. bool Platform::isPointOverWindow(const RenderWindow& window, const Vector2I& screenPos)
  359. {
  360. CFArrayRef windowDicts = CGWindowListCopyWindowInfo(
  361. kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
  362. kCGNullWindowID);
  363. if(!windowDicts)
  364. return nil;
  365. CocoaWindow* cocoaWindow;
  366. window.getCustomAttribute("COCOA_WINDOW", &cocoaWindow);
  367. int32_t requestedWindowNumber = (int32_t)[cocoaWindow->_getPrivateData()->window windowNumber];
  368. CGPoint point = CGPointMake(screenPos.x, screenPos.y);
  369. CFIndex numEntries = CFArrayGetCount(windowDicts);
  370. for(CFIndex i = 0; i < numEntries; i++)
  371. {
  372. CFDictionaryRef dict = (CFDictionaryRef)CFArrayGetValueAtIndex(windowDicts, i);
  373. CFNumberRef layerRef = (CFNumberRef) CFDictionaryGetValue(dict, kCGWindowLayer);
  374. if(!layerRef)
  375. continue;
  376. // Ignore windows outside of layer 0, as those appear to be desktop elements
  377. int32_t layer;
  378. CFNumberGetValue(layerRef, kCFNumberIntType, &layer);
  379. if(layer != 0)
  380. continue;
  381. CFDictionaryRef boundsRef = (CFDictionaryRef)CFDictionaryGetValue(dict, kCGWindowBounds);
  382. CGRect rect;
  383. CGRectMakeWithDictionaryRepresentation(boundsRef, &rect);
  384. if(CGRectContainsPoint(rect, point))
  385. {
  386. // Windows are ordered front to back intrinsically, so the first one we are within bounds of is the one we want
  387. CFNumberRef windowNumRef = (CFNumberRef)CFDictionaryGetValue(dict, kCGWindowNumber);
  388. int32_t windowNumber;
  389. CFNumberGetValue(windowNumRef, kCGWindowIDCFNumberType, &windowNumber);
  390. return requestedWindowNumber == windowNumber;
  391. }
  392. }
  393. return false;
  394. }
  395. void Platform::hideCursor()
  396. {
  397. Lock lock(mData->cursorMutex);
  398. if(!mData->cursorIsHidden)
  399. {
  400. [NSCursor performSelectorOnMainThread:@selector(unhide) withObject:nil waitUntilDone:NO];
  401. mData->cursorIsHidden = true;
  402. }
  403. }
  404. void Platform::showCursor()
  405. {
  406. Lock lock(mData->cursorMutex);
  407. if(mData->cursorIsHidden)
  408. {
  409. [NSCursor performSelectorOnMainThread:@selector(hide) withObject:nil waitUntilDone:NO];
  410. mData->cursorIsHidden = false;
  411. }
  412. }
  413. bool Platform::isCursorHidden()
  414. {
  415. Lock lock(mData->cursorMutex);
  416. return mData->cursorIsHidden;
  417. }
  418. void Platform::clipCursorToWindow(const RenderWindow& window)
  419. {
  420. CocoaWindow* cocoaWindow;
  421. window.getCustomAttribute("COCOA_WINDOW", &cocoaWindow);
  422. [mData->cursorManager
  423. performSelectorOnMainThread:@selector(clipCursorToWindow:)
  424. withObject:[NSValue valueWithPointer:cocoaWindow]
  425. waitUntilDone:NO];
  426. }
  427. void Platform::clipCursorToRect(const Rect2I& screenRect)
  428. {
  429. [mData->cursorManager
  430. performSelectorOnMainThread:@selector(clipCursorToRect:)
  431. withObject:[NSValue value:&screenRect withObjCType:@encode(Rect2I)]
  432. waitUntilDone:NO];
  433. }
  434. void Platform::clipCursorDisable()
  435. {
  436. [mData->cursorManager
  437. performSelectorOnMainThread:@selector(clipCursorDisable)
  438. withObject:nil
  439. waitUntilDone:NO];
  440. }
  441. void Platform::setCursor(PixelData& pixelData, const Vector2I& hotSpot)
  442. { @autoreleasepool {
  443. NSImage* image = MacOSPlatform::createNSImage(pixelData);
  444. NSPoint point = NSMakePoint(hotSpot.x, hotSpot.y);
  445. NSCursor* cursor = [[NSCursor alloc] initWithImage:image hotSpot:point];
  446. NSArray* params = @[cursor, [NSValue valueWithPoint:point]];
  447. [mData->cursorManager
  448. performSelectorOnMainThread:@selector(setCursor:) withObject:params waitUntilDone:NO];
  449. }}
  450. void Platform::setIcon(const PixelData& pixelData)
  451. { @autoreleasepool {
  452. NSImage* image = MacOSPlatform::createNSImage(pixelData);
  453. [NSApp performSelectorOnMainThread:@selector(setApplicationIconImage:) withObject:image waitUntilDone:NO];
  454. }}
  455. void Platform::setCaptionNonClientAreas(const ct::RenderWindow& window, const Vector<Rect2I>& nonClientAreas)
  456. { @autoreleasepool {
  457. NSMutableArray* params = [[NSMutableArray alloc] init];
  458. CocoaWindow* cocoaWindow;
  459. window.getCustomAttribute("COCOA_WINDOW", &cocoaWindow);
  460. [params addObject:[NSValue valueWithPointer:cocoaWindow]];
  461. for(auto& entry : nonClientAreas)
  462. [params addObject:[NSValue value:&entry withObjCType:@encode(bs::Rect2I)]];
  463. [mData->platformManager
  464. performSelectorOnMainThread:@selector(setCaptionNonClientAreas:)
  465. withObject:params
  466. waitUntilDone:NO];
  467. }}
  468. void Platform::setResizeNonClientAreas(const ct::RenderWindow& window, const Vector<NonClientResizeArea>& nonClientAreas)
  469. {
  470. // Do nothing, custom resize areas not needed on MacOS
  471. }
  472. void Platform::resetNonClientAreas(const ct::RenderWindow& window)
  473. {
  474. CocoaWindow* cocoaWindow;
  475. window.getCustomAttribute("COCOA_WINDOW", &cocoaWindow);
  476. NSValue* windowValue = [NSValue valueWithPointer:cocoaWindow];
  477. [mData->platformManager
  478. performSelectorOnMainThread:@selector(resetNonClientAreas:)
  479. withObject:windowValue
  480. waitUntilDone:NO];
  481. }
  482. void Platform::sleep(UINT32 duration)
  483. {
  484. usleep(duration * 1000);
  485. }
  486. void Platform::copyToClipboard(const WString& string)
  487. { @autoreleasepool {
  488. String utf8String = UTF8::fromWide(string);
  489. NSString* text = [NSString stringWithUTF8String:utf8String.c_str()];
  490. [mData->platformManager performSelectorOnMainThread:@selector(setClipboardText:)
  491. withObject:text
  492. waitUntilDone:NO];
  493. }}
  494. WString Platform::copyFromClipboard()
  495. {
  496. Lock lock(mData->clipboardMutex);
  497. return mData->cachedClipboardData;
  498. }
  499. WString Platform::keyCodeToUnicode(UINT32 keyCode)
  500. {
  501. TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
  502. CFDataRef layoutData = (CFDataRef)TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
  503. const UCKeyboardLayout* keyLayout = (const UCKeyboardLayout*)CFDataGetBytePtr(layoutData);
  504. UINT32 keysDown = 0;
  505. UniChar chars[4];
  506. UniCharCount length = 0;
  507. UCKeyTranslate(
  508. keyLayout,
  509. (unsigned short)keyCode,
  510. kUCKeyActionDisplay,
  511. 0,
  512. LMGetKbdType(),
  513. kUCKeyTranslateNoDeadKeysBit,
  514. &keysDown,
  515. sizeof(chars) / sizeof(chars[0]),
  516. &length,
  517. chars);
  518. CFRelease(keyLayout);
  519. U16String u16String((char16_t*)chars, (size_t)length);
  520. String utf8String = UTF8::fromUTF16(u16String);
  521. return UTF8::toWide(utf8String);
  522. }
  523. void Platform::openFolder(const Path& path)
  524. {
  525. String pathStr = path.toString();
  526. NSURL* url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:pathStr.c_str()]];
  527. [mData->platformManager
  528. performSelectorOnMainThread:@selector(openFolder:)
  529. withObject:url
  530. waitUntilDone:NO];
  531. }
  532. void Platform::_startUp()
  533. {
  534. mData->appDelegate = [[BSAppDelegate alloc] init];
  535. mData->cursorManager = [[BSCursor alloc] initWithPlatformData:mData];
  536. mData->platformManager = [[BSPlatform alloc] initWithPlatformData:mData];
  537. [BSApplication sharedApplication];
  538. [NSApp setDelegate:mData->appDelegate];
  539. [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
  540. createApplicationMenu();
  541. [NSApp finishLaunching];
  542. }
  543. void Platform::_update()
  544. {
  545. CocoaDragAndDrop::update();
  546. {
  547. Lock lock(mData->cursorMutex);
  548. mData->cursorPos = [mData->cursorManager getPosition];
  549. }
  550. INT32 changeCount = [mData->platformManager getClipboardChangeCount];
  551. if(mData->clipboardChangeCount != changeCount)
  552. {
  553. NSString* string = [mData->platformManager getClipboardText];
  554. String utf8String = [string UTF8String];
  555. {
  556. Lock lock(mData->clipboardMutex);
  557. mData->cachedClipboardData = UTF8::toWide(utf8String);
  558. }
  559. mData->clipboardChangeCount = changeCount;
  560. }
  561. _messagePump();
  562. }
  563. void Platform::_coreUpdate()
  564. {
  565. // Do nothing
  566. }
  567. void Platform::_shutDown()
  568. {
  569. // Do nothing
  570. }
  571. void Platform::_messagePump()
  572. { @autoreleasepool {
  573. while(true)
  574. {
  575. if(!mData->modalWindows.empty())
  576. {
  577. NSModalSession session = mData->modalWindows.back().session;
  578. if([NSApp runModalSession:session] != NSModalResponseContinue)
  579. break;
  580. }
  581. else
  582. {
  583. NSEvent* event = [NSApp
  584. nextEventMatchingMask:NSEventMaskAny
  585. untilDate:[NSDate distantPast]
  586. inMode:NSDefaultRunLoopMode
  587. dequeue:YES];
  588. if (!event)
  589. break;
  590. [NSApp sendEvent:event];
  591. }
  592. }
  593. }}
  594. void MacOSPlatform::registerWindow(CocoaWindow* window)
  595. {
  596. // First window is assumed to be main
  597. if(!mData->mainWindow)
  598. mData->mainWindow = window;
  599. CocoaWindow::Pimpl* windowData = window->_getPrivateData();
  600. if(windowData->isModal)
  601. {
  602. ModalWindowInfo info = { window->_getWindowId(), windowData->modalSession };
  603. mData->modalWindows.push_back(info);
  604. }
  605. mData->allWindows[window->_getWindowId()] = window;
  606. }
  607. void MacOSPlatform::unregisterWindow(CocoaWindow* window)
  608. {
  609. CocoaWindow::Pimpl* windowData = window->_getPrivateData();
  610. if(windowData->isModal)
  611. {
  612. UINT32 windowId = window->_getWindowId();
  613. auto iterFind = std::find_if(mData->modalWindows.begin(), mData->modalWindows.end(),
  614. [windowId](const ModalWindowInfo& x)
  615. {
  616. return x.windowId == windowId;
  617. });
  618. if(iterFind != mData->modalWindows.end())
  619. mData->modalWindows.erase(iterFind);
  620. }
  621. mData->allWindows.erase(window->_getWindowId());
  622. [mData->cursorManager unregisterWindow:windowData->window];
  623. // Shut down app when the main window is closed
  624. if(mData->mainWindow == window)
  625. {
  626. bs::gCoreApplication().quitRequested();
  627. mData->mainWindow = nullptr;
  628. }
  629. }
  630. NSImage* MacOSPlatform::createNSImage(const PixelData& data)
  631. {
  632. // Premultiply alpha
  633. Vector<Color> colors = data.getColors();
  634. for(auto& color : colors)
  635. {
  636. color.r *= color.a;
  637. color.g *= color.a;
  638. color.b *= color.a;
  639. }
  640. // Convert to RGBA
  641. SPtr<PixelData> rgbaData = PixelData::create(data.getWidth(), data.getHeight(), 1, PF_RGBA8);
  642. rgbaData->setColors(colors);
  643. @autoreleasepool
  644. {
  645. INT32 pitch = data.getWidth() * sizeof(UINT32);
  646. NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc]
  647. initWithBitmapDataPlanes:nullptr
  648. pixelsWide:data.getWidth()
  649. pixelsHigh:data.getHeight()
  650. bitsPerSample:8
  651. samplesPerPixel:4
  652. hasAlpha:YES
  653. isPlanar:NO
  654. colorSpaceName:NSDeviceRGBColorSpace
  655. bytesPerRow:pitch
  656. bitsPerPixel:32];
  657. unsigned char* pixels = [imageRep bitmapData];
  658. memcpy(pixels, rgbaData->getData(), data.getHeight() * pitch);
  659. NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(data.getWidth(), data.getHeight())];
  660. [image addRepresentation:imageRep];
  661. return image;
  662. }
  663. }
  664. void MacOSPlatform::sendInputCommandEvent(InputCommandType inputCommand)
  665. {
  666. onInputCommand(inputCommand);
  667. }
  668. void MacOSPlatform::sendCharInputEvent(UINT32 character)
  669. {
  670. onCharInput(character);
  671. }
  672. void MacOSPlatform::sendPointerButtonPressedEvent(
  673. const Vector2I& pos,
  674. OSMouseButton button,
  675. const OSPointerButtonStates& buttonStates)
  676. {
  677. onCursorButtonPressed(pos, button, buttonStates);
  678. }
  679. void MacOSPlatform::sendPointerButtonReleasedEvent(
  680. const Vector2I& pos,
  681. OSMouseButton button,
  682. const OSPointerButtonStates& buttonStates)
  683. {
  684. onCursorButtonReleased(pos, button, buttonStates);
  685. }
  686. void MacOSPlatform::sendPointerDoubleClickEvent(const Vector2I& pos, const OSPointerButtonStates& buttonStates)
  687. {
  688. onCursorDoubleClick(pos, buttonStates);
  689. }
  690. void MacOSPlatform::sendPointerMovedEvent(const Vector2I& pos, const OSPointerButtonStates& buttonStates)
  691. {
  692. onCursorMoved(pos, buttonStates);
  693. }
  694. void MacOSPlatform::sendMouseWheelScrollEvent(float delta)
  695. {
  696. onMouseWheelScrolled(delta);
  697. }
  698. void MacOSPlatform::notifyWindowEvent(bs::WindowEventType type, bs::UINT32 windowId)
  699. {
  700. CocoaWindow* window = nullptr;
  701. {
  702. auto iterFind = mData->allWindows.find(windowId);
  703. if(iterFind == mData->allWindows.end())
  704. return;
  705. window = iterFind->second;
  706. }
  707. auto renderWindow = (RenderWindow*)window->_getUserData();
  708. if(renderWindow == nullptr)
  709. {
  710. // If it's a render window we allow the client code to handle the message, otherwise we just destroy it
  711. if(type == WindowEventType::CloseRequested)
  712. window->_destroy();
  713. return;
  714. }
  715. renderWindow->_notifyWindowEvent(type);
  716. }
  717. NSCursor* MacOSPlatform::_getCurrentCursor()
  718. {
  719. return [mData->cursorManager currentCursor];
  720. }
  721. bool MacOSPlatform::_clipCursor(Vector2I& pos)
  722. {
  723. return [mData->cursorManager clipCursor:pos];
  724. }
  725. void MacOSPlatform::_updateClipBounds(NSWindow* window)
  726. {
  727. [mData->cursorManager updateClipBounds:window];
  728. }
  729. void MacOSPlatform::_setCursorPosition(const Vector2I& position)
  730. {
  731. [mData->cursorManager setPosition:position];
  732. }
  733. }