zenform 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- zenform/__init__.py +6 -0
- zenform/__main__.py +5 -0
- zenform/cli.py +201 -0
- zenform/config.py +161 -0
- zenform/favicons.py +86 -0
- zenform/model.py +409 -0
- zenform/mozlz4.py +86 -0
- zenform/profile.py +93 -0
- zenform-0.1.0.dist-info/METADATA +123 -0
- zenform-0.1.0.dist-info/RECORD +13 -0
- zenform-0.1.0.dist-info/WHEEL +4 -0
- zenform-0.1.0.dist-info/entry_points.txt +2 -0
- zenform-0.1.0.dist-info/licenses/LICENSE +21 -0
zenform/__init__.py
ADDED
zenform/__main__.py
ADDED
zenform/cli.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""The zenform command line: doctor, dump, plan, apply, rollback."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from zenform import TESTED_ZEN, __version__, config, model, mozlz4, profile
|
|
12
|
+
from zenform.favicons import Favicons
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _load_session(prof: str) -> dict:
|
|
16
|
+
path = os.path.join(prof, profile.SESSION)
|
|
17
|
+
if not os.path.exists(path):
|
|
18
|
+
raise SystemExit(f"No {profile.SESSION} in {prof}. Has Zen been opened with this profile?")
|
|
19
|
+
session = mozlz4.read(path)
|
|
20
|
+
problems = model.check_session_shape(session)
|
|
21
|
+
if problems:
|
|
22
|
+
raise SystemExit(
|
|
23
|
+
"This session file does not look like the format zenform knows:\n "
|
|
24
|
+
+ "\n ".join(problems)
|
|
25
|
+
+ "\nRun `zenform doctor`; Zen may have changed its format."
|
|
26
|
+
)
|
|
27
|
+
return session
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _plan(args, prof: str):
|
|
31
|
+
cfg = config.find_config(args.config)
|
|
32
|
+
spec = config.load_config(cfg)
|
|
33
|
+
session = _load_session(prof)
|
|
34
|
+
icons = None if args.no_favicons else Favicons(prof)
|
|
35
|
+
new, ops = model.apply_layout(session, spec, reset_pins=args.reset_pins, favicons=icons)
|
|
36
|
+
return cfg, spec, session, new, ops
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def cmd_doctor(args) -> int:
|
|
40
|
+
ok = True
|
|
41
|
+
|
|
42
|
+
def line(mark, text):
|
|
43
|
+
nonlocal ok
|
|
44
|
+
ok = ok and mark != "FAIL"
|
|
45
|
+
print(f"{mark:5} {text}")
|
|
46
|
+
|
|
47
|
+
line("ok", f"zenform {__version__}, Python {sys.version.split()[0]}")
|
|
48
|
+
try:
|
|
49
|
+
prof = args.profile or profile.default_profile()
|
|
50
|
+
line("ok", f"profile: {prof}")
|
|
51
|
+
except SystemExit as e:
|
|
52
|
+
line("FAIL", str(e))
|
|
53
|
+
return 1
|
|
54
|
+
version = profile.zen_version()
|
|
55
|
+
if version is None:
|
|
56
|
+
line("warn", "could not read the installed Zen version")
|
|
57
|
+
elif version in TESTED_ZEN:
|
|
58
|
+
line("ok", f"Zen {version} (tested)")
|
|
59
|
+
else:
|
|
60
|
+
line(
|
|
61
|
+
"warn",
|
|
62
|
+
f"Zen {version} has not been tested (tested: {', '.join(TESTED_ZEN)}); plan output is still safe to read",
|
|
63
|
+
)
|
|
64
|
+
line(
|
|
65
|
+
"warn" if profile.zen_running() else "ok",
|
|
66
|
+
"Zen is running: close it before `apply`" if profile.zen_running() else "Zen is closed",
|
|
67
|
+
)
|
|
68
|
+
try:
|
|
69
|
+
session = _load_session(prof)
|
|
70
|
+
names = ", ".join(model.workspace_names(session)) or "none"
|
|
71
|
+
pinned = sum(1 for t in session["tabs"] if t.get("pinned") and not t.get("zenIsEmpty"))
|
|
72
|
+
line("ok", f"session readable: {pinned} pins, {len(session['folders'])} folders, workspaces: {names}")
|
|
73
|
+
except (SystemExit, ValueError) as e:
|
|
74
|
+
line("FAIL", f"session: {e}")
|
|
75
|
+
backups = os.path.join(prof, profile.BACKUPS)
|
|
76
|
+
line("ok", f"{len(os.listdir(backups)) if os.path.isdir(backups) else 0} backup(s) in {profile.BACKUPS}/")
|
|
77
|
+
try:
|
|
78
|
+
cfg = config.find_config(args.config)
|
|
79
|
+
spec = config.load_config(cfg)
|
|
80
|
+
problems = model.validate_spec(spec)
|
|
81
|
+
line("FAIL" if problems else "ok", f"config {cfg}: " + ("; ".join(problems) if problems else "valid"))
|
|
82
|
+
for w in model.warnings(spec):
|
|
83
|
+
line("warn", w)
|
|
84
|
+
except SystemExit as e:
|
|
85
|
+
line("warn", f"config: {e}")
|
|
86
|
+
return 0 if ok else 1
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def cmd_dump(args) -> int:
|
|
90
|
+
prof = args.profile or profile.default_profile()
|
|
91
|
+
session = _load_session(prof)
|
|
92
|
+
names = model.workspace_names(session)
|
|
93
|
+
ws = args.workspace or (names[0] if len(names) == 1 else None)
|
|
94
|
+
if not ws:
|
|
95
|
+
raise SystemExit(f"Several workspaces ({', '.join(names)}); pass --workspace.")
|
|
96
|
+
written = config.write_config(config.current_spec(session, ws), args.out, force=args.force)
|
|
97
|
+
print(f"Wrote {len(written)} files to {args.out}:")
|
|
98
|
+
for p in written:
|
|
99
|
+
print(f" {os.path.relpath(p, args.out)}")
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def cmd_plan(args) -> int:
|
|
104
|
+
prof = args.profile or profile.default_profile()
|
|
105
|
+
_, spec, _, _, ops = _plan(args, prof)
|
|
106
|
+
warns = model.warnings(spec)
|
|
107
|
+
if args.json:
|
|
108
|
+
print(
|
|
109
|
+
json.dumps(
|
|
110
|
+
{"workspace": spec["workspace"], "changes": ops, "warnings": warns},
|
|
111
|
+
indent=2,
|
|
112
|
+
ensure_ascii=False,
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
else:
|
|
116
|
+
for w in warns:
|
|
117
|
+
print(f"warning: {w}", file=sys.stderr)
|
|
118
|
+
print(model.render_plan(ops))
|
|
119
|
+
print("\nThis is a plan; nothing was written. Close Zen, then run `zenform apply`.")
|
|
120
|
+
return 2 if args.exit_code and model.changes(ops) else 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def cmd_apply(args) -> int:
|
|
124
|
+
prof = args.profile or profile.default_profile()
|
|
125
|
+
_, spec, _, new, ops = _plan(args, prof)
|
|
126
|
+
for w in model.warnings(spec):
|
|
127
|
+
print(f"warning: {w}", file=sys.stderr)
|
|
128
|
+
print(model.render_plan(ops))
|
|
129
|
+
if profile.zen_running() and not args.force_running:
|
|
130
|
+
raise SystemExit("\nZen is open. Quit it first (it rewrites the file when it quits), then run again.")
|
|
131
|
+
problems = model.check(new, spec)
|
|
132
|
+
if problems:
|
|
133
|
+
raise SystemExit("\nThe result does not match the config, nothing written:\n " + "\n ".join(problems))
|
|
134
|
+
session_path = os.path.join(prof, profile.SESSION)
|
|
135
|
+
saved = profile.backup(prof)
|
|
136
|
+
tmp = session_path + ".tmp"
|
|
137
|
+
with open(tmp, "wb") as fh:
|
|
138
|
+
fh.write(mozlz4.encode(new))
|
|
139
|
+
os.replace(tmp, session_path)
|
|
140
|
+
after = model.check(mozlz4.read(session_path), spec)
|
|
141
|
+
if after:
|
|
142
|
+
shutil.copy2(saved, session_path)
|
|
143
|
+
raise SystemExit("\nRead-back check failed, backup restored:\n " + "\n ".join(after))
|
|
144
|
+
print(f"\nWritten and read back. Backup: {saved}\nUndo: zenform rollback (with Zen closed)")
|
|
145
|
+
return 0
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def cmd_rollback(args) -> int:
|
|
149
|
+
prof = args.profile or profile.default_profile()
|
|
150
|
+
if profile.zen_running() and not args.force_running:
|
|
151
|
+
raise SystemExit("Zen is open. Quit it first (it rewrites the file when it quits).")
|
|
152
|
+
backup = profile.newest_backup(prof)
|
|
153
|
+
if not backup:
|
|
154
|
+
raise SystemExit("No backup to restore.")
|
|
155
|
+
shutil.copy2(backup, os.path.join(prof, profile.SESSION))
|
|
156
|
+
print(f"Restored {backup}")
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
161
|
+
ap = argparse.ArgumentParser(
|
|
162
|
+
prog="zenform", description="Zen browser as code: plan and apply your sidebar from files."
|
|
163
|
+
)
|
|
164
|
+
ap.add_argument("--version", action="version", version=f"zenform {__version__}")
|
|
165
|
+
ap.add_argument("--config", help="the config directory (default: $ZENFORM_CONFIG, else the current directory)")
|
|
166
|
+
ap.add_argument("--profile", help="a Zen profile folder (default: the one Zen starts with)")
|
|
167
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
168
|
+
|
|
169
|
+
sub.add_parser("doctor", help="check the profile, the Zen version, the session format and the config").set_defaults(
|
|
170
|
+
fn=cmd_doctor
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
d = sub.add_parser("dump", help="write the current pins as a config directory (start here)")
|
|
174
|
+
d.add_argument("--out", required=True, help="directory to write the config to")
|
|
175
|
+
d.add_argument("--workspace", help="the workspace (default: the only one)")
|
|
176
|
+
d.add_argument("--force", action="store_true", help="overwrite an existing config")
|
|
177
|
+
d.set_defaults(fn=cmd_dump)
|
|
178
|
+
|
|
179
|
+
for name, fn, helptext in (
|
|
180
|
+
("plan", cmd_plan, "show what applying would change; writes nothing"),
|
|
181
|
+
("apply", cmd_apply, "apply the config (Zen must be closed); backs up first"),
|
|
182
|
+
):
|
|
183
|
+
p = sub.add_parser(name, help=helptext)
|
|
184
|
+
p.add_argument("--reset-pins", action="store_true", help="also send each pin back to its home page")
|
|
185
|
+
p.add_argument("--no-favicons", action="store_true", help="do not fill in missing pin icons")
|
|
186
|
+
if name == "plan":
|
|
187
|
+
p.add_argument("--json", action="store_true", help="print the plan as JSON")
|
|
188
|
+
p.add_argument("--exit-code", action="store_true", help="exit 2 if there is anything to change")
|
|
189
|
+
else:
|
|
190
|
+
p.add_argument("--force-running", action="store_true", help="do not refuse while Zen is open")
|
|
191
|
+
p.set_defaults(fn=fn)
|
|
192
|
+
|
|
193
|
+
r = sub.add_parser("rollback", help="restore the newest backup (Zen must be closed)")
|
|
194
|
+
r.add_argument("--force-running", action="store_true", help="do not refuse while Zen is open")
|
|
195
|
+
r.set_defaults(fn=cmd_rollback)
|
|
196
|
+
return ap
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def main(argv=None) -> int:
|
|
200
|
+
args = build_parser().parse_args(argv)
|
|
201
|
+
return args.fn(args)
|
zenform/config.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""The config directory: reading it into a spec, and writing the current browser state out as one.
|
|
2
|
+
|
|
3
|
+
zenform.toml workspace = "Work" which workspace; keep_folders = [...]
|
|
4
|
+
essentials.toml pins = [ {label, url}, ] the icon tiles
|
|
5
|
+
folders/NN-name.toml name = "MRs" one file per pinned folder, in file-name order
|
|
6
|
+
pins = [ {label, url}, ]
|
|
7
|
+
loose.toml pins = [ ... ] optional: pins outside any folder, after the folders
|
|
8
|
+
|
|
9
|
+
Unknown keys are errors, so a typo does not silently do nothing.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import tomllib
|
|
18
|
+
|
|
19
|
+
from zenform import model
|
|
20
|
+
|
|
21
|
+
ROOT_KEYS = {"workspace", "keep_folders"}
|
|
22
|
+
PINS_KEYS = {"pins"}
|
|
23
|
+
FOLDER_KEYS = {"name", "collapsed", "pins"}
|
|
24
|
+
PIN_KEYS = {"label", "url"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _load(path: str, allowed: set[str]) -> dict:
|
|
28
|
+
try:
|
|
29
|
+
with open(path, "rb") as fh:
|
|
30
|
+
data = tomllib.load(fh)
|
|
31
|
+
except tomllib.TOMLDecodeError as e:
|
|
32
|
+
raise SystemExit(f"{path}: not valid TOML: {e}") from None
|
|
33
|
+
unknown = set(data) - allowed
|
|
34
|
+
if unknown:
|
|
35
|
+
raise SystemExit(f"{path}: unknown key(s) {sorted(unknown)}; allowed: {sorted(allowed)}")
|
|
36
|
+
for pin in data.get("pins", []):
|
|
37
|
+
bad = set(pin) - PIN_KEYS
|
|
38
|
+
if bad:
|
|
39
|
+
raise SystemExit(f"{path}: a pin has unknown key(s) {sorted(bad)}; allowed: {sorted(PIN_KEYS)}")
|
|
40
|
+
return data
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def find_config(arg: str | None) -> str:
|
|
44
|
+
path = arg or os.environ.get("ZENFORM_CONFIG") or os.getcwd()
|
|
45
|
+
if not os.path.isfile(os.path.join(path, "zenform.toml")):
|
|
46
|
+
raise SystemExit(f"No zenform.toml in {path}. Pass --config DIR or set ZENFORM_CONFIG (see `zenform dump`).")
|
|
47
|
+
return path
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load_config(path: str) -> dict:
|
|
51
|
+
root = _load(os.path.join(path, "zenform.toml"), ROOT_KEYS)
|
|
52
|
+
spec: dict = {
|
|
53
|
+
"workspace": root.get("workspace"),
|
|
54
|
+
"keep_folders": root.get("keep_folders", []),
|
|
55
|
+
"essentials": [],
|
|
56
|
+
"folders": [],
|
|
57
|
+
"pins": [],
|
|
58
|
+
}
|
|
59
|
+
ess = os.path.join(path, "essentials.toml")
|
|
60
|
+
if os.path.isfile(ess):
|
|
61
|
+
spec["essentials"] = _load(ess, PINS_KEYS).get("pins", [])
|
|
62
|
+
folders = os.path.join(path, "folders")
|
|
63
|
+
if os.path.isdir(folders):
|
|
64
|
+
for name in sorted(os.listdir(folders)):
|
|
65
|
+
if name.endswith(".toml"):
|
|
66
|
+
f = _load(os.path.join(folders, name), FOLDER_KEYS)
|
|
67
|
+
if not f.get("name"):
|
|
68
|
+
raise SystemExit(f'{os.path.join(folders, name)}: a folder needs name = "..."')
|
|
69
|
+
spec["folders"].append(f)
|
|
70
|
+
loose = os.path.join(path, "loose.toml")
|
|
71
|
+
if os.path.isfile(loose):
|
|
72
|
+
spec["pins"] = _load(loose, PINS_KEYS).get("pins", [])
|
|
73
|
+
return spec
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# --- writing ----------------------------------------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _s(value: str) -> str:
|
|
80
|
+
return json.dumps(value, ensure_ascii=False)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _pins_block(pins: list[dict]) -> str:
|
|
84
|
+
if not pins:
|
|
85
|
+
return "pins = []\n"
|
|
86
|
+
width = max(len(_s(p["label"])) for p in pins)
|
|
87
|
+
rows = [f" {{label = {_s(p['label']) + ',':<{width + 1}} url = {_s(p['url'])}}}," for p in pins]
|
|
88
|
+
return "pins = [\n" + "\n".join(rows) + "\n]\n"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _slug(name: str) -> str:
|
|
92
|
+
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") or "folder"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def current_spec(session: dict, workspace: str) -> dict:
|
|
96
|
+
"""The session's pins for one workspace, as a spec."""
|
|
97
|
+
ws = model.workspace_id(session, workspace)
|
|
98
|
+
tabs = session["tabs"]
|
|
99
|
+
|
|
100
|
+
def pin(t):
|
|
101
|
+
return {"label": model.tab_label(t), "url": model.home_url(t)}
|
|
102
|
+
|
|
103
|
+
folders = []
|
|
104
|
+
for f in session.get("folders", []):
|
|
105
|
+
if f.get("workspaceId") == ws:
|
|
106
|
+
pins = [pin(t) for t in tabs if t.get("groupId") == f["id"] and not t.get("zenIsEmpty")]
|
|
107
|
+
folders.append({"name": f["name"], "pins": pins})
|
|
108
|
+
return {
|
|
109
|
+
"workspace": workspace,
|
|
110
|
+
"keep_folders": [],
|
|
111
|
+
"essentials": [pin(t) for t in tabs if t.get("zenEssential")],
|
|
112
|
+
"folders": folders,
|
|
113
|
+
"pins": [
|
|
114
|
+
pin(t)
|
|
115
|
+
for t in tabs
|
|
116
|
+
if t.get("pinned")
|
|
117
|
+
and not t.get("zenEssential")
|
|
118
|
+
and t.get("zenWorkspace") == ws
|
|
119
|
+
and not t.get("groupId")
|
|
120
|
+
and not t.get("zenIsEmpty")
|
|
121
|
+
],
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def write_config(spec: dict, outdir: str, *, force: bool = False) -> list[str]:
|
|
126
|
+
"""Write a spec as a config directory. Refuses to overwrite an existing one unless force."""
|
|
127
|
+
if os.path.exists(os.path.join(outdir, "zenform.toml")) and not force:
|
|
128
|
+
raise SystemExit(f"{outdir} already has a zenform.toml; use --force to overwrite.")
|
|
129
|
+
os.makedirs(os.path.join(outdir, "folders"), exist_ok=True)
|
|
130
|
+
for old in os.listdir(os.path.join(outdir, "folders")):
|
|
131
|
+
if old.endswith(".toml"):
|
|
132
|
+
os.unlink(os.path.join(outdir, "folders", old))
|
|
133
|
+
written = []
|
|
134
|
+
|
|
135
|
+
def put(rel: str, text: str) -> None:
|
|
136
|
+
path = os.path.join(outdir, rel)
|
|
137
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
138
|
+
fh.write(text)
|
|
139
|
+
written.append(path)
|
|
140
|
+
|
|
141
|
+
keep = ", ".join(_s(n) for n in spec.get("keep_folders", []))
|
|
142
|
+
put(
|
|
143
|
+
"zenform.toml",
|
|
144
|
+
f"# zenform config: `zenform plan` shows what applying it would change; `zenform apply` does it (Zen closed).\n"
|
|
145
|
+
f"workspace = {_s(spec['workspace'])}\n\n"
|
|
146
|
+
f"# Folders zenform never touches (Zen manages these itself).\n"
|
|
147
|
+
f"keep_folders = [{keep}]\n",
|
|
148
|
+
)
|
|
149
|
+
put(
|
|
150
|
+
"essentials.toml",
|
|
151
|
+
"# The icon tiles. label: 14 characters or fewer. url: the pin's home page.\n"
|
|
152
|
+
+ _pins_block(spec["essentials"]),
|
|
153
|
+
)
|
|
154
|
+
for i, f in enumerate(spec["folders"], start=1):
|
|
155
|
+
put(
|
|
156
|
+
f"folders/{i * 10:02d}-{_slug(f['name'])}.toml",
|
|
157
|
+
f"name = {_s(f['name'])}\n\n" + _pins_block(f["pins"]),
|
|
158
|
+
)
|
|
159
|
+
if spec.get("pins"):
|
|
160
|
+
put("loose.toml", "# Pins outside any folder, shown after the folders.\n" + _pins_block(spec["pins"]))
|
|
161
|
+
return written
|
zenform/favicons.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Icons for pins, from the profile's favicons.sqlite (read from a copy, never the original)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import os
|
|
7
|
+
import shutil
|
|
8
|
+
import sqlite3
|
|
9
|
+
import tempfile
|
|
10
|
+
import urllib.parse
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def sniff_mime(b: bytes) -> str | None:
|
|
14
|
+
if b[:4] == b"\x89PNG":
|
|
15
|
+
return "image/png"
|
|
16
|
+
if b[:4] == b"\x00\x00\x01\x00":
|
|
17
|
+
return "image/x-icon"
|
|
18
|
+
if b[:3] == b"GIF":
|
|
19
|
+
return "image/gif"
|
|
20
|
+
if b[:2] == b"\xff\xd8":
|
|
21
|
+
return "image/jpeg"
|
|
22
|
+
if b[:4] == b"RIFF" and b[8:12] == b"WEBP":
|
|
23
|
+
return "image/webp"
|
|
24
|
+
head = b[:200].lstrip().lower()
|
|
25
|
+
if head.startswith((b"<svg", b"<?xml")):
|
|
26
|
+
return "image/svg+xml"
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _origin(url: str) -> str:
|
|
31
|
+
u = urllib.parse.urlsplit(url)
|
|
32
|
+
return f"{u.scheme}://{u.netloc}"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _segments(url: str) -> list[str]:
|
|
36
|
+
return [x for x in urllib.parse.urlsplit(url).path.split("/") if x]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Favicons:
|
|
40
|
+
"""Find an icon by page URL, then by the closest page on the same site, then by the site's root icon."""
|
|
41
|
+
|
|
42
|
+
MAX_BYTES = 150_000
|
|
43
|
+
|
|
44
|
+
def __init__(self, profile: str | None):
|
|
45
|
+
self.by_origin: dict[str, list[tuple[str, int, bytes]]] = {}
|
|
46
|
+
src = os.path.join(profile, "favicons.sqlite") if profile else ""
|
|
47
|
+
if not src or not os.path.exists(src):
|
|
48
|
+
return
|
|
49
|
+
with tempfile.TemporaryDirectory() as tmp: # a copy: Zen may hold the original open
|
|
50
|
+
for suffix in ("", "-wal"):
|
|
51
|
+
if os.path.exists(src + suffix):
|
|
52
|
+
shutil.copy2(src + suffix, os.path.join(tmp, "favicons.sqlite" + suffix))
|
|
53
|
+
con = sqlite3.connect(os.path.join(tmp, "favicons.sqlite"))
|
|
54
|
+
try:
|
|
55
|
+
pages = con.execute(
|
|
56
|
+
"select p.page_url, i.width, i.data from moz_pages_w_icons p "
|
|
57
|
+
"join moz_icons_to_pages ip on ip.page_id = p.id join moz_icons i on i.id = ip.icon_id "
|
|
58
|
+
"where i.data is not null"
|
|
59
|
+
).fetchall()
|
|
60
|
+
roots = con.execute(
|
|
61
|
+
"select icon_url, width, data from moz_icons where root = 1 and data is not null"
|
|
62
|
+
).fetchall()
|
|
63
|
+
except sqlite3.Error:
|
|
64
|
+
pages, roots = [], []
|
|
65
|
+
finally:
|
|
66
|
+
con.close()
|
|
67
|
+
for page_url, width, data in pages + roots:
|
|
68
|
+
if data and len(data) <= self.MAX_BYTES and sniff_mime(data):
|
|
69
|
+
self.by_origin.setdefault(_origin(page_url), []).append((page_url, width or 0, bytes(data)))
|
|
70
|
+
|
|
71
|
+
def find(self, url: str) -> str | None:
|
|
72
|
+
cands = self.by_origin.get(_origin(url))
|
|
73
|
+
if not cands:
|
|
74
|
+
return None
|
|
75
|
+
want = _segments(url)
|
|
76
|
+
|
|
77
|
+
def score(c):
|
|
78
|
+
common = 0
|
|
79
|
+
for a, b in zip(want, _segments(c[0]), strict=False):
|
|
80
|
+
if a != b:
|
|
81
|
+
break
|
|
82
|
+
common += 1
|
|
83
|
+
return (c[0] == url, common, min(c[1] or 32, 64))
|
|
84
|
+
|
|
85
|
+
data = max(cands, key=score)[2]
|
|
86
|
+
return f"data:{sniff_mime(data)};base64,{base64.b64encode(data).decode()}"
|
zenform/model.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
"""The layout and the session: applying one to the other.
|
|
2
|
+
|
|
3
|
+
`apply_layout(session, spec)` is pure: it returns a new session and a list of operations (dicts), and never
|
|
4
|
+
touches the input. The operations are the plan; `render_plan` turns them into text, `plan --json` prints them as is.
|
|
5
|
+
|
|
6
|
+
A spec is what config.load_config builds from the files:
|
|
7
|
+
|
|
8
|
+
{"workspace": "Work", "keep_folders": [...], "essentials": [pin], "folders": [{"name", "pins", "collapsed"?}],
|
|
9
|
+
"pins": [pin]} # pin = {"label": ..., "url": ...}; "pins" are loose pins, after the folders
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import copy
|
|
15
|
+
import time
|
|
16
|
+
import uuid
|
|
17
|
+
|
|
18
|
+
from zenform.favicons import Favicons
|
|
19
|
+
|
|
20
|
+
MAX_LABEL = 14 # the sidebar cuts a pin's label off about here
|
|
21
|
+
ESSENTIALS_GRID = 9 # a 3x3 grid; more still works, as a fourth row
|
|
22
|
+
|
|
23
|
+
# Operations that change something (the others, like icons, only inform).
|
|
24
|
+
CHANGING = {"add", "relabel", "move", "unpin", "remove_folder"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# --- reading a session ----------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def home_url(tab: dict) -> str:
|
|
31
|
+
"""The page a pin goes back to: Zen's own record of it, else the page it is on."""
|
|
32
|
+
init = (tab.get("_zenPinnedInitialState") or {}).get("entry") or {}
|
|
33
|
+
if init.get("url"):
|
|
34
|
+
return init["url"]
|
|
35
|
+
entries = tab.get("entries") or [{}]
|
|
36
|
+
i = (tab.get("index") or 1) - 1
|
|
37
|
+
return (entries[i] if 0 <= i < len(entries) else entries[-1]).get("url", "")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def tab_label(tab: dict) -> str:
|
|
41
|
+
if tab.get("zenStaticLabel"):
|
|
42
|
+
return tab["zenStaticLabel"]
|
|
43
|
+
init = (tab.get("_zenPinnedInitialState") or {}).get("entry") or {}
|
|
44
|
+
return init.get("title") or home_url(tab)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def workspace_names(session: dict) -> list[str]:
|
|
48
|
+
return [s.get("name", "?") for s in session.get("spaces", [])]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def workspace_id(session: dict, name: str) -> str:
|
|
52
|
+
for space in session.get("spaces", []):
|
|
53
|
+
if space.get("name") == name:
|
|
54
|
+
return space["uuid"]
|
|
55
|
+
raise SystemExit(f"No workspace named {name!r} in the session (it has: {', '.join(workspace_names(session))}).")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def check_session_shape(session: dict) -> list[str]:
|
|
59
|
+
"""What a session must have for zenform to work on it; an empty list means it looks right."""
|
|
60
|
+
problems = [f"missing key {k!r}" for k in ("tabs", "folders", "groups", "spaces") if k not in session]
|
|
61
|
+
for t in session.get("tabs", [])[:50]:
|
|
62
|
+
if t.get("pinned") and "zenEssential" not in t:
|
|
63
|
+
problems.append("a pinned tab has no zenEssential field (Zen's format may have changed)")
|
|
64
|
+
break
|
|
65
|
+
return problems
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# --- building session entries ---------------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def new_sync_id() -> str:
|
|
72
|
+
return f"{int(time.time() * 1000)}-{uuid.uuid4()}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _base_tab(url: str, *, workspace, group) -> dict:
|
|
76
|
+
return {
|
|
77
|
+
"lastAccessed": int(time.time() * 1000),
|
|
78
|
+
"pinned": True,
|
|
79
|
+
"hidden": False,
|
|
80
|
+
**({"groupId": group} if group else {}),
|
|
81
|
+
"zenWorkspace": workspace,
|
|
82
|
+
"zenSyncId": new_sync_id(),
|
|
83
|
+
"zenPinnedIcon": None,
|
|
84
|
+
"zenHasStaticIcon": False,
|
|
85
|
+
"zenGlanceId": None,
|
|
86
|
+
"zenIsGlance": False,
|
|
87
|
+
"zenLiveFolderItemId": None,
|
|
88
|
+
"searchMode": None,
|
|
89
|
+
"userContextId": 0,
|
|
90
|
+
"attributes": {},
|
|
91
|
+
"index": 1,
|
|
92
|
+
"userTypedValue": "",
|
|
93
|
+
"userTypedClear": 0,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def new_pin(label: str, url: str, *, essential: bool, group, workspace) -> dict:
|
|
98
|
+
return {
|
|
99
|
+
**_base_tab(url, workspace=None if essential else workspace, group=group),
|
|
100
|
+
"entries": [{"url": url, "title": label}],
|
|
101
|
+
"zenEssential": essential,
|
|
102
|
+
"zenDefaultUserContextId": "true",
|
|
103
|
+
"zenIsEmpty": False,
|
|
104
|
+
"zenStaticLabel": label,
|
|
105
|
+
"_zenPinnedInitialState": {"entry": {"url": url, "title": label}, "image": None},
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def new_placeholder(group: str, workspace: str) -> dict:
|
|
110
|
+
return {
|
|
111
|
+
**_base_tab("about:blank", workspace=workspace, group=group),
|
|
112
|
+
"entries": [{"url": "about:blank"}],
|
|
113
|
+
"zenEssential": False,
|
|
114
|
+
"zenDefaultUserContextId": None,
|
|
115
|
+
"zenIsEmpty": True,
|
|
116
|
+
"_zenPinnedInitialState": {"entry": {"url": "about:blank"}, "image": None},
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def unpin(tab: dict) -> None:
|
|
121
|
+
tab["pinned"] = False
|
|
122
|
+
tab["zenEssential"] = False
|
|
123
|
+
for key in ("groupId", "zenStaticLabel", "_zenPinnedInitialState"):
|
|
124
|
+
tab.pop(key, None)
|
|
125
|
+
tab["zenHasStaticIcon"] = False
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# --- checking a spec ------------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _all_pins(spec: dict):
|
|
132
|
+
for e in spec.get("essentials", []):
|
|
133
|
+
yield "essentials", e
|
|
134
|
+
for f in spec.get("folders", []):
|
|
135
|
+
for p in f.get("pins", []):
|
|
136
|
+
yield f.get("name", "?"), p
|
|
137
|
+
for p in spec.get("pins", []):
|
|
138
|
+
yield "pins", p
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def validate_spec(spec: dict) -> list[str]:
|
|
142
|
+
problems = []
|
|
143
|
+
if not spec.get("workspace"):
|
|
144
|
+
problems.append('the config needs workspace = "..." in zenform.toml')
|
|
145
|
+
for f in spec.get("folders", []):
|
|
146
|
+
if not f.get("name"):
|
|
147
|
+
problems.append("a folder has no name")
|
|
148
|
+
for _, it in _all_pins(spec):
|
|
149
|
+
if not it.get("label") or not it.get("url"):
|
|
150
|
+
problems.append(f"every pin needs a label and a url: {it}")
|
|
151
|
+
names = [f.get("name") for f in spec.get("folders", [])]
|
|
152
|
+
if len(set(names)) != len(names):
|
|
153
|
+
problems.append("two folders have the same name")
|
|
154
|
+
both = set(names) & set(spec.get("keep_folders", []))
|
|
155
|
+
if both:
|
|
156
|
+
problems.append(f"folders both defined and in keep_folders: {sorted(both)}")
|
|
157
|
+
return problems
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def warnings(spec: dict) -> list[str]:
|
|
161
|
+
out = []
|
|
162
|
+
seen: dict[str, str] = {}
|
|
163
|
+
if len(spec.get("essentials", [])) > ESSENTIALS_GRID:
|
|
164
|
+
out.append(f"{len(spec['essentials'])} essentials: more than the {ESSENTIALS_GRID} of a 3x3 grid")
|
|
165
|
+
for where, it in _all_pins(spec):
|
|
166
|
+
if len(it["label"]) > MAX_LABEL:
|
|
167
|
+
out.append(
|
|
168
|
+
f"label {it['label']!r} ({where}) is {len(it['label'])} characters; the sidebar shows about {MAX_LABEL}"
|
|
169
|
+
)
|
|
170
|
+
if it["url"] in seen:
|
|
171
|
+
out.append(f"{it['url']} is pinned twice ({seen[it['url']]} and {where})")
|
|
172
|
+
seen[it["url"]] = where
|
|
173
|
+
return out
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# --- applying -------------------------------------------------------------------------------------
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def apply_layout(session: dict, spec: dict, *, reset_pins: bool = False, favicons: Favicons | None = None):
|
|
180
|
+
"""Return (new_session, ops). Pure: the input is not changed."""
|
|
181
|
+
problems = validate_spec(spec)
|
|
182
|
+
if problems:
|
|
183
|
+
raise SystemExit("Config problems:\n " + "\n ".join(problems))
|
|
184
|
+
s = copy.deepcopy(session)
|
|
185
|
+
ws = workspace_id(s, spec["workspace"])
|
|
186
|
+
tabs: list[dict] = s["tabs"]
|
|
187
|
+
ops: list[dict] = []
|
|
188
|
+
|
|
189
|
+
old_folders = {f["name"]: f for f in s.get("folders", []) if f.get("workspaceId") == ws}
|
|
190
|
+
kept = {n: old_folders[n] for n in spec.get("keep_folders", []) if n in old_folders}
|
|
191
|
+
kept_ids = {f["id"] for f in kept.values()}
|
|
192
|
+
for n in spec.get("keep_folders", []):
|
|
193
|
+
if n not in old_folders:
|
|
194
|
+
ops.append({"op": "keep_missing", "folder": n})
|
|
195
|
+
|
|
196
|
+
def in_scope(t): # what the config owns: essentials, and this workspace's pins outside kept folders
|
|
197
|
+
return (
|
|
198
|
+
t.get("pinned")
|
|
199
|
+
and t.get("groupId") not in kept_ids
|
|
200
|
+
and (t.get("zenEssential") or t.get("zenWorkspace") == ws)
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
pool = [t for t in tabs if in_scope(t) and not t.get("zenIsEmpty")]
|
|
204
|
+
placeholders = [t for t in tabs if in_scope(t) and t.get("zenIsEmpty")]
|
|
205
|
+
used: set[int] = set()
|
|
206
|
+
icons_filled: list[str] = []
|
|
207
|
+
icons_missing: list[str] = []
|
|
208
|
+
|
|
209
|
+
def give_icon(t, label, url):
|
|
210
|
+
init = t.setdefault("_zenPinnedInitialState", {"entry": {"url": url, "title": label}, "image": None})
|
|
211
|
+
image = init.get("image") or t.get("image")
|
|
212
|
+
if not image and favicons is not None:
|
|
213
|
+
image = favicons.find(url)
|
|
214
|
+
(icons_filled if image else icons_missing).append(label)
|
|
215
|
+
if image:
|
|
216
|
+
init["image"] = image
|
|
217
|
+
t["image"] = image
|
|
218
|
+
|
|
219
|
+
def take(url):
|
|
220
|
+
for t in pool:
|
|
221
|
+
if id(t) not in used and home_url(t) == url:
|
|
222
|
+
used.add(id(t))
|
|
223
|
+
return t
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
def place(label, url, *, essential, group, where):
|
|
227
|
+
t = take(url)
|
|
228
|
+
if t is None:
|
|
229
|
+
t = new_pin(label, url, essential=essential, group=group, workspace=ws)
|
|
230
|
+
ops.append({"op": "add", "where": where, "label": label, "url": url})
|
|
231
|
+
else:
|
|
232
|
+
old = tab_label(t)
|
|
233
|
+
moved = bool(t.get("zenEssential")) != essential or t.get("groupId") != group
|
|
234
|
+
if old != label:
|
|
235
|
+
ops.append({"op": "relabel", "where": where, "from": old, "to": label, "url": url})
|
|
236
|
+
elif moved:
|
|
237
|
+
ops.append({"op": "move", "where": where, "label": label, "url": url})
|
|
238
|
+
t["zenStaticLabel"] = label
|
|
239
|
+
t["zenEssential"] = essential
|
|
240
|
+
t["zenWorkspace"] = None if essential else ws
|
|
241
|
+
if group:
|
|
242
|
+
t["groupId"] = group
|
|
243
|
+
else:
|
|
244
|
+
t.pop("groupId", None)
|
|
245
|
+
if reset_pins:
|
|
246
|
+
t["entries"] = [{"url": url, "title": label}]
|
|
247
|
+
t["index"] = 1
|
|
248
|
+
t["pinned"] = True
|
|
249
|
+
give_icon(t, label, url)
|
|
250
|
+
return t
|
|
251
|
+
|
|
252
|
+
ordered: list[dict] = []
|
|
253
|
+
for e in spec.get("essentials", []):
|
|
254
|
+
ordered.append(place(e["label"], e["url"], essential=True, group=None, where="essentials"))
|
|
255
|
+
|
|
256
|
+
# Folders: reuse one with the same name (and its collapsed state), else make it.
|
|
257
|
+
old_groups = {g["id"]: g for g in s.get("groups", [])}
|
|
258
|
+
keep_ids: set[str] = set()
|
|
259
|
+
new_folders: list[dict] = []
|
|
260
|
+
new_groups: list[dict] = []
|
|
261
|
+
prev = None
|
|
262
|
+
for f in spec.get("folders", []):
|
|
263
|
+
old = old_folders.get(f["name"])
|
|
264
|
+
fid = old["id"] if old else f"{int(time.time() * 1000)}-{len(new_folders) + 1}"
|
|
265
|
+
keep_ids.add(fid)
|
|
266
|
+
collapsed = f.get("collapsed", old["collapsed"] if old else False)
|
|
267
|
+
ph = next((p for p in placeholders if p.get("groupId") == fid), None)
|
|
268
|
+
if ph is None:
|
|
269
|
+
ph = new_placeholder(fid, ws)
|
|
270
|
+
ordered.append(ph)
|
|
271
|
+
for p in f.get("pins", []):
|
|
272
|
+
ordered.append(place(p["label"], p["url"], essential=False, group=fid, where=f["name"]))
|
|
273
|
+
folder = (
|
|
274
|
+
dict(old)
|
|
275
|
+
if old
|
|
276
|
+
else {
|
|
277
|
+
"pinned": True,
|
|
278
|
+
"splitViewGroup": False,
|
|
279
|
+
"id": fid,
|
|
280
|
+
"name": f["name"],
|
|
281
|
+
"saveOnWindowClose": True,
|
|
282
|
+
"parentId": None,
|
|
283
|
+
"userIcon": "",
|
|
284
|
+
"workspaceId": ws,
|
|
285
|
+
}
|
|
286
|
+
)
|
|
287
|
+
folder.update(
|
|
288
|
+
collapsed=collapsed,
|
|
289
|
+
emptyTabIds=[ph["zenSyncId"]],
|
|
290
|
+
prevSiblingInfo={"type": "group", "id": prev} if prev else None,
|
|
291
|
+
)
|
|
292
|
+
new_folders.append(folder)
|
|
293
|
+
group = (
|
|
294
|
+
dict(old_groups[fid])
|
|
295
|
+
if fid in old_groups
|
|
296
|
+
else {
|
|
297
|
+
"pinned": True,
|
|
298
|
+
"splitView": False,
|
|
299
|
+
"id": fid,
|
|
300
|
+
"name": f["name"],
|
|
301
|
+
"color": "zen-workspace-color",
|
|
302
|
+
"saveOnWindowClose": True,
|
|
303
|
+
}
|
|
304
|
+
)
|
|
305
|
+
group["collapsed"] = collapsed
|
|
306
|
+
new_groups.append(group)
|
|
307
|
+
prev = fid
|
|
308
|
+
for p in spec.get("pins", []):
|
|
309
|
+
ordered.append(place(p["label"], p["url"], essential=False, group=None, where="pins"))
|
|
310
|
+
|
|
311
|
+
# Folders named in keep_folders come last, exactly as they were.
|
|
312
|
+
for name, old in kept.items():
|
|
313
|
+
ops.append({"op": "keep_folder", "folder": name})
|
|
314
|
+
ordered.extend(t for t in tabs if t.get("groupId") == old["id"])
|
|
315
|
+
folder = dict(old)
|
|
316
|
+
folder["prevSiblingInfo"] = {"type": "group", "id": prev} if prev else None
|
|
317
|
+
new_folders.append(folder)
|
|
318
|
+
new_groups.append(
|
|
319
|
+
dict(old_groups[old["id"]])
|
|
320
|
+
if old["id"] in old_groups
|
|
321
|
+
else {
|
|
322
|
+
"pinned": True,
|
|
323
|
+
"splitView": False,
|
|
324
|
+
"id": old["id"],
|
|
325
|
+
"name": name,
|
|
326
|
+
"color": "zen-workspace-color",
|
|
327
|
+
"collapsed": old.get("collapsed", False),
|
|
328
|
+
"saveOnWindowClose": True,
|
|
329
|
+
}
|
|
330
|
+
)
|
|
331
|
+
prev = old["id"]
|
|
332
|
+
|
|
333
|
+
if favicons is not None:
|
|
334
|
+
ops.append({"op": "icons", "filled": len(icons_filled), "missing": icons_missing})
|
|
335
|
+
|
|
336
|
+
# Everything the config owned and no longer lists becomes an ordinary tab.
|
|
337
|
+
for t in pool:
|
|
338
|
+
if id(t) not in used:
|
|
339
|
+
ops.append({"op": "unpin", "label": tab_label(t), "url": home_url(t)})
|
|
340
|
+
unpin(t)
|
|
341
|
+
for n, f in old_folders.items():
|
|
342
|
+
if f["id"] not in keep_ids and f["id"] not in kept_ids:
|
|
343
|
+
ops.append({"op": "remove_folder", "folder": n})
|
|
344
|
+
gone = {id(p) for p in placeholders if p.get("groupId") not in keep_ids} # kept folders are not in placeholders
|
|
345
|
+
in_ordered = {id(t) for t in ordered}
|
|
346
|
+
rest = [t for t in tabs if id(t) not in gone and id(t) not in in_ordered]
|
|
347
|
+
s["tabs"] = ordered + rest
|
|
348
|
+
ours = {f["id"] for f in old_folders.values()}
|
|
349
|
+
s["folders"] = [f for f in s.get("folders", []) if f.get("workspaceId") != ws] + new_folders
|
|
350
|
+
s["groups"] = [g for g in s.get("groups", []) if g["id"] not in ours] + new_groups
|
|
351
|
+
return s, ops
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def check(session: dict, spec: dict) -> list[str]:
|
|
355
|
+
"""After writing: does the session say what the config says?"""
|
|
356
|
+
ws = workspace_id(session, spec["workspace"])
|
|
357
|
+
errs = []
|
|
358
|
+
ess = [(tab_label(t), home_url(t)) for t in session["tabs"] if t.get("zenEssential")]
|
|
359
|
+
want = [(e["label"], e["url"]) for e in spec.get("essentials", [])]
|
|
360
|
+
if ess != want:
|
|
361
|
+
errs.append(f"essentials differ: {ess} != {want}")
|
|
362
|
+
folders = {f["name"]: f for f in session.get("folders", []) if f.get("workspaceId") == ws}
|
|
363
|
+
for f in spec.get("folders", []):
|
|
364
|
+
fo = folders.get(f["name"])
|
|
365
|
+
if not fo:
|
|
366
|
+
errs.append(f"folder {f['name']} missing")
|
|
367
|
+
continue
|
|
368
|
+
got = [
|
|
369
|
+
(tab_label(t), home_url(t))
|
|
370
|
+
for t in session["tabs"]
|
|
371
|
+
if t.get("groupId") == fo["id"] and not t.get("zenIsEmpty")
|
|
372
|
+
]
|
|
373
|
+
exp = [(p["label"], p["url"]) for p in f.get("pins", [])]
|
|
374
|
+
if got != exp:
|
|
375
|
+
errs.append(f"folder {f['name']} differs: {got} != {exp}")
|
|
376
|
+
if not any(t.get("zenSyncId") in fo["emptyTabIds"] for t in session["tabs"]):
|
|
377
|
+
errs.append(f"folder {f['name']} lost its placeholder")
|
|
378
|
+
extra = set(folders) - {f["name"] for f in spec.get("folders", [])} - set(spec.get("keep_folders", []))
|
|
379
|
+
if extra:
|
|
380
|
+
errs.append(f"unexpected folders: {sorted(extra)}")
|
|
381
|
+
return errs
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def changes(ops: list[dict]) -> list[dict]:
|
|
385
|
+
return [o for o in ops if o["op"] in CHANGING]
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def render_plan(ops: list[dict]) -> str:
|
|
389
|
+
lines = []
|
|
390
|
+
for o in ops:
|
|
391
|
+
kind = o["op"]
|
|
392
|
+
if kind == "add":
|
|
393
|
+
lines.append(f" + {o['label']} [{o['where']}] {o['url'][:70]}")
|
|
394
|
+
elif kind == "relabel":
|
|
395
|
+
lines.append(f" ~ {o['from']!r} -> {o['to']!r} [{o['where']}]")
|
|
396
|
+
elif kind == "move":
|
|
397
|
+
lines.append(f" ~ {o['label']!r} moved to [{o['where']}]")
|
|
398
|
+
elif kind == "unpin":
|
|
399
|
+
lines.append(f" - unpin {o['label']!r} (becomes an ordinary tab)")
|
|
400
|
+
elif kind == "remove_folder":
|
|
401
|
+
lines.append(f" - remove folder {o['folder']!r}")
|
|
402
|
+
elif kind == "keep_folder":
|
|
403
|
+
lines.append(f" = folder {o['folder']!r} kept as is")
|
|
404
|
+
elif kind == "keep_missing":
|
|
405
|
+
lines.append(f" ? keep_folders: no folder {o['folder']!r} in Zen; ignored")
|
|
406
|
+
elif kind == "icons":
|
|
407
|
+
miss = f"; none found for {', '.join(o['missing'])} (open each page once)" if o["missing"] else ""
|
|
408
|
+
lines.append(f" icons: {o['filled']} filled from the favicon database{miss}")
|
|
409
|
+
return "\n".join(lines) if lines else " (nothing to do)"
|
zenform/mozlz4.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""The mozlz4 container Firefox and Zen use for session files, with a small pure-Python LZ4 block codec.
|
|
2
|
+
|
|
3
|
+
Layout: b"mozLz40\\0" + little-endian uint32 uncompressed size + one LZ4 block. The reader handles any block. The
|
|
4
|
+
writer emits the simplest valid one (a single literals-only sequence): it is a little larger than a compressed file,
|
|
5
|
+
and Zen compresses it again the next time it saves.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import struct
|
|
12
|
+
|
|
13
|
+
MAGIC = b"mozLz40\0"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def lz4_decompress(src: bytes, size: int) -> bytes:
|
|
17
|
+
out = bytearray()
|
|
18
|
+
i, n = 0, len(src)
|
|
19
|
+
while i < n:
|
|
20
|
+
token = src[i]
|
|
21
|
+
i += 1
|
|
22
|
+
lit = token >> 4
|
|
23
|
+
if lit == 15:
|
|
24
|
+
while True:
|
|
25
|
+
b = src[i]
|
|
26
|
+
i += 1
|
|
27
|
+
lit += b
|
|
28
|
+
if b != 255:
|
|
29
|
+
break
|
|
30
|
+
out += src[i : i + lit]
|
|
31
|
+
i += lit
|
|
32
|
+
if i >= n:
|
|
33
|
+
break
|
|
34
|
+
offset = src[i] | (src[i + 1] << 8)
|
|
35
|
+
i += 2
|
|
36
|
+
length = token & 15
|
|
37
|
+
if length == 15:
|
|
38
|
+
while True:
|
|
39
|
+
b = src[i]
|
|
40
|
+
i += 1
|
|
41
|
+
length += b
|
|
42
|
+
if b != 255:
|
|
43
|
+
break
|
|
44
|
+
length += 4
|
|
45
|
+
start = len(out) - offset
|
|
46
|
+
if offset == 0 or start < 0:
|
|
47
|
+
raise ValueError("corrupt LZ4 block (bad offset)")
|
|
48
|
+
if offset >= length:
|
|
49
|
+
out += out[start : start + length]
|
|
50
|
+
else: # overlapping copy
|
|
51
|
+
for k in range(length):
|
|
52
|
+
out.append(out[start + k])
|
|
53
|
+
if len(out) != size:
|
|
54
|
+
raise ValueError(f"corrupt LZ4 block (expected {size} bytes, got {len(out)})")
|
|
55
|
+
return bytes(out)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def lz4_compress(data: bytes) -> bytes:
|
|
59
|
+
"""One literals-only sequence: valid LZ4, no compression."""
|
|
60
|
+
n = len(data)
|
|
61
|
+
out = bytearray()
|
|
62
|
+
if n < 15:
|
|
63
|
+
out.append(n << 4)
|
|
64
|
+
else:
|
|
65
|
+
out.append(0xF0)
|
|
66
|
+
rest = n - 15
|
|
67
|
+
while rest >= 255:
|
|
68
|
+
out.append(255)
|
|
69
|
+
rest -= 255
|
|
70
|
+
out.append(rest)
|
|
71
|
+
out += data
|
|
72
|
+
return bytes(out)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def read(path: str):
|
|
76
|
+
with open(path, "rb") as fh:
|
|
77
|
+
raw = fh.read()
|
|
78
|
+
if raw[:8] != MAGIC:
|
|
79
|
+
raise ValueError(f"{path} is not a mozlz4 file")
|
|
80
|
+
size = struct.unpack("<I", raw[8:12])[0]
|
|
81
|
+
return json.loads(lz4_decompress(raw[12:], size))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def encode(obj) -> bytes:
|
|
85
|
+
data = json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
|
86
|
+
return MAGIC + struct.pack("<I", len(data)) + lz4_compress(data)
|
zenform/profile.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Finding the Zen profile, knowing whether Zen is running, and backing the session file up."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import plistlib
|
|
7
|
+
import shutil
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
SESSION = "zen-sessions.jsonlz4"
|
|
13
|
+
BACKUPS = "zenform-backups"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def data_dir() -> str:
|
|
17
|
+
"""Where Zen keeps profiles.ini. Only macOS has been tested."""
|
|
18
|
+
if sys.platform == "darwin":
|
|
19
|
+
return os.path.expanduser("~/Library/Application Support/zen")
|
|
20
|
+
if sys.platform.startswith("win"):
|
|
21
|
+
return os.path.join(os.environ.get("APPDATA", ""), "zen")
|
|
22
|
+
flatpak = os.path.expanduser("~/.var/app/app.zen_browser.zen/.zen")
|
|
23
|
+
return flatpak if os.path.isdir(flatpak) else os.path.expanduser("~/.zen")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def default_profile() -> str:
|
|
27
|
+
"""The profile Zen starts with: the install's Default, else the profile flagged Default=1."""
|
|
28
|
+
base = data_dir()
|
|
29
|
+
ini = os.path.join(base, "profiles.ini")
|
|
30
|
+
if not os.path.exists(ini):
|
|
31
|
+
raise SystemExit(f"No profiles.ini in {base}; pass --profile.")
|
|
32
|
+
sections: dict[str, dict[str, str]] = {}
|
|
33
|
+
section = None
|
|
34
|
+
with open(ini, encoding="utf-8") as fh:
|
|
35
|
+
for line in fh:
|
|
36
|
+
line = line.strip()
|
|
37
|
+
if line.startswith("["):
|
|
38
|
+
section = line.strip("[]")
|
|
39
|
+
sections.setdefault(section, {})
|
|
40
|
+
elif "=" in line and section:
|
|
41
|
+
k, v = line.split("=", 1)
|
|
42
|
+
sections[section][k] = v
|
|
43
|
+
install_default = flagged = None
|
|
44
|
+
for name, kv in sections.items():
|
|
45
|
+
if name.startswith("Install") and "Default" in kv:
|
|
46
|
+
install_default = kv["Default"]
|
|
47
|
+
if name.startswith("Profile"):
|
|
48
|
+
if kv.get("Default") == "1":
|
|
49
|
+
flagged = kv.get("Path")
|
|
50
|
+
rel = install_default or flagged
|
|
51
|
+
path = os.path.join(base, rel) if rel else None
|
|
52
|
+
if not path or not os.path.isdir(path):
|
|
53
|
+
raise SystemExit("Could not find the Zen profile; pass --profile.")
|
|
54
|
+
return path
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def zen_running() -> bool:
|
|
58
|
+
try:
|
|
59
|
+
if sys.platform.startswith("win"):
|
|
60
|
+
out = subprocess.run(["tasklist", "/FI", "IMAGENAME eq zen.exe"], capture_output=True, text=True).stdout
|
|
61
|
+
return "zen.exe" in out
|
|
62
|
+
ps = subprocess.run(["ps", "-axo", "command="], capture_output=True, text=True, check=True).stdout
|
|
63
|
+
except (OSError, subprocess.CalledProcessError):
|
|
64
|
+
return False
|
|
65
|
+
for line in ps.splitlines():
|
|
66
|
+
first = line.split(" -", 1)[0]
|
|
67
|
+
if "/Contents/MacOS/zen" in first or first.endswith(("/zen", "/zen-bin")):
|
|
68
|
+
return True
|
|
69
|
+
return False
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def zen_version() -> str | None:
|
|
73
|
+
"""The installed app's version (macOS), or None."""
|
|
74
|
+
for app in ("/Applications/Zen.app", os.path.expanduser("~/Applications/Zen.app")):
|
|
75
|
+
plist = os.path.join(app, "Contents", "Info.plist")
|
|
76
|
+
if os.path.exists(plist):
|
|
77
|
+
with open(plist, "rb") as fh:
|
|
78
|
+
return plistlib.load(fh).get("CFBundleShortVersionString")
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def backup(profile: str) -> str:
|
|
83
|
+
folder = os.path.join(profile, BACKUPS)
|
|
84
|
+
os.makedirs(folder, exist_ok=True)
|
|
85
|
+
dest = os.path.join(folder, f"{SESSION}.{time.strftime('%Y%m%d-%H%M%S')}")
|
|
86
|
+
shutil.copy2(os.path.join(profile, SESSION), dest)
|
|
87
|
+
return dest
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def newest_backup(profile: str) -> str | None:
|
|
91
|
+
folder = os.path.join(profile, BACKUPS)
|
|
92
|
+
files = sorted(os.listdir(folder)) if os.path.isdir(folder) else []
|
|
93
|
+
return os.path.join(folder, files[-1]) if files else None
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: zenform
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zen browser as code: keep your pins, essentials and folders in readable files, then plan and apply them.
|
|
5
|
+
Project-URL: Homepage, https://github.com/cathal-killeen/zenform
|
|
6
|
+
Project-URL: Source, https://github.com/cathal-killeen/zenform
|
|
7
|
+
Project-URL: Issues, https://github.com/cathal-killeen/zenform/issues
|
|
8
|
+
Author: Cathal Killeen
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: config-as-code,dotfiles,pinned-tabs,zen-browser
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Operating System :: MacOS
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Utilities
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# zenform
|
|
21
|
+
|
|
22
|
+
**Zen browser as code.** Keep your sidebar (Essentials, pinned folders, pinned tabs, labels and icons) in small, readable files. See what applying them would change, then apply.
|
|
23
|
+
|
|
24
|
+
```console
|
|
25
|
+
$ zenform plan
|
|
26
|
+
+ 117 Exports [Now] https://tracker.example.com/browse/APP-117
|
|
27
|
+
~ 'Inbox - me@example.com - Mail' -> 'Mail' [essentials]
|
|
28
|
+
- unpin 'Old pin' (becomes an ordinary tab)
|
|
29
|
+
icons: 1 filled from the favicon database
|
|
30
|
+
|
|
31
|
+
This is a plan; nothing was written. Close Zen, then run `zenform apply`.
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
> **Status: alpha, and unofficial.** zenform is an independent tool and is not affiliated with Zen Browser. It edits an
|
|
35
|
+
> undocumented file that Zen can change in any release; see [Safety](#safety). Tested on macOS with Zen 1.24.3b.
|
|
36
|
+
|
|
37
|
+
## Why
|
|
38
|
+
|
|
39
|
+
- **Sync with git or a synced folder.** Your browser setup becomes a few text files you can version, review and share between machines. Syncing config files is safe; syncing the browser's own state files is not.
|
|
40
|
+
- **Readable.** One file per concern, TOML, one pin per line, so a diff shows exactly what changed.
|
|
41
|
+
- **Works with AI agents.** `dump` gives an agent the current state in the same format it edits, `plan --json` is a safe dry run it can read, and it never needs to touch your live profile. See [AGENTS.md](AGENTS.md).
|
|
42
|
+
|
|
43
|
+
## Install
|
|
44
|
+
|
|
45
|
+
```console
|
|
46
|
+
uv tool install zenform # or: pipx install zenform
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Python 3.11 or newer, no other dependencies. From source: `uv tool install git+https://github.com/cathal-killeen/zenform`.
|
|
50
|
+
|
|
51
|
+
## Use
|
|
52
|
+
|
|
53
|
+
```console
|
|
54
|
+
zenform dump --out ~/zen-config # write your current pins as a config directory (start here)
|
|
55
|
+
$EDITOR ~/zen-config/folders/10-*.toml
|
|
56
|
+
export ZENFORM_CONFIG=~/zen-config # or pass --config, or run from inside the directory
|
|
57
|
+
zenform plan # what would change; writes nothing
|
|
58
|
+
# quit Zen, then:
|
|
59
|
+
zenform apply # backs up, writes, reads back to check
|
|
60
|
+
zenform rollback # undo the last apply (Zen closed)
|
|
61
|
+
zenform doctor # profile, Zen version, session format, config
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## The config
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
zen-config/
|
|
68
|
+
zenform.toml workspace = "Work"; keep_folders = ["Pull Requests"]
|
|
69
|
+
essentials.toml the icon tiles
|
|
70
|
+
folders/
|
|
71
|
+
10-code.toml name = "Code"; pins = [ ... ] (folders appear in file-name order)
|
|
72
|
+
20-tickets.toml
|
|
73
|
+
loose.toml optional: pins outside any folder
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
```toml
|
|
77
|
+
# folders/10-code.toml
|
|
78
|
+
name = "Code"
|
|
79
|
+
|
|
80
|
+
pins = [
|
|
81
|
+
{label = "app MRs", url = "https://git.example.com/team/app/-/merge_requests"},
|
|
82
|
+
{label = "api MRs", url = "https://git.example.com/team/api/-/merge_requests"},
|
|
83
|
+
]
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
- **label**: what the sidebar shows; keep it to 14 characters or fewer (zenform warns).
|
|
87
|
+
- **url**: the pin's *home page*. A pin Zen already has with the same home URL keeps its history and icon, so reuse the URL `dump` printed for pins you keep.
|
|
88
|
+
- **keep_folders**: folders zenform leaves exactly as they are (for example folders Zen manages itself).
|
|
89
|
+
- Unknown keys are errors, so a typo does not silently do nothing.
|
|
90
|
+
|
|
91
|
+
See [`examples/config`](examples/config).
|
|
92
|
+
|
|
93
|
+
## What apply does and does not do
|
|
94
|
+
|
|
95
|
+
- Pins in the config are created, relabelled or moved. A pin the config no longer lists becomes an **ordinary tab; nothing is closed**. Open tabs are never edited.
|
|
96
|
+
- A pin with no icon is given one from your profile's favicon database (sites you have visited), so it is not blank until its page loads. If the site was never visited, it stays blank until opened once.
|
|
97
|
+
- Only the workspace named in `zenform.toml` is managed. Essentials span workspaces, so they are always managed.
|
|
98
|
+
|
|
99
|
+
## Safety
|
|
100
|
+
|
|
101
|
+
Zen keeps pins in `zen-sessions.jsonlz4` and rewrites it while running and on quit. So:
|
|
102
|
+
|
|
103
|
+
- `apply` **refuses to run while Zen is open**, backs the file up to `zenform-backups/` in the profile first, checks the result before writing and reads it back after, and restores the backup itself if that check fails.
|
|
104
|
+
- `plan` and `dump` only read. The favicon database is read from a copy.
|
|
105
|
+
- The format is undocumented ([what we know](docs/session-format.md)). `doctor` warns on a Zen version that has not been tested, and every command refuses a session file that does not have the expected shape.
|
|
106
|
+
- Do not put real session files in a public repo: they contain your tab history.
|
|
107
|
+
|
|
108
|
+
## Agents
|
|
109
|
+
|
|
110
|
+
Point an agent at the config directory and [AGENTS.md](AGENTS.md). The loop is: `zenform dump` for the current state, edit the files, `zenform plan --json` to check, and leave the `apply` to you.
|
|
111
|
+
|
|
112
|
+
## Development
|
|
113
|
+
|
|
114
|
+
```console
|
|
115
|
+
PYTHONPATH=src python3 -W error -m unittest discover -s tests
|
|
116
|
+
uvx ruff check .
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Standard library only, on purpose: it has to work on a bare machine, and a tool that edits your browser should be easy to audit.
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
zenform/__init__.py,sha256=y6V_g9Omjs0WFYRV7UjdR14WXRgqAMFH7vqXAK7fhXI,170
|
|
2
|
+
zenform/__main__.py,sha256=OoMHhqCVjnfUZfSZvzDxCZkIt9b5JKRgSErmNeisDQA,59
|
|
3
|
+
zenform/cli.py,sha256=FkhusnYoBizWvftFR5JLG6vRNkV36fuwsjugOyLM1HY,8168
|
|
4
|
+
zenform/config.py,sha256=F4HhGL1HzNELH50c8FfnJWE7otTfB4UkCufcwc0FyXg,6006
|
|
5
|
+
zenform/favicons.py,sha256=DWWM29wKW_sZ0KHQwCZUJmr8el99KMy5dMFPqclPj2k,3066
|
|
6
|
+
zenform/model.py,sha256=LLnej0OmWN1nFqNbQPrCtfwR0P2aGlvCx5_GyhLBPNQ,16090
|
|
7
|
+
zenform/mozlz4.py,sha256=G8BlkHJNjL62uGAtQX_CxzU9HNEmHml7uBA0wv_CO4Q,2497
|
|
8
|
+
zenform/profile.py,sha256=AbDJ6Ih0VMV0h0Xk3FI4HDSkXf3UWFKiBkgXoTcmsZo,3484
|
|
9
|
+
zenform-0.1.0.dist-info/METADATA,sha256=U9touMnG0u1AV5vfN9XwzCRdzdsEmu0BiDoKwORvWmM,5499
|
|
10
|
+
zenform-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
11
|
+
zenform-0.1.0.dist-info/entry_points.txt,sha256=mWtv2kyqDcy7qwpBUZsHq5Y8MbGYOxuEt_L_NUe91no,45
|
|
12
|
+
zenform-0.1.0.dist-info/licenses/LICENSE,sha256=XCZl1AJQ3aXkyM9-19wzA1-8Z0iQLclwuHniN9UZTtU,1071
|
|
13
|
+
zenform-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cathal Killeen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|