hivedesk 1.0.0 → 1.0.1

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.
Files changed (89) hide show
  1. package/CHANGELOG.md +122 -111
  2. package/desktop/controller.js +85 -7
  3. package/desktop/native.js +4 -1
  4. package/desktop/release-notes/1.0.1.json +12 -0
  5. package/desktop/scripts/package.mjs +134 -123
  6. package/desktop/shell.html +5 -2
  7. package/desktop/workarea.js +440 -0
  8. package/i18n/de.json +247 -4
  9. package/i18n/en.json +247 -4
  10. package/i18n/es.json +247 -4
  11. package/i18n/fr.json +247 -4
  12. package/i18n/it.json +247 -4
  13. package/i18n/ja.json +247 -4
  14. package/i18n/ko.json +247 -4
  15. package/i18n/parts/downloads.de.json +29 -0
  16. package/i18n/parts/downloads.en.json +29 -0
  17. package/i18n/parts/downloads.es.json +29 -0
  18. package/i18n/parts/downloads.fr.json +29 -0
  19. package/i18n/parts/downloads.it.json +29 -0
  20. package/i18n/parts/downloads.ja.json +29 -0
  21. package/i18n/parts/downloads.ko.json +29 -0
  22. package/i18n/parts/downloads.pt-BR.json +29 -0
  23. package/i18n/parts/downloads.ru.json +29 -0
  24. package/i18n/parts/downloads.zh-CN.json +29 -0
  25. package/i18n/parts/office.de.json +184 -0
  26. package/i18n/parts/office.en.json +184 -0
  27. package/i18n/parts/office.es.json +184 -0
  28. package/i18n/parts/office.fr.json +184 -0
  29. package/i18n/parts/office.it.json +184 -0
  30. package/i18n/parts/office.ja.json +184 -0
  31. package/i18n/parts/office.ko.json +184 -0
  32. package/i18n/parts/office.pt-BR.json +184 -0
  33. package/i18n/parts/office.ru.json +184 -0
  34. package/i18n/parts/office.zh-CN.json +184 -0
  35. package/i18n/pt-BR.json +247 -4
  36. package/i18n/ru.json +247 -4
  37. package/i18n/zh-CN.json +247 -4
  38. package/package.json +3 -2
  39. package/src/brain/manager.js +23 -7
  40. package/src/brain/models.js +146 -30
  41. package/src/brain/runtime.js +61 -13
  42. package/src/crew/domains/flow.js +2 -1
  43. package/src/crew/engine.js +172 -22
  44. package/src/crew/legacy.js +72 -0
  45. package/src/crew/planner.js +14 -1
  46. package/src/crew/talk.js +110 -3
  47. package/src/crew/taskgraph.js +12 -2
  48. package/src/crew/worker.js +60 -2
  49. package/src/index.js +4 -1
  50. package/src/phone/hub.js +15 -3
  51. package/src/phone/port.js +1 -1
  52. package/src/replay/reduce.js +1 -0
  53. package/src/tools/check.js +2 -0
  54. package/src/voice/index.js +1 -1
  55. package/src/voice/piper.js +10 -4
  56. package/src/voice/store.js +2 -1
  57. package/src/voice/whisper.js +63 -25
  58. package/ui/city/activity.js +4 -1
  59. package/ui/city/city.js +5 -5
  60. package/ui/city/scene.js +2 -1
  61. package/ui/css/hive.css +20 -0
  62. package/ui/js/dock.js +2 -2
  63. package/ui/js/dom.js +23 -18
  64. package/ui/js/i18n.js +12 -0
  65. package/ui/js/main.js +43 -3
  66. package/ui/js/md.js +130 -0
  67. package/ui/js/net.js +6 -0
  68. package/ui/js/palette.js +2 -2
  69. package/ui/js/store.js +20 -2
  70. package/ui/js/topbar.js +2 -2
  71. package/ui/js/voice/index.js +3 -2
  72. package/ui/js/widgets/brief.js +28 -10
  73. package/ui/js/widgets/chat.js +16 -4
  74. package/ui/js/widgets/files.js +3 -3
  75. package/ui/js/widgets/memory.js +3 -3
  76. package/ui/js/widgets/replay.js +3 -3
  77. package/ui/js/widgets/settings.js +2 -2
  78. package/ui/js/widgets/timeline.js +2 -2
  79. package/ui/js/widgets/worker.js +17 -6
  80. package/ui/models/index.js +3 -2
  81. package/ui/models/window.js +2 -2
  82. package/ui/office/office.js +662 -623
  83. package/ui/office/popout.js +4 -3
  84. package/ui/office/scene.js +47 -28
  85. package/ui/phone/core/client.js +11 -5
  86. package/ui/phone/desktop.js +2 -1
  87. package/ui/widget.html +8 -8
  88. package/ui/widget.js +35 -20
  89. package/ui/workbench/searchview.js +3 -3
@@ -0,0 +1,440 @@
1
+ // The work area maximize of the custom (borderless) frame, and keeping the window on a display.
2
+ //
3
+ // Why: on Windows the custom frame is a window without WS_CAPTION and WS_THICKFRAME. ShowWindow(SW_MAXIMIZE)
4
+ // on such a window fills the whole monitor rectangle, so the taskbar is covered. Instead of the native
5
+ // maximize, the controller places the window exactly on rcWork of its monitor and remembers the bounds to
6
+ // restore. macOS keeps the native maximize: Neutralino calls [NSWindow zoom:], which uses the screen's
7
+ // visibleFrame (no dock, no menu bar) also for a borderless window. Linux keeps gtk_window_maximize, which
8
+ // the window manager fits inside the panels (_NET_WORKAREA).
9
+ //
10
+ // Units. Neutralino 5.6 on Windows makes its process per monitor DPI aware (webview.h setDpi calls
11
+ // SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE)), and window.move, window.setSize,
12
+ // window.getSize and window.getPosition go straight to MoveWindow, SetWindowPos and GetWindowRect with no
13
+ // scaling. So on Windows every value the runtime takes or returns is in physical pixels, at 100, 125 and 150
14
+ // percent alike (the shell page multiplies its CSS pixels by devicePixelRatio before it moves the window
15
+ // for the same reason). The display helper below asks for per monitor awareness too, so rcWork comes back in
16
+ // physical pixels and is used as is. If that request fails (an old Windows, a policy), Windows hands a DPI
17
+ // unaware process rectangles scaled to 96 DPI; the display mode (EnumDisplaySettings) always reports the
18
+ // real pixels and position of the monitor, so the factor pelsWidth / monitorWidth turns those rectangles
19
+ // back into physical pixels (normalizeDisplays). On macOS and Linux the runtime works in points and logical
20
+ // pixels and the native maximize is kept, so nothing is converted there.
21
+ import { spawn } from 'node:child_process';
22
+ import { encodeCommand } from '../src/compute/win-gpu.js';
23
+
24
+ /** @typedef {{ x: number, y: number, width: number, height: number }} Rect */
25
+ /** @typedef {{ monitor: Rect, work: Rect, primary: boolean, scale: number }} Display */
26
+
27
+ const isNum = Number.isFinite;
28
+ export const validRect = (r) => !!r && [r.x, r.y, r.width, r.height].every(isNum) && r.width > 0 && r.height > 0;
29
+ const roundRect = (r) => ({ x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) });
30
+
31
+ /** The area two rectangles share (0 when they do not touch). */
32
+ export function overlap(a, b) {
33
+ const w = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);
34
+ const h = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);
35
+ return w > 0 && h > 0 ? w * h : 0;
36
+ }
37
+
38
+ /**
39
+ * Turns the helper's answer into displays in physical pixels.
40
+ * A rectangle that came back scaled to 96 DPI (the helper could not get DPI awareness) is mapped onto the
41
+ * real pixels of the display mode: physical = modePosition + (logical - monitorOrigin) * pelsWidth / monitorWidth.
42
+ * @param {any} raw { aware, list: [{ monitor, work, primary, dpi, mode: { x, y, width, height } }] }
43
+ * @returns {Display[]}
44
+ */
45
+ export function normalizeDisplays(raw) {
46
+ const list = Array.isArray(raw?.list) ? raw.list : Array.isArray(raw) ? raw : raw?.list ? [raw.list] : [];
47
+ const out = [];
48
+ for (const d of list) {
49
+ if (!validRect(d?.monitor) || !validRect(d?.work)) continue;
50
+ let monitor = roundRect(d.monitor);
51
+ let work = roundRect(d.work);
52
+ const mode = validRect(d.mode) ? d.mode : null;
53
+ const k = mode ? mode.width / monitor.width : 1;
54
+ if (mode && Math.abs(k - 1) > 0.01 && k > 0.2 && k < 8) {
55
+ const map = (r) => roundRect({ x: mode.x + (r.x - monitor.x) * k, y: mode.y + (r.y - monitor.y) * k, width: r.width * k, height: r.height * k });
56
+ work = map(work);
57
+ monitor = map(monitor);
58
+ }
59
+ const dpi = isNum(d.dpi) && d.dpi > 0 ? d.dpi : 96 * (mode && k > 0.2 && k < 8 ? k : 1);
60
+ out.push({ monitor, work, primary: d.primary === true, scale: Math.round((dpi / 96) * 100) / 100 });
61
+ }
62
+ return out;
63
+ }
64
+
65
+ /** Logical (96 DPI) pixels of a display to physical pixels and back, for values the shell page sends in CSS pixels. */
66
+ export const toPhysical = (v, scale) => Math.round(v * (scale > 0 ? scale : 1));
67
+ export const toLogical = (v, scale) => Math.round(v / (scale > 0 ? scale : 1));
68
+
69
+ /**
70
+ * The display a window is on, like MonitorFromWindow(MONITOR_DEFAULTTONEAREST): the one sharing the largest
71
+ * area with the window, else the one nearest to its center, else the primary one.
72
+ * @param {Display[]} displays @param {Rect} rect
73
+ */
74
+ export function pickDisplay(displays, rect) {
75
+ if (!displays?.length) return null;
76
+ if (!validRect(rect)) return displays.find((d) => d.primary) || displays[0];
77
+ let best = null;
78
+ let bestArea = 0;
79
+ for (const d of displays) {
80
+ const a = overlap(d.monitor, rect);
81
+ if (a > bestArea) { best = d; bestArea = a; }
82
+ }
83
+ if (best) return best;
84
+ const cx = rect.x + rect.width / 2;
85
+ const cy = rect.y + rect.height / 2;
86
+ let dist = Infinity;
87
+ for (const d of displays) {
88
+ const m = d.monitor;
89
+ const dx = Math.max(m.x - cx, 0, cx - (m.x + m.width));
90
+ const dy = Math.max(m.y - cy, 0, cy - (m.y + m.height));
91
+ const dd = dx * dx + dy * dy;
92
+ if (dd < dist) { dist = dd; best = d; }
93
+ }
94
+ return best;
95
+ }
96
+
97
+ /** A width x height rectangle in the middle of a work area (never larger than it). */
98
+ export function centerIn(work, width, height) {
99
+ const w = Math.round(Math.min(width, work.width));
100
+ const h = Math.round(Math.min(height, work.height));
101
+ return { x: Math.round(work.x + (work.width - w) / 2), y: Math.round(work.y + (work.height - h) / 2), width: w, height: h };
102
+ }
103
+
104
+ /** The bounds of the work area maximize: exactly the work area of the window's display. */
105
+ export function workAreaBounds(displays, rect) {
106
+ const d = pickDisplay(displays, rect);
107
+ return d ? { ...d.work } : null;
108
+ }
109
+
110
+ /**
111
+ * True when the title bar of a window is reachable: at least `grab` pixels of its top strip
112
+ * (`bar` pixels high) lie inside the work area of one display.
113
+ */
114
+ export function reachable(displays, rect, { bar = 36, grab = 120 } = {}) {
115
+ if (!validRect(rect)) return false;
116
+ const strip = { x: rect.x, y: rect.y, width: rect.width, height: Math.min(bar, rect.height) };
117
+ return displays.some((d) => {
118
+ const w = Math.min(strip.x + strip.width, d.work.x + d.work.width) - Math.max(strip.x, d.work.x);
119
+ const top = rect.y >= d.work.y && rect.y < d.work.y + d.work.height - Math.min(bar, rect.height) / 2;
120
+ return w >= Math.min(grab, rect.width) && top;
121
+ });
122
+ }
123
+
124
+ /**
125
+ * Keeps saved or restored bounds on screen: no larger than the work area of the chosen display, and
126
+ * moved to the center of that work area when the title bar would be off every display.
127
+ * @param {Display[]} displays @param {Rect} rect @param {{ width: number, height: number }} [min]
128
+ * @returns {Rect}
129
+ */
130
+ export function clampToDisplays(displays, rect, min = { width: 0, height: 0 }) {
131
+ if (!displays?.length || !validRect(rect)) return rect;
132
+ const d = pickDisplay(displays, rect) || displays[0];
133
+ const wa = d.work;
134
+ const width = Math.max(Math.min(rect.width, wa.width), Math.min(min.width || 0, wa.width));
135
+ const height = Math.max(Math.min(rect.height, wa.height), Math.min(min.height || 0, wa.height));
136
+ let out = { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(width), height: Math.round(height) };
137
+ if (!reachable(displays, out)) {
138
+ const home = overlap(d.monitor, rect) > 0 ? d : (displays.find((x) => x.primary) || d);
139
+ out = centerIn(home.work, out.width, out.height);
140
+ }
141
+ return out;
142
+ }
143
+
144
+ /** True when two rectangles are the same within `tol` pixels on every side. */
145
+ export function sameRect(a, b, tol = 1) {
146
+ return validRect(a) && validRect(b) && Math.abs(a.x - b.x) <= tol && Math.abs(a.y - b.y) <= tol
147
+ && Math.abs(a.width - b.width) <= tol && Math.abs(a.height - b.height) <= tol;
148
+ }
149
+
150
+ // One JSON line per "displays" request. The type is compiled once per helper process.
151
+ export const WIN_DISPLAYS_SCRIPT = String.raw`
152
+ $ErrorActionPreference = 'Stop'
153
+ $ok = $false
154
+ try {
155
+ Add-Type -TypeDefinition @'
156
+ using System;
157
+ using System.Text;
158
+ using System.Collections.Generic;
159
+ using System.Runtime.InteropServices;
160
+ public static class HdDisplays {
161
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
162
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
163
+ public struct MONITORINFOEX { public int cbSize; public RECT rcMonitor; public RECT rcWork; public uint dwFlags;
164
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szDevice; }
165
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
166
+ public struct DEVMODE {
167
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName;
168
+ public short dmSpecVersion, dmDriverVersion, dmSize, dmDriverExtra; public int dmFields;
169
+ public int dmPositionX, dmPositionY, dmDisplayOrientation, dmDisplayFixedOutput;
170
+ public short dmColor, dmDuplex, dmYResolution, dmTTOption, dmCollate;
171
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName;
172
+ public short dmLogPixels; public int dmBitsPerPel, dmPelsWidth, dmPelsHeight, dmDisplayFlags, dmDisplayFrequency;
173
+ public int dmICMMethod, dmICMIntent, dmMediaType, dmDitherType, dmReserved1, dmReserved2, dmPanningWidth, dmPanningHeight;
174
+ }
175
+ delegate bool EnumProc(IntPtr hMonitor, IntPtr hdc, IntPtr rect, IntPtr data);
176
+ [DllImport("user32.dll")] static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr clip, EnumProc proc, IntPtr data);
177
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFOEX info);
178
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern bool EnumDisplaySettings(string device, int mode, ref DEVMODE dm);
179
+ [DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr ctx);
180
+ [DllImport("user32.dll")] static extern bool SetProcessDPIAware();
181
+ [DllImport("shcore.dll")] static extern int SetProcessDpiAwareness(int value);
182
+ [DllImport("shcore.dll")] static extern int GetDpiForMonitor(IntPtr hMonitor, int type, out uint x, out uint y);
183
+ static bool Aware() {
184
+ try { if (SetThreadDpiAwarenessContext(new IntPtr(-4)) != IntPtr.Zero) return true; } catch { }
185
+ try { int hr = SetProcessDpiAwareness(2); if (hr == 0 || hr == unchecked((int)0x80070005)) return true; } catch { }
186
+ try { return SetProcessDPIAware(); } catch { return false; }
187
+ }
188
+ static string R(RECT r) { return "{\"x\":" + r.Left + ",\"y\":" + r.Top + ",\"width\":" + (r.Right - r.Left) + ",\"height\":" + (r.Bottom - r.Top) + "}"; }
189
+ public static string List() {
190
+ bool aware = Aware();
191
+ List<string> items = new List<string>();
192
+ EnumProc proc = delegate (IntPtr h, IntPtr hdc, IntPtr rect, IntPtr data) {
193
+ MONITORINFOEX mi = new MONITORINFOEX(); mi.cbSize = Marshal.SizeOf(typeof(MONITORINFOEX));
194
+ if (!GetMonitorInfo(h, ref mi)) return true;
195
+ StringBuilder s = new StringBuilder();
196
+ s.Append("{\"monitor\":").Append(R(mi.rcMonitor)).Append(",\"work\":").Append(R(mi.rcWork));
197
+ s.Append(",\"primary\":").Append((mi.dwFlags & 1) != 0 ? "true" : "false");
198
+ try { uint dx, dy; if (GetDpiForMonitor(h, 0, out dx, out dy) == 0) s.Append(",\"dpi\":").Append(dx); } catch { }
199
+ DEVMODE dm = new DEVMODE(); dm.dmSize = (short)Marshal.SizeOf(typeof(DEVMODE));
200
+ if (EnumDisplaySettings(mi.szDevice, -1, ref dm) && dm.dmPelsWidth > 0)
201
+ s.Append(",\"mode\":{\"x\":" + dm.dmPositionX + ",\"y\":" + dm.dmPositionY + ",\"width\":" + dm.dmPelsWidth + ",\"height\":" + dm.dmPelsHeight + "}");
202
+ s.Append("}");
203
+ items.Add(s.ToString());
204
+ return true;
205
+ };
206
+ EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, proc, IntPtr.Zero);
207
+ GC.KeepAlive(proc);
208
+ return "{\"type\":\"displays\",\"aware\":" + (aware ? "true" : "false") + ",\"list\":[" + String.Join(",", items.ToArray()) + "]}";
209
+ }
210
+ }
211
+ '@
212
+ $ok = $true } catch { }
213
+ while (($line = [Console]::In.ReadLine()) -ne $null) {
214
+ $cmd = $line.Trim()
215
+ if ($cmd -eq 'quit') { break }
216
+ if ($cmd -eq 'displays') {
217
+ if ($ok) { try { [Console]::Out.WriteLine([HdDisplays]::List()) } catch { [Console]::Out.WriteLine('{"type":"displays","list":[],"error":"failed"}') } }
218
+ else { [Console]::Out.WriteLine('{"type":"displays","list":[],"error":"no type"}') }
219
+ [Console]::Out.Flush()
220
+ }
221
+ }
222
+ `;
223
+
224
+ /**
225
+ * The displays of this PC through one hidden PowerShell process that compiles the type once and stays for
226
+ * `idleMs` after the last request (so a click on Maximize answers in milliseconds, and an idle app holds
227
+ * no extra process). Any failure answers null; the caller then falls back.
228
+ */
229
+ export class WinDisplays {
230
+ /** @param {{ spawnImpl?: typeof spawn, exe?: string, idleMs?: number }} [o] */
231
+ constructor(o = {}) {
232
+ this.spawnImpl = o.spawnImpl || spawn;
233
+ this.exe = o.exe || 'powershell.exe';
234
+ this.idleMs = o.idleMs ?? 120000;
235
+ this.proc = null;
236
+ this.waiters = [];
237
+ this.failures = 0;
238
+ this.idle = null;
239
+ this.chain = Promise.resolve();
240
+ }
241
+
242
+ _start() {
243
+ if (this.proc || this.failures >= 3) return;
244
+ let proc;
245
+ try {
246
+ proc = this.spawnImpl(this.exe, ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encodeCommand(WIN_DISPLAYS_SCRIPT)], {
247
+ windowsHide: true, stdio: ['pipe', 'pipe', 'ignore']
248
+ });
249
+ } catch {
250
+ this.failures = 3;
251
+ return;
252
+ }
253
+ this.proc = proc;
254
+ let buf = '';
255
+ proc.stdout.setEncoding('utf8');
256
+ proc.stdout.on('data', (chunk) => {
257
+ if (this.proc !== proc) return;
258
+ buf += chunk;
259
+ let i;
260
+ while ((i = buf.indexOf('\n')) !== -1) {
261
+ const line = buf.slice(0, i).trim();
262
+ buf = buf.slice(i + 1);
263
+ if (!line.startsWith('{')) continue;
264
+ const w = this.waiters.shift();
265
+ if (!w) continue;
266
+ try { w.resolve(JSON.parse(line)); } catch { w.resolve(null); }
267
+ }
268
+ });
269
+ const dead = () => {
270
+ if (this.proc !== proc) return;
271
+ this.proc = null;
272
+ this.failures++;
273
+ for (const w of this.waiters.splice(0)) w.resolve(null);
274
+ };
275
+ proc.on('error', dead);
276
+ proc.on('exit', dead);
277
+ proc.stdin.on('error', () => { /* gone; exit handles it */ });
278
+ proc.unref?.();
279
+ proc.stdout.unref?.();
280
+ proc.stdin.unref?.();
281
+ }
282
+
283
+ /** @returns {Promise<Display[] | null>} */
284
+ list(timeoutMs = 6000) {
285
+ const run = () => new Promise((resolve) => {
286
+ clearTimeout(this.idle);
287
+ this._start();
288
+ if (!this.proc) return resolve(null);
289
+ const w = { resolve: (v) => { clearTimeout(timer); resolve(v); } };
290
+ const timer = setTimeout(() => {
291
+ const i = this.waiters.indexOf(w);
292
+ if (i !== -1) this.waiters.splice(i, 1);
293
+ this.failures++;
294
+ this.close();
295
+ resolve(null);
296
+ }, timeoutMs);
297
+ timer.unref?.();
298
+ this.waiters.push(w);
299
+ try { this.proc.stdin.write('displays\n'); } catch { w.resolve(null); }
300
+ }).then((raw) => {
301
+ if (this.idleMs > 0) { this.idle = setTimeout(() => this.close(), this.idleMs); this.idle.unref?.(); }
302
+ const list = raw ? normalizeDisplays(raw) : [];
303
+ return list.length ? list : null;
304
+ });
305
+ const p = this.chain.then(run, run);
306
+ this.chain = p.catch(() => {});
307
+ return p;
308
+ }
309
+
310
+ close() {
311
+ clearTimeout(this.idle);
312
+ const p = this.proc;
313
+ this.proc = null;
314
+ for (const w of this.waiters.splice(0)) w.resolve(null);
315
+ if (p) {
316
+ try { p.stdin.write('quit\n'); p.stdin.end(); } catch { /* gone */ }
317
+ setTimeout(() => { try { p.kill(); } catch { /* gone */ } }, 1000).unref?.();
318
+ }
319
+ }
320
+ }
321
+
322
+ /**
323
+ * The work area maximize of one window. `call` is NativeWindow.call (Neutralino methods), `displays`
324
+ * answers the displays in the runtime's units (or null). maximize() answers false when there is no display
325
+ * information; the caller then uses the native maximize.
326
+ */
327
+ export class WorkAreaMax {
328
+ /** @param {{ call: (m: string, d?: object) => Promise<any>, displays: () => Promise<Display[] | null>, min?: { width: number, height: number }, sizeExtra?: object }} o */
329
+ constructor(o) {
330
+ this.call = o.call;
331
+ this.displays = o.displays;
332
+ this.min = o.min || { width: 0, height: 0 };
333
+ this.sizeExtra = o.sizeExtra || {};
334
+ this.maximized = false;
335
+ this.restore = null;
336
+ this.placed = null;
337
+ this.busy = 0;
338
+ this.nativeOnly = false;
339
+ }
340
+
341
+ async bounds() {
342
+ const [s, p] = await Promise.all([this.call('window.getSize'), this.call('window.getPosition')]);
343
+ return { x: p.x, y: p.y, width: s.width, height: s.height };
344
+ }
345
+
346
+ /** Moves and sizes the window, then reads it back; a second pass when the first did not land (a DPI change on the way). */
347
+ async place(r) {
348
+ let now = null;
349
+ for (let i = 0; i < 2; i++) {
350
+ await this.call('window.move', { x: r.x, y: r.y });
351
+ await this.call('window.setSize', { width: r.width, height: r.height, ...this.sizeExtra });
352
+ now = await this.bounds();
353
+ if (sameRect(now, r)) break;
354
+ }
355
+ return now;
356
+ }
357
+
358
+ async _run(fn) {
359
+ this.busy++;
360
+ try { return await fn(); } finally { this.busy--; }
361
+ }
362
+
363
+ /** Starts maximized: the saved normal bounds become the restore bounds, the window already sits on `work`. */
364
+ adopt(restore, work) {
365
+ this.maximized = true;
366
+ this.restore = validRect(restore) ? { ...restore } : null;
367
+ this.placed = validRect(work) ? { ...work } : null;
368
+ }
369
+
370
+ maximize() {
371
+ return this._run(async () => {
372
+ if (await this.call('window.isMaximized')) await this.call('window.unmaximize');
373
+ const cur = await this.bounds();
374
+ const list = await this.displays();
375
+ const wa = list && workAreaBounds(list, cur);
376
+ if (!wa) return false;
377
+ if (!(this.maximized && this.restore)) this.restore = cur;
378
+ this.maximized = true;
379
+ this.placed = await this.place(wa);
380
+ return true;
381
+ });
382
+ }
383
+
384
+ unmaximize() {
385
+ return this._run(async () => {
386
+ const r = this.restore;
387
+ this.maximized = false;
388
+ this.restore = null;
389
+ this.placed = null;
390
+ if (!r) return true;
391
+ const list = await this.displays();
392
+ await this.place(list ? clampToDisplays(list, r, this.min) : r);
393
+ return true;
394
+ });
395
+ }
396
+
397
+ toggle() { return this.maximized ? this.unmaximize() : this.maximize(); }
398
+
399
+ /** Places the window on the work area again when something moved it while maximized at start (the runtime's first show). */
400
+ async ensure() {
401
+ if (!this.maximized || this.busy) return;
402
+ const now = await this.bounds();
403
+ const list = await this.displays();
404
+ const wa = list && workAreaBounds(list, now);
405
+ if (wa && !sameRect(now, wa)) await this._run(async () => { this.placed = await this.place(wa); });
406
+ else if (wa) this.placed = now;
407
+ }
408
+
409
+ /**
410
+ * Follows the real window on each state read. Win+Up, the taskbar or the system menu maximize natively
411
+ * (the whole monitor): that becomes a work area maximize, with the normal placement as restore bounds.
412
+ * A maximized window that the OS or the user moved away from the work area is no longer maximized.
413
+ * @returns {Promise<boolean>} maximized
414
+ */
415
+ async sync({ nativeMax, minimized, bounds }) {
416
+ if (this.busy || minimized) return this.maximized;
417
+ if (!nativeMax) this.nativeOnly = false;
418
+ if (nativeMax && this.nativeOnly) return true;
419
+ if (nativeMax) {
420
+ await this._run(async () => {
421
+ await this.call('window.unmaximize');
422
+ const normal = await this.bounds();
423
+ const list = await this.displays();
424
+ const wa = list && workAreaBounds(list, normal);
425
+ // No display information: give the window back its native maximize and leave it so.
426
+ if (!wa) { this.nativeOnly = true; await this.call('window.maximize'); return; }
427
+ if (!(this.maximized && this.restore)) this.restore = normal;
428
+ this.maximized = true;
429
+ this.placed = await this.place(wa);
430
+ });
431
+ return this.maximized || this.nativeOnly;
432
+ }
433
+ if (this.maximized && this.placed && validRect(bounds) && !sameRect(bounds, this.placed, 2)) {
434
+ this.maximized = false;
435
+ this.restore = null;
436
+ this.placed = null;
437
+ }
438
+ return this.maximized;
439
+ }
440
+ }