index.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import * as electron from 'electron'
  2. import { app, BrowserWindow, desktopCapturer, ipcMain, Menu, Notification, screen, shell, Tray } from 'electron'
  3. import path, { join } from 'path'
  4. import { electronApp, is, optimizer } from '@electron-toolkit/utils'
  5. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  6. // @ts-ignore
  7. import { useCheckUpdate } from './useCheckUpdate'
  8. import vimConfig from '/src/renderer/src/config/VimConfig'
  9. //刷新托盘定时器
  10. let flashIconTimer: NodeJS.Timeout | null = null
  11. let cutWindow: BrowserWindow | null = null
  12. const iconPath =
  13. process.platform === 'win32' ? '../../resources/icon.ico' : '../../resources/icon.png'
  14. const emptyIconPath =
  15. process.platform === 'win32' ? '../../resources/empty.ico' : '../../resources/empty.png'
  16. let appIcon: Electron.Tray | null = null
  17. function createWindow(): void {
  18. // Create the browser window.
  19. const mainWindow = new BrowserWindow({
  20. show: false,
  21. autoHideMenuBar: true,
  22. webPreferences: {
  23. contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
  24. webSecurity: true,
  25. nodeIntegration: true, // 解决require is not defined问题
  26. webviewTag: true, // 解决webview无法显示问题
  27. preload: join(__dirname, '../preload/index.js'),
  28. sandbox: false
  29. },
  30. useContentSize: true,
  31. width: 1000,
  32. height: 600,
  33. frame: false
  34. })
  35. mainWindow.on('ready-to-show', () => {
  36. mainWindow.show()
  37. useCheckUpdate(app)
  38. })
  39. // 处理窗口失去焦点事件
  40. mainWindow.on('blur', () => {
  41. mainWindow.webContents.send('BLUR', true)
  42. })
  43. // 处理窗口获得焦点事件
  44. mainWindow.on('focus', () => {
  45. mainWindow.webContents.send('FOCUS', false)
  46. })
  47. /**
  48. * 系统休眠
  49. */
  50. electron.powerMonitor.on('suspend', () => {
  51. mainWindow.webContents.send('SLEEP')
  52. })
  53. /**
  54. * 系统唤醒
  55. */
  56. electron.powerMonitor.on('resume', () => {
  57. mainWindow.webContents.send('RESUME')
  58. })
  59. mainWindow.webContents.setWindowOpenHandler((details) => {
  60. shell.openExternal(details.url).then()
  61. return { action: 'deny' }
  62. })
  63. // HMR for renderer base on electron-vite cli.
  64. // Load the remote URL for development or the local html file for production.
  65. if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
  66. mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']).then()
  67. } else {
  68. mainWindow.loadFile(join(__dirname, '../renderer/index.html')).then()
  69. }
  70. ipcMain.on('min', () => {
  71. mainWindow.minimize()
  72. })
  73. ipcMain.on('openURL', (e: Electron.IpcMainEvent, url: string) => {
  74. e.preventDefault()
  75. shell.openExternal(url).then()
  76. })
  77. ipcMain.on('max', () => {
  78. if (mainWindow.isMaximized()) {
  79. mainWindow.unmaximize()
  80. } else {
  81. mainWindow.maximize()
  82. }
  83. })
  84. // 只是隐藏任务栏
  85. ipcMain.on('close', () => {
  86. hideMain(mainWindow)
  87. })
  88. // 闪烁任务栏
  89. ipcMain.on('flashFrame', () => {
  90. //没有聚焦
  91. if (!mainWindow.isFocused()) {
  92. mainWindow.flashFrame(true)
  93. }
  94. })
  95. /**
  96. * 发生系统通知
  97. * @param content 通知内容
  98. * @param url 点击通知跳转的url
  99. */
  100. ipcMain.on(
  101. 'NOTIFICATION',
  102. (e: Electron.IpcMainEvent, content: string, url: string | undefined) => {
  103. e.preventDefault()
  104. if (!mainWindow.isFocused()) {
  105. new Notification({
  106. title: vimConfig.name,
  107. body: content,
  108. timeoutType: 'never'
  109. })
  110. .on('click', (event) => {
  111. event.preventDefault()
  112. showMain(mainWindow)
  113. if (url) {
  114. shell.openExternal(url).then()
  115. }
  116. })
  117. .show()
  118. }
  119. }
  120. )
  121. appIcon = createTray(mainWindow, iconPath)
  122. // 闪烁任务栏
  123. ipcMain.on('flashIcon', () => {
  124. if (!mainWindow.isVisible()) {
  125. clearFlashIconTimer()
  126. let count = 0
  127. flashIconTimer = setInterval(() => {
  128. count++
  129. if (appIcon) {
  130. if (count % 2 === 0) {
  131. appIcon.setImage(path.join(__dirname, emptyIconPath))
  132. } else {
  133. appIcon.setImage(path.join(__dirname, iconPath))
  134. }
  135. }
  136. }, 500)
  137. }
  138. })
  139. ipcMain.on('clearFlashIcon', () => {
  140. clearFlashIconTimer()
  141. if (appIcon) {
  142. appIcon.setImage(path.join(__dirname, iconPath))
  143. }
  144. })
  145. // 获取设备窗口信息
  146. ipcMain.handle('getSource', async () => {
  147. const sources = await desktopCapturer.getSources({
  148. types: ['screen'],
  149. thumbnailSize: getSize()
  150. })
  151. //当前的屏幕id
  152. const { id } = screen.getDisplayNearestPoint(screen.getCursorScreenPoint())
  153. //多屏情况下,只截图当前的屏幕
  154. return sources.find((source) => source.display_id === id + '') ?? sources[0]
  155. })
  156. /**
  157. * 点击截屏弹出截屏窗口
  158. */
  159. ipcMain.on('OPEN_CUT_SCREEN', async (event, args) => {
  160. event.preventDefault()
  161. closeCutWindow()
  162. if (args) {
  163. mainWindow.hide()
  164. }
  165. await createCutWindow()
  166. if (cutWindow) {
  167. cutWindow.show()
  168. }
  169. })
  170. /**
  171. * 截屏事件
  172. */
  173. ipcMain.on('CUT_SCREEN', async (e, cutInfo) => {
  174. e.preventDefault()
  175. closeCutWindow()
  176. mainWindow.webContents.send('GET_CUT_INFO', cutInfo)
  177. mainWindow.show()
  178. })
  179. /**
  180. * 关闭截屏窗口
  181. */
  182. ipcMain.on('CLOSE_CUT_SCREEN', async () => {
  183. closeCutWindow()
  184. mainWindow.show()
  185. })
  186. }
  187. /**
  188. * 隐藏窗口,隐藏任务栏
  189. */
  190. function hideMain(win: BrowserWindow) {
  191. win.setSkipTaskbar(true)
  192. win.hide()
  193. }
  194. /**
  195. * 清除图片闪烁的定时器
  196. */
  197. function clearFlashIconTimer() {
  198. if (flashIconTimer) {
  199. clearInterval(flashIconTimer)
  200. if (appIcon) {
  201. appIcon.setImage(path.join(__dirname, iconPath))
  202. }
  203. }
  204. }
  205. /**
  206. * 获取截屏的size
  207. */
  208. function getSize() {
  209. const { size, scaleFactor } = screen.getDisplayNearestPoint(screen.getCursorScreenPoint())
  210. return {
  211. width: Math.floor(size.width * scaleFactor),
  212. height: Math.floor(size.height * scaleFactor)
  213. }
  214. }
  215. /**
  216. * 创建一个截屏窗口
  217. */
  218. async function createCutWindow() {
  219. cutWindow = new BrowserWindow({
  220. useContentSize: true,
  221. autoHideMenuBar: true,
  222. movable: false,
  223. frame: false,
  224. resizable: false,
  225. hasShadow: false,
  226. transparent: true,
  227. fullscreen: true,
  228. simpleFullscreen: true,
  229. alwaysOnTop: false,
  230. webPreferences: {
  231. contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
  232. webSecurity: false,
  233. nodeIntegration: true, // 解决require is not defined问题
  234. webviewTag: true, // 解决webview无法显示问题
  235. preload: join(__dirname, '../preload/index.js'),
  236. sandbox: false
  237. }
  238. })
  239. const cutPage = process.platform === 'win32' ? 'cutWin32' : 'cutLinux'
  240. if (process.env['ELECTRON_RENDERER_URL']) {
  241. await cutWindow.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#/${cutPage}`)
  242. if (!process.env.IS_TEST) cutWindow.webContents.openDevTools()
  243. } else {
  244. await cutWindow.loadFile(join(__dirname, '../renderer/index.html'), { hash: cutPage })
  245. }
  246. cutWindow.maximize()
  247. cutWindow.setFullScreen(true)
  248. }
  249. function closeCutWindow() {
  250. cutWindow && cutWindow.close()
  251. cutWindow = null
  252. }
  253. app.whenReady().then(() => {
  254. electronApp.setAppUserModelId('com.electron')
  255. app.on('browser-window-created', (_, window) => {
  256. optimizer.watchWindowShortcuts(window)
  257. })
  258. createWindow()
  259. app.on('activate', () => {
  260. if (BrowserWindow.getAllWindows().length === 0) createWindow()
  261. })
  262. })
  263. app.on('window-all-closed', () => {
  264. if (process.platform !== 'darwin') {
  265. app.quit()
  266. }
  267. })
  268. app.on('browser-window-focus', () => {
  269. clearFlashIconTimer()
  270. })
  271. /**
  272. * 创建托盘图标
  273. * @param win
  274. * @param iconPath
  275. */
  276. function createTray(win: BrowserWindow, iconPath: string) {
  277. // 托盘
  278. const appIcon = new Tray(path.join(__dirname, iconPath))
  279. const contextMenu = Menu.buildFromTemplate([
  280. {
  281. label: '显示',
  282. click: () => {
  283. showMain(win)
  284. }
  285. },
  286. {
  287. label: '退出',
  288. click: () => {
  289. app.quit()
  290. }
  291. }
  292. ])
  293. appIcon.setToolTip(vimConfig.name)
  294. appIcon.setContextMenu(contextMenu)
  295. appIcon.on('click', () => {
  296. showMain(win)
  297. })
  298. return appIcon
  299. }
  300. /**
  301. * 展示窗口,打开任务栏
  302. */
  303. function showMain(win: BrowserWindow) {
  304. win.setSkipTaskbar(false)
  305. win.show()
  306. clearFlashIconTimer()
  307. }