Skip to content

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

:bug: Preserve settings window context and AI updates https://github.com/siyuan-note/siyuan/issues/20002

Daniele6fb0b3d988f
diff --git a/app/src/assets/scss/component/_dialog.scss b/app/src/assets/scss/component/_dialog.scss
index 51a770957d..612383d1c4 100644
--- a/app/src/assets/scss/component/_dialog.scss
+++ b/app/src/assets/scss/component/_dialog.scss
@@ -24,6 +24,7 @@
#windowControls {
margin-left: auto;
+ -webkit-app-region: no-drag;
}
}
diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.ts
index b34407d474..e069a85b32 100644
--- a/app/src/config/bazaar.ts
+++ b/app/src/config/bazaar.ts
@@ -826,7 +826,9 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}
const showDisable = ["icons", "themes"].includes(bazaarType) && bazaarItem.current;
const plugin = bazaarType === "plugins" ?
app.plugins.find((item: Plugin) => item.name === bazaarItem.name) : undefined;
- const hasSetting = plugin ? hasPluginSetting(plugin) : false;
+ const host = getSettingsWindowHost();
+ const hasSetting = bazaarType === "plugins" &&
+ (host ? host.hasPluginSetting(bazaarItem.name) : Boolean(plugin && hasPluginSetting(plugin)));
const showPublishSwitch = bazaarType === "plugins" && window.siyuan.config.publish.enable;
const publishEnabled = isBazaarPluginEnabledInPublish(bazaarItem);
const publishSwitchHTML = showPublishSwitch ? `<span class="config-bazaar__publish-controls"><label data-type="plugin-publish-enable-label" class="config-bazaar__publish-switch ariaLabel" data-position="north" aria-label="${escapeAttr(bazaarItem.disabledInPublish ? window.siyuan.languages.pluginDisabledInPublishTip : window.siyuan.languages.publishService)}">
diff --git a/app/src/config/setting/nativeWindow.ts b/app/src/config/setting/nativeWindow.ts
index 8548e83c50..c8fa5b8633 100644
--- a/app/src/config/setting/nativeWindow.ts
+++ b/app/src/config/setting/nativeWindow.ts
@@ -9,6 +9,7 @@ import {subscribeGlobalPluginState, applyPluginReload} from "../../plugin/global
import {loadPlugin, unloadPlugin} from "../../plugin/loader";
import {sendGlobalShortcut, sendUnregisterGlobalShortcut} from "../../boot/globalEvent/globalShortcut";
import {Constants} from "../../constants";
+import {hasPluginSetting} from "../../plugin";
import type {App} from "../../index";
import type {ISettingsWindowHost} from "./windowContext";
import type {TSettingTab} from "./tabs";
@@ -72,9 +73,13 @@ export const openNativeSettings = async (app: App, command: ISettingsCommand = {
applyPluginReload: async data => { await applyPluginReload(app, data); },
loadPlugin: async data => { await loadPlugin(app, data); },
unloadPlugin: async name => { await unloadPlugin(app, name); },
+ hasPluginSetting: name => {
+ const item = app.plugins.find(item => item.name === name);
+ return Boolean(item && hasPluginSetting(item));
+ },
openPluginSetting: async name => {
const item = app.plugins.find(item => item.name === name);
- if (!item) return;
+ if (!item || !hasPluginSetting(item)) return;
const sequence = openSequence;
await item.openSetting();
// 插件沿用原窗口对话框时显示其所属窗口,原生设置窗口自行接管焦点。
diff --git a/app/src/config/setting/sync.test.ts b/app/src/config/setting/sync.test.ts
index 63cb42c821..721cb71ff9 100644
--- a/app/src/config/setting/sync.test.ts
+++ b/app/src/config/setting/sync.test.ts
@@ -2,7 +2,8 @@ import * as assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
-import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {createSourceFile, isClassDeclaration, isMethodDeclaration, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {getAgentDefaultModelID, getUsableAgentModels} from "../../layout/dock/agent/agentModel";
test("settings notifications update runtime configuration and refresh the registered tab", async () => {
const compiled = transpileModule(readFileSync("src/config/setting/sync.ts", "utf8"), {
@@ -23,3 +24,72 @@ test("settings notifications update runtime configuration and refresh the regist
assert.equal(config.editor.fontSize, 18);
assert.deepEqual(remounted, ["editor"]);
});
+
+for (const mobile of [false, true]) {
+ test(`AI settings received from another window notify the agent model picker (mobile=${mobile})`, async () => {
+ const {parse} = require("ifdef-loader/preprocessor");
+ const compile = (file: string) => transpileModule(parse(readFileSync(file, "utf8"),
+ {MOBILE: mobile, BROWSER: mobile}, false, true), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const ai = (model: string) => ({
+ providers: [{id: "provider", name: "Provider", enabled: true,
+ models: [{id: model, name: model, enabled: true}]}],
+ });
+ type AIConfig = ReturnType<typeof ai>;
+ const config = {ai: ai("old-model"), editor: {}, appearance: {}, keymap: {}};
+ let next = ai("new-model");
+ let changed = 0;
+ let models: string[] = [];
+ const agentSource = createSourceFile("AgentChat.ts", readFileSync("src/layout/dock/agent/AgentChat.ts", "utf8"),
+ ScriptTarget.ES2021, true);
+ const agentClass = agentSource.statements.find(statement => isClassDeclaration(statement) && statement.name.text === "AgentChat");
+ assert.ok(isClassDeclaration(agentClass));
+ const checkConfig = agentClass.members.find(member => isMethodDeclaration(member) && member.name.getText(agentSource) === "checkConfigChanged");
+ const agentExports = {} as {Observer: {prototype: {checkConfigChanged: () => void}}};
+ const agent = {
+ modelOptions: getUsableAgentModels(config.ai), defaultModelID: "", entries: [{}],
+ checkStreamingMarkdownChanged() {},
+ refreshModelOptions() {
+ const options = getUsableAgentModels(config.ai);
+ this.modelOptions = options;
+ this.defaultModelID = getAgentDefaultModelID(config.ai, options);
+ models = options.map(item => item.id);
+ },
+ };
+ const windowContext = {siyuan: {config}, dispatchEvent: (event: {type: string}) => {
+ assert.equal(event.type, "siyuan-ai-config-changed");
+ changed++;
+ agentExports.Observer.prototype.checkConfigChanged.call(agent);
+ }};
+ runInNewContext(transpileModule(`export class Observer {${checkConfig.getText(agentSource)}}`, {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports: agentExports, window: windowContext, getUsableAgentModels, getAgentDefaultModelID});
+ const aiExports = {} as {aiConfigApi: {apply: (value: AIConfig) => void}};
+ runInNewContext(compile("src/config/tabs/ai/aiRuntime.ts"), {
+ exports: aiExports, window: windowContext, CustomEvent: class {constructor(public type: string) {}},
+ require: () => ({createConfigNamespaceApi: (options: {setConfig: (value: AIConfig) => void}) => ({apply: options.setConfig})}),
+ });
+ const dependencies = {
+ fetchSyncPost: async () => ({code: 0, data: {conf: JSON.parse(JSON.stringify({...config, ai: next}))}}),
+ systemConfig: (value: unknown) => value,
+ objEquals: (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right),
+ ...aiExports, syncSettingTasks() {}, remountOpenSettingTab: async () => {}, getSettingTabDefs: () => [{id: "ai"}],
+ };
+ const exports = {} as {refreshSettingConfig: (namespace?: string) => Promise<void>};
+ runInNewContext(compile("src/config/setting/sync.ts"), {exports, require: () => dependencies, window: windowContext, console});
+ await exports.refreshSettingConfig("ai");
+ assert.equal(changed, 1);
+ assert.ok(models.some(model => model.includes("new-model")));
+ assert.ok(!models.some(model => model.includes("old-model")));
+ await exports.refreshSettingConfig("ai");
+ assert.equal(changed, 1);
+ next = ai("third-model");
+ await exports.refreshSettingConfig();
+ assert.equal(changed, 2);
+ assert.ok(models.some(model => model.includes("third-model")));
+ next.providers[0].enabled = false;
+ await exports.refreshSettingConfig("ai");
+ assert.deepEqual(models, []);
+ });
+}
diff --git a/app/src/config/setting/sync.ts b/app/src/config/setting/sync.ts
index 06f6b52042..44976efd5d 100644
--- a/app/src/config/setting/sync.ts
+++ b/app/src/config/setting/sync.ts
@@ -2,6 +2,7 @@ import {fetchSyncPost} from "../../util/fetch";
import {systemConfig} from "../systemConfig";
import {editorConfigApi} from "../tabs/editorRuntime";
import {appearanceConfigApi} from "../tabs/appearanceRuntime";
+import {aiConfigApi} from "../tabs/ai/aiRuntime";
import {objEquals} from "../../util/functions";
import {syncSettingTasks} from "./taskBlocker";
/// #if !MOBILE
@@ -36,6 +37,9 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {
if (includes("appearance") && !objEquals(window.siyuan.config.appearance, next.appearance)) {
appearanceConfigApi.apply(next.appearance);
}
+ if (includes("ai") && !objEquals(window.siyuan.config.ai, next.ai)) {
+ aiConfigApi.apply(next.ai);
+ }
/// #if !MOBILE
if (includes("keymap") && !objEquals(window.siyuan.config.keymap, next.keymap)) {
applyKeymap(next.keymap);
@@ -45,7 +49,7 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {
window.siyuan.config.keymap = next.keymap;
}
/// #endif
- const simple = ["ai", "export", "fileTree", "search", "flashcard", "secrets", "variables", "sync", "repo", "system", "bazaar", "publish"] as const;
+ const simple = ["export", "fileTree", "search", "flashcard", "secrets", "variables", "sync", "repo", "system", "bazaar", "publish"] as const;
for (const key of simple) {
if (includes(key)) {
Object.assign(window.siyuan.config, {[key]: next[key]});
@@ -53,7 +57,7 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {
}
/// #if !MOBILE
const tabs: Record<string, TSettingTab> = {fileTree: "file", secrets: "secretsVariables", variables: "secretsVariables", system: "app", publish: "access"};
- for (const namespace of namespaces.has("*") ? [...simple, "editor", "keymap", "appearance"] : namespaces) {
+ for (const namespace of namespaces.has("*") ? [...simple, "editor", "keymap", "appearance", "ai"] : namespaces) {
const tab = getSettingTabDefs().find(definition => definition.id === (tabs[namespace] || namespace));
if (tab) void remountOpenSettingTab(tab.id);
}
diff --git a/app/src/config/setting/windowContext.ts b/app/src/config/setting/windowContext.ts
index 22ecd591a0..0f5c242f5c 100644
--- a/app/src/config/setting/windowContext.ts
+++ b/app/src/config/setting/windowContext.ts
@@ -12,6 +12,7 @@ export interface ISettingsWindowHost {
loadPlugin: (data: IPluginData) => Promise<void>;
unloadPlugin: (name: string) => Promise<void>;
openPluginSetting: (name: string) => Promise<void>;
+ hasPluginSetting: (name: string) => boolean;
suspendShortcuts: () => void;
restoreShortcuts: () => void;
plugin?: {
diff --git a/app/src/util/frontend.test.ts b/app/src/util/frontend.test.ts
new file mode 100644
index 0000000000..dce530a206
--- /dev/null
+++ b/app/src/util/frontend.test.ts
@@ -0,0 +1,35 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+
+const {parse} = require("ifdef-loader/preprocessor");
+
+const getFrontend = (mobile: boolean, native: boolean, toolbar: boolean, settings: boolean) => {
+ const source = createSourceFile("functions.ts", parse(readFileSync("src/util/functions.ts", "utf8"),
+ {MOBILE: mobile, BROWSER: !native}, false, true), ScriptTarget.ES2021, true);
+ const declarations = source.statements.filter(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => ["getFrontend", "isWindow"].includes(item.name.getText(source))));
+ const exports = {} as {getFrontend: () => string};
+ runInNewContext(transpileModule(declarations.map(item => item.getText(source)).join("\n"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {
+ exports, window: {navigator: {userAgent: native ? "SiYuan/3.8.7 Electron" : "Mozilla/5.0"}},
+ document: {getElementById: () => toolbar ? {} : null, body: {classList: {contains: () => settings}}},
+ });
+ return exports.getFrontend();
+};
+
+test("native settings use desktop package compatibility rather than document-window compatibility", () => {
+ assert.equal(getFrontend(false, true, false, true), "desktop");
+});
+
+test("main windows, detached documents, browsers and mobile retain their frontend identities", () => {
+ assert.equal(getFrontend(false, true, true, false), "desktop");
+ assert.equal(getFrontend(false, true, false, false), "desktop-window");
+ assert.equal(getFrontend(false, false, true, false), "browser-desktop");
+ assert.equal(getFrontend(false, false, false, true), "browser-desktop");
+ assert.equal(getFrontend(true, true, false, false), "mobile");
+ assert.equal(getFrontend(true, false, false, false), "browser-mobile");
+});
diff --git a/app/src/util/functions.ts b/app/src/util/functions.ts
index 5d21f24ed5..8849c766b6 100644
--- a/app/src/util/functions.ts
+++ b/app/src/util/functions.ts
@@ -30,7 +30,8 @@ export const getFrontend = () => {
}
/// #else
if (window.navigator.userAgent.startsWith("SiYuan/")) {
- if (isWindow()) {
+ // 设置窗口使用桌面主窗口的集市包兼容性,文档新窗口单独判断。
+ if (isWindow() && !document.body.classList.contains("body--settings")) {
return "desktop-window";
}
return "desktop";
diff --git a/app/tests/fixtures/windowHitTest.ps1 b/app/tests/fixtures/windowHitTest.ps1
new file mode 100644
index 0000000000..de3a8881d8
--- /dev/null
+++ b/app/tests/fixtures/windowHitTest.ps1
@@ -0,0 +1,38 @@
+param([string]$WindowHandle, [string]$Points)
+
+Add-Type -TypeDefinition @'
+using System;
+using System.Runtime.InteropServices;
+public static class SettingsHitTest {
+ [StructLayout(LayoutKind.Sequential)]
+ public struct Point { public int X; public int Y; }
+ [StructLayout(LayoutKind.Sequential)]
+ public struct Rect { public int Left; public int Top; public int Right; public int Bottom; }
+ [DllImport("user32.dll")]
+ public static extern bool GetClientRect(IntPtr window, out Rect rect);
+ [DllImport("user32.dll")]
+ public static extern bool ClientToScreen(IntPtr window, ref Point point);
+ [DllImport("user32.dll", SetLastError = true)]
+ public static extern IntPtr SendMessageTimeout(IntPtr window, uint message, IntPtr wParam,
+ IntPtr lParam, uint flags, uint timeout, out UIntPtr result);
+ public static long HitTest(long handle, double x, double y) {
+ var window = new IntPtr(handle);
+ Rect rect;
+ if (!GetClientRect(window, out rect)) throw new Exception("GetClientRect failed");
+ var point = new Point { X = (int)Math.Round(x * (rect.Right - rect.Left)),
+ Y = (int)Math.Round(y * (rect.Bottom - rect.Top)) };
+ if (!ClientToScreen(window, ref point)) throw new Exception("ClientToScreen failed");
+ var position = new IntPtr((point.Y << 16) | (point.X & 0xffff));
+ UIntPtr result;
+ if (SendMessageTimeout(window, 0x84, IntPtr.Zero, position, 2, 3000, out result) == IntPtr.Zero)
+ throw new Exception("WM_NCHITTEST failed");
+ return (long)result.ToUInt64();
+ }
+}
+'@
+
+$results = @()
+foreach ($point in ($Points | ConvertFrom-Json)) {
+ $results += [SettingsHitTest]::HitTest([long]$WindowHandle, [double]$point.x, [double]$point.y)
+}
+ConvertTo-Json -InputObject $results -Compress
diff --git a/app/tests/settingsBazaar.test.js b/app/tests/settingsBazaar.test.js
new file mode 100644
index 0000000000..e68bad177c
--- /dev/null
+++ b/app/tests/settingsBazaar.test.js
@@ -0,0 +1,67 @@
+const assert = require("node:assert/strict");
+const {readFileSync} = require("node:fs");
+const {test} = require("node:test");
+const {runInNewContext} = require("node:vm");
+const ts = require("typescript");
+
+const source = ts.createSourceFile("bazaar.ts", readFileSync("src/config/bazaar.ts", "utf8"), ts.ScriptTarget.ES2021, true);
+const declaration = source.statements.find(statement => ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(source) === "bazaar"));
+const object = declaration.declarationList.declarations[0].initializer;
+const render = object.properties.find(property => property.name?.getText(source) === "_genMyHTML");
+const compiled = ts.transpileModule(`export const bazaar = {${render.getText(source)}};`, {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+}).outputText;
+
+for (const mode of ["settings-window", "main-window", "mobile"]) {
+ test(`installed package cards use plugin ownership for setting buttons (${mode})`, () => {
+ const packages = ["none", "configured", "custom"].map(name => ({name, preferredName: name, preferredDesc: ""}));
+ const classList = {contains: () => false, add() {}, remove() {}};
+ const activeButton = {classList, getAttribute: () => "myPlugins"};
+ const content = {innerHTML: "", getAttribute() {}, setAttribute() {}, removeAttribute() {},
+ previousElementSibling: {querySelector: selector => selector === ".b3-text-field" ? null :
+ selector === ".counter" ? {classList} : activeButton}};
+ const settingNames = [];
+ const exports = {};
+ runInNewContext(compiled, {exports,
+ BAZAAR_PACKAGE_CONFIG: {plugins: {myType: "myPlugins", api: {installed: "/installed"}},
+ themes: {myType: "myPlugins", api: {installed: "/installed"}}},
+ fetchPost: (_url, _data, callback) => {callback({data: {packages}}); return Promise.resolve();},
+ getFrontend: () => "desktop", isMobile: () => mode === "mobile", isBrowser: () => false,
+ getHostCapabilities: () => ({localFileSystem: true}),
+ getSettingsWindowHost: () => mode === "settings-window" ? {hasPluginSetting: name => {
+ settingNames.push(name);
+ return name !== "none";
+ }} : undefined,
+ hasPluginSetting: plugin => {
+ assert.notEqual(mode, "settings-window");
+ return plugin.name !== "none";
+ },
+ isBazaarPluginEnabledInPublish: () => false, getRatingKey: (_type, name) => name,
+ escapeHtml: value => value, escapeAttr: value => value, genRatePackageActionHTML: () => "",
+ loadDownloadedRatings() {}, loadDownloadedUserRatings() {},
+ window: {siyuan: {config: {publish: {enable: false}, bazaar: {petalDisabled: false}},
+ languages: {config: "Settings", uninstall: "Uninstall", disable: "Disable", enable: "Enable"}}},
+ });
+ const {bazaar} = exports;
+ Object.assign(bazaar, {
+ element: {querySelector: selector => selector === "#configBazaarDownloaded" ? content : null},
+ _data: {downloadedRatingKeys: new Set(), userRatings: new Map()},
+ _syncPluginGlobalSwitch() {}, _updateDownloadedToolbar() {}, _updateDownloadedSortSelect() {},
+ _getDownloadedSortValue: () => "", _captureMount: () => 0, _isMountCurrent: () => true,
+ _applyDownloadedDeprecations() {}, _sortDownloadedPackages: items => items, _getUpdatedItem() {},
+ _genPackageIconHTML: () => "", _genUpdateButtonHTML: () => "", _genIncompatibleChipHTML: () => "",
+ _genDeprecatedChipHTML: () => "", _genFundingHTML: () => "", _genOpenStorageHTML: () => "",
+ _loadDownloadedDeprecations() {},
+ });
+ bazaar._genMyHTML("plugins", {plugins: packages});
+ const cards = content.innerHTML.split('<div data-name="').slice(1);
+ assert.equal(cards.length, 3);
+ assert.deepEqual(cards.map(card => card.includes('data-type="setting"')), [false, true, true]);
+ assert.deepEqual(settingNames, mode === "settings-window" ? ["none", "configured", "custom"] : []);
+ settingNames.length = 0;
+ bazaar._genMyHTML("themes", {plugins: packages});
+ assert.ok(!content.innerHTML.includes('data-type="setting"'));
+ assert.deepEqual(settingNames, []);
+ });
+}
diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.js
index 2004df7ae5..d723b454a5 100644
--- a/app/tests/settingsWindow.test.js
+++ b/app/tests/settingsWindow.test.js
@@ -33,17 +33,24 @@ const rendererModules = (sources) => {
const fit = loadRendererModule(sources.fit, {
"../../boot/windowControls": controls, "../../protyle/util/compatibility": {isMac: () => process.platform === "darwin"},
});
- return {Dialog, genUUID, context, fit, controls};
+ const frontend = loadRendererModule(sources.frontend, {
+ "./hostCapabilities": {getHostCapabilities: () => ({})}, "../editor/pdfAssetLink": {},
+ });
+ return {Dialog, genUUID, context, fit, controls, frontend};
};
const bootChild = async (sources) => {
const {ipcRenderer} = require("electron");
const {waitForSettingsWindowPaint} = loadRendererModule(sources.paint, {});
- const {Dialog, genUUID, context, fit} = rendererModules(sources);
+ const {Dialog, genUUID, context, fit, frontend} = rendererModules(sources);
+ require("node:assert/strict").equal(frontend.getFrontend(), "desktop", navigator.userAgent);
const host = await new Promise(resolve => {
const token = new URLSearchParams(location.search).get("settingsWindowToken");
window.opener.dispatchEvent(new CustomEvent("siyuan-settings-host-" + token, {detail: resolve}));
});
+ class Plugin {openSetting() {}}
+ const pluginSettings = {};
+ new Function("Plugin", "exports", sources.pluginSettings)(Plugin, pluginSettings);
await waitForSettingsWindowPaint(async () => {
const theme = document.createElement("link");
theme.id = "pendingTheme";
@@ -62,7 +69,7 @@ const bootChild = async (sources) => {
canceled.remove();
if (host.plugin) {
const {Setting} = loadRendererModule(sources.setting, {
- "../util/functions": {isMobile: () => false, getFrontend: () => "desktop-window"},
+ "../util/functions": {isMobile: () => false, getFrontend: frontend.getFrontend},
"../dialog": {Dialog}, "../config/setting/nativeWindow": {},
"../config/setting/windowContext": context, "../config/setting/windowDialog": fit,
"../util/genID": {genUUID},
@@ -75,6 +82,9 @@ const bootChild = async (sources) => {
});
window.addEventListener("unload", () => host.plugin.closed());
} else {
+ const withoutSettings = host.app.plugins.find(plugin => plugin.name === "without-settings");
+ require("node:assert/strict").equal(pluginSettings.hasPluginSetting(withoutSettings), true);
+ require("node:assert/strict").equal(host.hasPluginSetting(withoutSettings.name), false);
document.body.append(document.createElement("div"));
}
});
@@ -87,6 +97,9 @@ const runCases = async (sources) => {
const assert = require("node:assert/strict");
const {ipcRenderer} = require("electron");
const {Dialog, genUUID, context, fit} = rendererModules(sources);
+ class Plugin {openSetting() {}}
+ const pluginSettings = {};
+ new Function("Plugin", "exports", sources.pluginSettings)(Plugin, pluginSettings);
const native = loadRendererModule(sources.native, {
electron: {ipcRenderer}, "../../util/genID": {genUUID}, "../../protyle/util/compatibility": {setStorageVal() {}},
"../../layout/util": {exportLayout: async options => options.cb()}, "../../dialog/processSystem": {exitSiYuan: async () => {}},
@@ -94,6 +107,7 @@ const runCases = async (sources) => {
"../../plugin/loader": {loadPlugin: async () => {}, unloadPlugin: async () => {}},
"../../boot/globalEvent/globalShortcut": {sendGlobalShortcut() {}, sendUnregisterGlobalShortcut() {}},
"../../constants": {Constants: {SIYUAN_CMD: "siyuan-cmd"}},
+ "../../plugin": pluginSettings,
});
const {Setting} = loadRendererModule(sources.setting, {
"../util/functions": {isMobile: () => false, getFrontend: () => "desktop"}, "../dialog": {Dialog},
@@ -136,6 +150,15 @@ const runCases = async (sources) => {
await ipcRenderer.invoke("test-settings-size", 493, 376);
await wait();
const childDocument = control.ownerDocument;
+ if (process.platform === "win32") {
+ const points = ["#drag", "#minWindow", "#maxWindow", "#closeWindow"].map(selector => {
+ const rect = childDocument.querySelector(selector).getBoundingClientRect();
+ return {x: (rect.left + rect.right) / 2 / childDocument.defaultView.innerWidth,
+ y: (rect.top + rect.bottom) / 2 / childDocument.defaultView.innerHeight};
+ });
+ const hits = await ipcRenderer.invoke("test-settings-hit-test", points);
+ assert.deepEqual(hits, [2, 1, 1, 1]);
+ }
for (const theme of ["daylight", "midnight"]) {
const link = childDocument.getElementById("fixtureTheme");
await new Promise(resolve => {
@@ -177,6 +200,8 @@ const runCases = async (sources) => {
await wait();
assert.equal(confirmed, 1);
assert.equal(destroyed, 2);
+ const withoutSettings = Object.assign(new Plugin(), {name: "without-settings"});
+ window.siyuan.ws.app.plugins.push(withoutSettings);
await native.openNativeSettings(window.siyuan.ws.app, {tab: "appearance"});
await ipcRenderer.invoke("test-settings-wait");
const builtinHost = await ipcRenderer.invoke("test-settings-token");
@@ -184,7 +209,17 @@ const runCases = async (sources) => {
window.dispatchEvent(new CustomEvent("siyuan-settings-host-" + builtinHost, {detail: resolve}));
});
const legacySetting = new Setting({});
+ assert.equal(host.hasPluginSetting("without-settings"), false);
+ assert.equal(host.hasPluginSetting("missing"), false);
+ const emptyCommands = (await ipcRenderer.invoke("test-settings-commands")).length;
+ await host.openPluginSetting("without-settings");
+ await wait();
+ assert.equal((await ipcRenderer.invoke("test-settings-commands")).length, emptyCommands);
+ const configured = Object.assign(new Plugin(), {name: "configured", setting: new Setting({})});
+ window.siyuan.ws.app.plugins.push(configured);
+ assert.equal(host.hasPluginSetting("configured"), true);
window.siyuan.ws.app.plugins.push({name: "legacy", openSetting: () => legacySetting.open("Legacy plugin")});
+ assert.equal(host.hasPluginSetting("legacy"), true);
await host.openPluginSetting("legacy");
assert.equal(legacySetting.dialog.element.ownerDocument, document);
await wait();
@@ -209,6 +244,7 @@ if (process.versions.electron && process.type === "browser") {
const {createServer} = require("node:http");
const {createSettingsWindows} = require("../electron/settingsWindows");
app.setPath("userData", process.argv[2]);
+ app.userAgentFallback = "SiYuan/fixture Electron";
app.whenReady().then(async () => {
let owner;
let code = 0;
@@ -226,11 +262,22 @@ if (process.versions.electron && process.type === "browser") {
fs.readFileSync(path.join(__dirname, "../appearance/themes", name, "theme.css"), "utf8")]));
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"})) {
- sources[key] = ts.transpileModule(fs.readFileSync(path.join(__dirname, "../src", file), "utf8"), {
+ paint: "config/setting/windowPaint.ts", frontend: "util/functions.ts"})) {
+ let source = fs.readFileSync(path.join(__dirname, "../src", file), "utf8");
+ if (key === "frontend") {
+ source = require("ifdef-loader/preprocessor").parse(source, {MOBILE: false, BROWSER: false}, false, true);
+ }
+ sources[key] = ts.transpileModule(source, {
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
}).outputText;
}
+ 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) &&
+ statement.declarationList.declarations.some(item => item.name.getText(pluginSource) === "hasPluginSetting"));
+ sources.pluginSettings = ts.transpileModule(pluginSetting.getText(pluginSource), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+ }).outputText;
const server = createServer((request, response) => {
const pathname = new URL(request.url, "http://localhost").pathname;
if (pathname.startsWith("/fixture/")) {
@@ -263,6 +310,12 @@ if (process.versions.electron && process.type === "browser") {
const origin = "http://127.0.0.1:" + server.address().port;
const policy = createSettingsWindows({ipcMain, screen, getTarget: id => owner?.webContents.id === id ? {origin, mode: "local"} : undefined,
initialize: win => {
+ win.webContents.on("console-message", details => {
+ if (details.level === "error" && details.message.startsWith("Uncaught")) {
+ console.error(details.message);
+ app.exit(1);
+ }
+ });
children.add(win);
assert.equal(win.getParentWindow(), null);
assert.equal(win.isModal(), false);
@@ -297,6 +350,19 @@ if (process.versions.electron && process.type === "browser") {
ipcMain.handle("test-settings-size", (_event, width, height) => {
for (const child of children) child.setSize(width, height);
});
+ if (process.platform === "win32") {
+ const {promisify} = require("node:util");
+ const {execFile} = require("node:child_process");
+ ipcMain.handle("test-settings-hit-test", async (_event, points) => {
+ const child = [...children][0];
+ const buffer = child.getNativeWindowHandle();
+ const handle = buffer.length === 8 ? buffer.readBigUInt64LE().toString() : String(buffer.readUInt32LE());
+ const {stdout} = await promisify(execFile)("powershell.exe", ["-NoProfile", "-NonInteractive",
+ "-File", path.join(__dirname, "fixtures/windowHitTest.ps1"), handle, JSON.stringify(points)],
+ {windowsHide: true, timeout: 15000});
+ return JSON.parse(stdout);
+ });
+ }
try {
owner = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
owner.webContents.setWindowOpenHandler(details => {