initial commit

This commit is contained in:
timothykim committed 2026-10-21 20:40:39 -04:00
commit 97dd8da178
11 files changed
+480

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
.*.swp
web-ext-artifacts/
extension/.amo-upload-uuid
dist/quick-profile.xpi
Binary file not shown.
+27
View File
@@ -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 <path> --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`).
+58
View File
@@ -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);
+54
View File
@@ -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);
}
+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
<circle cx="8" cy="8" r="8" fill="#5b5b66"/>
<circle cx="8" cy="6" r="2.5" fill="#fff"/>
<path d="M3.5 13a4.5 4.5 0 0 1 9 0z" fill="#fff"/>
</svg>

After

Width:  |  Height:  |  Size: 237 B

+28
View File
@@ -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
}
}
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Quick Profile</title>
<style>
:root { color-scheme: light dark; font: message-box; }
body { margin: 12px; }
h1 { font-size: 1.1em; margin: 0 0 8px; }
p { margin: 0 0 12px; opacity: 0.8; }
ul { list-style: none; margin: 0; padding: 0; }
label {
display: flex; align-items: center; gap: 10px;
padding: 6px 8px; border-radius: 6px; cursor: pointer;
}
label:hover { background: color-mix(in srgb, currentColor 8%, transparent); }
img { width: 24px; height: 24px; border-radius: 50%; }
.path { font-size: 0.85em; opacity: 0.6; }
#status { margin-top: 12px; min-height: 1.2em; }
.error { color: #d70022; }
code { font-family: monospace; }
</style>
</head>
<body>
<h1>Profile to open</h1>
<p>Clicking the toolbar button opens (or focuses) this profile.</p>
<ul id="profiles"></ul>
<div id="status"></div>
<script src="common.js"></script>
<script src="options.js"></script>
</body>
</html>
+64
View File
@@ -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();
+22
View File
@@ -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" <<EOF
{
"name": "quick_profile",
"description": "Quick Profile native host",
"path": "$HOST_SCRIPT",
"type": "stdio",
"allowed_extensions": ["quick-profile@timothykim"]
}
EOF
echo "Installed $MANIFEST_DIR/quick_profile.json -> $HOST_SCRIPT"
+186
View File
@@ -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("<H", data, pos + 10)
+ struct.unpack_from("<I", data, pos + 20)
+ struct.unpack_from("<HHH", data, pos + 28)
+ struct.unpack_from("<I", data, pos + 42)
)
name = data[pos + 46:pos + 46 + name_len].decode()
if name in wanted:
lname_len, lextra_len = struct.unpack_from("<HH", data, local_off + 26)
start = local_off + 30 + lname_len + lextra_len
blob = data[start:start + csize]
out[name] = zlib.decompress(blob, -15) if method == 8 else blob
wanted.discard(name)
pos += 46 + name_len + extra_len + comment_len
return out
def avatar_images(avatars):
"""Map avatar name -> {"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()