window.ts 18 KB

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