window.ts 17 KB

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