window.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. private visible = new Subject<boolean>()
  29. private closed = new Subject<void>()
  30. private window?: GlasstronWindow
  31. private windowConfig: ElectronConfig
  32. private windowBounds?: Rectangle
  33. private closing = false
  34. private lastVibrancy: { enabled: boolean, type?: string } | null = null
  35. private disableVibrancyWhileDragging = false
  36. private configStore: any
  37. private touchBarControl: any
  38. get visible$ (): Observable<boolean> { return this.visible }
  39. get closed$ (): Observable<void> { return this.closed }
  40. constructor (private application: Application, options?: WindowOptions) {
  41. this.configStore = loadConfig()
  42. options = options ?? {}
  43. this.windowConfig = new ElectronConfig({ name: 'window' })
  44. this.windowBounds = this.windowConfig.get('windowBoundaries')
  45. const maximized = this.windowConfig.get('maximized')
  46. const bwOptions: BrowserWindowConstructorOptions = {
  47. width: 800,
  48. height: 600,
  49. title: 'Tabby',
  50. minWidth: 400,
  51. minHeight: 300,
  52. webPreferences: {
  53. nodeIntegration: true,
  54. preload: path.join(__dirname, 'sentry.js'),
  55. backgroundThrottling: false,
  56. contextIsolation: false,
  57. },
  58. maximizable: true,
  59. frame: false,
  60. show: false,
  61. backgroundColor: '#00000000',
  62. }
  63. if (this.windowBounds) {
  64. Object.assign(bwOptions, this.windowBounds)
  65. const closestDisplay = screen.getDisplayNearestPoint( { x: this.windowBounds.x, y: this.windowBounds.y } )
  66. const [left1, top1, right1, bottom1] = [this.windowBounds.x, this.windowBounds.y, this.windowBounds.x + this.windowBounds.width, this.windowBounds.y + this.windowBounds.height]
  67. const [left2, top2, right2, bottom2] = [closestDisplay.bounds.x, closestDisplay.bounds.y, closestDisplay.bounds.x + closestDisplay.bounds.width, closestDisplay.bounds.y + closestDisplay.bounds.height]
  68. if ((left2 > right1 || right2 < left1 || top2 > bottom1 || bottom2 < top1) && !maximized) {
  69. bwOptions.x = closestDisplay.bounds.width / 2 - bwOptions.width / 2
  70. bwOptions.y = closestDisplay.bounds.height / 2 - bwOptions.height / 2
  71. }
  72. }
  73. if ((this.configStore.appearance || {}).frame === 'native') {
  74. bwOptions.frame = true
  75. } else {
  76. if (process.platform === 'darwin') {
  77. bwOptions.titleBarStyle = 'hidden'
  78. }
  79. }
  80. if (process.platform === 'darwin') {
  81. this.window = new BrowserWindow(bwOptions) as GlasstronWindow
  82. } else {
  83. this.window = new glasstron.BrowserWindow(bwOptions)
  84. }
  85. this.window.once('ready-to-show', () => {
  86. if (process.platform === 'darwin') {
  87. this.window.setVibrancy(macOSVibrancyType)
  88. } else if (process.platform === 'win32' && (this.configStore.appearance || {}).vibrancy) {
  89. this.setVibrancy(true)
  90. }
  91. if (!options.hidden) {
  92. if (maximized) {
  93. this.window.maximize()
  94. } else {
  95. this.window.show()
  96. }
  97. this.window.focus()
  98. this.window.moveTop()
  99. application.focus()
  100. }
  101. })
  102. this.window.on('blur', () => {
  103. if ((this.configStore.appearance?.dock ?? 'off') !== 'off' && this.configStore.appearance?.dockHideOnBlur) {
  104. this.hide()
  105. }
  106. })
  107. enableRemote(this.window.webContents)
  108. this.window.loadURL(`file://${app.getAppPath()}/dist/index.html`, { extraHeaders: 'pragma: no-cache\n' })
  109. this.window.webContents.setVisualZoomLevelLimits(1, 1)
  110. this.window.webContents.setZoomFactor(1)
  111. if (process.platform === 'darwin') {
  112. this.touchBarControl = new TouchBar.TouchBarSegmentedControl({
  113. segments: [],
  114. change: index => this.send('touchbar-selection', index),
  115. })
  116. this.window.setTouchBar(new TouchBar({
  117. items: [this.touchBarControl],
  118. }))
  119. } else {
  120. this.window.setMenu(null)
  121. }
  122. this.setupWindowManagement()
  123. this.ready = new Promise(resolve => {
  124. const listener = event => {
  125. if (event.sender === this.window.webContents) {
  126. ipcMain.removeListener('app:ready', listener as any)
  127. resolve()
  128. }
  129. }
  130. ipcMain.on('app:ready', listener)
  131. })
  132. }
  133. setVibrancy (enabled: boolean, type?: string, userRequested?: boolean): void {
  134. if (userRequested ?? true) {
  135. this.lastVibrancy = { enabled, type }
  136. }
  137. if (process.platform === 'win32') {
  138. if (parseFloat(os.release()) >= 10) {
  139. this.window.blurType = enabled ? type === 'fluent' ? 'acrylic' : 'blurbehind' : null
  140. try {
  141. this.window.setBlur(enabled)
  142. } catch (error) {
  143. console.error('Failed to set window blur', error)
  144. }
  145. } else {
  146. DwmEnableBlurBehindWindow(this.window, enabled)
  147. }
  148. } else if (process.platform === 'linux') {
  149. this.window.setBackgroundColor(enabled ? '#00000000' : '#131d27')
  150. this.window.setBlur(enabled)
  151. } else {
  152. this.window.setVibrancy(enabled ? macOSVibrancyType : null)
  153. }
  154. }
  155. show (): void {
  156. this.window.show()
  157. this.window.moveTop()
  158. }
  159. focus (): void {
  160. this.window.focus()
  161. }
  162. send (event: string, ...args: any[]): void {
  163. if (!this.window) {
  164. return
  165. }
  166. this.window.webContents.send(event, ...args)
  167. if (event === 'host:config-change') {
  168. this.configStore = args[0]
  169. }
  170. }
  171. isDestroyed (): boolean {
  172. return !this.window || this.window.isDestroyed()
  173. }
  174. isFocused (): boolean {
  175. return this.window.isFocused()
  176. }
  177. isVisible (): boolean {
  178. return this.window.isVisible()
  179. }
  180. hide (): void {
  181. if (process.platform === 'darwin') {
  182. // Lose focus
  183. Menu.sendActionToFirstResponder('hide:')
  184. }
  185. this.window.blur()
  186. if (process.platform !== 'darwin') {
  187. this.window.hide()
  188. }
  189. }
  190. present (): void {
  191. if (!this.window.isVisible()) {
  192. // unfocused, invisible
  193. this.window.show()
  194. this.window.focus()
  195. } else {
  196. if (!this.configStore.appearance?.dock || this.configStore.appearance?.dock === 'off') {
  197. // not docked, visible
  198. setTimeout(() => {
  199. this.window.show()
  200. this.window.focus()
  201. })
  202. } else {
  203. if (this.configStore.appearance?.dockAlwaysOnTop) {
  204. // docked, visible, on top
  205. this.window.hide()
  206. } else {
  207. // docked, visible, not on top
  208. this.window.focus()
  209. }
  210. }
  211. }
  212. }
  213. passCliArguments (argv: string[], cwd: string, secondInstance: boolean): void {
  214. this.send('cli', parseArgs(argv, cwd), cwd, secondInstance)
  215. }
  216. private setupWindowManagement () {
  217. this.window.on('show', () => {
  218. this.visible.next(true)
  219. this.send('host:window-shown')
  220. })
  221. this.window.on('hide', () => {
  222. this.visible.next(false)
  223. })
  224. const moveSubscription = new Observable<void>(observer => {
  225. this.window.on('move', () => observer.next())
  226. }).pipe(debounceTime(250)).subscribe(() => {
  227. this.send('host:window-moved')
  228. })
  229. this.window.on('closed', () => {
  230. moveSubscription.unsubscribe()
  231. })
  232. this.window.on('enter-full-screen', () => this.send('host:window-enter-full-screen'))
  233. this.window.on('leave-full-screen', () => this.send('host:window-leave-full-screen'))
  234. this.window.on('close', event => {
  235. if (!this.closing) {
  236. event.preventDefault()
  237. this.send('host:window-close-request')
  238. return
  239. }
  240. this.windowConfig.set('windowBoundaries', this.windowBounds)
  241. this.windowConfig.set('maximized', this.window.isMaximized())
  242. })
  243. this.window.on('closed', () => {
  244. this.destroy()
  245. })
  246. this.window.on('resize', () => {
  247. if (!this.window.isMaximized()) {
  248. this.windowBounds = this.window.getBounds()
  249. }
  250. })
  251. this.window.on('move', () => {
  252. if (!this.window.isMaximized()) {
  253. this.windowBounds = this.window.getBounds()
  254. }
  255. })
  256. this.window.on('focus', () => {
  257. this.send('host:window-focused')
  258. })
  259. ipcMain.on('ready', event => {
  260. if (!this.window || event.sender !== this.window.webContents) {
  261. return
  262. }
  263. this.window.webContents.send('start', {
  264. config: this.configStore,
  265. executable: app.getPath('exe'),
  266. windowID: this.window.id,
  267. isFirstWindow: this.window.id === 1,
  268. userPluginsPath: this.application.userPluginsPath,
  269. })
  270. })
  271. ipcMain.on('window-minimize', event => {
  272. if (!this.window || event.sender !== this.window.webContents) {
  273. return
  274. }
  275. this.window.minimize()
  276. })
  277. ipcMain.on('window-set-bounds', (event, bounds) => {
  278. if (!this.window || event.sender !== this.window.webContents) {
  279. return
  280. }
  281. this.window.setBounds(bounds)
  282. })
  283. ipcMain.on('window-set-always-on-top', (event, flag) => {
  284. if (!this.window || event.sender !== this.window.webContents) {
  285. return
  286. }
  287. this.window.setAlwaysOnTop(flag)
  288. })
  289. ipcMain.on('window-set-vibrancy', (event, enabled, type) => {
  290. if (!this.window || event.sender !== this.window.webContents) {
  291. return
  292. }
  293. this.setVibrancy(enabled, type)
  294. })
  295. ipcMain.on('window-set-title', (event, title) => {
  296. if (!this.window || event.sender !== this.window.webContents) {
  297. return
  298. }
  299. this.window.setTitle(title)
  300. })
  301. ipcMain.on('window-bring-to-front', event => {
  302. if (!this.window || event.sender !== this.window.webContents) {
  303. return
  304. }
  305. if (this.window.isMinimized()) {
  306. this.window.restore()
  307. }
  308. this.window.show()
  309. this.window.moveTop()
  310. })
  311. ipcMain.on('window-close', event => {
  312. if (!this.window || event.sender !== this.window.webContents) {
  313. return
  314. }
  315. this.closing = true
  316. this.window.close()
  317. })
  318. ipcMain.on('window-set-touch-bar', (_event, segments, selectedIndex) => {
  319. this.touchBarControl.segments = segments.map(s => ({
  320. label: s.label,
  321. icon: s.hasActivity ? activityIcon : undefined,
  322. }))
  323. this.touchBarControl.selectedIndex = selectedIndex
  324. })
  325. this.window.webContents.on('new-window', event => event.preventDefault())
  326. ipcMain.on('window-set-disable-vibrancy-while-dragging', (_event, value) => {
  327. this.disableVibrancyWhileDragging = value
  328. })
  329. let moveEndedTimeout: any = null
  330. const onBoundsChange = () => {
  331. if (!this.lastVibrancy?.enabled || !this.disableVibrancyWhileDragging) {
  332. return
  333. }
  334. this.setVibrancy(false, undefined, false)
  335. if (moveEndedTimeout) {
  336. clearTimeout(moveEndedTimeout)
  337. }
  338. moveEndedTimeout = setTimeout(() => {
  339. this.setVibrancy(this.lastVibrancy.enabled, this.lastVibrancy.type)
  340. }, 50)
  341. }
  342. this.window.on('move', onBoundsChange)
  343. this.window.on('resize', onBoundsChange)
  344. ipcMain.on('window-set-traffic-light-position', (_event, x, y) => {
  345. this.window.setTrafficLightPosition({ x, y })
  346. })
  347. ipcMain.on('window-set-opacity', (_event, opacity) => {
  348. this.window.setOpacity(opacity)
  349. })
  350. ipcMain.on('window-set-progress-bar', (_event, value) => {
  351. this.window.setProgressBar(value, { mode: value < 0 ? 'none' : 'normal' })
  352. })
  353. }
  354. private destroy () {
  355. this.window = null
  356. this.closed.next()
  357. this.visible.complete()
  358. this.closed.complete()
  359. }
  360. }