Resolve issues with circular dependencies

This commit is contained in:
Albert Zhang 2023-11-29 23:29:09 -05:00
parent 02aa716bc8
commit 4725ac4674
No known key found for this signature in database
GPG key ID: D74C859E94CA6DDC
5 changed files with 41 additions and 40 deletions

View file

@ -7,7 +7,7 @@
import { app, NativeImage, nativeImage } from "electron"; import { app, NativeImage, nativeImage } from "electron";
import { join } from "path"; import { join } from "path";
import { BADGE_DIR, TRAY_ICON_DIR, TRAY_ICON_PATH } from "shared/paths"; import { BADGE_DIR, TRAY_ICON_DIR, TRAY_ICON_PATH } from "shared/paths";
import type { VencordBrowserWindow } from "./mainWindow"; import { globals } from "./mainWindow";
const imgCache = new Map<string, NativeImage>(); const imgCache = new Map<string, NativeImage>();
@ -31,17 +31,11 @@ function loadTrayIcon(index: number) {
let lastIndex: null | number = -1; let lastIndex: null | number = -1;
let mainWin: null | VencordBrowserWindow;
function getMainWin() {
if (mainWin != null) return mainWin;
return (mainWin = (require("./mainWindow") as typeof import("./mainWindow")).mainWin);
}
export function setBadgeCount(count: number, tray: boolean = false) { export function setBadgeCount(count: number, tray: boolean = false) {
const [index, description] = getBadgeIndexAndDescription(count); const [index, description] = getBadgeIndexAndDescription(count);
if (tray) { if (tray) {
getMainWin()._vencord_tray?.setImage(loadTrayIcon(index ?? 0)); globals.tray?.setImage(loadTrayIcon(index ?? 0));
} }
switch (process.platform) { switch (process.platform) {
@ -61,9 +55,7 @@ export function setBadgeCount(count: number, tray: boolean = false) {
lastIndex = index; lastIndex = index;
// circular import shenanigans globals.mainWin?.setOverlayIcon(index === null ? null : loadBadge(index), description);
const mainWin = getMainWin();
mainWin.setOverlayIcon(index === null ? null : loadBadge(index), description);
break; break;
} }
} }

View file

@ -7,7 +7,7 @@
import Server from "arrpc"; import Server from "arrpc";
import { IpcEvents } from "shared/IpcEvents"; import { IpcEvents } from "shared/IpcEvents";
import { mainWin } from "./mainWindow"; import { globals } from "./mainWindow";
import { Settings } from "./settings"; import { Settings } from "./settings";
let server: any; let server: any;
@ -19,12 +19,13 @@ export async function initArRPC() {
try { try {
server = await new Server(); server = await new Server();
server.on("activity", (data: any) => mainWin.webContents.send(IpcEvents.ARRPC_ACTIVITY, JSON.stringify(data))); const { mainWin } = globals;
server.on("activity", (data: any) => mainWin!.webContents.send(IpcEvents.ARRPC_ACTIVITY, JSON.stringify(data)));
server.on("invite", (invite: string, callback: (valid: boolean) => void) => { server.on("invite", (invite: string, callback: (valid: boolean) => void) => {
invite = String(invite); invite = String(invite);
if (!inviteCodeRegex.test(invite)) return callback(false); if (!inviteCodeRegex.test(invite)) return callback(false);
mainWin.webContents mainWin!.webContents
// Safety: Result of JSON.stringify should always be safe to equal // Safety: Result of JSON.stringify should always be safe to equal
// Also, just to be super super safe, invite is regex validated above // Also, just to be super super safe, invite is regex validated above
.executeJavaScript(`Vesktop.openInviteModal(${JSON.stringify(invite)})`) .executeJavaScript(`Vesktop.openInviteModal(${JSON.stringify(invite)})`)

View file

@ -9,12 +9,12 @@ import "./ipc";
import { app, BrowserWindow } from "electron"; import { app, BrowserWindow } from "electron";
import { checkUpdates } from "updater/main"; import { checkUpdates } from "updater/main";
import { Settings } from "./settings";
import { DATA_DIR } from "./constants"; import { DATA_DIR } from "./constants";
import { createFirstLaunchTour } from "./firstLaunch"; import { createFirstLaunchTour } from "./firstLaunch";
import { createWindows, mainWin } from "./mainWindow"; import { createWindows, globals } from "./mainWindow";
import { registerMediaPermissionsHandler } from "./mediaPermissions"; import { registerMediaPermissionsHandler } from "./mediaPermissions";
import { registerScreenShareHandler } from "./screenShare"; import { registerScreenShareHandler } from "./screenShare";
import { Settings } from "./settings";
if (IS_DEV) { if (IS_DEV) {
require("source-map-support").install(); require("source-map-support").install();
@ -43,8 +43,9 @@ function init() {
); );
app.on("second-instance", (_event, _cmdLine, _cwd, data: any) => { app.on("second-instance", (_event, _cmdLine, _cwd, data: any) => {
let mainWin;
if (data.IS_DEV) app.quit(); if (data.IS_DEV) app.quit();
else if (mainWin) { else if ((mainWin = globals.mainWin)) {
if (mainWin.isMinimized()) mainWin.restore(); if (mainWin.isMinimized()) mainWin.restore();
if (!mainWin.isVisible()) mainWin.show(); if (!mainWin.isVisible()) mainWin.show();
mainWin.focus(); mainWin.focus();

View file

@ -15,10 +15,11 @@ import { join } from "path";
import { debounce } from "shared/utils/debounce"; import { debounce } from "shared/utils/debounce";
import { IpcEvents } from "../shared/IpcEvents"; import { IpcEvents } from "../shared/IpcEvents";
import { setBadgeCount } from "./appBadge";
import { autoStart } from "./autoStart"; import { autoStart } from "./autoStart";
import { VENCORD_FILES_DIR, VENCORD_QUICKCSS_FILE, VENCORD_THEMES_DIR } from "./constants"; import { VENCORD_FILES_DIR, VENCORD_QUICKCSS_FILE, VENCORD_THEMES_DIR } from "./constants";
import { mainWin } from "./mainWindow"; import { globals } from "./mainWindow";
// !!IMPORTANT!! ./appBadge import must occur after ./mainWindow
import { setBadgeCount } from "./appBadge";
import { Settings } from "./settings"; import { Settings } from "./settings";
import { handle, handleSync } from "./utils/ipcWrappers"; import { handle, handleSync } from "./utils/ipcWrappers";
import { isValidVencordInstall } from "./utils/vencordLoader"; import { isValidVencordInstall } from "./utils/vencordLoader";
@ -64,6 +65,8 @@ handle(IpcEvents.SHOW_ITEM_IN_FOLDER, (_, path) => {
}); });
handle(IpcEvents.FOCUS, () => { handle(IpcEvents.FOCUS, () => {
const mainWin = globals.mainWin!;
if (process.platform === "win32") mainWin.minimize(); // Windows is weird if (process.platform === "win32") mainWin.minimize(); // Windows is weird
mainWin.restore(); mainWin.restore();
@ -75,14 +78,14 @@ handle(IpcEvents.CLOSE, e => {
}); });
handle(IpcEvents.MINIMIZE, e => { handle(IpcEvents.MINIMIZE, e => {
mainWin.minimize(); globals.mainWin!.minimize();
}); });
handle(IpcEvents.MAXIMIZE, e => { handle(IpcEvents.MAXIMIZE, e => {
if (mainWin.isMaximized()) { if (globals.mainWin!.isMaximized()) {
mainWin.unmaximize(); globals.mainWin!.unmaximize();
} else { } else {
mainWin.maximize(); globals.mainWin!.maximize();
} }
}); });
@ -103,7 +106,7 @@ handle(IpcEvents.SPELLCHECK_ADD_TO_DICTIONARY, (e, word: string) => {
}); });
handle(IpcEvents.SELECT_VENCORD_DIR, async () => { handle(IpcEvents.SELECT_VENCORD_DIR, async () => {
const res = await dialog.showOpenDialog(mainWin!, { const res = await dialog.showOpenDialog(globals.mainWin!, {
properties: ["openDirectory"] properties: ["openDirectory"]
}); });
if (!res.filePaths.length) return "cancelled"; if (!res.filePaths.length) return "cancelled";
@ -126,7 +129,7 @@ open(VENCORD_QUICKCSS_FILE, "a+").then(fd => {
VENCORD_QUICKCSS_FILE, VENCORD_QUICKCSS_FILE,
{ persistent: false }, { persistent: false },
debounce(async () => { debounce(async () => {
mainWin?.webContents.postMessage("VencordQuickCssUpdate", await readCss()); globals.mainWin?.webContents.postMessage("VencordQuickCssUpdate", await readCss());
}, 50) }, 50)
); );
}); });
@ -136,6 +139,6 @@ watch(
VENCORD_THEMES_DIR, VENCORD_THEMES_DIR,
{ persistent: false }, { persistent: false },
debounce(() => { debounce(() => {
mainWin?.webContents.postMessage("VencordThemeUpdate", void 0); globals.mainWin?.webContents.postMessage("VencordThemeUpdate", void 0);
}) })
); );

View file

@ -24,6 +24,7 @@ import type { SettingsStore } from "shared/utils/SettingsStore";
import { ICON_PATH, TRAY_ICON_PATH } from "../shared/paths"; import { ICON_PATH, TRAY_ICON_PATH } from "../shared/paths";
import { createAboutWindow } from "./about"; import { createAboutWindow } from "./about";
import { initArRPC } from "./arrpc"; import { initArRPC } from "./arrpc";
import { Settings, VencordSettings } from "./settings";
import { import {
DATA_DIR, DATA_DIR,
DEFAULT_HEIGHT, DEFAULT_HEIGHT,
@ -34,7 +35,6 @@ import {
UserAgent, UserAgent,
VENCORD_FILES_DIR VENCORD_FILES_DIR
} from "./constants"; } from "./constants";
import { Settings, VencordSettings } from "./settings";
import { createSplashWindow } from "./splash"; import { createSplashWindow } from "./splash";
import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally"; import { makeLinksOpenExternally } from "./utils/makeLinksOpenExternally";
import { applyDeckKeyboardFix, askToApplySteamLayout, isDeckGameMode } from "./utils/steamOS"; import { applyDeckKeyboardFix, askToApplySteamLayout, isDeckGameMode } from "./utils/steamOS";
@ -48,12 +48,12 @@ app.on("before-quit", () => {
isQuitting = true; isQuitting = true;
}); });
type VencordBrowserWindow = BrowserWindow & { // Fixes circular dependency issues with export const
_vencord_tray?: Tray; export const globals = {
tray: <null | Tray>null,
mainWin: <null | BrowserWindow>null
}; };
export let mainWin: VencordBrowserWindow;
function makeSettingsListenerHelpers<O extends object>(o: SettingsStore<O>) { function makeSettingsListenerHelpers<O extends object>(o: SettingsStore<O>) {
const listeners = new Map<(data: any) => void, PropertyKey>(); const listeners = new Map<(data: any) => void, PropertyKey>();
@ -75,7 +75,7 @@ function makeSettingsListenerHelpers<O extends object>(o: SettingsStore<O>) {
const [addSettingsListener, removeSettingsListeners] = makeSettingsListenerHelpers(Settings); const [addSettingsListener, removeSettingsListeners] = makeSettingsListenerHelpers(Settings);
const [addVencordSettingsListener, removeVencordSettingsListeners] = makeSettingsListenerHelpers(VencordSettings); const [addVencordSettingsListener, removeVencordSettingsListeners] = makeSettingsListenerHelpers(VencordSettings);
function initTray(win: VencordBrowserWindow) { function initTray(win: BrowserWindow) {
const trayMenu = Menu.buildFromTemplate([ const trayMenu = Menu.buildFromTemplate([
{ {
label: "Open", label: "Open",
@ -121,7 +121,7 @@ function initTray(win: VencordBrowserWindow) {
} }
]); ]);
const tray = new Tray(TRAY_ICON_PATH); const tray = (globals.tray = new Tray(TRAY_ICON_PATH));
tray.setToolTip("Vesktop"); tray.setToolTip("Vesktop");
tray.setContextMenu(trayMenu); tray.setContextMenu(trayMenu);
tray.on("click", () => win.show()); tray.on("click", () => win.show());
@ -204,7 +204,7 @@ function initMenuBar(win: BrowserWindow) {
label: "Settings", label: "Settings",
accelerator: "CmdOrCtrl+,", accelerator: "CmdOrCtrl+,",
async click() { async click() {
mainWin.webContents.executeJavaScript( globals.mainWin!.webContents.executeJavaScript(
"Vencord.Webpack.Common.SettingsRouter.open('My Account')" "Vencord.Webpack.Common.SettingsRouter.open('My Account')"
); );
} }
@ -332,10 +332,14 @@ function initWindowBoundsListeners(win: BrowserWindow) {
win.on("move", saveBounds); win.on("move", saveBounds);
} }
function initSettingsListeners(win: VencordBrowserWindow) { function initSettingsListeners(win: BrowserWindow) {
addSettingsListener("tray", enable => { addSettingsListener("tray", enable => {
if (enable) initTray(win); if (enable) {
else win._vencord_tray?.destroy(); initTray(win);
} else if (globals.tray) {
globals.tray.destroy();
globals.tray = null;
}
}); });
addSettingsListener("disableMinSize", disable => { addSettingsListener("disableMinSize", disable => {
if (disable) { if (disable) {
@ -373,7 +377,7 @@ function initSpellCheck(win: BrowserWindow) {
}); });
} }
function createMainWindow(): VencordBrowserWindow { function createMainWindow(): BrowserWindow {
// Clear up previous settings listeners // Clear up previous settings listeners
removeSettingsListeners(); removeSettingsListeners();
removeVencordSettingsListeners(); removeVencordSettingsListeners();
@ -384,7 +388,7 @@ function createMainWindow(): VencordBrowserWindow {
const noFrame = frameless === true || (process.platform === "win32" && discordWindowsTitleBar === true); const noFrame = frameless === true || (process.platform === "win32" && discordWindowsTitleBar === true);
const win = (mainWin = new BrowserWindow({ const win = (globals.mainWin = new BrowserWindow({
show: false, show: false,
webPreferences: { webPreferences: {
nodeIntegration: false, nodeIntegration: false,
@ -452,7 +456,7 @@ export async function createWindows() {
await ensureVencordFiles(); await ensureVencordFiles();
runVencordMain(); runVencordMain();
mainWin = createMainWindow(); const mainWin = (globals.mainWin = createMainWindow());
mainWin.webContents.on("did-finish-load", () => { mainWin.webContents.on("did-finish-load", () => {
splash.destroy(); splash.destroy();