From 558e81c012c06c392d1a9a9d868743694163b345 Mon Sep 17 00:00:00 2001 From: iMumd Date: Sun, 1 Nov 2026 01:14:36 +0000 Subject: [PATCH 1/3] feat: add bounded private libraries, downloads and isolated window launching --- src/main/downloads.js | 41 +++++++++++++++++++++++++++++++++++ src/main/session.js | 5 +++-- src/main/window-launcher.js | 15 +++++++++++++ src/shared/session-library.js | 31 ++++++++++++++++++++++++++ tools/test-downloads.js | 30 +++++++++++++++++++++++++ tools/test-session-library.js | 20 +++++++++++++++++ tools/test-window-launcher.js | 19 ++++++++++++++++ 7 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 src/main/downloads.js create mode 100644 src/main/window-launcher.js create mode 100644 src/shared/session-library.js create mode 100644 tools/test-downloads.js create mode 100644 tools/test-session-library.js create mode 100644 tools/test-window-launcher.js diff --git a/src/main/downloads.js b/src/main/downloads.js new file mode 100644 index 0000000..26a4ed0 --- /dev/null +++ b/src/main/downloads.js @@ -0,0 +1,41 @@ +'use strict'; +const path = require('node:path'); +const { randomUUID } = require('node:crypto'); + +class Store { + constructor(notify = () => {}) { this.records = new Map(); this.notify = notify; } + track(item, directory) { + if (this.records.size >= 100) { + const stale = [...this.records].find(([, value]) => value.state !== 'progressing'); + if (stale) this.records.delete(stale[0]); + else { item.cancel(); return; } + } + const id = randomUUID(); + const name = String(item.getFilename() || 'download').replace(/[\\/<>:"|?*\x00-\x1f]/g, '_').slice(0, 180); + const file = path.join(directory, id + '-' + name); + item.setSavePath(file); + const record = { id, name, file, item, state: 'progressing', received: 0, total: item.getTotalBytes(), paused: false }; + this.records.set(id, record); + const update = (state) => { + record.state = state; record.received = item.getReceivedBytes(); record.total = item.getTotalBytes(); + record.paused = state === 'progressing' && item.isPaused(); this.notify(); + }; + item.on('updated', (_event, state) => update(state)); + item.once('done', (_event, state) => update(state)); + this.notify(); + return id; + } + list() { return [...this.records.values()].map(({ id, name, state, received, total, paused }) => ({ id, name, state, received, total, paused })); } + get(id) { const item = this.records.get(id); if (!item) throw new Error('Unknown download'); return item; } + control(id, action) { + const record = this.get(id); + if (record.state !== 'progressing') throw new Error('Download is not active'); + if (action === 'cancel') record.item.cancel(); + else if (action === 'pause') record.item.pause(); + else if (action === 'resume') record.item.resume(); + else throw new Error('Unsupported download action'); + record.paused = record.item.isPaused(); + this.notify(); + } +} +module.exports = { Store }; diff --git a/src/main/session.js b/src/main/session.js index a5470e2..a213dcc 100644 --- a/src/main/session.js +++ b/src/main/session.js @@ -123,9 +123,10 @@ function configureSession(ses, fp, partition, opts = {}) { try { ses.on('will-download', (event, item) => { try { + if (opts.onDownload) { opts.onDownload(item); return; } const name = item.getFilename() || `file-${Date.now()}`; - item.setSavePath(path.join(downloadDir, name)); - } catch {} + item.setSavePath(path.join(downloadDir, path.basename(name))); + } catch { try { item.cancel(); } catch {} } }); } catch {} } diff --git a/src/main/window-launcher.js b/src/main/window-launcher.js new file mode 100644 index 0000000..d82c071 --- /dev/null +++ b/src/main/window-launcher.js @@ -0,0 +1,15 @@ +'use strict'; + +// Each browser window has its own main process, session maps and temporary +// directories. Do not reuse the single-window controller's global tab state. +function launch(app, { spawn = require('node:child_process').spawn, env = process.env, auditPath } = {}) { + const environment = { ...env }; + delete environment.ELECTRON_RUN_AS_NODE; + delete environment.FATHI_WINDOW_AUDIT_PATH; + const args = app.isPackaged ? [] : [app.getAppPath()]; + if (auditPath) { args.push('--fathi-window-audit'); environment.FATHI_WINDOW_AUDIT_PATH = auditPath; } + const child = spawn(process.execPath, args, { detached: !auditPath, stdio: 'ignore', env: environment }); + if (!auditPath) child.unref(); + return child; +} +module.exports = { launch, auditWindows: new Map() }; diff --git a/src/shared/session-library.js b/src/shared/session-library.js new file mode 100644 index 0000000..a6585f2 --- /dev/null +++ b/src/shared/session-library.js @@ -0,0 +1,31 @@ +(function (root, factory) { + if (typeof module === 'object' && module.exports) module.exports = factory(); + else root.SessionLibrary = factory(); +})(typeof window === 'object' ? window : globalThis, function () { + 'use strict'; + class Store { + constructor() { this.bookmarks = []; this.history = []; this.sequence = 0; } + record(url, title = '') { + try { if (!['http:', 'https:'].includes(new URL(url).protocol)) return null; } catch { return null; } + return { id: String(++this.sequence), url, title: String(title || url), at: Date.now() }; + } + bookmark(url, title) { + const existing = this.bookmarks.find((item) => item.url === url); + if (existing) return existing; + const item = this.record(url, title); + if (item) { this.bookmarks.push(item); if (this.bookmarks.length > 200) this.bookmarks.shift(); } + return item; + } + visit(url, title) { + const item = this.record(url, title); + if (!item) return null; + if (this.history[0]?.url === url) { Object.assign(this.history[0], { title: item.title, at: item.at }); return this.history[0]; } + this.history.unshift(item); + if (this.history.length > 300) this.history.pop(); + return item; + } + removeBookmark(id) { this.bookmarks = this.bookmarks.filter((item) => item.id !== id); } + clearHistory() { this.history.length = 0; } + } + return { Store }; +}); diff --git a/tools/test-downloads.js b/tools/test-downloads.js new file mode 100644 index 0000000..87983ef --- /dev/null +++ b/tools/test-downloads.js @@ -0,0 +1,30 @@ +'use strict'; +const test = require('node:test'); const assert = require('node:assert/strict'); const path = require('node:path'); +const { EventEmitter } = require('node:events'); const { Store } = require('../src/main/downloads'); +function item(name = 'fixture.txt') { + const value = new EventEmitter(); let paused = false; + Object.assign(value, { getFilename: () => name, getReceivedBytes: () => 7, getTotalBytes: () => 10, + isPaused: () => paused, pause: () => { paused = true; }, resume: () => { paused = false; }, + cancel: () => { value.cancelled = true; }, setSavePath: (file) => { value.file = file; } }); + return value; +} +test('downloads use unique bounded temporary names and do not expose file paths', () => { + const store = new Store(); const first = item('../unsafe\\fixture.txt'); const second = item('../unsafe\\fixture.txt'); + store.track(first, path.resolve('temp')); store.track(second, path.resolve('temp')); + assert.notEqual(first.file, second.file); assert.equal(path.dirname(first.file), path.resolve('temp')); + assert.equal(store.list().length, 2); assert.equal('file' in store.list()[0], false); assert.equal('item' in store.list()[0], false); +}); +test('download progress, pause/resume and completed action validation stay truthful', () => { + const store = new Store(); const download = item(); const id = store.track(download, path.resolve('temp')); + store.control(id, 'pause'); assert.equal(store.list()[0].paused, true); + store.control(id, 'resume'); assert.equal(store.list()[0].paused, false); + download.emit('updated', {}, 'progressing'); assert.equal(store.list()[0].received, 7); + download.emit('done', {}, 'completed'); assert.equal(store.list()[0].state, 'completed'); + assert.throws(() => store.control(id, 'cancel'), /not active/); assert.throws(() => store.get('unknown'), /Unknown/); +}); +test('download cap cancels overflow rather than silently saving elsewhere', () => { + const store = new Store(); + for (let i = 0; i < 100; i++) store.track(item(), path.resolve('temp')); + const extra = item(); assert.equal(store.track(extra, path.resolve('temp')), undefined); + assert.equal(extra.cancelled, true); assert.equal(store.list().length, 100); +}); diff --git a/tools/test-session-library.js b/tools/test-session-library.js new file mode 100644 index 0000000..4e56e6d --- /dev/null +++ b/tools/test-session-library.js @@ -0,0 +1,20 @@ +'use strict'; +const test = require('node:test'); const assert = require('node:assert/strict'); +const { Store } = require('../src/shared/session-library'); +test('bookmarks deduplicate URLs and reject executable/internal schemes', () => { + const store = new Store(); + const first = store.bookmark('https://example.test/', ''); + assert.equal(store.bookmark(first.url, 'again'), first); + for (const url of ['javascript:alert(1)', 'data:text/html,bad', 'file:///secret', 'fathi://newtab', 'not a URL']) assert.equal(store.bookmark(url, 'test'), null); + assert.equal(store.bookmarks.length, 1); + store.removeBookmark(first.id); assert.equal(store.bookmarks.length, 0); +}); +test('session library bounds history/bookmarks without sharing state between windows', () => { + const store = new Store(); + for (let i = 0; i < 400; i++) { store.visit('https://example.test/' + i, 'test'); store.bookmark('https://example.test/' + i, 'test'); } + assert.equal(store.history.length, 300); assert.equal(store.bookmarks.length, 200); + store.visit('https://example.test/399', 'new title'); assert.equal(store.history.length, 300); + assert.equal(store.history[0].title, 'new title'); + store.clearHistory(); assert.equal(store.history.length, 0); assert.equal(store.bookmarks.length, 200); + const other = new Store(); assert.equal(other.history.length, 0); assert.equal(other.bookmarks.length, 0); +}); diff --git a/tools/test-window-launcher.js b/tools/test-window-launcher.js new file mode 100644 index 0000000..cbbebc5 --- /dev/null +++ b/tools/test-window-launcher.js @@ -0,0 +1,19 @@ +'use strict'; +const test = require('node:test'); const assert = require('node:assert/strict'); +const { launch } = require('../src/main/window-launcher'); +test('development windows launch the actual app, not a blank Electron process or test runner', () => { + let invocation; let unref = false; + launch({ isPackaged: false, getAppPath: () => '/browser' }, { + env: { ELECTRON_RUN_AS_NODE: '1', FATHI_WINDOW_AUDIT_PATH: 'old', SAFE: 'yes' }, + spawn: (...args) => { invocation = args; return { unref: () => { unref = true; } }; } + }); + assert.equal(invocation[0], process.execPath); assert.deepEqual(invocation[1], ['/browser']); + assert.equal(invocation[2].env.ELECTRON_RUN_AS_NODE, undefined); assert.equal(invocation[2].env.FATHI_WINDOW_AUDIT_PATH, undefined); + assert.equal(invocation[2].env.SAFE, 'yes'); assert.equal(invocation[2].stdio, 'ignore'); assert.equal(unref, true); +}); +test('packaged windows start their installed executable; audit windows are explicitly isolated', () => { + let invocation; + launch({ isPackaged: true }, { env: {}, auditPath: '/temporary/audit.json', spawn: (...args) => { invocation = args; return {}; } }); + assert.deepEqual(invocation[1], ['--fathi-window-audit']); assert.equal(invocation[2].detached, false); + assert.equal(invocation[2].env.FATHI_WINDOW_AUDIT_PATH, '/temporary/audit.json'); +}); From 725e7100dbb970bdc0ba9c15be7c1a8e22934131 Mon Sep 17 00:00:00 2001 From: iMumd Date: Sun, 1 Nov 2026 01:14:37 +0000 Subject: [PATCH 2/3] feat: wire expanded Chrome controls and preserve immediate address-bar typing --- src/main/main.js | 83 ++++++++++++- src/main/settings.js | 16 ++- src/preload/ui.js | 10 ++ src/renderer/app.js | 202 ++++++++++++++++++++++++++++--- src/renderer/i18n.js | 38 ++++++ src/renderer/index.html | 7 ++ src/renderer/styles.css | 8 ++ src/shared/shortcuts.js | 45 +++++-- tools/test-settings-shortcuts.js | 33 +++++ tools/test-shortcuts.js | 15 +++ 10 files changed, 430 insertions(+), 27 deletions(-) create mode 100644 tools/test-settings-shortcuts.js diff --git a/src/main/main.js b/src/main/main.js index eb973ed..2ed91d2 100644 --- a/src/main/main.js +++ b/src/main/main.js @@ -43,7 +43,7 @@ for (const d of [TMP_SESSION, DOWNLOAD_DIR]) { } // Chromium's cache / cookies / GPUCache all go here and are wiped on quit. app.setPath('sessionData', TMP_SESSION); -if (process.argv.includes('--fathi-e2e')) { +if (process.argv.includes('--fathi-e2e') || process.argv.includes('--fathi-window-audit')) { const testConfig = path.join(TMP_SESSION, 'test-config'); fs.mkdirSync(testConfig, { recursive: true }); app.setPath('userData', testConfig); @@ -66,6 +66,11 @@ const researchScope = require('./research-scope'); const identityRuntime = require('./identity-runtime'); const browserShortcuts = require('../shared/shortcuts'); const systemInfo = require('./system-info'); +const windowLauncher = require('./window-launcher'); +const downloads = new (require('./downloads').Store)(() => { + if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send('fathi:downloads:changed'); +}); +const auditWindows = windowLauncher.auditWindows; /* ----------------------------------------------------------------- state */ @@ -94,7 +99,7 @@ async function ensureSession(partition, fp) { proxyMgr.assign(partition); protocolPages.bind(ses); - configureSession(ses, fp, partition, { downloadDir: DOWNLOAD_DIR, proxy: false }); + configureSession(ses, fp, partition, { downloadDir: DOWNLOAD_DIR, proxy: false, onDownload: (item) => downloads.track(item, DOWNLOAD_DIR) }); partitions.set(partition, { ses, fp }); // A guest must not navigate before its proxy is configured. await proxyMgr.applyTo(ses, partition); @@ -279,10 +284,10 @@ app.on('web-contents-created', (_event, wc) => { wc.on('before-input-event', (event, input) => { if (input.type !== 'keyDown') return; - const name = browserShortcuts.resolve(input, settings.get().shortcuts); + const name = browserShortcuts.resolve(input, settings.get().shortcuts, process.platform); if (!name || !mainWindow) return; if (name !== 'stop') event.preventDefault(); - if (input.isAutoRepeat && ['newTab', 'reopenTab', 'print', 'savePage', 'fullscreen', 'devtools', 'closeWindow', 'quit'].includes(name)) return; + if (input.isAutoRepeat && ['newTab', 'newWindow', 'newPrivateWindow', 'reopenTab', 'print', 'printSystem', 'savePage', 'fullscreen', 'devtools', 'closeWindow', 'quit'].includes(name)) return; mainWindow.webContents.send('fathi:shortcut', { name, wcId: wc.id }); }); @@ -346,6 +351,58 @@ ipcMain.handle('fathi:app:info', () => ok({ })); ipcMain.handle('fathi:win:minimize', () => { if (mainWindow) mainWindow.minimize(); return ok({}); }); +ipcMain.handle('fathi:window:new', async (event, options = {}) => { + try { + if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may open a window'); + const auditPath = process.argv.includes('--fathi-e2e') + ? path.join(TMP_SESSION, `window-${require('node:crypto').randomUUID()}.json`) : undefined; + const child = windowLauncher.launch(app, { auditPath }); + await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); + if (auditPath) auditWindows.set(child.pid, { child, auditPath }); + return ok({ pid: child.pid, ...(auditPath ? { auditPath } : {}) }); + } catch (e) { return fail(e); } +}); +ipcMain.handle('fathi:window:close-audit', async (event, pid) => { + if (event.sender !== mainWindow?.webContents || !process.argv.includes('--fathi-e2e')) return fail('Test-only action'); + const record = auditWindows.get(pid); + if (!record) return fail('Unknown test window'); + const { child } = record; + if (child.exitCode === null && child.signalCode === null) await new Promise((resolve) => { child.once('exit', resolve); child.kill(); }); + auditWindows.delete(pid); + for (const directory of [path.join(os.tmpdir(), `fathi-session-${pid}`), path.join(os.tmpdir(), `fathi-downloads-${pid}`)]) { + try { fs.rmSync(directory, { recursive: true, force: true }); } catch {} + } + return ok({}); +}); +ipcMain.handle('fathi:downloads:list', (event) => event.sender === mainWindow?.webContents ? ok({ items: downloads.list() }) : fail('Only browser chrome may read downloads')); +ipcMain.handle('fathi:downloads:action', async (event, { id, action } = {}) => { + try { + if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may manage downloads'); + if (['pause', 'resume', 'cancel'].includes(action)) { downloads.control(id, action); return ok({}); } + const record = downloads.get(id); + if (record.state !== 'completed' || !fs.existsSync(record.file)) return fail('Download is not available'); + if (action === 'show') { shell.showItemInFolder(record.file); return ok({}); } + if (action !== 'save') return fail('Unsupported download action'); + const result = await dialog.showSaveDialog(mainWindow, { defaultPath: record.name }); + if (!result.canceled && result.filePath) await fs.promises.copyFile(record.file, result.filePath); + return ok({ canceled: result.canceled }); + } catch (e) { return fail(e); } +}); +ipcMain.handle('fathi:tasks:list', (event) => { + if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may read tasks'); + return ok({ items: app.getAppMetrics().map((item) => ({ pid: item.pid, type: item.type, + cpu: Number(item.cpu?.percentCPUUsage || 0), memoryMB: Number(item.memory?.workingSetSize || 0) / 1024 })) }); +}); +ipcMain.handle('fathi:privacy:clear', async (event) => { + if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may clear session data'); + try { + await Promise.all([...partitions.values()].map(async ({ ses }) => { + await ses.closeAllConnections(); await ses.clearAuthCache(); + await ses.clearStorageData(); await ses.clearCache(); await ses.clearHostResolverCache(); + })); + return ok({}); + } catch (e) { return fail(e); } +}); ipcMain.handle('fathi:win:toggle-maximize', () => { if (!mainWindow) return ok({}); mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize(); @@ -369,6 +426,13 @@ ipcMain.handle('fathi:page:print', async (event, wcId) => { return await new Promise((resolve) => wc.print({}, (success, reason) => resolve(success ? ok({}) : fail(reason || 'Printing cancelled')))); } catch (e) { return fail(e); } }); +ipcMain.handle('fathi:page:open', async (event) => { + try { + if (event.sender !== mainWindow?.webContents) return fail('Only browser chrome may open local files'); + const result = await dialog.showOpenDialog(mainWindow, { properties: ['openFile'] }); + return ok({ url: result.canceled || !result.filePaths[0] ? null : pathToFileURL(result.filePaths[0]).href }); + } catch (e) { return fail(e); } +}); ipcMain.handle('fathi:page:save', async (event, wcId) => { try { const wc = ownedPage(event, wcId); @@ -885,6 +949,17 @@ app.whenReady().then(async () => { } catch {} createWindow(); + if (process.argv.includes('--fathi-window-audit') && process.env.FATHI_WINDOW_AUDIT_PATH) { + mainWindow.webContents.once('did-finish-load', async () => { + try { + for (let i = 0; i < 150; i++) { + const state = await mainWindow.webContents.executeJavaScript(`typeof state !== 'undefined' && state.tabs.length === 1 && activeTab().identityReady && !activeTab().loading && ({ partition: activeTab().partition, focus: document.activeElement.id })`); + if (state) { fs.writeFileSync(process.env.FATHI_WINDOW_AUDIT_PATH, JSON.stringify(state)); break; } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + } catch {} + }); + } intercept.init(mainWindow); updater.init(mainWindow); network.init(mainWindow, { diff --git a/src/main/settings.js b/src/main/settings.js index 8880870..b668316 100644 --- a/src/main/settings.js +++ b/src/main/settings.js @@ -11,6 +11,7 @@ const DEFAULT_PROXY = process.env.FATHI_PROXY || ''; const DEFAULTS = { version: 2, + shortcutProfileVersion: 2, language: 'en', // 'en' | 'ar' theme: 'dark', // 'light' | 'dark' searchEngine: 'duckduckgo', @@ -98,12 +99,25 @@ function load() { raw = {}; } current = merge(DEFAULTS, raw); + let changed = false; // v1 configs shipped a light theme; v2 is black by default. if (!raw.version || raw.version < 2) { current.theme = 'dark'; current.version = 2; - try { save(current); } catch (e) {} + changed = true; } + if ((raw.shortcutProfileVersion || 0) < 2) { + const previous = isObject(raw.shortcuts) ? raw.shortcuts : {}; + const legacy = { fingerprint: 'Ctrl+D', toggleDevice: 'Ctrl+Shift+M', toggleProxy: 'Ctrl+Shift+P', toggleInterceptor: 'Ctrl+Shift+I' }; + for (const [name, value] of Object.entries(legacy)) { + const target = DEFAULTS.shortcuts[name]; + const claimed = Object.entries(previous).some(([other, binding]) => other !== name && binding === target); + if (previous[name] === value && !claimed) current.shortcuts[name] = target; + } + current.shortcutProfileVersion = 2; + changed = true; + } + if (changed) { try { save(current); } catch {} } return current; } diff --git a/src/preload/ui.js b/src/preload/ui.js index 33445cb..a6cd937 100644 --- a/src/preload/ui.js +++ b/src/preload/ui.js @@ -10,6 +10,7 @@ const EVENTS = new Set([ 'fathi:new-tab', 'fathi:close-tab', 'fathi:shortcut', + 'fathi:downloads:changed', 'fathi:win:state', 'fathi:proxy:changed', 'fathi:tor:changed', @@ -31,6 +32,7 @@ contextBridge.exposeInMainWorld('api', { }, win: { + new: (options = {}) => ipcRenderer.invoke('fathi:window:new', options), minimize: () => ipcRenderer.invoke('fathi:win:minimize'), toggleMaximize: () => ipcRenderer.invoke('fathi:win:toggle-maximize'), toggleFullscreen: () => ipcRenderer.invoke('fathi:win:toggle-fullscreen'), @@ -43,9 +45,17 @@ contextBridge.exposeInMainWorld('api', { quit: () => ipcRenderer.invoke('fathi:app:quit') }, page: { + open: () => ipcRenderer.invoke('fathi:page:open'), print: (wcId) => ipcRenderer.invoke('fathi:page:print', wcId), save: (wcId) => ipcRenderer.invoke('fathi:page:save', wcId) }, + library: { + downloads: () => ipcRenderer.invoke('fathi:downloads:list'), + download: (id, action) => ipcRenderer.invoke('fathi:downloads:action', { id, action }), + tasks: () => ipcRenderer.invoke('fathi:tasks:list'), + clear: () => ipcRenderer.invoke('fathi:privacy:clear'), + closeAuditWindow: (pid) => ipcRenderer.invoke('fathi:window:close-audit', pid) + }, fp: { create: () => ipcRenderer.invoke('fathi:fp:new'), diff --git a/src/renderer/app.js b/src/renderer/app.js index 824667c..ebe537d 100644 --- a/src/renderer/app.js +++ b/src/renderer/app.js @@ -33,6 +33,8 @@ const state = { let seq = 0; const closedTabs = []; // URL/device only, bounded and never persisted. +const sessionLibrary = new SessionLibrary.Store(); +let bookmarkBarVisible = false; /* ------------------------------------------------------------------ utils */ @@ -202,6 +204,7 @@ function searchUrl(query) { function normalizeInput(input) { const s = String(input || '').trim(); if (!s) return null; + if (s.startsWith('?')) return searchUrl(s.slice(1).trim()); if (/^fathi:\/\//i.test(s)) return s; if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) return s; if (/^[a-z][a-z0-9+.-]*:/i.test(s) && !/^\w+\.\w/.test(s)) return s; @@ -267,6 +270,15 @@ function makeTabElement(tab) { } async function createTab(opts = {}) { + const blank = !opts.url || /^fathi:\/\/newtab(?:[/?#]|$)/i.test(opts.url); + const foreground = opts.activate !== false; + if (foreground) { closeSettings(); closeGuide(); closeAppMenu(); } + if (blank && foreground) { + // Focus before asynchronous proxy/session setup, so immediate typing lands + // in the omnibox instead of the previous page. + omnibox.value = ''; + omnibox.focus(); + } const prep = await window.api.tab.prepare({ deviceId: opts.deviceId || (state.settings && state.settings.defaultDevice) || 'desktop', landscape: !!opts.landscape @@ -299,8 +311,9 @@ async function createTab(opts = {}) { proxy: prep.proxy, wv, startUrl, + sourceOf: startUrl.startsWith('view-source:') ? startUrl.slice('view-source:'.length) : null, identityReady: false, - focusAddressOnReady: !opts.url && opts.activate !== false, + focusAddressOnReady: blank && foreground, url: opts.url || startUrl, title: t('tab.new'), favicon: null, @@ -316,7 +329,7 @@ async function createTab(opts = {}) { tabstrip.insertBefore(tab.el, ref); wireWebview(tab); - if (opts.activate !== false || !state.activeId) activate(id, { focus: false }); + if (foreground || !state.activeId) activate(id, { focus: false, preserveAddress: blank && foreground }); // Safety net: if the guest was created but no navigation started (rare // first-attach race), kick it once more. @@ -326,8 +339,9 @@ async function createTab(opts = {}) { } catch {} }, 1200); - if (opts.activate !== false) { - if (!opts.url) { omnibox.focus(); omnibox.select(); } + if (foreground) { + if (blank && document.activeElement === omnibox) { /* preserve text already typed */ } + else if (blank && state.activeId === id) omnibox.focus(); else if (state.activeId === id) focusPage(tab); } refreshFingerprintList(); @@ -337,12 +351,15 @@ async function createTab(opts = {}) { function wireWebview(tab) { const wv = tab.wv; const el = tab.el; + const reportedUrl = (url) => tab.sourceOf === url ? 'view-source:' + url : url; const setTitle = (title) => { tab.title = title || t('tab.untitled'); el.querySelector('.tab-title').textContent = tab.title; el.title = tab.title + '\n' + (tab.url || ''); if (state.activeId === tab.id) document.title = tab.title + ' · Fathi'; + const visit = sessionLibrary.history.find((item) => item.url === tab.url); + if (visit) visit.title = tab.title; }; const setFavicon = (src) => { @@ -385,7 +402,7 @@ function wireWebview(tab) { wv.addEventListener('did-start-navigation', (e) => { if (!e.isMainFrame) return; - tab.url = e.url; + tab.url = reportedUrl(e.url); if (state.activeId === tab.id) { updateSecurityIcon(); if (document.activeElement !== omnibox) updateOmnibox(); @@ -393,13 +410,15 @@ function wireWebview(tab) { }); wv.addEventListener('did-navigate', (e) => { - tab.url = e.url; + tab.url = reportedUrl(e.url); + sessionLibrary.visit(tab.url, tab.title); if (state.activeId === tab.id) { updateOmnibox(); updateSecurityIcon(); updateNavButtons(); } }); wv.addEventListener('did-navigate-in-page', (e) => { if (!e.isMainFrame) return; - tab.url = e.url; + tab.url = reportedUrl(e.url); + sessionLibrary.visit(tab.url, tab.title); if (state.activeId === tab.id) { updateOmnibox(); updateSecurityIcon(); } }); @@ -500,11 +519,11 @@ function focusPage(tab = activeTab()) { try { tab.wv.focus(); } catch {} } -function activate(id, { focus = true } = {}) { +function activate(id, { focus = true, preserveAddress = false } = {}) { const tab = state.tabs.find((x) => x.id === id); if (!tab) return; if (state.activeId !== id) closeFind(false); - omnibox.blur(); + if (!preserveAddress) omnibox.blur(); state.activeId = id; for (const other of state.tabs) { @@ -690,13 +709,17 @@ function updateChips() { omnibox.addEventListener('focus', () => { omnibox.select(); }); omnibox.addEventListener('keydown', (e) => { if (e.key === 'Enter') { + e.preventDefault(); const v = omnibox.value.trim(); - if (v) navigate(v); + if (v && e.altKey) createTab({ url: normalizeInput(v) }); + else if (v && (e.ctrlKey || e.metaKey) && !/[\s/:.]/.test(v)) navigate('https://www.' + v + '.com'); + else if (v) navigate(v); else omnibox.blur(); } if (e.key === 'Escape') { - updateOmnibox(); + e.preventDefault(); omnibox.blur(); + updateOmnibox(); focusPage(); } }); omnibox.addEventListener('input', () => { @@ -1943,23 +1966,79 @@ async function runShortcut(name) { const tab = activeTab(); switch (name) { case 'newTab': return createTab(); + case 'newWindow': + case 'newPrivateWindow': { + const result = await window.api.win.new(); + if (!result.ok) toast(result.error, 'err'); + return; + } case 'closeTab': if (tab) return closeTab(tab.id); return; case 'reopenTab': return reopenClosedTab(); case 'nextTab': return cycleTab(1); case 'prevTab': return cycleTab(-1); case 'focusAddress': omnibox.focus(); omnibox.select(); return; + case 'focusSearch': omnibox.value = '? '; omnibox.focus(); omnibox.setSelectionRange(2, 2); return; + case 'focusNext': return cycleBrowserFocus(1); + case 'focusPrevious': return cycleBrowserFocus(-1); + case 'focusToolbar': return $('#toolbar button:not(:disabled)')?.focus(); + case 'focusMenu': return $('#btn-menu').focus(); + case 'focusPage': return focusPage(); + case 'focusDialog': { + const overlay = ['#guide-overlay', '#settings-overlay', '#app-menu'].map($).find((item) => !item.classList.contains('hidden')); + return [...(overlay?.querySelectorAll('input, button, textarea, select') || [])].find((item) => !item.disabled && item.getClientRects().length)?.focus(); + } + case 'moveTabLeft': return moveCurrentTab(-1); + case 'moveTabRight': return moveCurrentTab(1); + case 'openFile': { + const result = await window.api.page.open(); + if (result.ok && result.url) return createTab({ url: result.url }); + if (!result.ok) toast(result.error, 'err'); + return; + } + case 'focusBookmarks': + bookmarkBarVisible = true; renderBookmarkBar(); + return $('#bookmarks-bar button')?.focus(); + case 'menu': return openAppMenu(); + case 'bookmark': sessionLibrary.bookmark(tab?.url, tab?.title); renderBookmarkBar(); return openSettings('bookmarks'); + case 'bookmarkAll': + for (const item of state.tabs) sessionLibrary.bookmark(item.url, item.title); + renderBookmarkBar(); return openSettings('bookmarks'); + case 'bookmarkManager': return openSettings('bookmarks'); + case 'bookmarkBar': bookmarkBarVisible = !bookmarkBarVisible; return renderBookmarkBar(); + case 'history': return openSettings('history'); + case 'downloads': return openSettings('downloads'); + case 'tasks': return openSettings('tasks'); + case 'clearData': return openSettings('privacy'); + case 'searchTabs': return openSettings('tabs'); + case 'viewSource': + if (tab && /^https?:\/\//i.test(tab.url)) return createTab({ url: 'view-source:' + tab.url }); + return; + case 'inspectPage': + if (tab) { try { tab.wv.inspectElement(0, 0); } catch {} } + return; case 'reload': if (tab) { try { tab.wv.reload(); } catch {} } return; case 'hardReload': return hardReload(); case 'back': if (tab) { try { tab.wv.goBack(); } catch {} } return; case 'forward': if (tab) { try { tab.wv.goForward(); } catch {} } return; case 'home': return navigate(newTabUrl()); case 'find': return openFind(); + case 'findSelection': { + if (!tab) return; + const text = await tab.wv.executeJavaScript(`(() => { + const el = document.activeElement; + return (typeof el?.selectionStart === 'number' ? el.value.slice(el.selectionStart, el.selectionEnd) : String(window.getSelection())).slice(0, 4096); + })()`); + openFind(); + if (text) { $('#page-find-input').value = text; findInPage(true, false); } + return; + } case 'findNext': return findInPage(true); case 'findPrevious': return findInPage(false); case 'print': + case 'printSystem': case 'savePage': { if (!tab?.wcId) return; - const result = await window.api.page[name === 'print' ? 'print' : 'save'](tab.wcId); + const result = await window.api.page[name === 'savePage' ? 'save' : 'print'](tab.wcId); if (!result.ok) toast(result.error, 'err'); return; } @@ -2001,6 +2080,16 @@ function cycleTab(delta) { activate(state.tabs[next].id); } +function moveCurrentTab(delta) { + const tab = activeTab(); + const from = state.tabs.indexOf(tab); + const to = Math.max(0, Math.min(state.tabs.length - 1, from + delta)); + if (from < 0 || from === to) return; + state.tabs.splice(from, 1); state.tabs.splice(to, 0, tab); + state.tabs.forEach((item) => tabstrip.appendChild(item.el)); + tab.el.scrollIntoView({ block: 'nearest', inline: 'nearest' }); +} + async function toggleInterceptor() { const res = await window.api.intercept.set(!ix.enabled); if (res && res.ok) { @@ -2016,10 +2105,10 @@ async function toggleInterceptor() { document.addEventListener('keydown', (e) => { if (e.defaultPrevented) return; if (e.isComposing) return; - const name = BrowserShortcuts.resolve(e, shortcuts()); + const name = BrowserShortcuts.resolve(e, shortcuts(), state.info?.platform); if (!name) return; e.preventDefault(); - if (e.repeat && ['newTab', 'reopenTab', 'print', 'savePage', 'fullscreen', 'devtools', 'closeWindow', 'quit'].includes(name)) return; + if (e.repeat && ['newTab', 'newWindow', 'newPrivateWindow', 'reopenTab', 'print', 'printSystem', 'savePage', 'fullscreen', 'devtools', 'closeWindow', 'quit'].includes(name)) return; runShortcut(name); }); @@ -2140,8 +2229,22 @@ function openAppMenu() { menu.style.top = Math.max(8, top) + 'px'; const version = $('#am-version'); if (version && state.info) version.textContent = 'v' + state.info.version; + menu.querySelector('button:not(:disabled)')?.focus(); } +$('#app-menu').addEventListener('keydown', (event) => { + const buttons = [...$('#app-menu').querySelectorAll('button:not(:disabled)')]; + if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { + event.preventDefault(); event.stopPropagation(); + const index = buttons.indexOf(document.activeElement); + const next = event.key === 'Home' ? 0 : event.key === 'End' ? buttons.length - 1 + : (index + (event.key === 'ArrowDown' ? 1 : -1) + buttons.length) % buttons.length; + buttons[next]?.focus(); + } + if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeAppMenu(); $('#app-menu-btn').focus(); } + if (event.key.toLowerCase() === 'x' && !(event.ctrlKey || event.metaKey || event.altKey)) { event.preventDefault(); window.api.app.quit(); } +}); + function closeAppMenu() { $('#app-menu')?.classList.add('hidden'); } @@ -2302,6 +2405,71 @@ function openSettings(section) { renderSection(state.section); } +function cycleBrowserFocus(delta) { + const targets = [omnibox, $('#newtab-btn'), $('#btn-menu'), activeTab()?.wv].filter(Boolean); + const current = targets.indexOf(document.activeElement); + const next = targets[(current + delta + targets.length) % targets.length]; + next?.focus(); +} + +function renderBookmarkBar() { + const bar = $('#bookmarks-bar'); + bar.classList.toggle('hidden', !bookmarkBarVisible); + bar.innerHTML = sessionLibrary.bookmarks.map((item) => ``).join(''); + bar.querySelectorAll('[data-bookmark]').forEach((button) => button.addEventListener('click', (event) => { + const item = sessionLibrary.bookmarks.find((entry) => entry.id === button.dataset.bookmark); + if (item) event.ctrlKey || event.metaKey ? createTab({ url: item.url, activate: false }) : navigate(item.url); + })); +} + +async function renderLibrary(section) { + const body = $('#settings-body'); + const heading = `

${esc(t('library.' + section))}

${esc(t('library.ephemeral'))}

`; + if (section === 'privacy') { + body.innerHTML = `${heading}

${esc(t('library.clearHint'))}

`; + $('#clear-session-data').addEventListener('click', async (event) => { + event.currentTarget.disabled = true; + const result = await window.api.library.clear(); + if (result.ok) sessionLibrary.clearHistory(); + const status = $('#clear-session-status'); + if (status) status.textContent = result.ok ? t('library.cleared') : result.error; + }); + return; + } + if (section === 'downloads' || section === 'tasks') { + const result = await window.api.library[section === 'downloads' ? 'downloads' : 'tasks'](); + if (state.section !== section) return; + if (!result.ok) { body.innerHTML = `${heading}

${esc(result.error)}

`; return; } + body.innerHTML = heading + (section === 'downloads' + ? result.items.map((item) => `
${esc(item.name)}${esc(item.state)} · ${item.received} / ${item.total} B
${(item.state === 'completed' ? ['save', 'show'] : item.state === 'progressing' ? [item.paused ? 'resume' : 'pause', 'cancel'] : []).map((action) => ``).join('')}
`).join('') + : `${result.items.map((item) => ``).join('')}
PID${esc(t('library.process'))}CPU %MiB
${item.pid}${esc(item.type)}${item.cpu.toFixed(1)}${item.memoryMB.toFixed(1)}
`) + ``; + $('#library-refresh').addEventListener('click', () => renderLibrary(section)); + body.querySelectorAll('[data-download]').forEach((button) => button.addEventListener('click', async () => { + const response = await window.api.library.download(button.dataset.download, button.dataset.action); + if (!response.ok) toast(response.error, 'err'); + if (state.section === section) renderLibrary(section); + })); + return; + } + const items = section === 'tabs' ? state.tabs.map((tab) => ({ id: tab.id, url: tab.url, title: tab.title })) + : section === 'bookmarks' ? sessionLibrary.bookmarks : sessionLibrary.history; + body.innerHTML = `${heading}
`; + const render = () => { + const query = $('#library-filter').value.toLowerCase(); + $('#library-results').innerHTML = items.filter((item) => (item.title + ' ' + item.url).toLowerCase().includes(query)).map((item) => `
${esc(item.url)}${section === 'bookmarks' ? `` : ''}
`).join(''); + body.querySelectorAll('[data-entry]').forEach((button) => button.addEventListener('click', () => { + const item = items.find((entry) => entry.id === button.dataset.entry); + closeSettings(); + if (section === 'tabs') activate(item.id); else createTab({ url: item.url }); + })); + body.querySelectorAll('[data-remove-bookmark]').forEach((button) => button.addEventListener('click', () => { + sessionLibrary.removeBookmark(button.dataset.removeBookmark); renderBookmarkBar(); renderLibrary(section); + })); + }; + $('#library-filter').addEventListener('input', render); render(); + $('#library-filter').focus(); +} + function closeSettings() { $('#settings-overlay').classList.add('hidden'); } @@ -2339,6 +2507,7 @@ const CHECK_LINKS = [ function renderSection(section) { const body = $('#settings-body'); const S = state.settings || {}; + if (['bookmarks', 'history', 'downloads', 'tasks', 'privacy', 'tabs'].includes(section)) { renderLibrary(section); return; } if (section === 'research') { renderResearch(); return; } if (section === 'whatsnew') { @@ -3258,6 +3427,11 @@ window.api.on('fathi:shortcut', ({ name, wcId }) => { runShortcut(name); }); window.api.on('fathi:focus-omnibox', () => { omnibox.focus(); omnibox.select(); }); +let downloadRefresh = null; +window.api.on('fathi:downloads:changed', () => { + if (downloadRefresh || state.section !== 'downloads' || $('#settings-overlay').classList.contains('hidden')) return; + downloadRefresh = setTimeout(() => { downloadRefresh = null; if (state.section === 'downloads') renderLibrary('downloads'); }, 150); +}); window.api.on('fathi:new-tab', () => createTab()); window.api.on('fathi:close-tab', ({ wcId }) => { const tab = tabByWcId(wcId); diff --git a/src/renderer/i18n.js b/src/renderer/i18n.js index 1402424..eefdf0b 100644 --- a/src/renderer/i18n.js +++ b/src/renderer/i18n.js @@ -6,6 +6,25 @@ (function () { const DICT = { en: { + 'sc.newWindow': 'New private window', 'sc.newPrivateWindow': 'New private window (alternate)', + 'sc.printSystem': 'System print dialog', 'sc.focusBookmarks': 'Focus the bookmarks bar', + 'sc.findSelection': 'Find selected text in this page', + 'sc.moveTabLeft': 'Move tab left', 'sc.moveTabRight': 'Move tab right', 'sc.openFile': 'Open a local file', + 'sc.focusPage': 'Focus page contents', 'sc.focusDialog': 'Focus the open dialog', 'sc.focusMenu': 'Focus the last toolbar control', + 'sc.focusSearch': 'Search from the address bar', 'sc.focusNext': 'Next browser area', 'sc.focusPrevious': 'Previous browser area', + 'sc.focusToolbar': 'Focus the toolbar', 'sc.menu': 'Open the browser menu', 'sc.viewSource': 'View page source', + 'sc.inspectPage': 'Inspect the page', 'sc.bookmark': 'Bookmark this page for this session', + 'sc.bookmarkAll': 'Bookmark all tabs for this session', 'sc.bookmarkManager': 'Session bookmarks', + 'sc.bookmarkBar': 'Toggle the bookmarks bar', 'sc.history': 'Session history', 'sc.downloads': 'Downloads', + 'sc.tasks': 'Task manager', 'sc.clearData': 'Clear session data', 'sc.searchTabs': 'Search open tabs', + 'library.bookmarks': 'Session bookmarks', 'library.history': 'Session history', 'library.downloads': 'Downloads', + 'library.tasks': 'Window task manager', 'library.privacy': 'Clear session data', 'library.tabs': 'Search open tabs', + 'library.ephemeral': 'Private and session-only. Records are not saved to disk. Downloads stay in temporary storage unless you explicitly save a copy.', + 'library.clearHint': 'Clear history, cookies, storage, authentication and cache for all tabs in this window. Bookmarks are retained. Other windows are independent.', + 'library.clear': 'Clear this window’s session data', 'library.cleared': 'Session data cleared.', + 'library.save': 'Save a copy', 'library.show': 'Show temporary file', 'library.pause': 'Pause', 'library.resume': 'Resume', + 'library.cancel': 'Cancel', 'library.process': 'Process', 'library.refresh': 'Refresh', 'library.search': 'Search title or URL', + 'library.remove': 'Remove', 'sc.home': 'Open the home page', 'sc.find': 'Find in page', 'sc.findNext': 'Next match', @@ -575,6 +594,25 @@ }, ar: { + 'sc.newWindow': 'نافذة خاصة جديدة', 'sc.newPrivateWindow': 'نافذة خاصة جديدة (بديل)', + 'sc.printSystem': 'حوار طباعة النظام', 'sc.focusBookmarks': 'التركيز على شريط العلامات', + 'sc.findSelection': 'البحث عن النص المحدد في الصفحة', + 'sc.moveTabLeft': 'نقل التبويب لليسار', 'sc.moveTabRight': 'نقل التبويب لليمين', 'sc.openFile': 'فتح ملف محلي', + 'sc.focusPage': 'التركيز على محتوى الصفحة', 'sc.focusDialog': 'التركيز على الحوار المفتوح', 'sc.focusMenu': 'التركيز على آخر عنصر بالأدوات', + 'sc.focusSearch': 'البحث من شريط العنوان', 'sc.focusNext': 'منطقة المتصفح التالية', 'sc.focusPrevious': 'منطقة المتصفح السابقة', + 'sc.focusToolbar': 'التركيز على شريط الأدوات', 'sc.menu': 'فتح قائمة المتصفح', 'sc.viewSource': 'عرض مصدر الصفحة', + 'sc.inspectPage': 'فحص الصفحة', 'sc.bookmark': 'حفظ الصفحة في علامات الجلسة', + 'sc.bookmarkAll': 'حفظ جميع التبويبات في علامات الجلسة', 'sc.bookmarkManager': 'علامات الجلسة', + 'sc.bookmarkBar': 'إظهار شريط العلامات أو إخفاؤه', 'sc.history': 'سجل الجلسة', 'sc.downloads': 'التنزيلات', + 'sc.tasks': 'مدير المهام', 'sc.clearData': 'مسح بيانات الجلسة', 'sc.searchTabs': 'البحث في التبويبات المفتوحة', + 'library.bookmarks': 'علامات الجلسة', 'library.history': 'سجل الجلسة', 'library.downloads': 'التنزيلات', + 'library.tasks': 'مدير مهام النافذة', 'library.privacy': 'مسح بيانات الجلسة', 'library.tabs': 'البحث في التبويبات', + 'library.ephemeral': 'خاصة ومؤقتة للجلسة. لا تُحفظ السجلات على القرص. تبقى التنزيلات مؤقتة ما لم تحفظ نسخة صراحةً.', + 'library.clearHint': 'مسح السجل والكوكيز والتخزين والمصادقة والكاش لكل تبويبات هذه النافذة. تبقى العلامات. النوافذ الأخرى مستقلة.', + 'library.clear': 'مسح بيانات جلسة هذه النافذة', 'library.cleared': 'تم مسح بيانات الجلسة.', + 'library.save': 'حفظ نسخة', 'library.show': 'عرض الملف المؤقت', 'library.pause': 'إيقاف مؤقت', 'library.resume': 'استئناف', + 'library.cancel': 'إلغاء', 'library.process': 'العملية', 'library.refresh': 'تحديث', 'library.search': 'البحث بالعنوان أو الرابط', + 'library.remove': 'إزالة', 'sc.home': 'فتح الصفحة الرئيسية', 'sc.find': 'البحث في الصفحة', 'sc.findNext': 'النتيجة التالية', diff --git a/src/renderer/index.html b/src/renderer/index.html index ed093b1..8d8ebe5 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -107,6 +107,7 @@ +