core.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. ; (function () {
  5. function uid() {
  6. return window.crypto.getRandomValues(new Uint32Array(1))[0]
  7. }
  8. if (!window.__TAURI__) {
  9. Object.defineProperty(window, '__TAURI__', {
  10. value: {}
  11. })
  12. }
  13. const osName = __TEMPLATE_os_name__
  14. window.__TAURI__.convertFileSrc = function convertFileSrc(filePath, protocol = 'asset') {
  15. const path = encodeURIComponent(filePath)
  16. return osName === 'windows' || osName === 'android'
  17. ? `https://${protocol}.localhost/${path}`
  18. : `${protocol}://localhost/${path}`
  19. }
  20. window.__TAURI__.transformCallback = function transformCallback(
  21. callback,
  22. once
  23. ) {
  24. var identifier = uid()
  25. var prop = `_${identifier}`
  26. Object.defineProperty(window, prop, {
  27. value: (result) => {
  28. if (once) {
  29. Reflect.deleteProperty(window, prop)
  30. }
  31. return callback && callback(result)
  32. },
  33. writable: false,
  34. configurable: true
  35. })
  36. return identifier
  37. }
  38. const ipcQueue = []
  39. let isWaitingForIpc = false
  40. function waitForIpc() {
  41. if ('__TAURI_IPC__' in window) {
  42. for (const action of ipcQueue) {
  43. action()
  44. }
  45. } else {
  46. setTimeout(waitForIpc, 50)
  47. }
  48. }
  49. window.__TAURI_INVOKE__ = function invoke(cmd, payload = {}, options) {
  50. return new Promise(function (resolve, reject) {
  51. const callback = window.__TAURI__.transformCallback(function (r) {
  52. resolve(r)
  53. delete window[`_${error}`]
  54. }, true)
  55. const error = window.__TAURI__.transformCallback(function (e) {
  56. reject(e)
  57. delete window[`_${callback}`]
  58. }, true)
  59. const action = () => {
  60. window.__TAURI_IPC__({
  61. cmd,
  62. callback,
  63. error,
  64. payload,
  65. options
  66. })
  67. }
  68. if (window.__TAURI_IPC__) {
  69. action()
  70. } else {
  71. ipcQueue.push(action)
  72. if (!isWaitingForIpc) {
  73. waitForIpc()
  74. isWaitingForIpc = true
  75. }
  76. }
  77. })
  78. }
  79. })()