diff --git a/CHANGELOG.md b/CHANGELOG.md index 51dcebc..b483060 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +- Focus new tabs before session setup and preserve immediately typed search text, + including explicit new-tab URLs and native toolbar clicks. +- Add real independent private windows, session bookmarks/history, temporary + download management, process metrics, tab search and explicit session clearing. +- Expand the Chrome-style profile with tab reordering, source viewing, local-file + opening, search/toolbar focus, platform aliases and legacy-default migration. - Unify Chrome-style keyboard shortcuts across browser chrome and page input, including tab cycling/selection, real URL reopening with a fresh identity, find, zoom, reload, fullscreen, page save/print and DevTools. diff --git a/README.md b/README.md index 48d1757..65bf85c 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,11 @@ Live rules cover header values and supported text bodies, including when manual interception is off. See the [rule limits](docs/interception-and-rules.md) before relying on a transformation. +The [keyboard profile](docs/keyboard-shortcuts.md) includes new private windows, +session bookmarks/history, downloads and tab search. New tabs focus the address +bar immediately. Browsing records stay in memory; bookmark/history data is not +made persistent by these controls. + Research tools do not automatically crawl, scan, or attack targets. Passive notes do not issue extra requests and are not confirmed vulnerability reports. JWT inspection decodes claims; it does not verify their signature. diff --git a/docs/keyboard-shortcuts.md b/docs/keyboard-shortcuts.md index 9c1e9f3..d80b7d7 100644 --- a/docs/keyboard-shortcuts.md +++ b/docs/keyboard-shortcuts.md @@ -1,86 +1,126 @@ -# Keyboard and tab behavior +# Keyboard and private browser controls -Status: unreleased source changes after 1.0.2. These shortcuts work in browser -chrome and focused web pages, including page text fields. They are local to the -browser, not system-wide hotkeys. Native copy/paste, undo/redo, selection and -ordinary typing are left to the focused field. +Status: unreleased source changes after 1.0.2. Shortcuts work in browser chrome +and focused pages, including text fields. They are not system-wide hooks. +The profile was checked against [Chrome's desktop shortcut reference](https://support.google.com/chrome/answer/157179?hl=en). +Fathi implements equivalents where it has the feature; it is not a Chrome clone. -## Defaults +## Windows and Linux defaults | Action | Keys | | --- | --- | -| New tab | Ctrl+T | -| Close tab | Ctrl+W, Ctrl+F4, or middle-click its tab | -| Reopen last closed tab | Ctrl+Shift+T | -| Next / previous tab | Ctrl+Tab / Ctrl+Shift+Tab; Ctrl+PageDown / Ctrl+PageUp | +| New private window | Ctrl+N or Ctrl+Shift+N | +| New tab / reopen closed tab | Ctrl+T / Ctrl+Shift+T | +| Close tab / window | Ctrl+W or Ctrl+F4 / Ctrl+Shift+W | +| Next / previous tab | Ctrl+Tab or Ctrl+PageDown / Ctrl+Shift+Tab or Ctrl+PageUp | +| Move tab right / left | Ctrl+Shift+PageDown / Ctrl+Shift+PageUp | | Select tab 1–8 / last tab | Ctrl+1–8 / Ctrl+9 | -| Address bar | Ctrl+L, Alt+D, Ctrl+K, F6 | -| Reload / bypass cache | Ctrl+R or F5 / Ctrl+Shift+R or Ctrl+F5 | -| Back / forward | Alt+Left / Alt+Right; Ctrl+[ / Ctrl+] | -| Home / stop loading | Alt+Home / Escape | -| Find in page | Ctrl+F | -| Next / previous match | Enter / Shift+Enter in Find; Ctrl+G / Ctrl+Shift+G; F3 / Shift+F3 | -| Zoom in / out / reset | Ctrl+Plus (or Ctrl+=) / Ctrl+- / Ctrl+0 | +| Search open tabs | Ctrl+Shift+A | +| Address bar / explicit search | Ctrl+L or Alt+D / Ctrl+K or Ctrl+E | +| Next / previous browser area | F6 / Shift+F6 | +| Page / first enabled toolbar item / last toolbar item | Ctrl+F6 / Alt+Shift+T / F10 | +| Bookmarks bar / open dialog focus | Alt+Shift+B / Alt+Shift+A | +| Browser menu | Alt+F or Alt+E; arrow keys navigate, Escape dismisses, X quits this instance | +| Back / forward / home | Alt+Left / Alt+Right / Alt+Home | +| Reload / bypass cache | Ctrl+R or F5 / Ctrl+Shift+R, Shift+F5 or Ctrl+F5 | +| Stop loading / dismiss | Escape | +| Find / next / previous match | Ctrl+F / Ctrl+G or F3 / Ctrl+Shift+G or Shift+F3 | +| Find selected text | Ctrl+Alt+E | +| Find-bar next / previous match | Enter / Shift+Enter | +| Bookmark current page / all open tabs | Ctrl+D / Ctrl+Shift+D | +| Bookmark manager / bar visibility | Ctrl+Shift+O / Ctrl+Shift+B | +| History / downloads / task metrics | Ctrl+H / Ctrl+J / Shift+Escape | +| Clear session data options | Ctrl+Shift+Delete | +| View source / inspect page | Ctrl+U / Ctrl+Shift+C | +| Page DevTools | F12, Ctrl+Shift+I or Ctrl+Shift+J | +| Open local file / save page | Ctrl+O / Ctrl+S | +| Print dialog | Ctrl+P or Ctrl+Shift+P | +| Zoom in / out / reset | Ctrl+Plus or Ctrl+= / Ctrl+- / Ctrl+0 | | Fullscreen | F11 | -| Print / save page | Ctrl+P / Ctrl+S | -| Page DevTools | F12, Ctrl+Shift+I, Ctrl+Shift+J | -| Close window / quit | Ctrl+Shift+W / Ctrl+Q | -| Settings / guide | Ctrl+, / Ctrl+/ | -| Fingerprint settings | Ctrl+D | -| Device / proxy / interceptor | Ctrl+Shift+M / Ctrl+Shift+P / Ctrl+Alt+I | - -On macOS, Command is also accepted for the Ctrl-style letter/number bindings. -Use **Control+Tab** to cycle tabs: Command+Tab belongs to macOS and is not -overridden. OS-reserved shortcuts and function-key settings can take precedence. -Native print dialogs, save dialogs, fullscreen transitions and OS-specific -shortcuts still need manual validation on each packaged target; automated live -keyboard checks currently run on Windows. - -Fathi is not claiming every Chrome feature or shortcut. There is no new -multi-window manager, bookmark manager or persistent history/download library -in this change. Ctrl+D remains Fathi's fingerprint settings shortcut. Closing -the last tab retains the existing behavior of opening a fresh private tab; -Ctrl+Shift+W explicitly closes the window. - -## Customization - -Use Settings → Shortcuts to record, clear, save or reset bindings. Ctrl+Tab and -Ctrl+Shift+Tab can now be recorded. Ordinary Tab / Shift+Tab moves between -fields; Backspace clears a binding and Escape leaves the recorder. - -Chrome-style aliases are active only while their action keeps its default -binding. Rebinding or clearing an action disables its aliases. Explicit custom -bindings take precedence, and existing saved bindings are preserved. In -particular, older configurations may still bind Ctrl+Shift+I to the interceptor. -Reset shortcuts (or rebind it) to use Ctrl+Shift+I for DevTools and Ctrl+Alt+I -for interception. The same resolver is used for chrome and webview input. - -## Smoother tabs without weakening isolation - -- Switching tabs focuses the selected page and keeps its tab visible, without - animating through intermediate tabs during rapid keyboard switching. -- New blank tabs focus the address bar. Background links stay in the background - and open next to their originating tab. -- Closing a tab removes it and selects its neighbor immediately; session cleanup - is still awaited, but does not leave stale tab indexes while input continues. -- Background loads no longer reset the foreground progress indicator. User zoom - is not reset on every document-ready event. Reduced-motion preferences are - respected. - -Reopening keeps at most **10 URL/device entries in memory**, not on disk, and -creates a **new partition and fingerprint**. It does not restore cookies, -storage, passwords, POST submissions, page form contents or the old identity. -Internal identity/device replacement does not populate the reopen stack. All -entries disappear when the browser closes. Printing, saving a page and copying -diagnostics are explicit user-directed exports, not automatic persistence. - -## About diagnostics - -About displays the actual host OS name/version/build, machine architecture, -application architecture, Chromium/Electron/Node versions and packaged versus -development status. These values are not the tab's spoofed identity. Both info -APIs use the same collector; no Windows edition is guessed from a kernel number. -Copied diagnostics exclude usernames, hostnames, local paths and browsing data. +| Settings / guide | Ctrl+, / Ctrl+/ or F1 | +| Fingerprint / device / proxy / interception | Ctrl+Alt+D / Ctrl+Alt+M / Ctrl+Alt+P / Ctrl+Alt+I | +| Quit this window's application instance | Ctrl+Q | + +In the address bar, **Alt+Enter** opens the input in a new foreground tab; +**Ctrl+Enter** completes a bare site name to `https://www..com`. A leading +`?` forces a search rather than URL navigation. Native page/text controls keep +Tab/Shift+Tab, Space/Shift+Space, Home/End, page scrolling, word navigation, +selection, copy/paste and undo/redo. Non-Latin physical letter keys are normalized +for browser commands; IME composition and AltGraph typing are not intercepted. + +## macOS + +Command is accepted for the common letter/number bindings. Use **Control+Tab** +to cycle tabs; Command+Tab belongs to macOS. Additional Command aliases include +Y for history, Shift+J for downloads, Option+B for bookmarks, Option+U for source, +Option+I/J for DevTools, Shift+H for home, Option+F for search, and E for finding +selected text. Command+Left/Right navigates history; Option+Left/Right remains +native text navigation. Command+H/M is left to the native hide/minimize handling. +Control+Command+F is an additional fullscreen shortcut. + +OS-reserved gestures, function-key settings and native dialogs can take +precedence. Automated live keyboard tests run on Windows; native printing, +file pickers and packaged macOS/Linux GUI behavior still require manual checks. + +## New-tab focus + +New blank tabs, explicit `fathi://newtab` URLs, the plus button and Fathi's new-tab +button focus the **top address/search bar**. Foreground creation dismisses panels +that would cover it. Focus happens before asynchronous session/proxy setup and +text typed immediately is preserved. Page readiness does not reselect or erase +that text. Background tabs do not steal focus. + +## Private feature semantics + +- **Windows:** Ctrl+N and Ctrl+Shift+N launch real, independent application + processes, each with its own window, temporary directories, tab sessions and + fingerprint maps. All Fathi windows are private; there is no persistent normal + mode. Configuration is shared on disk but not live-synchronized. Quitting one + instance does not terminate the other windows. Cross-window tab dragging is + not implemented. +- **Bookmarks:** up to 200 deduplicated HTTP(S) bookmarks in memory, with a bar, + manager and removal controls. Bookmark-all uses a flat session collection, + not a persistent folder. These disappear on window close. +- **History:** up to 300 in-memory HTTP(S) visits for the current window. Internal + pages, executable URL schemes and local file paths are not recorded here. +- **Downloads:** up to 100 tracked records with native progress, active + pause/resume/cancel, and completed-file reveal/save-copy controls. Files use + unique names in the temporary download directory and are wiped on exit. + Only an explicit Save a copy action exports them outside it. Records expose no + local paths to the renderer; downloads are never executed automatically. +- **Task manager:** read-only process CPU/memory metrics for this instance, not + an arbitrary PID termination interface. +- **Clear data:** opens a confirmation panel; the shortcut alone deletes + nothing. The button clears this window's history, cookies, storage, auth and + cache. It retains bookmarks and does not affect independent windows. Reload a + page to reset data already held in its JavaScript memory. +- **Source/inspection:** source uses Chromium's actual `view-source:` viewer in + a fresh isolated tab, so authenticated pages may require signing in again. + Inspect opens DevTools at the top-left page element; it is not a promise of + Chrome's interactive element-picker or exact console-panel selection. + +Closing the last tab still opens a fresh private tab. Reopen keeps at most +10 URL/device entries in memory and always creates a new partition/fingerprint; +it does not restore cookies, passwords, POST data, forms or the old identity. +Printing, saving, copying and file selection are explicit user-directed actions. + +## Customization and compatibility + +Settings → Shortcuts supports recording, clearing, saving and reset. Tab and +Shift+Tab move between recorder fields; Ctrl+Tab can be captured; Backspace +clears and Escape leaves the recorder. Rebinding/clearing disables that action's +aliases. Explicit custom bindings take precedence. + +Known shipped legacy bindings migrate once to free Ctrl+D for bookmarks, +Ctrl+Shift+P for printing and Ctrl+Shift+I for DevTools. Distinct custom bindings +and already-versioned profiles are preserved. If a custom binding already claims +the migration's target, it is not overwritten; resolve the conflict or reset the +profile deliberately. Only configuration is persisted, never the session library. + +Google accounts/guest profiles, sync, password/payment management, Chrome-only +feedback services, tab groups/multi-selection, split view, caret-browsing controls +and address predictions are not implemented or mapped to unrelated actions. +This is broad desktop shortcut coverage, **not every feature in Chrome**. ## Validation @@ -89,8 +129,10 @@ npm test npx electron . --fathi-e2e --fathi-browser-audit --fathi-identity-audit --fathi-intercept-audit ``` -The browser audit sends real Electron key events through focused webviews and -chrome. It checks tab navigation from a textarea, numbered tabs, custom guest -bindings, shortcut recording, find matches, zoom, close/reopen with new identity, -background selection and actual About system fields. Unit tests cover all -default/alias resolution, IME/AltGraph safeguards and runtime diagnostics. +The live audit uses real key/mouse input and isolated local fixtures. It opens +and closes actual additional browser processes, reads a completed download, +checks source viewing, clears actual session storage, verifies immediate typing +and new-tab buttons, and exercises tab movement and library shortcuts. Unit +tests cover default/alias/platform matching, migration, library caps, download +state and safe window launch construction. Existing identity and interception +audits remain enabled. diff --git a/package.json b/package.json index 6477acb..53c0fd7 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "license": "MIT", "main": "src/main/main.js", "scripts": { - "test": "node tools/check-syntax.js && node --test tools/test-research.js tools/test-network.js tools/test-identity.js tools/test-certificate.js tools/test-update-fallback.js tools/test-intercept.js tools/test-shortcuts.js tools/test-system-info.js && node tools/test-rules.js", + "test": "node tools/check-syntax.js && node --test tools/test-research.js tools/test-network.js tools/test-identity.js tools/test-certificate.js tools/test-update-fallback.js tools/test-intercept.js tools/test-shortcuts.js tools/test-system-info.js tools/test-session-library.js tools/test-downloads.js tools/test-window-launcher.js tools/test-settings-shortcuts.js && node tools/test-rules.js", "start": "electron .", "icons": "node tools/make-icons.js && node tools/make-installer-art.js", "dist:win": "electron-builder --win nsis portable --x64 --publish never", diff --git a/src/main/browser-checks.js b/src/main/browser-checks.js index 7a12832..7f50d8f 100644 --- a/src/main/browser-checks.js +++ b/src/main/browser-checks.js @@ -1,13 +1,18 @@ 'use strict'; const http = require('node:http'); +const fs = require('node:fs'); const { webContents } = require('electron'); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function run(ui) { const checks = []; const add = (name, pass, detail = '') => checks.push({ name, pass: !!pass, detail: JSON.stringify(detail) }); const evaluate = (source) => ui.executeJavaScript(source); - const saved = await evaluate(`({ ids: state.tabs.map(t => t.id), active: state.activeId, shortcuts: state.settings.shortcuts, closed: closedTabs.slice() })`); - const server = http.createServer((_req, res) => { + const saved = await evaluate(`({ ids: state.tabs.map(t => t.id), active: state.activeId, shortcuts: state.settings.shortcuts, closed: closedTabs.slice(), history: sessionLibrary.history.slice(), bookmarks: sessionLibrary.bookmarks.slice() })`); + const server = http.createServer((req, res) => { + if (req.url === '/fixture-download.txt') { + res.setHeader('Content-Disposition', 'attachment; filename="keyboard-fixture.txt"'); + res.end('Synthetic download fixture'); return; + } res.setHeader('Content-Type', 'text/html'); res.setHeader('Cache-Control', 'no-store'); res.end('Keyboard fixture

needle needle

Background link'); }); @@ -52,6 +57,19 @@ async function run(ui) { add('Ctrl+T creates a blank tab and focuses the address bar', newFocus.url.startsWith('fathi://newtab') && newFocus.focus === 'omnibox', newFocus); await press(ui, 'W', ['control']); await until(`state.tabs.length === ${beforeNew}`); + const typed = await evaluate(`(async () => { openSettings('general'); const pending = createTab({ url: newTabUrl() }); omnibox.value = 'typed during setup'; await pending; return { value: omnibox.value, focus: document.activeElement.id, id: activeTab().id, uncovered: $('#settings-overlay').classList.contains('hidden') }; })()`); + add('explicit new-tab URLs uncover the address bar and preserve immediate typing during setup', typed.value === 'typed during setup' && typed.focus === 'omnibox' && typed.uncovered, typed); + await evaluate(`closeTab(${JSON.stringify(typed.id)}, { silent: true })`); + for (const selector of ['#newtab-btn', '#btn-shuffle']) { + const count = await evaluate('state.tabs.length'); + const point = await evaluate(`(() => { const r = $(${JSON.stringify(selector)}).getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()`); + ui.focus(); + ui.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point }); + ui.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point }); + await until(`state.tabs.length === ${count + 1} && activeTab().url.startsWith('fathi://newtab') && !activeTab().loading`); + add(`${selector} native click gives the address bar initial focus`, await evaluate('document.activeElement === omnibox')); + await evaluate('closeTab(state.activeId, { silent: true })'); + } await evaluate(`activate(${JSON.stringify(a.id)});`); await press(a.wc, 'F', ['control']); @@ -113,10 +131,88 @@ async function run(ui) { add('middle-click links open adjacent background tabs without stealing focus', await evaluate(`state.activeId === ${JSON.stringify(a.id)} && state.tabs[state.tabs.findIndex(t => t.id === ${JSON.stringify(a.id)}) + 1].url === ${JSON.stringify(origin + '/background')}`)); await press(a.wc, 'PageDown', ['control']); add('Ctrl+PageDown cycles to the adjacent tab', await evaluate(`activeTab().url === ${JSON.stringify(origin + '/background')}`)); + + await evaluate(`activate(${JSON.stringify(a.id)})`); + await press(a.wc, 'D', ['control']); + add('Ctrl+D creates a real session bookmark and opens its manager', await evaluate(`state.section === 'bookmarks' && sessionLibrary.bookmarks.some(item => item.url === ${JSON.stringify(origin + '/a')}) && $('#library-results').textContent.includes('Keyboard fixture')`)); + const escaped = await evaluate(`(() => { sessionLibrary.bookmarks[0].title = ''; renderLibrary('bookmarks'); return !$('#settings-body img'); })()`); + add('bookmark titles render as text, not executable markup', escaped); + await evaluate('closeSettings()'); + await press(a.wc, 'B', ['control', 'shift']); + add('Ctrl+Shift+B displays an actual session bookmarks bar', await evaluate(`!$('#bookmarks-bar').classList.contains('hidden') && $('#bookmarks-bar [data-bookmark]') !== null`)); + await press(a.wc, 'H', ['control']); + add('Ctrl+H displays real in-memory navigation history', await evaluate(`state.section === 'history' && sessionLibrary.history.some(item => item.url === ${JSON.stringify(origin + '/a')}) && $('#library-results .library-row') !== null`)); + await evaluate('closeSettings()'); + await press(a.wc, 'A', ['control', 'shift']); + add('Ctrl+Shift+A opens a focused filter for current tabs', await evaluate(`state.section === 'tabs' && document.activeElement === $('#library-filter')`)); + await evaluate('closeSettings()'); + await press(a.wc, 'Escape', ['shift']); + await until(`state.section === 'tasks' && $('#settings-body tbody tr')`); + add('Shift+Escape shows actual process CPU and memory metrics', await evaluate(`$('#settings-body tbody').textContent.length > 5`)); + await evaluate('closeSettings()'); + a.wc.downloadURL(origin + '/fixture-download.txt'); + await until(`(async () => (await window.api.library.downloads()).items.some(item => item.name === 'keyboard-fixture.txt' && item.state === 'completed'))()`); + await press(a.wc, 'J', ['control']); + await until(`state.section === 'downloads' && $('#settings-body').textContent.includes('keyboard-fixture.txt')`); + add('Ctrl+J displays a real completed temporary download', true); + await evaluate('closeSettings()'); + const preSource = await evaluate('state.tabs.length'); + await press(a.wc, 'U', ['control']); + await until(`state.tabs.length === ${preSource + 1} && activeTab().identityReady && !activeTab().loading`); + const sourceWcId = await evaluate('activeTab().wcId'); + const sourceText = await webContents.fromId(sourceWcId).executeJavaScript('document.body.innerText'); + add('Ctrl+U opens Chromium view-source, not a DOM snapshot', sourceText.includes('Keyboard fixture'), { nativeUrl: webContents.fromId(sourceWcId).getURL(), sourceVisible: sourceText.includes('Keyboard fixture') }); + await evaluate('closeTab(state.activeId, { silent: true })'); + await evaluate(`activate(${JSON.stringify(a.id)})`); + await press(a.wc, 'T', ['alt', 'shift']); + add('Alt+Shift+T focuses the first enabled toolbar control', await evaluate(`document.activeElement.matches('#toolbar button:not(:disabled)')`)); + await press(ui, 'F10'); + add('F10 focuses the rightmost toolbar control', await evaluate(`document.activeElement === $('#btn-menu')`)); + await evaluate(`activate(${JSON.stringify(a.id)})`); + for (const modifiers of [['control'], ['control', 'shift']]) { + const windows = require('./window-launcher').auditWindows; + const beforePids = new Set(windows.keys()); + await press(a.wc, 'N', modifiers); + let record; + for (let i = 0; i < 200; i++) { + record = [...windows].find(([pid]) => !beforePids.has(pid)); + if (record && fs.existsSync(record[1].auditPath)) break; + await sleep(50); + } + if (!record || !fs.existsSync(record[1].auditPath)) throw new Error('New-window readiness acknowledgement missing'); + const snapshot = JSON.parse(fs.readFileSync(record[1].auditPath, 'utf8')); + add(`${modifiers.length === 1 ? 'Ctrl+N' : 'Ctrl+Shift+N'} opens a real isolated window with address focus`, snapshot.focus === 'omnibox' && snapshot.partition.startsWith('fathi-tab-')); + await evaluate(`window.api.library.closeAuditWindow(${record[0]})`); + ui.getOwnerBrowserWindow().focus(); + } + await a.wc.executeJavaScript(`document.cookie = 'clear_fixture=1'; localStorage.setItem('clear_fixture', '1')`); + await press(a.wc, 'Delete', ['control', 'shift']); + add('Ctrl+Shift+Delete opens explicit confirmation without clearing automatically', await evaluate(`state.section === 'privacy' && $('#clear-session-data') !== null`) && await a.wc.executeJavaScript(`localStorage.getItem('clear_fixture') === '1'`)); + await evaluate(`$('#clear-session-data').click()`); + await until(`$('#clear-session-status')?.textContent === t('library.cleared')`); + add('confirmed clear wipes actual session storage and history, not bookmarks', await a.wc.executeJavaScript(`document.cookie === '' && localStorage.getItem('clear_fixture') === null`) && await evaluate(`sessionLibrary.history.length === 0 && sessionLibrary.bookmarks.length > 0`)); + add('new library features never enter persistent settings', await evaluate(`(async () => { const s = (await window.api.settings.get()).settings; return !('history' in s) && !('bookmarks' in s) && !('downloads' in s); })()`)); + await evaluate(`closeSettings(); activate(${JSON.stringify(a.id)})`); + const position = await evaluate(`state.tabs.findIndex(t => t.id === ${JSON.stringify(a.id)})`); + await press(a.wc, 'PageDown', ['control', 'shift']); + add('Ctrl+Shift+PageDown moves the tab and its DOM element together', await evaluate(`state.tabs.indexOf(activeTab()) === ${position + 1} && [...tabstrip.children].map(el => el.dataset.id).join() === state.tabs.map(t => t.id).join()`)); + await press(a.wc, 'PageUp', ['control', 'shift']); + add('Ctrl+Shift+PageUp moves the tab back without changing identity', await evaluate(`state.tabs.indexOf(activeTab()) === ${position}`)); + await press(a.wc, 'K', ['control']); + add('Ctrl+K focuses explicit search mode in the address bar', await evaluate(`document.activeElement === omnibox && omnibox.value === '? '`)); + const beforeAltEnter = await evaluate('state.tabs.length'); + await evaluate(`omnibox.value = ${JSON.stringify(origin + '/alt-enter')}`); + await press(ui, 'Enter', ['alt']); + await until(`state.tabs.length === ${beforeAltEnter + 1} && activeTab().url === ${JSON.stringify(origin + '/alt-enter')} && !activeTab().loading`); + add('Alt+Enter opens the address in a real new tab', true); + await evaluate('closeTab(state.activeId, { silent: true })'); } finally { + for (const [pid] of require('./window-launcher').auditWindows) await evaluate(`window.api.library.closeAuditWindow(${pid})`).catch(() => {}); await evaluate(`closeFind(false); closeSettings(); (async () => { for (const t of [...state.tabs]) if (!${JSON.stringify(saved.ids)}.includes(t.id)) await closeTab(t.id, { silent: true }); closedTabs.splice(0, closedTabs.length, ...${JSON.stringify(saved.closed)}); + sessionLibrary.history = ${JSON.stringify(saved.history)}; sessionLibrary.bookmarks = ${JSON.stringify(saved.bookmarks)}; + bookmarkBarVisible = false; renderBookmarkBar(); const s = await window.api.settings.set({ shortcuts: ${JSON.stringify(saved.shortcuts)} }); state.settings = s.settings; activate(${JSON.stringify(saved.active)}); })()`).catch(() => {}); 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/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/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/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/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/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 @@ +