preload.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. const fs = require('fs')
  2. const path = require('path')
  3. const { ipcRenderer, contextBridge, shell, clipboard, webFrame } = require('electron')
  4. const IS_MAC = process.platform === 'darwin'
  5. const IS_WIN32 = process.platform === 'win32'
  6. const ALLOWED_EXTERNAL_PROTOCOLS = ['https:', 'http:', 'mailto:', 'zotero:', 'file:']
  7. function getFilePathFromClipboard () {
  8. if (IS_WIN32) {
  9. const rawFilePath = clipboard.read('FileNameW')
  10. return rawFilePath.replace(new RegExp(String.fromCharCode(0), 'g'), '')
  11. } else if (IS_MAC) {
  12. return clipboard.read('public.file-url').replace('file://', '')
  13. } else {
  14. return clipboard.readText()
  15. }
  16. }
  17. /**
  18. * Read the contents of the clipboard for a custom format.
  19. * @param {string} format The custom format to read.
  20. * @returns Buffer containing the contents of the clipboard for the specified format, or null if not available.
  21. */
  22. function getClipboardData (format) {
  23. if (clipboard.has(format, "clipboard")) {
  24. return clipboard.readBuffer(format)
  25. }
  26. else {
  27. return null;
  28. }
  29. }
  30. contextBridge.exposeInMainWorld('apis', {
  31. doAction: async (arg) => {
  32. return await ipcRenderer.invoke('main', arg)
  33. },
  34. invoke: async (channel, args) => {
  35. return await ipcRenderer.invoke(channel, ...args)
  36. },
  37. addListener: ipcRenderer.on.bind(ipcRenderer),
  38. removeListener: ipcRenderer.removeListener.bind(ipcRenderer),
  39. removeAllListeners: ipcRenderer.removeAllListeners.bind(ipcRenderer),
  40. on: (channel, callback) => {
  41. const newCallback = (_, data) => callback(data)
  42. ipcRenderer.on(channel, newCallback)
  43. },
  44. off: (channel, callback) => {
  45. if (!callback) {
  46. ipcRenderer.removeAllListeners(channel)
  47. } else {
  48. ipcRenderer.removeListener(channel, callback)
  49. }
  50. },
  51. once: (channel, callback) => {
  52. ipcRenderer.on(channel, callback)
  53. },
  54. checkForUpdates: async (...args) => {
  55. await ipcRenderer.invoke('check-for-updates', ...args)
  56. },
  57. setUpdatesCallback (cb) {
  58. if (typeof cb !== 'function') return
  59. const channel = 'updates-callback'
  60. ipcRenderer.removeAllListeners(channel)
  61. ipcRenderer.on(channel, cb)
  62. },
  63. installUpdatesAndQuitApp () {
  64. ipcRenderer.invoke('install-updates', true)
  65. },
  66. async openExternal (url, options) {
  67. const protocol = new URL(url).protocol
  68. if (!ALLOWED_EXTERNAL_PROTOCOLS.includes(protocol)) {
  69. throw new Error('illegal protocol')
  70. }
  71. await shell.openExternal(url, options)
  72. },
  73. async openPath (path) {
  74. await shell.openPath(path)
  75. },
  76. /**
  77. * save all publish assets to disk
  78. *
  79. * @param {string} html html file with embedded state
  80. */
  81. exportPublishAssets (html, customCSSPath, exportCSSPath, repoPath, assetFilenames, outputDir) {
  82. ipcRenderer.invoke(
  83. 'export-publish-assets',
  84. html,
  85. customCSSPath,
  86. exportCSSPath,
  87. repoPath,
  88. assetFilenames,
  89. outputDir
  90. )
  91. },
  92. /**
  93. * When from is empty. The resource maybe from
  94. * client paste or screenshoot.
  95. * @param repoPathRoot
  96. * @param to
  97. * @param from?
  98. * @returns {Promise<void>}
  99. */
  100. async copyFileToAssets (repoPathRoot, to, from) {
  101. if (from && fs.statSync(from).isDirectory()) {
  102. throw new Error('not support copy directory')
  103. }
  104. const dest = path.join(repoPathRoot, to)
  105. const assetsRoot = path.dirname(dest)
  106. await fs.promises.mkdir(assetsRoot, { recursive: true })
  107. from = from || getFilePathFromClipboard()
  108. if (from) {
  109. try {
  110. // console.debug('copy file: ', from, dest)
  111. await fs.promises.copyFile(from, dest)
  112. return path.basename(from)
  113. } catch (e) {
  114. from = decodeURIComponent(from)
  115. await fs.promises.copyFile(from, dest)
  116. return path.basename(from)
  117. }
  118. }
  119. // support image
  120. // console.debug('read image: ', from, dest)
  121. const nImg = clipboard.readImage()
  122. if (nImg && !nImg.isEmpty()) {
  123. const rawExt = path.extname(dest)
  124. return await fs.promises.writeFile(
  125. dest.replace(rawExt, '.png'),
  126. nImg.toPNG()
  127. )
  128. }
  129. },
  130. toggleMaxOrMinActiveWindow (isToggleMin = false) {
  131. ipcRenderer.invoke('toggle-max-or-min-active-win', isToggleMin)
  132. },
  133. /**
  134. * internal
  135. * @param type
  136. * @param args
  137. * @private
  138. */
  139. async _callApplication (type, ...args) {
  140. return await ipcRenderer.invoke('call-application', type, ...args)
  141. },
  142. /**
  143. * internal
  144. * @param type
  145. * @param args
  146. * @private
  147. */
  148. async _callMainWin (type, ...args) {
  149. return await ipcRenderer.invoke('call-main-win', type, ...args)
  150. },
  151. getFilePathFromClipboard,
  152. getClipboardData,
  153. setZoomFactor (factor) {
  154. webFrame.setZoomFactor(factor)
  155. },
  156. setZoomLevel (level) {
  157. webFrame.setZoomLevel(level)
  158. },
  159. isAbsolutePath: path.isAbsolute.bind(path)
  160. })