window.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 } 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', '>=') ? 'under-window' : '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. this.window = new BrowserWindow(bwOptions) as GlasstronWindow
  89. } else {
  90. this.window = new glasstron.BrowserWindow(bwOptions)
  91. }
  92. this.webContents = this.window.webContents
  93. this.window.once('ready-to-show', () => {
  94. if (process.platform === 'darwin') {
  95. this.window.setVibrancy(macOSVibrancyType)
  96. } else if (process.platform === 'win32' && this.configStore.appearance?.vibrancy) {
  97. this.setVibrancy(true)
  98. }
  99. if (!options.hidden) {
  100. if (maximized) {
  101. this.window.maximize()
  102. } else {
  103. this.window.show()
  104. }
  105. this.window.focus()
  106. this.window.moveTop()
  107. application.focus()
  108. }
  109. })
  110. this.window.on('blur', () => {
  111. if (
  112. (this.configStore.appearance?.dock ?? 'off') !== 'off' &&
  113. this.configStore.appearance?.dockHideOnBlur &&
  114. !BrowserWindow.getFocusedWindow()
  115. ) {
  116. this.hide()
  117. }
  118. })
  119. enableRemote(this.window.webContents)
  120. this.window.loadURL(`file://${app.getAppPath()}/dist/index.html`, { extraHeaders: 'pragma: no-cache\n' })
  121. this.window.webContents.setVisualZoomLevelLimits(1, 1)
  122. this.window.webContents.setZoomFactor(1)
  123. this.window.webContents.session.setPermissionCheckHandler(() => true)
  124. this.window.webContents.session.setDevicePermissionHandler(() => true)
  125. if (process.platform === 'darwin') {
  126. this.touchBarControl = new TouchBar.TouchBarSegmentedControl({
  127. segments: [],
  128. change: index => this.send('touchbar-selection', index),
  129. })
  130. this.window.setTouchBar(new TouchBar({
  131. items: [this.touchBarControl],
  132. }))
  133. } else {
  134. this.window.setMenu(null)
  135. }
  136. this.setupWindowManagement()
  137. this.setupUpdater()
  138. this.ready = new Promise(resolve => {
  139. const listener = event => {
  140. if (event.sender === this.window.webContents) {
  141. ipcMain.removeListener('app:ready', listener as any)
  142. resolve()
  143. }
  144. }
  145. ipcMain.on('app:ready', listener)
  146. })
  147. }
  148. makeMain (): void {
  149. this.isMainWindow = true
  150. this.window.webContents.send('host:became-main-window')
  151. }
  152. setVibrancy (enabled: boolean, type?: string, userRequested?: boolean): void {
  153. if (userRequested ?? true) {
  154. this.lastVibrancy = { enabled, type }
  155. }
  156. if (process.platform === 'win32') {
  157. if (parseFloat(os.release()) >= 10) {
  158. this.window.blurType = enabled ? type === 'fluent' ? 'acrylic' : 'blurbehind' : null
  159. try {
  160. this.window.setBlur(enabled)
  161. this.isFluentVibrancy = enabled && type === 'fluent'
  162. } catch (error) {
  163. console.error('Failed to set window blur', error)
  164. }
  165. } else {
  166. DwmEnableBlurBehindWindow(this.window.getNativeWindowHandle(), enabled)
  167. }
  168. } else if (process.platform === 'linux') {
  169. this.window.setBackgroundColor(enabled ? '#00000000' : '#131d27')
  170. this.window.setBlur(enabled)
  171. } else {
  172. this.window.setVibrancy(enabled ? macOSVibrancyType : null)
  173. }
  174. }
  175. focus (): void {
  176. this.window.focus()
  177. }
  178. send (event: string, ...args: any[]): void {
  179. if (!this.window) {
  180. return
  181. }
  182. this.window.webContents.send(event, ...args)
  183. if (event === 'host:config-change') {
  184. this.configStore = args[0]
  185. this.enableDockedWindowStyles(this.isDockedOnTop())
  186. }
  187. }
  188. isDestroyed (): boolean {
  189. return !this.window || this.window.isDestroyed()
  190. }
  191. isFocused (): boolean {
  192. return this.window.isFocused()
  193. }
  194. isVisible (): boolean {
  195. return this.window.isVisible()
  196. }
  197. isDockedOnTop (): boolean {
  198. return this.isMainWindow && this.configStore.appearance?.dock && this.configStore.appearance?.dock !== 'off' && (this.configStore.appearance?.dockAlwaysOnTop ?? true)
  199. }
  200. async hide (): Promise<void> {
  201. if (process.platform === 'darwin') {
  202. // Lose focus
  203. Menu.sendActionToFirstResponder('hide:')
  204. if (this.isDockedOnTop()) {
  205. await this.enableDockedWindowStyles(false)
  206. }
  207. }
  208. this.window.blur()
  209. this.window.hide()
  210. }
  211. async show (): Promise<void> {
  212. await this.enableDockedWindowStyles(this.isDockedOnTop())
  213. this.window.show()
  214. this.window.focus()
  215. }
  216. async present (): Promise<void> {
  217. await this.show()
  218. this.window.moveTop()
  219. }
  220. passCliArguments (argv: string[], cwd: string, secondInstance: boolean): void {
  221. this.send('cli', parseArgs(argv, cwd), cwd, secondInstance)
  222. }
  223. private async enableDockedWindowStyles (enabled: boolean) {
  224. if (process.platform === 'darwin') {
  225. if (enabled) {
  226. if (!this.dockHidden) {
  227. app.dock.hide()
  228. this.dockHidden = true
  229. }
  230. this.window.setAlwaysOnTop(true, 'screen-saver', 1)
  231. if (!this.window.isVisibleOnAllWorkspaces()) {
  232. this.window.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true })
  233. }
  234. if (this.window.fullScreenable) {
  235. this.window.setFullScreenable(false)
  236. }
  237. } else {
  238. if (this.dockHidden) {
  239. await app.dock.show()
  240. this.dockHidden = false
  241. }
  242. if (this.window.isAlwaysOnTop()) {
  243. this.window.setAlwaysOnTop(false)
  244. }
  245. if (this.window.isVisibleOnAllWorkspaces()) {
  246. this.window.setVisibleOnAllWorkspaces(false)
  247. }
  248. if (!this.window.fullScreenable) {
  249. this.window.setFullScreenable(true)
  250. }
  251. }
  252. }
  253. }
  254. private setupWindowManagement () {
  255. this.window.on('show', () => {
  256. this.visible.next(true)
  257. this.send('host:window-shown')
  258. })
  259. this.window.on('hide', () => {
  260. this.visible.next(false)
  261. })
  262. const moveSubscription = new Observable<void>(observer => {
  263. this.window.on('move', () => observer.next())
  264. }).pipe(debounceTime(250)).subscribe(() => {
  265. this.send('host:window-moved')
  266. })
  267. this.window.on('closed', () => {
  268. moveSubscription.unsubscribe()
  269. })
  270. this.window.on('enter-full-screen', () => this.send('host:window-enter-full-screen'))
  271. this.window.on('leave-full-screen', () => this.send('host:window-leave-full-screen'))
  272. this.window.on('maximize', () => this.send('host:window-maximized'))
  273. this.window.on('unmaximize', () => this.send('host:window-unmaximized'))
  274. this.window.on('close', event => {
  275. if (!this.closing) {
  276. event.preventDefault()
  277. this.send('host:window-close-request')
  278. return
  279. }
  280. this.windowConfig.set('windowBoundaries', this.windowBounds)
  281. this.windowConfig.set('maximized', this.window.isMaximized())
  282. })
  283. this.window.on('closed', () => {
  284. this.destroy()
  285. })
  286. this.window.on('resize', () => {
  287. if (!this.window.isMaximized()) {
  288. this.windowBounds = this.window.getBounds()
  289. }
  290. })
  291. this.window.on('move', () => {
  292. if (!this.window.isMaximized()) {
  293. this.windowBounds = this.window.getBounds()
  294. }
  295. })
  296. this.window.on('focus', () => {
  297. this.send('host:window-focused')
  298. })
  299. this.on('ready', () => {
  300. this.window?.webContents.send('start', {
  301. config: this.configStore,
  302. executable: app.getPath('exe'),
  303. windowID: this.window.id,
  304. isMainWindow: this.isMainWindow,
  305. userPluginsPath: this.application.userPluginsPath,
  306. })
  307. })
  308. this.on('window-minimize', () => {
  309. this.window?.minimize()
  310. })
  311. this.on('window-set-bounds', (_, bounds) => {
  312. this.window?.setBounds(bounds)
  313. })
  314. this.on('window-set-always-on-top', (_, flag) => {
  315. this.window?.setAlwaysOnTop(flag)
  316. })
  317. this.on('window-set-vibrancy', (_, enabled, type) => {
  318. this.setVibrancy(enabled, type)
  319. })
  320. this.on('window-set-window-controls-color', (_, theme) => {
  321. if (process.platform === 'win32') {
  322. const symbolColor: string = theme.foreground
  323. this.window?.setTitleBarOverlay(
  324. {
  325. symbolColor: symbolColor,
  326. height: 32,
  327. },
  328. )
  329. }
  330. })
  331. this.on('window-set-title', (_, title) => {
  332. this.window?.setTitle(title)
  333. })
  334. this.on('window-bring-to-front', () => {
  335. if (this.window?.isMinimized()) {
  336. this.window.restore()
  337. }
  338. this.present()
  339. })
  340. this.on('window-close', () => {
  341. this.closing = true
  342. this.window.close()
  343. })
  344. this.on('window-set-touch-bar', (_, segments, selectedIndex) => {
  345. this.touchBarControl.segments = segments.map(s => ({
  346. label: s.label,
  347. icon: s.hasActivity ? activityIcon : undefined,
  348. }))
  349. this.touchBarControl.selectedIndex = selectedIndex
  350. })
  351. this.window.webContents.setWindowOpenHandler(() => {
  352. return { action: 'deny' }
  353. })
  354. ipcMain.on('window-set-disable-vibrancy-while-dragging', (_event, value) => {
  355. this.disableVibrancyWhileDragging = value && this.configStore.hacks?.disableVibrancyWhileDragging
  356. })
  357. let moveEndedTimeout: any = null
  358. const onBoundsChange = () => {
  359. if (!this.lastVibrancy?.enabled || !this.disableVibrancyWhileDragging || !this.isFluentVibrancy) {
  360. return
  361. }
  362. this.setVibrancy(false, undefined, false)
  363. if (moveEndedTimeout) {
  364. clearTimeout(moveEndedTimeout)
  365. }
  366. moveEndedTimeout = setTimeout(() => {
  367. this.setVibrancy(this.lastVibrancy.enabled, this.lastVibrancy.type)
  368. }, 50)
  369. }
  370. this.window.on('move', onBoundsChange)
  371. this.window.on('resize', onBoundsChange)
  372. ipcMain.on('window-set-traffic-light-position', (_event, x, y) => {
  373. this.window.setWindowButtonPosition({ x, y })
  374. })
  375. ipcMain.on('window-set-opacity', (_event, opacity) => {
  376. this.window.setOpacity(opacity)
  377. })
  378. this.on('window-set-progress-bar', (_, value) => {
  379. this.window?.setProgressBar(value, { mode: value < 0 ? 'none' : 'normal' })
  380. })
  381. }
  382. on (event: string, listener: (...args: any[]) => void): void {
  383. ipcMain.on(event, (e, ...args) => {
  384. if (!this.window || e.sender !== this.window.webContents) {
  385. return
  386. }
  387. listener(e, ...args)
  388. })
  389. }
  390. private setupUpdater () {
  391. autoUpdater.autoDownload = true
  392. autoUpdater.autoInstallOnAppQuit = true
  393. autoUpdater.on('update-available', () => {
  394. this.send('updater:update-available')
  395. })
  396. autoUpdater.on('update-not-available', () => {
  397. this.send('updater:update-not-available')
  398. })
  399. autoUpdater.on('error', err => {
  400. this.send('updater:error', err)
  401. })
  402. autoUpdater.on('update-downloaded', () => {
  403. this.send('updater:update-downloaded')
  404. })
  405. this.on('updater:check-for-updates', () => {
  406. autoUpdater.checkForUpdates()
  407. })
  408. this.on('updater:quit-and-install', () => {
  409. autoUpdater.quitAndInstall()
  410. })
  411. }
  412. private destroy () {
  413. this.window = null
  414. this.closed.next()
  415. this.visible.complete()
  416. this.closed.complete()
  417. }
  418. }