project-client/src/main/mainWindow.ts

471 lines
13 KiB
TypeScript
Raw Normal View History

2023-04-10 05:49:50 +09:00
/*
* SPDX-License-Identifier: GPL-3.0
2023-07-14 02:03:13 +09:00
* Vesktop, a desktop app aiming to give you a snappier Discord Experience
2023-04-10 05:49:50 +09:00
* Copyright (c) 2023 Vendicated and Vencord contributors
*/
import {
app,
BrowserWindow,
BrowserWindowConstructorOptions,
dialog,
Menu,
MenuItemConstructorOptions,
nativeTheme,
Tray
} from "electron";
import { rm } from "fs/promises";
2023-03-30 08:02:30 +09:00
import { join } from "path";
2023-06-25 10:44:19 +09:00
import { IpcEvents } from "shared/IpcEvents";
import { isTruthy } from "shared/utils/guards";
2023-06-21 21:39:41 +09:00
import { once } from "shared/utils/once";
import type { SettingsStore } from "shared/utils/SettingsStore";
2023-04-10 05:49:50 +09:00
2023-04-04 08:35:37 +09:00
import { ICON_PATH } from "../shared/paths";
import { createAboutWindow } from "./about";
2023-06-21 21:39:41 +09:00
import { initArRPC } from "./arrpc";
import {
DATA_DIR,
DEFAULT_HEIGHT,
DEFAULT_WIDTH,
MessageBoxChoice,
MIN_HEIGHT,
MIN_WIDTH,
UserAgent,
VENCORD_FILES_DIR
} from "./constants";
import { Settings, VencordSettings } from "./settings";
2023-06-21 21:39:41 +09:00
import { createSplashWindow } from "./splash";
import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally";
import { applyDeckKeyboardFix, askToApplySteamLayout, isDeckGameMode } from "./utils/steamOS";
2023-06-21 21:39:41 +09:00
import { downloadVencordFiles, ensureVencordFiles } from "./utils/vencordLoader";
2023-03-30 08:02:30 +09:00
let isQuitting = false;
let tray: Tray;
2023-04-04 07:41:52 +09:00
applyDeckKeyboardFix();
app.on("before-quit", () => {
isQuitting = true;
});
export let mainWin: BrowserWindow;
function makeSettingsListenerHelpers<O extends object>(o: SettingsStore<O>) {
const listeners = new Map<(data: any) => void, PropertyKey>();
const addListener: typeof o.addChangeListener = (path, cb) => {
listeners.set(cb, path);
o.addChangeListener(path, cb);
};
const removeAllListeners = () => {
for (const [listener, path] of listeners) {
o.removeChangeListener(path as any, listener);
}
listeners.clear();
};
return [addListener, removeAllListeners] as const;
}
const [addSettingsListener, removeSettingsListeners] = makeSettingsListenerHelpers(Settings);
const [addVencordSettingsListener, removeVencordSettingsListeners] = makeSettingsListenerHelpers(VencordSettings);
function initTray(win: BrowserWindow) {
2023-04-04 08:35:37 +09:00
const trayMenu = Menu.buildFromTemplate([
{
label: "Open",
click() {
win.show();
},
enabled: false
},
2023-04-06 07:08:28 +09:00
{
label: "About",
click: createAboutWindow
},
{
label: "Update Vencord",
async click() {
await downloadVencordFiles();
app.relaunch();
app.quit();
}
},
{
label: "Reset Vesktop",
async click() {
await clearData(win);
}
},
2023-04-06 10:52:06 +09:00
{
type: "separator"
},
2023-04-06 07:08:28 +09:00
{
label: "Relaunch",
click() {
app.relaunch();
app.quit();
}
},
2023-04-04 08:35:37 +09:00
{
2023-07-14 02:03:13 +09:00
label: "Quit Vesktop",
2023-04-04 08:35:37 +09:00
click() {
isQuitting = true;
app.quit();
}
}
]);
tray = new Tray(ICON_PATH);
2023-07-14 02:03:13 +09:00
tray.setToolTip("Vesktop");
2023-04-04 08:35:37 +09:00
tray.setContextMenu(trayMenu);
tray.on("click", () => win.show());
win.on("show", () => {
trayMenu.items[0].enabled = false;
});
win.on("hide", () => {
trayMenu.items[0].enabled = true;
});
}
async function clearData(win: BrowserWindow) {
const { response } = await dialog.showMessageBox(win, {
message: "Are you sure you want to reset Vesktop?",
detail: "This will log you out, clear caches and reset all your settings!\n\nVesktop will automatically restart after this operation.",
buttons: ["Yes", "No"],
cancelId: MessageBoxChoice.Cancel,
defaultId: MessageBoxChoice.Default,
type: "warning"
});
if (response === MessageBoxChoice.Cancel) return;
win.close();
await win.webContents.session.clearStorageData();
await win.webContents.session.clearCache();
await win.webContents.session.clearCodeCaches({});
await rm(DATA_DIR, { force: true, recursive: true });
app.relaunch();
app.quit();
}
type MenuItemList = Array<MenuItemConstructorOptions | false>;
2023-04-06 00:25:29 +09:00
function initMenuBar(win: BrowserWindow) {
const isWindows = process.platform === "win32";
const isDarwin = process.platform === "darwin";
2023-04-10 08:04:41 +09:00
const wantCtrlQ = !isWindows || VencordSettings.store.winCtrlQ;
const subMenu = [
{
2023-07-14 02:03:13 +09:00
label: "About Vesktop",
click: createAboutWindow
},
{
label: "Force Update Vencord",
async click() {
await downloadVencordFiles();
app.relaunch();
app.quit();
},
2023-07-14 02:03:13 +09:00
toolTip: "Vesktop will automatically restart after this operation"
},
{
label: "Reset Vesktop",
async click() {
await clearData(win);
},
toolTip: "Vesktop will automatically restart after this operation"
},
{
label: "Relaunch",
accelerator: "CmdOrCtrl+Shift+R",
click() {
app.relaunch();
app.quit();
}
},
...(!isDarwin
? []
: ([
{
type: "separator"
},
{
label: "Settings",
accelerator: "CmdOrCtrl+,",
async click() {
mainWin.webContents.executeJavaScript(
"Vencord.Webpack.Common.SettingsRouter.open('My Account')"
);
}
},
{
type: "separator"
},
{
label: "Hide Vesktop", // Should probably remove the label, but it says "Hide VencordDesktop" instead of "Hide Vesktop"
role: "hide"
},
{
role: "hideOthers"
},
{
role: "unhide"
},
{
type: "separator"
}
] satisfies MenuItemList)),
{
label: "Quit",
accelerator: wantCtrlQ ? "CmdOrCtrl+Q" : void 0,
visible: !isWindows,
role: "quit",
click() {
app.quit();
}
},
isWindows && {
label: "Quit",
accelerator: "Alt+F4",
role: "quit",
click() {
app.quit();
}
},
// See https://github.com/electron/electron/issues/14742 and https://github.com/electron/electron/issues/5256
{
label: "Zoom in (hidden, hack for Qwertz and others)",
accelerator: "CmdOrCtrl+=",
role: "zoomIn",
visible: false
}
] satisfies MenuItemList;
2023-04-06 00:25:29 +09:00
const menu = Menu.buildFromTemplate([
{
2023-07-14 02:03:13 +09:00
label: "Vesktop",
role: "appMenu",
submenu: subMenu.filter(isTruthy)
2023-04-06 00:25:29 +09:00
},
{ role: "fileMenu" },
{ role: "editMenu" },
{ role: "viewMenu" },
{ role: "windowMenu" }
2023-04-06 00:25:29 +09:00
]);
Menu.setApplicationMenu(menu);
}
2023-04-09 12:04:49 +09:00
function getWindowBoundsOptions(): BrowserWindowConstructorOptions {
// We want the default window behaivour to apply in game mode since it expects everything to be fullscreen and maximized.
if (isDeckGameMode) return {};
2023-04-10 08:04:41 +09:00
const { x, y, width, height } = Settings.store.windowBounds ?? {};
2023-04-09 12:04:49 +09:00
const options = {
width: width ?? DEFAULT_WIDTH,
height: height ?? DEFAULT_HEIGHT
} as BrowserWindowConstructorOptions;
2023-04-04 11:17:38 +09:00
if (x != null && y != null) {
options.x = x;
options.y = y;
}
2023-04-10 08:04:41 +09:00
if (!Settings.store.disableMinSize) {
2023-04-09 12:04:49 +09:00
options.minWidth = MIN_WIDTH;
options.minHeight = MIN_HEIGHT;
}
2023-04-04 11:17:38 +09:00
return options;
}
function getDarwinOptions(): BrowserWindowConstructorOptions {
const options = {
titleBarStyle: "hidden",
trafficLightPosition: { x: 10, y: 10 }
} as BrowserWindowConstructorOptions;
const { splashTheming, splashBackground } = Settings.store;
const { macosTranslucency } = VencordSettings.store;
if (macosTranslucency) {
options.vibrancy = "sidebar";
options.backgroundColor = "#ffffff00";
} else {
if (splashTheming) {
options.backgroundColor = splashBackground;
} else {
options.backgroundColor = nativeTheme.shouldUseDarkColors ? "#313338" : "#ffffff";
}
}
return options;
}
2023-04-04 11:17:38 +09:00
function initWindowBoundsListeners(win: BrowserWindow) {
2023-04-09 12:04:49 +09:00
const saveState = () => {
2023-04-10 08:04:41 +09:00
Settings.store.maximized = win.isMaximized();
Settings.store.minimized = win.isMinimized();
2023-04-09 12:04:49 +09:00
};
2023-04-04 11:17:38 +09:00
2023-04-09 12:04:49 +09:00
win.on("maximize", saveState);
win.on("minimize", saveState);
win.on("unmaximize", saveState);
2023-04-04 11:17:38 +09:00
const saveBounds = () => {
2023-04-10 08:04:41 +09:00
Settings.store.windowBounds = win.getBounds();
2023-04-04 11:17:38 +09:00
};
win.on("resize", saveBounds);
win.on("move", saveBounds);
}
function initSettingsListeners(win: BrowserWindow) {
addSettingsListener("tray", enable => {
2023-04-11 02:18:00 +09:00
if (enable) initTray(win);
else tray?.destroy();
});
addSettingsListener("disableMinSize", disable => {
if (disable) {
// 0 no work
win.setMinimumSize(1, 1);
} else {
win.setMinimumSize(MIN_WIDTH, MIN_HEIGHT);
const { width, height } = win.getBounds();
win.setBounds({
width: Math.max(width, MIN_WIDTH),
height: Math.max(height, MIN_HEIGHT)
});
}
});
addVencordSettingsListener("macosTranslucency", enabled => {
if (enabled) {
win.setVibrancy("sidebar");
win.setBackgroundColor("#ffffff00");
} else {
win.setVibrancy(null);
win.setBackgroundColor("#ffffff");
}
});
2023-07-29 04:54:17 +09:00
addSettingsListener("enableMenu", enabled => {
win.setAutoHideMenuBar(enabled ?? false);
});
}
2023-06-25 10:44:19 +09:00
function initSpellCheck(win: BrowserWindow) {
win.webContents.on("context-menu", (_, data) => {
win.webContents.send(IpcEvents.SPELLCHECK_RESULT, data.misspelledWord, data.dictionarySuggestions);
});
}
2023-06-21 21:39:41 +09:00
function createMainWindow() {
// Clear up previous settings listeners
removeSettingsListeners();
removeVencordSettingsListeners();
const { staticTitle, transparencyOption, enableMenu, discordWindowsTitleBar } = Settings.store;
const { frameless } = VencordSettings.store;
2023-08-07 07:23:27 +09:00
const noFrame = frameless === true || (process.platform === "win32" && discordWindowsTitleBar === true);
2023-04-10 05:49:50 +09:00
const win = (mainWin = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: false,
sandbox: false,
contextIsolation: true,
devTools: true,
2023-06-25 10:44:19 +09:00
preload: join(__dirname, "preload.js"),
spellcheck: true
},
2023-04-04 11:17:38 +09:00
icon: ICON_PATH,
2023-08-07 07:23:27 +09:00
frame: !noFrame,
...(transparencyOption &&
transparencyOption !== "none" && {
backgroundColor: "#00000000",
backgroundMaterial: transparencyOption,
transparent: true
}),
...(staticTitle && { title: "Vesktop" }),
...(process.platform === "darwin" && getDarwinOptions()),
2023-07-29 04:54:17 +09:00
...getWindowBoundsOptions(),
autoHideMenuBar: enableMenu
2023-04-10 05:49:50 +09:00
}));
win.setMenuBarVisibility(false);
2023-04-04 07:41:52 +09:00
win.on("close", e => {
const useTray = !isDeckGameMode && Settings.store.minimizeToTray !== false && Settings.store.tray !== false;
if (isQuitting || (process.platform !== "darwin" && !useTray)) return;
2023-04-04 07:41:52 +09:00
e.preventDefault();
if (process.platform === "darwin") app.hide();
else win.hide();
2023-04-04 07:41:52 +09:00
return false;
2023-03-30 08:02:30 +09:00
});
2023-04-20 11:26:56 +09:00
if (Settings.store.staticTitle) win.on("page-title-updated", e => e.preventDefault());
2023-04-04 11:17:38 +09:00
initWindowBoundsListeners(win);
if (!isDeckGameMode && (Settings.store.tray ?? true) && process.platform !== "darwin") initTray(win);
2023-04-06 00:25:29 +09:00
initMenuBar(win);
makeLinksOpenExternally(win);
initSettingsListeners(win);
2023-06-25 10:44:19 +09:00
initSpellCheck(win);
2023-04-04 07:41:52 +09:00
win.webContents.setUserAgent(UserAgent);
2023-04-10 05:49:50 +09:00
const subdomain =
2023-04-10 08:04:41 +09:00
Settings.store.discordBranch === "canary" || Settings.store.discordBranch === "ptb"
? `${Settings.store.discordBranch}.`
: "";
win.loadURL(`https://${subdomain}discord.com/app`);
2023-03-30 08:02:30 +09:00
return win;
}
2023-06-21 21:39:41 +09:00
const runVencordMain = once(() => require(join(VENCORD_FILES_DIR, "vencordDesktopMain.js")));
export async function createWindows() {
const splash = createSplashWindow();
// SteamOS letterboxes and scales it terribly, so just full screen it
if (isDeckGameMode) splash.setFullScreen(true);
2023-06-21 21:39:41 +09:00
await ensureVencordFiles();
runVencordMain();
mainWin = createMainWindow();
mainWin.webContents.on("did-finish-load", () => {
2023-06-21 21:39:41 +09:00
splash.destroy();
mainWin!.show();
if (Settings.store.maximized && !isDeckGameMode) {
2023-06-21 21:39:41 +09:00
mainWin!.maximize();
}
if (isDeckGameMode) {
// always use entire display
mainWin!.setFullScreen(true);
askToApplySteamLayout(mainWin);
}
2023-06-21 21:39:41 +09:00
});
initArRPC();
}