window.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import { autoUpdater } from 'electron-updater'
  2. import { Subject, Observable, debounceTime } from 'rxjs'
  3. import { BrowserWindow, app, ipcMain, Rectangle, Menu, screen, BrowserWindowConstructorOptions, TouchBar, nativeImage, WebContents } from 'electron'
  4. import ElectronConfig = require('electron-config')
  5. import { enable as enableRemote } from '@electron/remote/main'
  6. import * as path from 'path'
  7. import macOSRelease from 'macos-release'
  8. import { compare as compareVersions } from 'compare-versions'
  9. import type { Application } from './app'
  10. import { parseArgs } from './cli'
  11. export interface WindowOptions {
  12. hidden?: boolean
  13. }
  14. const macOSVibrancyType: any = process.platform === 'darwin' ? compareVersions(macOSRelease().version || '0.0', '10.14', '>=') ? 'under-window' : 'dark' : null
  15. const activityIcon = nativeImage.createFromPath(`${app.getAppPath()}/assets/activity.png`)
  16. export class Window {
  17. ready: Promise<void>
  18. isMainWindow = false
  19. webContents: WebContents
  20. private visible = new Subject<boolean>()
  21. private closed = new Subject<void>()
  22. private window?: BrowserWindow
  23. private windowConfig: ElectronConfig
  24. private windowBounds?: Rectangle
  25. private closing = false
  26. private touchBarControl: any
  27. private dockHidden = false
  28. get visible$ (): Observable<boolean> { return this.visible }
  29. get closed$ (): Observable<void> { return this.closed }
  30. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  31. constructor (private application: Application, private configStore: any, options?: WindowOptions) {
  32. options = options ?? {}
  33. this.windowConfig = new ElectronConfig({ name: 'window' })
  34. this.windowBounds = this.windowConfig.get('windowBoundaries')
  35. const maximized = this.windowConfig.get('maximized')
  36. const bwOptions: BrowserWindowConstructorOptions = {
  37. width: 800,
  38. height: 600,
  39. title: 'Tabby',
  40. minWidth: 400,
  41. minHeight: 300,
  42. webPreferences: {
  43. nodeIntegration: true,
  44. preload: path.join(__dirname, 'sentry.js'),
  45. backgroundThrottling: false,
  46. contextIsolation: false,
  47. },
  48. maximizable: true,
  49. frame: false,
  50. transparent: true,
  51. show: false,
  52. backgroundColor: '#00000000',
  53. acceptFirstMouse: true,
  54. }
  55. if (this.windowBounds) {
  56. Object.assign(bwOptions, this.windowBounds)
  57. const closestDisplay = screen.getDisplayNearestPoint( { x: this.windowBounds.x, y: this.windowBounds.y } )
  58. const [left1, top1, right1, bottom1] = [this.windowBounds.x, this.windowBounds.y, this.windowBounds.x + this.windowBounds.width, this.windowBounds.y + this.windowBounds.height]
  59. const [left2, top2, right2, bottom2] = [closestDisplay.bounds.x, closestDisplay.bounds.y, closestDisplay.bounds.x + closestDisplay.bounds.width, closestDisplay.bounds.y + closestDisplay.bounds.height]
  60. if ((left2 > right1 || right2 < left1 || top2 > bottom1 || bottom2 < top1) && !maximized) {
  61. bwOptions.x = closestDisplay.bounds.width / 2 - bwOptions.width / 2
  62. bwOptions.y = closestDisplay.bounds.height / 2 - bwOptions.height / 2
  63. }
  64. }
  65. if (this.configStore.appearance?.frame === 'native') {
  66. bwOptions.frame = true
  67. } else {
  68. bwOptions.titleBarStyle = 'hidden'
  69. if (process.platform === 'win32') {
  70. bwOptions.titleBarOverlay = {
  71. color: '#00000000',
  72. }
  73. }
  74. }
  75. this.window = new BrowserWindow(bwOptions)
  76. // https://github.com/electron/electron/issues/39959#issuecomment-1758736966
  77. this.window.on('blur', () => {
  78. this.window.setBackgroundColor('#00000000')
  79. })
  80. this.window.on('focus', () => {
  81. this.window.setBackgroundColor('#00000000')
  82. })
  83. this.webContents = this.window.webContents
  84. this.window.once('ready-to-show', () => {
  85. if (process.platform === 'darwin') {
  86. this.window.setVibrancy(macOSVibrancyType)
  87. } else if (process.platform === 'win32' && this.configStore.appearance?.vibrancy) {
  88. this.setVibrancy(true)
  89. }
  90. if (!options.hidden) {
  91. if (maximized) {
  92. this.window.maximize()
  93. } else {
  94. this.window.show()
  95. }
  96. this.window.focus()
  97. this.window.moveTop()
  98. application.focus()
  99. }
  100. })
  101. this.window.on('blur', () => {
  102. if (
  103. (this.configStore.appearance?.dock ?? 'off') !== 'off' &&
  104. this.configStore.appearance?.dockHideOnBlur &&
  105. !BrowserWindow.getFocusedWindow()
  106. ) {
  107. this.hide()
  108. }
  109. })
  110. enableRemote(this.window.webContents)
  111. this.window.loadURL(`file://${app.getAppPath()}/dist/index.html`, { extraHeaders: 'pragma: no-cache\n' })
  112. this.window.webContents.setVisualZoomLevelLimits(1, 1)
  113. this.window.webContents.setZoomFactor(1)
  114. this.window.webContents.session.setPermissionCheckHandler(() => true)
  115. this.window.webContents.session.setDevicePermissionHandler(() => true)
  116. if (process.platform === 'darwin') {
  117. this.touchBarControl = new TouchBar.TouchBarSegmentedControl({
  118. segments: [],
  119. change: index => this.send('touchbar-selection', index),
  120. })
  121. this.window.setTouchBar(new TouchBar({
  122. items: [this.touchBarControl],
  123. }))
  124. } else {
  125. this.window.setMenu(null)
  126. }
  127. this.setupWindowManagement()
  128. this.setupUpdater()
  129. this.ready = new Promise(resolve => {
  130. const listener = event => {
  131. if (event.sender === this.window.webContents) {
  132. ipcMain.removeListener('app:ready', listener as any)
  133. resolve()
  134. }
  135. }
  136. ipcMain.on('app:ready', listener)
  137. })
  138. }
  139. makeMain (): void {
  140. this.isMainWindow = true
  141. this.window.webContents.send('host:became-main-window')
  142. }
  143. setMaterial (material: 'mica'|'acrylic'|'auto'): void {
  144. this.window.setBackgroundMaterial(material)
  145. }
  146. setVibrancy (enabled: boolean): void {
  147. if (process.platform === 'darwin') {
  148. this.window.setVibrancy(enabled ? macOSVibrancyType : null)
  149. }
  150. }
  151. focus (): void {
  152. this.window.focus()
  153. }
  154. send (event: string, ...args: any[]): void {
  155. if (!this.window) {
  156. return
  157. }
  158. this.window.webContents.send(event, ...args)
  159. if (event === 'host:config-change') {
  160. this.configStore = args[0]
  161. this.enableDockedWindowStyles(this.isDockedOnTop())
  162. }
  163. }
  164. isDestroyed (): boolean {
  165. return !this.window || this.window.isDestroyed()
  166. }
  167. isFocused (): boolean {
  168. return this.window.isFocused()
  169. }
  170. isVisible (): boolean {
  171. return this.window.isVisible()
  172. }
  173. isDockedOnTop (): boolean {
  174. return this.isMainWindow && this.configStore.appearance?.dock && this.configStore.appearance?.dock !== 'off' && (this.configStore.appearance?.dockAlwaysOnTop ?? true)
  175. }
  176. async hide (): Promise<void> {
  177. if (process.platform === 'darwin') {
  178. // Lose focus
  179. Menu.sendActionToFirstResponder('hide:')
  180. if (this.isDockedOnTop()) {
  181. await this.enableDockedWindowStyles(false)
  182. }
  183. }
  184. this.window.blur()
  185. this.window.hide()
  186. }
  187. async show (): Promise<void> {
  188. await this.enableDockedWindowStyles(this.isDockedOnTop())
  189. this.window.show()
  190. this.window.focus()
  191. }
  192. async present (): Promise<void> {
  193. await this.show()
  194. this.window.moveTop()
  195. }
  196. passCliArguments (argv: string[], cwd: string, secondInstance: boolean): void {
  197. this.send('cli', parseArgs(argv, cwd), cwd, secondInstance)
  198. }
  199. private async enableDockedWindowStyles (enabled: boolean) {
  200. if (process.platform === 'darwin') {
  201. if (enabled) {
  202. if (!this.dockHidden) {
  203. app.dock.hide()
  204. this.dockHidden = true
  205. }
  206. this.window.setAlwaysOnTop(true, 'screen-saver', 1)
  207. if (!this.window.isVisibleOnAllWorkspaces()) {
  208. this.window.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })
  209. }
  210. if (this.window.fullScreenable) {
  211. this.window.setFullScreenable(false)
  212. }
  213. } else {
  214. if (this.dockHidden) {
  215. await app.dock.show()
  216. this.dockHidden = false
  217. }
  218. if (this.window.isAlwaysOnTop()) {
  219. this.window.setAlwaysOnTop(false)
  220. }
  221. if (this.window.isVisibleOnAllWorkspaces()) {
  222. this.window.setVisibleOnAllWorkspaces(false)
  223. }
  224. if (!this.window.fullScreenable) {
  225. this.window.setFullScreenable(true)
  226. }
  227. }
  228. }
  229. }
  230. private setupWindowManagement () {
  231. this.window.on('show', () => {
  232. this.visible.next(true)
  233. this.send('host:window-shown')
  234. })
  235. this.window.on('hide', () => {
  236. this.visible.next(false)
  237. })
  238. const moveSubscription = new Observable<void>(observer => {
  239. this.window.on('move', () => observer.next())
  240. }).pipe(debounceTime(250)).subscribe(() => {
  241. this.send('host:window-moved')
  242. })
  243. this.window.on('closed', () => {
  244. moveSubscription.unsubscribe()
  245. })
  246. this.window.on('enter-full-screen', () => this.send('host:window-enter-full-screen'))
  247. this.window.on('leave-full-screen', () => this.send('host:window-leave-full-screen'))
  248. this.window.on('maximize', () => this.send('host:window-maximized'))
  249. this.window.on('unmaximize', () => this.send('host:window-unmaximized'))
  250. this.window.on('close', event => {
  251. if (!this.closing) {
  252. event.preventDefault()
  253. this.send('host:window-close-request')
  254. return
  255. }
  256. this.windowConfig.set('windowBoundaries', this.windowBounds)
  257. this.windowConfig.set('maximized', this.window.isMaximized())
  258. })
  259. this.window.on('closed', () => {
  260. this.destroy()
  261. })
  262. this.window.on('resize', () => {
  263. if (!this.window.isMaximized()) {
  264. this.windowBounds = this.window.getBounds()
  265. }
  266. })
  267. this.window.on('move', () => {
  268. if (!this.window.isMaximized()) {
  269. this.windowBounds = this.window.getBounds()
  270. }
  271. })
  272. this.window.on('focus', () => {
  273. this.send('host:window-focused')
  274. })
  275. this.on('ready', () => {
  276. this.window?.webContents.send('start', {
  277. config: this.configStore,
  278. executable: app.getPath('exe'),
  279. windowID: this.window.id,
  280. isMainWindow: this.isMainWindow,
  281. userPluginsPath: this.application.userPluginsPath,
  282. })
  283. })
  284. this.on('window-minimize', () => {
  285. this.window?.minimize()
  286. })
  287. this.on('window-set-bounds', (_, bounds) => {
  288. this.window?.setBounds(bounds)
  289. })
  290. this.on('window-set-always-on-top', (_, flag) => {
  291. this.window?.setAlwaysOnTop(flag)
  292. })
  293. this.on('window-set-vibrancy', (_, enabled) => {
  294. this.setVibrancy(enabled)
  295. })
  296. this.on('window-set-material', (_, material) => {
  297. this.setMaterial(material)
  298. })
  299. this.on('window-set-window-controls-color', (_, theme) => {
  300. if (process.platform === 'win32') {
  301. const symbolColor: string = theme.foreground
  302. this.window?.setTitleBarOverlay(
  303. {
  304. symbolColor: symbolColor,
  305. height: 32,
  306. },
  307. )
  308. }
  309. })
  310. this.on('window-set-title', (_, title) => {
  311. this.window?.setTitle(title)
  312. })
  313. this.on('window-bring-to-front', () => {
  314. if (this.window?.isMinimized()) {
  315. this.window.restore()
  316. }
  317. this.present()
  318. })
  319. this.on('window-close', () => {
  320. this.closing = true
  321. this.window.close()
  322. })
  323. this.on('window-set-touch-bar', (_, segments, selectedIndex) => {
  324. this.touchBarControl.segments = segments.map(s => ({
  325. label: s.label,
  326. icon: s.hasActivity ? activityIcon : undefined,
  327. }))
  328. this.touchBarControl.selectedIndex = selectedIndex
  329. })
  330. this.window.webContents.setWindowOpenHandler(() => {
  331. return { action: 'deny' }
  332. })
  333. ipcMain.on('window-set-traffic-light-position', (_event, x, y) => {
  334. this.window.setWindowButtonPosition({ x, y })
  335. })
  336. ipcMain.on('window-set-opacity', (_event, opacity) => {
  337. this.window.setOpacity(opacity)
  338. })
  339. this.on('window-set-progress-bar', (_, value) => {
  340. this.window?.setProgressBar(value, { mode: value < 0 ? 'none' : 'normal' })
  341. })
  342. }
  343. on (event: string, listener: (...args: any[]) => void): void {
  344. ipcMain.on(event, (e, ...args) => {
  345. if (!this.window || e.sender !== this.window.webContents) {
  346. return
  347. }
  348. listener(e, ...args)
  349. })
  350. }
  351. private setupUpdater () {
  352. autoUpdater.autoDownload = true
  353. autoUpdater.autoInstallOnAppQuit = true
  354. autoUpdater.on('update-available', () => {
  355. this.send('updater:update-available')
  356. })
  357. autoUpdater.on('update-not-available', () => {
  358. this.send('updater:update-not-available')
  359. })
  360. autoUpdater.on('error', err => {
  361. this.send('updater:error', err)
  362. })
  363. autoUpdater.on('update-downloaded', () => {
  364. this.send('updater:update-downloaded')
  365. })
  366. this.on('updater:check-for-updates', () => {
  367. autoUpdater.checkForUpdates()
  368. })
  369. this.on('updater:quit-and-install', () => {
  370. autoUpdater.quitAndInstall()
  371. })
  372. }
  373. private destroy () {
  374. this.window = null
  375. this.closed.next()
  376. this.visible.complete()
  377. this.closed.complete()
  378. }
  379. }