"""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 from .account_storage import profile_directory, remove_account_files 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.pending_closes, self.pending_removals = set(), set() 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) self.setup_menus() note = W.QLabel("各账号独立登录并持续刷新状态,切换页签不影响其他账号;策略可分别开启或关闭。") 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) self.tabs.tabBar().setContextMenuPolicy(C.Qt.ContextMenuPolicy.CustomContextMenu) self.tabs.tabBar().customContextMenuRequested.connect(self.account_tab_menu) 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): if profile.get("open", True): self.open_profile(profile) self.update_account_actions() gui.compact_layouts(central) def setup_menus(self): accounts = self.menuBar().addMenu("账号(&A)") for text, handler in (("新增账号页签", self.add_profile), ("打开已保存账号…", self.choose_profile), ("恢复各页签的保存会话", self.resume_all)): accounts.addAction(text, handler) self.close_account_action = accounts.addAction("关闭当前账号页签", lambda: self.close_profile(self.tabs.currentIndex())) self.remove_account_action = accounts.addAction("移除当前账号…", self.remove_current_profile) self.remove_saved_action = accounts.addAction("移除已保存账号…", self.choose_remove_profile) accounts.aboutToShow.connect(self.update_account_actions) accounts.addSeparator() accounts.addAction("退出", self.close) strategies_run = self.menuBar().addMenu("策略(&R)") strategies_run.addAction("开启全部账号策略", self.start_all_strategies) strategies_run.addAction("关闭全部账号策略", self.stop_all) strategies = self.menuBar().addMenu("策略配置(&S)") self.save_policy_action = strategies.addAction("保存当前账号策略", self.save_current_policies) self.save_policy_action.setShortcut("Ctrl+S") self.import_policy_action = strategies.addAction("导入当前账号策略…", lambda: self.run_account_action("import_policies")) self.export_policy_action = strategies.addAction("导出当前账号策略…", lambda: self.run_account_action("export_policies")) self.policy_actions = (self.save_policy_action, self.import_policy_action, self.export_policy_action) strategies.aboutToShow.connect(self.update_account_actions) help_menu = self.menuBar().addMenu("帮助(&H)") self.about_action = help_menu.addAction("关于…", self.show_about) def update_account_actions(self): window = self.tabs.currentWidget() for action in self.policy_actions: action.setEnabled(window is not None and not window.closed) for action in (self.close_account_action, self.remove_account_action): action.setEnabled(window is not None and not window.closed) self.remove_saved_action.setEnabled(bool(self.profiles)) def run_account_action(self, method): window = self.tabs.currentWidget() if window is not None and not window.closed: return getattr(window, method)() def save_current_policies(self): value = self.run_account_action("persist_settings") if value is not None: label = self.tabs.tabText(self.tabs.currentIndex()) self.statusBar().showMessage(f"已保存账号“{label}”的策略", 5000) else: self.statusBar().showMessage("策略尚未保存,请检查当前账号的输入和提示", 5000) def show_about(self): W.QMessageBox.about(self, "关于牧羊人之心牧场辅助", f"牧羊人之心牧场辅助\n\n辅助版本:{gui.APP_VERSION}\n适配游戏版本:{gui.GAME_VERSION}") def open_profile(self, profile): identifier = profile["id"] if not any(p["id"] == identifier for p in self.profiles): return if identifier in self.pending_removals: self.statusBar().showMessage("此账号正在移除,请等待当前请求完成", 5000) return if identifier in self.windows: if self.windows[identifier].closed: self.statusBar().showMessage("此账号正在关闭,请稍后重新打开", 5000) return self.tabs.setCurrentWidget(self.windows[identifier]) return folder = profile_directory(self.root, 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.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) profile["open"] = True self.save_index() def add_profile(self): profile = {"id": uuid.uuid4().hex, "label": f"账号 {len(self.profiles) + 1}", "open": True} 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) self.update_account_actions() def choose_profile(self): if not self.profiles: return profiles = list(self.profiles) labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in profiles] label, accepted = W.QInputDialog.getItem(self, "打开账号页签", "保存的账号工作区", labels, 0, False) if accepted: self.open_profile(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 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 start_all_strategies(self): for window in self.windows.values(): if not window.engine.demo and not window.closed: window.start_workflow() def stop_all(self): for window in self.windows.values(): window.stop_workflow() def close_profile(self, index): window = self.tabs.widget(index) if window is None: return identifier = next(k for k, value in self.windows.items() if value is window) self.close_profile_id(identifier) def close_profile_id(self, identifier): window = self.windows.get(identifier) if window is None: return profile = next(p for p in self.profiles if p["id"] == identifier) if profile.get("open", True): profile["open"] = False self.save_index() window.monitoring = False window.stop_workflow() window.timer.stop() window.hatch_timer.stop() window.engine.auto = False window.closed = True window.pending_refresh = None window.setEnabled(False) self.update_account_actions() if window.busy: if identifier not in self.pending_closes: self.pending_closes.add(identifier) C.QTimer.singleShot(100, lambda: self.finish_close_profile(identifier)) return window.close() self.tabs.removeTab(self.tabs.indexOf(window)) del self.windows[identifier] self.locks.pop(identifier).unlock() window.deleteLater() if identifier in self.pending_removals: self.finish_remove_profile(identifier) def finish_close_profile(self, identifier): self.pending_closes.discard(identifier) self.close_profile_id(identifier) def account_tab_menu(self, position): index = self.tabs.tabBar().tabAt(position) window = self.tabs.widget(index) if window is None: return identifier = next(k for k, value in self.windows.items() if value is window) menu = W.QMenu(self) self.tab_context_menu = menu menu.addAction("关闭账号页签", lambda: self.close_profile_id(identifier)) menu.addAction("移除此账号…", lambda: self.confirm_remove_profile(identifier)) menu.popup(self.tabs.tabBar().mapToGlobal(position)) def remove_current_profile(self): window = self.tabs.currentWidget() if window is not None: self.confirm_remove_profile(next(k for k, value in self.windows.items() if value is window)) def choose_remove_profile(self): if not self.profiles: return profiles = list(self.profiles) labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in profiles] label, accepted = W.QInputDialog.getItem(self, "移除已保存账号", "选择要移除的账号(含已关闭页签)", labels, 0, False) if accepted and label: self.confirm_remove_profile(profiles[labels.index(label)]["id"]) def confirm_remove_profile(self, identifier): profile = next((p for p in self.profiles if p["id"] == identifier), None) if profile is None or identifier in self.pending_removals: return label = profile.get("label", "账号") text = f"移除“{label}”?\n\n将删除该账号的本地密码、会话、策略、地图缓存和运行记录,无法恢复。\n此操作不会注销游戏账号。" if W.QMessageBox.question(self, "移除账号", text, W.QMessageBox.StandardButton.Yes | W.QMessageBox.StandardButton.No, W.QMessageBox.StandardButton.No) != W.QMessageBox.StandardButton.Yes: return self.pending_removals.add(identifier) if identifier in self.windows: self.statusBar().showMessage("正在停止该账号,当前请求完成后移除", 5000) self.close_profile_id(identifier) else: self.finish_remove_profile(identifier) def finish_remove_profile(self, identifier): lock = None try: folder = profile_directory(self.root, identifier) if folder.exists(): lock = C.QLockFile(str(folder / "workspace.lock")) if not lock.tryLock(0): raise ValueError("该账号正在其他窗口使用,请关闭后重试") remove_account_files(self.root, identifier) lock.unlock() lock = None if identifier != "default": folder.rmdir() old_profiles = self.profiles self.profiles = [p for p in self.profiles if p["id"] != identifier] try: self.save_index() except OSError: self.profiles = old_profiles raise self.statusBar().showMessage("已移除账号及其本地记录", 5000) except (OSError, ValueError) as error: self.statusBar().showMessage("账号未完全移除:" + str(error), 10000) finally: if lock is not None: lock.unlock() self.pending_removals.discard(identifier) self.update_account_actions() def closeEvent(self, event): self.stop_all() for window in self.windows.values(): window.timer.stop() window.monitoring = False 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 identifier in list(self.pending_removals): if identifier in self.windows: self.close_profile_id(identifier) for window in self.windows.values(): window.close() for lock in self.locks.values(): lock.unlock() self.save_index() event.accept()