app.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import { app, ipcMain, Menu, Tray, shell, screen, globalShortcut, MenuItemConstructorOptions } 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 { loadConfig } 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. private configStore: any
  23. userPluginsPath: string
  24. constructor () {
  25. remote.initialize()
  26. this.useBuiltinGraphics()
  27. this.ptyManager.init(this)
  28. ipcMain.on('app:config-change', (_event, config) => {
  29. this.broadcast('host:config-change', config)
  30. this.configStore = 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. this.configStore = loadConfig()
  55. if (process.platform === 'linux') {
  56. app.commandLine.appendSwitch('no-sandbox')
  57. if (((this.configStore.appearance || {}).opacity || 1) !== 1) {
  58. app.commandLine.appendSwitch('enable-transparent-visuals')
  59. app.disableHardwareAcceleration()
  60. }
  61. if (this.configStore.hacks?.disableGPU) {
  62. app.commandLine.appendSwitch('disable-gpu')
  63. app.disableHardwareAcceleration()
  64. }
  65. }
  66. this.userPluginsPath = path.join(
  67. app.getPath('userData'),
  68. 'plugins',
  69. )
  70. if (!fs.existsSync(this.userPluginsPath)) {
  71. fs.mkdirSync(this.userPluginsPath)
  72. }
  73. app.commandLine.appendSwitch('disable-http-cache')
  74. app.commandLine.appendSwitch('max-active-webgl-contexts', '9000')
  75. app.commandLine.appendSwitch('lang', 'EN')
  76. app.allowRendererProcessReuse = false
  77. for (const flag of this.configStore.flags || [['force_discrete_gpu', '0']]) {
  78. app.commandLine.appendSwitch(flag[0], flag[1])
  79. }
  80. app.on('window-all-closed', () => {
  81. if (this.quitRequested || process.platform !== 'darwin') {
  82. app.quit()
  83. }
  84. })
  85. }
  86. init (): void {
  87. screen.on('display-metrics-changed', () => this.broadcast('host:display-metrics-changed'))
  88. screen.on('display-added', () => this.broadcast('host:displays-changed'))
  89. screen.on('display-removed', () => this.broadcast('host:displays-changed'))
  90. }
  91. async newWindow (options?: WindowOptions): Promise<Window> {
  92. const window = new Window(this, options)
  93. this.windows.push(window)
  94. if (this.windows.length === 1){
  95. window.makeMain()
  96. }
  97. window.visible$.subscribe(visible => {
  98. if (visible) {
  99. this.disableTray()
  100. } else {
  101. this.enableTray()
  102. }
  103. })
  104. window.closed$.subscribe(() => {
  105. this.windows = this.windows.filter(x => x !== window)
  106. if (!this.windows.some(x => x.isMainWindow)) {
  107. this.windows[0]?.makeMain()
  108. this.windows[0]?.present()
  109. }
  110. })
  111. if (process.platform === 'darwin') {
  112. this.setupMenu()
  113. }
  114. await window.ready
  115. window.present()
  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. async send (event: string, ...args: any[]): Promise<void> {
  146. if (!this.hasWindows()) {
  147. await this.newWindow()
  148. }
  149. this.windows.filter(w => !w.isDestroyed())[0].send(event, ...args)
  150. }
  151. enableTray (): void {
  152. if (this.tray || process.platform === 'linux') {
  153. return
  154. }
  155. if (process.platform === 'darwin') {
  156. this.tray = new Tray(`${app.getAppPath()}/assets/tray-darwinTemplate.png`)
  157. this.tray.setPressedImage(`${app.getAppPath()}/assets/tray-darwinHighlightTemplate.png`)
  158. } else {
  159. this.tray = new Tray(`${app.getAppPath()}/assets/tray.png`)
  160. }
  161. this.tray.on('click', () => setTimeout(() => this.focus()))
  162. const contextMenu = Menu.buildFromTemplate([{
  163. label: 'Show',
  164. click: () => this.focus(),
  165. }])
  166. if (process.platform !== 'darwin') {
  167. this.tray.setContextMenu(contextMenu)
  168. }
  169. this.tray.setToolTip(`Tabby ${app.getVersion()}`)
  170. }
  171. disableTray (): void {
  172. if (process.platform === 'linux') {
  173. return
  174. }
  175. this.tray?.destroy()
  176. this.tray = null
  177. }
  178. hasWindows (): boolean {
  179. return !!this.windows.length
  180. }
  181. focus (): void {
  182. for (const window of this.windows) {
  183. window.present()
  184. }
  185. }
  186. handleSecondInstance (argv: string[], cwd: string): void {
  187. this.presentAllWindows()
  188. this.windows[this.windows.length - 1].passCliArguments(argv, cwd, true)
  189. }
  190. private useBuiltinGraphics (): void {
  191. if (process.platform === 'win32') {
  192. const keyPath = 'SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences'
  193. const valueName = app.getPath('exe')
  194. if (!wnr.getRegistryValue(wnr.HK.CU, keyPath, valueName)) {
  195. wnr.setRegistryValue(wnr.HK.CU, keyPath, valueName, wnr.REG.SZ, 'GpuPreference=1;')
  196. }
  197. }
  198. }
  199. private setupMenu () {
  200. const template: MenuItemConstructorOptions[] = [
  201. {
  202. label: 'Application',
  203. submenu: [
  204. { role: 'about', label: 'About Tabby' },
  205. { type: 'separator' },
  206. {
  207. label: 'Preferences',
  208. accelerator: 'Cmd+,',
  209. click: async () => {
  210. if (!this.hasWindows()) {
  211. await this.newWindow()
  212. }
  213. this.windows[0].send('host:preferences-menu')
  214. },
  215. },
  216. { type: 'separator' },
  217. { role: 'services', submenu: [] },
  218. { type: 'separator' },
  219. { role: 'hide' },
  220. { role: 'hideOthers' },
  221. { role: 'unhide' },
  222. { type: 'separator' },
  223. {
  224. label: 'Quit',
  225. accelerator: 'Cmd+Q',
  226. click: () => {
  227. this.quitRequested = true
  228. app.quit()
  229. },
  230. },
  231. ],
  232. },
  233. {
  234. label: 'Edit',
  235. submenu: [
  236. { role: 'undo' },
  237. { role: 'redo' },
  238. { type: 'separator' },
  239. { role: 'cut' },
  240. { role: 'copy' },
  241. { role: 'paste' },
  242. { role: 'pasteAndMatchStyle' },
  243. { role: 'delete' },
  244. { role: 'selectAll' },
  245. ],
  246. },
  247. {
  248. label: 'View',
  249. submenu: [
  250. { role: 'toggleDevTools' },
  251. { type: 'separator' },
  252. { role: 'togglefullscreen' },
  253. ],
  254. },
  255. {
  256. role: 'window',
  257. submenu: [
  258. { role: 'minimize' },
  259. { role: 'zoom' },
  260. { type: 'separator' },
  261. { role: 'front' },
  262. ],
  263. },
  264. {
  265. role: 'help',
  266. submenu: [
  267. {
  268. label: 'Website',
  269. click () {
  270. shell.openExternal('https://eugeny.github.io/tabby')
  271. },
  272. },
  273. ],
  274. },
  275. ]
  276. if (process.env.TABBY_DEV) {
  277. template[2].submenu['unshift']({ role: 'reload' })
  278. }
  279. Menu.setApplicationMenu(Menu.buildFromTemplate(template))
  280. }
  281. }