library_godot_display.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. /*************************************************************************/
  2. /* library_godot_display.js */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. /*
  31. * Display Server listeners.
  32. * Keeps track of registered event listeners so it can remove them on shutdown.
  33. */
  34. const GodotDisplayListeners = {
  35. $GodotDisplayListeners__deps: ['$GodotOS'],
  36. $GodotDisplayListeners__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayListeners.clear(); resolve(); });',
  37. $GodotDisplayListeners: {
  38. handlers: [],
  39. has: function (target, event, method, capture) {
  40. return GodotDisplayListeners.handlers.findIndex(function (e) {
  41. return e.target === target && e.event === event && e.method === method && e.capture === capture;
  42. }) !== -1;
  43. },
  44. add: function (target, event, method, capture) {
  45. if (GodotDisplayListeners.has(target, event, method, capture)) {
  46. return;
  47. }
  48. function Handler(p_target, p_event, p_method, p_capture) {
  49. this.target = p_target;
  50. this.event = p_event;
  51. this.method = p_method;
  52. this.capture = p_capture;
  53. }
  54. GodotDisplayListeners.handlers.push(new Handler(target, event, method, capture));
  55. target.addEventListener(event, method, capture);
  56. },
  57. clear: function () {
  58. GodotDisplayListeners.handlers.forEach(function (h) {
  59. h.target.removeEventListener(h.event, h.method, h.capture);
  60. });
  61. GodotDisplayListeners.handlers.length = 0;
  62. },
  63. },
  64. };
  65. mergeInto(LibraryManager.library, GodotDisplayListeners);
  66. /*
  67. * Drag and drop handler.
  68. * This is pretty big, but basically detect dropped files on GodotConfig.canvas,
  69. * process them one by one (recursively for directories), and copies them to
  70. * the temporary FS path '/tmp/drop-[random]/' so it can be emitted as a godot
  71. * event (that requires a string array of paths).
  72. *
  73. * NOTE: The temporary files are removed after the callback. This means that
  74. * deferred callbacks won't be able to access the files.
  75. */
  76. const GodotDisplayDragDrop = {
  77. $GodotDisplayDragDrop__deps: ['$FS', '$GodotFS'],
  78. $GodotDisplayDragDrop: {
  79. promises: [],
  80. pending_files: [],
  81. add_entry: function (entry) {
  82. if (entry.isDirectory) {
  83. GodotDisplayDragDrop.add_dir(entry);
  84. } else if (entry.isFile) {
  85. GodotDisplayDragDrop.add_file(entry);
  86. } else {
  87. GodotRuntime.error('Unrecognized entry...', entry);
  88. }
  89. },
  90. add_dir: function (entry) {
  91. GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) {
  92. const reader = entry.createReader();
  93. reader.readEntries(function (entries) {
  94. for (let i = 0; i < entries.length; i++) {
  95. GodotDisplayDragDrop.add_entry(entries[i]);
  96. }
  97. resolve();
  98. });
  99. }));
  100. },
  101. add_file: function (entry) {
  102. GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) {
  103. entry.file(function (file) {
  104. const reader = new FileReader();
  105. reader.onload = function () {
  106. const f = {
  107. 'path': file.relativePath || file.webkitRelativePath,
  108. 'name': file.name,
  109. 'type': file.type,
  110. 'size': file.size,
  111. 'data': reader.result,
  112. };
  113. if (!f['path']) {
  114. f['path'] = f['name'];
  115. }
  116. GodotDisplayDragDrop.pending_files.push(f);
  117. resolve();
  118. };
  119. reader.onerror = function () {
  120. GodotRuntime.print('Error reading file');
  121. reject();
  122. };
  123. reader.readAsArrayBuffer(file);
  124. }, function (err) {
  125. GodotRuntime.print('Error!');
  126. reject();
  127. });
  128. }));
  129. },
  130. process: function (resolve, reject) {
  131. if (GodotDisplayDragDrop.promises.length === 0) {
  132. resolve();
  133. return;
  134. }
  135. GodotDisplayDragDrop.promises.pop().then(function () {
  136. setTimeout(function () {
  137. GodotDisplayDragDrop.process(resolve, reject);
  138. }, 0);
  139. });
  140. },
  141. _process_event: function (ev, callback) {
  142. ev.preventDefault();
  143. if (ev.dataTransfer.items) {
  144. // Use DataTransferItemList interface to access the file(s)
  145. for (let i = 0; i < ev.dataTransfer.items.length; i++) {
  146. const item = ev.dataTransfer.items[i];
  147. let entry = null;
  148. if ('getAsEntry' in item) {
  149. entry = item.getAsEntry();
  150. } else if ('webkitGetAsEntry' in item) {
  151. entry = item.webkitGetAsEntry();
  152. }
  153. if (entry) {
  154. GodotDisplayDragDrop.add_entry(entry);
  155. }
  156. }
  157. } else {
  158. GodotRuntime.error('File upload not supported');
  159. }
  160. new Promise(GodotDisplayDragDrop.process).then(function () {
  161. const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
  162. const drops = [];
  163. const files = [];
  164. FS.mkdir(DROP);
  165. GodotDisplayDragDrop.pending_files.forEach((elem) => {
  166. const path = elem['path'];
  167. GodotFS.copy_to_fs(DROP + path, elem['data']);
  168. let idx = path.indexOf('/');
  169. if (idx === -1) {
  170. // Root file
  171. drops.push(DROP + path);
  172. } else {
  173. // Subdir
  174. const sub = path.substr(0, idx);
  175. idx = sub.indexOf('/');
  176. if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
  177. drops.push(DROP + sub);
  178. }
  179. }
  180. files.push(DROP + path);
  181. });
  182. GodotDisplayDragDrop.promises = [];
  183. GodotDisplayDragDrop.pending_files = [];
  184. callback(drops);
  185. if (GodotConfig.persistent_drops) {
  186. // Delay removal at exit.
  187. GodotOS.atexit(function (resolve, reject) {
  188. GodotDisplayDragDrop.remove_drop(files, DROP);
  189. resolve();
  190. });
  191. } else {
  192. GodotDisplayDragDrop.remove_drop(files, DROP);
  193. }
  194. });
  195. },
  196. remove_drop: function (files, drop_path) {
  197. const dirs = [drop_path.substr(0, drop_path.length - 1)];
  198. // Remove temporary files
  199. files.forEach(function (file) {
  200. FS.unlink(file);
  201. let dir = file.replace(drop_path, '');
  202. let idx = dir.lastIndexOf('/');
  203. while (idx > 0) {
  204. dir = dir.substr(0, idx);
  205. if (dirs.indexOf(drop_path + dir) === -1) {
  206. dirs.push(drop_path + dir);
  207. }
  208. idx = dir.lastIndexOf('/');
  209. }
  210. });
  211. // Remove dirs.
  212. dirs.sort(function (a, b) {
  213. const al = (a.match(/\//g) || []).length;
  214. const bl = (b.match(/\//g) || []).length;
  215. if (al > bl) {
  216. return -1;
  217. } else if (al < bl) {
  218. return 1;
  219. }
  220. return 0;
  221. }).forEach(function (dir) {
  222. FS.rmdir(dir);
  223. });
  224. },
  225. handler: function (callback) {
  226. return function (ev) {
  227. GodotDisplayDragDrop._process_event(ev, callback);
  228. };
  229. },
  230. },
  231. };
  232. mergeInto(LibraryManager.library, GodotDisplayDragDrop);
  233. const GodotDisplayVK = {
  234. $GodotDisplayVK__deps: ['$GodotRuntime', '$GodotConfig', '$GodotDisplayListeners'],
  235. $GodotDisplayVK__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayVK.clear(); resolve(); });',
  236. $GodotDisplayVK: {
  237. textinput: null,
  238. textarea: null,
  239. available: function () {
  240. return GodotConfig.virtual_keyboard && 'ontouchstart' in window;
  241. },
  242. init: function (input_cb) {
  243. function create(what) {
  244. const elem = document.createElement(what);
  245. elem.style.display = 'none';
  246. elem.style.position = 'absolute';
  247. elem.style.zIndex = '-1';
  248. elem.style.background = 'transparent';
  249. elem.style.padding = '0px';
  250. elem.style.margin = '0px';
  251. elem.style.overflow = 'hidden';
  252. elem.style.width = '0px';
  253. elem.style.height = '0px';
  254. elem.style.border = '0px';
  255. elem.style.outline = 'none';
  256. elem.readonly = true;
  257. elem.disabled = true;
  258. GodotDisplayListeners.add(elem, 'input', function (evt) {
  259. const c_str = GodotRuntime.allocString(elem.value);
  260. input_cb(c_str, elem.selectionEnd);
  261. GodotRuntime.free(c_str);
  262. }, false);
  263. GodotDisplayListeners.add(elem, 'blur', function (evt) {
  264. elem.style.display = 'none';
  265. elem.readonly = true;
  266. elem.disabled = true;
  267. }, false);
  268. GodotConfig.canvas.insertAdjacentElement('beforebegin', elem);
  269. return elem;
  270. }
  271. GodotDisplayVK.textinput = create('input');
  272. GodotDisplayVK.textarea = create('textarea');
  273. GodotDisplayVK.updateSize();
  274. },
  275. show: function (text, multiline, start, end) {
  276. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  277. return;
  278. }
  279. if (GodotDisplayVK.textinput.style.display !== '' || GodotDisplayVK.textarea.style.display !== '') {
  280. GodotDisplayVK.hide();
  281. }
  282. GodotDisplayVK.updateSize();
  283. const elem = multiline ? GodotDisplayVK.textarea : GodotDisplayVK.textinput;
  284. elem.readonly = false;
  285. elem.disabled = false;
  286. elem.value = text;
  287. elem.style.display = 'block';
  288. elem.focus();
  289. elem.setSelectionRange(start, end);
  290. },
  291. hide: function () {
  292. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  293. return;
  294. }
  295. [GodotDisplayVK.textinput, GodotDisplayVK.textarea].forEach(function (elem) {
  296. elem.blur();
  297. elem.style.display = 'none';
  298. elem.value = '';
  299. });
  300. },
  301. updateSize: function () {
  302. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  303. return;
  304. }
  305. const rect = GodotConfig.canvas.getBoundingClientRect();
  306. function update(elem) {
  307. elem.style.left = `${rect.left}px`;
  308. elem.style.top = `${rect.top}px`;
  309. elem.style.width = `${rect.width}px`;
  310. elem.style.height = `${rect.height}px`;
  311. }
  312. update(GodotDisplayVK.textinput);
  313. update(GodotDisplayVK.textarea);
  314. },
  315. clear: function () {
  316. if (GodotDisplayVK.textinput) {
  317. GodotDisplayVK.textinput.remove();
  318. GodotDisplayVK.textinput = null;
  319. }
  320. if (GodotDisplayVK.textarea) {
  321. GodotDisplayVK.textarea.remove();
  322. GodotDisplayVK.textarea = null;
  323. }
  324. },
  325. },
  326. };
  327. mergeInto(LibraryManager.library, GodotDisplayVK);
  328. /*
  329. * Display server cursor helper.
  330. * Keeps track of cursor status and custom shapes.
  331. */
  332. const GodotDisplayCursor = {
  333. $GodotDisplayCursor__deps: ['$GodotOS', '$GodotConfig'],
  334. $GodotDisplayCursor__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayCursor.clear(); resolve(); });',
  335. $GodotDisplayCursor: {
  336. shape: 'auto',
  337. visible: true,
  338. cursors: {},
  339. set_style: function (style) {
  340. GodotConfig.canvas.style.cursor = style;
  341. },
  342. set_shape: function (shape) {
  343. GodotDisplayCursor.shape = shape;
  344. let css = shape;
  345. if (shape in GodotDisplayCursor.cursors) {
  346. const c = GodotDisplayCursor.cursors[shape];
  347. css = `url("${c.url}") ${c.x} ${c.y}, auto`;
  348. }
  349. if (GodotDisplayCursor.visible) {
  350. GodotDisplayCursor.set_style(css);
  351. }
  352. },
  353. clear: function () {
  354. GodotDisplayCursor.set_style('');
  355. GodotDisplayCursor.shape = 'auto';
  356. GodotDisplayCursor.visible = true;
  357. Object.keys(GodotDisplayCursor.cursors).forEach(function (key) {
  358. URL.revokeObjectURL(GodotDisplayCursor.cursors[key]);
  359. delete GodotDisplayCursor.cursors[key];
  360. });
  361. },
  362. },
  363. };
  364. mergeInto(LibraryManager.library, GodotDisplayCursor);
  365. /*
  366. * Display Gamepad API helper.
  367. */
  368. const GodotDisplayGamepads = {
  369. $GodotDisplayGamepads__deps: ['$GodotRuntime', '$GodotDisplayListeners'],
  370. $GodotDisplayGamepads: {
  371. samples: [],
  372. get_pads: function () {
  373. try {
  374. // Will throw in iframe when permission is denied.
  375. // Will throw/warn in the future for insecure contexts.
  376. // See https://github.com/w3c/gamepad/pull/120
  377. const pads = navigator.getGamepads();
  378. if (pads) {
  379. return pads;
  380. }
  381. return [];
  382. } catch (e) {
  383. return [];
  384. }
  385. },
  386. get_samples: function () {
  387. return GodotDisplayGamepads.samples;
  388. },
  389. get_sample: function (index) {
  390. const samples = GodotDisplayGamepads.samples;
  391. return index < samples.length ? samples[index] : null;
  392. },
  393. sample: function () {
  394. const pads = GodotDisplayGamepads.get_pads();
  395. const samples = [];
  396. for (let i = 0; i < pads.length; i++) {
  397. const pad = pads[i];
  398. if (!pad) {
  399. samples.push(null);
  400. continue;
  401. }
  402. const s = {
  403. standard: pad.mapping === 'standard',
  404. buttons: [],
  405. axes: [],
  406. connected: pad.connected,
  407. };
  408. for (let b = 0; b < pad.buttons.length; b++) {
  409. s.buttons.push(pad.buttons[b].value);
  410. }
  411. for (let a = 0; a < pad.axes.length; a++) {
  412. s.axes.push(pad.axes[a]);
  413. }
  414. samples.push(s);
  415. }
  416. GodotDisplayGamepads.samples = samples;
  417. },
  418. init: function (onchange) {
  419. GodotDisplayListeners.samples = [];
  420. function add(pad) {
  421. const guid = GodotDisplayGamepads.get_guid(pad);
  422. const c_id = GodotRuntime.allocString(pad.id);
  423. const c_guid = GodotRuntime.allocString(guid);
  424. onchange(pad.index, 1, c_id, c_guid);
  425. GodotRuntime.free(c_id);
  426. GodotRuntime.free(c_guid);
  427. }
  428. const pads = GodotDisplayGamepads.get_pads();
  429. for (let i = 0; i < pads.length; i++) {
  430. // Might be reserved space.
  431. if (pads[i]) {
  432. add(pads[i]);
  433. }
  434. }
  435. GodotDisplayListeners.add(window, 'gamepadconnected', function (evt) {
  436. add(evt.gamepad);
  437. }, false);
  438. GodotDisplayListeners.add(window, 'gamepaddisconnected', function (evt) {
  439. onchange(evt.gamepad.index, 0);
  440. }, false);
  441. },
  442. get_guid: function (pad) {
  443. if (pad.mapping) {
  444. return pad.mapping;
  445. }
  446. const ua = navigator.userAgent;
  447. let os = 'Unknown';
  448. if (ua.indexOf('Android') >= 0) {
  449. os = 'Android';
  450. } else if (ua.indexOf('Linux') >= 0) {
  451. os = 'Linux';
  452. } else if (ua.indexOf('iPhone') >= 0) {
  453. os = 'iOS';
  454. } else if (ua.indexOf('Macintosh') >= 0) {
  455. // Updated iPads will fall into this category.
  456. os = 'MacOSX';
  457. } else if (ua.indexOf('Windows') >= 0) {
  458. os = 'Windows';
  459. }
  460. const id = pad.id;
  461. // Chrom* style: NAME (Vendor: xxxx Product: xxxx)
  462. const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i;
  463. // Firefox/Safari style (safari may remove leading zeores)
  464. const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i;
  465. let vendor = '';
  466. let product = '';
  467. if (exp1.test(id)) {
  468. const match = exp1.exec(id);
  469. vendor = match[1].padStart(4, '0');
  470. product = match[2].padStart(4, '0');
  471. } else if (exp2.test(id)) {
  472. const match = exp2.exec(id);
  473. vendor = match[1].padStart(4, '0');
  474. product = match[2].padStart(4, '0');
  475. }
  476. if (!vendor || !product) {
  477. return `${os}Unknown`;
  478. }
  479. return os + vendor + product;
  480. },
  481. },
  482. };
  483. mergeInto(LibraryManager.library, GodotDisplayGamepads);
  484. const GodotDisplayScreen = {
  485. $GodotDisplayScreen__deps: ['$GodotConfig', '$GodotOS', '$GL', 'emscripten_webgl_get_current_context'],
  486. $GodotDisplayScreen: {
  487. desired_size: [0, 0],
  488. hidpi: true,
  489. getPixelRatio: function () {
  490. return GodotDisplayScreen.hidpi ? window.devicePixelRatio || 1 : 1;
  491. },
  492. isFullscreen: function () {
  493. const elem = document.fullscreenElement || document.mozFullscreenElement
  494. || document.webkitFullscreenElement || document.msFullscreenElement;
  495. if (elem) {
  496. return elem === GodotConfig.canvas;
  497. }
  498. // But maybe knowing the element is not supported.
  499. return document.fullscreen || document.mozFullScreen
  500. || document.webkitIsFullscreen;
  501. },
  502. hasFullscreen: function () {
  503. return document.fullscreenEnabled || document.mozFullScreenEnabled
  504. || document.webkitFullscreenEnabled;
  505. },
  506. requestFullscreen: function () {
  507. if (!GodotDisplayScreen.hasFullscreen()) {
  508. return 1;
  509. }
  510. const canvas = GodotConfig.canvas;
  511. try {
  512. const promise = (canvas.requestFullscreen || canvas.msRequestFullscreen
  513. || canvas.mozRequestFullScreen || canvas.mozRequestFullscreen
  514. || canvas.webkitRequestFullscreen
  515. ).call(canvas);
  516. // Some browsers (Safari) return undefined.
  517. // For the standard ones, we need to catch it.
  518. if (promise) {
  519. promise.catch(function () {
  520. // nothing to do.
  521. });
  522. }
  523. } catch (e) {
  524. return 1;
  525. }
  526. return 0;
  527. },
  528. exitFullscreen: function () {
  529. if (!GodotDisplayScreen.isFullscreen()) {
  530. return 0;
  531. }
  532. try {
  533. const promise = document.exitFullscreen();
  534. if (promise) {
  535. promise.catch(function () {
  536. // nothing to do.
  537. });
  538. }
  539. } catch (e) {
  540. return 1;
  541. }
  542. return 0;
  543. },
  544. _updateGL: function () {
  545. const gl_context_handle = _emscripten_webgl_get_current_context(); // eslint-disable-line no-undef
  546. const gl = GL.getContext(gl_context_handle);
  547. if (gl) {
  548. GL.resizeOffscreenFramebuffer(gl);
  549. }
  550. },
  551. updateSize: function () {
  552. const isFullscreen = GodotDisplayScreen.isFullscreen();
  553. const wantsFullWindow = GodotConfig.canvas_resize_policy === 2;
  554. const noResize = GodotConfig.canvas_resize_policy === 0;
  555. const wwidth = GodotDisplayScreen.desired_size[0];
  556. const wheight = GodotDisplayScreen.desired_size[1];
  557. const canvas = GodotConfig.canvas;
  558. let width = wwidth;
  559. let height = wheight;
  560. if (noResize) {
  561. // Don't resize canvas, just update GL if needed.
  562. if (canvas.width !== width || canvas.height !== height) {
  563. GodotDisplayScreen.desired_size = [canvas.width, canvas.height];
  564. GodotDisplayScreen._updateGL();
  565. return 1;
  566. }
  567. return 0;
  568. }
  569. const scale = GodotDisplayScreen.getPixelRatio();
  570. if (isFullscreen || wantsFullWindow) {
  571. // We need to match screen size.
  572. width = window.innerWidth * scale;
  573. height = window.innerHeight * scale;
  574. }
  575. const csw = `${width / scale}px`;
  576. const csh = `${height / scale}px`;
  577. if (canvas.style.width !== csw || canvas.style.height !== csh || canvas.width !== width || canvas.height !== height) {
  578. // Size doesn't match.
  579. // Resize canvas, set correct CSS pixel size, update GL.
  580. canvas.width = width;
  581. canvas.height = height;
  582. canvas.style.width = csw;
  583. canvas.style.height = csh;
  584. GodotDisplayScreen._updateGL();
  585. return 1;
  586. }
  587. return 0;
  588. },
  589. },
  590. };
  591. mergeInto(LibraryManager.library, GodotDisplayScreen);
  592. /**
  593. * Display server interface.
  594. *
  595. * Exposes all the functions needed by DisplayServer implementation.
  596. */
  597. const GodotDisplay = {
  598. $GodotDisplay__deps: ['$GodotConfig', '$GodotRuntime', '$GodotDisplayCursor', '$GodotDisplayListeners', '$GodotDisplayDragDrop', '$GodotDisplayGamepads', '$GodotDisplayScreen', '$GodotDisplayVK'],
  599. $GodotDisplay: {
  600. window_icon: '',
  601. findDPI: function () {
  602. function testDPI(dpi) {
  603. return window.matchMedia(`(max-resolution: ${dpi}dpi)`).matches;
  604. }
  605. function bisect(low, high, func) {
  606. const mid = parseInt(((high - low) / 2) + low, 10);
  607. if (high - low <= 1) {
  608. return func(high) ? high : low;
  609. }
  610. if (func(mid)) {
  611. return bisect(low, mid, func);
  612. }
  613. return bisect(mid, high, func);
  614. }
  615. try {
  616. const dpi = bisect(0, 800, testDPI);
  617. return dpi >= 96 ? dpi : 96;
  618. } catch (e) {
  619. return 96;
  620. }
  621. },
  622. },
  623. godot_js_display_is_swap_ok_cancel__sig: 'i',
  624. godot_js_display_is_swap_ok_cancel: function () {
  625. const win = (['Windows', 'Win64', 'Win32', 'WinCE']);
  626. const plat = navigator.platform || '';
  627. if (win.indexOf(plat) !== -1) {
  628. return 1;
  629. }
  630. return 0;
  631. },
  632. godot_js_display_alert__sig: 'vi',
  633. godot_js_display_alert: function (p_text) {
  634. window.alert(GodotRuntime.parseString(p_text)); // eslint-disable-line no-alert
  635. },
  636. godot_js_display_screen_dpi_get__sig: 'i',
  637. godot_js_display_screen_dpi_get: function () {
  638. return GodotDisplay.findDPI();
  639. },
  640. godot_js_display_pixel_ratio_get__sig: 'f',
  641. godot_js_display_pixel_ratio_get: function () {
  642. return GodotDisplayScreen.getPixelRatio();
  643. },
  644. godot_js_display_fullscreen_request__sig: 'i',
  645. godot_js_display_fullscreen_request: function () {
  646. return GodotDisplayScreen.requestFullscreen();
  647. },
  648. godot_js_display_fullscreen_exit__sig: 'i',
  649. godot_js_display_fullscreen_exit: function () {
  650. return GodotDisplayScreen.exitFullscreen();
  651. },
  652. godot_js_display_desired_size_set__sig: 'v',
  653. godot_js_display_desired_size_set: function (width, height) {
  654. GodotDisplayScreen.desired_size = [width, height];
  655. GodotDisplayScreen.updateSize();
  656. },
  657. godot_js_display_size_update__sig: 'i',
  658. godot_js_display_size_update: function () {
  659. const updated = GodotDisplayScreen.updateSize();
  660. if (updated) {
  661. GodotDisplayVK.updateSize();
  662. }
  663. return updated;
  664. },
  665. godot_js_display_screen_size_get__sig: 'vii',
  666. godot_js_display_screen_size_get: function (width, height) {
  667. const scale = GodotDisplayScreen.getPixelRatio();
  668. GodotRuntime.setHeapValue(width, window.screen.width * scale, 'i32');
  669. GodotRuntime.setHeapValue(height, window.screen.height * scale, 'i32');
  670. },
  671. godot_js_display_window_size_get: function (p_width, p_height) {
  672. GodotRuntime.setHeapValue(p_width, GodotConfig.canvas.width, 'i32');
  673. GodotRuntime.setHeapValue(p_height, GodotConfig.canvas.height, 'i32');
  674. },
  675. godot_js_display_compute_position: function (x, y, r_x, r_y) {
  676. const canvas = GodotConfig.canvas;
  677. const rect = canvas.getBoundingClientRect();
  678. const rw = canvas.width / rect.width;
  679. const rh = canvas.height / rect.height;
  680. GodotRuntime.setHeapValue(r_x, (x - rect.x) * rw, 'i32');
  681. GodotRuntime.setHeapValue(r_y, (y - rect.y) * rh, 'i32');
  682. },
  683. /*
  684. * Canvas
  685. */
  686. godot_js_display_canvas_focus__sig: 'v',
  687. godot_js_display_canvas_focus: function () {
  688. GodotConfig.canvas.focus();
  689. },
  690. godot_js_display_canvas_is_focused__sig: 'i',
  691. godot_js_display_canvas_is_focused: function () {
  692. return document.activeElement === GodotConfig.canvas;
  693. },
  694. /*
  695. * Touchscreen
  696. */
  697. godot_js_display_touchscreen_is_available__sig: 'i',
  698. godot_js_display_touchscreen_is_available: function () {
  699. return 'ontouchstart' in window;
  700. },
  701. /*
  702. * Clipboard
  703. */
  704. godot_js_display_clipboard_set__sig: 'ii',
  705. godot_js_display_clipboard_set: function (p_text) {
  706. const text = GodotRuntime.parseString(p_text);
  707. if (!navigator.clipboard || !navigator.clipboard.writeText) {
  708. return 1;
  709. }
  710. navigator.clipboard.writeText(text).catch(function (e) {
  711. // Setting OS clipboard is only possible from an input callback.
  712. GodotRuntime.error('Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:', e);
  713. });
  714. return 0;
  715. },
  716. godot_js_display_clipboard_get__sig: 'ii',
  717. godot_js_display_clipboard_get: function (callback) {
  718. const func = GodotRuntime.get_func(callback);
  719. try {
  720. navigator.clipboard.readText().then(function (result) {
  721. const ptr = GodotRuntime.allocString(result);
  722. func(ptr);
  723. GodotRuntime.free(ptr);
  724. }).catch(function (e) {
  725. // Fail graciously.
  726. });
  727. } catch (e) {
  728. // Fail graciously.
  729. }
  730. },
  731. /*
  732. * Window
  733. */
  734. godot_js_display_window_title_set__sig: 'vi',
  735. godot_js_display_window_title_set: function (p_data) {
  736. document.title = GodotRuntime.parseString(p_data);
  737. },
  738. godot_js_display_window_icon_set__sig: 'vii',
  739. godot_js_display_window_icon_set: function (p_ptr, p_len) {
  740. let link = document.getElementById('-gd-engine-icon');
  741. if (link === null) {
  742. link = document.createElement('link');
  743. link.rel = 'icon';
  744. link.id = '-gd-engine-icon';
  745. document.head.appendChild(link);
  746. }
  747. const old_icon = GodotDisplay.window_icon;
  748. const png = new Blob([GodotRuntime.heapSlice(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
  749. GodotDisplay.window_icon = URL.createObjectURL(png);
  750. link.href = GodotDisplay.window_icon;
  751. if (old_icon) {
  752. URL.revokeObjectURL(old_icon);
  753. }
  754. },
  755. /*
  756. * Cursor
  757. */
  758. godot_js_display_cursor_set_visible__sig: 'vi',
  759. godot_js_display_cursor_set_visible: function (p_visible) {
  760. const visible = p_visible !== 0;
  761. if (visible === GodotDisplayCursor.visible) {
  762. return;
  763. }
  764. GodotDisplayCursor.visible = visible;
  765. if (visible) {
  766. GodotDisplayCursor.set_shape(GodotDisplayCursor.shape);
  767. } else {
  768. GodotDisplayCursor.set_style('none');
  769. }
  770. },
  771. godot_js_display_cursor_is_hidden__sig: 'i',
  772. godot_js_display_cursor_is_hidden: function () {
  773. return !GodotDisplayCursor.visible;
  774. },
  775. godot_js_display_cursor_set_shape__sig: 'vi',
  776. godot_js_display_cursor_set_shape: function (p_string) {
  777. GodotDisplayCursor.set_shape(GodotRuntime.parseString(p_string));
  778. },
  779. godot_js_display_cursor_set_custom_shape__sig: 'viiiii',
  780. godot_js_display_cursor_set_custom_shape: function (p_shape, p_ptr, p_len, p_hotspot_x, p_hotspot_y) {
  781. const shape = GodotRuntime.parseString(p_shape);
  782. const old_shape = GodotDisplayCursor.cursors[shape];
  783. if (p_len > 0) {
  784. const png = new Blob([GodotRuntime.heapSlice(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
  785. const url = URL.createObjectURL(png);
  786. GodotDisplayCursor.cursors[shape] = {
  787. url: url,
  788. x: p_hotspot_x,
  789. y: p_hotspot_y,
  790. };
  791. } else {
  792. delete GodotDisplayCursor.cursors[shape];
  793. }
  794. if (shape === GodotDisplayCursor.shape) {
  795. GodotDisplayCursor.set_shape(GodotDisplayCursor.shape);
  796. }
  797. if (old_shape) {
  798. URL.revokeObjectURL(old_shape.url);
  799. }
  800. },
  801. /*
  802. * Listeners
  803. */
  804. godot_js_display_notification_cb__sig: 'viiiii',
  805. godot_js_display_notification_cb: function (callback, p_enter, p_exit, p_in, p_out) {
  806. const canvas = GodotConfig.canvas;
  807. const func = GodotRuntime.get_func(callback);
  808. const notif = [p_enter, p_exit, p_in, p_out];
  809. ['mouseover', 'mouseleave', 'focus', 'blur'].forEach(function (evt_name, idx) {
  810. GodotDisplayListeners.add(canvas, evt_name, function () {
  811. func(notif[idx]);
  812. }, true);
  813. });
  814. },
  815. godot_js_display_paste_cb__sig: 'vi',
  816. godot_js_display_paste_cb: function (callback) {
  817. const func = GodotRuntime.get_func(callback);
  818. GodotDisplayListeners.add(window, 'paste', function (evt) {
  819. const text = evt.clipboardData.getData('text');
  820. const ptr = GodotRuntime.allocString(text);
  821. func(ptr);
  822. GodotRuntime.free(ptr);
  823. }, false);
  824. },
  825. godot_js_display_drop_files_cb__sig: 'vi',
  826. godot_js_display_drop_files_cb: function (callback) {
  827. const func = GodotRuntime.get_func(callback);
  828. const dropFiles = function (files) {
  829. const args = files || [];
  830. if (!args.length) {
  831. return;
  832. }
  833. const argc = args.length;
  834. const argv = GodotRuntime.allocStringArray(args);
  835. func(argv, argc);
  836. GodotRuntime.freeStringArray(argv, argc);
  837. };
  838. const canvas = GodotConfig.canvas;
  839. GodotDisplayListeners.add(canvas, 'dragover', function (ev) {
  840. // Prevent default behavior (which would try to open the file(s))
  841. ev.preventDefault();
  842. }, false);
  843. GodotDisplayListeners.add(canvas, 'drop', GodotDisplayDragDrop.handler(dropFiles));
  844. },
  845. godot_js_display_setup_canvas__sig: 'viiii',
  846. godot_js_display_setup_canvas: function (p_width, p_height, p_fullscreen, p_hidpi) {
  847. const canvas = GodotConfig.canvas;
  848. GodotDisplayListeners.add(canvas, 'contextmenu', function (ev) {
  849. ev.preventDefault();
  850. }, false);
  851. GodotDisplayListeners.add(canvas, 'webglcontextlost', function (ev) {
  852. alert('WebGL context lost, please reload the page'); // eslint-disable-line no-alert
  853. ev.preventDefault();
  854. }, false);
  855. GodotDisplayScreen.hidpi = !!p_hidpi;
  856. switch (GodotConfig.canvas_resize_policy) {
  857. case 0: // None
  858. GodotDisplayScreen.desired_size = [canvas.width, canvas.height];
  859. break;
  860. case 1: // Project
  861. GodotDisplayScreen.desired_size = [p_width, p_height];
  862. break;
  863. default: // Full window
  864. // Ensure we display in the right place, the size will be handled by updateSize
  865. canvas.style.position = 'absolute';
  866. canvas.style.top = 0;
  867. canvas.style.left = 0;
  868. break;
  869. }
  870. GodotDisplayScreen.updateSize();
  871. if (p_fullscreen) {
  872. GodotDisplayScreen.requestFullscreen();
  873. }
  874. },
  875. /*
  876. * Virtual Keyboard
  877. */
  878. godot_js_display_vk_show__sig: 'viiii',
  879. godot_js_display_vk_show: function (p_text, p_multiline, p_start, p_end) {
  880. const text = GodotRuntime.parseString(p_text);
  881. const start = p_start > 0 ? p_start : 0;
  882. const end = p_end > 0 ? p_end : start;
  883. GodotDisplayVK.show(text, p_multiline, start, end);
  884. },
  885. godot_js_display_vk_hide__sig: 'v',
  886. godot_js_display_vk_hide: function () {
  887. GodotDisplayVK.hide();
  888. },
  889. godot_js_display_vk_available__sig: 'i',
  890. godot_js_display_vk_available: function () {
  891. return GodotDisplayVK.available();
  892. },
  893. godot_js_display_vk_cb__sig: 'vi',
  894. godot_js_display_vk_cb: function (p_input_cb) {
  895. const input_cb = GodotRuntime.get_func(p_input_cb);
  896. if (GodotDisplayVK.available()) {
  897. GodotDisplayVK.init(input_cb);
  898. }
  899. },
  900. /*
  901. * Gamepads
  902. */
  903. godot_js_display_gamepad_cb__sig: 'vi',
  904. godot_js_display_gamepad_cb: function (change_cb) {
  905. const onchange = GodotRuntime.get_func(change_cb);
  906. GodotDisplayGamepads.init(onchange);
  907. },
  908. godot_js_display_gamepad_sample_count__sig: 'i',
  909. godot_js_display_gamepad_sample_count: function () {
  910. return GodotDisplayGamepads.get_samples().length;
  911. },
  912. godot_js_display_gamepad_sample__sig: 'i',
  913. godot_js_display_gamepad_sample: function () {
  914. GodotDisplayGamepads.sample();
  915. return 0;
  916. },
  917. godot_js_display_gamepad_sample_get__sig: 'iiiiiii',
  918. godot_js_display_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) {
  919. const sample = GodotDisplayGamepads.get_sample(p_index);
  920. if (!sample || !sample.connected) {
  921. return 1;
  922. }
  923. const btns = sample.buttons;
  924. const btns_len = btns.length < 16 ? btns.length : 16;
  925. for (let i = 0; i < btns_len; i++) {
  926. GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float');
  927. }
  928. GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32');
  929. const axes = sample.axes;
  930. const axes_len = axes.length < 10 ? axes.length : 10;
  931. for (let i = 0; i < axes_len; i++) {
  932. GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float');
  933. }
  934. GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32');
  935. const is_standard = sample.standard ? 1 : 0;
  936. GodotRuntime.setHeapValue(r_standard, is_standard, 'i32');
  937. return 0;
  938. },
  939. };
  940. autoAddDeps(GodotDisplay, '$GodotDisplay');
  941. mergeInto(LibraryManager.library, GodotDisplay);