CocoaWindow.mm 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. if (this->windowState == 2) {
  137. NSRect viewBounds = [this->view bounds];
  138. NSRect viewInWindow = [this->view convertRect:viewBounds toView:nil];
  139. CGWarpMouseCursorPosition(CGPointMake(viewInWindow.origin.x + x, viewInWindow.origin.y + y));
  140. // Prevent stalling after the move.
  141. CGAssociateMouseAndMouseCursorPosition(true);
  142. // TODO: How can the mouse move event be sent in the correct order in case of already having move events waiting?
  143. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, dsr::IVector2D(x, y));
  144. return true;
  145. } else {
  146. // Setting the cursor position is not reliable in windowed mode, because the fetching the window location often returns outdated coordinates.
  147. return false;
  148. }
  149. }
  150. void CocoaWindow::setFullScreen(bool enabled) {
  151. int newWindowState = enabled ? 2 : 1;
  152. if (newWindowState != this->windowState) {
  153. if (enabled) {
  154. // Entering full screen from the start or for an existing window.
  155. [this->view enterFullScreenMode:[NSScreen mainScreen] withOptions:nil];
  156. this->windowState = 2;
  157. } else {
  158. if (this->windowState == 2) {
  159. // Leaving full screen instead of initializing a new window.
  160. [this->view exitFullScreenModeWithOptions:nil];
  161. }
  162. this->windowState = 1;
  163. }
  164. }
  165. }
  166. void CocoaWindow::updateTitle() {
  167. // Get the title and convert it into the native string type.
  168. NSString *windowTitle = dsrToNsString(this->title);
  169. // Set the window title.
  170. [window setTitle:windowTitle];
  171. }
  172. CocoaWindow::CocoaWindow(const dsr::String& title, int width, int height) {
  173. if (!applicationInitialized) {
  174. application = [NSApplication sharedApplication];
  175. [application setActivationPolicy:NSApplicationActivationPolicyRegular];
  176. [application setPresentationOptions:NSApplicationPresentationDefault];
  177. [application activateIgnoringOtherApps:YES];
  178. applicationInitialized = true;
  179. }
  180. bool fullScreen = false;
  181. if (width < 1 || height < 1) {
  182. fullScreen = true;
  183. width = 400;
  184. height = 300;
  185. }
  186. // Create a window
  187. @autoreleasepool {
  188. this->window = [[NSWindow alloc]
  189. initWithContentRect:NSMakeRect(0, 0, width, height)
  190. styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable
  191. backing: NSBackingStoreBuffered
  192. defer: NO];
  193. }
  194. NSButton* zoomButton = [window standardWindowButton:NSWindowZoomButton];
  195. [zoomButton setEnabled:NO];
  196. // Get the view
  197. this->view = [window contentView];
  198. this->setFullScreen(fullScreen);
  199. // Create a color space
  200. this->colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
  201. if (this->colorSpace == nullptr) {
  202. dsr::throwError(U"Could not create a Core Graphics color space!\n");
  203. }
  204. // Set the title
  205. this->setTitle(title);
  206. // Allocate a canvas
  207. this->resizeCanvas(width, height);
  208. // Show the window.
  209. [window center];
  210. [window makeKeyAndOrderFront:nil];
  211. [window makeFirstResponder:nil];
  212. }
  213. static dsr::DsrKey getDsrKey(uint16_t keyCode) {
  214. dsr::DsrKey result = dsr::DsrKey_Unhandled;
  215. if (keyCode == 53) {
  216. result = dsr::DsrKey_Escape;
  217. } else if (keyCode == 122) {
  218. result = dsr::DsrKey_F1;
  219. } else if (keyCode == 120) {
  220. result = dsr::DsrKey_F2;
  221. } else if (keyCode == 99) {
  222. result = dsr::DsrKey_F3;
  223. } else if (keyCode == 118) {
  224. result = dsr::DsrKey_F4;
  225. } else if (keyCode == 96) {
  226. result = dsr::DsrKey_F5;
  227. } else if (keyCode == 97) {
  228. result = dsr::DsrKey_F6;
  229. } else if (keyCode == 98) {
  230. result = dsr::DsrKey_F7;
  231. } else if (keyCode == 100) {
  232. result = dsr::DsrKey_F8;
  233. } else if (keyCode == 101) {
  234. result = dsr::DsrKey_F9;
  235. } else if (keyCode == 109) {
  236. result = dsr::DsrKey_F10;
  237. } else if (keyCode == 103) {
  238. result = dsr::DsrKey_F11;
  239. } else if (keyCode == 111) {
  240. result = dsr::DsrKey_F12;
  241. } else if (keyCode == 105) { // F13 replaces the pause key that does not even have a keycode on MacOS.
  242. result = dsr::DsrKey_Pause;
  243. } else if (keyCode == 49) {
  244. result = dsr::DsrKey_Space;
  245. } else if (keyCode == 48) {
  246. result = dsr::DsrKey_Tab;
  247. } else if (keyCode == 36) {
  248. result = dsr::DsrKey_Return;
  249. } else if (keyCode == 51) {
  250. result = dsr::DsrKey_BackSpace;
  251. } else if (keyCode == 117) {
  252. result = dsr::DsrKey_Delete;
  253. } else if (keyCode == 123) {
  254. result = dsr::DsrKey_LeftArrow;
  255. } else if (keyCode == 124) {
  256. result = dsr::DsrKey_RightArrow;
  257. } else if (keyCode == 126) {
  258. result = dsr::DsrKey_UpArrow;
  259. } else if (keyCode == 125) {
  260. result = dsr::DsrKey_DownArrow;
  261. } else if (keyCode == 29) {
  262. result = dsr::DsrKey_0;
  263. } else if (keyCode == 18) {
  264. result = dsr::DsrKey_1;
  265. } else if (keyCode == 19) {
  266. result = dsr::DsrKey_2;
  267. } else if (keyCode == 20) {
  268. result = dsr::DsrKey_3;
  269. } else if (keyCode == 21) {
  270. result = dsr::DsrKey_4;
  271. } else if (keyCode == 23) {
  272. result = dsr::DsrKey_5;
  273. } else if (keyCode == 22) {
  274. result = dsr::DsrKey_6;
  275. } else if (keyCode == 26) {
  276. result = dsr::DsrKey_7;
  277. } else if (keyCode == 28) {
  278. result = dsr::DsrKey_8;
  279. } else if (keyCode == 25) {
  280. result = dsr::DsrKey_9;
  281. } else if (keyCode == 0) {
  282. result = dsr::DsrKey_A;
  283. } else if (keyCode == 11) {
  284. result = dsr::DsrKey_B;
  285. } else if (keyCode == 8) {
  286. result = dsr::DsrKey_C;
  287. } else if (keyCode == 2) {
  288. result = dsr::DsrKey_D;
  289. } else if (keyCode == 14) {
  290. result = dsr::DsrKey_E;
  291. } else if (keyCode == 3) {
  292. result = dsr::DsrKey_F;
  293. } else if (keyCode == 5) {
  294. result = dsr::DsrKey_G;
  295. } else if (keyCode == 4) {
  296. result = dsr::DsrKey_H;
  297. } else if (keyCode == 34) {
  298. result = dsr::DsrKey_I;
  299. } else if (keyCode == 38) {
  300. result = dsr::DsrKey_J;
  301. } else if (keyCode == 40) {
  302. result = dsr::DsrKey_K;
  303. } else if (keyCode == 37) {
  304. result = dsr::DsrKey_L;
  305. } else if (keyCode == 46) {
  306. result = dsr::DsrKey_M;
  307. } else if (keyCode == 45) {
  308. result = dsr::DsrKey_N;
  309. } else if (keyCode == 31) {
  310. result = dsr::DsrKey_O;
  311. } else if (keyCode == 35) {
  312. result = dsr::DsrKey_P;
  313. } else if (keyCode == 12) {
  314. result = dsr::DsrKey_Q;
  315. } else if (keyCode == 15) {
  316. result = dsr::DsrKey_R;
  317. } else if (keyCode == 1) {
  318. result = dsr::DsrKey_S;
  319. } else if (keyCode == 17) {
  320. result = dsr::DsrKey_T;
  321. } else if (keyCode == 32) {
  322. result = dsr::DsrKey_U;
  323. } else if (keyCode == 9) {
  324. result = dsr::DsrKey_V;
  325. } else if (keyCode == 13) {
  326. result = dsr::DsrKey_W;
  327. } else if (keyCode == 7) {
  328. result = dsr::DsrKey_X;
  329. } else if (keyCode == 16) {
  330. result = dsr::DsrKey_Y;
  331. } else if (keyCode == 6) {
  332. result = dsr::DsrKey_Z;
  333. } else if (keyCode == 114 || keyCode == 106) { // Insert on PC keyboard or F16 on Mac Keyboard.
  334. result = dsr::DsrKey_Insert;
  335. } else if (keyCode == 115) {
  336. result = dsr::DsrKey_Home;
  337. } else if (keyCode == 119) {
  338. result = dsr::DsrKey_End;
  339. } else if (keyCode == 116) {
  340. result = dsr::DsrKey_PageUp;
  341. } else if (keyCode == 121) {
  342. result = dsr::DsrKey_PageDown;
  343. }
  344. return result;
  345. }
  346. void CocoaWindow::prefetchEvents() {
  347. @autoreleasepool {
  348. CGFloat canvasWidth = NSWidth(this->view.bounds);
  349. CGFloat canvasHeight = NSHeight(this->view.bounds);
  350. // Process events
  351. while (true) {
  352. NSEvent *event = [application nextEventMatchingMask:NSEventMaskAny untilDate:nil inMode:NSDefaultRunLoopMode dequeue:YES];
  353. if (event == nullptr) break;
  354. if ([event type] == NSEventTypeLeftMouseDown
  355. || [event type] == NSEventTypeLeftMouseDragged
  356. || [event type] == NSEventTypeLeftMouseUp
  357. || [event type] == NSEventTypeRightMouseDown
  358. || [event type] == NSEventTypeRightMouseDragged
  359. || [event type] == NSEventTypeRightMouseUp
  360. || [event type] == NSEventTypeOtherMouseDown
  361. || [event type] == NSEventTypeOtherMouseDragged
  362. || [event type] == NSEventTypeOtherMouseUp
  363. || [event type] == NSEventTypeMouseMoved
  364. || [event type] == NSEventTypeMouseEntered
  365. || [event type] == NSEventTypeMouseExited
  366. || [event type] == NSEventTypeScrollWheel) {
  367. NSPoint point = [this->view convertPoint:[event locationInWindow] fromView:nil];
  368. // This nasty hack combines an old mouse event with a canvas size that may have changed since the mouse event was created.
  369. // 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.
  370. dsr::IVector2D mousePosition = dsr::IVector2D(int32_t(point.x), int32_t(canvasHeight - point.y));
  371. if ([event type] == NSEventTypeLeftMouseDown) {
  372. //dsr::printText(U"LeftMouseDown at ", mousePosition, U"\n");
  373. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  374. if (this->pressedControl) {
  375. // In case that control is released before the click is done, remember that the left click is a right click.
  376. this->modifiedClick = 1;
  377. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, mousePosition);
  378. } else if (this->pressedCommand) {
  379. // In case that control is released before the click is done, remember that the left click is a middle click.
  380. this->modifiedClick = 2;
  381. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, mousePosition);
  382. } else {
  383. // Assume that the user only has one left mouse button, so that the state can be reset on each new left click.
  384. this->modifiedClick = 0;
  385. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Left, mousePosition);
  386. }
  387. } else if ([event type] == NSEventTypeLeftMouseDragged) {
  388. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  389. } else if ([event type] == NSEventTypeLeftMouseUp) {
  390. if (this->modifiedClick == 1) {
  391. // If the last left click was a control click, then the release should be treated as releasing the right mouse button.
  392. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, mousePosition);
  393. this->modifiedClick = 0;
  394. } else if (this->modifiedClick == 2) {
  395. // If the last left click was a command click, then the release should be treated as releasing the middle mouse button.
  396. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, mousePosition);
  397. this->modifiedClick = 0;
  398. } else {
  399. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Left, mousePosition);
  400. }
  401. } else if ([event type] == NSEventTypeRightMouseDown) {
  402. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  403. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, mousePosition);
  404. } else if ([event type] == NSEventTypeRightMouseDragged) {
  405. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  406. } else if ([event type] == NSEventTypeRightMouseUp) {
  407. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, mousePosition);
  408. } else if ([event type] == NSEventTypeOtherMouseDown) {
  409. this->cursorInside = true; // In case that enter events are missing, any proof of being inside of the window should be used.
  410. this->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, mousePosition);
  411. } else if ([event type] == NSEventTypeOtherMouseDragged) {
  412. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  413. } else if ([event type] == NSEventTypeOtherMouseUp) {
  414. this->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, mousePosition);
  415. } else if ([event type] == NSEventTypeMouseMoved) {
  416. // When not dragging, only allow move events inside of the view, to be consistent with other operating systems.
  417. if ((this->cursorInside || this->windowState == 2) && mousePosition.y >= 0) {
  418. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, mousePosition);
  419. }
  420. } else if ([event type] == NSEventTypeMouseEntered) {
  421. // 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.
  422. if (this->trackingNumber == 0) this->trackingNumber = event.trackingNumber;
  423. // Only accept enter events to our view.
  424. if (event.trackingNumber == this->trackingNumber) {
  425. this->cursorInside = true;
  426. }
  427. } else if ([event type] == NSEventTypeMouseExited) {
  428. // Only accept exit events from our view.
  429. if (event.trackingNumber == this->trackingNumber) {
  430. this->cursorInside = false;
  431. }
  432. } else if ([event type] == NSEventTypeScrollWheel) {
  433. if (event.scrollingDeltaY > 0.0) {
  434. this->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollUp, mousePosition);
  435. }
  436. if (event.scrollingDeltaY < 0.0) {
  437. this->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollDown, mousePosition);
  438. }
  439. }
  440. [application sendEvent:event];
  441. } else if ([event type] == NSEventTypeKeyDown
  442. || [event type] == NSEventTypeKeyUp
  443. || [event type] == NSEventTypeFlagsChanged) {
  444. dsr::DsrKey code = getDsrKey(event.keyCode);
  445. if ([event type] == NSEventTypeKeyDown) {
  446. if (!(event.isARepeat)) {
  447. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', code);
  448. }
  449. // Get typed characters
  450. if (event.characters != nullptr) {
  451. // Convert to a standard text format.
  452. const char *characters = [event.characters cStringUsingEncoding:NSUTF8StringEncoding];
  453. if (characters != nullptr) {
  454. // Convert to a DSR string.
  455. dsr::String dsrCharacters = dsr::string_dangerous_decodeFromData(characters, dsr::CharacterEncoding::BOM_UTF8);
  456. // Send one type event for each character.
  457. for (intptr_t c = 0; c < string_length(dsrCharacters); c++) {
  458. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyType, dsrCharacters[c], code);
  459. }
  460. }
  461. }
  462. } else if ([event type] == NSEventTypeKeyUp) {
  463. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', code);
  464. } else if ([event type] == NSEventTypeFlagsChanged) {
  465. NSEventModifierFlags newModifierFlags = [event modifierFlags];
  466. bool newControl = (newModifierFlags & NSEventModifierFlagControl) != 0u;
  467. bool newCommand = (newModifierFlags & NSEventModifierFlagCommand) != 0u;
  468. bool newControlCommand = (newModifierFlags & (NSEventModifierFlagControl | NSEventModifierFlagCommand)) != 0u;
  469. bool newShift = (newModifierFlags & NSEventModifierFlagShift) != 0u;
  470. bool newAltOption = (newModifierFlags & NSEventModifierFlagOption) != 0u;
  471. if (newControlCommand && !pressedControlCommand) {
  472. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Control);
  473. } else if (!newControlCommand && pressedControlCommand) {
  474. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Control);
  475. }
  476. if (newShift && !pressedShift) {
  477. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Shift);
  478. } else if (!newShift && pressedShift) {
  479. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Shift);
  480. }
  481. if (newAltOption && !pressedAltOption) {
  482. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, U'\0', dsr::DsrKey_Alt);
  483. } else if (!newAltOption && pressedAltOption) {
  484. this->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, U'\0', dsr::DsrKey_Alt);
  485. }
  486. this->pressedControl = newControl;
  487. this->pressedCommand = newCommand;
  488. this->pressedControlCommand = newControlCommand;
  489. this->pressedShift = newShift;
  490. this->pressedAltOption = newAltOption;
  491. }
  492. // TODO: Make sure that this does not break anything important.
  493. // Supressing beeps by not forwarding key events to the system.
  494. } else {
  495. [application sendEvent:event];
  496. }
  497. [application updateWindows];
  498. }
  499. // Handle changes to the window.
  500. if (![window isMiniaturized]) {
  501. if ([window isVisible]) {
  502. // The window is still visible, so check if it needs to resize the canvas.
  503. int32_t wholeCanvasWidth = int32_t(canvasWidth);
  504. int32_t wholeCanvasHeight = int32_t(canvasHeight);
  505. if (this->windowWidth != wholeCanvasWidth || this->windowHeight != wholeCanvasHeight) {
  506. this->resizeCanvas(wholeCanvasWidth, wholeCanvasHeight);
  507. this->windowWidth = wholeCanvasWidth;
  508. this->windowHeight = wholeCanvasHeight;
  509. // Make a request to resize the canvas
  510. this->receivedWindowResize(wholeCanvasWidth, wholeCanvasHeight);
  511. }
  512. } else {
  513. // The window is no longer visible, so send a close event to the application.
  514. this->receivedWindowCloseEvent();
  515. }
  516. }
  517. }
  518. }
  519. static const dsr::PackOrderIndex MacOSPackOrder = dsr::PackOrderIndex::ABGR;
  520. void CocoaWindow::resizeCanvas(int width, int height) {
  521. for (int b = 0; b < bufferCount; b++) {
  522. if (image_exists(this->canvas[b])) {
  523. if (image_getWidth(this->canvas[b]) == width && image_getHeight(this->canvas[b]) == height) {
  524. // The canvas already has the requested resolution.
  525. return;
  526. } else {
  527. // Preserve the pre-existing image.
  528. dsr::AlignedImageRgbaU8 newImage = image_create_RgbaU8_native(width, height, MacOSPackOrder);
  529. dsr::draw_copy(newImage, this->canvas[b]);
  530. this->canvas[b] = newImage;
  531. }
  532. } else {
  533. // Allocate a new image.
  534. this->canvas[b] = image_create_RgbaU8_native(width, height, MacOSPackOrder);
  535. }
  536. }
  537. }
  538. CocoaWindow::~CocoaWindow() {
  539. if (this->colorSpace != nullptr) {
  540. CGColorSpaceRelease(this->colorSpace);
  541. }
  542. [this->window close];
  543. window = nullptr;
  544. }
  545. void CocoaWindow::showCanvas() {
  546. if (![window isMiniaturized]) {
  547. @autoreleasepool {
  548. this->drawIndex = (this->drawIndex + 1) % bufferCount;
  549. this->showIndex = (this->showIndex + 1) % bufferCount;
  550. this->prefetchEvents();
  551. int displayIndex = this->showIndex;
  552. if (this->view != nullptr) {
  553. // Get image dimensions.
  554. int32_t width = dsr::image_getWidth(this->canvas[displayIndex]);
  555. int32_t height = dsr::image_getHeight(this->canvas[displayIndex]);
  556. int32_t stride = dsr::image_getStride(this->canvas[displayIndex]);
  557. // Make a deep clone of the finished image before it gets overwritten by another frame.
  558. this->delayedCanvas = dsr::buffer_clone(this->canvas[displayIndex].impl_buffer);
  559. uint8_t *pixelData = dsr::buffer_dangerous_getUnsafeData(this->delayedCanvas);
  560. CGDataProvider *provider = CGDataProviderCreateWithData(nullptr, pixelData, stride * height, nullptr);
  561. CGImage *image = CGImageCreate(width, height, 8, 32, stride, this->colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast, provider, nullptr, false, kCGRenderingIntentDefault);
  562. CGDataProviderRelease(provider);
  563. if (image == nullptr) {
  564. dsr::throwError(U"Could not create a Core Graphics image!\n");
  565. return;
  566. }
  567. this->view.wantsLayer = YES;
  568. this->view.layer.contents = (__bridge id)image;
  569. CGImageRelease(image);
  570. }
  571. }
  572. }
  573. }
  574. dsr::Handle<dsr::BackendWindow> createBackendWindow(const dsr::String& title, int width, int height) {
  575. return dsr::handle_create<CocoaWindow>(title, width, height);
  576. }