Win32Window.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. 
  2. /*
  3. Link to these dependencies for MS Windows:
  4. gdi32
  5. user32
  6. kernel32
  7. comctl32
  8. */
  9. #include <tchar.h>
  10. #include <windows.h>
  11. #include <windowsx.h>
  12. #include "../DFPSR/api/imageAPI.h"
  13. #include "../DFPSR/api/drawAPI.h"
  14. #include "../DFPSR/api/bufferAPI.h"
  15. #include "../DFPSR/api/timeAPI.h"
  16. #include "../DFPSR/implementation/gui/BackendWindow.h"
  17. #include "../DFPSR/settings.h"
  18. #ifndef DISABLE_MULTI_THREADING
  19. #include <mutex>
  20. #include <future>
  21. static std::mutex windowLock;
  22. inline void lockWindow() { windowLock.lock(); }
  23. inline void unlockWindow() { windowLock.unlock(); }
  24. #else
  25. inline void lockWindow() {}
  26. inline void unlockWindow() {}
  27. #endif
  28. static const int bufferCount = 2;
  29. class Win32Window : public dsr::BackendWindow {
  30. public:
  31. // The native windows handle
  32. HWND hwnd;
  33. // The cursors
  34. HCURSOR noCursor, defaultCursor;
  35. // Because scroll events don't give a cursor location, remember it from other mouse events.
  36. dsr::IVector2D lastMousePos;
  37. // Keep track of when the cursor is inside of the window,
  38. // so that we can show it again when leaving the window
  39. bool cursorIsInside = false;
  40. // Double buffering to allow drawing to a canvas while displaying the previous one
  41. dsr::AlignedImageRgbaU8 canvas[bufferCount];
  42. int drawIndex = 0 % bufferCount;
  43. int showIndex = 1 % bufferCount;
  44. bool firstFrame = true;
  45. #ifndef DISABLE_MULTI_THREADING
  46. // The background worker for displaying the result using a separate thread protected by a mutex
  47. std::future<void> displayFuture;
  48. #endif
  49. // Remembers the dimensions of the window from creation and resize events
  50. // This allow requesting the size of the window at any time
  51. int windowWidth = 0, windowHeight = 0;
  52. private:
  53. // Called before the application fetches events from the input queue
  54. // Closing the window, moving the mouse, pressing a key, et cetera
  55. void prefetchEvents() override;
  56. void prefetchEvents_impl();
  57. // Called to change the cursor visibility and returning true on success
  58. bool setCursorVisibility(bool visible) override;
  59. // Place the cursor within the window
  60. bool setCursorPosition(int x, int y) override;
  61. private:
  62. // Helper methods specific to calling XLib
  63. void updateTitle_locked();
  64. private:
  65. // Canvas methods
  66. dsr::AlignedImageRgbaU8 getCanvas() override { return this->canvas[this->drawIndex]; }
  67. void resizeCanvas(int width, int height) override;
  68. // Window methods
  69. void setTitle(const dsr::String &newTitle) override {
  70. this->title = newTitle;
  71. this->updateTitle_locked();
  72. }
  73. void removeOldWindow_locked();
  74. void createWindowed_locked(const dsr::String& title, int width, int height);
  75. void createFullscreen_locked();
  76. void prepareWindow_locked();
  77. int windowState = 0; // 0=none, 1=windowed, 2=fullscreen
  78. public:
  79. // Constructors
  80. Win32Window(const Win32Window&) = delete; // Non-copyable because of pointer aliasing.
  81. Win32Window(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. ~Win32Window();
  86. // Interface
  87. void setFullScreen(bool enabled) override;
  88. bool isFullScreen() override { return this->windowState == 2; }
  89. void redraw(HWND& hwnd, bool locked, bool swap); // HWND is passed by argument because drawing might be called before the constructor has assigned it to this->hwnd
  90. void showCanvas() override;
  91. // Clipboard
  92. dsr::ReadableString loadFromClipboard(double timeoutInSeconds) override;
  93. void saveToClipboard(const dsr::ReadableString &text, double timeoutInSeconds) override;
  94. };
  95. static LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
  96. static const wchar_t* windowClassName = L"DfpsrWindowApplication";
  97. dsr::ReadableString Win32Window::loadFromClipboard(double timeoutInSeconds) {
  98. dsr::String result = U"";
  99. if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
  100. // TODO: Repeat attempts to open the clipboard in a delayed loop until the timeout is reached.
  101. if (OpenClipboard(this->hwnd)) {
  102. HGLOBAL globalBuffer = GetClipboardData(CF_UNICODETEXT);
  103. void *globalData = GlobalLock(globalBuffer);
  104. if (globalData) {
  105. result = dsr::string_dangerous_decodeFromData(globalData, dsr::CharacterEncoding::BOM_UTF16LE);
  106. GlobalUnlock(globalBuffer);
  107. }
  108. CloseClipboard();
  109. }
  110. } else if (IsClipboardFormatAvailable(CF_TEXT)) {
  111. // TODO: Repeat attempts to open the clipboard in a delayed loop until the timeout is reached.
  112. if (OpenClipboard(this->hwnd)) {
  113. HGLOBAL globalBuffer = GetClipboardData(CF_TEXT);
  114. void *globalData = GlobalLock(globalBuffer);
  115. if (globalData) {
  116. // TODO: Use a built-in conversion from native text formats.
  117. // If the text is not in Unicode format, assume Latin-1.
  118. result = dsr::string_dangerous_decodeFromData(globalData, dsr::CharacterEncoding::Raw_Latin1);
  119. GlobalUnlock(globalBuffer);
  120. }
  121. CloseClipboard();
  122. }
  123. }
  124. return result;
  125. }
  126. void Win32Window::saveToClipboard(const dsr::ReadableString &text, double timeoutInSeconds) {
  127. // TODO: Repeat attempts to open the clipboard in a delayed loop until the timeout is reached.
  128. if (OpenClipboard(this->hwnd)) {
  129. EmptyClipboard();
  130. dsr::Buffer savedText = dsr::string_saveToMemory(text, dsr::CharacterEncoding::BOM_UTF16LE, dsr::LineEncoding::CrLf, false, true);
  131. int64_t textSize = dsr::buffer_getSize(savedText);
  132. HGLOBAL globalBuffer = GlobalAlloc(GMEM_MOVEABLE, textSize);
  133. if (globalBuffer) {
  134. void *globalData = GlobalLock(globalBuffer);
  135. uint8_t *localData = dsr::buffer_dangerous_getUnsafeData(savedText);
  136. memcpy(globalData, localData, textSize);
  137. GlobalUnlock(globalBuffer);
  138. SetClipboardData(CF_UNICODETEXT, globalBuffer);
  139. } else {
  140. dsr::sendWarning(U"Could not allocate global memory for saving text to the clipboard!\n");
  141. }
  142. CloseClipboard();
  143. }
  144. }
  145. void Win32Window::updateTitle_locked() {
  146. lockWindow();
  147. dsr::Buffer nativeTitle = dsr::string_saveToMemory(this->title, dsr::CharacterEncoding::BOM_UTF16LE, dsr::LineEncoding::CrLf, false, true);
  148. if (!SetWindowTextW(this->hwnd, (wchar_t*)dsr::buffer_dangerous_getUnsafeData(nativeTitle))) {
  149. dsr::printText("Warning! Could not assign the window title ", dsr::string_mangleQuote(this->title), ".\n");
  150. }
  151. unlockWindow();
  152. }
  153. // The method can be seen as locked, but it overrides a virtual method that is independent of threading.
  154. bool Win32Window::setCursorPosition(int x, int y) {
  155. lockWindow();
  156. POINT point; point.x = x; point.y = y;
  157. ClientToScreen(this->hwnd, &point);
  158. SetCursorPos(point.x, point.y);
  159. // TODO: How can the mouse move event be sent in the correct order in case of already having move events waiting?
  160. this->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, dsr::IVector2D(x, y));
  161. unlockWindow();
  162. return true;
  163. }
  164. bool Win32Window::setCursorVisibility(bool visible) {
  165. // Cursor visibility is deferred, so no need to lock access here.
  166. // Remember the cursor's visibility for anyone asking
  167. this->visibleCursor = visible;
  168. // Indicate that the feature is implemented
  169. return true;
  170. }
  171. void Win32Window::setFullScreen(bool enabled) {
  172. if (this->windowState == 1 && enabled) {
  173. // Clean up any previous window
  174. removeOldWindow_locked();
  175. // Create the new window and graphics context
  176. this->createFullscreen_locked();
  177. } else if (this->windowState == 2 && !enabled) {
  178. // Clean up any previous window
  179. removeOldWindow_locked();
  180. // Create the new window and graphics context
  181. this->createWindowed_locked(this->title, 800, 600); // TODO: Remember the dimensions from last windowed mode
  182. }
  183. }
  184. void Win32Window::removeOldWindow_locked() {
  185. lockWindow();
  186. if (this->windowState != 0) {
  187. DestroyWindow(this->hwnd);
  188. }
  189. this->windowState = 0;
  190. unlockWindow();
  191. }
  192. void Win32Window::prepareWindow_locked() {
  193. lockWindow();
  194. // Reallocate the canvas
  195. this->resizeCanvas(this->windowWidth, this->windowHeight);
  196. // Show the window
  197. ShowWindow(this->hwnd, SW_NORMAL);
  198. // Repaint
  199. UpdateWindow(this->hwnd);
  200. unlockWindow();
  201. }
  202. static bool registered = false;
  203. static void registerIfNeeded() {
  204. if (!registered) {
  205. // The Window structure
  206. WNDCLASSEXW wincl;
  207. memset(&wincl, 0, sizeof(WNDCLASSEXW));
  208. wincl.cbSize = sizeof(WNDCLASSEXW);
  209. wincl.style = 0;
  210. wincl.lpfnWndProc = WindowProcedure;
  211. wincl.cbClsExtra = 0;
  212. wincl.cbWndExtra = sizeof(LPVOID);
  213. wincl.hInstance = NULL;
  214. wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
  215. wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
  216. // Use Windows's default color as the background of the window
  217. wincl.hbrBackground = (HBRUSH)COLOR_BACKGROUND; // TODO: Make black
  218. wincl.lpszMenuName = NULL;
  219. wincl.lpszClassName = windowClassName;
  220. // Use default icon and mouse-pointer
  221. wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
  222. // Register the window class, and if it fails quit the program
  223. if (!RegisterClassExW (&wincl)) {
  224. dsr::throwError("Call to RegisterClassExW failed!\n");
  225. }
  226. registered = true;
  227. }
  228. }
  229. void Win32Window::createWindowed_locked(const dsr::String& title, int width, int height) {
  230. // Request to resize the canvas and interface according to the new window
  231. this->windowWidth = width;
  232. this->windowHeight = height;
  233. this->receivedWindowResize(width, height);
  234. lockWindow();
  235. // Register the Window class during first creation
  236. registerIfNeeded();
  237. // The class is registered, let's create the program
  238. this->hwnd = CreateWindowExW(
  239. 0, // dwExStyle
  240. windowClassName, // lpClassName
  241. L"", // lpWindowName
  242. WS_OVERLAPPEDWINDOW, // dwStyle
  243. CW_USEDEFAULT, // x
  244. CW_USEDEFAULT, // y
  245. width, // nWidth
  246. height, // nHeight
  247. HWND_DESKTOP, // hWndParent
  248. NULL, // hMenu
  249. NULL, // hInstance
  250. (LPVOID)this // lpParam
  251. );
  252. unlockWindow();
  253. this->updateTitle_locked();
  254. this->windowState = 1;
  255. this->prepareWindow_locked();
  256. }
  257. void Win32Window::createFullscreen_locked() {
  258. lockWindow();
  259. int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  260. int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  261. // Request to resize the canvas and interface according to the new window
  262. this->windowWidth = screenWidth;
  263. this->windowHeight = screenHeight;
  264. this->receivedWindowResize(screenWidth, screenHeight);
  265. // Register the Window class during first creation
  266. registerIfNeeded();
  267. // The class is registered, let's create the program
  268. this->hwnd = CreateWindowExW(
  269. 0, // dwExStyle
  270. windowClassName, // lpClassName
  271. L"", // lpWindowName
  272. WS_POPUP | WS_VISIBLE, // dwStyle
  273. 0, // x
  274. 0, // y
  275. screenWidth, // nWidth
  276. screenHeight, // nHeight
  277. HWND_DESKTOP, // hWndParent
  278. NULL, // hMenu
  279. NULL, // hInstance
  280. (LPVOID)this // lpParam
  281. );
  282. unlockWindow();
  283. this->windowState = 2;
  284. this->prepareWindow_locked();
  285. }
  286. Win32Window::Win32Window(const dsr::String& title, int width, int height) {
  287. bool fullScreen = false;
  288. if (width < 1 || height < 1) {
  289. fullScreen = true;
  290. }
  291. // Remember the title
  292. this->title = title;
  293. lockWindow();
  294. // Get the default cursor
  295. this->defaultCursor = LoadCursor(0, IDC_ARROW);
  296. // Create an invisible cursor using masks padded to 32 bits for safety
  297. uint32_t cursorAndMask = 0b11111111;
  298. uint32_t cursorXorMask = 0b00000000;
  299. this->noCursor = CreateCursor(NULL, 0, 0, 1, 1, (const void*)&cursorAndMask, (const void*)&cursorXorMask);
  300. unlockWindow();
  301. // Create a window
  302. if (fullScreen) {
  303. this->createFullscreen_locked();
  304. } else {
  305. this->createWindowed_locked(title, width, height);
  306. }
  307. }
  308. static dsr::DsrKey getDsrKey(WPARAM keyCode) {
  309. dsr::DsrKey result = dsr::DsrKey_Unhandled;
  310. if (keyCode == VK_ESCAPE) {
  311. result = dsr::DsrKey_Escape;
  312. } else if (keyCode == VK_F1) {
  313. result = dsr::DsrKey_F1;
  314. } else if (keyCode == VK_F2) {
  315. result = dsr::DsrKey_F2;
  316. } else if (keyCode == VK_F3) {
  317. result = dsr::DsrKey_F3;
  318. } else if (keyCode == VK_F4) {
  319. result = dsr::DsrKey_F4;
  320. } else if (keyCode == VK_F5) {
  321. result = dsr::DsrKey_F5;
  322. } else if (keyCode == VK_F6) {
  323. result = dsr::DsrKey_F6;
  324. } else if (keyCode == VK_F7) {
  325. result = dsr::DsrKey_F7;
  326. } else if (keyCode == VK_F8) {
  327. result = dsr::DsrKey_F8;
  328. } else if (keyCode == VK_F9) {
  329. result = dsr::DsrKey_F9;
  330. } else if (keyCode == VK_F10) {
  331. result = dsr::DsrKey_F10;
  332. } else if (keyCode == VK_F11) {
  333. result = dsr::DsrKey_F11;
  334. } else if (keyCode == VK_F12) {
  335. result = dsr::DsrKey_F12;
  336. } else if (keyCode == VK_PAUSE) {
  337. result = dsr::DsrKey_Pause;
  338. } else if (keyCode == VK_SPACE) {
  339. result = dsr::DsrKey_Space;
  340. } else if (keyCode == VK_TAB) {
  341. result = dsr::DsrKey_Tab;
  342. } else if (keyCode == VK_RETURN) {
  343. result = dsr::DsrKey_Return;
  344. } else if (keyCode == VK_BACK) {
  345. result = dsr::DsrKey_BackSpace;
  346. } else if (keyCode == VK_LSHIFT || keyCode == VK_SHIFT || keyCode == VK_RSHIFT) {
  347. result = dsr::DsrKey_Shift;
  348. } else if (keyCode == VK_LCONTROL || keyCode == VK_CONTROL || keyCode == VK_RCONTROL) {
  349. result = dsr::DsrKey_Control;
  350. } else if (keyCode == VK_LMENU || keyCode == VK_MENU || keyCode == VK_RMENU) {
  351. result = dsr::DsrKey_Alt;
  352. } else if (keyCode == VK_DELETE) {
  353. result = dsr::DsrKey_Delete;
  354. } else if (keyCode == VK_LEFT) {
  355. result = dsr::DsrKey_LeftArrow;
  356. } else if (keyCode == VK_RIGHT) {
  357. result = dsr::DsrKey_RightArrow;
  358. } else if (keyCode == VK_UP) {
  359. result = dsr::DsrKey_UpArrow;
  360. } else if (keyCode == VK_DOWN) {
  361. result = dsr::DsrKey_DownArrow;
  362. } else if (keyCode == 0x30) {
  363. result = dsr::DsrKey_0;
  364. } else if (keyCode == 0x31) {
  365. result = dsr::DsrKey_1;
  366. } else if (keyCode == 0x32) {
  367. result = dsr::DsrKey_2;
  368. } else if (keyCode == 0x33) {
  369. result = dsr::DsrKey_3;
  370. } else if (keyCode == 0x34) {
  371. result = dsr::DsrKey_4;
  372. } else if (keyCode == 0x35) {
  373. result = dsr::DsrKey_5;
  374. } else if (keyCode == 0x36) {
  375. result = dsr::DsrKey_6;
  376. } else if (keyCode == 0x37) {
  377. result = dsr::DsrKey_7;
  378. } else if (keyCode == 0x38) {
  379. result = dsr::DsrKey_8;
  380. } else if (keyCode == 0x39) {
  381. result = dsr::DsrKey_9;
  382. } else if (keyCode == 0x41) {
  383. result = dsr::DsrKey_A;
  384. } else if (keyCode == 0x42) {
  385. result = dsr::DsrKey_B;
  386. } else if (keyCode == 0x43) {
  387. result = dsr::DsrKey_C;
  388. } else if (keyCode == 0x44) {
  389. result = dsr::DsrKey_D;
  390. } else if (keyCode == 0x45) {
  391. result = dsr::DsrKey_E;
  392. } else if (keyCode == 0x46) {
  393. result = dsr::DsrKey_F;
  394. } else if (keyCode == 0x47) {
  395. result = dsr::DsrKey_G;
  396. } else if (keyCode == 0x48) {
  397. result = dsr::DsrKey_H;
  398. } else if (keyCode == 0x49) {
  399. result = dsr::DsrKey_I;
  400. } else if (keyCode == 0x4A) {
  401. result = dsr::DsrKey_J;
  402. } else if (keyCode == 0x4B) {
  403. result = dsr::DsrKey_K;
  404. } else if (keyCode == 0x4C) {
  405. result = dsr::DsrKey_L;
  406. } else if (keyCode == 0x4D) {
  407. result = dsr::DsrKey_M;
  408. } else if (keyCode == 0x4E) {
  409. result = dsr::DsrKey_N;
  410. } else if (keyCode == 0x4F) {
  411. result = dsr::DsrKey_O;
  412. } else if (keyCode == 0x50) {
  413. result = dsr::DsrKey_P;
  414. } else if (keyCode == 0x51) {
  415. result = dsr::DsrKey_Q;
  416. } else if (keyCode == 0x52) {
  417. result = dsr::DsrKey_R;
  418. } else if (keyCode == 0x53) {
  419. result = dsr::DsrKey_S;
  420. } else if (keyCode == 0x54) {
  421. result = dsr::DsrKey_T;
  422. } else if (keyCode == 0x55) {
  423. result = dsr::DsrKey_U;
  424. } else if (keyCode == 0x56) {
  425. result = dsr::DsrKey_V;
  426. } else if (keyCode == 0x57) {
  427. result = dsr::DsrKey_W;
  428. } else if (keyCode == 0x58) {
  429. result = dsr::DsrKey_X;
  430. } else if (keyCode == 0x59) {
  431. result = dsr::DsrKey_Y;
  432. } else if (keyCode == 0x5A) {
  433. result = dsr::DsrKey_Z;
  434. } else if (keyCode == 0x2D) {
  435. result = dsr::DsrKey_Insert;
  436. } else if (keyCode == 0x24) {
  437. result = dsr::DsrKey_Home;
  438. } else if (keyCode == 0x23) {
  439. result = dsr::DsrKey_End;
  440. } else if (keyCode == 0x21) {
  441. result = dsr::DsrKey_PageUp;
  442. } else if (keyCode == 0x22) {
  443. result = dsr::DsrKey_PageDown;
  444. }
  445. return result;
  446. }
  447. // Called from DispatchMessage via prefetchEvents
  448. static LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
  449. // Get the Win32Window owning the given hwnd
  450. Win32Window *parent = nullptr;
  451. if (message == WM_CREATE) {
  452. // Cast the pointer argument into CREATESTRUCT and get the lParam given to the window on creation
  453. CREATESTRUCT *createStruct = (CREATESTRUCT*)lParam;
  454. parent = (Win32Window*)createStruct->lpCreateParams;
  455. if (parent == nullptr) {
  456. dsr::throwError("Null handle retreived from lParam (", (intptr_t)parent, ") in WM_CREATE message.\n");
  457. }
  458. SetWindowLongPtr(hwnd, GWLP_USERDATA, (intptr_t)parent);
  459. } else {
  460. // Get the parent
  461. parent = (Win32Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
  462. if (parent == nullptr) {
  463. // Don't try to handle global events unrelated to any window
  464. return DefWindowProc(hwnd, message, wParam, lParam);
  465. }
  466. }
  467. // Get the cursor location relative to the window.
  468. // Excluding scroll events that don't provide valid cursor locations.
  469. if (message == WM_LBUTTONDOWN
  470. || message == WM_LBUTTONUP
  471. || message == WM_RBUTTONDOWN
  472. || message == WM_RBUTTONUP
  473. || message == WM_MBUTTONDOWN
  474. || message == WM_MBUTTONUP
  475. || message == WM_MOUSEMOVE) {
  476. parent->lastMousePos = dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
  477. }
  478. // Check that we're using the correct window instance (This might not be the case while toggling full-screen)
  479. // Handle the message
  480. int result = 0;
  481. switch (message) {
  482. case WM_QUIT:
  483. PostQuitMessage(wParam);
  484. break;
  485. case WM_CLOSE:
  486. parent->receivedWindowCloseEvent();
  487. DestroyWindow(hwnd);
  488. break;
  489. case WM_LBUTTONDOWN:
  490. parent->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Left, parent->lastMousePos);
  491. break;
  492. case WM_LBUTTONUP:
  493. parent->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Left, parent->lastMousePos);
  494. break;
  495. case WM_RBUTTONDOWN:
  496. parent->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, parent->lastMousePos);
  497. break;
  498. case WM_RBUTTONUP:
  499. parent->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, parent->lastMousePos);
  500. break;
  501. case WM_MBUTTONDOWN:
  502. parent->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, parent->lastMousePos);
  503. break;
  504. case WM_MBUTTONUP:
  505. parent->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, parent->lastMousePos);
  506. break;
  507. case WM_MOUSEMOVE:
  508. parent->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, parent->lastMousePos);
  509. break;
  510. case WM_SETCURSOR:
  511. if (LOWORD(lParam) == HTCLIENT) {
  512. if (parent->visibleCursor) {
  513. SetCursor(parent->defaultCursor);
  514. } else {
  515. SetCursor(parent->noCursor);
  516. }
  517. }
  518. break;
  519. case WM_MOUSEWHEEL:
  520. {
  521. int delta = GET_WHEEL_DELTA_WPARAM(wParam);
  522. if (delta > 0) {
  523. parent->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollUp, parent->lastMousePos);
  524. } else if (delta < 0) {
  525. parent->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollDown, parent->lastMousePos);
  526. }
  527. }
  528. break;
  529. case WM_KEYDOWN: case WM_SYSKEYDOWN: case WM_KEYUP: case WM_SYSKEYUP:
  530. {
  531. dsr::DsrChar character = wParam; // Raw 16-bit character
  532. dsr::DsrKey dsrKey = getDsrKey(wParam); // Portable key-code
  533. bool previouslyPressed = lParam & (1 << 30);
  534. // For now, just let Windows send both Alt and Ctrl events from AltGr.
  535. // Would however be better if it could be consistent with other platforms.
  536. if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) {
  537. // If not repeated
  538. if (!previouslyPressed) {
  539. // Physical key down
  540. parent->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, character, dsrKey);
  541. dsr::printText(U"Down event (key = ", dsrKey, U")\n");
  542. }
  543. } else { // message == WM_KEYUP || message == WM_SYSKEYUP
  544. // Physical key up
  545. parent->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, character, dsrKey);
  546. dsr::printText(U"Up event (key = ", dsrKey, U")\n");
  547. }
  548. }
  549. break;
  550. case WM_CHAR:
  551. {
  552. // Typing event.
  553. dsr::DsrChar character = wParam; // Raw 16-bit character
  554. dsr::DsrKey dsrKey = getDsrKey(wParam); // Portable key-code
  555. parent->receivedKeyboardEvent(dsr::KeyboardEventType::KeyType, character, dsrKey);
  556. }
  557. break;
  558. case WM_PAINT:
  559. // BeginPaint and EndPaint must be called with the given hwnd to prevent having the redraw message sent again
  560. parent->redraw(hwnd, false, false);
  561. break;
  562. case WM_SIZE:
  563. // If there's no size during minimization, don't try to resize the canvas
  564. if (wParam != SIZE_MINIMIZED) {
  565. int width = LOWORD(lParam);
  566. int height = HIWORD(lParam);
  567. parent->windowWidth = width;
  568. parent->windowHeight = height;
  569. parent->receivedWindowResize(width, height);
  570. }
  571. // Resize the window as requested
  572. result = DefWindowProc(hwnd, message, wParam, lParam);
  573. break;
  574. default:
  575. result = DefWindowProc(hwnd, message, wParam, lParam);
  576. }
  577. return result;
  578. }
  579. void Win32Window::prefetchEvents_impl() {
  580. MSG messages;
  581. if (IsWindowUnicode(this->hwnd)) {
  582. while (PeekMessageW(&messages, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&messages); DispatchMessage(&messages); }
  583. } else {
  584. while (PeekMessage(&messages, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&messages); DispatchMessage(&messages); }
  585. }
  586. }
  587. void Win32Window::prefetchEvents() {
  588. // Only prefetch new events if nothing else is locking.
  589. if (windowLock.try_lock()) {
  590. this->prefetchEvents_impl();
  591. unlockWindow();
  592. }
  593. }
  594. // Locked because it overrides
  595. void Win32Window::resizeCanvas(int width, int height) {
  596. // Create a new canvas
  597. // Even thou Windows is using RGBA pack order for the window, the bitmap format used for drawing is using BGRA order
  598. for (int bufferIndex = 0; bufferIndex < bufferCount; bufferIndex++) {
  599. dsr::AlignedImageRgbaU8 previousCanvas = this->canvas[bufferIndex];
  600. this->canvas[bufferIndex] = dsr::image_create_RgbaU8_native(width, height, dsr::PackOrderIndex::BGRA);
  601. if (image_exists(previousCanvas)) {
  602. // Until the application's main loop has redrawn, fill the new canvas with a copy of the old one with black borders.
  603. dsr::draw_copy(this->canvas[bufferIndex], previousCanvas);
  604. }
  605. }
  606. this->firstFrame = true;
  607. }
  608. Win32Window::~Win32Window() {
  609. #ifndef DISABLE_MULTI_THREADING
  610. // Wait for the last update of the window to finish so that it doesn't try to operate on freed resources
  611. if (this->displayFuture.valid()) {
  612. this->displayFuture.wait();
  613. }
  614. #endif
  615. lockWindow();
  616. // Destroy the invisible cursor
  617. DestroyCursor(this->noCursor);
  618. // Destroy the native window
  619. DestroyWindow(this->hwnd);
  620. unlockWindow();
  621. }
  622. // The lock argument must be true if not already within a lock and false if inside of a lock.
  623. void Win32Window::redraw(HWND& hwnd, bool lock, bool swap) {
  624. #ifndef DISABLE_MULTI_THREADING
  625. // Wait for the previous update to finish, to avoid flooding the system with new threads waiting for windowLock
  626. if (this->displayFuture.valid()) {
  627. this->displayFuture.wait();
  628. }
  629. #endif
  630. if (lock) {
  631. // Any other requests will have to wait.
  632. lockWindow();
  633. // Last chance to prefetch events before uploading the canvas.
  634. this->prefetchEvents_impl();
  635. }
  636. if (swap) {
  637. this->drawIndex = (this->drawIndex + 1) % bufferCount;
  638. this->showIndex = (this->showIndex + 1) % bufferCount;
  639. }
  640. this->prefetchEvents();
  641. int displayIndex = this->showIndex;
  642. std::function<void()> task = [this, displayIndex, lock]() {
  643. // Let the source bitmap use a padded width to safely handle the stride
  644. // Windows requires 8-byte alignment, but the image format uses larger alignment.
  645. int paddedWidth = dsr::image_getStride(this->canvas[displayIndex]) / 4;
  646. //int width = dsr::image_getWidth(this->canvas[displayIndex]);
  647. int height = dsr::image_getHeight(this->canvas[displayIndex]);
  648. InvalidateRect(this->hwnd, NULL, false);
  649. PAINTSTRUCT paintStruct;
  650. HDC targetContext = BeginPaint(this->hwnd, &paintStruct);
  651. BITMAPINFO bmi = {};
  652. bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
  653. bmi.bmiHeader.biWidth = paddedWidth;
  654. bmi.bmiHeader.biHeight = -height;
  655. bmi.bmiHeader.biPlanes = 1;
  656. bmi.bmiHeader.biBitCount = 32;
  657. bmi.bmiHeader.biCompression = BI_RGB;
  658. SetDIBitsToDevice(targetContext, 0, 0, paddedWidth, height, 0, 0, 0, height, dsr::image_dangerous_getData(this->canvas[displayIndex]), &bmi, DIB_RGB_COLORS);
  659. EndPaint(this->hwnd, &paintStruct);
  660. if (lock) {
  661. unlockWindow();
  662. }
  663. };
  664. #ifdef DISABLE_MULTI_THREADING
  665. // Perform instantly
  666. task();
  667. #else
  668. if (this->firstFrame) {
  669. // The first frame will be cloned when double buffering.
  670. if (bufferCount == 2) {
  671. // TODO: Only do this for the absolute first frame, not after resize.
  672. dsr::draw_copy(this->canvas[this->drawIndex], this->canvas[this->showIndex]);
  673. }
  674. // Single-thread the first frame to keep it safe.
  675. task();
  676. this->firstFrame = false;
  677. } else {
  678. // Run in the background while doing other things
  679. this->displayFuture = std::async(std::launch::async, task);
  680. }
  681. #endif
  682. }
  683. void Win32Window::showCanvas() {
  684. this->redraw(this->hwnd, true, true);
  685. }
  686. dsr::Handle<dsr::BackendWindow> createBackendWindow(const dsr::String& title, int width, int height) {
  687. return dsr::handle_create<Win32Window>(title, width, height);
  688. }