axon-shell 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- axon_shell/__init__.py +10 -0
- axon_shell/assets/axon.ico +0 -0
- axon_shell/assets/icon-256.png +0 -0
- axon_shell/assets/shell.js +364 -0
- axon_shell/window.py +529 -0
- axon_shell-0.2.1.dist-info/METADATA +183 -0
- axon_shell-0.2.1.dist-info/RECORD +10 -0
- axon_shell-0.2.1.dist-info/WHEEL +5 -0
- axon_shell-0.2.1.dist-info/licenses/LICENSE +21 -0
- axon_shell-0.2.1.dist-info/top_level.txt +1 -0
axon_shell/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""axon-shell —— 给 Axon 应用一层可复用的「桌面应用外观」。
|
|
2
|
+
|
|
3
|
+
它不是框架核心:`axon-gui` 只管通道与窗口基类,这个包只提供
|
|
4
|
+
「VSCode 那种观感」需要的两半——Python 侧的无边框窗口,以及前端皮肤。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .window import AxonShellWindow, AxonWindow, WindowBridge, assets_dir
|
|
8
|
+
|
|
9
|
+
__all__ = ["AxonShellWindow", "AxonWindow", "WindowBridge", "assets_dir"]
|
|
10
|
+
__version__ = "0.2.1"
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
/* axon-shell runtime —— 只做「网页自己做不了」的那一层。
|
|
2
|
+
*
|
|
3
|
+
* 它不做任何视觉:没有标题栏、没有按钮、没有 CSS。标题栏长什么样、
|
|
4
|
+
* 菜单放哪儿、按钮用什么图标,全部由你的 HTML/CSS 决定。
|
|
5
|
+
*
|
|
6
|
+
* 它提供四件事:
|
|
7
|
+
* 1. 拖拽区上报:页面里标 data-axon-drag 的元素,其矩形(扣掉里面的
|
|
8
|
+
* 按钮/输入框)会上报给 Qt。Windows 上这些矩形被当作 HTCAPTION,
|
|
9
|
+
* 于是拖动、双击最大化、右键系统菜单都是系统原生行为。
|
|
10
|
+
* 2. 窗口按钮接线:任何 [data-axon-window="min|max|close"] 点了就执行。
|
|
11
|
+
* 3. 窗口状态与原生菜单事件:window:state / window:menu 转到 JS 回调。
|
|
12
|
+
* 4. 兜底:Linux 上系统不做命中测试,这里补拖动与 8 向缩放。
|
|
13
|
+
*
|
|
14
|
+
* 用法:
|
|
15
|
+
* <script src="/vendor/axon.umd.cjs"></script>
|
|
16
|
+
* <script src="/axon-shell/shell.js"></script>
|
|
17
|
+
* <script>
|
|
18
|
+
* await AxonInit(); // axon 自己的握手,见 axon-gui 文档
|
|
19
|
+
* AxonShell.init(); // 接上拖拽区、窗口按钮、状态事件
|
|
20
|
+
* </script>
|
|
21
|
+
*/
|
|
22
|
+
(function (global) {
|
|
23
|
+
"use strict";
|
|
24
|
+
|
|
25
|
+
const doc = global.document;
|
|
26
|
+
const root = () => doc.documentElement;
|
|
27
|
+
|
|
28
|
+
const state = {
|
|
29
|
+
ready: false,
|
|
30
|
+
platform: "",
|
|
31
|
+
frame: { x: 0, y: 0, width: 0, height: 0 },
|
|
32
|
+
maximized: false,
|
|
33
|
+
fullScreen: false,
|
|
34
|
+
listeners: { state: [], menu: [] },
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/* ── axon 库 ─────────────────────────────────────────────── */
|
|
38
|
+
function lib() {
|
|
39
|
+
const api = global.axon;
|
|
40
|
+
if (!api) throw new Error("axon-shell: 先加载 axon 的产物(window.axon)");
|
|
41
|
+
return api;
|
|
42
|
+
}
|
|
43
|
+
function win() {
|
|
44
|
+
return lib().Axon.Window;
|
|
45
|
+
}
|
|
46
|
+
function logError(err) {
|
|
47
|
+
console.error("[axon-shell]", err);
|
|
48
|
+
}
|
|
49
|
+
function emit(kind, payload) {
|
|
50
|
+
for (const cb of state.listeners[kind]) {
|
|
51
|
+
try {
|
|
52
|
+
cb(payload);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
logError(err);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/* ── 拖拽区:把 data-axon-drag 的矩形报给 Qt ─────────────── */
|
|
60
|
+
function regions() {
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const bar of doc.querySelectorAll("[data-axon-drag]")) {
|
|
63
|
+
const rect = bar.getBoundingClientRect();
|
|
64
|
+
if (!rect.width || !rect.height) continue;
|
|
65
|
+
const holes = [];
|
|
66
|
+
for (const el of bar.querySelectorAll(
|
|
67
|
+
'[data-axon-no-drag], button, input, textarea, select, a, [role="button"]',
|
|
68
|
+
)) {
|
|
69
|
+
const r = el.getBoundingClientRect();
|
|
70
|
+
if (r.width && r.height) holes.push(r);
|
|
71
|
+
}
|
|
72
|
+
// 一条横向长条,被里面的交互元素切成若干段
|
|
73
|
+
let segments = [[rect.left, rect.right]];
|
|
74
|
+
for (const b of holes) {
|
|
75
|
+
segments = segments.flatMap(([a, c]) => {
|
|
76
|
+
if (b.right <= a || b.left >= c) return [[a, c]];
|
|
77
|
+
const cut = [];
|
|
78
|
+
if (b.left > a) cut.push([a, Math.min(b.left, c)]);
|
|
79
|
+
if (b.right < c) cut.push([Math.max(b.right, a), c]);
|
|
80
|
+
return cut;
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
for (const [a, c] of segments) {
|
|
84
|
+
if (c - a <= 4) continue;
|
|
85
|
+
out.push({
|
|
86
|
+
x: Math.round(a),
|
|
87
|
+
y: Math.round(rect.top),
|
|
88
|
+
w: Math.round(c - a),
|
|
89
|
+
h: Math.round(rect.height),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
let dragTimer = null;
|
|
97
|
+
function refreshDragRegions() {
|
|
98
|
+
clearTimeout(dragTimer);
|
|
99
|
+
dragTimer = setTimeout(async () => {
|
|
100
|
+
try {
|
|
101
|
+
await win().setDragRegions(regions());
|
|
102
|
+
} catch (err) {
|
|
103
|
+
logError(err);
|
|
104
|
+
}
|
|
105
|
+
}, 40);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/* ── 窗口状态 ───────────────────────────────────────────── */
|
|
109
|
+
function applyState(data) {
|
|
110
|
+
if (!data) return;
|
|
111
|
+
state.platform = data.platform || state.platform;
|
|
112
|
+
state.maximized = !!data.maximized;
|
|
113
|
+
state.fullScreen = !!data.fullScreen;
|
|
114
|
+
state.frame = {
|
|
115
|
+
x: data.x ?? state.frame.x,
|
|
116
|
+
y: data.y ?? state.frame.y,
|
|
117
|
+
width: data.width ?? state.frame.width,
|
|
118
|
+
height: data.height ?? state.frame.height,
|
|
119
|
+
};
|
|
120
|
+
root().dataset.axonMaximized = String(state.maximized);
|
|
121
|
+
emit("state", snapshot());
|
|
122
|
+
refreshDragRegions();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function refreshState() {
|
|
126
|
+
try {
|
|
127
|
+
applyState(await win().state());
|
|
128
|
+
} catch (err) {
|
|
129
|
+
logError(err);
|
|
130
|
+
}
|
|
131
|
+
return state;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/* ── 窗口按钮:[data-axon-window="min|max|close"] ────────── */
|
|
135
|
+
function action(name) {
|
|
136
|
+
if (name === "min") return win().minimize();
|
|
137
|
+
if (name === "max") return win().toggleMaximize().then((v) => applyState({ maximized: v }));
|
|
138
|
+
if (name === "close") return win().close();
|
|
139
|
+
return Promise.resolve();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function bindControls(target) {
|
|
143
|
+
target.addEventListener("click", (event) => {
|
|
144
|
+
const el = event.target.closest("[data-axon-window]");
|
|
145
|
+
if (!el || !target.contains(el)) return;
|
|
146
|
+
event.preventDefault();
|
|
147
|
+
action(el.dataset.axonWindow).catch(logError);
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/* ── 非 Windows / macOS:系统不做命中测试,这里补 ────────── */
|
|
152
|
+
function enableFallback() {
|
|
153
|
+
const bar = () => doc.querySelector("[data-axon-drag]");
|
|
154
|
+
let frame = null;
|
|
155
|
+
let dragging = false;
|
|
156
|
+
|
|
157
|
+
async function beginDrag(event) {
|
|
158
|
+
if (event.button !== 0) return;
|
|
159
|
+
if (state.maximized || !bar()) return;
|
|
160
|
+
const hit = event.target.closest(
|
|
161
|
+
'[data-axon-no-drag], button, input, textarea, select, a, [role="button"]',
|
|
162
|
+
);
|
|
163
|
+
if (hit) return;
|
|
164
|
+
event.preventDefault();
|
|
165
|
+
try {
|
|
166
|
+
if (await win().beginSystemMove()) return;
|
|
167
|
+
} catch {
|
|
168
|
+
/* 系统不支持,走手动 */
|
|
169
|
+
}
|
|
170
|
+
frame = (await win().frame()) || state.frame;
|
|
171
|
+
const sx = event.screenX;
|
|
172
|
+
const sy = event.screenY;
|
|
173
|
+
let pending = null;
|
|
174
|
+
dragging = true;
|
|
175
|
+
const move = (e) => {
|
|
176
|
+
pending = { x: frame.x + (e.screenX - sx), y: frame.y + (e.screenY - sy) };
|
|
177
|
+
if (move.raf) return;
|
|
178
|
+
move.raf = requestAnimationFrame(() => {
|
|
179
|
+
move.raf = null;
|
|
180
|
+
if (pending) win().moveTo(pending.x, pending.y).catch(() => {});
|
|
181
|
+
});
|
|
182
|
+
};
|
|
183
|
+
const up = () => {
|
|
184
|
+
dragging = false;
|
|
185
|
+
removeEventListener("pointermove", move);
|
|
186
|
+
removeEventListener("pointerup", up);
|
|
187
|
+
refreshState();
|
|
188
|
+
};
|
|
189
|
+
addEventListener("pointermove", move);
|
|
190
|
+
addEventListener("pointerup", up);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
doc.addEventListener("pointerdown", (event) => {
|
|
194
|
+
if (dragging) return;
|
|
195
|
+
const zone = event.target.closest("[data-axon-drag]");
|
|
196
|
+
if (zone) beginDrag(event);
|
|
197
|
+
});
|
|
198
|
+
doc.addEventListener("dblclick", (event) => {
|
|
199
|
+
const zone = event.target.closest("[data-axon-drag]");
|
|
200
|
+
if (!zone) return;
|
|
201
|
+
if (event.target.closest('[data-axon-no-drag], button, input, textarea, select, a')) return;
|
|
202
|
+
win()
|
|
203
|
+
.toggleMaximize()
|
|
204
|
+
.then((v) => applyState({ maximized: v }))
|
|
205
|
+
.catch(logError);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// 8 向缩放的透明命中条(只是热区,不是视觉)
|
|
209
|
+
if (!doc.querySelector("[data-axon-resize]")) {
|
|
210
|
+
const layer = doc.createElement("div");
|
|
211
|
+
layer.dataset.axonResize = "1";
|
|
212
|
+
Object.assign(layer.style, {
|
|
213
|
+
position: "fixed",
|
|
214
|
+
inset: "0",
|
|
215
|
+
pointerEvents: "none",
|
|
216
|
+
zIndex: "2147483647",
|
|
217
|
+
});
|
|
218
|
+
const edges = [
|
|
219
|
+
["top", "top:0;left:0;right:0;height:5px;cursor:ns-resize"],
|
|
220
|
+
["bottom", "bottom:0;left:0;right:0;height:5px;cursor:ns-resize"],
|
|
221
|
+
["left", "left:0;top:0;bottom:0;width:5px;cursor:ew-resize"],
|
|
222
|
+
["right", "right:0;top:0;bottom:0;width:5px;cursor:ew-resize"],
|
|
223
|
+
["top-left", "top:0;left:0;width:10px;height:10px;cursor:nwse-resize"],
|
|
224
|
+
["top-right", "top:0;right:0;width:10px;height:10px;cursor:nesw-resize"],
|
|
225
|
+
["bottom-left", "bottom:0;left:0;width:10px;height:10px;cursor:nesw-resize"],
|
|
226
|
+
["bottom-right", "bottom:0;right:0;width:10px;height:10px;cursor:nwse-resize"],
|
|
227
|
+
];
|
|
228
|
+
for (const [edge, css] of edges) {
|
|
229
|
+
const handle = doc.createElement("div");
|
|
230
|
+
handle.dataset.axonResizeEdge = edge;
|
|
231
|
+
handle.style.cssText = "position:absolute;pointer-events:auto;" + css;
|
|
232
|
+
handle.addEventListener("pointerdown", (event) => beginResize(event, edge));
|
|
233
|
+
layer.appendChild(handle);
|
|
234
|
+
}
|
|
235
|
+
doc.body.appendChild(layer);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function beginResize(event, edge) {
|
|
239
|
+
event.preventDefault();
|
|
240
|
+
const start = (await win().frame()) || state.frame;
|
|
241
|
+
const sx = event.screenX;
|
|
242
|
+
const sy = event.screenY;
|
|
243
|
+
let pending = null;
|
|
244
|
+
const move = (e) => {
|
|
245
|
+
const dx = e.screenX - sx;
|
|
246
|
+
const dy = e.screenY - sy;
|
|
247
|
+
let { x, y, width, height } = start;
|
|
248
|
+
if (edge.includes("right")) width = Math.max(480, start.width + dx);
|
|
249
|
+
if (edge.includes("left")) {
|
|
250
|
+
width = Math.max(480, start.width - dx);
|
|
251
|
+
x = start.x + (start.width - width);
|
|
252
|
+
}
|
|
253
|
+
if (edge.includes("bottom")) height = Math.max(320, start.height + dy);
|
|
254
|
+
if (edge.includes("top")) {
|
|
255
|
+
height = Math.max(320, start.height - dy);
|
|
256
|
+
y = start.y + (start.height - height);
|
|
257
|
+
}
|
|
258
|
+
pending = { x, y, width, height };
|
|
259
|
+
if (move.raf) return;
|
|
260
|
+
move.raf = requestAnimationFrame(() => {
|
|
261
|
+
move.raf = null;
|
|
262
|
+
if (!pending) return;
|
|
263
|
+
win().resizeTo(pending.width, pending.height).catch(() => {});
|
|
264
|
+
win().moveTo(pending.x, pending.y).catch(() => {});
|
|
265
|
+
});
|
|
266
|
+
};
|
|
267
|
+
const up = () => {
|
|
268
|
+
removeEventListener("pointermove", move);
|
|
269
|
+
removeEventListener("pointerup", up);
|
|
270
|
+
refreshState();
|
|
271
|
+
};
|
|
272
|
+
addEventListener("pointermove", move);
|
|
273
|
+
addEventListener("pointerup", up);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/* ── 原生菜单:交给 Qt 画 ───────────────────────────────── */
|
|
278
|
+
function nativeMenu(spec, opts) {
|
|
279
|
+
const options = opts || {};
|
|
280
|
+
return win()
|
|
281
|
+
.popupMenu(spec, options.x, options.y)
|
|
282
|
+
.then((requestId) => requestId);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/* ── 初始化 ─────────────────────────────────────────────── */
|
|
286
|
+
function init(options) {
|
|
287
|
+
const opts = options || {};
|
|
288
|
+
if (state.ready) {
|
|
289
|
+
refreshDragRegions();
|
|
290
|
+
return snapshot();
|
|
291
|
+
}
|
|
292
|
+
state.ready = true;
|
|
293
|
+
|
|
294
|
+
if (opts.controls !== false) bindControls(doc);
|
|
295
|
+
|
|
296
|
+
try {
|
|
297
|
+
const { AxonEvent } = lib();
|
|
298
|
+
AxonEvent.addListener("window:state", (payload) => applyState(payload || {}));
|
|
299
|
+
AxonEvent.addListener("window:menu", (payload) => emit("menu", payload || {}));
|
|
300
|
+
} catch (err) {
|
|
301
|
+
logError(err);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
addEventListener("resize", refreshDragRegions);
|
|
305
|
+
// 页面布局稳定后(字体、图片)再报一次
|
|
306
|
+
setTimeout(refreshDragRegions, 120);
|
|
307
|
+
|
|
308
|
+
refreshState()
|
|
309
|
+
.then(() => win().platform())
|
|
310
|
+
.then((platform) => {
|
|
311
|
+
state.platform = platform;
|
|
312
|
+
if (platform !== "win32" && platform !== "darwin" && opts.fallback !== false) {
|
|
313
|
+
enableFallback();
|
|
314
|
+
}
|
|
315
|
+
refreshDragRegions();
|
|
316
|
+
emit("state", snapshot());
|
|
317
|
+
})
|
|
318
|
+
.catch(logError);
|
|
319
|
+
|
|
320
|
+
return state;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function snapshot() {
|
|
324
|
+
return {
|
|
325
|
+
platform: state.platform,
|
|
326
|
+
frame: { ...state.frame },
|
|
327
|
+
maximized: state.maximized,
|
|
328
|
+
fullScreen: state.fullScreen,
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
global.AxonShell = {
|
|
333
|
+
init,
|
|
334
|
+
drag: { refresh: refreshDragRegions, regions },
|
|
335
|
+
window: {
|
|
336
|
+
state: snapshot,
|
|
337
|
+
refresh: refreshState,
|
|
338
|
+
minimize: () => win().minimize(),
|
|
339
|
+
toggleMaximize: () => win().toggleMaximize().then((v) => applyState({ maximized: v })),
|
|
340
|
+
close: () => win().close(),
|
|
341
|
+
setTitle: (text) => win().setTitle(text),
|
|
342
|
+
setAlwaysOnTop: (on) => win().setAlwaysOnTop(on),
|
|
343
|
+
frame: () => win().frame(),
|
|
344
|
+
onState(cb) {
|
|
345
|
+
state.listeners.state.push(cb);
|
|
346
|
+
return () => {
|
|
347
|
+
state.listeners.state = state.listeners.state.filter((fn) => fn !== cb);
|
|
348
|
+
};
|
|
349
|
+
},
|
|
350
|
+
},
|
|
351
|
+
menu: {
|
|
352
|
+
native: nativeMenu,
|
|
353
|
+
onSelect(cb) {
|
|
354
|
+
state.listeners.menu.push(cb);
|
|
355
|
+
return () => {
|
|
356
|
+
state.listeners.menu = state.listeners.menu.filter((fn) => fn !== cb);
|
|
357
|
+
};
|
|
358
|
+
},
|
|
359
|
+
},
|
|
360
|
+
get state() {
|
|
361
|
+
return state;
|
|
362
|
+
},
|
|
363
|
+
};
|
|
364
|
+
})(window);
|
axon_shell/window.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
"""无边框窗口 + 自定义标题栏骨架。
|
|
2
|
+
|
|
3
|
+
`AxonShellWindow` 就是 `AxonGUI` 加了一层「窗口外观由网页决定」的能力:
|
|
4
|
+
|
|
5
|
+
* 没有系统标题栏、边框、按钮,全部由网页绘制(VSCode / Electron 那种观感);
|
|
6
|
+
* 网页通过 `Axon.Window` 控制器调用最小化 / 最大化 / 恢复 / 关闭 / 置顶 / 全屏;
|
|
7
|
+
* 顶部拖拽区由网页用 `[data-axon-drag]` 标记后上报,Windows 上走原生 `WM_NCHITTEST`
|
|
8
|
+
(于是拖动、双击最大化、拖到屏幕边缘贴靠、四边缩放全是系统行为,没有手搓抖动);
|
|
9
|
+
* 其它平台回退到网页驱动:`beginSystemMove()` 失败时用 `moveTo/resizeTo` 按屏幕坐标增量移动;
|
|
10
|
+
* 右键菜单由 Python 侧 `QMenu` 弹出(可选),选中项以 `window:menu` 事件回传,
|
|
11
|
+
网页也可以完全用 HTML 自己画菜单——两条路都在示例里。
|
|
12
|
+
|
|
13
|
+
窗口状态变化会以 `window:state` 事件广播给前端:`{maximized, fullScreen, width, height, x, y, platform}`。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import ctypes
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Iterable, Optional, Sequence, TypedDict
|
|
22
|
+
|
|
23
|
+
from PySide6.QtCore import QEvent, QObject, QPoint, Qt, QTimer, Slot
|
|
24
|
+
from PySide6.QtGui import QAction, QActionGroup, QCursor, QGuiApplication, QIcon, QKeySequence
|
|
25
|
+
from PySide6.QtWidgets import QMenu, QApplication
|
|
26
|
+
|
|
27
|
+
from axon import AxonController, AxonEvent, AxonGUI, AxonMagicGUI
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
WebName = str
|
|
32
|
+
|
|
33
|
+
__all__ = ["AxonShellWindow", "AxonWindow", "WindowBridge", "assets_dir"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def assets_dir() -> str:
|
|
37
|
+
"""前端资源目录(`shell.js` 与图标),用静态服务挂出去即可。"""
|
|
38
|
+
return str(Path(__file__).resolve().parent / "assets")
|
|
39
|
+
|
|
40
|
+
# Win32 WM_NCHITTEST 的返回值
|
|
41
|
+
HTTRANSPARENT = -1
|
|
42
|
+
HTNOWHERE = 0
|
|
43
|
+
HTCLIENT = 1
|
|
44
|
+
HTCAPTION = 2
|
|
45
|
+
HTLEFT = 10
|
|
46
|
+
HTRIGHT = 11
|
|
47
|
+
HTTOP = 12
|
|
48
|
+
HTTOPLEFT = 13
|
|
49
|
+
HTTOPRIGHT = 14
|
|
50
|
+
HTBOTTOM = 15
|
|
51
|
+
HTBOTTOMLEFT = 16
|
|
52
|
+
HTBOTTOMRIGHT = 17
|
|
53
|
+
WM_NCHITTEST = 0x0084
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class DragRect(TypedDict):
|
|
57
|
+
"""网页上报的拖拽区(CSS 像素,窗口坐标系)。"""
|
|
58
|
+
|
|
59
|
+
x: float
|
|
60
|
+
y: float
|
|
61
|
+
w: float
|
|
62
|
+
h: float
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class MenuItem(TypedDict, total=False):
|
|
66
|
+
id: str
|
|
67
|
+
label: str
|
|
68
|
+
kind: str # normal | separator | check | radio | submenu
|
|
69
|
+
checked: bool
|
|
70
|
+
disabled: bool
|
|
71
|
+
shortcut: str
|
|
72
|
+
submenu: list["MenuItem"]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class MenuSpec(TypedDict, total=False):
|
|
76
|
+
title: str
|
|
77
|
+
items: list[MenuItem]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
PLATFORM = (
|
|
81
|
+
"win32" if sys.platform == "win32" else "darwin" if sys.platform == "darwin" else "linux"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class AxonShellWindow(AxonGUI):
|
|
86
|
+
"""无边框窗口:外观与交互交给网页。"""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
web_name: WebName,
|
|
91
|
+
url: str,
|
|
92
|
+
options: Optional[dict[str, Any]] = None,
|
|
93
|
+
*,
|
|
94
|
+
title: str = "Axon",
|
|
95
|
+
min_size: tuple[int, int] = (760, 520),
|
|
96
|
+
size: tuple[int, int] = (1280, 840),
|
|
97
|
+
resize_border: int = 6,
|
|
98
|
+
drag_regions: Iterable[DragRect] = (),
|
|
99
|
+
):
|
|
100
|
+
opts: dict[str, Any] = dict(options or {})
|
|
101
|
+
# 无边框窗口一律自己画右键菜单, 否则 QWebEngineView 会弹原生菜单把自定义 UI 盖掉
|
|
102
|
+
opts.setdefault("disable_native_context_menu", True)
|
|
103
|
+
super().__init__(web_name, url, opts)
|
|
104
|
+
|
|
105
|
+
if AxonMagicGUI.instance is None:
|
|
106
|
+
# 窗口控制必须回到 Qt 主线程执行, 这里兜底建一个
|
|
107
|
+
AxonMagicGUI()
|
|
108
|
+
|
|
109
|
+
self._resize_border = int(resize_border)
|
|
110
|
+
self._drag_regions: list[DragRect] = [dict(r) for r in drag_regions]
|
|
111
|
+
self._menu_seq = 0
|
|
112
|
+
self._active_menu: Optional[QMenu] = None
|
|
113
|
+
self._last_menu: Optional[QMenu] = None # 测试钩子
|
|
114
|
+
self._state_dirty = False
|
|
115
|
+
|
|
116
|
+
self.setWindowFlag(Qt.WindowType.FramelessWindowHint, True)
|
|
117
|
+
self.setWindowTitle(title)
|
|
118
|
+
self.setMinimumSize(*min_size)
|
|
119
|
+
self._fit_to_screen(size)
|
|
120
|
+
self._apply_icon(QApplication.instance())
|
|
121
|
+
|
|
122
|
+
self.window_bridge = WindowBridge(self)
|
|
123
|
+
AxonController.register(self.window_bridge, web_name=web_name, id="Window")
|
|
124
|
+
self.loadFinished.connect(lambda _ok: self._emit_state())
|
|
125
|
+
|
|
126
|
+
def _fit_to_screen(self, desired: tuple[int, int]) -> None:
|
|
127
|
+
"""窗口别大过屏幕:按可用区域收 94%,然后居中。"""
|
|
128
|
+
screen = QGuiApplication.primaryScreen()
|
|
129
|
+
available = screen.availableGeometry() if screen else None
|
|
130
|
+
width, height = desired
|
|
131
|
+
if available is not None:
|
|
132
|
+
width = min(width, int(available.width() * 0.94))
|
|
133
|
+
height = min(height, int(available.height() * 0.94))
|
|
134
|
+
self.resize(width, height)
|
|
135
|
+
if available is not None:
|
|
136
|
+
self.move(
|
|
137
|
+
available.x() + (available.width() - width) // 2,
|
|
138
|
+
available.y() + (available.height() - height) // 2,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
@staticmethod
|
|
142
|
+
def _apply_icon(app: Optional[QApplication]) -> None:
|
|
143
|
+
"""没图标就补一个(宿主已经设过就不覆盖)。"""
|
|
144
|
+
icon_file = Path(assets_dir()) / "icon-256.png"
|
|
145
|
+
if app is None or not icon_file.is_file() or not app.windowIcon().isNull():
|
|
146
|
+
return
|
|
147
|
+
app.setWindowIcon(QIcon(str(icon_file)))
|
|
148
|
+
|
|
149
|
+
# ------------------------------------------------------------------ 平台/状态
|
|
150
|
+
@property
|
|
151
|
+
def platform(self) -> str:
|
|
152
|
+
return PLATFORM
|
|
153
|
+
|
|
154
|
+
def window_state(self) -> dict[str, Any]:
|
|
155
|
+
return {
|
|
156
|
+
"maximized": self.isMaximized(),
|
|
157
|
+
"fullScreen": self.isFullScreen(),
|
|
158
|
+
"width": self.width(),
|
|
159
|
+
"height": self.height(),
|
|
160
|
+
"x": self.x(),
|
|
161
|
+
"y": self.y(),
|
|
162
|
+
"platform": PLATFORM,
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
def set_drag_regions(self, regions: Sequence[DragRect]):
|
|
166
|
+
self._drag_regions = [
|
|
167
|
+
{
|
|
168
|
+
"x": float(r.get("x", 0)),
|
|
169
|
+
"y": float(r.get("y", 0)),
|
|
170
|
+
"w": float(r.get("w", 0)),
|
|
171
|
+
"h": float(r.get("h", 0)),
|
|
172
|
+
}
|
|
173
|
+
for r in regions or ()
|
|
174
|
+
]
|
|
175
|
+
|
|
176
|
+
# ------------------------------------------------------------------ 事件回传
|
|
177
|
+
def _emit_state(self):
|
|
178
|
+
try:
|
|
179
|
+
AxonEvent.dispatch_js_event(
|
|
180
|
+
self.web_name, "window:state", [self.window_state()]
|
|
181
|
+
)
|
|
182
|
+
except Exception:
|
|
183
|
+
# 前端还没握手完时不必吵: 页面加载完成后会主动取一次 state()
|
|
184
|
+
pass
|
|
185
|
+
|
|
186
|
+
def _schedule_state(self):
|
|
187
|
+
if self._state_dirty:
|
|
188
|
+
return
|
|
189
|
+
self._state_dirty = True
|
|
190
|
+
|
|
191
|
+
def flush():
|
|
192
|
+
self._state_dirty = False
|
|
193
|
+
self._emit_state()
|
|
194
|
+
|
|
195
|
+
QTimer.singleShot(60, flush)
|
|
196
|
+
|
|
197
|
+
def changeEvent(self, event: QEvent, /) -> None:
|
|
198
|
+
if event.type() == QEvent.Type.WindowStateChange:
|
|
199
|
+
self._schedule_state()
|
|
200
|
+
super().changeEvent(event)
|
|
201
|
+
|
|
202
|
+
def moveEvent(self, event) -> None: # noqa: N802 - Qt 命名
|
|
203
|
+
super().moveEvent(event)
|
|
204
|
+
self._schedule_state()
|
|
205
|
+
|
|
206
|
+
def resizeEvent(self, event) -> None: # noqa: N802 - Qt 命名
|
|
207
|
+
super().resizeEvent(event)
|
|
208
|
+
self._schedule_state()
|
|
209
|
+
|
|
210
|
+
def _emit_menu_selected(self, request_id: str, item_id: Optional[str]):
|
|
211
|
+
try:
|
|
212
|
+
AxonEvent.dispatch_js_event(
|
|
213
|
+
self.web_name,
|
|
214
|
+
"window:menu",
|
|
215
|
+
[{"requestId": request_id, "id": item_id}],
|
|
216
|
+
)
|
|
217
|
+
except Exception:
|
|
218
|
+
pass
|
|
219
|
+
|
|
220
|
+
# ------------------------------------------------------------------ Windows 原生命中测试
|
|
221
|
+
def _hit_test(self, pos: QPoint) -> Optional[int]:
|
|
222
|
+
"""返回 WM_NCHITTEST 结果;None 表示交回 Qt 默认处理。"""
|
|
223
|
+
if not self.rect().contains(pos):
|
|
224
|
+
return None
|
|
225
|
+
border = self._resize_border
|
|
226
|
+
w, h = self.width(), self.height()
|
|
227
|
+
x, y = pos.x(), pos.y()
|
|
228
|
+
if border and not self.isMaximized() and not self.isFullScreen():
|
|
229
|
+
on_left, on_right = x < border, x >= w - border
|
|
230
|
+
on_top, on_bottom = y < border, y >= h - border
|
|
231
|
+
if on_top and on_left:
|
|
232
|
+
return HTTOPLEFT
|
|
233
|
+
if on_top and on_right:
|
|
234
|
+
return HTTOPRIGHT
|
|
235
|
+
if on_bottom and on_left:
|
|
236
|
+
return HTBOTTOMLEFT
|
|
237
|
+
if on_bottom and on_right:
|
|
238
|
+
return HTBOTTOMRIGHT
|
|
239
|
+
if on_left:
|
|
240
|
+
return HTLEFT
|
|
241
|
+
if on_right:
|
|
242
|
+
return HTRIGHT
|
|
243
|
+
if on_top:
|
|
244
|
+
return HTTOP
|
|
245
|
+
if on_bottom:
|
|
246
|
+
return HTBOTTOM
|
|
247
|
+
for region in self._drag_regions:
|
|
248
|
+
if (
|
|
249
|
+
region["x"] <= x <= region["x"] + region["w"]
|
|
250
|
+
and region["y"] <= y <= region["y"] + region["h"]
|
|
251
|
+
):
|
|
252
|
+
return HTCAPTION
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
def nativeEvent(self, eventType, message): # noqa: N802 (Qt 命名)
|
|
256
|
+
if PLATFORM == "win32":
|
|
257
|
+
try:
|
|
258
|
+
if bytes(eventType) in (b"windows_generic_MSG", b"windows_dispatcher_MSG"):
|
|
259
|
+
from ctypes import wintypes
|
|
260
|
+
|
|
261
|
+
msg = wintypes.MSG.from_address(int(message))
|
|
262
|
+
if msg.message == WM_NCHITTEST:
|
|
263
|
+
x = ctypes.c_short(msg.lParam & 0xFFFF).value
|
|
264
|
+
y = ctypes.c_short((msg.lParam >> 16) & 0xFFFF).value
|
|
265
|
+
hit = self._hit_test(self.mapFromGlobal(QPoint(x, y)))
|
|
266
|
+
if hit is not None:
|
|
267
|
+
return True, hit
|
|
268
|
+
except Exception:
|
|
269
|
+
# 任何异常都不能影响窗口正常事件分发
|
|
270
|
+
pass
|
|
271
|
+
return super().nativeEvent(eventType, message)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _as_bool(value: Any) -> bool:
|
|
275
|
+
if isinstance(value, str):
|
|
276
|
+
return value.strip().lower() in ("1", "true", "yes", "on")
|
|
277
|
+
return bool(value)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class _MenuBuilder:
|
|
281
|
+
"""把前端传来的菜单描述翻译成 QMenu,并把选中项回传给前端。"""
|
|
282
|
+
|
|
283
|
+
def __init__(self, window: AxonShellWindow, request_id: str):
|
|
284
|
+
self.window = window
|
|
285
|
+
self.request_id = request_id
|
|
286
|
+
|
|
287
|
+
def build(self, spec: MenuSpec) -> QMenu:
|
|
288
|
+
menu = QMenu(self.window)
|
|
289
|
+
title = spec.get("title")
|
|
290
|
+
if title:
|
|
291
|
+
menu.setTitle(str(title))
|
|
292
|
+
self._fill(menu, spec.get("items") or [])
|
|
293
|
+
return menu
|
|
294
|
+
|
|
295
|
+
def _fill(self, menu: QMenu, items: Sequence[MenuItem]):
|
|
296
|
+
group: Optional[QActionGroup] = None
|
|
297
|
+
for item in items:
|
|
298
|
+
kind = str(item.get("kind") or "normal")
|
|
299
|
+
if kind == "separator":
|
|
300
|
+
menu.addSeparator()
|
|
301
|
+
continue
|
|
302
|
+
action = QAction(str(item.get("label") or ""), menu)
|
|
303
|
+
action.setData(item.get("id"))
|
|
304
|
+
if item.get("shortcut"):
|
|
305
|
+
action.setShortcut(QKeySequence(str(item["shortcut"])))
|
|
306
|
+
if item.get("disabled"):
|
|
307
|
+
action.setEnabled(False)
|
|
308
|
+
if kind == "check":
|
|
309
|
+
action.setCheckable(True)
|
|
310
|
+
action.setChecked(_as_bool(item.get("checked")))
|
|
311
|
+
elif kind == "radio":
|
|
312
|
+
if group is None:
|
|
313
|
+
group = QActionGroup(menu)
|
|
314
|
+
group.setExclusive(True)
|
|
315
|
+
action.setCheckable(True)
|
|
316
|
+
action.setActionGroup(group)
|
|
317
|
+
action.setChecked(_as_bool(item.get("checked")))
|
|
318
|
+
if item.get("submenu"):
|
|
319
|
+
action.setMenu(self.build({"items": item["submenu"] or []}))
|
|
320
|
+
# 每个 action 自己上报:不依赖 QMenu.triggered
|
|
321
|
+
# (菜单在离屏/被提前关闭时 QMenu 可能已失效,action 仍应可用)
|
|
322
|
+
action.triggered.connect(
|
|
323
|
+
lambda _checked=False, act=action: self._on_triggered(act)
|
|
324
|
+
)
|
|
325
|
+
menu.addAction(action)
|
|
326
|
+
|
|
327
|
+
def _on_triggered(self, action: QAction):
|
|
328
|
+
item_id = action.data()
|
|
329
|
+
menu = action.parent()
|
|
330
|
+
while isinstance(menu, QMenu):
|
|
331
|
+
menu.close()
|
|
332
|
+
menu = menu.parent()
|
|
333
|
+
self.window._active_menu = None
|
|
334
|
+
self.window._emit_menu_selected(
|
|
335
|
+
self.request_id, None if item_id is None else str(item_id)
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class WindowBridge(QObject):
|
|
340
|
+
"""暴露给网页的 `Axon.Window`。
|
|
341
|
+
|
|
342
|
+
这些方法都是同步调用, 但它们必须跑在 Qt 主线程: 控制器默认在线程池里执行,
|
|
343
|
+
所以统一用 `AxonMagicGUI.run(...)` 回主线程, 再等结果。
|
|
344
|
+
"""
|
|
345
|
+
|
|
346
|
+
def __init__(self, window: AxonShellWindow):
|
|
347
|
+
super().__init__()
|
|
348
|
+
self._window = window
|
|
349
|
+
|
|
350
|
+
def _gui(self, func, timeout: float = 5.0):
|
|
351
|
+
return AxonMagicGUI.run(func).result(timeout)
|
|
352
|
+
|
|
353
|
+
# ---------------------------------------------------------------- 只读信息
|
|
354
|
+
@Slot(result="QVariantMap")
|
|
355
|
+
def state(self) -> dict[str, Any]:
|
|
356
|
+
return self._gui(self._window.window_state)
|
|
357
|
+
|
|
358
|
+
@Slot(result="QString")
|
|
359
|
+
def platform(self) -> str:
|
|
360
|
+
return PLATFORM
|
|
361
|
+
|
|
362
|
+
@Slot(result=bool)
|
|
363
|
+
def isMaximized(self) -> bool: # noqa: N802
|
|
364
|
+
return self._gui(self._window.isMaximized)
|
|
365
|
+
|
|
366
|
+
@Slot(result="QVariantMap")
|
|
367
|
+
def frame(self) -> dict[str, Any]:
|
|
368
|
+
def read():
|
|
369
|
+
geo = self._window.frameGeometry()
|
|
370
|
+
return {
|
|
371
|
+
"x": geo.x(),
|
|
372
|
+
"y": geo.y(),
|
|
373
|
+
"width": geo.width(),
|
|
374
|
+
"height": geo.height(),
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
return self._gui(read)
|
|
378
|
+
|
|
379
|
+
# ---------------------------------------------------------------- 窗口按钮
|
|
380
|
+
@Slot()
|
|
381
|
+
def minimize(self):
|
|
382
|
+
self._gui(self._window.showMinimized)
|
|
383
|
+
|
|
384
|
+
@Slot()
|
|
385
|
+
def maximize(self):
|
|
386
|
+
self._gui(self._window.showMaximized)
|
|
387
|
+
|
|
388
|
+
@Slot()
|
|
389
|
+
def restore(self):
|
|
390
|
+
self._gui(self._window.showNormal)
|
|
391
|
+
|
|
392
|
+
@Slot(result=bool)
|
|
393
|
+
def toggleMaximize(self) -> bool: # noqa: N802
|
|
394
|
+
def toggle():
|
|
395
|
+
if self._window.isMaximized():
|
|
396
|
+
self._window.showNormal()
|
|
397
|
+
else:
|
|
398
|
+
self._window.showMaximized()
|
|
399
|
+
return self._window.isMaximized()
|
|
400
|
+
|
|
401
|
+
return bool(self._gui(toggle))
|
|
402
|
+
|
|
403
|
+
@Slot()
|
|
404
|
+
def toggleFullScreen(self): # noqa: N802
|
|
405
|
+
def toggle():
|
|
406
|
+
if self._window.isFullScreen():
|
|
407
|
+
self._window.showNormal()
|
|
408
|
+
else:
|
|
409
|
+
self._window.showFullScreen()
|
|
410
|
+
|
|
411
|
+
self._gui(toggle)
|
|
412
|
+
|
|
413
|
+
@Slot()
|
|
414
|
+
def close(self):
|
|
415
|
+
self._gui(self._window.close)
|
|
416
|
+
|
|
417
|
+
@Slot(bool)
|
|
418
|
+
def setAlwaysOnTop(self, on: bool): # noqa: N802
|
|
419
|
+
value = _as_bool(on)
|
|
420
|
+
|
|
421
|
+
def apply():
|
|
422
|
+
flags = self._window.windowFlags()
|
|
423
|
+
if value:
|
|
424
|
+
flags |= Qt.WindowType.WindowStaysOnTopHint
|
|
425
|
+
else:
|
|
426
|
+
flags &= ~Qt.WindowType.WindowStaysOnTopHint
|
|
427
|
+
visible = self._window.isVisible()
|
|
428
|
+
self._window.setWindowFlags(flags)
|
|
429
|
+
if visible:
|
|
430
|
+
self._window.show()
|
|
431
|
+
|
|
432
|
+
self._gui(apply)
|
|
433
|
+
|
|
434
|
+
@Slot(str)
|
|
435
|
+
def setTitle(self, title: str): # noqa: N802
|
|
436
|
+
self._gui(lambda: self._window.setWindowTitle(str(title)))
|
|
437
|
+
|
|
438
|
+
# ---------------------------------------------------------------- 拖动/缩放
|
|
439
|
+
@Slot("QVariantList")
|
|
440
|
+
def setDragRegions(self, *regions): # noqa: N802
|
|
441
|
+
"""网页上报可拖拽区域。
|
|
442
|
+
|
|
443
|
+
两种写法都收:`setDragRegions([{...}, {...}])`(一个数组参数)与
|
|
444
|
+
`setDragRegions({...}, {...})`(摊开)。前者在旧版 axon-gui 上会被
|
|
445
|
+
当成打包写法展开,所以这里两种形状都要能接。
|
|
446
|
+
"""
|
|
447
|
+
if len(regions) == 1 and isinstance(regions[0], (list, tuple)):
|
|
448
|
+
regions = tuple(regions[0])
|
|
449
|
+
data = [dict(r) for r in regions if isinstance(r, dict)]
|
|
450
|
+
self._gui(lambda: self._window.set_drag_regions(data))
|
|
451
|
+
|
|
452
|
+
@Slot(result=bool)
|
|
453
|
+
def beginSystemMove(self) -> bool: # noqa: N802
|
|
454
|
+
"""交给系统拖窗(X11/macOS 可用);Windows 走原生命中测试,不需要它。"""
|
|
455
|
+
|
|
456
|
+
def begin():
|
|
457
|
+
handle = self._window.windowHandle()
|
|
458
|
+
if handle is None:
|
|
459
|
+
return False
|
|
460
|
+
return bool(handle.startSystemMove())
|
|
461
|
+
|
|
462
|
+
try:
|
|
463
|
+
return bool(self._gui(begin))
|
|
464
|
+
except Exception:
|
|
465
|
+
return False
|
|
466
|
+
|
|
467
|
+
@Slot(int, int)
|
|
468
|
+
def moveTo(self, x: int, y: int):
|
|
469
|
+
self._gui(lambda: self._window.move(int(x), int(y)))
|
|
470
|
+
|
|
471
|
+
@Slot(int, int)
|
|
472
|
+
def resizeTo(self, width: int, height: int): # noqa: N802
|
|
473
|
+
def apply():
|
|
474
|
+
w = max(int(width), self._window.minimumWidth())
|
|
475
|
+
h = max(int(height), self._window.minimumHeight())
|
|
476
|
+
self._window.resize(w, h)
|
|
477
|
+
|
|
478
|
+
self._gui(apply)
|
|
479
|
+
|
|
480
|
+
@Slot(int, int)
|
|
481
|
+
def moveBy(self, dx: int, dy: int):
|
|
482
|
+
def apply():
|
|
483
|
+
self._window.move(self._window.x() + int(dx), self._window.y() + int(dy))
|
|
484
|
+
|
|
485
|
+
self._gui(apply)
|
|
486
|
+
|
|
487
|
+
# ---------------------------------------------------------------- 菜单
|
|
488
|
+
@Slot("QVariantMap", result="QString")
|
|
489
|
+
def popupMenu(self, spec, x=None, y=None): # noqa: N802
|
|
490
|
+
"""弹出原生菜单,不阻塞;选中项通过 `window:menu` 事件回来。
|
|
491
|
+
|
|
492
|
+
x / y 是相对窗口左上角的坐标,省略时用鼠标位置。
|
|
493
|
+
"""
|
|
494
|
+
payload: MenuSpec = dict(spec or {})
|
|
495
|
+
self._window._menu_seq += 1
|
|
496
|
+
request_id = f"menu-{self._window._menu_seq}"
|
|
497
|
+
|
|
498
|
+
def show():
|
|
499
|
+
if self._window._active_menu is not None:
|
|
500
|
+
self._window._active_menu.close()
|
|
501
|
+
self._window._active_menu = None
|
|
502
|
+
builder = _MenuBuilder(self._window, request_id)
|
|
503
|
+
menu = builder.build(payload)
|
|
504
|
+
menu.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
|
|
505
|
+
self._window._active_menu = menu
|
|
506
|
+
self._window._last_menu = menu
|
|
507
|
+
if payload.get("title"):
|
|
508
|
+
menu.setTitle(str(payload["title"]))
|
|
509
|
+
if isinstance(x, (int, float)) and isinstance(y, (int, float)):
|
|
510
|
+
anchor = self._window.mapToGlobal(QPoint(int(x), int(y)))
|
|
511
|
+
else:
|
|
512
|
+
anchor = QCursor.pos()
|
|
513
|
+
menu.popup(anchor)
|
|
514
|
+
|
|
515
|
+
AxonMagicGUI.run(show)
|
|
516
|
+
return request_id
|
|
517
|
+
|
|
518
|
+
@Slot()
|
|
519
|
+
def closeMenu(self): # noqa: N802
|
|
520
|
+
def hide():
|
|
521
|
+
if self._window._active_menu is not None:
|
|
522
|
+
self._window._active_menu.close()
|
|
523
|
+
self._window._active_menu = None
|
|
524
|
+
|
|
525
|
+
self._gui(hide)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
# 旧名字,方便迁移
|
|
529
|
+
AxonWindow = AxonShellWindow
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: axon-shell
|
|
3
|
+
Version: 0.2.1
|
|
4
|
+
Summary: The native window layer for Axon apps: frameless window, drag regions, window control, native menu bridge. No UI, no CSS.
|
|
5
|
+
Author: STofone
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/AxonGUI/AxonShell
|
|
8
|
+
Project-URL: Homepage, https://github.com/AxonGUI/AxonShell
|
|
9
|
+
Project-URL: Issues, https://github.com/AxonGUI/AxonShell/issues
|
|
10
|
+
Keywords: axon,axon-gui,pyside6,qt,desktop,frameless-window,window-controls,native-menu
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Topic :: Desktop Environment :: Window Managers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Requires-Python: >=3.12
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: axon-gui>=5.3.4
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
<p align="center">
|
|
22
|
+
<img src="assets/axon-mark.svg" width="72" alt="Axon" />
|
|
23
|
+
</p>
|
|
24
|
+
|
|
25
|
+
# axon-shell
|
|
26
|
+
|
|
27
|
+
给 [Axon](https://github.com/AxonGUI/Axon) 应用补上**网页做不了的那一层**:无边框窗口、可拖动的区域、窗口按钮的原生行为、窗口状态事件、原生菜单桥。
|
|
28
|
+
|
|
29
|
+
这个包**不含任何界面**——没有标题栏、没有菜单条、没有按钮样式、没有主题、没有一行 CSS。标题栏长什么样、菜单怎么排、按钮用什么图标,全是你自己在页面里写的;它只负责让这些东西真的能拖动、能最小化、能关掉。
|
|
30
|
+
|
|
31
|
+
<sub>简体中文 · [English](README.en.md)</sub>
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## 为什么需要它
|
|
36
|
+
|
|
37
|
+
浏览器里做不出下面三件事,这三件也只有它们需要 Python:
|
|
38
|
+
|
|
39
|
+
1. **无边框窗口**:去掉系统标题栏(`FramelessWindowHint`),整块界面归你;
|
|
40
|
+
2. **拖动与缩放仍然有效**:Windows 上必须接管 `WM_NCHITTEST` 返回 `HTCAPTION`,系统才会给你真实的拖动、双击最大化、拖到边缘贴靠、四边缩放;Linux/macOS 上则退化成 `startSystemMove()` 与指针增量;
|
|
41
|
+
3. **控制窗口**:最小化 / 最大化 / 还原 / 关闭 / 置顶 / 改尺寸,以及「窗口状态变了」的事件。
|
|
42
|
+
|
|
43
|
+
其余全部是前端的事。所以这个包很小,也故意很小:你随时可以不用它,自己写 `Axon.Window` 的调用。
|
|
44
|
+
|
|
45
|
+
<p align="center"><img src="assets/screenshot.png" alt="示例:只有一条可拖动的顶栏和三个窗口按钮" width="760"></p>
|
|
46
|
+
|
|
47
|
+
## 安装
|
|
48
|
+
|
|
49
|
+
`axon-gui` 与 `axon-shell` 都还没上 PyPI(上架后是两条 `pip install`)。现在:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
# 1) 框架本体:Release 里的 wheel(自带 PySide6)
|
|
53
|
+
pip install "https://github.com/AxonGUI/Axon/releases/download/v5.3.4/axon_gui-5.3.4-py3-none-any.whl"
|
|
54
|
+
|
|
55
|
+
# 2) 外观层。--no-deps:PyPI 上还没有 axon-gui,让 pip 自己解析会 404
|
|
56
|
+
pip install --no-deps "git+https://github.com/AxonGUI/AxonShell.git"
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
装完 `python -c "import axon, axon_shell"` 不报错就对了。
|
|
60
|
+
|
|
61
|
+
## 三十秒接上
|
|
62
|
+
|
|
63
|
+
**Python 侧**——只换窗口类:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
import sys
|
|
67
|
+
from PySide6.QtWidgets import QApplication
|
|
68
|
+
from axon import AxonController, AxonMagicGUI
|
|
69
|
+
from axon_shell import AxonShellWindow
|
|
70
|
+
|
|
71
|
+
WEB = "MainView"
|
|
72
|
+
|
|
73
|
+
@AxonController(WEB, id="App")
|
|
74
|
+
class App:
|
|
75
|
+
def hello(self, name: str) -> str:
|
|
76
|
+
return f"你好,{name}"
|
|
77
|
+
|
|
78
|
+
def main() -> int:
|
|
79
|
+
app = QApplication(sys.argv[:1])
|
|
80
|
+
AxonMagicGUI() # AxonShellWindow 内部要用
|
|
81
|
+
window = AxonShellWindow(WEB, "http://127.0.0.1:8000/", title="我的应用")
|
|
82
|
+
window.show()
|
|
83
|
+
return app.exec()
|
|
84
|
+
|
|
85
|
+
raise SystemExit(main())
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
**页面侧**——写自己的标题栏,标两个属性就活了:
|
|
89
|
+
|
|
90
|
+
```html
|
|
91
|
+
<script src="/axon.umd.cjs"></script> <!-- axon-gui 的 UMD 产物 -->
|
|
92
|
+
<script src="/axon-shell/shell.js"></script> <!-- 这个包唯一的 JS 文件 -->
|
|
93
|
+
|
|
94
|
+
<header data-axon-drag> <!-- 这块区域可以拖动窗口 -->
|
|
95
|
+
<span>我的应用</span>
|
|
96
|
+
<button data-axon-window="min">–</button> <!-- 三个按钮的行为自动接上 -->
|
|
97
|
+
<button data-axon-window="max">□</button>
|
|
98
|
+
<button data-axon-window="close">×</button>
|
|
99
|
+
</header>
|
|
100
|
+
|
|
101
|
+
<script>
|
|
102
|
+
(async () => {
|
|
103
|
+
await window.axon.AxonInit();
|
|
104
|
+
window.AxonShell.init(); // 接上拖拽区、按钮、状态事件
|
|
105
|
+
window.AxonShell.window.onState(s => console.log(s.frame));
|
|
106
|
+
})();
|
|
107
|
+
</script>
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`shell.js` 从包里取,静态服务挂到 `/axon-shell/` 即可:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from axon_shell import assets_dir
|
|
114
|
+
print(assets_dir()) # .../axon_shell/assets
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
> `data-axon-drag` 里面的按钮、输入框、链接会自动被排除在拖动区之外;
|
|
118
|
+
> 不想被自动排除的,加 `data-axon-no-drag` 也可以反过来用。
|
|
119
|
+
|
|
120
|
+
## 它提供什么
|
|
121
|
+
|
|
122
|
+
### Python
|
|
123
|
+
|
|
124
|
+
| 名字 | 说明 |
|
|
125
|
+
| --- | --- |
|
|
126
|
+
| `AxonShellWindow(web_name, url, title=…, size=…, min_size=…, options=…)` | 继承 `AxonGUI`,去系统边框、设图标、初始尺寸不超出屏幕,注册 `Axon.Window` |
|
|
127
|
+
| `Axon.Window`(控制器) | `minimize` `maximize` `restore` `toggleMaximize` `toggleFullScreen` `close` `setAlwaysOnTop` `setTitle` `setDragRegions` `beginSystemMove` `moveTo` `resizeTo` `moveBy` `frame` `state` `platform` `popupMenu` `closeMenu` |
|
|
128
|
+
| 事件 `window:state` | 最大化 / 全屏 / 位置尺寸变化(60ms 合并后推一次) |
|
|
129
|
+
| 事件 `window:menu` | 原生菜单被选中:`{requestId, id}` |
|
|
130
|
+
| `assets_dir()` | `assets` 目录,里面只有 `shell.js`、图标 |
|
|
131
|
+
|
|
132
|
+
`Axon.Window` 是从 `axon-gui` 的通道调进去的,所以页面里也能直接写
|
|
133
|
+
`await Axon.Window.resizeTo(1200, 800)`,不必经过这个 JS 文件。
|
|
134
|
+
|
|
135
|
+
### 前端(`window.AxonShell`)
|
|
136
|
+
|
|
137
|
+
| 名字 | 说明 |
|
|
138
|
+
| --- | --- |
|
|
139
|
+
| `init(opts?)` | 幂等安装:`data-axon-window` 点击、`[data-axon-drag]` 上报、状态/菜单事件订阅 |
|
|
140
|
+
| `drag.refresh()` / `drag.regions()` | 重新计算拖动区(布局变了要调);返回 `[{left,top,width,height}, …]` |
|
|
141
|
+
| `window.state()` | `{platform, frame:{x,y,width,height}, maximized, fullScreen}` |
|
|
142
|
+
| `window.minimize()` `toggleMaximize()` `close()` `setTitle()` `setAlwaysOnTop()` `refresh()` | 常用窗口操作 |
|
|
143
|
+
| `window.onState(cb)` | 订阅窗口状态 |
|
|
144
|
+
| `menu.native(spec)` / `menu.onSelect(cb)` | 让 Qt 弹原生菜单;`spec` 是 `{id?, title?, items:[…]}`,每项 `{id,label,shortcut?,kind?:separator/check/radio,checked?,disabled?,items?}` |
|
|
145
|
+
| `enableFallback()` | 非 win32/darwin 上补拖动与 8 向缩放(`init()` 会自动开) |
|
|
146
|
+
|
|
147
|
+
`init()` 之后 `<html>` 上会有 `data-axon-platform="win32|linux|darwin"` 与
|
|
148
|
+
`data-axon-maximized="true|false"`,你在 CSS 里可以据此调布局(比如去掉圆角)。
|
|
149
|
+
|
|
150
|
+
## 各平台怎么动窗口
|
|
151
|
+
|
|
152
|
+
- **Windows**:Python 接管 `WM_NCHITTEST`——上报的拖动区返回 `HTCAPTION`,边框 6px 返回 `HTLEFT/HTRIGHT/HTTOP/...`。拖动、双击最大化、贴边、四边缩放全是系统行为,没有 JS 手搓的延迟。
|
|
153
|
+
- **Linux / macOS**:`startSystemMove()`(X11/macOS 支持);不支持时 `shell.js` 用指针增量 + `moveTo/resizeTo` 兜底,8 向缩放靠 8 条透明热区。
|
|
154
|
+
|
|
155
|
+
所以拖动区只要「标出来」就行,不用写 `-webkit-app-region`(Qt 也不认这个)。
|
|
156
|
+
|
|
157
|
+
## 示例
|
|
158
|
+
|
|
159
|
+
`examples/basic/` 是一个最小应用:一条可拖动的顶栏、三个窗口按钮、三行演示按钮。
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
cd examples/basic
|
|
163
|
+
python main.py # 需要先 npm install axon-gui(或设 AXON_BUNDLE 指到 axon.umd.cjs)
|
|
164
|
+
python main.py --smoke # 无头自检
|
|
165
|
+
python ../../tests/verify.py # 端到端:拖拽区、按钮、状态、缩放、Python 往返、原生菜单
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
想看「照着这个自己写一整套 VSCode 外观」的完整例子,看
|
|
169
|
+
[Axon 文档里的窗口外观页](https://axongui.github.io/Axon/guide/window-chrome)。
|
|
170
|
+
|
|
171
|
+
## 验证
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
python examples/basic/main.py --smoke # 连通 + 拖拽区 + 窗口
|
|
175
|
+
python tests/verify.py # 11 条断言,退出码 = 失败数
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## 版本
|
|
179
|
+
|
|
180
|
+
`0.2.0` —— 从「带皮肤」收缩成「只做原生那层」。之前的 0.1.x 包含标题栏/菜单/主题,
|
|
181
|
+
现在都删了:那些东西你写得比我好。
|
|
182
|
+
|
|
183
|
+
MIT © STofone
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
axon_shell/__init__.py,sha256=UCPaPDaABy1wgQLa9VzSg4WyNUYh_yEiJnx8-C3M6EU,442
|
|
2
|
+
axon_shell/window.py,sha256=_FbwUBLFaF9E4_vJy0JF5WPwJ4kHVHRj1_rjG7ax3as,18397
|
|
3
|
+
axon_shell/assets/axon.ico,sha256=na_Qgb-aSmQk4voImwxbNHYn8BbXYs9A_xs98yj4SLs,372526
|
|
4
|
+
axon_shell/assets/icon-256.png,sha256=RD0XLJFKu3b-I7PaS1GIDV9S2MftjxCba7sRyF7dA0c,7550
|
|
5
|
+
axon_shell/assets/shell.js,sha256=jFSf7mXMeH2bx2Xg5AV798l7ye2gEepgJoE64YY5_Ho,12495
|
|
6
|
+
axon_shell-0.2.1.dist-info/licenses/LICENSE,sha256=zkGqfEq2kKsrsmKN-HNQLVrdE9pDslVSYcCw_R5U2AQ,1064
|
|
7
|
+
axon_shell-0.2.1.dist-info/METADATA,sha256=0d4oQxxdey3L4f_Sr0HzUBPAweUv1bb3_DaVkwu9aUE,8079
|
|
8
|
+
axon_shell-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
axon_shell-0.2.1.dist-info/top_level.txt,sha256=-tIfPCGOFY6JxDRu7i7TOayAsgU6DOM1KCjNazGlKDI,11
|
|
10
|
+
axon_shell-0.2.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 STofone
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
axon_shell
|