window.ts 17 KB

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