library_godot_display.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. const dirs = [DROP.substr(0, DROP.length - 1)];
  186. // Remove temporary files
  187. files.forEach(function (file) {
  188. FS.unlink(file);
  189. let dir = file.replace(DROP, '');
  190. let idx = dir.lastIndexOf('/');
  191. while (idx > 0) {
  192. dir = dir.substr(0, idx);
  193. if (dirs.indexOf(DROP + dir) === -1) {
  194. dirs.push(DROP + dir);
  195. }
  196. idx = dir.lastIndexOf('/');
  197. }
  198. });
  199. // Remove dirs.
  200. dirs.sort(function (a, b) {
  201. const al = (a.match(/\//g) || []).length;
  202. const bl = (b.match(/\//g) || []).length;
  203. if (al > bl) {
  204. return -1;
  205. } else if (al < bl) {
  206. return 1;
  207. }
  208. return 0;
  209. }).forEach(function (dir) {
  210. FS.rmdir(dir);
  211. });
  212. });
  213. },
  214. handler: function (callback) {
  215. return function (ev) {
  216. GodotDisplayDragDrop._process_event(ev, callback);
  217. };
  218. },
  219. },
  220. };
  221. mergeInto(LibraryManager.library, GodotDisplayDragDrop);
  222. const GodotDisplayVK = {
  223. $GodotDisplayVK__deps: ['$GodotRuntime', '$GodotConfig', '$GodotDisplayListeners'],
  224. $GodotDisplayVK__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayVK.clear(); resolve(); });',
  225. $GodotDisplayVK: {
  226. textinput: null,
  227. textarea: null,
  228. available: function () {
  229. return GodotConfig.virtual_keyboard && 'ontouchstart' in window;
  230. },
  231. init: function (input_cb) {
  232. function create(what) {
  233. const elem = document.createElement(what);
  234. elem.style.display = 'none';
  235. elem.style.position = 'absolute';
  236. elem.style.zIndex = '-1';
  237. elem.style.background = 'transparent';
  238. elem.style.padding = '0px';
  239. elem.style.margin = '0px';
  240. elem.style.overflow = 'hidden';
  241. elem.style.width = '0px';
  242. elem.style.height = '0px';
  243. elem.style.border = '0px';
  244. elem.style.outline = 'none';
  245. elem.readonly = true;
  246. elem.disabled = true;
  247. GodotDisplayListeners.add(elem, 'input', function (evt) {
  248. const c_str = GodotRuntime.allocString(elem.value);
  249. input_cb(c_str, elem.selectionEnd);
  250. GodotRuntime.free(c_str);
  251. }, false);
  252. GodotDisplayListeners.add(elem, 'blur', function (evt) {
  253. elem.style.display = 'none';
  254. elem.readonly = true;
  255. elem.disabled = true;
  256. }, false);
  257. GodotConfig.canvas.insertAdjacentElement('beforebegin', elem);
  258. return elem;
  259. }
  260. GodotDisplayVK.textinput = create('input');
  261. GodotDisplayVK.textarea = create('textarea');
  262. GodotDisplayVK.updateSize();
  263. },
  264. show: function (text, multiline, start, end) {
  265. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  266. return;
  267. }
  268. if (GodotDisplayVK.textinput.style.display !== '' || GodotDisplayVK.textarea.style.display !== '') {
  269. GodotDisplayVK.hide();
  270. }
  271. GodotDisplayVK.updateSize();
  272. const elem = multiline ? GodotDisplayVK.textarea : GodotDisplayVK.textinput;
  273. elem.readonly = false;
  274. elem.disabled = false;
  275. elem.value = text;
  276. elem.style.display = 'block';
  277. elem.focus();
  278. elem.setSelectionRange(start, end);
  279. },
  280. hide: function () {
  281. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  282. return;
  283. }
  284. [GodotDisplayVK.textinput, GodotDisplayVK.textarea].forEach(function (elem) {
  285. elem.blur();
  286. elem.style.display = 'none';
  287. elem.value = '';
  288. });
  289. },
  290. updateSize: function () {
  291. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  292. return;
  293. }
  294. const rect = GodotConfig.canvas.getBoundingClientRect();
  295. function update(elem) {
  296. elem.style.left = `${rect.left}px`;
  297. elem.style.top = `${rect.top}px`;
  298. elem.style.width = `${rect.width}px`;
  299. elem.style.height = `${rect.height}px`;
  300. }
  301. update(GodotDisplayVK.textinput);
  302. update(GodotDisplayVK.textarea);
  303. },
  304. clear: function () {
  305. if (GodotDisplayVK.textinput) {
  306. GodotDisplayVK.textinput.remove();
  307. GodotDisplayVK.textinput = null;
  308. }
  309. if (GodotDisplayVK.textarea) {
  310. GodotDisplayVK.textarea.remove();
  311. GodotDisplayVK.textarea = null;
  312. }
  313. },
  314. },
  315. };
  316. mergeInto(LibraryManager.library, GodotDisplayVK);
  317. /*
  318. * Display server cursor helper.
  319. * Keeps track of cursor status and custom shapes.
  320. */
  321. const GodotDisplayCursor = {
  322. $GodotDisplayCursor__deps: ['$GodotOS', '$GodotConfig'],
  323. $GodotDisplayCursor__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayCursor.clear(); resolve(); });',
  324. $GodotDisplayCursor: {
  325. shape: 'auto',
  326. visible: true,
  327. cursors: {},
  328. set_style: function (style) {
  329. GodotConfig.canvas.style.cursor = style;
  330. },
  331. set_shape: function (shape) {
  332. GodotDisplayCursor.shape = shape;
  333. let css = shape;
  334. if (shape in GodotDisplayCursor.cursors) {
  335. const c = GodotDisplayCursor.cursors[shape];
  336. css = `url("${c.url}") ${c.x} ${c.y}, auto`;
  337. }
  338. if (GodotDisplayCursor.visible) {
  339. GodotDisplayCursor.set_style(css);
  340. }
  341. },
  342. clear: function () {
  343. GodotDisplayCursor.set_style('');
  344. GodotDisplayCursor.shape = 'auto';
  345. GodotDisplayCursor.visible = true;
  346. Object.keys(GodotDisplayCursor.cursors).forEach(function (key) {
  347. URL.revokeObjectURL(GodotDisplayCursor.cursors[key]);
  348. delete GodotDisplayCursor.cursors[key];
  349. });
  350. },
  351. },
  352. };
  353. mergeInto(LibraryManager.library, GodotDisplayCursor);
  354. /*
  355. * Display Gamepad API helper.
  356. */
  357. const GodotDisplayGamepads = {
  358. $GodotDisplayGamepads__deps: ['$GodotRuntime', '$GodotDisplayListeners'],
  359. $GodotDisplayGamepads: {
  360. samples: [],
  361. get_pads: function () {
  362. try {
  363. // Will throw in iframe when permission is denied.
  364. // Will throw/warn in the future for insecure contexts.
  365. // See https://github.com/w3c/gamepad/pull/120
  366. const pads = navigator.getGamepads();
  367. if (pads) {
  368. return pads;
  369. }
  370. return [];
  371. } catch (e) {
  372. return [];
  373. }
  374. },
  375. get_samples: function () {
  376. return GodotDisplayGamepads.samples;
  377. },
  378. get_sample: function (index) {
  379. const samples = GodotDisplayGamepads.samples;
  380. return index < samples.length ? samples[index] : null;
  381. },
  382. sample: function () {
  383. const pads = GodotDisplayGamepads.get_pads();
  384. const samples = [];
  385. for (let i = 0; i < pads.length; i++) {
  386. const pad = pads[i];
  387. if (!pad) {
  388. samples.push(null);
  389. continue;
  390. }
  391. const s = {
  392. standard: pad.mapping === 'standard',
  393. buttons: [],
  394. axes: [],
  395. connected: pad.connected,
  396. };
  397. for (let b = 0; b < pad.buttons.length; b++) {
  398. s.buttons.push(pad.buttons[b].value);
  399. }
  400. for (let a = 0; a < pad.axes.length; a++) {
  401. s.axes.push(pad.axes[a]);
  402. }
  403. samples.push(s);
  404. }
  405. GodotDisplayGamepads.samples = samples;
  406. },
  407. init: function (onchange) {
  408. GodotDisplayListeners.samples = [];
  409. function add(pad) {
  410. const guid = GodotDisplayGamepads.get_guid(pad);
  411. const c_id = GodotRuntime.allocString(pad.id);
  412. const c_guid = GodotRuntime.allocString(guid);
  413. onchange(pad.index, 1, c_id, c_guid);
  414. GodotRuntime.free(c_id);
  415. GodotRuntime.free(c_guid);
  416. }
  417. const pads = GodotDisplayGamepads.get_pads();
  418. for (let i = 0; i < pads.length; i++) {
  419. // Might be reserved space.
  420. if (pads[i]) {
  421. add(pads[i]);
  422. }
  423. }
  424. GodotDisplayListeners.add(window, 'gamepadconnected', function (evt) {
  425. add(evt.gamepad);
  426. }, false);
  427. GodotDisplayListeners.add(window, 'gamepaddisconnected', function (evt) {
  428. onchange(evt.gamepad.index, 0);
  429. }, false);
  430. },
  431. get_guid: function (pad) {
  432. if (pad.mapping) {
  433. return pad.mapping;
  434. }
  435. const ua = navigator.userAgent;
  436. let os = 'Unknown';
  437. if (ua.indexOf('Android') >= 0) {
  438. os = 'Android';
  439. } else if (ua.indexOf('Linux') >= 0) {
  440. os = 'Linux';
  441. } else if (ua.indexOf('iPhone') >= 0) {
  442. os = 'iOS';
  443. } else if (ua.indexOf('Macintosh') >= 0) {
  444. // Updated iPads will fall into this category.
  445. os = 'MacOSX';
  446. } else if (ua.indexOf('Windows') >= 0) {
  447. os = 'Windows';
  448. }
  449. const id = pad.id;
  450. // Chrom* style: NAME (Vendor: xxxx Product: xxxx)
  451. const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i;
  452. // Firefox/Safari style (safari may remove leading zeores)
  453. const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i;
  454. let vendor = '';
  455. let product = '';
  456. if (exp1.test(id)) {
  457. const match = exp1.exec(id);
  458. vendor = match[1].padStart(4, '0');
  459. product = match[2].padStart(4, '0');
  460. } else if (exp2.test(id)) {
  461. const match = exp2.exec(id);
  462. vendor = match[1].padStart(4, '0');
  463. product = match[2].padStart(4, '0');
  464. }
  465. if (!vendor || !product) {
  466. return `${os}Unknown`;
  467. }
  468. return os + vendor + product;
  469. },
  470. },
  471. };
  472. mergeInto(LibraryManager.library, GodotDisplayGamepads);
  473. const GodotDisplayScreen = {
  474. $GodotDisplayScreen__deps: ['$GodotConfig', '$GodotOS', '$GL', 'emscripten_webgl_get_current_context'],
  475. $GodotDisplayScreen: {
  476. desired_size: [0, 0],
  477. hidpi: true,
  478. getPixelRatio: function () {
  479. return GodotDisplayScreen.hidpi ? window.devicePixelRatio || 1 : 1;
  480. },
  481. isFullscreen: function () {
  482. const elem = document.fullscreenElement || document.mozFullscreenElement
  483. || document.webkitFullscreenElement || document.msFullscreenElement;
  484. if (elem) {
  485. return elem === GodotConfig.canvas;
  486. }
  487. // But maybe knowing the element is not supported.
  488. return document.fullscreen || document.mozFullScreen
  489. || document.webkitIsFullscreen;
  490. },
  491. hasFullscreen: function () {
  492. return document.fullscreenEnabled || document.mozFullScreenEnabled
  493. || document.webkitFullscreenEnabled;
  494. },
  495. requestFullscreen: function () {
  496. if (!GodotDisplayScreen.hasFullscreen()) {
  497. return 1;
  498. }
  499. const canvas = GodotConfig.canvas;
  500. try {
  501. const promise = (canvas.requestFullscreen || canvas.msRequestFullscreen
  502. || canvas.mozRequestFullScreen || canvas.mozRequestFullscreen
  503. || canvas.webkitRequestFullscreen
  504. ).call(canvas);
  505. // Some browsers (Safari) return undefined.
  506. // For the standard ones, we need to catch it.
  507. if (promise) {
  508. promise.catch(function () {
  509. // nothing to do.
  510. });
  511. }
  512. } catch (e) {
  513. return 1;
  514. }
  515. return 0;
  516. },
  517. exitFullscreen: function () {
  518. if (!GodotDisplayScreen.isFullscreen()) {
  519. return 0;
  520. }
  521. try {
  522. const promise = document.exitFullscreen();
  523. if (promise) {
  524. promise.catch(function () {
  525. // nothing to do.
  526. });
  527. }
  528. } catch (e) {
  529. return 1;
  530. }
  531. return 0;
  532. },
  533. _updateGL: function () {
  534. const gl_context_handle = _emscripten_webgl_get_current_context(); // eslint-disable-line no-undef
  535. const gl = GL.getContext(gl_context_handle);
  536. if (gl) {
  537. GL.resizeOffscreenFramebuffer(gl);
  538. }
  539. },
  540. updateSize: function () {
  541. const isFullscreen = GodotDisplayScreen.isFullscreen();
  542. const wantsFullWindow = GodotConfig.canvas_resize_policy === 2;
  543. const noResize = GodotConfig.canvas_resize_policy === 0;
  544. const wwidth = GodotDisplayScreen.desired_size[0];
  545. const wheight = GodotDisplayScreen.desired_size[1];
  546. const canvas = GodotConfig.canvas;
  547. let width = wwidth;
  548. let height = wheight;
  549. if (noResize) {
  550. // Don't resize canvas, just update GL if needed.
  551. if (canvas.width !== width || canvas.height !== height) {
  552. GodotDisplayScreen.desired_size = [canvas.width, canvas.height];
  553. GodotDisplayScreen._updateGL();
  554. return 1;
  555. }
  556. return 0;
  557. }
  558. const scale = GodotDisplayScreen.getPixelRatio();
  559. if (isFullscreen || wantsFullWindow) {
  560. // We need to match screen size.
  561. width = window.innerWidth * scale;
  562. height = window.innerHeight * scale;
  563. }
  564. const csw = `${width / scale}px`;
  565. const csh = `${height / scale}px`;
  566. if (canvas.style.width !== csw || canvas.style.height !== csh || canvas.width !== width || canvas.height !== height) {
  567. // Size doesn't match.
  568. // Resize canvas, set correct CSS pixel size, update GL.
  569. canvas.width = width;
  570. canvas.height = height;
  571. canvas.style.width = csw;
  572. canvas.style.height = csh;
  573. GodotDisplayScreen._updateGL();
  574. return 1;
  575. }
  576. return 0;
  577. },
  578. },
  579. };
  580. mergeInto(LibraryManager.library, GodotDisplayScreen);
  581. /**
  582. * Display server interface.
  583. *
  584. * Exposes all the functions needed by DisplayServer implementation.
  585. */
  586. const GodotDisplay = {
  587. $GodotDisplay__deps: ['$GodotConfig', '$GodotRuntime', '$GodotDisplayCursor', '$GodotDisplayListeners', '$GodotDisplayDragDrop', '$GodotDisplayGamepads', '$GodotDisplayScreen', '$GodotDisplayVK'],
  588. $GodotDisplay: {
  589. window_icon: '',
  590. findDPI: function () {
  591. function testDPI(dpi) {
  592. return window.matchMedia(`(max-resolution: ${dpi}dpi)`).matches;
  593. }
  594. function bisect(low, high, func) {
  595. const mid = parseInt(((high - low) / 2) + low, 10);
  596. if (high - low <= 1) {
  597. return func(high) ? high : low;
  598. }
  599. if (func(mid)) {
  600. return bisect(low, mid, func);
  601. }
  602. return bisect(mid, high, func);
  603. }
  604. try {
  605. const dpi = bisect(0, 800, testDPI);
  606. return dpi >= 96 ? dpi : 96;
  607. } catch (e) {
  608. return 96;
  609. }
  610. },
  611. },
  612. godot_js_display_is_swap_ok_cancel__sig: 'i',
  613. godot_js_display_is_swap_ok_cancel: function () {
  614. const win = (['Windows', 'Win64', 'Win32', 'WinCE']);
  615. const plat = navigator.platform || '';
  616. if (win.indexOf(plat) !== -1) {
  617. return 1;
  618. }
  619. return 0;
  620. },
  621. godot_js_display_alert__sig: 'vi',
  622. godot_js_display_alert: function (p_text) {
  623. window.alert(GodotRuntime.parseString(p_text)); // eslint-disable-line no-alert
  624. },
  625. godot_js_display_screen_dpi_get__sig: 'i',
  626. godot_js_display_screen_dpi_get: function () {
  627. return GodotDisplay.findDPI();
  628. },
  629. godot_js_display_pixel_ratio_get__sig: 'f',
  630. godot_js_display_pixel_ratio_get: function () {
  631. return GodotDisplayScreen.getPixelRatio();
  632. },
  633. godot_js_display_fullscreen_request__sig: 'i',
  634. godot_js_display_fullscreen_request: function () {
  635. return GodotDisplayScreen.requestFullscreen();
  636. },
  637. godot_js_display_fullscreen_exit__sig: 'i',
  638. godot_js_display_fullscreen_exit: function () {
  639. return GodotDisplayScreen.exitFullscreen();
  640. },
  641. godot_js_display_desired_size_set__sig: 'v',
  642. godot_js_display_desired_size_set: function (width, height) {
  643. GodotDisplayScreen.desired_size = [width, height];
  644. GodotDisplayScreen.updateSize();
  645. },
  646. godot_js_display_size_update__sig: 'i',
  647. godot_js_display_size_update: function () {
  648. const updated = GodotDisplayScreen.updateSize();
  649. if (updated) {
  650. GodotDisplayVK.updateSize();
  651. }
  652. return updated;
  653. },
  654. godot_js_display_screen_size_get__sig: 'vii',
  655. godot_js_display_screen_size_get: function (width, height) {
  656. const scale = GodotDisplayScreen.getPixelRatio();
  657. GodotRuntime.setHeapValue(width, window.screen.width * scale, 'i32');
  658. GodotRuntime.setHeapValue(height, window.screen.height * scale, 'i32');
  659. },
  660. godot_js_display_window_size_get: function (p_width, p_height) {
  661. GodotRuntime.setHeapValue(p_width, GodotConfig.canvas.width, 'i32');
  662. GodotRuntime.setHeapValue(p_height, GodotConfig.canvas.height, 'i32');
  663. },
  664. godot_js_display_compute_position: function (x, y, r_x, r_y) {
  665. const canvas = GodotConfig.canvas;
  666. const rect = canvas.getBoundingClientRect();
  667. const rw = canvas.width / rect.width;
  668. const rh = canvas.height / rect.height;
  669. GodotRuntime.setHeapValue(r_x, (x - rect.x) * rw, 'i32');
  670. GodotRuntime.setHeapValue(r_y, (y - rect.y) * rh, 'i32');
  671. },
  672. /*
  673. * Canvas
  674. */
  675. godot_js_display_canvas_focus__sig: 'v',
  676. godot_js_display_canvas_focus: function () {
  677. GodotConfig.canvas.focus();
  678. },
  679. godot_js_display_canvas_is_focused__sig: 'i',
  680. godot_js_display_canvas_is_focused: function () {
  681. return document.activeElement === GodotConfig.canvas;
  682. },
  683. /*
  684. * Touchscreen
  685. */
  686. godot_js_display_touchscreen_is_available__sig: 'i',
  687. godot_js_display_touchscreen_is_available: function () {
  688. return 'ontouchstart' in window;
  689. },
  690. /*
  691. * Clipboard
  692. */
  693. godot_js_display_clipboard_set__sig: 'ii',
  694. godot_js_display_clipboard_set: function (p_text) {
  695. const text = GodotRuntime.parseString(p_text);
  696. if (!navigator.clipboard || !navigator.clipboard.writeText) {
  697. return 1;
  698. }
  699. navigator.clipboard.writeText(text).catch(function (e) {
  700. // Setting OS clipboard is only possible from an input callback.
  701. GodotRuntime.error('Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:', e);
  702. });
  703. return 0;
  704. },
  705. godot_js_display_clipboard_get__sig: 'ii',
  706. godot_js_display_clipboard_get: function (callback) {
  707. const func = GodotRuntime.get_func(callback);
  708. try {
  709. navigator.clipboard.readText().then(function (result) {
  710. const ptr = GodotRuntime.allocString(result);
  711. func(ptr);
  712. GodotRuntime.free(ptr);
  713. }).catch(function (e) {
  714. // Fail graciously.
  715. });
  716. } catch (e) {
  717. // Fail graciously.
  718. }
  719. },
  720. /*
  721. * Window
  722. */
  723. godot_js_display_window_title_set__sig: 'vi',
  724. godot_js_display_window_title_set: function (p_data) {
  725. document.title = GodotRuntime.parseString(p_data);
  726. },
  727. godot_js_display_window_icon_set__sig: 'vii',
  728. godot_js_display_window_icon_set: function (p_ptr, p_len) {
  729. let link = document.getElementById('-gd-engine-icon');
  730. if (link === null) {
  731. link = document.createElement('link');
  732. link.rel = 'icon';
  733. link.id = '-gd-engine-icon';
  734. document.head.appendChild(link);
  735. }
  736. const old_icon = GodotDisplay.window_icon;
  737. const png = new Blob([GodotRuntime.heapSlice(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
  738. GodotDisplay.window_icon = URL.createObjectURL(png);
  739. link.href = GodotDisplay.window_icon;
  740. if (old_icon) {
  741. URL.revokeObjectURL(old_icon);
  742. }
  743. },
  744. /*
  745. * Cursor
  746. */
  747. godot_js_display_cursor_set_visible__sig: 'vi',
  748. godot_js_display_cursor_set_visible: function (p_visible) {
  749. const visible = p_visible !== 0;
  750. if (visible === GodotDisplayCursor.visible) {
  751. return;
  752. }
  753. GodotDisplayCursor.visible = visible;
  754. if (visible) {
  755. GodotDisplayCursor.set_shape(GodotDisplayCursor.shape);
  756. } else {
  757. GodotDisplayCursor.set_style('none');
  758. }
  759. },
  760. godot_js_display_cursor_is_hidden__sig: 'i',
  761. godot_js_display_cursor_is_hidden: function () {
  762. return !GodotDisplayCursor.visible;
  763. },
  764. godot_js_display_cursor_set_shape__sig: 'vi',
  765. godot_js_display_cursor_set_shape: function (p_string) {
  766. GodotDisplayCursor.set_shape(GodotRuntime.parseString(p_string));
  767. },
  768. godot_js_display_cursor_set_custom_shape__sig: 'viiiii',
  769. godot_js_display_cursor_set_custom_shape: function (p_shape, p_ptr, p_len, p_hotspot_x, p_hotspot_y) {
  770. const shape = GodotRuntime.parseString(p_shape);
  771. const old_shape = GodotDisplayCursor.cursors[shape];
  772. if (p_len > 0) {
  773. const png = new Blob([GodotRuntime.heapSlice(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
  774. const url = URL.createObjectURL(png);
  775. GodotDisplayCursor.cursors[shape] = {
  776. url: url,
  777. x: p_hotspot_x,
  778. y: p_hotspot_y,
  779. };
  780. } else {
  781. delete GodotDisplayCursor.cursors[shape];
  782. }
  783. if (shape === GodotDisplayCursor.shape) {
  784. GodotDisplayCursor.set_shape(GodotDisplayCursor.shape);
  785. }
  786. if (old_shape) {
  787. URL.revokeObjectURL(old_shape.url);
  788. }
  789. },
  790. /*
  791. * Listeners
  792. */
  793. godot_js_display_notification_cb__sig: 'viiiii',
  794. godot_js_display_notification_cb: function (callback, p_enter, p_exit, p_in, p_out) {
  795. const canvas = GodotConfig.canvas;
  796. const func = GodotRuntime.get_func(callback);
  797. const notif = [p_enter, p_exit, p_in, p_out];
  798. ['mouseover', 'mouseleave', 'focus', 'blur'].forEach(function (evt_name, idx) {
  799. GodotDisplayListeners.add(canvas, evt_name, function () {
  800. func.bind(null, notif[idx]);
  801. }, true);
  802. });
  803. },
  804. godot_js_display_paste_cb__sig: 'vi',
  805. godot_js_display_paste_cb: function (callback) {
  806. const func = GodotRuntime.get_func(callback);
  807. GodotDisplayListeners.add(window, 'paste', function (evt) {
  808. const text = evt.clipboardData.getData('text');
  809. const ptr = GodotRuntime.allocString(text);
  810. func(ptr);
  811. GodotRuntime.free(ptr);
  812. }, false);
  813. },
  814. godot_js_display_drop_files_cb__sig: 'vi',
  815. godot_js_display_drop_files_cb: function (callback) {
  816. const func = GodotRuntime.get_func(callback);
  817. const dropFiles = function (files) {
  818. const args = files || [];
  819. if (!args.length) {
  820. return;
  821. }
  822. const argc = args.length;
  823. const argv = GodotRuntime.allocStringArray(args);
  824. func(argv, argc);
  825. GodotRuntime.freeStringArray(argv, argc);
  826. };
  827. const canvas = GodotConfig.canvas;
  828. GodotDisplayListeners.add(canvas, 'dragover', function (ev) {
  829. // Prevent default behavior (which would try to open the file(s))
  830. ev.preventDefault();
  831. }, false);
  832. GodotDisplayListeners.add(canvas, 'drop', GodotDisplayDragDrop.handler(dropFiles));
  833. },
  834. godot_js_display_setup_canvas__sig: 'viiii',
  835. godot_js_display_setup_canvas: function (p_width, p_height, p_fullscreen, p_hidpi) {
  836. const canvas = GodotConfig.canvas;
  837. GodotDisplayListeners.add(canvas, 'contextmenu', function (ev) {
  838. ev.preventDefault();
  839. }, false);
  840. GodotDisplayListeners.add(canvas, 'webglcontextlost', function (ev) {
  841. alert('WebGL context lost, please reload the page'); // eslint-disable-line no-alert
  842. ev.preventDefault();
  843. }, false);
  844. GodotDisplayScreen.hidpi = !!p_hidpi;
  845. switch (GodotConfig.canvas_resize_policy) {
  846. case 0: // None
  847. GodotDisplayScreen.desired_size = [canvas.width, canvas.height];
  848. break;
  849. case 1: // Project
  850. GodotDisplayScreen.desired_size = [p_width, p_height];
  851. break;
  852. default: // Full window
  853. // Ensure we display in the right place, the size will be handled by updateSize
  854. canvas.style.position = 'absolute';
  855. canvas.style.top = 0;
  856. canvas.style.left = 0;
  857. break;
  858. }
  859. GodotDisplayScreen.updateSize();
  860. if (p_fullscreen) {
  861. GodotDisplayScreen.requestFullscreen();
  862. }
  863. },
  864. /*
  865. * Virtual Keyboard
  866. */
  867. godot_js_display_vk_show__sig: 'viiii',
  868. godot_js_display_vk_show: function (p_text, p_multiline, p_start, p_end) {
  869. const text = GodotRuntime.parseString(p_text);
  870. const start = p_start > 0 ? p_start : 0;
  871. const end = p_end > 0 ? p_end : start;
  872. GodotDisplayVK.show(text, p_multiline, start, end);
  873. },
  874. godot_js_display_vk_hide__sig: 'v',
  875. godot_js_display_vk_hide: function () {
  876. GodotDisplayVK.hide();
  877. },
  878. godot_js_display_vk_available__sig: 'i',
  879. godot_js_display_vk_available: function () {
  880. return GodotDisplayVK.available();
  881. },
  882. godot_js_display_vk_cb__sig: 'vi',
  883. godot_js_display_vk_cb: function (p_input_cb) {
  884. const input_cb = GodotRuntime.get_func(p_input_cb);
  885. if (GodotDisplayVK.available()) {
  886. GodotDisplayVK.init(input_cb);
  887. }
  888. },
  889. /*
  890. * Gamepads
  891. */
  892. godot_js_display_gamepad_cb__sig: 'vi',
  893. godot_js_display_gamepad_cb: function (change_cb) {
  894. const onchange = GodotRuntime.get_func(change_cb);
  895. GodotDisplayGamepads.init(onchange);
  896. },
  897. godot_js_display_gamepad_sample_count__sig: 'i',
  898. godot_js_display_gamepad_sample_count: function () {
  899. return GodotDisplayGamepads.get_samples().length;
  900. },
  901. godot_js_display_gamepad_sample__sig: 'i',
  902. godot_js_display_gamepad_sample: function () {
  903. GodotDisplayGamepads.sample();
  904. return 0;
  905. },
  906. godot_js_display_gamepad_sample_get__sig: 'iiiiiii',
  907. godot_js_display_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) {
  908. const sample = GodotDisplayGamepads.get_sample(p_index);
  909. if (!sample || !sample.connected) {
  910. return 1;
  911. }
  912. const btns = sample.buttons;
  913. const btns_len = btns.length < 16 ? btns.length : 16;
  914. for (let i = 0; i < btns_len; i++) {
  915. GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float');
  916. }
  917. GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32');
  918. const axes = sample.axes;
  919. const axes_len = axes.length < 10 ? axes.length : 10;
  920. for (let i = 0; i < axes_len; i++) {
  921. GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float');
  922. }
  923. GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32');
  924. const is_standard = sample.standard ? 1 : 0;
  925. GodotRuntime.setHeapValue(r_standard, is_standard, 'i32');
  926. return 0;
  927. },
  928. };
  929. autoAddDeps(GodotDisplay, '$GodotDisplay');
  930. mergeInto(LibraryManager.library, GodotDisplay);