SDL_emscriptenvideo.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_VIDEO_DRIVER_EMSCRIPTEN
  20. #include "../SDL_sysvideo.h"
  21. #include "../SDL_pixels_c.h"
  22. #include "../../events/SDL_events_c.h"
  23. #include "SDL_emscriptenvideo.h"
  24. #include "SDL_emscriptenopengles.h"
  25. #include "SDL_emscriptenframebuffer.h"
  26. #include "SDL_emscriptenevents.h"
  27. #include "SDL_emscriptenmouse.h"
  28. #define EMSCRIPTENVID_DRIVER_NAME "emscripten"
  29. // Initialization/Query functions
  30. static bool Emscripten_VideoInit(SDL_VideoDevice *_this);
  31. static bool Emscripten_SetDisplayMode(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_DisplayMode *mode);
  32. static void Emscripten_VideoQuit(SDL_VideoDevice *_this);
  33. static bool Emscripten_GetDisplayUsableBounds(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_Rect *rect);
  34. static bool Emscripten_CreateWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_PropertiesID create_props);
  35. static void Emscripten_SetWindowSize(SDL_VideoDevice *_this, SDL_Window *window);
  36. static void Emscripten_GetWindowSizeInPixels(SDL_VideoDevice *_this, SDL_Window *window, int *w, int *h);
  37. static void Emscripten_DestroyWindow(SDL_VideoDevice *_this, SDL_Window *window);
  38. static SDL_FullscreenResult Emscripten_SetWindowFullscreen(SDL_VideoDevice *_this, SDL_Window *window, SDL_VideoDisplay *display, SDL_FullscreenOp fullscreen);
  39. static void Emscripten_PumpEvents(SDL_VideoDevice *_this);
  40. static void Emscripten_SetWindowTitle(SDL_VideoDevice *_this, SDL_Window *window);
  41. static bool pumpevents_has_run = false;
  42. static int pending_swap_interval = -1;
  43. // Emscripten driver bootstrap functions
  44. static void Emscripten_DeleteDevice(SDL_VideoDevice *device)
  45. {
  46. SDL_free(device);
  47. }
  48. static SDL_SystemTheme Emscripten_GetSystemTheme(void)
  49. {
  50. /* Technically, light theme can mean explicit light theme or no preference.
  51. https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme#syntax */
  52. int theme_code = EM_ASM_INT({
  53. if (!window.matchMedia) {
  54. return -1;
  55. }
  56. if (window.matchMedia('(prefers-color-scheme: light)').matches) {
  57. return 0;
  58. }
  59. if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  60. return 1;
  61. }
  62. return -1;
  63. });
  64. switch (theme_code) {
  65. case 0:
  66. return SDL_SYSTEM_THEME_LIGHT;
  67. case 1:
  68. return SDL_SYSTEM_THEME_DARK;
  69. default:
  70. return SDL_SYSTEM_THEME_UNKNOWN;
  71. }
  72. }
  73. static void Emscripten_ListenSystemTheme(void)
  74. {
  75. MAIN_THREAD_EM_ASM({
  76. if (window.matchMedia) {
  77. if (typeof(Module['SDL3']) === 'undefined') {
  78. Module['SDL3'] = {};
  79. }
  80. var SDL3 = Module['SDL3'];
  81. SDL3.eventHandlerThemeChanged = function(event) {
  82. _Emscripten_SendSystemThemeChangedEvent();
  83. };
  84. SDL3.themeChangedMatchMedia = window.matchMedia('(prefers-color-scheme: dark)');
  85. SDL3.themeChangedMatchMedia.addEventListener('change', SDL3.eventHandlerThemeChanged);
  86. }
  87. });
  88. }
  89. static void Emscripten_UnlistenSystemTheme(void)
  90. {
  91. MAIN_THREAD_EM_ASM({
  92. if (typeof(Module['SDL3']) !== 'undefined') {
  93. var SDL3 = Module['SDL3'];
  94. SDL3.themeChangedMatchMedia.removeEventListener('change', SDL3.eventHandlerThemeChanged);
  95. SDL3.themeChangedMatchMedia = undefined;
  96. SDL3.eventHandlerThemeChanged = undefined;
  97. }
  98. });
  99. }
  100. EMSCRIPTEN_KEEPALIVE void Emscripten_SendSystemThemeChangedEvent(void)
  101. {
  102. SDL_SetSystemTheme(Emscripten_GetSystemTheme());
  103. }
  104. static SDL_VideoDevice *Emscripten_CreateDevice(void)
  105. {
  106. SDL_VideoDevice *device;
  107. // Initialize all variables that we clean on shutdown
  108. device = (SDL_VideoDevice *)SDL_calloc(1, sizeof(SDL_VideoDevice));
  109. if (!device) {
  110. return NULL;
  111. }
  112. /* Firefox sends blur event which would otherwise prevent full screen
  113. * when the user clicks to allow full screen.
  114. * See https://bugzilla.mozilla.org/show_bug.cgi?id=1144964
  115. */
  116. SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
  117. // Set the function pointers
  118. device->VideoInit = Emscripten_VideoInit;
  119. device->VideoQuit = Emscripten_VideoQuit;
  120. device->GetDisplayUsableBounds = Emscripten_GetDisplayUsableBounds;
  121. device->SetDisplayMode = Emscripten_SetDisplayMode;
  122. device->PumpEvents = Emscripten_PumpEvents;
  123. device->CreateSDLWindow = Emscripten_CreateWindow;
  124. device->SetWindowTitle = Emscripten_SetWindowTitle;
  125. /*device->SetWindowIcon = Emscripten_SetWindowIcon;
  126. device->SetWindowPosition = Emscripten_SetWindowPosition;*/
  127. device->SetWindowSize = Emscripten_SetWindowSize;
  128. /*device->ShowWindow = Emscripten_ShowWindow;
  129. device->HideWindow = Emscripten_HideWindow;
  130. device->RaiseWindow = Emscripten_RaiseWindow;
  131. device->MaximizeWindow = Emscripten_MaximizeWindow;
  132. device->MinimizeWindow = Emscripten_MinimizeWindow;
  133. device->RestoreWindow = Emscripten_RestoreWindow;
  134. device->SetWindowMouseGrab = Emscripten_SetWindowMouseGrab;*/
  135. device->GetWindowSizeInPixels = Emscripten_GetWindowSizeInPixels;
  136. device->DestroyWindow = Emscripten_DestroyWindow;
  137. device->SetWindowFullscreen = Emscripten_SetWindowFullscreen;
  138. device->CreateWindowFramebuffer = Emscripten_CreateWindowFramebuffer;
  139. device->UpdateWindowFramebuffer = Emscripten_UpdateWindowFramebuffer;
  140. device->DestroyWindowFramebuffer = Emscripten_DestroyWindowFramebuffer;
  141. device->GL_LoadLibrary = Emscripten_GLES_LoadLibrary;
  142. device->GL_GetProcAddress = Emscripten_GLES_GetProcAddress;
  143. device->GL_UnloadLibrary = Emscripten_GLES_UnloadLibrary;
  144. device->GL_CreateContext = Emscripten_GLES_CreateContext;
  145. device->GL_MakeCurrent = Emscripten_GLES_MakeCurrent;
  146. device->GL_SetSwapInterval = Emscripten_GLES_SetSwapInterval;
  147. device->GL_GetSwapInterval = Emscripten_GLES_GetSwapInterval;
  148. device->GL_SwapWindow = Emscripten_GLES_SwapWindow;
  149. device->GL_DestroyContext = Emscripten_GLES_DestroyContext;
  150. device->free = Emscripten_DeleteDevice;
  151. Emscripten_ListenSystemTheme();
  152. device->system_theme = Emscripten_GetSystemTheme();
  153. return device;
  154. }
  155. VideoBootStrap Emscripten_bootstrap = {
  156. EMSCRIPTENVID_DRIVER_NAME, "SDL emscripten video driver",
  157. Emscripten_CreateDevice,
  158. NULL, // no ShowMessageBox implementation
  159. false
  160. };
  161. bool Emscripten_VideoInit(SDL_VideoDevice *_this)
  162. {
  163. SDL_DisplayMode mode;
  164. // Use a fake 32-bpp desktop mode
  165. SDL_zero(mode);
  166. mode.format = SDL_PIXELFORMAT_XRGB8888;
  167. emscripten_get_screen_size(&mode.w, &mode.h);
  168. mode.pixel_density = emscripten_get_device_pixel_ratio();
  169. if (SDL_AddBasicVideoDisplay(&mode) == 0) {
  170. return false;
  171. }
  172. Emscripten_InitMouse();
  173. // Assume we have a mouse and keyboard
  174. SDL_AddKeyboard(SDL_DEFAULT_KEYBOARD_ID, NULL, false);
  175. SDL_AddMouse(SDL_DEFAULT_MOUSE_ID, NULL, false);
  176. // We're done!
  177. return true;
  178. }
  179. static bool Emscripten_SetDisplayMode(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_DisplayMode *mode)
  180. {
  181. // can't do this
  182. return true;
  183. }
  184. static void Emscripten_VideoQuit(SDL_VideoDevice *_this)
  185. {
  186. Emscripten_QuitMouse();
  187. Emscripten_UnlistenSystemTheme();
  188. pumpevents_has_run = false;
  189. pending_swap_interval = -1;
  190. }
  191. static bool Emscripten_GetDisplayUsableBounds(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_Rect *rect)
  192. {
  193. if (rect) {
  194. rect->x = 0;
  195. rect->y = 0;
  196. rect->w = MAIN_THREAD_EM_ASM_INT({
  197. return window.innerWidth;
  198. });
  199. rect->h = MAIN_THREAD_EM_ASM_INT({
  200. return window.innerHeight;
  201. });
  202. }
  203. return true;
  204. }
  205. bool Emscripten_ShouldSetSwapInterval(int interval)
  206. {
  207. if (!pumpevents_has_run) {
  208. pending_swap_interval = interval;
  209. return false;
  210. }
  211. return true;
  212. }
  213. static void Emscripten_PumpEvents(SDL_VideoDevice *_this)
  214. {
  215. if (!pumpevents_has_run) {
  216. // we assume you've set a mainloop by the time you've called pumpevents, so we delay initial SetInterval changes until then.
  217. // otherwise you'll get a warning on the javascript console.
  218. pumpevents_has_run = true;
  219. if (pending_swap_interval >= 0) {
  220. Emscripten_GLES_SetSwapInterval(_this, pending_swap_interval);
  221. pending_swap_interval = -1;
  222. }
  223. }
  224. }
  225. EMSCRIPTEN_KEEPALIVE void requestFullscreenThroughSDL(SDL_Window *window)
  226. {
  227. SDL_SetWindowFullscreen(window, true);
  228. }
  229. static bool Emscripten_CreateWindow(SDL_VideoDevice *_this, SDL_Window *window, SDL_PropertiesID props)
  230. {
  231. SDL_WindowData *wdata;
  232. double scaled_w, scaled_h;
  233. double css_w, css_h;
  234. const char *selector;
  235. // Allocate window internal data
  236. wdata = (SDL_WindowData *)SDL_calloc(1, sizeof(SDL_WindowData));
  237. if (!wdata) {
  238. return false;
  239. }
  240. selector = SDL_GetHint(SDL_HINT_EMSCRIPTEN_CANVAS_SELECTOR);
  241. if (!selector) {
  242. selector = "#canvas";
  243. }
  244. wdata->canvas_id = SDL_strdup(selector);
  245. if (window->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY) {
  246. wdata->pixel_ratio = emscripten_get_device_pixel_ratio();
  247. } else {
  248. wdata->pixel_ratio = 1.0f;
  249. }
  250. scaled_w = SDL_floor(window->w * wdata->pixel_ratio);
  251. scaled_h = SDL_floor(window->h * wdata->pixel_ratio);
  252. // set a fake size to check if there is any CSS sizing the canvas
  253. emscripten_set_canvas_element_size(wdata->canvas_id, 1, 1);
  254. emscripten_get_element_css_size(wdata->canvas_id, &css_w, &css_h);
  255. wdata->external_size = SDL_floor(css_w) != 1 || SDL_floor(css_h) != 1;
  256. if ((window->flags & SDL_WINDOW_RESIZABLE) && wdata->external_size) {
  257. // external css has resized us
  258. scaled_w = css_w * wdata->pixel_ratio;
  259. scaled_h = css_h * wdata->pixel_ratio;
  260. SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_RESIZED, SDL_lroundf(css_w), SDL_lroundf(css_h));
  261. }
  262. emscripten_set_canvas_element_size(wdata->canvas_id, SDL_lroundf(scaled_w), SDL_lroundf(scaled_h));
  263. // if the size is not being controlled by css, we need to scale down for hidpi
  264. if (!wdata->external_size) {
  265. if (wdata->pixel_ratio != 1.0f) {
  266. // scale canvas down
  267. emscripten_set_element_css_size(wdata->canvas_id, window->w, window->h);
  268. }
  269. }
  270. wdata->window = window;
  271. // Setup driver data for this window
  272. window->internal = wdata;
  273. // One window, it always has focus
  274. SDL_SetMouseFocus(window);
  275. SDL_SetKeyboardFocus(window);
  276. Emscripten_RegisterEventHandlers(wdata);
  277. // disable the emscripten "fullscreen" button.
  278. MAIN_THREAD_EM_ASM({
  279. Module['requestFullscreen'] = function(lockPointer, resizeCanvas) {
  280. _requestFullscreenThroughSDL($0);
  281. };
  282. }, window);
  283. // Window has been successfully created
  284. return true;
  285. }
  286. static void Emscripten_SetWindowSize(SDL_VideoDevice *_this, SDL_Window *window)
  287. {
  288. SDL_WindowData *data;
  289. if (window->internal) {
  290. data = window->internal;
  291. // update pixel ratio
  292. if (window->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY) {
  293. data->pixel_ratio = emscripten_get_device_pixel_ratio();
  294. }
  295. emscripten_set_canvas_element_size(data->canvas_id, SDL_lroundf(window->pending.w * data->pixel_ratio), SDL_lroundf(window->pending.h * data->pixel_ratio));
  296. // scale canvas down
  297. if (!data->external_size && data->pixel_ratio != 1.0f) {
  298. emscripten_set_element_css_size(data->canvas_id, window->pending.w, window->pending.h);
  299. }
  300. SDL_SendWindowEvent(window, SDL_EVENT_WINDOW_RESIZED, window->pending.w, window->pending.h);
  301. }
  302. }
  303. static void Emscripten_GetWindowSizeInPixels(SDL_VideoDevice *_this, SDL_Window *window, int *w, int *h)
  304. {
  305. SDL_WindowData *data;
  306. if (window->internal) {
  307. data = window->internal;
  308. *w = SDL_lroundf(window->w * data->pixel_ratio);
  309. *h = SDL_lroundf(window->h * data->pixel_ratio);
  310. }
  311. }
  312. static void Emscripten_DestroyWindow(SDL_VideoDevice *_this, SDL_Window *window)
  313. {
  314. SDL_WindowData *data;
  315. if (window->internal) {
  316. data = window->internal;
  317. Emscripten_UnregisterEventHandlers(data);
  318. // We can't destroy the canvas, so resize it to zero instead
  319. emscripten_set_canvas_element_size(data->canvas_id, 0, 0);
  320. SDL_free(data->canvas_id);
  321. SDL_free(window->internal);
  322. window->internal = NULL;
  323. }
  324. // just ignore clicks on the fullscreen button while there's no SDL window.
  325. MAIN_THREAD_EM_ASM({ Module['requestFullscreen'] = function(lockPointer, resizeCanvas) {}; });
  326. }
  327. static SDL_FullscreenResult Emscripten_SetWindowFullscreen(SDL_VideoDevice *_this, SDL_Window *window, SDL_VideoDisplay *display, SDL_FullscreenOp fullscreen)
  328. {
  329. SDL_WindowData *data;
  330. int res = -1;
  331. if (window->internal) {
  332. data = window->internal;
  333. if (fullscreen) {
  334. EmscriptenFullscreenStrategy strategy;
  335. bool is_fullscreen_desktop = !window->fullscreen_exclusive;
  336. SDL_zero(strategy);
  337. strategy.scaleMode = is_fullscreen_desktop ? EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH : EMSCRIPTEN_FULLSCREEN_SCALE_ASPECT;
  338. if (!is_fullscreen_desktop) {
  339. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_NONE;
  340. } else if (window->flags & SDL_WINDOW_HIGH_PIXEL_DENSITY) {
  341. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_HIDEF;
  342. } else {
  343. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  344. }
  345. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  346. strategy.canvasResizedCallback = Emscripten_HandleCanvasResize;
  347. strategy.canvasResizedCallbackUserData = data;
  348. data->fullscreen_mode_flags = (window->flags & SDL_WINDOW_FULLSCREEN);
  349. data->fullscreen_resize = is_fullscreen_desktop;
  350. res = emscripten_request_fullscreen_strategy(data->canvas_id, 1, &strategy);
  351. } else {
  352. res = emscripten_exit_fullscreen();
  353. }
  354. }
  355. if (res == EMSCRIPTEN_RESULT_SUCCESS) {
  356. return SDL_FULLSCREEN_SUCCEEDED;
  357. } else if (res == EMSCRIPTEN_RESULT_DEFERRED) {
  358. return SDL_FULLSCREEN_PENDING;
  359. } else {
  360. return SDL_FULLSCREEN_FAILED;
  361. }
  362. }
  363. static void Emscripten_SetWindowTitle(SDL_VideoDevice *_this, SDL_Window *window)
  364. {
  365. emscripten_set_window_title(window->title);
  366. }
  367. #endif // SDL_VIDEO_DRIVER_EMSCRIPTEN