Skip to content

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

:sparkles: Save and restore window geometry in layouts https://github.com/siyuan-note/siyuan/issues/10809

Daniel25478c91e824
diff --git a/app/electron/main.js b/app/electron/main.js
index 0f7e330615..4e3aecfdf0 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -74,6 +74,7 @@ const {
} = require("./remoteKernel");
const {dispatchWindowMessage} = require("./windowMessaging");
const {WindowWorkspaceRegistry, flushWindowWorkspaces} = require("./windowWorkspaces");
+const {captureWindowGeometry, normalizeWindowGeometry, restoreWindowGeometry} = require("./windowGeometry");
const windowWorkspaces = new WindowWorkspaceRegistry();
const {createNotebookSystemLock, prepareNotebookSystemLock} = require("./notebookSystemLock");
const {
@@ -3123,6 +3124,14 @@ app.whenReady().then(() => {
app.exit();
});
ipcMain.handle("siyuan-get", async (event, data) => {
+ if (data.cmd === "getWindowGeometry" || data.cmd === "setWindowGeometry") {
+ const window = getWindowByContentId(event.sender.id);
+ if (!window || !getWindowKernelTarget(event.sender.id) || event.senderFrame !== event.sender.mainFrame) {
+ return false;
+ }
+ return data.cmd === "getWindowGeometry" ? captureWindowGeometry(window) :
+ restoreWindowGeometry(window, data.geometry, screen);
+ }
if (data.cmd === "getLinuxInputMethodSetting" || data.cmd === "setLinuxInputMethodSetting") {
if (process.platform !== "linux" || !initializedWindowIds.has(event.sender.id) ||
!getWindowKernelTarget(event.sender.id) || event.senderFrame !== event.sender.mainFrame) {
@@ -3782,12 +3791,14 @@ app.whenReady().then(() => {
const mainWindow = BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0];
const mainBounds = mainWindow.getBounds();
const mainScreen = screen.getDisplayNearestPoint({x: mainBounds.x, y: mainBounds.y});
+ const geometry = workspaceID ? normalizeWindowGeometry(data.windowGeometry, screen) : undefined;
const win = new BrowserWindow({
title: "SiYuan",
show: true,
trafficLightPosition: {x: 8, y: 13},
width: Math.floor(data.width || mainScreen.size.width * 0.7),
height: Math.floor(data.height || mainScreen.size.height * 0.9),
+ ...geometry,
minWidth: 493,
minHeight: 376,
fullscreenable: true,
@@ -3813,7 +3824,14 @@ app.whenReady().then(() => {
windowWorkspaces.associate(win, kernelTarget.origin, workspaceID);
}
- if (data.position) {
+ if (geometry) {
+ if (data.windowGeometry.maximized) {
+ win.maximize();
+ }
+ if (data.windowGeometry.fullscreen) {
+ win.setFullScreen(true);
+ }
+ } else if (data.position) {
win.setPosition(data.position.x, data.position.y);
} else {
win.center();
@@ -3837,7 +3855,7 @@ app.whenReady().then(() => {
event.preventDefault();
});
const targetScreen = screen.getDisplayNearestPoint(screen.getCursorScreenPoint());
- if (mainScreen.id !== targetScreen.id) {
+ if (!geometry && mainScreen.id !== targetScreen.id) {
win.setBounds(targetScreen.workArea);
}
});
diff --git a/app/electron/windowGeometry.js b/app/electron/windowGeometry.js
new file mode 100644
index 0000000000..70e853d743
--- /dev/null
+++ b/app/electron/windowGeometry.js
@@ -0,0 +1,78 @@
+const isWindowGeometry = value => value?.version === 1 &&
+ ["x", "y", "width", "height"].every(key => Number.isSafeInteger(value[key]) && Math.abs(value[key]) < 10000000) &&
+ value.width > 0 && value.height > 0 && typeof value.maximized === "boolean" && typeof value.fullscreen === "boolean";
+
+const captureWindowGeometry = window => ({
+ version: 1,
+ ...window.getNormalBounds(),
+ maximized: window.isMaximized(),
+ fullscreen: window.isFullScreen(),
+});
+
+// 标题栏仍可操作时保留跨屏边界,否则移入当前显示器工作区。
+const normalizeWindowGeometry = (value, screen) => {
+ if (!isWindowGeometry(value)) {
+ return;
+ }
+ const bounds = {x: value.x, y: value.y, width: Math.max(493, value.width), height: Math.max(376, value.height)};
+ const reachable = screen.getAllDisplays().some(({workArea}) => {
+ const visibleWidth = Math.min(bounds.x + bounds.width, workArea.x + workArea.width) - Math.max(bounds.x, workArea.x);
+ return visibleWidth >= 160 && bounds.y >= workArea.y && bounds.y + 32 <= workArea.y + workArea.height;
+ });
+ if (reachable) {
+ return bounds;
+ }
+ const {workArea} = screen.getDisplayMatching({x: value.x, y: value.y, width: value.width, height: value.height});
+ const width = Math.max(493, Math.min(value.width, workArea.width));
+ const height = Math.max(376, Math.min(value.height, workArea.height));
+ return {
+ x: Math.max(workArea.x, Math.min(value.x, workArea.x + Math.max(0, workArea.width - width))),
+ y: Math.max(workArea.y, Math.min(value.y, workArea.y + Math.max(0, workArea.height - height))),
+ width,
+ height,
+ };
+};
+
+const leaveFullScreen = window => new Promise(resolve => {
+ const finish = () => {
+ clearTimeout(timer);
+ window.removeListener("leave-full-screen", finish);
+ resolve(!window.isDestroyed() && !window.isFullScreen());
+ };
+ const timer = setTimeout(finish, 3000);
+ window.once("leave-full-screen", finish);
+ window.setFullScreen(false);
+ if (!window.isFullScreen()) {
+ finish();
+ }
+});
+
+const restoreWindowGeometry = async (window, value, screen) => {
+ const bounds = normalizeWindowGeometry(value, screen);
+ if (!bounds || window.isDestroyed()) {
+ return false;
+ }
+ // macOS 退出全屏为异步操作,完成后再设置普通窗口边界。
+ if (window.isFullScreen() && !await leaveFullScreen(window)) {
+ return false;
+ }
+ if (window.isDestroyed()) {
+ return false;
+ }
+ if (window.isMinimized()) {
+ window.restore();
+ }
+ if (window.isMaximized()) {
+ window.unmaximize();
+ }
+ window.setBounds(bounds);
+ if (value.maximized) {
+ window.maximize();
+ }
+ if (value.fullscreen) {
+ window.setFullScreen(true);
+ }
+ return true;
+};
+
+module.exports = {captureWindowGeometry, normalizeWindowGeometry, restoreWindowGeometry};
diff --git a/app/electron/windowGeometry.test.js b/app/electron/windowGeometry.test.js
new file mode 100644
index 0000000000..296fcbc03c
--- /dev/null
+++ b/app/electron/windowGeometry.test.js
@@ -0,0 +1,158 @@
+const assert = require("node:assert/strict");
+const {EventEmitter} = require("node:events");
+const {test} = require("node:test");
+const {readFileSync} = require("node:fs");
+const {runInNewContext} = require("node:vm");
+const {captureWindowGeometry, normalizeWindowGeometry, restoreWindowGeometry} = require("./windowGeometry");
+
+const state = (values = {}) => ({version: 1, x: 100, y: 80, width: 900, height: 700,
+ maximized: false, fullscreen: false, ...values});
+const display = {workArea: {x: 0, y: 0, width: 1920, height: 1040}};
+const screen = {getDisplayMatching: () => display, getAllDisplays: () => [display]};
+const fixture = (initial = state()) => {
+ const window = new EventEmitter();
+ const calls = [];
+ Object.assign(window, {
+ isDestroyed: () => false,
+ isMaximized: () => initial.maximized,
+ isFullScreen: () => initial.fullscreen,
+ isMinimized: () => false,
+ getNormalBounds: () => ({x: initial.x, y: initial.y, width: initial.width, height: initial.height}),
+ unmaximize: () => calls.push("unmaximize"),
+ maximize: () => calls.push("maximize"),
+ setBounds: bounds => calls.push(bounds),
+ setFullScreen: value => {
+ calls.push(["fullscreen", value]);
+ initial.fullscreen = value;
+ },
+ });
+ return {window, calls};
+};
+
+test("最大化窗口保存普通窗口边界和状态", () => {
+ const saved = state({maximized: true});
+ assert.deepEqual(captureWindowGeometry(fixture(saved).window), saved);
+});
+
+test("负坐标显示器上的布局保持原大小和位置", () => {
+ const saved = state({x: -1500, y: 80});
+ assert.deepEqual(normalizeWindowGeometry(saved, {
+ getDisplayMatching: () => ({workArea: {x: -1920, y: 0, width: 1920, height: 1080}}),
+ getAllDisplays: () => [{workArea: {x: -1920, y: 0, width: 1920, height: 1080}}],
+ }), {x: -1500, y: 80, width: 900, height: 700});
+});
+
+test("跨屏窗口保留原位置和超过单个显示器的宽度", () => {
+ const right = {workArea: {x: 1920, y: 0, width: 1920, height: 1040}};
+ const screens = {getAllDisplays: () => [display, right], getDisplayMatching: () => right};
+ for (const bounds of [{x: 1600, y: 100, width: 1000, height: 700}, {x: 800, y: 100, width: 2800, height: 700}]) {
+ assert.deepEqual(normalizeWindowGeometry(state(bounds), screens), bounds);
+ }
+});
+
+test("部分移出屏幕但标题栏仍可操作时保留边界", () => {
+ const bounds = {x: -100, y: 100, width: 900, height: 1100};
+ assert.deepEqual(normalizeWindowGeometry(state(bounds), screen), bounds);
+});
+
+test("仅内容可见或标题栏可见区域过小时移回工作区", () => {
+ for (const bounds of [{x: 100, y: -100, width: 900, height: 700}, {x: 1900, y: 100, width: 900, height: 700}]) {
+ const restored = normalizeWindowGeometry(state(bounds), screen);
+ assert.ok(restored.x >= 0 && restored.y >= 0);
+ assert.ok(restored.x + restored.width <= display.workArea.width);
+ assert.ok(restored.y + restored.height <= display.workArea.height);
+ }
+});
+
+test("移除显示器或缩小工作区后窗口保持可见并遵守最小尺寸", () => {
+ assert.deepEqual(normalizeWindowGeometry(state({x: 5000, y: -2000, width: 3000, height: 2000}), screen),
+ {x: 0, y: 0, width: 1920, height: 1040});
+ assert.deepEqual(normalizeWindowGeometry(state({width: 10, height: 20}), screen),
+ {x: 100, y: 80, width: 493, height: 376});
+});
+
+test("缺失、未知版本和非法窗口信息不改变窗口", async () => {
+ for (const saved of [undefined, null, {}, state({version: 2}), state({width: -1}),
+ state({x: Infinity}), state({height: 1.5}), state({maximized: "true"})]) {
+ const f = fixture();
+ assert.equal(await restoreWindowGeometry(f.window, saved, screen), false);
+ assert.deepEqual(f.calls, []);
+ }
+});
+
+test("先取消最大化并恢复边界,再按保存状态最大化", async () => {
+ const f = fixture(state({maximized: true}));
+ assert.equal(await restoreWindowGeometry(f.window, state({maximized: true}), screen), true);
+ assert.deepEqual(f.calls, ["unmaximize", {x: 100, y: 80, width: 900, height: 700}, "maximize"]);
+});
+
+test("异步退出全屏后才恢复边界和全屏状态", async () => {
+ const f = fixture(state({fullscreen: true}));
+ let fullscreen = true;
+ f.window.isFullScreen = () => fullscreen;
+ f.window.setFullScreen = value => f.calls.push(["fullscreen", value]);
+ const restored = restoreWindowGeometry(f.window, state({fullscreen: true}), screen);
+ assert.deepEqual(f.calls, [["fullscreen", false]]);
+ fullscreen = false;
+ f.window.emit("leave-full-screen");
+ assert.equal(await restored, true);
+ assert.deepEqual(f.calls, [["fullscreen", false], {x: 100, y: 80, width: 900, height: 700}, ["fullscreen", true]]);
+ assert.equal(f.window.listenerCount("leave-full-screen"), 0);
+});
+
+const openWindow = windowGeometry => {
+ const source = readFileSync("electron/main.js", "utf8");
+ const start = source.indexOf('ipcMain.on("siyuan-open-window",');
+ const end = source.indexOf('ipcMain.on("siyuan-open-workspace",', start);
+ const calls = [];
+ let options;
+ let open;
+ class Window extends EventEmitter {
+ static getFocusedWindow() {
+ return {getBounds: () => ({x: 0, y: 0})};
+ }
+ constructor(value) {
+ super();
+ options = value;
+ this.webContents = {session: {setSpellCheckerLanguages: () => {}}};
+ }
+ center() { calls.push("center"); }
+ setPosition(x, y) { calls.push({x, y}); }
+ setBounds(bounds) { calls.push(bounds); }
+ maximize() { calls.push("maximize"); }
+ setFullScreen() { calls.push("fullscreen"); }
+ setAlwaysOnTop() {}
+ loadURL() {}
+ }
+ const workArea = {x: 1920, y: 0, width: 1280, height: 1000};
+ runInNewContext(source.slice(start, end), {
+ ipcMain: {on: (_name, callback) => open = callback},
+ BrowserWindow: Window, URL, process: {platform: "win32"},
+ getWindowKernelTarget: () => ({origin: "http://127.0.0.1:6806", mode: "local"}),
+ windowWorkspaces: {get: () => undefined, associate: () => {}},
+ screen: {
+ ...screen,
+ getDisplayNearestPoint: point => point.x === 2000 ? {id: 2, workArea} : {id: 1, size: {width: 1920, height: 1080}},
+ getCursorScreenPoint: () => ({x: 2000, y: 20}),
+ },
+ normalizeWindowGeometry, path: {join: () => "icon"}, appDir: "", appVer: "test",
+ remote: {enable: () => {}}, bindSpellcheckContextMenu: () => {}, rememberWindowKernelTarget: () => {},
+ windowNavigate: () => {},
+ });
+ open({sender: {id: 1}}, {
+ url: "http://127.0.0.1:6806/stage/build/app/window.html?windowWorkspace=20260924100000-abcdefg",
+ windowGeometry,
+ });
+ return {options, calls, workArea};
+};
+
+test("新窗口创建时使用保存边界,不被鼠标所在显示器覆盖", () => {
+ const f = openWindow(state({maximized: true}));
+ assert.deepEqual([f.options.x, f.options.y, f.options.width, f.options.height], [100, 80, 900, 700]);
+ assert.deepEqual(f.calls, ["maximize"]);
+});
+
+test("旧窗口布局继续使用默认窗口位置", () => {
+ const f = openWindow(undefined);
+ assert.deepEqual(f.calls, ["center", f.workArea]);
+});
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100906-0u4zfq3.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100906-0u4zfq3.sy
index a6c2be9e44..086e9141bf 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100906-0u4zfq3.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100906-0u4zfq3.sy
@@ -804,7 +804,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "A new window layout saves the tabs, splits, and reading positions of a named window. Main window layouts and new window layouts are grouped in the same layout menu and saved separately. Select up to one main window layout and multiple new window layouts, then click Open above the list to open them together. This selection is not saved. This feature is available in the desktop client; tabs from encrypted notebooks are excluded."
+ "Data": "A new window layout saves the tabs, splits, and reading positions of a named window. Main window layouts and new window layouts are grouped in the same layout menu and saved separately. Saving or updating a main window layout also records its size, position, and maximized or fullscreen state. Named new windows save this information automatically. Opening a layout restores these window settings; if the display configuration has changed, the window is adjusted to an available display. Older layouts without window settings remain usable. Window positioning and resizing depend on the operating system and may be restricted on Wayland. Select up to one main window layout and multiple new window layouts, then click Open above the list to open them together. This selection is not saved. This feature is available in the desktop client; tabs from encrypted notebooks are excluded."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200822191536-rm6hwid.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200822191536-rm6hwid.sy
index 7dece20774..8c50c77c43 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200822191536-rm6hwid.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200822191536-rm6hwid.sy
@@ -808,7 +808,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "新窗口布局用于保存一个已命名窗口的页签、分屏和阅读位置。主窗口布局和新窗口布局在同一个布局菜单内分组显示,分别保存。最多勾选一个主窗口布局,并可勾选多个新窗口布局,然后点击列表上方的打开按钮即可一起打开;本次勾选不会保存。此功能适用于桌面客户端;加密笔记本的页签不会写入布局配置。"
+ "Data": "新窗口布局用于保存一个已命名窗口的页签、分屏和阅读位置。主窗口布局和新窗口布局在同一个布局菜单内分组显示,分别保存。保存或更新主窗口布局时,也会记录窗口大小、位置以及最大化或全屏状态;已命名的新窗口会自动保存这些信息。打开布局时会恢复相应窗口状态,显示器配置变化后会调整到可用显示器内。没有窗口信息的旧布局仍可正常使用。窗口位置和大小的恢复受操作系统限制,Wayland 环境可能不支持。最多勾选一个主窗口布局,并可勾选多个新窗口布局,然后点击列表上方的打开按钮即可一起打开;本次勾选不会保存。此功能适用于桌面客户端;加密笔记本的页签不会写入布局配置。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123216-tlxw66f.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123216-tlxw66f.sy
index 88690fd93f..10fcc18a51 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123216-tlxw66f.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123216-tlxw66f.sy
@@ -808,7 +808,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "新視窗版面配置用於儲存已命名視窗的分頁、分割畫面和閱讀位置。主視窗版面配置和新視窗版面配置在同一個版面配置選單內分組顯示,分別儲存。最多勾選一個主視窗版面配置,並可勾選多個新視窗版面配置,再點擊清單上方的開啟按鈕一起開啟;本次勾選不會儲存。此功能適用於桌面用戶端;加密筆記本的分頁不會寫入版面配置。"
+ "Data": "新視窗版面配置用於儲存已命名視窗的分頁、分割畫面和閱讀位置。主視窗版面配置和新視窗版面配置在同一個版面配置選單內分組顯示,分別儲存。儲存或更新主視窗版面配置時,也會記錄視窗大小、位置,以及最大化或全螢幕狀態;已命名的新視窗會自動儲存這些資訊。開啟版面配置時會還原相應的視窗狀態,顯示器配置改變後會調整至可用顯示器內。沒有視窗資訊的舊版面配置仍可正常使用。視窗位置和大小的還原受作業系統限制,Wayland 環境可能不支援。最多勾選一個主視窗版面配置,並可勾選多個新視窗版面配置,再點擊清單上方的開啟按鈕一起開啟;本次勾選不會儲存。此功能適用於桌面用戶端;加密筆記本的分頁不會寫入版面配置。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-7yv4y5z.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-7yv4y5z.sy
index 66dada66f3..8d76373aef 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-7yv4y5z.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-7yv4y5z.sy
@@ -813,7 +813,7 @@
"Children": [
{
"Type": "NodeText",
- "Data": "新しいウィンドウのレイアウトには、名前を付けたウィンドウのタブ、画面分割、閲覧位置が保存されます。メインウィンドウのレイアウトと新しいウィンドウのレイアウトは同じレイアウトメニュー内でグループ分けされ、別々に保存されます。メインウィンドウのレイアウトは最大1件、新しいウィンドウのレイアウトは複数選択でき、一覧の上にある開くボタンでまとめて開けます。この選択内容は保存されません。この機能はデスクトップクライアントで利用できます。暗号化されたノートブックのタブは保存されません。"
+ "Data": "新しいウィンドウのレイアウトには、名前を付けたウィンドウのタブ、画面分割、閲覧位置が保存されます。メインウィンドウのレイアウトと新しいウィンドウのレイアウトは同じレイアウトメニュー内でグループ分けされ、別々に保存されます。メインウィンドウのレイアウトを保存または更新すると、ウィンドウのサイズ、位置、最大化や全画面表示の状態も記録されます。名前を付けた新しいウィンドウでは、これらの情報が自動保存されます。レイアウトを開くとウィンドウの状態が復元され、ディスプレイ構成が変わった場合は利用可能な画面内に調整されます。ウィンドウ情報を含まない以前のレイアウトも引き続き使用できます。位置とサイズの復元はOSの制約を受け、Wayland環境では利用できない場合があります。メインウィンドウのレイアウトは最大1件、新しいウィンドウのレイアウトは複数選択でき、一覧の上にある開くボタンでまとめて開けます。この選択内容は保存されません。この機能はデスクトップクライアントで利用できます。暗号化されたノートブックのタブは保存されません。"
}
]
},
diff --git a/app/src/layout/util.ts b/app/src/layout/util.ts
index b0fa139f54..55e76aa821 100644
--- a/app/src/layout/util.ts
+++ b/app/src/layout/util.ts
@@ -163,8 +163,23 @@ export const resetLayout = () => {
};
let saveCount = 0;
+let saveRetryTimeout = 0;
+let layoutSavingSuspended = false;
+const layoutSaveRequests = new Set<Promise<void>>();
+
+// 切换布局前停止自动保存并等待在途请求,成功后保持暂停直到页面刷新,失败时由调用方恢复。
+export const suspendLayoutSaving = async () => {
+ layoutSavingSuspended = true;
+ window.clearTimeout(saveRetryTimeout);
+ saveCount = 0;
+ await Promise.allSettled(layoutSaveRequests);
+ return () => {
+ layoutSavingSuspended = false;
+ };
+};
+
export const saveLayout = () => {
- if (!window.siyuan.layout?.layout) {
+ if (layoutSavingSuspended || !window.siyuan.layout?.layout) {
return;
}
const breakObj = {};
@@ -190,7 +205,7 @@ export const saveLayout = () => {
}
if (Object.keys(breakObj).length > 0 && saveCount < 10) {
saveCount++;
- setTimeout(() => {
+ saveRetryTimeout = window.setTimeout(() => {
saveLayout();
}, Constants.TIMEOUT_LOAD * saveCount);
} else {
@@ -204,7 +219,9 @@ export const saveLayout = () => {
layout: layoutJSON,
errorExit: false // 后台不接受该参数,用于请求发生错误时退出程序
};
- fetchPost("/api/system/setUILayout", request);
+ const saving = fetchPost("/api/system/setUILayout", request);
+ layoutSaveRequests.add(saving);
+ void saving.then(() => layoutSaveRequests.delete(saving), () => layoutSaveRequests.delete(saving));
}
}
}
@@ -229,6 +246,10 @@ export const exportLayout = async (options: {
// 关闭时滚动位置保存超时,继续保存布局并执行退出流程。
console.warn("Save scroll timed out before closing");
});
+ if (layoutSavingSuspended) {
+ options.cb();
+ return;
+ }
if (isWindow()) {
const layoutJSON: any = {
layout: {},
diff --git a/app/src/menus/layouts.test.ts b/app/src/menus/layouts.test.ts
index 8d527b93f6..91ecad6d73 100644
--- a/app/src/menus/layouts.test.ts
+++ b/app/src/menus/layouts.test.ts
@@ -3,27 +3,51 @@ import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import type {IWindowGeometry} from "../window/geometry";
+
+const tick = () => new Promise<void>(resolve => setImmediate(resolve));
const compiled = transpileModule(readFileSync("src/menus/layouts.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
}).outputText;
+const compiledUtil = transpileModule(readFileSync("src/layout/util.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+}).outputText;
-const fixture = () => {
- const layouts = [{name: "Reading", time: 1, layout: {saved: true}, filesPaths: ["saved-path"]}];
+const fixture = (geometryAvailable = true) => {
+ const layouts = [{name: "Reading", time: 1, layout: {saved: true}, filesPaths: ["saved-path"],
+ windowGeometry: undefined as IWindowGeometry | undefined}];
+ const geometry: IWindowGeometry = {version: 1, x: 80, y: 100, width: 1100, height: 800, maximized: true, fullscreen: false};
const calls: Array<{action: string, value?: unknown}> = [];
+ const util = {} as typeof import("../layout/util");
+ class Layout {
+ direction = "lr";
+ children: unknown[] = [];
+ }
let dialog: any;
const dependencies = {
+ Layout,
Constants: {LOCAL_LAYOUTS: "layouts", LOCAL_FILESPATHS: "paths",
SIYUAN_WINDOW_WORKSPACE_GET_OPEN: "siyuan-window-workspace-get-open"},
- setStorageVal: (key: string, value: unknown, callback?: () => void) => {
+ setStorageVal: async (key: string, value: unknown, callback?: () => void) => {
calls.push({action: key, value: JSON.parse(JSON.stringify(value))});
callback?.();
},
- fetchPost: (url: string, value: unknown, callback: () => void) => {
+ fetchPost: async (url: string, value: unknown, callback?: () => void) => {
calls.push({action: url, value});
- callback();
+ callback?.();
},
getAllLayout: () => ({current: true}),
+ suspendLayoutSaving: () => util.suspendLayoutSaving(),
+ isWindow: () => false,
+ getAllEditor: (): unknown[] => [],
+ withFetchTimeout: async (callback: () => Promise<void>) => callback(),
+ captureWindowGeometry: async () => geometryAvailable ? geometry : undefined,
+ restoreWindowGeometry: async (value?: IWindowGeometry) => {
+ if (value) {
+ calls.push({action: "geometry", value});
+ }
+ },
openInputDialog: (options: unknown) => {
dialog = options;
return {element: {setAttribute: () => {}}};
@@ -34,14 +58,19 @@ const fixture = () => {
openWindowWorkspace: (value: string) => calls.push({action: "open", value}),
removeWindowWorkspace: (value: string) => calls.push({action: "delete", value}),
};
- const window = {siyuan: {
+ const dock = {elements: [{querySelectorAll: (): unknown[] => []}, {querySelectorAll: (): unknown[] => []}]};
+ const window = {clearTimeout, setTimeout, siyuan: {
+ layout: {layout: new Layout(), bottomDock: dock, leftDock: dock, rightDock: dock},
+ config: {readonly: false},
storage: {layouts, paths: ["current-path"]},
languages: {openBy: "Open", windowWorkspaceSwitch: "Switch", use: "Use", update: "Update", rename: "Rename",
delete: "Delete", confirm: "Confirm", mainWindowLayouts: "Main window layouts", _kernel: {142: "Empty"}},
}, location: {reload: () => calls.push({action: "reload"})}};
+ runInNewContext(compiledUtil, {exports: util, require: () => dependencies, window,
+ document: {querySelector: () => ({getAttribute: () => "#iconDock"})}});
const api = {} as typeof import("./layouts");
runInNewContext(compiled, {exports: api, require: () => dependencies, window});
- return {api, window, calls, dialog: () => dialog};
+ return {api, util, dependencies, window, calls, geometry, dialog: () => dialog};
};
test("主窗口布局更多菜单按使用、更新、重命名、删除排列", () => {
@@ -68,6 +97,7 @@ test("新窗口布局不提供更新,已打开时显示切换", () => {
test("重命名仅改变名称,弹窗以主窗口布局为标题并使用确定按钮", () => {
const f = fixture();
+ f.window.siyuan.storage.layouts[0].windowGeometry = {...f.geometry, width: 900};
f.api.getLayoutActions({type: "main", name: "Reading"})[2].click(undefined, undefined);
assert.equal(f.dialog().title, "Main window layouts");
assert.equal(f.dialog().confirmText, "Confirm");
@@ -76,24 +106,28 @@ test("重命名仅改变名称,弹窗以主窗口布局为标题并使用确
assert.equal(f.window.siyuan.storage.layouts[0].name, "Renamed");
assert.deepEqual(f.window.siyuan.storage.layouts[0].layout, {saved: true});
assert.deepEqual(f.window.siyuan.storage.layouts[0].filesPaths, ["saved-path"]);
+ assert.equal(f.window.siyuan.storage.layouts[0].windowGeometry.width, 900);
});
-test("更新保存当前布局和文档树状态,打开恢复已保存布局", () => {
+test("更新保存当前布局、文档树状态和窗口边界,打开后先恢复窗口再刷新", async () => {
const f = fixture();
const actions = f.api.getLayoutActions({type: "main", name: "Reading"});
- actions[1].click(undefined, undefined);
+ await actions[1].click(undefined, undefined);
assert.equal(f.window.siyuan.storage.layouts[0].name, "Reading");
assert.deepEqual(JSON.parse(JSON.stringify(f.window.siyuan.storage.layouts[0].layout)), {current: true});
assert.deepEqual(f.window.siyuan.storage.layouts[0].filesPaths, ["current-path"]);
+ assert.deepEqual(f.window.siyuan.storage.layouts[0].windowGeometry, f.geometry);
actions[0].click(undefined, undefined);
- assert.equal(f.calls[1].action, "/api/system/setUILayout");
- assert.deepEqual(JSON.parse(JSON.stringify(f.calls[1].value)), {layout: {current: true}});
+ await tick();
+ assert.equal(f.calls[3].action, "/api/system/setUILayout");
+ assert.deepEqual(JSON.parse(JSON.stringify(f.calls[3].value)), {layout: {current: true}});
assert.equal(f.calls[f.calls.length - 1].action, "reload");
+ assert.deepEqual(f.calls.slice(-4).map(call => call.action), ["geometry", "paths", "/api/system/setUILayout", "reload"]);
});
test("删除只移除选中的布局", () => {
const f = fixture();
- f.window.siyuan.storage.layouts.push({name: "Other", time: 1, layout: {saved: true}, filesPaths: []});
+ f.window.siyuan.storage.layouts.push({name: "Other", time: 1, layout: {saved: true}, filesPaths: [], windowGeometry: undefined});
f.api.getLayoutActions({type: "main", name: "Reading"})[3].click(undefined, undefined);
assert.deepEqual(f.window.siyuan.storage.layouts.map(item => item.name), ["Other"]);
assert.deepEqual(f.window.siyuan.storage.paths, ["current-path"]);
@@ -102,7 +136,8 @@ test("删除只移除选中的布局", () => {
test("批量打开先启动所有新窗口布局,再恢复主窗口布局", async () => {
const f = fixture();
await f.api.openSelectedLayouts("Reading", ["window-a", "window-b"]);
- assert.deepEqual(f.calls.map(call => call.action), ["open", "open", "/api/system/setUILayout", "paths", "reload"]);
+ await tick();
+ assert.deepEqual(f.calls.map(call => call.action), ["open", "open", "paths", "/api/system/setUILayout", "reload"]);
assert.deepEqual(f.calls.slice(0, 2).map(call => call.value), ["window-a", "window-b"]);
});
@@ -111,3 +146,66 @@ test("批量打开可以只选择新窗口布局", async () => {
await f.api.openSelectedLayouts("", ["window-a", "window-b"]);
assert.deepEqual(f.calls.map(call => call.action), ["open", "open"]);
});
+
+test("无法获取原生窗口状态时更新布局保留已保存的窗口边界", async () => {
+ const f = fixture(false);
+ f.window.siyuan.storage.layouts[0].windowGeometry = f.geometry;
+ await f.api.getLayoutActions({type: "main", name: "Reading"})[1].click(undefined, undefined);
+ assert.deepEqual(f.window.siyuan.storage.layouts[0].windowGeometry, f.geometry);
+ assert.deepEqual(JSON.parse(JSON.stringify(f.window.siyuan.storage.layouts[0].layout)), {current: true});
+});
+
+test("切换等待在途保存,窗口缩放及刷新前的延迟保存不会覆盖目标布局", async () => {
+ const f = fixture();
+ let completeSave: () => void;
+ let completeStorage: () => void;
+ const fetchPost = f.dependencies.fetchPost;
+ f.dependencies.fetchPost = async (url, value, callback) => {
+ await new Promise<void>(resolve => completeSave = resolve);
+ await fetchPost(url, value, callback);
+ };
+ f.util.saveLayout();
+ const storage = f.dependencies.setStorageVal;
+ f.dependencies.setStorageVal = async (key, value, callback) => {
+ await new Promise<void>(resolve => completeStorage = resolve);
+ await storage(key, value, callback);
+ };
+ f.window.siyuan.storage.layouts[0].windowGeometry = f.geometry;
+ const opening = f.api.openSelectedLayouts("Reading", []);
+ await tick();
+ assert.deepEqual(f.calls, []);
+ f.dependencies.fetchPost = fetchPost;
+ completeSave();
+ await tick();
+ assert.deepEqual(f.calls.map(call => call.action), ["/api/system/setUILayout", "geometry"]);
+ f.util.saveLayout();
+ await f.util.exportLayout({cb: () => {}, errorExit: false});
+ assert.equal(f.calls.length, 2);
+ completeStorage();
+ await opening;
+ f.util.saveLayout();
+ assert.deepEqual(f.calls.map(call => call.action),
+ ["/api/system/setUILayout", "geometry", "paths", "/api/system/setUILayout", "reload"]);
+ assert.deepEqual(JSON.parse(JSON.stringify(f.calls[3].value)), {layout: {saved: true}});
+});
+
+test("恢复请求失败后恢复自动保存并允许再次切换", async () => {
+ for (const failure of ["storage", "layout"]) {
+ const f = fixture();
+ const storage = f.dependencies.setStorageVal;
+ const fetchPost = f.dependencies.fetchPost;
+ if (failure === "storage") {
+ f.dependencies.setStorageVal = async () => {};
+ } else {
+ f.dependencies.fetchPost = async () => {};
+ }
+ await f.api.openSelectedLayouts("Reading", []);
+ assert.equal(f.calls.some(call => call.action === "reload"), false);
+ f.dependencies.setStorageVal = storage;
+ f.dependencies.fetchPost = fetchPost;
+ f.util.saveLayout();
+ assert.equal(f.calls.at(-1).action, "/api/system/setUILayout");
+ await f.api.openSelectedLayouts("Reading", []);
+ assert.equal(f.calls.at(-1).action, "reload");
+ }
+});
diff --git a/app/src/menus/layouts.ts b/app/src/menus/layouts.ts
index 0d0a42d712..8984742bbb 100644
--- a/app/src/menus/layouts.ts
+++ b/app/src/menus/layouts.ts
@@ -1,7 +1,7 @@
import {Constants} from "../constants";
import {setStorageVal} from "../protyle/util/compatibility";
import {fetchPost} from "../util/fetch";
-import {getAllLayout} from "../layout/util";
+import {getAllLayout, suspendLayoutSaving} from "../layout/util";
import {showMessage} from "../dialog/message";
import {openInputDialog} from "../dialog/inputDialog";
import {confirmDialog} from "../dialog/confirmDialog";
@@ -11,10 +11,14 @@ import {isBrowser} from "../util/functions";
import {editWindowWorkspace, getWindowWorkspaces, openWindowWorkspace, removeWindowWorkspace} from "../window/workspace";
import {MenuItem} from "./Menu";
import * as dayjs from "dayjs";
+import {captureWindowGeometry, restoreWindowGeometry} from "../window/geometry";
+import type {IWindowGeometry} from "../window/geometry";
/// #if !BROWSER
import {ipcRenderer} from "electron";
/// #endif
+type SavedLayout = ISaveLayout & {windowGeometry?: IWindowGeometry};
+
const editLayout = (layoutName?: string) => {
const dialog = openInputDialog({
positionId: Constants.DIALOG_SAVEWORKSPACE,
@@ -24,7 +28,7 @@ const editLayout = (layoutName?: string) => {
placeholder: window.siyuan.languages.memo,
width: "520px",
confirmText: window.siyuan.languages.confirm,
- onConfirm: (value, dialog) => {
+ onConfirm: async (value, dialog) => {
value = value.trim();
if (!value) {
showMessage(window.siyuan.languages["_kernel"]["142"]);
@@ -42,9 +46,10 @@ const editLayout = (layoutName?: string) => {
});
return;
}
- const hadName = window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((item: ISaveLayout) => {
+ const hadName = window.siyuan.storage[Constants.LOCAL_LAYOUTS].find((item: SavedLayout) => {
if (item.name === value) {
- confirmDialog(window.siyuan.languages.save, window.siyuan.languages.exportTplTip, () => {
+ confirmDialog(window.siyuan.languages.save, window.siyuan.languages.exportTplTip, async () => {
+ item.windowGeometry = await captureWindowGeometry() ?? item.windowGeometry;
item.layout = getAllLayout();
item.time = Date.now();
item.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];
@@ -57,6 +62,7 @@ const editLayout = (layoutName?: string) => {
return;
}
window.siyuan.storage[Constants.LOCAL_LAYOUTS].push({
+ windowGeometry: await captureWindowGeometry(),
name: value,
time: Date.now(),
layout: getAllLayout(),
@@ -68,26 +74,46 @@ const editLayout = (layoutName?: string) => {
dialog.element.setAttribute("data-key", Constants.DIALOG_SAVEWORKSPACE);
};
-const openLayout = (name: string) => {
- const item: ISaveLayout = window.siyuan.storage[Constants.LOCAL_LAYOUTS]
+let openingLayout = false;
+const openLayout = async (name: string) => {
+ const item: SavedLayout = window.siyuan.storage[Constants.LOCAL_LAYOUTS]
.find((layout: ISaveLayout) => layout.name === name);
- if (!item) {
+ if (!item || openingLayout) {
return;
}
- fetchPost("/api/system/setUILayout", {layout: item.layout}, () => {
+ openingLayout = true;
+ const resumeLayoutSaving = await suspendLayoutSaving();
+ let reloading = false;
+ try {
+ await restoreWindowGeometry(item.windowGeometry).catch(console.error);
if (item.filesPaths) {
+ const previous = window.siyuan.storage[Constants.LOCAL_FILESPATHS];
window.siyuan.storage[Constants.LOCAL_FILESPATHS] = item.filesPaths;
- setStorageVal(Constants.LOCAL_FILESPATHS, item.filesPaths, () => window.location.reload());
- } else {
+ let saved = false;
+ await setStorageVal(Constants.LOCAL_FILESPATHS, item.filesPaths, () => saved = true);
+ if (!saved) {
+ window.siyuan.storage[Constants.LOCAL_FILESPATHS] = previous;
+ return;
+ }
+ }
+ await fetchPost("/api/system/setUILayout", {layout: item.layout}, () => {
+ reloading = true;
window.location.reload();
+ });
+ } catch (error) {
+ console.error(error);
+ } finally {
+ if (!reloading) {
+ resumeLayoutSaving();
+ openingLayout = false;
}
- });
+ }
};
export const openSelectedLayouts = async (mainName: string, workspaceIDs: string[]) => {
await Promise.allSettled(workspaceIDs.map(id => openWindowWorkspace(id)));
if (mainName) {
- openLayout(mainName);
+ await openLayout(mainName);
}
};
@@ -103,17 +129,18 @@ export const getLayoutActions = (target: LayoutTarget, time?: number): IMenu[] =
if (target.type === "window") {
void openWindowWorkspace(target.id);
} else {
- openLayout(target.name);
+ void openLayout(target.name);
}
},
}, ...(target.type === "main" ? [{
id: "update",
icon: "iconRefresh",
label: window.siyuan.languages.update,
- click: () => {
- const item: ISaveLayout = window.siyuan.storage[Constants.LOCAL_LAYOUTS]
+ click: async () => {
+ const item: SavedLayout = window.siyuan.storage[Constants.LOCAL_LAYOUTS]
.find((layout: ISaveLayout) => layout.name === target.name);
if (item) {
+ item.windowGeometry = await captureWindowGeometry() ?? item.windowGeometry;
item.layout = getAllLayout();
item.filesPaths = window.siyuan.storage[Constants.LOCAL_FILESPATHS];
item.time = Date.now();
diff --git a/app/src/window/geometry.ts b/app/src/window/geometry.ts
new file mode 100644
index 0000000000..87fa1efec8
--- /dev/null
+++ b/app/src/window/geometry.ts
@@ -0,0 +1,37 @@
+import {Constants} from "../constants";
+import {isBrowser} from "../util/functions";
+/// #if !BROWSER
+import {ipcRenderer} from "electron";
+/// #endif
+
+export interface IWindowGeometry {
+ version: 1;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ maximized: boolean;
+ fullscreen: boolean;
+}
+
+export const captureWindowGeometry = async (): Promise<IWindowGeometry | undefined> => {
+ if (isBrowser()) {
+ return;
+ }
+ /// #if !BROWSER
+ try {
+ return await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "getWindowGeometry"}) || undefined;
+ } catch (error) {
+ console.error(error);
+ }
+ /// #endif
+};
+
+export const restoreWindowGeometry = async (geometry?: IWindowGeometry) => {
+ if (isBrowser() || !geometry) {
+ return;
+ }
+ /// #if !BROWSER
+ await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "setWindowGeometry", geometry});
+ /// #endif
+};
diff --git a/app/src/window/openNewWindow.ts b/app/src/window/openNewWindow.ts
index 5671134524..c9e3905030 100644
--- a/app/src/window/openNewWindow.ts
+++ b/app/src/window/openNewWindow.ts
@@ -10,6 +10,7 @@ import {getAssetExtension, getDisplayName} from "../util/pathName";
import {getSearch} from "../util/functions";
import {isBrowserRenderableImagePath} from "../util/imageURL";
import {appendRemoteQuery} from "../util/hostCapabilities";
+import type {IWindowGeometry} from "./geometry";
interface windowOptions {
position?: {
@@ -28,11 +29,11 @@ const getWindowURL = (layout: unknown) => {
return appendRemoteQuery(url).href;
};
-export const openNewWindowByWorkspace = (id: string) => {
+export const openNewWindowByWorkspace = (id: string, windowGeometry?: IWindowGeometry) => {
/// #if !BROWSER
const url = new URL(getWindowURL([]));
url.searchParams.set("windowWorkspace", id);
- ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {url: url.href, alwaysOnTop: false});
+ ipcRenderer.send(Constants.SIYUAN_OPEN_WINDOW, {url: url.href, alwaysOnTop: false, windowGeometry});
/// #endif
};
diff --git a/app/src/window/workspace.test.ts b/app/src/window/workspace.test.ts
index d453612a19..bec2c6a891 100644
--- a/app/src/window/workspace.test.ts
+++ b/app/src/window/workspace.test.ts
@@ -4,6 +4,7 @@ import {test} from "node:test";
import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
import * as core from "./workspaceCore";
+import type {IWindowGeometry} from "./geometry";
const compiled = transpileModule(readFileSync("src/window/workspace.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
@@ -28,12 +29,14 @@ const fixture = (initialStorage: Record<string, unknown> = {}, workspaceID = "")
incomplete: false,
focus: false,
gate: undefined as Promise<void> | undefined,
+ geometry: undefined as IWindowGeometry | undefined,
};
let dialogOptions: any;
let url = new URL(`http://127.0.0.1:6806/stage/build/app/window.html?windowWorkspace=${workspaceID}`);
const writes: Array<{key: string, value: any}> = [];
const messages: string[] = [];
const opened: string[] = [];
+ const openedGeometries: Array<IWindowGeometry | undefined> = [];
const associated: string[] = [];
const dependencies = {
...core,
@@ -43,6 +46,7 @@ const fixture = (initialStorage: Record<string, unknown> = {}, workspaceID = "")
getSearch: (key: string) => url.searchParams.get(key),
isBrowser: () => false,
isWindow: () => true,
+ captureWindowGeometry: async () => state.geometry,
setStorageVal: async (key: string, value: unknown, callback: () => void) => {
writes.push({key, value: clone(value)});
if (state.gate) {
@@ -69,7 +73,10 @@ const fixture = (initialStorage: Record<string, unknown> = {}, workspaceID = "")
confirmDialog: (_title: string, _message: string, confirm: () => void) => confirm(),
showMessage: (message: string) => messages.push(message),
escapeHtml: (text: string) => text,
- openNewWindowByWorkspace: (workspace: string) => opened.push(workspace),
+ openNewWindowByWorkspace: (workspace: string, geometry?: IWindowGeometry) => {
+ opened.push(workspace);
+ openedGeometries.push(geometry);
+ },
ipcRenderer: {invoke: async (_channel: string, data: {cmd: string, id: string}) => {
if (data.cmd === "siyuan-window-workspace-set") {
associated.push(data.id);
@@ -99,7 +106,7 @@ const fixture = (initialStorage: Record<string, unknown> = {}, workspaceID = "")
console, URL, Event, Lute: {NewNodeID: () => id},
});
return {
- api, state, storage, disk, writes, messages, opened, associated, window,
+ api, state, storage, disk, writes, messages, opened, openedGeometries, associated, window,
dialog: () => dialogOptions,
boot: () => {
const restored = api.getWindowWorkspaceLayout();
@@ -116,11 +123,13 @@ const savedStorage = () => ({
test("保存命名窗口,重新加载后恢复文档、PDF 页码和阅读位置", async () => {
const f = fixture();
+ f.state.geometry = {version: 1, x: 80, y: 60, width: 900, height: 700, maximized: false, fullscreen: false};
f.boot();
f.api.editWindowWorkspace();
await f.dialog().onConfirm(" Reading ", {destroy: () => {}});
assert.equal((f.disk[prefix + id] as core.IWindowWorkspace).name, "Reading");
assert.deepEqual(f.associated, [id]);
+ assert.deepEqual((f.disk[prefix + id + "-layout"] as core.IWindowWorkspaceSnapshot).windowGeometry, f.state.geometry);
const reopened = fixture(f.disk, id);
assert.equal(reopened.api.getWindowWorkspaces()[0].time,
(f.disk[prefix + id + "-layout"] as core.IWindowWorkspaceSnapshot).time);
@@ -132,6 +141,30 @@ test("保存命名窗口,重新加载后恢复文档、PDF 页码和阅读位
assert.deepEqual(reopened.opened, [id]);
});
+test("移动或缩放新窗口也会自动保存,重新打开时传递窗口边界", async () => {
+ const f = fixture(savedStorage(), id);
+ f.boot();
+ f.state.geometry = {version: 1, x: -1200, y: 80, width: 900, height: 700, maximized: false, fullscreen: false};
+ assert.equal(await f.api.flushWindowWorkspace(), true);
+ assert.deepEqual((f.disk[prefix + id + "-layout"] as core.IWindowWorkspaceSnapshot).windowGeometry, f.state.geometry);
+ assert.equal(await f.api.flushWindowWorkspace(), true);
+ assert.equal(f.writes.length, 1);
+ f.state.geometry = {...f.state.geometry, x: -1100, width: 1000, maximized: true};
+ assert.equal(await f.api.flushWindowWorkspace(), true);
+ assert.equal(f.writes.length, 2);
+ const reopened = fixture(f.disk, id);
+ reopened.boot();
+ await reopened.api.openWindowWorkspace(id);
+ assert.deepEqual(reopened.openedGeometries, [f.state.geometry]);
+});
+
+test("旧窗口快照没有窗口边界时仍可打开", async () => {
+ const f = fixture(savedStorage(), id);
+ assert.deepEqual(clone(f.boot()), layout());
+ await f.api.openWindowWorkspace(id);
+ assert.deepEqual(f.openedGeometries, [undefined]);
+});
+
test("自动保存布局不会覆盖其他窗口写入的工作区名称", async () => {
const f = fixture(savedStorage(), id);
f.boot();
diff --git a/app/src/window/workspace.ts b/app/src/window/workspace.ts
index e7dfe293fd..147264a4f5 100644
--- a/app/src/window/workspace.ts
+++ b/app/src/window/workspace.ts
@@ -10,6 +10,7 @@ import {showMessage} from "../dialog/message";
import {escapeHtml} from "../util/escape";
import {setWindowWorkspaceTitle} from "../util/processTitle";
import {openNewWindowByWorkspace} from "./openNewWindow";
+import {captureWindowGeometry} from "./geometry";
import {
isWindowWorkspace,
isWindowWorkspaceID,
@@ -30,6 +31,9 @@ let saveTimer = 0;
let lastSaved = "";
let lastSaveOK = true;
+const snapshotContent = (snapshot: IWindowWorkspaceSnapshot) =>
+ JSON.stringify({layout: snapshot.layout, windowGeometry: snapshot.windowGeometry});
+
export const getWindowWorkspace = (id: string) => {
const value: unknown = window.siyuan.storage?.[infoKey(id)];
return isWindowWorkspace(value) && value.id === id ? value : undefined;
@@ -91,14 +95,14 @@ const writer = new WindowWorkspaceWriter<{id: string, snapshot: IWindowWorkspace
const saved = await persist(layoutKey(id), snapshot);
if (currentID === id) {
if (saved) {
- lastSaved = JSON.stringify(snapshot.layout);
+ lastSaved = snapshotContent(snapshot);
}
lastSaveOK = saved;
}
return saved;
});
-const capture = (): IWindowWorkspaceSnapshot | undefined => {
+const capture = async (): Promise<IWindowWorkspaceSnapshot | undefined> => {
if (!window.siyuan.layout?.layout) {
return;
}
@@ -109,6 +113,16 @@ const capture = (): IWindowWorkspaceSnapshot | undefined => {
return;
}
const snapshot: IWindowWorkspaceSnapshot = {version: 1, time: Date.now(), layout};
+ try {
+ snapshot.windowGeometry = await captureWindowGeometry();
+ const previous: unknown = currentID ? window.siyuan.storage[layoutKey(currentID)] : undefined;
+ if (!snapshot.windowGeometry && isWindowWorkspaceSnapshot(previous)) {
+ snapshot.windowGeometry = previous.windowGeometry;
+ }
+ } catch (error) {
+ console.error(error);
+ return;
+ }
return isWindowWorkspaceSnapshot(snapshot) ? snapshot : undefined;
};
@@ -117,11 +131,15 @@ export const flushWindowWorkspace = async () => {
if (!currentID || !ready || window.siyuan.config.readonly || !getWindowWorkspace(currentID)) {
return true;
}
- const snapshot = capture();
+ const id = currentID;
+ const snapshot = await capture();
+ if (id !== currentID) {
+ return true;
+ }
if (!snapshot) {
return false;
}
- if (lastSaveOK && JSON.stringify(snapshot.layout) === lastSaved) {
+ if (lastSaveOK && snapshotContent(snapshot) === lastSaved) {
return true;
}
lastSaveOK = false;
@@ -168,7 +186,7 @@ export const getWindowWorkspaceLayout = () => {
return;
}
currentID = id;
- lastSaved = JSON.stringify(snapshot.layout);
+ lastSaved = snapshotContent(snapshot);
return JSON.parse(JSON.stringify(snapshot.layout)) as Config.TPersistedUILayoutItem;
};
@@ -186,11 +204,12 @@ export const openWindowWorkspace = async (id: string) => {
return;
}
/// #endif
- if (!getWindowWorkspace(id) || !isWindowWorkspaceSnapshot(window.siyuan.storage[layoutKey(id)])) {
+ const snapshot: unknown = window.siyuan.storage[layoutKey(id)];
+ if (!getWindowWorkspace(id) || !isWindowWorkspaceSnapshot(snapshot)) {
showMessage(window.siyuan.languages.windowWorkspaceUnavailable, 6000, "error");
return;
}
- openNewWindowByWorkspace(id);
+ openNewWindowByWorkspace(id, snapshot.windowGeometry);
};
const removeWorkspace = async (id: string) => {
@@ -253,7 +272,7 @@ export const editWindowWorkspace = (id?: string) => {
throw new Error("Window workspace rename failed");
}
} else {
- const snapshot = capture();
+ const snapshot = await capture();
if (!snapshot) {
throw new Error("Window layout is not ready");
}
@@ -266,7 +285,7 @@ export const editWindowWorkspace = (id?: string) => {
if (!await associate(newID)) {
throw new Error("Window workspace association failed");
}
- lastSaved = JSON.stringify(snapshot.layout);
+ lastSaved = snapshotContent(snapshot);
lastSaveOK = true;
}
dialog.destroy();
@@ -328,9 +347,10 @@ export const initWindowWorkspace = () => {
toolbar.insertBefore(button, document.getElementById("pinWindow"));
button.addEventListener("click", () => editWindowWorkspace(currentID));
window.addEventListener("siyuan-window-layout", scheduleSave);
+ window.addEventListener("resize", scheduleSave);
document.addEventListener("scroll", scheduleSave, true);
window.addEventListener("blur", () => void flushWindowWorkspace());
- // PDF 页码由嵌入页面更新,定期比较快照,仅在布局或阅读位置改变时写入。
+ // 定期比较布局、阅读位置和窗口边界,仅在状态改变时写入。
window.setInterval(() => {
if (currentID && document.visibilityState === "visible") {
void flushWindowWorkspace();
diff --git a/app/src/window/workspaceCore.ts b/app/src/window/workspaceCore.ts
index 4acc5ababc..91c508d70a 100644
--- a/app/src/window/workspaceCore.ts
+++ b/app/src/window/workspaceCore.ts
@@ -1,3 +1,5 @@
+import type {IWindowGeometry} from "./geometry";
+
export interface IWindowWorkspace {
version: 1;
id: string;
@@ -9,6 +11,7 @@ export interface IWindowWorkspaceSnapshot {
version: 1;
time: number;
layout: Config.TPersistedUILayoutItem;
+ windowGeometry?: IWindowGeometry;
}
const isObject = (value: unknown): value is Record<string, unknown> =>