1
0

window.ts 16 KB

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