Win32Window.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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. void 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 TCHAR windowClassName[] = _T("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. if (!SetWindowTextA(this->hwnd, dsr::FixedAscii<512>(this->title).getPointer())) {
  148. dsr::printText("Warning! Could not assign the window title ", dsr::string_mangleQuote(this->title), ".\n");
  149. }
  150. unlockWindow();
  151. }
  152. // The method can be seen as locked, but it overrides a virtual method that is independent of threading.
  153. void Win32Window::setCursorPosition(int x, int y) {
  154. lockWindow();
  155. POINT point; point.x = x; point.y = y;
  156. ClientToScreen(this->hwnd, &point);
  157. SetCursorPos(point.x, point.y);
  158. unlockWindow();
  159. }
  160. bool Win32Window::setCursorVisibility(bool visible) {
  161. // Cursor visibility is deferred, so no need to lock access here.
  162. // Remember the cursor's visibility for anyone asking
  163. this->visibleCursor = visible;
  164. // Indicate that the feature is implemented
  165. return true;
  166. }
  167. void Win32Window::setFullScreen(bool enabled) {
  168. if (this->windowState == 1 && enabled) {
  169. // Clean up any previous window
  170. removeOldWindow_locked();
  171. // Create the new window and graphics context
  172. this->createFullscreen_locked();
  173. } else if (this->windowState == 2 && !enabled) {
  174. // Clean up any previous window
  175. removeOldWindow_locked();
  176. // Create the new window and graphics context
  177. this->createWindowed_locked(this->title, 800, 600); // TODO: Remember the dimensions from last windowed mode
  178. }
  179. }
  180. void Win32Window::removeOldWindow_locked() {
  181. lockWindow();
  182. if (this->windowState != 0) {
  183. DestroyWindow(this->hwnd);
  184. }
  185. this->windowState = 0;
  186. unlockWindow();
  187. }
  188. void Win32Window::prepareWindow_locked() {
  189. lockWindow();
  190. // Reallocate the canvas
  191. this->resizeCanvas(this->windowWidth, this->windowHeight);
  192. // Show the window
  193. ShowWindow(this->hwnd, SW_NORMAL);
  194. // Repaint
  195. UpdateWindow(this->hwnd);
  196. unlockWindow();
  197. }
  198. static bool registered = false;
  199. static void registerIfNeeded() {
  200. if (!registered) {
  201. // The Window structure
  202. WNDCLASSEX wincl;
  203. memset(&wincl, 0, sizeof(WNDCLASSEX));
  204. wincl.hInstance = NULL;
  205. wincl.lpszClassName = windowClassName;
  206. wincl.lpfnWndProc = WindowProcedure;
  207. wincl.style = 0;
  208. wincl.cbSize = sizeof(WNDCLASSEX);
  209. // Use default icon and mouse-pointer
  210. wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
  211. wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
  212. wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
  213. wincl.lpszMenuName = NULL;
  214. wincl.cbClsExtra = 0;
  215. wincl.cbWndExtra = sizeof(LPVOID);
  216. // Use Windows's default color as the background of the window
  217. wincl.hbrBackground = (HBRUSH)COLOR_BACKGROUND; // TODO: Make black
  218. // Register the window class, and if it fails quit the program
  219. if (!RegisterClassEx (&wincl)) {
  220. dsr::throwError("Call to RegisterClassEx failed!\n");
  221. }
  222. registered = true;
  223. }
  224. }
  225. void Win32Window::createWindowed_locked(const dsr::String& title, int width, int height) {
  226. // Request to resize the canvas and interface according to the new window
  227. this->windowWidth = width;
  228. this->windowHeight = height;
  229. this->receivedWindowResize(width, height);
  230. lockWindow();
  231. // Register the Window class during first creation
  232. registerIfNeeded();
  233. // The class is registered, let's create the program
  234. this->hwnd = CreateWindowEx(
  235. 0, // dwExStyle
  236. windowClassName, // lpClassName
  237. _T(""), // lpWindowName
  238. WS_OVERLAPPEDWINDOW, // dwStyle
  239. CW_USEDEFAULT, // x
  240. CW_USEDEFAULT, // y
  241. width, // nWidth
  242. height, // nHeight
  243. HWND_DESKTOP, // hWndParent
  244. NULL, // hMenu
  245. NULL, // hInstance
  246. (LPVOID)this // lpParam
  247. );
  248. unlockWindow();
  249. this->updateTitle_locked();
  250. this->windowState = 1;
  251. this->prepareWindow_locked();
  252. }
  253. void Win32Window::createFullscreen_locked() {
  254. lockWindow();
  255. int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  256. int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  257. // Request to resize the canvas and interface according to the new window
  258. this->windowWidth = screenWidth;
  259. this->windowHeight = screenHeight;
  260. this->receivedWindowResize(screenWidth, screenHeight);
  261. // Register the Window class during first creation
  262. registerIfNeeded();
  263. // The class is registered, let's create the program
  264. this->hwnd = CreateWindowEx(
  265. 0, // dwExStyle
  266. windowClassName, // lpClassName
  267. _T(""), // lpWindowName
  268. WS_POPUP | WS_VISIBLE, // dwStyle
  269. 0, // x
  270. 0, // y
  271. screenWidth, // nWidth
  272. screenHeight, // nHeight
  273. HWND_DESKTOP, // hWndParent
  274. NULL, // hMenu
  275. NULL, // hInstance
  276. (LPVOID)this // lpParam
  277. );
  278. unlockWindow();
  279. this->windowState = 2;
  280. this->prepareWindow_locked();
  281. }
  282. Win32Window::Win32Window(const dsr::String& title, int width, int height) {
  283. bool fullScreen = false;
  284. if (width < 1 || height < 1) {
  285. fullScreen = true;
  286. }
  287. // Remember the title
  288. this->title = title;
  289. lockWindow();
  290. // Get the default cursor
  291. this->defaultCursor = LoadCursor(0, IDC_ARROW);
  292. // Create an invisible cursor using masks padded to 32 bits for safety
  293. uint32_t cursorAndMask = 0b11111111;
  294. uint32_t cursorXorMask = 0b00000000;
  295. this->noCursor = CreateCursor(NULL, 0, 0, 1, 1, (const void*)&cursorAndMask, (const void*)&cursorXorMask);
  296. unlockWindow();
  297. // Create a window
  298. if (fullScreen) {
  299. this->createFullscreen_locked();
  300. } else {
  301. this->createWindowed_locked(title, width, height);
  302. }
  303. }
  304. static dsr::DsrKey getDsrKey(WPARAM keyCode) {
  305. dsr::DsrKey result = dsr::DsrKey_Unhandled;
  306. if (keyCode == VK_ESCAPE) {
  307. result = dsr::DsrKey_Escape;
  308. } else if (keyCode == VK_F1) {
  309. result = dsr::DsrKey_F1;
  310. } else if (keyCode == VK_F2) {
  311. result = dsr::DsrKey_F2;
  312. } else if (keyCode == VK_F3) {
  313. result = dsr::DsrKey_F3;
  314. } else if (keyCode == VK_F4) {
  315. result = dsr::DsrKey_F4;
  316. } else if (keyCode == VK_F5) {
  317. result = dsr::DsrKey_F5;
  318. } else if (keyCode == VK_F6) {
  319. result = dsr::DsrKey_F6;
  320. } else if (keyCode == VK_F7) {
  321. result = dsr::DsrKey_F7;
  322. } else if (keyCode == VK_F8) {
  323. result = dsr::DsrKey_F8;
  324. } else if (keyCode == VK_F9) {
  325. result = dsr::DsrKey_F9;
  326. } else if (keyCode == VK_F10) {
  327. result = dsr::DsrKey_F10;
  328. } else if (keyCode == VK_F11) {
  329. result = dsr::DsrKey_F11;
  330. } else if (keyCode == VK_F12) {
  331. result = dsr::DsrKey_F12;
  332. } else if (keyCode == VK_PAUSE) {
  333. result = dsr::DsrKey_Pause;
  334. } else if (keyCode == VK_SPACE) {
  335. result = dsr::DsrKey_Space;
  336. } else if (keyCode == VK_TAB) {
  337. result = dsr::DsrKey_Tab;
  338. } else if (keyCode == VK_RETURN) {
  339. result = dsr::DsrKey_Return;
  340. } else if (keyCode == VK_BACK) {
  341. result = dsr::DsrKey_BackSpace;
  342. } else if (keyCode == VK_LSHIFT || keyCode == VK_SHIFT || keyCode == VK_RSHIFT) {
  343. result = dsr::DsrKey_Shift;
  344. } else if (keyCode == VK_LCONTROL || keyCode == VK_CONTROL || keyCode == VK_RCONTROL) {
  345. result = dsr::DsrKey_Control;
  346. } else if (keyCode == VK_LMENU || keyCode == VK_MENU || keyCode == VK_RMENU) {
  347. result = dsr::DsrKey_Alt;
  348. } else if (keyCode == VK_DELETE) {
  349. result = dsr::DsrKey_Delete;
  350. } else if (keyCode == VK_LEFT) {
  351. result = dsr::DsrKey_LeftArrow;
  352. } else if (keyCode == VK_RIGHT) {
  353. result = dsr::DsrKey_RightArrow;
  354. } else if (keyCode == VK_UP) {
  355. result = dsr::DsrKey_UpArrow;
  356. } else if (keyCode == VK_DOWN) {
  357. result = dsr::DsrKey_DownArrow;
  358. } else if (keyCode == 0x30) {
  359. result = dsr::DsrKey_0;
  360. } else if (keyCode == 0x31) {
  361. result = dsr::DsrKey_1;
  362. } else if (keyCode == 0x32) {
  363. result = dsr::DsrKey_2;
  364. } else if (keyCode == 0x33) {
  365. result = dsr::DsrKey_3;
  366. } else if (keyCode == 0x34) {
  367. result = dsr::DsrKey_4;
  368. } else if (keyCode == 0x35) {
  369. result = dsr::DsrKey_5;
  370. } else if (keyCode == 0x36) {
  371. result = dsr::DsrKey_6;
  372. } else if (keyCode == 0x37) {
  373. result = dsr::DsrKey_7;
  374. } else if (keyCode == 0x38) {
  375. result = dsr::DsrKey_8;
  376. } else if (keyCode == 0x39) {
  377. result = dsr::DsrKey_9;
  378. } else if (keyCode == 0x41) {
  379. result = dsr::DsrKey_A;
  380. } else if (keyCode == 0x42) {
  381. result = dsr::DsrKey_B;
  382. } else if (keyCode == 0x43) {
  383. result = dsr::DsrKey_C;
  384. } else if (keyCode == 0x44) {
  385. result = dsr::DsrKey_D;
  386. } else if (keyCode == 0x45) {
  387. result = dsr::DsrKey_E;
  388. } else if (keyCode == 0x46) {
  389. result = dsr::DsrKey_F;
  390. } else if (keyCode == 0x47) {
  391. result = dsr::DsrKey_G;
  392. } else if (keyCode == 0x48) {
  393. result = dsr::DsrKey_H;
  394. } else if (keyCode == 0x49) {
  395. result = dsr::DsrKey_I;
  396. } else if (keyCode == 0x4A) {
  397. result = dsr::DsrKey_J;
  398. } else if (keyCode == 0x4B) {
  399. result = dsr::DsrKey_K;
  400. } else if (keyCode == 0x4C) {
  401. result = dsr::DsrKey_L;
  402. } else if (keyCode == 0x4D) {
  403. result = dsr::DsrKey_M;
  404. } else if (keyCode == 0x4E) {
  405. result = dsr::DsrKey_N;
  406. } else if (keyCode == 0x4F) {
  407. result = dsr::DsrKey_O;
  408. } else if (keyCode == 0x50) {
  409. result = dsr::DsrKey_P;
  410. } else if (keyCode == 0x51) {
  411. result = dsr::DsrKey_Q;
  412. } else if (keyCode == 0x52) {
  413. result = dsr::DsrKey_R;
  414. } else if (keyCode == 0x53) {
  415. result = dsr::DsrKey_S;
  416. } else if (keyCode == 0x54) {
  417. result = dsr::DsrKey_T;
  418. } else if (keyCode == 0x55) {
  419. result = dsr::DsrKey_U;
  420. } else if (keyCode == 0x56) {
  421. result = dsr::DsrKey_V;
  422. } else if (keyCode == 0x57) {
  423. result = dsr::DsrKey_W;
  424. } else if (keyCode == 0x58) {
  425. result = dsr::DsrKey_X;
  426. } else if (keyCode == 0x59) {
  427. result = dsr::DsrKey_Y;
  428. } else if (keyCode == 0x5A) {
  429. result = dsr::DsrKey_Z;
  430. } else if (keyCode == 0x2D) {
  431. result = dsr::DsrKey_Insert;
  432. } else if (keyCode == 0x24) {
  433. result = dsr::DsrKey_Home;
  434. } else if (keyCode == 0x23) {
  435. result = dsr::DsrKey_End;
  436. } else if (keyCode == 0x21) {
  437. result = dsr::DsrKey_PageUp;
  438. } else if (keyCode == 0x22) {
  439. result = dsr::DsrKey_PageDown;
  440. }
  441. return result;
  442. }
  443. // Called from DispatchMessage via prefetchEvents
  444. static LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
  445. // Get the Win32Window owning the given hwnd
  446. Win32Window *parent = nullptr;
  447. if (message == WM_CREATE) {
  448. // Cast the pointer argument into CREATESTRUCT and get the lParam given to the window on creation
  449. CREATESTRUCT *createStruct = (CREATESTRUCT*)lParam;
  450. parent = (Win32Window*)createStruct->lpCreateParams;
  451. if (parent == nullptr) {
  452. dsr::throwError("Null handle retreived from lParam (", (intptr_t)parent, ") in WM_CREATE message.\n");
  453. }
  454. SetWindowLongPtr(hwnd, GWLP_USERDATA, (intptr_t)parent);
  455. } else {
  456. // Get the parent
  457. parent = (Win32Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
  458. if (parent == nullptr) {
  459. // Don't try to handle global events unrelated to any window
  460. return DefWindowProc(hwnd, message, wParam, lParam);
  461. }
  462. }
  463. // Get the cursor location relative to the window.
  464. // Excluding scroll events that don't provide valid cursor locations.
  465. if (message == WM_LBUTTONDOWN
  466. || message == WM_LBUTTONUP
  467. || message == WM_RBUTTONDOWN
  468. || message == WM_RBUTTONUP
  469. || message == WM_MBUTTONDOWN
  470. || message == WM_MBUTTONUP
  471. || message == WM_MOUSEMOVE) {
  472. parent->lastMousePos = dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
  473. }
  474. // Check that we're using the correct window instance (This might not be the case while toggling full-screen)
  475. // Handle the message
  476. int result = 0;
  477. switch (message) {
  478. case WM_QUIT:
  479. PostQuitMessage(wParam);
  480. break;
  481. case WM_CLOSE:
  482. parent->receivedWindowCloseEvent();
  483. DestroyWindow(hwnd);
  484. break;
  485. case WM_LBUTTONDOWN:
  486. parent->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Left, parent->lastMousePos);
  487. break;
  488. case WM_LBUTTONUP:
  489. parent->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Left, parent->lastMousePos);
  490. break;
  491. case WM_RBUTTONDOWN:
  492. parent->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, parent->lastMousePos);
  493. break;
  494. case WM_RBUTTONUP:
  495. parent->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, parent->lastMousePos);
  496. break;
  497. case WM_MBUTTONDOWN:
  498. parent->receivedMouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, parent->lastMousePos);
  499. break;
  500. case WM_MBUTTONUP:
  501. parent->receivedMouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, parent->lastMousePos);
  502. break;
  503. case WM_MOUSEMOVE:
  504. parent->receivedMouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, parent->lastMousePos);
  505. break;
  506. case WM_SETCURSOR:
  507. if (LOWORD(lParam) == HTCLIENT) {
  508. if (parent->visibleCursor) {
  509. SetCursor(parent->defaultCursor);
  510. } else {
  511. SetCursor(parent->noCursor);
  512. }
  513. }
  514. break;
  515. case WM_MOUSEWHEEL:
  516. {
  517. int delta = GET_WHEEL_DELTA_WPARAM(wParam);
  518. if (delta > 0) {
  519. parent->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollUp, parent->lastMousePos);
  520. } else if (delta < 0) {
  521. parent->receivedMouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollDown, parent->lastMousePos);
  522. }
  523. }
  524. break;
  525. case WM_KEYDOWN: case WM_SYSKEYDOWN: case WM_KEYUP: case WM_SYSKEYUP:
  526. {
  527. dsr::DsrChar character;
  528. if (IsWindowUnicode(hwnd)) {
  529. dsr::CharacterEncoding encoding = dsr::CharacterEncoding::BOM_UTF16LE;
  530. dsr::String characterString = dsr::string_dangerous_decodeFromData((const void*)&wParam, encoding);
  531. character = characterString[0]; // Convert from UTF-16 surrogate to UTF-32 Unicode character
  532. } else {
  533. character = wParam; // Raw ansi character
  534. }
  535. dsr::DsrKey dsrKey = getDsrKey(wParam); // Portable key-code
  536. bool previouslyPressed = lParam & (1 << 30);
  537. // For now, just let Windows send both Alt and Ctrl events from AltGr.
  538. // Would however be better if it could be consistent with other platforms.
  539. if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) {
  540. // If not repeated
  541. if (!previouslyPressed) {
  542. // Physical key down
  543. parent->receivedKeyboardEvent(dsr::KeyboardEventType::KeyDown, character, dsrKey);
  544. }
  545. // Press typing with repeat
  546. parent->receivedKeyboardEvent(dsr::KeyboardEventType::KeyType, character, dsrKey);
  547. } else { // message == WM_KEYUP || message == WM_SYSKEYUP
  548. // Physical key up
  549. parent->receivedKeyboardEvent(dsr::KeyboardEventType::KeyUp, character, dsrKey);
  550. }
  551. }
  552. break;
  553. case WM_PAINT:
  554. //parent->receivedWindowRedrawEvent();
  555. // BeginPaint and EndPaint must be called with the given hwnd to prevent having the redraw message sent again
  556. parent->redraw(hwnd, false, false);
  557. // Passing on the event to prevent flooding with more messages. This is only a temporary solution.
  558. // TODO: Avoid overwriting the result with any background color.
  559. //result = DefWindowProc(hwnd, message, wParam, lParam);
  560. break;
  561. case WM_SIZE:
  562. // If there's no size during minimization, don't try to resize the canvas
  563. if (wParam != SIZE_MINIMIZED) {
  564. int width = LOWORD(lParam);
  565. int height = HIWORD(lParam);
  566. parent->windowWidth = width;
  567. parent->windowHeight = height;
  568. parent->receivedWindowResize(width, height);
  569. }
  570. // Resize the window as requested
  571. result = DefWindowProc(hwnd, message, wParam, lParam);
  572. break;
  573. default:
  574. result = DefWindowProc(hwnd, message, wParam, lParam);
  575. }
  576. return result;
  577. }
  578. void Win32Window::prefetchEvents_impl() {
  579. MSG messages;
  580. if (IsWindowUnicode(this->hwnd)) {
  581. while (PeekMessageW(&messages, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&messages); DispatchMessage(&messages); }
  582. } else {
  583. while (PeekMessage(&messages, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&messages); DispatchMessage(&messages); }
  584. }
  585. }
  586. void Win32Window::prefetchEvents() {
  587. // Only prefetch new events if nothing else is locking.
  588. if (windowLock.try_lock()) {
  589. this->prefetchEvents_impl();
  590. unlockWindow();
  591. }
  592. }
  593. // Locked because it overrides
  594. void Win32Window::resizeCanvas(int width, int height) {
  595. // Create a new canvas
  596. // Even thou Windows is using RGBA pack order for the window, the bitmap format used for drawing is using BGRA order
  597. for (int bufferIndex = 0; bufferIndex < bufferCount; bufferIndex++) {
  598. dsr::AlignedImageRgbaU8 previousCanvas = this->canvas[bufferIndex];
  599. this->canvas[bufferIndex] = dsr::image_create_RgbaU8_native(width, height, dsr::PackOrderIndex::BGRA);
  600. if (image_exists(previousCanvas)) {
  601. // Until the application's main loop has redrawn, fill the new canvas with a copy of the old one with black borders.
  602. dsr::draw_copy(this->canvas[bufferIndex], previousCanvas);
  603. }
  604. }
  605. this->firstFrame = true;
  606. }
  607. Win32Window::~Win32Window() {
  608. #ifndef DISABLE_MULTI_THREADING
  609. // Wait for the last update of the window to finish so that it doesn't try to operate on freed resources
  610. if (this->displayFuture.valid()) {
  611. this->displayFuture.wait();
  612. }
  613. #endif
  614. lockWindow();
  615. // Destroy the invisible cursor
  616. DestroyCursor(this->noCursor);
  617. // Destroy the native window
  618. DestroyWindow(this->hwnd);
  619. unlockWindow();
  620. }
  621. // The lock argument must be true if not already within a lock and false if inside of a lock.
  622. void Win32Window::redraw(HWND& hwnd, bool lock, bool swap) {
  623. #ifndef DISABLE_MULTI_THREADING
  624. // Wait for the previous update to finish, to avoid flooding the system with new threads waiting for windowLock
  625. if (this->displayFuture.valid()) {
  626. this->displayFuture.wait();
  627. }
  628. #endif
  629. if (lock) {
  630. // Any other requests will have to wait.
  631. lockWindow();
  632. // Last chance to prefetch events before uploading the canvas.
  633. this->prefetchEvents_impl();
  634. }
  635. if (swap) {
  636. this->drawIndex = (this->drawIndex + 1) % bufferCount;
  637. this->showIndex = (this->showIndex + 1) % bufferCount;
  638. }
  639. this->prefetchEvents();
  640. int displayIndex = this->showIndex;
  641. std::function<void()> task = [this, displayIndex, lock]() {
  642. // Let the source bitmap use a padded width to safely handle the stride
  643. // Windows requires 8-byte alignment, but the image format uses larger alignment.
  644. int paddedWidth = dsr::image_getStride(this->canvas[displayIndex]) / 4;
  645. //int width = dsr::image_getWidth(this->canvas[displayIndex]);
  646. int height = dsr::image_getHeight(this->canvas[displayIndex]);
  647. InvalidateRect(this->hwnd, NULL, false);
  648. PAINTSTRUCT paintStruct;
  649. HDC targetContext = BeginPaint(this->hwnd, &paintStruct);
  650. BITMAPINFO bmi = {};
  651. bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
  652. bmi.bmiHeader.biWidth = paddedWidth;
  653. bmi.bmiHeader.biHeight = -height;
  654. bmi.bmiHeader.biPlanes = 1;
  655. bmi.bmiHeader.biBitCount = 32;
  656. bmi.bmiHeader.biCompression = BI_RGB;
  657. SetDIBitsToDevice(targetContext, 0, 0, paddedWidth, height, 0, 0, 0, height, dsr::image_dangerous_getData(this->canvas[displayIndex]), &bmi, DIB_RGB_COLORS);
  658. EndPaint(this->hwnd, &paintStruct);
  659. if (lock) {
  660. unlockWindow();
  661. }
  662. };
  663. #ifdef DISABLE_MULTI_THREADING
  664. // Perform instantly
  665. task();
  666. #else
  667. if (this->firstFrame) {
  668. // The first frame will be cloned when double buffering.
  669. if (bufferCount == 2) {
  670. // TODO: Only do this for the absolute first frame, not after resize.
  671. dsr::draw_copy(this->canvas[this->drawIndex], this->canvas[this->showIndex]);
  672. }
  673. // Single-thread the first frame to keep it safe.
  674. task();
  675. this->firstFrame = false;
  676. } else {
  677. // Run in the background while doing other things
  678. this->displayFuture = std::async(std::launch::async, task);
  679. }
  680. #endif
  681. }
  682. void Win32Window::showCanvas() {
  683. this->redraw(this->hwnd, true, true);
  684. }
  685. dsr::Handle<dsr::BackendWindow> createBackendWindow(const dsr::String& title, int width, int height) {
  686. return dsr::handle_create<Win32Window>(title, width, height);
  687. }