Win32Window.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. #include "../DFPSR/api/imageAPI.h"
  2. #include "../DFPSR/gui/BackendWindow.h"
  3. /*
  4. Link to these dependencies for MS Windows:
  5. gdi32
  6. user32
  7. kernel32
  8. comctl32
  9. */
  10. #include <tchar.h>
  11. #include <windows.h>
  12. #include <windowsx.h>
  13. class Win32Window : public dsr::BackendWindow {
  14. public:
  15. // The native windows handle
  16. HWND hwnd;
  17. // Double buffering to allow drawing to a canvas while displaying the previous one
  18. // The image which can be drawn to
  19. dsr::AlignedImageRgbaU8 canvas;
  20. // Remembers the dimensions of the window from creation and resize events
  21. // This allow requesting the size of the window at any time
  22. int windowWidth = 0, windowHeight = 0;
  23. private:
  24. // Called before the application fetches events from the input queue
  25. // Closing the window, moving the mouse, pressing a key, et cetera
  26. void prefetchEvents() override;
  27. private:
  28. // Helper methods specific to calling XLib
  29. void updateTitle();
  30. private:
  31. // Canvas methods
  32. dsr::AlignedImageRgbaU8 getCanvas() override { return this->canvas; }
  33. void resizeCanvas(int width, int height) override;
  34. // Window methods
  35. void setTitle(const dsr::String &newTitle) override {
  36. this->title = newTitle;
  37. this->updateTitle();
  38. }
  39. void removeOldWindow();
  40. void createWindow(const dsr::String& title, int width, int height);
  41. void createWindowed(const dsr::String& title, int width, int height);
  42. void createFullscreen();
  43. void prepareWindow();
  44. int windowState = 0; // 0=none, 1=windowed, 2=fullscreen
  45. public:
  46. // Constructors
  47. Win32Window(const Win32Window&) = delete; // Non-copyable because of pointer aliasing.
  48. Win32Window(const dsr::String& title, int width, int height);
  49. int getWidth() const override { return this->windowWidth; };
  50. int getHeight() const override { return this->windowHeight; };
  51. // Destructor
  52. ~Win32Window();
  53. // Interface
  54. void setFullScreen(bool enabled) override;
  55. bool isFullScreen() override { return this->windowState == 2; }
  56. void redraw(HWND& hwnd); // HWND is passed by argument because drawing might be called before the constructor has assigned it to this->hwnd
  57. void showCanvas() override;
  58. };
  59. static LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
  60. static TCHAR windowClassName[] = _T("DfpsrWindowApplication");
  61. void Win32Window::updateTitle() {
  62. if (!SetWindowTextA(this->hwnd, this->title.toStdString().c_str())) {
  63. dsr::printText("Warning! Could not assign the window title ", dsr::string_mangleQuote(this->title), ".\n");
  64. }
  65. }
  66. void Win32Window::setFullScreen(bool enabled) {
  67. if (this->windowState == 1 && enabled) {
  68. // Clean up any previous window
  69. removeOldWindow();
  70. // Create the new window and graphics context
  71. this->createFullscreen();
  72. } else if (this->windowState == 2 && !enabled) {
  73. // Clean up any previous window
  74. removeOldWindow();
  75. // Create the new window and graphics context
  76. this->createWindowed(this->title, 800, 600); // TODO: Remember the dimensions from last windowed mode
  77. }
  78. }
  79. void Win32Window::removeOldWindow() {
  80. if (this->windowState != 0) {
  81. DestroyWindow(this->hwnd);
  82. }
  83. this->windowState = 0;
  84. }
  85. void Win32Window::prepareWindow() {
  86. // Reallocate the canvas
  87. this->resizeCanvas(this->windowWidth, this->windowHeight);
  88. // Show the window
  89. ShowWindow(this->hwnd, SW_NORMAL);
  90. // Repaint
  91. UpdateWindow(this->hwnd);
  92. }
  93. void Win32Window::createWindow(const dsr::String& title, int width, int height) {
  94. // Request to resize the canvas and interface according to the new window
  95. this->windowWidth = width;
  96. this->windowHeight = height;
  97. this->receivedWindowResize(width, height);
  98. // The Window structure
  99. WNDCLASSEX wincl;
  100. memset(&wincl, 0, sizeof(WNDCLASSEX));
  101. wincl.hInstance = NULL;
  102. wincl.lpszClassName = windowClassName;
  103. wincl.lpfnWndProc = WindowProcedure;
  104. wincl.style = 0;
  105. wincl.cbSize = sizeof(WNDCLASSEX);
  106. // Use default icon and mouse-pointer
  107. wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
  108. wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
  109. wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
  110. wincl.lpszMenuName = NULL; // No menu
  111. wincl.cbClsExtra = 0; // No extra bytes after the window class
  112. wincl.cbWndExtra = sizeof(LPVOID); // structure or the window instance
  113. // Use Windows's default color as the background of the window
  114. wincl.hbrBackground = (HBRUSH)COLOR_BACKGROUND; // TODO: Make black
  115. // Register the window class, and if it fails quit the program
  116. if (!RegisterClassEx (&wincl)) {
  117. dsr::throwError("Call to RegisterClassEx failed!\n");
  118. }
  119. // The class is registered, let's create the program
  120. this->hwnd = CreateWindowEx(
  121. 0, // Extended possibilites for variation
  122. windowClassName, // Classname
  123. _T("MyWindow"), // Title Text
  124. WS_OVERLAPPEDWINDOW, // default window
  125. CW_USEDEFAULT, // Windows decides the position
  126. CW_USEDEFAULT, // where the window ends up on the screen
  127. width, // The programs width
  128. height, // and height in pixels
  129. HWND_DESKTOP, // The window is a child-window to desktop
  130. NULL, // No menu
  131. NULL, // Program Instance handler
  132. (LPVOID)this // Pointer to the window wrapper
  133. );
  134. // TODO: Set the title
  135. this->updateTitle();
  136. }
  137. void Win32Window::createWindowed(const dsr::String& title, int width, int height) {
  138. // Create the window
  139. this->createWindow(title, width, height);
  140. this->windowState = 1;
  141. this->prepareWindow();
  142. }
  143. void Win32Window::createFullscreen() {
  144. // TODO: Implement borderless, decorationless, maximized full-screen
  145. createWindowed("Full-screen is not yet supported on Windows", 800, 600);
  146. this->windowState = 2;
  147. this->prepareWindow();
  148. }
  149. Win32Window::Win32Window(const dsr::String& title, int width, int height) {
  150. bool fullScreen = false;
  151. if (width < 1 || height < 1) {
  152. fullScreen = true;
  153. }
  154. // Remember the title
  155. this->title = title;
  156. // Create a window
  157. if (fullScreen) {
  158. this->createFullscreen();
  159. } else {
  160. this->createWindowed(title, width, height);
  161. }
  162. }
  163. static dsr::DsrKey getDsrKey(WPARAM keyCode) {
  164. dsr::DsrKey result = dsr::DsrKey_Unhandled;
  165. if (keyCode == VK_ESCAPE) {
  166. result = dsr::DsrKey_Escape;
  167. } else if (keyCode == VK_F1) {
  168. result = dsr::DsrKey_F1;
  169. } else if (keyCode == VK_F2) {
  170. result = dsr::DsrKey_F2;
  171. } else if (keyCode == VK_F3) {
  172. result = dsr::DsrKey_F3;
  173. } else if (keyCode == VK_F4) {
  174. result = dsr::DsrKey_F4;
  175. } else if (keyCode == VK_F5) {
  176. result = dsr::DsrKey_F5;
  177. } else if (keyCode == VK_F6) {
  178. result = dsr::DsrKey_F6;
  179. } else if (keyCode == VK_F7) {
  180. result = dsr::DsrKey_F7;
  181. } else if (keyCode == VK_F8) {
  182. result = dsr::DsrKey_F8;
  183. } else if (keyCode == VK_F9) {
  184. result = dsr::DsrKey_F9;
  185. } else if (keyCode == VK_F10) {
  186. result = dsr::DsrKey_F10;
  187. } else if (keyCode == VK_F11) {
  188. result = dsr::DsrKey_F11;
  189. } else if (keyCode == VK_F12) {
  190. result = dsr::DsrKey_F12;
  191. } else if (keyCode == VK_PAUSE) {
  192. result = dsr::DsrKey_Pause;
  193. } else if (keyCode == VK_SPACE) {
  194. result = dsr::DsrKey_Space;
  195. } else if (keyCode == VK_TAB) {
  196. result = dsr::DsrKey_Tab;
  197. } else if (keyCode == VK_RETURN) {
  198. result = dsr::DsrKey_Return;
  199. } else if (keyCode == VK_BACK) {
  200. result = dsr::DsrKey_BackSpace;
  201. } else if (keyCode == VK_LSHIFT) {
  202. result = dsr::DsrKey_LeftShift;
  203. } else if (keyCode == VK_RSHIFT) {
  204. result = dsr::DsrKey_RightShift;
  205. } else if (keyCode == VK_LCONTROL) {
  206. result = dsr::DsrKey_LeftControl;
  207. } else if (keyCode == VK_RCONTROL) {
  208. result = dsr::DsrKey_RightControl;
  209. } else if (keyCode == VK_LMENU) {
  210. result = dsr::DsrKey_LeftAlt;
  211. } else if (keyCode == VK_RMENU) {
  212. result = dsr::DsrKey_RightAlt;
  213. } else if (keyCode == VK_DELETE) {
  214. result = dsr::DsrKey_Delete;
  215. } else if (keyCode == VK_LEFT) {
  216. result = dsr::DsrKey_LeftArrow;
  217. } else if (keyCode == VK_RIGHT) {
  218. result = dsr::DsrKey_RightArrow;
  219. } else if (keyCode == VK_UP) {
  220. result = dsr::DsrKey_UpArrow;
  221. } else if (keyCode == VK_DOWN) {
  222. result = dsr::DsrKey_DownArrow;
  223. } else if (keyCode == 0x30) {
  224. result = dsr::DsrKey_0;
  225. } else if (keyCode == 0x31) {
  226. result = dsr::DsrKey_1;
  227. } else if (keyCode == 0x32) {
  228. result = dsr::DsrKey_2;
  229. } else if (keyCode == 0x33) {
  230. result = dsr::DsrKey_3;
  231. } else if (keyCode == 0x34) {
  232. result = dsr::DsrKey_4;
  233. } else if (keyCode == 0x35) {
  234. result = dsr::DsrKey_5;
  235. } else if (keyCode == 0x36) {
  236. result = dsr::DsrKey_6;
  237. } else if (keyCode == 0x37) {
  238. result = dsr::DsrKey_7;
  239. } else if (keyCode == 0x38) {
  240. result = dsr::DsrKey_8;
  241. } else if (keyCode == 0x39) {
  242. result = dsr::DsrKey_9;
  243. } else if (keyCode == 0x41) {
  244. result = dsr::DsrKey_A;
  245. } else if (keyCode == 0x42) {
  246. result = dsr::DsrKey_B;
  247. } else if (keyCode == 0x43) {
  248. result = dsr::DsrKey_C;
  249. } else if (keyCode == 0x44) {
  250. result = dsr::DsrKey_D;
  251. } else if (keyCode == 0x45) {
  252. result = dsr::DsrKey_E;
  253. } else if (keyCode == 0x46) {
  254. result = dsr::DsrKey_F;
  255. } else if (keyCode == 0x47) {
  256. result = dsr::DsrKey_G;
  257. } else if (keyCode == 0x48) {
  258. result = dsr::DsrKey_H;
  259. } else if (keyCode == 0x49) {
  260. result = dsr::DsrKey_I;
  261. } else if (keyCode == 0x4A) {
  262. result = dsr::DsrKey_J;
  263. } else if (keyCode == 0x4B) {
  264. result = dsr::DsrKey_K;
  265. } else if (keyCode == 0x4C) {
  266. result = dsr::DsrKey_L;
  267. } else if (keyCode == 0x4D) {
  268. result = dsr::DsrKey_M;
  269. } else if (keyCode == 0x4E) {
  270. result = dsr::DsrKey_N;
  271. } else if (keyCode == 0x4F) {
  272. result = dsr::DsrKey_O;
  273. } else if (keyCode == 0x50) {
  274. result = dsr::DsrKey_P;
  275. } else if (keyCode == 0x51) {
  276. result = dsr::DsrKey_Q;
  277. } else if (keyCode == 0x52) {
  278. result = dsr::DsrKey_R;
  279. } else if (keyCode == 0x53) {
  280. result = dsr::DsrKey_S;
  281. } else if (keyCode == 0x54) {
  282. result = dsr::DsrKey_T;
  283. } else if (keyCode == 0x55) {
  284. result = dsr::DsrKey_U;
  285. } else if (keyCode == 0x56) {
  286. result = dsr::DsrKey_V;
  287. } else if (keyCode == 0x57) {
  288. result = dsr::DsrKey_W;
  289. } else if (keyCode == 0x58) {
  290. result = dsr::DsrKey_X;
  291. } else if (keyCode == 0x59) {
  292. result = dsr::DsrKey_Y;
  293. } else if (keyCode == 0x5A) {
  294. result = dsr::DsrKey_Z;
  295. }
  296. return result;
  297. }
  298. // Called from DispatchMessage via prefetchEvents
  299. static LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
  300. // Get the Win32Window owning the given hwnd
  301. Win32Window *parent = nullptr;
  302. if (message == WM_CREATE) {
  303. // Cast the pointer argument into CREATESTRUCT and get the lParam given to the window on creation
  304. CREATESTRUCT *createStruct = (CREATESTRUCT*)lParam;
  305. parent = (Win32Window*)createStruct->lpCreateParams;
  306. if (parent == nullptr) {
  307. dsr::throwError("Null handle retreived from lParam (", (intptr_t)parent, ") in WM_CREATE message.\n");
  308. }
  309. SetWindowLongPtr(hwnd, GWLP_USERDATA, (intptr_t)parent);
  310. } else {
  311. // Get the parent
  312. parent = (Win32Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA);
  313. if (parent == nullptr) {
  314. // Don't try to handle global events unrelated to any window
  315. return DefWindowProc(hwnd, message, wParam, lParam);
  316. }
  317. }
  318. // Check that we're using the correct window instance (This might not be the case while toggling full-screen)
  319. // Handle the message
  320. int result = 0;
  321. switch (message) {
  322. case -1:
  323. dsr::throwError("Unknown error in Window handler!\n");
  324. break;
  325. case WM_QUIT:
  326. PostQuitMessage(wParam);
  327. break;
  328. case WM_CLOSE:
  329. parent->queueInputEvent(new dsr::WindowEvent(dsr::WindowEventType::Close, parent->windowWidth, parent->windowHeight));
  330. DestroyWindow(hwnd);
  331. break;
  332. case WM_LBUTTONDOWN:
  333. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Left, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  334. break;
  335. case WM_LBUTTONUP:
  336. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Left, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  337. break;
  338. case WM_RBUTTONDOWN:
  339. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Right, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  340. break;
  341. case WM_RBUTTONUP:
  342. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Right, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  343. break;
  344. case WM_MBUTTONDOWN:
  345. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseDown, dsr::MouseKeyEnum::Middle, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  346. break;
  347. case WM_MBUTTONUP:
  348. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseUp, dsr::MouseKeyEnum::Middle, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  349. break;
  350. case WM_MOUSEMOVE:
  351. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::MouseMove, dsr::MouseKeyEnum::NoKey, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  352. break;
  353. case WM_MOUSEWHEEL:
  354. {
  355. int delta = GET_WHEEL_DELTA_WPARAM(wParam);
  356. if (delta > 0) {
  357. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollUp, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  358. } else if (delta < 0) {
  359. parent->queueInputEvent(new dsr::MouseEvent(dsr::MouseEventType::Scroll, dsr::MouseKeyEnum::ScrollDown, dsr::IVector2D(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))));
  360. }
  361. }
  362. break;
  363. case WM_KEYDOWN: case WM_KEYUP:
  364. {
  365. char character = wParam; // System specific key-code
  366. dsr::DsrKey dsrKey = getDsrKey(wParam); // Portable key-code
  367. if (message == WM_KEYDOWN) {
  368. // Physical key down
  369. parent->queueInputEvent(new dsr::KeyboardEvent(dsr::KeyboardEventType::KeyDown, character, dsrKey));
  370. // First press typing
  371. parent->queueInputEvent(new dsr::KeyboardEvent(dsr::KeyboardEventType::KeyType, character, dsrKey));
  372. } else { // message == WM_KEYUP
  373. // Physical key up
  374. parent->queueInputEvent(new dsr::KeyboardEvent(dsr::KeyboardEventType::KeyUp, character, dsrKey));
  375. }
  376. }
  377. break;
  378. case WM_PAINT:
  379. parent->queueInputEvent(new dsr::WindowEvent(dsr::WindowEventType::Redraw, parent->windowWidth, parent->windowHeight));
  380. // BeginPaint and EndPaint must be called with the given hwnd to prevent having the redraw message sent again
  381. parent->redraw(hwnd);
  382. // Passing on the event to prevent flooding with more messages. This is only a temporary solution.
  383. // TODO: Avoid overwriting the result with any background color.
  384. //result = DefWindowProc(hwnd, message, wParam, lParam);
  385. break;
  386. case WM_SIZE:
  387. // If there's no size during minimization, don't try to resize the canvas
  388. if (wParam != SIZE_MINIMIZED) {
  389. int width = LOWORD(lParam);
  390. int height = HIWORD(lParam);
  391. parent->windowWidth = width;
  392. parent->windowHeight = height;
  393. parent->receivedWindowResize(width, height);
  394. }
  395. // Resize the window as requested
  396. result = DefWindowProc(hwnd, message, wParam, lParam);
  397. break;
  398. // TODO: Keyboard presses & typing
  399. default:
  400. result = DefWindowProc(hwnd, message, wParam, lParam);
  401. }
  402. return result;
  403. }
  404. void Win32Window::prefetchEvents() {
  405. MSG messages;
  406. // Windows hangs unless we process application events for each window
  407. while (PeekMessage(&messages, NULL, 0, 0, PM_REMOVE)) {
  408. //dsr::printText("Received an event ", messages.message, "(", messages.wParam, ", ", (intptr_t)messages.lParam, ")\n");
  409. TranslateMessage(&messages);
  410. DispatchMessage(&messages); // Calling WindowProcedure for each window instance
  411. }
  412. }
  413. // Locked because it overrides
  414. void Win32Window::resizeCanvas(int width, int height) {
  415. // Create a new canvas
  416. // Even thou Windows is using RGBA pack order for the window, the bitmap format used for drawing is using BGRA order
  417. this->canvas = dsr::image_create_RgbaU8_native(width, height, dsr::PackOrderIndex::BGRA);
  418. }
  419. Win32Window::~Win32Window() {
  420. // Destroy the native window
  421. DestroyWindow(this->hwnd);
  422. }
  423. void Win32Window::redraw(HWND& hwnd) {
  424. // Let the source bitmap use a padded width to safely handle the stride
  425. // Windows require 8-byte alignment, but the image format uses 16-byte alignment.
  426. int paddedWidth = dsr::image_getStride(this->canvas) / 4;
  427. //int width = dsr::image_getWidth(this->canvas);
  428. int height = dsr::image_getHeight(this->canvas);
  429. InvalidateRect(this->hwnd, NULL, false);
  430. PAINTSTRUCT paintStruct;
  431. HDC targetContext = BeginPaint(this->hwnd, &paintStruct);
  432. BITMAPINFO bmi = {};
  433. bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
  434. bmi.bmiHeader.biWidth = paddedWidth;
  435. bmi.bmiHeader.biHeight = -height;
  436. bmi.bmiHeader.biPlanes = 1;
  437. bmi.bmiHeader.biBitCount = 32;
  438. bmi.bmiHeader.biCompression = BI_RGB;
  439. SetDIBitsToDevice(targetContext, 0, 0, paddedWidth, height, 0, 0, 0, height, dsr::image_dangerous_getData(this->canvas), &bmi, DIB_RGB_COLORS);
  440. EndPaint(this->hwnd, &paintStruct);
  441. }
  442. void Win32Window::showCanvas() {
  443. this->prefetchEvents();
  444. this->redraw(this->hwnd);
  445. }
  446. std::shared_ptr<dsr::BackendWindow> createBackendWindow(const dsr::String& title, int width, int height) {
  447. auto backend = std::make_shared<Win32Window>(title, width, height);
  448. return std::dynamic_pointer_cast<dsr::BackendWindow>(backend);
  449. }