Skip to content

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

:bug: Fix appearance refresh and PDF selection regressions with alpha9 test repairs

Daniel70a867b8fc39
diff --git a/app/electron/connectionManager.test.js b/app/electron/connectionManager.test.js
index 4d806bd4c1..05647c4c97 100644
--- a/app/electron/connectionManager.test.js
+++ b/app/electron/connectionManager.test.js
@@ -163,7 +163,14 @@ if (!process.versions.electron) {
dialogHost = new BrowserWindow({show: false, width: 900, height: 700,
webPreferences: {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false, offscreen: true}});
await dialogHost.loadURL("data:text/html,<html><body></body></html>");
- const runDialog = code => dialogHost.webContents.executeJavaScript(code);
+ const runDialog = async code => {
+ const result = await dialogHost.webContents.executeJavaScript(`(async () => {
+ try { return {value: await (0, eval)(${JSON.stringify(code)})}; }
+ catch (error) { return {error: error.stack || String(error)}; }
+ })()`);
+ if (result.error) throw new Error(result.error);
+ return result.value;
+ };
const ts = require("typescript");
const compile = name => ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src", name), "utf8"), {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
@@ -191,7 +198,7 @@ if (!process.versions.electron) {
};
modules["../util/escape"] = load(${JSON.stringify(compile("util/escape.ts"))});
modules["../util/zIndex"] = load(${JSON.stringify(compile("util/zIndex.ts"))});
- modules["./index"] = load(${JSON.stringify(compile("dialog/index.ts"))});
+ modules["./index"] = load(${JSON.stringify(require("../tests/fixtures/anchoredInputRuntime.cjs").withAnchoredInputRuntime(compile("dialog/index.ts")))});
window.openRemoteConnection = load(${JSON.stringify(compile("dialog/remoteConnection.ts"))}).openRemoteConnection;
window.openRemoteConnection(${JSON.stringify(origin)});
})()`);
diff --git a/app/src/asset/pdf/text_layer_builder.js b/app/src/asset/pdf/text_layer_builder.js
index 7a917c3655..3c7b1a3171 100644
--- a/app/src/asset/pdf/text_layer_builder.js
+++ b/app/src/asset/pdf/text_layer_builder.js
@@ -269,7 +269,7 @@ class TextLayerBuilder {
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
// eslint-disable-next-line no-var
- var isFirefoxOrModernChromium, prevRange;
+ var isFirefox, prevRange;
}
document.addEventListener(
@@ -309,33 +309,19 @@ class TextLayerBuilder {
if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
return;
}
- if (isFirefoxOrModernChromium === undefined) {
- if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("CHROME")) {
- isFirefoxOrModernChromium =
- getComputedStyle(
- this.#textLayers.values().next().value
- ).getPropertyValue("-moz-user-select") === "none";
- }
- if (
- (typeof PDFJSDev !== "undefined" && PDFJSDev.test("CHROME")) ||
- !isFirefoxOrModernChromium
- ) {
- // navigator.userAgentData is only available in secure contexts
- const chromiumVersion = navigator.userAgentData
- ? navigator.userAgentData.brands.find(
- ({ brand }) => brand === "Chromium"
- )?.version
- : /\bChrome\/(\d+)\b/.exec(navigator.userAgent)?.[1];
-
- isFirefoxOrModernChromium =
- !!chromiumVersion && parseInt(chromiumVersion, 10) >= 148;
- }
+ if (isFirefox === undefined) {
+ isFirefox =
+ (typeof PDFJSDev === "undefined" || !PDFJSDev.test("CHROME")) &&
+ getComputedStyle(
+ this.#textLayers.values().next().value
+ ).getPropertyValue("-moz-user-select") === "none";
}
- if (isFirefoxOrModernChromium) {
+ if (isFirefox) {
return;
}
- // In browsers other than Firefox or Chromium 148+, when hovering over
+ // Chromium 154 仍会在非选中的 endOfContent 上冻结选区,不能按版本跳过补偿。
+ // In browsers other than Firefox, when hovering over
// an empty space (thus, on .endOfContent), the selection will expand to
// cover all the text between the current selection and .endOfContent.
// By moving .endOfContent to right after (or before, depending on which
diff --git a/app/src/layout/dock/Graph.test.ts b/app/src/layout/dock/Graph.test.ts
index 92a6fc80a8..725ae8be98 100644
--- a/app/src/layout/dock/Graph.test.ts
+++ b/app/src/layout/dock/Graph.test.ts
@@ -3,7 +3,8 @@ import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
-import {flushSettingSaves, trackSettingRequest} from "../../config/setting/pending";
+import {flushSettingSaves, trackSettingSave} from "../../config/setting/pending";
+import {mergeRecordByDottedPath} from "../../config/util/dotPath";
for (const type of ["global", "local", "pin"]) {
test(`reset flushes the latest delayed graph settings before acknowledging (${type})`, async () => {
@@ -16,16 +17,50 @@ for (const type of ["global", "local", "pin"]) {
const code = transpileModule(readFileSync("src/layout/dock/Graph.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText;
+ const runtimeWindow = {
+ siyuan: {config: {graph: {}}},
+ setTimeout: (callback: () => void) => { timers.set(++timerID, callback); return timerID; },
+ clearTimeout: (id: number) => timers.delete(id),
+ };
+ let requestStarted: () => void;
+ const started = new Promise<void>(resolve => { requestStarted = resolve; });
+ const configExports = {} as typeof import("../../config/util/configApi");
+ runInNewContext(transpileModule(readFileSync("src/config/util/configApi.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {
+ exports: configExports, window: runtimeWindow, structuredClone,
+ require: (name: string) => {
+ if (name === "../../util/fetch") return {fetchSyncPost: (url: string, data: typeof writes[number]) => {
+ assert.equal(url, "/api/graph/setGraphConf");
+ writes.push(data);
+ requestStarted();
+ return request.then(() => ({code: 0}));
+ }};
+ if (name === "./dotPath") return {mergeRecordByDottedPath};
+ if (name === "../setting/pending") return {trackSettingSave};
+ if (name === "../setting/sync") return {
+ refreshSettingConfigAfter: async (namespace: string, save: () => Promise<boolean>) => {
+ assert.equal(namespace, "graph");
+ return save();
+ },
+ };
+ throw new Error("Unexpected config fixture module: " + name);
+ },
+ });
+ const unusedModules = new Set(["./panelSearch", "../Tab", "../util", "../tabUtil", "../../block/Panel",
+ "../../protyle/breadcrumb/action", "../../util/fetch", "../../editor/util",
+ "../../protyle/util/compatibility", "../../search/util", "../../util/noRelyPCFunction",
+ "../../editor", "../../util/pathName", "./graph/GraphEngine", "../../protyle/header/documentMenu",
+ "../../constants"]);
runInNewContext(code, {
- exports,
- require: () => ({Model: class {}, fetchPost: (url: string, data: typeof writes[number]) => {
- writes.push(data);
- return trackSettingRequest(url, request);
- }}),
- window: {
- siyuan: {config: {graph: {}}},
- setTimeout: (callback: () => void) => { timers.set(++timerID, callback); return timerID; },
- clearTimeout: (id: number) => timers.delete(id),
+ exports, window: runtimeWindow,
+ require: (name: string) => {
+ if (name === "../Model") return {Model: class {}};
+ if (name === "../../config/util/configApi") return configExports;
+ assert.ok(unusedModules.has(name), "Unexpected graph fixture module: " + name);
+ return new Proxy({}, {get: (_target, key) => {
+ throw new Error(`Unexpected graph fixture dependency: ${name}.${String(key)}`);
+ }});
},
});
let conf = {dailyNote: false};
@@ -40,9 +75,11 @@ for (const type of ["global", "local", "pin"]) {
graph.scheduleGraphSearch();
const resume = graph.suspendSettingsSaving();
assert.equal(timers.size, 0);
+ await started;
assert.equal(writes.length, 1);
assert.equal(writes[0].type, type === "global" ? "global" : "local");
- assert.equal(writes[0].conf, conf);
+ assert.deepEqual(writes[0].conf, conf);
+ assert.notEqual(writes[0].conf, conf, "queued configuration is copied before saving");
graph.searchGraph();
assert.equal(writes.length, 1);
let flushed = false;
diff --git a/app/tests/anchoredInputRuntime.test.js b/app/tests/anchoredInputRuntime.test.js
new file mode 100644
index 0000000000..ffbc6bfabb
--- /dev/null
+++ b/app/tests/anchoredInputRuntime.test.js
@@ -0,0 +1,36 @@
+const assert = require("node:assert/strict");
+const {readFileSync} = require("node:fs");
+const path = require("node:path");
+const {test} = require("node:test");
+const ts = require("typescript");
+const {compileAnchoredInputRuntime, withAnchoredInputRuntime} = require("./fixtures/anchoredInputRuntime.cjs");
+
+test("dialog fixtures load the real anchored input dependency graph", () => {
+ const source = compileAnchoredInputRuntime();
+ const api = new Function("return " + source)();
+ assert.equal(api.getAnchoredInputMask(), undefined);
+ assert.equal(api.closeAnchoredInput(false), undefined);
+ assert.equal(typeof api.openAnchoredInput, "function");
+ assert.throws(() => new Function("return " + source.replace('"./anchoredInputPosition":', '"./missingPosition":'))(),
+ /Unexpected anchored input fixture module/);
+});
+
+test("dialog fixture wrapper preserves strict external dependency resolution", () => {
+ const source = ts.transpileModule(readFileSync(path.join(__dirname, "../src/dialog/index.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ const imports = [];
+ const allowed = new Set(["../util/genID", "../util/zIndex", "./moveResize", "../util/functions",
+ "../protyle/util/compatibility", "../constants", "../block/panelOwnership"]);
+ const exports = {};
+ new Function("require", "exports", withAnchoredInputRuntime(source))(name => {
+ assert.ok(allowed.has(name), "Unexpected dialog fixture dependency: " + name);
+ imports.push(name);
+ return {};
+ }, exports);
+ assert.equal(typeof exports.Dialog, "function");
+ assert.equal(imports.includes("./anchoredInput"), false);
+ assert.equal(imports.length, allowed.size);
+ assert.throws(() => new Function("require", "exports", withAnchoredInputRuntime('require("./unexpected")'))(
+ name => { throw new Error("Unmocked dependency: " + name); }, {}), /Unmocked dependency: \.\/unexpected/);
+});
diff --git a/app/tests/dialogFocus.test.js b/app/tests/dialogFocus.test.js
index 88c5a736bb..fa922656d3 100644
--- a/app/tests/dialogFocus.test.js
+++ b/app/tests/dialogFocus.test.js
@@ -562,9 +562,10 @@ if (process.versions.electron && process.type === "browser") {
}
});
const ts = require("typescript");
- const source = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src/dialog/index.ts"), "utf8"), {
+ const {withAnchoredInputRuntime} = require("./fixtures/anchoredInputRuntime.cjs");
+ const source = withAnchoredInputRuntime(ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src/dialog/index.ts"), "utf8"), {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
- }).outputText;
+ }).outputText);
await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(source)})`);
const positionSource = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src/util/setPosition.ts"), "utf8"), {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
diff --git a/app/tests/fixtures/anchoredInputRuntime.cjs b/app/tests/fixtures/anchoredInputRuntime.cjs
new file mode 100644
index 0000000000..f254d96870
--- /dev/null
+++ b/app/tests/fixtures/anchoredInputRuntime.cjs
@@ -0,0 +1,32 @@
+const {readFileSync} = require("node:fs");
+const path = require("node:path");
+const ts = require("typescript");
+
+const compileAnchoredInputRuntime = () => {
+ const sources = Object.fromEntries(["anchoredInput", "anchoredInputPosition"].map(name => ["./" + name,
+ ts.transpileModule(readFileSync(path.join(__dirname, "../../src/dialog", name + ".ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText]));
+ // 保留输入层及定位实现,只隔离系统键盘桥;未知依赖立即报错。
+ return `(() => {
+ const sources = ${JSON.stringify(sources)};
+ const modules = {"../mobile/util/mobileAppUtil": {callMobileAppShowKeyboard() {}}};
+ const load = name => {
+ if (Object.hasOwn(modules, name)) return modules[name];
+ if (!Object.hasOwn(sources, name)) throw new Error("Unexpected anchored input fixture module: " + name);
+ const exports = {};
+ modules[name] = exports;
+ new Function("require", "exports", sources[name])(load, exports);
+ return exports;
+ };
+ return load("./anchoredInput");
+ })()`;
+};
+
+const withAnchoredInputRuntime = source => `
+ const anchoredInputRuntime = ${compileAnchoredInputRuntime()};
+ const parentRequire = require;
+ require = name => name === "./anchoredInput" ? anchoredInputRuntime : parentRequire(name);
+ ${source}`;
+
+module.exports = {compileAnchoredInputRuntime, withAnchoredInputRuntime};
diff --git a/app/tests/historySnapshots.test.js b/app/tests/historySnapshots.test.js
index 1eab22b092..f65d098959 100644
--- a/app/tests/historySnapshots.test.js
+++ b/app/tests/historySnapshots.test.js
@@ -169,6 +169,7 @@ if (process.versions.electron && process.type === "browser") {
for (const name of ["dialog/index", "util/escape", "history/docSnapshots", "history/snapshotDetail", "history/notebookDialogs", "history/repoFile"]) {
sources[name] = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src", name + ".ts"), "utf8"), {compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020}}).outputText;
}
+ sources["dialog/index"] = require("./fixtures/anchoredInputRuntime.cjs").withAnchoredInputRuntime(sources["dialog/index"]);
for (const mobile of [false, true]) {
const styles = sass.compile(path.join(__dirname, `../src/assets/scss/${mobile ? "mobile" : "base"}.scss`), {logger: sass.Logger.silent}).css;
for (const dark of [false, true]) {
diff --git a/app/tests/inlineMathSelection.test.js b/app/tests/inlineMathSelection.test.js
index 356bad82ad..389953450d 100644
--- a/app/tests/inlineMathSelection.test.js
+++ b/app/tests/inlineMathSelection.test.js
@@ -38,6 +38,7 @@ const setup = async (source, suffix) => {
};
const setupEdge = async (mode) => {
+ window.mathSelectionDiagnosticAbort?.abort();
document.body.innerHTML = '<div class="protyle-wysiwyg" contenteditable="false" data-readonly="false">' +
'<div data-node-id="20261010232335-t6hx5pb" data-type="NodeParagraph" class="p">' +
'<div contenteditable="true" spellcheck="false"><span data-inline-wrap="token"></span>' +
@@ -69,12 +70,32 @@ const setupEdge = async (mode) => {
const rect = math.getBoundingClientRect();
const after = point(math.nextSibling, 1);
const before = point(prefix.firstChild, prefix.textContent.length - 2);
+ const diagnosticAbort = new AbortController();
+ window.mathSelectionDiagnosticAbort = diagnosticAbort;
+ window.mathSelectionDiagnostics = {mode, events: []};
+ const recordSelection = (phase, event) => {
+ const selection = getSelection();
+ const describe = node => node ? {name: node.nodeName,
+ text: node.textContent?.slice(0, 180), parent: node.parentElement?.outerHTML.slice(0, 512)} : null;
+ const events = window.mathSelectionDiagnostics.events;
+ if (events.length >= 48) return;
+ events.push({phase, text: selection?.toString(), collapsed: selection?.isCollapsed,
+ anchor: describe(selection?.anchorNode), anchorOffset: selection?.anchorOffset,
+ focus: describe(selection?.focusNode), focusOffset: selection?.focusOffset,
+ pointer: event && typeof event.clientX === "number" ? {x: event.clientX, y: event.clientY,
+ target: event.target?.outerHTML?.slice(0, 512)} : null});
+ };
+ for (const type of ["mousedown", "selectionchange", "mouseup", "click"]) {
+ document.addEventListener(type, event => recordSelection(type, event), {signal: diagnosticAbort.signal});
+ }
document.addEventListener("click", () => {
// 使用编辑器的延迟光标校正,验证鼠标释放后的选区不会被折叠。
setTimeout(() => {
const selection = getSelection();
if (selection.rangeCount) {
+ recordSelection("before-caret-normalization");
window.mathSelectionAPI.normalizeInlineMathCaret(selection.getRangeAt(0));
+ recordSelection("after-caret-normalization");
}
}, 0);
}, {once: true});
@@ -144,7 +165,8 @@ const runElectron = async () => {
win.webContents.debugger.attach("1.3");
const send = params => win.webContents.debugger.sendCommand("Input.dispatchMouseEvent", params);
const drag = async (from, to, edge = false) => {
- await win.webContents.executeJavaScript("getSelection().removeAllRanges(); true;");
+ await win.webContents.executeJavaScript(`getSelection().removeAllRanges();
+ if (window.mathSelectionDiagnostics) window.mathSelectionDiagnostics.events = []; true;`);
await send({type: "mouseMoved", ...from});
await send({type: "mousePressed", ...from, button: "left", clickCount: 1});
for (let step = 1; step <= 15; step++) {
@@ -155,7 +177,29 @@ const runElectron = async () => {
await new Promise(resolve => setTimeout(resolve, 30));
const text = await win.webContents.executeJavaScript("getSelection().toString()");
if (edge) {
- assert.match(text, /I[\s\S]*E/, JSON.stringify(text));
+ try {
+ assert.match(text, /I[\s\S]*E/, JSON.stringify(text));
+ } catch (error) {
+ try {
+ const diagnostics = await win.webContents.executeJavaScript(`(() => {
+ const math = document.querySelector('[data-type="inline-math"]');
+ const describePoint = point => {
+ const hit = document.elementFromPoint(point.x, point.y);
+ const caret = document.caretRangeFromPoint(point.x, point.y);
+ return {point, hit: hit?.outerHTML.slice(0, 512),
+ caretText: caret?.startContainer.textContent?.slice(0, 180), caretOffset: caret?.startOffset};
+ };
+ return {...window.mathSelectionDiagnostics,
+ from: describePoint(${JSON.stringify(from)}), to: describePoint(${JSON.stringify(to)}),
+ math: math?.getBoundingClientRect().toJSON(), viewport: [innerWidth, innerHeight],
+ selection: {text: getSelection().toString(), collapsed: getSelection().isCollapsed}};
+ })()`);
+ error.message += "\nSelection diagnostics: " + JSON.stringify(diagnostics);
+ } catch {
+ // 页面关闭或诊断失败时仍保留原始选区断言。
+ }
+ throw error;
+ }
const markdown = await win.webContents.executeJavaScript(`(() => {
const copy = document.createElement("div");
copy.append(getSelection().getRangeAt(0).cloneContents());
diff --git a/app/tests/pdfTextSelectionBoundary.test.js b/app/tests/pdfTextSelectionBoundary.test.js
new file mode 100644
index 0000000000..2b55288a83
--- /dev/null
+++ b/app/tests/pdfTextSelectionBoundary.test.js
@@ -0,0 +1,105 @@
+const assert = require("node:assert/strict");
+const {readFileSync} = require("node:fs");
+const path = require("node:path");
+const {test} = require("node:test");
+const ts = require("typescript");
+
+const source = readFileSync(path.join(__dirname, "../src/asset/pdf/text_layer_builder.js"), "utf8");
+const parsed = ts.createSourceFile("text_layer_builder.js", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS);
+const builder = parsed.statements.find(node => ts.isClassDeclaration(node) && node.name?.text === "TextLayerBuilder");
+assert.ok(builder);
+const listener = builder.members.find(node => node.name?.getText(parsed) === "#enableGlobalSelectionListener");
+assert.ok(listener);
+
+// 驱动真实监听器的 DOM 协议,不把模拟范围当作浏览器原生划选结果。
+const fixture = ({version = 154, firefox = false, brands = false} = {}) => {
+ const events = new Map();
+ const classes = new Set();
+ const insertions = [];
+ const end = {style: {}, childNodes: []};
+ const layer = {
+ style: {width: "666px", height: "833px"},
+ classList: {add: name => classes.add(name), remove: name => classes.delete(name)},
+ closest: selector => selector === ".textLayer" ? layer : null,
+ append: node => insertions.push({node, before: null}),
+ insertBefore: (node, before) => insertions.push({node, before}),
+ };
+ const next = {};
+ const span = {parentElement: layer, parentNode: layer, nextSibling: next,
+ classList: {contains: () => false}, childNodes: [{}]};
+ const text = {nodeType: 3, parentNode: span};
+ let backward = false;
+ let rangeCount = 1;
+ const range = {startContainer: text, endContainer: text, startOffset: 0, endOffset: 8,
+ intersectsNode: node => node === layer,
+ compareBoundaryPoints: () => backward ? 0 : 1,
+ cloneRange: () => ({})};
+ const document = {
+ addEventListener: (name, callback) => events.set(name, callback),
+ getSelection: () => ({rangeCount, getRangeAt: () => range}),
+ };
+ const Harness = new Function("document", "window", "getComputedStyle", "Node", "Range", "navigator", `
+ return class {
+ static #textLayers = new Map();
+ static #selectionChangeAC = null;
+ ${listener.getText(parsed)}
+ static start(layer, end) {
+ this.#textLayers.set(layer, end);
+ this.#enableGlobalSelectionListener();
+ }
+ };
+ `)(document, {addEventListener: (name, callback) => events.set(name, callback)},
+ () => ({getPropertyValue: () => firefox ? "none" : ""}), {TEXT_NODE: 3},
+ {END_TO_END: 2, START_TO_END: 1},
+ {userAgent: `Mozilla/5.0 Chrome/${version}.0.0.0`,
+ userAgentData: brands ? {brands: [{brand: "Chromium", version: String(version)}]} : undefined});
+ Harness.start(layer, end);
+ return {end, span, next, classes, insertions,
+ fire: name => events.get(name)(),
+ backward: () => { backward = true; },
+ clear: () => { rangeCount = 0; }};
+};
+
+for (const version of [147, 148, 154]) {
+ for (const brands of [false, true]) {
+ test(`Chromium ${version}, brands=${brands}: empty-space selection remains selectable beside the active span`, () => {
+ const item = fixture({version, brands});
+ item.fire("pointerdown");
+ item.fire("selectionchange");
+ assert.equal(item.end.style.userSelect, "text");
+ assert.equal(item.end.style.width, "666px");
+ assert.equal(item.end.style.height, "833px");
+ assert.equal(item.insertions.at(-1).before, item.next);
+ assert.ok(item.classes.has("selecting"));
+ item.fire("pointerup");
+ assert.equal(item.end.style.width, "");
+ assert.equal(item.end.style.height, "");
+ assert.equal(item.insertions.at(-1).before, null);
+ assert.ok(!item.classes.has("selecting"));
+ });
+ }
+}
+
+test("reverse PDF selection positions the empty-space sentinel before the active span", () => {
+ const item = fixture();
+ item.fire("selectionchange");
+ item.backward();
+ item.fire("selectionchange");
+ assert.equal(item.insertions.at(-1)?.before, item.span);
+});
+
+test("clearing PDF selection resets the sentinel and selecting class", () => {
+ const item = fixture();
+ item.fire("selectionchange");
+ item.clear();
+ item.fire("selectionchange");
+ assert.equal(item.insertions.at(-1).before, null);
+ assert.ok(!item.classes.has("selecting"));
+});
+
+test("Firefox retains its native empty-space selection handling", () => {
+ const item = fixture({firefox: true});
+ item.fire("selectionchange");
+ assert.equal(item.insertions.length, 0);
+ assert.equal(item.end.style.userSelect, undefined);
+});
diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.js
index c9efa51a04..0c19367ddc 100644
--- a/app/tests/settingsWindow.test.js
+++ b/app/tests/settingsWindow.test.js
@@ -459,6 +459,7 @@ if (process.versions.electron && process.type === "browser") {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
}).outputText;
}
+ sources.dialog = require("./fixtures/anchoredInputRuntime.cjs").withAnchoredInputRuntime(sources.dialog);
const pluginSource = ts.createSourceFile("plugin/index.ts", fs.readFileSync(path.join(__dirname, "../src/plugin/index.ts"), "utf8"),
ts.ScriptTarget.ES2021, true);
const pluginSetting = pluginSource.statements.find(statement => ts.isVariableStatement(statement) &&
diff --git a/kernel/api/setting.go b/kernel/api/setting.go
index b57f9b8559..d5470a9d34 100644
--- a/kernel/api/setting.go
+++ b/kernel/api/setting.go
@@ -564,7 +564,7 @@ func applyAppearanceSetting(c *gin.Context, request apicontract.SetAppearanceReq
if !request.HasField("globalFontFamilies") {
appearance.GlobalFontFamilies = model.Conf.Appearance.Load().GlobalFontFamilies
}
- issues, applyErr := model.ApplyConfSection("appearance", appearance)
+ issues, applyErr := model.ApplyAppearanceSetting(appearance)
recordSettingIssues(c, issues)
err = applyErr
if err != nil {
diff --git a/kernel/api/setting_appearance_refresh_test.go b/kernel/api/setting_appearance_refresh_test.go
new file mode 100644
index 0000000000..35e856e904
--- /dev/null
+++ b/kernel/api/setting_appearance_refresh_test.go
@@ -0,0 +1,173 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gorilla/websocket"
+ "github.com/olahol/melody"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractAppearanceSameSelectionRefreshesPackages(t *testing.T) {
+ for _, endpoint := range []string{"setAppearance", "patch"} {
+ t.Run(endpoint, func(t *testing.T) {
+ previous, readOnly, mode, lang := model.Conf, util.ReadOnly, util.Mode, util.Lang
+ working, appearance, themes, icons := util.WorkingDir, util.AppearancePath, util.ThemesPath, util.IconsPath
+ confDir, dataDir, repoDir := util.ConfDir, util.DataDir, util.RepoDir
+ t.Cleanup(func() {
+ model.Conf, util.ReadOnly, util.Mode, util.Lang = previous, readOnly, mode, lang
+ util.WorkingDir, util.AppearancePath, util.ThemesPath, util.IconsPath = working, appearance, themes, icons
+ util.ConfDir, util.DataDir, util.RepoDir = confDir, dataDir, repoDir
+ model.ApplyConfRuntime()
+ })
+ root := t.TempDir()
+ t.Cleanup(model.CloseWatchThemes)
+ util.WorkingDir, util.ConfDir = filepath.Join(root, "working"), filepath.Join(root, "conf")
+ util.DataDir, util.RepoDir = filepath.Join(root, "data"), filepath.Join(root, "repo")
+ util.AppearancePath = filepath.Join(util.ConfDir, "appearance")
+ util.ThemesPath, util.IconsPath = filepath.Join(util.DataDir, "themes"), filepath.Join(util.DataDir, "icons")
+ if err := os.MkdirAll(util.ConfDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ util.Mode, util.ReadOnly = "prod", false
+ model.Conf = model.NewAppConf()
+ model.NormalizeAppConf(model.Conf)
+ write := func(path, content string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, name := range []string{"daylight", "midnight", "custom"} {
+ base := filepath.Join(util.WorkingDir, "appearance", "themes", name)
+ if name == "custom" {
+ base = filepath.Join(util.ThemesPath, name)
+ }
+ write(filepath.Join(base, "theme.json"), `{"name":"`+name+`","version":"1.0.0","modes":["light","dark"]}`)
+ write(filepath.Join(base, "theme.css"), ":root {}")
+ }
+ for _, name := range []string{"litheness", "custom"} {
+ base := filepath.Join(util.WorkingDir, "appearance", "icons", name)
+ if name == "custom" {
+ base = filepath.Join(util.IconsPath, name)
+ }
+ write(filepath.Join(base, "icon.json"), `{"name":"`+name+`","version":"1.0.0"}`)
+ write(filepath.Join(base, "icon.js"), "// icon")
+ }
+ write(filepath.Join(util.WorkingDir, "appearance", "emojis", "conf.json"), "[]")
+ selected := conf.NewAppearance()
+ selected.ThemeLight, selected.ThemeDark, selected.Icon = "custom", "custom", "custom"
+ selected.ModeOS, selected.HideStatusBar = false, true
+ body, err := json.Marshal(selected)
+ if err != nil {
+ t.Fatal(err)
+ }
+ code, message, _ := settingContractRequest(t, "setAppearance", setAppearance, string(body))
+ if code != 0 || model.Conf.Appearance.Load().ThemeLight != "custom" || model.Conf.Appearance.Load().Icon != "custom" {
+ t.Fatalf("initial package selection failed: %d %s", code, message)
+ }
+ model.CloseWatchThemes()
+ for _, directory := range []string{util.ThemesPath, util.IconsPath} {
+ if err = os.RemoveAll(filepath.Join(directory, "custom")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ connection, push := appearanceSettingTestConnection(t)
+ var data json.RawMessage
+ if endpoint == "setAppearance" {
+ code, message, data = settingContractRequest(t, endpoint, setAppearance, string(body))
+ } else {
+ code, message, data = settingContractRequest(t, endpoint, patchSetting,
+ `{"appearance":{"themeLight":"custom","themeDark":"custom","icon":"custom"}}`)
+ }
+ if code != 0 {
+ t.Fatalf("refresh failed: %d %s", code, message)
+ }
+ assertFallback := func(value *conf.Appearance) {
+ t.Helper()
+ if value.ThemeLight != "daylight" || value.ThemeDark != "midnight" || value.Icon != "litheness" ||
+ value.ThemeVer != "1.0.0" || value.IconVer != "1.0.0" || !value.HideStatusBar {
+ t.Fatalf("refresh did not expose the final fallback snapshot: %+v", value)
+ }
+ }
+ assertFallback(model.Conf.Appearance.Load())
+ if endpoint == "setAppearance" {
+ var response conf.Appearance
+ if err = json.Unmarshal(data, &response); err != nil {
+ t.Fatal(err)
+ }
+ assertFallback(&response)
+ } else if string(data) != "null" {
+ t.Fatalf("successful patch response changed: %s", data)
+ }
+ if err = push.Broadcast([]byte(`{"cmd":"appearance-refresh-barrier"}`)); err != nil {
+ t.Fatal(err)
+ }
+ if err = connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ notifications := 0
+ for {
+ var event struct {
+ Cmd string
+ Data json.RawMessage
+ }
+ if err = connection.ReadJSON(&event); err != nil {
+ t.Fatal(err)
+ }
+ if event.Cmd == "appearance-refresh-barrier" {
+ break
+ }
+ if event.Cmd == "setAppearance" {
+ var appearance conf.Appearance
+ if err = json.Unmarshal(event.Data, &appearance); err != nil {
+ t.Fatal(err)
+ }
+ assertFallback(&appearance)
+ notifications++
+ }
+ }
+ if notifications != 1 {
+ t.Fatalf("expected one refreshed appearance notification, got %d", notifications)
+ }
+ })
+ }
+}
+
+func appearanceSettingTestConnection(t *testing.T) (*websocket.Conn, *melody.Melody) {
+ t.Helper()
+ push := melody.New()
+ connected := make(chan *melody.Session, 1)
+ push.HandleConnect(func(session *melody.Session) {
+ util.AddPushChan(session)
+ connected <- session
+ })
+ push.HandleDisconnect(util.RemovePushChan)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = push.HandleRequest(w, r) }))
+ t.Cleanup(func() { _ = push.Close(); server.Close() })
+ connection, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+
+ "/?app=appearance-refresh-test&id=main&type=main", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case session := <-connected:
+ t.Cleanup(func() { _ = connection.Close(); util.RemovePushChan(session) })
+ case <-time.After(5 * time.Second):
+ _ = connection.Close()
+ t.Fatal("websocket registration timed out")
+ }
+ return connection, push
+}
diff --git a/kernel/model/appearance_packages_test.go b/kernel/model/appearance_packages_test.go
index 70920a1558..b0591d0161 100644
--- a/kernel/model/appearance_packages_test.go
+++ b/kernel/model/appearance_packages_test.go
@@ -178,3 +178,87 @@ func TestRefreshAppearanceConfigFallsBackAfterRemoval(t *testing.T) {
t.Fatalf("appearance fallback retained stale package state: %+v", Conf.Appearance.Load())
}
}
+
+func TestApplyAppearanceRefreshesUnchangedPackageSelection(t *testing.T) {
+ for _, change := range []string{"remove-theme", "remove-icon", "incompatible-packages", "update-versions", "remove-script"} {
+ t.Run(change, func(t *testing.T) {
+ prepareConfConsistencyTest(t)
+ setupAppearancePackagesTest(t)
+ oldWorkingDir := util.WorkingDir
+ util.WorkingDir = t.TempDir()
+ t.Cleanup(func() {
+ CloseWatchThemes()
+ util.WorkingDir = oldWorkingDir
+ })
+ writeAppearanceTestFile(t, filepath.Join(util.WorkingDir, "appearance", "emojis", "conf.json"), "[]")
+ writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "theme.js"), "script")
+ selected := cloneConfSection(Conf.Appearance.Load())
+ selected.ThemeLight, selected.ThemeDark, selected.Icon = "custom", "custom", "custom"
+ Conf.Appearance.Store(selected)
+ refreshAppearanceConfig()
+ held := Conf.Appearance.Load()
+ before, err := json.Marshal(held)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !held.ThemeJS || held.ThemeVer != "1.0.0" || held.IconVer != "1.0.0" {
+ t.Fatalf("initial packages were not loaded: %+v", held)
+ }
+ light, dark, icon, version, script := "custom", "custom", "custom", "1.0.0", true
+ switch change {
+ case "remove-theme":
+ err = os.RemoveAll(filepath.Join(util.ThemesPath, "custom"))
+ light, dark, script = "daylight", "midnight", false
+ case "remove-icon":
+ err = os.RemoveAll(filepath.Join(util.IconsPath, "custom"))
+ icon = "litheness"
+ case "incompatible-packages":
+ writeAppearanceTestPackage(t, "themes", "custom", "2.0.0", "999.0.0")
+ writeAppearanceTestPackage(t, "icons", "custom", "2.0.0", "999.0.0")
+ light, dark, icon, script = "daylight", "midnight", "litheness", false
+ case "update-versions":
+ writeAppearanceTestPackage(t, "themes", "custom", "2.0.0", "")
+ writeAppearanceTestPackage(t, "icons", "custom", "2.0.0", "")
+ version = "2.0.0"
+ case "remove-script":
+ err = os.Remove(filepath.Join(util.ThemesPath, "custom", "theme.js"))
+ script = false
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ // 包文件变化不改变设置请求,提交仍应刷新资源及可用包列表。
+ if _, err = ApplyAppearanceSetting(held); err != nil {
+ t.Fatal(err)
+ }
+ actual := Conf.Appearance.Load()
+ if actual.ThemeLight != light || actual.ThemeDark != dark || actual.Icon != icon ||
+ actual.ThemeVer != version || actual.IconVer != version || actual.ThemeJS != script {
+ t.Fatalf("unchanged selection retained stale package state: %+v", actual)
+ }
+ if containTheme("custom", actual.LightThemes) != (light == "custom") ||
+ containTheme("custom", actual.DarkThemes) != (dark == "custom") ||
+ containIcon("custom", actual.Icons) != (icon == "custom") {
+ t.Fatal("package availability was not refreshed")
+ }
+ after, err := json.Marshal(held)
+ if err != nil || string(before) != string(after) {
+ t.Fatal("resource refresh mutated the submitted snapshot")
+ }
+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var saved struct {
+ Appearance conf.Appearance `json:"appearance"`
+ }
+ if err = json.Unmarshal(data, &saved); err != nil {
+ t.Fatal(err)
+ }
+ if saved.Appearance.ThemeLight != light || saved.Appearance.ThemeDark != dark || saved.Appearance.Icon != icon ||
+ saved.Appearance.ThemeVer != version || saved.Appearance.IconVer != version || saved.Appearance.ThemeJS != script {
+ t.Fatalf("refreshed selection was not persisted: %+v", saved.Appearance)
+ }
+ })
+ }
+}
diff --git a/kernel/model/conf_specs.go b/kernel/model/conf_specs.go
index 657d2d122d..219a5cc988 100644
--- a/kernel/model/conf_specs.go
+++ b/kernel/model/conf_specs.go
@@ -11,7 +11,7 @@ import (
func confSectionSpecs() map[string]registeredSection {
return map[string]registeredSection{
- "appearance": appearanceSectionSpec(),
+ "appearance": appearanceSectionSpec(false),
"fileTree": newSectionSpec("fileTree", &Conf.FileTree, conf.NormalizeFileTree, fileTreeReactions()...),
"tag": newSectionSpec("tag", &Conf.Tag, conf.NormalizeTag),
"editor": newSectionSpec("editor", &Conf.Editor, conf.NormalizeEditor, editorReactions()...),
@@ -68,11 +68,16 @@ func bazaarReactions() []Reaction[*conf.Bazaar] {
}}}
}
-func appearanceSectionSpec() *SectionSpec[*conf.Appearance] {
+// ApplyAppearanceSetting 在同一段写锁内提交设置并刷新磁盘资源,内部偏好更新仍按资源字段变化触发反应。
+func ApplyAppearanceSetting(value *conf.Appearance) ([]Issue, error) {
+ return Apply(appearanceSectionSpec(true), value)
+}
+
+func appearanceSectionSpec(refreshResources bool) *SectionSpec[*conf.Appearance] {
spec := newSectionSpec("appearance", &Conf.Appearance, func(value *conf.Appearance) *conf.Appearance {
return conf.NormalizeAppearance(value, util.IsMobileContainer())
}, Reaction[*conf.Appearance]{Name: "appearance-resources", Changed: func(old, next *conf.Appearance) bool {
- return old.Lang != next.Lang || old.Icon != next.Icon || old.ThemeLight != next.ThemeLight ||
+ return refreshResources || old.Lang != next.Lang || old.Icon != next.Icon || old.ThemeLight != next.ThemeLight ||
old.ThemeDark != next.ThemeDark || old.Mode != next.Mode || old.ModeOS != next.ModeOS
}, Apply: func(old, next *conf.Appearance) {
InitAppearance()
diff --git a/kernel/model/file_corrupted_windows_test.go b/kernel/model/file_corrupted_windows_test.go
index 12806438d3..41cf04a0fd 100644
--- a/kernel/model/file_corrupted_windows_test.go
+++ b/kernel/model/file_corrupted_windows_test.go
@@ -1,9 +1,9 @@
package model
import (
+ "bytes"
"os"
"path/filepath"
- "syscall"
"testing"
"github.com/88250/lute/ast"
@@ -11,7 +11,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-func TestDocIALSharingViolationRecovers(t *testing.T) {
+func TestDocIALLockedReadRecovers(t *testing.T) {
fixture := setupFileOperationTest(t)
originalWorkspace := util.WorkspaceDir
util.WorkspaceDir = t.TempDir()
@@ -25,36 +25,24 @@ func TestDocIALSharingViolationRecovers(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(func() { cache.RemoveDocIALInBox(document, fixture.box.ID) })
- ptr, err := syscall.UTF16PtrFromString(filePath)
- if err != nil {
- t.Fatal(err)
- }
- handle, err := syscall.CreateFile(ptr, syscall.GENERIC_READ, syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
- nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0)
- if err != nil {
- t.Fatal(err)
- }
- closed := false
- defer func() {
- if !closed {
- syscall.CloseHandle(handle)
- }
- }()
- requireReadSharingViolation(t, filePath, handle)
+ release := lockFirstByteForTest(t, filePath)
if attrs := cache.GetDocIALInBox(document, fixture.box.ID); attrs != nil {
- t.Fatalf("sharing-violation fixture unexpectedly has cached attributes: %v", attrs)
+ t.Fatalf("read-lock fixture unexpectedly has cached attributes: %v", attrs)
}
if attrs := fixture.box.docIAL(document); attrs != nil {
t.Fatalf("unreadable file returned attributes: %v", attrs)
}
- if _, err = os.Stat(filepath.Join(util.WorkspaceDir, "corrupted")); !os.IsNotExist(err) {
- t.Fatalf("sharing violation created a backup: %v", err)
+ if attrs := cache.GetDocIALInBox(document, fixture.box.ID); attrs != nil {
+ t.Fatalf("failed read populated document attributes: %v", attrs)
}
- if err = syscall.CloseHandle(handle); err != nil {
- t.Fatal(err)
+ if _, err := os.Stat(filepath.Join(util.WorkspaceDir, "corrupted")); !os.IsNotExist(err) {
+ t.Fatalf("locked read created a backup: %v", err)
+ }
+ release()
+ if data, err := os.ReadFile(filePath); err != nil || !bytes.Equal(data, raw) {
+ t.Fatalf("locked read changed document data: %q, %v", data, err)
}
- closed = true
if attrs := fixture.box.docIAL(document); attrs["title"] != "Source" {
- t.Fatalf("document did not recover after sharing violation: %v", attrs)
+ t.Fatalf("document did not recover after the read lock ended: %v", attrs)
}
}
diff --git a/kernel/model/file_sharing_windows_test.go b/kernel/model/file_sharing_windows_test.go
index a628bdf6f0..05eae99662 100644
--- a/kernel/model/file_sharing_windows_test.go
+++ b/kernel/model/file_sharing_windows_test.go
@@ -3,41 +3,96 @@ package model
import (
"errors"
"os"
+ "path/filepath"
"runtime"
- "syscall"
"testing"
"golang.org/x/sys/windows"
)
-func requireReadSharingViolation(t *testing.T, path string, held syscall.Handle) {
+func lockFirstByteForTest(t *testing.T, path string) func() {
t.Helper()
- _, beforeStatErr := os.ReadFile(path)
- if _, err := os.Stat(path); err != nil {
+ info, err := os.Stat(path)
+ if err != nil {
t.Fatal(err)
}
- _, afterStatErr := os.ReadFile(path)
- if errors.Is(beforeStatErr, windows.ERROR_SHARING_VIOLATION) && errors.Is(afterStatErr, windows.ERROR_SHARING_VIOLATION) {
- return
+ if !info.Mode().IsRegular() || info.Size() == 0 {
+ t.Fatalf("read-lock fixture must be a nonempty regular file: %q", path)
}
-
- // 前置条件不成立时对比原生打开结果与文件身份,区分句柄、路径和读取实现问题。
- var heldInfo, probeInfo windows.ByHandleFileInformation
- heldInfoErr := windows.GetFileInformationByHandle(windows.Handle(held), &heldInfo)
ptr, err := windows.UTF16PtrFromString(path)
if err != nil {
t.Fatal(err)
}
- probe, openErr := windows.CreateFile(ptr, windows.GENERIC_READ,
+ handle, err := windows.CreateFile(ptr, windows.GENERIC_READ,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
- var probeInfoErr error
- if openErr == nil {
- defer windows.CloseHandle(probe)
- probeInfoErr = windows.GetFileInformationByHandle(probe, &probeInfo)
- }
- t.Fatalf("read-denying fixture failed: path=%q, go=%s, read before Stat=%v, read after Stat=%v, native open=%v, held identity=%x:%x:%x (error=%v), probe identity=%x:%x:%x (error=%v)",
- path, runtime.Version(), beforeStatErr, afterStatErr, openErr,
- heldInfo.VolumeSerialNumber, heldInfo.FileIndexHigh, heldInfo.FileIndexLow, heldInfoErr,
- probeInfo.VolumeSerialNumber, probeInfo.FileIndexHigh, probeInfo.FileIndexLow, probeInfoErr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var overlapped windows.Overlapped
+ locked := false
+ release := func() {
+ t.Helper()
+ if handle == windows.InvalidHandle {
+ return
+ }
+ var unlockErr error
+ if locked {
+ unlockErr = windows.UnlockFileEx(handle, 0, 1, 0, &overlapped)
+ }
+ closeErr := windows.CloseHandle(handle)
+ handle = windows.InvalidHandle
+ if err := errors.Join(unlockErr, closeErr); err != nil {
+ t.Fatalf("release read-lock fixture %q: %v", path, err)
+ }
+ }
+ t.Cleanup(release)
+ // 独占首字节阻止其他句柄的实际读取,不依赖打开句柄时的共享检查。
+ if err = windows.LockFileEx(handle, windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overlapped); err != nil {
+ t.Fatal(err)
+ }
+ locked = true
+ _, beforeStatErr := os.ReadFile(path)
+ if _, err = os.Stat(path); err != nil {
+ t.Fatal(err)
+ }
+ _, afterStatErr := os.ReadFile(path)
+ if !errors.Is(beforeStatErr, windows.ERROR_LOCK_VIOLATION) || !errors.Is(afterStatErr, windows.ERROR_LOCK_VIOLATION) {
+ t.Fatalf("byte-range read lock failed: path=%q, go=%s, read before Stat=%v, read after Stat=%v", path, runtime.Version(), beforeStatErr, afterStatErr)
+ }
+ return release
+}
+
+func TestReadLockFixtureRangeAndCleanup(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ explicit bool
+ }{{name: "cleanup"}, {name: "explicit release", explicit: true}} {
+ path := filepath.Join(t.TempDir(), "locked.txt")
+ if err := os.WriteFile(path, []byte("ab"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ t.Run(test.name, func(t *testing.T) {
+ release := lockFirstByteForTest(t, path)
+ file, err := os.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer file.Close()
+ var data [1]byte
+ if n, readErr := file.ReadAt(data[:], 1); readErr != nil || n != 1 || data[0] != 'b' {
+ t.Fatalf("unlocked byte could not be read: n=%d, data=%q, error=%v", n, data, readErr)
+ }
+ if _, readErr := file.ReadAt(data[:], 0); !errors.Is(readErr, windows.ERROR_LOCK_VIOLATION) {
+ t.Fatalf("first byte was not exclusively locked: %v", readErr)
+ }
+ if test.explicit {
+ release()
+ release()
+ }
+ })
+ if data, err := os.ReadFile(path); err != nil || string(data) != "ab" {
+ t.Fatalf("fixture cleanup did not restore unchanged readable data: %q, %v", data, err)
+ }
+ }
}
diff --git a/kernel/model/sync_ignore_windows_test.go b/kernel/model/sync_ignore_windows_test.go
index f8c59b0451..89050b0d77 100644
--- a/kernel/model/sync_ignore_windows_test.go
+++ b/kernel/model/sync_ignore_windows_test.go
@@ -3,7 +3,6 @@ package model
import (
"os"
"path/filepath"
- "syscall"
"testing"
"github.com/siyuan-note/siyuan/kernel/util"
@@ -20,34 +19,19 @@ func TestSyncIgnoreReadFailureRecovers(t *testing.T) {
}
invalidateSyncIgnoreRules(p)
t.Cleanup(func() { invalidateSyncIgnoreRules(p) })
- ptr, err := syscall.UTF16PtrFromString(p)
- if err != nil {
- t.Fatal(err)
- }
- h, err := syscall.CreateFile(ptr, syscall.GENERIC_READ, syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE,
- nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0)
- if err != nil {
- t.Fatal(err)
- }
- closed := false
- defer func() {
- if !closed {
- syscall.CloseHandle(h)
- }
- }()
- requireReadSharingViolation(t, p, h)
+ release := lockFirstByteForTest(t, p)
if _, matcher, loadErr := getSyncIgnoreRules(); loadErr == nil || matcher != nil {
t.Fatalf("unreadable rules must return an error without a matcher: error=%v, matcher=%v", loadErr, matcher)
}
if !PathsAffectSync(filepath.Join(util.DataDir, "private", "secret.txt")) {
t.Fatal("read failure must conservatively schedule sync")
}
- if err = syscall.CloseHandle(h); err != nil {
- t.Fatal(err)
+ release()
+ if data, err := os.ReadFile(p); err != nil || string(data) != "/private/**/*" {
+ t.Fatalf("locked read changed ignore rules: %q, %v", data, err)
}
- closed = true
_, matcher := mustSyncIgnoreRules(t)
if !matcher.MatchesPath("/private/secret.txt") {
- t.Fatal("rules did not recover after the sharing violation ended")
+ t.Fatal("rules did not recover after the read lock ended")
}
}