"""One process with independent account workspaces and workers.""" import json from pathlib import Path import re import uuid from PySide6 import QtCore as C, QtWidgets as W from . import gui from .api import Session from .sessions import identity class AccountsWindow(W.QMainWindow): def __init__(self, root=None): super().__init__() gui.use_native_scrollbars() self.root = Path(root or gui.STATE).resolve() self.root.mkdir(parents=True, exist_ok=True) self.index_path = self.root / "accounts.json" self.windows, self.locks, self.profiles = {}, {}, [] self.setWindowTitle("牧羊人之心牧场辅助 — 多账号") font = self.font() font.setPointSizeF(8.5) self.setFont(font) self.resize(1100, 740) central = W.QWidget() layout = W.QVBoxLayout(central) self.setCentralWidget(central) toolbar = W.QHBoxLayout() for text, handler in (("新增账号页签", self.add_profile), ("打开已保存账号", self.choose_profile), ("恢复各页签的保存会话", self.resume_all), ("全部开始监控", self.monitor_all), ("全部停止", self.stop_all)): button = W.QPushButton(text) button.clicked.connect(handler) toolbar.addWidget(button) toolbar.addStretch() layout.addLayout(toolbar) note = W.QLabel("每个页签独立登录、保存 Token 和运行。切换页签不会停止其他账号;自动执行需在各账号里分别开启。") note.setWordWrap(True) layout.addWidget(note) self.tabs = W.QTabWidget() self.tabs.currentChanged.connect(self.activate_profile) self.tabs.setTabsClosable(True) self.tabs.tabCloseRequested.connect(self.close_profile) layout.addWidget(self.tabs, 1) try: self.profiles = json.loads(self.index_path.read_text(encoding="utf-8"))["profiles"] except (OSError, ValueError, KeyError, TypeError): self.profiles = [{"id": "default", "label": "账号 1"}] self.profiles = [p for p in self.profiles if isinstance(p, dict) and re.fullmatch(r"default|[a-f0-9]{32}", str(p.get("id", "")))] for profile in list(self.profiles): self.open_profile(profile) if not self.profiles: self.add_profile() gui.compact_layouts(central) def open_profile(self, profile): identifier = profile["id"] if identifier in self.windows: self.tabs.setCurrentWidget(self.windows[identifier]) return folder = self.root if identifier == "default" else self.root / "profiles" / identifier folder.mkdir(parents=True, exist_ok=True) lock = C.QLockFile(str(folder / "workspace.lock")) if not lock.tryLock(0): self.statusBar().showMessage("有账号工作区已在其他程序窗口打开,未重复运行") return window = gui.Window(folder) window.connection_guard = lambda session: self.allow_connection(window, session) window.login_guard = lambda account: self.allow_login(window, account) window.device_guard = lambda serial: self.allow_device(window, serial) window.profile_changed.connect(lambda label: self.rename_profile(identifier, label)) self.windows[identifier], self.locks[identifier] = window, lock self.tabs.addTab(window, profile.get("label", "账号")) self.tabs.setCurrentWidget(window) def add_profile(self): profile = {"id": uuid.uuid4().hex, "label": f"账号 {len(self.profiles) + 1}"} self.profiles.append(profile) self.open_profile(profile) self.save_index() def activate_profile(self, *args): active = self.tabs.currentWidget() for window in self.windows.values(): window.set_presentation_active(window is active) def choose_profile(self): if not self.profiles: return labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in self.profiles] label, accepted = W.QInputDialog.getItem(self, "打开账号页签", "保存的账号工作区", labels, 0, False) if accepted: self.open_profile(self.profiles[labels.index(label)]) def rename_profile(self, identifier, label): for profile in self.profiles: if profile["id"] == identifier: profile["label"] = label window = self.windows.get(identifier) if window: self.tabs.setTabText(self.tabs.indexOf(window), label) self.save_index() def save_index(self): temporary = self.index_path.with_suffix(".tmp") temporary.write_text(json.dumps({"profiles": self.profiles}, ensure_ascii=False, indent=2), encoding="utf-8") temporary.replace(self.index_path) def allow_login(self, requester, account): for window in self.windows.values(): if window is not requester and not window.engine.demo and window.account.text().strip() == account: self.tabs.setCurrentWidget(window) return False return True def allow_connection(self, requester, session): if not isinstance(session, Session): return True for window in self.windows.values(): other = window.engine.client if window is not requester and other and isinstance(other.session, Session) and identity(other.session) == identity(session): self.tabs.setCurrentWidget(window) return False return True def allow_device(self, requester, serial): return not any(window is not requester and window.farm.running and (not serial or not window.farm.adb.serial or serial == window.farm.adb.serial) for window in self.windows.values()) def resume_all(self): for window in self.windows.values(): if window.engine.demo and not window.busy and window.saved_sessions.count(): window.resume_session() def monitor_all(self): for window in self.windows.values(): if not window.engine.demo: window.start_monitor.setChecked(True) def stop_all(self): for window in self.windows.values(): window.start_monitor.setChecked(False) window.start_farm.setChecked(False) window.execute.setChecked(False) def close_profile(self, index): window = self.tabs.widget(index) if window is None: return window.start_monitor.setChecked(False) window.start_farm.setChecked(False) window.timer.stop() window.closed = True window.pending_refresh = None if window.busy: C.QTimer.singleShot(250, lambda: self.close_profile(self.tabs.indexOf(window))) return identifier = next(k for k, value in self.windows.items() if value is window) window.close() self.tabs.removeTab(index) del self.windows[identifier] self.locks.pop(identifier).unlock() # Workspaces and saved sessions remain on disk for the next launch. window.deleteLater() def closeEvent(self, event): self.stop_all() for window in self.windows.values(): window.timer.stop() window.closed = True window.pending_refresh = None if any(window.busy for window in self.windows.values()): self.setEnabled(False) self.statusBar().showMessage("正在完成当前请求,完成后自动关闭并保存会话") C.QTimer.singleShot(250, self.close) event.ignore() return for window in self.windows.values(): window.close() for lock in self.locks.values(): lock.unlock() self.save_index() event.accept()