diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a261f29 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +dist/* diff --git a/README.md b/README.md index a692766..a06a0d3 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,92 @@ -# tab-park +# Tab Park -A light weight tab unloader \ No newline at end of file +Tab Park frees up memory by putting tabs you are not using to sleep. A +parked tab stays in the tab strip with its title and icon, but Firefox lets +go of the page itself. Click the tab and it comes back, like a refresh. + +That is the whole idea. It is not a tab manager, a session saver, or a +workspace. It parks tabs. + +## How to use + +Install it from addons.mozilla.org once it is listed. The toolbar button +opens a small panel with everything on it: + +- **Unload this tab** moves you to the next tab that is still awake, then + parks the one you were on. If every other tab is already parked, it opens + a new tab to move you to instead. +- **Unload other tabs in this window** parks every other tab in the window, + leaving the one you are on. Pinned tabs are left alone. +- **Never park this tab** takes the current tab out of the idle sweep and + out of "Unload other tabs". Handy for a chat or a dashboard you keep open + for hours. +- **Auto-unload** parks a tab after it has been idle for a while. A tab is + idle when it has not been the tab you were looking at for the chosen + time; looking at a tab resets its clock. It is off by default, and the + default idle time is 5 minutes. + +Keyboard shortcuts: `Ctrl+Alt+P` parks the current tab, `Ctrl+Alt+A` parks +every other tab in the window, leaving the one you are on. Open the +extension's Preferences and click Manage Extension Shortcuts, or use +`about:addons` under the gear icon. + +## What it never does + +- It never closes a tab. Nothing is lost; everything stays where it was. +- It never parks pinned tabs, the tab you are on, tabs that are still + loading, or tabs that would show a "leave this page?" warning. +- It never parks a tab that is playing sound, so your music keeps going. + You can turn that safeguard off in the toolbar panel. +- It never reads your browsing. The extension has no permission to see + your tabs or your websites, so it cannot look at addresses, titles, or + page content. It can only see the state a tab is in, awake or parked, + pinned, playing sound, and how long ago you last looked at it. That is + exactly what it needs to decide what to park. +- It never talks to the network, shows notifications, or collects anything. + Settings stay on your machine. The only permissions are `storage` and + `alarms`. + +One consequence of those small permissions: "Never park this tab" is tied to +the tab itself and lasts only until that tab is closed or Firefox restarts. + +## How it is different + +Most tab unloaders are tab managers with an unloading feature bolted on. +They ask for access to your tabs or to every site you visit, and then offer +rules, schedules, whitelists, statistics, and a settings page full of +switches. + +Tab Park does one thing: it parks tabs, on demand or once they have been +idle long enough. The permission list is the short version of that +difference. + +## Settings + +The toolbar panel has the auto-unload switch, the idle time, the skip-sound +toggle, and the "Never park this tab" button. The extension's Preferences page +only shows the current keyboard shortcuts and a button that opens Firefox's +Manage Extension Shortcuts page. + +## A small quirk + +On Firefox 153, a parked tab does not get the faded look that Firefox's own +Unload Tab menu item gives, unless you set `browser.tabs.fadeOutUnloadedTabs` +to true in `about:config`. Firefox 160 fades them properly (bug 2000401). + +## For developers + +`tools/build.sh` writes `dist/tabpark/` (unpacked) and `dist/tabpark.xpi` +(zipped). The xpi is what you upload to AMO. `npx web-ext lint --source-dir +dist/tabpark` is clean. + +The test harness drives the real extension in Firefox through Selenium; see +`test/harness/README.md`. + +To try it without installing, load it temporarily from +`about:debugging#/runtime/this-firefox` (Load Temporary Add-on, pick +`manifest.json`). + +## The name + +A park is where something waits without going away. That is what happens to +the tab: it stays in the strip, out of memory, until you come back. diff --git a/background.js b/background.js new file mode 100644 index 0000000..9d4ad68 --- /dev/null +++ b/background.js @@ -0,0 +1,90 @@ +// Tab Park - keyboard commands, popup actions and the idle sweep. Loaded +// after common.js, so the tu* helpers are in scope. + +const TU_ALARM = 'tu-idle-sweep'; +const TU_SWEEP_MINUTES = 0.25; // 15 s + +// ---------- idle sweep + +async function tuSyncAlarm() { + const { autoUnload } = await tuSettings(); + if (autoUnload) { + browser.alarms.create(TU_ALARM, { periodInMinutes: TU_SWEEP_MINUTES }); + } else { + await browser.alarms.clear(TU_ALARM); + } +} + +async function tuSweep() { + const { autoUnload, idleSeconds, skipAudible } = await tuSettings(); + if (!autoUnload) return 0; + const cutoff = Date.now() - idleSeconds * 1000; + const protectedIds = await tuProtectedIds(); + const tabs = await browser.tabs.query({}); + const idle = tuCandidates(tabs, { skipAudible }).filter(tab => + !protectedIds.has(tab.id) && + typeof tab.lastAccessed === 'number' && tab.lastAccessed <= cutoff + ); + return tuDiscard(idle); +} + +// ---------- wiring + +browser.runtime.onInstalled.addListener(() => { + tuSyncAlarm(); +}); + +browser.runtime.onStartup.addListener(() => { + tuSyncAlarm(); +}); + +browser.storage.onChanged.addListener((changes, area) => { + if (area === 'local' && changes.autoUnload) tuSyncAlarm(); +}); + +// Forget the parking tab once the user navigates it or closes it. Without the +// "tabs" permission there is no URL to compare, but the tab has finished its +// initial load before the id is recorded, so any later load is a navigation. +browser.tabs.onUpdated.addListener(async (tabId, changeInfo) => { + if (changeInfo.status !== 'loading') return; + if (tabId === await tuParkingTabId()) { + await browser.storage.session.remove(TU_PARKING_KEY); + } +}); + +browser.tabs.onRemoved.addListener(async tabId => { + if (tabId === await tuParkingTabId()) { + await browser.storage.session.remove(TU_PARKING_KEY); + } + if (await tuIsProtected(tabId)) { + await tuSetProtected(tabId, false); + } +}); + +browser.alarms.onAlarm.addListener(alarm => { + if (alarm.name === TU_ALARM) tuSweep(); +}); + +browser.commands.onCommand.addListener(async command => { + const [tab] = await browser.tabs.query({ active: true, currentWindow: true }); + if (!tab) return; + if (command === 'unload-current') { + await tuUnloadActiveTab(tab); + } else if (command === 'unload-others') { + await tuUnloadOtherTabs(tab.windowId, tab.id); + } +}); + +// The popup hands the work over instead of doing it itself: switching tabs +// closes the popup, which would kill the rest of its async handler. +browser.runtime.onMessage.addListener(message => { + if (!message || typeof message !== 'object') return; + if (message.type === 'tu:unload-current') { + if (typeof message.windowId !== 'number') return false; + return browser.tabs.query({ active: true, windowId: message.windowId }) + .then(([tab]) => tab ? tuUnloadActiveTab(tab) : false); + } + if (message.type === 'tu:unload-others') { + return tuUnloadOtherTabs(message.windowId, message.tabId); + } +}); diff --git a/common.js b/common.js new file mode 100644 index 0000000..5bf2fc5 --- /dev/null +++ b/common.js @@ -0,0 +1,190 @@ +// Tab Park - settings and discard helpers shared by the background page, +// the popup and the options page. Loaded as a classic script, so declarations +// here are visible to whatever script follows. + +const TU_DEFAULTS = { + autoUnload: false, + idleSeconds: 300, + skipAudible: true +}; + +// Below this the sweep would fight the user's own tab switching. +const TU_MIN_IDLE_SECONDS = 10; + +async function tuSettings() { + const stored = await browser.storage.local.get(TU_DEFAULTS); + const idle = Math.round(Number(stored.idleSeconds)); + return { + autoUnload: Boolean(stored.autoUnload), + idleSeconds: Number.isFinite(idle) && idle >= TU_MIN_IDLE_SECONDS ? idle : TU_DEFAULTS.idleSeconds, + skipAudible: Boolean(stored.skipAudible) + }; +} + +async function tuSaveSettings(patch) { + await browser.storage.local.set(patch); +} + +// A tab is a discard candidate when it is loaded, not pinned, not the active +// tab of its window, and not mid-navigation. Firefox refuses to discard the +// active tab, so filtering it here keeps the counts honest. +function tuCandidates(tabs, { skipAudible = false } = {}) { + return tabs.filter(tab => + !tab.discarded && + !tab.pinned && + !tab.active && + tab.status !== 'loading' && + (!skipAudible || !tab.audible) + ); +} + +const TU_PARKING_KEY = 'parkingTabId'; + +// The blank tab we opened to park the window on. Without the "tabs" +// permission Firefox does not reveal a tab's URL, so the id is the only way +// to tell this tab apart from a page the user opened. +async function tuParkingTabId() { + const stored = await browser.storage.session.get(TU_PARKING_KEY); + const id = stored[TU_PARKING_KEY]; + return typeof id === 'number' ? id : null; +} + +async function tuSetParkingTabId(tabId) { + await browser.storage.session.set({ [TU_PARKING_KEY]: tabId }); +} + +// A blank tab is the one place unloading makes no sense: there is nothing to +// free, and unloading it would only put another blank tab in its place. +// Without the "tabs" permission Firefox does not reveal tab URLs, so the id +// of the tab we opened is the only signal available. +async function tuIsParkingTab(tab) { + if (!tab) return false; + return tab.id === await tuParkingTabId(); +} + +const TU_PROTECTED_KEY = 'protectedTabIds'; + +// Tabs the user marked "never park". Stored by id, so the mark lives as long +// as the tab does. Without the "tabs" permission there is no stable +// identifier to carry it across a restart. +async function tuProtectedIds() { + const stored = await browser.storage.session.get(TU_PROTECTED_KEY); + const ids = stored[TU_PROTECTED_KEY]; + return new Set(Array.isArray(ids) ? ids.filter(id => typeof id === 'number') : []); +} + +async function tuIsProtected(tabId) { + return (await tuProtectedIds()).has(tabId); +} + +async function tuSetProtected(tabId, protect) { + const ids = await tuProtectedIds(); + if (protect) ids.add(tabId); + else ids.delete(tabId); + await browser.storage.session.set({ [TU_PROTECTED_KEY]: [...ids] }); +} + +async function tuWaitActive(tabId, timeoutMs = 1000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const tab = await browser.tabs.get(tabId).catch(() => null); + if (!tab) return false; + if (tab.active) return true; + await new Promise(resolve => setTimeout(resolve, 25)); + } + return false; +} + +async function tuWaitComplete(tabId, timeoutMs = 2000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const tab = await browser.tabs.get(tabId).catch(() => null); + if (!tab) return false; + if (tab.status === 'complete') return true; + await new Promise(resolve => setTimeout(resolve, 25)); + } + return false; +} + +// Opens the blank tab the window parks on. The id is recorded only after the +// initial load finishes, so a later "loading" event means the user navigated +// it and the id can be dropped. +async function tuCreateParkingTab(windowId) { + const created = await browser.tabs.create({ windowId, active: true }); + await tuWaitActive(created.id); + await tuWaitComplete(created.id); + await tuSetParkingTabId(created.id); + return created; +} + +// Discards in one batch, then reads the tabs back so the caller gets the +// number that actually unloaded. A tab with a beforeunload prompt cannot be +// discarded and rejects the batch, so fall back to one at a time. +async function tuDiscard(tabs) { + const ids = tabs.map(tab => tab.id).filter(id => typeof id === 'number'); + if (ids.length === 0) return 0; + try { + await browser.tabs.discard(ids); + } catch (e) { + for (const id of ids) { + await browser.tabs.discard(id).catch(() => {}); + } + } + const after = await browser.tabs.query({}); + const byId = new Map(after.map(tab => [tab.id, tab])); + return ids.filter(id => { + const tab = byId.get(id); + return !tab || tab.discarded; + }).length; +} + +// Unloads every candidate in the window except the tab the user asked to +// keep. tuCandidates already excludes the active tab; keepTabId covers the +// context menu case, where the tab to keep is not the active one. +async function tuUnloadOtherTabs(windowId, keepTabId) { + if (typeof windowId !== 'number') return 0; + const { skipAudible } = await tuSettings(); + const protectedIds = await tuProtectedIds(); + const tabs = await browser.tabs.query({ windowId }); + return tuDiscard( + tuCandidates(tabs, { skipAudible }) + .filter(tab => tab.id !== keepTabId && !protectedIds.has(tab.id)) + ); +} + +// Unloads the active tab without leaving a blank window: switch to the next +// loaded tab first (wrapping around), or open a fresh tab when every other +// tab is already unloaded. Firefox will not discard the active tab, so the +// order matters. The discard is verified because tabs.discard() resolves +// without doing anything if the tab is still selected. +async function tuUnloadActiveTab(tab) { + if (await tuIsParkingTab(tab)) return false; + + const tabs = await browser.tabs.query({ windowId: tab.windowId }); + const current = tabs.find(other => other.id === tab.id) || tab; + const loaded = tabs + .filter(other => other.id !== current.id && !other.discarded && other.status !== 'loading') + .sort((a, b) => a.index - b.index); + const next = loaded.find(other => other.index > current.index) || loaded[0]; + + if (next) { + await browser.tabs.update(next.id, { active: true }); + } else if (tabs.length > 1) { + await tuCreateParkingTab(current.windowId); + } else { + // The only tab in the window: there is nowhere to switch to. + return false; + } + + for (let attempt = 0; attempt < 3; attempt++) { + try { + await browser.tabs.discard(current.id); + } catch (e) { + return false; + } + const after = await browser.tabs.get(current.id).catch(() => null); + if (!after || after.discarded) return true; + await new Promise(resolve => setTimeout(resolve, 120)); + } + return false; +} diff --git a/icons/icon-128.png b/icons/icon-128.png new file mode 100644 index 0000000..9c8b7ef Binary files /dev/null and b/icons/icon-128.png differ diff --git a/icons/icon-16.png b/icons/icon-16.png new file mode 100644 index 0000000..fca55e1 Binary files /dev/null and b/icons/icon-16.png differ diff --git a/icons/icon-32.png b/icons/icon-32.png new file mode 100644 index 0000000..f280ed8 Binary files /dev/null and b/icons/icon-32.png differ diff --git a/icons/icon-48.png b/icons/icon-48.png new file mode 100644 index 0000000..6b114b2 Binary files /dev/null and b/icons/icon-48.png differ diff --git a/icons/icon-96.png b/icons/icon-96.png new file mode 100644 index 0000000..ae40530 Binary files /dev/null and b/icons/icon-96.png differ diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..d5a76b9 --- /dev/null +++ b/manifest.json @@ -0,0 +1,55 @@ +{ + "manifest_version": 3, + "name": "Tab Park", + "version": "0.1.0", + "description": "Unload tabs on demand, or automatically after they have been idle for a while.", + "browser_specific_settings": { + "gecko": { + "id": "tabpark@neutrino.local", + "strict_min_version": "140.0", + "data_collection_permissions": { + "required": ["none"] + } + } + }, + "icons": { + "16": "icons/icon-16.png", + "32": "icons/icon-32.png", + "48": "icons/icon-48.png", + "96": "icons/icon-96.png", + "128": "icons/icon-128.png" + }, + "permissions": ["storage", "alarms"], + "background": { + "scripts": ["common.js", "background.js"] + }, + "action": { + "default_title": "Tab Park", + "default_popup": "popup.html", + "default_icon": { + "16": "icons/icon-16.png", + "32": "icons/icon-32.png", + "48": "icons/icon-48.png", + "96": "icons/icon-96.png", + "128": "icons/icon-128.png" + } + }, + "options_ui": { + "page": "options.html", + "open_in_tab": false + }, + "commands": { + "unload-current": { + "suggested_key": { + "default": "Ctrl+Alt+P" + }, + "description": "Unload this tab and switch to the next loaded tab" + }, + "unload-others": { + "suggested_key": { + "default": "Ctrl+Alt+A" + }, + "description": "Unload other tabs in this window" + } + } +} diff --git a/options.css b/options.css new file mode 100644 index 0000000..6fb2aa7 --- /dev/null +++ b/options.css @@ -0,0 +1,73 @@ +:root { + color-scheme: light dark; + --fg: #1c1e24; + --muted: #5d6472; + --line: #d9dce3; +} + +@media (prefers-color-scheme: dark) { + :root { + --fg: #e8eaf0; + --muted: #9aa3b5; + --line: #3a4152; + } +} + +body { + max-width: 560px; + margin: 0 auto; + padding: 24px 20px 40px; + font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; + color: var(--fg); +} + +h1 { + margin: 0 0 20px; + font-size: 20px; + font-weight: 600; +} + +h2 { + margin: 0 0 10px; + font-size: 14px; + font-weight: 600; +} + +section { + margin: 0 0 24px; + padding: 16px; + border: 1px solid var(--line); + border-radius: 8px; +} + +p { + margin: 8px 0 0; + color: var(--muted); +} + +.hint { + font-size: 13px; +} + +kbd { + padding: 1px 5px; + font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; + color: var(--fg); + border: 1px solid var(--line); + border-bottom-width: 2px; + border-radius: 4px; +} + +button { + padding: 7px 12px; + font: inherit; + color: var(--fg); + background: transparent; + border: 1px solid var(--line); + border-radius: 6px; + cursor: pointer; +} + +button:hover { + border-color: var(--muted); +} diff --git a/options.html b/options.html new file mode 100644 index 0000000..048e2e1 --- /dev/null +++ b/options.html @@ -0,0 +1,24 @@ + + + + + + Tab Park shortcuts + + +

Tab Park

+ +
+

Keyboard shortcuts

+

unloads the current tab and switches + to the next loaded tab.

+

unloads every other tab in this window, + leaving the one you are on.

+

+

These are the shortcuts in effect now. Change them in the + Firefox shortcuts page.

+
+ + + + diff --git a/options.js b/options.js new file mode 100644 index 0000000..6ffc516 --- /dev/null +++ b/options.js @@ -0,0 +1,35 @@ +// Tab Park - preferences. The only thing here is the keyboard shortcuts, +// which live in Firefox's own shortcuts page. This page shows what is bound +// right now and opens that page. + +const $ = id => document.getElementById(id); + +function tuKeys(shortcut) { + const fragment = document.createDocumentFragment(); + if (!shortcut) { + fragment.append('Not set'); + return fragment; + } + shortcut.split('+').forEach((key, index) => { + if (index) fragment.append('+'); + const kbd = document.createElement('kbd'); + kbd.textContent = key; + fragment.append(kbd); + }); + return fragment; +} + +async function tuLoadShortcuts() { + const commands = await browser.commands.getAll(); + const byName = Object.fromEntries(commands.map(command => [command.name, command.shortcut])); + $('shortcut-current').replaceChildren(tuKeys(byName['unload-current'])); + $('shortcut-all').replaceChildren(tuKeys(byName['unload-others'])); +} + +$('shortcuts').addEventListener('click', () => { + browser.commands.openShortcutSettings(); +}); + +browser.commands.onChanged.addListener(tuLoadShortcuts); + +tuLoadShortcuts(); diff --git a/popup.css b/popup.css new file mode 100644 index 0000000..c06aee7 --- /dev/null +++ b/popup.css @@ -0,0 +1,115 @@ +:root { + color-scheme: light dark; + --fg: #1c1e24; + --muted: #5d6472; + --line: #d9dce3; + --accent: #2f6fed; + --accent-fg: #ffffff; +} + +@media (prefers-color-scheme: dark) { + :root { + --fg: #e8eaf0; + --muted: #9aa3b5; + --line: #3a4152; + --accent: #5b8dff; + --accent-fg: #0d1017; + } +} + +body { + width: 264px; + margin: 0; + padding: 12px; + font: 13px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; + color: var(--fg); +} + +h1 { + margin: 0 0 2px; + font-size: 13px; + font-weight: 600; +} + +.counts { + margin: 0 0 10px; + color: var(--muted); + font-size: 12px; +} + +button { + display: block; + width: 100%; + margin: 0 0 6px; + padding: 7px 10px; + font: inherit; + color: var(--fg); + background: transparent; + border: 1px solid var(--line); + border-radius: 6px; + cursor: pointer; +} + +button:hover { + border-color: var(--muted); +} + +button.primary { + color: var(--accent-fg); + background: var(--accent); + border-color: var(--accent); +} + +button.primary:hover { + filter: brightness(1.08); +} + +.status { + min-height: 1.4em; + margin: 0; + color: var(--muted); + font-size: 12px; +} + +hr { + margin: 8px 0 10px; + border: 0; + border-top: 1px solid var(--line); +} + +.row { + display: flex; + align-items: center; + gap: 6px; + margin: 0 0 6px; +} + +.row.indent { + padding-left: 20px; + color: var(--muted); +} + +.row input[type="number"] { + width: 64px; + padding: 2px 4px; + font: inherit; + color: var(--fg); + background: transparent; + border: 1px solid var(--line); + border-radius: 4px; +} + +.row input:disabled, +.row input:disabled + span { + opacity: 0.5; +} + +.hint { + margin: 10px 0 0; + color: var(--muted); + font-size: 11px; +} + +.hint a { + color: inherit; +} diff --git a/popup.html b/popup.html new file mode 100644 index 0000000..6b71233 --- /dev/null +++ b/popup.html @@ -0,0 +1,42 @@ + + + + + + Tab Park + + +

Tab Park

+

Reading tabs...

+ + + + + +

+ +
+ + + + + +

Keyboard shortcuts are set in Preferences.

+ + + + + diff --git a/popup.js b/popup.js new file mode 100644 index 0000000..72b6d23 --- /dev/null +++ b/popup.js @@ -0,0 +1,93 @@ +// Tab Park - popup. Actions are handed to the background page: switching +// tabs closes the popup and would otherwise kill the rest of the handler. + +const $ = id => document.getElementById(id); + +function tuSetStatus(text) { + $('status').textContent = text; +} + +async function tuRefreshCounts() { + const tabs = await browser.tabs.query({ currentWindow: true }); + const loaded = tabs.filter(tab => !tab.discarded).length; + const pinned = tabs.filter(tab => tab.pinned).length; + const parts = [`${loaded} loaded`, `${tabs.length - loaded} unloaded`]; + if (pinned) parts.push(`${pinned} pinned`); + $('counts').textContent = parts.join(', '); +} + +function tuSyncDisabled() { + const on = $('auto').checked; + $('idle').disabled = !on; +} + +async function tuLoadForm() { + const settings = await tuSettings(); + $('auto').checked = settings.autoUnload; + $('idle').value = settings.idleSeconds; + $('skip-audible').checked = settings.skipAudible; + tuSyncDisabled(); +} + +async function tuLoadProtect() { + const [tab] = await browser.tabs.query({ active: true, currentWindow: true }); + if (!tab) return; + $('protect').checked = await tuIsProtected(tab.id); +} + +$('protect').addEventListener('change', async () => { + const [tab] = await browser.tabs.query({ active: true, currentWindow: true }); + if (tab) await tuSetProtected(tab.id, $('protect').checked); +}); + +$('auto').addEventListener('change', async () => { + tuSyncDisabled(); + await tuSaveSettings({ autoUnload: $('auto').checked }); +}); + +$('idle').addEventListener('change', async () => { + const value = Math.max(TU_MIN_IDLE_SECONDS, Math.round(Number($('idle').value) || TU_DEFAULTS.idleSeconds)); + $('idle').value = value; + await tuSaveSettings({ idleSeconds: value }); +}); + +$('skip-audible').addEventListener('change', () => { + tuSaveSettings({ skipAudible: $('skip-audible').checked }); +}); + +$('unload-current').addEventListener('click', async () => { + const win = await browser.windows.getCurrent(); + tuSetStatus('Unloading...'); + try { + const ok = await browser.runtime.sendMessage({ type: 'tu:unload-current', windowId: win.id }); + if (ok === false) tuSetStatus('Nothing to unload here'); + } catch (e) { + // Expected when the tab switch closes the popup mid-request. + } +}); + +$('unload-others').addEventListener('click', async () => { + const win = await browser.windows.getCurrent(); + const [tab] = await browser.tabs.query({ active: true, currentWindow: true }); + tuSetStatus('Unloading...'); + try { + const count = await browser.runtime.sendMessage({ + type: 'tu:unload-others', + windowId: win.id, + tabId: tab ? tab.id : null + }); + tuSetStatus(count ? `Unloaded ${count} tab${count === 1 ? '' : 's'}` : 'Nothing to unload'); + await tuRefreshCounts(); + } catch (e) { + tuSetStatus('Could not unload tabs'); + } +}); + +$('options').addEventListener('click', event => { + event.preventDefault(); + browser.runtime.openOptionsPage(); +}); + +tuLoadForm(); +tuLoadProtect(); +tuRefreshCounts(); diff --git a/test/harness/README.md b/test/harness/README.md new file mode 100644 index 0000000..d28f072 --- /dev/null +++ b/test/harness/README.md @@ -0,0 +1,53 @@ +# Test harness + +Drives the real extension in real Firefox through Selenium and asserts on the +browser's own tab state. + +``` +build-test-extension.sh copies the extension to /tmp/tabpark-test-build and + adds the test hook (fixture host permission, content + script, background hook) +test-hook-content.js forwards page messages to the background +test-hook-background.js exposes tuUnloadOtherTabs / tuUnloadActiveTab / tuSweep + plus pin, activate, close, settings and state +driver.py the main test +protect.py the per-tab exception test +``` + +Requirements: `firefox-esr`, `python3-selenium`, geckodriver, Xvfb. On this +host geckodriver lives at `/tmp/rig/bin/geckodriver`; override with +`GECKODRIVER=...`. + +``` +Xvfb :99 -screen 0 1280x1024x24 -nolisten tcp & +DISPLAY=:99 python3 test/harness/driver.py +DISPLAY=:99 python3 test/harness/no-tabs.py +DISPLAY=:99 python3 test/harness/protect.py +``` + +`driver.py` adds the `tabs` permission to the test variant only, so the hook +can identify tabs by URL. The extension code never reads tab URLs. +`no-tabs.py` builds without it and identifies tabs by id, matching the shipped +permission set exactly. + +The driver serves `/p1` ... `/p6` from `127.0.0.1:8765` and counts hits, so a +reload after unloading is observable independently of the extension. + +Covered: + +- unload others: keeps the active tab, discards every other non-pinned + tab, leaves the pinned tab loaded, tab count unchanged +- unload current: focus moves to the next loaded tab before the old tab is + discarded; keeps the tab count +- unload current on a blank tab: refused, nothing changes, pressing again is + still a no-op +- unload current when nothing else is loaded: opens a new tab and discards + the old one +- unload current on a pinned tab: honoured when asked directly +- idle sweep: enabling auto-unload creates the alarm, the alarm (not a direct + call) discards tabs idle past the threshold, the active tab survives +- a discarded tab reloads when selected (server hit count increases) +- popup and options pages render, read the saved settings, and the popup + button drives the background +- per-tab exception: a protected tab survives unload-others and the idle + sweep, and is discarded once unprotected diff --git a/test/harness/build-test-extension.sh b/test/harness/build-test-extension.sh new file mode 100755 index 0000000..b4ddee8 --- /dev/null +++ b/test/harness/build-test-extension.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# Builds the test variant of Tab Park into /tmp/tabpark-test-build: +# identical extension code, plus +# - the "tabs" permission, for the test hook only: it reports tab URLs so +# the driver can identify tabs. The extension code never reads tab URLs. +# - host permission for the fixture server +# - content/test-hook-content.js, which forwards page messages +# - background/test-hook-background.js, which exposes the real helpers +set -euo pipefail + +SRC=/workspace/tabpark +OUT=/tmp/tabpark-test-build +rm -rf "$OUT" +mkdir -p "$OUT/content" "$OUT/background" + +cp "$SRC"/manifest.json "$SRC"/common.js "$SRC"/background.js \ + "$SRC"/popup.html "$SRC"/popup.js "$SRC"/popup.css \ + "$SRC"/options.html "$SRC"/options.js "$SRC"/options.css "$OUT"/ +cp -r "$SRC"/icons "$OUT"/ +cp "$SRC"/test/harness/test-hook-content.js "$OUT/content/test-hook-content.js" +cp "$SRC"/test/harness/test-hook-background.js "$OUT/background/test-hook-background.js" + +python3 - "$OUT/manifest.json" <<'PY' +import json, os, sys +p = sys.argv[1] +m = json.load(open(p)) +if os.environ.get('TU_NO_TABS') != '1' and 'tabs' not in m['permissions']: + m['permissions'].append('tabs') +m['host_permissions'] = ['http://127.0.0.1/*'] +m['content_scripts'] = [{ + 'matches': ['http://127.0.0.1/*'], + 'js': ['content/test-hook-content.js'], + 'run_at': 'document_start' +}] +m['background']['scripts'].append('background/test-hook-background.js') +json.dump(m, open(p, 'w'), indent=2) +PY + +echo "built $OUT" diff --git a/test/harness/driver.py b/test/harness/driver.py new file mode 100644 index 0000000..e533e3b --- /dev/null +++ b/test/harness/driver.py @@ -0,0 +1,421 @@ +#!/usr/bin/env python3 +"""End-to-end test for Tab Park in real Firefox. + +Builds the test variant, serves fixture pages on 127.0.0.1, installs the +extension temporarily, and drives it through a test hook. Every assertion is +made against the browser's own tab state (tabs.query), not against the +extension's bookkeeping. + +Run with: DISPLAY=:99 python3 test/harness/driver.py +""" + +import collections +import json +import os +import re +import subprocess +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.firefox.options import Options +from selenium.webdriver.firefox.service import Service +from selenium.webdriver.support.ui import WebDriverWait + +HERE = Path(__file__).resolve().parent +BUILD = Path('/tmp/tabpark-test-build') +GECKODRIVER = os.environ.get('GECKODRIVER', '/tmp/rig/bin/geckodriver') +FIREFOX = os.environ.get('FIREFOX', '/usr/bin/firefox-esr') +PORT = int(os.environ.get('TU_PORT', '8765')) +BASE = f'http://127.0.0.1:{PORT}' + +HITS = collections.Counter() +CHECKS = [] + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + path = self.path.split('?')[0] + if not path.startswith('/p'): + self.send_error(404) + return + HITS[path] += 1 + body = (f'' + f'{path}

{path}

').encode() + self.send_response(200) + self.send_header('Content-Type', 'text/html; charset=utf-8') + self.send_header('Content-Length', str(len(body))) + self.send_header('Cache-Control', 'no-store') + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +def check(name, condition, detail=''): + CHECKS.append((name, bool(condition))) + line = ('PASS ' if condition else 'FAIL ') + name + if detail and not condition: + line += f' [{detail}]' + print(line, flush=True) + + +def launch(): + opts = Options() + opts.binary_location = FIREFOX + for key, value in { + 'browser.shell.checkDefaultBrowser': False, + 'browser.startup.homepage_override.mstone': 'ignore', + 'browser.aboutwelcome.enabled': False, + 'datareporting.policy.dataSubmissionEnabled': False, + 'toolkit.telemetry.reportingpolicy.firstRun': False, + 'extensions.autoDisableScopes': 0, + 'extensions.enabledScopes': 15, + }.items(): + opts.set_preference(key, value) + service = Service(executable_path=GECKODRIVER, service_args=['--allow-system-access']) + return webdriver.Firefox(options=opts, service=service) + + +def wait_uuid(driver, addon_id, timeout=20): + prefs = Path(driver.capabilities['moz:profile']) / 'prefs.js' + deadline = time.time() + timeout + while time.time() < deadline: + if prefs.exists(): + match = re.search( + r'user_pref\("extensions\.webextensions\.uuids",\s*"(.*)"\);', + prefs.read_text(errors='replace')) + if match: + uuids = json.loads(match.group(1).replace('\\"', '"')) + if addon_id in uuids: + return uuids[addon_id] + time.sleep(0.2) + raise RuntimeError('extension uuid not found in prefs.js') + + +def hook(driver, cmd, **kwargs): + payload = {'cmd': cmd, **kwargs} + last = None + for _ in range(5): + result = driver.execute_async_script(""" + const payload = arguments[0]; + const done = arguments[arguments.length - 1]; + const id = 'r' + Math.random(); + const timer = setTimeout(() => { + window.removeEventListener('message', onMessage); + done({timeout: true}); + }, 5000); + function onMessage(event) { + if (!event.data || event.data.tuResult !== id) return; + clearTimeout(timer); + window.removeEventListener('message', onMessage); + done(event.data); + } + window.addEventListener('message', onMessage); + window.postMessage(Object.assign({tuTest: true, id}, payload), '*'); + """, payload) + if not result.get('timeout'): + if 'error' in result: + last = result['error'] + if 'Could not establish connection' not in last: + raise RuntimeError(f'{cmd}: {last}') + else: + return result.get('value') + time.sleep(0.4) + raise RuntimeError(f'hook {cmd} failed: {last or "timeout"}') + + +def state(driver): + return hook(driver, 'state') + + +def by_url(tabs, suffix): + return next(tab for tab in tabs if (tab.get('url') or '').endswith(suffix)) + + +def wait_tab(driver, suffix, timeout=10): + """Poll until a tab with this URL suffix is visible. + + A tab that is reloading after a discard briefly has no url, so a single + state() read can miss it. + """ + deadline = time.time() + timeout + while time.time() < deadline: + tabs = state(driver) + match = next((tab for tab in tabs if (tab.get('url') or '').endswith(suffix)), None) + if match: + return match + time.sleep(0.25) + raise RuntimeError(f'tab {suffix} not found') + + +def use(driver, handles, path): + driver.switch_to.window(handles[path]) + + +def fire(driver, cmd, **kwargs): + """Post a hook command without waiting for the reply. + + Needed when the command discards the tab it is sent from: the async + script would die with "Document was unloaded" before answering. + """ + driver.execute_script(""" + window.postMessage(Object.assign({tuTest: true, id: 'fire'}, arguments[0]), '*'); + """, {'cmd': cmd, **kwargs}) + + +def build(): + subprocess.run([str(HERE / 'build-test-extension.sh')], check=True) + + +def main(): + build() + server = ThreadingHTTPServer(('127.0.0.1', PORT), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + + driver = launch() + handles = {} + try: + addon_id = driver.install_addon(str(BUILD), temporary=True) + uuid = wait_uuid(driver, addon_id) + print(f'installed {addon_id} as {uuid}', flush=True) + + driver.get(BASE + '/p1') + handles['/p1'] = driver.current_window_handle + for i in range(2, 6): + driver.switch_to.new_window('tab') + driver.get(BASE + f'/p{i}') + handles[f'/p{i}'] = driver.current_window_handle + time.sleep(1.0) + + tabs = state(driver) + check('five fixture tabs are open', len(tabs) == 5, f'{len(tabs)} tabs') + check('all five start loaded', all(not tab['discarded'] for tab in tabs)) + + shortcuts = {cmd['name']: cmd['shortcut'] for cmd in hook(driver, 'commands')} + check('unload-current shortcut registered', + shortcuts.get('unload-current') == 'Ctrl+Alt+P', str(shortcuts)) + check('unload-others shortcut registered', + shortcuts.get('unload-others') == 'Ctrl+Alt+A', str(shortcuts)) + + manifest = json.loads((Path('/workspace/tabpark') / 'manifest.json').read_text()) + check('shipped manifest does not request the tabs permission', + 'tabs' not in manifest['permissions'], str(manifest['permissions'])) + check('shipped manifest does not request the menus permission', + 'menus' not in manifest['permissions'], str(manifest['permissions'])) + + synthetic = [ + {'id': 1, 'discarded': False, 'pinned': False, 'active': False, + 'status': 'complete', 'audible': True}, + {'id': 2, 'discarded': False, 'pinned': False, 'active': False, + 'status': 'complete', 'audible': False}, + ] + check('audible tabs are skipped when the setting is on', + hook(driver, 'candidates', tabs=synthetic, skipAudible=True) == [2]) + check('audible tabs are included when the setting is off', + hook(driver, 'candidates', tabs=synthetic, skipAudible=False) == [1, 2]) + + hook(driver, 'pin', tabId=by_url(tabs, '/p1')['id']) + tabs = state(driver) + check('p1 is pinned', by_url(tabs, '/p1')['pinned']) + + # ---- unload others: keep the active tab, unload the rest + hook(driver, 'activate', tabId=by_url(tabs, '/p2')['id']) + time.sleep(0.4) + # Call from the pinned tab: switching the WebDriver context activates + # that tab, so p2 is re-activated afterwards. + use(driver, handles, '/p1') + hook(driver, 'activate', tabId=by_url(tabs, '/p2')['id']) + time.sleep(0.3) + count = hook(driver, 'unload-others', tabId=by_url(tabs, '/p2')['id']) + time.sleep(0.6) + tabs = state(driver) + active = next(tab for tab in tabs if tab['active']) + check('unload-others reports three tabs', count == 3, f'count={count}') + check('unload-others keeps the tab count', len(tabs) == 5, f'{len(tabs)} tabs') + check('unload-others leaves the pinned tab loaded', not by_url(tabs, '/p1')['discarded']) + check('unload-others leaves the active tab loaded', not by_url(tabs, '/p2')['discarded']) + check('unload-others discards p3, p4, p5', + all(by_url(tabs, f'/p{i}')['discarded'] for i in (3, 4, 5))) + check('unload-others keeps the active tab active', + active['url'].endswith('/p2'), active['url']) + + # ---- unload current: focus moves to the next loaded tab + use(driver, handles, '/p1') + tabs = state(driver) + hook(driver, 'activate', tabId=by_url(tabs, '/p4')['id']) + time.sleep(0.8) + hook(driver, 'activate', tabId=by_url(tabs, '/p3')['id']) + time.sleep(0.8) + tabs = state(driver) + check('p3 and p4 are loaded for the next test', + not by_url(tabs, '/p3')['discarded'] and not by_url(tabs, '/p4')['discarded']) + hook(driver, 'unload-current') + time.sleep(0.6) + tabs = state(driver) + check('unload-current discards the tab it left', by_url(tabs, '/p3')['discarded']) + active = next(tab for tab in tabs if tab['active']) + check('unload-current lands on the next loaded tab', + active['url'].endswith('/p4'), active['url']) + check('unload-current keeps the tab count', len(tabs) == 5, f'{len(tabs)} tabs') + + # ---- unload current when nothing else is loaded: open a new tab + tabs = state(driver) + hook(driver, 'unpin', tabId=by_url(tabs, '/p1')['id']) + tabs = state(driver) + hook(driver, 'activate', tabId=by_url(tabs, '/p4')['id']) + time.sleep(0.6) + use(driver, handles, '/p4') + hook(driver, 'discard-all') + time.sleep(0.5) + tabs = state(driver) + loaded = [tab for tab in tabs if not tab['discarded']] + check('only p4 is loaded before the last-tab test', len(loaded) == 1, + str([tab['url'] for tab in loaded])) + before = len(tabs) + before_handles = set(driver.window_handles) + fire(driver, 'unload-current') + time.sleep(1.5) + new_handles = [h for h in driver.window_handles if h not in before_handles] + check('unload-current opens a tab when all others are unloaded', + len(new_handles) == 1, f'{before} -> {len(driver.window_handles)} handles') + if new_handles: + driver.switch_to.window(new_handles[0]) + driver.get(BASE + '/p6') + handles['/p6'] = driver.current_window_handle + tabs = state(driver) + check('the old tab is discarded', by_url(tabs, '/p4')['discarded']) + check('the new tab is active and loaded', + len(tabs) == before + 1 and not next(t for t in tabs if t['active'])['discarded'], + f'{before} -> {len(tabs)} tabs') + + # ---- idle sweep, driven by the alarm rather than a direct call + for path in ('/p3', '/p4', '/p5'): + tabs = state(driver) + hook(driver, 'activate', tabId=by_url(tabs, path)['id']) + time.sleep(0.8) + hook(driver, 'settings', values={'autoUnload': True, 'idleSeconds': 10, 'skipAudible': True}) + tabs = state(driver) + hook(driver, 'activate', tabId=by_url(tabs, '/p3')['id']) + time.sleep(0.5) + use(driver, handles, '/p3') + alarms = hook(driver, 'alarms') + check('enabling auto-unload creates the sweep alarm', + any(alarm['name'] == 'tu-idle-sweep' for alarm in alarms), str(alarms)) + + start = time.time() + discarded_at = None + while time.time() - start < 75: + tabs = state(driver) + if by_url(tabs, '/p4')['discarded'] and by_url(tabs, '/p5')['discarded']: + discarded_at = time.time() - start + break + time.sleep(2) + check('the idle sweep discards idle tabs', discarded_at is not None, + f'still loaded after {time.time() - start:.0f}s') + if discarded_at is not None: + print(f' sweep latency: {discarded_at:.0f}s after enabling', flush=True) + tabs = state(driver) + check('the idle sweep leaves the active tab loaded', not by_url(tabs, '/p3')['discarded']) + + # ---- a discarded tab really reloads when selected + tabs = state(driver) + check('p4 is discarded before the reload check', by_url(tabs, '/p4')['discarded']) + before_hits = HITS['/p4'] + hook(driver, 'activate', tabId=by_url(tabs, '/p4')['id']) + reloaded = False + try: + WebDriverWait(driver, 20).until(lambda d: HITS['/p4'] > before_hits) + reloaded = True + except Exception: + pass + check('selecting a discarded tab reloads the page', reloaded, + f'{before_hits} -> {HITS["/p4"]}') + p4 = wait_tab(driver, '/p4') + check('the reloaded tab is no longer discarded', not p4['discarded']) + + # ---- an explicit unload of a pinned tab is honoured + tabs = state(driver) + hook(driver, 'pin', tabId=by_url(tabs, '/p1')['id']) + hook(driver, 'activate', tabId=by_url(tabs, '/p1')['id']) + time.sleep(0.8) + hook(driver, 'unload-current') + time.sleep(0.6) + tabs = state(driver) + check('unload-current unloads a pinned tab when asked directly', + by_url(tabs, '/p1')['discarded']) + + # ---- extension pages render + driver.switch_to.new_window('tab') + driver.get(f'moz-extension://{uuid}/popup.html') + WebDriverWait(driver, 10).until( + lambda d: d.find_element(By.ID, 'counts').text != 'Reading tabs...') + counts = driver.find_element(By.ID, 'counts').text + check('popup renders the tab counts', 'loaded' in counts, counts) + idle_value = driver.find_element(By.ID, 'idle').get_attribute('value') + check('popup shows the saved threshold', idle_value == '10', idle_value) + + # Pin this tab so the bulk unload does not discard the page under test + # before it can show the result. + driver.execute_async_script(""" + const done = arguments[0]; + browser.tabs.query({active: true, currentWindow: true}) + .then(([tab]) => browser.tabs.update(tab.id, {pinned: true})) + .then(() => done(true), error => done(String(error))); + """) + driver.find_element(By.ID, 'unload-others').click() + WebDriverWait(driver, 15).until( + lambda d: d.find_element(By.ID, 'status').text != 'Unloading...') + status = driver.find_element(By.ID, 'status').text + check('popup button unloads through the background', + status.startswith('Unloaded') or status == 'Nothing to unload', status) + + driver.get(f'moz-extension://{uuid}/options.html') + WebDriverWait(driver, 10).until( + lambda d: d.find_element(By.ID, 'shortcut-current').text) + current = driver.find_element(By.ID, 'shortcut-current').text + check('options page shows the current shortcut', + 'Ctrl' in current and 'Alt' in current and 'P' in current, current) + + # ---- a single-tab window is left alone + main_handle = driver.current_window_handle + driver.switch_to.new_window('window') + driver.get(f'moz-extension://{uuid}/popup.html') + WebDriverWait(driver, 10).until( + lambda d: d.find_element(By.ID, 'counts').text != 'Reading tabs...') + win_id = driver.execute_async_script( + "const done = arguments[0]; browser.windows.getCurrent().then(w => done(w.id));") + before = driver.execute_async_script( + "const done = arguments[0]; browser.tabs.query({}).then(t => done(t.length));") + result = driver.execute_async_script(""" + const winId = arguments[0]; + const done = arguments[arguments.length - 1]; + browser.runtime.sendMessage({type: 'tu:unload-current', windowId: winId}) + .then(done, error => done('ERR ' + error)); + """, win_id) + time.sleep(0.5) + after = driver.execute_async_script( + "const done = arguments[0]; browser.tabs.query({}).then(t => done(t.length));") + check('unload-current leaves a single-tab window alone', + result is False and after == before, f'{result} {before}->{after}') + driver.close() + driver.switch_to.window(main_handle) + finally: + driver.quit() + server.shutdown() + + failed = [name for name, ok in CHECKS if not ok] + print(f'\n{len(CHECKS) - len(failed)}/{len(CHECKS)} checks passed', flush=True) + if failed: + print('failed: ' + ', '.join(failed), flush=True) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/test/harness/no-tabs.py b/test/harness/no-tabs.py new file mode 100644 index 0000000..680625a --- /dev/null +++ b/test/harness/no-tabs.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 +"""Exercises the default build, which has no "tabs" permission. + +The main driver adds "tabs" so it can identify tabs by URL. This one builds +without it and identifies tabs by id, which is the shipped configuration. + +Run with: DISPLAY=:99 python3 test/harness/no-tabs.py +""" + +import os +import sys +import threading +import time +from http.server import ThreadingHTTPServer + +from driver import (BASE, BUILD, CHECKS, PORT, Handler, build, check, hook, + launch, state, wait_uuid) + + +def active_id(driver): + return next(tab['id'] for tab in state(driver) if tab['active']) + + +def by_id(tabs, tab_id): + return next(tab for tab in tabs if tab['id'] == tab_id) + + +def main(): + os.environ['TU_NO_TABS'] = '1' + build() + + server = ThreadingHTTPServer(('127.0.0.1', PORT), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + + driver = launch() + handles = {} + ids = {} + try: + addon_id = driver.install_addon(str(BUILD), temporary=True) + wait_uuid(driver, addon_id) + print(f'installed {addon_id} without the tabs permission', flush=True) + + driver.get(BASE + '/p1') + handles['/p1'] = driver.current_window_handle + ids['/p1'] = active_id(driver) + for i in (2, 3): + driver.switch_to.new_window('tab') + driver.get(BASE + f'/p{i}') + handles[f'/p{i}'] = driver.current_window_handle + ids[f'/p{i}'] = active_id(driver) + time.sleep(0.5) + + tabs = state(driver) + check('three tabs open without the tabs permission', len(tabs) == 3, str(len(tabs))) + + hook(driver, 'pin', tabId=ids['/p1']) + hook(driver, 'activate', tabId=ids['/p2']) + time.sleep(0.3) + # switch_to activates p1, so re-activate p2 before the bulk unload + driver.switch_to.window(handles['/p1']) + hook(driver, 'activate', tabId=ids['/p2']) + time.sleep(0.3) + + count = hook(driver, 'unload-others', tabId=ids['/p2']) + time.sleep(0.5) + tabs = state(driver) + check('unload-others reports one tab', count == 1, f'count={count}') + check('unload-others keeps the tab count', len(tabs) == 3, f'{len(tabs)} tabs') + check('the pinned tab survives', not by_id(tabs, ids['/p1'])['discarded']) + check('the kept tab survives', not by_id(tabs, ids['/p2'])['discarded']) + check('p3 is discarded', by_id(tabs, ids['/p3'])['discarded']) + + hook(driver, 'activate', tabId=ids['/p3']) + time.sleep(0.8) + hook(driver, 'unload-current') + time.sleep(0.5) + tabs = state(driver) + check('unload-current discards the tab it left', by_id(tabs, ids['/p3'])['discarded']) + active = next(tab for tab in tabs if tab['active']) + check('unload-current lands on a loaded tab', not active['discarded']) + + hook(driver, 'protect', tabId=ids['/p2'], value=True) + hook(driver, 'unload-others', tabId=ids['/p1']) + time.sleep(0.4) + tabs = state(driver) + check('unload-others skips the protected tab', not by_id(tabs, ids['/p2'])['discarded']) + + hook(driver, 'protect', tabId=ids['/p2'], value=False) + hook(driver, 'unload-others', tabId=ids['/p1']) + time.sleep(0.4) + tabs = state(driver) + check('unload-others discards it once unprotected', by_id(tabs, ids['/p2'])['discarded']) + + parked = hook(driver, 'park') + check('the parking tab is created', bool(parked and parked.get('id'))) + hook(driver, 'activate', tabId=parked['id']) + time.sleep(0.3) + result = hook(driver, 'unload-current') + check('unload-current refuses the parking tab', result is False, str(result)) + finally: + driver.quit() + server.shutdown() + + failed = [name for name, ok in CHECKS if not ok] + print(f'\n{len(CHECKS) - len(failed)}/{len(CHECKS)} checks passed', flush=True) + if failed: + print('failed: ' + ', '.join(failed), flush=True) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/test/harness/protect.py b/test/harness/protect.py new file mode 100644 index 0000000..8c565dc --- /dev/null +++ b/test/harness/protect.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Tests the per-tab "Never park this tab" exception. + +Run with: DISPLAY=:99 python3 test/harness/protect.py +""" + +import sys +import threading +import time +from http.server import ThreadingHTTPServer + +from driver import (BASE, BUILD, CHECKS, PORT, Handler, build, check, hook, + launch, state, wait_uuid) + + +def active_id(driver): + return next(tab['id'] for tab in state(driver) if tab['active']) + + +def by_id(tabs, tab_id): + return next(tab for tab in tabs if tab['id'] == tab_id) + + +def main(): + build() + server = ThreadingHTTPServer(('127.0.0.1', PORT), Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + + driver = launch() + handles = {} + ids = {} + try: + addon_id = driver.install_addon(str(BUILD), temporary=True) + wait_uuid(driver, addon_id) + + driver.get(BASE + '/p1') + handles['/p1'] = driver.current_window_handle + ids['/p1'] = active_id(driver) + for i in (2, 3): + driver.switch_to.new_window('tab') + driver.get(BASE + f'/p{i}') + handles[f'/p{i}'] = driver.current_window_handle + ids[f'/p{i}'] = active_id(driver) + time.sleep(0.5) + + hook(driver, 'protect', tabId=ids['/p2'], value=True) + check('p2 is marked protected', ids['/p2'] in hook(driver, 'protected')) + + # Call from p2: it is the active tab and protected, so it survives and + # the other two become candidates. + driver.switch_to.window(handles['/p2']) + hook(driver, 'unload-others', tabId=ids['/p2']) + time.sleep(0.5) + tabs = state(driver) + check('unload-others skips the protected tab', not by_id(tabs, ids['/p2'])['discarded']) + check('unload-others still discards the rest', + by_id(tabs, ids['/p1'])['discarded'] and by_id(tabs, ids['/p3'])['discarded']) + + hook(driver, 'settings', values={'autoUnload': True, 'idleSeconds': 10, 'skipAudible': True}) + driver.switch_to.window(handles['/p1']) + time.sleep(11) + hook(driver, 'sweep') + time.sleep(0.5) + tabs = state(driver) + check('the idle sweep skips the protected tab', not by_id(tabs, ids['/p2'])['discarded']) + + hook(driver, 'protect', tabId=ids['/p2'], value=False) + check('p2 is no longer protected', ids['/p2'] not in hook(driver, 'protected')) + hook(driver, 'sweep') + time.sleep(0.5) + tabs = state(driver) + check('the sweep discards it once unprotected', by_id(tabs, ids['/p2'])['discarded']) + finally: + driver.quit() + server.shutdown() + + failed = [name for name, ok in CHECKS if not ok] + print(f'\n{len(CHECKS) - len(failed)}/{len(CHECKS)} checks passed', flush=True) + if failed: + print('failed: ' + ', '.join(failed), flush=True) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/test/harness/test-hook-background.js b/test/harness/test-hook-background.js new file mode 100644 index 0000000..5ff27df --- /dev/null +++ b/test/harness/test-hook-background.js @@ -0,0 +1,65 @@ +// Test-only background hook. Appended after common.js and background.js, so +// the real helpers (tuUnloadOtherTabs, tuUnloadActiveTab, tuSweep, ...) are in +// scope. It exists so the Selenium driver can trigger the extension from a +// normal page and read back the browser's own tab state. + +async function tuTestState() { + const tabs = await browser.tabs.query({}); + return tabs.map(tab => ({ + id: tab.id, + index: tab.index, + windowId: tab.windowId, + url: tab.url, + title: tab.title, + active: tab.active, + pinned: tab.pinned, + discarded: tab.discarded, + audible: tab.audible, + lastAccessed: tab.lastAccessed + })); +} + +browser.runtime.onMessage.addListener((message, sender) => { + if (!message || message.type !== 'tu-test') return; + const windowId = sender.tab ? sender.tab.windowId : undefined; + switch (message.cmd) { + case 'state': + return tuTestState(); + case 'unload-others': + return tuUnloadOtherTabs(windowId, message.tabId); + case 'park': + return tuCreateParkingTab(windowId); + case 'unload-current': + return browser.tabs.query({ active: true, windowId }) + .then(([tab]) => tab ? tuUnloadActiveTab(tab) : false); + case 'pin': + return browser.tabs.update(message.tabId, { pinned: true }); + case 'unpin': + return browser.tabs.update(message.tabId, { pinned: false }); + case 'activate': + return browser.tabs.update(message.tabId, { active: true }); + case 'close': + return browser.tabs.remove(message.tabId); + case 'discard-all': + return browser.tabs.query({ windowId }) + .then(tabs => tuDiscard(tuCandidates(tabs))); + case 'settings': + return browser.storage.local.set(message.values); + case 'sweep': + return tuSweep(); + case 'alarms': + return browser.alarms.getAll(); + case 'parking': + return tuParkingTabId(); + case 'protect': + return tuSetProtected(message.tabId, message.value); + case 'protected': + return tuProtectedIds().then(ids => [...ids]); + case 'candidates': + return Promise.resolve( + tuCandidates(message.tabs, { skipAudible: message.skipAudible }).map(tab => tab.id) + ); + case 'commands': + return browser.commands.getAll(); + } +}); diff --git a/test/harness/test-hook-content.js b/test/harness/test-hook-content.js new file mode 100644 index 0000000..9b232a9 --- /dev/null +++ b/test/harness/test-hook-content.js @@ -0,0 +1,10 @@ +// Test-only content script: forwards page messages to the background hook. +// Injected by build-test-extension.sh into the fixture pages only. +window.addEventListener('message', event => { + if (event.source !== window || !event.data || event.data.tuTest !== true) return; + const { id, cmd, tabId, values, value, tabs, skipAudible } = event.data; + browser.runtime.sendMessage({ type: 'tu-test', cmd, tabId, values, value, tabs, skipAudible }).then( + value => window.postMessage({ tuResult: id, value }, '*'), + error => window.postMessage({ tuResult: id, error: String(error) }, '*') + ); +}); diff --git a/tools/build.sh b/tools/build.sh new file mode 100755 index 0000000..7758432 --- /dev/null +++ b/tools/build.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Builds the loadable copy of the extension: +# dist/tabpark unpacked, for about:debugging +# dist/tabpark.xpi zipped, for handing over or uploading to AMO +set -euo pipefail + +SRC="$(cd "$(dirname "$0")/.." && pwd)" +OUT="$SRC/dist" +DEST="$OUT/tabpark" + +rm -rf "$OUT" +mkdir -p "$DEST" + +cp "$SRC"/manifest.json "$SRC"/common.js "$SRC"/background.js \ + "$SRC"/popup.html "$SRC"/popup.js "$SRC"/popup.css \ + "$SRC"/options.html "$SRC"/options.js "$SRC"/options.css "$DEST"/ +cp -r "$SRC"/icons "$DEST"/ + +python3 - "$OUT" <<'PY' +import os, sys, zipfile +out = sys.argv[1] +src = os.path.join(out, 'tabpark') +xpi = os.path.join(out, 'tabpark.xpi') +with zipfile.ZipFile(xpi, 'w', zipfile.ZIP_DEFLATED) as archive: + for root, _, files in os.walk(src): + for filename in files: + full = os.path.join(root, filename) + archive.write(full, os.path.relpath(full, src)) +PY + +cat > "$OUT/README.md" <<'MD' +# Tab Park build + +`tabpark/` is the unpacked extension. Load it with +about:debugging#/runtime/this-firefox > Load Temporary Add-on > pick +`tabpark/manifest.json`. + +`tabpark.xpi` is the same files zipped, for handing to someone else or +uploading to addons.mozilla.org. +MD + +echo "built $DEST and $OUT/tabpark.xpi" diff --git a/tools/gen-icons.js b/tools/gen-icons.js new file mode 100644 index 0000000..2cdd06c --- /dev/null +++ b/tools/gen-icons.js @@ -0,0 +1,120 @@ +// Generates the Tab Park toolbar icons: a tab parked inside a parking bay. +// Flat shapes, no gradients, and a simplified 16/32px version so the bay +// outline and the tab still read in the toolbar. +const zlib = require('zlib'); +const fs = require('fs'); +const path = require('path'); + +function crc32(buf) { + let table = crc32.table; + if (!table) { + table = crc32.table = new Int32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c; + } + } + let c = 0xffffffff; + for (let i = 0; i < buf.length; i++) c = table[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function chunk(type, data) { + const len = Buffer.alloc(4); + len.writeUInt32BE(data.length); + const body = Buffer.concat([Buffer.from(type, 'ascii'), data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(body)); + return Buffer.concat([len, body, crc]); +} + +function png(width, height, rgba) { + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; ihdr[9] = 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; + const raw = Buffer.alloc((width * 4 + 1) * height); + for (let y = 0; y < height; y++) { + raw[y * (width * 4 + 1)] = 0; + rgba.copy(raw, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4); + } + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', ihdr), + chunk('IDAT', zlib.deflateSync(raw, { level: 9 })), + chunk('IEND', Buffer.alloc(0)) + ]); +} + +function inRoundedRect(x, y, x0, y0, x1, y1, r) { + const cx = Math.max(x0 + r, Math.min(x1 - r, x)); + const cy = Math.max(y0 + r, Math.min(y1 - r, y)); + return Math.hypot(x - cx, y - cy) <= r; +} + +function render(size) { + const rgba = Buffer.alloc(size * size * 4); + const bg = [24, 42, 68]; + const bay = [242, 244, 248]; + const tab = [201, 154, 78]; + const tabTop = [169, 124, 54]; + const fold = [138, 100, 40]; + + const radius = size * 0.22; + const bayOuter = { x0: size * 0.12, y0: size * 0.12, x1: size * 0.88, y1: size * 0.88, r: size * 0.10 }; + const stroke = Math.max(size * 0.055, 1.1); + const bayInner = { + x0: bayOuter.x0 + stroke, + y0: bayOuter.y0 + stroke, + x1: bayOuter.x1 - stroke, + y1: bayOuter.y1 - stroke, + r: Math.max(bayOuter.r - stroke, 0) + }; + const tabRect = { x0: size * 0.22, y0: size * 0.24, x1: size * 0.78, y1: size * 0.76, r: size * 0.055 }; + const barBottom = tabRect.y0 + size * 0.10; + const foldSize = size * 0.12; + const showFold = size >= 32; + + const samples = 4; + for (let y = 0; y < size; y++) { + for (let x = 0; x < size; x++) { + let r = 0, g = 0, b = 0, covered = 0; + for (let sy = 0; sy < samples; sy++) { + for (let sx = 0; sx < samples; sx++) { + const px = x + (sx + 0.5) / samples; + const py = y + (sy + 0.5) / samples; + if (!inRoundedRect(px, py, 0, 0, size, size, radius)) continue; + + let color = bg; + const inBayOuter = inRoundedRect(px, py, bayOuter.x0, bayOuter.y0, bayOuter.x1, bayOuter.y1, bayOuter.r); + const inBayInner = inRoundedRect(px, py, bayInner.x0, bayInner.y0, bayInner.x1, bayInner.y1, bayInner.r); + if (inBayOuter && !inBayInner) color = bay; + + const inTab = inRoundedRect(px, py, tabRect.x0, tabRect.y0, tabRect.x1, tabRect.y1, tabRect.r); + if (inTab) { + color = py < barBottom ? tabTop : tab; + if (showFold && (px - tabRect.x0) + (py - tabRect.y0) < foldSize) { + color = fold; + } + } + + r += color[0]; g += color[1]; b += color[2]; covered++; + } + } + const i = (y * size + x) * 4; + rgba[i] = covered ? Math.round(r / covered) : 0; + rgba[i + 1] = covered ? Math.round(g / covered) : 0; + rgba[i + 2] = covered ? Math.round(b / covered) : 0; + rgba[i + 3] = Math.round(255 * covered / (samples * samples)); + } + } + return png(size, size, rgba); +} + +const dir = path.join(__dirname, '..', 'icons'); +fs.mkdirSync(dir, { recursive: true }); +for (const s of [16, 32, 48, 96, 128]) { + fs.writeFileSync(path.join(dir, `icon-${s}.png`), render(s)); + console.log(`wrote icon-${s}.png`); +}