Skip to content

Commit

Permalink
feat: cleanup in all files, fixed userscript meta & advSlider
Browse files Browse the repository at this point in the history
  • Loading branch information
KraXen72 committed Jun 20, 2023
1 parent cc1e4b4 commit cedb501
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 114 deletions.
4 changes: 4 additions & 0 deletions src/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ interface Window {
errAlert: Function;
OffCliV: boolean;
getGameActivity: Function
windows: [ {
settingType: 'basic' | 'advanced';
toggleType: Function;
}, ...Object[]];
}

/*
Expand Down
45 changes: 6 additions & 39 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,6 @@ import Swapper from './resourceswapper';

/// <reference path="global.d.ts" />

// Credits / mentions (if not mentioned on github)
/*
* Gato/creepycats - Gatoclient
* LukeTheDuke - Gatoclient-lite
* Mixaz and IDKR team - https://github.com/idkr-client/idkr
* wa#3991 / paintingofblue - matchmaker implementation
* Commander/asger-finding (AKC client) - resource swapper implementation
* Giant - JANREX client
* Tae - logo for the client <3
*/

const docsPath = app.getPath('documents');
const swapperPath = pathJoin(docsPath, 'Crankshaft/swapper');
const settingsPath = pathJoin(docsPath, 'Crankshaft/settings.json');
Expand Down Expand Up @@ -58,24 +47,20 @@ const settingsSkeleton = {
matchmaker_minRemainingTime: 120
};

// export type settingsKeys = keyof typeof settingsSkeleton

if (!existsSync(swapperPath)) mkdirSync(swapperPath, { recursive: true });
if (!existsSync(userscriptsPath)) mkdirSync(userscriptsPath, { recursive: true });
if (!existsSync(userscriptTrackerPath)) writeFileSync(userscriptTrackerPath, '{}', { encoding: 'utf-8' });

// Before we can read the settings, we need to make sure they exist, if they don't, then we create a template
if (!existsSync(settingsPath)) writeFileSync(settingsPath, JSON.stringify(settingsSkeleton, null, 2), { encoding: 'utf-8', flag: 'wx' });


// Read settings to apply them to the command line arguments
const userPrefs = settingsSkeleton;
Object.assign(userPrefs, JSON.parse(readFileSync(settingsPath, { encoding: 'utf-8' })));

// convert legacy settings files to newer formats
let modifiedSettings = false;

// fullscreen was a true/false, now it's "windowed", "fullscreen" or "borderless"
// initially, fullscreen was a true/false, now it's "windowed", "fullscreen" or "borderless"
if (typeof userPrefs.fullscreen === 'boolean') {
modifiedSettings = true;
if (userPrefs.fullscreen === true) userPrefs.fullscreen = 'fullscreen'; else userPrefs.fullscreen = 'windowed';
Expand All @@ -84,18 +69,14 @@ if (typeof userPrefs.fullscreen === 'boolean') {
// write the new settings format to the settings.json file right after the conversion
if (modifiedSettings) writeFileSync(settingsPath, JSON.stringify(userPrefs, null, 2), { encoding: 'utf-8' });


// Window definitions
/* eslint-disable init-declarations */
let mainWindow: BrowserWindow;
let socialWindowReference: BrowserWindow;
/* eslint-disable init-declarations */

ipcMain.on('logMainConsole', (event, data) => { console.log(data); });

// send usercript path to preload
ipcMain.on('preload_requests_userscriptPath', () => {
mainWindow.webContents.send('main_sends_userscriptPath', userscriptsPath, __dirname);
ipcMain.on('initializeUserscripts', () => {
mainWindow.webContents.send('main_initializes_userscripts', userscriptsPath, __dirname);
});

// initial request of settings to populate the settingsUI
Expand Down Expand Up @@ -162,7 +143,6 @@ function customGenericWin(url: string, providedMenuTemplate: (MenuItemConstructo
]);
}


const thisMenu = Menu.buildFromTemplate(providedMenuTemplate);

genericWin.setMenu(thisMenu);
Expand Down Expand Up @@ -253,7 +233,7 @@ app.on('ready', () => {

mainWindow.webContents.send('checkForUpdates', app.getVersion());
mainWindow.webContents.send('injectClientCSS', userPrefs, app.getVersion()); // tell preload to inject settingcss and splashcss + other
mainWindow.webContents.on('did-finish-load', () => { mainWindow.webContents.send('main_did-finish-load'); });
mainWindow.webContents.on('did-finish-load', () => { mainWindow.webContents.send('main_did-finish-load'); }); // only used to updateRPC in preload with real data

if (userPrefs.discordRPC) {
// eslint-disable-next-line
Expand Down Expand Up @@ -291,8 +271,6 @@ app.on('ready', () => {

mainWindow.loadFile(pathJoin($assets, 'dummy.html'));

// mainWindow.loadURL('https://krunker.io')

if (userPrefs.logDebugToConsole) {
console.log('GPU INFO BEGIN');
app.getGPUInfo('complete').then(completeObj => {
Expand Down Expand Up @@ -328,11 +306,6 @@ app.on('ready', () => {
{ type: 'separator' },
...constructDevtoolsSubmenu(mainWindow, userPrefs.alwaysWaitForDevTools || null)
]

/*
* you can add a relaunch command with: { label: 'Relaunch Client', accelerator: 'F10', click: () => { app.relaunch(); app.exit(); } }
* it is not recommended! - it is prone to cause memory leaks & does not restart the client fully
*/
};

if (process.platform !== 'darwin') csMenuTemplate.push({ label: 'About', submenu: aboutSubmenu });
Expand All @@ -352,7 +325,6 @@ app.on('ready', () => {
const freeSpinHostnames = ['youtube.com', 'twitch.tv', 'twitter.com', 'reddit.com', 'discord.com', 'accounts.google.com', 'instagram.com'];

// sanity check, if social window is destroyed but the reference still exists
// eslint-disable-next-line no-void
if (typeof socialWindowReference !== 'undefined' && socialWindowReference.isDestroyed()) socialWindowReference = void 0;

if (url.includes('https://krunker.io/social.html') && typeof socialWindowReference !== 'undefined') {
Expand Down Expand Up @@ -396,6 +368,7 @@ app.on('ready', () => {
mainWindow.loadURL(url);
} else { // for any other link, fall back to creating a custom window with strippedMenu.
event.preventDefault();
console.log(`genericWindow created for ${url}`, socialWindowReference);
const genericWin = customGenericWin(url, strippedMenuTemplate);
event.newGuest = genericWin;

Expand All @@ -417,19 +390,13 @@ app.on('ready', () => {
}
});

// mainWindow.webContents.on("will-navigate", (event: Event, url: string) => { console.log(url) })

// Resource Swapper, thanks idkr
if (userPrefs.resourceSwapper) {
const CrankshaftSwapInstance = new Swapper(mainWindow, swapperPath);
CrankshaftSwapInstance.start();
}
});

/*
* for the 2nd attempt at fixing the memory leak, i am just going to rely on standard electron lifecycle logic
* when all windows close, the app should exit itself
*/
// for the 2nd attempt at fixing the memory leak, i am just going to rely on standard electron lifecycle logic - when all windows close, the app should exit itself
// eslint-disable-next-line consistent-return
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') return app.quit(); // don't quit on mac systems unless user explicitly quits
Expand Down
50 changes: 26 additions & 24 deletions src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@ document.addEventListener('DOMContentLoaded', () => {
// Side Menu Settings Thing
const settingsSideMenu = document.querySelector('.menuItem[onclick*="showWindow(1)"]');
settingsSideMenu.addEventListener('click', () => { updateSettingsTabs(lastActiveTab, true, true); });

// @ts-ignore cba to add it to the window interface
try { window.windows[0].toggleType({ checked: true }); } catch (err) { strippedConsole.warn("couldn't toggle Advanced slider"); }
});

ipcRenderer.on('checkForUpdates', async(event, currentVersion) => {
Expand Down Expand Up @@ -113,9 +110,9 @@ ipcRenderer.on('initDiscordRPC', () => {
document.addEventListener('pointerlockchange', updateRPC); // thank God this exists
});

ipcRenderer.on('matchmakerRedirect', (event, _userPrefs: UserPrefs) => fetchGame(_userPrefs));
ipcRenderer.on('matchmakerRedirect', (_event, _userPrefs: UserPrefs) => fetchGame(_userPrefs));

ipcRenderer.on('injectClientCSS', (_event, _userPrefs: UserPrefs, version) => {
ipcRenderer.on('injectClientCSS', (_event, _userPrefs: UserPrefs, version: string) => {
// eslint-disable-next-line
const { matchmaker, matchmaker_F6 } = _userPrefs;

Expand Down Expand Up @@ -143,6 +140,15 @@ ipcRenderer.on('injectClientCSS', (_event, _userPrefs: UserPrefs, version) => {
innerHTML: readFileSync(pathJoin($assets, 'full_logo.svg'), { encoding: 'utf-8' })
});

const clearSplash = (_observer: MutationObserver) => {
try {
logoSVG.remove();
_observer.disconnect();
} catch (e) {
console.log('splash screen was already cleared.');
}
};

instructionHider.appendChild(logoSVG);

// i am not sure if you should be injecting more elements into a svg element, but it seems to work. feel free to pr a better version tho.
Expand All @@ -151,16 +157,12 @@ ipcRenderer.on('injectClientCSS', (_event, _userPrefs: UserPrefs, version) => {

const observerConfig = { attributes: true, childList: true, subtree: true };
const callback = (mutationList: MutationRecord[], observer: MutationObserver) => {
for (const mutation of mutationList) {
if (mutation.type === 'childList') {
logoSVG.remove();
observer.disconnect();
}
}
for (const mutation of mutationList) if (mutation.type === 'childList') clearSplash(observer);
};

const observer = new MutationObserver(callback);
observer.observe(document.getElementById('instructions'), observerConfig);
document.addEventListener('pointerlockchange', () => { clearSplash(observer); }, { once: true });
}

if (hideAds) {
Expand All @@ -170,22 +172,25 @@ ipcRenderer.on('injectClientCSS', (_event, _userPrefs: UserPrefs, version) => {
if (menuTimer) toggleSettingCSS(styleSettingsCSS.menuTimer, 'menuTimer', true);
if (quickClassPicker) toggleSettingCSS(styleSettingsCSS.quickClassPicker, 'quickClassPicker', true);
if (hideReCaptcha) toggleSettingCSS(styleSettingsCSS.hideReCaptcha, 'hideReCaptcha', true);
if (userscripts) ipcRenderer.send('preload_requests_userscriptPath');
if (userscripts) ipcRenderer.send('initializeUserscripts');
});


/**
* make sure our setting tab is always called as it should be and has the proper onclick
* @param activeTab the tab that should get active class
* @param hookSearch if true, it will also add an eventlistener to search and reset settings
* @param coldStart if client tab is selected upon launch of settings themselved, also call renderSettings()
*/
function updateSettingsTabs(activeTab: number, hookSearch = true, coldStart = false) {
strippedConsole.log('update settings tabs');
const activeClass = 'tabANew';
const settHolder = document.getElementById('settHolder');

// @ts-ignore
if (window?.windows[0]?.settingsType === 'basic') window.windows[0].toggleType({ checked: true });
if (window?.windows[0]?.settingType === 'basic') {
window.windows[0].toggleType({ checked: true });
setTimeout(() => updateSettingsTabs(activeTab, hookSearch, coldStart), 700);
return;
}

// FIXME currently, if user clicks too fast, while krunker is still loading, settings might not be hooked - investigate & fix

Expand All @@ -194,7 +199,7 @@ function updateSettingsTabs(activeTab: number, hookSearch = true, coldStart = fa
// eslint-disable-next-line no-param-reassign
hookSearch = false;

const settSearchCallback = () => { updateSettingsTabs(0, hookSearch); };
const settSearchCallback = () => updateSettingsTabs(0, hookSearch);

try {
try { document.getElementById('settSearch').removeEventListener('input', settSearchCallback); } catch (e) { }
Expand All @@ -208,14 +213,11 @@ function updateSettingsTabs(activeTab: number, hookSearch = true, coldStart = fa
}

try {
const advSliderElem = document.querySelector('.advancedSwitch input#typeBtn');
const advSwitchCallback = () => {
advSliderElem.setAttribute('disabled', 'disabled');
setTimeout(() => {
advSliderElem.removeAttribute('disabled');
updateSettingsTabs(0, true);
}, 700);
};
const advSliderElem: HTMLInputElement = document.querySelector('.advancedSwitch input#typeBtn');
advSliderElem.disabled = true;
advSliderElem.nextElementSibling.setAttribute('title', 'Crankshaft auto-enables advanced settings mode');

const advSwitchCallback = () => updateSettingsTabs(0, true);

try { advSliderElem.removeEventListener('change', advSwitchCallback); } catch (e) { }
advSliderElem.addEventListener('change', advSwitchCallback);
Expand Down
4 changes: 0 additions & 4 deletions src/resourceswapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,12 @@ const TARGET_GAME_DOMAIN = 'krunker.io';
*/
export default class {

/** Target window. */
private browserWindow: Electron.BrowserWindow;

/** The list of URLs to swap. */
private urls: string[] = [];

/** Has start() been called on the class? */
private started = false;

/** which directory to swap */
private swapDir: string;

/**
Expand Down
21 changes: 8 additions & 13 deletions src/settingsui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { writeFileSync } from 'fs';
import { ipcRenderer } from 'electron'; // add app if crashes
import { createElement, haveSameContents, toggleSettingCSS } from './utils';
import { styleSettingsCSS, classPickerBottom } from './preload';
import { styleSettingsCSS, classPickerBottom, strippedConsole } from './preload';
import { su } from './userscripts';
import { MATCHMAKER_GAMEMODES, MATCHMAKER_REGIONS } from './matchmaker';

Expand Down Expand Up @@ -254,10 +254,9 @@ class SettingElem {

/**
* update the settings when you change something in the gui
* @param {{elem: Element, callback: 'normal'|Function}} elemAndCb
* @param {{elem: HTMLElement, callback: 'normal'|Function}} elemAndCb
*/
// eslint-disable-next-line @typescript-eslint/ban-types
update({ elem, callback }: { elem: Element; callback: 'normal' | 'userscript' | Function; }) {
update({ elem, callback }: { elem: HTMLElement; callback: 'normal' | 'userscript' | Function; }) {
if (this.updateKey === '') throw 'Invalid update key';
const target = elem.querySelector('.s-update') as HTMLInputElement;

Expand Down Expand Up @@ -327,9 +326,7 @@ class SettingElem {
}


/**
* this initializes the element and its eventlisteners.
*/
/** this initializes the element and its eventlisteners.*/
get elem() {
if (this.#wrapper !== false) return this.#wrapper; // returnt he element if already initialized

Expand All @@ -356,9 +353,7 @@ class SettingElem {

// i am insane for making this

/**
* a settings generation helper. has some skeleton elements and methods that make them. purpose: prevents code duplication
*/
/** a settings generation helper. has some skeleton elements and methods that make them. purpose: prevents code duplication */
const skeleton = {
/** make a setting cateogry */
category: (title: string, innerHTML: string, elemClass = 'mainSettings') => `
Expand Down Expand Up @@ -460,7 +455,6 @@ export function renderSettings() {
{ desc: 'Go to the Crankshaft <a href="https://github.com/KraXen72/crankshaft#userscripts">README.md</a> to download some made by the client dev.' })));
}

// <div class="settingsBtn" id="userscript-disclaimer" style="width: auto;">DISCLAIMER</div>
const userscriptSettings: RenderReadySetting[] = su.userscripts
.map(userscript => {
const obj: RenderReadySetting = {
Expand All @@ -473,12 +467,13 @@ export function renderSettings() {
userscriptReference: userscript,
callback: 'userscript'
};
if (userscript.meta) { // render custom metadata if provided in userscrsipt.exported
if (userscript.meta) { // render custom metadata if provided
strippedConsole.log(`${userscript.name} has metadata:`, userscript.meta);
const thisMeta = userscript.meta;
Object.assign(obj, {
title: 'name' in thisMeta && thisMeta.name ? thisMeta.name : userscript.name,
desc: `${'desc' in thisMeta && thisMeta.desc ? thisMeta.desc.slice(0, 60) : ''}
${'author' in thisMeta && thisMeta.author ? `&#8226; by ${thisMeta.author}` : ''}
${'author' in thisMeta && thisMeta.author ? `&#8226; ${thisMeta.author}` : ''}
${'version' in thisMeta && thisMeta.version ? `&#8226; v${thisMeta.version}` : ''}
${'src' in thisMeta && thisMeta.src ? ` &#8226; <a target="_blank" href="${thisMeta.src}">source</a>` : ''}`
});
Expand Down
Loading

0 comments on commit cedb501

Please sign in to comment.