app.ts 10 KB

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