Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Show detached windows after theme paint https://github.com/siyuan-note/siyuan/issues/20192

Daniel63b1b4001c18
diff --git a/app/electron/main.js b/app/electron/main.js
index 7954720dff..8590a4165e 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -128,6 +128,7 @@ const notebookSystemLock = createNotebookSystemLock({
});
const windowKernelTargets = new Map();
const initializedWindowIds = new Set();
+const pendingWindowIds = new Set();
createSettingsTaskBridge({
ipcMain,
getTarget: id => getWindowKernelTarget(id),
@@ -3875,7 +3876,9 @@ app.whenReady().then(() => {
}
const existingWindow = windowWorkspaces.get(kernelTarget.origin, workspaceID);
if (existingWindow) {
- showWindow(existingWindow);
+ if (!pendingWindowIds.has(existingWindow.webContents.id)) {
+ showWindow(existingWindow);
+ }
return;
}
}
@@ -3885,7 +3888,7 @@ app.whenReady().then(() => {
const geometry = workspaceID ? normalizeWindowGeometry(data.windowGeometry, screen) : undefined;
const win = new BrowserWindow({
title: "SiYuan",
- show: true,
+ show: false,
trafficLightPosition: {x: 8, y: 13},
width: Math.floor(data.width || mainScreen.size.width * 0.7),
height: Math.floor(data.height || mainScreen.size.height * 0.9),
@@ -3897,6 +3900,7 @@ app.whenReady().then(() => {
icon: path.join(appDir, "stage", "icon-large.png"),
titleBarStyle: "hidden",
webPreferences: {
+ backgroundThrottling: false,
contextIsolation: false,
nodeIntegration: true,
nodeIntegrationInSubFrames: false,
@@ -3915,16 +3919,61 @@ app.whenReady().then(() => {
windowWorkspaces.associate(win, kernelTarget.origin, workspaceID);
}
- if (geometry) {
- if (data.windowGeometry.maximized) {
+ // 原生窗口和主题内容均完成绘制后再显示,最大化和全屏也延后到此时执行。
+ const windowId = win.webContents.id;
+ pendingWindowIds.add(windowId);
+ let painted = false;
+ let initialized = false;
+ const stopWaiting = () => {
+ clearTimeout(readyTimeout);
+ ipcMain.removeListener("siyuan-window-ready", onWindowReady);
+ pendingWindowIds.delete(windowId);
+ };
+ const revealWindow = () => {
+ if (!painted || !initialized || win.isDestroyed() || !pendingWindowIds.has(windowId)) {
+ return;
+ }
+ stopWaiting();
+ if (geometry && data.windowGeometry.maximized) {
win.maximize();
}
- if (data.windowGeometry.fullscreen) {
+ if (geometry && data.windowGeometry.fullscreen) {
win.setFullScreen(true);
}
- } else if (data.position) {
+ showWindow(win);
+ win.webContents.setBackgroundThrottling(true);
+ };
+ const onWindowReady = readyEvent => {
+ if (readyEvent.sender.id === windowId) {
+ initialized = true;
+ revealWindow();
+ }
+ };
+ ipcMain.on("siyuan-window-ready", onWindowReady);
+ win.once("ready-to-show", () => {
+ painted = true;
+ revealWindow();
+ });
+ win.webContents.on("did-finish-load", () => {
+ if (getWindowPathname(win) !== "/stage/build/app/window.html") {
+ initialized = true;
+ revealWindow();
+ }
+ });
+ // 初始化失败时显示窗口供用户处理,避免留下无法访问的隐藏窗口。
+ const readyTimeout = setTimeout(() => {
+ if (!win.isDestroyed()) {
+ writeLog("siyuan-window-ready timeout, force showing detached window");
+ painted = true;
+ initialized = true;
+ revealWindow();
+ }
+ }, 60000);
+ win.once("closed", stopWaiting);
+
+ if (!geometry && data.position) {
win.setPosition(data.position.x, data.position.y);
- } else {
+ } else if (!geometry) {
win.center();
}
win.setAlwaysOnTop(data.alwaysOnTop, "win32" === process.platform ? "pop-up-menu" : "floating");
diff --git a/app/electron/windowGeometry.test.js b/app/electron/windowGeometry.test.js
index 296fcbc03c..c981550b19 100644
--- a/app/electron/windowGeometry.test.js
+++ b/app/electron/windowGeometry.test.js
@@ -105,8 +105,12 @@ const openWindow = windowGeometry => {
const start = source.indexOf('ipcMain.on("siyuan-open-window",');
const end = source.indexOf('ipcMain.on("siyuan-open-workspace",', start);
const calls = [];
+ const timers = new Set();
+ const ipcMain = new EventEmitter();
+ const pendingWindowIds = new Set();
let options;
- let open;
+ const windows = [];
+ let pathname = "/stage/build/app/window.html";
class Window extends EventEmitter {
static getFocusedWindow() {
return {getBounds: () => ({x: 0, y: 0})};
@@ -114,7 +118,12 @@ const openWindow = windowGeometry => {
constructor(value) {
super();
options = value;
- this.webContents = {session: {setSpellCheckerLanguages: () => {}}};
+ windows.push(this);
+ this.destroyed = false;
+ this.webContents = Object.assign(new EventEmitter(), {id: 2,
+ session: {setSpellCheckerLanguages: () => {}},
+ setBackgroundThrottling: value => calls.push(["throttling", value]),
+ });
}
center() { calls.push("center"); }
setPosition(x, y) { calls.push({x, y}); }
@@ -123,13 +132,14 @@ const openWindow = windowGeometry => {
setFullScreen() { calls.push("fullscreen"); }
setAlwaysOnTop() {}
loadURL() {}
+ isDestroyed() { return this.destroyed; }
}
const workArea = {x: 1920, y: 0, width: 1280, height: 1000};
runInNewContext(source.slice(start, end), {
- ipcMain: {on: (_name, callback) => open = callback},
+ ipcMain, pendingWindowIds,
BrowserWindow: Window, URL, process: {platform: "win32"},
getWindowKernelTarget: () => ({origin: "http://127.0.0.1:6806", mode: "local"}),
- windowWorkspaces: {get: () => undefined, associate: () => {}},
+ windowWorkspaces: {get: () => windows[0], associate: () => {}},
screen: {
...screen,
getDisplayNearestPoint: point => point.x === 2000 ? {id: 2, workArea} : {id: 1, size: {width: 1920, height: 1080}},
@@ -138,21 +148,94 @@ const openWindow = windowGeometry => {
normalizeWindowGeometry, path: {join: () => "icon"}, appDir: "", appVer: "test",
remote: {enable: () => {}}, bindSpellcheckContextMenu: () => {}, rememberWindowKernelTarget: () => {},
windowNavigate: () => {},
+ showWindow: () => calls.push("show"), getWindowPathname: () => pathname, writeLog: () => {},
+ setTimeout: callback => { timers.add(callback); return callback; },
+ clearTimeout: timer => timers.delete(timer),
});
- open({sender: {id: 1}}, {
+ const open = () => ipcMain.emit("siyuan-open-window", {sender: {id: 1}}, {
url: "http://127.0.0.1:6806/stage/build/app/window.html?windowWorkspace=20260924100000-abcdefg",
windowGeometry,
});
- return {options, calls, workArea};
+ open();
+ const win = windows[0];
+ return {options, calls, workArea, win, ipcMain, timers, pendingWindowIds, open,
+ navigate: value => { pathname = value; win.webContents.emit("did-finish-load"); },
+ ready: () => ipcMain.emit("siyuan-window-ready", {sender: win.webContents}),
+ };
};
test("新窗口创建时使用保存边界,不被鼠标所在显示器覆盖", () => {
const f = openWindow(state({maximized: true}));
assert.deepEqual([f.options.x, f.options.y, f.options.width, f.options.height], [100, 80, 900, 700]);
- assert.deepEqual(f.calls, ["maximize"]);
+ assert.deepEqual(f.calls, []);
+ f.win.emit("ready-to-show");
+ f.ready();
+ assert.deepEqual(f.calls, ["maximize", "show", ["throttling", true]]);
});
test("旧窗口布局继续使用默认窗口位置", () => {
const f = openWindow(undefined);
assert.deepEqual(f.calls, ["center", f.workArea]);
});
+
+for (const rendererFirst of [true, false]) {
+ test(`新窗口等待自身内容和原生绘制就绪:rendererFirst=${rendererFirst}`, () => {
+ const f = openWindow(state());
+ assert.equal(f.options.show, false);
+ assert.equal(f.options.webPreferences.backgroundThrottling, false);
+ f.ipcMain.emit("siyuan-window-ready", {sender: {id: 99}});
+ f.navigate("/stage/build/app/window.html");
+ f.open();
+ assert.deepEqual(f.calls, []);
+ if (rendererFirst) f.ready();
+ else f.win.emit("ready-to-show");
+ assert.deepEqual(f.calls, []);
+ f.open();
+ assert.deepEqual(f.calls, []);
+ if (rendererFirst) f.win.emit("ready-to-show");
+ else f.ready();
+ assert.deepEqual(f.calls, ["show", ["throttling", true]]);
+ assert.equal(f.timers.size, 0);
+ assert.equal(f.ipcMain.listenerCount("siyuan-window-ready"), 0);
+ assert.equal(f.pendingWindowIds.size, 0);
+ f.ready();
+ f.win.emit("ready-to-show");
+ assert.deepEqual(f.calls, ["show", ["throttling", true]]);
+ f.open();
+ assert.equal(f.calls.at(-1), "show");
+ });
+}
+
+test("全屏窗口也等到内容绘制完成再恢复状态", () => {
+ const f = openWindow(state({fullscreen: true}));
+ assert.deepEqual(f.calls, []);
+ f.ready();
+ f.win.emit("ready-to-show");
+ assert.deepEqual(f.calls, ["fullscreen", "show", ["throttling", true]]);
+});
+
+test("跳转到认证页面后等待原生绘制完成并显示", () => {
+ const f = openWindow(state());
+ f.navigate("/check-auth");
+ assert.deepEqual(f.calls, []);
+ f.win.emit("ready-to-show");
+ assert.deepEqual(f.calls, ["show", ["throttling", true]]);
+});
+
+test("初始化超时可显示窗口,关闭窗口会清理等待资源", () => {
+ const f = openWindow(state());
+ [...f.timers][0]();
+ assert.deepEqual(f.calls, ["show", ["throttling", true]]);
+ assert.equal(f.ipcMain.listenerCount("siyuan-window-ready"), 0);
+ const closed = openWindow(state());
+ const timeout = [...closed.timers][0];
+ closed.win.destroyed = true;
+ closed.win.emit("closed");
+ closed.ready();
+ closed.win.emit("ready-to-show");
+ timeout();
+ assert.deepEqual(closed.calls, []);
+ assert.equal(closed.timers.size, 0);
+ assert.equal(closed.ipcMain.listenerCount("siyuan-window-ready"), 0);
+ assert.equal(closed.pendingWindowIds.size, 0);
+});
diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.ts
index f51e36f13d..8c0b8412f0 100644
--- a/app/src/config/setting/window.ts
+++ b/app/src/config/setting/window.ts
@@ -39,7 +39,7 @@ import type {ISettingsCommand} from "./nativeWindow";
import {getSettingTabDefs} from "./tabs";
import {onWindowsMsg} from "../../window/onWindowsMsg";
import {applyWindowState} from "../../boot/windowControls";
-import {waitForSettingsWindowPaint} from "./windowPaint";
+import {waitForWindowPaint} from "../../util/windowPaint";
import {createSettingsWindowRuntime, resolveSettingsWindowHost, startSettingsWindow} from "./windowRuntime";
let disposeSettingsWindow = () => {};
@@ -208,7 +208,7 @@ const initialize = async () => {
if (!isActive()) return;
applyWindowState(fullscreen ? "enter-full-screen" : "leave-full-screen");
applyWindowState(maximized ? "maximize" : "unmaximize");
- await waitForSettingsWindowPaint(async () => {
+ await waitForWindowPaint(async () => {
await loadAssets(window.siyuan.config.appearance);
if (!isActive()) return;
await setInlineStyle();
diff --git a/app/src/config/setting/windowPaint.test.ts b/app/src/util/windowPaint.test.ts
similarity index 93%
rename from app/src/config/setting/windowPaint.test.ts
rename to app/src/util/windowPaint.test.ts
index a9c897664c..85e52fe44d 100644
--- a/app/src/config/setting/windowPaint.test.ts
+++ b/app/src/util/windowPaint.test.ts
@@ -12,7 +12,7 @@ const fixture = () => {
const listeners = new Map<string, () => void>();
const styles: unknown[] = [];
const exports = {} as typeof import("./windowPaint");
- runInNewContext(transpileModule(readFileSync("src/config/setting/windowPaint.ts", "utf8"), {
+ runInNewContext(transpileModule(readFileSync("src/util/windowPaint.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText, {exports, document: {head: {querySelectorAll: () => styles}},
MutationObserver: class {observe() {} disconnect() { disconnected = true; }},
@@ -35,7 +35,7 @@ const fixture = () => {
frames.clear();
callbacks.forEach(callback => callback());
};
- return {wait: exports.waitForSettingsWindowPaint, frames, timers, listeners, addStyle, nextFrame,
+ return {wait: exports.waitForWindowPaint, frames, timers, listeners, addStyle, nextFrame,
disconnected: () => disconnected};
};
diff --git a/app/src/config/setting/windowPaint.ts b/app/src/util/windowPaint.ts
similarity index 93%
rename from app/src/config/setting/windowPaint.ts
rename to app/src/util/windowPaint.ts
index 9374eb2a35..82027abdde 100644
--- a/app/src/config/setting/windowPaint.ts
+++ b/app/src/util/windowPaint.ts
@@ -1,7 +1,7 @@
const FRAME_WAIT_LIMIT = 250;
-// 等主题样式和设置内容绘制完成,再通知主进程显示原生窗口。
-export const waitForSettingsWindowPaint = async (render: () => Promise<void>) => {
+// 等主题样式和窗口内容绘制完成,再通知主进程显示原生窗口。
+export const waitForWindowPaint = async (render: () => Promise<void>) => {
const initialStyles = new Set(document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]'));
const styles = new Map<HTMLLinkElement, () => void>();
const pending: Promise<void>[] = [];
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index cf6688d59d..e8424f67b7 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -46,6 +46,8 @@ import {emitToPlugins} from "../plugin/EventBusCore";
import {initializeEnglishCommandTranslations} from "../command/english";
import {loadLanguages} from "../boot/loadLanguages";
import {installPluginStorageFetchAppId} from "../util/fetchAppId";
+import {waitForWindowPaint} from "../util/windowPaint";
+import {ipcRenderer} from "electron";
class App {
public plugins: import("../plugin").Plugin[] = [];
@@ -251,11 +253,12 @@ class App {
window.siyuan.menus = new Menus(this);
fetchPost("/api/setting/getCloudUser", {cached: true}, async userResponse => {
window.siyuan.user = userResponse.data && "userId" in userResponse.data ? userResponse.data : null;
- await init(this);
+ await waitForWindowPaint(() => init(this));
setTitle("", true);
initMessage();
window.siyuan.isReady = true;
mainWs.flushMainMessages();
+ ipcRenderer.send("siyuan-window-ready");
fetchPost("/api/setting/getCloudUser", {});
});
});
diff --git a/app/src/window/init.ts b/app/src/window/init.ts
index 597aaec35b..df16b9b8a3 100644
--- a/app/src/window/init.ts
+++ b/app/src/window/init.ts
@@ -5,7 +5,7 @@ import {adjustLayout, getInstanceById, JSONToCenter} from "../layout/util";
import {newCenterEmptyTab, resizeTabs, setTabPosition} from "../layout/tabUtil";
import {initStatus} from "../layout/status";
import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";
-import {initAssets, setInlineStyle} from "../util/assets";
+import {enqueueAppearanceUpdate, initAssets, setInlineStyle} from "../util/assets";
import {renderSnippet} from "../config/util/snippets";
import {getSearch} from "../util/functions";
import {initDesktopHost, initWindow} from "../boot/onGetConfig";
@@ -90,7 +90,9 @@ export const init = async (app: App) => {
/// #endif
appearanceConfigApi.apply(window.siyuan.config.appearance);
initAssets();
- setInlineStyle();
+ await enqueueAppearanceUpdate(async () => {
+ await setInlineStyle();
+ });
renderSnippet();
let resizeTimeout = 0;
window.addEventListener("resize", () => {
diff --git a/app/tests/settingsBoot.test.js b/app/tests/settingsBoot.test.js
index f1941df7ec..f1241ea860 100644
--- a/app/tests/settingsBoot.test.js
+++ b/app/tests/settingsBoot.test.js
@@ -103,7 +103,7 @@ const createBoot = (plugin = false, failed = "", waitForStyles = false) => {
}},
"./tabs": {getSettingTabDefs: () => []},
"../search/dialog": {switchSettingTab: () => wait("assets")},
- "./windowPaint": {waitForSettingsWindowPaint: async render => render()},
+ "../../util/windowPaint": {waitForWindowPaint: async render => render()},
"./windowRuntime": {resolveSettingsWindowHost: () => host, createSettingsWindowRuntime: (_active, deferScripts) => {
assert.equal(deferScripts, true);
return {
diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.js
index 74549c6feb..aee19b82a2 100644
--- a/app/tests/settingsWindow.test.js
+++ b/app/tests/settingsWindow.test.js
@@ -47,7 +47,7 @@ const rendererModules = (sources) => {
const bootChild = async (sources) => {
const {ipcRenderer} = require("electron");
- const {waitForSettingsWindowPaint} = loadRendererModule(sources.paint, {});
+ const {waitForWindowPaint} = loadRendererModule(sources.paint, {});
const {Dialog, genUUID, context, fit, frontend, titles} = rendererModules(sources);
require("node:assert/strict").equal(navigator.userAgent.startsWith("SiYuan/"), false);
require("node:assert/strict").equal(frontend.getFrontend(), "desktop", navigator.userAgent);
@@ -58,7 +58,7 @@ const bootChild = async (sources) => {
class Plugin {openSetting() {}}
const pluginSettings = {};
new Function("Plugin", "exports", sources.pluginSettings)(Plugin, pluginSettings);
- await waitForSettingsWindowPaint(async () => {
+ await waitForWindowPaint(async () => {
const theme = document.createElement("link");
theme.id = "pendingTheme";
theme.rel = "stylesheet";
@@ -442,7 +442,7 @@ if (process.versions.electron && process.type === "browser") {
"\n.config__panel {border-radius: var(--b3-border-radius-b);}\n"]));
for (const [key, file] of Object.entries({dialog: "dialog/index.ts", setting: "plugin/Setting.ts",
native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts", controls: "boot/windowControls.ts",
- paint: "config/setting/windowPaint.ts", frontend: "util/functions.ts", titles: "util/processTitle.ts",
+ paint: "util/windowPaint.ts", frontend: "util/functions.ts", titles: "util/processTitle.ts",
mount: "config/setting/mount.ts", save: "config/setting/save.ts", fragments: "config/render/fragments.ts",
bazaarPath: "config/bazaar/openPath.ts", tooltip: "dialog/tooltip.ts"})) {
let source = fs.readFileSync(path.join(__dirname, "../src", file), "utf8");