Win32Window.cpp 18 KB

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