CocoaWindow.mm 26 KB

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