-
-
Notifications
You must be signed in to change notification settings - Fork 973
Expand file tree
/
Copy pathemain-util.ts
More file actions
352 lines (318 loc) · 11.8 KB
/
emain-util.ts
File metadata and controls
352 lines (318 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright 2025, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
import * as electron from "electron";
import { getWebServerEndpoint } from "../frontend/util/endpoints";
export const WaveAppPathVarName = "WAVETERM_APP_PATH";
export const WaveAppResourcesPathVarName = "WAVETERM_RESOURCES_PATH";
export const WaveAppElectronExecPath = "WAVETERM_ELECTRONEXECPATH";
const MinZoomLevel = 0.4;
const MaxZoomLevel = 2.6;
const ZoomDelta = 0.2;
// Note: Chromium automatically syncs zoom factor across all WebContents
// sharing the same origin/session, so we only need to notify renderers
// to update their CSS/state — not call setZoomFactor on each one.
// We broadcast to all WebContents (including devtools, webviews, etc.) but
// that is safe because "zoom-factor-change" is a custom app-defined event
// that only our renderers listen to; unrecognized IPC messages are ignored.
function broadcastZoomFactorChanged(newZoomFactor: number): void {
for (const wc of electron.webContents.getAllWebContents()) {
if (wc.isDestroyed()) {
continue;
}
wc.send("zoom-factor-change", newZoomFactor);
}
}
export function increaseZoomLevel(webContents: electron.WebContents): void {
const newZoom = Math.min(MaxZoomLevel, webContents.getZoomFactor() + ZoomDelta);
webContents.setZoomFactor(newZoom);
broadcastZoomFactorChanged(newZoom);
}
export function decreaseZoomLevel(webContents: electron.WebContents): void {
const newZoom = Math.max(MinZoomLevel, webContents.getZoomFactor() - ZoomDelta);
webContents.setZoomFactor(newZoom);
broadcastZoomFactorChanged(newZoom);
}
export function resetZoomLevel(webContents: electron.WebContents): void {
webContents.setZoomFactor(1);
broadcastZoomFactorChanged(1);
}
export function getElectronExecPath(): string {
return process.execPath;
}
// not necessarily exact, but we use this to help get us unstuck in certain cases
let lastCtrlShiftSate: boolean = false;
export function delay(ms): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function setCtrlShift(wc: Electron.WebContents, state: boolean) {
lastCtrlShiftSate = state;
wc.send("control-shift-state-update", state);
}
export function handleCtrlShiftFocus(sender: Electron.WebContents, focused: boolean) {
if (!focused) {
setCtrlShift(sender, false);
}
}
export function handleCtrlShiftState(sender: Electron.WebContents, waveEvent: WaveKeyboardEvent) {
if (waveEvent.type == "keyup") {
if (waveEvent.key === "Control" || waveEvent.key === "Shift") {
setCtrlShift(sender, false);
}
if (waveEvent.key == "Meta") {
if (waveEvent.control && waveEvent.shift) {
setCtrlShift(sender, true);
}
}
if (lastCtrlShiftSate) {
if (!waveEvent.control || !waveEvent.shift) {
setCtrlShift(sender, false);
}
}
return;
}
if (waveEvent.type == "keydown") {
if (waveEvent.key === "Control" || waveEvent.key === "Shift" || waveEvent.key === "Meta") {
if (waveEvent.control && waveEvent.shift && !waveEvent.meta) {
// Set the control and shift without the Meta key
setCtrlShift(sender, true);
} else {
// Unset if Meta is pressed
setCtrlShift(sender, false);
}
}
return;
}
}
export function shNavHandler(event: Electron.Event<Electron.WebContentsWillNavigateEventParams>, url: string) {
const isDev = !electron.app.isPackaged;
if (
isDev &&
(url.startsWith("http://127.0.0.1:5173/index.html") ||
url.startsWith("http://localhost:5173/index.html") ||
url.startsWith("http://127.0.0.1:5174/index.html") ||
url.startsWith("http://localhost:5174/index.html"))
) {
// this is a dev-mode hot-reload, ignore it
console.log("allowing hot-reload of index.html");
return;
}
event.preventDefault();
if (url.startsWith("https://") || url.startsWith("http://") || url.startsWith("file://")) {
console.log("open external, shNav", url);
electron.shell.openExternal(url);
} else {
console.log("navigation canceled", url);
}
}
function frameOrAncestorHasName(frame: Electron.WebFrameMain, name: string): boolean {
let cur: Electron.WebFrameMain = frame;
while (cur != null) {
if (cur.name === name) {
return true;
}
cur = cur.parent;
}
return false;
}
export function shFrameNavHandler(event: Electron.Event<Electron.WebContentsWillFrameNavigateEventParams>) {
if (!event.frame?.parent) {
// only use this handler to process iframe events (non-iframe events go to shNavHandler)
return;
}
const url = event.url;
console.log(`frame-navigation url=${url} frame=${event.frame.name}`);
if (event.frame.name == "webview") {
// "webview" links always open in new window
// this will *not* effect the initial load because srcdoc does not count as an electron navigation
console.log("open external, frameNav", url);
event.preventDefault();
electron.shell.openExternal(url);
return;
}
if (
frameOrAncestorHasName(event.frame, "pdfview") &&
(url.startsWith("blob:file:///") ||
url.startsWith("chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai/") ||
url.startsWith(getWebServerEndpoint() + "/wave/stream-file?") ||
url.startsWith(getWebServerEndpoint() + "/wave/stream-file/") ||
url.startsWith(getWebServerEndpoint() + "/wave/stream-local-file?"))
) {
// allowed
return;
}
if (event.frame.name != null && event.frame.name.startsWith("tsunami:")) {
// Parse port from frame name: tsunami:[port]:[blockid]
const nameParts = event.frame.name.split(":");
const expectedPort = nameParts.length >= 2 ? nameParts[1] : null;
try {
const tsunamiUrl = new URL(url);
if (
tsunamiUrl.protocol === "http:" &&
tsunamiUrl.hostname === "localhost" &&
expectedPort &&
tsunamiUrl.port === expectedPort
) {
// allowed
return;
}
// If navigation is not to expected port, open externally
event.preventDefault();
electron.shell.openExternal(url);
return;
} catch (e) {
// Invalid URL, fall through to prevent navigation
}
}
event.preventDefault();
console.log("frame navigation canceled", event.frame.name, url);
}
function isWindowFullyVisible(bounds: electron.Rectangle): boolean {
const displays = electron.screen.getAllDisplays();
// Helper function to check if a point is inside any display
function isPointInDisplay(x: number, y: number) {
for (const display of displays) {
const { x: dx, y: dy, width, height } = display.bounds;
if (x >= dx && x < dx + width && y >= dy && y < dy + height) {
return true;
}
}
return false;
}
// Check all corners of the window
const topLeft = isPointInDisplay(bounds.x, bounds.y);
const topRight = isPointInDisplay(bounds.x + bounds.width, bounds.y);
const bottomLeft = isPointInDisplay(bounds.x, bounds.y + bounds.height);
const bottomRight = isPointInDisplay(bounds.x + bounds.width, bounds.y + bounds.height);
return topLeft && topRight && bottomLeft && bottomRight;
}
function findDisplayWithMostArea(bounds: electron.Rectangle): electron.Display {
const displays = electron.screen.getAllDisplays();
let maxArea = 0;
let bestDisplay = null;
for (let display of displays) {
const { x, y, width, height } = display.bounds;
const overlapX = Math.max(0, Math.min(bounds.x + bounds.width, x + width) - Math.max(bounds.x, x));
const overlapY = Math.max(0, Math.min(bounds.y + bounds.height, y + height) - Math.max(bounds.y, y));
const overlapArea = overlapX * overlapY;
if (overlapArea > maxArea) {
maxArea = overlapArea;
bestDisplay = display;
}
}
return bestDisplay;
}
function adjustBoundsToFitDisplay(bounds: electron.Rectangle, display: electron.Display): electron.Rectangle {
const { x: dx, y: dy, width: dWidth, height: dHeight } = display.workArea;
let { x, y, width, height } = bounds;
// Adjust width and height to fit within the display's work area
width = Math.min(width, dWidth);
height = Math.min(height, dHeight);
// Adjust x to ensure the window fits within the display
if (x < dx) {
x = dx;
} else if (x + width > dx + dWidth) {
x = dx + dWidth - width;
}
// Adjust y to ensure the window fits within the display
if (y < dy) {
y = dy;
} else if (y + height > dy + dHeight) {
y = dy + dHeight - height;
}
return { x, y, width, height };
}
export function ensureBoundsAreVisible(bounds: electron.Rectangle): electron.Rectangle {
if (!isWindowFullyVisible(bounds)) {
let targetDisplay = findDisplayWithMostArea(bounds);
if (!targetDisplay) {
targetDisplay = electron.screen.getPrimaryDisplay();
}
return adjustBoundsToFitDisplay(bounds, targetDisplay);
}
return bounds;
}
export function waveKeyToElectronKey(waveKey: string): string {
const waveParts = waveKey.split(":");
const electronParts: Array<string> = waveParts.map((part: string) => {
const digitRegexpMatch = new RegExp("^c{Digit([0-9])}$").exec(part);
const numpadRegexpMatch = new RegExp("^c{Numpad([0-9])}$").exec(part);
const lowercaseCharMatch = new RegExp("^([a-z])$").exec(part);
if (part == "ArrowUp") {
return "Up";
}
if (part == "ArrowDown") {
return "Down";
}
if (part == "ArrowLeft") {
return "Left";
}
if (part == "ArrowRight") {
return "Right";
}
if (part == "Soft1") {
return "F21";
}
if (part == "Soft2") {
return "F22";
}
if (part == "Soft3") {
return "F23";
}
if (part == "Soft4") {
return "F24";
}
if (part == " ") {
return "Space";
}
if (part == "CapsLock") {
return "Capslock";
}
if (part == "NumLock") {
return "Numlock";
}
if (part == "ScrollLock") {
return "Scrolllock";
}
if (part == "AudioVolumeUp") {
return "VolumeUp";
}
if (part == "AudioVolumeDown") {
return "VolumeDown";
}
if (part == "AudioVolumeMute") {
return "VolumeMute";
}
if (part == "MediaTrackNext") {
return "MediaNextTrack";
}
if (part == "MediaTrackPrevious") {
return "MediaPreviousTrack";
}
if (part == "Decimal") {
return "numdec";
}
if (part == "Add") {
return "numadd";
}
if (part == "Subtract") {
return "numsub";
}
if (part == "Multiply") {
return "nummult";
}
if (part == "Divide") {
return "numdiv";
}
if (digitRegexpMatch && digitRegexpMatch.length > 1) {
return digitRegexpMatch[1];
}
if (numpadRegexpMatch && numpadRegexpMatch.length > 1) {
return `num${numpadRegexpMatch[1]}`;
}
if (lowercaseCharMatch && lowercaseCharMatch.length > 1) {
return lowercaseCharMatch[1].toUpperCase();
}
return part;
});
return electronParts.join("+");
}