commit 97dd8da17861c33cb8d4543a2c46f68260bbbf71 Author: Timothy Kim Date: Wed Oct 21 20:40:39 2026 -0400 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8aec54b --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.*.swp +web-ext-artifacts/ +extension/.amo-upload-uuid +dist/quick-profile.xpi diff --git a/22d0e17ada8245a4bc80-1.0.0.xpi b/22d0e17ada8245a4bc80-1.0.0.xpi new file mode 100644 index 0000000..e4f06c6 Binary files /dev/null and b/22d0e17ada8245a4bc80-1.0.0.xpi differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..af189d7 --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +# Quick Profile + +Toolbar button that opens (or focuses) a chosen Firefox profile in one click. The button shows that profile's avatar in its theme colors. + +Extensions cannot launch profiles, so a small native messaging host (`host/quick_profile_host.py`) does the work. Firefox spawns it per click; it runs `firefox --profile --profiles-activate`, the same command Firefox's own profile switcher uses. + +## Install + +1. Register the native host (once per user): + + host/install.sh + +2. Install the extension **in each profile** that should have the button. + - Development: `about:debugging` → This Firefox → Load Temporary Add-on → `extension/manifest.json` (removed on restart). + - Permanent: release Firefox requires a signed add-on. Sign it as unlisted (private, not published on AMO): + + npx web-ext sign --source-dir extension --channel unlisted \ + --api-key "$AMO_JWT_ISSUER" --api-secret "$AMO_JWT_SECRET" + + Keys: https://addons.mozilla.org/developers/addon/api/key/. Install the resulting `.xpi` via `about:addons` → gear → Install Add-on From File. + +3. Choose the target: `about:addons` → Quick Profile → Preferences, or click the button before configuring it. + +## Notes + +- The icon is refreshed at startup and whenever the target changes. If you change a profile's avatar, reselect it or restart to update the button. +- Linux only (`~/.mozilla/firefox`, `/proc`). diff --git a/extension/background.js b/extension/background.js new file mode 100644 index 0000000..12f925a --- /dev/null +++ b/extension/background.js @@ -0,0 +1,58 @@ +"use strict"; + +async function getTarget() { + const { targetPath } = await browser.storage.local.get("targetPath"); + return targetPath || null; +} + +async function resetButton(title) { + await browser.action.setIcon({ path: "icons/fallback.svg" }); + await browser.action.setTitle({ title }); +} + +async function refreshButton() { + const targetPath = await getTarget(); + if (!targetPath) { + return resetButton("Quick Profile: choose a profile"); + } + let profiles; + try { + profiles = await listProfiles(); + } catch (e) { + return resetButton(`Quick Profile: ${e.message}`); + } + const profile = profiles.find(p => p.path === targetPath); + if (!profile) { + return resetButton("Quick Profile: configured profile no longer exists"); + } + try { + const [i16, i32] = await Promise.all([renderIcon(profile, 16), renderIcon(profile, 32)]); + await browser.action.setIcon({ imageData: { 16: i16, 32: i32 } }); + } catch (e) { + await browser.action.setIcon({ path: "icons/fallback.svg" }); + } + await browser.action.setTitle({ title: `Open ${profile.name}` }); +} + +browser.action.onClicked.addListener(async () => { + const targetPath = await getTarget(); + if (!targetPath) { + return browser.runtime.openOptionsPage(); + } + try { + await callHost({ cmd: "launch", path: targetPath }); + } catch (e) { + await browser.action.setTitle({ title: `Quick Profile: ${e.message}` }); + await browser.action.setBadgeText({ text: "!" }); + setTimeout(() => browser.action.setBadgeText({ text: "" }), 3000); + } +}); + +browser.storage.onChanged.addListener((changes, area) => { + if (area === "local" && "targetPath" in changes) { + refreshButton(); + } +}); + +browser.runtime.onStartup.addListener(refreshButton); +browser.runtime.onInstalled.addListener(refreshButton); diff --git a/extension/common.js b/extension/common.js new file mode 100644 index 0000000..55a458e --- /dev/null +++ b/extension/common.js @@ -0,0 +1,54 @@ +"use strict"; + +const HOST = "quick_profile"; + +async function callHost(msg) { + const reply = await browser.runtime.sendNativeMessage(HOST, msg); + if (!reply || !reply.ok) { + throw new Error(reply?.error || "no reply from native host"); + } + return reply; +} + +async function listProfiles() { + return (await callHost({ cmd: "list" })).profiles; +} + +// Firefox's avatar SVGs paint the badge circle with context-fill and the +// glyph with context-stroke; chrome CSS supplies those from the profile +// theme. Outside chrome we substitute the colors directly. +function avatarDataURL(profile, size) { + const svg = profile.images?.[size]; + if (!svg) { + return profile.images?.custom || null; + } + const colored = svg + .replaceAll("context-fill", profile.themeBg) + .replaceAll("context-stroke", profile.themeFg); + return "data:image/svg+xml;charset=utf-8," + encodeURIComponent(colored); +} + +function loadImage(src) { + return new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => resolve(img); + img.onerror = () => reject(new Error("failed to load avatar image")); + img.src = src; + }); +} + +async function renderIcon(profile, px) { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = px; + const ctx = canvas.getContext("2d"); + const isCustom = !profile.images?.["16"]; + const img = await loadImage(avatarDataURL(profile, px <= 16 ? "16" : "48")); + if (isCustom) { + // Custom avatars are plain images: clip to a circle like Firefox does. + ctx.beginPath(); + ctx.arc(px / 2, px / 2, px / 2, 0, 2 * Math.PI); + ctx.clip(); + } + ctx.drawImage(img, 0, 0, px, px); + return ctx.getImageData(0, 0, px, px); +} diff --git a/extension/icons/fallback.svg b/extension/icons/fallback.svg new file mode 100644 index 0000000..a9bcd56 --- /dev/null +++ b/extension/icons/fallback.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extension/manifest.json b/extension/manifest.json new file mode 100644 index 0000000..c2e3d74 --- /dev/null +++ b/extension/manifest.json @@ -0,0 +1,28 @@ +{ + "manifest_version": 3, + "name": "Quick Profile", + "version": "1.0.0", + "description": "One-click toolbar button that opens a chosen Firefox profile.", + "browser_specific_settings": { + "gecko": { + "id": "quick-profile@timothykim", + "strict_min_version": "138.0" + } + }, + "permissions": ["nativeMessaging", "storage"], + "background": { + "scripts": ["common.js", "background.js"] + }, + "action": { + "default_title": "Quick Profile: choose a profile", + "default_icon": "icons/fallback.svg" + }, + "icons": { + "48": "icons/fallback.svg", + "96": "icons/fallback.svg" + }, + "options_ui": { + "page": "options.html", + "open_in_tab": false + } +} diff --git a/extension/options.html b/extension/options.html new file mode 100644 index 0000000..18db63d --- /dev/null +++ b/extension/options.html @@ -0,0 +1,32 @@ + + + + + Quick Profile + + + +

Profile to open

+

Clicking the toolbar button opens (or focuses) this profile.

+ +
+ + + + diff --git a/extension/options.js b/extension/options.js new file mode 100644 index 0000000..b82a173 --- /dev/null +++ b/extension/options.js @@ -0,0 +1,64 @@ +"use strict"; + +const list = document.getElementById("profiles"); +const status = document.getElementById("status"); + +function showError(text) { + status.className = "error"; + status.textContent = text; +} + +async function init() { + let profiles; + try { + profiles = await listProfiles(); + } catch (e) { + showError( + `Cannot reach the native host (${e.message}). Run host/install.sh, then reload this page.` + ); + return; + } + if (!profiles.length) { + showError("No profiles found in ~/.mozilla/firefox/Profile Groups."); + return; + } + + const { targetPath } = await browser.storage.local.get("targetPath"); + + for (const profile of profiles) { + const li = document.createElement("li"); + const label = document.createElement("label"); + + const radio = document.createElement("input"); + radio.type = "radio"; + radio.name = "target"; + radio.value = profile.path; + radio.checked = profile.path === targetPath; + radio.addEventListener("change", async () => { + await browser.storage.local.set({ targetPath: profile.path }); + status.className = ""; + status.textContent = `Saved: ${profile.name}`; + }); + + const img = document.createElement("img"); + img.alt = ""; + const src = avatarDataURL(profile, "48"); + if (src) { + img.src = src; + } + + const text = document.createElement("div"); + const name = document.createElement("div"); + name.textContent = profile.name; + const path = document.createElement("div"); + path.className = "path"; + path.textContent = profile.path; + text.append(name, path); + + label.append(radio, img, text); + li.append(label); + list.append(li); + } +} + +init(); diff --git a/host/install.sh b/host/install.sh new file mode 100755 index 0000000..87dcf6d --- /dev/null +++ b/host/install.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Register the native messaging host with Firefox for the current user. +set -euo pipefail + +HOST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HOST_SCRIPT="$HOST_DIR/quick_profile_host.py" +MANIFEST_DIR="$HOME/.mozilla/native-messaging-hosts" + +chmod +x "$HOST_SCRIPT" +mkdir -p "$MANIFEST_DIR" + +cat > "$MANIFEST_DIR/quick_profile.json" < $HOST_SCRIPT" diff --git a/host/quick_profile_host.py b/host/quick_profile_host.py new file mode 100755 index 0000000..71b0103 --- /dev/null +++ b/host/quick_profile_host.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Native messaging host for the Quick Profile extension. + +Firefox spawns this once per message: read one request, write one reply, exit. + +Requests: + {"cmd": "list"} -> {"ok": true, "profiles": [...]} + {"cmd": "launch", "path": "..."} -> {"ok": true} +""" + +import base64 +import glob +import json +import mimetypes +import os +import shutil +import sqlite3 +import struct +import subprocess +import sys +import zlib + +FIREFOX_DIR = os.path.expanduser("~/.mozilla/firefox") +GROUPS_DIR = os.path.join(FIREFOX_DIR, "Profile Groups") +AVATAR_PREFIX = "chrome/browser/content/browser/profiles/assets/" + +# Mirrors STANDARD_AVATARS in SelectableProfile.sys.mjs; anything else is a +# custom image stored in "Profile Groups/avatars/". +STANDARD_AVATARS = { + "barbell", "bike", "book", "briefcase", "canvas", "craft", + "default-favicon", "diamond", "flower", "folder", "hammer", "heart", + "heart-rate", "history", "leaf", "lightbulb", "makeup", "message", + "musical-note", "palette", "paw-print", "plane", "present", "shopping", + "soccer", "sparkle-single", "star", "video-game-controller", +} + + +def read_message(): + raw_len = sys.stdin.buffer.read(4) + if len(raw_len) < 4: + sys.exit(0) + (length,) = struct.unpack("@I", raw_len) + return json.loads(sys.stdin.buffer.read(length)) + + +def send_message(msg): + data = json.dumps(msg).encode() + sys.stdout.buffer.write(struct.pack("@I", len(data))) + sys.stdout.buffer.write(data) + sys.stdout.buffer.flush() + + +def firefox_binary(): + """The Firefox that spawned us, so we launch the same build.""" + try: + exe = os.readlink(f"/proc/{os.getppid()}/exe") + if os.path.basename(exe).startswith("firefox"): + return exe + except OSError: + pass + return shutil.which("firefox") or "firefox" + + +def read_jar(jar_path, names): + """Extract `names` from a Mozilla jar. + + omni.ja is an "optimized" jar: the central directory sits at the front of + the file, after a 4-byte readahead header, so zipfile rejects it. Walk the + central directory ourselves instead. + """ + wanted = set(names) + out = {} + with open(jar_path, "rb") as f: + data = f.read() + pos = data.find(b"PK\x01\x02") + while pos != -1 and data[pos:pos + 4] == b"PK\x01\x02" and wanted: + (method, csize, name_len, extra_len, comment_len, local_off) = ( + struct.unpack_from(" {"16": svg, "48": svg} or {"custom": data URL}.""" + images = {} + standard = [a for a in avatars if a in STANDARD_AVATARS] + if standard: + app_dir = os.path.dirname(os.path.realpath(firefox_binary())) + omni = os.path.join(app_dir, "browser", "omni.ja") + try: + files = read_jar( + omni, + [f"{AVATAR_PREFIX}{size}_{a}.svg" for a in standard for size in (16, 48)], + ) + except OSError: + files = {} + for a in standard: + images[a] = { + size: files[f"{AVATAR_PREFIX}{size}_{a}.svg"].decode() + for size in ("16", "48") + if f"{AVATAR_PREFIX}{size}_{a}.svg" in files + } + for a in avatars: + if a in STANDARD_AVATARS: + continue + path = os.path.join(GROUPS_DIR, "avatars", a) + try: + with open(path, "rb") as f: + mime = mimetypes.guess_type(path)[0] or "image/png" + images[a] = { + "custom": f"data:{mime};base64,{base64.b64encode(f.read()).decode()}" + } + except OSError: + images[a] = {} + return images + + +def list_profiles(): + profiles = {} + for db in sorted(glob.glob(os.path.join(GROUPS_DIR, "*.sqlite"))): + try: + conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + rows = conn.execute( + "SELECT path, name, avatar, themeFg, themeBg FROM Profiles ORDER BY id" + ).fetchall() + conn.close() + except sqlite3.Error: + continue + for path, name, avatar, fg, bg in rows: + abspath = path if os.path.isabs(path) else os.path.join(FIREFOX_DIR, path) + profiles.setdefault(abspath, { + "path": abspath, + "name": name, + "avatar": avatar, + "themeFg": fg, + "themeBg": bg, + }) + result = list(profiles.values()) + images = avatar_images({p["avatar"] for p in result}) + for p in result: + p["images"] = images.get(p["avatar"], {}) + return result + + +def launch(path): + # Same arguments as SelectableProfileService.launchInstance. If the + # profile is already running, Firefox's remoting service focuses it. + if not os.path.isdir(path): + raise ValueError(f"profile directory not found: {path}") + subprocess.Popen( + [firefox_binary(), "--profile", path, "--profiles-activate"], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + + +def main(): + msg = read_message() + try: + cmd = msg.get("cmd") + if cmd == "list": + send_message({"ok": True, "profiles": list_profiles()}) + elif cmd == "launch": + launch(msg["path"]) + send_message({"ok": True}) + else: + send_message({"ok": False, "error": f"unknown command: {cmd}"}) + except Exception as e: + send_message({"ok": False, "error": str(e)}) + + +if __name__ == "__main__": + main()