CocoaWindow.mm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. NSView *view = [window contentView];
  293. CGFloat canvasWidth = NSWidth(view.bounds);
  294. CGFloat canvasHeight = NSHeight(view.bounds);
  295. // Process events
  296. while (true) {
  297. NSEvent *event = [application nextEventMatchingMask:NSEventMaskAny untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
  298. if (event == nullptr) break;
  299. if ([event type] == NSEventTypeLeftMouseDown
  300. || [event type] == NSEventTypeLeftMouseDragged
  301. || [event type] == NSEventTypeLeftMouseUp
  302. || [event type] == NSEventTypeRightMouseDown
  303. || [event type] == NSEventTypeRightMouseDragged
  304. || [event type] == NSEventTypeRightMouseUp
  305. || [event type] == NSEventTypeOtherMouseDown
  306. || [event type] == NSEventTypeOtherMouseDragged
  307. || [event type] == NSEventTypeOtherMouseUp
  308. || [event type] == NSEventTypeMouseMoved
  309. || [event type] == NSEventTypeMouseEntered
  310. || [event type] == NSEventTypeMouseExited
  311. || [event type] == NSEventTypeScrollWheel) {
  312. NSPoint point = [view convertPoint:[event locationInWindow] fromView:nil];
  313. // This nasty hack combines an old mouse event with a canvas size that may have changed since the mouse event was created.
  314. // 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.
  315. dsr::IVector2D mousePosition = dsr::IVector2D(int32_t(point.x), int32_t(canvasHeight - point.y));
  316. if ([event type] == NSEventTypeLeftMouseDown) {
  317. //dsr::printText(U"LeftMouseDown at ", mousePosition, U"\n");
  318. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  319. if (this->pressedControl) {
  320. // In case that control is released before the click is done, remember that the left click is a right click.
  321. this->modifiedClick = 1;
  322. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, mousePosition);
  323. } else if (this->pressedCommand) {
  324. // In case that control is released before the click is done, remember that the left click is a middle click.
  325. this->modifiedClick = 2;
  326. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, mousePosition);
  327. } else {
  328. // Assume that the user only has one left mouse button, so that the state can be reset on each new left click.
  329. this->modifiedClick = 0;
  330. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Left, mousePosition);
  331. }
  332. } else if ([event type] == NSEventTypeLeftMouseDragged) {
  333. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  334. } else if ([event type] == NSEventTypeLeftMouseUp) {
  335. if (this->modifiedClick == 1) {
  336. // If the last left click was a control click, then the release should be treated as releasing the right mouse button.
  337. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, mousePosition);
  338. this->modifiedClick = 0;
  339. } else if (this->modifiedClick == 2) {
  340. // If the last left click was a command click, then the release should be treated as releasing the middle mouse button.
  341. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, mousePosition);
  342. this->modifiedClick = 0;
  343. } else {
  344. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Left, mousePosition);
  345. }
  346. } else if ([event type] == NSEventTypeRightMouseDown) {
  347. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  348. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, mousePosition);
  349. } else if ([event type] == NSEventTypeRightMouseDragged) {
  350. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  351. } else if ([event type] == NSEventTypeRightMouseUp) {
  352. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, mousePosition);
  353. } else if ([event type] == NSEventTypeOtherMouseDown) {
  354. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  355. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, mousePosition);
  356. } else if ([event type] == NSEventTypeOtherMouseDragged) {
  357. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  358. } else if ([event type] == NSEventTypeOtherMouseUp) {
  359. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, mousePosition);
  360. } else if ([event type] == NSEventTypeMouseMoved) {
  361. // When not dragging, only allow move events inside of the view, to be consistent with other operating systems.
  362. if (this->cursorInside && mousePosition.y >= 0) {
  363. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  364. }
  365. } else if ([event type] == NSEventTypeMouseEntered) {
  366. // 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.
  367. if (this->trackingNumber == 0) this->trackingNumber = event.trackingNumber;
  368. // Only accept enter events to our view.
  369. if (event.trackingNumber == this->trackingNumber) {
  370. this->cursorInside = true;
  371. }
  372. } else if ([event type] == NSEventTypeMouseExited) {
  373. // Only accept exit events from our view.
  374. if (event.trackingNumber == this->trackingNumber) {
  375. this->cursorInside = false;
  376. }
  377. } else if ([event type] == NSEventTypeScrollWheel) {
  378. if (event.scrollingDeltaY > 0.0) {
  379. this->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollUp, mousePosition);
  380. }
  381. if (event.scrollingDeltaY < 0.0) {
  382. this->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollDown, mousePosition);
  383. }
  384. }
  385. [this->window makeKeyAndOrderFront:nil];
  386. } else if ([event type] == NSEventTypeKeyDown
  387. || [event type] == NSEventTypeKeyUp
  388. || [event type] == NSEventTypeFlagsChanged) {
  389. dsr::DsrKey code = getDsrKey(event.keyCode);
  390. if ([event type] == NSEventTypeKeyDown) {
  391. if (!(event.isARepeat)) {
  392. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', code);
  393. }
  394. // Get typed characters
  395. if (event.characters != nullptr) {
  396. // Convert to a standard text format.
  397. const char *characters = [event.characters cStringUsingEncoding:NSUTF8StringEncoding];
  398. if (characters != nullptr) {
  399. // Convert to a DSR string.
  400. dsr::String dsrCharacters = dsr::string_dangerous_decodeFromData(characters, dsr::CharacterEncoding::BOM_UTF8);
  401. // Send one type event for each character.
  402. for (intptr_t c = 0; c < string_length(dsrCharacters); c++) {
  403. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyType, dsrCharacters[c], code);
  404. }
  405. }
  406. }
  407. } else if ([event type] == NSEventTypeKeyUp) {
  408. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', code);
  409. } else if ([event type] == NSEventTypeFlagsChanged) {
  410. NSEventModifierFlags newModifierFlags = [event modifierFlags];
  411. bool newControl = (newModifierFlags & NSEventModifierFlagControl) != 0u;
  412. bool newCommand = (newModifierFlags & NSEventModifierFlagCommand) != 0u;
  413. bool newControlCommand = (newModifierFlags & (NSEventModifierFlagControl | NSEventModifierFlagCommand)) != 0u;
  414. bool newShift = (newModifierFlags & NSEventModifierFlagShift) != 0u;
  415. bool newAltOption = (newModifierFlags & NSEventModifierFlagOption) != 0u;
  416. if (newControlCommand && !pressedControlCommand) {
  417. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Control);
  418. } else if (!newControlCommand && pressedControlCommand) {
  419. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Control);
  420. }
  421. if (newShift && !pressedShift) {
  422. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Shift);
  423. } else if (!newShift && pressedShift) {
  424. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Shift);
  425. }
  426. if (newAltOption && !pressedAltOption) {
  427. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Alt);
  428. } else if (!newAltOption && pressedAltOption) {
  429. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Alt);
  430. }
  431. this->pressedControl = newControl;
  432. this->pressedCommand = newCommand;
  433. this->pressedControlCommand = newControlCommand;
  434. this->pressedShift = newShift;
  435. this->pressedAltOption = newAltOption;
  436. }
  437. }
  438. [application sendEvent:event];
  439. [application updateWindows];
  440. }
  441. // Handle changes to the window.
  442. if ([window isVisible]) {
  443. // The window is still visible, so check if it needs to resize the canvas.
  444. int32_t wholeCanvasWidth = int32_t(canvasWidth);
  445. int32_t wholeCanvasHeight = int32_t(canvasHeight);
  446. this->resizeCanvas(wholeCanvasWidth, wholeCanvasHeight);
  447. if (this->windowWidth != wholeCanvasWidth || this->windowHeight != wholeCanvasHeight) {
  448. this->windowWidth = wholeCanvasWidth;
  449. this->windowHeight = wholeCanvasHeight;
  450. // Make a request to resize the canvas
  451. this->receivedWindowResize(wholeCanvasWidth, wholeCanvasHeight);
  452. }
  453. } else {
  454. // The window is no longer visible, so send a close event to the application.
  455. this->receivedWindowCloseEvent();
  456. }
  457. }
  458. }
  459. static const dsr::PackOrderIndex MacOSPackOrder = dsr::PackOrderIndex::ABGR;
  460. void CocoaWindow::resizeCanvas(int width, int height) {
  461. for (int b = 0; b < bufferCount; b++) {
  462. if (image_exists(this->canvas[b])) {
  463. if (image_getWidth(this->canvas[b]) == width && image_getHeight(this->canvas[b]) == height) {
  464. // The canvas already has the requested resolution.
  465. return;
  466. } else {
  467. // Preserve the pre-existing image.
  468. dsr::AlignedImageRgbaU8 newImage = image_create_RgbaU8_native(width, height, MacOSPackOrder);
  469. dsr::draw_copy(newImage, this->canvas[b]);
  470. this->canvas[b] = newImage;
  471. }
  472. } else {
  473. // Allocate a new image.
  474. this->canvas[b] = image_create_RgbaU8_native(width, height, MacOSPackOrder);
  475. }
  476. }
  477. }
  478. CocoaWindow::~CocoaWindow() {
  479. if (this->colorSpace != nullptr) {
  480. CGColorSpaceRelease(this->colorSpace);
  481. }
  482. [this->window close];
  483. window = nullptr;
  484. }
  485. void CocoaWindow::showCanvas() {
  486. @autoreleasepool {
  487. this->drawIndex = (this->drawIndex + 1) % bufferCount;
  488. this->showIndex = (this->showIndex + 1) % bufferCount;
  489. this->prefetchEvents();
  490. int displayIndex = this->showIndex;
  491. NSView *view = [window contentView];
  492. if (view != nullptr) {
  493. int32_t width = dsr::image_getWidth(this->canvas[displayIndex]);
  494. int32_t height = dsr::image_getHeight(this->canvas[displayIndex]);
  495. int32_t stride = dsr::image_getStride(this->canvas[displayIndex]);
  496. uint8_t *pixelData = dsr::image_dangerous_getData(this->canvas[displayIndex]);
  497. CGDataProvider *provider = CGDataProviderCreateWithData(nullptr, pixelData, stride * height, nullptr);
  498. CGImage *image = CGImageCreate(width, height, 8, 32, stride, this->colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast, provider, nullptr, false, kCGRenderingIntentDefault);
  499. CGDataProviderRelease(provider);
  500. if (image == nullptr) {
  501. dsr::throwError(U"Could not create a Core Graphics image!\n");
  502. return;
  503. }
  504. view.wantsLayer = YES;
  505. view.layer.contents = (__bridge id)image;
  506. CGImageRelease(image);
  507. // TODO: Replace frame-rate throttling with correct synchronization.
  508. static const double minimumFrameTime = 1.0 / 120.0;
  509. double newTime = dsr::time_getSeconds();
  510. if (newTime < this->lastDisplayTime + minimumFrameTime) {
  511. dsr::time_sleepSeconds(this->lastDisplayTime + minimumFrameTime - newTime);
  512. }
  513. this->lastDisplayTime = newTime;
  514. }
  515. }
  516. }
  517. dsr::Handle<dsr::BackendWindow> createBackendWindow(const dsr::String& title, int width, int height) {
  518. return dsr::handle_create<CocoaWindow>(title, width, height);
  519. }