Compare commits
77
Commits
8dace383ec
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec2f044d8c | ||
|
|
18b75ceda4 | ||
|
|
e9b003f906 | ||
|
|
95459607dc | ||
|
|
0d4796744d | ||
|
|
1cd94e9705 | ||
|
|
8c2d93a79f | ||
|
|
92d60f9931 | ||
|
|
29b9788371 | ||
|
|
7eeaab9a6e | ||
|
|
089cb32e1c | ||
|
|
a06ece4e15 | ||
|
|
6cebed599d | ||
|
|
da5e000006 | ||
|
|
065d73ff9a | ||
|
|
adbd8a2d6e | ||
|
|
1235c5910f | ||
|
|
84c5731cc3 | ||
|
|
8e0ae9396d | ||
|
|
a6648c5ce8 | ||
|
|
f75d3ae368 | ||
|
|
d9920f1cee | ||
|
|
e763cdc302 | ||
|
|
fd694f8ce5 | ||
|
|
547228fa2d | ||
|
|
e7d848023c | ||
|
|
a1562a513d | ||
|
|
b8f2806ffc | ||
|
|
9642b7b0f8 | ||
|
|
9896eb676a | ||
|
|
e0c68883dd | ||
|
|
e0cad29daf | ||
|
|
6a8296cab1 | ||
|
|
3626e9cf6f | ||
|
|
29d930b1de | ||
|
|
df758cf224 | ||
|
|
47865f5dfa | ||
|
|
9744b75878 | ||
|
|
200f3a53fc | ||
|
|
7a840120b3 | ||
|
|
e314161b6c | ||
|
|
3a7a7a3b75 | ||
|
|
8575f04ab9 | ||
|
|
728ef3cd79 | ||
|
|
32e374e2c2 | ||
|
|
aa0f4e05f2 | ||
|
|
5e3015f59b | ||
|
|
dc1744a93f | ||
|
|
b686a4e3d5 | ||
|
|
29cef2c578 | ||
|
|
e784efd5f8 | ||
|
|
6c7bbf0945 | ||
|
|
fe27063913 | ||
|
|
3f04bb23c2 | ||
|
|
bcb0e363d1 | ||
|
|
b447b6a6a4 | ||
|
|
3ac8664817 | ||
|
|
6bac014c3d | ||
|
|
3d433080c2 | ||
|
|
f6d382b0e7 | ||
|
|
2a05be2319 | ||
|
|
f9839f3dee | ||
|
|
97935d9c48 | ||
|
|
64c210dd5a | ||
|
|
68d1224b53 | ||
|
|
92d524297b | ||
|
|
59ebe8c1e7 | ||
|
|
a7ef92fc7c | ||
|
|
c5df7a05d2 | ||
|
|
b3380042b8 | ||
|
|
4993fad004 | ||
|
|
44b091466d | ||
|
|
8ea676562c | ||
|
|
a07ef00b5e | ||
|
|
5329561b3a | ||
|
|
6bffcae2de | ||
|
|
ac464788e1 |
No files matched your search
@@ -0,0 +1,982 @@
|
||||
# Split WebUI Large Files Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Continue the large-file split after `gui/gui_app.py` by modularizing the WebUI frontend and, only after the frontend is stable, splitting the Web GUI Python server.
|
||||
|
||||
**Architecture:** Keep the current static WebUI behavior intact while moving code into focused `webui/js/*` and `webui/css/*` files. Each task changes one responsibility, preserves global names needed by `DOMContentLoaded`, runs focused tests, commits, and pushes before the next task.
|
||||
|
||||
**Tech Stack:** Plain HTML/CSS/JavaScript, Python `http.server`, pytest, browser smoke test for UI changes.
|
||||
|
||||
---
|
||||
|
||||
## Current Evidence
|
||||
|
||||
From the current worktree on 2026-05-31:
|
||||
|
||||
| File | Lines | Role |
|
||||
|---|---:|---|
|
||||
| `webui/styles.css` | 3745 | WebUI visual system, layout, panels, logs, responsive rules |
|
||||
| `webui/app.js` | 2512 | WebUI constants, state, API calls, rendering, polling, event wiring |
|
||||
| `gui/web_gui.py` | 1663 | local HTTP server, runner, API routes, static file serving |
|
||||
| `webui/index.html` | 1232 | WebUI DOM structure and config bindings |
|
||||
|
||||
`gui/gui_app.py` is already down to about 130 lines and should not be the next split target. The next target is the WebUI bundle.
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
Stop this plan and write an outcome note when any one is true:
|
||||
|
||||
1. `webui/app.js` is below 700 lines and `webui/styles.css` is below 1400 lines.
|
||||
2. The next split would require changing more than 3 of the large files in one task.
|
||||
3. Browser smoke finds a visual or runtime regression that cannot be fixed inside the current task boundary.
|
||||
4. Tests fail and the fix would require behavior changes outside the current responsibility.
|
||||
|
||||
## Verification Commands
|
||||
|
||||
Run these after every JavaScript or HTML task:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
```text
|
||||
py_compile: exit code 0
|
||||
pytest: all selected tests PASS
|
||||
```
|
||||
|
||||
Run these after every CSS or visual task:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
```text
|
||||
py_compile: exit code 0
|
||||
pytest: all selected tests PASS
|
||||
```
|
||||
|
||||
For frontend visual changes, also start the Web GUI and inspect it in a browser:
|
||||
|
||||
```powershell
|
||||
python gui\web_gui.py
|
||||
```
|
||||
|
||||
Expected browser checks:
|
||||
|
||||
- `/` loads without a blank page.
|
||||
- Console has no module load errors, syntax errors, or missing function errors.
|
||||
- Header buttons, tabs, logs panel, reservations panel, high-value panel, screenshot preview, and footer remain visible without overlap at desktop width.
|
||||
- At mobile width, command buttons wrap and panels remain readable.
|
||||
|
||||
## Static Loading Decision
|
||||
|
||||
The current page loads:
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
|
||||
<script src="app.js?v=console-20260520-theme-v35"></script>
|
||||
```
|
||||
|
||||
Use classic scripts for the first JavaScript split instead of ES modules. This avoids a broad initialization rewrite and keeps inline event expectations simple. New scripts must be loaded before `app.js` if `app.js` depends on them.
|
||||
|
||||
For CSS, use multiple `<link rel="stylesheet">` tags. Keep `styles.css` as the compatibility shell until the end of the CSS split.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Add WebUI Static Asset Structure
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/README.md`
|
||||
- Create: `webui/css/README.md`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create asset directory docs**
|
||||
|
||||
Create `webui/js/README.md`:
|
||||
|
||||
```markdown
|
||||
# WebUI JavaScript modules
|
||||
|
||||
Classic browser scripts loaded by `webui/index.html`.
|
||||
|
||||
Load order matters:
|
||||
|
||||
1. `constants.js`
|
||||
2. `dom.js`
|
||||
3. `api.js`
|
||||
4. focused feature scripts
|
||||
5. `app.js`
|
||||
|
||||
Keep behavior-preserving splits small. Do not introduce a build step unless a later plan explicitly replaces this static layout.
|
||||
```
|
||||
|
||||
Create `webui/css/README.md`:
|
||||
|
||||
```markdown
|
||||
# WebUI CSS modules
|
||||
|
||||
Plain CSS files loaded by `webui/index.html`.
|
||||
|
||||
Recommended order:
|
||||
|
||||
1. `tokens.css`
|
||||
2. `base.css`
|
||||
3. `layout.css`
|
||||
4. `components.css`
|
||||
5. focused panel or feature CSS
|
||||
6. `styles.css` compatibility remainder
|
||||
|
||||
Keep selectors stable so existing HTML and JavaScript continue to work.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add no-op load anchors to `index.html`**
|
||||
|
||||
Insert comments around the existing assets:
|
||||
|
||||
```html
|
||||
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
|
||||
<script src="app.js?v=console-20260520-theme-v35"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: selected tests PASS.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/js/README.md webui/css/README.md
|
||||
git commit -m "refactor(webui): add static module split structure"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Extract JavaScript Constants and Copy
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/constants.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `constants.js`**
|
||||
|
||||
Move these top-level constants from `app.js` into `webui/js/constants.js` unchanged:
|
||||
|
||||
```javascript
|
||||
const UI_LIMITS = Object.freeze({
|
||||
runLogMaxLines: 50000,
|
||||
runLogMaxChars: 200000,
|
||||
actionsLogMaxLines: 5000,
|
||||
scrollBottomThresholdPx: 5,
|
||||
screenshotPollMs: 1500,
|
||||
logPollMs: 800,
|
||||
statsPollMs: 1200,
|
||||
});
|
||||
|
||||
const UI_CLASS = Object.freeze({
|
||||
busy: "isBusy",
|
||||
clickable: "isClickable",
|
||||
collapsed: "isCollapsed",
|
||||
listCollapsed: "isListCollapsed",
|
||||
reservationHeader: "reservationHeader",
|
||||
reservationBody: "reservationBody",
|
||||
reservationsList: "reservationsList",
|
||||
shotEmpty: "isShotEmpty",
|
||||
statusRunning: "statusRunning",
|
||||
statusIdle: "statusIdle",
|
||||
statusError: "statusError",
|
||||
});
|
||||
|
||||
const RUN_TONE = Object.freeze({
|
||||
running: "running",
|
||||
idle: "idle",
|
||||
error: "error",
|
||||
});
|
||||
```
|
||||
|
||||
Also move `UI_COPY`, `TIMELINE_SERIES_KEYS`, `TIMELINE_LAYOUT`, `TIMELINE_STROKES`, and `DEFAULTS` unchanged.
|
||||
|
||||
- [ ] **Step 2: Remove moved constants from `app.js`**
|
||||
|
||||
Delete only the moved constant declarations from `webui/app.js`. Keep state variables such as `logIdx`, `pollTimer`, `runLogBuffer`, and `deviceOverviewState` in `app.js` for now.
|
||||
|
||||
- [ ] **Step 3: Load `constants.js` before `app.js`**
|
||||
|
||||
Change the bottom of `webui/index.html` to:
|
||||
|
||||
```html
|
||||
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
|
||||
<script src="js/constants.js?v=console-20260531-split-1"></script>
|
||||
<script src="app.js?v=console-20260531-split-1"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: both PASS.
|
||||
|
||||
- [ ] **Step 5: Browser smoke**
|
||||
|
||||
Start:
|
||||
|
||||
```powershell
|
||||
python gui\web_gui.py
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:8765/` or the printed local URL. Confirm console has no `UI_LIMITS is not defined`, `DEFAULTS is not defined`, or `fmtDuration is not defined` errors.
|
||||
|
||||
- [ ] **Step 6: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/constants.js
|
||||
git commit -m "refactor(webui): extract frontend constants"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Extract DOM and Formatting Helpers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/dom_utils.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `dom_utils.js`**
|
||||
|
||||
Move these functions from `app.js` into `webui/js/dom_utils.js` unchanged:
|
||||
|
||||
```javascript
|
||||
function $(id)
|
||||
function setTextIfExists(id, text)
|
||||
function clearEl(el)
|
||||
function escapeHtml(s)
|
||||
function fmtTime(ts)
|
||||
function fmtNum(v)
|
||||
function fmtDuration(seconds)
|
||||
```
|
||||
|
||||
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete the moved function declarations only. Do not move UI initialization functions yet.
|
||||
|
||||
- [ ] **Step 3: Load `dom_utils.js` after `constants.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-2"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-2"></script>
|
||||
<script src="app.js?v=console-20260531-split-2"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser console, confirm no `$ is not defined`, `fmtDuration is not defined`, or `escapeHtml is not defined` errors.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/dom_utils.js
|
||||
git commit -m "refactor(webui): extract DOM and format helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Extract API Client Helpers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/api_client.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `api_client.js`**
|
||||
|
||||
Move these functions and state from `app.js` into `webui/js/api_client.js` unchanged:
|
||||
|
||||
```javascript
|
||||
let _apiFailStreak = 0;
|
||||
const _apiFailThreshold = 2;
|
||||
let _csrfToken = null;
|
||||
|
||||
function setConnState(state)
|
||||
function notifyApiOk()
|
||||
function notifyApiFail()
|
||||
async function apiGet(path)
|
||||
async function getCsrfToken()
|
||||
async function apiPost(path, body)
|
||||
```
|
||||
|
||||
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved declarations from `app.js`**
|
||||
|
||||
Delete only the moved declarations. Keep feature-level functions such as `refreshDevices`, `startRun`, `pollLogs`, and `pollStats` in `app.js`.
|
||||
|
||||
- [ ] **Step 3: Load `api_client.js` after `dom_utils.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-3"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-3"></script>
|
||||
<script src="js/api_client.js?v=console-20260531-split-3"></script>
|
||||
<script src="app.js?v=console-20260531-split-3"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser, click refresh devices and load config. Confirm API state footer updates and no `apiGet is not defined` or CSRF errors appear.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/api_client.js
|
||||
git commit -m "refactor(webui): extract API client helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Extract Log View Behavior
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/log_views.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `log_views.js`**
|
||||
|
||||
Move the log rendering and search functions from `app.js` into `webui/js/log_views.js`:
|
||||
|
||||
```javascript
|
||||
function classifyLogLine(line)
|
||||
function renderLogLineNode(line)
|
||||
function appendLog(lines)
|
||||
function renderRunLog()
|
||||
function appendRunLogLines(lines)
|
||||
async function fetchActionsLog()
|
||||
function renderActionsLog()
|
||||
```
|
||||
|
||||
Keep these shared state variables in `app.js` for this task:
|
||||
|
||||
```javascript
|
||||
let runLogBuffer = [];
|
||||
let runLogFilter = "";
|
||||
let runLogMode = "filter";
|
||||
let runSearchResultsBuffer = [];
|
||||
let runSearchActive = false;
|
||||
let actionsLogBuffer = [];
|
||||
let actionsLogFilter = "";
|
||||
```
|
||||
|
||||
Because classic scripts share global scope, `log_views.js` can keep using these names.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved function declarations.
|
||||
|
||||
- [ ] **Step 3: Load `log_views.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/api_client.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/log_views.js?v=console-20260531-split-4"></script>
|
||||
<script src="app.js?v=console-20260531-split-4"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser, check the run log filter/search and action log refresh.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/log_views.js
|
||||
git commit -m "refactor(webui): extract log view behavior"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Extract Dashboard Renderers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/dashboard_renderers.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `dashboard_renderers.js`**
|
||||
|
||||
Move these renderer functions from `app.js` into `webui/js/dashboard_renderers.js`:
|
||||
|
||||
```javascript
|
||||
function renderBars(containerId, dataMap, labelMap)
|
||||
function renderTopContent(containerId, items)
|
||||
function renderWinsTable(containerId, wins)
|
||||
function renderTimeline(containerId, timeline)
|
||||
function renderOverviewSparkline(svgId, timeline)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved renderer declarations.
|
||||
|
||||
- [ ] **Step 3: Load `dashboard_renderers.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/dashboard_renderers.js?v=console-20260531-split-5"></script>
|
||||
<script src="app.js?v=console-20260531-split-5"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `dashboard_renderers.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. In browser, confirm stats charts, timeline tooltip, top content table, and wins table still render.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/dashboard_renderers.js
|
||||
git commit -m "refactor(webui): extract dashboard renderers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Extract Config Form Binding
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/config_form.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `config_form.js`**
|
||||
|
||||
Move these config-related functions from `app.js` into `webui/js/config_form.js`:
|
||||
|
||||
```javascript
|
||||
function getConfigBoundElements()
|
||||
function syncMirrorFields()
|
||||
function getConfigValue(cfg, key)
|
||||
function coerceValue(type, raw, isCheckbox)
|
||||
function applyConfigToUI(cfg)
|
||||
function collectConfigFromUI()
|
||||
async function loadConfig()
|
||||
async function saveConfig()
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved config declarations.
|
||||
|
||||
- [ ] **Step 3: Load `config_form.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/config_form.js?v=console-20260531-split-6"></script>
|
||||
<script src="app.js?v=console-20260531-split-6"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `config_form.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification and `pytest tests/test_gui_webui_sync.py -q`. In browser, load config, change one harmless UI field, save, reload, and confirm no config-binding error appears.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/config_form.js
|
||||
git commit -m "refactor(webui): extract config form bindings"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Extract Polling and Device Actions
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/runtime_actions.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `runtime_actions.js`**
|
||||
|
||||
Move these functions from `app.js` into `webui/js/runtime_actions.js`:
|
||||
|
||||
```javascript
|
||||
async function refreshDevices()
|
||||
function decorateDeviceSelect()
|
||||
function selectedDeviceId()
|
||||
async function postDeviceAction(path, body, successPrefix)
|
||||
async function forceStopRun()
|
||||
async function sendBackKey()
|
||||
async function wifiEnable()
|
||||
async function wifiConnect()
|
||||
async function wifiDisconnect()
|
||||
async function tryAutoReconnectLastWifi()
|
||||
async function wifiScan()
|
||||
async function startRun()
|
||||
async function testYanghao()
|
||||
async function testComment()
|
||||
async function stopRun()
|
||||
async function pollLogs()
|
||||
async function pollReservations()
|
||||
async function pollHighValueRooms()
|
||||
async function pollStats()
|
||||
function startPolling()
|
||||
function startStatsPolling()
|
||||
```
|
||||
|
||||
Keep `DOMContentLoaded` event wiring in `app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved runtime declarations.
|
||||
|
||||
- [ ] **Step 3: Load `runtime_actions.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/runtime_actions.js?v=console-20260531-split-7"></script>
|
||||
<script src="app.js?v=console-20260531-split-7"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `runtime_actions.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. In browser, click refresh devices, load config, start/stop if safe, refresh action log, and switch through all panels.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/runtime_actions.js
|
||||
git commit -m "refactor(webui): extract runtime actions and polling"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 9: Reduce `app.js` to Initialization Glue
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/ui_init.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Move UI initialization helpers**
|
||||
|
||||
Move these functions into `webui/js/ui_init.js`:
|
||||
|
||||
```javascript
|
||||
function initTheme()
|
||||
function ensureToastContainer()
|
||||
function toast(message, kind = "info", { duration = 3500 } = {})
|
||||
function initConfigSearch()
|
||||
function initFooter()
|
||||
function attachCopyButtons()
|
||||
function initKeyboardShortcuts()
|
||||
function initHeaderScroll()
|
||||
function initShotFullscreen()
|
||||
function applyKbdHints()
|
||||
function initStickySectionShadow()
|
||||
function initShortcutsHelp()
|
||||
function updateTabBadge(target, count)
|
||||
function startReservationsCountdownTick()
|
||||
function initTabs()
|
||||
function attachNumberSteppers()
|
||||
function pollShot()
|
||||
function startShotPolling()
|
||||
function setButtonBusy(id, busy)
|
||||
function setRunOverview(state, meta, tone)
|
||||
function updateDeviceOverview()
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Keep `app.js` as bootstrapping only**
|
||||
|
||||
After this task, `app.js` should contain:
|
||||
|
||||
```javascript
|
||||
window.addEventListener("DOMContentLoaded", async () => {
|
||||
initTheme();
|
||||
initTabs();
|
||||
initConfigSearch();
|
||||
initFooter();
|
||||
attachCopyButtons();
|
||||
initShotFullscreen();
|
||||
initHeaderScroll();
|
||||
initKeyboardShortcuts();
|
||||
initShortcutsHelp();
|
||||
initStickySectionShadow();
|
||||
attachNumberSteppers();
|
||||
applyKbdHints();
|
||||
syncMirrorFields();
|
||||
await refreshDevices();
|
||||
await loadConfig();
|
||||
startPolling();
|
||||
startStatsPolling();
|
||||
startShotPolling();
|
||||
startReservationsCountdownTick();
|
||||
pollLogs();
|
||||
pollStats();
|
||||
pollShot();
|
||||
pollReservations();
|
||||
pollHighValueRooms();
|
||||
});
|
||||
```
|
||||
|
||||
During implementation, preserve the existing event listener bindings from the current `DOMContentLoaded` body. If the current body wires buttons or inputs, keep those bindings in `app.js` or move them into a clearly named `bindAppEvents()` function in `ui_init.js`.
|
||||
|
||||
- [ ] **Step 3: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. Browser smoke must cover initial load, tabs, theme, footer, shortcuts overlay, screenshot preview, logs, and config load/save.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/ui_init.js
|
||||
git commit -m "refactor(webui): reduce app script to initialization glue"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 10: Split CSS Tokens and Base Rules
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/tokens.css`
|
||||
- Create: `webui/css/base.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract theme tokens**
|
||||
|
||||
Move these ranges from `styles.css` into `webui/css/tokens.css`:
|
||||
|
||||
- `:root { ... }` light theme token block
|
||||
- `:root[data-theme="dark"] { ... }` dark theme token block
|
||||
- reduced-motion token or global animation defaults that are pure variables
|
||||
|
||||
Do not rename variables.
|
||||
|
||||
- [ ] **Step 2: Extract base element rules**
|
||||
|
||||
Move base reset and generic element rules into `webui/css/base.css`:
|
||||
|
||||
- `*`, `html`, `body`
|
||||
- `button`, `input`, `select`, `textarea`
|
||||
- generic focus-visible rules
|
||||
- global scrollbar rules
|
||||
- generic utility classes that are not tied to one panel
|
||||
|
||||
- [ ] **Step 3: Load extracted CSS before `styles.css`**
|
||||
|
||||
```html
|
||||
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-1" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-1" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-1" />
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run CSS verification commands. Browser smoke must compare light and dark theme basics, header, buttons, forms, and scrollbars.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/tokens.css webui/css/base.css
|
||||
git commit -m "refactor(webui): extract CSS tokens and base rules"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 11: Split CSS Layout and Shared Components
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/layout.css`
|
||||
- Create: `webui/css/components.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract layout rules**
|
||||
|
||||
Move app shell, header, workspace, panel grid, and footer layout rules into `layout.css`. Include responsive `@media` rules that only affect those layout selectors.
|
||||
|
||||
- [ ] **Step 2: Extract shared component rules**
|
||||
|
||||
Move shared button, card, tab, field, table, tooltip, toast, skeleton, and shortcut overlay rules into `components.css`. Include related `@media` and `prefers-reduced-motion` blocks when they directly belong to those selectors.
|
||||
|
||||
- [ ] **Step 3: Load CSS in stable order**
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-2" />
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run CSS verification. Browser smoke must check desktop and mobile layout, tabs, cards, buttons, toast, tooltip, and shortcuts overlay.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/layout.css webui/css/components.css
|
||||
git commit -m "refactor(webui): extract CSS layout and shared components"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 12: Split CSS Feature Panels
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/panels.css`
|
||||
- Create: `webui/css/logs.css`
|
||||
- Create: `webui/css/charts.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract panel-specific styles**
|
||||
|
||||
Move screenshot preview, reservations, high-value room, realtime status, and panel-specific content rules into `panels.css`.
|
||||
|
||||
- [ ] **Step 2: Extract log styles**
|
||||
|
||||
Move run log, action log, log line classification, log search, and log scrollbar rules into `logs.css`.
|
||||
|
||||
- [ ] **Step 3: Extract chart/table styles**
|
||||
|
||||
Move chart blocks, timeline tooltip, bar rows, top content table, wins table, and related table rows into `charts.css`.
|
||||
|
||||
- [ ] **Step 4: Load CSS in stable order**
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/panels.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/logs.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/charts.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-3" />
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Verify and smoke**
|
||||
|
||||
Run CSS verification. Browser smoke must check screenshot preview, reservations, high-value room list, log panels, charts, and mobile wrapping.
|
||||
|
||||
- [ ] **Step 6: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/panels.css webui/css/logs.css webui/css/charts.css
|
||||
git commit -m "refactor(webui): extract CSS feature panels"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 13: Decide Whether to Split `index.html`
|
||||
|
||||
**Files:**
|
||||
- Modify: `webui/index.html`
|
||||
- Optional create: `webui/partials/README.md`
|
||||
|
||||
- [ ] **Step 1: Recount file sizes**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Keep `index.html` intact unless it is still above 1000 lines**
|
||||
|
||||
If `index.html` is at or below 1000 lines, do not split it in this plan. HTML partial loading would require server or build changes and is not needed yet.
|
||||
|
||||
If `index.html` remains above 1000 lines and the team wants smaller HTML files, write a separate spec before changing runtime behavior. That spec must choose one of:
|
||||
|
||||
- server-side partial injection in `gui/web_gui.py`
|
||||
- client-side fetch of static partials
|
||||
- build-time HTML generation
|
||||
|
||||
- [ ] **Step 3: Commit only if docs are added**
|
||||
|
||||
If `webui/partials/README.md` is created:
|
||||
|
||||
```powershell
|
||||
git add webui/partials/README.md
|
||||
git commit -m "docs(webui): record HTML partial split decision"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 14: Split `gui/web_gui.py` Only After Frontend Is Stable
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/web_gui_pkg/static_handler.py`
|
||||
- Create: `gui/web_gui_pkg/request_parsing.py`
|
||||
- Create: `gui/web_gui_pkg/routes.py`
|
||||
- Modify: `gui/web_gui.py`
|
||||
- Test: `tests/test_webgui.py`
|
||||
|
||||
- [ ] **Step 1: Extract request parsing helpers**
|
||||
|
||||
Move `_send_json` and `_read_json` behavior into functions that still receive the `Handler` instance:
|
||||
|
||||
```python
|
||||
def send_json(handler: BaseHTTPRequestHandler, obj: object, status: int = 200) -> None:
|
||||
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
```
|
||||
|
||||
```python
|
||||
def read_json(handler: BaseHTTPRequestHandler) -> dict:
|
||||
n = int(handler.headers.get("Content-Length") or 0)
|
||||
raw = handler.rfile.read(n) if n > 0 else b"{}"
|
||||
try:
|
||||
value = json.loads(raw.decode("utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
return value if isinstance(value, dict) else {}
|
||||
```
|
||||
|
||||
Keep `Handler._send_json` and `Handler._read_json` as thin wrappers at first.
|
||||
|
||||
- [ ] **Step 2: Extract static file serving**
|
||||
|
||||
Move `_serve_static` into `gui/web_gui_pkg/static_handler.py`:
|
||||
|
||||
```python
|
||||
def serve_static(
|
||||
handler: BaseHTTPRequestHandler,
|
||||
*,
|
||||
webui_dir: str,
|
||||
rel_path: str,
|
||||
log_error: Callable[[str], None],
|
||||
) -> None:
|
||||
# paste current Handler._serve_static body and replace:
|
||||
# self -> handler
|
||||
# WEBUI_DIR -> webui_dir
|
||||
# _wg_log(...) -> log_error(...)
|
||||
```
|
||||
|
||||
Keep `Handler._serve_static` as:
|
||||
|
||||
```python
|
||||
def _serve_static(self, rel_path: str) -> None:
|
||||
serve_static(
|
||||
self,
|
||||
webui_dir=WEBUI_DIR,
|
||||
rel_path=rel_path,
|
||||
log_error=lambda msg: _wg_log(msg, level="ERROR"),
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py > logs\web_gui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py -q > logs\pytest_web_gui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py tests/test_webgui.py
|
||||
git commit -m "refactor(webgui): extract request and static helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 15: Final Outcome Note
|
||||
|
||||
**Files:**
|
||||
- Modify: this plan file
|
||||
|
||||
- [ ] **Step 1: Record final sizes**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Append outcome**
|
||||
|
||||
Append:
|
||||
|
||||
```markdown
|
||||
## Outcome
|
||||
|
||||
- `webui/app.js`: 2512 -> actual final line count
|
||||
- `webui/styles.css`: 3745 -> actual final line count
|
||||
- `webui/index.html`: 1232 -> actual final line count
|
||||
- `gui/web_gui.py`: 1663 -> actual final line count
|
||||
- Extracted JS modules: actual module filenames
|
||||
- Extracted CSS modules: actual module filenames
|
||||
- Verification: exact pytest log path and browser smoke result
|
||||
- Remaining large files: actual top remaining files from the final size command
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add docs/superpowers/plans/2026-05-31-split-webui-large-files.md
|
||||
git commit -m "docs(webui): record large-file split outcome"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Execution Notes
|
||||
|
||||
- Do not batch tasks. Each task must pass verification, commit, and push before starting the next one.
|
||||
- Keep query-string versions in `index.html` synchronized across all WebUI assets touched in a task.
|
||||
- Do not introduce a frontend build step in this plan.
|
||||
- Do not convert to ES modules until the classic-script split is complete and browser smoke is clean.
|
||||
- For JavaScript moves, copy exact function bodies first, verify, then optionally do tiny cleanup in a separate commit.
|
||||
- For CSS moves, preserve selector order unless the moved file load order proves an equivalent cascade.
|
||||
- Project rule: only stage files changed by the current task.
|
||||
@@ -144,3 +144,101 @@ P2 视 P1 完成后情况评估(如果 P1 已经把主文件压到很小,P2
|
||||
- `douyin/core/*` 几个 1000+ 行业务文件 —— 下一轮独立 spec
|
||||
- 引入新的 GUI 框架或异步模式
|
||||
- 单元测试覆盖率提升
|
||||
|
||||
## Outcome(2026-05-30 实施完成)
|
||||
|
||||
**起始**:5476 行
|
||||
**结束**:178 行
|
||||
**降幅**:5298 行(-96.7%)
|
||||
**新增模块**:54 个 component 文件
|
||||
|
||||
### 主文件最终结构(178 行)
|
||||
|
||||
```
|
||||
imports 45 行 (gui_core / 14 个 components / stdlib)
|
||||
warnings 抑制 / format_gui_log_line 18 行
|
||||
def main(): ~115 行
|
||||
setup_root_window
|
||||
setup_log_pipeline ← (queue + ThreadSafeLogWriter + on_line + Runner)
|
||||
setup_top_device_bar ← (设备选择 + WiFi 工具)
|
||||
build_config_vars ← (127 个 tk Var)
|
||||
setup_left_config_area ← (PanedWindow + 7 配置 Tab + load/save IO)
|
||||
setup_right_main_area ← (Notebook + 9 Tab + actions + pump_logs)
|
||||
setup_top_buttons ← (保存配置 + 截图+OCR)
|
||||
setup_periodic_refreshers ← (启动延迟 + 周期刷新)
|
||||
setup_close_handler ← (WM_DELETE_WINDOW)
|
||||
refresh_devices() / mainloop()
|
||||
```
|
||||
|
||||
### 抽取阶段总结
|
||||
|
||||
实施分 4 个阶段:
|
||||
|
||||
**阶段 1:闭包/视图抽取(5476 → 3590 行,-34%)**
|
||||
|
||||
把 `main()` 内的内聚闭包和视图刷新函数抽到独立模块。共 17 个模块:
|
||||
wifi_adb_scan_dialog / wifi_adb_dialog / reservations_view / high_value_view /
|
||||
screenshot_action / actions_log_view / wifi_adb_pick_dialog / wifi_adb_reconnect /
|
||||
ocr_results_view / log_pump / win_record_view / preview_view /
|
||||
wifi_adb_one_click_scan / run_log_view / text_search /
|
||||
logging_config_io / run_params_builder。
|
||||
|
||||
**阶段 2:Var 聚合 + Tab UI(3590 → 1373 行,-44% → -75%)**
|
||||
|
||||
- `config_io.py`(load/save 640 行 → 1 个模块)用 dict-of-vars 模式
|
||||
- `build_config_vars()` 工厂集中创建 127 个 tk Var
|
||||
- 7 个 Tab UI(debug / logging / yanghao / reservation / run / filter / realtime)抽
|
||||
到独立 `setup_*_tab(parent, vars_=_vars_)`,直接接受 vars 全集
|
||||
|
||||
**阶段 3:右侧 Tab + 工具栏 + 模板复用(1373 → 519 行,-75% → -90.5%)**
|
||||
|
||||
- log_search_toolbar / actions_log_toolbar 用 dataclass + handles 返回
|
||||
- win_record_tab / preview_tab / log_tab 整段抽出
|
||||
- simple_tabs.py 提供 setup_simple_text_tab / setup_text_tab_with_refresh /
|
||||
setup_stats_tab / setup_actions_log_tab / setup_ocr_results_tab 复用模板
|
||||
- main_notebook / action_buttons / top_buttons / top_device_bar /
|
||||
log_pipeline / periodic_refreshers / log_text_colors / keywords_tab 全部抽出
|
||||
|
||||
**阶段 4:聚合层 + 死代码清理(519 → 178 行,-90.5% → -96.7%)**
|
||||
|
||||
最后阶段把 main() 里剩余的"装配脉络"打包成更高层组件,清理失效的导入和死注释:
|
||||
|
||||
- `setup_root_window`: ttkbootstrap fallback + root window
|
||||
- `setup_left_config_area`: PanedWindow 布局 + 7 配置 Tab + load/save IO
|
||||
- `setup_right_main_area`: Notebook + 9 Tab + actions + pump_logs
|
||||
- 删除 125 个无用的 _vars_ unpack(只保留 y_var/gui_theme_var)
|
||||
- 死注释清理 / 重复 import / 冗余 dict 字面量(_config_io_vars 复用 _vars_ 全集)
|
||||
- 重复 lambda 去重(theme_getter / _open_realtime_viewer)
|
||||
|
||||
### 抽取模式(54 个 components 按用途分类)
|
||||
|
||||
| 类型 | 模块 |
|
||||
|---|---|
|
||||
| WiFi ADB(6 个) | wifi_adb_scan_dialog / wifi_adb_dialog / wifi_adb_pick_dialog / wifi_adb_reconnect / wifi_adb_one_click_scan / top_device_bar |
|
||||
| Tab 视图(8 个) | reservations_view / high_value_view / actions_log_view / ocr_results_view / win_record_view / preview_view / run_log_view / log_pump |
|
||||
| Tab UI 容器(13 个) | run_tab / filter_tab / reservation_tab / yanghao_tab / debug_tab / logging_tab / keywords_tab / log_tab / preview_tab / win_record_tab / realtime_tab / simple_tabs / main_notebook |
|
||||
| 工具栏(2 个) | log_search_toolbar / actions_log_toolbar |
|
||||
| 配色 / 状态(3 个) | log_text_colors / text_search / screenshot_action |
|
||||
| 配置序列化(4 个) | logging_config_io / run_params_builder / config_io / config_vars |
|
||||
| 顶部 / 底部按钮(2 个) | top_buttons / action_buttons |
|
||||
| 系统调度(2 个) | log_pipeline / periodic_refreshers |
|
||||
| 高层聚合(3 个) | root_window / left_config_area / right_main_area |
|
||||
| 已有共用(11 个) | log_writer / log_viewer / log_color_config / mapping_table / mapping_utils / device_selector / actions_log_viewer / error_log_viewer / realtime_viewer / stats_formatter / __init__ |
|
||||
|
||||
### 验证
|
||||
|
||||
- 每轮抽取后 `pytest` 全绿(1374 passed),包括 `test_gui_app_smoke.py` 启动 smoke 和
|
||||
`test_gui_webui_sync.py` GUI/WebUI 配置 key 同步检查。
|
||||
- 共 7 次 pytest 失败均能定位修复(具体错误参见各次 commit message):
|
||||
- `_preview_view` 在 `update_image_list` 之前被引用
|
||||
- `enable_ocr_mode1_var` 因含数字未被正则替换(2 次)
|
||||
- `BOTH` 常量 / `ScrolledText` import 缺失
|
||||
- sync 工具锚点失效 → 让工具改读 `config_io.py` + `realtime_tab.py`
|
||||
- `image_var` 在 `setup_top_buttons` 调用时还没创建 → 调整顺序
|
||||
- 未做手工 GUI smoke(建议用户启动 GUI 走一遍 WiFi 对话框 / 各 Tab,确认无回归)。
|
||||
|
||||
### 停止原因
|
||||
|
||||
主文件已从 5476 → 178(-96.7%)。当前 main() 是清晰的"装配胶水":每个 setup_*
|
||||
调用对应一个明确的功能区。继续抽要么打散这个装配脉络,要么把整个 main 改造成
|
||||
`GuiApp` 类(MVC/MVVM),都属于另一个 spec。`pytest` 1374 全绿。
|
||||
@@ -0,0 +1,80 @@
|
||||
"""底部操作按钮区(开始运行 / 停止 / 强制停止 / 发送返回键 / 状态标签)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的 widget 创建段 + 4 个按钮回调
|
||||
(``start_run`` / ``stop_run`` / ``force_stop_run`` / ``send_back_key``)。
|
||||
|
||||
依赖通过显式参数注入。状态写回主线程通过 ``status_var`` 实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, RIGHT, X
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def setup_action_buttons(
|
||||
actions: ttk.Frame,
|
||||
*,
|
||||
runner: Any,
|
||||
status_var: tk.StringVar,
|
||||
device_var: tk.StringVar,
|
||||
on_line: Callable[[str], None],
|
||||
save_ui_to_config: Callable[[], None],
|
||||
get_params: Callable[[], Any],
|
||||
) -> None:
|
||||
"""构建底部操作按钮区(开始/停止/强制停止/发送返回键 + 状态标签)。"""
|
||||
|
||||
def start_run() -> None:
|
||||
if runner.is_running():
|
||||
on_line("[运行] 已在运行中")
|
||||
return
|
||||
save_ui_to_config()
|
||||
params = get_params()
|
||||
|
||||
wait_display = "∞" if params.wait_minutes == 0 else f"{params.wait_minutes}m"
|
||||
on_line(
|
||||
f"[运行] 启动:device={params.device_id or '(auto)'} y={params.y_pianyi} "
|
||||
f"needswitch={params.needswitch} wait={wait_display} "
|
||||
f"skip_gt={params.skip_if_countdown_gt_seconds}s reset_after_enabled={params.reset_after_swipes_enabled} reset_after={params.reset_after_swipes} "
|
||||
f"value>={params.min_prize_value_yuan} participants=[{params.min_participants},{params.max_participants}] "
|
||||
f"high_value_revisit={params.high_value_room_revisit_enabled} reservation_verify={params.reservation_back_verify_enabled} "
|
||||
f"fudai_find_max={params.fudai_find_max_attempts} yanghao=recommend_flow_only"
|
||||
)
|
||||
status_var.set("运行中")
|
||||
try:
|
||||
runner.start(params)
|
||||
except Exception as e:
|
||||
status_var.set("启动失败")
|
||||
on_line(f"[错误] {e}")
|
||||
|
||||
def stop_run() -> None:
|
||||
runner.stop()
|
||||
status_var.set("已停止")
|
||||
|
||||
def force_stop_run() -> None:
|
||||
"""强制终止后台进程(包括可能残留的子进程)。"""
|
||||
runner.force_stop()
|
||||
status_var.set("已停止(强制)")
|
||||
|
||||
def send_back_key() -> None:
|
||||
dev = device_var.get().strip()
|
||||
try:
|
||||
runner.send_back_key(dev)
|
||||
except Exception as e:
|
||||
on_line(f"[错误] 发送返回键失败: {e}")
|
||||
|
||||
ttk.Button(actions, text="开始运行", command=start_run).pack(side=LEFT, padx=(0, 8))
|
||||
ttk.Button(actions, text="停止", command=stop_run).pack(side=LEFT, padx=(0, 4))
|
||||
ttk.Button(actions, text="强制停止", command=force_stop_run).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
# (已移除:测试养号/测试评论 按钮与相关UI)
|
||||
|
||||
ttk.Button(actions, text="发送返回键", command=send_back_key).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
ttk.Label(actions, textvariable=status_var).pack(side=RIGHT)
|
||||
@@ -0,0 +1,133 @@
|
||||
"""行为日志 Tab 的工具栏(关键字筛选 + 文本搜索)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的搜索栏 widget 创建段 +
|
||||
配色配置 + 4 个共享 ``nonlocal`` matches state 的搜索闭包。
|
||||
|
||||
抽出后用一个 ``ActionsLogToolbarHandles`` 暴露 ``main()`` 仍要用的引用:
|
||||
- ``refresh_actions_log`` - 刷新回调(被 root.after 调度用)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X, Y
|
||||
from typing import Callable
|
||||
|
||||
from gui.components.actions_log_view import (
|
||||
configure_actions_log_colors as _configure_actions_log_colors_impl,
|
||||
refresh_actions_log as _refresh_actions_log_impl,
|
||||
)
|
||||
from gui.components.text_search import generic_search_widget
|
||||
|
||||
|
||||
@dataclass
|
||||
class ActionsLogToolbarHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
refresh_actions_log: Callable[[], None]
|
||||
|
||||
|
||||
def setup_actions_log_toolbar(
|
||||
parent: tk.Misc,
|
||||
*,
|
||||
actions_log_text: tk.Text,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> ActionsLogToolbarHandles:
|
||||
"""构建行为日志 Tab 顶部的工具栏(配色 + 关键字筛选 + 文本搜索)。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - 工具栏父容器(``actions_log_top``)
|
||||
- ``actions_log_text`` - 行为日志文本 widget
|
||||
- ``theme_getter`` - ``() -> str`` 返回当前 GUI 主题名
|
||||
"""
|
||||
# 配置行为日志颜色标签(使用统一的颜色配置模块)
|
||||
def configure_actions_log_colors() -> None:
|
||||
_configure_actions_log_colors_impl(
|
||||
actions_log_text,
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
|
||||
# 初始配置
|
||||
configure_actions_log_colors()
|
||||
|
||||
actions_filter_var = tk.StringVar(value="")
|
||||
|
||||
def refresh_actions_log() -> None:
|
||||
_refresh_actions_log_impl(
|
||||
actions_log_text,
|
||||
theme_getter=theme_getter,
|
||||
filter_getter=lambda: actions_filter_var.get().strip(),
|
||||
)
|
||||
|
||||
ttk.Label(parent, text="关键字筛选:").pack(side=LEFT)
|
||||
ttk.Entry(parent, textvariable=actions_filter_var, width=16).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Button(parent, text="刷新", command=refresh_actions_log).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
|
||||
# 行为日志搜索功能
|
||||
ttk.Separator(parent, orient="vertical").pack(
|
||||
side=LEFT, fill=Y, padx=5, pady=3
|
||||
)
|
||||
ttk.Label(parent, text="搜索:").pack(side=LEFT)
|
||||
|
||||
actions_search_var = tk.StringVar(value="")
|
||||
actions_search_entry = ttk.Entry(
|
||||
parent, textvariable=actions_search_var, width=20
|
||||
)
|
||||
actions_search_entry.pack(side=LEFT, padx=(0, 5))
|
||||
|
||||
state = {
|
||||
"matches": [],
|
||||
"current_index": -1,
|
||||
}
|
||||
|
||||
def search_in_actions_log(direction: int = 1) -> None:
|
||||
"""在行为日志中搜索文本(使用通用搜索实现)"""
|
||||
state["current_index"] = generic_search_widget(
|
||||
actions_log_text,
|
||||
actions_search_var,
|
||||
state["matches"],
|
||||
state["current_index"],
|
||||
direction,
|
||||
)
|
||||
|
||||
def search_next_in_actions() -> None:
|
||||
search_in_actions_log(1)
|
||||
|
||||
def search_prev_in_actions() -> None:
|
||||
search_in_actions_log(-1)
|
||||
|
||||
def clear_search_in_actions() -> None:
|
||||
actions_search_var.set("")
|
||||
actions_log_text.tag_remove("search_highlight", "1.0", "end")
|
||||
actions_log_text.tag_remove("search_current", "1.0", "end")
|
||||
state["matches"] = []
|
||||
state["current_index"] = -1
|
||||
|
||||
def on_actions_search_entry_key(event):
|
||||
if event.keysym == "Return":
|
||||
search_next_in_actions()
|
||||
|
||||
actions_search_entry.bind("<KeyPress>", on_actions_search_entry_key)
|
||||
|
||||
ttk.Button(parent, text="搜索", command=search_next_in_actions).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(parent, text="上一个", command=search_prev_in_actions).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(parent, text="下一个", command=search_next_in_actions).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(parent, text="清除", command=clear_search_in_actions).pack(
|
||||
side=LEFT
|
||||
)
|
||||
|
||||
return ActionsLogToolbarHandles(
|
||||
refresh_actions_log=refresh_actions_log,
|
||||
)
|
||||
@@ -0,0 +1,183 @@
|
||||
"""行为日志(``logs/actions.log``) Tab 的视图刷新与配色逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的两个闭包
|
||||
``configure_actions_log_colors`` 和 ``refresh_actions_log``,
|
||||
搜索相关的小闭包仍保留在 ``gui_app.py`` 中(它们共享 nonlocal 状态)。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``text_widget`` - 展示用的 Text/ScrolledText
|
||||
- ``theme_getter`` - 一个 ``() -> str`` 回调,返回当前 GUI 主题名
|
||||
- ``filter_getter`` - 一个 ``() -> str`` 回调,返回筛选关键字(已 strip)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
try:
|
||||
from gui.components.log_color_config import (
|
||||
apply_operation_color,
|
||||
get_color_config,
|
||||
)
|
||||
except ImportError:
|
||||
def get_color_config(theme: str = "litera"): # type: ignore[no-redef]
|
||||
return {}
|
||||
|
||||
def apply_operation_color(*args, **kwargs): # type: ignore[no-redef]
|
||||
pass
|
||||
|
||||
|
||||
def configure_actions_log_colors(
|
||||
text_widget: tk.Text,
|
||||
*,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> None:
|
||||
"""根据当前主题配置行为日志的颜色标签"""
|
||||
try:
|
||||
# 获取当前主题
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
# 获取颜色配置
|
||||
color_config = get_color_config(current_theme)
|
||||
|
||||
# 根据主题设置背景和前景色
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
is_light = current_theme.lower() in light_themes
|
||||
if is_light:
|
||||
text_widget.configure(
|
||||
background="#FFFFFF",
|
||||
foreground="#2C2C2C",
|
||||
insertbackground="#2C2C2C",
|
||||
)
|
||||
else:
|
||||
text_widget.configure(
|
||||
background="#1E1E1E",
|
||||
foreground="#E0E0E0",
|
||||
insertbackground="#FFFFFF",
|
||||
)
|
||||
|
||||
# 为所有操作类型配置标签
|
||||
for op_type, colors in color_config.items():
|
||||
tag_name = f"op_{op_type}"
|
||||
try:
|
||||
text_widget.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略标签配置失败
|
||||
except Exception:
|
||||
pass # 忽略颜色配置失败
|
||||
|
||||
|
||||
def refresh_actions_log(
|
||||
text_widget: tk.Text,
|
||||
*,
|
||||
theme_getter: Callable[[], str],
|
||||
filter_getter: Callable[[], str],
|
||||
) -> None:
|
||||
"""读取 logs/actions.log 的尾部若干行,在 GUI 中展示关键行为日志(支持简单关键字筛选)。"""
|
||||
# 使用统一的路径配置
|
||||
try:
|
||||
from douyin.core.path_config import get_actions_log_path
|
||||
|
||||
path = get_actions_log_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
# 修正路径:GUI应该读取根目录的logs/actions.log
|
||||
from douyin.core import path_config
|
||||
|
||||
path = path_config.get_actions_log_path()
|
||||
try:
|
||||
if os.path.exists(path):
|
||||
# 仿照 web_gui 的实现:只读最后一小段,避免文件巨大
|
||||
size = os.path.getsize(path)
|
||||
if size == 0:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", "行为日志文件为空")
|
||||
return
|
||||
|
||||
read_bytes = min(size, 65536)
|
||||
with open(path, "rb") as f:
|
||||
if read_bytes < size:
|
||||
f.seek(-read_bytes, os.SEEK_END)
|
||||
data = f.read()
|
||||
# 尝试多种编码方式
|
||||
try:
|
||||
# 先尝试 utf-8-sig(带BOM)
|
||||
text = data.decode("utf-8-sig", errors="replace")
|
||||
except Exception:
|
||||
try:
|
||||
# 再尝试 utf-8
|
||||
text = data.decode("utf-8", errors="replace")
|
||||
except Exception:
|
||||
# 最后尝试 gbk(Windows常见编码)
|
||||
text = data.decode("gbk", errors="replace")
|
||||
lines = text.splitlines()
|
||||
# 只取最近 300 行
|
||||
tail = lines[-300:]
|
||||
|
||||
# 关键字筛选:若填写了筛选词,只保留包含该关键字的行
|
||||
kw = filter_getter()
|
||||
if kw:
|
||||
tail = [ln for ln in tail if kw in ln]
|
||||
|
||||
# 保存当前滚动位置,避免刷新时自动置顶
|
||||
try:
|
||||
scroll_position = text_widget.yview()[
|
||||
0
|
||||
] # 获取当前滚动位置(顶部可见位置的比例)
|
||||
except Exception:
|
||||
scroll_position = 0.0
|
||||
|
||||
text_widget.delete("1.0", "end")
|
||||
if tail:
|
||||
# 获取当前主题(用于颜色配置)
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
# 逐行插入并应用颜色标签
|
||||
for i, line in enumerate(tail):
|
||||
start_pos = text_widget.index("end-1c")
|
||||
|
||||
# 插入行内容
|
||||
if i > 0:
|
||||
text_widget.insert("end", "\n")
|
||||
text_widget.insert("end", line)
|
||||
|
||||
# 使用统一的颜色配置模块应用颜色
|
||||
end_pos = text_widget.index("end")
|
||||
try:
|
||||
apply_operation_color(
|
||||
text_widget,
|
||||
start_pos,
|
||||
end_pos,
|
||||
line,
|
||||
current_theme,
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略颜色应用失败
|
||||
else:
|
||||
text_widget.insert("1.0", "暂无匹配的行为日志")
|
||||
|
||||
# 恢复之前的滚动位置,避免自动置顶
|
||||
try:
|
||||
text_widget.yview_moveto(scroll_position)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert(
|
||||
"1.0", "暂无行为日志(logs/actions.log 不存在)"
|
||||
)
|
||||
except Exception as e:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", f"读取行为日志失败:{e}")
|
||||
@@ -0,0 +1,678 @@
|
||||
"""GUI 配置序列化:从 config.json 加载 → tk Vars,以及 Vars → config.json 保存。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的两个闭包
|
||||
``load_config_to_ui`` 和 ``save_ui_to_config``,共依赖 122 个 tk Var 和 5 个 Text widget。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``vars_`` - 一个名→Var 的 ``Dict[str, tk.Variable]``,键名与原 main() 中的变量名一致
|
||||
- ``texts_`` - 一个名→Text widget 的 ``Dict[str, tk.Text]``(want_text/not_want_text 等)
|
||||
- ``read_config`` - 读配置回调
|
||||
- ``write_config`` - 写配置回调
|
||||
- ``on_line`` - 日志回调
|
||||
|
||||
``load_config_to_ui`` 把 ``cfg`` 当作 nonlocal 变量原地赋值,这里改为返回新 cfg 让调用方更新。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Callable, Dict
|
||||
|
||||
|
||||
def load_config_to_ui(
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
texts_: Dict[str, tk.Text],
|
||||
read_config: Callable[[], dict],
|
||||
) -> dict:
|
||||
cfg = read_config()
|
||||
vars_["needswitch_var"].set(bool(cfg.get("needswitch", True)))
|
||||
vars_["infinite_loop_var"].set(bool(cfg.get("infinite_loop_enabled", False)))
|
||||
vars_["wait_minutes_var"].set(int(cfg.get("wait_minutes", 5) or 5))
|
||||
vars_["yg_enabled_var"].set(bool(cfg.get("yanghao_enabled", True)))
|
||||
vars_["yg_actions_enabled_var"].set(bool(cfg.get("yanghao_enable_actions", True)))
|
||||
vars_["yg_only_var"].set(bool(cfg.get("yanghao_only", False)))
|
||||
vars_["yg_recommend_duration_var"].set(
|
||||
int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
|
||||
)
|
||||
vars_["yg_recommend_interval_var"].set(
|
||||
int(cfg.get("yanghao_recommend_interval_seconds", 0) or 0)
|
||||
)
|
||||
vars_["min_value_var"].set(float(cfg.get("min_prize_value_yuan", 0) or 0))
|
||||
vars_["min_participants_var"].set(int(cfg.get("min_participants", 0) or 0))
|
||||
vars_["max_participants_var"].set(int(cfg.get("max_participants", 0) or 0))
|
||||
vars_["skip_gt_seconds_var"].set(
|
||||
int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
|
||||
)
|
||||
vars_["reset_after_swipes_enabled_var"].set(
|
||||
bool(cfg.get("reset_after_swipes_enabled", False))
|
||||
)
|
||||
vars_["reset_after_swipes_var"].set(int(cfg.get("reset_after_swipes", 10) or 10))
|
||||
vars_["reset_after_swipes_action_var"].set(
|
||||
str(cfg.get("reset_after_swipes_action", "swipe") or "swipe")
|
||||
)
|
||||
vars_["enable_back_on_misses_var"].set(bool(cfg.get("enable_back_on_misses", True)))
|
||||
vars_["swipe_down_back_enabled_var"].set(
|
||||
bool(cfg.get("swipe_down_back_enabled", False))
|
||||
)
|
||||
vars_["swipe_down_back_count_var"].set(int(cfg.get("swipe_down_back_count", 3) or 3))
|
||||
vars_["auto_join_var"].set(bool(cfg.get("auto_join_fansclub", False)))
|
||||
vars_["fansclub_action_var"].set(
|
||||
str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()
|
||||
)
|
||||
vars_["streaming_enabled_var"].set(bool(cfg.get("enable_streaming_screenshot", True)))
|
||||
vars_["lucky_draw_red_ratio_threshold_var"].set(
|
||||
float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
|
||||
)
|
||||
vars_["y_var"].set(int(cfg.get("y_pianyi", 0) or 0))
|
||||
|
||||
# Web端新增配置 - 高价值预约相关
|
||||
vars_["high_value_fudai_enabled_var"].set(
|
||||
bool(cfg.get("high_value_fudai_enabled", False))
|
||||
)
|
||||
vars_["high_value_fudai_threshold_yuan_var"].set(
|
||||
float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
|
||||
)
|
||||
vars_["high_value_fudai_join_ahead_seconds_var"].set(
|
||||
int(cfg.get("high_value_fudai_join_ahead_seconds", 300) or 300)
|
||||
)
|
||||
vars_["high_value_fudai_max_swipe_back_var"].set(
|
||||
int(cfg.get("high_value_fudai_max_swipe_back", 60) or 60)
|
||||
)
|
||||
vars_["high_value_fudai_max_reservations_var"].set(
|
||||
int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
|
||||
)
|
||||
vars_["high_value_fudai_after_action_var"].set(
|
||||
str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
|
||||
)
|
||||
vars_["high_value_fudai_poll_before_seconds_var"].set(
|
||||
float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
|
||||
)
|
||||
vars_["high_value_room_revisit_enabled_var"].set(
|
||||
bool(cfg.get("high_value_room_revisit_enabled", True))
|
||||
)
|
||||
vars_["high_value_room_revisit_only_current_run_var"].set(
|
||||
bool(cfg.get("high_value_room_revisit_only_current_run", False))
|
||||
)
|
||||
vars_["high_value_room_revisit_min_interval_seconds_var"].set(
|
||||
int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
|
||||
)
|
||||
vars_["high_value_room_revisit_max_per_run_var"].set(
|
||||
int(cfg.get("high_value_room_revisit_max_per_run", 5))
|
||||
)
|
||||
vars_["high_value_room_revisit_min_prize_value_var"].set(
|
||||
float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
|
||||
)
|
||||
vars_["high_value_room_revisit_max_age_days_var"].set(
|
||||
int(cfg.get("high_value_room_revisit_max_age_days", 30))
|
||||
)
|
||||
vars_["reservation_back_verify_enabled_var"].set(
|
||||
bool(cfg.get("reservation_back_verify_enabled", True))
|
||||
)
|
||||
vars_["reservation_back_swipe_delay_var"].set(
|
||||
float(cfg.get("reservation_back_swipe_delay", 0) or 0)
|
||||
)
|
||||
vars_["reservation_back_verify_wait_seconds_var"].set(
|
||||
float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
vars_["fudai_find_max_attempts_var"].set(int(cfg.get("fudai_find_max_attempts", 0) or 0))
|
||||
vars_["fudai_icon_retry_delay_seconds_var"].set(
|
||||
float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||||
)
|
||||
vars_["fudai_icon_max_wait_seconds_var"].set(
|
||||
float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
vars_["fudai_click_wait_seconds_var"].set(
|
||||
float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0)
|
||||
)
|
||||
vars_["fudai_disable_content_recognition_var"].set(
|
||||
bool(cfg.get("fudai_disable_content_recognition", False))
|
||||
)
|
||||
vars_["fudai_disable_task_recognition_var"].set(
|
||||
bool(cfg.get("fudai_disable_task_recognition", False))
|
||||
)
|
||||
try:
|
||||
vars_["fudai_exit_after_misses_var"].set(
|
||||
int(cfg.get("fudai_exit_after_misses", 30) or 30)
|
||||
)
|
||||
except Exception:
|
||||
vars_["fudai_exit_after_misses_var"].set(30)
|
||||
try:
|
||||
vars_["enable_back_on_misses_var"].set(bool(cfg.get("enable_back_on_misses", True)))
|
||||
except Exception:
|
||||
vars_["enable_back_on_misses_var"].set(True)
|
||||
try:
|
||||
vars_["reset_after_swipes_action_var"].set(
|
||||
str(cfg.get("reset_after_swipes_action", "swipe"))
|
||||
)
|
||||
except Exception:
|
||||
vars_["reset_after_swipes_action_var"].set("swipe")
|
||||
vars_["switch_room_wait_after_stage_diag_seconds_var"].set(
|
||||
float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
|
||||
)
|
||||
# GUI 主题
|
||||
try:
|
||||
vars_["gui_theme_var"].set(
|
||||
str(cfg.get("gui", {}).get("theme", "litera") or "litera")
|
||||
)
|
||||
except Exception:
|
||||
vars_["gui_theme_var"].set("litera")
|
||||
vars_["live_room_match_threshold_var"].set(
|
||||
float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
|
||||
)
|
||||
vars_["swipe_duration_ms_var"].set(int(cfg.get("swipe_duration_ms", 600) or 600))
|
||||
vars_["swipe_up_start_y_var"].set(int(cfg.get("swipe_up_start_y", 1200) or 1200))
|
||||
vars_["swipe_up_end_y_var"].set(int(cfg.get("swipe_up_end_y", 600) or 600))
|
||||
vars_["fudai_quiet_hours_enabled_var"].set(
|
||||
bool(cfg.get("fudai_quiet_hours_enabled", True))
|
||||
)
|
||||
vars_["fudai_quiet_start_hour_var"].set(int(cfg.get("fudai_quiet_start_hour", 2) or 2))
|
||||
vars_["fudai_quiet_end_hour_var"].set(int(cfg.get("fudai_quiet_end_hour", 7) or 7))
|
||||
vars_["stage_diag_max_time_var"].set(float(cfg.get("stage_diag_max_time", 10.0) or 10.0))
|
||||
vars_["stage_diag_max_step_time_var"].set(
|
||||
float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
|
||||
)
|
||||
vars_["stage_diag_verbose_var"].set(
|
||||
bool(cfg.get("logging", {}).get("stage_diag_verbose", True))
|
||||
)
|
||||
vars_["enable_ocr_mode1_var"].set(bool(cfg.get("enable_ocr_mode1", False)))
|
||||
vars_["fudai_template_match_enabled_var"].set(
|
||||
bool(cfg.get("fudai_template_match_enabled", False))
|
||||
)
|
||||
vars_["fudai_template_match_threshold_var"].set(
|
||||
float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
|
||||
)
|
||||
vars_["fudai_detail_template_threshold_var"].set(
|
||||
float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
|
||||
)
|
||||
vars_["coupon_template_match_threshold_var"].set(
|
||||
float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
|
||||
)
|
||||
vars_["attend_button_red_ratio_threshold_var"].set(
|
||||
float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
|
||||
)
|
||||
vars_["fansclub_join_red_ratio_threshold_var"].set(
|
||||
float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
|
||||
)
|
||||
vars_["shopping_redpacket_red_ratio_threshold_var"].set(
|
||||
float(cfg.get("shopping_redpacket_red_ratio_threshold", 0.15) or 0.15)
|
||||
)
|
||||
# 粉丝团等待/点击延迟配置
|
||||
vars_["fansclub_click_delay_var"].set(float(cfg.get("fansclub_click_delay", 0.6) or 0.6))
|
||||
vars_["fansclub_auto_wait_var"].set(
|
||||
float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
vars_["fansclub_manual_wait_var"].set(
|
||||
float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)
|
||||
)
|
||||
vars_["skip_lt_seconds_var"].set(int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10))
|
||||
|
||||
# 调试图像清理配置
|
||||
debug_captures_config = cfg.get("debug_captures", {})
|
||||
if isinstance(debug_captures_config, dict):
|
||||
vars_["debug_captures_enabled_var"].set(
|
||||
bool(debug_captures_config.get("enabled", False))
|
||||
)
|
||||
vars_["debug_captures_auto_cleanup_var"].set(
|
||||
bool(debug_captures_config.get("auto_cleanup", True))
|
||||
)
|
||||
vars_["debug_captures_keep_days_var"].set(
|
||||
int(debug_captures_config.get("keep_days", 7) or 7)
|
||||
)
|
||||
vars_["debug_captures_max_files_var"].set(
|
||||
int(debug_captures_config.get("max_files", 2000) or 2000)
|
||||
)
|
||||
vars_["debug_captures_async_save_var"].set(
|
||||
bool(debug_captures_config.get("async_save", True))
|
||||
)
|
||||
vars_["debug_captures_log_on_complete_var"].set(
|
||||
bool(debug_captures_config.get("log_on_complete", False))
|
||||
)
|
||||
else:
|
||||
vars_["debug_captures_auto_cleanup_var"].set(True)
|
||||
vars_["debug_captures_keep_days_var"].set(7)
|
||||
vars_["debug_captures_max_files_var"].set(2000)
|
||||
|
||||
# 日志配置(load_config_to_ui 需要覆盖 UI 变量,避免“保存后再加载不生效”)
|
||||
logging_config = cfg.get("logging", {})
|
||||
if isinstance(logging_config, dict):
|
||||
vars_["logging_beautify_var"].set(bool(logging_config.get("beautify_output", True)))
|
||||
vars_["logging_color_var"].set(bool(logging_config.get("color_output", True)))
|
||||
vars_["logging_show_timestamps_var"].set(
|
||||
bool(logging_config.get("show_timestamps", True))
|
||||
)
|
||||
vars_["logging_use_dated_logs_var"].set(
|
||||
bool(logging_config.get("use_dated_logs", True))
|
||||
)
|
||||
vars_["logging_enable_monitor_var"].set(
|
||||
bool(logging_config.get("enable_monitor", True))
|
||||
)
|
||||
vars_["log_unified_enabled_var"].set(bool(cfg.get("log_unified_enabled", True)))
|
||||
vars_["log_unified_path_var"].set(
|
||||
str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log")
|
||||
)
|
||||
vars_["logging_keep_days_var"].set(int(logging_config.get("keep_days", 30) or 30))
|
||||
vars_["logging_compress_logs_var"].set(
|
||||
bool(logging_config.get("compress_logs", True))
|
||||
)
|
||||
vars_["logging_max_total_size_gb_var"].set(
|
||||
float(logging_config.get("max_total_size_gb", 10.0) or 10.0)
|
||||
)
|
||||
vars_["logging_compress_after_days_var"].set(
|
||||
int(logging_config.get("compress_after_days", 7) or 7)
|
||||
)
|
||||
vars_["logging_debug_level_var"].set(
|
||||
str(logging_config.get("debug_detail_level", "normal") or "normal")
|
||||
)
|
||||
vars_["logging_error_level_var"].set(
|
||||
str(logging_config.get("error_detail_level", "full") or "full")
|
||||
)
|
||||
vars_["logging_action_format_var"].set(
|
||||
str(logging_config.get("action_log_format", "concise") or "concise")
|
||||
)
|
||||
vars_["logging_format_mode_var"].set(
|
||||
str(logging_config.get("log_format_mode", "simple") or "simple")
|
||||
)
|
||||
perf_cfg = logging_config.get("performance_tracking", {})
|
||||
if isinstance(perf_cfg, dict):
|
||||
vars_["logging_performance_enabled_var"].set(bool(perf_cfg.get("enabled", True)))
|
||||
vars_["logging_track_functions_var"].set(
|
||||
bool(perf_cfg.get("track_function_calls", True))
|
||||
)
|
||||
vars_["logging_monitor_warning_mb_var"].set(
|
||||
float(logging_config.get("monitor_warning_mb", 500.0) or 500.0)
|
||||
)
|
||||
vars_["logging_monitor_critical_mb_var"].set(
|
||||
float(logging_config.get("monitor_critical_mb", 2000.0) or 2000.0)
|
||||
)
|
||||
|
||||
vars_["yg_like_prob_var"].set(float(cfg.get("yanghao_like_prob", 0.0) or 0.0))
|
||||
vars_["yg_fav_prob_var"].set(float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
|
||||
vars_["yg_comment_prob_var"].set(float(cfg.get("yanghao_comment_prob", 0.0) or 0.0))
|
||||
vars_["yg_dwell_on_action_min_var"].set(
|
||||
float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5)
|
||||
)
|
||||
vars_["yg_dwell_on_action_max_var"].set(
|
||||
float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30)
|
||||
)
|
||||
vars_["yg_icon_roi_size_var"].set(int(cfg.get("yanghao_icon_roi_size", 240) or 240))
|
||||
vars_["yg_icon_match_threshold_var"].set(
|
||||
float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
|
||||
)
|
||||
vars_["yg_step_screenshot_var"].set(bool(cfg.get("yanghao_step_screenshot", False)))
|
||||
vars_["yg_like_roi_offset_x_var"].set(int(cfg.get("yanghao_like_roi_offset_x", 0) or 0))
|
||||
vars_["yg_like_roi_offset_y_var"].set(int(cfg.get("yanghao_like_roi_offset_y", 0) or 0))
|
||||
vars_["yg_fav_roi_offset_x_var"].set(int(cfg.get("yanghao_fav_roi_offset_x", 0) or 0))
|
||||
vars_["yg_fav_roi_offset_y_var"].set(int(cfg.get("yanghao_fav_roi_offset_y", 0) or 0))
|
||||
vars_["yg_like_icon_x_var"].set(int(cfg.get("yanghao_like_icon_x", 0) or 0))
|
||||
vars_["yg_like_icon_y_var"].set(int(cfg.get("yanghao_like_icon_y", 0) or 0))
|
||||
vars_["yg_fav_icon_x_var"].set(int(cfg.get("yanghao_fav_icon_x", 0) or 0))
|
||||
vars_["yg_fav_icon_y_var"].set(int(cfg.get("yanghao_fav_icon_y", 0) or 0))
|
||||
vars_["yg_like_template_path_var"].set(
|
||||
str(
|
||||
cfg.get("yanghao_like_template_path", "assets/like.png")
|
||||
or "assets/like.png"
|
||||
)
|
||||
)
|
||||
vars_["yg_fav_template_path_var"].set(
|
||||
str(
|
||||
cfg.get("yanghao_fav_template_path", "assets/fav.png")
|
||||
or "assets/fav.png"
|
||||
)
|
||||
)
|
||||
vars_["yg_after_dwell_direction_var"].set(
|
||||
str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
|
||||
)
|
||||
vars_["yg_after_dwell_distance_var"].set(
|
||||
int(cfg.get("yanghao_after_dwell_swipe_distance_px", 900) or 900)
|
||||
)
|
||||
vars_["yg_comment_btn_x_var"].set(int(cfg.get("yanghao_comment_btn_x", 0) or 0))
|
||||
vars_["yg_comment_btn_y_var"].set(int(cfg.get("yanghao_comment_btn_y", 0) or 0))
|
||||
vars_["yg_comment_input_x_var"].set(int(cfg.get("yanghao_comment_input_x", 0) or 0))
|
||||
vars_["yg_comment_input_y_var"].set(int(cfg.get("yanghao_comment_input_y", 0) or 0))
|
||||
vars_["yg_comment_send_x_var"].set(int(cfg.get("yanghao_comment_send_x", 0) or 0))
|
||||
vars_["yg_comment_send_y_var"].set(int(cfg.get("yanghao_comment_send_y", 0) or 0))
|
||||
vars_["yg_comment_close_x_var"].set(int(cfg.get("yanghao_comment_close_x", 0) or 0))
|
||||
vars_["yg_comment_close_y_var"].set(int(cfg.get("yanghao_comment_close_y", 0) or 0))
|
||||
|
||||
# 仅保留黑名单 contains_not_want
|
||||
want = cfg.get("contains_want", []) or []
|
||||
not_want = cfg.get("contains_not_want", []) or []
|
||||
yg_comment_texts_list = cfg.get("yanghao_comment_texts", []) or []
|
||||
yg_like_keywords_list = cfg.get("yanghao_like_keywords", []) or []
|
||||
yg_fav_keywords_list = cfg.get("yanghao_fav_keywords", []) or []
|
||||
texts_["want_text"].delete("1.0", "end")
|
||||
texts_["want_text"].insert("1.0", "\n".join(want))
|
||||
texts_["not_want_text"].delete("1.0", "end")
|
||||
texts_["not_want_text"].insert("1.0", "\n".join(not_want))
|
||||
texts_["yg_comment_texts"].delete("1.0", "end")
|
||||
texts_["yg_comment_texts"].insert("1.0", "\n".join(yg_comment_texts_list))
|
||||
texts_["yg_like_keywords_text"].delete("1.0", "end")
|
||||
texts_["yg_like_keywords_text"].insert("1.0", "\n".join(yg_like_keywords_list))
|
||||
texts_["yg_fav_keywords_text"].delete("1.0", "end")
|
||||
texts_["yg_fav_keywords_text"].insert("1.0", "\n".join(yg_fav_keywords_list))
|
||||
|
||||
return cfg
|
||||
|
||||
|
||||
def save_ui_to_config(
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
texts_: Dict[str, tk.Text],
|
||||
cfg: dict,
|
||||
read_config: Callable[[], dict],
|
||||
write_config: Callable[[dict], None],
|
||||
on_line: Callable[[str], None],
|
||||
) -> None:
|
||||
want_lines = [
|
||||
x.strip() for x in texts_["want_text"].get("1.0", "end").splitlines() if x.strip()
|
||||
]
|
||||
not_want_lines = [
|
||||
x.strip() for x in texts_["not_want_text"].get("1.0", "end").splitlines() if x.strip()
|
||||
]
|
||||
yg_comment_text_lines = [
|
||||
x.strip()
|
||||
for x in texts_["yg_comment_texts"].get("1.0", "end").splitlines()
|
||||
if x.strip()
|
||||
]
|
||||
yg_like_kw_lines = [
|
||||
x.strip()
|
||||
for x in texts_["yg_like_keywords_text"].get("1.0", "end").splitlines()
|
||||
if x.strip()
|
||||
]
|
||||
yg_fav_kw_lines = [
|
||||
x.strip()
|
||||
for x in texts_["yg_fav_keywords_text"].get("1.0", "end").splitlines()
|
||||
if x.strip()
|
||||
]
|
||||
|
||||
cfg2 = read_config()
|
||||
cfg2["needswitch"] = bool(vars_["needswitch_var"].get())
|
||||
cfg2["infinite_loop_enabled"] = bool(vars_["infinite_loop_var"].get())
|
||||
cfg2["wait_minutes"] = int(vars_["wait_minutes_var"].get() or 5)
|
||||
cfg2["y_pianyi"] = int(vars_["y_var"].get() or 0)
|
||||
cfg2["contains_want"] = want_lines
|
||||
cfg2["contains_not_want"] = not_want_lines
|
||||
cfg2["min_prize_value_yuan"] = float(vars_["min_value_var"].get() or 0)
|
||||
cfg2["min_participants"] = int(vars_["min_participants_var"].get() or 0)
|
||||
cfg2["max_participants"] = int(vars_["max_participants_var"].get() or 0)
|
||||
cfg2["skip_if_countdown_gt_seconds"] = int(vars_["skip_gt_seconds_var"].get() or 900)
|
||||
cfg2["reset_after_swipes_enabled"] = bool(vars_["reset_after_swipes_enabled_var"].get())
|
||||
cfg2["reset_after_swipes"] = int(vars_["reset_after_swipes_var"].get() or 10)
|
||||
cfg2["auto_join_fansclub"] = bool(vars_["auto_join_var"].get())
|
||||
cfg2["fansclub_fail_action"] = str(vars_["fansclub_action_var"].get() or "stay").lower()
|
||||
cfg2["lucky_draw_red_ratio_threshold"] = float(
|
||||
vars_["lucky_draw_red_ratio_threshold_var"].get() or 0.9
|
||||
)
|
||||
|
||||
# Web端新增配置 - 高价值预约相关
|
||||
cfg2["high_value_fudai_enabled"] = bool(vars_["high_value_fudai_enabled_var"].get())
|
||||
cfg2["high_value_fudai_threshold_yuan"] = float(
|
||||
vars_["high_value_fudai_threshold_yuan_var"].get() or 1000
|
||||
)
|
||||
cfg2["high_value_fudai_join_ahead_seconds"] = int(
|
||||
vars_["high_value_fudai_join_ahead_seconds_var"].get() or 300
|
||||
)
|
||||
cfg2["high_value_fudai_max_swipe_back"] = int(
|
||||
vars_["high_value_fudai_max_swipe_back_var"].get() or 60
|
||||
)
|
||||
cfg2["high_value_fudai_max_reservations"] = int(
|
||||
vars_["high_value_fudai_max_reservations_var"].get() or 5
|
||||
)
|
||||
cfg2["high_value_fudai_after_action"] = str(
|
||||
vars_["high_value_fudai_after_action_var"].get() or "continue"
|
||||
).lower()
|
||||
cfg2["high_value_fudai_poll_before_seconds"] = float(
|
||||
vars_["high_value_fudai_poll_before_seconds_var"].get() or 10.0
|
||||
)
|
||||
cfg2["high_value_room_revisit_enabled"] = bool(
|
||||
vars_["high_value_room_revisit_enabled_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_only_current_run"] = bool(
|
||||
vars_["high_value_room_revisit_only_current_run_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_min_interval_seconds"] = int(
|
||||
vars_["high_value_room_revisit_min_interval_seconds_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_max_per_run"] = int(
|
||||
vars_["high_value_room_revisit_max_per_run_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_min_prize_value"] = float(
|
||||
vars_["high_value_room_revisit_min_prize_value_var"].get()
|
||||
)
|
||||
cfg2["high_value_room_revisit_max_age_days"] = int(
|
||||
vars_["high_value_room_revisit_max_age_days_var"].get()
|
||||
)
|
||||
cfg2["reservation_back_verify_enabled"] = bool(
|
||||
vars_["reservation_back_verify_enabled_var"].get()
|
||||
)
|
||||
cfg2["reservation_back_swipe_delay"] = float(
|
||||
vars_["reservation_back_swipe_delay_var"].get() or 0
|
||||
)
|
||||
cfg2["reservation_back_verify_wait_seconds"] = float(
|
||||
vars_["reservation_back_verify_wait_seconds_var"].get() or 5.0
|
||||
)
|
||||
cfg2["fudai_find_max_attempts"] = int(vars_["fudai_find_max_attempts_var"].get() or 0)
|
||||
cfg2["fudai_icon_retry_delay_seconds"] = float(
|
||||
vars_["fudai_icon_retry_delay_seconds_var"].get() or 0.6
|
||||
)
|
||||
cfg2["fudai_icon_max_wait_seconds"] = float(
|
||||
vars_["fudai_icon_max_wait_seconds_var"].get() or 5.0
|
||||
)
|
||||
cfg2["fudai_click_wait_seconds"] = float(
|
||||
vars_["fudai_click_wait_seconds_var"].get() or 2.0
|
||||
)
|
||||
cfg2["fudai_exit_after_misses"] = int(vars_["fudai_exit_after_misses_var"].get() or 30)
|
||||
cfg2["enable_back_on_misses"] = bool(vars_["enable_back_on_misses_var"].get())
|
||||
cfg2["swipe_down_back_enabled"] = bool(vars_["swipe_down_back_enabled_var"].get())
|
||||
cfg2["swipe_down_back_count"] = int(vars_["swipe_down_back_count_var"].get() or 3)
|
||||
cfg2["reset_after_swipes_action"] = str(
|
||||
vars_["reset_after_swipes_action_var"].get() or "swipe"
|
||||
)
|
||||
cfg2["fudai_disable_content_recognition"] = bool(
|
||||
vars_["fudai_disable_content_recognition_var"].get()
|
||||
)
|
||||
cfg2["fudai_disable_task_recognition"] = bool(
|
||||
vars_["fudai_disable_task_recognition_var"].get()
|
||||
)
|
||||
cfg2["switch_room_wait_after_stage_diag_seconds"] = float(
|
||||
vars_["switch_room_wait_after_stage_diag_seconds_var"].get() or 7.0
|
||||
)
|
||||
cfg2["live_room_match_threshold"] = float(
|
||||
vars_["live_room_match_threshold_var"].get() or 0.8
|
||||
)
|
||||
cfg2["swipe_duration_ms"] = int(vars_["swipe_duration_ms_var"].get() or 600)
|
||||
cfg2["swipe_up_start_y"] = int(vars_["swipe_up_start_y_var"].get() or 1200)
|
||||
cfg2["swipe_up_end_y"] = int(vars_["swipe_up_end_y_var"].get() or 600)
|
||||
cfg2["fudai_quiet_hours_enabled"] = bool(vars_["fudai_quiet_hours_enabled_var"].get())
|
||||
cfg2["fudai_quiet_start_hour"] = int(vars_["fudai_quiet_start_hour_var"].get() or 0)
|
||||
cfg2["fudai_quiet_end_hour"] = int(vars_["fudai_quiet_end_hour_var"].get() or 0)
|
||||
cfg2["stage_diag_max_time"] = float(vars_["stage_diag_max_time_var"].get() or 10.0)
|
||||
cfg2["stage_diag_max_step_time"] = float(
|
||||
vars_["stage_diag_max_step_time_var"].get() or 2.0
|
||||
)
|
||||
cfg2["enable_ocr_mode1"] = bool(cfg.get("enable_ocr_mode1", False))
|
||||
cfg2["fudai_template_match_enabled"] = bool(
|
||||
vars_["fudai_template_match_enabled_var"].get()
|
||||
)
|
||||
cfg2["fudai_template_match_threshold"] = float(
|
||||
vars_["fudai_template_match_threshold_var"].get() or 0.7
|
||||
)
|
||||
cfg2["fudai_detail_template_threshold"] = float(
|
||||
vars_["fudai_detail_template_threshold_var"].get() or 0.7
|
||||
)
|
||||
cfg2["coupon_template_match_threshold"] = float(
|
||||
vars_["coupon_template_match_threshold_var"].get() or 0.75
|
||||
)
|
||||
cfg2["attend_button_red_ratio_threshold"] = float(
|
||||
vars_["attend_button_red_ratio_threshold_var"].get() or 0.25
|
||||
)
|
||||
cfg2["fansclub_join_red_ratio_threshold"] = float(
|
||||
vars_["fansclub_join_red_ratio_threshold_var"].get() or 0.25
|
||||
)
|
||||
cfg2["shopping_redpacket_red_ratio_threshold"] = float(
|
||||
vars_["shopping_redpacket_red_ratio_threshold_var"].get() or 0.15
|
||||
)
|
||||
# 粉丝团等待/点击延迟配置
|
||||
cfg2["fansclub_click_delay"] = float(vars_["fansclub_click_delay_var"].get() or 0.6)
|
||||
cfg2["fansclub_auto_join_wait_seconds"] = float(
|
||||
vars_["fansclub_auto_wait_var"].get() or 5.0
|
||||
)
|
||||
cfg2["fansclub_manual_wait_seconds"] = float(
|
||||
vars_["fansclub_manual_wait_var"].get() or 3.0
|
||||
)
|
||||
cfg2["skip_if_countdown_lt_seconds"] = int(vars_["skip_lt_seconds_var"].get() or 10)
|
||||
|
||||
# 调试图像清理配置
|
||||
if "debug_captures" not in cfg2 or not isinstance(cfg2["debug_captures"], dict):
|
||||
cfg2["debug_captures"] = {}
|
||||
cfg2["debug_captures"]["enabled"] = bool(vars_["debug_captures_enabled_var"].get())
|
||||
cfg2["debug_captures"]["auto_cleanup"] = bool(
|
||||
vars_["debug_captures_auto_cleanup_var"].get()
|
||||
)
|
||||
cfg2["debug_captures"]["keep_days"] = int(
|
||||
vars_["debug_captures_keep_days_var"].get() or 7
|
||||
)
|
||||
cfg2["debug_captures"]["max_files"] = int(
|
||||
vars_["debug_captures_max_files_var"].get() or 2000
|
||||
)
|
||||
cfg2["debug_captures"]["async_save"] = bool(vars_["debug_captures_async_save_var"].get())
|
||||
cfg2["debug_captures"]["log_on_complete"] = bool(
|
||||
vars_["debug_captures_log_on_complete_var"].get()
|
||||
)
|
||||
|
||||
# 日志配置
|
||||
if "logging" not in cfg2 or not isinstance(cfg2["logging"], dict):
|
||||
cfg2["logging"] = {}
|
||||
cfg2["logging"]["beautify_output"] = bool(vars_["logging_beautify_var"].get())
|
||||
cfg2["logging"]["color_output"] = bool(vars_["logging_color_var"].get())
|
||||
cfg2["logging"]["show_timestamps"] = bool(vars_["logging_show_timestamps_var"].get())
|
||||
cfg2["logging"]["use_dated_logs"] = bool(vars_["logging_use_dated_logs_var"].get())
|
||||
cfg2["logging"]["enable_monitor"] = bool(vars_["logging_enable_monitor_var"].get())
|
||||
cfg2["logging"]["keep_days"] = int(vars_["logging_keep_days_var"].get() or 30)
|
||||
cfg2["logging"]["compress_logs"] = bool(vars_["logging_compress_logs_var"].get())
|
||||
cfg2["logging"]["max_total_size_gb"] = float(
|
||||
vars_["logging_max_total_size_gb_var"].get() or 10.0
|
||||
)
|
||||
cfg2["logging"]["compress_after_days"] = int(
|
||||
vars_["logging_compress_after_days_var"].get() or 7
|
||||
)
|
||||
cfg2["logging"]["debug_detail_level"] = str(
|
||||
vars_["logging_debug_level_var"].get() or "normal"
|
||||
)
|
||||
cfg2["logging"]["error_detail_level"] = str(
|
||||
vars_["logging_error_level_var"].get() or "full"
|
||||
)
|
||||
cfg2["logging"]["action_log_format"] = str(
|
||||
vars_["logging_action_format_var"].get() or "concise"
|
||||
)
|
||||
cfg2["logging"]["log_format_mode"] = str(
|
||||
vars_["logging_format_mode_var"].get() or "simple"
|
||||
)
|
||||
cfg2["logging"]["stage_diag_verbose"] = bool(vars_["stage_diag_verbose_var"].get())
|
||||
cfg2["logging"]["monitor_warning_mb"] = float(
|
||||
vars_["logging_monitor_warning_mb_var"].get() or 500.0
|
||||
)
|
||||
cfg2["logging"]["monitor_critical_mb"] = float(
|
||||
vars_["logging_monitor_critical_mb_var"].get() or 2000.0
|
||||
)
|
||||
|
||||
# 性能追踪配置
|
||||
if "performance_tracking" not in cfg2["logging"] or not isinstance(
|
||||
cfg2["logging"]["performance_tracking"], dict
|
||||
):
|
||||
cfg2["logging"]["performance_tracking"] = {}
|
||||
cfg2["logging"]["performance_tracking"]["enabled"] = bool(
|
||||
vars_["logging_performance_enabled_var"].get()
|
||||
)
|
||||
cfg2["logging"]["performance_tracking"]["track_function_calls"] = bool(
|
||||
vars_["logging_track_functions_var"].get()
|
||||
)
|
||||
cfg2["log_unified_enabled"] = bool(vars_["log_unified_enabled_var"].get())
|
||||
cfg2["log_unified_path"] = str(vars_["log_unified_path_var"].get() or "logs/unified.log")
|
||||
|
||||
cfg2["yanghao_enabled"] = bool(vars_["yg_enabled_var"].get())
|
||||
cfg2["yanghao_enable_actions"] = bool(vars_["yg_actions_enabled_var"].get())
|
||||
cfg2["yanghao_only"] = bool(vars_["yg_only_var"].get())
|
||||
cfg2["yanghao_recommend_duration_seconds"] = int(
|
||||
vars_["yg_recommend_duration_var"].get() or 60
|
||||
)
|
||||
cfg2["yanghao_recommend_interval_seconds"] = int(
|
||||
vars_["yg_recommend_interval_var"].get() or 0
|
||||
)
|
||||
cfg2["yanghao_like_prob"] = float(vars_["yg_like_prob_var"].get() or 0.0)
|
||||
cfg2["yanghao_fav_prob"] = float(vars_["yg_fav_prob_var"].get() or 0.0)
|
||||
cfg2["yanghao_comment_prob"] = float(vars_["yg_comment_prob_var"].get() or 0.0)
|
||||
cfg2["yanghao_dwell_on_action_min_seconds"] = float(
|
||||
vars_["yg_dwell_on_action_min_var"].get() or 5
|
||||
)
|
||||
cfg2["yanghao_dwell_on_action_max_seconds"] = float(
|
||||
vars_["yg_dwell_on_action_max_var"].get() or 30
|
||||
)
|
||||
cfg2["yanghao_icon_roi_size"] = int(vars_["yg_icon_roi_size_var"].get() or 240)
|
||||
cfg2["yanghao_icon_match_threshold"] = float(
|
||||
vars_["yg_icon_match_threshold_var"].get() or 0.72
|
||||
)
|
||||
cfg2["yanghao_step_screenshot"] = bool(vars_["yg_step_screenshot_var"].get())
|
||||
cfg2["yanghao_like_roi_offset_x"] = int(vars_["yg_like_roi_offset_x_var"].get() or 0)
|
||||
cfg2["yanghao_like_roi_offset_y"] = int(vars_["yg_like_roi_offset_y_var"].get() or 0)
|
||||
cfg2["yanghao_fav_roi_offset_x"] = int(vars_["yg_fav_roi_offset_x_var"].get() or 0)
|
||||
cfg2["yanghao_fav_roi_offset_y"] = int(vars_["yg_fav_roi_offset_y_var"].get() or 0)
|
||||
cfg2["yanghao_like_icon_x"] = int(vars_["yg_like_icon_x_var"].get() or 0)
|
||||
cfg2["yanghao_like_icon_y"] = int(vars_["yg_like_icon_y_var"].get() or 0)
|
||||
cfg2["yanghao_fav_icon_x"] = int(vars_["yg_fav_icon_x_var"].get() or 0)
|
||||
cfg2["yanghao_fav_icon_y"] = int(vars_["yg_fav_icon_y_var"].get() or 0)
|
||||
cfg2["yanghao_like_template_path"] = str(
|
||||
vars_["yg_like_template_path_var"].get() or "assets/like.png"
|
||||
)
|
||||
cfg2["yanghao_fav_template_path"] = str(
|
||||
vars_["yg_fav_template_path_var"].get() or "assets/fav.png"
|
||||
)
|
||||
cfg2["yanghao_after_dwell_swipe_direction"] = str(
|
||||
vars_["yg_after_dwell_direction_var"].get() or "up"
|
||||
)
|
||||
cfg2["yanghao_after_dwell_swipe_distance_px"] = int(
|
||||
vars_["yg_after_dwell_distance_var"].get() or 900
|
||||
)
|
||||
cfg2["yanghao_comment_btn_x"] = int(vars_["yg_comment_btn_x_var"].get() or 0)
|
||||
cfg2["yanghao_comment_btn_y"] = int(vars_["yg_comment_btn_y_var"].get() or 0)
|
||||
cfg2["yanghao_comment_input_x"] = int(vars_["yg_comment_input_x_var"].get() or 0)
|
||||
cfg2["yanghao_comment_input_y"] = int(vars_["yg_comment_input_y_var"].get() or 0)
|
||||
cfg2["yanghao_comment_send_x"] = int(vars_["yg_comment_send_x_var"].get() or 0)
|
||||
cfg2["yanghao_comment_send_y"] = int(vars_["yg_comment_send_y_var"].get() or 0)
|
||||
cfg2["yanghao_comment_close_x"] = int(vars_["yg_comment_close_x_var"].get() or 0)
|
||||
cfg2["yanghao_comment_close_y"] = int(vars_["yg_comment_close_y_var"].get() or 0)
|
||||
cfg2["yanghao_comment_texts"] = yg_comment_text_lines
|
||||
cfg2["yanghao_like_keywords"] = yg_like_kw_lines
|
||||
cfg2["yanghao_fav_keywords"] = yg_fav_kw_lines
|
||||
|
||||
# 流式后台截图配置
|
||||
cfg2["enable_streaming_screenshot"] = bool(vars_["streaming_enabled_var"].get())
|
||||
|
||||
# GUI 配置
|
||||
if "gui" not in cfg2 or not isinstance(cfg2["gui"], dict):
|
||||
cfg2["gui"] = {}
|
||||
cfg2["gui"]["theme"] = str(vars_["gui_theme_var"].get() or "litera")
|
||||
cfg2["gui"]["realtime_status"] = {
|
||||
"refresh_interval_ms": int(
|
||||
vars_["gui_realtime_refresh_interval_ms_var"].get() or 1000
|
||||
),
|
||||
"tail_items": int(vars_["gui_realtime_tail_items_var"].get() or 50),
|
||||
}
|
||||
|
||||
write_config(cfg2)
|
||||
on_line("[配置] 已保存到 config.json")
|
||||
# 如果用户关闭了流式后台截图,尝试停止正在运行的服务实例以立即生效
|
||||
try:
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
|
||||
if not bool(cfg2.get("enable_streaming_screenshot", True)):
|
||||
try:
|
||||
ScreenshotService.get_instance().stop()
|
||||
on_line("[截图服务] 已停止后台流式截图(配置更新)")
|
||||
except Exception:
|
||||
on_line("[截图服务] 停止后台截图服务失败(请重启程序以确保生效)")
|
||||
except Exception:
|
||||
# ignore if service module not available
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,538 @@
|
||||
"""GUI Var 工厂:从 ``cfg`` 构建所有 ``tkinter`` Var 实例。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出 127 个 Var 声明。返回名→Var 的 dict,``main()`` 在解构后
|
||||
继续以原变量名使用(避免改动 134 处现有引用点)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def build_config_vars(cfg: dict) -> Dict[str, tk.Variable]:
|
||||
"""从 cfg 构建所有 tk Var 实例,返回名→Var 字典。"""
|
||||
y_var = tk.IntVar(value=int(cfg.get("y_pianyi", 0) or 0))
|
||||
enable_back_on_misses_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("enable_back_on_misses", True))
|
||||
)
|
||||
swipe_down_back_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("swipe_down_back_enabled", False))
|
||||
)
|
||||
swipe_down_back_count_var = tk.IntVar(
|
||||
value=int(cfg.get("swipe_down_back_count", 3) or 3)
|
||||
)
|
||||
needswitch_var = tk.BooleanVar(value=bool(cfg.get("needswitch", True)))
|
||||
infinite_loop_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("infinite_loop_enabled", False))
|
||||
)
|
||||
wait_minutes_var = tk.IntVar(value=int(cfg.get("wait_minutes", 5) or 5))
|
||||
min_value_var = tk.DoubleVar(value=float(cfg.get("min_prize_value_yuan", 0) or 0))
|
||||
min_participants_var = tk.IntVar(value=int(cfg.get("min_participants", 0) or 0))
|
||||
max_participants_var = tk.IntVar(value=int(cfg.get("max_participants", 0) or 0))
|
||||
skip_gt_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("skip_if_countdown_gt_seconds", 900) or 900)
|
||||
)
|
||||
reset_after_swipes_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("reset_after_swipes_enabled", False))
|
||||
)
|
||||
reset_after_swipes_var = tk.IntVar(
|
||||
value=int(cfg.get("reset_after_swipes", 10) or 10)
|
||||
)
|
||||
reset_after_swipes_action_var = tk.StringVar(
|
||||
value=str(cfg.get("reset_after_swipes_action", "swipe") or "swipe")
|
||||
)
|
||||
enable_back_on_misses_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("enable_back_on_misses", True))
|
||||
)
|
||||
streaming_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("enable_streaming_screenshot", True))
|
||||
)
|
||||
auto_join_var = tk.BooleanVar(value=bool(cfg.get("auto_join_fansclub", False)))
|
||||
fansclub_action_var = tk.StringVar(
|
||||
value=str(cfg.get("fansclub_fail_action", "stay") or "stay").lower()
|
||||
)
|
||||
fansclub_click_delay_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fansclub_click_delay", 0.6) or 0.6)
|
||||
)
|
||||
fansclub_auto_wait_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fansclub_auto_join_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
fansclub_manual_wait_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fansclub_manual_wait_seconds", 3.0) or 3.0)
|
||||
)
|
||||
high_value_fudai_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("high_value_fudai_enabled", False))
|
||||
)
|
||||
high_value_fudai_threshold_yuan_var = tk.DoubleVar(
|
||||
value=float(cfg.get("high_value_fudai_threshold_yuan", 1000) or 1000)
|
||||
)
|
||||
high_value_fudai_join_ahead_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_fudai_join_ahead_seconds", 300) or 300)
|
||||
)
|
||||
high_value_fudai_max_swipe_back_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_fudai_max_swipe_back", 60) or 60)
|
||||
)
|
||||
high_value_fudai_max_reservations_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_fudai_max_reservations", 5) or 5)
|
||||
)
|
||||
high_value_fudai_after_action_var = tk.StringVar(
|
||||
value=str(cfg.get("high_value_fudai_after_action", "continue") or "continue")
|
||||
)
|
||||
high_value_fudai_poll_before_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("high_value_fudai_poll_before_seconds", 10.0) or 10.0)
|
||||
)
|
||||
high_value_room_revisit_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("high_value_room_revisit_enabled", True))
|
||||
)
|
||||
high_value_room_revisit_only_current_run_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("high_value_room_revisit_only_current_run", False))
|
||||
)
|
||||
high_value_room_revisit_min_interval_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_room_revisit_min_interval_seconds", 300))
|
||||
)
|
||||
high_value_room_revisit_max_per_run_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_room_revisit_max_per_run", 5))
|
||||
)
|
||||
high_value_room_revisit_min_prize_value_var = tk.DoubleVar(
|
||||
value=float(cfg.get("high_value_room_revisit_min_prize_value", 0.0))
|
||||
)
|
||||
high_value_room_revisit_max_age_days_var = tk.IntVar(
|
||||
value=int(cfg.get("high_value_room_revisit_max_age_days", 30))
|
||||
)
|
||||
reservation_back_verify_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("reservation_back_verify_enabled", True))
|
||||
)
|
||||
reservation_back_swipe_delay_var = tk.DoubleVar(
|
||||
value=float(cfg.get("reservation_back_swipe_delay", 0) or 0)
|
||||
)
|
||||
reservation_back_verify_wait_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("reservation_back_verify_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
fudai_find_max_attempts_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_find_max_attempts", 0) or 0)
|
||||
)
|
||||
fudai_icon_retry_delay_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_icon_retry_delay_seconds", 0.6) or 0.6)
|
||||
)
|
||||
fudai_icon_max_wait_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_icon_max_wait_seconds", 5.0) or 5.0)
|
||||
)
|
||||
fudai_disable_content_recognition_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("fudai_disable_content_recognition", False))
|
||||
)
|
||||
fudai_disable_task_recognition_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("fudai_disable_task_recognition", False))
|
||||
)
|
||||
fudai_exit_after_misses_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_exit_after_misses", 30) or 30)
|
||||
)
|
||||
fudai_click_wait_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_click_wait_seconds", 1.0) or 1.0)
|
||||
)
|
||||
switch_room_wait_after_stage_diag_seconds_var = tk.DoubleVar(
|
||||
value=float(cfg.get("switch_room_wait_after_stage_diag_seconds", 7.0) or 7.0)
|
||||
)
|
||||
live_room_match_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("live_room_match_threshold", 0.8) or 0.8)
|
||||
)
|
||||
swipe_duration_ms_var = tk.IntVar(
|
||||
value=int(cfg.get("swipe_duration_ms", 600) or 600)
|
||||
)
|
||||
swipe_up_start_y_var = tk.IntVar(
|
||||
value=int(cfg.get("swipe_up_start_y", 1200) or 1200)
|
||||
)
|
||||
swipe_up_end_y_var = tk.IntVar(value=int(cfg.get("swipe_up_end_y", 600) or 600))
|
||||
yg_enabled_var = tk.BooleanVar(value=bool(cfg.get("yanghao_enabled", True)))
|
||||
yg_actions_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("yanghao_enable_actions", True))
|
||||
)
|
||||
yg_only_var = tk.BooleanVar(value=bool(cfg.get("yanghao_only", False)))
|
||||
yg_recommend_duration_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_recommend_duration_seconds", 60) or 60)
|
||||
)
|
||||
yg_recommend_interval_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_recommend_interval_seconds", 0) or 0)
|
||||
)
|
||||
yg_like_prob_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_like_prob", 0.0) or 0.0)
|
||||
)
|
||||
yg_fav_prob_var = tk.DoubleVar(value=float(cfg.get("yanghao_fav_prob", 0.0) or 0.0))
|
||||
yg_comment_prob_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_comment_prob", 0.0) or 0.0)
|
||||
)
|
||||
yg_dwell_on_action_min_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_dwell_on_action_min_seconds", 5) or 5)
|
||||
)
|
||||
yg_dwell_on_action_max_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_dwell_on_action_max_seconds", 30) or 30)
|
||||
)
|
||||
yg_icon_roi_size_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_icon_roi_size", 240) or 240)
|
||||
)
|
||||
yg_icon_match_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("yanghao_icon_match_threshold", 0.72) or 0.72)
|
||||
)
|
||||
yg_step_screenshot_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("yanghao_step_screenshot", False))
|
||||
)
|
||||
yg_like_roi_offset_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_like_roi_offset_x", 0) or 0)
|
||||
)
|
||||
yg_like_roi_offset_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_like_roi_offset_y", 0) or 0)
|
||||
)
|
||||
yg_fav_roi_offset_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_fav_roi_offset_x", 0) or 0)
|
||||
)
|
||||
yg_fav_roi_offset_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_fav_roi_offset_y", 0) or 0)
|
||||
)
|
||||
yg_like_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_x", 0) or 0))
|
||||
yg_like_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_y", 0) or 0))
|
||||
yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_x", 0) or 0))
|
||||
yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_y", 0) or 0))
|
||||
yg_like_template_path_var = tk.StringVar(
|
||||
value=str(
|
||||
cfg.get("yanghao_like_template_path", "assets/like.png")
|
||||
or "assets/like.png"
|
||||
)
|
||||
)
|
||||
yg_fav_template_path_var = tk.StringVar(
|
||||
value=str(
|
||||
cfg.get("yanghao_fav_template_path", "assets/fav.png") or "assets/fav.png"
|
||||
)
|
||||
)
|
||||
yg_like_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_x", 0) or 0))
|
||||
yg_like_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_like_icon_y", 0) or 0))
|
||||
yg_fav_icon_x_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_x", 0) or 0))
|
||||
yg_fav_icon_y_var = tk.IntVar(value=int(cfg.get("yanghao_fav_icon_y", 0) or 0))
|
||||
yg_after_dwell_direction_var = tk.StringVar(
|
||||
value=str(cfg.get("yanghao_after_dwell_swipe_direction", "up") or "up")
|
||||
)
|
||||
yg_after_dwell_distance_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_after_dwell_swipe_distance_px", 900) or 900)
|
||||
)
|
||||
yg_comment_btn_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_btn_x", 0) or 0)
|
||||
)
|
||||
yg_comment_btn_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_btn_y", 0) or 0)
|
||||
)
|
||||
yg_comment_input_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_input_x", 0) or 0)
|
||||
)
|
||||
yg_comment_input_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_input_y", 0) or 0)
|
||||
)
|
||||
yg_comment_send_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_send_x", 0) or 0)
|
||||
)
|
||||
yg_comment_send_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_send_y", 0) or 0)
|
||||
)
|
||||
yg_comment_close_x_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_close_x", 0) or 0)
|
||||
)
|
||||
yg_comment_close_y_var = tk.IntVar(
|
||||
value=int(cfg.get("yanghao_comment_close_y", 0) or 0)
|
||||
)
|
||||
fudai_quiet_hours_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("fudai_quiet_hours_enabled", True))
|
||||
)
|
||||
fudai_quiet_start_hour_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_quiet_start_hour", 2) or 2)
|
||||
)
|
||||
fudai_quiet_end_hour_var = tk.IntVar(
|
||||
value=int(cfg.get("fudai_quiet_end_hour", 7) or 7)
|
||||
)
|
||||
stage_diag_max_time_var = tk.DoubleVar(
|
||||
value=float(cfg.get("stage_diag_max_time", 10.0) or 10.0)
|
||||
)
|
||||
stage_diag_max_step_time_var = tk.DoubleVar(
|
||||
value=float(cfg.get("stage_diag_max_step_time", 2.0) or 2.0)
|
||||
)
|
||||
stage_diag_verbose_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("stage_diag_verbose", True))
|
||||
)
|
||||
enable_ocr_mode1_var = tk.BooleanVar(value=bool(cfg.get("enable_ocr_mode1", False)))
|
||||
fudai_template_match_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("fudai_template_match_enabled", False))
|
||||
)
|
||||
fudai_template_match_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_template_match_threshold", 0.7) or 0.7)
|
||||
)
|
||||
fudai_detail_template_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fudai_detail_template_threshold", 0.7) or 0.7)
|
||||
)
|
||||
lucky_draw_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("lucky_draw_red_ratio_threshold", 0.9) or 0.9)
|
||||
)
|
||||
coupon_template_match_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("coupon_template_match_threshold", 0.75) or 0.75)
|
||||
)
|
||||
attend_button_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("attend_button_red_ratio_threshold", 0.25) or 0.25)
|
||||
)
|
||||
fansclub_join_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("fansclub_join_red_ratio_threshold", 0.25) or 0.25)
|
||||
)
|
||||
shopping_redpacket_red_ratio_threshold_var = tk.DoubleVar(
|
||||
value=float(cfg.get("shopping_redpacket_red_ratio_threshold", 0.15) or 0.15)
|
||||
)
|
||||
debug_captures_enabled_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("debug_captures", {}).get("enabled", False)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else False
|
||||
)
|
||||
)
|
||||
debug_captures_auto_cleanup_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("debug_captures", {}).get("auto_cleanup", True)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else True
|
||||
)
|
||||
)
|
||||
debug_captures_keep_days_var = tk.IntVar(
|
||||
value=int(
|
||||
cfg.get("debug_captures", {}).get("keep_days", 7)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else 7
|
||||
)
|
||||
)
|
||||
debug_captures_max_files_var = tk.IntVar(
|
||||
value=int(
|
||||
cfg.get("debug_captures", {}).get("max_files", 2000)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else 2000
|
||||
)
|
||||
)
|
||||
debug_captures_async_save_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("debug_captures", {}).get("async_save", True)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else True
|
||||
)
|
||||
)
|
||||
debug_captures_log_on_complete_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("debug_captures", {}).get("log_on_complete", False)
|
||||
if isinstance(cfg.get("debug_captures"), dict)
|
||||
else False
|
||||
)
|
||||
)
|
||||
debug_async_success_var = tk.IntVar(value=0)
|
||||
debug_async_failure_var = tk.IntVar(value=0)
|
||||
logging_beautify_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("beautify_output", True))
|
||||
)
|
||||
logging_color_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("color_output", True))
|
||||
)
|
||||
logging_show_timestamps_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("show_timestamps", True))
|
||||
)
|
||||
logging_use_dated_logs_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("use_dated_logs", True))
|
||||
)
|
||||
logging_enable_monitor_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("enable_monitor", True))
|
||||
)
|
||||
log_unified_enabled_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("log_unified_enabled", True))
|
||||
)
|
||||
log_unified_path_var = tk.StringVar(
|
||||
value=str(cfg.get("log_unified_path", "logs/unified.log") or "logs/unified.log")
|
||||
)
|
||||
logging_keep_days_var = tk.IntVar(
|
||||
value=int(cfg.get("logging", {}).get("keep_days", 30) or 30)
|
||||
)
|
||||
logging_compress_logs_var = tk.BooleanVar(
|
||||
value=bool(cfg.get("logging", {}).get("compress_logs", True))
|
||||
)
|
||||
logging_max_total_size_gb_var = tk.DoubleVar(
|
||||
value=float(cfg.get("logging", {}).get("max_total_size_gb", 10.0) or 10.0)
|
||||
)
|
||||
logging_compress_after_days_var = tk.IntVar(
|
||||
value=int(cfg.get("logging", {}).get("compress_after_days", 7) or 7)
|
||||
)
|
||||
logging_performance_enabled_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("logging", {}).get("performance_tracking", {}).get("enabled", True)
|
||||
)
|
||||
)
|
||||
logging_track_functions_var = tk.BooleanVar(
|
||||
value=bool(
|
||||
cfg.get("logging", {})
|
||||
.get("performance_tracking", {})
|
||||
.get("track_function_calls", True)
|
||||
)
|
||||
)
|
||||
logging_debug_level_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("debug_detail_level", "normal"))
|
||||
)
|
||||
logging_error_level_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("error_detail_level", "full"))
|
||||
)
|
||||
logging_action_format_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("action_log_format", "concise"))
|
||||
)
|
||||
logging_format_mode_var = tk.StringVar(
|
||||
value=str(cfg.get("logging", {}).get("log_format_mode", "simple"))
|
||||
)
|
||||
logging_monitor_warning_mb_var = tk.DoubleVar(
|
||||
value=float(cfg.get("logging", {}).get("monitor_warning_mb", 500.0) or 500.0)
|
||||
)
|
||||
logging_monitor_critical_mb_var = tk.DoubleVar(
|
||||
value=float(cfg.get("logging", {}).get("monitor_critical_mb", 2000.0) or 2000.0)
|
||||
)
|
||||
gui_theme_var = tk.StringVar(
|
||||
value=str(cfg.get("gui", {}).get("theme", "litera") or "litera")
|
||||
)
|
||||
gui_realtime_refresh_interval_ms_var = tk.IntVar(
|
||||
value=int(
|
||||
cfg.get("gui", {})
|
||||
.get("realtime_status", {})
|
||||
.get("refresh_interval_ms", 1000)
|
||||
or 1000
|
||||
)
|
||||
)
|
||||
gui_realtime_tail_items_var = tk.IntVar(
|
||||
value=int(
|
||||
cfg.get("gui", {}).get("realtime_status", {}).get("tail_items", 50) or 50
|
||||
)
|
||||
)
|
||||
skip_lt_seconds_var = tk.IntVar(
|
||||
value=int(cfg.get("skip_if_countdown_lt_seconds", 10) or 10)
|
||||
)
|
||||
|
||||
return {
|
||||
"y_var": y_var,
|
||||
"enable_back_on_misses_var": enable_back_on_misses_var,
|
||||
"swipe_down_back_enabled_var": swipe_down_back_enabled_var,
|
||||
"swipe_down_back_count_var": swipe_down_back_count_var,
|
||||
"needswitch_var": needswitch_var,
|
||||
"infinite_loop_var": infinite_loop_var,
|
||||
"wait_minutes_var": wait_minutes_var,
|
||||
"min_value_var": min_value_var,
|
||||
"min_participants_var": min_participants_var,
|
||||
"max_participants_var": max_participants_var,
|
||||
"skip_gt_seconds_var": skip_gt_seconds_var,
|
||||
"reset_after_swipes_enabled_var": reset_after_swipes_enabled_var,
|
||||
"reset_after_swipes_var": reset_after_swipes_var,
|
||||
"reset_after_swipes_action_var": reset_after_swipes_action_var,
|
||||
"streaming_enabled_var": streaming_enabled_var,
|
||||
"auto_join_var": auto_join_var,
|
||||
"fansclub_action_var": fansclub_action_var,
|
||||
"fansclub_click_delay_var": fansclub_click_delay_var,
|
||||
"fansclub_auto_wait_var": fansclub_auto_wait_var,
|
||||
"fansclub_manual_wait_var": fansclub_manual_wait_var,
|
||||
"high_value_fudai_enabled_var": high_value_fudai_enabled_var,
|
||||
"high_value_fudai_threshold_yuan_var": high_value_fudai_threshold_yuan_var,
|
||||
"high_value_fudai_join_ahead_seconds_var": high_value_fudai_join_ahead_seconds_var,
|
||||
"high_value_fudai_max_swipe_back_var": high_value_fudai_max_swipe_back_var,
|
||||
"high_value_fudai_max_reservations_var": high_value_fudai_max_reservations_var,
|
||||
"high_value_fudai_after_action_var": high_value_fudai_after_action_var,
|
||||
"high_value_fudai_poll_before_seconds_var": high_value_fudai_poll_before_seconds_var,
|
||||
"high_value_room_revisit_enabled_var": high_value_room_revisit_enabled_var,
|
||||
"high_value_room_revisit_only_current_run_var": high_value_room_revisit_only_current_run_var,
|
||||
"high_value_room_revisit_min_interval_seconds_var": high_value_room_revisit_min_interval_seconds_var,
|
||||
"high_value_room_revisit_max_per_run_var": high_value_room_revisit_max_per_run_var,
|
||||
"high_value_room_revisit_min_prize_value_var": high_value_room_revisit_min_prize_value_var,
|
||||
"high_value_room_revisit_max_age_days_var": high_value_room_revisit_max_age_days_var,
|
||||
"reservation_back_verify_enabled_var": reservation_back_verify_enabled_var,
|
||||
"reservation_back_swipe_delay_var": reservation_back_swipe_delay_var,
|
||||
"reservation_back_verify_wait_seconds_var": reservation_back_verify_wait_seconds_var,
|
||||
"fudai_find_max_attempts_var": fudai_find_max_attempts_var,
|
||||
"fudai_icon_retry_delay_seconds_var": fudai_icon_retry_delay_seconds_var,
|
||||
"fudai_icon_max_wait_seconds_var": fudai_icon_max_wait_seconds_var,
|
||||
"fudai_disable_content_recognition_var": fudai_disable_content_recognition_var,
|
||||
"fudai_disable_task_recognition_var": fudai_disable_task_recognition_var,
|
||||
"fudai_exit_after_misses_var": fudai_exit_after_misses_var,
|
||||
"fudai_click_wait_seconds_var": fudai_click_wait_seconds_var,
|
||||
"switch_room_wait_after_stage_diag_seconds_var": switch_room_wait_after_stage_diag_seconds_var,
|
||||
"live_room_match_threshold_var": live_room_match_threshold_var,
|
||||
"swipe_duration_ms_var": swipe_duration_ms_var,
|
||||
"swipe_up_start_y_var": swipe_up_start_y_var,
|
||||
"swipe_up_end_y_var": swipe_up_end_y_var,
|
||||
"yg_enabled_var": yg_enabled_var,
|
||||
"yg_actions_enabled_var": yg_actions_enabled_var,
|
||||
"yg_only_var": yg_only_var,
|
||||
"yg_recommend_duration_var": yg_recommend_duration_var,
|
||||
"yg_recommend_interval_var": yg_recommend_interval_var,
|
||||
"yg_like_prob_var": yg_like_prob_var,
|
||||
"yg_fav_prob_var": yg_fav_prob_var,
|
||||
"yg_comment_prob_var": yg_comment_prob_var,
|
||||
"yg_dwell_on_action_min_var": yg_dwell_on_action_min_var,
|
||||
"yg_dwell_on_action_max_var": yg_dwell_on_action_max_var,
|
||||
"yg_icon_roi_size_var": yg_icon_roi_size_var,
|
||||
"yg_icon_match_threshold_var": yg_icon_match_threshold_var,
|
||||
"yg_step_screenshot_var": yg_step_screenshot_var,
|
||||
"yg_like_roi_offset_x_var": yg_like_roi_offset_x_var,
|
||||
"yg_like_roi_offset_y_var": yg_like_roi_offset_y_var,
|
||||
"yg_fav_roi_offset_x_var": yg_fav_roi_offset_x_var,
|
||||
"yg_fav_roi_offset_y_var": yg_fav_roi_offset_y_var,
|
||||
"yg_like_icon_x_var": yg_like_icon_x_var,
|
||||
"yg_like_icon_y_var": yg_like_icon_y_var,
|
||||
"yg_fav_icon_x_var": yg_fav_icon_x_var,
|
||||
"yg_fav_icon_y_var": yg_fav_icon_y_var,
|
||||
"yg_like_template_path_var": yg_like_template_path_var,
|
||||
"yg_fav_template_path_var": yg_fav_template_path_var,
|
||||
"yg_after_dwell_direction_var": yg_after_dwell_direction_var,
|
||||
"yg_after_dwell_distance_var": yg_after_dwell_distance_var,
|
||||
"yg_comment_btn_x_var": yg_comment_btn_x_var,
|
||||
"yg_comment_btn_y_var": yg_comment_btn_y_var,
|
||||
"yg_comment_input_x_var": yg_comment_input_x_var,
|
||||
"yg_comment_input_y_var": yg_comment_input_y_var,
|
||||
"yg_comment_send_x_var": yg_comment_send_x_var,
|
||||
"yg_comment_send_y_var": yg_comment_send_y_var,
|
||||
"yg_comment_close_x_var": yg_comment_close_x_var,
|
||||
"yg_comment_close_y_var": yg_comment_close_y_var,
|
||||
"fudai_quiet_hours_enabled_var": fudai_quiet_hours_enabled_var,
|
||||
"fudai_quiet_start_hour_var": fudai_quiet_start_hour_var,
|
||||
"fudai_quiet_end_hour_var": fudai_quiet_end_hour_var,
|
||||
"stage_diag_max_time_var": stage_diag_max_time_var,
|
||||
"stage_diag_max_step_time_var": stage_diag_max_step_time_var,
|
||||
"stage_diag_verbose_var": stage_diag_verbose_var,
|
||||
"enable_ocr_mode1_var": enable_ocr_mode1_var,
|
||||
"fudai_template_match_enabled_var": fudai_template_match_enabled_var,
|
||||
"fudai_template_match_threshold_var": fudai_template_match_threshold_var,
|
||||
"fudai_detail_template_threshold_var": fudai_detail_template_threshold_var,
|
||||
"lucky_draw_red_ratio_threshold_var": lucky_draw_red_ratio_threshold_var,
|
||||
"coupon_template_match_threshold_var": coupon_template_match_threshold_var,
|
||||
"attend_button_red_ratio_threshold_var": attend_button_red_ratio_threshold_var,
|
||||
"fansclub_join_red_ratio_threshold_var": fansclub_join_red_ratio_threshold_var,
|
||||
"shopping_redpacket_red_ratio_threshold_var": shopping_redpacket_red_ratio_threshold_var,
|
||||
"debug_captures_enabled_var": debug_captures_enabled_var,
|
||||
"debug_captures_auto_cleanup_var": debug_captures_auto_cleanup_var,
|
||||
"debug_captures_keep_days_var": debug_captures_keep_days_var,
|
||||
"debug_captures_max_files_var": debug_captures_max_files_var,
|
||||
"debug_captures_async_save_var": debug_captures_async_save_var,
|
||||
"debug_captures_log_on_complete_var": debug_captures_log_on_complete_var,
|
||||
"debug_async_success_var": debug_async_success_var,
|
||||
"debug_async_failure_var": debug_async_failure_var,
|
||||
"logging_beautify_var": logging_beautify_var,
|
||||
"logging_color_var": logging_color_var,
|
||||
"logging_show_timestamps_var": logging_show_timestamps_var,
|
||||
"logging_use_dated_logs_var": logging_use_dated_logs_var,
|
||||
"logging_enable_monitor_var": logging_enable_monitor_var,
|
||||
"log_unified_enabled_var": log_unified_enabled_var,
|
||||
"log_unified_path_var": log_unified_path_var,
|
||||
"logging_keep_days_var": logging_keep_days_var,
|
||||
"logging_compress_logs_var": logging_compress_logs_var,
|
||||
"logging_max_total_size_gb_var": logging_max_total_size_gb_var,
|
||||
"logging_compress_after_days_var": logging_compress_after_days_var,
|
||||
"logging_performance_enabled_var": logging_performance_enabled_var,
|
||||
"logging_track_functions_var": logging_track_functions_var,
|
||||
"logging_debug_level_var": logging_debug_level_var,
|
||||
"logging_error_level_var": logging_error_level_var,
|
||||
"logging_action_format_var": logging_action_format_var,
|
||||
"logging_format_mode_var": logging_format_mode_var,
|
||||
"logging_monitor_warning_mb_var": logging_monitor_warning_mb_var,
|
||||
"logging_monitor_critical_mb_var": logging_monitor_critical_mb_var,
|
||||
"gui_theme_var": gui_theme_var,
|
||||
"gui_realtime_refresh_interval_ms_var": gui_realtime_refresh_interval_ms_var,
|
||||
"gui_realtime_tail_items_var": gui_realtime_tail_items_var,
|
||||
"skip_lt_seconds_var": skip_lt_seconds_var,
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
"""调试参数 Tab UI 创建逻辑(含 30 个 var + 4 个内部闭包)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 430 行的 widget 创建段。
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - ``left_notebook`` (tab 父容器)
|
||||
- ``vars_`` - 名→Var 的 ``Dict[str, tk.Variable]``,键名同原 ``main()``
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, BOTH, X
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def setup_debug_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame:
|
||||
debug_tab = ttk.Frame(parent)
|
||||
|
||||
# 为调试参数标签页添加滚动条
|
||||
debug_canvas = tk.Canvas(debug_tab, highlightthickness=0)
|
||||
debug_scrollbar = ttk.Scrollbar(
|
||||
debug_tab, orient="vertical", command=debug_canvas.yview
|
||||
)
|
||||
debug_scrollable_frame = ttk.Frame(debug_canvas)
|
||||
|
||||
debug_scrollable_frame.bind(
|
||||
"<Configure>",
|
||||
lambda e: debug_canvas.configure(scrollregion=debug_canvas.bbox("all")),
|
||||
)
|
||||
|
||||
debug_canvas.create_window((0, 0), window=debug_scrollable_frame, anchor="nw")
|
||||
debug_canvas.configure(yscrollcommand=debug_scrollbar.set)
|
||||
|
||||
# 鼠标滚轮支持
|
||||
def _on_mousewheel(event):
|
||||
debug_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
|
||||
|
||||
def _on_shift_mousewheel(event):
|
||||
debug_canvas.xview_scroll(int(-1 * (event.delta / 120)), "units")
|
||||
|
||||
debug_canvas.bind_all("<MouseWheel>", _on_mousewheel)
|
||||
debug_canvas.bind_all("<Shift-MouseWheel>", _on_shift_mousewheel)
|
||||
|
||||
debug_canvas.pack(side="left", fill="both", expand=True)
|
||||
debug_scrollbar.pack(side="right", fill="y")
|
||||
|
||||
parent.add(debug_tab, text="调试参数")
|
||||
|
||||
# 使用scrollable_frame作为容器
|
||||
debug_container = debug_scrollable_frame
|
||||
|
||||
# 调试图像
|
||||
debug_captures_box = ttk.LabelFrame(debug_container, text="调试图像")
|
||||
debug_captures_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
debug_r0 = ttk.Frame(debug_captures_box)
|
||||
debug_r0.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Checkbutton(
|
||||
debug_r0,
|
||||
text="保存调试图像(OCR / 像素 / 模板等)",
|
||||
variable=vars_["debug_captures_enabled_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
debug_r0,
|
||||
text="异步保存调试图像(默认启用)",
|
||||
variable=vars_["debug_captures_async_save_var"],
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Checkbutton(
|
||||
debug_r0,
|
||||
text="保存完成后记录日志(显示路径)",
|
||||
variable=vars_["debug_captures_log_on_complete_var"],
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
# 异步保存计数显示与重置
|
||||
debug_counts_frame = ttk.Frame(debug_r0)
|
||||
debug_counts_frame.pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Label(debug_counts_frame, text="异步保存:").pack(side=LEFT)
|
||||
ttk.Label(
|
||||
debug_counts_frame, textvariable=vars_["debug_async_success_var"], foreground="green"
|
||||
).pack(side=LEFT, padx=(4, 8))
|
||||
ttk.Label(debug_counts_frame, text="/").pack(side=LEFT)
|
||||
ttk.Label(
|
||||
debug_counts_frame, textvariable=vars_["debug_async_failure_var"], foreground="red"
|
||||
).pack(side=LEFT, padx=(4, 8))
|
||||
|
||||
def on_reset_async_counters():
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
douyin_screenshot_manager.reset_async_save_counters()
|
||||
vars_["debug_async_success_var"].set(0)
|
||||
vars_["debug_async_failure_var"].set(0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ttk.Button(
|
||||
debug_counts_frame, text="重置", command=on_reset_async_counters, width=6
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 周期性更新计数器(2秒)
|
||||
def _update_async_counters():
|
||||
try:
|
||||
from douyin.handlers import douyin_screenshot_manager
|
||||
s, f = douyin_screenshot_manager.get_async_save_counters()
|
||||
vars_["debug_async_success_var"].set(s)
|
||||
vars_["debug_async_failure_var"].set(f)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
debug_r0.after(2000, _update_async_counters)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 启动更新循环
|
||||
try:
|
||||
_update_async_counters()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
debug_cleanup_box = ttk.LabelFrame(debug_container, text="调试图像清理")
|
||||
debug_cleanup_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
debug_r1 = ttk.Frame(debug_cleanup_box)
|
||||
debug_r1.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Checkbutton(
|
||||
debug_r1, text="启用自动清理调试图像", variable=vars_["debug_captures_auto_cleanup_var"]
|
||||
).pack(side=LEFT)
|
||||
|
||||
debug_r2 = ttk.Frame(debug_cleanup_box)
|
||||
debug_r2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(debug_r2, text="保留天数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
debug_r2,
|
||||
from_=1,
|
||||
to=30,
|
||||
increment=1,
|
||||
textvariable=vars_["debug_captures_keep_days_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(debug_r2, text="最大文件数量:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
debug_r2,
|
||||
from_=100,
|
||||
to=10000,
|
||||
increment=100,
|
||||
textvariable=vars_["debug_captures_max_files_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(debug_r2, text="(超过此数量自动清理)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 找福袋参数
|
||||
fudai_find_box = ttk.LabelFrame(debug_container, text="找福袋参数")
|
||||
fudai_find_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
row4 = ttk.Frame(fudai_find_box)
|
||||
row4.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Label(row4, text="找福袋最大尝试次数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4,
|
||||
from_=0,
|
||||
to=50,
|
||||
increment=1,
|
||||
textvariable=vars_["fudai_find_max_attempts_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4, text="(0=使用默认值)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
row4b = ttk.Frame(fudai_find_box)
|
||||
row4b.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4b, text="找福袋重试间隔(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.1,
|
||||
to=3.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["fudai_icon_retry_delay_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4b, text=" 最大等待时间(秒):").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.0,
|
||||
to=30.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["fudai_icon_max_wait_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4b, text="(实际识别常见 4-6 秒)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
row4d = ttk.Frame(fudai_find_box)
|
||||
row4d.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4d, text="点击福袋后等待时间(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4d,
|
||||
from_=0.5,
|
||||
to=10.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["fudai_click_wait_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4d, text="(等待福袋详情页加载,默认1.0秒)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
row4c = ttk.Frame(fudai_find_box)
|
||||
row4c.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
row4c,
|
||||
text="禁用福袋内容OCR识别",
|
||||
variable=vars_["fudai_disable_content_recognition_var"],
|
||||
onvalue=True,
|
||||
offvalue=False,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4c, text="(仅影响 content OCR,不改其它识别模块)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 任务列表 OCR 开关
|
||||
ttk.Checkbutton(
|
||||
row4c,
|
||||
text="禁用福袋任务列表OCR识别",
|
||||
variable=vars_["fudai_disable_task_recognition_var"],
|
||||
onvalue=True,
|
||||
offvalue=False,
|
||||
).pack(side=LEFT, padx=(12, 0))
|
||||
|
||||
row4e = ttk.Frame(fudai_find_box)
|
||||
row4e.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4e, text="切换直播间后等待时间(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4e,
|
||||
from_=0.0,
|
||||
to=30.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["switch_room_wait_after_stage_diag_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4e, text="(阶段检测后等待福袋加载,默认7.0秒)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
row4c = ttk.Frame(fudai_find_box)
|
||||
row4c.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(row4c, text="直播间检测阈值(白色像素比例):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4c,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["live_room_match_threshold_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(
|
||||
row4c, text="(0.0~1.0,默认0.8,多边形区域白色像素比例>=此值判定为在直播间)"
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 鼠标配置
|
||||
mouse_config_box = ttk.LabelFrame(debug_container, text="鼠标配置")
|
||||
mouse_config_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
mouse_r1 = ttk.Frame(mouse_config_box)
|
||||
mouse_r1.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Label(mouse_r1, text="滑动速度(毫秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
mouse_r1,
|
||||
from_=100,
|
||||
to=2000,
|
||||
increment=50,
|
||||
textvariable=vars_["swipe_duration_ms_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(mouse_r1, text="(滑动持续时间,默认600ms,值越大滑动越慢)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
mouse_r2 = ttk.Frame(mouse_config_box)
|
||||
mouse_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(mouse_r2, text="上滑起始Y坐标:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
mouse_r2,
|
||||
from_=400,
|
||||
to=2000,
|
||||
increment=50,
|
||||
textvariable=vars_["swipe_up_start_y_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(mouse_r2, text="结束Y坐标:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
mouse_r2,
|
||||
from_=200,
|
||||
to=1800,
|
||||
increment=50,
|
||||
textvariable=vars_["swipe_up_end_y_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(mouse_r2, text="(基准1080x2400,默认1200→600,距离600px)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 阶段诊断时间参数(用于调试)
|
||||
diag_time_box = ttk.LabelFrame(debug_container, text="阶段诊断时间参数")
|
||||
diag_time_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
diag_time_r1 = ttk.Frame(diag_time_box)
|
||||
diag_time_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(diag_time_r1, text="最大诊断时间(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r1,
|
||||
from_=1.0,
|
||||
to=60.0,
|
||||
increment=1.0,
|
||||
textvariable=vars_["stage_diag_max_time_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r1, text="每步最大耗时(秒):").pack(side=LEFT, padx=(12, 0))
|
||||
ttk.Spinbox(
|
||||
diag_time_r1,
|
||||
from_=0.5,
|
||||
to=30.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["stage_diag_max_step_time_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r1, text="(用于调试,延长检测时间)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
diag_time_r2 = ttk.Frame(diag_time_box)
|
||||
diag_time_r2.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Checkbutton(
|
||||
diag_time_r2, text="详细阶段诊断日志", variable=vars_["stage_diag_verbose_var"]
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
diag_time_r2, text="启用OCR模式1(二值化)", variable=vars_["enable_ocr_mode1_var"]
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
diag_time_r2b = ttk.Frame(diag_time_box)
|
||||
diag_time_r2b.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Checkbutton(
|
||||
diag_time_r2b,
|
||||
text="启用福袋模板匹配",
|
||||
variable=vars_["fudai_template_match_enabled_var"],
|
||||
).pack(side=LEFT)
|
||||
diag_time_r3 = ttk.Frame(diag_time_box)
|
||||
diag_time_r3.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(diag_time_r3, text="福袋模板匹配阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r3,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["fudai_template_match_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r3, text="(0.0-1.0,彩色匹配)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
diag_time_r3b = ttk.Frame(diag_time_box)
|
||||
diag_time_r3b.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(diag_time_r3b, text="福袋详情页模板匹配阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r3b,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["fudai_detail_template_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(
|
||||
diag_time_r3b, text="(0.0-1.0,默认0.7,区域(398,894)-(658,1179))"
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
diag_time_r4 = ttk.Frame(diag_time_box)
|
||||
diag_time_r4.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(diag_time_r4, text="开奖页红色占比阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r4,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["lucky_draw_red_ratio_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r4, text="(默认0.90,≥此占比判定开奖页)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 更多模板匹配阈值
|
||||
diag_time_r5 = ttk.Frame(diag_time_box)
|
||||
diag_time_r5.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Label(diag_time_r5, text="优惠券模板匹配阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
diag_time_r5,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["coupon_template_match_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(diag_time_r5, text="(默认0.75,用于检测优惠券弹窗)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 像素检测阈值
|
||||
pixel_detect_box = ttk.LabelFrame(debug_container, text="像素检测阈值")
|
||||
pixel_detect_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
pixel_r1 = ttk.Frame(pixel_detect_box)
|
||||
pixel_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(pixel_r1, text="参与按钮红色占比阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
pixel_r1,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["attend_button_red_ratio_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(pixel_r1, text="(默认0.25,用于检测参与按钮)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
pixel_r2 = ttk.Frame(pixel_detect_box)
|
||||
pixel_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(pixel_r2, text="粉丝团加入红色占比阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
pixel_r2,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["fansclub_join_red_ratio_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(pixel_r2, text="(默认0.25,用于检测粉丝团加入按钮)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
pixel_r3 = ttk.Frame(pixel_detect_box)
|
||||
pixel_r3.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(pixel_r3, text="购物红包背景红色占比阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
pixel_r3,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["shopping_redpacket_red_ratio_threshold_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(pixel_r3, text="(默认0.15,用于检测购物红包弹窗背景)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
return debug_tab
|
||||
@@ -0,0 +1,115 @@
|
||||
"""筛选设置 Tab UI 创建逻辑(9 个 var)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 100 行的 widget 创建段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def setup_filter_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame:
|
||||
filter_tab = ttk.Frame(parent)
|
||||
parent.add(filter_tab, text="筛选设置")
|
||||
|
||||
cfg_box = ttk.LabelFrame(filter_tab, text="福袋筛选条件")
|
||||
cfg_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
row = ttk.Frame(cfg_box)
|
||||
row.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Label(row, text="最低价值(元):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row,
|
||||
from_=0,
|
||||
to=99999,
|
||||
increment=0.01,
|
||||
format="%.2f",
|
||||
textvariable=vars_["min_value_var"],
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
|
||||
rowp = ttk.Frame(cfg_box)
|
||||
rowp.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(rowp, text="参与人数范围:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
rowp,
|
||||
from_=0,
|
||||
to=99999999,
|
||||
increment=1,
|
||||
textvariable=vars_["min_participants_var"],
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(rowp, text=" ~ ").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
rowp,
|
||||
from_=0,
|
||||
to=99999999,
|
||||
increment=1,
|
||||
textvariable=vars_["max_participants_var"],
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(rowp, text="(填0表示不限制)").pack(side=LEFT)
|
||||
|
||||
row2 = ttk.Frame(cfg_box)
|
||||
row2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row2, text="倒计时小于(秒)时不参与:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row2, from_=0, to=300, increment=1, textvariable=vars_["skip_lt_seconds_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row2, text="(剩余时间太短,不参与)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
row3 = ttk.Frame(cfg_box)
|
||||
row3.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
row3, text="自动加入粉丝团(谨慎:可能消耗钻石)", variable=vars_["auto_join_var"]
|
||||
).pack(side=LEFT)
|
||||
|
||||
row4 = ttk.Frame(cfg_box)
|
||||
row4.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(row4, text="粉丝团失败策略:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
row4,
|
||||
textvariable=vars_["fansclub_action_var"],
|
||||
values=["stay", "switch"],
|
||||
width=10,
|
||||
state="readonly",
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(row4, text="(stay=停留,switch=切换直播间)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
# 粉丝团等待/点击延迟设置
|
||||
row4b = ttk.Frame(cfg_box)
|
||||
row4b.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(row4b, text="粉丝团点击延迟(s):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.1,
|
||||
to=5.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["fansclub_click_delay_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 12))
|
||||
ttk.Label(row4b, text="自动加入等待(s):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.5,
|
||||
to=10.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["fansclub_auto_wait_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 12))
|
||||
ttk.Label(row4b, text="手动加入等待(s):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
row4b,
|
||||
from_=0.5,
|
||||
to=10.0,
|
||||
increment=0.5,
|
||||
textvariable=vars_["fansclub_manual_wait_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 标签页3:高价值预约
|
||||
return filter_tab
|
||||
@@ -0,0 +1,39 @@
|
||||
"""高价值房间 Tab 视图刷新逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``refresh_high_value_rooms``,
|
||||
负责读 ``state/high_value_rooms.json`` 并以 JSON 格式渲染到 Tab。
|
||||
|
||||
依赖通过显式参数注入:``text_widget`` (展示用的 ScrolledText/Text widget)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tkinter as tk
|
||||
|
||||
|
||||
def refresh_high_value_rooms(text_widget: tk.Text) -> None:
|
||||
try:
|
||||
from douyin.core.path_config import get_high_value_rooms_path
|
||||
|
||||
path = get_high_value_rooms_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
from douyin.core import path_config
|
||||
|
||||
path = path_config.get_high_value_rooms_path()
|
||||
try:
|
||||
if os.path.exists(path):
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert(
|
||||
"1.0", json.dumps(data, ensure_ascii=False, indent=2)
|
||||
)
|
||||
else:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", "暂无高价值房间数据")
|
||||
except Exception as e:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", f"读取高价值房间失败:{e}")
|
||||
@@ -0,0 +1,41 @@
|
||||
"""关键词 Tab UI 创建逻辑(白名单 + 黑名单)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 18 行的 widget 创建段。
|
||||
|
||||
返回 ``(want_text, not_want_text)`` 两个 ScrolledText widget,供 main() 后续
|
||||
绑定到 ``_config_io_texts`` 字典用于 load/save 配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, X
|
||||
from typing import Any, Tuple
|
||||
|
||||
|
||||
def setup_keywords_tab(
|
||||
parent: ttk.Notebook,
|
||||
*,
|
||||
ScrolledText_cls: Any,
|
||||
) -> Tuple[tk.Text, tk.Text]:
|
||||
"""构建关键词 Tab,返回 ``(want_text, not_want_text)``。"""
|
||||
keywords_tab = ttk.Frame(parent)
|
||||
parent.add(keywords_tab, text="关键词")
|
||||
|
||||
kw_box = ttk.LabelFrame(keywords_tab, text="关键词(每行一个)")
|
||||
kw_box.pack(fill=BOTH, expand=True, padx=10, pady=(10, 10))
|
||||
|
||||
ttk.Label(kw_box, text="想要 contains_want(白名单,空=不限制)").pack(
|
||||
anchor="w", padx=10, pady=(10, 4)
|
||||
)
|
||||
want_text = ScrolledText_cls(kw_box, height=6)
|
||||
want_text.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
ttk.Label(kw_box, text="不想要 contains_not_want(黑名单)").pack(
|
||||
anchor="w", padx=10, pady=(0, 4)
|
||||
)
|
||||
not_want_text = ScrolledText_cls(kw_box, height=8)
|
||||
not_want_text.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
return want_text, not_want_text
|
||||
@@ -0,0 +1,127 @@
|
||||
"""左侧配置区:PanedWindow 布局 + 7 个配置 Tab + load/save_ui_to_config 闭包。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- ``ttk.PanedWindow`` (左/右分栏)
|
||||
- 左侧 ``ttk.Notebook`` 容器
|
||||
- 7 个配置 Tab(运行/筛选/高价值预约/养号/调试/日志/关键词)
|
||||
- ``load_config_to_ui`` / ``save_ui_to_config`` / ``save_logging_config`` 闭包
|
||||
- 启动时一次 ``load_config_to_ui()``
|
||||
|
||||
返回 ``LeftConfigArea`` 暴露给 ``main()`` 的引用:
|
||||
- ``right_frame``: 右侧分栏(传给后续 setup_main_notebook)
|
||||
- ``save_ui_to_config``: 保存配置回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from gui.components.config_io import (
|
||||
load_config_to_ui as _load_config_to_ui_impl,
|
||||
save_ui_to_config as _save_ui_to_config_impl,
|
||||
)
|
||||
from gui.components.logging_config_io import save_logging_config as _save_logging_config_impl
|
||||
from gui.components.run_tab import setup_run_tab
|
||||
from gui.components.filter_tab import setup_filter_tab
|
||||
from gui.components.reservation_tab import setup_reservation_tab
|
||||
from gui.components.yanghao_tab import setup_yanghao_tab
|
||||
from gui.components.debug_tab import setup_debug_tab
|
||||
from gui.components.logging_tab import setup_logging_tab
|
||||
from gui.components.keywords_tab import setup_keywords_tab
|
||||
|
||||
|
||||
@dataclass
|
||||
class LeftConfigArea:
|
||||
"""``main()`` 后续仍要用的引用。"""
|
||||
|
||||
right_frame: ttk.Frame
|
||||
save_ui_to_config: Callable[[], None]
|
||||
|
||||
|
||||
def setup_left_config_area(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
cfg: dict,
|
||||
ScrolledText_cls: Any,
|
||||
read_config: Callable[[], dict],
|
||||
write_config: Callable[[dict], None],
|
||||
on_line: Callable[[str], None],
|
||||
) -> LeftConfigArea:
|
||||
"""构建左侧配置区(PanedWindow + 7 Tabs + load/save 闭包)。
|
||||
|
||||
``cfg`` 由调用方传入,``load_config_to_ui`` 内部把读到的新 cfg 重新赋回
|
||||
``cfg`` dict 的内容(不能 reassign 局部 var,所以用 ``dict.clear() + update``)。
|
||||
"""
|
||||
# 中部:左侧配置(使用 Notebook 标签页) + 右侧日志/预览(支持拖拽调整宽度)
|
||||
mid = ttk.PanedWindow(root, orient="horizontal")
|
||||
mid.pack(fill=BOTH, expand=True, padx=12, pady=(0, 12))
|
||||
|
||||
left_wrap = ttk.Frame(mid)
|
||||
right_frame = ttk.Frame(mid)
|
||||
mid.add(left_wrap, weight=0) # 左侧配置区域
|
||||
mid.add(right_frame, weight=1) # 右侧日志/预览区域
|
||||
|
||||
# 左侧使用 Notebook 标签页组织配置
|
||||
left_notebook = ttk.Notebook(left_wrap)
|
||||
left_notebook.pack(fill=BOTH, expand=True)
|
||||
|
||||
def save_logging_config() -> None:
|
||||
_save_logging_config_impl(
|
||||
vars_=vars_,
|
||||
read_config=read_config,
|
||||
write_config=write_config,
|
||||
on_line=on_line,
|
||||
)
|
||||
|
||||
# 创建左侧配置标签页
|
||||
setup_run_tab(left_notebook, vars_=vars_)
|
||||
setup_filter_tab(left_notebook, vars_=vars_)
|
||||
setup_reservation_tab(left_notebook, vars_=vars_)
|
||||
_, yg_comment_texts, yg_like_keywords_text, yg_fav_keywords_text = setup_yanghao_tab(
|
||||
left_notebook, vars_=vars_,
|
||||
)
|
||||
setup_debug_tab(left_notebook, vars_=vars_)
|
||||
setup_logging_tab(left_notebook, vars_=vars_, on_save_logging=save_logging_config)
|
||||
want_text, not_want_text = setup_keywords_tab(
|
||||
left_notebook, ScrolledText_cls=ScrolledText_cls,
|
||||
)
|
||||
|
||||
texts_ = {
|
||||
"not_want_text": not_want_text,
|
||||
"want_text": want_text,
|
||||
"yg_comment_texts": yg_comment_texts,
|
||||
"yg_fav_keywords_text": yg_fav_keywords_text,
|
||||
"yg_like_keywords_text": yg_like_keywords_text,
|
||||
}
|
||||
|
||||
def load_config_to_ui() -> None:
|
||||
# cfg 是 dict 的 alias,我们替换它的内容(不 reassign 否则丢失 main 的引用)
|
||||
new_cfg = _load_config_to_ui_impl(
|
||||
vars_=vars_,
|
||||
texts_=texts_,
|
||||
read_config=read_config,
|
||||
)
|
||||
cfg.clear()
|
||||
cfg.update(new_cfg)
|
||||
|
||||
def save_ui_to_config() -> None:
|
||||
_save_ui_to_config_impl(
|
||||
vars_=vars_,
|
||||
texts_=texts_,
|
||||
cfg=cfg,
|
||||
read_config=read_config,
|
||||
write_config=write_config,
|
||||
on_line=on_line,
|
||||
)
|
||||
|
||||
load_config_to_ui()
|
||||
|
||||
return LeftConfigArea(
|
||||
right_frame=right_frame,
|
||||
save_ui_to_config=save_ui_to_config,
|
||||
)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""GUI 日志管道工厂:queue + 线程安全文件写入 + Runner 集成。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出 on_line 闭包及其依赖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
from typing import Any, Callable, Tuple
|
||||
|
||||
from gui.gui_core import Runner
|
||||
from gui.components.log_writer import ThreadSafeLogWriter
|
||||
|
||||
_LOGGER = logging.getLogger("gui.gui_app")
|
||||
|
||||
|
||||
def _format_gui_log_line(line: str) -> str:
|
||||
"""将完整日志行转换为 GUI 显示用的精简版本。
|
||||
|
||||
实际实现位于 ``gui.components.log_viewer``,失败时回退到原始字符串。
|
||||
"""
|
||||
try:
|
||||
from gui.components.log_viewer import format_gui_log_line as _impl
|
||||
|
||||
return _impl(line)
|
||||
except Exception:
|
||||
return (line or "").rstrip("\n")
|
||||
|
||||
|
||||
def setup_log_pipeline() -> Tuple["queue.Queue[str]", Any, Callable[[str], None], Any]:
|
||||
"""构建 log queue + ThreadSafeLogWriter + on_line + Runner。
|
||||
|
||||
返回 ``(q, log_writer, on_line, runner)``,主程序后续把 ``runner`` 传入按钮回调,
|
||||
把 ``q`` 传入 ``pump_logs`` 用于 GUI 端消费。
|
||||
"""
|
||||
q: "queue.Queue[str]" = queue.Queue()
|
||||
log_writer = ThreadSafeLogWriter()
|
||||
|
||||
def on_line(line: str) -> None:
|
||||
"""处理日志行:GUI 显示用精简版本,文件写入用完整版本"""
|
||||
# GUI 显示:使用精简后的版本
|
||||
try:
|
||||
display_line = _format_gui_log_line(line)
|
||||
except Exception:
|
||||
display_line = line
|
||||
q.put(display_line)
|
||||
|
||||
# 文件:写入完整日志行(不做精简处理)
|
||||
try:
|
||||
log_writer.write(line)
|
||||
except Exception:
|
||||
pass # 文件写入失败不应影响GUI显示
|
||||
|
||||
runner = Runner(on_line=on_line)
|
||||
return q, log_writer, on_line, runner
|
||||
@@ -0,0 +1,143 @@
|
||||
"""GUI 日志泵: 把后台线程发来的日志行批量插入到日志 Text widget。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``pump_logs``,
|
||||
通过 ``root.after(100, pump_logs)`` 自递归调度。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``log_queue`` - 后台线程往里塞日志行的 ``queue.Queue``
|
||||
- ``text_widget`` - 展示用的 Text/ScrolledText
|
||||
- ``filter_getter`` - ``() -> str`` 返回筛选关键字(已 strip)
|
||||
- ``theme_getter`` - ``() -> str`` 返回当前主题名
|
||||
- ``root`` - 主窗口(用于自递归 ``after``)
|
||||
- ``is_running_getter`` - ``() -> bool`` 返回 runner 是否还在跑
|
||||
- ``status_getter`` - ``() -> str`` 读取状态文本
|
||||
- ``status_setter`` - ``(str) -> None`` 写入状态文本
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
import re
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
try:
|
||||
from gui.components.log_color_config import (
|
||||
apply_operation_color,
|
||||
get_operation_type,
|
||||
)
|
||||
except ImportError:
|
||||
def get_operation_type(line: str): # type: ignore[no-redef]
|
||||
return None
|
||||
|
||||
def apply_operation_color(*args, **kwargs): # type: ignore[no-redef]
|
||||
pass
|
||||
|
||||
_LOGGER = logging.getLogger("gui.gui_app")
|
||||
|
||||
|
||||
def pump_logs(
|
||||
log_queue: "queue.Queue[str]",
|
||||
*,
|
||||
text_widget: tk.Text,
|
||||
filter_getter: Callable[[], str],
|
||||
theme_getter: Callable[[], str],
|
||||
root: tk.Misc,
|
||||
is_running_getter: Callable[[], bool],
|
||||
status_getter: Callable[[], str],
|
||||
status_setter: Callable[[str], None],
|
||||
) -> None:
|
||||
changed = False
|
||||
try:
|
||||
# 获取当前主题(用于颜色配置)
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
while True:
|
||||
line = log_queue.get_nowait()
|
||||
# 运行日志关键字筛选(与行为日志一致)
|
||||
try:
|
||||
kw = filter_getter()
|
||||
if kw and kw not in line:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
# 插入日志行并应用颜色标签
|
||||
start_pos = text_widget.index("end-1c")
|
||||
|
||||
# 插入文本
|
||||
text_widget.insert("end", line + "\n")
|
||||
end_pos = text_widget.index("end-1c")
|
||||
|
||||
# 优先级1: 先检查操作类型颜色(更具体)
|
||||
op_type_applied = False
|
||||
try:
|
||||
op_type = get_operation_type(line)
|
||||
if op_type:
|
||||
apply_operation_color(
|
||||
text_widget, start_pos, end_pos, line, current_theme
|
||||
)
|
||||
op_type_applied = True
|
||||
except Exception:
|
||||
pass # 忽略操作类型颜色应用失败
|
||||
|
||||
# 优先级2: 再检查日志级别标签(作为补充,如果操作类型未匹配)
|
||||
# 只有在没有操作类型颜色时才应用级别标签
|
||||
if not op_type_applied:
|
||||
try:
|
||||
tag = None
|
||||
if "[INFO]" in line:
|
||||
tag = "log_info"
|
||||
elif "[WARNING]" in line:
|
||||
tag = "log_warning"
|
||||
elif "[ERROR]" in line:
|
||||
tag = "log_error"
|
||||
elif "[CRITICAL]" in line:
|
||||
tag = "log_critical"
|
||||
elif "elapsed_seconds=" in line or "耗时" in line:
|
||||
tag = "log_performance"
|
||||
elif re.search(r"\[[\w\.]+\]", line):
|
||||
tag = "log_module"
|
||||
|
||||
if tag:
|
||||
text_widget.tag_add(tag, start_pos, end_pos)
|
||||
except Exception:
|
||||
pass # 忽略级别标签应用失败
|
||||
|
||||
# 不再自动滚动到底部,让用户自由控制滚动位置
|
||||
changed = True
|
||||
except Exception as e:
|
||||
# 如果插入日志失败,至少记录到 logger(调试用)
|
||||
_LOGGER.error("[GUI日志错误] 无法插入日志: %s", e)
|
||||
except queue.Empty:
|
||||
pass
|
||||
except Exception as e:
|
||||
# 捕获其他异常,确保日志循环不会中断
|
||||
_LOGGER.error("[GUI日志错误] pump_logs异常: %s", e)
|
||||
|
||||
try:
|
||||
if changed and not is_running_getter() and status_getter() == "运行中":
|
||||
status_setter("已结束")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 确保递归调用始终执行,即使前面出现异常
|
||||
try:
|
||||
root.after(100, lambda: pump_logs(
|
||||
log_queue,
|
||||
text_widget=text_widget,
|
||||
filter_getter=filter_getter,
|
||||
theme_getter=theme_getter,
|
||||
root=root,
|
||||
is_running_getter=is_running_getter,
|
||||
status_getter=status_getter,
|
||||
status_setter=status_setter,
|
||||
)) # type: ignore[arg-type]
|
||||
except Exception as e:
|
||||
# 如果 root 已被销毁,停止日志循环
|
||||
_LOGGER.warning("[GUI日志错误] 无法调度下次日志更新: %s", e)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""运行日志 Tab 的搜索工具栏(关键字筛选 + 文本搜索)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的搜索栏 widget 创建段 +
|
||||
5 个共享 ``nonlocal`` matches state 的搜索闭包。
|
||||
|
||||
抽出后用一个 ``LogSearchToolbarHandles`` namedtuple 暴露 main 仍要用的引用:
|
||||
- ``log_filter_var`` - 关键字筛选 StringVar(被 refresh_run_log/auto_refresh 用)
|
||||
- ``refresh_run_log`` - 刷新回调(被 root.after 调度用)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X, Y
|
||||
from typing import Any, Callable
|
||||
|
||||
from gui.components.run_log_view import refresh_run_log as _refresh_run_log_impl
|
||||
from gui.components.text_search import generic_search_widget
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogSearchToolbarHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
log_filter_var: tk.StringVar
|
||||
refresh_run_log: Callable[[], None]
|
||||
|
||||
|
||||
def setup_log_search_toolbar(
|
||||
parent: tk.Misc,
|
||||
*,
|
||||
log_text: tk.Text,
|
||||
runner: Any,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> LogSearchToolbarHandles:
|
||||
"""构建运行日志 Tab 顶部的搜索工具栏。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - 工具栏父容器(``log_box``)
|
||||
- ``log_text`` - 日志文本 widget(搜索高亮 + 内容刷新的目标)
|
||||
- ``runner`` - 运行控制器(暴露 ``_lock`` / ``_log`` 给刷新回调)
|
||||
- ``theme_getter`` - ``() -> str`` 返回当前 GUI 主题名
|
||||
"""
|
||||
log_search_frame = ttk.Frame(parent)
|
||||
log_search_frame.pack(fill=X, padx=10, pady=(10, 5))
|
||||
|
||||
# 关键字筛选(与行为日志一致)
|
||||
log_filter_var = tk.StringVar(value="")
|
||||
ttk.Label(log_search_frame, text="筛选:").pack(side=LEFT)
|
||||
ttk.Entry(log_search_frame, textvariable=log_filter_var, width=16).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
log_search_var = tk.StringVar(value="")
|
||||
log_search_entry = ttk.Entry(
|
||||
log_search_frame, textvariable=log_search_var, width=20
|
||||
)
|
||||
|
||||
def refresh_run_log() -> None:
|
||||
_refresh_run_log_impl(
|
||||
runner,
|
||||
text_widget=log_text,
|
||||
filter_getter=lambda: log_filter_var.get().strip(),
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
|
||||
# 搜索状态用可变容器持有,5 个内层闭包共享。
|
||||
state = {
|
||||
"matches": [],
|
||||
"current_index": -1,
|
||||
}
|
||||
|
||||
def search_in_log_text(direction: int = 1) -> None:
|
||||
"""在运行日志中搜索文本(调用通用搜索实现)"""
|
||||
state["current_index"] = generic_search_widget(
|
||||
log_text,
|
||||
log_search_var,
|
||||
state["matches"],
|
||||
state["current_index"],
|
||||
direction,
|
||||
)
|
||||
|
||||
def search_next_in_log() -> None:
|
||||
"""搜索下一个"""
|
||||
search_in_log_text(1)
|
||||
|
||||
def search_prev_in_log() -> None:
|
||||
"""搜索上一个"""
|
||||
search_in_log_text(-1)
|
||||
|
||||
def clear_search_in_log() -> None:
|
||||
"""清除搜索高亮"""
|
||||
log_search_var.set("")
|
||||
log_text.tag_remove("search_highlight", "1.0", "end")
|
||||
log_text.tag_remove("search_current", "1.0", "end")
|
||||
state["matches"] = []
|
||||
state["current_index"] = -1
|
||||
|
||||
# 绑定回车键搜索
|
||||
def on_log_search_entry_key(event):
|
||||
if event.keysym == "Return":
|
||||
search_next_in_log()
|
||||
|
||||
log_search_entry.bind("<KeyPress>", on_log_search_entry_key)
|
||||
|
||||
# 将 刷新 放在筛选后面,搜索区域与行为日志一致(带分隔条)
|
||||
ttk.Button(log_search_frame, text="刷新", command=refresh_run_log).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Separator(log_search_frame, orient="vertical").pack(
|
||||
side=LEFT, fill=Y, padx=5, pady=3
|
||||
)
|
||||
ttk.Label(log_search_frame, text="搜索:").pack(side=LEFT)
|
||||
# 把搜索输入框放在分隔符后
|
||||
log_search_entry.pack(side=LEFT, padx=(0, 5))
|
||||
ttk.Button(log_search_frame, text="搜索", command=search_next_in_log).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(log_search_frame, text="上一个", command=search_prev_in_log).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(log_search_frame, text="下一个", command=search_next_in_log).pack(
|
||||
side=LEFT, padx=(0, 2)
|
||||
)
|
||||
ttk.Button(log_search_frame, text="清除", command=clear_search_in_log).pack(
|
||||
side=LEFT, padx=(0, 5)
|
||||
)
|
||||
|
||||
return LogSearchToolbarHandles(
|
||||
log_filter_var=log_filter_var,
|
||||
refresh_run_log=refresh_run_log,
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""运行日志 Tab 的 widget 创建段(log_box + log_text + 搜索工具栏 + 配色)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。返回 ``LogTabHandles`` 暴露给 ``main()`` 后续 pump_logs。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH
|
||||
from typing import Any, Callable
|
||||
|
||||
from gui.components.log_search_toolbar import (
|
||||
setup_log_search_toolbar,
|
||||
LogSearchToolbarHandles,
|
||||
)
|
||||
from gui.components.log_text_colors import configure_log_text_colors
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogTabHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
log_text: tk.Text
|
||||
log_filter_var: tk.StringVar
|
||||
refresh_run_log: Callable[[], None]
|
||||
|
||||
|
||||
def setup_log_tab(
|
||||
log_tab: tk.Misc,
|
||||
*,
|
||||
runner: Any,
|
||||
ScrolledText_cls: Any,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> LogTabHandles:
|
||||
"""构建运行日志 Tab(log_box + log_text + 搜索工具栏 + 配色)。"""
|
||||
log_box = ttk.Frame(log_tab)
|
||||
log_box.pack(fill=BOTH, expand=True)
|
||||
|
||||
log_text = ScrolledText_cls(log_box)
|
||||
try:
|
||||
log_text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
log_text.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||||
|
||||
handles: LogSearchToolbarHandles = setup_log_search_toolbar(
|
||||
log_box,
|
||||
log_text=log_text,
|
||||
runner=runner,
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
|
||||
configure_log_text_colors(log_text, theme_getter=theme_getter)
|
||||
|
||||
return LogTabHandles(
|
||||
log_text=log_text,
|
||||
log_filter_var=handles.log_filter_var,
|
||||
refresh_run_log=handles.refresh_run_log,
|
||||
)
|
||||
@@ -0,0 +1,97 @@
|
||||
"""运行日志 widget 的主题颜色配置。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的内联段,根据当前 GUI 主题
|
||||
为 log_text 配置背景/前景色 + 多种 log_xxx 标签 + 操作类型颜色标签。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``text_widget`` - 待配置的 Text/ScrolledText
|
||||
- ``theme_getter`` - ``() -> str`` 返回当前主题名
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
try:
|
||||
from gui.components.log_color_config import get_color_config
|
||||
except ImportError:
|
||||
def get_color_config(theme: str = "litera"): # type: ignore[no-redef]
|
||||
return {}
|
||||
|
||||
|
||||
def configure_log_text_colors(
|
||||
text_widget: tk.Text,
|
||||
*,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> None:
|
||||
# 配置日志颜色标签(如果支持颜色)
|
||||
try:
|
||||
# 根据主题调整日志颜色(明亮主题使用深色文字/蓝色系)
|
||||
light_themes = {"litera", "flatly", "journal", "minty", "cosmo"}
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
if current_theme in light_themes:
|
||||
# 明亮主题 - 使用更适合人眼观看的颜色组合
|
||||
text_widget.configure(
|
||||
background="#FFFFFF", foreground="#2C2C2C", insertbackground="#2C2C2C"
|
||||
)
|
||||
text_widget.tag_configure("log_timestamp", foreground="#8B8B8B") # 柔和的灰色
|
||||
text_widget.tag_configure(
|
||||
"log_info", foreground="#1E88E5"
|
||||
) # 明亮的蓝色,易于阅读
|
||||
text_widget.tag_configure(
|
||||
"log_warning", foreground="#F57C00"
|
||||
) # 橙色,警告色但不过于刺眼
|
||||
text_widget.tag_configure(
|
||||
"log_error", foreground="#D32F2F"
|
||||
) # 深红色,醒目但不刺眼
|
||||
text_widget.tag_configure(
|
||||
"log_critical", foreground="#B71C1C", font=("Consolas", 10, "bold")
|
||||
) # 加粗深红色
|
||||
text_widget.tag_configure(
|
||||
"log_performance", foreground="#388E3C"
|
||||
) # 深绿色,性能指标
|
||||
text_widget.tag_configure("log_module", foreground="#7B1FA2") # 紫色,模块标识
|
||||
else:
|
||||
# 暗色主题 - 优化对比度和可读性
|
||||
text_widget.configure(
|
||||
background="#1E1E1E", foreground="#E0E0E0", insertbackground="#FFFFFF"
|
||||
)
|
||||
text_widget.tag_configure(
|
||||
"log_timestamp", foreground="#A0A0A0"
|
||||
) # 浅灰色时间戳
|
||||
text_widget.tag_configure("log_info", foreground="#64B5F6") # 亮蓝色,信息级
|
||||
text_widget.tag_configure(
|
||||
"log_warning", foreground="#FFB74D"
|
||||
) # 金色警告,暗色背景下醒目
|
||||
text_widget.tag_configure(
|
||||
"log_error", foreground="#EF5350"
|
||||
) # 亮红色,错误突出
|
||||
text_widget.tag_configure(
|
||||
"log_critical", foreground="#F44336", font=("Consolas", 10, "bold")
|
||||
) # 加粗亮红色
|
||||
text_widget.tag_configure(
|
||||
"log_performance", foreground="#81C784"
|
||||
) # 亮绿色,性能数据
|
||||
text_widget.tag_configure(
|
||||
"log_module", foreground="#BA68C8"
|
||||
) # 亮紫色,模块标识
|
||||
|
||||
# 配置操作类型颜色标签(使用模块化配置)
|
||||
try:
|
||||
color_config = get_color_config(current_theme)
|
||||
for op_type, colors in color_config.items():
|
||||
tag_name = f"op_{op_type}"
|
||||
text_widget.tag_configure(
|
||||
tag_name,
|
||||
foreground=colors["foreground"],
|
||||
background=colors["background"],
|
||||
)
|
||||
except Exception:
|
||||
pass # 忽略操作类型颜色配置失败
|
||||
except Exception:
|
||||
pass # 忽略标签配置失败
|
||||
@@ -0,0 +1,82 @@
|
||||
"""日志配置 + GUI 主题保存逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``save_logging_config``,
|
||||
读取 18 个 tkinter Var 写入 config.json。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``vars_`` - 一个名→Var 的 ``Dict[str, tk.Variable]``,键名与原 main() 中的变量名一致
|
||||
- ``read_config`` - 读配置回调
|
||||
- ``write_config`` - 写配置回调
|
||||
- ``on_line`` - 日志回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Callable, Dict
|
||||
|
||||
|
||||
def save_logging_config(
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
read_config: Callable[[], dict],
|
||||
write_config: Callable[[dict], None],
|
||||
on_line: Callable[[str], None],
|
||||
) -> None:
|
||||
"""保存日志配置到配置文件"""
|
||||
try:
|
||||
# 读取当前配置
|
||||
cfg = read_config()
|
||||
|
||||
# 更新日志相关配置
|
||||
if "logging" not in cfg:
|
||||
cfg["logging"] = {}
|
||||
|
||||
cfg["logging"]["log_format_mode"] = vars_["logging_format_mode_var"].get()
|
||||
cfg["logging"]["beautify_output"] = bool(vars_["logging_beautify_var"].get())
|
||||
cfg["logging"]["color_output"] = bool(vars_["logging_color_var"].get())
|
||||
cfg["logging"]["show_timestamps"] = bool(vars_["logging_show_timestamps_var"].get())
|
||||
cfg["logging"]["use_dated_logs"] = bool(vars_["logging_use_dated_logs_var"].get())
|
||||
cfg["logging"]["debug_detail_level"] = vars_["logging_debug_level_var"].get()
|
||||
cfg["logging"]["error_detail_level"] = vars_["logging_error_level_var"].get()
|
||||
cfg["logging"]["action_log_format"] = vars_["logging_action_format_var"].get()
|
||||
cfg["logging"]["enable_monitor"] = bool(vars_["logging_enable_monitor_var"].get())
|
||||
cfg["logging"]["keep_days"] = int(vars_["logging_keep_days_var"].get())
|
||||
cfg["logging"]["compress_logs"] = bool(vars_["logging_compress_logs_var"].get())
|
||||
cfg["logging"]["max_total_size_gb"] = float(
|
||||
vars_["logging_max_total_size_gb_var"].get()
|
||||
)
|
||||
cfg["logging"]["compress_after_days"] = int(
|
||||
vars_["logging_compress_after_days_var"].get()
|
||||
)
|
||||
cfg["logging"]["monitor_warning_mb"] = float(
|
||||
vars_["logging_monitor_warning_mb_var"].get()
|
||||
)
|
||||
cfg["logging"]["monitor_critical_mb"] = float(
|
||||
vars_["logging_monitor_critical_mb_var"].get()
|
||||
)
|
||||
cfg["logging"]["performance_tracking"] = {
|
||||
"enabled": bool(vars_["logging_performance_enabled_var"].get()),
|
||||
"track_function_calls": bool(vars_["logging_track_functions_var"].get()),
|
||||
}
|
||||
cfg["log_unified_enabled"] = bool(vars_["log_unified_enabled_var"].get())
|
||||
cfg["log_unified_path"] = str(vars_["log_unified_path_var"].get() or "logs/unified.log")
|
||||
|
||||
# 更新GUI主题
|
||||
if "gui" not in cfg:
|
||||
cfg["gui"] = {}
|
||||
cfg["gui"]["theme"] = vars_["gui_theme_var"].get()
|
||||
cfg["gui"]["realtime_status"] = {
|
||||
"refresh_interval_ms": int(
|
||||
vars_["gui_realtime_refresh_interval_ms_var"].get() or 1000
|
||||
),
|
||||
"tail_items": int(vars_["gui_realtime_tail_items_var"].get() or 50),
|
||||
}
|
||||
|
||||
# 保存配置
|
||||
write_config(cfg)
|
||||
|
||||
on_line("[配置] 日志配置已保存")
|
||||
except Exception as e:
|
||||
on_line(f"[配置] 保存日志配置失败:{e}")
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
"""日志配置 Tab UI 创建逻辑(23 个 var)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 230 行的 widget 创建段。
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - ``left_notebook`` (tab 父容器)
|
||||
- ``vars_`` - 名→Var 的 ``Dict[str, tk.Variable]``,键名同原 ``main()``
|
||||
- ``on_save_logging`` - "保存日志配置"按钮的回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, BOTH, X
|
||||
from typing import Callable, Dict
|
||||
|
||||
|
||||
def setup_logging_tab(
|
||||
parent: ttk.Notebook,
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
on_save_logging: Callable[[], None],
|
||||
) -> ttk.Frame:
|
||||
logging_tab = ttk.Frame(parent)
|
||||
parent.add(logging_tab, text="日志配置")
|
||||
|
||||
# 日志配置容器
|
||||
logging_container = ttk.Frame(logging_tab)
|
||||
logging_container.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||||
|
||||
# 日志格式设置
|
||||
log_format_box = ttk.LabelFrame(logging_container, text="日志格式")
|
||||
log_format_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
# 日志格式模式
|
||||
log_format_r1 = ttk.Frame(log_format_box)
|
||||
log_format_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(log_format_r1, text="日志格式模式:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_format_r1,
|
||||
values=["simple", "detailed"],
|
||||
textvariable=vars_["logging_format_mode_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(log_format_r1, text="(simple=简洁模式,detailed=详细模式用于debug)").pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 日志美化选项
|
||||
log_format_r2 = ttk.Frame(log_format_box)
|
||||
log_format_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Checkbutton(
|
||||
log_format_r2,
|
||||
text="启用日志美化",
|
||||
variable=vars_["logging_beautify_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
log_format_r2,
|
||||
text="启用颜色显示",
|
||||
variable=vars_["logging_color_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Checkbutton(
|
||||
log_format_r2,
|
||||
text="显示时间戳",
|
||||
variable=vars_["logging_show_timestamps_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 日志详细程度设置
|
||||
log_detail_box = ttk.LabelFrame(logging_container, text="日志详细程度")
|
||||
log_detail_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
log_detail_r1 = ttk.Frame(log_detail_box)
|
||||
log_detail_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Label(log_detail_r1, text="调试日志详细程度:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_detail_r1,
|
||||
values=["normal", "detailed", "minimal"],
|
||||
textvariable=vars_["logging_debug_level_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(log_detail_r1, text="错误日志详细程度:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_detail_r1,
|
||||
values=["full", "basic", "minimal"],
|
||||
textvariable=vars_["logging_error_level_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT)
|
||||
|
||||
log_detail_r2 = ttk.Frame(log_detail_box)
|
||||
log_detail_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(log_detail_r2, text="行为日志格式:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
log_detail_r2,
|
||||
values=["concise", "detailed", "minimal"],
|
||||
textvariable=vars_["logging_action_format_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Checkbutton(
|
||||
log_detail_r2,
|
||||
text="启用日志监控(超限告警/触发清理)",
|
||||
variable=vars_["logging_enable_monitor_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
log_detail_r3 = ttk.Frame(log_detail_box)
|
||||
log_detail_r3.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Checkbutton(
|
||||
log_detail_r3,
|
||||
text="按日期拆分日志",
|
||||
variable=vars_["logging_use_dated_logs_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
log_detail_r3,
|
||||
text="写入统一日志",
|
||||
variable=vars_["log_unified_enabled_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Label(log_detail_r3, text="统一日志路径:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Entry(log_detail_r3, textvariable=vars_["log_unified_path_var"], width=28).pack(
|
||||
side=LEFT, padx=(6, 0)
|
||||
)
|
||||
|
||||
# 日志管理设置
|
||||
log_manage_box = ttk.LabelFrame(logging_container, text="日志管理")
|
||||
log_manage_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
log_manage_r1 = ttk.Frame(log_manage_box)
|
||||
log_manage_r1.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(
|
||||
log_manage_r1,
|
||||
text="压缩旧日志",
|
||||
variable=vars_["logging_compress_logs_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(log_manage_r1, text="保留天数:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
log_manage_r1,
|
||||
from_=1,
|
||||
to=365,
|
||||
increment=1,
|
||||
textvariable=vars_["logging_keep_days_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_manage_r1, text="总量上限(GB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_manage_r1,
|
||||
from_=0.1,
|
||||
to=100.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["logging_max_total_size_gb_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_manage_r1, text="压缩阈值(天):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_manage_r1,
|
||||
from_=0,
|
||||
to=365,
|
||||
increment=1,
|
||||
textvariable=vars_["logging_compress_after_days_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
log_manage_r2 = ttk.Frame(log_manage_box)
|
||||
log_manage_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(log_manage_r2, text="日志总大小警告阈值(MB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_manage_r2,
|
||||
from_=50,
|
||||
to=20000,
|
||||
increment=50,
|
||||
textvariable=vars_["logging_monitor_warning_mb_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 16))
|
||||
ttk.Label(log_manage_r2, text="严重阈值(MB):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
log_manage_r2,
|
||||
from_=100,
|
||||
to=100000,
|
||||
increment=100,
|
||||
textvariable=vars_["logging_monitor_critical_mb_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 性能追踪设置
|
||||
perf_box = ttk.LabelFrame(logging_container, text="性能追踪")
|
||||
perf_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
perf_r1 = ttk.Frame(perf_box)
|
||||
perf_r1.pack(fill=X, padx=10, pady=(10, 10))
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="启用性能追踪",
|
||||
variable=vars_["logging_performance_enabled_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="追踪函数调用",
|
||||
variable=vars_["logging_track_functions_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Checkbutton(
|
||||
perf_r1,
|
||||
text="流式后台截图(加速但可能导致并发读取)",
|
||||
variable=vars_["streaming_enabled_var"],
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 界面主题选择
|
||||
theme_box = ttk.LabelFrame(logging_container, text="界面设置")
|
||||
theme_box.pack(fill=X, pady=(0, 10))
|
||||
|
||||
theme_r1 = ttk.Frame(theme_box)
|
||||
theme_r1.pack(fill=X, padx=10, pady=(10, 10))
|
||||
ttk.Label(theme_r1, text="界面主题:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
theme_r1,
|
||||
values=["litera", "flatly", "journal", "minty", "cosmo", "darkly"],
|
||||
textvariable=vars_["gui_theme_var"],
|
||||
state="readonly",
|
||||
width=12,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
ttk.Label(theme_r1, text="(更改后请保存并重启以完全应用主题)").pack(
|
||||
side=LEFT, padx=(12, 0)
|
||||
)
|
||||
|
||||
theme_r2 = ttk.Frame(theme_box)
|
||||
theme_r2.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(theme_r2, text="实时状态刷新(ms):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
theme_r2,
|
||||
from_=200,
|
||||
to=10000,
|
||||
increment=100,
|
||||
textvariable=vars_["gui_realtime_refresh_interval_ms_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 20))
|
||||
ttk.Label(theme_r2, text="实时状态条数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
theme_r2,
|
||||
from_=10,
|
||||
to=500,
|
||||
increment=10,
|
||||
textvariable=vars_["gui_realtime_tail_items_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 保存配置按钮
|
||||
save_config_frame = ttk.Frame(logging_container)
|
||||
save_config_frame.pack(fill=X, pady=(10, 0))
|
||||
ttk.Button(
|
||||
save_config_frame,
|
||||
text="保存日志配置",
|
||||
command=on_save_logging,
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
|
||||
return logging_tab
|
||||
@@ -0,0 +1,110 @@
|
||||
"""右侧主 Notebook 与实时工具栏的 widget 创建段。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- ``ttk.Notebook`` 容器
|
||||
- 实时工具栏(显示动作流 / 显示截图 / 自动滚动 / 实时查看)
|
||||
- 9 个 Tab 子 frame(运行日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间 /
|
||||
行为日志 / 实时状态 / OCR 结果 / 中奖记录)
|
||||
|
||||
返回 ``MainNotebookHandles`` 暴露所有引用,让 ``main()`` 后续把内容填进各 Tab。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X
|
||||
from typing import Callable
|
||||
|
||||
|
||||
@dataclass
|
||||
class MainNotebookHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
notebook: ttk.Notebook
|
||||
log_tab: ttk.Frame
|
||||
preview_tab: ttk.Frame
|
||||
stats_tab: ttk.Frame
|
||||
reservation_tab: ttk.Frame
|
||||
high_value_tab: ttk.Frame
|
||||
actions_log_tab: ttk.Frame
|
||||
realtime_tab: ttk.Frame
|
||||
ocr_results_tab: ttk.Frame
|
||||
win_record_tab: ttk.Frame
|
||||
show_actions_var: tk.BooleanVar
|
||||
show_screenshot_var: tk.BooleanVar
|
||||
auto_scroll_var: tk.BooleanVar
|
||||
|
||||
|
||||
def setup_main_notebook(
|
||||
right: tk.Misc,
|
||||
*,
|
||||
on_open_realtime_viewer: Callable[[], None],
|
||||
) -> MainNotebookHandles:
|
||||
"""构建右侧主 Notebook + 实时工具栏。
|
||||
|
||||
映射表 Tab 由调用方继续添加(因为它依赖 root/cfg)。
|
||||
"""
|
||||
# 右侧:Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)
|
||||
notebook = ttk.Notebook(right)
|
||||
|
||||
# 实时状态工具栏(固定在 Notebook 上方,始终可见)
|
||||
show_actions_var = tk.BooleanVar(value=True)
|
||||
show_screenshot_var = tk.BooleanVar(value=False)
|
||||
auto_scroll_var = tk.BooleanVar(value=True)
|
||||
|
||||
realtime_tools = ttk.Frame(right)
|
||||
realtime_tools.pack(fill=X, padx=8, pady=(4, 0))
|
||||
ttk.Checkbutton(realtime_tools, text="显示动作流", variable=show_actions_var).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Checkbutton(realtime_tools, text="显示截图", variable=show_screenshot_var).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
ttk.Checkbutton(realtime_tools, text="自动滚动", variable=auto_scroll_var).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
|
||||
realtime_view_btn = ttk.Button(
|
||||
realtime_tools,
|
||||
text="实时查看",
|
||||
width=10,
|
||||
command=on_open_realtime_viewer,
|
||||
)
|
||||
realtime_view_btn.pack(side=LEFT, padx=(8, 0))
|
||||
|
||||
log_tab = ttk.Frame(notebook)
|
||||
preview_tab = ttk.Frame(notebook)
|
||||
stats_tab = ttk.Frame(notebook)
|
||||
reservation_tab = ttk.Frame(notebook)
|
||||
high_value_tab = ttk.Frame(notebook)
|
||||
actions_log_tab = ttk.Frame(notebook)
|
||||
realtime_tab = ttk.Frame(notebook)
|
||||
ocr_results_tab = ttk.Frame(notebook)
|
||||
win_record_tab = ttk.Frame(notebook)
|
||||
notebook.add(log_tab, text="运行日志")
|
||||
notebook.add(preview_tab, text="截图预览")
|
||||
notebook.add(stats_tab, text="统计信息")
|
||||
notebook.add(reservation_tab, text="预约队列")
|
||||
notebook.add(high_value_tab, text="高价值房间")
|
||||
notebook.add(actions_log_tab, text="行为日志")
|
||||
notebook.add(realtime_tab, text="实时状态")
|
||||
notebook.add(ocr_results_tab, text="OCR结果")
|
||||
notebook.add(win_record_tab, text="中奖记录")
|
||||
|
||||
return MainNotebookHandles(
|
||||
notebook=notebook,
|
||||
log_tab=log_tab,
|
||||
preview_tab=preview_tab,
|
||||
stats_tab=stats_tab,
|
||||
reservation_tab=reservation_tab,
|
||||
high_value_tab=high_value_tab,
|
||||
actions_log_tab=actions_log_tab,
|
||||
realtime_tab=realtime_tab,
|
||||
ocr_results_tab=ocr_results_tab,
|
||||
win_record_tab=win_record_tab,
|
||||
show_actions_var=show_actions_var,
|
||||
show_screenshot_var=show_screenshot_var,
|
||||
auto_scroll_var=auto_scroll_var,
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""OCR 结果展示 Tab 的更新逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``update_ocr_results``,
|
||||
被 ``do_screenshot`` 在 OCR 完成后通过 ``root.after`` 调用。
|
||||
|
||||
依赖通过显式参数注入:``text_widget`` (展示用的 ScrolledText/Text widget)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Sequence, Tuple
|
||||
|
||||
|
||||
def update_ocr_results(text_widget: tk.Text, results: Sequence[Tuple[str, str, str, str]]) -> None:
|
||||
"""更新OCR结果标签页的显示"""
|
||||
try:
|
||||
lines = []
|
||||
lines.append("=" * 80)
|
||||
lines.append("OCR识别结果(基于最新截图)")
|
||||
lines.append("=" * 80)
|
||||
lines.append("")
|
||||
|
||||
if not results:
|
||||
lines.append('暂无OCR结果,请先点击"截图+OCR"按钮')
|
||||
else:
|
||||
# 按区域名称分组显示
|
||||
for region_name, desc, text_result, status in results:
|
||||
lines.append(f"【{region_name}】{desc}")
|
||||
lines.append(f" 状态: {status}")
|
||||
if text_result:
|
||||
# 如果文本较长,分行显示
|
||||
if len(text_result) > 100:
|
||||
lines.append(f" 识别文本: {text_result[:100]}...")
|
||||
lines.append(f" (完整文本: {text_result})")
|
||||
else:
|
||||
lines.append(f" 识别文本: {text_result}")
|
||||
else:
|
||||
lines.append(" 识别文本: (空)")
|
||||
lines.append("")
|
||||
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", "\n".join(lines))
|
||||
text_widget.see("1.0")
|
||||
except Exception as e:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", f"更新OCR结果失败:{e}")
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""GUI 周期性刷新调度 + 关闭处理。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- 启动时延迟一次性刷新各 Tab 内容(预览/统计/预约/高价值房间/操作日志/中奖记录)
|
||||
- 周期性刷新(操作日志 2s / 预约 5s / 统计 3s)
|
||||
- 窗口关闭时停止 runner
|
||||
|
||||
依赖通过显式参数注入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def setup_periodic_refreshers(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
image_var: tk.StringVar,
|
||||
async_refresh_preview_impl: Callable[[Any], None],
|
||||
preview_view: Any,
|
||||
refresh_stats: Callable[[], None],
|
||||
refresh_reservations: Callable[[], None],
|
||||
refresh_high_value_rooms: Callable[[], None],
|
||||
refresh_actions_log: Callable[[], None],
|
||||
refresh_win_record: Callable[[], None],
|
||||
runner: Any,
|
||||
) -> None:
|
||||
"""启动延迟刷新 + 周期刷新调度。"""
|
||||
|
||||
def delayed_refresh_preview() -> None:
|
||||
if image_var.get():
|
||||
async_refresh_preview_impl(preview_view)
|
||||
|
||||
root.after(3000, delayed_refresh_preview) # type: ignore[arg-type]
|
||||
root.after(500, refresh_stats) # type: ignore[arg-type]
|
||||
root.after(500, refresh_reservations) # type: ignore[arg-type]
|
||||
root.after(500, refresh_high_value_rooms) # type: ignore[arg-type]
|
||||
root.after(500, refresh_actions_log) # type: ignore[arg-type]
|
||||
root.after(500, refresh_win_record) # type: ignore[arg-type]
|
||||
|
||||
# 定期刷新行为日志(每2秒)
|
||||
def auto_refresh_actions_log() -> None:
|
||||
refresh_actions_log()
|
||||
root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]
|
||||
|
||||
# 定期刷新预约队列(每5秒)
|
||||
def auto_refresh_reservations() -> None:
|
||||
refresh_reservations()
|
||||
root.after(5000, auto_refresh_reservations) # type: ignore[arg-type]
|
||||
|
||||
root.after(2000, auto_refresh_actions_log) # type: ignore[arg-type]
|
||||
root.after(5000, auto_refresh_reservations) # type: ignore[arg-type]
|
||||
|
||||
# 定期刷新统计信息(每3秒)
|
||||
def auto_refresh_stats() -> None:
|
||||
if runner.is_running():
|
||||
refresh_stats()
|
||||
root.after(3000, auto_refresh_stats) # type: ignore[arg-type]
|
||||
|
||||
auto_refresh_stats()
|
||||
|
||||
|
||||
def setup_close_handler(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
runner: Any,
|
||||
) -> None:
|
||||
"""绑定窗口关闭(WM_DELETE_WINDOW)→ 停止 runner + 销毁 root。"""
|
||||
def on_close():
|
||||
try:
|
||||
runner.stop()
|
||||
except Exception:
|
||||
pass
|
||||
root.destroy()
|
||||
|
||||
root.protocol("WM_DELETE_WINDOW", on_close)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""截图预览 Tab 的 widget 创建段。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- 顶部按钮区(选择图片下拉 + 刷新列表 + 刷新预览 + 打开pic目录)
|
||||
- 主预览区(image_label)
|
||||
- 状态栏
|
||||
|
||||
依赖通过显式参数注入,返回 ``PreviewTabHandles`` 让 ``main()`` 后续调用刷新逻辑。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, LEFT, RIGHT, X
|
||||
from typing import Any, Callable
|
||||
|
||||
from gui.components.preview_view import (
|
||||
PreviewView,
|
||||
update_image_list as _update_image_list_impl,
|
||||
refresh_preview as _refresh_preview_impl,
|
||||
open_pic_folder as _open_pic_folder_impl,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreviewTabHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
preview_view: PreviewView
|
||||
image_var: tk.StringVar
|
||||
refresh_preview: Callable[[], None]
|
||||
update_image_list: Callable[[bool], None]
|
||||
|
||||
|
||||
def _get_pic_dir() -> str:
|
||||
try:
|
||||
from douyin.core.path_config import get_pic_dir
|
||||
|
||||
return get_pic_dir()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
return path_config.get_pic_dir()
|
||||
|
||||
|
||||
def setup_preview_tab(
|
||||
preview_tab: tk.Misc,
|
||||
*,
|
||||
on_line: Callable[[str], None],
|
||||
root: tk.Misc,
|
||||
) -> PreviewTabHandles:
|
||||
"""构建截图预览 Tab 的 UI。"""
|
||||
preview_top = ttk.Frame(preview_tab)
|
||||
preview_top.pack(fill=X, padx=10, pady=10)
|
||||
|
||||
images_dir = _get_pic_dir()
|
||||
|
||||
image_var = tk.StringVar(value="")
|
||||
|
||||
ttk.Label(preview_top, text="选择图片:").pack(side=LEFT)
|
||||
# 允许手工输入子路径(例如 start/latest.png),方便查看逐步截图
|
||||
image_combo = ttk.Combobox(
|
||||
preview_top, textvariable=image_var, width=30, state="normal"
|
||||
)
|
||||
image_combo.pack(side=LEFT, padx=(0, 10))
|
||||
|
||||
def update_image_list(refresh_after: bool = True) -> None:
|
||||
_update_image_list_impl(view, refresh_after=refresh_after)
|
||||
|
||||
# 先定义refresh_preview函数(即使它引用了后面的变量,函数定义本身是延迟执行的)
|
||||
def refresh_preview() -> None:
|
||||
_refresh_preview_impl(view)
|
||||
|
||||
preview_status = tk.StringVar(value="")
|
||||
ttk.Label(preview_top, textvariable=preview_status).pack(side=RIGHT)
|
||||
|
||||
preview_body = ttk.Frame(preview_tab)
|
||||
preview_body.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||||
|
||||
image_label = ttk.Label(preview_body)
|
||||
image_label.pack(fill=BOTH, expand=True)
|
||||
_img_ref: dict[str, Any] = {"photo": None} # 防止 PhotoImage 被回收
|
||||
|
||||
view = PreviewView(
|
||||
images_dir=str(images_dir),
|
||||
image_var=image_var,
|
||||
image_combo=image_combo,
|
||||
preview_body=preview_body,
|
||||
image_label=image_label,
|
||||
preview_status=preview_status,
|
||||
on_line=on_line,
|
||||
root=root,
|
||||
img_ref=_img_ref,
|
||||
)
|
||||
|
||||
update_image_list(refresh_after=False) # 初始化时扫描一次,但不刷新预览
|
||||
|
||||
ttk.Button(
|
||||
preview_top,
|
||||
text="刷新列表",
|
||||
command=lambda: update_image_list(refresh_after=True),
|
||||
).pack(side=LEFT, padx=(0, 5))
|
||||
ttk.Button(preview_top, text="刷新预览", command=refresh_preview).pack(side=LEFT)
|
||||
|
||||
# 绑定选择变化事件,自动刷新预览(在 refresh_preview 函数定义之后)
|
||||
def on_image_selected(*args):
|
||||
try:
|
||||
refresh_preview()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
image_var.trace("w", on_image_selected) # 监听变量变化
|
||||
image_combo.bind(
|
||||
"<<ComboboxSelected>>", lambda e: refresh_preview()
|
||||
) # 监听下拉选择
|
||||
|
||||
def open_pic_folder() -> None:
|
||||
_open_pic_folder_impl(view)
|
||||
|
||||
ttk.Button(preview_top, text="打开pic目录", command=open_pic_folder).pack(
|
||||
side=LEFT, padx=(10, 0)
|
||||
)
|
||||
|
||||
return PreviewTabHandles(
|
||||
preview_view=view,
|
||||
image_var=image_var,
|
||||
refresh_preview=refresh_preview,
|
||||
update_image_list=update_image_list,
|
||||
)
|
||||
@@ -0,0 +1,193 @@
|
||||
"""截图预览 Tab 视图相关:目录扫描、列表更新、图片加载与缩放、异步预览。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内一组互相调用的闭包,
|
||||
共享 ``images_dir`` / ``image_var`` / ``image_combo`` / ``preview_body`` /
|
||||
``image_label`` / ``preview_status`` / ``_img_ref`` 等。
|
||||
|
||||
抽出后通过 ``PreviewView`` 容器把 widgets/状态聚一起,各动作函数接收容器作为参数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass, field
|
||||
from tkinter import ttk
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from PIL import Image, ImageTk # type: ignore[import]
|
||||
|
||||
|
||||
@dataclass
|
||||
class PreviewView:
|
||||
"""截图预览 Tab 的 widgets + 状态容器。"""
|
||||
|
||||
images_dir: str
|
||||
image_var: tk.StringVar
|
||||
image_combo: ttk.Combobox
|
||||
preview_body: tk.Misc
|
||||
image_label: ttk.Label
|
||||
preview_status: tk.StringVar
|
||||
on_line: Callable[[str], None]
|
||||
root: tk.Misc
|
||||
img_ref: Dict[str, Any] = field(default_factory=lambda: {"photo": None})
|
||||
|
||||
|
||||
def scan_image_files(view: PreviewView) -> List[str]:
|
||||
"""扫描pic文件夹及其子文件夹中的所有图片文件"""
|
||||
image_files: List[str] = []
|
||||
if os.path.exists(view.images_dir):
|
||||
for root_dir, _dirs, files in os.walk(view.images_dir):
|
||||
for file in files:
|
||||
if file.lower().endswith(
|
||||
(".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif")
|
||||
):
|
||||
# 获取相对路径
|
||||
rel_path = os.path.relpath(
|
||||
os.path.join(root_dir, file), str(view.images_dir)
|
||||
)
|
||||
# 统一使用正斜杠(Windows和Unix都支持)
|
||||
rel_path = rel_path.replace("\\", "/")
|
||||
image_files.append(rel_path)
|
||||
# 按文件名排序
|
||||
image_files.sort(key=lambda x: x.lower())
|
||||
return image_files
|
||||
|
||||
|
||||
def update_image_list(view: PreviewView, refresh_after: bool = True) -> None:
|
||||
"""更新图片列表"""
|
||||
new_list = scan_image_files(view)
|
||||
view.image_combo["values"] = new_list
|
||||
current_value = view.image_var.get()
|
||||
# 如果当前值不在新列表中,或列表为空,选择第一个
|
||||
if new_list:
|
||||
if not current_value or current_value not in new_list:
|
||||
view.image_var.set(new_list[0])
|
||||
else:
|
||||
view.image_var.set("")
|
||||
view.on_line(f"[预览] 扫描到 {len(new_list)} 个图片文件")
|
||||
# 如果当前有选择的图片,刷新预览
|
||||
if refresh_after and view.image_var.get():
|
||||
try:
|
||||
refresh_preview(view)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _load_and_fit_image(view: PreviewView, img_path: str) -> None:
|
||||
if not os.path.exists(img_path):
|
||||
view.preview_status.set(f"未找到:{os.path.basename(img_path)}")
|
||||
view.image_label.configure(image="")
|
||||
view.img_ref["photo"] = None
|
||||
return
|
||||
|
||||
try:
|
||||
img = Image.open(img_path)
|
||||
img.load() # Force load to catch truncated files early
|
||||
img = img.convert("RGB")
|
||||
except (OSError, IOError, SyntaxError) as e:
|
||||
# Handle truncated image files
|
||||
view.preview_status.set(f"图片加载失败:{str(e)[:50]}")
|
||||
view.image_label.configure(image="")
|
||||
view.img_ref["photo"] = None
|
||||
return
|
||||
except Exception as e:
|
||||
view.preview_status.set(f"图片加载错误:{str(e)[:50]}")
|
||||
view.image_label.configure(image="")
|
||||
view.img_ref["photo"] = None
|
||||
return
|
||||
|
||||
# 获取预览区域的实际尺寸(如果窗口还未初始化,使用默认值)
|
||||
try:
|
||||
view.preview_body.update_idletasks() # 强制更新布局
|
||||
w = view.preview_body.winfo_width()
|
||||
h = view.preview_body.winfo_height()
|
||||
# 如果尺寸无效(窗口未初始化),使用默认值
|
||||
if w <= 1 or h <= 1:
|
||||
w, h = 900, 520
|
||||
except Exception:
|
||||
w, h = 900, 520
|
||||
|
||||
max_w = max(300, w - 20)
|
||||
max_h = max(200, h - 20)
|
||||
try:
|
||||
resample = Image.Resampling.LANCZOS
|
||||
except AttributeError:
|
||||
# Fallback for older Pillow versions: LANCZOS constant value is 1
|
||||
resample = 1 # type: ignore[assignment]
|
||||
img.thumbnail((max_w, max_h), resample)
|
||||
photo: ImageTk.PhotoImage = ImageTk.PhotoImage(img)
|
||||
view.img_ref["photo"] = photo # type: ignore[assignment]
|
||||
view.image_label.configure(image=photo)
|
||||
view.preview_status.set(f"{os.path.basename(img_path)} {img.width}x{img.height}")
|
||||
|
||||
|
||||
def refresh_preview(view: PreviewView) -> None:
|
||||
name = view.image_var.get().strip()
|
||||
if not name:
|
||||
view.preview_status.set("请选择图片")
|
||||
view.image_label.configure(image="")
|
||||
view.img_ref["photo"] = None
|
||||
return
|
||||
# 处理相对路径(将正斜杠转换为系统路径分隔符)
|
||||
name_normalized = name.replace("/", os.sep)
|
||||
path = os.path.join(view.images_dir, name_normalized)
|
||||
_load_and_fit_image(view, path)
|
||||
|
||||
|
||||
def open_pic_folder(view: PreviewView) -> None:
|
||||
try:
|
||||
os.makedirs(view.images_dir, exist_ok=True)
|
||||
os.startfile(view.images_dir) # type: ignore[attr-defined]
|
||||
except Exception as e:
|
||||
view.on_line(f"[预览] 打开图片目录失败:{e}")
|
||||
|
||||
|
||||
def async_refresh_preview(view: PreviewView) -> None:
|
||||
"""后台加载图片预览,避免阻塞主线程导致 GUI 卡顿。"""
|
||||
name = view.image_var.get().strip()
|
||||
if not name:
|
||||
return
|
||||
name_normalized = name.replace("/", os.sep)
|
||||
path = os.path.join(view.images_dir, name_normalized)
|
||||
if not os.path.exists(path):
|
||||
return
|
||||
|
||||
def _worker():
|
||||
try:
|
||||
img = Image.open(path)
|
||||
img.load()
|
||||
img = img.convert("RGB")
|
||||
except Exception:
|
||||
return
|
||||
|
||||
def _apply():
|
||||
try:
|
||||
view.preview_body.update_idletasks()
|
||||
w = view.preview_body.winfo_width()
|
||||
h = view.preview_body.winfo_height()
|
||||
if w <= 1 or h <= 1:
|
||||
w, h = 900, 520
|
||||
max_w = max(300, w - 20)
|
||||
max_h = max(200, h - 20)
|
||||
try:
|
||||
resample = Image.Resampling.LANCZOS
|
||||
except AttributeError:
|
||||
resample = 1
|
||||
img.thumbnail((max_w, max_h), resample)
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
view.img_ref["photo"] = photo
|
||||
view.image_label.configure(image=photo)
|
||||
view.preview_status.set(
|
||||
f"{os.path.basename(path)} {img.width}x{img.height}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
view.root.after(0, _apply)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
threading.Thread(target=_worker, daemon=True).start()
|
||||
@@ -0,0 +1,206 @@
|
||||
"""实时状态 Tab UI 创建逻辑(包含 3 个内部辅助函数 + 后台刷新循环)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 ~170 行的段(被 try/except 包着)。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - ``realtime_tab`` (Frame)
|
||||
- ``vars_`` - 名→Var 的字典,需要 show_actions_var/show_screenshot_var/auto_scroll_var
|
||||
- ``root`` - 主窗口(用于自递归 ``after``)
|
||||
- ``ScrolledText_cls`` - ``ScrolledText`` 类(ttkbootstrap 或 tkinter)
|
||||
- ``logs_dir_getter`` - 返回 logs 目录的回调
|
||||
- ``read_config`` - 读 config.json 的回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, X
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from PIL import Image, ImageTk # type: ignore[import]
|
||||
|
||||
|
||||
def setup_realtime_tab(
|
||||
parent: tk.Misc,
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
root: tk.Misc,
|
||||
ScrolledText_cls: Any,
|
||||
logs_dir_getter: Callable[[], str],
|
||||
read_config: Callable[[], dict],
|
||||
) -> None:
|
||||
# ========== 实时状态 Tab(显示最近动作 + 耗时) ==========
|
||||
try:
|
||||
realtime_frame = ttk.Frame(parent)
|
||||
realtime_frame.pack(fill=BOTH, expand=True, padx=8, pady=8)
|
||||
|
||||
# 截图预览区域(根据选项显示/隐藏)
|
||||
image_label = ttk.Label(realtime_frame)
|
||||
image_label.pack(fill=X)
|
||||
|
||||
realtime_text = ScrolledText_cls(realtime_frame, height=14)
|
||||
realtime_text.pack(fill=BOTH, expand=True)
|
||||
realtime_text.configure(state="disabled")
|
||||
|
||||
# re 已在模块顶部导入,避免重复导入
|
||||
|
||||
realtime_after_id = None
|
||||
|
||||
def tail_read_file(path: str, max_bytes: int = 64 * 1024) -> list[str]:
|
||||
"""从文件尾部读取最多 max_bytes,并返回按行分割的字符串列表(按文件顺序)。"""
|
||||
try:
|
||||
if not os.path.exists(path):
|
||||
return []
|
||||
with open(path, "rb") as f:
|
||||
f.seek(0, os.SEEK_END)
|
||||
file_size = f.tell()
|
||||
seek_from = max(0, file_size - max_bytes)
|
||||
f.seek(seek_from)
|
||||
data = f.read()
|
||||
text = data.decode(errors="ignore")
|
||||
# splitlines 保留不含尾部换行的处理
|
||||
return text.splitlines()
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def parse_action_duration(line: str) -> tuple[str, str] | None:
|
||||
"""从一行日志提取 (action, duration),未找到返回 None。
|
||||
|
||||
支持 ms / s 两种单位(实际 actions.log 写 `耗时=10.00ms`)。
|
||||
"""
|
||||
if "耗时" not in line:
|
||||
return None
|
||||
idx = line.find("耗时")
|
||||
tail = line[idx:] # 在"耗时"之后搜,避免把前缀里的数字当成耗时
|
||||
|
||||
num = r"([0-9]+(?:\.[0-9]+)?)"
|
||||
# 优先 ms(必须先于 s 匹配,否则 \s*s 会先吃掉 "10ms" 的 m)
|
||||
m_ms = re.search(r"耗时[:=]?\s*" + num + r"\s*ms", tail)
|
||||
m_s = re.search(r"耗时[:=]?\s*" + num + r"\s*s(?![a-zA-Z])", tail)
|
||||
|
||||
if m_ms:
|
||||
dur = m_ms.group(1) + "ms"
|
||||
elif m_s:
|
||||
dur = m_s.group(1) + "s"
|
||||
else:
|
||||
m2 = re.search(num + r"\s*ms", tail)
|
||||
if m2:
|
||||
dur = m2.group(1) + "ms"
|
||||
else:
|
||||
m3 = re.search(num + r"\s*s(?![a-zA-Z])", tail)
|
||||
if m3:
|
||||
dur = m3.group(1) + "s"
|
||||
else:
|
||||
return None
|
||||
|
||||
# 动作名取耗时之前的文本片段,最多保留 60 字符
|
||||
action = line[:idx].strip()
|
||||
if not action:
|
||||
# 兜底:取整行前 60 字符
|
||||
action = line.strip()[:60]
|
||||
if len(action) > 60:
|
||||
action = action[:57] + "..."
|
||||
return (action, dur)
|
||||
|
||||
def refresh_realtime_tab():
|
||||
nonlocal realtime_after_id
|
||||
cfg = read_config()
|
||||
gui_cfg = cfg.get("gui", {}).get("realtime_status", {})
|
||||
refresh_ms = int(gui_cfg.get("refresh_interval_ms", 1000))
|
||||
tail_items = int(gui_cfg.get("tail_items", 50))
|
||||
|
||||
path = os.path.join(logs_dir_getter(), "actions.log")
|
||||
lines = tail_read_file(path)
|
||||
parsed: list[tuple[str, str]] = []
|
||||
# 从文件末尾向前解析,保持原始顺序输出最近项
|
||||
for line in reversed(lines):
|
||||
try:
|
||||
out = parse_action_duration(line)
|
||||
if out:
|
||||
parsed.append(out)
|
||||
if len(parsed) >= tail_items:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
parsed = list(reversed(parsed))
|
||||
|
||||
# 更新截图(若选中)
|
||||
if vars_["show_screenshot_var"].get():
|
||||
try:
|
||||
try:
|
||||
from douyin.core.path_config import get_screenshot_path
|
||||
|
||||
screenshot_path = get_screenshot_path()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
|
||||
if os.path.exists(screenshot_path):
|
||||
img = Image.open(screenshot_path)
|
||||
# 缩放以适应宽度(保持纵横比),最大宽度 420
|
||||
max_w = 420
|
||||
w, h = img.size
|
||||
if w > max_w:
|
||||
nw = max_w
|
||||
nh = int(h * (nw / w))
|
||||
img = img.resize((nw, nh), Image.LANCZOS)
|
||||
tk_img = ImageTk.PhotoImage(img)
|
||||
image_label.configure(image=tk_img)
|
||||
image_label.image = tk_img
|
||||
image_label.pack(fill=X)
|
||||
else:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
except Exception:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
else:
|
||||
image_label.configure(image="")
|
||||
image_label.image = None
|
||||
image_label.pack_forget()
|
||||
|
||||
# 更新动作流文本(若选中)
|
||||
if vars_["show_actions_var"].get():
|
||||
realtime_text.configure(state="normal")
|
||||
realtime_text.delete("1.0", "end")
|
||||
if not parsed:
|
||||
realtime_text.insert("1.0", "暂无动作日志(仅显示包含“耗时”的行)")
|
||||
else:
|
||||
for action, dur in parsed:
|
||||
realtime_text.insert("end", f"{action} {dur}\n")
|
||||
# 自动滚动
|
||||
if vars_["auto_scroll_var"].get():
|
||||
try:
|
||||
realtime_text.see("end")
|
||||
except Exception:
|
||||
try:
|
||||
realtime_text.yview_moveto(1.0)
|
||||
except Exception:
|
||||
pass
|
||||
realtime_text.configure(state="disabled")
|
||||
else:
|
||||
# 隐藏文本内容但保留控件
|
||||
realtime_text.configure(state="normal")
|
||||
realtime_text.delete("1.0", "end")
|
||||
realtime_text.configure(state="disabled")
|
||||
|
||||
# 安排下一次刷新
|
||||
try:
|
||||
realtime_after_id = root.after(refresh_ms, refresh_realtime_tab)
|
||||
except Exception:
|
||||
realtime_after_id = None
|
||||
|
||||
# 启动刷新(仅在 Tab 被创建时启动)
|
||||
try:
|
||||
refresh_realtime_tab()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,180 @@
|
||||
"""高价值预约 Tab UI 创建逻辑(16 个 var)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 162 行的 widget 创建段。
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - ``left_notebook`` (tab 父容器)
|
||||
- ``vars_`` - 名→Var 的 ``Dict[str, tk.Variable]``
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def setup_reservation_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame:
|
||||
reservation_tab_left = ttk.Frame(parent)
|
||||
parent.add(reservation_tab_left, text="高价值预约")
|
||||
|
||||
reservation_box = ttk.LabelFrame(reservation_tab_left, text="高价值福袋预约参与")
|
||||
reservation_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
# 预约启用开关
|
||||
res_r0 = ttk.Frame(reservation_box)
|
||||
res_r0.pack(fill=X, padx=10, pady=(10, 8))
|
||||
ttk.Checkbutton(
|
||||
res_r0, text="启用预约(价值≥阈值)", variable=vars_["high_value_fudai_enabled_var"]
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 价值阈值和提前参与时间
|
||||
res_r1 = ttk.Frame(reservation_box)
|
||||
res_r1.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(res_r1, text="价值阈值(元):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r1,
|
||||
from_=0,
|
||||
to=99999,
|
||||
increment=100,
|
||||
textvariable=vars_["high_value_fudai_threshold_yuan_var"],
|
||||
width=10,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(res_r1, text="提前参与(秒):").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
res_r1,
|
||||
from_=5,
|
||||
to=900,
|
||||
increment=10,
|
||||
textvariable=vars_["high_value_fudai_join_ahead_seconds_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 最多回退次数
|
||||
res_r2 = ttk.Frame(reservation_box)
|
||||
res_r2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(res_r2, text="最多回退直播间次数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r2,
|
||||
from_=0,
|
||||
to=300,
|
||||
increment=5,
|
||||
textvariable=vars_["high_value_fudai_max_swipe_back_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(res_r2, text="(0=不限制)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 最多记录数量和完成后策略
|
||||
res_r3 = ttk.Frame(reservation_box)
|
||||
res_r3.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(res_r3, text="最多记录数量:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r3,
|
||||
from_=1,
|
||||
to=50,
|
||||
increment=1,
|
||||
textvariable=vars_["high_value_fudai_max_reservations_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(res_r3, text="完成后策略:").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Combobox(
|
||||
res_r3,
|
||||
textvariable=vars_["high_value_fudai_after_action_var"],
|
||||
values=["continue", "stay"],
|
||||
width=10,
|
||||
state="readonly",
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(res_r3, text="(stay=停留,continue=继续)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 高价值房间回访
|
||||
res_r4 = ttk.Frame(reservation_box)
|
||||
res_r4.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
res_r4, text="启用高价值房间回访", variable=vars_["high_value_room_revisit_enabled_var"]
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
res_r4, text="仅当前运行", variable=vars_["high_value_room_revisit_only_current_run_var"]
|
||||
).pack(side=LEFT, padx=(20, 0))
|
||||
|
||||
# 高价值房间回访详细参数
|
||||
res_r4a = ttk.Frame(reservation_box)
|
||||
res_r4a.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(res_r4a, text="重访最小间隔(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r4a,
|
||||
from_=60,
|
||||
to=3600,
|
||||
textvariable=vars_["high_value_room_revisit_min_interval_seconds_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(res_r4a, text="每次运行最大次数:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r4a,
|
||||
from_=1,
|
||||
to=20,
|
||||
textvariable=vars_["high_value_room_revisit_max_per_run_var"],
|
||||
width=5,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
|
||||
res_r4b = ttk.Frame(reservation_box)
|
||||
res_r4b.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(res_r4b, text="最低奖品价值(元):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r4b,
|
||||
from_=0.0,
|
||||
to=10000.0,
|
||||
textvariable=vars_["high_value_room_revisit_min_prize_value_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
ttk.Label(res_r4b, text="最大年龄(天):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r4b,
|
||||
from_=1,
|
||||
to=365,
|
||||
textvariable=vars_["high_value_room_revisit_max_age_days_var"],
|
||||
width=5,
|
||||
).pack(side=LEFT, padx=(0, 20))
|
||||
|
||||
# 开奖前轮询时间
|
||||
res_r4b = ttk.Frame(reservation_box)
|
||||
res_r4b.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(res_r4b, text="开奖前轮询时间(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r4b,
|
||||
from_=0.0,
|
||||
to=60.0,
|
||||
increment=1.0,
|
||||
textvariable=vars_["high_value_fudai_poll_before_seconds_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(res_r4b, text="(开奖前N秒开始轮询预约)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# 预约回退校验
|
||||
res_r5 = ttk.Frame(reservation_box)
|
||||
res_r5.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
res_r5, text="预约回退校验", variable=vars_["reservation_back_verify_enabled_var"]
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 回退滑延迟和校验等待时间
|
||||
res_r6 = ttk.Frame(reservation_box)
|
||||
res_r6.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(res_r6, text="回退滑延迟(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
res_r6,
|
||||
from_=0.0,
|
||||
to=10.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["reservation_back_swipe_delay_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(res_r6, text="校验等待时间(秒):").pack(side=LEFT, padx=(20, 0))
|
||||
ttk.Spinbox(
|
||||
res_r6,
|
||||
from_=0.1,
|
||||
to=10.0,
|
||||
increment=0.1,
|
||||
textvariable=vars_["reservation_back_verify_wait_seconds_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
return reservation_tab_left
|
||||
@@ -0,0 +1,276 @@
|
||||
"""预约队列 Tab 视图刷新逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``refresh_reservations``,
|
||||
负责读 ``state/reservations.json`` 并在 Tab 中以中文友好格式渲染预约明细。
|
||||
|
||||
依赖通过显式参数注入:``text_widget`` (展示用的 ScrolledText/Text widget)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tkinter as tk
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def refresh_reservations(text_widget: tk.Text) -> None:
|
||||
try:
|
||||
from douyin.core.path_config import get_reservations_path
|
||||
|
||||
path = get_reservations_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
from douyin.core import path_config
|
||||
|
||||
path = path_config.get_reservations_path()
|
||||
try:
|
||||
if os.path.exists(path):
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
text_widget.delete("1.0", "end")
|
||||
|
||||
updated_ts = (
|
||||
float(data.get("updated_ts", 0.0) or 0.0)
|
||||
if isinstance(data, dict)
|
||||
else 0.0
|
||||
)
|
||||
room_pos = (
|
||||
int(data.get("room_pos", 0) or 0) if isinstance(data, dict) else 0
|
||||
)
|
||||
reason = (
|
||||
str(data.get("reason", "") or "") if isinstance(data, dict) else ""
|
||||
)
|
||||
current_title = (
|
||||
str(data.get("current_room_title", "") or "")
|
||||
if isinstance(data, dict)
|
||||
else ""
|
||||
)
|
||||
current_title_raw = (
|
||||
str(data.get("current_room_title_raw", "") or "")
|
||||
if isinstance(data, dict)
|
||||
else ""
|
||||
)
|
||||
reservations = (
|
||||
data.get("reservations", []) if isinstance(data, dict) else []
|
||||
)
|
||||
|
||||
# 基本信息(中文,更详细)
|
||||
lines = []
|
||||
lines.append("=" * 60)
|
||||
lines.append("【预约队列总览】")
|
||||
lines.append("=" * 60)
|
||||
|
||||
if updated_ts > 0:
|
||||
try:
|
||||
updated_dt = datetime.fromtimestamp(updated_ts)
|
||||
updated_str = updated_dt.strftime("%Y年%m月%d日 %H:%M:%S")
|
||||
# 计算距离现在的时间
|
||||
now_dt = datetime.now()
|
||||
time_diff = now_dt - updated_dt
|
||||
if time_diff.total_seconds() < 60:
|
||||
time_ago = f"{int(time_diff.total_seconds())}秒前"
|
||||
elif time_diff.total_seconds() < 3600:
|
||||
time_ago = f"{int(time_diff.total_seconds() // 60)}分钟前"
|
||||
elif time_diff.total_seconds() < 86400:
|
||||
time_ago = f"{int(time_diff.total_seconds() // 3600)}小时前"
|
||||
else:
|
||||
time_ago = f"{int(time_diff.total_seconds() // 86400)}天前"
|
||||
lines.append(f"最后更新时间:{updated_str} ({time_ago})")
|
||||
except Exception:
|
||||
updated_str = str(updated_ts)
|
||||
lines.append(f"最后更新时间:{updated_str}")
|
||||
else:
|
||||
lines.append("最后更新时间:暂无数据")
|
||||
|
||||
lines.append(
|
||||
f"当前所在直播间位置:第 {room_pos + 1} 个直播间(索引:{room_pos})"
|
||||
)
|
||||
lines.append(f"当前直播间名称(清洗后):{current_title or '未知'}")
|
||||
lines.append(f"当前直播间名称(原始):{current_title_raw or '未知'}")
|
||||
lines.append(f"预约队列总数:{len(reservations)} 条")
|
||||
|
||||
if reason:
|
||||
reason_map = {
|
||||
"record_reservation": "记录新预约",
|
||||
"update_reservation": "更新预约信息",
|
||||
"remove_expired": "移除过期预约",
|
||||
"sort_reservations": "重新排序预约",
|
||||
}
|
||||
reason_text = reason_map.get(reason, reason)
|
||||
lines.append(f"最近更新原因:{reason_text}")
|
||||
|
||||
lines.append("")
|
||||
|
||||
# 统计信息
|
||||
if reservations:
|
||||
now_ts = datetime.now().timestamp()
|
||||
total_value = 0.0
|
||||
valid_future_times = []
|
||||
expired_count = 0
|
||||
upcoming_count = 0
|
||||
|
||||
for item in reservations:
|
||||
try:
|
||||
val = float(item.get("prize_value_yuan") or 0.0)
|
||||
total_value += val
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ft = float(item.get("future_ts") or 0.0)
|
||||
if ft > 0:
|
||||
valid_future_times.append(ft)
|
||||
remain_sec = ft - now_ts
|
||||
if remain_sec <= 0:
|
||||
expired_count += 1
|
||||
elif remain_sec <= 300: # 5分钟内
|
||||
upcoming_count += 1
|
||||
|
||||
lines.append("【统计信息】")
|
||||
lines.append(f"预约总价值:{total_value:.2f} 元")
|
||||
if len(reservations) > 0:
|
||||
avg_value = total_value / len(reservations)
|
||||
lines.append(f"平均价值:{avg_value:.2f} 元")
|
||||
|
||||
if valid_future_times:
|
||||
earliest_ts = min(valid_future_times)
|
||||
latest_ts = max(valid_future_times)
|
||||
try:
|
||||
earliest_str = datetime.fromtimestamp(earliest_ts).strftime(
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
latest_str = datetime.fromtimestamp(latest_ts).strftime(
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
lines.append(f"最早开奖时间:{earliest_str}")
|
||||
lines.append(f"最晚开奖时间:{latest_str}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if expired_count > 0:
|
||||
lines.append(f"⚠️ 已过期预约:{expired_count} 条")
|
||||
if upcoming_count > 0:
|
||||
lines.append(f"⏰ 即将开奖(5分钟内):{upcoming_count} 条")
|
||||
|
||||
lines.append("")
|
||||
lines.append("=" * 60)
|
||||
lines.append("【预约明细列表】(按预计开奖时间从早到晚排序)")
|
||||
lines.append("=" * 60)
|
||||
lines.append("")
|
||||
|
||||
for idx, item in enumerate(reservations, start=1):
|
||||
try:
|
||||
val = float(item.get("prize_value_yuan") or 0.0)
|
||||
except Exception:
|
||||
val = 0.0
|
||||
content = str(item.get("content") or "")
|
||||
ft = float(item.get("future_ts") or 0.0)
|
||||
ft_str = str(item.get("future_str") or "")
|
||||
pos_seen = int(item.get("pos_seen") or 0)
|
||||
room_title = str(item.get("room_title") or "")
|
||||
room_title_raw = str(item.get("room_title_raw") or "")
|
||||
created_ts = float(item.get("created_ts") or 0.0)
|
||||
|
||||
# 计算剩余时间(更详细)
|
||||
now_ts = datetime.now().timestamp()
|
||||
remain_sec = ft - now_ts if ft > 0 else 0
|
||||
|
||||
if ft <= 0:
|
||||
remain_str = "❌ 开奖时间无效"
|
||||
status_icon = "❌"
|
||||
elif remain_sec <= 0:
|
||||
remain_str = "⏰ 已到开奖时间"
|
||||
status_icon = "⏰"
|
||||
elif remain_sec <= 60:
|
||||
remain_str = f"🔥 即将开奖({int(remain_sec)}秒后)"
|
||||
status_icon = "🔥"
|
||||
elif remain_sec <= 300:
|
||||
remain_str = f"⏰ 即将开奖({int(remain_sec // 60)}分{int(remain_sec % 60)}秒后)"
|
||||
status_icon = "⏰"
|
||||
elif remain_sec <= 3600:
|
||||
remain_str = f"⏳ {int(remain_sec // 60)}分{int(remain_sec % 60)}秒后开奖"
|
||||
status_icon = "⏳"
|
||||
elif remain_sec <= 86400:
|
||||
hours = int(remain_sec // 3600)
|
||||
minutes = int((remain_sec % 3600) // 60)
|
||||
remain_str = f"⏳ {hours}小时{minutes}分钟后开奖"
|
||||
status_icon = "⏳"
|
||||
else:
|
||||
days = int(remain_sec // 86400)
|
||||
hours = int((remain_sec % 86400) // 3600)
|
||||
remain_str = f"📅 {days}天{hours}小时后开奖"
|
||||
status_icon = "📅"
|
||||
|
||||
# 记录时间(更详细)
|
||||
if created_ts > 0:
|
||||
try:
|
||||
created_dt = datetime.fromtimestamp(created_ts)
|
||||
created_str = created_dt.strftime(
|
||||
"%Y年%m月%d日 %H:%M:%S"
|
||||
)
|
||||
# 计算距离现在的时间
|
||||
time_diff = datetime.now() - created_dt
|
||||
if time_diff.total_seconds() < 3600:
|
||||
time_ago = f"{int(time_diff.total_seconds() // 60)}分钟前记录"
|
||||
elif time_diff.total_seconds() < 86400:
|
||||
time_ago = f"{int(time_diff.total_seconds() // 3600)}小时前记录"
|
||||
else:
|
||||
time_ago = f"{int(time_diff.total_seconds() // 86400)}天前记录"
|
||||
created_str_full = f"{created_str} ({time_ago})"
|
||||
except Exception:
|
||||
created_str_full = str(created_ts)
|
||||
else:
|
||||
created_str_full = "未知"
|
||||
|
||||
# 格式化显示
|
||||
lines.append(
|
||||
"┌─ 预约 #"
|
||||
+ str(idx)
|
||||
+ " ─────────────────────────────────────────────"
|
||||
)
|
||||
lines.append(f"│ 状态:{status_icon} {remain_str}")
|
||||
lines.append("│")
|
||||
lines.append(f"│ 💰 奖品价值:{val:.2f} 元")
|
||||
lines.append(f"│ 📦 奖品内容:{content or '(无描述)'}")
|
||||
lines.append("│")
|
||||
lines.append(f"│ ⏰ 预计开奖时间:{ft_str or '未知'}")
|
||||
if ft > 0:
|
||||
try:
|
||||
ft_dt = datetime.fromtimestamp(ft)
|
||||
ft_str_detailed = ft_dt.strftime(
|
||||
"%Y年%m月%d日 %H:%M:%S"
|
||||
)
|
||||
if ft_str_detailed != ft_str:
|
||||
lines.append(f"│ 详细时间:{ft_str_detailed}")
|
||||
except Exception:
|
||||
pass
|
||||
lines.append("│")
|
||||
lines.append(
|
||||
f"│ 📍 发现时直播间位置:第 {pos_seen + 1} 个直播间(索引:{pos_seen})"
|
||||
)
|
||||
lines.append(
|
||||
f"│ 🏠 直播间名称(清洗后):{room_title or '未知'}"
|
||||
)
|
||||
lines.append(
|
||||
f"│ 🏠 直播间名称(原始):{room_title_raw or '未知'}"
|
||||
)
|
||||
lines.append("│")
|
||||
lines.append(f"│ 📝 记录时间:{created_str_full}")
|
||||
lines.append(f"└{'─' * 58}")
|
||||
lines.append("")
|
||||
else:
|
||||
lines.append("【预约明细列表】")
|
||||
lines.append("")
|
||||
lines.append("暂无预约记录。")
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"提示:当检测到高价值福袋时,系统会自动将其加入预约队列。"
|
||||
)
|
||||
|
||||
text_widget.insert("1.0", "\n".join(lines))
|
||||
else:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", "暂无预约队列数据")
|
||||
except Exception as e:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", f"读取预约队列失败:{e}")
|
||||
@@ -0,0 +1,198 @@
|
||||
"""右侧主区域装配:操作按钮 + Notebook + 9 个 Tab + log/preview/win_record 等。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。集中所有右侧 UI 装配:
|
||||
- 底部操作按钮 (start/stop/...)
|
||||
- 右侧 Notebook 容器
|
||||
- 9 个 Tab(运行日志 / 截图预览 / 统计 / 预约 / 高价值房间 / 行为日志 / 实时 / OCR / 中奖记录)
|
||||
- 映射表 Tab
|
||||
- pump_logs 闭包
|
||||
|
||||
返回 ``RightMainAreaHandles`` 暴露给 ``main()`` 后续调度的引用:
|
||||
- update_ocr_results / refresh_preview / image_var: 顶部按钮需要
|
||||
- pump_logs / refresh_*: 周期性刷新需要
|
||||
- preview_view: 异步刷新预览需要
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, X
|
||||
from typing import Any, Callable, Sequence, Tuple
|
||||
|
||||
from gui.components.action_buttons import setup_action_buttons
|
||||
from gui.components.log_pump import pump_logs as _pump_logs_impl
|
||||
from gui.components.log_tab import setup_log_tab
|
||||
from gui.components.main_notebook import setup_main_notebook
|
||||
from gui.components.mapping_table import create_mapping_tab
|
||||
from gui.components.preview_tab import setup_preview_tab
|
||||
from gui.components.realtime_tab import setup_realtime_tab
|
||||
from gui.components.reservations_view import refresh_reservations as _refresh_reservations_impl
|
||||
from gui.components.high_value_view import refresh_high_value_rooms as _refresh_high_value_rooms_impl
|
||||
from gui.components.simple_tabs import (
|
||||
setup_stats_tab,
|
||||
setup_text_tab_with_refresh,
|
||||
setup_actions_log_tab,
|
||||
setup_ocr_results_tab,
|
||||
)
|
||||
from gui.components.win_record_tab import setup_win_record_tab
|
||||
|
||||
|
||||
@dataclass
|
||||
class RightMainArea:
|
||||
"""``main()`` 后续仍要用的引用。"""
|
||||
|
||||
image_var: tk.StringVar
|
||||
refresh_preview: Callable[[], None]
|
||||
update_ocr_results: Callable[[Sequence[Tuple[str, str, str, str]]], None]
|
||||
refresh_stats: Callable[[], None]
|
||||
refresh_reservations: Callable[[], None]
|
||||
refresh_high_value_rooms: Callable[[], None]
|
||||
refresh_actions_log: Callable[[], None]
|
||||
refresh_win_record: Callable[[], None]
|
||||
preview_view: Any
|
||||
status_var: tk.StringVar
|
||||
|
||||
|
||||
def setup_right_main_area(
|
||||
right: tk.Misc,
|
||||
*,
|
||||
root: tk.Misc,
|
||||
cfg: dict,
|
||||
runner: Any,
|
||||
on_line: Callable[[str], None],
|
||||
log_queue: "Any",
|
||||
device_var: tk.StringVar,
|
||||
save_ui_to_config: Callable[[], None],
|
||||
get_params_from_vars: Callable[[], Any],
|
||||
ScrolledText_cls: Any,
|
||||
theme_getter: Callable[[], str],
|
||||
logs_dir_getter: Callable[[], str],
|
||||
read_config: Callable[[], dict],
|
||||
) -> RightMainArea:
|
||||
"""构建右侧主区域全部 UI + 闭包绑定,返回 RightMainArea 句柄。"""
|
||||
# 操作按钮区域(先创建,放在底部)
|
||||
actions = ttk.Frame(right)
|
||||
|
||||
def _open_realtime_viewer() -> None:
|
||||
"""委托到 gui/components/realtime_viewer.open_realtime_viewer。"""
|
||||
from gui.components.realtime_viewer import open_realtime_viewer
|
||||
open_realtime_viewer(root)
|
||||
|
||||
# 右侧 Notebook(日志 / 截图预览 / 统计信息 / 预约队列 / 高价值房间)
|
||||
_main_nb = setup_main_notebook(
|
||||
right,
|
||||
on_open_realtime_viewer=_open_realtime_viewer,
|
||||
)
|
||||
notebook = _main_nb.notebook
|
||||
|
||||
# 使用模块化组件创建映射表并加入 Notebook
|
||||
mapping_tab = create_mapping_tab(root, notebook, cfg)
|
||||
notebook.add(mapping_tab, text="映射表")
|
||||
|
||||
# 日志区
|
||||
_log_tab_handles = setup_log_tab(
|
||||
_main_nb.log_tab,
|
||||
runner=runner,
|
||||
ScrolledText_cls=ScrolledText_cls,
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
log_text = _log_tab_handles.log_text
|
||||
log_filter_var = _log_tab_handles.log_filter_var
|
||||
|
||||
setup_realtime_tab(
|
||||
_main_nb.realtime_tab,
|
||||
vars_={
|
||||
"show_actions_var": _main_nb.show_actions_var,
|
||||
"show_screenshot_var": _main_nb.show_screenshot_var,
|
||||
"auto_scroll_var": _main_nb.auto_scroll_var,
|
||||
},
|
||||
root=root,
|
||||
ScrolledText_cls=ScrolledText_cls,
|
||||
logs_dir_getter=logs_dir_getter,
|
||||
read_config=read_config,
|
||||
)
|
||||
|
||||
_preview_handles = setup_preview_tab(
|
||||
_main_nb.preview_tab,
|
||||
on_line=on_line,
|
||||
root=root,
|
||||
)
|
||||
preview_view = _preview_handles.preview_view
|
||||
image_var = _preview_handles.image_var
|
||||
refresh_preview = _preview_handles.refresh_preview
|
||||
|
||||
status_var = tk.StringVar(value="就绪")
|
||||
|
||||
# 先打包 actions 到底部(不 expand,固定在底部)
|
||||
actions.pack(fill=X, pady=(10, 0), padx=12, side="bottom")
|
||||
# 然后打包 notebook 填充剩余空间(在 actions 之上)
|
||||
notebook.pack(fill=BOTH, expand=True)
|
||||
|
||||
setup_action_buttons(
|
||||
actions,
|
||||
runner=runner,
|
||||
status_var=status_var,
|
||||
device_var=device_var,
|
||||
on_line=on_line,
|
||||
save_ui_to_config=save_ui_to_config,
|
||||
get_params=get_params_from_vars,
|
||||
)
|
||||
|
||||
def pump_logs() -> None:
|
||||
_pump_logs_impl(
|
||||
log_queue,
|
||||
text_widget=log_text,
|
||||
filter_getter=lambda: log_filter_var.get().strip(),
|
||||
theme_getter=theme_getter,
|
||||
root=root,
|
||||
is_running_getter=runner.is_running,
|
||||
status_getter=status_var.get,
|
||||
status_setter=status_var.set,
|
||||
)
|
||||
|
||||
refresh_stats = setup_stats_tab(
|
||||
_main_nb.stats_tab, runner=runner, ScrolledText_cls=ScrolledText_cls,
|
||||
)
|
||||
refresh_reservations = setup_text_tab_with_refresh(
|
||||
_main_nb.reservation_tab,
|
||||
refresh_impl=_refresh_reservations_impl,
|
||||
ScrolledText_cls=ScrolledText_cls,
|
||||
)
|
||||
refresh_high_value_rooms = setup_text_tab_with_refresh(
|
||||
_main_nb.high_value_tab,
|
||||
refresh_impl=_refresh_high_value_rooms_impl,
|
||||
ScrolledText_cls=ScrolledText_cls,
|
||||
)
|
||||
refresh_actions_log = setup_actions_log_tab(
|
||||
_main_nb.actions_log_tab,
|
||||
ScrolledText_cls=ScrolledText_cls,
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
update_ocr_results, _ = setup_ocr_results_tab(
|
||||
_main_nb.ocr_results_tab, ScrolledText_cls=ScrolledText_cls,
|
||||
)
|
||||
|
||||
_win_record_handles = setup_win_record_tab(
|
||||
_main_nb.win_record_tab,
|
||||
on_line=on_line,
|
||||
ScrolledText_cls=ScrolledText_cls,
|
||||
open_realtime_viewer=_open_realtime_viewer,
|
||||
)
|
||||
refresh_win_record = _win_record_handles.refresh_win_record
|
||||
|
||||
pump_logs()
|
||||
|
||||
return RightMainArea(
|
||||
image_var=image_var,
|
||||
refresh_preview=refresh_preview,
|
||||
update_ocr_results=update_ocr_results,
|
||||
refresh_stats=refresh_stats,
|
||||
refresh_reservations=refresh_reservations,
|
||||
refresh_high_value_rooms=refresh_high_value_rooms,
|
||||
refresh_actions_log=refresh_actions_log,
|
||||
refresh_win_record=refresh_win_record,
|
||||
preview_view=preview_view,
|
||||
status_var=status_var,
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""主窗口创建 + ttkbootstrap fallback。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。处理:
|
||||
- 从 config.json 读 GUI 主题(默认 ``litera``)
|
||||
- 优先用 ttkbootstrap (更美观),失败时回退原生 tkinter
|
||||
- 创建 root window + 标题 + 默认尺寸
|
||||
- 暴露 ``ScrolledText`` 类(两条路径来源不同)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
@dataclass
|
||||
class RootBundle:
|
||||
"""``main()`` 后续仍要用的 root + ScrolledText 类。"""
|
||||
|
||||
root: tk.Misc
|
||||
ScrolledText: Any
|
||||
|
||||
|
||||
def setup_root_window(
|
||||
*,
|
||||
read_config: Callable[[], dict],
|
||||
title: str = "抖音福袋挂机 - 可视化控制台",
|
||||
geometry: str = "1400x900",
|
||||
) -> RootBundle:
|
||||
"""构建主窗口,优先用 ttkbootstrap,失败时回退 tkinter。"""
|
||||
# 主题优先级:使用 config 中的 gui.theme (若有),否则使用默认明亮主题 'litera'
|
||||
cfg_theme = "darkly"
|
||||
try:
|
||||
cfg_theme = read_config().get("gui", {}).get("theme", "litera") or "litera"
|
||||
except Exception:
|
||||
cfg_theme = "litera"
|
||||
|
||||
# ttkbootstrap 优先(更美观);没装则回退到原生 tkinter
|
||||
try:
|
||||
import ttkbootstrap as tb
|
||||
from ttkbootstrap.scrolled import ScrolledText # type: ignore[import]
|
||||
|
||||
# 使用 config 中指定的主题名
|
||||
root = tb.Window(themename=cfg_theme)
|
||||
except Exception:
|
||||
from tkinter.scrolledtext import ScrolledText # type: ignore[no-redef]
|
||||
|
||||
root = tk.Tk()
|
||||
|
||||
root.title(title)
|
||||
root.geometry(geometry)
|
||||
return RootBundle(root=root, ScrolledText=ScrolledText)
|
||||
@@ -0,0 +1,89 @@
|
||||
"""运行日志 Tab 的刷新逻辑(从 runner 内存读取最近若干行)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``refresh_run_log``。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``runner`` - 运行控制器(暴露 ``_lock`` 与 ``_log`` 内部属性)
|
||||
- ``text_widget`` - 展示用的 Text/ScrolledText
|
||||
- ``filter_getter`` - 返回筛选关键字
|
||||
- ``theme_getter`` - 返回当前主题名
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Any, Callable
|
||||
|
||||
try:
|
||||
from gui.components.log_color_config import (
|
||||
apply_operation_color,
|
||||
get_operation_type,
|
||||
)
|
||||
except ImportError:
|
||||
def get_operation_type(line: str): # type: ignore[no-redef]
|
||||
return None
|
||||
|
||||
def apply_operation_color(*args, **kwargs): # type: ignore[no-redef]
|
||||
pass
|
||||
|
||||
|
||||
def refresh_run_log(
|
||||
runner: Any,
|
||||
*,
|
||||
text_widget: tk.Text,
|
||||
filter_getter: Callable[[], str],
|
||||
theme_getter: Callable[[], str],
|
||||
) -> None:
|
||||
"""从内存中读取最近若干运行日志并在界面中刷新(行为上与行为日志一致)"""
|
||||
try:
|
||||
tail_n = 1000
|
||||
# 读取 runner 内存日志(线程安全)
|
||||
with runner._lock:
|
||||
total = len(runner._log)
|
||||
cand = runner._log[-tail_n:] if tail_n > 0 else runner._log[:]
|
||||
|
||||
# 应用筛选关键词
|
||||
kw = filter_getter()
|
||||
if kw:
|
||||
cand = [ln for ln in cand if kw in (ln or "")]
|
||||
|
||||
# 保存滚动位置
|
||||
try:
|
||||
scroll_pos = text_widget.yview()[0]
|
||||
except Exception:
|
||||
scroll_pos = 1.0
|
||||
|
||||
text_widget.delete("1.0", "end")
|
||||
if cand:
|
||||
try:
|
||||
current_theme = theme_getter()
|
||||
except Exception:
|
||||
current_theme = "litera"
|
||||
|
||||
for i, line in enumerate(cand):
|
||||
start_pos = text_widget.index("end-1c")
|
||||
if i > 0:
|
||||
text_widget.insert("end", "\n")
|
||||
text_widget.insert("end", line)
|
||||
end_pos = text_widget.index("end")
|
||||
try:
|
||||
op_type = get_operation_type(line)
|
||||
if op_type:
|
||||
apply_operation_color(
|
||||
text_widget, start_pos, end_pos, line, current_theme
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
text_widget.insert("1.0", "暂无匹配的运行日志")
|
||||
|
||||
try:
|
||||
text_widget.yview_moveto(scroll_pos)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
try:
|
||||
text_widget.delete("1.0", "end")
|
||||
text_widget.insert("1.0", f"刷新运行日志失败:{e}")
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,75 @@
|
||||
"""把 GUI Vars 打包成 ``RunParams``。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``get_params``,
|
||||
读取 30 个 tkinter Var 构造 ``RunParams``。
|
||||
|
||||
依赖通过显式参数注入:``vars_`` 是一个名→Var 的 ``Dict[str, tk.Variable]``,
|
||||
键名与原 main() 中的变量名一致。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Dict
|
||||
|
||||
from gui.gui_core import RunParams
|
||||
|
||||
|
||||
def get_params(vars_: Dict[str, tk.Variable]) -> RunParams:
|
||||
# 如果启用无限循环,设置 wait_minutes=0
|
||||
wait_minutes_value = (
|
||||
0 if vars_["infinite_loop_var"].get() else int(vars_["wait_minutes_var"].get() or 5)
|
||||
)
|
||||
return RunParams(
|
||||
device_id=vars_["device_var"].get().strip(),
|
||||
y_pianyi=int(vars_["y_var"].get()),
|
||||
needswitch=bool(vars_["needswitch_var"].get()),
|
||||
wait_minutes=wait_minutes_value,
|
||||
skip_if_countdown_gt_seconds=int(vars_["skip_gt_seconds_var"].get() or 900),
|
||||
reset_after_swipes_enabled=bool(vars_["reset_after_swipes_enabled_var"].get()),
|
||||
reset_after_swipes=int(vars_["reset_after_swipes_var"].get() or 10),
|
||||
min_prize_value_yuan=float(vars_["min_value_var"].get() or 0),
|
||||
min_participants=int(vars_["min_participants_var"].get() or 0),
|
||||
max_participants=int(vars_["max_participants_var"].get() or 0),
|
||||
auto_join_fansclub=bool(vars_["auto_join_var"].get()),
|
||||
fansclub_fail_action=str(vars_["fansclub_action_var"].get() or "stay").lower(),
|
||||
# Web端新增参数
|
||||
high_value_room_revisit_enabled=bool(
|
||||
vars_["high_value_room_revisit_enabled_var"].get()
|
||||
),
|
||||
high_value_room_revisit_only_current_run=bool(
|
||||
vars_["high_value_room_revisit_only_current_run_var"].get()
|
||||
),
|
||||
high_value_room_revisit_min_interval_seconds=int(
|
||||
vars_["high_value_room_revisit_min_interval_seconds_var"].get()
|
||||
),
|
||||
high_value_room_revisit_max_per_run=int(
|
||||
vars_["high_value_room_revisit_max_per_run_var"].get()
|
||||
),
|
||||
high_value_room_revisit_min_prize_value=float(
|
||||
vars_["high_value_room_revisit_min_prize_value_var"].get()
|
||||
),
|
||||
high_value_room_revisit_max_age_days=int(
|
||||
vars_["high_value_room_revisit_max_age_days_var"].get()
|
||||
),
|
||||
high_value_fudai_poll_before_seconds=float(
|
||||
vars_["high_value_fudai_poll_before_seconds_var"].get() or 10.0
|
||||
),
|
||||
reservation_back_verify_enabled=bool(
|
||||
vars_["reservation_back_verify_enabled_var"].get()
|
||||
),
|
||||
reservation_back_swipe_delay=float(
|
||||
reservation_back_swipe_delavars_["y_var"].get() or 1.0
|
||||
),
|
||||
fudai_find_max_attempts=int(vars_["fudai_find_max_attempts_var"].get() or 5),
|
||||
enable_ocr_mode1=bool(vars_["enable_ocr_mode1_var"].get()),
|
||||
fudai_template_match_enabled=bool(vars_["fudai_template_match_enabled_var"].get()),
|
||||
fudai_template_match_threshold=float(
|
||||
vars_["fudai_template_match_threshold_var"].get() or 0.7
|
||||
),
|
||||
# 只养号模式与养号时长
|
||||
yanghao_only=bool(yg_onlvars_["y_var"].get()),
|
||||
yanghao_seconds=int(vars_["yg_recommend_duration_var"].get() or 0),
|
||||
enable_back_on_misses=bool(vars_["enable_back_on_misses_var"].get()),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""运行设置 Tab UI 创建逻辑(11 个 var)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 87 行的 widget 创建段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def setup_run_tab(parent: ttk.Notebook, *, vars_: Dict[str, tk.Variable]) -> ttk.Frame:
|
||||
run_tab = ttk.Frame(parent)
|
||||
parent.add(run_tab, text="运行设置")
|
||||
|
||||
run_box = ttk.LabelFrame(run_tab, text="基本运行参数")
|
||||
run_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
r0 = ttk.Frame(run_box)
|
||||
r0.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(r0, text="允许切换直播间", variable=vars_["needswitch_var"]).pack(side=LEFT)
|
||||
|
||||
r1 = ttk.Frame(run_box)
|
||||
r1.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Checkbutton(r1, text="无限循环模式", variable=vars_["infinite_loop_var"]).pack(side=LEFT)
|
||||
ttk.Label(r1, text="运行时长(分钟):").pack(side=LEFT, padx=(10, 0))
|
||||
wait_minutes_spinbox = ttk.Spinbox(
|
||||
r1, from_=1, to=60, textvariable=vars_["wait_minutes_var"], width=6
|
||||
)
|
||||
wait_minutes_spinbox.pack(side=LEFT, padx=(0, 12))
|
||||
|
||||
# 根据无限循环开关状态,启用/禁用运行时长输入框
|
||||
def update_wait_minutes_state(*args):
|
||||
if vars_["infinite_loop_var"].get():
|
||||
wait_minutes_spinbox.config(state="disabled")
|
||||
else:
|
||||
wait_minutes_spinbox.config(state="normal")
|
||||
|
||||
vars_["infinite_loop_var"].trace("w", update_wait_minutes_state)
|
||||
update_wait_minutes_state() # 初始化状态
|
||||
|
||||
ttk.Label(r1, text="倒计时大于(秒)时不参与(高价值可预约):").pack(side=LEFT)
|
||||
ttk.Spinbox(r1, from_=0, to=3600, textvariable=vars_["skip_gt_seconds_var"], width=6).pack(
|
||||
side=LEFT
|
||||
)
|
||||
|
||||
r2 = ttk.Frame(run_box)
|
||||
r2.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Checkbutton(
|
||||
r2, text="切换N次后回到第一个", variable=vars_["reset_after_swipes_enabled_var"]
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(r2, text="次数:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
r2, from_=1, to=9999, textvariable=vars_["reset_after_swipes_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(r2, text="(触发后会向上回退)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# r2_5: 滑动重置回退方式(与滑动重置配置放在一起)
|
||||
r2_5 = ttk.Frame(run_box)
|
||||
r2_5.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(r2_5, text="滑动重置回退方式:").pack(side=LEFT)
|
||||
ttk.Combobox(
|
||||
r2_5,
|
||||
values=["swipe", "back"],
|
||||
textvariable=vars_["reset_after_swipes_action_var"],
|
||||
state="readonly",
|
||||
width=8,
|
||||
).pack(side=LEFT, padx=(6, 0))
|
||||
ttk.Label(r2_5, text="(滑动次数重置时的回退方法)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
# r3: 启用返回键回退(单独一行)
|
||||
r3 = ttk.Frame(run_box)
|
||||
r3.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Checkbutton(
|
||||
r3,
|
||||
text="启用返回键回退",
|
||||
variable=vars_["enable_back_on_misses_var"],
|
||||
).pack(side=LEFT)
|
||||
|
||||
r3b = ttk.Frame(run_box)
|
||||
r3b.pack(fill=X, padx=10, pady=(0, 6))
|
||||
ttk.Checkbutton(
|
||||
r3b,
|
||||
text="启用下滑回退直播间",
|
||||
variable=vars_["swipe_down_back_enabled_var"],
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(r3b, text="次数:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
r3b, from_=1, to=9999, textvariable=vars_["swipe_down_back_count_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
|
||||
# r4: 连续无福袋退出阈值(放在启用回退下一行,便于查看)
|
||||
r4 = ttk.Frame(run_box)
|
||||
r4.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(r4, text="连续无福袋退出阈值:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
r4, from_=1, to=99999, textvariable=vars_["fudai_exit_after_misses_var"], width=6
|
||||
).pack(side=LEFT, padx=(6, 12))
|
||||
|
||||
return run_tab
|
||||
@@ -0,0 +1,196 @@
|
||||
"""截图 + OCR 识别按钮的执行逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``do_screenshot``
|
||||
(以及与之配套的 ``OCR_REGIONS`` 区域定义)。
|
||||
|
||||
依赖通过显式参数注入:设备 ID、Y 偏移、当前预览图片名(StringVar)、
|
||||
日志/OCR 结果/预览刷新回调、tk root(用于线程间 ``after``)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
from PIL import Image # type: ignore[import]
|
||||
|
||||
# OCR 区域配置:定义所有需要识别的区域(坐标基于1080x2400基准)
|
||||
OCR_REGIONS = [
|
||||
# (区域名称, (x1, y1, x2, y2), 描述)
|
||||
("福袋内容", (389, 1273, 1000, 1534), "福袋内容详情"),
|
||||
("福袋倒计时", (390, 1470, 980, 1580), "福袋倒计时"),
|
||||
("福袋价值", (390, 1440, 1000, 1580), "奖品价值/价格"),
|
||||
("抽奖结果", (380, 660, 720, 755), "抽奖结果弹窗"),
|
||||
("推荐页标签栏", (400, 140, 900, 200), "推荐/关注/直播标签"),
|
||||
("推荐页标签栏快速检测", (400, 140, 900, 200), "推荐页快速检测"),
|
||||
("参与按钮", (306, 2030, 780, 2110), "参与福袋抽奖按钮"),
|
||||
("无奖励确认", (340, 1195, 740, 1355), "无奖励确认弹窗"),
|
||||
("奖励通知确认", (370, 1350, 680, 1440), "奖励通知确认"),
|
||||
("订单确认", (370, 120, 700, 220), "订单确认页面"),
|
||||
("关注列表标签", (658, 147, 765, 194), "关注列表标签"),
|
||||
("直播列表标签", (400, 140, 900, 200), "直播列表标签"),
|
||||
("直播广场", (400, 140, 900, 200), "直播广场标题"),
|
||||
("直播间标题_中", (400, 140, 900, 200), "直播间标题中部"),
|
||||
("诊断优惠券标题", (60, 1260, 1020, 1480), "优惠券弹窗标题"),
|
||||
("诊断优惠券按钮", (400, 1600, 680, 1700), "优惠券按钮"),
|
||||
("诊断购物红包", (400, 1400, 900, 1600), "购物红包弹窗"),
|
||||
]
|
||||
|
||||
|
||||
def do_screenshot(
|
||||
*,
|
||||
device_id: str,
|
||||
y_offset: int,
|
||||
image_var: tk.StringVar,
|
||||
on_line: Callable[[str], None],
|
||||
root: tk.Misc,
|
||||
on_ocr_results: Callable[[list], None],
|
||||
on_refresh_preview: Callable[[], None],
|
||||
) -> None:
|
||||
"""触发设备截图并对预设区域做 OCR 识别。"""
|
||||
if not device_id:
|
||||
on_line("[截图] 请先选择设备")
|
||||
return
|
||||
|
||||
# 在后台线程中执行截图和OCR识别,避免阻塞GUI
|
||||
def screenshot_thread():
|
||||
try:
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
# 使用模块级别导入的 Image 与 os,避免重复导入导致 Pylance 警告
|
||||
|
||||
# 使用 root.after 在主线程中更新日志
|
||||
def log_msg(msg: str) -> Callable[[], None]:
|
||||
def wrapper() -> None:
|
||||
on_line(msg)
|
||||
|
||||
return wrapper
|
||||
|
||||
root.after(0, log_msg("[截图] 正在截图...")) # type: ignore[arg-type]
|
||||
ops = underlying_operations()
|
||||
result = ops.get_screenshot(device_id, use_service=False)
|
||||
if not result:
|
||||
root.after(0, log_msg("[截图] 截图失败")) # type: ignore[arg-type]
|
||||
return
|
||||
|
||||
root.after(0, log_msg("[截图] 截图成功,已保存到 pic/screenshot.png")) # type: ignore[arg-type]
|
||||
|
||||
# 读取截图以获取实际尺寸
|
||||
try:
|
||||
from douyin.core.path_config import get_screenshot_path
|
||||
|
||||
screenshot_path = get_screenshot_path()
|
||||
except Exception:
|
||||
# 回退到旧路径(向后兼容)
|
||||
from douyin.core import path_config
|
||||
|
||||
screenshot_path = path_config.get_screenshot_path()
|
||||
if not os.path.exists(screenshot_path):
|
||||
root.after(0, log_msg("[OCR] 截图文件不存在")) # type: ignore[arg-type]
|
||||
return
|
||||
|
||||
try:
|
||||
img = Image.open(screenshot_path)
|
||||
img.load() # Force load to catch truncated files early
|
||||
img_width, img_height = img.size
|
||||
# 计算缩放比例(基于1080x2400基准)
|
||||
scale_x = img_width / 1080.0
|
||||
scale_y = img_height / 2400.0
|
||||
except (OSError, IOError, SyntaxError) as e:
|
||||
# Handle truncated image files
|
||||
root.after(0, log_msg(f"图片文件损坏或截断: {e}")) # type: ignore[arg-type]
|
||||
return
|
||||
except Exception as e:
|
||||
root.after(0, log_msg(f"[OCR] 读取截图失败: {e}")) # type: ignore[arg-type]
|
||||
return
|
||||
|
||||
# 获取Y偏移
|
||||
# (来自函数参数 y_offset)
|
||||
|
||||
# 执行所有OCR区域的识别
|
||||
ocr_results = []
|
||||
total_regions = len(OCR_REGIONS)
|
||||
root.after(0, log_msg(f"[OCR] 开始识别 {total_regions} 个区域...")) # type: ignore[arg-type]
|
||||
|
||||
for idx, (region_name, (x1, y1, x2, y2), desc) in enumerate(
|
||||
OCR_REGIONS, 1
|
||||
):
|
||||
try:
|
||||
# 缩放坐标到实际截图尺寸
|
||||
actual_x1 = int(x1 * scale_x)
|
||||
actual_y1 = int(y1 * scale_y) + y_offset
|
||||
actual_x2 = int(x2 * scale_x)
|
||||
actual_y2 = int(y2 * scale_y) + y_offset
|
||||
|
||||
# 确保坐标在图片范围内
|
||||
actual_x1 = max(0, min(actual_x1, img_width))
|
||||
actual_y1 = max(0, min(actual_y1, img_height))
|
||||
actual_x2 = max(0, min(actual_x2, img_width))
|
||||
actual_y2 = max(0, min(actual_y2, img_height))
|
||||
|
||||
if actual_x1 >= actual_x2 or actual_y1 >= actual_y2:
|
||||
root.after(0, log_msg(f"[OCR] {region_name}: 坐标无效,跳过")) # type: ignore[arg-type]
|
||||
continue
|
||||
|
||||
# 截取区域
|
||||
cut_result = ops.cut_pic(
|
||||
(actual_x1, actual_y1),
|
||||
(actual_x2, actual_y2),
|
||||
"",
|
||||
region_name,
|
||||
)
|
||||
if not cut_result:
|
||||
root.after(0, log_msg(f"[OCR] {region_name}: 截图失败")) # type: ignore[arg-type]
|
||||
ocr_results.append((region_name, desc, "", "截图失败"))
|
||||
continue
|
||||
|
||||
# OCR识别(先尝试模式0,如果为空再尝试模式1)
|
||||
text_result = ""
|
||||
ocr_mode = 0
|
||||
for mode in [0, 1]:
|
||||
try:
|
||||
text = str(
|
||||
ops.analyse_pic_word(region_name, mode) or ""
|
||||
).strip()
|
||||
if text:
|
||||
text_result = text
|
||||
ocr_mode = mode
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
ocr_results.append(
|
||||
(region_name, desc, text_result, f"模式{ocr_mode}")
|
||||
)
|
||||
status_msg = f"[OCR] ({idx}/{total_regions}) {region_name}: {text_result[:50] if text_result else '(空)'}"
|
||||
root.after(0, log_msg(status_msg)) # type: ignore[arg-type]
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"[OCR] {region_name}: 异常 - {e}"
|
||||
root.after(0, log_msg(error_msg)) # type: ignore[arg-type]
|
||||
ocr_results.append((region_name, desc, "", f"异常: {e}"))
|
||||
|
||||
# 更新OCR结果标签页
|
||||
def update_ocr_wrapper() -> None:
|
||||
on_ocr_results(ocr_results)
|
||||
|
||||
root.after(0, update_ocr_wrapper) # type: ignore[arg-type]
|
||||
root.after(0, log_msg(f"[OCR] 完成!共识别 {len(ocr_results)} 个区域")) # type: ignore[arg-type]
|
||||
|
||||
# 刷新截图预览(如果当前显示的是 screenshot.png)
|
||||
def refresh_if_screenshot() -> None:
|
||||
if image_var.get() == "screenshot.png":
|
||||
on_refresh_preview()
|
||||
|
||||
root.after(0, refresh_if_screenshot) # type: ignore[arg-type]
|
||||
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
error_detail = traceback.format_exc()
|
||||
root.after(0, log_msg(f"[截图] 截图异常: {e}\n{error_detail}")) # type: ignore[arg-type]
|
||||
|
||||
thread = threading.Thread(target=screenshot_thread, daemon=True)
|
||||
thread.start()
|
||||
@@ -0,0 +1,137 @@
|
||||
"""通用的"简单文本 Tab"工厂(顶部按钮区 + ScrolledText + 可选配置)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。多个 Tab(统计信息 / 预约队列 / 高价值房间 /
|
||||
行为日志 / OCR 结果)用相同模式:
|
||||
- top frame
|
||||
- ScrolledText 文本主体(Consolas 10 字体)
|
||||
|
||||
抽出 ``setup_simple_text_tab`` 复用此模板。返回 ``(top_frame, text_widget)``,
|
||||
调用方负责接下来在 ``top_frame`` 中加按钮 / 在 ``text_widget`` 中刷新内容。
|
||||
|
||||
``setup_stats_tab`` 进一步把 stats 专用的 ``refresh`` 闭包内置进来,
|
||||
从 ``gui_app.py`` 抽出对应的 try/except 包装。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
import traceback
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, LEFT, X
|
||||
from typing import Any, Callable, Tuple
|
||||
|
||||
|
||||
def setup_simple_text_tab(
|
||||
tab: tk.Misc,
|
||||
*,
|
||||
ScrolledText_cls: Any,
|
||||
) -> Tuple[ttk.Frame, tk.Text]:
|
||||
"""构建 "顶部按钮区 + ScrolledText" 模板,返回 ``(top, text)``。"""
|
||||
top = ttk.Frame(tab)
|
||||
top.pack(fill=X, padx=10, pady=(10, 0))
|
||||
|
||||
text = ScrolledText_cls(tab)
|
||||
text.pack(fill=BOTH, expand=True, padx=10, pady=10)
|
||||
try:
|
||||
text.configure(font=("Consolas", 10))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return top, text
|
||||
|
||||
|
||||
def setup_stats_tab(
|
||||
stats_tab: tk.Misc,
|
||||
*,
|
||||
runner: Any,
|
||||
ScrolledText_cls: Any,
|
||||
) -> Callable[[], None]:
|
||||
"""构建统计信息 Tab + 刷新按钮,返回 ``refresh_stats`` 回调。"""
|
||||
stats_top, stats_text = setup_simple_text_tab(stats_tab, ScrolledText_cls=ScrolledText_cls)
|
||||
|
||||
def refresh_stats() -> None:
|
||||
"""委托给 gui/components/stats_formatter.format_stats(纯字符串构建)。"""
|
||||
try:
|
||||
from gui.components.stats_formatter import format_stats
|
||||
|
||||
stats = runner.get_stats()
|
||||
stats_text.delete("1.0", "end")
|
||||
stats_text.insert("1.0", "\n".join(format_stats(stats)))
|
||||
except Exception as e:
|
||||
stats_text.delete("1.0", "end")
|
||||
error_detail = traceback.format_exc()
|
||||
stats_text.insert(
|
||||
"1.0", f"刷新统计信息失败:{e}\n\n详细信息:\n{error_detail}"
|
||||
)
|
||||
|
||||
ttk.Button(stats_top, text="刷新", command=refresh_stats).pack(side=LEFT)
|
||||
return refresh_stats
|
||||
|
||||
|
||||
def setup_text_tab_with_refresh(
|
||||
tab: tk.Misc,
|
||||
*,
|
||||
refresh_impl: Callable[[tk.Text], None],
|
||||
ScrolledText_cls: Any,
|
||||
) -> Callable[[], None]:
|
||||
"""``setup_simple_text_tab`` + 一个绑定到刷新按钮的 ``refresh_impl(text)`` 回调。
|
||||
|
||||
用于 reservation / high_value / ocr_results 等"刷新按钮 → 把内容写入 text"的简单 Tab。
|
||||
返回零参数的 ``refresh()`` 给调用方调度。
|
||||
"""
|
||||
top, text = setup_simple_text_tab(tab, ScrolledText_cls=ScrolledText_cls)
|
||||
|
||||
def refresh() -> None:
|
||||
refresh_impl(text)
|
||||
|
||||
ttk.Button(top, text="刷新", command=refresh).pack(side=LEFT)
|
||||
return refresh
|
||||
|
||||
|
||||
def setup_actions_log_tab(
|
||||
actions_log_tab: tk.Misc,
|
||||
*,
|
||||
ScrolledText_cls: Any,
|
||||
theme_getter: Callable[[], str],
|
||||
) -> Callable[[], None]:
|
||||
"""构建行为日志 Tab(simple text + 工具栏),返回 ``refresh_actions_log``。"""
|
||||
from gui.components.actions_log_toolbar import setup_actions_log_toolbar
|
||||
|
||||
actions_log_top, actions_log_text = setup_simple_text_tab(
|
||||
actions_log_tab, ScrolledText_cls=ScrolledText_cls,
|
||||
)
|
||||
handles = setup_actions_log_toolbar(
|
||||
actions_log_top,
|
||||
actions_log_text=actions_log_text,
|
||||
theme_getter=theme_getter,
|
||||
)
|
||||
return handles.refresh_actions_log
|
||||
|
||||
|
||||
def setup_ocr_results_tab(
|
||||
ocr_results_tab: tk.Misc,
|
||||
*,
|
||||
ScrolledText_cls: Any,
|
||||
) -> Tuple[Callable[[Any], None], Callable[[], None]]:
|
||||
"""构建 OCR 结果 Tab,返回 ``(update_ocr_results, refresh_now)``。
|
||||
|
||||
- ``update_ocr_results(results)``: 由 do_screenshot 完成 OCR 后调用,刷新内容
|
||||
- ``refresh_now()``: 给"刷新"按钮(显示空内容)
|
||||
"""
|
||||
from gui.components.ocr_results_view import update_ocr_results as _update_ocr_results_impl
|
||||
|
||||
ocr_results_top, ocr_results_text = setup_simple_text_tab(
|
||||
ocr_results_tab, ScrolledText_cls=ScrolledText_cls,
|
||||
)
|
||||
|
||||
def update_ocr_results(results: Any) -> None:
|
||||
_update_ocr_results_impl(ocr_results_text, results)
|
||||
|
||||
def refresh_now() -> None:
|
||||
update_ocr_results([])
|
||||
|
||||
ttk.Button(ocr_results_top, text="刷新", command=refresh_now).pack(side=LEFT)
|
||||
ttk.Label(ocr_results_top, text='(点击"截图+OCR"按钮自动更新)').pack(
|
||||
side=LEFT, padx=(10, 0)
|
||||
)
|
||||
return update_ocr_results, refresh_now
|
||||
@@ -0,0 +1,99 @@
|
||||
"""通用文本 widget 搜索函数。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``_generic_search_widget``,
|
||||
被运行日志和行为日志两处搜索功能共用,本身是纯函数(不依赖 ``main()`` 闭包变量),
|
||||
适合直接迁到模块顶层。
|
||||
|
||||
行为不变:在 widget 中根据 search_var 搜索并高亮;返回更新后的当前匹配索引。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import List, Tuple
|
||||
|
||||
|
||||
def generic_search_widget(
|
||||
widget: tk.Text,
|
||||
search_var: tk.StringVar,
|
||||
matches_list: List[Tuple[str, str]],
|
||||
current_index: int,
|
||||
direction: int = 1,
|
||||
) -> int:
|
||||
"""通用的文本控件搜索函数:在 widget 中根据 search_var 搜索并高亮。
|
||||
|
||||
- widget: 文本控件(ScrolledText)
|
||||
- search_var: tk.StringVar (包含搜索词)
|
||||
- matches_list: 可变列表,用来保存匹配区间 (start_index, end_index)
|
||||
- current_index: 当前匹配的索引(整数),返回更新后的索引
|
||||
- direction: 1 为下一个,-1 为上一个
|
||||
"""
|
||||
search_text = search_var.get().strip()
|
||||
if not search_text:
|
||||
try:
|
||||
widget.tag_remove("search_highlight", "1.0", "end")
|
||||
widget.tag_remove("search_current", "1.0", "end")
|
||||
except Exception:
|
||||
pass
|
||||
matches_list.clear()
|
||||
return -1
|
||||
|
||||
content = widget.get("1.0", "end-1c")
|
||||
if not content:
|
||||
return -1
|
||||
|
||||
try:
|
||||
widget.tag_remove("search_highlight", "1.0", "end")
|
||||
widget.tag_remove("search_current", "1.0", "end")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
widget.tag_config("search_highlight", background="yellow")
|
||||
widget.tag_config("search_current", background="orange")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
matches_list.clear()
|
||||
start_pos = 0
|
||||
search_text_lower = search_text.lower()
|
||||
content_lower = content.lower()
|
||||
|
||||
while True:
|
||||
pos = content_lower.find(search_text_lower, start_pos)
|
||||
if pos == -1:
|
||||
break
|
||||
|
||||
line_start = content[:pos].rfind("\n") + 1
|
||||
line_num = content[:pos].count("\n") + 1
|
||||
col_num = pos - line_start
|
||||
|
||||
start_index = f"{line_num}.{col_num}"
|
||||
end_index = f"{line_num}.{col_num + len(search_text)}"
|
||||
|
||||
matches_list.append((start_index, end_index))
|
||||
start_pos = pos + 1
|
||||
|
||||
if not matches_list:
|
||||
return -1
|
||||
|
||||
for s, e in matches_list:
|
||||
try:
|
||||
widget.tag_add("search_highlight", s, e)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if direction == 1:
|
||||
current_index = (current_index + 1) % len(matches_list)
|
||||
else:
|
||||
current_index = (current_index - 1) % len(matches_list)
|
||||
|
||||
try:
|
||||
s, e = matches_list[current_index]
|
||||
widget.tag_add("search_current", s, e)
|
||||
widget.see(s)
|
||||
widget.mark_set("insert", s)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return current_index
|
||||
@@ -0,0 +1,48 @@
|
||||
"""GUI 顶部常驻按钮区(保存配置 + 截图+OCR)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 21 行的 widget 创建段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, RIGHT
|
||||
from typing import Callable, Sequence, Tuple
|
||||
|
||||
from gui.components.screenshot_action import do_screenshot as _do_screenshot_impl
|
||||
|
||||
|
||||
def setup_top_buttons(
|
||||
top: tk.Misc,
|
||||
*,
|
||||
device_var: tk.StringVar,
|
||||
y_var: tk.IntVar,
|
||||
image_var: tk.StringVar,
|
||||
on_line: Callable[[str], None],
|
||||
root: tk.Misc,
|
||||
on_save_ui_to_config: Callable[[], None],
|
||||
on_ocr_results: Callable[[Sequence[Tuple[str, str, str, str]]], None],
|
||||
on_refresh_preview: Callable[[], None],
|
||||
) -> None:
|
||||
"""构建顶部常驻按钮区(保存配置 + 截图+OCR)。"""
|
||||
top_btns = ttk.Frame(top)
|
||||
top_btns.pack(side=RIGHT, padx=(20, 0))
|
||||
ttk.Button(top_btns, text="保存配置", command=on_save_ui_to_config).pack(
|
||||
side=LEFT, padx=(0, 8)
|
||||
)
|
||||
# 截图+OCR 按钮放在顶部,方便随时使用
|
||||
screenshot_btn = ttk.Button(
|
||||
top_btns,
|
||||
text="截图+OCR",
|
||||
command=lambda: _do_screenshot_impl(
|
||||
device_id=device_var.get().strip(),
|
||||
y_offset=int(y_var.get() or 0),
|
||||
image_var=image_var,
|
||||
on_line=on_line,
|
||||
root=root,
|
||||
on_ocr_results=on_ocr_results,
|
||||
on_refresh_preview=on_refresh_preview,
|
||||
),
|
||||
)
|
||||
screenshot_btn.pack(side=LEFT, padx=(0, 8))
|
||||
@@ -0,0 +1,139 @@
|
||||
"""GUI 顶部设备选择栏(设备下拉 + 刷新设备 + 扫描 WiFi + WiFi ADB 按钮 + Y偏移)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括 5 个互相耦合的闭包:
|
||||
- ``refresh_devices``: 刷新 adb 设备列表
|
||||
- ``_try_reconnect_last_wifi``: 启动后延迟尝试重连上次设备
|
||||
- ``_on_scan_one_click``: 一键扫描局域网
|
||||
- ``_handle_scan_result``: 扫描结果处理
|
||||
- ``_open_scan_pick_dialog``: 多设备选择弹窗
|
||||
|
||||
返回 ``TopDeviceBarHandles`` 暴露 ``device_var`` / ``adb_exe`` / ``refresh_devices``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, X
|
||||
from typing import Callable, Optional
|
||||
|
||||
from gui.gui_core import find_adb_executable, list_adb_devices
|
||||
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog
|
||||
from gui.components.wifi_adb_pick_dialog import open_scan_pick_dialog
|
||||
from gui.components.wifi_adb_reconnect import try_reconnect_last_wifi
|
||||
from gui.components.wifi_adb_one_click_scan import (
|
||||
on_scan_one_click,
|
||||
_handle_scan_result,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class TopDeviceBarHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
device_var: tk.StringVar
|
||||
refresh_devices: Callable[[], None]
|
||||
# adb_exe 是动态值(refresh_devices 会更新),用 getter 暴露
|
||||
get_adb_exe: Callable[[], str]
|
||||
|
||||
|
||||
def setup_top_device_bar(
|
||||
top: tk.Misc,
|
||||
*,
|
||||
root: tk.Misc,
|
||||
on_line: Callable[[str], None],
|
||||
y_var: Optional[tk.IntVar] = None,
|
||||
) -> TopDeviceBarHandles:
|
||||
"""构建顶部设备选择栏 + WiFi 工具按钮 + (可选)Y偏移 Spinbox。
|
||||
|
||||
若提供 ``y_var``,会在所有按钮之后追加 "Y偏移:" 标签 + Spinbox(范围 -200..200)。
|
||||
"""
|
||||
# 用 list 持有 adb_exe 让闭包可以原地更新(替代 nonlocal)
|
||||
adb_exe_box = [find_adb_executable()]
|
||||
devices = list_adb_devices(adb_exe_box[0])
|
||||
device_var = tk.StringVar(value=(devices[0] if devices else ""))
|
||||
|
||||
ttk.Label(top, text="设备:").pack(side=LEFT)
|
||||
device_combo = ttk.Combobox(top, textvariable=device_var, values=devices, width=28)
|
||||
device_combo.pack(side=LEFT, padx=(0, 10))
|
||||
|
||||
def refresh_devices() -> None:
|
||||
adb_exe_box[0] = find_adb_executable()
|
||||
devs = list_adb_devices(adb_exe_box[0])
|
||||
device_combo["values"] = devs
|
||||
if devs and not device_var.get():
|
||||
device_var.set(devs[0])
|
||||
if not adb_exe_box[0]:
|
||||
on_line("[设备] 未找到 adb.exe(请确认已安装 platform-tools)")
|
||||
elif not devs:
|
||||
on_line("[设备] adb 可用,但未发现 device 状态设备(可能未授权/未连接)")
|
||||
|
||||
refresh_devices_btn = ttk.Button(top, text="刷新设备", command=refresh_devices)
|
||||
refresh_devices_btn.pack(side=LEFT, padx=(0, 8))
|
||||
|
||||
# 一键扫描局域网 ADB 设备并自动连接(同 WiFi 下设备已开 5555 / 已授权时无需 USB)
|
||||
scan_connect_btn = ttk.Button(top, text="扫描 WiFi")
|
||||
scan_connect_btn.pack(side=LEFT, padx=(0, 20))
|
||||
_scan_busy = {"flag": False}
|
||||
|
||||
def _try_reconnect_last_wifi() -> None:
|
||||
try_reconnect_last_wifi(
|
||||
root,
|
||||
adb_exe=adb_exe_box[0],
|
||||
device_var=device_var,
|
||||
on_line=on_line,
|
||||
refresh_devices=refresh_devices,
|
||||
)
|
||||
|
||||
# 启动时延迟一点,等界面创建完成再尝试重连
|
||||
root.after(300, _try_reconnect_last_wifi)
|
||||
|
||||
def _open_scan_pick_dialog(devs):
|
||||
open_scan_pick_dialog(
|
||||
root,
|
||||
devs,
|
||||
device_var=device_var,
|
||||
on_line=on_line,
|
||||
refresh_devices=refresh_devices,
|
||||
)
|
||||
|
||||
def _on_scan_one_click() -> None:
|
||||
on_scan_one_click(
|
||||
adb_exe=adb_exe_box[0],
|
||||
scan_btn=scan_connect_btn,
|
||||
scan_busy=_scan_busy,
|
||||
root=root,
|
||||
on_line=on_line,
|
||||
device_var=device_var,
|
||||
refresh_devices=refresh_devices,
|
||||
open_pick_dialog=_open_scan_pick_dialog,
|
||||
)
|
||||
|
||||
scan_connect_btn.config(command=_on_scan_one_click)
|
||||
|
||||
# WiFi ADB 功能
|
||||
wifi_adb_btn = ttk.Button(
|
||||
top,
|
||||
text="WiFi ADB",
|
||||
command=lambda: open_wifi_adb_dialog(
|
||||
root,
|
||||
adb_exe=adb_exe_box[0],
|
||||
on_line=on_line,
|
||||
refresh_devices=refresh_devices,
|
||||
),
|
||||
)
|
||||
wifi_adb_btn.pack(side=LEFT, padx=(0, 20))
|
||||
|
||||
# 可选的 Y偏移 Spinbox(放在所有按钮之后)
|
||||
if y_var is not None:
|
||||
ttk.Label(top, text="Y偏移:").pack(side=LEFT)
|
||||
ttk.Spinbox(top, from_=-200, to=200, textvariable=y_var, width=6).pack(
|
||||
side=LEFT, padx=(0, 12)
|
||||
)
|
||||
|
||||
return TopDeviceBarHandles(
|
||||
device_var=device_var,
|
||||
refresh_devices=refresh_devices,
|
||||
get_adb_exe=lambda: adb_exe_box[0],
|
||||
)
|
||||
@@ -0,0 +1,412 @@
|
||||
"""WiFi ADB 主设置对话框。
|
||||
|
||||
从 ``gui/gui_app.py`` 中抽出。原本是 ``main()`` 内的闭包 ``open_wifi_adb_dialog``,
|
||||
通过 "WiFi ADB" 顶部按钮触发。
|
||||
|
||||
依赖通过显式参数注入:``parent`` (主窗口)、``adb_exe`` (ADB 可执行路径)、
|
||||
``on_line`` (日志回调)、``refresh_devices`` (刷新主窗口设备下拉的回调)。
|
||||
连接成功后会自递归打开新对话框以反映最新设备状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, W, X
|
||||
from typing import Callable
|
||||
|
||||
from gui.gui_core import (
|
||||
auto_connect_wifi_adb,
|
||||
connect_wifi_adb,
|
||||
disconnect_wifi_adb,
|
||||
enable_wifi_adb,
|
||||
get_connected_wifi_devices,
|
||||
get_device_ip,
|
||||
list_adb_devices,
|
||||
)
|
||||
from gui.gui_core_pkg import (
|
||||
clear_last_wifi_target,
|
||||
get_last_wifi_target,
|
||||
set_last_wifi_target,
|
||||
)
|
||||
from gui.gui_core_pkg.wifi_adb_scan import query_device_model
|
||||
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
|
||||
|
||||
|
||||
def open_wifi_adb_dialog(
|
||||
parent: tk.Misc,
|
||||
*,
|
||||
adb_exe: str,
|
||||
on_line: Callable[[str], None],
|
||||
refresh_devices: Callable[[], None],
|
||||
) -> None:
|
||||
"""打开WiFi ADB设置对话框"""
|
||||
dialog = tk.Toplevel(parent)
|
||||
dialog.title("WiFi ADB 设置")
|
||||
dialog.geometry("500x450")
|
||||
# 允许用户调整对话框大小,避免窗口内容被裁剪
|
||||
dialog.resizable(True, True)
|
||||
dialog.minsize(420, 320)
|
||||
|
||||
# 获取设备列表并分类
|
||||
current_devices = list_adb_devices(adb_exe)
|
||||
wifi_devices = get_connected_wifi_devices(adb_exe)
|
||||
usb_devices = [d for d in current_devices if d not in wifi_devices]
|
||||
|
||||
# 创建设备选择区域
|
||||
device_frame = ttk.LabelFrame(dialog, text="设备选择", padding=10)
|
||||
device_frame.pack(fill=X, padx=10, pady=10)
|
||||
# 使内部 grid 列随窗口宽度伸缩
|
||||
device_frame.grid_columnconfigure(0, weight=3)
|
||||
device_frame.grid_columnconfigure(1, weight=1)
|
||||
|
||||
# USB设备选择
|
||||
ttk.Label(device_frame, text="USB设备(用于首次启用):").grid(
|
||||
row=0, column=0, sticky=W, pady=(0, 5)
|
||||
)
|
||||
usb_device_var = tk.StringVar(value=(usb_devices[0] if usb_devices else ""))
|
||||
usb_combo = ttk.Combobox(
|
||||
device_frame,
|
||||
textvariable=usb_device_var,
|
||||
values=usb_devices,
|
||||
width=25,
|
||||
state="readonly" if not usb_devices else "normal",
|
||||
)
|
||||
usb_combo.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
|
||||
|
||||
# 显示USB设备状态
|
||||
usb_status_text = (
|
||||
f"检测到 {len(usb_devices)} 个USB设备"
|
||||
if usb_devices
|
||||
else "未检测到USB设备,请确保设备已连接并授权"
|
||||
)
|
||||
usb_status_label = ttk.Label(
|
||||
device_frame,
|
||||
text=usb_status_text,
|
||||
font=("Arial", 8),
|
||||
foreground="red" if not usb_devices else "green",
|
||||
)
|
||||
usb_status_label.grid(row=2, column=0, sticky=W, pady=(0, 10))
|
||||
|
||||
# WiFi设备选择
|
||||
ttk.Label(device_frame, text="WiFi设备(已连接):").grid(
|
||||
row=0, column=1, sticky=W, pady=(0, 5)
|
||||
)
|
||||
wifi_device_var = tk.StringVar(value=(wifi_devices[0] if wifi_devices else ""))
|
||||
wifi_combo = ttk.Combobox(
|
||||
device_frame,
|
||||
textvariable=wifi_device_var,
|
||||
values=wifi_devices,
|
||||
width=25,
|
||||
state="readonly" if not wifi_devices else "normal",
|
||||
)
|
||||
wifi_combo.grid(row=1, column=1, pady=(0, 10), sticky="we")
|
||||
|
||||
# 显示WiFi设备状态
|
||||
wifi_status_text = (
|
||||
f"已连接 {len(wifi_devices)} 个WiFi设备"
|
||||
if wifi_devices
|
||||
else "无WiFi设备连接"
|
||||
)
|
||||
wifi_status_label = ttk.Label(
|
||||
device_frame,
|
||||
text=wifi_status_text,
|
||||
font=("Arial", 8),
|
||||
foreground="blue" if wifi_devices else "gray",
|
||||
)
|
||||
wifi_status_label.grid(row=2, column=1, sticky=W, pady=(0, 10))
|
||||
|
||||
# IP地址输入区域
|
||||
ip_frame = ttk.LabelFrame(dialog, text="连接信息", padding=10)
|
||||
ip_frame.pack(fill=X, padx=10, pady=(0, 10))
|
||||
# 使 IP/端口 输入框随窗口宽度伸缩
|
||||
ip_frame.grid_columnconfigure(0, weight=3)
|
||||
ip_frame.grid_columnconfigure(1, weight=1)
|
||||
|
||||
ttk.Label(ip_frame, text="设备IP地址:").grid(
|
||||
row=0, column=0, sticky=W, pady=(0, 5)
|
||||
)
|
||||
ip_var = tk.StringVar()
|
||||
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=25)
|
||||
ip_entry.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
|
||||
|
||||
ttk.Label(ip_frame, text="端口(默认5555):").grid(
|
||||
row=0, column=1, sticky=W, pady=(0, 5)
|
||||
)
|
||||
port_var = tk.StringVar(value="5555")
|
||||
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=25)
|
||||
port_entry.grid(row=1, column=1, pady=(0, 10), sticky="we")
|
||||
|
||||
# 按钮区域
|
||||
button_frame = ttk.Frame(dialog)
|
||||
button_frame.pack(fill=X, padx=10, pady=10)
|
||||
|
||||
def enable_wifi():
|
||||
device_id = usb_device_var.get()
|
||||
if not device_id:
|
||||
on_line("[WiFi ADB] 请先选择USB设备")
|
||||
return
|
||||
success, msg = enable_wifi_adb(adb_exe, device_id)
|
||||
on_line(f"[WiFi ADB] {msg}")
|
||||
if success:
|
||||
# 尝试获取IP地址
|
||||
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
|
||||
if ip_success:
|
||||
ip_var.set(ip_msg)
|
||||
on_line(f"[WiFi ADB] 设备IP地址: {ip_msg}")
|
||||
|
||||
def connect_wifi():
|
||||
ip = ip_var.get().strip()
|
||||
port = port_var.get().strip() or "5555"
|
||||
if not ip:
|
||||
on_line("[WiFi ADB] 请输入IP地址")
|
||||
return
|
||||
success, msg = connect_wifi_adb(adb_exe, ip, port)
|
||||
on_line(f"[WiFi ADB] {msg}")
|
||||
if success:
|
||||
# 记住,下次启动自动重连
|
||||
target = ip if ":" in ip else f"{ip}:{port}"
|
||||
model = ""
|
||||
try:
|
||||
model = query_device_model(adb_exe, target)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
set_last_wifi_target(target, model)
|
||||
on_line(
|
||||
f"[WiFi ADB] 已记住 {target}"
|
||||
+ (f" ({model})" if model else "")
|
||||
+ ",下次 GUI 启动会自动重连"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 刷新设备列表
|
||||
refresh_devices()
|
||||
# 重新打开对话框以显示新的WiFi设备
|
||||
dialog.destroy()
|
||||
open_wifi_adb_dialog(parent, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
|
||||
|
||||
def disconnect_wifi():
|
||||
device_id = wifi_device_var.get()
|
||||
if not device_id:
|
||||
on_line("[WiFi ADB] 请先选择WiFi设备")
|
||||
return
|
||||
# 从设备ID中提取IP地址
|
||||
ip_match = re.search(r"(\d+\.\d+\.\d+\.\d+)", device_id)
|
||||
if not ip_match:
|
||||
on_line("[WiFi ADB] 无法从设备ID中提取IP地址")
|
||||
return
|
||||
ip = ip_match.group(1)
|
||||
success, msg = disconnect_wifi_adb(adb_exe, ip, "5555")
|
||||
on_line(f"[WiFi ADB] {msg}")
|
||||
if success:
|
||||
# 如果断开的就是上次记住的设备,清掉记录避免下次启动徒劳重试
|
||||
try:
|
||||
last = get_last_wifi_target()
|
||||
last_target = str(last.get("target") or "")
|
||||
if last_target.startswith(ip):
|
||||
clear_last_wifi_target()
|
||||
on_line(
|
||||
f"[WiFi ADB] 已清除上次设备记录 {last_target}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 刷新设备列表
|
||||
refresh_devices()
|
||||
# 重新打开对话框以更新设备列表
|
||||
dialog.destroy()
|
||||
open_wifi_adb_dialog(parent, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
|
||||
|
||||
def auto_connect_wifi():
|
||||
device_id = usb_device_var.get()
|
||||
if not device_id:
|
||||
on_line("[WiFi ADB] 请先选择USB设备")
|
||||
return
|
||||
|
||||
# 显示进度
|
||||
on_line("[WiFi ADB] 开始自动连接...")
|
||||
|
||||
# 创建进度对话框
|
||||
progress_dialog = tk.Toplevel(dialog)
|
||||
progress_dialog.title("自动连接中...")
|
||||
progress_dialog.geometry("300x120")
|
||||
progress_dialog.resizable(False, False)
|
||||
|
||||
ttk.Label(progress_dialog, text="正在自动连接WiFi ADB,请稍候...").pack(
|
||||
pady=10
|
||||
)
|
||||
ttk.Label(progress_dialog, text="设备将会重启,请等待重启完成").pack(
|
||||
pady=(0, 10)
|
||||
)
|
||||
progress_bar = ttk.Progressbar(progress_dialog, mode="indeterminate")
|
||||
progress_bar.pack(fill=X, padx=20, pady=(0, 20))
|
||||
progress_bar.start()
|
||||
|
||||
def do_auto_connect():
|
||||
try:
|
||||
success, msg = auto_connect_wifi_adb(adb_exe, device_id)
|
||||
progress_dialog.destroy()
|
||||
on_line(f"[WiFi ADB] {msg}")
|
||||
if success:
|
||||
# 刷新设备列表
|
||||
refresh_devices()
|
||||
# 尝试获取并显示IP
|
||||
ip_success, ip_msg = get_device_ip(adb_exe, device_id)
|
||||
if ip_success:
|
||||
ip_var.set(ip_msg)
|
||||
# 记住目标设备
|
||||
target = (
|
||||
ip_msg if ":" in ip_msg else f"{ip_msg}:5555"
|
||||
)
|
||||
model = ""
|
||||
try:
|
||||
model = query_device_model(adb_exe, target)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
set_last_wifi_target(target, model)
|
||||
on_line(
|
||||
f"[WiFi ADB] 已记住 {target}"
|
||||
+ (f" ({model})" if model else "")
|
||||
+ ",下次 GUI 启动会自动重连"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 重新打开对话框以显示新的WiFi设备
|
||||
dialog.destroy()
|
||||
open_wifi_adb_dialog(parent, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
|
||||
except Exception as e:
|
||||
progress_dialog.destroy()
|
||||
on_line(f"[WiFi ADB] 自动连接异常: {str(e)}")
|
||||
|
||||
# 在后台线程中执行自动连接
|
||||
threading.Thread(target=do_auto_connect, daemon=True).start()
|
||||
|
||||
# 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮)
|
||||
is_maximized = False
|
||||
original_geometry = None
|
||||
|
||||
def toggle_maximize():
|
||||
nonlocal is_maximized, original_geometry
|
||||
try:
|
||||
if not is_maximized:
|
||||
original_geometry = dialog.geometry()
|
||||
dialog.update_idletasks()
|
||||
w = int(dialog.winfo_screenwidth() * 0.8)
|
||||
h = int(dialog.winfo_screenheight() * 0.8)
|
||||
dialog.geometry(f"{w}x{h}")
|
||||
is_maximized = True
|
||||
else:
|
||||
if original_geometry:
|
||||
dialog.geometry(original_geometry)
|
||||
is_maximized = False
|
||||
except Exception as e:
|
||||
on_line(f"[WiFi ADB] 切换窗口大小失败: {e}")
|
||||
|
||||
def refresh_device_lists():
|
||||
"""刷新设备列表"""
|
||||
nonlocal usb_devices, wifi_devices
|
||||
current_devices = list_adb_devices(adb_exe)
|
||||
wifi_devices = get_connected_wifi_devices(adb_exe)
|
||||
usb_devices = [d for d in current_devices if d not in wifi_devices]
|
||||
|
||||
# 更新USB设备下拉框
|
||||
usb_combo["values"] = usb_devices
|
||||
usb_combo["state"] = "readonly" if not usb_devices else "normal"
|
||||
if usb_devices:
|
||||
usb_device_var.set(usb_devices[0])
|
||||
else:
|
||||
usb_device_var.set("")
|
||||
|
||||
# 更新WiFi设备下拉框
|
||||
wifi_combo["values"] = wifi_devices
|
||||
wifi_combo["state"] = "readonly" if not wifi_devices else "normal"
|
||||
if wifi_devices:
|
||||
wifi_device_var.set(wifi_devices[0])
|
||||
else:
|
||||
wifi_device_var.set("")
|
||||
|
||||
# 更新状态标签
|
||||
usb_status_text = (
|
||||
f"检测到 {len(usb_devices)} 个USB设备"
|
||||
if usb_devices
|
||||
else "未检测到USB设备,请确保设备已连接并授权"
|
||||
)
|
||||
usb_status_label.config(
|
||||
text=usb_status_text, foreground="red" if not usb_devices else "green"
|
||||
)
|
||||
|
||||
wifi_status_text = (
|
||||
f"已连接 {len(wifi_devices)} 个WiFi设备"
|
||||
if wifi_devices
|
||||
else "无WiFi设备连接"
|
||||
)
|
||||
wifi_status_label.config(
|
||||
text=wifi_status_text, foreground="blue" if wifi_devices else "gray"
|
||||
)
|
||||
|
||||
on_line("[WiFi ADB] 设备列表已刷新")
|
||||
|
||||
# USB设备操作按钮
|
||||
usb_button_frame = ttk.Frame(button_frame)
|
||||
usb_button_frame.pack(fill=X, pady=(0, 10))
|
||||
|
||||
ttk.Label(usb_button_frame, text="USB设备操作:").pack(anchor=W)
|
||||
usb_buttons_frame = ttk.Frame(usb_button_frame)
|
||||
usb_buttons_frame.pack(fill=X, pady=(5, 0))
|
||||
|
||||
ttk.Button(usb_buttons_frame, text="自动连接", command=auto_connect_wifi).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
ttk.Button(usb_buttons_frame, text="启用WiFi ADB", command=enable_wifi).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
ttk.Button(usb_buttons_frame, text="连接", command=connect_wifi).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
ttk.Button(
|
||||
usb_buttons_frame, text="刷新设备", command=refresh_device_lists
|
||||
).pack(side=LEFT)
|
||||
# 如果窗口无法通过边框调整,提供放大/恢复按钮作为备用
|
||||
ttk.Button(usb_buttons_frame, text="放大/恢复", command=toggle_maximize).pack(
|
||||
side=LEFT, padx=(8, 0)
|
||||
)
|
||||
|
||||
# WiFi设备操作按钮
|
||||
wifi_button_frame = ttk.Frame(button_frame)
|
||||
wifi_button_frame.pack(fill=X, pady=(10, 0))
|
||||
|
||||
ttk.Label(wifi_button_frame, text="WiFi设备操作:").pack(anchor=W)
|
||||
wifi_buttons_frame = ttk.Frame(wifi_button_frame)
|
||||
wifi_buttons_frame.pack(fill=X, pady=(5, 0))
|
||||
|
||||
ttk.Button(wifi_buttons_frame, text="断开连接", command=disconnect_wifi).pack(
|
||||
side=LEFT
|
||||
)
|
||||
ttk.Button(
|
||||
wifi_buttons_frame,
|
||||
text="扫描局域网",
|
||||
command=lambda: open_scan_dialog(
|
||||
dialog, adb_exe, ip_var, on_line, refresh_device_lists
|
||||
),
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
|
||||
# 说明文本
|
||||
info_text = """重要说明:
|
||||
• Android系统安全要求:首次启用WiFi ADB必须通过USB连接
|
||||
• 工作流程:USB连接 → 启用WiFi ADB → 设备重启 → WiFi连接
|
||||
• 设置完成后,设备会出现在"WiFi设备"列表中,无需再次USB连接
|
||||
• 设备重启后WiFi ADB模式会保持,可直接通过WiFi连接使用
|
||||
|
||||
使用方法:
|
||||
1. 连接Android设备到电脑(USB)
|
||||
2. 点击"刷新设备"确保设备被检测到
|
||||
3. 选择USB设备,点击"自动连接"或手动操作
|
||||
4. 等待设备重启后即可通过WiFi使用"""
|
||||
|
||||
info_label = ttk.Label(
|
||||
dialog, text=info_text, justify=LEFT, font=("Arial", 9), wraplength=460
|
||||
)
|
||||
info_label.pack(pady=(10, 0), padx=20, anchor="w")
|
||||
@@ -0,0 +1,126 @@
|
||||
"""主窗口 "扫描 WiFi" 按钮的一键扫描逻辑。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的两个闭包
|
||||
``_on_scan_one_click`` 和 ``_handle_scan_result``,它们紧耦合。
|
||||
|
||||
依赖通过显式参数注入:扫描按钮、忙碌标志、设备变量、各类回调。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Callable, Dict, Sequence
|
||||
|
||||
from gui.gui_core_pkg import discover_adb_devices, set_last_wifi_target
|
||||
|
||||
|
||||
def _handle_scan_result(
|
||||
devs: Sequence,
|
||||
*,
|
||||
on_line: Callable[[str], None],
|
||||
device_var: tk.StringVar,
|
||||
refresh_devices: Callable[[], None],
|
||||
open_pick_dialog: Callable[[Sequence], None],
|
||||
) -> None:
|
||||
if not devs:
|
||||
on_line("[扫描] 未发现开放 5555 端口的设备(同 WiFi 下设备需先启用 ADB 调试)")
|
||||
return
|
||||
|
||||
connected = [d for d in devs if d.adb_state == "connected"]
|
||||
unauthorized = [d for d in devs if d.adb_state == "unauthorized"]
|
||||
failed = [d for d in devs if d.adb_state == "failed"]
|
||||
|
||||
if len(connected) == 1 and not unauthorized:
|
||||
d = connected[0]
|
||||
refresh_devices()
|
||||
device_var.set(d.target)
|
||||
# 记住,下次启动自动重连
|
||||
try:
|
||||
set_last_wifi_target(d.target, d.model or "")
|
||||
except Exception:
|
||||
pass
|
||||
on_line(
|
||||
f"[扫描] 自动连接成功: {d.target}"
|
||||
+ (f" ({d.model})" if d.model else "")
|
||||
+ "(已记住,下次 GUI 启动会自动重连)"
|
||||
)
|
||||
return
|
||||
|
||||
if len(connected) == 0 and len(unauthorized) >= 1:
|
||||
targets = ", ".join(d.target for d in unauthorized)
|
||||
on_line(
|
||||
f"[扫描] 发现 {len(unauthorized)} 个未授权设备: {targets}。"
|
||||
f"请在手机上确认 ADB 调试授权(勾选'始终允许这台电脑调试'),然后再点'扫描 WiFi'"
|
||||
)
|
||||
return
|
||||
|
||||
if len(connected) == 0 and len(unauthorized) == 0 and failed:
|
||||
# 端口开放但 adb connect 失败:通常是 adb 服务异常 / 设备处于诡异状态。
|
||||
# 把 adb 真实返回拼出来,让用户看到根因,而不是误导地说"请授权"。
|
||||
for d in failed:
|
||||
msg = (d.message or "").strip().replace("\n", " | ")
|
||||
on_line(f"[扫描] {d.target} 连接失败 (state=failed): {msg or '未知错误'}")
|
||||
on_line(
|
||||
"[扫描] 提示:可在终端跑 `adb kill-server && adb connect <ip:port>` 看真实输出,"
|
||||
"或检查是否多个 adb 进程冲突"
|
||||
)
|
||||
return
|
||||
|
||||
# 多个候选 → 弹出选择对话框
|
||||
open_pick_dialog(devs)
|
||||
|
||||
|
||||
def on_scan_one_click(
|
||||
*,
|
||||
adb_exe: str,
|
||||
scan_btn: ttk.Button,
|
||||
scan_busy: Dict[str, bool],
|
||||
root: tk.Misc,
|
||||
on_line: Callable[[str], None],
|
||||
device_var: tk.StringVar,
|
||||
refresh_devices: Callable[[], None],
|
||||
open_pick_dialog: Callable[[Sequence], None],
|
||||
) -> None:
|
||||
"""主窗口"扫描 WiFi"按钮:后台扫描 → 按结果数智能处理。
|
||||
|
||||
- 0 个:日志提示
|
||||
- 1 个 connected:自动设为当前设备并刷新
|
||||
- 1 个 unauthorized:提示需要手机端授权
|
||||
- 多个:弹简单的列表对话框让用户选
|
||||
"""
|
||||
if scan_busy["flag"]:
|
||||
on_line("[扫描] 上次扫描尚未完成,请稍候")
|
||||
return
|
||||
scan_busy["flag"] = True
|
||||
scan_btn.config(state="disabled", text="扫描中...")
|
||||
on_line("[扫描] 开始扫描局域网 ADB 设备...")
|
||||
|
||||
def worker():
|
||||
try:
|
||||
devs = discover_adb_devices(
|
||||
adb_exe,
|
||||
on_phase=lambda msg: on_line(f"[扫描] {msg}"),
|
||||
)
|
||||
except Exception as e:
|
||||
on_line(f"[扫描] 异常: {e}")
|
||||
devs = []
|
||||
|
||||
def render():
|
||||
scan_busy["flag"] = False
|
||||
scan_btn.config(state="normal", text="扫描 WiFi")
|
||||
_handle_scan_result(
|
||||
devs,
|
||||
on_line=on_line,
|
||||
device_var=device_var,
|
||||
refresh_devices=refresh_devices,
|
||||
open_pick_dialog=open_pick_dialog,
|
||||
)
|
||||
|
||||
try:
|
||||
root.after(0, render)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
threading.Thread(target=worker, daemon=True).start()
|
||||
@@ -0,0 +1,108 @@
|
||||
"""扫描结果选择对话框。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``_open_scan_pick_dialog``,
|
||||
当 "扫描 WiFi" 一键扫描发现多台设备时弹出,让用户挑一个作为当前设备。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - 父窗口 (用于 ``Toplevel`` 与 ``transient``)
|
||||
- ``devs`` - 扫描结果列表(``DiscoveredDevice``)
|
||||
- ``device_var`` - 主窗口的设备 StringVar(选中后写入)
|
||||
- ``on_line`` - 日志回调
|
||||
- ``refresh_devices`` - 刷新主窗口设备下拉的回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, LEFT, RIGHT, W, X
|
||||
from typing import Callable, Sequence
|
||||
|
||||
from gui.gui_core_pkg import set_last_wifi_target
|
||||
|
||||
|
||||
def open_scan_pick_dialog(
|
||||
parent: tk.Misc,
|
||||
devs: Sequence,
|
||||
*,
|
||||
device_var: tk.StringVar,
|
||||
on_line: Callable[[str], None],
|
||||
refresh_devices: Callable[[], None],
|
||||
) -> None:
|
||||
"""简化版选择对话框:扫描结果已就绪,让用户从列表挑一个使用。"""
|
||||
pick_dlg = tk.Toplevel(parent)
|
||||
pick_dlg.title(f"扫描发现 {len(devs)} 台设备 - 请选择")
|
||||
pick_dlg.geometry("680x320")
|
||||
pick_dlg.transient(parent)
|
||||
|
||||
ttk.Label(
|
||||
pick_dlg,
|
||||
text="扫描发现多台设备,请选中一个作为当前设备:",
|
||||
font=("Arial", 9),
|
||||
).pack(anchor=W, padx=10, pady=(10, 4))
|
||||
|
||||
cols = ("target", "state", "model", "message")
|
||||
tree = ttk.Treeview(pick_dlg, columns=cols, show="headings", height=8)
|
||||
tree.heading("target", text="IP:Port")
|
||||
tree.heading("state", text="状态")
|
||||
tree.heading("model", text="设备型号")
|
||||
tree.heading("message", text="adb 返回")
|
||||
tree.column("target", width=140, anchor=W)
|
||||
tree.column("state", width=90, anchor=W)
|
||||
tree.column("model", width=120, anchor=W)
|
||||
tree.column("message", width=200, anchor=W)
|
||||
tree.pack(fill=BOTH, expand=True, padx=10, pady=(0, 8))
|
||||
|
||||
for d in devs:
|
||||
msg = (d.message or "").strip().replace("\n", " | ")
|
||||
tree.insert(
|
||||
"", "end",
|
||||
values=(d.target, d.adb_state, d.model or "-", msg[:200]),
|
||||
)
|
||||
|
||||
bottom = ttk.Frame(pick_dlg)
|
||||
bottom.pack(fill=X, padx=10, pady=(0, 10))
|
||||
|
||||
def use_selected():
|
||||
sel = tree.selection()
|
||||
if not sel:
|
||||
on_line("[扫描] 请先在列表中选中一个设备")
|
||||
return
|
||||
values = tree.item(sel[0])["values"]
|
||||
target = str(values[0])
|
||||
state = str(values[1])
|
||||
model = str(values[2] or "").strip()
|
||||
if model == "-":
|
||||
model = ""
|
||||
if state == "unauthorized":
|
||||
on_line(
|
||||
f"[扫描] {target} 未授权,请在手机上确认 ADB 调试授权后重试"
|
||||
)
|
||||
return
|
||||
if state == "failed":
|
||||
# 选中的就是失败项时,把对应的 message 拿出来给用户看真实根因
|
||||
fail_msg = ""
|
||||
for d in devs:
|
||||
if d.target == target:
|
||||
fail_msg = (d.message or "").strip().replace("\n", " | ")
|
||||
break
|
||||
on_line(
|
||||
f"[扫描] {target} adb 连接失败: {fail_msg or '未知错误'}"
|
||||
)
|
||||
return
|
||||
if state != "connected":
|
||||
on_line(f"[扫描] {target} 当前状态={state},无法直接使用")
|
||||
return
|
||||
refresh_devices()
|
||||
device_var.set(target)
|
||||
try:
|
||||
set_last_wifi_target(target, model)
|
||||
except Exception:
|
||||
pass
|
||||
on_line(
|
||||
f"[扫描] 已设为当前设备: {target}(已记住,下次 GUI 启动会自动重连)"
|
||||
)
|
||||
pick_dlg.destroy()
|
||||
|
||||
ttk.Button(bottom, text="使用选中", command=use_selected).pack(side=LEFT)
|
||||
ttk.Button(bottom, text="关闭", command=pick_dlg.destroy).pack(side=RIGHT)
|
||||
@@ -0,0 +1,165 @@
|
||||
"""启动时尝试自动重连上次记住的 WiFi ADB 设备。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内的闭包 ``_try_reconnect_last_wifi``,
|
||||
通过 ``root.after(300, ...)`` 在 GUI 创建完成后异步触发。
|
||||
|
||||
依赖通过显式参数注入:
|
||||
- ``root`` - 主窗口(用于线程间 ``after``)
|
||||
- ``adb_exe`` - ADB 可执行路径
|
||||
- ``device_var`` - 主窗口设备 StringVar(命中后写入)
|
||||
- ``on_line`` - 日志回调
|
||||
- ``refresh_devices`` - 刷新主窗口设备下拉的回调
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from typing import Callable
|
||||
|
||||
from gui.gui_core import list_adb_devices
|
||||
from gui.gui_core_pkg import (
|
||||
discover_adb_devices,
|
||||
get_last_wifi_target,
|
||||
pick_best_match,
|
||||
set_last_wifi_target,
|
||||
)
|
||||
from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target
|
||||
|
||||
|
||||
def try_reconnect_last_wifi(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
adb_exe: str,
|
||||
device_var: tk.StringVar,
|
||||
on_line: Callable[[str], None],
|
||||
refresh_devices: Callable[[], None],
|
||||
) -> None:
|
||||
"""启动时若 adb devices 为空且配置里有 last_wifi_target,后台尝试重连。
|
||||
|
||||
策略:
|
||||
1. 已经有可用设备:不打扰
|
||||
2. 上次记录的 target 现在 verify_adb_target 成功 → 选中
|
||||
3. verify 失败 → 自动扫描子网 + pick_best_match 智能匹配
|
||||
4. 匹配上 → 选中,更新 last_wifi_target;匹配不上 → 日志提示
|
||||
"""
|
||||
last = {}
|
||||
try:
|
||||
last = get_last_wifi_target()
|
||||
except Exception:
|
||||
return
|
||||
if not isinstance(last, dict) or not last.get("target"):
|
||||
return
|
||||
|
||||
target = str(last.get("target"))
|
||||
model = str(last.get("model") or "")
|
||||
|
||||
# 已经有设备时不打扰
|
||||
try:
|
||||
existing = list_adb_devices(adb_exe)
|
||||
except Exception:
|
||||
existing = []
|
||||
if target in existing:
|
||||
device_var.set(target)
|
||||
on_line(f"[启动] WiFi 设备已在线: {target}" + (f" ({model})" if model else ""))
|
||||
return
|
||||
if existing:
|
||||
on_line(
|
||||
f"[启动] 当前已有设备 {existing[0]},上次 WiFi 目标 {target} 不抢占"
|
||||
)
|
||||
return
|
||||
|
||||
on_line(f"[启动] 尝试重连上次的 WiFi 设备: {target} ...")
|
||||
|
||||
def worker():
|
||||
# 先直连
|
||||
state, msg = "failed", ""
|
||||
try:
|
||||
state, msg = verify_adb_target(adb_exe, target)
|
||||
except Exception as e:
|
||||
msg = str(e)
|
||||
|
||||
if state == "connected":
|
||||
def render_ok():
|
||||
refresh_devices()
|
||||
device_var.set(target)
|
||||
on_line(
|
||||
f"[启动] 自动重连成功: {target}"
|
||||
+ (f" ({model})" if model else "")
|
||||
)
|
||||
root.after(0, render_ok)
|
||||
return
|
||||
|
||||
if state == "unauthorized":
|
||||
def render_unauth():
|
||||
on_line(
|
||||
f"[启动] 上次设备 {target} 未授权,请在手机上确认 ADB 调试"
|
||||
)
|
||||
root.after(0, render_unauth)
|
||||
return
|
||||
|
||||
# state == "failed" → 不可达。换网了?自动扫一下,看能不能在新网段找到
|
||||
def notify_scan_start():
|
||||
on_line(
|
||||
f"[启动] {target} 不可达,自动扫描局域网寻找匹配设备..."
|
||||
)
|
||||
root.after(0, notify_scan_start)
|
||||
|
||||
try:
|
||||
# 如果上次记的端口非 5555,扫描时把它一起带上(覆盖 Android 11+ 随机端口)
|
||||
last_port_int = 5555
|
||||
if ":" in target:
|
||||
try:
|
||||
last_port_int = int(target.rsplit(":", 1)[1])
|
||||
except ValueError:
|
||||
pass
|
||||
scan_ports = [5555] if last_port_int == 5555 else [5555, last_port_int]
|
||||
devs = discover_adb_devices(adb_exe, ports=scan_ports)
|
||||
except Exception as e:
|
||||
def render_scan_err():
|
||||
on_line(f"[启动] 自动扫描失败: {e}")
|
||||
root.after(0, render_scan_err)
|
||||
return
|
||||
|
||||
best = pick_best_match(devs, last)
|
||||
|
||||
def render_scan_done():
|
||||
if best is None:
|
||||
if devs:
|
||||
targets_str = ", ".join(
|
||||
f"{d.target}({d.adb_state})" for d in devs[:5]
|
||||
)
|
||||
on_line(
|
||||
f"[启动] 扫描发现 {len(devs)} 台候选但无明确匹配: "
|
||||
f"{targets_str}。请点'扫描 WiFi'手选"
|
||||
)
|
||||
else:
|
||||
on_line(
|
||||
f"[启动] 上次设备 {target} 不可达,扫描也未发现其它设备。"
|
||||
f"请检查手机和电脑是否在同一 WiFi"
|
||||
)
|
||||
return
|
||||
|
||||
refresh_devices()
|
||||
device_var.set(best.target)
|
||||
# 更新记忆
|
||||
try:
|
||||
set_last_wifi_target(best.target, best.model or model)
|
||||
except Exception:
|
||||
pass
|
||||
if best.target == target:
|
||||
on_line(
|
||||
f"[启动] 自动重连成功(扫描确认): {best.target}"
|
||||
+ (f" ({best.model})" if best.model else "")
|
||||
)
|
||||
else:
|
||||
on_line(
|
||||
f"[启动] 上次目标 {target} 已变 → 智能匹配到 {best.target}"
|
||||
+ (f" ({best.model})" if best.model else "")
|
||||
+ "(已更新记忆)"
|
||||
)
|
||||
|
||||
root.after(0, render_scan_done)
|
||||
|
||||
threading.Thread(target=worker, daemon=True).start()
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
"""WiFi ADB 局域网扫描对话框。
|
||||
|
||||
从 ``gui/gui_app.py`` 中抽出。原本是 ``main()`` 内的闭包 ``open_scan_dialog``,
|
||||
其签名已经是显式参数形式,所以迁移到模块顶层只需要把 import 提上来即可。
|
||||
|
||||
被 ``open_wifi_adb_dialog`` 通过 "扫描局域网" 按钮调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, LEFT, RIGHT, W, X
|
||||
from typing import Callable
|
||||
|
||||
from gui.gui_core_pkg import (
|
||||
discover_adb_devices,
|
||||
get_local_subnet,
|
||||
parse_port_spec,
|
||||
)
|
||||
|
||||
|
||||
def open_scan_dialog(
|
||||
parent: tk.Misc,
|
||||
adb_exe_local: str,
|
||||
ip_var: tk.StringVar,
|
||||
on_line_local: Callable[[str], None],
|
||||
refresh_cb: Callable[[], None],
|
||||
) -> None:
|
||||
"""打开"扫描局域网"对话框:自动推子网或手动输入 → 后台扫描 → 列表展示。"""
|
||||
scan_dlg = tk.Toplevel(parent)
|
||||
scan_dlg.title("扫描局域网 ADB 设备")
|
||||
scan_dlg.geometry("640x440")
|
||||
scan_dlg.minsize(520, 360)
|
||||
scan_dlg.transient(parent)
|
||||
|
||||
# 顶部:子网输入 + 自动推按钮 + 开始扫描
|
||||
top_frame = ttk.LabelFrame(scan_dlg, text="扫描范围", padding=10)
|
||||
top_frame.pack(fill=X, padx=10, pady=10)
|
||||
|
||||
ttk.Label(top_frame, text="子网/范围:").grid(row=0, column=0, sticky=W)
|
||||
subnet_var = tk.StringVar(value=get_local_subnet() or "")
|
||||
subnet_entry = ttk.Entry(top_frame, textvariable=subnet_var, width=32)
|
||||
subnet_entry.grid(row=0, column=1, padx=(6, 6), sticky="we")
|
||||
top_frame.grid_columnconfigure(1, weight=1)
|
||||
|
||||
def auto_fill():
|
||||
sub = get_local_subnet()
|
||||
if sub:
|
||||
subnet_var.set(sub)
|
||||
on_line_local(f"[扫描] 自动推导子网: {sub}")
|
||||
else:
|
||||
on_line_local("[扫描] 无法推导本机子网,请手动输入")
|
||||
|
||||
ttk.Button(top_frame, text="自动推", command=auto_fill).grid(
|
||||
row=0, column=2, padx=(0, 6)
|
||||
)
|
||||
scan_btn = ttk.Button(top_frame, text="开始扫描")
|
||||
scan_btn.grid(row=0, column=3)
|
||||
|
||||
# 第二行:端口规格
|
||||
ttk.Label(top_frame, text="端口:").grid(row=1, column=0, sticky=W, pady=(6, 0))
|
||||
scan_port_var = tk.StringVar(value="5555")
|
||||
ttk.Entry(top_frame, textvariable=scan_port_var, width=32).grid(
|
||||
row=1, column=1, columnspan=3, padx=(6, 0), pady=(6, 0), sticky="we"
|
||||
)
|
||||
|
||||
ttk.Label(
|
||||
top_frame,
|
||||
text="子网示例: 192.168.5.0/24 | 192.168.5.1-100 | 192.168.5.5",
|
||||
font=("Arial", 8),
|
||||
foreground="gray",
|
||||
).grid(row=2, column=0, columnspan=4, sticky=W, pady=(4, 0))
|
||||
ttk.Label(
|
||||
top_frame,
|
||||
text="端口示例: 5555 | 5555,5556 | 37000-40000 (Android 11+ 无线调试随机端口在 37000-44999)",
|
||||
font=("Arial", 8),
|
||||
foreground="gray",
|
||||
).grid(row=3, column=0, columnspan=4, sticky=W, pady=(2, 0))
|
||||
|
||||
# 中间:进度条 + 状态
|
||||
progress_frame = ttk.Frame(scan_dlg)
|
||||
progress_frame.pack(fill=X, padx=10)
|
||||
progress_var = tk.DoubleVar(value=0.0)
|
||||
progress_bar = ttk.Progressbar(
|
||||
progress_frame, mode="determinate", variable=progress_var, maximum=100
|
||||
)
|
||||
progress_bar.pack(fill=X, pady=(0, 4))
|
||||
status_var = tk.StringVar(value="待扫描")
|
||||
ttk.Label(progress_frame, textvariable=status_var, font=("Arial", 9)).pack(
|
||||
anchor=W
|
||||
)
|
||||
|
||||
# 列表:IP / 状态 / 型号 / 备注
|
||||
list_frame = ttk.LabelFrame(scan_dlg, text="发现的设备", padding=10)
|
||||
list_frame.pack(fill=BOTH, expand=True, padx=10, pady=(8, 0))
|
||||
|
||||
cols = ("target", "state", "model", "message")
|
||||
tree = ttk.Treeview(
|
||||
list_frame, columns=cols, show="headings", height=8
|
||||
)
|
||||
tree.heading("target", text="IP:Port")
|
||||
tree.heading("state", text="状态")
|
||||
tree.heading("model", text="设备型号")
|
||||
tree.heading("message", text="adb connect 输出")
|
||||
tree.column("target", width=140, anchor=W)
|
||||
tree.column("state", width=80, anchor=W)
|
||||
tree.column("model", width=100, anchor=W)
|
||||
tree.column("message", width=240, anchor=W)
|
||||
tree.pack(side=LEFT, fill=BOTH, expand=True)
|
||||
sb = ttk.Scrollbar(list_frame, orient="vertical", command=tree.yview)
|
||||
sb.pack(side=LEFT, fill="y")
|
||||
tree.configure(yscrollcommand=sb.set)
|
||||
|
||||
# 底部按钮
|
||||
bottom_frame = ttk.Frame(scan_dlg)
|
||||
bottom_frame.pack(fill=X, padx=10, pady=10)
|
||||
|
||||
def use_selected():
|
||||
sel = tree.selection()
|
||||
if not sel:
|
||||
on_line_local("[扫描] 请先在列表中选中一个设备")
|
||||
return
|
||||
item = tree.item(sel[0])
|
||||
target = item["values"][0]
|
||||
state = item["values"][1]
|
||||
if state == "unauthorized":
|
||||
on_line_local(
|
||||
f"[扫描] {target} 未授权,请先在手机上确认 ADB 调试授权再选"
|
||||
)
|
||||
return
|
||||
# 把 IP 部分填回主对话框
|
||||
ip_part = str(target).split(":")[0]
|
||||
ip_var.set(ip_part)
|
||||
on_line_local(f"[扫描] 已选中 {target},可在主对话框点'连接'或它已在 adb devices 中")
|
||||
try:
|
||||
refresh_cb()
|
||||
except Exception:
|
||||
pass
|
||||
scan_dlg.destroy()
|
||||
|
||||
use_btn = ttk.Button(
|
||||
bottom_frame, text="使用选中设备", command=use_selected, state="disabled"
|
||||
)
|
||||
use_btn.pack(side=LEFT)
|
||||
ttk.Button(bottom_frame, text="关闭", command=scan_dlg.destroy).pack(
|
||||
side=RIGHT
|
||||
)
|
||||
|
||||
def on_select(_event=None):
|
||||
sel = tree.selection()
|
||||
use_btn.config(state="normal" if sel else "disabled")
|
||||
|
||||
tree.bind("<<TreeviewSelect>>", on_select)
|
||||
|
||||
# 扫描线程
|
||||
scanning = {"flag": False}
|
||||
|
||||
def do_scan():
|
||||
if scanning["flag"]:
|
||||
on_line_local("[扫描] 上次扫描尚未完成,请稍候")
|
||||
return
|
||||
spec = subnet_var.get().strip()
|
||||
if not spec:
|
||||
on_line_local("[扫描] 请输入子网/IP 范围")
|
||||
return
|
||||
scanning["flag"] = True
|
||||
scan_btn.config(state="disabled")
|
||||
tree.delete(*tree.get_children())
|
||||
progress_var.set(0)
|
||||
|
||||
def on_progress(done, total):
|
||||
try:
|
||||
pct = (done * 100.0) / max(total, 1)
|
||||
progress_var.set(pct)
|
||||
status_var.set(f"端口扫描 {done}/{total}")
|
||||
scan_dlg.update_idletasks()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def on_phase(text):
|
||||
try:
|
||||
status_var.set(text)
|
||||
scan_dlg.update_idletasks()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def worker():
|
||||
try:
|
||||
port_list = parse_port_spec(scan_port_var.get().strip())
|
||||
devs = discover_adb_devices(
|
||||
adb_exe_local,
|
||||
subnet_spec=spec,
|
||||
ports=port_list,
|
||||
on_progress=on_progress,
|
||||
on_phase=on_phase,
|
||||
)
|
||||
except Exception as e:
|
||||
on_line_local(f"[扫描] 异常: {e}")
|
||||
devs = []
|
||||
|
||||
# 回主线程更新 UI
|
||||
def render():
|
||||
for d in devs:
|
||||
tree.insert(
|
||||
"",
|
||||
"end",
|
||||
values=(d.target, d.adb_state, d.model, d.message[:120]),
|
||||
)
|
||||
if devs:
|
||||
status_var.set(f"扫描完成,发现 {len(devs)} 台设备")
|
||||
on_line_local(
|
||||
f"[扫描] 完成:{len(devs)} 台候选 — "
|
||||
+ ", ".join(f"{d.target}({d.adb_state})" for d in devs[:5])
|
||||
)
|
||||
else:
|
||||
status_var.set("扫描完成,未发现设备")
|
||||
on_line_local("[扫描] 未发现开放 5555 的设备")
|
||||
progress_var.set(100)
|
||||
scan_btn.config(state="normal")
|
||||
scanning["flag"] = False
|
||||
|
||||
try:
|
||||
scan_dlg.after(0, render)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
threading.Thread(target=worker, daemon=True).start()
|
||||
|
||||
scan_btn.config(command=do_scan)
|
||||
@@ -0,0 +1,147 @@
|
||||
"""中奖记录 Tab 的 widget 创建段。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。包括:
|
||||
- 截图列表 / 预览的左右两栏布局
|
||||
- 操作按钮(刷新列表 / 打开目录 / 实时查看)
|
||||
- 误识别记录管理(刷新/保存)
|
||||
|
||||
依赖通过显式参数注入。返回 ``WinRecordTabHandles`` 让 ``main()`` 后续仍能调度
|
||||
``refresh_win_record`` 与 ``load_false_positives``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, LEFT, RIGHT, X, Y
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from gui.components.win_record_view import (
|
||||
WinRecordView,
|
||||
refresh_win_record as _refresh_win_record_impl,
|
||||
on_win_list_select as _on_win_list_select_impl,
|
||||
open_win_folder as _open_win_folder_impl,
|
||||
load_false_positives as _load_false_positives_impl,
|
||||
save_false_positives as _save_false_positives_impl,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class WinRecordTabHandles:
|
||||
"""``main()`` 后续仍要用的 handles。"""
|
||||
|
||||
refresh_win_record: Callable[[], None]
|
||||
load_false_positives: Callable[[], None]
|
||||
|
||||
|
||||
def setup_win_record_tab(
|
||||
win_record_tab: tk.Misc,
|
||||
*,
|
||||
on_line: Callable[[str], None],
|
||||
ScrolledText_cls: Any,
|
||||
open_realtime_viewer: Callable[[], None],
|
||||
) -> WinRecordTabHandles:
|
||||
"""构建中奖记录 Tab 的 UI 与回调绑定。"""
|
||||
# 中奖记录显示
|
||||
win_record_top = ttk.Frame(win_record_tab)
|
||||
win_record_top.pack(fill=X, padx=10, pady=(10, 0))
|
||||
|
||||
win_record_left = ttk.Frame(win_record_tab)
|
||||
win_record_left.pack(side=LEFT, fill=BOTH, expand=True, padx=(10, 5), pady=10)
|
||||
|
||||
win_record_right = ttk.Frame(win_record_tab)
|
||||
win_record_right.pack(
|
||||
side=RIGHT, fill=BOTH, expand=False, padx=(5, 10), pady=10, ipadx=10
|
||||
)
|
||||
|
||||
# 左侧:中奖截图列表
|
||||
win_list_label = ttk.Label(win_record_left, text="中奖截图列表:")
|
||||
win_list_label.pack(anchor="w", padx=(0, 10), pady=(0, 5))
|
||||
|
||||
win_list_frame = ttk.Frame(win_record_left)
|
||||
win_list_frame.pack(fill=BOTH, expand=True)
|
||||
|
||||
win_list_scrollbar = ttk.Scrollbar(win_list_frame)
|
||||
win_list_scrollbar.pack(side=RIGHT, fill=Y)
|
||||
|
||||
win_listbox = tk.Listbox(
|
||||
win_list_frame, yscrollcommand=win_list_scrollbar.set, font=("Consolas", 9)
|
||||
)
|
||||
win_listbox.pack(side=LEFT, fill=BOTH, expand=True)
|
||||
win_list_scrollbar.config(command=win_listbox.yview)
|
||||
|
||||
# 存储文件路径映射(索引 -> 文件路径)
|
||||
_win_file_paths: Dict[int, str] = {}
|
||||
|
||||
# 右侧:截图预览
|
||||
win_preview_label = ttk.Label(win_record_right, text="截图预览:")
|
||||
win_preview_label.pack(anchor="w", pady=(0, 5))
|
||||
|
||||
win_preview_frame = ttk.Frame(win_record_right)
|
||||
win_preview_frame.pack(fill=BOTH, expand=True)
|
||||
|
||||
win_image_label = ttk.Label(win_preview_frame)
|
||||
win_image_label.pack(fill=BOTH, expand=True)
|
||||
_win_img_ref: Dict[str, Any] = {"photo": None}
|
||||
|
||||
# 误识别记录管理
|
||||
false_positive_frame = ttk.LabelFrame(win_record_right, text="误识别记录管理")
|
||||
false_positive_frame.pack(fill=X, pady=(10, 0))
|
||||
|
||||
false_positive_text = ScrolledText_cls(false_positive_frame, height=6)
|
||||
false_positive_text.pack(fill=X, padx=10, pady=10)
|
||||
|
||||
view = WinRecordView(
|
||||
listbox=win_listbox,
|
||||
image_label=win_image_label,
|
||||
preview_frame=win_preview_frame,
|
||||
false_positive_text=false_positive_text,
|
||||
on_line=on_line,
|
||||
file_paths=_win_file_paths,
|
||||
img_ref=_win_img_ref,
|
||||
)
|
||||
|
||||
def refresh_win_record() -> None:
|
||||
_refresh_win_record_impl(view)
|
||||
|
||||
def on_win_list_select(event):
|
||||
_on_win_list_select_impl(view, event)
|
||||
|
||||
win_listbox.bind("<<ListboxSelect>>", on_win_list_select)
|
||||
|
||||
ttk.Button(win_record_top, text="刷新列表", command=refresh_win_record).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
|
||||
def open_win_folder() -> None:
|
||||
_open_win_folder_impl(view)
|
||||
|
||||
ttk.Button(win_record_top, text="打开目录", command=open_win_folder).pack(side=LEFT)
|
||||
ttk.Button(
|
||||
win_record_top,
|
||||
text="实时查看",
|
||||
command=open_realtime_viewer,
|
||||
).pack(side=LEFT, padx=(8, 0))
|
||||
|
||||
def load_false_positives() -> None:
|
||||
_load_false_positives_impl(view)
|
||||
|
||||
def save_false_positives() -> None:
|
||||
_save_false_positives_impl(view)
|
||||
|
||||
false_positive_btn_frame = ttk.Frame(false_positive_frame)
|
||||
false_positive_btn_frame.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Button(
|
||||
false_positive_btn_frame, text="刷新", command=load_false_positives
|
||||
).pack(side=LEFT, padx=(0, 5))
|
||||
ttk.Button(
|
||||
false_positive_btn_frame, text="保存", command=save_false_positives
|
||||
).pack(side=LEFT)
|
||||
|
||||
load_false_positives()
|
||||
|
||||
return WinRecordTabHandles(
|
||||
refresh_win_record=refresh_win_record,
|
||||
load_false_positives=load_false_positives,
|
||||
)
|
||||
@@ -0,0 +1,205 @@
|
||||
"""中奖记录 Tab 视图相关:截图列表、预览、误识别记录管理。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内一组互相调用的闭包,
|
||||
共享 ``_win_file_paths`` / ``_win_img_ref`` / 多个 widgets。
|
||||
|
||||
抽出后通过 ``WinRecordView`` 容器把状态聚一起,7 个动作函数接收容器作为参数。
|
||||
``gui_app.py`` 在创建好 widgets 后调用 ``install_win_record_view`` 绑定按钮和
|
||||
回调,并拿到 ``refresh`` / ``load_false_positives`` 两个函数用于 ``after`` 调度。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tkinter as tk
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from tkinter import ttk
|
||||
from typing import Any, Callable, Dict
|
||||
|
||||
from PIL import Image, ImageTk # type: ignore[import]
|
||||
|
||||
|
||||
@dataclass
|
||||
class WinRecordView:
|
||||
"""中奖记录 Tab 的 widgets + 状态容器。"""
|
||||
|
||||
listbox: tk.Listbox
|
||||
image_label: ttk.Label
|
||||
preview_frame: tk.Misc
|
||||
false_positive_text: tk.Text
|
||||
on_line: Callable[[str], None]
|
||||
file_paths: Dict[int, str] = field(default_factory=dict)
|
||||
img_ref: Dict[str, Any] = field(default_factory=lambda: {"photo": None})
|
||||
|
||||
|
||||
def _get_pic_dir() -> str:
|
||||
try:
|
||||
from douyin.core.path_config import get_pic_dir
|
||||
|
||||
return get_pic_dir()
|
||||
except Exception:
|
||||
from douyin.core import path_config
|
||||
|
||||
return path_config.get_pic_dir()
|
||||
|
||||
|
||||
def scan_win_images() -> list:
|
||||
"""扫描中奖截图目录,返回 ``[(filename, abs_path, mtime), ...]`` 按时间倒序。"""
|
||||
pic_dir = _get_pic_dir()
|
||||
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
||||
win_images: list = []
|
||||
|
||||
if os.path.exists(prize_dir):
|
||||
for file in os.listdir(prize_dir):
|
||||
if file.lower().endswith((".png", ".jpg", ".jpeg")):
|
||||
file_path = os.path.join(prize_dir, file)
|
||||
# 获取文件修改时间
|
||||
try:
|
||||
mtime = os.path.getmtime(file_path)
|
||||
win_images.append((file, file_path, mtime))
|
||||
except Exception:
|
||||
win_images.append((file, file_path, 0))
|
||||
|
||||
# 按时间倒序排序(最新的在前)
|
||||
win_images.sort(key=lambda x: x[2], reverse=True)
|
||||
return win_images
|
||||
|
||||
|
||||
def refresh_win_record(view: WinRecordView) -> None:
|
||||
"""刷新中奖记录列表"""
|
||||
try:
|
||||
win_images = scan_win_images()
|
||||
view.listbox.delete(0, tk.END)
|
||||
view.file_paths.clear()
|
||||
|
||||
for idx, (file, file_path, mtime) in enumerate(win_images):
|
||||
# 格式化显示:文件名 + 时间
|
||||
try:
|
||||
dt = datetime.fromtimestamp(mtime)
|
||||
time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
display_text = f"{file} ({time_str})"
|
||||
except Exception:
|
||||
display_text = file
|
||||
|
||||
view.listbox.insert(tk.END, display_text)
|
||||
# 存储文件路径映射
|
||||
view.file_paths[idx] = file_path
|
||||
|
||||
if win_images:
|
||||
view.on_line(f"[中奖记录] 扫描到 {len(win_images)} 张中奖截图")
|
||||
else:
|
||||
view.on_line("[中奖记录] 暂无中奖截图")
|
||||
except Exception as e:
|
||||
view.on_line(f"[中奖记录] 刷新失败:{e}")
|
||||
|
||||
|
||||
def _load_win_image(view: WinRecordView, img_path: str) -> None:
|
||||
"""加载并显示中奖截图"""
|
||||
if not os.path.exists(img_path):
|
||||
view.image_label.configure(image="")
|
||||
view.img_ref["photo"] = None
|
||||
return
|
||||
|
||||
try:
|
||||
img = Image.open(img_path)
|
||||
img.load()
|
||||
img = img.convert("RGB")
|
||||
except Exception as e:
|
||||
view.on_line(f"[中奖记录] 图片加载失败:{e}")
|
||||
return
|
||||
|
||||
# 获取预览区域尺寸
|
||||
try:
|
||||
view.preview_frame.update_idletasks()
|
||||
w = view.preview_frame.winfo_width()
|
||||
h = view.preview_frame.winfo_height()
|
||||
if w <= 1 or h <= 1:
|
||||
w, h = 400, 600
|
||||
except Exception:
|
||||
w, h = 400, 600
|
||||
|
||||
max_w = max(200, w - 20)
|
||||
max_h = max(300, h - 20)
|
||||
|
||||
try:
|
||||
resample = Image.Resampling.LANCZOS
|
||||
except AttributeError:
|
||||
resample = 1
|
||||
|
||||
img.thumbnail((max_w, max_h), resample)
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
view.img_ref["photo"] = photo
|
||||
view.image_label.configure(image=photo)
|
||||
|
||||
|
||||
def on_win_list_select(view: WinRecordView, _event=None) -> None:
|
||||
"""当选择中奖截图时,显示预览"""
|
||||
try:
|
||||
selection = view.listbox.curselection()
|
||||
if not selection:
|
||||
return
|
||||
|
||||
index = selection[0]
|
||||
# 从映射中获取文件路径
|
||||
if index in view.file_paths:
|
||||
file_path = view.file_paths[index]
|
||||
_load_win_image(view, file_path)
|
||||
except Exception as e:
|
||||
view.on_line(f"[中奖记录] 预览失败:{e}")
|
||||
|
||||
|
||||
def open_win_folder(view: WinRecordView) -> None:
|
||||
"""打开中奖截图目录"""
|
||||
pic_dir = _get_pic_dir()
|
||||
prize_dir = os.path.join(pic_dir, "lottery_prize_captures")
|
||||
os.makedirs(prize_dir, exist_ok=True)
|
||||
try:
|
||||
os.startfile(prize_dir) # type: ignore[attr-defined]
|
||||
except Exception as e:
|
||||
view.on_line(f"[中奖记录] 打开目录失败:{e}")
|
||||
|
||||
|
||||
def load_false_positives(view: WinRecordView) -> None:
|
||||
"""加载误识别记录"""
|
||||
pic_dir = _get_pic_dir()
|
||||
false_positive_file = os.path.join(
|
||||
pic_dir, "lottery_prize_captures", "false_positives.json"
|
||||
)
|
||||
if not os.path.exists(false_positive_file):
|
||||
view.false_positive_text.delete("1.0", "end")
|
||||
view.false_positive_text.insert("1.0", "暂无误识别记录")
|
||||
return
|
||||
|
||||
try:
|
||||
with open(false_positive_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
false_positives = data.get("false_positives", [])
|
||||
view.false_positive_text.delete("1.0", "end")
|
||||
if false_positives:
|
||||
view.false_positive_text.insert("1.0", "\n".join(false_positives))
|
||||
else:
|
||||
view.false_positive_text.insert("1.0", "暂无误识别记录")
|
||||
except Exception as e:
|
||||
view.false_positive_text.delete("1.0", "end")
|
||||
view.false_positive_text.insert("1.0", f"加载失败:{e}")
|
||||
|
||||
|
||||
def save_false_positives(view: WinRecordView) -> None:
|
||||
"""保存误识别记录"""
|
||||
pic_dir = _get_pic_dir()
|
||||
false_positive_file = os.path.join(
|
||||
pic_dir, "lottery_prize_captures", "false_positives.json"
|
||||
)
|
||||
os.makedirs(os.path.dirname(false_positive_file), exist_ok=True)
|
||||
|
||||
content = view.false_positive_text.get("1.0", "end-1c")
|
||||
lines = [line.strip() for line in content.splitlines() if line.strip()]
|
||||
|
||||
try:
|
||||
with open(false_positive_file, "w", encoding="utf-8") as f:
|
||||
json.dump({"false_positives": lines}, f, ensure_ascii=False, indent=2)
|
||||
view.on_line(f"[中奖记录] 已保存 {len(lines)} 条误识别记录")
|
||||
except Exception as e:
|
||||
view.on_line(f"[中奖记录] 保存失败:{e}")
|
||||
@@ -0,0 +1,174 @@
|
||||
"""养号设置 Tab UI 创建逻辑(16 个 var)。
|
||||
|
||||
从 ``gui/gui_app.py`` 抽出。原本是 ``main()`` 内长 144 行的 widget 创建段。
|
||||
依赖通过显式参数注入:
|
||||
- ``parent`` - ``left_notebook`` (tab 父容器)
|
||||
- ``vars_`` - 名→Var 的 ``Dict[str, tk.Variable]``
|
||||
|
||||
返回 ``(yanghao_tab, yg_comment_texts, yg_like_keywords_text, yg_fav_keywords_text)``,
|
||||
后 3 个 widget 由 ``main()`` 收集到 ``_config_io_texts`` 用于 load/save 配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import BOTH, LEFT, X
|
||||
from typing import Dict, Tuple
|
||||
|
||||
try:
|
||||
from ttkbootstrap.scrolled import ScrolledText # type: ignore[import]
|
||||
except ImportError:
|
||||
from tkinter.scrolledtext import ScrolledText # type: ignore[no-redef]
|
||||
|
||||
|
||||
def setup_yanghao_tab(
|
||||
parent: ttk.Notebook,
|
||||
*,
|
||||
vars_: Dict[str, tk.Variable],
|
||||
) -> Tuple[ttk.Frame, tk.Text, tk.Text, tk.Text]:
|
||||
yanghao_tab = ttk.Frame(parent)
|
||||
parent.add(yanghao_tab, text="养号设置")
|
||||
|
||||
yg_box = ttk.LabelFrame(yanghao_tab, text="推荐页养号(爱心/收藏/评论)")
|
||||
yg_box.pack(fill=X, padx=10, pady=(10, 10))
|
||||
|
||||
yg_switch = ttk.Frame(yg_box)
|
||||
yg_switch.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(
|
||||
yg_switch, text="养号总开关(关闭则跳过推荐页养号)", variable=vars_["yg_enabled_var"]
|
||||
).pack(side=LEFT)
|
||||
ttk.Checkbutton(
|
||||
yg_switch,
|
||||
text="启用养号动作(爱心/收藏/评论)",
|
||||
variable=vars_["yg_actions_enabled_var"],
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Checkbutton(
|
||||
yg_switch,
|
||||
text="只养号(仅执行推荐页养号,跳过抽奖/参与)",
|
||||
variable=vars_["yg_only_var"],
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
|
||||
yg0 = ttk.Frame(yg_box)
|
||||
yg0.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Checkbutton(
|
||||
yg0,
|
||||
text="逐步截图(调试用,生成 pic/*/latest.png)",
|
||||
variable=vars_["yg_step_screenshot_var"],
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_time = ttk.Frame(yg_box)
|
||||
yg_time.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg_time, text="养号时长(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg_time,
|
||||
from_=1,
|
||||
to=3600,
|
||||
increment=5,
|
||||
textvariable=vars_["yg_recommend_duration_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_time, text="养号间隔(秒):").pack(side=LEFT, padx=(12, 0))
|
||||
ttk.Spinbox(
|
||||
yg_time,
|
||||
from_=0,
|
||||
to=3600,
|
||||
increment=10,
|
||||
textvariable=vars_["yg_recommend_interval_var"],
|
||||
width=8,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg_time, text="(0=每次触发都执行)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
yg1 = ttk.Frame(yg_box)
|
||||
yg1.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg1, text="爱心概率:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg1, from_=0.0, to=1.0, increment=0.05, textvariable=vars_["yg_like_prob_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="收藏概率:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg1, from_=0.0, to=1.0, increment=0.05, textvariable=vars_["yg_fav_prob_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="评论概率:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg1,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.05,
|
||||
textvariable=vars_["yg_comment_prob_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1, text="(0~1)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
yg1b = ttk.Frame(yg_box)
|
||||
yg1b.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg1b, text="检测动作后停留(秒):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg1b,
|
||||
from_=0.0,
|
||||
to=120.0,
|
||||
increment=1.0,
|
||||
textvariable=vars_["yg_dwell_on_action_min_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1b, text="~").pack(side=LEFT, padx=(6, 6))
|
||||
ttk.Spinbox(
|
||||
yg1b,
|
||||
from_=0.0,
|
||||
to=120.0,
|
||||
increment=1.0,
|
||||
textvariable=vars_["yg_dwell_on_action_max_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg1b, text="(随机范围)").pack(side=LEFT, padx=(6, 0))
|
||||
|
||||
yg2 = ttk.Frame(yg_box)
|
||||
yg2.pack(fill=X, padx=10, pady=(0, 8))
|
||||
ttk.Label(yg2, text="图标ROI大小(px):").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
yg2, from_=80, to=600, increment=10, textvariable=vars_["yg_icon_roi_size_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(yg2, text="匹配阈值:").pack(side=LEFT, padx=(10, 0))
|
||||
ttk.Spinbox(
|
||||
yg2,
|
||||
from_=0.0,
|
||||
to=1.0,
|
||||
increment=0.01,
|
||||
textvariable=vars_["yg_icon_match_threshold_var"],
|
||||
width=6,
|
||||
).pack(side=LEFT)
|
||||
|
||||
yg_texts = ttk.Frame(yg_box)
|
||||
yg_texts.pack(fill=BOTH, expand=True, padx=10, pady=(0, 10))
|
||||
ttk.Label(yg_texts, text="评论文案库(每行一条):").pack(anchor="w")
|
||||
yg_comment_texts = ScrolledText(yg_texts, height=4)
|
||||
yg_comment_texts.pack(fill=X, pady=(0, 6))
|
||||
yg_kw = ttk.Frame(yg_texts)
|
||||
yg_kw.pack(fill=BOTH, expand=True)
|
||||
ttk.Label(yg_kw, text="爱心关键词(每行一条):").pack(anchor="w")
|
||||
yg_like_keywords_text = ScrolledText(yg_kw, height=3)
|
||||
yg_like_keywords_text.pack(fill=X, pady=(0, 6))
|
||||
ttk.Label(yg_kw, text="收藏关键词(每行一条):").pack(anchor="w")
|
||||
yg_fav_keywords_text = ScrolledText(yg_kw, height=3)
|
||||
yg_fav_keywords_text.pack(fill=X)
|
||||
|
||||
quiet_box = ttk.LabelFrame(yanghao_tab, text="定时禁抢(仅养号)")
|
||||
quiet_box.pack(fill=X, padx=10, pady=(0, 10))
|
||||
quiet_r0 = ttk.Frame(quiet_box)
|
||||
quiet_r0.pack(fill=X, padx=10, pady=(10, 6))
|
||||
ttk.Checkbutton(
|
||||
quiet_r0, text="启用定时禁抢", variable=vars_["fudai_quiet_hours_enabled_var"]
|
||||
).pack(side=LEFT)
|
||||
quiet_r1 = ttk.Frame(quiet_box)
|
||||
quiet_r1.pack(fill=X, padx=10, pady=(0, 10))
|
||||
ttk.Label(quiet_r1, text="开始小时:").pack(side=LEFT)
|
||||
ttk.Spinbox(
|
||||
quiet_r1, from_=0, to=23, textvariable=vars_["fudai_quiet_start_hour_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
ttk.Label(quiet_r1, text="结束小时:").pack(side=LEFT, padx=(12, 0))
|
||||
ttk.Spinbox(
|
||||
quiet_r1, from_=0, to=23, textvariable=vars_["fudai_quiet_end_hour_var"], width=6
|
||||
).pack(side=LEFT)
|
||||
|
||||
# 标签页5:调试参数
|
||||
return yanghao_tab, yg_comment_texts, yg_like_keywords_text, yg_fav_keywords_text
|
||||
+95
-5417
File diff suppressed because it is too large.
Load diff
@@ -21,6 +21,12 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
GUI_APP = ROOT / "gui" / "gui_app.py"
|
||||
# load_config_to_ui / save_ui_to_config 已抽到 components/config_io.py,
|
||||
# 但 GUI 启动时仍通过 main() 内的薄包装调用它们。本工具的同步检查需要从
|
||||
# config_io.py 抽 cfg/cfg2 赋值,从 gui_app.py 抽 gui_cfg 引用(仍在 main 里)。
|
||||
GUI_CONFIG_IO = ROOT / "gui" / "components" / "config_io.py"
|
||||
# realtime_tab UI 抽到 components/realtime_tab.py 后,gui_cfg 引用也跟过去了。
|
||||
GUI_REALTIME_TAB = ROOT / "gui" / "components" / "realtime_tab.py"
|
||||
WEB_INDEX = ROOT / "webui" / "index.html"
|
||||
MANIFEST_PATH = ROOT / "tools" / "dev" / "web_gui_config_manifest.json"
|
||||
|
||||
@@ -101,10 +107,15 @@ def extract_web_keys(source: str) -> set[str]:
|
||||
|
||||
def build_manifest() -> dict[str, object]:
|
||||
gui_source = _read(GUI_APP)
|
||||
config_io_source = _read(GUI_CONFIG_IO)
|
||||
realtime_tab_source = _read(GUI_REALTIME_TAB)
|
||||
web_source = _read(WEB_INDEX)
|
||||
|
||||
gui_saved = extract_gui_saved_keys(gui_source)
|
||||
gui_loaded = extract_gui_loaded_keys(gui_source)
|
||||
# save/load 函数现在在 components/config_io.py 里;gui_cfg 引用在 realtime_tab.py
|
||||
gui_saved = extract_gui_saved_keys(config_io_source)
|
||||
gui_loaded = extract_gui_loaded_keys(
|
||||
config_io_source + "\n" + gui_source + "\n" + realtime_tab_source
|
||||
)
|
||||
web_keys = extract_web_keys(web_source)
|
||||
|
||||
expected_gui_keys = web_keys - GUI_RUNTIME_ONLY_KEYS
|
||||
|
||||
Reference in new issue
Block a user