CocoaWindow.mm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. 
  2. // Early alpha version!
  3. // Do not use in released applications.
  4. // Missing features:
  5. // * Copy and paste with clipboard.
  6. // Not yet implemented.
  7. // * Minimizing the window
  8. // It just bounces back instantly.
  9. // * Toggling full-screen
  10. // The window and view do not resize when entering or leaving full-screen.
  11. // The application does not detect when the window has been maximized.
  12. // * Synchronization of canvas upload.
  13. // There is a temporary frame-rate limiting hack to hide the worst glitches.
  14. // * Setting cursor position and visibility.
  15. // Not yet implemented.
  16. // See if anything more is missing...
  17. #import <Cocoa/Cocoa.h>
  18. #include "../DFPSR/api/imageAPI.h"
  19. #include "../DFPSR/api/drawAPI.h"
  20. #include "../DFPSR/api/timeAPI.h"
  21. #include "../DFPSR/implementation/gui/BackendWindow.h"
  22. #include "../DFPSR/base/heap.h"
  23. #include <climits>
  24. #include "../DFPSR/settings.h"
  25. static const int bufferCount = 2;
  26. static bool applicationInitialized = false;
  27. static NSApplication *application;
  28. class CocoaWindow : public dsr::BackendWindow {
  29. private:
  30. // Handle to the Cocoa window
  31. NSWindow *window = nullptr;
  32. // The Core Graphics color space
  33. CGColorSpace *colorSpace = nullptr;
  34. // Identity to track enter and exit events for.
  35. SInt trackingNumber = 0;
  36. // Only accept non-drag move events when inside of the window.
  37. bool cursorInside = false;
  38. // Keeping track of control and command clicks.
  39. // 0 for regular left click.
  40. // 1 for control click converted to right mouse button.
  41. // 2 for command click converted to middle mouse button.
  42. int modifiedClick = 0;
  43. // Last modifiers to allow converting NSEventTypeFlagsChanged into up and down key press events.
  44. bool pressedControl = false;
  45. bool pressedCommand = false;
  46. bool pressedControlCommand = false;
  47. bool pressedShift = false;
  48. bool pressedAltOption = false;
  49. // TODO: Replace frame-rate throttling with correct synchronization.
  50. double lastDisplayTime = 0.0;
  51. // Double buffering to allow drawing to a canvas while displaying the previous one
  52. // The image which can be drawn to, sharing memory with the Cocoa image
  53. dsr::AlignedImageRgbaU8 canvas[bufferCount];
  54. // An Cocoa image wrapped around the canvas pixel data
  55. //NSImage *canvasNS[bufferCount] = {};
  56. int drawIndex = 0 % bufferCount;
  57. int showIndex = 1 % bufferCount;
  58. // Remembers the dimensions of the window from creation and resize events
  59. // This allow requesting the size of the window at any time
  60. int windowWidth = 0, windowHeight = 0;
  61. // Called before the application fetches events from the input queue
  62. // Closing the window, moving the mouse, pressing a key, et cetera
  63. void prefetchEvents() override;
  64. /*
  65. // Called to change the cursor visibility and returning true on success
  66. void applyCursorVisibility();
  67. bool setCursorVisibility(bool visible) override;
  68. // Place the cursor within the window
  69. void setCursorPosition(int x, int y) override;
  70. */
  71. private:
  72. // Helper methods specific to calling XLib
  73. void updateTitle();
  74. private:
  75. // Canvas methods
  76. dsr::AlignedImageRgbaU8 getCanvas() override { return this->canvas[this->drawIndex]; }
  77. void resizeCanvas(int width, int height) override;
  78. // Window methods
  79. void setTitle(const dsr::String &newTitle) override {
  80. this->title = newTitle;
  81. this->updateTitle();
  82. }
  83. int windowState = 0; // 0=none, 1=windowed, 2=fullscreen
  84. public:
  85. // Constructors
  86. CocoaWindow(const CocoaWindow&) = delete; // Non-copyable because of pointer aliasing.
  87. CocoaWindow(const dsr::String& title, int width, int height);
  88. int getWidth() const override { return this->windowWidth; };
  89. int getHeight() const override { return this->windowHeight; };
  90. // Destructor
  91. ~CocoaWindow();
  92. // Full-screen
  93. void setFullScreen(bool enabled) override {
  94. int newWindowState = enabled ? 2 : 1;
  95. if (newWindowState != this->windowState) {
  96. if (enabled) {
  97. this->window.styleMask &= ~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable);
  98. } else {
  99. this->window.styleMask |= NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable;
  100. }
  101. this->windowState = newWindowState;
  102. }
  103. };
  104. bool isFullScreen() override { return this->windowState == 2; }
  105. // Showing the content
  106. void showCanvas() override;
  107. // TODO: Implement clipboard access.
  108. //dsr::ReadableString loadFromClipboard(double timeoutInSeconds) override;
  109. //void saveToClipboard(const dsr::ReadableString &text, double timeoutInSeconds) override;
  110. };
  111. void CocoaWindow::updateTitle() {
  112. // Encode the title string as null terminated UFT-8.
  113. dsr::Buffer utf8_title = dsr::string_saveToMemory(this->title, dsr::CharacterEncoding::BOM_UTF8, dsr::LineEncoding::Lf, false, true);
  114. // Create a native string for MacOS.
  115. NSString *windowTitle = [NSString stringWithUTF8String:(char *)(dsr::buffer_dangerous_getUnsafeData(utf8_title))];
  116. // Set the window title.
  117. [window setTitle:windowTitle];
  118. }
  119. CocoaWindow::CocoaWindow(const dsr::String& title, int width, int height) {
  120. if (!applicationInitialized) {
  121. application = [NSApplication sharedApplication];
  122. [application setActivationPolicy:NSApplicationActivationPolicyRegular];
  123. [application setPresentationOptions:NSApplicationPresentationDefault];
  124. [application activateIgnoringOtherApps:YES];
  125. applicationInitialized = true;
  126. }
  127. bool fullScreen = false;
  128. if (width < 1 || height < 1) {
  129. fullScreen = true;
  130. width = 400;
  131. height = 300;
  132. }
  133. NSRect region = NSMakeRect(0, 0, width, height);
  134. // Create a window
  135. @autoreleasepool {
  136. this->window = [[NSWindow alloc]
  137. initWithContentRect:region
  138. styleMask:0
  139. backing: NSBackingStoreBuffered
  140. defer: NO];
  141. }
  142. this->setFullScreen(fullScreen);
  143. // Create a color space
  144. this->colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
  145. if (this->colorSpace == nullptr) {
  146. dsr::throwError(U"Could not create a Core Graphics color space!\n");
  147. }
  148. // Set the title
  149. this->setTitle(title);
  150. // Allocate a canvas
  151. this->resizeCanvas(width, height);
  152. // Show the window.
  153. [window center];
  154. [window makeKeyAndOrderFront:nil];
  155. [window makeFirstResponder:nil];
  156. }
  157. static dsr::DsrKey getDsrKey(uint16_t keyCode) {
  158. dsr::DsrKey result = dsr::DsrKey_Unhandled;
  159. if (keyCode == 53) {
  160. result = dsr::DsrKey_Escape;
  161. } else if (keyCode == 122) {
  162. result = dsr::DsrKey_F1;
  163. } else if (keyCode == 120) {
  164. result = dsr::DsrKey_F2;
  165. } else if (keyCode == 99) {
  166. result = dsr::DsrKey_F3;
  167. } else if (keyCode == 118) {
  168. result = dsr::DsrKey_F4;
  169. } else if (keyCode == 96) {
  170. result = dsr::DsrKey_F5;
  171. } else if (keyCode == 97) {
  172. result = dsr::DsrKey_F6;
  173. } else if (keyCode == 98) {
  174. result = dsr::DsrKey_F7;
  175. } else if (keyCode == 100) {
  176. result = dsr::DsrKey_F8;
  177. } else if (keyCode == 101) {
  178. result = dsr::DsrKey_F9;
  179. } else if (keyCode == 109) {
  180. result = dsr::DsrKey_F10;
  181. } else if (keyCode == 103) {
  182. result = dsr::DsrKey_F11;
  183. } else if (keyCode == 111) {
  184. result = dsr::DsrKey_F12;
  185. } else if (keyCode == 105) { // F13 replaces the pause key that does not even have a keycode on MacOS.
  186. result = dsr::DsrKey_Pause;
  187. } else if (keyCode == 49) {
  188. result = dsr::DsrKey_Space;
  189. } else if (keyCode == 48) {
  190. result = dsr::DsrKey_Tab;
  191. } else if (keyCode == 36) {
  192. result = dsr::DsrKey_Return;
  193. } else if (keyCode == 51) {
  194. result = dsr::DsrKey_BackSpace;
  195. } else if (keyCode == 117) {
  196. result = dsr::DsrKey_Delete;
  197. } else if (keyCode == 123) {
  198. result = dsr::DsrKey_LeftArrow;
  199. } else if (keyCode == 124) {
  200. result = dsr::DsrKey_RightArrow;
  201. } else if (keyCode == 126) {
  202. result = dsr::DsrKey_UpArrow;
  203. } else if (keyCode == 125) {
  204. result = dsr::DsrKey_DownArrow;
  205. } else if (keyCode == 29) {
  206. result = dsr::DsrKey_0;
  207. } else if (keyCode == 18) {
  208. result = dsr::DsrKey_1;
  209. } else if (keyCode == 19) {
  210. result = dsr::DsrKey_2;
  211. } else if (keyCode == 20) {
  212. result = dsr::DsrKey_3;
  213. } else if (keyCode == 21) {
  214. result = dsr::DsrKey_4;
  215. } else if (keyCode == 23) {
  216. result = dsr::DsrKey_5;
  217. } else if (keyCode == 22) {
  218. result = dsr::DsrKey_6;
  219. } else if (keyCode == 26) {
  220. result = dsr::DsrKey_7;
  221. } else if (keyCode == 28) {
  222. result = dsr::DsrKey_8;
  223. } else if (keyCode == 25) {
  224. result = dsr::DsrKey_9;
  225. } else if (keyCode == 0) {
  226. result = dsr::DsrKey_A;
  227. } else if (keyCode == 11) {
  228. result = dsr::DsrKey_B;
  229. } else if (keyCode == 8) {
  230. result = dsr::DsrKey_C;
  231. } else if (keyCode == 2) {
  232. result = dsr::DsrKey_D;
  233. } else if (keyCode == 14) {
  234. result = dsr::DsrKey_E;
  235. } else if (keyCode == 3) {
  236. result = dsr::DsrKey_F;
  237. } else if (keyCode == 5) {
  238. result = dsr::DsrKey_G;
  239. } else if (keyCode == 4) {
  240. result = dsr::DsrKey_H;
  241. } else if (keyCode == 34) {
  242. result = dsr::DsrKey_I;
  243. } else if (keyCode == 38) {
  244. result = dsr::DsrKey_J;
  245. } else if (keyCode == 40) {
  246. result = dsr::DsrKey_K;
  247. } else if (keyCode == 37) {
  248. result = dsr::DsrKey_L;
  249. } else if (keyCode == 46) {
  250. result = dsr::DsrKey_M;
  251. } else if (keyCode == 45) {
  252. result = dsr::DsrKey_N;
  253. } else if (keyCode == 31) {
  254. result = dsr::DsrKey_O;
  255. } else if (keyCode == 35) {
  256. result = dsr::DsrKey_P;
  257. } else if (keyCode == 12) {
  258. result = dsr::DsrKey_Q;
  259. } else if (keyCode == 15) {
  260. result = dsr::DsrKey_R;
  261. } else if (keyCode == 1) {
  262. result = dsr::DsrKey_S;
  263. } else if (keyCode == 17) {
  264. result = dsr::DsrKey_T;
  265. } else if (keyCode == 32) {
  266. result = dsr::DsrKey_U;
  267. } else if (keyCode == 9) {
  268. result = dsr::DsrKey_V;
  269. } else if (keyCode == 13) {
  270. result = dsr::DsrKey_W;
  271. } else if (keyCode == 7) {
  272. result = dsr::DsrKey_X;
  273. } else if (keyCode == 16) {
  274. result = dsr::DsrKey_Y;
  275. } else if (keyCode == 6) {
  276. result = dsr::DsrKey_Z;
  277. } else if (keyCode == 114 || keyCode == 106) { // Insert on PC keyboard or F16 on Mac Keyboard.
  278. result = dsr::DsrKey_Insert;
  279. } else if (keyCode == 115) {
  280. result = dsr::DsrKey_Home;
  281. } else if (keyCode == 119) {
  282. result = dsr::DsrKey_End;
  283. } else if (keyCode == 116) {
  284. result = dsr::DsrKey_PageUp;
  285. } else if (keyCode == 121) {
  286. result = dsr::DsrKey_PageDown;
  287. }
  288. return result;
  289. }
  290. void CocoaWindow::prefetchEvents() {
  291. @autoreleasepool {
  292. // TODO: Send resize events to the program and resize the canvas when the canvas size has changed.
  293. NSView *view = [window contentView];
  294. CGFloat canvasWidth = NSWidth(view.bounds);
  295. CGFloat canvasHeight = NSHeight(view.bounds);
  296. // Process events
  297. while (true) {
  298. NSEvent *event = [application nextEventMatchingMask:NSEventMaskAny untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
  299. if (event == nullptr) break;
  300. if ([event type] == NSEventTypeLeftMouseDown
  301. || [event type] == NSEventTypeLeftMouseDragged
  302. || [event type] == NSEventTypeLeftMouseUp
  303. || [event type] == NSEventTypeRightMouseDown
  304. || [event type] == NSEventTypeRightMouseDragged
  305. || [event type] == NSEventTypeRightMouseUp
  306. || [event type] == NSEventTypeOtherMouseDown
  307. || [event type] == NSEventTypeOtherMouseDragged
  308. || [event type] == NSEventTypeOtherMouseUp
  309. || [event type] == NSEventTypeMouseMoved
  310. || [event type] == NSEventTypeMouseEntered
  311. || [event type] == NSEventTypeMouseExited
  312. || [event type] == NSEventTypeScrollWheel) {
  313. NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
  314. // This nasty hack combines an old mouse event with a canvas size that may have changed since the mouse event was created.
  315. // TODO: Find a way to get the canvas height from when the mouse event was actually created, so that lagging while resizing a window can not place click events at the wrong coordiates.
  316. dsr::IVector2D mousePosition = dsr::IVector2D(int32_t(point.x), int32_t(canvasHeight - point.y));
  317. if ([event type] == NSEventTypeLeftMouseDown) {
  318. //dsr::printText(U"LeftMouseDown at ", mousePosition, U"\n");
  319. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  320. if (this->pressedControl) {
  321. // In case that control is released before the click is done, remember that the left click is a right click.
  322. this->modifiedClick = 1;
  323. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, mousePosition);
  324. } else if (this->pressedCommand) {
  325. // In case that control is released before the click is done, remember that the left click is a middle click.
  326. this->modifiedClick = 2;
  327. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, mousePosition);
  328. } else {
  329. // Assume that the user only has one left mouse button, so that the state can be reset on each new left click.
  330. this->modifiedClick = 0;
  331. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Left, mousePosition);
  332. }
  333. } else if ([event type] == NSEventTypeLeftMouseDragged) {
  334. //dsr::printText(U"LeftMouseDragged at ", mousePosition, U"\n");
  335. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  336. } else if ([event type] == NSEventTypeLeftMouseUp) {
  337. //dsr::printText(U"LeftMouseUp at ", mousePosition, U"\n");
  338. if (this->modifiedClick == 1) {
  339. // If the last left click was a control click, then the release should be treated as releasing the right mouse button.
  340. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, mousePosition);
  341. this->modifiedClick = 0;
  342. } else if (this->modifiedClick == 2) {
  343. // If the last left click was a command click, then the release should be treated as releasing the middle mouse button.
  344. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, mousePosition);
  345. this->modifiedClick = 0;
  346. } else {
  347. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Left, mousePosition);
  348. }
  349. } else if ([event type] == NSEventTypeRightMouseDown) {
  350. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  351. //dsr::printText(U"RightMouseDown at ", mousePosition, U"\n");
  352. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, mousePosition);
  353. } else if ([event type] == NSEventTypeRightMouseDragged) {
  354. //dsr::printText(U"RightMouseDragged at ", mousePosition, U"\n");
  355. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  356. } else if ([event type] == NSEventTypeRightMouseUp) {
  357. //dsr::printText(U"RightMouseUp at ", mousePosition, U"\n");
  358. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, mousePosition);
  359. } else if ([event type] == NSEventTypeOtherMouseDown) {
  360. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  361. //dsr::printText(U"OtherMouseDown at ", mousePosition, U"\n");
  362. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, mousePosition);
  363. } else if ([event type] == NSEventTypeOtherMouseDragged) {
  364. //dsr::printText(U"OtherMouseDragged at ", mousePosition, U"\n");
  365. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  366. } else if ([event type] == NSEventTypeOtherMouseUp) {
  367. //dsr::printText(U"OtherMouseUp at ", mousePosition, U"\n");
  368. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, mousePosition);
  369. } else if ([event type] == NSEventTypeMouseMoved) {
  370. //dsr::printText(U"cursorInside = ", this->cursorInside, U"\n");
  371. // When not dragging, only allow move events inside of the view, to be consistent with other operating systems.
  372. if (this->cursorInside && mousePosition.y >= 0) {
  373. //dsr::printText(U"MouseMoved at ", mousePosition, U"\n");
  374. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  375. }
  376. } else if ([event type] == NSEventTypeMouseEntered) {
  377. // TODO: This hack assumes that the first entering event goes to our view, but it would be more robust to get the tracking number directly from view.
  378. if (this->trackingNumber == 0) this->trackingNumber = event.trackingNumber;
  379. // Only accept enter events to our view.
  380. if (event.trackingNumber == this->trackingNumber) {
  381. this->cursorInside = true;
  382. //dsr::printText(U"MouseEntered at ", mousePosition, U" in ", event.trackingNumber, U"\n");
  383. }
  384. } else if ([event type] == NSEventTypeMouseExited) {
  385. // Only accept exit events from our view.
  386. if (event.trackingNumber == this->trackingNumber) {
  387. this->cursorInside = false;
  388. //dsr::printText(U"MouseExited at ", mousePosition, U" in ", event.trackingNumber, U"\n");
  389. }
  390. } else if ([event type] == NSEventTypeScrollWheel) {
  391. //dsr::printText(U"ScrollWheel at ", mousePosition, U"\n");
  392. // TODO: Which direction is considered up/down on MacOS when scroll wheels are inverted relative to PC?
  393. if (event.scrollingDeltaY > 0.0) {
  394. this->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollUp, mousePosition);
  395. }
  396. if (event.scrollingDeltaY < 0.0) {
  397. this->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollDown, mousePosition);
  398. }
  399. }
  400. [this->window makeKeyAndOrderFront:nil];
  401. } else if ([event type] == NSEventTypeKeyDown
  402. || [event type] == NSEventTypeKeyUp
  403. || [event type] == NSEventTypeFlagsChanged) {
  404. dsr::DsrKey code = getDsrKey(event.keyCode);
  405. if ([event type] == NSEventTypeKeyDown) {
  406. if (!(event.isARepeat)) {
  407. //dsr::printText(U"KeyDown: keyCode ", event.keyCode, U" -> ", getName(code), U"\n");
  408. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', code);
  409. }
  410. // Get typed characters
  411. if (event.characters != nullptr) {
  412. // Convert to a standard text format.
  413. const char *characters = [event.characters cStringUsingEncoding:NSUTF8StringEncoding];
  414. if (characters != nullptr) {
  415. // Convert to a DSR string.
  416. dsr::String dsrCharacters = dsr::string_dangerous_decodeFromData(characters, dsr::CharacterEncoding::BOM_UTF8);
  417. // Send one type event for each character.
  418. for (intptr_t c = 0; c < string_length(dsrCharacters); c++) {
  419. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyType, dsrCharacters[c], code);
  420. }
  421. }
  422. }
  423. //dsr::printText(U"KeyType: keyCode ", event.keyCode, U" -> ", getName(code), U"\n");
  424. } else if ([event type] == NSEventTypeKeyUp) {
  425. //dsr::printText(U"KeyUp: keyCode ", event.keyCode, U" -> ", getName(code), U"\n");
  426. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', code);
  427. } else if ([event type] == NSEventTypeFlagsChanged) {
  428. //dsr::printText(U"FlagsChanged\n");
  429. NSEventModifierFlags newModifierFlags = [event modifierFlags];
  430. bool newControl = (newModifierFlags & NSEventModifierFlagControl) != 0u;
  431. bool newCommand = (newModifierFlags & NSEventModifierFlagCommand) != 0u;
  432. bool newControlCommand = (newModifierFlags & (NSEventModifierFlagControl | NSEventModifierFlagCommand)) != 0u;
  433. bool newShift = (newModifierFlags & NSEventModifierFlagShift) != 0u;
  434. bool newAltOption = (newModifierFlags & NSEventModifierFlagOption) != 0u;
  435. if (newControlCommand && !pressedControlCommand) {
  436. //dsr::printText(U"KeyDown: Control\n");
  437. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Control);
  438. } else if (!newControlCommand && pressedControlCommand) {
  439. //dsr::printText(U"KeyUp: Control\n");
  440. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Control);
  441. }
  442. if (newShift && !pressedShift) {
  443. //dsr::printText(U"KeyDown: Shift\n");
  444. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Shift);
  445. } else if (!newShift && pressedShift) {
  446. //dsr::printText(U"KeyUp: Shift\n");
  447. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Shift);
  448. }
  449. if (newAltOption && !pressedAltOption) {
  450. //dsr::printText(U"KeyDown: Alt\n");
  451. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Alt);
  452. } else if (!newAltOption && pressedAltOption) {
  453. //dsr::printText(U"KeyUp: Alt\n");
  454. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Alt);
  455. }
  456. this->pressedControl = newControl;
  457. this->pressedCommand = newCommand;
  458. this->pressedControlCommand = newControlCommand;
  459. this->pressedShift = newShift;
  460. this->pressedAltOption = newAltOption;
  461. }
  462. }
  463. [application sendEvent:event];
  464. [application updateWindows];
  465. }
  466. // Handle changes to the window.
  467. if ([window isVisible]) {
  468. // The window is still visible, so check if it needs to resize the canvas.
  469. int32_t wholeCanvasWidth = int32_t(canvasWidth);
  470. int32_t wholeCanvasHeight = int32_t(canvasHeight);
  471. this->resizeCanvas(wholeCanvasWidth, wholeCanvasHeight);
  472. if (this->windowWidth != wholeCanvasWidth || this->windowHeight != wholeCanvasHeight) {
  473. this->windowWidth = wholeCanvasWidth;
  474. this->windowHeight = wholeCanvasHeight;
  475. // Make a request to resize the canvas
  476. this->receivedWindowResize(wholeCanvasWidth, wholeCanvasHeight);
  477. }
  478. } else {
  479. // The window is no longer visible, so send a close event to the application.
  480. this->receivedWindowCloseEvent();
  481. }
  482. }
  483. }
  484. static const dsr::PackOrderIndex MacOSPackOrder = dsr::PackOrderIndex::ABGR;
  485. void CocoaWindow::resizeCanvas(int width, int height) {
  486. for (int b = 0; b < bufferCount; b++) {
  487. if (image_exists(this->canvas[b])) {
  488. if (image_getWidth(this->canvas[b]) == width && image_getHeight(this->canvas[b]) == height) {
  489. // The canvas already has the requested resolution.
  490. return;
  491. } else {
  492. // Preserve the pre-existing image.
  493. dsr::AlignedImageRgbaU8 newImage = image_create_RgbaU8_native(width, height, MacOSPackOrder);
  494. dsr::draw_copy(newImage, this->canvas[b]);
  495. this->canvas[b] = newImage;
  496. }
  497. } else {
  498. // Allocate a new image.
  499. this->canvas[b] = image_create_RgbaU8_native(width, height, MacOSPackOrder);
  500. }
  501. }
  502. }
  503. CocoaWindow::~CocoaWindow() {
  504. if (this->colorSpace != nullptr) {
  505. CGColorSpaceRelease(this->colorSpace);
  506. }
  507. [this->window close];
  508. window = nullptr;
  509. }
  510. void CocoaWindow::showCanvas() {
  511. @autoreleasepool {
  512. this->drawIndex = (this->drawIndex + 1) % bufferCount;
  513. this->showIndex = (this->showIndex + 1) % bufferCount;
  514. this->prefetchEvents();
  515. int displayIndex = this->showIndex;
  516. NSView *view = [window contentView];
  517. if (view != nullptr) {
  518. int32_t width = dsr::image_getWidth(this->canvas[displayIndex]);
  519. int32_t height = dsr::image_getHeight(this->canvas[displayIndex]);
  520. int32_t stride = dsr::image_getStride(this->canvas[displayIndex]);
  521. uint8_t *pixelData = dsr::image_dangerous_getData(this->canvas[displayIndex]);
  522. CGDataProvider *provider = CGDataProviderCreateWithData(nullptr, pixelData, stride * height, nullptr);
  523. CGImage *image = CGImageCreate(width, height, 8, 32, stride, this->colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast, provider, nullptr, false, kCGRenderingIntentDefault);
  524. CGDataProviderRelease(provider);
  525. if (image == nullptr) {
  526. dsr::throwError(U"Could not create a Core Graphics image!\n");
  527. return;
  528. }
  529. view.wantsLayer = YES;
  530. view.layer.contents = (__bridge id)image;
  531. CGImageRelease(image);
  532. // TODO: Replace frame-rate throttling with correct synchronization.
  533. static const double minimumFrameTime = 1.0 / 120.0;
  534. double newTime = dsr::time_getSeconds();
  535. if (newTime < this->lastDisplayTime + minimumFrameTime) {
  536. dsr::time_sleepSeconds(this->lastDisplayTime + minimumFrameTime - newTime);
  537. }
  538. this->lastDisplayTime = newTime;
  539. }
  540. }
  541. }
  542. dsr::Handle<dsr::BackendWindow> createBackendWindow(const dsr::String& title, int width, int height) {
  543. return dsr::handle_create<CocoaWindow>(title, width, height);
  544. }