-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
489 lines (450 loc) · 18.7 KB
/
Copy pathmain.js
File metadata and controls
489 lines (450 loc) · 18.7 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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
const { app, BaseWindow, WebContentsView, session, net, ipcMain } = require('electron');
const path = require('node:path');
const fs = require('node:fs');
const { mangle } = require('./glitch/mangle');
const DEBUG = !!process.env.WRONG_DEBUG;
const CHROME_DEFAULT = 80;
const CHROME_EXPANDED = 340;
let chromeHeight = CHROME_DEFAULT;
const PARTITION = 'persist:glitch';
// Persistent settings
const settingsPath = () => path.join(app.getPath('userData'), 'settings.json');
function loadSettings() {
try { return JSON.parse(fs.readFileSync(settingsPath(), 'utf8')); }
catch { return null; }
}
function saveSettings(s) {
try { fs.mkdirSync(path.dirname(settingsPath()), { recursive: true }); }
catch {}
// Write to a temp file then atomically rename, so a crash/kill mid-write can
// never leave a half-written settings.json (which loadSettings would treat as
// corrupt and silently discard, resetting the user back to defaults).
const p = settingsPath();
const tmp = p + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(s, null, 2));
fs.renameSync(tmp, p);
}
const defaultSettings = {
intensity: 0.005,
enabled: true,
videoEnabled: false,
videoFx: 0,
zalgoIntensity: 0.4,
zalgoEnabled: true,
cssFilter: 'none',
audioGlitch: 0,
profile: 'custom',
};
const state = Object.assign({}, defaultSettings, loadSettings() || {});
// Persist is debounced: dragging a slider fires set-* IPC dozens of times a
// second, and a synchronous disk write on each blocks the main process. Coalesce
// into a trailing write, and flush synchronously on quit so nothing is lost.
let persistTimer = null;
function persist() {
if (persistTimer) return;
persistTimer = setTimeout(() => {
persistTimer = null;
try { saveSettings(state); } catch (e) { if (DEBUG) console.warn('[GB] persist failed:', e); }
}, 400);
}
function persistNow() {
if (persistTimer) { clearTimeout(persistTimer); persistTimer = null; }
try { saveSettings(state); } catch (e) { if (DEBUG) console.warn('[GB] persist failed:', e); }
}
// Whitelist + clamp a profile object coming from the renderer before it is
// merged into state. apply-profile would otherwise Object.assign raw input,
// bypassing every per-setter clamp and letting arbitrary keys reach disk.
const clamp = (v, lo, hi, dflt) => {
const n = Number(v);
if (!Number.isFinite(n)) return dflt;
return n < lo ? lo : n > hi ? hi : n;
};
function sanitizeProfile(p) {
if (!p || typeof p !== 'object') return {};
const out = {};
if ('intensity' in p) out.intensity = clamp(p.intensity, 0, 0.2, state.intensity);
if ('videoFx' in p) out.videoFx = clamp(p.videoFx, 0, 1, state.videoFx);
if ('zalgoIntensity' in p) out.zalgoIntensity = clamp(p.zalgoIntensity, 0, 1, state.zalgoIntensity);
if ('audioGlitch' in p) out.audioGlitch = clamp(p.audioGlitch, 0, 1, state.audioGlitch);
if ('enabled' in p) out.enabled = !!p.enabled;
if ('videoEnabled' in p) out.videoEnabled = !!p.videoEnabled;
if ('zalgoEnabled' in p) out.zalgoEnabled = !!p.zalgoEnabled;
if ('cssFilter' in p) out.cssFilter = String(p.cssFilter || 'none');
return out;
}
app.setName('WRONG');
if (process.argv.includes('--cpu')) {
app.disableHardwareAcceleration();
app.commandLine.appendSwitch('disable-gpu');
app.commandLine.appendSwitch('disable-gpu-compositing');
}
// On Windows, hardware video decode keeps decoded frames in a GPU texture path
// that drawImage(video) to a 2D canvas can't reliably read back — frame-level
// mosh sees black/empty pixels and renders nothing. Forcing software video
// decode lets the canvas pull real pixels.
if (process.platform === 'win32') {
app.commandLine.appendSwitch('disable-accelerated-video-decode');
app.commandLine.appendSwitch('disable-features', 'UseDXGIMapStaging');
}
let win, chrome;
const tabs = []; // { id, view, title, url }
let activeId = null;
let nextTabId = 1;
function activeTab() { return tabs.find(t => t.id === activeId) || null; }
function broadcastGlitch(view) {
view.webContents.send('zalgo', state.zalgoIntensity, state.zalgoEnabled);
view.webContents.send('css-filter', state.cssFilter);
view.webContents.send('audio-glitch', state.audioGlitch);
view.webContents.send('video-fx', state.videoFx);
}
function sendTabsToChrome() {
if (!chrome) return;
chrome.webContents.send('tabs', {
tabs: tabs.map(t => ({ id: t.id, title: t.title || 'new tab', url: t.url || '' })),
activeId,
});
}
// Tell each tab whether it's the active one, so inactive (parked off-screen)
// tabs can stop running the per-frame video mosh.
function broadcastActive() {
for (const t of tabs) {
try { t.view.webContents.send('tab-active', t.id === activeId); } catch {}
}
}
function layout() {
if (!win) return;
const { width, height } = win.getContentBounds();
chrome.setBounds({ x: 0, y: 0, width, height: chromeHeight });
for (const t of tabs) {
const visible = t.id === activeId;
t.view.setBounds({
x: 0,
y: visible ? chromeHeight : -10000,
width,
height: Math.max(0, height - chromeHeight),
});
}
}
const NEWTAB_URL = 'file://' + path.join(__dirname, 'newtab.html');
const PROFILES = {
off: { intensity: 0, enabled: false, zalgoIntensity: 0, zalgoEnabled: false, audioGlitch: 0, videoFx: 0, cssFilter: 'none' },
subtle: { intensity: 0.003, enabled: true, zalgoIntensity: 0.15, zalgoEnabled: true, audioGlitch: 0, videoFx: 0, cssFilter: 'none' },
heavy: { intensity: 0.02, enabled: true, zalgoIntensity: 0.6, zalgoEnabled: true, audioGlitch: 0.1, videoFx: 0.5, cssFilter: 'chromatic' },
videodrome: { intensity: 0.04, enabled: true, zalgoIntensity: 1.0, zalgoEnabled: true, audioGlitch: 0.3, videoFx: 0.75, cssFilter: 'vhs' },
vaporwave: { intensity: 0.005, enabled: true, zalgoIntensity: 0.2, zalgoEnabled: true, audioGlitch: 0, videoFx: 0.25, cssFilter: 'hue' },
datamosh: { intensity: 0.06, enabled: true, zalgoIntensity: 0, zalgoEnabled: false, audioGlitch: 0.05, videoFx: 0.9, cssFilter: 'scan' },
};
function createTab(initialUrl = NEWTAB_URL) {
const id = nextTabId++;
const view = new WebContentsView({
webPreferences: {
partition: PARTITION,
preload: path.join(__dirname, 'preload.js'),
sandbox: false,
},
});
const tab = { id, view, title: 'new tab', url: initialUrl };
tabs.push(tab);
win.contentView.addChildView(view);
const wc = view.webContents;
wc.on('page-title-updated', (_e, title) => {
tab.title = title;
sendTabsToChrome();
});
const onNav = (_e, url) => {
tab.url = url;
if (tab.id === activeId) chrome.webContents.send('url-changed', url);
sendTabsToChrome();
};
wc.on('did-navigate', onNav);
wc.on('did-navigate-in-page', onNav);
wc.on('did-finish-load', () => { broadcastGlitch(view); wc.send('tab-active', tab.id === activeId); });
wc.on('before-input-event', handleShortcut);
if (DEBUG) {
wc.on('console-message', (_e, _level, message) => {
if (message.startsWith('[GB]')) console.log(`[tab ${id}] ${message}`);
});
}
wc.setWindowOpenHandler(({ url }) => {
createTab(url);
return { action: 'deny' };
});
wc.on('render-process-gone', (_e, details) => {
if (details.reason === 'clean-exit') return;
tab.title = `[crashed] ${tab.title}`;
sendTabsToChrome();
// Auto-reload once after a short delay; if it crashes again leave it.
if (!tab._reloadedAfterCrash) {
tab._reloadedAfterCrash = true;
tab._reloadTimer = setTimeout(() => {
tab._reloadTimer = null;
try { wc.reload(); } catch {}
}, 500);
}
});
wc.loadURL(initialUrl);
setActiveTab(id);
return tab;
}
function setActiveTab(id) {
if (!tabs.find(t => t.id === id)) return;
activeId = id;
layout();
const t = activeTab();
if (t) chrome.webContents.send('url-changed', t.url || '');
sendTabsToChrome();
broadcastActive();
}
function closeTab(id) {
const idx = tabs.findIndex(t => t.id === id);
if (idx < 0) return;
const tab = tabs[idx];
if (tab._reloadTimer) { clearTimeout(tab._reloadTimer); tab._reloadTimer = null; }
win.contentView.removeChildView(tab.view);
tab.view.webContents.close();
tabs.splice(idx, 1);
if (tabs.length === 0) {
createTab(NEWTAB_URL);
return;
}
if (activeId === id) {
setActiveTab(tabs[Math.min(idx, tabs.length - 1)].id);
} else {
sendTabsToChrome();
}
}
function cycleTab(dir) {
if (tabs.length < 2) return;
const idx = tabs.findIndex(t => t.id === activeId);
const next = (idx + dir + tabs.length) % tabs.length;
setActiveTab(tabs[next].id);
}
function handleShortcut(event, input) {
if (input.type !== 'keyDown') return;
const key = input.key.toLowerCase();
if (input.key === 'F11') {
win.setFullScreen(!win.isFullScreen());
event.preventDefault();
} else if (input.key === 'Escape' && win.isFullScreen()) {
win.setFullScreen(false);
event.preventDefault();
} else if (input.control && key === 'l') {
chrome.webContents.focus();
chrome.webContents.send('focus-url');
event.preventDefault();
} else if (input.control && key === 'r') {
activeTab()?.view.webContents.reload();
event.preventDefault();
} else if (input.control && key === 't') {
createTab(NEWTAB_URL);
chrome.webContents.send('focus-url');
event.preventDefault();
} else if (input.control && key === 'w') {
if (activeId) closeTab(activeId);
event.preventDefault();
} else if (input.control && input.key === 'Tab') {
cycleTab(input.shift ? -1 : 1);
event.preventDefault();
} else if (input.control && key === 'f') {
chrome.webContents.send('open-find');
event.preventDefault();
} else if (input.control && input.shift && key === 'i') {
activeTab()?.view.webContents.openDevTools({ mode: 'detach' });
event.preventDefault();
} else if (input.alt && input.key === 'ArrowLeft') {
const t = activeTab();
if (t && t.view.webContents.navigationHistory.canGoBack()) t.view.webContents.navigationHistory.goBack();
event.preventDefault();
} else if (input.alt && input.key === 'ArrowRight') {
const t = activeTab();
if (t && t.view.webContents.navigationHistory.canGoForward()) t.view.webContents.navigationHistory.goForward();
event.preventDefault();
} else if (input.control && /^[1-9]$/.test(input.key)) {
const n = parseInt(input.key, 10) - 1;
if (tabs[n]) setActiveTab(tabs[n].id);
event.preventDefault();
}
}
app.whenReady().then(() => {
const ses = session.fromPartition(PARTITION);
// Read a body capped at `max` bytes. If it fits, return its bytes for
// mangling. If it exceeds the cap, return a ReadableStream that re-emits the
// buffered chunks then streams the rest unchanged — so main-process memory
// stays bounded to ~max and we never hand back an already-consumed Response.
const readCapped = async (body, max) => {
const reader = body.getReader();
const chunks = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
total += value.length;
if (total > max) {
const stream = new ReadableStream({
start(controller) { for (const c of chunks) controller.enqueue(c); },
async pull(controller) {
const r = await reader.read();
if (r.done) controller.close();
else controller.enqueue(r.value);
},
cancel(reason) { return reader.cancel(reason); },
});
return { stream };
}
}
const bytes = new Uint8Array(total);
let o = 0;
for (const c of chunks) { bytes.set(c, o); o += c.length; }
return { bytes };
};
const handle = async (request) => {
let upstream;
try {
upstream = await net.fetch(request, { bypassCustomProtocolHandlers: true });
if (!state.enabled || state.intensity <= 0) return upstream;
// Null-body statuses (1xx, 204, 205, 304) can't be wrapped in a Response
// with bytes — Response constructor throws. Pass through unchanged.
const s = upstream.status;
if (s === 204 || s === 205 || s === 304 || (s >= 100 && s < 200)) return upstream;
// content-type tokens are case-insensitive; lowercase so e.g. IMAGE/PNG
// is matched and so mangle()'s own startsWith dispatch stays consistent.
const ct = (upstream.headers.get('content-type') ?? '').toLowerCase();
const isImage = /^image\//.test(ct);
// octet-stream included so CDNs serving fragmented mp4/webm as a generic
// binary type still reach the (container-sniffing) AV mangler.
const isAV = /^(audio|video)\//.test(ct) || ct === 'application/octet-stream';
if (!isImage && !isAV) return upstream;
// Video/audio byte mangling crashes decoders too easily; opt-in only.
if (isAV && !state.videoEnabled) return upstream;
if (!upstream.body) return upstream;
const MAX_BYTES = isImage ? 12 * 1024 * 1024 : 4 * 1024 * 1024;
const lenHeader = upstream.headers.get('content-length');
if (lenHeader && parseInt(lenHeader, 10) > MAX_BYTES) return upstream;
const headers = new Headers(upstream.headers);
headers.delete('content-length'); // body is re-emitted chunked
const { bytes, stream } = await readCapped(upstream.body, MAX_BYTES);
// Over the cap: pass the original bytes through unmodified (bounded mem).
if (stream) return new Response(stream, { status: s, headers });
if (bytes.length > 0) mangle(bytes, ct, state.intensity);
return new Response(bytes, { status: s, headers });
} catch (e) {
if (DEBUG) console.warn('[GB] protocol handle failed:', request.url, e?.message || e);
// Routine network failures (DNS, reset, TLS, abort) reach here. Re-throw
// so Chromium shows its normal error path instead of an unhandled
// rejection; only pass upstream through if its body is still intact.
if (upstream && !upstream.bodyUsed) return upstream;
throw e;
}
};
ses.protocol.handle('https', handle);
ses.protocol.handle('http', handle);
win = new BaseWindow({
width: 1280,
height: 800,
title: 'WRONG',
backgroundColor: '#000',
show: false,
icon: path.join(__dirname, 'build/icon.png'),
});
win.maximize();
win.show();
chrome = new WebContentsView({
webPreferences: { preload: path.join(__dirname, 'chrome-preload.js') },
});
win.contentView.addChildView(chrome);
chrome.webContents.loadFile('chrome.html');
chrome.webContents.on('before-input-event', handleShortcut);
chrome.webContents.once('did-finish-load', () => {
chrome.webContents.send('init-state', state);
createTab(NEWTAB_URL);
});
win.on('resize', layout);
win.on('maximize', layout);
win.on('unmaximize', layout);
win.on('enter-full-screen', layout);
win.on('leave-full-screen', layout);
// IPC
ipcMain.on('navigate', (_e, url) => {
if (!/^[a-z]+:\/\//i.test(url)) {
// crude: contains a dot and no spaces -> url, else search
if (/^\S+\.\S+/.test(url)) url = 'https://' + url;
else url = 'https://duckduckgo.com/?q=' + encodeURIComponent(url);
}
activeTab()?.view.webContents.loadURL(url);
});
ipcMain.on('back', () => {
const t = activeTab();
if (t?.view.webContents.navigationHistory.canGoBack()) t.view.webContents.navigationHistory.goBack();
});
ipcMain.on('forward', () => {
const t = activeTab();
if (t?.view.webContents.navigationHistory.canGoForward()) t.view.webContents.navigationHistory.goForward();
});
ipcMain.on('reload', () => activeTab()?.view.webContents.reload());
ipcMain.on('tab:new', (_e, url) => createTab(url || NEWTAB_URL));
ipcMain.on('tab:close', (_e, id) => closeTab(id));
ipcMain.on('tab:activate', (_e, id) => setActiveTab(id));
ipcMain.on('find', (_e, text) => {
const t = activeTab();
if (!t) return;
if (text) t.view.webContents.findInPage(text);
else t.view.webContents.stopFindInPage('clearSelection');
});
ipcMain.on('find-stop', () => {
activeTab()?.view.webContents.stopFindInPage('clearSelection');
});
const broadcastAll = () => { for (const t of tabs) broadcastGlitch(t.view); };
ipcMain.on('set-intensity', (_e, v) => { state.intensity = Math.max(0, Math.min(0.2, v)); persist(); });
ipcMain.on('toggle-enabled', (_e, v) => { state.enabled = !!v; persist(); });
ipcMain.on('toggle-video', (_e, v) => { state.videoEnabled = !!v; persist(); });
ipcMain.on('set-zalgo', (_e, v) => { state.zalgoIntensity = Math.max(0, Math.min(1, v)); broadcastAll(); persist(); });
ipcMain.on('toggle-zalgo', (_e, v) => { state.zalgoEnabled = !!v; broadcastAll(); persist(); });
ipcMain.on('set-css-filter', (_e, name) => { state.cssFilter = name; broadcastAll(); persist(); });
ipcMain.on('set-audio-glitch', (_e, v) => { state.audioGlitch = Math.max(0, Math.min(1, v)); broadcastAll(); persist(); });
ipcMain.on('set-video-fx', (_e, v) => { state.videoFx = Math.max(0, Math.min(1, v)); broadcastAll(); persist(); });
ipcMain.on('apply-profile', (_e, p) => {
Object.assign(state, sanitizeProfile(p), { profile: (p && p.name) || 'custom' });
broadcastAll();
persist();
chrome.webContents.send('init-state', state);
});
ipcMain.on('apply-profile-by-name', (_e, name) => {
const p = PROFILES[name];
if (!p) return;
Object.assign(state, p, { profile: name });
broadcastAll();
persist();
chrome.webContents.send('init-state', state);
});
ipcMain.on('relaunch', (_e, mode) => {
persistNow();
const cpuFlag = mode === 'cpu' ? ['--cpu'] : [];
// AppImage / portable .exe both extract to a temp dir that dies when
// the parent process exits — so relaunching against process.execPath
// points at a path that no longer exists by the time the child spawns.
// electron-builder sets these env vars to the persistent launcher path.
const launcher = process.env.APPIMAGE || process.env.PORTABLE_EXECUTABLE_FILE;
let opts;
if (launcher) {
opts = { execPath: launcher, args: cpuFlag };
} else {
// Dev / installed: process.argv = [electron-bin, app-path, ...flags]
const base = process.argv.slice(1).filter(a => a !== '--cpu');
opts = { args: [...base, ...cpuFlag] };
}
try { app.relaunch(opts); } catch (e) { if (DEBUG) console.warn('[GB] relaunch failed:', e); }
app.quit();
});
ipcMain.handle('get-mode', () => process.argv.includes('--cpu') ? 'cpu' : 'gpu');
ipcMain.on('chrome-expanded', (_e, val) => {
// true -> full settings popover; a number -> exact height (e.g. the find
// bar only needs a little); anything else collapses back to the toolbar.
if (val === true) chromeHeight = CHROME_EXPANDED;
else if (typeof val === 'number' && val > CHROME_DEFAULT) chromeHeight = val;
else chromeHeight = CHROME_DEFAULT;
layout();
});
});
app.on('before-quit', persistNow); // flush any debounced settings write
app.on('window-all-closed', () => app.quit());