window.ts 16 KB

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