1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00
lens/src/main/window-manager.ts
Roman d656a9e289
Upgrade to webpack@5 (#4725)
* attempt to upgrade webpack@5 and all relevant packages to latest version -- part 1

Signed-off-by: Roman <ixrock@gmail.com>

* debugging webpack@5 usage -- part 1

Signed-off-by: Roman <ixrock@gmail.com>

* - attempt to use "react-refresh-typescript" with webpack@5 thingy
- extending getTSLoader() to accept more options from ts-loader

Signed-off-by: Roman <ixrock@gmail.com>

* more fixes, updating webpack loaders

Signed-off-by: Roman <ixrock@gmail.com>

* merge-fixes, using internal webpack@5 asset handlers (type: "asset/*")

Signed-off-by: Roman <ixrock@gmail.com>

* fix: raw-loader / <Icon svg="./*">, updated mocked types for importing resources via webpack

Signed-off-by: Roman <ixrock@gmail.com>

* removing webpack-dev-server, clean up

Signed-off-by: Roman <ixrock@gmail.com>

* fix master-merge conflict

Signed-off-by: Roman <ixrock@gmail.com>

* fix/reverted: use sourceMap for styles

Signed-off-by: Roman <ixrock@gmail.com>

* fix lint

Signed-off-by: Roman <ixrock@gmail.com>

* fix: loading svg icons inline as data-url (workaround for "?raw" as it fails in tests and "!!raw-loader!" seems doesn't work at all in webpack@5)

Signed-off-by: Roman <ixrock@gmail.com>

* attempt to use webpack-dev-server via node-api -- part 1

Signed-off-by: Roman <ixrock@gmail.com>

* attempt to use webpack-dev-server via node-api -- part 2

Signed-off-by: Roman <ixrock@gmail.com>

* fix: incorrect parsing svg-icon xml-content by <HotbarEntityIcon/>

Signed-off-by: Roman <ixrock@gmail.com>

* fix: more random fixes related to incorrect parsing svg-icon content, added static Icon.isSvg(content: string)

Signed-off-by: Roman <ixrock@gmail.com>

* attempt to fix: "Uncaught (in promise) DOMException: A network error occurred." when loading cluster frame -- part 1

Signed-off-by: Roman <ixrock@gmail.com>

* fix: loading cluster frame + error in loading terminal default font (which was causing network exception error and hidden cluster-view)
fix: proxying websockets (e.g. terminal)

Signed-off-by: Roman <ixrock@gmail.com>

* fix: wait lensProxy.listen() to obtain lensProxy.port for webpack-dev-server

Signed-off-by: Roman <ixrock@gmail.com>

* fix lint

Signed-off-by: Roman <ixrock@gmail.com>

* fix unit tests

Signed-off-by: Roman <ixrock@gmail.com>

* reverted auto-formatted imports with 2 lines (.idea/webstorm)

Signed-off-by: Roman <ixrock@gmail.com>

* fix: handle warnings in main-process compilation files

Signed-off-by: Roman <ixrock@gmail.com>

* fix: handle warnings in "renderer" compilation

Signed-off-by: Roman <ixrock@gmail.com>

* fix: move app fonts preloading into html/css files, clean up

Signed-off-by: Roman <ixrock@gmail.com>

* update "webpack@5", "typescript@4.5" in bundled extensions / attempt to fix weird errors in build pipeline:

ERROR in /home/runner/work/lens/lens/src/extensions/npm/extensions/dist/src/common/catalog/catalog-category-registry.d.ts
6:27-35
[tsl] ERROR in /home/runner/work/lens/lens/src/extensions/npm/extensions/dist/src/common/catalog/catalog-category-registry.d.ts(6,28)
      TS1005: ',' expected.

ERROR in /home/runner/work/lens/lens/src/extensions/npm/extensions/dist/src/renderer/components/select/select.d.ts
8:14-28
[tsl] ERROR in /home/runner/work/lens/lens/src/extensions/npm/extensions/dist/src/renderer/components/select/select.d.ts(8,15)
      TS1005: ',' expected.

ERROR in /home/runner/work/lens/lens/src/extensions/npm/extensions/dist/src/renderer/api/catalog-entity-registry.d.ts
8:14-22
[tsl] ERROR in /home/runner/work/lens/lens/src/extensions/npm/extensions/dist/src/renderer/api/catalog-entity-registry.d.ts(8,15)
      TS1005: ',' expected.

Signed-off-by: Roman <ixrock@gmail.com>

* fix: handle errors in bundled extensions compilation process

Signed-off-by: Roman <ixrock@gmail.com>

* fix: "webpack" not found in production

Signed-off-by: Roman <ixrock@gmail.com>

* fix: removed preloading fonts in template via <link preload> since it's not bundled with HtmlWebpackPlugin() anyway anda all fonts loaded via css @font-face rule

Signed-off-by: Roman <ixrock@gmail.com>

* apply HMR at least for css/styles and use manual page reload on app/scripts change

Signed-off-by: Roman <ixrock@gmail.com>

* use `react-refresh-typescript` and `@pmmmwh/react-refresh-webpack-plugin` to support HMR in most cases

Signed-off-by: Roman <ixrock@gmail.com>

* responding to comments

Signed-off-by: Roman <ixrock@gmail.com>

* revered extension version in package-lock.json (autoupdated on `make dev`)

Signed-off-by: Roman <ixrock@gmail.com>
2022-02-15 17:04:12 +02:00

279 lines
8.9 KiB
TypeScript

/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import type { ClusterId } from "../common/cluster-types";
import { makeObservable, observable } from "mobx";
import { app, BrowserWindow, dialog, ipcMain, shell, webContents } from "electron";
import windowStateKeeper from "electron-window-state";
import { appEventBus } from "../common/app-event-bus/event-bus";
import { ipcMainOn } from "../common/ipc";
import { delay, iter, Singleton } from "../common/utils";
import { ClusterFrameInfo, clusterFrameMap } from "../common/cluster-frames";
import { IpcRendererNavigationEvents } from "../renderer/navigation/events";
import logger from "./logger";
import { isMac, productName } from "../common/vars";
import { LensProxy } from "./lens-proxy";
import { bundledExtensionsLoaded } from "../common/ipc/extension-handling";
function isHideable(window: BrowserWindow | null): boolean {
return Boolean(window && !window.isDestroyed());
}
export interface SendToViewArgs {
channel: string;
frameInfo?: ClusterFrameInfo;
data?: any[];
}
export class WindowManager extends Singleton {
public mainContentUrl = `http://localhost:${LensProxy.getInstance().port}`;
protected mainWindow: BrowserWindow;
protected splashWindow: BrowserWindow;
protected windowState: windowStateKeeper.State;
protected disposers: Record<string, Function> = {};
@observable activeClusterId: ClusterId;
constructor() {
super();
makeObservable(this);
this.bindEvents();
}
private async initMainWindow(showSplash: boolean) {
// Manage main window size and position with state persistence
if (!this.windowState) {
this.windowState = windowStateKeeper({
defaultHeight: 900,
defaultWidth: 1440,
});
}
if (!this.mainWindow) {
// show icon in dock (mac-os only)
app.dock?.show();
const { width, height, x, y } = this.windowState;
this.mainWindow = new BrowserWindow({
x, y, width, height,
title: productName,
show: false,
minWidth: 700, // accommodate 800 x 600 display minimum
minHeight: 500, // accommodate 800 x 600 display minimum
titleBarStyle: isMac ? "hiddenInset" : "hidden",
frame: isMac,
backgroundColor: "#1e2124",
webPreferences: {
nodeIntegration: true,
nodeIntegrationInSubFrames: true,
webviewTag: true,
contextIsolation: false,
nativeWindowOpen: false,
},
});
this.windowState.manage(this.mainWindow);
// open external links in default browser (target=_blank, window.open)
this.mainWindow
.on("focus", () => {
appEventBus.emit({ name: "app", action: "focus" });
})
.on("blur", () => {
appEventBus.emit({ name: "app", action: "blur" });
})
.on("closed", () => {
// clean up
this.windowState.unmanage();
this.mainWindow = null;
this.splashWindow = null;
app.dock?.hide(); // hide icon in dock (mac-os)
})
.webContents
.on("dom-ready", () => {
appEventBus.emit({ name: "app", action: "dom-ready" });
})
.on("did-fail-load", (_event, code, desc) => {
logger.error(`[WINDOW-MANAGER]: Failed to load Main window`, { code, desc });
})
.on("did-finish-load", () => {
logger.info("[WINDOW-MANAGER]: Main window loaded");
})
.on("will-attach-webview", (event, webPreferences, params) => {
logger.debug("[WINDOW-MANAGER]: Attaching webview");
// Following is security recommendations because we allow webview tag (webviewTag: true)
// suggested by https://www.electronjs.org/docs/tutorial/security#11-verify-webview-options-before-creation
// and https://www.electronjs.org/docs/tutorial/security#10-do-not-use-allowpopups
if (webPreferences.preload) {
logger.warn("[WINDOW-MANAGER]: Strip away preload scripts of webview");
delete webPreferences.preload;
}
// @ts-expect-error some electron version uses webPreferences.preloadURL/webPreferences.preload
if (webPreferences.preloadURL) {
logger.warn("[WINDOW-MANAGER]: Strip away preload scripts of webview");
delete webPreferences.preload;
}
if (params.allowpopups) {
logger.warn("[WINDOW-MANAGER]: We do not allow allowpopups props, stop webview from renderer");
// event.preventDefault() will destroy the guest page.
event.preventDefault();
return;
}
// Always disable Node.js integration for all webviews
webPreferences.nodeIntegration = false;
})
.setWindowOpenHandler((details) => {
shell.openExternal(details.url);
return { action: "deny" };
});
}
try {
if (showSplash) await this.showSplash();
logger.info(`[WINDOW-MANAGER]: Loading Main window from url: ${this.mainContentUrl} ...`);
await this.mainWindow.loadURL(this.mainContentUrl);
} catch (error) {
logger.error("Loading main window failed", { error });
dialog.showErrorBox("ERROR!", error.toString());
}
}
protected bindEvents() {
// track visible cluster from ui
ipcMainOn(IpcRendererNavigationEvents.CLUSTER_VIEW_CURRENT_ID, (event, clusterId: ClusterId) => {
this.activeClusterId = clusterId;
});
}
async ensureMainWindow(showSplash = true): Promise<BrowserWindow> {
// This needs to be ready to hear the IPC message before the window is loaded
let viewHasLoaded = Promise.resolve();
if (!this.mainWindow) {
viewHasLoaded = new Promise<void>(resolve => {
ipcMain.once(bundledExtensionsLoaded, () => resolve());
});
await this.initMainWindow(showSplash);
}
try {
await viewHasLoaded;
await delay(50); // wait just a bit longer to let the first round of rendering happen
logger.info("[WINDOW-MANAGER]: Main window has reported that it has loaded");
this.mainWindow.show();
this.splashWindow?.close();
this.splashWindow = undefined;
setTimeout(() => {
appEventBus.emit({ name: "app", action: "start" });
}, 1000);
} catch (error) {
logger.error(`Showing main window failed: ${error.stack || error}`);
dialog.showErrorBox("ERROR!", error.toString());
}
return this.mainWindow;
}
private sendToView({ channel, frameInfo, data = [] }: SendToViewArgs) {
if (frameInfo) {
this.mainWindow.webContents.sendToFrame([frameInfo.processId, frameInfo.frameId], channel, ...data);
} else {
this.mainWindow.webContents.send(channel, ...data);
}
}
async navigateExtension(extId: string, pageId?: string, params?: Record<string, any>, frameId?: number) {
await this.ensureMainWindow();
const frameInfo = iter.find(clusterFrameMap.values(), frameInfo => frameInfo.frameId === frameId);
this.sendToView({
channel: "extension:navigate",
frameInfo,
data: [extId, pageId, params],
});
}
async navigate(url: string, frameId?: number) {
await this.ensureMainWindow();
const frameInfo = iter.find(clusterFrameMap.values(), frameInfo => frameInfo.frameId === frameId);
const channel = frameInfo
? IpcRendererNavigationEvents.NAVIGATE_IN_CLUSTER
: IpcRendererNavigationEvents.NAVIGATE_IN_APP;
this.sendToView({
channel,
frameInfo,
data: [url],
});
}
reload() {
const frameInfo = clusterFrameMap.get(this.activeClusterId);
if (frameInfo) {
this.sendToView({ channel: IpcRendererNavigationEvents.RELOAD_PAGE, frameInfo });
} else {
webContents.getAllWebContents().filter(wc => wc.getType() === "window").forEach(wc => {
wc.reload();
wc.clearHistory();
});
}
}
async showSplash() {
if (!this.splashWindow) {
this.splashWindow = new BrowserWindow({
width: 500,
height: 300,
backgroundColor: "#1e2124",
center: true,
frame: false,
resizable: false,
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
nodeIntegrationInSubFrames: true,
nativeWindowOpen: true,
},
});
await this.splashWindow.loadURL("static://splash.html");
}
this.splashWindow.show();
}
hide() {
if (isHideable(this.mainWindow)) {
this.mainWindow.hide();
}
if (isHideable(this.splashWindow)) {
this.splashWindow.hide();
}
}
destroy() {
this.mainWindow.destroy();
this.splashWindow.destroy();
this.mainWindow = null;
this.splashWindow = null;
Object.entries(this.disposers).forEach(([name, dispose]) => {
dispose();
delete this.disposers[name];
});
}
}