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.
tabwright/gui.py ADDED
@@ -0,0 +1,672 @@
1
+ """Desktop GUI: a tree over the session model with drag-and-drop, tool context menus
2
+ from the registry, browser selection with running state and stop/start/apply, and a
3
+ library pane. Launch with ``tabwright gui``. Requires the ``gui`` extra (PySide6)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from PySide6.QtCore import QObject, Qt, QThread, QTimer, Signal
12
+ from PySide6.QtGui import QAction, QColor
13
+ from PySide6.QtWidgets import (
14
+ QAbstractItemView,
15
+ QApplication,
16
+ QComboBox,
17
+ QFileDialog,
18
+ QHBoxLayout,
19
+ QInputDialog,
20
+ QLabel,
21
+ QLineEdit,
22
+ QListWidget,
23
+ QMainWindow,
24
+ QMenu,
25
+ QMessageBox,
26
+ QPlainTextEdit,
27
+ QPushButton,
28
+ QSplitter,
29
+ QTreeWidget,
30
+ QTreeWidgetItem,
31
+ QVBoxLayout,
32
+ QWidget,
33
+ )
34
+
35
+ from tabwright import adapters, library, live, model, tools
36
+ from tabwright.adapters import snss
37
+ from tabwright.model import Group, Node, Session, Tab, Window
38
+
39
+ NODE = Qt.ItemDataRole.UserRole
40
+ COLOR_HEX = {
41
+ "grey": "#5f6368",
42
+ "blue": "#1a73e8",
43
+ "red": "#d93025",
44
+ "yellow": "#f9ab00",
45
+ "green": "#188038",
46
+ "pink": "#d01884",
47
+ "purple": "#a142f4",
48
+ "cyan": "#007b83",
49
+ "orange": "#fa903e",
50
+ }
51
+
52
+
53
+ def container_of(session: Session, node: Node) -> list | None:
54
+ if isinstance(node, Window):
55
+ return session.windows
56
+ for c in tools.containers(session):
57
+ if node in c:
58
+ return c
59
+ return None
60
+
61
+
62
+ def move_node(session: Session, node: Node, target: Node | None, index: int) -> bool:
63
+ """Move ``node`` into ``target`` (None = session level for windows) at ``index``. False if illegal."""
64
+ if isinstance(node, Window):
65
+ dest = session.windows if target is None else None
66
+ elif isinstance(node, Group):
67
+ dest = target.items if isinstance(target, Window) else None
68
+ else:
69
+ dest = (
70
+ target.items if isinstance(target, Window) else target.tabs if isinstance(target, Group) else None
71
+ )
72
+ if dest is None:
73
+ return False
74
+ src = container_of(session, node)
75
+ if src is dest and src.index(node) < index:
76
+ index -= 1
77
+ src.remove(node)
78
+ dest.insert(max(0, min(index, len(dest))), node)
79
+ return True
80
+
81
+
82
+ class Tree(QTreeWidget):
83
+ moved = Signal()
84
+
85
+ def __init__(self, win: MainWindow):
86
+ super().__init__()
87
+ self.win = win
88
+ self.setHeaderLabels(["Item", "URL"])
89
+ self.headerItem().setToolTip(0, "Window, group or tab; groups are drawn in their colour.")
90
+ self.headerItem().setToolTip(1, "The tab's URL.")
91
+ self.setColumnWidth(0, 420)
92
+ self.setDragDropMode(QAbstractItemView.DragDropMode.InternalMove)
93
+ self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
94
+ self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
95
+ self.customContextMenuRequested.connect(self.win.context_menu)
96
+
97
+ def dropEvent(self, event):
98
+ target_item = self.itemAt(event.position().toPoint())
99
+ pos = self.dropIndicatorPosition()
100
+ D = QAbstractItemView.DropIndicatorPosition
101
+ if target_item is None:
102
+ target, index = None, len(self.win.session.windows)
103
+ elif pos == D.OnItem:
104
+ target = target_item.data(0, NODE)
105
+ index = len(target.items if isinstance(target, Window) else getattr(target, "tabs", []))
106
+ else:
107
+ parent_item = target_item.parent()
108
+ target = parent_item.data(0, NODE) if parent_item else None
109
+ siblings = parent_item if parent_item else self.invisibleRootItem()
110
+ index = siblings.indexOfChild(target_item) + (1 if pos == D.BelowItem else 0)
111
+ nodes = [it.data(0, NODE) for it in self.selectedItems()]
112
+ ok = 0
113
+ for node in nodes:
114
+ if target is not None and node is target:
115
+ continue
116
+ if move_node(self.win.session, node, target, index):
117
+ ok += 1
118
+ index += 1
119
+ event.ignore()
120
+ if ok:
121
+ self.win.rebuild()
122
+ else:
123
+ self.win.status(f"cannot drop {', '.join(model.KINDS[type(n)] for n in nodes)} there")
124
+
125
+
126
+ class Worker(QThread):
127
+ done = Signal(object)
128
+
129
+ def __init__(self, fn, parent: QObject):
130
+ super().__init__(parent)
131
+ self.fn = fn
132
+
133
+ def run(self):
134
+ try:
135
+ self.done.emit(self.fn())
136
+ except Exception as e: # noqa: BLE001
137
+ self.done.emit({"error": str(e)})
138
+
139
+
140
+ class MainWindow(QMainWindow):
141
+ def __init__(self):
142
+ super().__init__()
143
+ self.setWindowTitle("tabwright")
144
+ self.resize(1300, 850)
145
+ self.session = Session()
146
+ self.data_dir: Path | None = None
147
+
148
+ top = QHBoxLayout()
149
+ self.browser = QComboBox()
150
+ self.browser.addItems(sorted(adapters.BROWSERS))
151
+ self.browser.setToolTip(
152
+ "Which browser the Load, Stop, Start and Apply buttons act on.\n"
153
+ "Chromium family: brave, chrome, chromium, edge, vivaldi. Firefox family: firefox, tor."
154
+ )
155
+ self.profile = QLineEdit("Default")
156
+ self.profile.setFixedWidth(100)
157
+ self.profile.setToolTip(
158
+ "Profile to read and write.\nChromium: the profile directory name (Default, Profile 1…).\n"
159
+ "Firefox: a profile name from profiles.ini; Default picks the default-marked one."
160
+ )
161
+ self.running = QLabel("")
162
+ self.running.setToolTip(
163
+ "Whether the selected browser is running (polled every 2 s).\n"
164
+ "'+ bridge' means the companion extension is connected, so Load (bridge) and Apply (bridge) work."
165
+ )
166
+ top.addWidget(QLabel("Browser"))
167
+ top.addWidget(self.browser)
168
+ top.addWidget(QLabel("Profile"))
169
+ top.addWidget(self.profile)
170
+ for text, slot, tip in [
171
+ (
172
+ "Load live",
173
+ self.load_live,
174
+ (
175
+ "Read the newest session file of the selected profile.\nWorks whether the browser is "
176
+ "running or not; while it runs the file may lag a little behind the real tab strip."
177
+ ),
178
+ ),
179
+ (
180
+ "Load (bridge)",
181
+ self.load_bridge,
182
+ (
183
+ "Snapshot the running browser through the companion extension: exact live state,\n"
184
+ "including window geometry and tab ids. Needs '+ bridge' in the status label."
185
+ ),
186
+ ),
187
+ (
188
+ "Open file…",
189
+ self.open_file,
190
+ "Open a saved session (SNSS, Firefox jsonlz4) or a model JSON file.",
191
+ ),
192
+ (
193
+ "Save SNSS…",
194
+ self.save_file,
195
+ (
196
+ "Write the tree to a session file in the selected browser's native format,\n"
197
+ "without touching any profile."
198
+ ),
199
+ ),
200
+ (
201
+ "Stop",
202
+ self.stop_browser,
203
+ (
204
+ "Ask the browser to quit (SIGTERM). It rewrites its session files on the way out.\n"
205
+ "Required before Apply to profile."
206
+ ),
207
+ ),
208
+ (
209
+ "Stop (force)",
210
+ lambda: self.stop_browser(True),
211
+ (
212
+ "Kill the browser (SIGKILL). Use when it is hung: session files stay exactly as on disk,\n"
213
+ "so nothing half-written replaces them."
214
+ ),
215
+ ),
216
+ ("Start", self.start_browser, "Launch the selected browser on the selected profile."),
217
+ (
218
+ "Apply to profile",
219
+ self.apply,
220
+ (
221
+ "Write the tree into the stopped browser's profile as a new session and mark it for restore.\n"
222
+ "On next start the browser offers (or performs) the restore. Refused while the browser runs."
223
+ ),
224
+ ),
225
+ (
226
+ "Apply (bridge)",
227
+ self.apply_bridge,
228
+ (
229
+ "Make the running browser match the tree, live: tabs are moved, grouped and created;\n"
230
+ "live tabs missing from the tree are closed. Asks for confirmation first."
231
+ ),
232
+ ),
233
+ ]:
234
+ b = QPushButton(text)
235
+ b.clicked.connect(slot)
236
+ b.setToolTip(tip)
237
+ top.addWidget(b)
238
+ if text == "Apply to profile":
239
+ self.apply_btn = b
240
+ top.addWidget(self.running)
241
+ top.addStretch()
242
+
243
+ self.tree = Tree(self)
244
+ self.tree.setToolTip(
245
+ "Windows > groups > tabs, in tab-strip order.\n"
246
+ "Drag to reorder: tabs into windows or groups, groups between windows.\n"
247
+ "Right-click for tools, colour, grouping and drop. Changes stay in the tree until you Apply."
248
+ )
249
+ self.report = QPlainTextEdit()
250
+ self.report.setReadOnly(True)
251
+ self.report.setMaximumBlockCount(5000)
252
+ self.report.setToolTip("Reports from tools (duplicates, stats, URL checks…) and other messages.")
253
+ left = QSplitter(Qt.Orientation.Vertical)
254
+ left.addWidget(self.tree)
255
+ left.addWidget(self.report)
256
+ left.setSizes([600, 200])
257
+
258
+ self.lib = QListWidget()
259
+ self.lib.setToolTip(
260
+ "Named sets saved as plain JSON under $XDG_DATA_HOME/tabwright/library.\n"
261
+ "A set is a whole session, a window, a group or a single tab; compose new sessions from them."
262
+ )
263
+ lib_box = QVBoxLayout()
264
+ lib_box.addWidget(QLabel("Library"))
265
+ lib_box.addWidget(self.lib)
266
+ for text, slot, tip in [
267
+ (
268
+ "Save selected as…",
269
+ self.lib_save,
270
+ "Save the selected tree node (or the whole session when nothing is selected) as a named set.",
271
+ ),
272
+ (
273
+ "Load into selected",
274
+ self.lib_load,
275
+ (
276
+ "Insert the highlighted library set into the selected window or group\n"
277
+ "(a saved window or session becomes new windows)."
278
+ ),
279
+ ),
280
+ ("Rename", self.lib_rename, "Rename the highlighted library set."),
281
+ ("Delete", self.lib_delete, "Delete the highlighted library set from disk."),
282
+ ]:
283
+ b = QPushButton(text)
284
+ b.clicked.connect(slot)
285
+ b.setToolTip(tip)
286
+ lib_box.addWidget(b)
287
+ lib_w = QWidget()
288
+ lib_w.setLayout(lib_box)
289
+ split = QSplitter()
290
+ split.addWidget(left)
291
+ split.addWidget(lib_w)
292
+ split.setSizes([1000, 300])
293
+
294
+ root = QVBoxLayout()
295
+ root.addLayout(top)
296
+ root.addWidget(split, 1)
297
+ w = QWidget()
298
+ w.setLayout(root)
299
+ self.setCentralWidget(w)
300
+ self.statusBar()
301
+
302
+ self.timer = QTimer(self)
303
+ self.timer.timeout.connect(self.poll)
304
+ self.timer.start(2000)
305
+ self.poll()
306
+ self.refresh_lib()
307
+
308
+ # ------------------------------------------------------------ state
309
+ def status(self, msg: str):
310
+ self.statusBar().showMessage(msg, 8000)
311
+
312
+ def log(self, obj):
313
+ self.report.appendPlainText(
314
+ obj if isinstance(obj, str) else json.dumps(obj, indent=2, ensure_ascii=False)
315
+ )
316
+
317
+ def poll(self):
318
+ pids = adapters.get(self.browser.currentText()).pids(self.browser.currentText(), self.data_dir)
319
+ bridge = " + bridge" if live.socket_path(self.browser.currentText(), self.data_dir).exists() else ""
320
+ self.running.setText(f"● running ({len(pids)}){bridge}" if pids else "○ stopped")
321
+ self.running.setStyleSheet(f"color: {'#188038' if pids else '#888'}; font-weight: bold")
322
+ self.apply_btn.setEnabled(not pids and bool(self.session.windows))
323
+
324
+ def set_session(self, s: Session, origin: str):
325
+ self.session = s
326
+ self.rebuild()
327
+ self.status(f"loaded {origin}: {len(s.windows)} windows, {len(s.tabs())} tabs")
328
+
329
+ def rebuild(self):
330
+ expanded = {id(it.data(0, NODE)) for it in self.iter_items() if it.isExpanded()}
331
+ self.tree.clear()
332
+ for wi, w in enumerate(self.session.windows):
333
+ wi_item = self.add_item(
334
+ self.tree.invisibleRootItem(), w, f"Window {wi} ({len(w.tabs())} tabs)", ""
335
+ )
336
+ geo = w.geometry
337
+ wi_item.setToolTip(
338
+ 0,
339
+ f"w{wi}: {len(w.tabs())} tabs in {len(w.groups())} groups, "
340
+ f"{sum(isinstance(i, Tab) for i in w.items)} loose\n"
341
+ + (
342
+ f"geometry {geo['width']}×{geo['height']} at ({geo['x']}, {geo['y']}), {geo['state']}"
343
+ if geo
344
+ else "geometry: browser default"
345
+ ),
346
+ )
347
+ wi_item.setExpanded(id(w) in expanded or not expanded)
348
+ for ii, it in enumerate(w.items):
349
+ if isinstance(it, Group):
350
+ g_item = self.add_item(wi_item, it, f"[{it.title}] ({len(it.tabs)})", "")
351
+ g_item.setForeground(0, QColor(COLOR_HEX.get(it.color, "#5f6368")))
352
+ g_item.setToolTip(
353
+ 0,
354
+ f"w{wi}/g{ii}: group '{it.title or '(untitled)'}', {it.color}"
355
+ f"{', collapsed' if it.collapsed else ''}, {len(it.tabs)} tabs",
356
+ )
357
+ g_item.setExpanded(id(it) in expanded)
358
+ for t in it.tabs:
359
+ self.add_tab(g_item, t)
360
+ else:
361
+ self.add_tab(wi_item, it)
362
+ self.poll()
363
+
364
+ def add_item(self, parent, node, text, url):
365
+ item = QTreeWidgetItem(parent, [text, url])
366
+ item.setData(0, NODE, node)
367
+ item.setFlags(item.flags() | Qt.ItemFlag.ItemIsDragEnabled | Qt.ItemFlag.ItemIsDropEnabled)
368
+ return item
369
+
370
+ def add_tab(self, parent, t: Tab):
371
+ item = self.add_item(parent, t, ("📌 " if t.pinned else "") + (t.title or t.url), t.url)
372
+ item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsDropEnabled)
373
+ tip = f"{t.title}\n{t.url}" + ("\npinned" if t.pinned else "") + ("\nactive tab" if t.active else "")
374
+ item.setToolTip(0, tip)
375
+ item.setToolTip(1, tip)
376
+ return item
377
+
378
+ def iter_items(self):
379
+ stack = [self.tree.invisibleRootItem()]
380
+ while stack:
381
+ it = stack.pop()
382
+ for i in range(it.childCount()):
383
+ c = it.child(i)
384
+ yield c
385
+ stack.append(c)
386
+
387
+ def selected_nodes(self) -> list[Node]:
388
+ return [it.data(0, NODE) for it in self.tree.selectedItems()]
389
+
390
+ # ------------------------------------------------------------ source / sink
391
+ def load_live(self):
392
+ b = self.browser.currentText()
393
+ try:
394
+ self.set_session(adapters.get(b).read_profile(b, self.profile.text(), self.data_dir), "profile")
395
+ except SystemExit as e:
396
+ self.status(str(e))
397
+
398
+ def load_bridge(self):
399
+ """Snapshot the running browser through the companion extension."""
400
+ try:
401
+ self.set_session(live.snapshot(self.browser.currentText(), self.data_dir), "bridge")
402
+ except SystemExit as e:
403
+ self.status(str(e))
404
+
405
+ def apply_bridge(self):
406
+ """Reconcile the running browser to the tree: tabs absent from it are closed."""
407
+ b = self.browser.currentText()
408
+ n = len(self.session.tabs())
409
+ q = QMessageBox.question(self, "Apply live", f"Make the running {b} match this tree ({n} tabs)?")
410
+ if q != QMessageBox.StandardButton.Yes:
411
+ return
412
+ try:
413
+ self.set_session(live.apply(self.session, b, self.data_dir), "bridge")
414
+ self.status("applied live")
415
+ except SystemExit as e:
416
+ self.status(str(e))
417
+
418
+ def open_file(self):
419
+ path, _ = QFileDialog.getOpenFileName(self, "Open session or saved set")
420
+ if not path:
421
+ return
422
+ if path.endswith(".json"):
423
+ node = model.loads(Path(path).read_text())
424
+ s = (
425
+ node
426
+ if isinstance(node, Session)
427
+ else Session(windows=[node] if isinstance(node, Window) else [Window(items=[node])])
428
+ )
429
+ else:
430
+ s = adapters.get(self.browser.currentText()).read(Path(path), browser=self.browser.currentText())
431
+ self.set_session(s, Path(path).name)
432
+
433
+ def save_file(self):
434
+ path, _ = QFileDialog.getSaveFileName(self, "Save SNSS session file", "Session_out")
435
+ if path:
436
+ snss.write_commands(path, snss.build(self.session))
437
+ self.status(f"wrote {path}")
438
+
439
+ def stop_browser(self, force=False):
440
+ b = self.browser.currentText()
441
+ if (
442
+ not force
443
+ and QMessageBox.question(
444
+ self,
445
+ "Stop",
446
+ f"Stop {b}? A graceful stop lets it rewrite its session "
447
+ "files first; use Stop (force) when it is hung.",
448
+ )
449
+ != QMessageBox.StandardButton.Yes
450
+ ):
451
+ return
452
+ ps = adapters.get(b).stop(b, self.data_dir, force=force)
453
+ self.status(f"stopped {ps}" if ps else f"{b} not running")
454
+ self.poll()
455
+
456
+ def start_browser(self):
457
+ pid = adapters.get(self.browser.currentText()).start(self.browser.currentText(), self.data_dir)
458
+ self.status(f"started pid {pid}")
459
+
460
+ def apply(self):
461
+ b = self.browser.currentText()
462
+ if adapters.get(b).pids(b, self.data_dir):
463
+ self.status(f"{b} is running; stop it first")
464
+ return
465
+ n = len(self.session.windows)
466
+ if (
467
+ QMessageBox.question(
468
+ self,
469
+ "Apply",
470
+ f"Write {n} window(s) into the {b} profile '{self.profile.text()}' and "
471
+ "mark it for restore on next start?",
472
+ )
473
+ != QMessageBox.StandardButton.Yes
474
+ ):
475
+ return
476
+ out = adapters.get(b).apply(self.session, b, self.profile.text(), self.data_dir)
477
+ self.status(f"wrote {out.name}; {b} will offer to restore it")
478
+
479
+ # ------------------------------------------------------------ tools
480
+ def context_menu(self, pos):
481
+ nodes = self.selected_nodes()
482
+ if not nodes:
483
+ return
484
+ menu = QMenu(self)
485
+ menu.setToolTipsVisible(True)
486
+ kinds = {model.KINDS[type(n)] for n in nodes}
487
+ if len(kinds) == 1:
488
+ kind = kinds.pop()
489
+ for t in tools.REGISTRY.values():
490
+ if kind in t.scopes:
491
+ a = QAction(("✎ " if t.transform else "⌕ ") + t.name, self)
492
+ a.setToolTip(
493
+ f"{t.help}\n{'Changes the tree' if t.transform else 'Report only'}; "
494
+ f"scope: {', '.join(t.scopes)}."
495
+ )
496
+ a.triggered.connect(lambda _=False, t=t, nodes=nodes: self.run_tool(t, nodes))
497
+ menu.addAction(a)
498
+ menu.addSeparator()
499
+ if kind == "group":
500
+ menu.addAction("Rename group…", lambda: self.rename_group(nodes[0])).setToolTip(
501
+ "Change the group's title."
502
+ )
503
+ menu.addAction("Ungroup", lambda: self.ungroup(nodes)).setToolTip(
504
+ "Dissolve the group; its tabs stay in place as loose tabs."
505
+ )
506
+ if kind == "tab" and len(nodes) > 1:
507
+ menu.addAction("Group selected tabs…", lambda: self.group_tabs(nodes)).setToolTip(
508
+ "Put the selected tabs into a new group at the position of the first one."
509
+ )
510
+ menu.addAction("New window", self.new_window).setToolTip("Add an empty window at the end.")
511
+ if kinds <= {"tab", "group"}:
512
+ menu.addAction("Colour…", lambda: self.color_nodes(nodes)).setToolTip(
513
+ "Set a group's colour. A loose tab becomes a one-tab group so it can carry a colour."
514
+ )
515
+ menu.addAction(f"Drop {len(nodes)} item(s)", lambda: self.drop(nodes)).setToolTip(
516
+ "Remove from the tree. Nothing closes in the browser until you Apply."
517
+ )
518
+ menu.exec(self.tree.viewport().mapToGlobal(pos))
519
+
520
+ def run_tool(self, t: tools.Tool, nodes: list[Node]):
521
+ opts = {}
522
+ for flag, kw in t.options.items():
523
+ name = flag.lstrip("-").replace("-", "_")
524
+ if "choices" in kw:
525
+ v, ok = QInputDialog.getItem(self, t.name, name, [str(c) for c in kw["choices"]], 0, False)
526
+ else:
527
+ v, ok = QInputDialog.getText(self, t.name, name, text=str(kw.get("default", "")))
528
+ if not ok:
529
+ return
530
+ opts[name] = kw.get("type", str)(v) if v != "" else kw.get("default")
531
+ if t.transform or t.name != "check-urls":
532
+ for n in nodes:
533
+ r = t.fn(n, **opts)
534
+ self.log(r["text"] if "text" in r else {"tool": t.name, "scope": model.KINDS[type(n)], **r})
535
+ if t.transform:
536
+ self.rebuild()
537
+ return
538
+ self.status("checking URLs…")
539
+ worker = Worker(lambda: [t.fn(n, **opts) for n in nodes], self)
540
+ worker.done.connect(lambda r: (self.log(r), self.status("check-urls done")))
541
+ worker.start()
542
+
543
+ def color_nodes(self, nodes: list[Node]):
544
+ c, ok = QInputDialog.getItem(self, "Colour", "Group colour", model.GROUP_COLORS, 0, False)
545
+ if not ok:
546
+ return
547
+ for n in nodes:
548
+ tools.color(self.session, self.path_of(n), c)
549
+ self.rebuild()
550
+
551
+ def path_of(self, node: Node) -> str:
552
+ for wi, w in enumerate(self.session.windows):
553
+ if node is w:
554
+ return f"w{wi}"
555
+ for ii, it in enumerate(w.items):
556
+ if node is it:
557
+ return f"w{wi}/g{ii}" if isinstance(it, Group) else f"w{wi}/t{w.tabs().index(it)}"
558
+ if isinstance(it, Group) and node in it.tabs:
559
+ return f"w{wi}/g{ii}/t{it.tabs.index(node)}"
560
+ raise KeyError("node not in session")
561
+
562
+ def drop(self, nodes: list[Node]):
563
+ for n in nodes:
564
+ c = container_of(self.session, n)
565
+ if c is not None and n in c:
566
+ c.remove(n)
567
+ self.rebuild()
568
+
569
+ def new_window(self):
570
+ self.session.windows.append(Window())
571
+ self.rebuild()
572
+
573
+ def rename_group(self, g: Group):
574
+ title, ok = QInputDialog.getText(self, "Rename group", "Title", text=g.title)
575
+ if ok:
576
+ g.title = title
577
+ self.rebuild()
578
+
579
+ def ungroup(self, groups: list[Node]):
580
+ for g in groups:
581
+ for w in self.session.windows:
582
+ if g in w.items:
583
+ i = w.items.index(g)
584
+ w.items[i : i + 1] = g.tabs
585
+ self.rebuild()
586
+
587
+ def group_tabs(self, tabs: list[Node]):
588
+ title, ok = QInputDialog.getText(self, "New group", "Title")
589
+ if not ok:
590
+ return
591
+ first = container_of(self.session, tabs[0])
592
+ for t in tabs:
593
+ container_of(self.session, t).remove(t)
594
+ host = next((w for w in self.session.windows if first is w.items), None)
595
+ if host is None: # tabs came from a group: put the new group beside it
596
+ host = next(w for w in self.session.windows for g in w.groups() if g.tabs is first)
597
+ host.items.append(Group(title=title, tabs=tabs))
598
+ self.rebuild()
599
+
600
+ # ------------------------------------------------------------ library
601
+ def refresh_lib(self):
602
+ self.lib.clear()
603
+ for name, kind in library.names():
604
+ self.lib.addItem(f"{name} ({kind})")
605
+
606
+ def lib_selected(self) -> str | None:
607
+ it = self.lib.currentItem()
608
+ return it.text().rsplit(" (", 1)[0] if it else None
609
+
610
+ def lib_save(self):
611
+ nodes = self.selected_nodes()
612
+ node = nodes[0] if len(nodes) == 1 else self.session
613
+ name, ok = QInputDialog.getText(self, "Save as", f"Name for this {model.KINDS[type(node)]}")
614
+ if ok and name:
615
+ library.save(name, node)
616
+ self.refresh_lib()
617
+ self.status(f"saved {name}")
618
+
619
+ def lib_load(self):
620
+ name = self.lib_selected()
621
+ if not name:
622
+ return
623
+ node = library.load(name)
624
+ sel = self.selected_nodes()
625
+ target = sel[0] if sel else None
626
+ if isinstance(node, Session):
627
+ self.session.windows.extend(node.windows)
628
+ elif isinstance(node, Window) or target is None:
629
+ self.session.windows.append(node if isinstance(node, Window) else Window(items=[node]))
630
+ elif not move_node_into(node, target):
631
+ self.status(f"cannot load a {model.KINDS[type(node)]} into a {model.KINDS[type(target)]}")
632
+ return
633
+ self.rebuild()
634
+
635
+ def lib_rename(self):
636
+ old = self.lib_selected()
637
+ if old:
638
+ new, ok = QInputDialog.getText(self, "Rename", "New name", text=old)
639
+ if ok and new:
640
+ library.rename(old, new)
641
+ self.refresh_lib()
642
+
643
+ def lib_delete(self):
644
+ name = self.lib_selected()
645
+ if (
646
+ name
647
+ and QMessageBox.question(self, "Delete", f"Delete saved set {name!r}?")
648
+ == QMessageBox.StandardButton.Yes
649
+ ):
650
+ library.delete(name)
651
+ self.refresh_lib()
652
+
653
+
654
+ def move_node_into(node: Node, target: Node) -> bool:
655
+ if isinstance(target, Window) and isinstance(node, (Group, Tab)):
656
+ target.items.append(node)
657
+ elif isinstance(target, Group) and isinstance(node, Tab):
658
+ target.tabs.append(node)
659
+ else:
660
+ return False
661
+ return True
662
+
663
+
664
+ def main(argv=None) -> int:
665
+ app = QApplication(argv or sys.argv)
666
+ win = MainWindow()
667
+ win.show()
668
+ return app.exec()
669
+
670
+
671
+ if __name__ == "__main__":
672
+ sys.exit(main())