core.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2019-2024 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. const osName = __TEMPLATE_os_name__
  9. Object.defineProperty(window.__TAURI_INTERNALS__, 'convertFileSrc', {
  10. value: function (filePath, protocol = 'asset') {
  11. const path = encodeURIComponent(filePath)
  12. return osName === 'windows' || osName === 'android'
  13. ? `http://${protocol}.localhost/${path}`
  14. : `${protocol}://localhost/${path}`
  15. }
  16. })
  17. Object.defineProperty(window.__TAURI_INTERNALS__, 'transformCallback', {
  18. value: function transformCallback(callback, once) {
  19. var identifier = uid()
  20. var prop = `_${identifier}`
  21. Object.defineProperty(window, prop, {
  22. value: (result) => {
  23. if (once) {
  24. Reflect.deleteProperty(window, prop)
  25. }
  26. return callback && callback(result)
  27. },
  28. writable: false,
  29. configurable: true
  30. })
  31. return identifier
  32. }
  33. })
  34. const ipcQueue = []
  35. let isWaitingForIpc = false
  36. function waitForIpc() {
  37. if ('ipc' in window.__TAURI_INTERNALS__) {
  38. for (const action of ipcQueue) {
  39. action()
  40. }
  41. } else {
  42. setTimeout(waitForIpc, 50)
  43. }
  44. }
  45. Object.defineProperty(window.__TAURI_INTERNALS__, 'invoke', {
  46. value: function (cmd, payload = {}, options) {
  47. return new Promise(function (resolve, reject) {
  48. const callback = window.__TAURI_INTERNALS__.transformCallback(function (
  49. r
  50. ) {
  51. resolve(r)
  52. delete window[`_${error}`]
  53. }, true)
  54. const error = window.__TAURI_INTERNALS__.transformCallback(function (
  55. e
  56. ) {
  57. reject(e)
  58. delete window[`_${callback}`]
  59. }, true)
  60. const action = () => {
  61. window.__TAURI_INTERNALS__.ipc({
  62. cmd,
  63. callback,
  64. error,
  65. payload,
  66. options
  67. })
  68. }
  69. if ('ipc' in window.__TAURI_INTERNALS__) {
  70. action()
  71. } else {
  72. ipcQueue.push(action)
  73. if (!isWaitingForIpc) {
  74. waitForIpc()
  75. isWaitingForIpc = true
  76. }
  77. }
  78. })
  79. }
  80. })
  81. })()