app.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import { app, ipcMain, Menu, Tray, shell, screen, globalShortcut, MenuItemConstructorOptions, WebContents } from 'electron'
  2. import promiseIpc from 'electron-promise-ipc'
  3. import * as remote from '@electron/remote/main'
  4. import { exec } from 'mz/child_process'
  5. import * as path from 'path'
  6. import * as fs from 'fs'
  7. import { Subject, throttleTime } from 'rxjs'
  8. import { saveConfig } from './config'
  9. import { Window, WindowOptions } from './window'
  10. import { pluginManager } from './pluginManager'
  11. import { PTYManager } from './pty'
  12. /* eslint-disable block-scoped-var */
  13. try {
  14. var wnr = require('windows-native-registry') // eslint-disable-line @typescript-eslint/no-var-requires, no-var
  15. } catch (_) { }
  16. export class Application {
  17. private tray?: Tray
  18. private ptyManager = new PTYManager()
  19. private windows: Window[] = []
  20. private globalHotkey$ = new Subject<void>()
  21. private quitRequested = false
  22. userPluginsPath: string
  23. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  24. constructor (private configStore: any) {
  25. remote.initialize()
  26. this.useBuiltinGraphics()
  27. this.ptyManager.init(this)
  28. ipcMain.handle('app:save-config', async (event, config) => {
  29. await saveConfig(config)
  30. this.broadcastExcept('host:config-change', event.sender, config)
  31. })
  32. ipcMain.on('app:register-global-hotkey', (_event, specs) => {
  33. globalShortcut.unregisterAll()
  34. for (const spec of specs) {
  35. globalShortcut.register(spec, () => this.globalHotkey$.next())
  36. }
  37. })
  38. this.globalHotkey$.pipe(throttleTime(100)).subscribe(() => {
  39. this.onGlobalHotkey()
  40. })
  41. ;(promiseIpc as any).on('plugin-manager:install', (name, version) => {
  42. return pluginManager.install(this.userPluginsPath, name, version)
  43. })
  44. ;(promiseIpc as any).on('plugin-manager:uninstall', (name) => {
  45. return pluginManager.uninstall(this.userPluginsPath, name)
  46. })
  47. ;(promiseIpc as any).on('get-default-mac-shell', async () => {
  48. try {
  49. return (await exec(`/usr/bin/dscl . -read /Users/${process.env.LOGNAME} UserShell`))[0].toString().split(' ')[1].trim()
  50. } catch {
  51. return '/bin/bash'
  52. }
  53. })
  54. if (process.platform === 'linux') {
  55. app.commandLine.appendSwitch('no-sandbox')
  56. if ((this.configStore.appearance?.opacity || 1) !== 1) {
  57. app.commandLine.appendSwitch('enable-transparent-visuals')
  58. app.disableHardwareAcceleration()
  59. }
  60. }
  61. if (this.configStore.hacks?.disableGPU) {
  62. app.commandLine.appendSwitch('disable-gpu')
  63. app.disableHardwareAcceleration()
  64. }
  65. this.userPluginsPath = path.join(
  66. app.getPath('userData'),
  67. 'plugins',
  68. )
  69. if (!fs.existsSync(this.userPluginsPath)) {
  70. fs.mkdirSync(this.userPluginsPath)
  71. }
  72. app.commandLine.appendSwitch('disable-http-cache')
  73. app.commandLine.appendSwitch('max-active-webgl-contexts', '9000')
  74. app.commandLine.appendSwitch('lang', 'EN')
  75. for (const flag of this.configStore.flags || [['force_discrete_gpu', '0']]) {
  76. app.commandLine.appendSwitch(flag[0], flag[1])
  77. }
  78. app.on('before-quit', () => {
  79. this.quitRequested = true
  80. })
  81. app.on('window-all-closed', () => {
  82. if (this.quitRequested || process.platform !== 'darwin') {
  83. app.quit()
  84. }
  85. })
  86. }
  87. init (): void {
  88. screen.on('display-metrics-changed', () => this.broadcast('host:display-metrics-changed'))
  89. screen.on('display-added', () => this.broadcast('host:displays-changed'))
  90. screen.on('display-removed', () => this.broadcast('host:displays-changed'))
  91. }
  92. async newWindow (options?: WindowOptions): Promise<Window> {
  93. const window = new Window(this, this.configStore, options)
  94. this.windows.push(window)
  95. if (this.windows.length === 1) {
  96. window.makeMain()
  97. }
  98. window.visible$.subscribe(visible => {
  99. if (visible) {
  100. this.disableTray()
  101. } else {
  102. this.enableTray()
  103. }
  104. })
  105. window.closed$.subscribe(() => {
  106. this.windows = this.windows.filter(x => x !== window)
  107. if (!this.windows.some(x => x.isMainWindow)) {
  108. this.windows[0]?.makeMain()
  109. this.windows[0]?.present()
  110. }
  111. })
  112. if (process.platform === 'darwin') {
  113. this.setupMenu()
  114. }
  115. await window.ready
  116. return window
  117. }
  118. onGlobalHotkey (): void {
  119. let isPresent = this.windows.some(x => x.isFocused() && x.isVisible())
  120. const isDockedOnTop = this.windows.some(x => x.isDockedOnTop())
  121. if (isDockedOnTop) {
  122. // if docked and on top, hide even if not focused right now
  123. isPresent = this.windows.some(x => x.isVisible())
  124. }
  125. if (isPresent) {
  126. for (const window of this.windows) {
  127. window.hide()
  128. }
  129. } else {
  130. for (const window of this.windows) {
  131. window.present()
  132. }
  133. }
  134. }
  135. presentAllWindows (): void {
  136. for (const window of this.windows) {
  137. window.present()
  138. }
  139. }
  140. broadcast (event: string, ...args: any[]): void {
  141. for (const window of this.windows) {
  142. window.send(event, ...args)
  143. }
  144. }
  145. broadcastExcept (event: string, except: WebContents, ...args: any[]): void {
  146. for (const window of this.windows) {
  147. if (window.webContents.id !== except.id) {
  148. window.send(event, ...args)
  149. }
  150. }
  151. }
  152. async send (event: string, ...args: any[]): Promise<void> {
  153. if (!this.hasWindows()) {
  154. await this.newWindow()
  155. }
  156. this.windows.filter(w => !w.isDestroyed())[0].send(event, ...args)
  157. }
  158. enableTray (): void {
  159. if (!!this.tray || process.platform === 'linux') {
  160. return
  161. }
  162. if (process.platform === 'darwin') {
  163. this.tray = new Tray(`${app.getAppPath()}/assets/tray-darwinTemplate.png`)
  164. this.tray.setPressedImage(`${app.getAppPath()}/assets/tray-darwinHighlightTemplate.png`)
  165. } else {
  166. this.tray = new Tray(`${app.getAppPath()}/assets/tray.png`)
  167. }
  168. this.tray.on('click', () => setTimeout(() => this.focus()))
  169. const contextMenu = Menu.buildFromTemplate([{
  170. label: 'Show',
  171. click: () => this.focus(),
  172. }])
  173. if (process.platform !== 'darwin') {
  174. this.tray.setContextMenu(contextMenu)
  175. }
  176. this.tray.setToolTip(`Tabby ${app.getVersion()}`)
  177. }
  178. disableTray (): void {
  179. if (process.platform === 'linux') {
  180. return
  181. }
  182. this.tray?.destroy()
  183. this.tray = null
  184. }
  185. hasWindows (): boolean {
  186. return !!this.windows.length
  187. }
  188. focus (): void {
  189. for (const window of this.windows) {
  190. window.present()
  191. }
  192. }
  193. async handleSecondInstance (argv: string[], cwd: string): Promise<void> {
  194. if (!this.windows.length) {
  195. await this.newWindow()
  196. }
  197. this.presentAllWindows()
  198. this.windows[this.windows.length - 1].passCliArguments(argv, cwd, true)
  199. }
  200. private useBuiltinGraphics (): void {
  201. if (process.platform === 'win32') {
  202. const keyPath = 'SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences'
  203. const valueName = app.getPath('exe')
  204. if (!wnr.getRegistryValue(wnr.HK.CU, keyPath, valueName)) {
  205. wnr.setRegistryValue(wnr.HK.CU, keyPath, valueName, wnr.REG.SZ, 'GpuPreference=1;')
  206. }
  207. }
  208. }
  209. private setupMenu () {
  210. const template: MenuItemConstructorOptions[] = [
  211. {
  212. label: 'Application',
  213. submenu: [
  214. { role: 'about', label: 'About Tabby' },
  215. { type: 'separator' },
  216. {
  217. label: 'Preferences',
  218. accelerator: 'Cmd+,',
  219. click: async () => {
  220. if (!this.hasWindows()) {
  221. await this.newWindow()
  222. }
  223. this.windows[0].send('host:preferences-menu')
  224. },
  225. },
  226. { type: 'separator' },
  227. { role: 'services', submenu: [] },
  228. { type: 'separator' },
  229. { role: 'hide' },
  230. { role: 'hideOthers' },
  231. { role: 'unhide' },
  232. { type: 'separator' },
  233. {
  234. label: 'Quit',
  235. accelerator: 'Cmd+Q',
  236. click: () => {
  237. this.quitRequested = true
  238. app.quit()
  239. },
  240. },
  241. ],
  242. },
  243. {
  244. label: 'Edit',
  245. submenu: [
  246. { role: 'undo' },
  247. { role: 'redo' },
  248. { type: 'separator' },
  249. { role: 'cut' },
  250. { role: 'copy' },
  251. { role: 'paste' },
  252. { role: 'pasteAndMatchStyle' },
  253. { role: 'delete' },
  254. { role: 'selectAll' },
  255. ],
  256. },
  257. {
  258. label: 'View',
  259. submenu: [
  260. { role: 'toggleDevTools' },
  261. { type: 'separator' },
  262. { role: 'togglefullscreen' },
  263. ],
  264. },
  265. {
  266. role: 'window',
  267. submenu: [
  268. { role: 'minimize' },
  269. { role: 'zoom' },
  270. { type: 'separator' },
  271. { role: 'front' },
  272. ],
  273. },
  274. {
  275. role: 'help',
  276. submenu: [
  277. {
  278. label: 'Website',
  279. click () {
  280. shell.openExternal('https://eugeny.github.io/tabby')
  281. },
  282. },
  283. ],
  284. },
  285. ]
  286. if (process.env.TABBY_DEV) {
  287. template[2].submenu['unshift']({ role: 'reload' })
  288. }
  289. Menu.setApplicationMenu(Menu.buildFromTemplate(template))
  290. }
  291. }