tabwright 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.
@@ -0,0 +1,261 @@
1
+ """Chromium SNSS session-file format: read, parse to the model, build from the model, write.
2
+
3
+ Layout (components/sessions/core/session_service_commands.cc): the file is
4
+ ``SNSS`` + int32 version, then commands as uint16 size, uint8 id, payload.
5
+ Raw-struct commands start with the SessionID; pickle commands start with a
6
+ 4-byte length header, then the SessionID. SessionIDs are shared between tabs
7
+ and windows.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import collections
13
+ import os
14
+ import struct
15
+
16
+ from tabwright.model import GROUP_COLORS, Group, Session, Tab, Window
17
+
18
+ SET_TAB_WINDOW, SET_TAB_INDEX, UPDATE_NAV, SET_SEL_NAV = 0, 2, 6, 7
19
+ SET_SEL_TAB, SET_WINDOW_TYPE, SET_PINNED, SET_BOUNDS = 8, 9, 12, 14
20
+ SHOW_STATES = {1: "normal", 2: "minimized", 3: "maximized", 5: "fullscreen"} # ui::mojom::WindowShowState
21
+ TAB_CLOSED, WINDOW_CLOSED, SET_ACTIVE_WINDOW = 16, 17, 20
22
+ SET_TAB_GROUP, GROUP_META, MARKER = 25, 27, 255
23
+ PICKLE_CMDS = {6, 13, 15, 19, 23, 27, 28, 29, 30, 31, 33, 34}
24
+ VERSION = 3
25
+
26
+ Command = tuple[int, bytes]
27
+
28
+
29
+ def read_commands(path: str) -> tuple[int, list[Command]]:
30
+ with open(path, "rb") as f:
31
+ data = f.read()
32
+ if data[:4] != b"SNSS":
33
+ raise ValueError(f"{path}: not an SNSS file")
34
+ version = struct.unpack("<i", data[4:8])[0]
35
+ off, cmds = 8, []
36
+ while off + 2 <= len(data):
37
+ (size,) = struct.unpack("<H", data[off : off + 2])
38
+ off += 2
39
+ if size == 0 or off + size > len(data):
40
+ break
41
+ cmds.append((data[off], data[off + 1 : off + size]))
42
+ off += size
43
+ return version, cmds
44
+
45
+
46
+ def write_commands(path: str, cmds: list[Command], version: int = VERSION) -> None:
47
+ with open(path, "wb") as f:
48
+ f.write(b"SNSS" + struct.pack("<i", version))
49
+ f.writelines(struct.pack("<H", 1 + len(p)) + bytes([cid]) + p for cid, p in cmds)
50
+
51
+
52
+ class Pickle:
53
+ """Reader for base::Pickle payloads (4-byte length header, fields 4-byte aligned)."""
54
+
55
+ def __init__(self, buf: bytes, off: int = 4):
56
+ self.buf, self.off = buf, off
57
+
58
+ def i32(self) -> int:
59
+ (v,) = struct.unpack_from("<i", self.buf, self.off)
60
+ self.off += 4
61
+ return v
62
+
63
+ def _bytes(self, n: int) -> bytes:
64
+ s = self.buf[self.off : self.off + n]
65
+ self.off = (self.off + n + 3) & ~3
66
+ return s
67
+
68
+ def string(self) -> str:
69
+ return self._bytes(self.i32()).decode("utf-8", "replace")
70
+
71
+ def string16(self) -> str:
72
+ return self._bytes(2 * self.i32()).decode("utf-16-le", "replace")
73
+
74
+
75
+ class PickleWriter:
76
+ def __init__(self):
77
+ self.parts: list[bytes] = []
78
+
79
+ def i32(self, v: int) -> PickleWriter:
80
+ self.parts.append(struct.pack("<i", v))
81
+ return self
82
+
83
+ def raw(self, b: bytes) -> PickleWriter:
84
+ self.parts.append(b + b"\0" * (-len(b) % 4))
85
+ return self
86
+
87
+ def string(self, s: str) -> PickleWriter:
88
+ b = s.encode("utf-8")
89
+ return self.i32(len(b)).raw(b)
90
+
91
+ def string16(self, s: str) -> PickleWriter:
92
+ return self.i32(len(s)).raw(s.encode("utf-16-le"))
93
+
94
+ def bytes(self) -> bytes:
95
+ body = b"".join(self.parts)
96
+ return struct.pack("<I", len(body)) + body
97
+
98
+
99
+ def first_id(cid: int, p: bytes) -> int | None:
100
+ off = 4 if cid in PICKLE_CMDS else 0
101
+ return struct.unpack_from("<i", p, off)[0] if len(p) >= off + 4 else None
102
+
103
+
104
+ def _group_meta(p: bytes) -> tuple[str, dict]:
105
+ token = p[4:20].hex()
106
+ pk = Pickle(p, off=20)
107
+ title = pk.string16()
108
+ color = pk.i32()
109
+ collapsed = pk.i32() != 0 if pk.off + 4 <= len(p) else False
110
+ return token, {
111
+ "title": title,
112
+ "color": GROUP_COLORS[color] if 0 <= color < len(GROUP_COLORS) else "grey",
113
+ "collapsed": collapsed,
114
+ }
115
+
116
+
117
+ def parse(cmds: list[Command], browser: str = "") -> Session:
118
+ """Build a Session from a command stream, honouring tab/window closes."""
119
+ tabwin, idx, sel, grp, groups, pinned, seltab, bounds = {}, {}, {}, {}, {}, {}, {}, {}
120
+ navs: dict[int, dict[int, tuple[str, str]]] = collections.defaultdict(dict)
121
+ closed: set[int] = set()
122
+ window_order: list[int] = []
123
+ for cid, p in cmds:
124
+ try:
125
+ if cid == SET_TAB_WINDOW:
126
+ w, t = struct.unpack_from("<ii", p, 0)
127
+ tabwin[t] = w
128
+ if w not in window_order:
129
+ window_order.append(w)
130
+ elif cid == SET_TAB_INDEX:
131
+ t, i = struct.unpack_from("<ii", p, 0)
132
+ idx[t] = i
133
+ elif cid == UPDATE_NAV:
134
+ pk = Pickle(p)
135
+ t, i = pk.i32(), pk.i32()
136
+ navs[t][i] = (pk.string(), pk.string16())
137
+ elif cid == SET_SEL_NAV:
138
+ t, i = struct.unpack_from("<ii", p, 0)
139
+ sel[t] = i
140
+ elif cid == SET_SEL_TAB:
141
+ w, i = struct.unpack_from("<ii", p, 0)
142
+ seltab[w] = i
143
+ elif cid == SET_PINNED:
144
+ t, pn = struct.unpack_from("<i?", p, 0)
145
+ pinned[t] = pn
146
+ elif cid == SET_BOUNDS:
147
+ w, x, y, wd, ht, st = struct.unpack_from("<iiiiii", p, 0)
148
+ bounds[w] = {
149
+ "x": x,
150
+ "y": y,
151
+ "width": wd,
152
+ "height": ht,
153
+ "state": SHOW_STATES.get(st, "normal"),
154
+ }
155
+ elif cid in (TAB_CLOSED, WINDOW_CLOSED):
156
+ closed.add(struct.unpack_from("<i", p, 0)[0])
157
+ elif cid == SET_TAB_GROUP:
158
+ t = struct.unpack_from("<i", p, 0)[0]
159
+ has = len(p) <= 24 or p[24] != 0
160
+ grp[t] = p[8:24].hex() if has else None
161
+ elif cid == GROUP_META:
162
+ tok, meta = _group_meta(p)
163
+ groups[tok] = meta
164
+ except (struct.error, IndexError):
165
+ continue
166
+ per_window: dict[int, list[tuple[int, int]]] = collections.defaultdict(list)
167
+ for t, w in tabwin.items():
168
+ if t in closed or w in closed or not navs.get(t):
169
+ continue
170
+ per_window[w].append((idx.get(t, -1), t))
171
+ session = Session(browser=browser)
172
+ for w in window_order:
173
+ if w not in per_window:
174
+ continue
175
+ win = Window(geometry=bounds.get(w), extra={"session_id": w})
176
+ active_index = seltab.get(w)
177
+ for pos, (_, t) in enumerate(sorted(per_window[w])):
178
+ n = navs[t]
179
+ s = sel.get(t) if sel.get(t) in n else max(n)
180
+ url, title = n[s]
181
+ tab = Tab(
182
+ url=url,
183
+ title=title,
184
+ pinned=pinned.get(t, False),
185
+ active=(pos == active_index),
186
+ extra={"session_id": t},
187
+ )
188
+ tok = grp.get(t)
189
+ if tok is not None and tok in groups:
190
+ last = win.items[-1] if win.items else None
191
+ if not (isinstance(last, Group) and last.extra.get("token") == tok):
192
+ m = groups[tok]
193
+ last = Group(
194
+ title=m["title"], color=m["color"], collapsed=m["collapsed"], extra={"token": tok}
195
+ )
196
+ win.items.append(last)
197
+ last.tabs.append(tab)
198
+ else:
199
+ win.items.append(tab)
200
+ session.windows.append(win)
201
+ return session
202
+
203
+
204
+ def build(session: Session) -> list[Command]:
205
+ """Emit a fresh, minimal command stream that restores ``session``.
206
+
207
+ SessionIDs are allocated from 1; Chromium remaps them on restore. Navigation
208
+ entries carry an empty page state, so each tab reloads from its URL.
209
+ """
210
+ cmds: list[Command] = []
211
+ next_id = 1
212
+
213
+ def alloc() -> int:
214
+ nonlocal next_id
215
+ next_id += 1
216
+ return next_id - 1
217
+
218
+ group_tokens: dict[int, bytes] = {}
219
+ for wi, win in enumerate(session.windows):
220
+ w = alloc()
221
+ cmds.append((SET_WINDOW_TYPE, struct.pack("<ii", w, 0)))
222
+ g = win.geometry or {}
223
+ st = {v: k for k, v in SHOW_STATES.items()}.get(g.get("state", "normal"), 1)
224
+ bounds = (g.get("x", 0), g.get("y", 0), g.get("width", 1600), g.get("height", 1000), st)
225
+ cmds.append((SET_BOUNDS, struct.pack("<iiiiii", w, *bounds)))
226
+ tabs = win.tabs()
227
+ active = next((i for i, t in enumerate(tabs) if t.active), 0)
228
+ cmds.append((SET_SEL_TAB, struct.pack("<ii", w, active)))
229
+ pos = 0
230
+ for item in win.items:
231
+ group = item if isinstance(item, Group) else None
232
+ if group is not None:
233
+ token = os.urandom(16)
234
+ group_tokens[id(group)] = token
235
+ color = GROUP_COLORS.index(group.color) if group.color in GROUP_COLORS else 0
236
+ meta = PickleWriter().raw(token).string16(group.title).i32(color).i32(int(group.collapsed))
237
+ cmds.append((GROUP_META, meta.bytes()))
238
+ for tab in group.tabs if group is not None else [item]:
239
+ t = alloc()
240
+ cmds.append((SET_TAB_WINDOW, struct.pack("<ii", w, t)))
241
+ cmds.append((SET_TAB_INDEX, struct.pack("<ii", t, pos)))
242
+ if tab.pinned:
243
+ cmds.append((SET_PINNED, struct.pack("<i?xxx", t, True)))
244
+ if group is not None:
245
+ cmds.append(
246
+ (
247
+ SET_TAB_GROUP,
248
+ struct.pack("<ii", t, 0) + group_tokens[id(group)] + b"\x01" + b"\0" * 7,
249
+ )
250
+ )
251
+ # index, virtual_url, title, page_state, transition (typed), type_mask
252
+ nav = (
253
+ PickleWriter().i32(t).i32(0).string(tab.url).string16(tab.title).string("").i32(1).i32(0)
254
+ )
255
+ cmds.append((UPDATE_NAV, nav.bytes()))
256
+ cmds.append((SET_SEL_NAV, struct.pack("<ii", t, 0)))
257
+ pos += 1
258
+ if wi == 0:
259
+ cmds.append((SET_ACTIVE_WINDOW, struct.pack("<i", w)))
260
+ cmds.append((MARKER, b""))
261
+ return cmds