window.ts 15 KB

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