-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathWindowManager.ts
More file actions
384 lines (336 loc) · 12.2 KB
/
WindowManager.ts
File metadata and controls
384 lines (336 loc) · 12.2 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import {
ActiveWindow,
AppLayoutPayload,
CreateWindowPayload,
events,
Functions,
minsky,
OPEN_DEV_TOOLS_IN_DEV_BUILD,
rendererAppName,
rendererAppURL,
RenderNativeWindow,
Utility,
} from '@minsky/shared';
import { StoreManager } from './StoreManager';
import { BrowserWindow, dialog, Menu, OpenDialogOptions, SaveDialogOptions, screen } from 'electron';
import log from 'electron-log';
import os from 'os';
import { join, dirname } from 'path';
import { format } from 'url';
//const logWindows = debug('minsky:electron_windows');
export class WindowManager {
static topOffset: number;
static electronTopOffset: number;
static leftOffset: number;
static canvasHeight: number;
static canvasWidth: number;
static scaleFactor: number;
static currentTab=minsky.canvas as RenderNativeWindow;
static activeWindows = new Map<number, ActiveWindow>();
private static uidToWindowMap = new Map<string, ActiveWindow>();
static getWindowByUid(uid: string): ActiveWindow {
return WindowManager.uidToWindowMap.get(uid);
}
static storeWindowMenu(win: BrowserWindow, menu: Menu) {
const details = WindowManager.activeWindows.get(win.id);
if (details) {
details.menu = menu;
}
if (Functions.isMacOS()) {
win.on('focus', function () {
Menu.setApplicationMenu(menu);
});
}
}
static setApplicationMenu(win: BrowserWindow) {
if (Functions.isMacOS()) {
const details = WindowManager.activeWindows.get(win.id);
if (details) {
Menu.setApplicationMenu(details.menu);
}
}
}
static async renderFrame() {
try
{
return WindowManager.currentTab?.renderFrame(
{
parentWindowId: WindowManager.activeWindows.get(1).systemWindowId.toString(),
offsetLeft: WindowManager.leftOffset,
offsetTop: WindowManager.topOffset+WindowManager.electronTopOffset,
childWidth: WindowManager.canvasWidth,
childHeight: WindowManager.canvasHeight,
scalingFactor: WindowManager.scaleFactor
});
}
catch (err) {
// absorb exceptions, which will mostly be due to bad windows
console.log(err);
}
}
static async setCurrentTab(tab/*: RenderNativeWindow*/) {
if (WindowManager.currentTab!==tab) {
await WindowManager.currentTab?.destroyFrame();
WindowManager.currentTab=tab;
return WindowManager.renderFrame();
}
}
static getSystemWindowId(menuWindow: BrowserWindow) {
const nativeBuffer = menuWindow.getNativeWindowHandle();
switch (nativeBuffer.length) {
case 4:
return BigInt(
os.endianness() == 'LE'
? nativeBuffer.readUInt32LE(0)
: nativeBuffer.readUInt32BE(0)
);
case 8:
return os.endianness() == 'LE'
? nativeBuffer.readBigUInt64LE(0)
: nativeBuffer.readBigUInt64BE(0);
default:
log.error('Unsupported native window handle type');
return BigInt(0);
}
}
static getMainWindow(): BrowserWindow {
return WindowManager.activeWindows.get(1)?.context; // TODO:: Is WindowManager accurate?
}
static focusIfWindowIsPresent(uid: string) {
const windowDetails = WindowManager.uidToWindowMap.get(uid);
if (windowDetails) {
windowDetails.context.focus();
return true;
}
return false;
}
static getWindowUrl(url: string) {
if (!Utility.isPackaged()) {
const initialURL = url ? rendererAppURL + url : rendererAppURL;
return initialURL;
}
const path = format({
pathname: join(__dirname, '..', rendererAppName, 'index.html'),
protocol: 'file:',
slashes: true,
});
const initialURL = path + (url || '#/');
return initialURL;
}
/// If options contains defaultPath that has starts with ':model/'
/// or ':data/', then the last directory visited with that type is
/// substituted.
/// returns the directory key for the StoreManager.
static processDefaultDirectory(options: OpenDialogOptions|SaveDialogOptions) {
let splitDefaultPath=/([^\/]*)\/?(.*)/.exec(options.defaultPath);
let defaultType=splitDefaultPath[1];
let defaultDirectoryKey="";
switch (defaultType) {
case ':models':
defaultDirectoryKey='defaultModelDirectory';
break;
case ':data':
defaultDirectoryKey='defaultDataDirectory';
break;
}
if (defaultDirectoryKey) {
let defaultDirectory=StoreManager.store.get(defaultDirectoryKey) as string;
if (defaultDirectory)
options['defaultPath']=defaultDirectory+'/'+splitDefaultPath[2];
}
return defaultDirectoryKey;
}
/// wrappers around the standard electron dialogs that saves the directory opened as a defaultPath
/// if options.defaultPath is set to either models or data.
static async showOpenDialog(...args: any[])
{
let options=args[args.length-1] as OpenDialogOptions;
let defaultDirectoryKey=this.processDefaultDirectory(options);
let res: Electron.OpenDialogReturnValue;
if (args.length>1)
res=await dialog.showOpenDialog(args[0],options);
else
res=await dialog.showOpenDialog(options);
if (!res.canceled && defaultDirectoryKey) {
StoreManager.store.set(defaultDirectoryKey,dirname(res.filePaths[0]));
}
return res;
}
/// wrappers around the standard electron dialogs that saves the directory opened as a defaultPath
/// if options.defaultPath is set to either models or data.
static async showSaveDialog(...args: any[])
{
let options=args[args.length-1] as SaveDialogOptions;
let defaultDirectoryKey=this.processDefaultDirectory(options);
let res: Electron.SaveDialogReturnValue;
if (args.length>1)
res=await dialog.showSaveDialog(args[0], options);
else
res=await dialog.showSaveDialog(options);
if (!res.canceled && defaultDirectoryKey) {
StoreManager.store.set(defaultDirectoryKey,dirname(res.filePath));
}
return res;
}
/// if window already exists attached to \a url, then raise it
/// @return window if it exists, null otherwise
static raiseWindow(url: string): BrowserWindow {
let window=null;
for (let i of WindowManager.activeWindows)
if (i[1].url==url) {
window=i[1].context;
break;
}
if (window) window.show();
return window;
}
static createPopupWindowWithRouting(
payload: CreateWindowPayload,
// eslint-disable-next-line @typescript-eslint/ban-types
onCloseCallback?: (ev : Electron.Event) => void
): BrowserWindow {
const window = WindowManager.createWindow(payload, onCloseCallback);
// strip off leading #, as URL doesn't know how to handle it. Add dummy protocol and host
const url = new URL(payload.url[0]=='#'? payload.url.slice(1): payload.url,"http://localhost");
url.searchParams.set('systemWindowId',WindowManager.getSystemWindowId(window).toString());
const relativeUrlString=(payload.url[0]=='#'?'#':'') + url.pathname+'?'+url.searchParams.toString();
window.loadURL(WindowManager.getWindowUrl(relativeUrlString));
return window;
}
static closeWindowByUid(uid: string) {
const windowDetails = WindowManager.uidToWindowMap.get(uid);
if (windowDetails) {
WindowManager.uidToWindowMap.delete(uid);
windowDetails.context.close();
}
}
static createMenuPopUpAndLoadFile(
payload: CreateWindowPayload
): BrowserWindow {
const window = WindowManager.createWindow(payload);
let [path,query]=payload.url.split('?');
const filePath = format({
pathname: path,
search: query,
protocol: 'file:',
slashes: true,
});
window.loadURL(filePath);
return window;
}
static createWindow(
payload: CreateWindowPayload,
onCloseCallback?: (ev : Electron.Event) => void
) {
const { width, height, minWidth, minHeight, title, modal = true, backgroundColor=StoreManager.store.get('backgroundColor'), alwaysOnTop, url } = payload;
// do not duplicate window if requested and window already exists
if (payload.raiseIfPresent) {
const childWindow=WindowManager.raiseWindow(url);
if (childWindow) return childWindow;
}
const childWindow = new BrowserWindow({
width,
height,
minWidth: minWidth || Math.min(width, 300),
minHeight: minHeight || Math.min(height, 200),
title,
resizable: true,
useContentSize: true,
minimizable: false,
show: false,
parent: modal ? WindowManager.getMainWindow() : null,
modal,
backgroundColor,
alwaysOnTop,
webPreferences: {
contextIsolation: true,
preload: join(__dirname, 'preload.js'),
nodeIntegration: true,
},
icon: __dirname + '/assets/favicon.png',
});
childWindow.setMenu(null);
childWindow.once('ready-to-show', () => {
childWindow.show();
});
childWindow.once('page-title-updated', (event) => {
event.preventDefault();
});
/* Dev tools results in lag in handling multiple key inputs. Hence enable only temporarily when needed */
if (Utility.isDevelopmentMode() && OPEN_DEV_TOOLS_IN_DEV_BUILD) {
childWindow.webContents.openDevTools({ mode: 'detach', activate: false });
// command to inspect popup
}
const windowId = WindowManager.getSystemWindowId(childWindow);
const childWindowDetails: ActiveWindow = {
id: childWindow.id,
size: childWindow.getSize(),
isMainWindow: false,
context: childWindow,
systemWindowId: windowId,
menu: null,
url,
};
if (payload.uid) {
WindowManager.uidToWindowMap.set(payload.uid, childWindowDetails);
}
WindowManager.activeWindows.set(childWindow.id, childWindowDetails);
childWindow.on('close', (ev : Electron.Event) => {
try {
if (payload?.uid) {
WindowManager.uidToWindowMap.delete(payload.uid);
}
if (childWindow?.id) {
WindowManager.activeWindows.delete(childWindow.id);
}
if (onCloseCallback) {
onCloseCallback(ev);
}
} catch (error) {
log.error(error);
}
});
// in the event the webcontents is closed without the containing window being so.
childWindow.webContents.on('destroyed', ()=> WindowManager.activeWindows.delete(childWindow.id));
return childWindow;
}
public static scrollToCenter() {
// TODO:: Replace WindowManager with something cleaner
WindowManager.getMainWindow().webContents.executeJavaScript(
`var container=document.getElementsByClassName('minsky-canvas-container')[0]; var canvas = container.getElementsByTagName('canvas')[0]; container.scrollTop=canvas.clientHeight/2; container.scrollLeft=canvas.clientWidth/2;`,
false
);
}
static onAppLayoutChanged(payload: AppLayoutPayload) {
WindowManager.topOffset = Math.round(payload.offset.top);
WindowManager.leftOffset = Math.round(payload.offset.left);
WindowManager.scaleFactor = screen.getPrimaryDisplay().scaleFactor;
if (Functions.isWindows())
// calculate WindowManager offset internally in C++
WindowManager.electronTopOffset = 0;
else
{
let size=WindowManager.getMainWindow().getSize();
let contentSize=WindowManager.getMainWindow().getContentSize();
WindowManager.electronTopOffset = size[1]-contentSize[1];
}
WindowManager.canvasHeight = payload.drawableArea.height;
WindowManager.canvasWidth = payload.drawableArea.width;
}
static showMouseCoordinateWindow({ mouseX, mouseY }) {
dialog.showMessageBox(WindowManager.getMainWindow(), {
message: `MouseX: ${mouseX}, MouseY: ${mouseY}`,
title: 'Mouse Coordinates',
type: 'info',
});
}
static refreshAllGodleyPopups() {
for (const win of WindowManager.activeWindows.values())
if (win.context!=WindowManager.getMainWindow()) {
try {
win.context?.webContents?.send(events.GODLEY_POPUP_REFRESH);
}
catch (err) {} // absorb any exceptions due to windows disappearing
}
}
}