core.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. 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. },
  54. true)
  55. const error = window.__TAURI_INTERNALS__.transformCallback(function (
  56. e
  57. ) {
  58. reject(e)
  59. delete window[`_${callback}`]
  60. },
  61. true)
  62. const action = () => {
  63. window.window.__TAURI_INTERNALS__.ipc({
  64. cmd,
  65. callback,
  66. error,
  67. payload,
  68. options
  69. })
  70. }
  71. if ('ipc' in window.__TAURI_INTERNALS__) {
  72. action()
  73. } else {
  74. ipcQueue.push(action)
  75. if (!isWaitingForIpc) {
  76. waitForIpc()
  77. isWaitingForIpc = true
  78. }
  79. }
  80. })
  81. }
  82. })
  83. })()