Win32Window.cpp 18 KB

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