Skip to content

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

:bug: Normalize Windows caption colors and isolate height updates https://github.com/siyuan-note/siyuan/issues/20870

Daniel9e87a1ea75e2
diff --git a/app/electron/windowControlsOverlay.js b/app/electron/windowControlsOverlay.js
index f396c72c02..9302cd54f5 100644
--- a/app/electron/windowControlsOverlay.js
+++ b/app/electron/windowControlsOverlay.js
@@ -8,16 +8,25 @@ const getTitleBarOverlayOptions = (platform = process.platform) => platform ===
// 只接收本窗口的尺寸和图标颜色,背景透出页面,保留主题的透明与渐变效果。
const updateTitleBarOverlay = (win, data, platform = process.platform) => {
if (platform !== "win32" || !win || win.isDestroyed() || !data || !Number.isInteger(data.height) ||
- data.height < 1 || data.height > 256 || typeof data.symbolColor !== "string" ||
- !data.symbolColor || data.symbolColor.length > 100) {
+ data.height < 1 || data.height > 256) {
return false;
}
- const style = {color: "#00000000", symbolColor: data.symbolColor, height: data.height};
- const key = JSON.stringify(style);
- if (styles.get(win) === key) return true;
+ const applied = styles.get(win) || {};
+ // 高度先独立更新,主题颜色无效时仍保持窗口按钮与顶栏对齐。
try {
- win.setTitleBarOverlay(style);
- styles.set(win, key);
+ if (applied.height !== data.height) {
+ win.setTitleBarOverlay({color: "#00000000", height: data.height});
+ applied.height = data.height;
+ styles.set(win, applied);
+ }
+ if (typeof data.symbolColor !== "string" || !data.symbolColor || data.symbolColor.length > 100) {
+ return false;
+ }
+ if (applied.symbolColor !== data.symbolColor) {
+ win.setTitleBarOverlay({color: "#00000000", symbolColor: data.symbolColor});
+ applied.symbolColor = data.symbolColor;
+ styles.set(win, applied);
+ }
return true;
} catch {
return false;
diff --git a/app/electron/windowControlsOverlay.test.js b/app/electron/windowControlsOverlay.test.js
index baca3b35c8..f8304ee660 100644
--- a/app/electron/windowControlsOverlay.test.js
+++ b/app/electron/windowControlsOverlay.test.js
@@ -8,18 +8,21 @@ test("caption overlays are Windows-only and keep the page background visible", (
assert.equal(getTitleBarOverlayOptions("linux"), false);
});
-test("caption updates deduplicate per window and preserve transparent theme backgrounds", () => {
+test("caption height and color updates deduplicate independently per window and preserve transparent backgrounds", () => {
const calls = [];
const win = {isDestroyed: () => false, setTitleBarOverlay: style => calls.push(style)};
const data = {height: 42, symbolColor: "rgb(85, 85, 85)", color: "#ffffff"};
assert.equal(updateTitleBarOverlay(win, data, "win32"), true);
assert.equal(updateTitleBarOverlay(win, data, "win32"), true);
- assert.equal(calls.length, 1);
- assert.deepEqual(calls[0], {color: "#00000000", symbolColor: data.symbolColor, height: 42});
+ assert.equal(calls.length, 2);
+ assert.deepEqual(calls[0], {color: "#00000000", height: 42});
+ assert.deepEqual(calls[1], {color: "#00000000", symbolColor: data.symbolColor});
assert.equal(updateTitleBarOverlay(win, {...data, height: 63}, "win32"), true);
- assert.equal(calls.at(-1).height, 63);
+ assert.deepEqual(calls.at(-1), {color: "#00000000", height: 63});
+ assert.equal(updateTitleBarOverlay(win, {...data, height: 63, symbolColor: "rgba(255, 0, 0, 0.5)"}, "win32"), true);
+ assert.deepEqual(calls.at(-1), {color: "#00000000", symbolColor: "rgba(255, 0, 0, 0.5)"});
assert.equal(updateTitleBarOverlay({...win}, data, "win32"), true);
- assert.equal(calls.length, 3);
+ assert.equal(calls.length, 6);
});
test("invalid caption dimensions, unavailable windows and non-Windows updates are ignored", () => {
@@ -27,9 +30,6 @@ test("invalid caption dimensions, unavailable windows and non-Windows updates ar
for (const height of [NaN, Infinity, -1, 0, 0.5, 257, "42", undefined]) {
assert.equal(updateTitleBarOverlay(win, {height, symbolColor: "#ffffff"}, "win32"), false);
}
- for (const symbolColor of [undefined, 1, "", "x".repeat(101)]) {
- assert.equal(updateTitleBarOverlay(win, {height: 42, symbolColor}, "win32"), false);
- }
assert.equal(updateTitleBarOverlay(win, null, "win32"), false);
assert.equal(updateTitleBarOverlay(undefined, {}, "win32"), false);
assert.equal(updateTitleBarOverlay({...win, isDestroyed: () => true}, {}, "win32"), false);
@@ -37,6 +37,32 @@ test("invalid caption dimensions, unavailable windows and non-Windows updates ar
assert.equal(updateTitleBarOverlay(win, {height: 42, symbolColor: "#fff"}, "darwin"), false);
});
+test("missing or malformed symbol colors do not block valid height updates", () => {
+ const calls = [];
+ const win = {isDestroyed: () => false, setTitleBarOverlay: style => calls.push(style)};
+ for (const symbolColor of [undefined, 1, "", "x".repeat(101)]) {
+ assert.equal(updateTitleBarOverlay(win, {height: 42, symbolColor}, "win32"), false);
+ }
+ assert.deepEqual(calls, [{color: "#00000000", height: 42}]);
+});
+
+test("native color rejection leaves the height applied and does not cache a failed color", () => {
+ const calls = [];
+ const win = {isDestroyed: () => false, setTitleBarOverlay: style => {
+ calls.push(style);
+ if (style.symbolColor === "oklch(0.7 0.15 150)") throw new Error("unsupported color");
+ }};
+ assert.equal(updateTitleBarOverlay(win, {height: 32, symbolColor: "#808080"}, "win32"), true);
+ assert.equal(updateTitleBarOverlay(win, {height: 63, symbolColor: "oklch(0.7 0.15 150)"}, "win32"), false);
+ assert.deepEqual(calls[2], {color: "#00000000", height: 63});
+ assert.equal(updateTitleBarOverlay(win, {height: 63, symbolColor: "oklch(0.7 0.15 150)"}, "win32"), false);
+ assert.equal(calls.length, 5, "failed colors are retried without repeating the successful height update");
+ assert.equal(updateTitleBarOverlay(win, {height: 63, symbolColor: "rgba(76, 184, 106, 1)"}, "win32"), true);
+ assert.deepEqual(calls.at(-1), {color: "#00000000", symbolColor: "rgba(76, 184, 106, 1)"});
+ assert.equal(updateTitleBarOverlay(win, {height: 63, symbolColor: "rgba(76, 184, 106, 1)"}, "win32"), true);
+ assert.equal(calls.length, 6);
+});
+
test("failed native caption updates do not poison later retries", () => {
let fail = true;
let calls = 0;
@@ -48,5 +74,5 @@ test("failed native caption updates do not poison later retries", () => {
assert.equal(updateTitleBarOverlay(win, style, "win32"), false);
fail = false;
assert.equal(updateTitleBarOverlay(win, style, "win32"), true);
- assert.equal(calls, 2);
+ assert.equal(calls, 3);
});
diff --git a/app/src/boot/windowControlsOverlay.test.ts b/app/src/boot/windowControlsOverlay.test.ts
index 57f264cff1..cd4afa2439 100644
--- a/app/src/boot/windowControlsOverlay.test.ts
+++ b/app/src/boot/windowControlsOverlay.test.ts
@@ -10,12 +10,13 @@ import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
const browserCases = async (sources: string[], css: string, nativeEnabled = true) => {
const check: typeof assert = require("node:assert/strict");
- const {webFrame} = require("electron") as typeof import("electron");
+ const {webFrame, ipcRenderer} = require("electron") as typeof import("electron");
+ const sent: Array<{cmd: string, height: number, symbolColor?: string}> = [];
document.body.innerHTML = `<style>${css}
:root{--b3-ui-panel-height:42px;--b3-ui-toolbar-height:32px;--b3-toolbar-color:#555555}
.fn__flex{display:flex}.fn__flex-1{flex:1;min-width:0}.fn__none{display:none!important}
.toolbar{padding:0}body{margin:0}#tooltip{--b3-tooltips-background:black;--b3-tooltips-color:white}
- </style><div id="toolbar" class="toolbar fn__flex"><div id="drag" class="fn__flex-1"></div>
+ </style><div id="toolbar" class="toolbar fn__flex"><div id="captionColor" class="toolbar__item"></div><div id="drag" class="fn__flex-1"></div>
<div id="windowControls" class="fn__flex"></div></div>
<div><div class="layout-tab-bar"></div></div><div id="tooltip" class="tooltip fn__none"></div>`;
window.siyuan = {isReady: true, languages: {min: "Minimize", max: "Maximize", restore: "Restore", close: "Close"},
@@ -29,7 +30,10 @@ const browserCases = async (sources: string[], css: string, nativeEnabled = true
resizeTopBar: () => { resizeCalls++; }, setToolbarLeftMac() {},
isMobile: () => false, isTouchHoverInput: () => false, emitToPlugins() {}, forEachPluginSubscriber() {}};
const load = (code: string, exports: object) => new Function("exports", "require", code)(exports, (id: string) => {
- if (id === "electron") return require("electron");
+ if (id === "electron") return {webFrame, ipcRenderer: {send: (channel: string, data: typeof sent[number]) => {
+ if (data?.cmd === "setTitleBarOverlay") sent.push(data);
+ ipcRenderer.send(channel, data);
+ }}};
if (id === "./windowControlsOverlay") return overlay;
return dependencies;
});
@@ -56,6 +60,14 @@ const browserCases = async (sources: string[], css: string, nativeEnabled = true
controls.initWindowControls(container, () => { closed++; });
check.equal(container.children.length, 0, "native controls replace the self-drawn buttons");
const api = (navigator as Navigator & {windowControlsOverlay: import("./windowControlsOverlay").IWindowControlsOverlay}).windowControlsOverlay;
+ const colors = [
+ {css: "oklch(70% .15 150)", rgba: [76, 184, 106, 1]},
+ {css: "oklab(0.6 0 0)", rgba: [128, 128, 128, 1]},
+ {css: "color(display-p3 1 0 0 / .5)", rgba: [255, 0, 0, 128 / 255]},
+ {css: "color-mix(in oklch, red 50%, transparent)", rgba: [255, 0, 0, 128 / 255]},
+ {css: "#123456", rgba: [18, 52, 86, 1]},
+ {css: "rgba(255, 0, 0, 0)", rgba: [0, 0, 0, 0]},
+ ];
for (const fused of [false, true]) for (const zoom of [0.67, 1, 1.5]) {
document.body.classList.toggle("body--toolbar-hide", fused);
webFrame.setZoomFactor(zoom);
@@ -66,6 +78,19 @@ const browserCases = async (sources: string[], css: string, nativeEnabled = true
check.ok(Math.abs(rect.left - safe.right) < 1.5);
check.ok(Math.abs(rect.right - innerWidth) < 1.5);
check.ok(document.getElementById("toolbar").getBoundingClientRect().height >= safe.height - 1);
+ for (const color of colors) {
+ document.getElementById("captionColor").style.color = color.css;
+ overlay.updateWindowControlsOverlay();
+ await new Promise(resolve => setTimeout(resolve, 100));
+ const style = sent.at(-1);
+ check.equal(style.symbolColor, `rgba(${color.rgba.join(", ")})`, `${color.css}, fused=${fused}, zoom=${zoom}`);
+ check.ok(Math.abs(api.getTitlebarAreaRect().height * zoom - style.height) < 1.5,
+ "modern theme colors must not block native height updates");
+ const applied = await ipcRenderer.invoke("overlay-test-state");
+ overlay.updateWindowControlsOverlay();
+ check.deepEqual(await ipcRenderer.invoke("overlay-test-state"), applied,
+ "unchanged color and geometry do not repeat native updates");
+ }
const target = document.createElement("span");
target.style.cssText = `position:fixed;right:${innerWidth - safe.right + 2}px;top:4px;width:20px;height:18px`;
document.body.append(target);
@@ -79,6 +104,34 @@ const browserCases = async (sources: string[], css: string, nativeEnabled = true
tooltip.hideTooltip();
target.remove();
}
+ const icon = document.getElementById("captionColor");
+ icon.style.color = "#aabbcc";
+ await ipcRenderer.invoke("overlay-test-reject-color");
+ overlay.updateWindowControlsOverlay();
+ const rejected = await ipcRenderer.invoke("overlay-test-state");
+ check.equal(rejected.rejections, 1);
+ overlay.updateWindowControlsOverlay();
+ const retried = await ipcRenderer.invoke("overlay-test-state");
+ check.equal(retried.symbolColor, "rgba(170, 187, 204, 1)", "an unchanged renderer request retries a failed native color");
+ check.equal(retried.rejections, 1);
+
+ icon.style.color = "#fedcba";
+ document.documentElement.style.setProperty("--b3-ui-panel-height", "46px");
+ const readPixels = CanvasRenderingContext2D.prototype.getImageData;
+ try {
+ CanvasRenderingContext2D.prototype.getImageData = () => { throw new Error("canvas temporarily unavailable"); };
+ overlay.updateWindowControlsOverlay();
+ check.equal(sent.at(-1).symbolColor, undefined);
+ const partial = await ipcRenderer.invoke("overlay-test-state");
+ check.equal(partial.height, 69, "a conversion failure still updates the native height");
+ check.equal(partial.symbolColor, retried.symbolColor, "a conversion failure keeps the applied symbol color");
+ } finally {
+ CanvasRenderingContext2D.prototype.getImageData = readPixels;
+ }
+ overlay.updateWindowControlsOverlay();
+ check.equal((await ipcRenderer.invoke("overlay-test-state")).symbolColor, "rgba(254, 220, 186, 1)",
+ "color conversion recovers without changing the requested CSS color");
+ document.documentElement.style.removeProperty("--b3-ui-panel-height");
webFrame.setZoomFactor(0.67);
document.body.classList.remove("body--toolbar-hide");
overlay.updateWindowControlsOverlay();
@@ -100,7 +153,7 @@ const browserCases = async (sources: string[], css: string, nativeEnabled = true
};
test("native Windows captions reserve geometry, preserve legacy controls and keep tooltips clear", {
- skip: process.platform !== "win32", timeout: 20000,
+ skip: process.platform !== "win32", timeout: 30000,
}, async () => {
const sources = ["src/boot/windowControlsOverlay.ts", "src/boot/windowControls.ts", "src/dialog/tooltip.ts"].map(file =>
transpileModule(readFileSync(file, "utf8"), {compilerOptions: {
@@ -118,6 +171,16 @@ app.setPath("userData",${JSON.stringify(path.join(temporary, "profile"))});
app.whenReady().then(async()=>{
const win=new BrowserWindow({show:false,width:800,height:600,frame:false,titleBarStyle:"hidden",
titleBarOverlay:{color:"#00000000"},webPreferences:{nodeIntegration:true,contextIsolation:false,backgroundThrottling:false}});
+ const nativeSet=win.setTitleBarOverlay.bind(win);
+ const state={updates:0,rejections:0,height:undefined,symbolColor:undefined};let rejectColor=false;
+ win.setTitleBarOverlay=style=>{
+ if(rejectColor&&style.symbolColor){rejectColor=false;state.rejections++;throw new Error("temporary native color failure");}
+ nativeSet(style);state.updates++;
+ if(style.height!==undefined)state.height=style.height;
+ if(style.symbolColor!==undefined)state.symbolColor=style.symbolColor;
+ };
+ ipcMain.handle("overlay-test-state",()=>({...state}));
+ ipcMain.handle("overlay-test-reject-color",()=>{rejectColor=true;});
ipcMain.on("siyuan-cmd",(event,data)=>{if(data.cmd==="setTitleBarOverlay")updateTitleBarOverlay(win,data);});
try{
const legacy=new BrowserWindow({show:false,width:800,height:600,frame:false,titleBarStyle:"hidden",
@@ -128,6 +191,11 @@ app.whenReady().then(async()=>{
if(fallback!=="Window controls overlay cases passed")throw new Error(fallback);
legacy.destroy();
await win.loadFile(${JSON.stringify(html)});
+ if(updateTitleBarOverlay(win,{height:55,symbolColor:"oklch(0.7 0.15 150)"})!==false)throw new Error("native parser unexpectedly accepted oklch");
+ await new Promise(resolve=>setTimeout(resolve,100));
+ if(await win.webContents.executeJavaScript("navigator.windowControlsOverlay.getTitlebarAreaRect().height")!==55)throw new Error("color rejection blocked native height");
+ updateTitleBarOverlay(win,{height:32,symbolColor:"#808080"});
+ await new Promise(resolve=>setTimeout(resolve,100));
const result=await win.webContents.executeJavaScript(${JSON.stringify("const __name=value=>value;(" +
browserCases.toString() + ")(" + JSON.stringify(sources) + "," + JSON.stringify(css) + ")")});
console.log(result);win.destroy();app.exit(0);
@@ -137,7 +205,7 @@ app.whenReady().then(async()=>{
delete env.ELECTRON_RUN_AS_NODE;
try {
const result = await promisify(execFile)(require("electron") as unknown as string, [script],
- {env, timeout: 15000, windowsHide: true});
+ {env, timeout: 25000, windowsHide: true});
assert.match(result.stdout, /Window controls overlay cases passed/);
} finally {
if (path.dirname(path.resolve(temporary)) === path.resolve(tmpdir()) &&
diff --git a/app/src/boot/windowControlsOverlay.ts b/app/src/boot/windowControlsOverlay.ts
index 09ee79d976..a67b76a97e 100644
--- a/app/src/boot/windowControlsOverlay.ts
+++ b/app/src/boot/windowControlsOverlay.ts
@@ -10,12 +10,38 @@ export interface IWindowControlsOverlay extends EventTarget {
let initialized = false;
let scheduled = false;
let minimumHeight = 31;
-let lastStyle = "";
let lastLayout = "";
let sizeObserver: ResizeObserver;
+let colorContext: CanvasRenderingContext2D | null | undefined;
+let lastComputedColor = "";
+let lastSymbolColor: string;
const getOverlay = () => (navigator as Navigator & {windowControlsOverlay?: IWindowControlsOverlay}).windowControlsOverlay;
+// 用浏览器解析主题颜色并转成 sRGB,避免把原生解析器不支持的颜色格式直接传入 Electron。
+const getSymbolColor = (color: string) => {
+ if (lastComputedColor === color) return lastSymbolColor;
+ try {
+ if (!CSS.supports("color", color)) return;
+ if (!colorContext) {
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 1;
+ colorContext = canvas.getContext("2d", {willReadFrequently: true});
+ }
+ if (!colorContext) return;
+ colorContext.clearRect(0, 0, 1, 1);
+ colorContext.fillStyle = color;
+ colorContext.fillRect(0, 0, 1, 1);
+ const [r, g, b, a] = colorContext.getImageData(0, 0, 1, 1).data;
+ lastComputedColor = color;
+ lastSymbolColor = `rgba(${r}, ${g}, ${b}, ${a / 255})`;
+ return lastSymbolColor;
+ } catch {
+ // 无法转换时仅同步高度,保留原有按钮颜色。
+ colorContext = undefined;
+ }
+};
+
export const updateWindowControlsOverlay = () => {
scheduled = false;
const overlay = getOverlay();
@@ -30,14 +56,11 @@ export const updateWindowControlsOverlay = () => {
const height = parseFloat(rootStyle.getPropertyValue(standalone || fused ?
"--b3-ui-panel-height" : "--b3-ui-toolbar-height")) || (standalone || fused ? 42 : 32);
const icon = toolbar.querySelector<HTMLElement>(".toolbar__item");
- const symbolColor = getComputedStyle(icon || toolbar).color;
+ const symbolColor = getSymbolColor(getComputedStyle(icon || toolbar).color);
const style = {cmd: "setTitleBarOverlay", symbolColor,
height: Math.max(minimumHeight, Math.round(height * webFrame.getZoomFactor()))};
- const styleKey = JSON.stringify(style);
- if (lastStyle !== styleKey) {
- lastStyle = styleKey;
- ipcRenderer.send(Constants.SIYUAN_CMD, style);
- }
+ // 主进程按实际应用成功的状态去重,同一请求在失败后仍可重试。
+ ipcRenderer.send(Constants.SIYUAN_CMD, style);
const topRows = new Set<Element>();
if (standalone || fused) {