Win32Window.cpp 26 KB

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