app.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. for (const flag of this.configStore.flags || [['force_discrete_gpu', '0']]) {
  77. app.commandLine.appendSwitch(flag[0], flag[1])
  78. }
  79. app.on('window-all-closed', () => {
  80. if (this.quitRequested || process.platform !== 'darwin') {
  81. app.quit()
  82. }
  83. })
  84. }
  85. init (): void {
  86. screen.on('display-metrics-changed', () => this.broadcast('host:display-metrics-changed'))
  87. screen.on('display-added', () => this.broadcast('host:displays-changed'))
  88. screen.on('display-removed', () => this.broadcast('host:displays-changed'))
  89. }
  90. async newWindow (options?: WindowOptions): Promise<Window> {
  91. const window = new Window(this, options)
  92. this.windows.push(window)
  93. if (this.windows.length === 1){
  94. window.makeMain()
  95. }
  96. window.visible$.subscribe(visible => {
  97. if (visible) {
  98. this.disableTray()
  99. } else {
  100. this.enableTray()
  101. }
  102. })
  103. window.closed$.subscribe(() => {
  104. this.windows = this.windows.filter(x => x !== window)
  105. if (!this.windows.some(x => x.isMainWindow)) {
  106. this.windows[0]?.makeMain()
  107. this.windows[0]?.present()
  108. }
  109. })
  110. if (process.platform === 'darwin') {
  111. this.setupMenu()
  112. }
  113. await window.ready
  114. window.present()
  115. return window
  116. }
  117. onGlobalHotkey (): void {
  118. let isPresent = this.windows.some(x => x.isFocused() && x.isVisible())
  119. const isDockedOnTop = this.windows.some(x => x.isDockedOnTop())
  120. if (isDockedOnTop) {
  121. // if docked and on top, hide even if not focused right now
  122. isPresent = this.windows.some(x => x.isVisible())
  123. }
  124. if (isPresent) {
  125. for (const window of this.windows) {
  126. window.hide()
  127. }
  128. } else {
  129. for (const window of this.windows) {
  130. window.present()
  131. }
  132. }
  133. }
  134. presentAllWindows (): void {
  135. for (const window of this.windows) {
  136. window.present()
  137. }
  138. }
  139. broadcast (event: string, ...args: any[]): void {
  140. for (const window of this.windows) {
  141. window.send(event, ...args)
  142. }
  143. }
  144. async send (event: string, ...args: any[]): Promise<void> {
  145. if (!this.hasWindows()) {
  146. await this.newWindow()
  147. }
  148. this.windows.filter(w => !w.isDestroyed())[0].send(event, ...args)
  149. }
  150. enableTray (): void {
  151. if (this.tray || process.platform === 'linux') {
  152. return
  153. }
  154. if (process.platform === 'darwin') {
  155. this.tray = new Tray(`${app.getAppPath()}/assets/tray-darwinTemplate.png`)
  156. this.tray.setPressedImage(`${app.getAppPath()}/assets/tray-darwinHighlightTemplate.png`)
  157. } else {
  158. this.tray = new Tray(`${app.getAppPath()}/assets/tray.png`)
  159. }
  160. this.tray.on('click', () => setTimeout(() => this.focus()))
  161. const contextMenu = Menu.buildFromTemplate([{
  162. label: 'Show',
  163. click: () => this.focus(),
  164. }])
  165. if (process.platform !== 'darwin') {
  166. this.tray.setContextMenu(contextMenu)
  167. }
  168. this.tray.setToolTip(`Tabby ${app.getVersion()}`)
  169. }
  170. disableTray (): void {
  171. if (process.platform === 'linux') {
  172. return
  173. }
  174. this.tray?.destroy()
  175. this.tray = null
  176. }
  177. hasWindows (): boolean {
  178. return !!this.windows.length
  179. }
  180. focus (): void {
  181. for (const window of this.windows) {
  182. window.present()
  183. }
  184. }
  185. handleSecondInstance (argv: string[], cwd: string): void {
  186. this.presentAllWindows()
  187. this.windows[this.windows.length - 1].passCliArguments(argv, cwd, true)
  188. }
  189. private useBuiltinGraphics (): void {
  190. if (process.platform === 'win32') {
  191. const keyPath = 'SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences'
  192. const valueName = app.getPath('exe')
  193. if (!wnr.getRegistryValue(wnr.HK.CU, keyPath, valueName)) {
  194. wnr.setRegistryValue(wnr.HK.CU, keyPath, valueName, wnr.REG.SZ, 'GpuPreference=1;')
  195. }
  196. }
  197. }
  198. private setupMenu () {
  199. const template: MenuItemConstructorOptions[] = [
  200. {
  201. label: 'Application',
  202. submenu: [
  203. { role: 'about', label: 'About Tabby' },
  204. { type: 'separator' },
  205. {
  206. label: 'Preferences',
  207. accelerator: 'Cmd+,',
  208. click: async () => {
  209. if (!this.hasWindows()) {
  210. await this.newWindow()
  211. }
  212. this.windows[0].send('host:preferences-menu')
  213. },
  214. },
  215. { type: 'separator' },
  216. { role: 'services', submenu: [] },
  217. { type: 'separator' },
  218. { role: 'hide' },
  219. { role: 'hideOthers' },
  220. { role: 'unhide' },
  221. { type: 'separator' },
  222. {
  223. label: 'Quit',
  224. accelerator: 'Cmd+Q',
  225. click: () => {
  226. this.quitRequested = true
  227. app.quit()
  228. },
  229. },
  230. ],
  231. },
  232. {
  233. label: 'Edit',
  234. submenu: [
  235. { role: 'undo' },
  236. { role: 'redo' },
  237. { type: 'separator' },
  238. { role: 'cut' },
  239. { role: 'copy' },
  240. { role: 'paste' },
  241. { role: 'pasteAndMatchStyle' },
  242. { role: 'delete' },
  243. { role: 'selectAll' },
  244. ],
  245. },
  246. {
  247. label: 'View',
  248. submenu: [
  249. { role: 'toggleDevTools' },
  250. { type: 'separator' },
  251. { role: 'togglefullscreen' },
  252. ],
  253. },
  254. {
  255. role: 'window',
  256. submenu: [
  257. { role: 'minimize' },
  258. { role: 'zoom' },
  259. { type: 'separator' },
  260. { role: 'front' },
  261. ],
  262. },
  263. {
  264. role: 'help',
  265. submenu: [
  266. {
  267. label: 'Website',
  268. click () {
  269. shell.openExternal('https://eugeny.github.io/tabby')
  270. },
  271. },
  272. ],
  273. },
  274. ]
  275. if (process.env.TABBY_DEV) {
  276. template[2].submenu['unshift']({ role: 'reload' })
  277. }
  278. Menu.setApplicationMenu(Menu.buildFromTemplate(template))
  279. }
  280. }