refactor: Introduce WindowManager for centralized window management
- Replaced direct window management functions with a WindowManager class to encapsulate window creation, retrieval, and destruction. - Updated router, tray, menu, updater, and other modules to utilize the new WindowManager methods. - Improved window state handling and ensured consistent window behavior across different platforms. - Added a backup of the previous window management implementation for reference. Signed-off-by: Innei <i@innei.in>
This commit is contained in:
@@ -21,12 +21,7 @@ import { updateNotificationsToken } from "./lib/user"
|
||||
import { logger } from "./logger"
|
||||
import { registerUpdater } from "./updater"
|
||||
import { cleanupOldRender } from "./updater/hot-updater"
|
||||
import {
|
||||
createMainWindow,
|
||||
getMainWindow,
|
||||
getMainWindowOrCreate,
|
||||
windowStateStoreKey,
|
||||
} from "./window"
|
||||
import { WindowManager } from "./window"
|
||||
|
||||
if (DEV) console.info("[main] env loaded:", env)
|
||||
|
||||
@@ -75,7 +70,7 @@ function bootstrap() {
|
||||
app.on("activate", () => {
|
||||
// On macOS it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
mainWindow = getMainWindowOrCreate()
|
||||
mainWindow = WindowManager.getMainWindowOrCreate()
|
||||
mainWindow.show()
|
||||
})
|
||||
|
||||
@@ -112,7 +107,7 @@ function bootstrap() {
|
||||
callback({ cancel: false, requestHeaders: details.requestHeaders })
|
||||
})
|
||||
|
||||
mainWindow = createMainWindow()
|
||||
mainWindow = WindowManager.createMainWindow()
|
||||
|
||||
updateProxy()
|
||||
registerUpdater()
|
||||
@@ -124,7 +119,7 @@ function bootstrap() {
|
||||
if (mainWindow.isMinimized()) mainWindow.restore()
|
||||
mainWindow.focus()
|
||||
} else {
|
||||
mainWindow = createMainWindow()
|
||||
mainWindow = WindowManager.createMainWindow()
|
||||
}
|
||||
url && handleOpen(url)
|
||||
})
|
||||
@@ -152,11 +147,11 @@ function bootstrap() {
|
||||
|
||||
app.on("before-quit", async () => {
|
||||
// store window pos when before app quit
|
||||
const window = getMainWindow()
|
||||
const window = WindowManager.getMainWindow()
|
||||
if (!window || window.isDestroyed()) return
|
||||
const bounds = window.getBounds()
|
||||
|
||||
store.set(windowStateStoreKey, {
|
||||
store.set(WindowManager.windowStateStoreKey, {
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
x: bounds.x,
|
||||
|
||||
@@ -17,7 +17,7 @@ import { updateNotificationsToken } from "./lib/user"
|
||||
import { logger } from "./logger"
|
||||
import { registerAppMenu } from "./menu"
|
||||
import { initializeSentry } from "./sentry"
|
||||
import { getMainWindowOrCreate } from "./window"
|
||||
import { WindowManager } from "./window"
|
||||
|
||||
if (process.argv.length === 3 && process.argv[2]!.startsWith("follow-dev:")) {
|
||||
process.env.NODE_ENV = "development"
|
||||
@@ -190,7 +190,7 @@ const registerPushNotifications = async () => {
|
||||
body: data.description,
|
||||
})
|
||||
notification.on("click", () => {
|
||||
const mainWindow = getMainWindowOrCreate()
|
||||
const mainWindow = WindowManager.getMainWindowOrCreate()
|
||||
mainWindow.restore()
|
||||
mainWindow.focus()
|
||||
const handlers = callWindowExpose(mainWindow)
|
||||
|
||||
@@ -10,10 +10,10 @@ import { i18n } from "~/lib/i18n"
|
||||
import { registerAppTray } from "~/lib/tray"
|
||||
import { logger } from "~/logger"
|
||||
import { cleanupOldRender, loadDynamicRenderEntry } from "~/updater/hot-updater"
|
||||
import { WindowManager } from "~/window"
|
||||
|
||||
import { downloadFile } from "../../lib/download"
|
||||
import { checkForAppUpdates, quitAndInstall } from "../../updater"
|
||||
import { getMainWindow } from "../../window"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
@@ -62,7 +62,7 @@ export class AppService extends IpcService {
|
||||
|
||||
const appLoadEntry = dynamicRenderEntry || path.resolve(__dirname, "../renderer/index.html")
|
||||
logger.info("appLoadEntry", appLoadEntry)
|
||||
const mainWindow = getMainWindow()
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
|
||||
for (const window of allWindows) {
|
||||
if (window === mainWindow) {
|
||||
|
||||
@@ -2,10 +2,11 @@ import { createRequire } from "node:module"
|
||||
|
||||
import { app, nativeTheme } from "electron"
|
||||
|
||||
import { WindowManager } from "~/window"
|
||||
|
||||
import { setProxyConfig, updateProxy } from "../../lib/proxy"
|
||||
import { store } from "../../lib/store"
|
||||
import { getTrayConfig, setTrayConfig } from "../../lib/tray"
|
||||
import { showSetting } from "../../window"
|
||||
import type { IpcContext } from "../base"
|
||||
import { IpcMethod, IpcService } from "../base"
|
||||
|
||||
@@ -35,7 +36,7 @@ export class SettingService extends IpcService {
|
||||
|
||||
@IpcMethod()
|
||||
openSettingWindow(_context: IpcContext): void {
|
||||
showSetting()
|
||||
WindowManager.showSetting()
|
||||
}
|
||||
|
||||
@IpcMethod()
|
||||
|
||||
@@ -5,7 +5,7 @@ import { hc } from "hono/client"
|
||||
import { ofetch } from "ofetch"
|
||||
|
||||
import { BETTER_AUTH_COOKIE_NAME_SESSION_TOKEN } from "~/constants/app"
|
||||
import { getMainWindow } from "~/window"
|
||||
import { WindowManager } from "~/window"
|
||||
|
||||
import { logger } from "../logger"
|
||||
|
||||
@@ -28,7 +28,7 @@ export const apiFetch = ofetch.create({
|
||||
export const apiClient = hc<AppType>("", {
|
||||
fetch: async (input, options = {}) => apiFetch(input.toString(), options),
|
||||
async headers() {
|
||||
const window = getMainWindow()
|
||||
const window = WindowManager.getMainWindow()
|
||||
const cookies = await window?.webContents.session.cookies.get({
|
||||
domain: new URL(env.VITE_API_URL).hostname,
|
||||
})
|
||||
|
||||
@@ -9,7 +9,7 @@ import { app, dialog } from "electron"
|
||||
|
||||
import { getIconPath } from "~/helper"
|
||||
import { logger } from "~/logger"
|
||||
import { getMainWindow } from "~/window"
|
||||
import { WindowManager } from "~/window"
|
||||
|
||||
import { t } from "./i18n"
|
||||
import { store, StoreKey } from "./store"
|
||||
@@ -23,7 +23,7 @@ const fastFolderSize = esModuleInterop(
|
||||
) as typeof import("fast-folder-size").default
|
||||
|
||||
export const clearAllDataAndConfirm = async () => {
|
||||
const win = getMainWindow()
|
||||
const win = WindowManager.getMainWindow()
|
||||
if (!win) return
|
||||
|
||||
// Dialog to confirm
|
||||
@@ -42,7 +42,7 @@ export const clearAllDataAndConfirm = async () => {
|
||||
}
|
||||
|
||||
export const clearAllData = async () => {
|
||||
const win = getMainWindow()
|
||||
const win = WindowManager.getMainWindow()
|
||||
if (!win) return
|
||||
const ses = win.webContents.session
|
||||
const caller = callWindowExpose(win)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { extractElectronWindowOptions } from "@follow/shared/electron"
|
||||
import type { BrowserWindow } from "electron/main"
|
||||
|
||||
import { logger } from "~/logger"
|
||||
import { createMainWindow, createWindow, getMainWindow } from "~/window"
|
||||
import { WindowManager } from "~/window"
|
||||
|
||||
export const handleUrlRouting = (url: string) => {
|
||||
const options = extractElectronWindowOptions(url)
|
||||
@@ -84,7 +84,7 @@ export const handleUrlRouting = (url: string) => {
|
||||
|
||||
default: {
|
||||
const { height, resizable = true, width } = options || {}
|
||||
createWindow({
|
||||
WindowManager.createWindow({
|
||||
extraPath: `#${uri}`,
|
||||
width: width ?? 800,
|
||||
height: height ?? 700,
|
||||
@@ -101,9 +101,9 @@ export const handleUrlRouting = (url: string) => {
|
||||
}
|
||||
|
||||
const callMainWindow = (url: string, fn: (mainWindow: BrowserWindow) => any) => {
|
||||
const mainWindow = getMainWindow()
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
if (!mainWindow) {
|
||||
createMainWindow()
|
||||
WindowManager.createMainWindow()
|
||||
|
||||
return handleUrlRouting(url)
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import { isMacOS, isMAS, isWindows } from "~/env"
|
||||
import { getTrayIconPath } from "~/helper"
|
||||
import { logger, revealLogFile } from "~/logger"
|
||||
import { checkForAppUpdates } from "~/updater"
|
||||
import { WindowManager } from "~/window"
|
||||
|
||||
import { getMainWindowOrCreate } from "../window"
|
||||
import { getDockCount } from "./dock"
|
||||
import { t } from "./i18n"
|
||||
import { store } from "./store"
|
||||
@@ -36,14 +36,14 @@ const getTrayContextMenu = () => {
|
||||
{
|
||||
label: t("menu.reload"),
|
||||
click: () => {
|
||||
const mainWindow = getMainWindowOrCreate()
|
||||
const mainWindow = WindowManager.getMainWindowOrCreate()
|
||||
mainWindow.webContents.reload()
|
||||
},
|
||||
},
|
||||
{
|
||||
label: t("menu.toggleDevTools"),
|
||||
click: () => {
|
||||
const mainWindow = getMainWindowOrCreate()
|
||||
const mainWindow = WindowManager.getMainWindowOrCreate()
|
||||
mainWindow.webContents.toggleDevTools()
|
||||
},
|
||||
},
|
||||
@@ -98,7 +98,7 @@ export const registerAppTray = () => {
|
||||
}
|
||||
|
||||
const showWindow = () => {
|
||||
const mainWindow = getMainWindowOrCreate()
|
||||
const mainWindow = WindowManager.getMainWindowOrCreate()
|
||||
if (mainWindow.isMinimized()) {
|
||||
mainWindow.restore()
|
||||
} else {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { clearAllDataAndConfirm } from "./lib/cleaner"
|
||||
import { t } from "./lib/i18n"
|
||||
import { revealLogFile } from "./logger"
|
||||
import { checkForAppUpdates, quitAndInstall } from "./updater"
|
||||
import { createWindow, getMainWindow, showSetting } from "./window"
|
||||
import { WindowManager } from "./window"
|
||||
|
||||
export const registerAppMenu = () => {
|
||||
const menus: Array<MenuItemConstructorOptions | MenuItem> = [
|
||||
@@ -23,14 +23,14 @@ export const registerAppMenu = () => {
|
||||
type: "normal",
|
||||
label: t("menu.about", { name }),
|
||||
click: () => {
|
||||
showSetting("about")
|
||||
WindowManager.showSetting("about")
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: t("menu.settings"),
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
click: () => showSetting(),
|
||||
click: () => WindowManager.showSetting(),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ role: "services", label: t("menu.services") },
|
||||
@@ -57,7 +57,7 @@ export const registerAppMenu = () => {
|
||||
label: t("menu.quickAdd"),
|
||||
accelerator: "CmdOrCtrl+N",
|
||||
click: () => {
|
||||
const mainWindow = getMainWindow()
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
if (!mainWindow) return
|
||||
mainWindow.show()
|
||||
const caller = callWindowExpose(mainWindow)
|
||||
@@ -70,7 +70,7 @@ export const registerAppMenu = () => {
|
||||
label: t("menu.discover"),
|
||||
accelerator: "CmdOrCtrl+T",
|
||||
click: () => {
|
||||
const mainWindow = getMainWindow()
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
if (!mainWindow) return
|
||||
mainWindow.show()
|
||||
|
||||
@@ -161,9 +161,9 @@ export const registerAppMenu = () => {
|
||||
{
|
||||
label: "Always on top",
|
||||
type: "checkbox",
|
||||
checked: getMainWindow()?.isAlwaysOnTop(),
|
||||
checked: WindowManager.getMainWindow()?.isAlwaysOnTop(),
|
||||
click: () => {
|
||||
const mainWindow = getMainWindow()
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
if (!mainWindow) return
|
||||
mainWindow.setAlwaysOnTop(!mainWindow.isAlwaysOnTop())
|
||||
registerAppMenu()
|
||||
@@ -186,7 +186,7 @@ export const registerAppMenu = () => {
|
||||
{
|
||||
label: t("menu.checkForUpdates"),
|
||||
click: async () => {
|
||||
getMainWindow()?.show()
|
||||
WindowManager.getMainWindow()?.show()
|
||||
await checkForAppUpdates()
|
||||
},
|
||||
},
|
||||
@@ -203,7 +203,7 @@ export const registerAppMenu = () => {
|
||||
{
|
||||
label: t("menu.followReleases"),
|
||||
click: () => {
|
||||
createWindow({
|
||||
WindowManager.createWindow({
|
||||
extraPath: `#add?url=${encodeURIComponent(
|
||||
"https://github.com/RSSNext/follow/releases.atom",
|
||||
)}`,
|
||||
|
||||
@@ -14,7 +14,7 @@ import { load } from "js-yaml"
|
||||
import { x } from "tar"
|
||||
|
||||
import { GITHUB_OWNER, GITHUB_REPO, HOTUPDATE_RENDER_ENTRY_DIR } from "~/constants/app"
|
||||
import { getMainWindow } from "~/window"
|
||||
import { WindowManager } from "~/window"
|
||||
|
||||
import { appUpdaterConfig } from "./configs"
|
||||
|
||||
@@ -180,7 +180,7 @@ export const hotUpdateRender = async (manifest: Manifest) => {
|
||||
)
|
||||
logger.info(`Hot update render success, update to ${manifest.version}`)
|
||||
|
||||
const mainWindow = getMainWindow()
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
if (!mainWindow) return false
|
||||
const caller = callWindowExpose(mainWindow)
|
||||
caller.readyToUpdate()
|
||||
|
||||
@@ -4,10 +4,10 @@ import { autoUpdater as defaultAutoUpdater } from "electron-updater"
|
||||
|
||||
import { GITHUB_OWNER, GITHUB_REPO } from "~/constants/app"
|
||||
import { canUpdateRender, CanUpdateRenderState, hotUpdateRender } from "~/updater/hot-updater"
|
||||
import { WindowManager } from "~/window"
|
||||
|
||||
import { channel, isWindows } from "../env"
|
||||
import { logger } from "../logger"
|
||||
import { destroyMainWindow, getMainWindow } from "../window"
|
||||
import { appUpdaterConfig } from "./configs"
|
||||
import { CustomGitHubProvider } from "./custom-github-provider"
|
||||
import { WindowsUpdater } from "./windows-updater"
|
||||
@@ -19,10 +19,9 @@ const disabled = !appUpdaterConfig.enableAppUpdate
|
||||
const autoUpdater = isWindows ? new WindowsUpdater() : defaultAutoUpdater
|
||||
|
||||
export const quitAndInstall = () => {
|
||||
const mainWindow = getMainWindow()
|
||||
|
||||
destroyMainWindow()
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
logger.info("Quit and install update, close main window, ", mainWindow?.id)
|
||||
WindowManager.destroyMainWindow()
|
||||
|
||||
setTimeout(() => {
|
||||
logger.info("Window is closed, quit and install update")
|
||||
@@ -142,7 +141,7 @@ export const registerUpdater = async () => {
|
||||
downloading = false
|
||||
logger.info("Update downloaded, ready to install")
|
||||
|
||||
const mainWindow = getMainWindow()
|
||||
const mainWindow = WindowManager.getMainWindow()
|
||||
if (!mainWindow) return
|
||||
const handlers = callWindowExpose(mainWindow)
|
||||
|
||||
|
||||
@@ -19,99 +19,32 @@ import { refreshBound } from "./lib/utils"
|
||||
import { logger } from "./logger"
|
||||
import { loadDynamicRenderEntry } from "./updater/hot-updater"
|
||||
|
||||
const windows = {
|
||||
mainWindow: null as BrowserWindow | null,
|
||||
}
|
||||
globalThis["windows"] = windows
|
||||
const { platform } = process
|
||||
const __dirname = fileURLToPath(new URL(".", import.meta.url))
|
||||
export function createWindow(
|
||||
options: {
|
||||
extraPath?: string
|
||||
height: number
|
||||
width: number
|
||||
} & BrowserWindowConstructorOptions,
|
||||
) {
|
||||
const { extraPath, height, width, ...configs } = options
|
||||
|
||||
const baseWindowConfig: Electron.BrowserWindowConstructorOptions = {
|
||||
width,
|
||||
height,
|
||||
show: false,
|
||||
resizable: configs?.resizable ?? true,
|
||||
autoHideMenuBar: true,
|
||||
alwaysOnTop: false,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, "../preload/index.mjs"),
|
||||
sandbox: false,
|
||||
webviewTag: true,
|
||||
webSecurity: !DEV,
|
||||
nodeIntegration: true,
|
||||
contextIsolation: true,
|
||||
class WindowManagerStatic {
|
||||
static readonly mainWindowDefaultSize = {
|
||||
height: 900,
|
||||
width: 1600,
|
||||
}
|
||||
|
||||
// Window configuration properties for better DX
|
||||
private readonly config = {
|
||||
windowStateStoreKey: "windowState",
|
||||
minWindowSize: {
|
||||
width: 1024,
|
||||
height: 500,
|
||||
},
|
||||
}
|
||||
|
||||
switch (platform) {
|
||||
case "darwin": {
|
||||
Object.assign(baseWindowConfig, {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: {
|
||||
x: 18,
|
||||
y: 18,
|
||||
},
|
||||
vibrancy: "sidebar",
|
||||
visualEffectState: "followWindow",
|
||||
transparent: true,
|
||||
} as Electron.BrowserWindowConstructorOptions)
|
||||
break
|
||||
}
|
||||
|
||||
case "win32": {
|
||||
Object.assign(baseWindowConfig, {
|
||||
icon: getIconPath(),
|
||||
|
||||
titleBarStyle: "hidden",
|
||||
// Electron material bug, comment this for now
|
||||
// backgroundMaterial: isWindows11 ? "mica" : undefined,
|
||||
|
||||
frame: true,
|
||||
} as Electron.BrowserWindowConstructorOptions)
|
||||
break
|
||||
}
|
||||
|
||||
default: {
|
||||
baseWindowConfig.icon = getIconPath()
|
||||
}
|
||||
}
|
||||
|
||||
// Create the browser window.
|
||||
const window = new BrowserWindow({
|
||||
...baseWindowConfig,
|
||||
...configs,
|
||||
})
|
||||
|
||||
window.on("leave-html-full-screen", () => {
|
||||
// To solve the vibrancy losing issue when leaving full screen mode
|
||||
// @see https://github.com/toeverything/AFFiNE/blob/280e24934a27557529479a70ab38c4f5fc65cb00/packages/frontend/electron/src/main/windows-manager/main-window.ts:L157
|
||||
refreshBound(window)
|
||||
refreshBound(window, 1000)
|
||||
})
|
||||
|
||||
window.on("ready-to-show", () => {
|
||||
const shouldShowWindow =
|
||||
!app.getLoginItemSettings().wasOpenedAsHidden && !process.argv.includes(START_IN_TRAY_ARGS)
|
||||
if (shouldShowWindow) window.show()
|
||||
})
|
||||
|
||||
window.webContents.setWindowOpenHandler((details) => {
|
||||
shell.openExternal(details.url)
|
||||
return { action: "deny" }
|
||||
})
|
||||
|
||||
const handleExternalProtocol = async (e: Event, url: string, window: BrowserWindow) => {
|
||||
const { protocol } = new URL(url)
|
||||
|
||||
const ignoreProtocols = [
|
||||
macOSTrafficLight: {
|
||||
x: 18,
|
||||
y: 18,
|
||||
},
|
||||
refreshBoundDelay: 1000,
|
||||
devToolsFont: {
|
||||
family:
|
||||
'consolas, operator mono, Cascadia Code, OperatorMonoSSmLig Nerd Font, "Agave Nerd Font", "Cascadia Code PL", monospace',
|
||||
size: "13px",
|
||||
},
|
||||
ignoreProtocols: [
|
||||
"http",
|
||||
"https",
|
||||
LEGACY_APP_PROTOCOL,
|
||||
@@ -120,228 +53,378 @@ export function createWindow(
|
||||
"code",
|
||||
"cursor",
|
||||
"app",
|
||||
]
|
||||
if (ignoreProtocols.includes(protocol.slice(0, -1))) {
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
] as const,
|
||||
vibrancy: {
|
||||
macOS: {
|
||||
type: "sidebar" as const,
|
||||
state: "followWindow" as const,
|
||||
},
|
||||
},
|
||||
windowPreferences: {
|
||||
preloadScript: path.join(__dirname, "../preload/index.mjs"),
|
||||
},
|
||||
} as const
|
||||
|
||||
const caller = callWindowExpose(window)
|
||||
const confirm = await caller.dialog.ask({
|
||||
title: t("dialog.openExternalApp.title"),
|
||||
message: t("dialog.openExternalApp.message", { url, interpolation: { escapeValue: false } }),
|
||||
confirmText: t("dialog.open"),
|
||||
cancelText: t("dialog.cancel"),
|
||||
readonly windowStateStoreKey = this.config.windowStateStoreKey
|
||||
|
||||
private windows = {
|
||||
mainWindow: null as BrowserWindow | null,
|
||||
}
|
||||
|
||||
private bindEvents(window: BrowserWindow) {
|
||||
window.on("leave-html-full-screen", () => {
|
||||
// To solve the vibrancy losing issue when leaving full screen mode
|
||||
// @see https://github.com/toeverything/AFFiNE/blob/280e24934a27557529479a70ab38c4f5fc65cb00/packages/frontend/electron/src/main/windows-manager/main-window.ts:L157
|
||||
refreshBound(window)
|
||||
refreshBound(window, this.config.refreshBoundDelay)
|
||||
})
|
||||
if (!confirm) {
|
||||
return
|
||||
}
|
||||
shell.openExternal(url)
|
||||
}
|
||||
|
||||
// Handle main window external links
|
||||
window.webContents.on("will-navigate", (e, url) => handleExternalProtocol(e, url, window))
|
||||
|
||||
// Handle webview external links
|
||||
window.webContents.on("did-attach-webview", (_, webContents) => {
|
||||
webContents.on("will-navigate", (e, url) => handleExternalProtocol(e, url, window))
|
||||
})
|
||||
|
||||
// HMR for renderer base on electron-vite cli.
|
||||
// Load the remote URL for development or the local html file for production.
|
||||
if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
|
||||
window.loadURL(process.env["ELECTRON_RENDERER_URL"] + (options?.extraPath || ""))
|
||||
|
||||
logger.log(process.env["ELECTRON_RENDERER_URL"] + (options?.extraPath || ""))
|
||||
} else {
|
||||
// Production entry
|
||||
const dynamicRenderEntry = loadDynamicRenderEntry()
|
||||
logger.info("load dynamic render entry", dynamicRenderEntry)
|
||||
const appLoadFileEntry = dynamicRenderEntry || path.resolve(__dirname, "../renderer/index.html")
|
||||
|
||||
const appLoadEntry = `${filePathToAppUrl(appLoadFileEntry)}${options?.extraPath || ""}`
|
||||
|
||||
window.loadURL(appLoadEntry)
|
||||
logger.log("load URL", appLoadEntry)
|
||||
}
|
||||
|
||||
if (isWindows) {
|
||||
// Change the default font-family and font-size of the devtools.
|
||||
// Make it consistent with Chrome on Windows, instead of SimSun.
|
||||
// ref: [[Feature Request]: Add possibility to change DevTools font · Issue #42055 · electron/electron](https://github.com/electron/electron/issues/42055)
|
||||
window.webContents.on("devtools-opened", () => {
|
||||
// source-code-font: For code such as Elements panel
|
||||
// monospace-font: For sidebar such as Event Listener Panel
|
||||
const css = `:root {--devtool-font-family: consolas, operator mono, Cascadia Code, OperatorMonoSSmLig Nerd Font,"Agave Nerd Font","Cascadia Code PL", monospace;--source-code-font-family:var(--devtool-font-family);--source-code-font-size: 13px;--monospace-font-family: var(--devtool-font-family);--monospace-font-size: 13px;}`
|
||||
window.webContents.devToolsWebContents?.executeJavaScript(`
|
||||
const overriddenStyle = document.createElement('style');
|
||||
overriddenStyle.innerHTML = '${css.replaceAll("\n", " ")}';
|
||||
document.body.append(overriddenStyle);
|
||||
document.querySelectorAll('.platform-windows').forEach(el => el.classList.remove('platform-windows'));
|
||||
addStyleToAutoComplete();
|
||||
const observer = new MutationObserver((mutationList, observer) => {
|
||||
for (const mutation of mutationList) {
|
||||
if (mutation.type === 'childList') {
|
||||
for (let i = 0; i < mutation.addedNodes.length; i++) {
|
||||
const item = mutation.addedNodes[i];
|
||||
if (item.classList.contains('editor-tooltip-host')) {
|
||||
addStyleToAutoComplete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, {childList: true});
|
||||
function addStyleToAutoComplete() {
|
||||
document.querySelectorAll('.editor-tooltip-host').forEach(element => {
|
||||
if (element.shadowRoot.querySelectorAll('[data-key="overridden-dev-tools-font"]').length === 0) {
|
||||
const overriddenStyle = document.createElement('style');
|
||||
overriddenStyle.setAttribute('data-key', 'overridden-dev-tools-font');
|
||||
overriddenStyle.innerHTML = '.cm-tooltip-autocomplete ul[role=listbox] {font-family: consolas !important;}';
|
||||
element.shadowRoot.append(overriddenStyle);
|
||||
}
|
||||
});
|
||||
}
|
||||
`)
|
||||
window.on("ready-to-show", () => {
|
||||
const shouldShowWindow =
|
||||
!app.getLoginItemSettings().wasOpenedAsHidden && !process.argv.includes(START_IN_TRAY_ARGS)
|
||||
if (shouldShowWindow) window.show()
|
||||
})
|
||||
}
|
||||
|
||||
// async render and main state
|
||||
window.on("maximize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.MAXIMIZED)
|
||||
})
|
||||
window.webContents.setWindowOpenHandler((details) => {
|
||||
shell.openExternal(details.url)
|
||||
return { action: "deny" }
|
||||
})
|
||||
|
||||
window.on("unmaximize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.NORMAL)
|
||||
})
|
||||
|
||||
window.on("minimize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.MINIMIZED)
|
||||
})
|
||||
|
||||
window.on("restore", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.NORMAL)
|
||||
})
|
||||
|
||||
return window
|
||||
}
|
||||
export const windowStateStoreKey = "windowState"
|
||||
export const createMainWindow = () => {
|
||||
const windowState = store.get(windowStateStoreKey)
|
||||
const primaryDisplay = screen.getPrimaryDisplay()
|
||||
const { workArea } = primaryDisplay
|
||||
|
||||
const maxWidth = workArea.width
|
||||
const maxHeight = workArea.height
|
||||
|
||||
const width = Math.min(windowState?.width || 1200, maxWidth)
|
||||
const height = Math.min(windowState?.height || 900, maxHeight)
|
||||
|
||||
const ensureInBounds = (value: number, min: number, max: number): number => {
|
||||
return Math.max(min, Math.min(value, max))
|
||||
}
|
||||
|
||||
const x =
|
||||
windowState?.x !== undefined
|
||||
? ensureInBounds(windowState.x, workArea.x, workArea.x + workArea.width - width)
|
||||
: undefined
|
||||
|
||||
const y =
|
||||
windowState?.y !== undefined
|
||||
? ensureInBounds(windowState.y, workArea.y, workArea.y + workArea.height - height)
|
||||
: undefined
|
||||
|
||||
const window = createWindow({
|
||||
width: windowState?.width || 1200,
|
||||
height: windowState?.height || 900,
|
||||
x,
|
||||
y,
|
||||
minWidth: Math.min(1024, maxWidth),
|
||||
minHeight: Math.min(500, maxHeight),
|
||||
})
|
||||
|
||||
window.on("close", () => {
|
||||
if (isWindows11) {
|
||||
const windowStoreKey = Symbol.for("maximized")
|
||||
if (window[windowStoreKey]) {
|
||||
const stored = window[windowStoreKey]
|
||||
store.set(windowStateStoreKey, {
|
||||
width: stored.size[0],
|
||||
height: stored.size[1],
|
||||
x: stored.position[0],
|
||||
y: stored.position[1],
|
||||
})
|
||||
const handleExternalProtocol = async (e: Event, url: string, window: BrowserWindow) => {
|
||||
const { protocol } = new URL(url)
|
||||
|
||||
if (this.config.ignoreProtocols.includes(protocol.slice(0, -1) as any)) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const bounds = window.getBounds()
|
||||
store.set(windowStateStoreKey, {
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
x: bounds.x,
|
||||
y: bounds.y,
|
||||
})
|
||||
})
|
||||
|
||||
windows.mainWindow = window
|
||||
|
||||
window.on("close", (event) => {
|
||||
const minimizeToTray = getTrayConfig()
|
||||
if (isMacOS || minimizeToTray) {
|
||||
event.preventDefault()
|
||||
if (window.isFullScreen()) {
|
||||
window.once("leave-full-screen", () => {
|
||||
window.hide()
|
||||
})
|
||||
window.setFullScreen(false)
|
||||
} else {
|
||||
window.hide()
|
||||
}
|
||||
e.preventDefault()
|
||||
|
||||
const caller = callWindowExpose(window)
|
||||
caller.onWindowClose()
|
||||
const confirm = await caller.dialog.ask({
|
||||
title: t("dialog.openExternalApp.title"),
|
||||
message: t("dialog.openExternalApp.message", {
|
||||
url,
|
||||
interpolation: { escapeValue: false },
|
||||
}),
|
||||
confirmText: t("dialog.open"),
|
||||
cancelText: t("dialog.cancel"),
|
||||
})
|
||||
if (!confirm) {
|
||||
return
|
||||
}
|
||||
shell.openExternal(url)
|
||||
}
|
||||
|
||||
// Handle main window external links
|
||||
window.webContents.on("will-navigate", (e, url) => handleExternalProtocol(e, url, window))
|
||||
|
||||
// Handle webview external links
|
||||
window.webContents.on("did-attach-webview", (_, webContents) => {
|
||||
webContents.on("will-navigate", (e, url) => handleExternalProtocol(e, url, window))
|
||||
})
|
||||
|
||||
if (isWindows) {
|
||||
// Change the default font-family and font-size of the devtools.
|
||||
// Make it consistent with Chrome on Windows, instead of SimSun.
|
||||
// ref: [[Feature Request]: Add possibility to change DevTools font · Issue #42055 · electron/electron](https://github.com/electron/electron/issues/42055)
|
||||
window.webContents.on("devtools-opened", () => {
|
||||
this.setupDevToolsFont(window)
|
||||
})
|
||||
}
|
||||
|
||||
this.bindWindowStateEvents(window)
|
||||
}
|
||||
|
||||
private setupDevToolsFont(window: BrowserWindow) {
|
||||
// source-code-font: For code such as Elements panel
|
||||
// monospace-font: For sidebar such as Event Listener Panel
|
||||
const css = `:root {--devtool-font-family: ${this.config.devToolsFont.family};--source-code-font-family:var(--devtool-font-family);--source-code-font-size: ${this.config.devToolsFont.size};--monospace-font-family: var(--devtool-font-family);--monospace-font-size: ${this.config.devToolsFont.size};}`
|
||||
const js = `
|
||||
const overriddenStyle = document.createElement('style');
|
||||
overriddenStyle.innerHTML = '${css.replaceAll("\n", " ")}';
|
||||
document.body.append(overriddenStyle);
|
||||
document.querySelectorAll('.platform-windows').forEach(el => el.classList.remove('platform-windows'));
|
||||
addStyleToAutoComplete();
|
||||
const observer = new MutationObserver((mutationList, observer) => {
|
||||
for (const mutation of mutationList) {
|
||||
if (mutation.type === 'childList') {
|
||||
for (let i = 0; i < mutation.addedNodes.length; i++) {
|
||||
const item = mutation.addedNodes[i];
|
||||
if (item instanceof HTMLElement && item.classList.contains('editor-tooltip-host')) {
|
||||
addStyleToAutoComplete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, {childList: true});
|
||||
function addStyleToAutoComplete() {
|
||||
document.querySelectorAll('.editor-tooltip-host').forEach(element => {
|
||||
if (element.shadowRoot && element.shadowRoot.querySelectorAll('[data-key="overridden-dev-tools-font"]').length === 0) {
|
||||
const overriddenStyle = document.createElement('style');
|
||||
overriddenStyle.setAttribute('data-key', 'overridden-dev-tools-font');
|
||||
overriddenStyle.innerHTML = '.cm-tooltip-autocomplete ul[role=listbox] {font-family: consolas !important;}';
|
||||
element.shadowRoot.append(overriddenStyle);
|
||||
}
|
||||
});
|
||||
}
|
||||
`
|
||||
window.webContents.devToolsWebContents?.executeJavaScript(js)
|
||||
}
|
||||
|
||||
private bindWindowStateEvents(window: BrowserWindow) {
|
||||
// async render and main state
|
||||
window.on("maximize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.MAXIMIZED)
|
||||
})
|
||||
|
||||
window.on("unmaximize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.NORMAL)
|
||||
})
|
||||
|
||||
window.on("minimize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.MINIMIZED)
|
||||
})
|
||||
|
||||
window.on("restore", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.NORMAL)
|
||||
})
|
||||
}
|
||||
|
||||
private bindMainWindowCloseHandlers(window: BrowserWindow) {
|
||||
window.on("close", () => {
|
||||
if (isWindows11) {
|
||||
const windowStoreKey = Symbol.for("maximized")
|
||||
if (window[windowStoreKey]) {
|
||||
const stored = window[windowStoreKey]
|
||||
store.set(this.windowStateStoreKey, {
|
||||
width: stored.size[0],
|
||||
height: stored.size[1],
|
||||
x: stored.position[0],
|
||||
y: stored.position[1],
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const bounds = window.getBounds()
|
||||
store.set(this.windowStateStoreKey, {
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
x: bounds.x,
|
||||
y: bounds.y,
|
||||
})
|
||||
})
|
||||
|
||||
window.on("close", (event) => {
|
||||
const minimizeToTray = getTrayConfig()
|
||||
if (isMacOS || minimizeToTray) {
|
||||
event.preventDefault()
|
||||
if (window.isFullScreen()) {
|
||||
window.once("leave-full-screen", () => {
|
||||
window.hide()
|
||||
})
|
||||
window.setFullScreen(false)
|
||||
} else {
|
||||
window.hide()
|
||||
}
|
||||
|
||||
const caller = callWindowExpose(window)
|
||||
caller.onWindowClose()
|
||||
} else {
|
||||
this.windows.mainWindow = null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private getPlatformSpecificWindowConfig(): Partial<BrowserWindowConstructorOptions> {
|
||||
const { platform } = process
|
||||
|
||||
switch (platform) {
|
||||
case "darwin": {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: {
|
||||
x: this.config.macOSTrafficLight.x,
|
||||
y: this.config.macOSTrafficLight.y,
|
||||
},
|
||||
vibrancy: this.config.vibrancy.macOS.type,
|
||||
visualEffectState: this.config.vibrancy.macOS.state,
|
||||
transparent: true,
|
||||
}
|
||||
}
|
||||
|
||||
case "win32": {
|
||||
return {
|
||||
icon: getIconPath(),
|
||||
titleBarStyle: "hidden",
|
||||
// Electron material bug, comment this for now
|
||||
// backgroundMaterial: isWindows11 ? "mica" : undefined,
|
||||
frame: true,
|
||||
}
|
||||
}
|
||||
|
||||
default: {
|
||||
return {
|
||||
icon: getIconPath(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createWindow = (
|
||||
options: {
|
||||
extraPath?: string
|
||||
height: number
|
||||
width: number
|
||||
} & BrowserWindowConstructorOptions,
|
||||
) => {
|
||||
const { extraPath, height, width, ...configs } = options
|
||||
|
||||
const baseWindowConfig: Electron.BrowserWindowConstructorOptions = {
|
||||
width,
|
||||
height,
|
||||
show: false,
|
||||
resizable: configs?.resizable ?? true,
|
||||
autoHideMenuBar: true,
|
||||
alwaysOnTop: false,
|
||||
webPreferences: {
|
||||
preload: this.config.windowPreferences.preloadScript,
|
||||
sandbox: false,
|
||||
webviewTag: true,
|
||||
webSecurity: !DEV,
|
||||
nodeIntegration: true,
|
||||
contextIsolation: true,
|
||||
},
|
||||
...this.getPlatformSpecificWindowConfig(),
|
||||
}
|
||||
|
||||
// Create the browser window.
|
||||
const window = new BrowserWindow({
|
||||
...baseWindowConfig,
|
||||
...configs,
|
||||
})
|
||||
|
||||
this.bindEvents(window)
|
||||
|
||||
// HMR for renderer base on electron-vite cli.
|
||||
// Load the remote URL for development or the local html file for production.
|
||||
if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
|
||||
window.loadURL(process.env["ELECTRON_RENDERER_URL"] + (options?.extraPath || ""))
|
||||
logger.log(process.env["ELECTRON_RENDERER_URL"] + (options?.extraPath || ""))
|
||||
} else {
|
||||
windows.mainWindow = null
|
||||
// Production entry
|
||||
const dynamicRenderEntry = loadDynamicRenderEntry()
|
||||
logger.info("load dynamic render entry", dynamicRenderEntry)
|
||||
const appLoadFileEntry =
|
||||
dynamicRenderEntry || path.resolve(__dirname, "../renderer/index.html")
|
||||
|
||||
const appLoadEntry = `${filePathToAppUrl(appLoadFileEntry)}${options?.extraPath || ""}`
|
||||
|
||||
window.loadURL(appLoadEntry)
|
||||
logger.log("load URL", appLoadEntry)
|
||||
}
|
||||
})
|
||||
|
||||
return window
|
||||
}
|
||||
return window
|
||||
}
|
||||
|
||||
export const showSetting = (path?: string) => {
|
||||
// We need to open the setting modal in the main window when the main window exists,
|
||||
// if we open a new window then the state between the two windows will be out of sync.
|
||||
if (windows.mainWindow) {
|
||||
if (windows.mainWindow.isMinimized()) {
|
||||
windows.mainWindow.restore()
|
||||
private ensureWindowBoundsInScreen(windowState?: {
|
||||
width?: number
|
||||
height?: number
|
||||
x?: number
|
||||
y?: number
|
||||
}) {
|
||||
const primaryDisplay = screen.getPrimaryDisplay()
|
||||
const { workArea } = primaryDisplay
|
||||
|
||||
const maxWidth = workArea.width
|
||||
const maxHeight = workArea.height
|
||||
|
||||
const defaultSize = WindowManagerStatic.mainWindowDefaultSize
|
||||
|
||||
const width = Math.min(windowState?.width || defaultSize.width, maxWidth)
|
||||
const height = Math.min(windowState?.height || defaultSize.height, maxHeight)
|
||||
|
||||
const ensureInBounds = (value: number, min: number, max: number): number => {
|
||||
return Math.max(min, Math.min(value, max))
|
||||
}
|
||||
windows.mainWindow.show()
|
||||
|
||||
callWindowExpose(windows.mainWindow).showSetting(path)
|
||||
return
|
||||
} else {
|
||||
windows.mainWindow = createMainWindow()
|
||||
windows.mainWindow.show()
|
||||
callWindowExpose(windows.mainWindow).showSetting(path)
|
||||
const x =
|
||||
windowState?.x !== undefined
|
||||
? ensureInBounds(windowState.x, workArea.x, workArea.x + workArea.width - width)
|
||||
: undefined
|
||||
|
||||
const y =
|
||||
windowState?.y !== undefined
|
||||
? ensureInBounds(windowState.y, workArea.y, workArea.y + workArea.height - height)
|
||||
: undefined
|
||||
|
||||
return { width, height, x, y, maxWidth, maxHeight }
|
||||
}
|
||||
|
||||
createMainWindow = () => {
|
||||
const windowState = store.get(this.windowStateStoreKey) as
|
||||
| {
|
||||
width?: number
|
||||
height?: number
|
||||
x?: number
|
||||
y?: number
|
||||
}
|
||||
| undefined
|
||||
const { width, height, x, y, maxWidth, maxHeight } =
|
||||
this.ensureWindowBoundsInScreen(windowState)
|
||||
|
||||
const window = this.createWindow({
|
||||
width,
|
||||
height,
|
||||
x,
|
||||
y,
|
||||
minWidth: Math.min(this.config.minWindowSize.width, maxWidth),
|
||||
minHeight: Math.min(this.config.minWindowSize.height, maxHeight),
|
||||
})
|
||||
|
||||
this.bindMainWindowCloseHandlers(window)
|
||||
|
||||
this.windows.mainWindow = window
|
||||
|
||||
return window
|
||||
}
|
||||
|
||||
showSetting = (path?: string) => {
|
||||
// We need to open the setting modal in the main window when the main window exists,
|
||||
// if we open a new window then the state between the two windows will be out of sync.
|
||||
if (this.windows.mainWindow) {
|
||||
if (this.windows.mainWindow.isMinimized()) {
|
||||
this.windows.mainWindow.restore()
|
||||
}
|
||||
this.windows.mainWindow.show()
|
||||
|
||||
callWindowExpose(this.windows.mainWindow).showSetting(path)
|
||||
return
|
||||
} else {
|
||||
this.windows.mainWindow = this.createMainWindow()
|
||||
this.windows.mainWindow.show()
|
||||
callWindowExpose(this.windows.mainWindow).showSetting(path)
|
||||
}
|
||||
}
|
||||
|
||||
getMainWindow = () => this.windows.mainWindow
|
||||
|
||||
getMainWindowOrCreate = () => {
|
||||
if (!this.windows.mainWindow) {
|
||||
return this.createMainWindow()
|
||||
}
|
||||
return this.windows.mainWindow
|
||||
}
|
||||
|
||||
destroyMainWindow = () => {
|
||||
this.windows.mainWindow?.destroy()
|
||||
this.windows.mainWindow = null
|
||||
}
|
||||
}
|
||||
|
||||
export const getMainWindow = () => windows.mainWindow
|
||||
|
||||
export const getMainWindowOrCreate = () => {
|
||||
if (!windows.mainWindow) {
|
||||
return createMainWindow()
|
||||
}
|
||||
return windows.mainWindow
|
||||
}
|
||||
|
||||
export const destroyMainWindow = () => {
|
||||
windows.mainWindow?.destroy()
|
||||
windows.mainWindow = null
|
||||
}
|
||||
export const WindowManager = new WindowManagerStatic()
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
import path from "node:path"
|
||||
import { fileURLToPath } from "node:url"
|
||||
|
||||
import { is } from "@electron-toolkit/utils"
|
||||
import { LEGACY_APP_PROTOCOL } from "@follow/shared"
|
||||
import { callWindowExpose, WindowState } from "@follow/shared/bridge"
|
||||
import { APP_PROTOCOL, DEV } from "@follow/shared/constants"
|
||||
import type { BrowserWindowConstructorOptions } from "electron"
|
||||
import { app, BrowserWindow, screen, shell } from "electron"
|
||||
import type { Event } from "electron/main"
|
||||
|
||||
import { START_IN_TRAY_ARGS } from "./constants/app"
|
||||
import { isMacOS, isWindows, isWindows11 } from "./env"
|
||||
import { filePathToAppUrl, getIconPath } from "./helper"
|
||||
import { t } from "./lib/i18n"
|
||||
import { store } from "./lib/store"
|
||||
import { getTrayConfig } from "./lib/tray"
|
||||
import { refreshBound } from "./lib/utils"
|
||||
import { logger } from "./logger"
|
||||
import { loadDynamicRenderEntry } from "./updater/hot-updater"
|
||||
|
||||
const __dirname = fileURLToPath(new URL(".", import.meta.url))
|
||||
|
||||
class WindowManagerStatic {
|
||||
static readonly mainWindowDefaultSize = {
|
||||
height: 900,
|
||||
width: 1600,
|
||||
}
|
||||
|
||||
// Window configuration properties for better DX
|
||||
private readonly config = {
|
||||
windowStateStoreKey: "windowState",
|
||||
minWindowSize: {
|
||||
width: 1024,
|
||||
height: 500,
|
||||
},
|
||||
macOSTrafficLight: {
|
||||
x: 18,
|
||||
y: 18,
|
||||
},
|
||||
refreshBoundDelay: 1000,
|
||||
devToolsFont: {
|
||||
family:
|
||||
'consolas, operator mono, Cascadia Code, OperatorMonoSSmLig Nerd Font, "Agave Nerd Font", "Cascadia Code PL", monospace',
|
||||
size: "13px",
|
||||
},
|
||||
ignoreProtocols: [
|
||||
"http",
|
||||
"https",
|
||||
LEGACY_APP_PROTOCOL,
|
||||
APP_PROTOCOL,
|
||||
"file",
|
||||
"code",
|
||||
"cursor",
|
||||
"app",
|
||||
] as const,
|
||||
vibrancy: {
|
||||
macOS: {
|
||||
type: "sidebar" as const,
|
||||
state: "followWindow" as const,
|
||||
},
|
||||
},
|
||||
windowPreferences: {
|
||||
preloadScript: path.join(__dirname, "../preload/index.mjs"),
|
||||
},
|
||||
} as const
|
||||
|
||||
readonly windowStateStoreKey = this.config.windowStateStoreKey
|
||||
|
||||
private windows = {
|
||||
mainWindow: null as BrowserWindow | null,
|
||||
}
|
||||
|
||||
constructor() {
|
||||
globalThis["windows"] = this.windows
|
||||
}
|
||||
|
||||
private bindEvents(window: BrowserWindow) {
|
||||
window.on("leave-html-full-screen", () => {
|
||||
// To solve the vibrancy losing issue when leaving full screen mode
|
||||
// @see https://github.com/toeverything/AFFiNE/blob/280e24934a27557529479a70ab38c4f5fc65cb00/packages/frontend/electron/src/main/windows-manager/main-window.ts:L157
|
||||
refreshBound(window)
|
||||
refreshBound(window, this.config.refreshBoundDelay)
|
||||
})
|
||||
|
||||
window.on("ready-to-show", () => {
|
||||
const shouldShowWindow =
|
||||
!app.getLoginItemSettings().wasOpenedAsHidden && !process.argv.includes(START_IN_TRAY_ARGS)
|
||||
if (shouldShowWindow) window.show()
|
||||
})
|
||||
|
||||
window.webContents.setWindowOpenHandler((details) => {
|
||||
shell.openExternal(details.url)
|
||||
return { action: "deny" }
|
||||
})
|
||||
|
||||
const handleExternalProtocol = async (e: Event, url: string, window: BrowserWindow) => {
|
||||
const { protocol } = new URL(url)
|
||||
|
||||
if (this.config.ignoreProtocols.includes(protocol.slice(0, -1) as any)) {
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
|
||||
const caller = callWindowExpose(window)
|
||||
const confirm = await caller.dialog.ask({
|
||||
title: t("dialog.openExternalApp.title"),
|
||||
message: t("dialog.openExternalApp.message", {
|
||||
url,
|
||||
interpolation: { escapeValue: false },
|
||||
}),
|
||||
confirmText: t("dialog.open"),
|
||||
cancelText: t("dialog.cancel"),
|
||||
})
|
||||
if (!confirm) {
|
||||
return
|
||||
}
|
||||
shell.openExternal(url)
|
||||
}
|
||||
|
||||
// Handle main window external links
|
||||
window.webContents.on("will-navigate", (e, url) => handleExternalProtocol(e, url, window))
|
||||
|
||||
// Handle webview external links
|
||||
window.webContents.on("did-attach-webview", (_, webContents) => {
|
||||
webContents.on("will-navigate", (e, url) => handleExternalProtocol(e, url, window))
|
||||
})
|
||||
|
||||
if (isWindows) {
|
||||
// Change the default font-family and font-size of the devtools.
|
||||
// Make it consistent with Chrome on Windows, instead of SimSun.
|
||||
// ref: [[Feature Request]: Add possibility to change DevTools font · Issue #42055 · electron/electron](https://github.com/electron/electron/issues/42055)
|
||||
window.webContents.on("devtools-opened", () => {
|
||||
this.setupDevToolsFont(window)
|
||||
})
|
||||
}
|
||||
|
||||
this.bindWindowStateEvents(window)
|
||||
}
|
||||
|
||||
private setupDevToolsFont(window: BrowserWindow) {
|
||||
// source-code-font: For code such as Elements panel
|
||||
// monospace-font: For sidebar such as Event Listener Panel
|
||||
const css = `:root {--devtool-font-family: ${this.config.devToolsFont.family};--source-code-font-family:var(--devtool-font-family);--source-code-font-size: ${this.config.devToolsFont.size};--monospace-font-family: var(--devtool-font-family);--monospace-font-size: ${this.config.devToolsFont.size};}`
|
||||
const js = `
|
||||
const overriddenStyle = document.createElement('style');
|
||||
overriddenStyle.innerHTML = '${css.replaceAll("\n", " ")}';
|
||||
document.body.append(overriddenStyle);
|
||||
document.querySelectorAll('.platform-windows').forEach(el => el.classList.remove('platform-windows'));
|
||||
addStyleToAutoComplete();
|
||||
const observer = new MutationObserver((mutationList, observer) => {
|
||||
for (const mutation of mutationList) {
|
||||
if (mutation.type === 'childList') {
|
||||
for (let i = 0; i < mutation.addedNodes.length; i++) {
|
||||
const item = mutation.addedNodes[i];
|
||||
if (item instanceof HTMLElement && item.classList.contains('editor-tooltip-host')) {
|
||||
addStyleToAutoComplete();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
observer.observe(document.body, {childList: true});
|
||||
function addStyleToAutoComplete() {
|
||||
document.querySelectorAll('.editor-tooltip-host').forEach(element => {
|
||||
if (element.shadowRoot && element.shadowRoot.querySelectorAll('[data-key="overridden-dev-tools-font"]').length === 0) {
|
||||
const overriddenStyle = document.createElement('style');
|
||||
overriddenStyle.setAttribute('data-key', 'overridden-dev-tools-font');
|
||||
overriddenStyle.innerHTML = '.cm-tooltip-autocomplete ul[role=listbox] {font-family: consolas !important;}';
|
||||
element.shadowRoot.append(overriddenStyle);
|
||||
}
|
||||
});
|
||||
}
|
||||
`
|
||||
window.webContents.devToolsWebContents?.executeJavaScript(js)
|
||||
}
|
||||
|
||||
private bindWindowStateEvents(window: BrowserWindow) {
|
||||
// async render and main state
|
||||
window.on("maximize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.MAXIMIZED)
|
||||
})
|
||||
|
||||
window.on("unmaximize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.NORMAL)
|
||||
})
|
||||
|
||||
window.on("minimize", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.MINIMIZED)
|
||||
})
|
||||
|
||||
window.on("restore", async () => {
|
||||
const caller = callWindowExpose(window)
|
||||
await caller.setWindowState(WindowState.NORMAL)
|
||||
})
|
||||
}
|
||||
|
||||
private bindMainWindowCloseHandlers(window: BrowserWindow) {
|
||||
window.on("close", () => {
|
||||
if (isWindows11) {
|
||||
const windowStoreKey = Symbol.for("maximized")
|
||||
if (window[windowStoreKey]) {
|
||||
const stored = window[windowStoreKey]
|
||||
store.set(this.windowStateStoreKey, {
|
||||
width: stored.size[0],
|
||||
height: stored.size[1],
|
||||
x: stored.position[0],
|
||||
y: stored.position[1],
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
const bounds = window.getBounds()
|
||||
store.set(this.windowStateStoreKey, {
|
||||
width: bounds.width,
|
||||
height: bounds.height,
|
||||
x: bounds.x,
|
||||
y: bounds.y,
|
||||
})
|
||||
})
|
||||
|
||||
window.on("close", (event) => {
|
||||
const minimizeToTray = getTrayConfig()
|
||||
if (isMacOS || minimizeToTray) {
|
||||
event.preventDefault()
|
||||
if (window.isFullScreen()) {
|
||||
window.once("leave-full-screen", () => {
|
||||
window.hide()
|
||||
})
|
||||
window.setFullScreen(false)
|
||||
} else {
|
||||
window.hide()
|
||||
}
|
||||
|
||||
const caller = callWindowExpose(window)
|
||||
caller.onWindowClose()
|
||||
} else {
|
||||
this.windows.mainWindow = null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private getPlatformSpecificWindowConfig(): Partial<BrowserWindowConstructorOptions> {
|
||||
const { platform } = process
|
||||
|
||||
switch (platform) {
|
||||
case "darwin": {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: {
|
||||
x: this.config.macOSTrafficLight.x,
|
||||
y: this.config.macOSTrafficLight.y,
|
||||
},
|
||||
vibrancy: this.config.vibrancy.macOS.type,
|
||||
visualEffectState: this.config.vibrancy.macOS.state,
|
||||
transparent: true,
|
||||
}
|
||||
}
|
||||
|
||||
case "win32": {
|
||||
return {
|
||||
icon: getIconPath(),
|
||||
titleBarStyle: "hidden",
|
||||
// Electron material bug, comment this for now
|
||||
// backgroundMaterial: isWindows11 ? "mica" : undefined,
|
||||
frame: true,
|
||||
}
|
||||
}
|
||||
|
||||
default: {
|
||||
return {
|
||||
icon: getIconPath(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
createWindow = (
|
||||
options: {
|
||||
extraPath?: string
|
||||
height: number
|
||||
width: number
|
||||
} & BrowserWindowConstructorOptions,
|
||||
) => {
|
||||
const { extraPath, height, width, ...configs } = options
|
||||
|
||||
const baseWindowConfig: Electron.BrowserWindowConstructorOptions = {
|
||||
width,
|
||||
height,
|
||||
show: false,
|
||||
resizable: configs?.resizable ?? true,
|
||||
autoHideMenuBar: true,
|
||||
alwaysOnTop: false,
|
||||
webPreferences: {
|
||||
preload: this.config.windowPreferences.preloadScript,
|
||||
sandbox: false,
|
||||
webviewTag: true,
|
||||
webSecurity: !DEV,
|
||||
nodeIntegration: true,
|
||||
contextIsolation: true,
|
||||
},
|
||||
...this.getPlatformSpecificWindowConfig(),
|
||||
}
|
||||
|
||||
// Create the browser window.
|
||||
const window = new BrowserWindow({
|
||||
...baseWindowConfig,
|
||||
...configs,
|
||||
})
|
||||
|
||||
this.bindEvents(window)
|
||||
|
||||
// HMR for renderer base on electron-vite cli.
|
||||
// Load the remote URL for development or the local html file for production.
|
||||
if (is.dev && process.env["ELECTRON_RENDERER_URL"]) {
|
||||
window.loadURL(process.env["ELECTRON_RENDERER_URL"] + (options?.extraPath || ""))
|
||||
logger.log(process.env["ELECTRON_RENDERER_URL"] + (options?.extraPath || ""))
|
||||
} else {
|
||||
// Production entry
|
||||
const dynamicRenderEntry = loadDynamicRenderEntry()
|
||||
logger.info("load dynamic render entry", dynamicRenderEntry)
|
||||
const appLoadFileEntry =
|
||||
dynamicRenderEntry || path.resolve(__dirname, "../renderer/index.html")
|
||||
|
||||
const appLoadEntry = `${filePathToAppUrl(appLoadFileEntry)}${options?.extraPath || ""}`
|
||||
|
||||
window.loadURL(appLoadEntry)
|
||||
logger.log("load URL", appLoadEntry)
|
||||
}
|
||||
|
||||
return window
|
||||
}
|
||||
|
||||
private ensureWindowBoundsInScreen(windowState?: {
|
||||
width?: number
|
||||
height?: number
|
||||
x?: number
|
||||
y?: number
|
||||
}) {
|
||||
const primaryDisplay = screen.getPrimaryDisplay()
|
||||
const { workArea } = primaryDisplay
|
||||
|
||||
const maxWidth = workArea.width
|
||||
const maxHeight = workArea.height
|
||||
|
||||
const defaultSize = WindowManagerStatic.mainWindowDefaultSize
|
||||
|
||||
const width = Math.min(windowState?.width || defaultSize.width, maxWidth)
|
||||
const height = Math.min(windowState?.height || defaultSize.height, maxHeight)
|
||||
|
||||
const ensureInBounds = (value: number, min: number, max: number): number => {
|
||||
return Math.max(min, Math.min(value, max))
|
||||
}
|
||||
|
||||
const x =
|
||||
windowState?.x !== undefined
|
||||
? ensureInBounds(windowState.x, workArea.x, workArea.x + workArea.width - width)
|
||||
: undefined
|
||||
|
||||
const y =
|
||||
windowState?.y !== undefined
|
||||
? ensureInBounds(windowState.y, workArea.y, workArea.y + workArea.height - height)
|
||||
: undefined
|
||||
|
||||
return { width, height, x, y, maxWidth, maxHeight }
|
||||
}
|
||||
|
||||
createMainWindow = () => {
|
||||
const windowState = store.get(this.windowStateStoreKey) as
|
||||
| {
|
||||
width?: number
|
||||
height?: number
|
||||
x?: number
|
||||
y?: number
|
||||
}
|
||||
| undefined
|
||||
const { width, height, x, y, maxWidth, maxHeight } =
|
||||
this.ensureWindowBoundsInScreen(windowState)
|
||||
|
||||
const window = this.createWindow({
|
||||
width,
|
||||
height,
|
||||
x,
|
||||
y,
|
||||
minWidth: Math.min(this.config.minWindowSize.width, maxWidth),
|
||||
minHeight: Math.min(this.config.minWindowSize.height, maxHeight),
|
||||
})
|
||||
|
||||
this.bindMainWindowCloseHandlers(window)
|
||||
|
||||
this.windows.mainWindow = window
|
||||
|
||||
return window
|
||||
}
|
||||
|
||||
showSetting = (path?: string) => {
|
||||
// We need to open the setting modal in the main window when the main window exists,
|
||||
// if we open a new window then the state between the two windows will be out of sync.
|
||||
if (this.windows.mainWindow) {
|
||||
if (this.windows.mainWindow.isMinimized()) {
|
||||
this.windows.mainWindow.restore()
|
||||
}
|
||||
this.windows.mainWindow.show()
|
||||
|
||||
callWindowExpose(this.windows.mainWindow).showSetting(path)
|
||||
return
|
||||
} else {
|
||||
this.windows.mainWindow = this.createMainWindow()
|
||||
this.windows.mainWindow.show()
|
||||
callWindowExpose(this.windows.mainWindow).showSetting(path)
|
||||
}
|
||||
}
|
||||
|
||||
getMainWindow = () => this.windows.mainWindow
|
||||
|
||||
getMainWindowOrCreate = () => {
|
||||
if (!this.windows.mainWindow) {
|
||||
return this.createMainWindow()
|
||||
}
|
||||
return this.windows.mainWindow
|
||||
}
|
||||
|
||||
destroyMainWindow = () => {
|
||||
this.windows.mainWindow?.destroy()
|
||||
this.windows.mainWindow = null
|
||||
}
|
||||
}
|
||||
|
||||
export const WindowManager = new WindowManagerStatic()
|
||||
Reference in New Issue
Block a user