yingyongbao_auto/desktop_app.py
2026-10-17 10:46:29 +08:00

909 lines
37 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from __future__ import annotations
import json
import sys
from pathlib import Path
from urllib.parse import urlparse
from PySide6.QtCore import QSettings, QStandardPaths, QPoint, QPointF, QUrl, Qt, QTimer
from PySide6.QtGui import QColor, QPainter, QPen, QWheelEvent
from PySide6.QtWidgets import (
QApplication,
QFrame,
QGridLayout,
QHBoxLayout,
QLabel,
QLineEdit,
QMainWindow,
QComboBox,
QPushButton,
QPlainTextEdit,
QScrollArea,
QSizePolicy,
QSpinBox,
QVBoxLayout,
QWidget,
)
from PySide6.QtTest import QTest
from PySide6.QtWebEngineCore import QWebEnginePage, QWebEngineProfile
from PySide6.QtWebEngineWidgets import QWebEngineView
from app_logging import LogEmitter, configure_ui_logging, get_instance_logger
from ocr_task import OCRService, qimage_to_bgr
from scripts import create_script, script_options
from scripts.base import BrowserScript
from scripts.loader import build_debug_script_class
APP_STYLE = """
QMainWindow, QWidget { background: #f7f8f5; color: #202826; font-family: Arial, 'PingFang SC'; }
QLineEdit, QSpinBox { background: white; border: 1px solid #dce3dd; padding: 9px 11px; min-height: 18px; }
QLineEdit:focus, QSpinBox:focus { border: 1px solid #94a83c; }
QPushButton { background: #202826; color: white; border: 0; padding: 10px 17px; font-weight: bold; }
QPushButton:hover { background: #35413c; }
QPushButton:disabled { background: #aab4ae; }
QPushButton#stop { background: #d96552; }
QPushButton#logToggle { background: #e7ebe4; color: #55605a; border: 1px solid #d3dcd2;
padding: 2px 10px; font-weight: normal; font-size: 11px; }
QPushButton#logToggle:hover { background: #d8e0d4; }
QLabel#eyebrow { color: #74807b; font-size: 10px; font-weight: bold; }
QLabel#title { font-size: 25px; font-weight: bold; }
QLabel#hint { color: #74807b; font-size: 12px; }
QFrame#instance { background: white; border: 1px solid #dce3dd; }
QLabel#instanceTitle { font-size: 13px; font-weight: bold; }
QLabel#instanceStatus { color: #74807b; font-size: 12px; }
QLabel#error { color: #d96552; }
QComboBox { background: white; border: 1px solid #dce3dd; padding: 9px 11px; min-width: 170px; }
"""
# The cloud-phone page renders its Home/Back/Recents controls in the toolbar strip
# below the video stream (420x330 view, stream bottom ~y294, Home button center ~y312).
CLOUD_PHONE_VIEW_WIDTH = 420
CLOUD_PHONE_VIEW_HEIGHT = 330
CLOUD_PHONE_HOME_Y_RATIO = 0.945
# Standard fx-cloudphone-h5 layout: the phone-stream video sits at this CSS rect.
# Fallback for ratio clicks when the live DOM probe has not answered yet.
DEFAULT_STREAM_RECT = {"x": 128, "y": 0, "width": 165, "height": 294}
def profile_root() -> Path:
root = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
candidates = []
if root:
candidates.append(Path(root) / "browser-profiles")
candidates.append(Path(__file__).resolve().parent / "data" / "browser-profiles")
for path in candidates:
try:
path.mkdir(parents=True, exist_ok=True)
return path
except OSError:
continue
raise RuntimeError("无法创建浏览器 Session 存储目录")
def valid_url(value: str) -> bool:
parsed = urlparse(value.strip())
return parsed.scheme in {"http", "https"} and bool(parsed.netloc)
class ClickIndicator(QWidget):
"""Small blue ring flashed at a click point for visual feedback."""
def __init__(self, parent: QWidget) -> None:
super().__init__(parent)
# Let synthetic clicks pass through to the web content underneath.
self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents)
self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground)
def paintEvent(self, event) -> None: # noqa: N802 - Qt naming
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(QPen(QColor(58, 122, 254, 235), 2))
painter.setBrush(QColor(58, 122, 254, 60))
painter.drawEllipse(3, 3, self.width() - 6, self.height() - 6)
painter.setBrush(QColor(58, 122, 254, 230))
radius = max(2, self.width() // 8)
painter.drawEllipse(
self.width() // 2 - radius,
self.height() // 2 - radius,
radius * 2,
radius * 2,
)
class BrowserInstance(QFrame):
def __init__(
self,
instance_id: int,
ocr_service: OCRService,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.setObjectName("instance")
self.setFixedWidth(CLOUD_PHONE_VIEW_WIDTH)
self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Preferred)
self.instance_id = instance_id
self.action_text = ""
self.ocr_service = ocr_service
self.page_ready = False
self.pending_script: "str | BrowserScript | None" = None
self.active_script = None
# CSS rect of the phone-stream element (video/canvas); cached for scrolling.
self.stream_rect: dict | None = None
self.logger = get_instance_logger(instance_id)
header = QHBoxLayout()
header.setContentsMargins(14, 12, 14, 10)
title = QLabel(f"INSTANCE {instance_id:02d}")
title.setObjectName("instanceTitle")
self.status = QLabel("等待中")
self.status.setObjectName("instanceStatus")
header.addWidget(title)
header.addStretch()
header.addWidget(self.status)
self.view = QWebEngineView()
self.view.setFixedSize(CLOUD_PHONE_VIEW_WIDTH, CLOUD_PHONE_VIEW_HEIGHT)
self.view.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
# Each instance has its own persistent profile: cookies, local storage and sessions survive restarts.
self.profile = QWebEngineProfile(f"fengyun-instance-{instance_id}", self)
storage = profile_root() / f"instance-{instance_id}"
storage.mkdir(parents=True, exist_ok=True)
self.profile.setPersistentStoragePath(str(storage))
self.profile.setCachePath(str(storage / "cache"))
self.profile.setPersistentCookiesPolicy(
QWebEngineProfile.PersistentCookiesPolicy.ForcePersistentCookies
)
self.page = QWebEnginePage(self.profile, self.view)
self.view.setPage(self.page)
self.view.loadStarted.connect(lambda: self.set_status("加载页面"))
self.view.loadFinished.connect(self._loaded)
self.page.titleChanged.connect(self._title_changed)
self.message = QLabel("尚未打开页面")
self.message.setObjectName("hint")
self.message.setWordWrap(True)
self.message.setContentsMargins(14, 8, 14, 12)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addLayout(header)
layout.addWidget(self.view, 1)
layout.addWidget(self.message)
def set_status(self, value: str) -> None:
self.status.setText(value)
def open(self, url: str, action_text: str) -> None:
self.action_text = action_text.strip()
self.page_ready = False
self.message.setText("正在打开页面")
self.logger.info("open url=%s action_text=%r", url, action_text)
self.view.setUrl(QUrl(url.strip()))
def _title_changed(self, title: str) -> None:
if title:
self.message.setText(title)
def _loaded(self, ok: bool) -> None:
self.logger.info("load_finished ok=%s url=%s title=%r", ok, self.page.url().toString(), self.page.title())
if not ok:
self.page_ready = False
self.set_status("加载失败")
self.message.setText("页面加载失败,请检查网址或网络")
return
self.page_ready = True
self.set_status("已打开")
self.message.setText("可直接点击、输入和滚动操作")
if self.pending_script:
pending = self.pending_script
self.pending_script = None
if isinstance(pending, str):
QTimer.singleShot(250, lambda: self.start_script(pending))
else:
# An ad-hoc script object parked by BrowserScript.start().
QTimer.singleShot(250, pending.start)
if self.action_text:
QTimer.singleShot(350, lambda: self._click_text(self.action_text))
def start_script(self, script_id: str) -> None:
if self.active_script and self.active_script.running:
return
self.active_script = create_script(script_id, self, self.ocr_service, self.logger)
self.active_script.start()
def run_script_class(self, script_class: type[BrowserScript]) -> None:
"""Run an ad-hoc script class (live debug panel) on this instance."""
if self.active_script and self.active_script.running:
return
self.active_script = script_class(self, self.ocr_service, self.logger)
self.active_script.start()
def stop_script(self) -> None:
if self.active_script:
self.active_script.stop()
def _web_event_target(self) -> QWidget:
"""Return the widget that actually receives web input events.
QWebEngineView renders its page inside an internal QQuickWidget child that fills
the view. QTest mouse events sent to the view itself are dropped (QWidget ignores
them and they propagate to the parent), so synthetic clicks must be delivered to
that child widget. It sits at (0, 0), so view coordinates work unchanged.
"""
children = [
child
for child in self.view.findChildren(QWidget)
if child.isVisible() and child.width() > 0 and child.height() > 0
]
if children:
return max(children, key=lambda child: child.width() * child.height())
return self.view
def _send_mouse_click(self, x: int, y: int) -> QWidget:
"""Deliver a synthetic left click to the web content at view coordinates (x, y)."""
target = self._web_event_target()
self.view.setFocus(Qt.FocusReason.OtherFocusReason)
QTest.mouseMove(target, QPoint(x, y))
QTest.mousePress(target, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, QPoint(x, y))
QTest.qWait(50)
QTest.mouseRelease(target, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, QPoint(x, y))
self.show_click_feedback(x, y)
return target
def show_click_feedback(self, x: int, y: int) -> None:
"""Flash a small blue ring at view coordinates (x, y) for 0.5s."""
size = 34
indicator = ClickIndicator(self)
indicator.setGeometry(
self.view.x() + x - size // 2,
self.view.y() + y - size // 2,
size,
size,
)
indicator.raise_()
indicator.show()
QTimer.singleShot(500, indicator.deleteLater)
def click_cloud_home(self, attempt: int = 1) -> None:
"""Click the Home control in the toolbar the cloud-phone page renders below the stream."""
script = """
(() => {
const candidates = [...document.querySelectorAll(
'canvas, video, img, iframe, [class*="canvas"], [class*="screen"], [class*="stream"], [class*="phone"]'
)]
.map((element) => {
const rect = element.getBoundingClientRect();
return {rect, area: rect.width * rect.height};
})
.filter((item) => item.rect.width > 80 && item.rect.height > 80)
.sort((left, right) => right.area - left.area);
const streamRect = candidates.length ? candidates[0].rect : null;
// Home/Back/Recents are page controls in the strip below the phone stream,
// not part of the streamed video, so aim for the middle of that strip.
const stripTop = streamRect ? streamRect.bottom : window.innerHeight * 0.9;
const probeX = streamRect ? streamRect.left + streamRect.width * 0.5 : window.innerWidth * 0.5;
const probeY = (stripTop + window.innerHeight) * 0.5;
let button = null;
let bestDistance = Infinity;
for (const element of document.querySelectorAll('button, [role="button"], [onclick]')) {
const rect = element.getBoundingClientRect();
if (!rect.width || !rect.height) continue;
if (rect.y < stripTop - 5) continue;
const distance = Math.hypot(
rect.x + rect.width * 0.5 - probeX,
rect.y + rect.height * 0.5 - probeY
);
if (distance < bestDistance) {
bestDistance = distance;
button = rect;
}
}
let target;
if (button && bestDistance <= 90) {
target = {
x: button.x + button.width * 0.5,
y: button.y + button.height * 0.5,
source: 'DOM toolbar button'
};
} else {
target = {x: probeX, y: probeY, source: 'below-stream strip'};
}
return JSON.stringify({
stream: streamRect
? {x: streamRect.x, y: streamRect.y, width: streamRect.width, height: streamRect.height}
: null,
probe: {x: probeX, y: probeY},
buttonDistance: button ? Math.round(bestDistance) : null,
target: target
});
})();
"""
def clicked(raw_stream: object) -> None:
data: object = raw_stream
if isinstance(raw_stream, str):
try:
data = json.loads(raw_stream)
except json.JSONDecodeError:
self.logger.warning("cloud home DOM probe returned invalid JSON=%r", raw_stream)
data = {}
if not isinstance(data, dict):
data = {}
if isinstance(data.get("stream"), dict):
self.stream_rect = data["stream"]
self.logger.info("cloud home DOM probe attempt=%d result=%r", attempt, data)
x = self.view.width() // 2
y = int(self.view.height() * CLOUD_PHONE_HOME_Y_RATIO)
source = "view fallback"
target = data.get("target")
if isinstance(target, dict):
try:
x = int(float(target["x"]))
y = int(float(target["y"]))
source = str(target.get("source") or "DOM target")
except (KeyError, TypeError, ValueError):
self.logger.warning("cloud home DOM target invalid=%r; using fallbacks", target)
if source == "view fallback":
detected = self._detect_cloud_home_point()
if detected is not None:
x, y = detected
source = "screenshot dark navigation bar"
self._send_mouse_click(x, y)
self.logger.info(
"cloud home clicked coord=(%d,%d) source=%s view=%dx%d probe=%r",
x,
y,
source,
self.view.width(),
self.view.height(),
data,
)
# Neither stream nor toolbar button means the page is still booting.
page_ready = bool(data.get("stream") or data.get("buttonDistance") is not None)
if attempt < 2 and not page_ready:
QTimer.singleShot(500, lambda: self.click_cloud_home(attempt + 1))
self.page.runJavaScript(script, clicked)
def probe_stream_rect(self, callback=None) -> None:
"""Locate the phone-stream element and cache its CSS rect (used for scrolling)."""
script = """
(() => {
const candidates = [...document.querySelectorAll(
'canvas, video, iframe, [class*="canvas"], [class*="screen"], [class*="stream"], [class*="phone"]'
)]
.map((element) => {
const rect = element.getBoundingClientRect();
return {rect, area: rect.width * rect.height};
})
.filter((item) => item.rect.width > 80 && item.rect.height > 80)
.sort((left, right) => right.area - left.area);
const rect = candidates.length ? candidates[0].rect : null;
return JSON.stringify({
stream: rect
? {x: rect.x, y: rect.y, width: rect.width, height: rect.height}
: null
});
})();
"""
def probed(raw: object) -> None:
data: object = raw
if isinstance(raw, str):
try:
data = json.loads(raw)
except json.JSONDecodeError:
data = {}
if isinstance(data, dict) and isinstance(data.get("stream"), dict):
self.stream_rect = data["stream"]
self.logger.info("stream rect probed rect=%r", self.stream_rect)
else:
self.logger.warning("stream rect probe found nothing result=%r", data)
if callback:
callback(self.stream_rect)
self.page.runJavaScript(script, probed)
def scroll_stream(self, delta_y: int = -240) -> None:
"""Scroll the phone stream; negative delta_y scrolls the content down."""
x = self.view.width() // 2
y = self.view.height() // 2
rect = self.stream_rect if isinstance(self.stream_rect, dict) else None
if rect is not None:
try:
x = int(float(rect["x"]) + float(rect["width"]) * 0.5)
y = int(float(rect["y"]) + float(rect["height"]) * 0.5)
except (KeyError, TypeError, ValueError):
self.logger.warning("stream rect invalid for scroll rect=%r", rect)
target = self._web_event_target()
self.view.setFocus(Qt.FocusReason.OtherFocusReason)
QTest.mouseMove(target, QPoint(x, y))
global_point = self.view.mapToGlobal(QPoint(x, y))
event = QWheelEvent(
QPointF(x, y),
QPointF(global_point),
QPoint(0, 0),
QPoint(0, delta_y),
Qt.MouseButton.NoButton,
Qt.KeyboardModifier.NoModifier,
Qt.ScrollPhase.NoScrollPhase,
False,
)
QApplication.sendEvent(target, event)
self.logger.info(
"stream scroll sent delta=%d coord=(%d,%d) widget=%s",
delta_y,
x,
y,
target.metaObject().className(),
)
def click_stream_ratio(self, x_ratio: float, y_ratio: float, callback=None) -> None:
"""Click a stream-relative point (icon targets OCR cannot read, e.g. an ad close X).
The point is expressed as a ratio of the phone-stream rect so it stays correct
if the H5 layout shifts; falls back to the default stream layout when the DOM
probe has not produced a rect.
"""
rect = self.stream_rect if isinstance(self.stream_rect, dict) else None
if rect is None:
self.logger.warning("stream ratio click without probed rect; using default layout")
rect = DEFAULT_STREAM_RECT
try:
x = int(float(rect["x"]) + float(rect["width"]) * x_ratio)
y = int(float(rect["y"]) + float(rect["height"]) * y_ratio)
except (KeyError, TypeError, ValueError):
self.logger.warning("stream rect invalid for ratio click rect=%r", rect)
return
target = self._send_mouse_click(x, y)
self.logger.info(
"stream ratio click x_ratio=%.3f y_ratio=%.3f coord=(%d,%d) rect=%r widget=%s",
x_ratio,
y_ratio,
x,
y,
rect,
target.metaObject().className(),
)
if callback:
callback(x, y)
def _detect_cloud_home_point(self) -> tuple[int, int] | None:
"""Find the center of the dark navigation toolbar below the phone stream."""
image = self.view.grab().toImage()
frame = qimage_to_bgr(image)
if frame.size == 0:
return None
height, width = frame.shape[:2]
gray = frame.mean(axis=2)
left = int(width * 0.2)
right = int(width * 0.8)
dark_fraction = (gray[:, left:right] < 55).mean(axis=1)
minimum_run = max(8, int(height * 0.04))
runs: list[tuple[int, int]] = []
run_start: int | None = None
for row, is_dark in enumerate(dark_fraction > 0.55):
if is_dark and run_start is None:
run_start = row
elif not is_dark and run_start is not None:
if row - run_start >= minimum_run:
runs.append((run_start, row))
run_start = None
if run_start is not None and height - run_start >= minimum_run:
runs.append((run_start, height))
lower_runs = [run for run in runs if run[0] >= int(height * 0.5)]
if not lower_runs:
self.logger.debug("cloud home screenshot detection found no dark navigation bar")
return None
start, end = lower_runs[-1]
dpr = float(image.devicePixelRatio() or 1.0)
point = (int((width * 0.5) / dpr), int(((start + end) * 0.5) / dpr))
self.logger.info(
"cloud home screenshot detection image=%dx%d dpr=%.3f dark_run=(%d,%d) point=(%d,%d)",
width,
height,
dpr,
start,
end,
point[0],
point[1],
)
return point
def click_ocr_point(self, x: int, y: int, match: object, callback) -> None:
# Inspect the DOM for diagnostics, then use a real WebEngine mouse event. Many sites ignore
# JavaScript-created MouseEvents because they are not trusted user input.
self.logger.info(
"click start coord=(%d,%d) view=%dx%d url=%s text=%r",
x,
y,
self.view.width(),
self.view.height(),
self.page.url().toString(),
match.text,
)
script = """
(() => {
const x = %d;
const y = %d;
const node = document.elementFromPoint(x, y);
const describe = (element) => {
if (!element) return null;
const rect = element.getBoundingClientRect();
return {
tag: element.tagName,
id: element.id || null,
className: typeof element.className === 'string' ? element.className.slice(0, 160) : null,
text: (element.innerText || element.getAttribute('aria-label') || '').trim().slice(0, 160),
rect: {x: rect.x, y: rect.y, width: rect.width, height: rect.height}
};
};
const metrics = {
devicePixelRatio: window.devicePixelRatio,
innerWidth: window.innerWidth,
innerHeight: window.innerHeight,
scrollX: window.scrollX,
scrollY: window.scrollY
};
if (!node) return JSON.stringify({metrics, node: null, clickable: null});
const target = node.closest('a, button, input, label, [role="button"], [onclick]');
return JSON.stringify({metrics, node: describe(node), clickable: describe(target)});
})();
""" % (x, y)
def inspected(raw_result: object) -> None:
result: object = raw_result
if isinstance(raw_result, str):
try:
result = json.loads(raw_result)
except json.JSONDecodeError:
result = {"raw": raw_result}
self.logger.info("click DOM probe result=%r", result)
target = self._send_mouse_click(x, y)
method = "原生鼠标"
self.logger.info(
"native mouse click sent coord=(%d,%d) widget=%s",
x,
y,
target.metaObject().className(),
)
callback({"method": method, "dom_probe": result}, match, x, y)
QTimer.singleShot(500, self._log_click_state)
self.page.runJavaScript(script, inspected)
def _log_click_state(self) -> None:
self.page.runJavaScript(
"""
(() => JSON.stringify({
url: location.href,
title: document.title,
active: document.activeElement ? {
tag: document.activeElement.tagName,
id: document.activeElement.id || null,
text: (document.activeElement.innerText || '').trim().slice(0, 120)
} : null
}))();
""",
lambda result: self.logger.info("click post-check result=%r", result),
)
def _click_text(self, text: str) -> None:
script = """
(function(targetText) {
const wanted = targetText.trim().toLowerCase();
const nodes = document.querySelectorAll('button, a, input, [role="button"], [onclick], label');
for (const node of nodes) {
const visible = !!(node.offsetWidth || node.offsetHeight || node.getClientRects().length);
const content = (node.innerText || node.value || node.getAttribute('aria-label') || '').trim().toLowerCase();
if (visible && content.includes(wanted)) {
node.click();
return true;
}
}
return false;
})(%s);
""" % json.dumps(text, ensure_ascii=False)
def result(value: object) -> None:
if value:
self.message.setText(f"已点击“{text}”")
else:
self.message.setText(f"未找到“{text}”,页面保持打开")
self.page.runJavaScript(script, result)
def close_browser(self) -> None:
if self.active_script:
self.active_script.stop()
self.active_script = None
self.pending_script = None
self.action_text = ""
self.page_ready = False
self.view.stop()
self.view.setUrl(QUrl("about:blank"))
def clear_cache(self) -> None:
self.profile.clearHttpCache()
self.profile.clearAllVisitedLinks()
self.profile.cookieStore().deleteAllCookies()
self.page.runJavaScript("window.localStorage.clear(); window.sessionStorage.clear();")
self.message.setText("缓存、Cookie 和当前页面存储已清除,请重新加载页面")
self.set_status("已清理")
class MainWindow(QMainWindow):
def __init__(self) -> None:
super().__init__()
self.setWindowTitle("Web 群控工作台 · 浏览器容器版")
self.resize(1440, 920)
self.instances: list[BrowserInstance] = []
self.ocr_service = OCRService()
self.settings = QSettings("Fengyun", "WebControl")
self.log_emitter = LogEmitter()
configure_ui_logging(self.log_emitter)
central = QWidget()
root = QVBoxLayout(central)
root.setContentsMargins(24, 20, 24, 20)
root.setSpacing(14)
eyebrow = QLabel("BROWSER CONTAINER / PYTHON + QT WEBENGINE")
eyebrow.setObjectName("eyebrow")
title = QLabel("Web 群控工作台")
title.setObjectName("title")
hint = QLabel("每个实例都是独立的真实浏览器容器,可直接操作页面。")
hint.setObjectName("hint")
root.addWidget(eyebrow)
root.addWidget(title)
root.addWidget(hint)
controls = QHBoxLayout()
controls.setSpacing(9)
self.url = QComboBox()
self.url.setEditable(True)
self.url.setInsertPolicy(QComboBox.InsertPolicy.NoInsert)
self.url.setMinimumWidth(380)
self.url.setPlaceholderText("目标网址,例如 https://example.com")
self._load_url_history()
self.count = QSpinBox()
self.count.setRange(1, 12)
self.count.setValue(1)
self.action_text = QLineEdit()
self.action_text.setPlaceholderText("可选:页面文字")
self.action_text.setMinimumWidth(180)
self.script = QComboBox()
for script_id, label in script_options():
self.script.addItem(label, script_id)
start = QPushButton("启动实例")
start.clicked.connect(self.start_instances)
run_script = QPushButton("开始脚本")
run_script.clicked.connect(self.start_script)
stop_script = QPushButton("停止脚本")
stop_script.clicked.connect(self.stop_scripts)
clear_cache = QPushButton("清除缓存")
clear_cache.clicked.connect(self.clear_cache)
stop = QPushButton("停止全部")
stop.setObjectName("stop")
stop.clicked.connect(self.stop_instances)
controls.addWidget(QLabel("网址"))
controls.addWidget(self.url, 1)
controls.addWidget(QLabel("数量"))
controls.addWidget(self.count)
controls.addWidget(self.action_text)
controls.addWidget(self.script)
controls.addWidget(start)
controls.addWidget(run_script)
controls.addWidget(stop_script)
controls.addWidget(clear_cache)
controls.addWidget(stop)
root.addLayout(controls)
self.error = QLabel("")
self.error.setObjectName("error")
root.addWidget(self.error)
self.log_view = QPlainTextEdit()
self.log_view.setReadOnly(True)
self.log_view.setMaximumBlockCount(600)
self.log_view.setPlaceholderText("脚本日志会显示在这里;完整日志保存在 data/logs/fengyun.log")
self.log_view.setMinimumHeight(140)
self.log_emitter.message.connect(self.log_view.appendPlainText)
# Bottom panel: a slim toggle bar (small arrow button) above the content,
# log on the left half, live step-debug input on the right. Collapsing the
# content hands the freed height back to the device grid above.
self.bottom_host = QWidget()
bottom = QVBoxLayout(self.bottom_host)
bottom.setContentsMargins(0, 0, 0, 0)
bottom.setSpacing(0)
toggle_bar = QHBoxLayout()
toggle_bar.setContentsMargins(0, 0, 0, 4)
self.log_toggle = QPushButton("▾ 隐藏日志")
self.log_toggle.setObjectName("logToggle")
self.log_toggle.setCursor(Qt.CursorShape.PointingHandCursor)
self.log_toggle.setFixedWidth(96)
self.log_toggle.clicked.connect(self.toggle_log_panel)
toggle_bar.addStretch()
toggle_bar.addWidget(self.log_toggle)
bottom.addLayout(toggle_bar)
self.bottom_content = QWidget()
content = QHBoxLayout(self.bottom_content)
content.setContentsMargins(0, 0, 0, 0)
content.setSpacing(14)
log_pane = QVBoxLayout()
log_pane.setSpacing(4)
log_pane.addWidget(QLabel("实时调试日志"))
log_pane.addWidget(self.log_view, 1)
content.addLayout(log_pane, 1)
debug_pane = QVBoxLayout()
debug_pane.setSpacing(4)
debug_pane.addWidget(QLabel("实时调试(粘贴步骤 JSON,点“运行调试步骤”立即执行)"))
self.debug_input = QPlainTextEdit()
self.debug_input.setPlaceholderText(
'单个步骤或步骤数组,例如:\n'
'{"kind": "cond_ratio_click", "confirm": "看15秒", '
'"alt_confirms": ["恭喜已获得"], "absent": "应用版本", '
'"x_ratio": 0.924, "y_ratio": 0.111, "label": "点击广告页右上角 X", "max_scans": 8}'
)
debug_pane.addWidget(self.debug_input, 1)
debug_row = QHBoxLayout()
debug_run = QPushButton("运行调试步骤")
debug_run.clicked.connect(self.run_debug_steps)
self.debug_error = QLabel("")
self.debug_error.setObjectName("error")
self.debug_error.setWordWrap(True)
debug_row.addWidget(debug_run)
debug_row.addWidget(self.debug_error, 1)
debug_pane.addLayout(debug_row)
content.addLayout(debug_pane, 1)
bottom.addWidget(self.bottom_content)
self.grid_host = QWidget()
self.grid = QGridLayout(self.grid_host)
self.grid.setContentsMargins(0, 0, 0, 0)
self.grid.setSpacing(14)
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setWidget(self.grid_host)
root.addWidget(scroll, 1)
root.addWidget(self.bottom_host)
self.setCentralWidget(central)
def start_instances(self) -> None:
target = self.url.currentText().strip()
if not valid_url(target):
self.error.setText("请输入完整的网址,例如 https://example.com")
return
self.error.setText("")
self._save_url(target)
self.stop_instances()
for index in range(self.count.value()):
card = BrowserInstance(index + 1, self.ocr_service, self.grid_host)
self.instances.append(card)
self.grid.addWidget(
card,
index // 3,
index % 3,
Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignHCenter,
)
card.open(target, self.action_text.text())
def _refresh_script_options(self) -> None:
"""Reload script definitions so edited/new JSON files show up without a restart."""
selected = self.script.currentData()
self.script.blockSignals(True)
self.script.clear()
for script_id, label in script_options():
self.script.addItem(label, script_id)
self.script.blockSignals(False)
if selected:
index = self.script.findData(selected)
if index >= 0:
self.script.setCurrentIndex(index)
def start_script(self) -> None:
if not self.instances:
self.error.setText("请先启动浏览器实例")
return
self.error.setText("")
self._refresh_script_options()
script_id = self.script.currentData()
if not script_id:
self.error.setText("没有可用的脚本,请检查 data/scripts/*.json")
return
for card in self.instances:
card.start_script(script_id)
def toggle_log_panel(self) -> None:
"""Collapse/expand the bottom log+debug content so the device grid can go fullscreen."""
expanded = not self.bottom_content.isVisible()
self.bottom_content.setVisible(expanded)
self.log_toggle.setText("▾ 隐藏日志" if expanded else "▴ 打开日志")
def run_debug_steps(self) -> None:
"""Parse the pasted step JSON and run it as an ad-hoc script on every instance."""
if not self.instances:
self.debug_error.setText("请先启动浏览器实例")
return
raw = self.debug_input.toPlainText().strip()
if not raw:
self.debug_error.setText("请输入步骤 JSON")
return
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
self.debug_error.setText(f"JSON 解析失败:{exc}")
return
steps = data if isinstance(data, list) else [data]
try:
script_class = build_debug_script_class(steps)
except (ValueError, TypeError) as exc:
self.debug_error.setText(f"步骤校验失败:{exc}")
return
self.debug_error.setText("")
self.error.setText("")
for card in self.instances:
card.run_script_class(script_class)
def stop_scripts(self) -> None:
for card in self.instances:
card.stop_script()
def clear_cache(self) -> None:
if not self.instances:
self.error.setText("请先启动浏览器实例")
return
for card in self.instances:
card.clear_cache()
self.error.setText("已清除所有实例的缓存、Cookie 和页面存储")
def _load_url_history(self) -> None:
history = self.settings.value("url_history", [])
if isinstance(history, str):
history = [history]
for url in history or []:
if isinstance(url, str) and valid_url(url):
self.url.addItem(url)
if self.url.count() == 0:
self.url.addItem("https://example.com")
def _save_url(self, url: str) -> None:
history = [self.url.itemText(index) for index in range(self.url.count())]
history = [item for item in history if item and item != url]
history.insert(0, url)
history = history[:20]
self.settings.setValue("url_history", history)
self.url.clear()
self.url.addItems(history)
self.url.setCurrentText(url)
def stop_instances(self) -> None:
for card in self.instances:
card.close_browser()
card.deleteLater()
self.instances.clear()
def closeEvent(self, event) -> None: # type: ignore[no-untyped-def]
self.stop_instances()
event.accept()
def main() -> int:
app = QApplication(sys.argv)
app.setStyle("Fusion")
app.setStyleSheet(APP_STYLE)
window = MainWindow()
window.show()
return app.exec()
if __name__ == "__main__":
raise SystemExit(main())