Compare commits
121 Commits
22d3c3462c
...
v1.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
| e4d838a9d0 | |||
| 70f78c2a6f | |||
| e40e7767c7 | |||
| 1b6c170d6c | |||
| 30a7a8e996 | |||
| d59ecc3090 | |||
| 7685f6a616 | |||
| ed8dec70a6 | |||
| dfa9ae1a0c | |||
| 06740776a9 | |||
| c8f9ae752f | |||
| 89c1e33257 | |||
| 862f86827a | |||
| ed98623cda | |||
| ab51c72a11 | |||
| 2fe4584129 | |||
| 92c5fa0dfb | |||
| 05ad9ba0b3 | |||
| 0069d5274b | |||
| 6a9c662287 | |||
| d7fff16991 | |||
| db345f9efc | |||
| 133433f2d8 | |||
| 6f32923865 | |||
| a716e5b945 | |||
| 588718f9c5 | |||
| 0ba76babc6 | |||
| dc7e5d8cd8 | |||
| 818acd4efc | |||
| 308a1dfcf3 | |||
| c250fa4a6e | |||
| 8f8e3e4ba7 | |||
| 88a74a7a47 | |||
| 5552af1345 | |||
| 6d05d4c7cb | |||
| 01f4ccaa0e | |||
| f9175371dc | |||
| 8e1b28f3fe | |||
| 57f1cfb3f2 | |||
| 007b4dc2ef | |||
| 0bad34d7a8 | |||
| 61d1b44402 | |||
| 72301c63fd | |||
| 609850ab60 | |||
| 8e14d45b71 | |||
| f6ef9af39d | |||
| 72dce83c55 | |||
| 67f297b434 | |||
| 86f0761eed | |||
| 79e5b43498 | |||
| b56d2c203e | |||
| 44dbde3355 | |||
| 62f8ec3d91 | |||
| 2d77cbec79 | |||
| 10d731518a | |||
| 9fdb6f7652 | |||
| ef903ee817 | |||
| d6e8eef8c8 | |||
| e893752c25 | |||
| 1cfd7382be | |||
| 1d9e41ab86 | |||
| 645f07b4d2 | |||
| 732f104c5c | |||
| a2bc1881bc | |||
| c1004ed2bc | |||
| 38489191f5 | |||
| 35253dadbb | |||
| c0b6e0899c | |||
| 9c1772b186 | |||
| 05b93799d4 | |||
| c337904010 | |||
| 779aad13b8 | |||
| f3360423e5 | |||
| bea12d5f0c | |||
| b24f39456e | |||
| bb63ee6f03 | |||
| 3ebebe015f | |||
| 02b3a62868 | |||
| d7e19dcd52 | |||
| 59c06b3a19 | |||
| b78fd2d1e4 | |||
| 2aace40a26 | |||
| df7ad92f7f | |||
| 910e3e3224 | |||
| f7167c13f4 | |||
| eb8da498a2 | |||
| b279b51b42 | |||
| 43336f98d2 | |||
| e77c561685 | |||
| 345cb95b98 | |||
| caa563e770 | |||
| 280028259f | |||
| a6bc103c73 | |||
| 2226e8ac90 | |||
| 106463b9e5 | |||
| 5e898180c7 | |||
| a03ab38279 | |||
| 4761cade26 | |||
| 531b05651e | |||
| 3cea7df736 | |||
| a0fd03f12f | |||
| 9b47886e5b | |||
| 82738be99a | |||
| e097b5afc9 | |||
| fe7453fe02 | |||
| 1d4b03d162 | |||
| 4642916fd5 | |||
| 5800437ba2 | |||
| 23467c1d3d | |||
| b8c0a29c59 | |||
| 87787ad3dc | |||
| e800f6ece1 | |||
| 600a304ab8 | |||
| c038c8005d | |||
| 6cf182c8c8 | |||
| 33c0f4414c | |||
| 2843300cf9 | |||
| 9bdc9a3de9 | |||
| 500ddd41c5 | |||
| 14c6db3384 | |||
| bbd97970a6 |
@@ -7,7 +7,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
@@ -15,7 +14,6 @@ on:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
# Allow manual trigger for testing
|
||||
workflow_dispatch:
|
||||
|
||||
#
|
||||
@@ -49,11 +47,13 @@ jobs:
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirement.txt
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
@@ -125,7 +125,7 @@ jobs:
|
||||
" binaries=[],"
|
||||
" datas=["
|
||||
" ('models\\common.onnx', 'ddddocr'),"
|
||||
" ('src\\gui\\resources\\icons\\AutoLibrary_32x32.ico', 'gui\\resources\\icons'),"
|
||||
" ('src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico', 'gui\\resources\\icons'),"
|
||||
" ],"
|
||||
" hiddenimports=[],"
|
||||
" hookspath=[],"
|
||||
@@ -153,7 +153,7 @@ jobs:
|
||||
" target_arch=None,"
|
||||
" codesign_identity=None,"
|
||||
" entitlements_file=None,"
|
||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_32x32.ico'],"
|
||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico'],"
|
||||
")"
|
||||
""
|
||||
"coll = COLLECT("
|
||||
@@ -169,9 +169,11 @@ jobs:
|
||||
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
||||
|
||||
Write-Host "✓ Main.spec (non-single file) generated successfully"
|
||||
Write-Host "`nGenerated Main.spec ============"
|
||||
Write-Host "`n========================================"
|
||||
Write-Host "Generated Main.spec"
|
||||
Write-Host "========================================"
|
||||
Get-Content "Main.spec" | Write-Host
|
||||
Write-Host "==================================`n"
|
||||
Write-Host "========================================`n"
|
||||
shell: pwsh
|
||||
|
||||
- name: Build with PyInstaller
|
||||
@@ -186,7 +188,7 @@ jobs:
|
||||
$distDir = "dist/AutoLibrary-$version"
|
||||
$zipName = "AutoLibrary.$tagName-windows-x86_64.zip"
|
||||
|
||||
echo "ZIP_NAME=$zipName" >> $env:GITHUB_OUTPUT
|
||||
"ZIP_NAME=$zipName" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
|
||||
|
||||
Write-Host "Looking for distribution directory: $distDir"
|
||||
if (Test-Path $distDir) {
|
||||
@@ -210,12 +212,283 @@ jobs:
|
||||
|
||||
- name: Upload build summary
|
||||
run: |
|
||||
Write-Host "## Build Test Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||
Write-Host "" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "✓ Pull request build test completed successfully!" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Version: ${{ steps.get_version.outputs.VERSION }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Pull Request #${{ github.event.pull_request.number }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Branch: ${{ github.event.pull_request.head.ref }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Event: ${{ github.event_name }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"## Build Test Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||
"" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"========================================" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"✓ Pull request build test completed successfully!" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Version: ${{ steps.get_version.outputs.VERSION }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Pull Request #${{ github.event.pull_request.number || 'N/A' }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Branch: ${{ github.event.pull_request.head.ref || github.ref }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Event: ${{ github.event_name }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
shell: pwsh
|
||||
|
||||
#
|
||||
# Build macOS
|
||||
#
|
||||
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- name: Get version info
|
||||
id: get_version
|
||||
run: |
|
||||
version="pr-test"
|
||||
tag_name="pr-test"
|
||||
echo "✓ Mode: Pull Request Test Build"
|
||||
echo "✓ Tag: $tag_name"
|
||||
echo "✓ Version: $version"
|
||||
echo "VERSION=$version" >> $GITHUB_OUTPUT
|
||||
echo "TAG_NAME=$tag_name" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
ddddocr_path=$(python -c "import ddddocr, os; print(os.path.dirname(ddddocr.__file__))")
|
||||
echo "ddddocr package location: $ddddocr_path"
|
||||
|
||||
init_file="$ddddocr_path/__init__.py"
|
||||
if [ -f "$init_file" ]; then
|
||||
echo "Fixing ddddocr compatibility in: $init_file"
|
||||
# macOS 使用 BSD sed,要求 -i 后跟备份后缀名(空字符串 = 不备份)
|
||||
sed -i '' 's/Image\.ANTIALIAS/Image.Resampling.LANCZOS/g' "$init_file"
|
||||
echo "✓ Fixed: Image.ANTIALIAS -> Image.Resampling.LANCZOS"
|
||||
else
|
||||
echo "✗ ddddocr __init__.py not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p models
|
||||
echo "✓ Created models directory"
|
||||
|
||||
# 多路径 fallback 搜索 ONNX 模型,提升 ddddocr 版本兼容性
|
||||
onnx_source=""
|
||||
onnx_dest="models/common.onnx"
|
||||
candidate_paths=(
|
||||
"$ddddocr_path/common.onnx"
|
||||
"$ddddocr_path/models/common.onnx"
|
||||
"$ddddocr_path/ddddocr/common.onnx"
|
||||
)
|
||||
for candidate in "${candidate_paths[@]}"; do
|
||||
if [ -f "$candidate" ]; then
|
||||
onnx_source="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
# 若以上候选均未命中,回退到全包搜索
|
||||
if [ -z "$onnx_source" ]; then
|
||||
echo "⚠ 未在已知路径找到 ONNX 模型,回退到全包搜索..."
|
||||
onnx_source=$(find "$ddddocr_path" -name "*.onnx" -type f 2>/dev/null | head -1)
|
||||
fi
|
||||
|
||||
if [ -n "$onnx_source" ] && [ -f "$onnx_source" ]; then
|
||||
cp "$onnx_source" "$onnx_dest"
|
||||
echo "✓ ONNX model copied: $onnx_source -> $onnx_dest"
|
||||
else
|
||||
echo "✗ ONNX model not found in ddddocr package"
|
||||
echo " Searched directory: $ddddocr_path"
|
||||
ls -la "$ddddocr_path/" || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -f "$onnx_dest" ]; then
|
||||
file_size=$(du -h "$onnx_dest" | cut -f1)
|
||||
echo "✓ Model file verified: $onnx_dest (Size: $file_size)"
|
||||
else
|
||||
echo "✗ Failed to copy model file"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Compile Qt Resource files
|
||||
run: |
|
||||
cd batchs
|
||||
bash compile_rc.sh
|
||||
|
||||
- name: Compile Qt UI files
|
||||
run: |
|
||||
cd batchs
|
||||
bash compile_ui.sh
|
||||
|
||||
- name: Generate 'Main.spec'
|
||||
env:
|
||||
APP_VERSION: ${{ steps.get_version.outputs.VERSION }}
|
||||
run: |
|
||||
version="$APP_VERSION"
|
||||
exe_name="AutoLibrary-$version"
|
||||
echo "Generating Main.spec for version: $version"
|
||||
echo "App name: $exe_name"
|
||||
|
||||
printf '%s\n' \
|
||||
'# -*- mode: python ; coding: utf-8 -*-' \
|
||||
'' \
|
||||
'a = Analysis(' \
|
||||
" ['src/Main.py']," \
|
||||
' pathex=[],' \
|
||||
' binaries=[],' \
|
||||
' datas=[' \
|
||||
" ('models/common.onnx', 'ddddocr')," \
|
||||
" ('src/gui/resources/icons/AutoLibrary_Logo_64.ico', 'gui/resources/icons')," \
|
||||
' ],' \
|
||||
' hiddenimports=[],' \
|
||||
' hookspath=[],' \
|
||||
' hooksconfig={},' \
|
||||
' runtime_hooks=[],' \
|
||||
' excludes=[],' \
|
||||
' noarchive=False,' \
|
||||
' optimize=0,' \
|
||||
')' \
|
||||
'pyz = PYZ(a.pure)' \
|
||||
'' \
|
||||
'exe = EXE(' \
|
||||
' pyz,' \
|
||||
' a.scripts,' \
|
||||
' [],' \
|
||||
' exclude_binaries=True,' \
|
||||
" name='AutoLibrary'," \
|
||||
' debug=False,' \
|
||||
' bootloader_ignore_signals=False,' \
|
||||
' strip=False,' \
|
||||
' upx=True,' \
|
||||
' upx_exclude=[],' \
|
||||
' runtime_tmpdir=None,' \
|
||||
' console=False,' \
|
||||
' disable_windowed_traceback=False,' \
|
||||
' argv_emulation=False,' \
|
||||
' target_arch=None,' \
|
||||
' codesign_identity=None,' \
|
||||
' entitlements_file=None,' \
|
||||
" icon=['src/gui/resources/icons/AutoLibrary_Logo_64.ico']," \
|
||||
')' \
|
||||
'' \
|
||||
'coll = COLLECT(' \
|
||||
' exe,' \
|
||||
' a.binaries,' \
|
||||
' a.zipfiles,' \
|
||||
' a.datas,' \
|
||||
' strip=False,' \
|
||||
' upx=True,' \
|
||||
' upx_exclude=[],' \
|
||||
" name='${exe_name}'," \
|
||||
')' \
|
||||
'' \
|
||||
'app = BUNDLE(' \
|
||||
' coll,' \
|
||||
" name='AutoLibrary.app'," \
|
||||
" icon='src/gui/resources/icons/AutoLibrary_Logo.icns'," \
|
||||
" bundle_identifier='com.kenanzhu.autolibrary'," \
|
||||
' info_plist={' \
|
||||
" 'NSHighResolutionCapable': 'True'," \
|
||||
" 'CFBundleName': 'AutoLibrary'," \
|
||||
" 'CFBundleDisplayName': 'AutoLibrary'," \
|
||||
" 'CFBundleShortVersionString': '${version}'," \
|
||||
" 'CFBundleVersion': '${version}'," \
|
||||
" 'CFBundleExecutable': 'AutoLibrary'," \
|
||||
" 'NSPrincipalClass': 'NSApplication'," \
|
||||
" 'LSMinimumSystemVersion': '11.0'," \
|
||||
" 'NSRequiresAquaSystemAppearance': 'False'," \
|
||||
" 'NSHumanReadableCopyright': 'Copyright 2025 - 2026 KenanZhu. All rights reserved.'," \
|
||||
' },' \
|
||||
')' \
|
||||
> Main.spec
|
||||
|
||||
echo "✓ Main.spec generated successfully"
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "Generated Main.spec"
|
||||
echo "========================================"
|
||||
cat Main.spec
|
||||
echo "========================================"
|
||||
|
||||
- name: Build with PyInstaller
|
||||
run: |
|
||||
python -m PyInstaller Main.spec
|
||||
|
||||
- name: Create DMG
|
||||
run: |
|
||||
tag_name="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
dmg_name="AutoLibrary.$tag_name-macos-arm64.dmg"
|
||||
app_path="dist/AutoLibrary.app"
|
||||
|
||||
if [ ! -d "$app_path" ]; then
|
||||
echo "✗ App bundle not found: $app_path"
|
||||
echo "Files in dist directory:"
|
||||
ls -la dist/
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Creating DMG from: $app_path"
|
||||
xattr -cr "$app_path" 2>/dev/null || true
|
||||
|
||||
tmp_dmg_dir=$(mktemp -d)
|
||||
cp -R "$app_path" "$tmp_dmg_dir/"
|
||||
ln -s /Applications "$tmp_dmg_dir/Applications"
|
||||
|
||||
hdiutil create \
|
||||
-volname "AutoLibrary $tag_name" \
|
||||
-srcfolder "$tmp_dmg_dir" \
|
||||
-ov \
|
||||
-format UDZO \
|
||||
"$dmg_name"
|
||||
|
||||
rm -rf "$tmp_dmg_dir"
|
||||
|
||||
if [ -f "$dmg_name" ]; then
|
||||
dmg_size=$(du -h "$dmg_name" | cut -f1)
|
||||
echo "✓ DMG created: $dmg_name (Size: $dmg_size)"
|
||||
else
|
||||
echo "✗ Failed to create DMG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✓ Artifacts ready:"
|
||||
echo " - $dmg_name"
|
||||
echo " - $app_path"
|
||||
|
||||
- name: Archive artifacts
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-macos-arm64
|
||||
path: |
|
||||
AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-macos-arm64.dmg
|
||||
dist/AutoLibrary.app/**
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload build summary
|
||||
run: |
|
||||
tag_name="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
version="${{ steps.get_version.outputs.VERSION }}"
|
||||
dmg_name="AutoLibrary.$tag_name-macos-arm64.dmg"
|
||||
|
||||
{
|
||||
echo "## Build Test Summary (macOS)"
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "✓ Pull request build test completed successfully!"
|
||||
echo "- Version: $version"
|
||||
echo "- Tag: $tag_name"
|
||||
echo "- Pull Request #${{ github.event.pull_request.number || 'N/A' }}"
|
||||
echo "- Branch: ${{ github.event.pull_request.head.ref || github.ref }}"
|
||||
echo "- Event: ${{ github.event_name }}"
|
||||
echo "- DMG: $dmg_name"
|
||||
echo ""
|
||||
echo "### How to test on macOS"
|
||||
echo '1. Download the DMG artifact'
|
||||
echo '2. Open the DMG and drag AutoLibrary.app to /Applications'
|
||||
echo '3. Right-click → Open the app (to bypass Gatekeeper)'
|
||||
} >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
name: Build
|
||||
|
||||
# This workflow compiles the application for Windows platform using PyInstaller, and
|
||||
# archives the built artifacts as 'AutoLibrary.<tag_name>-windows-x86_64.zip'.
|
||||
# This workflow compiles the application for Windows and macOS platforms using
|
||||
# PyInstaller, and archives the built artifacts.
|
||||
#
|
||||
# - Windows: AutoLibrary.<tag_name>-windows-x86_64.zip
|
||||
# - macOS: AutoLibrary.<tag_name>-macos-arm64.dmg
|
||||
#
|
||||
# It is triggered when called by the release workflow.
|
||||
|
||||
@@ -76,20 +79,22 @@ jobs:
|
||||
run: |
|
||||
$versionInfoFile = "src/gui/ALVersionInfo.py"
|
||||
Write-Host "Verifying $versionInfoFile content:"
|
||||
Write-Host "=================================="
|
||||
Write-Host "========================================"
|
||||
Get-Content $versionInfoFile | Write-Host
|
||||
Write-Host "=================================="
|
||||
Write-Host "========================================"
|
||||
shell: pwsh
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirement.txt
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
@@ -161,7 +166,7 @@ jobs:
|
||||
" binaries=[],"
|
||||
" datas=["
|
||||
" ('models\\common.onnx', 'ddddocr'),"
|
||||
" ('src\\gui\\resources\\icons\\AutoLibrary_32x32.ico', 'gui\\resources\\icons'),"
|
||||
" ('src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico', 'gui\\resources\\icons'),"
|
||||
" ],"
|
||||
" hiddenimports=[],"
|
||||
" hookspath=[],"
|
||||
@@ -189,7 +194,7 @@ jobs:
|
||||
" target_arch=None,"
|
||||
" codesign_identity=None,"
|
||||
" entitlements_file=None,"
|
||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_32x32.ico'],"
|
||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico'],"
|
||||
")"
|
||||
""
|
||||
"coll = COLLECT("
|
||||
@@ -205,9 +210,11 @@ jobs:
|
||||
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
||||
|
||||
Write-Host "✓ Main.spec (non-single file) generated successfully"
|
||||
Write-Host "`nGenerated Main.spec ============"
|
||||
Write-Host "`n========================================"
|
||||
Write-Host "Generated Main.spec"
|
||||
Write-Host "========================================"
|
||||
Get-Content "Main.spec" | Write-Host
|
||||
Write-Host "==================================`n"
|
||||
Write-Host "========================================`n"
|
||||
shell: pwsh
|
||||
|
||||
- name: Build with PyInstaller
|
||||
@@ -222,7 +229,7 @@ jobs:
|
||||
$distDir = "dist/AutoLibrary-$version"
|
||||
$zipName = "AutoLibrary.$tagName-windows-x86_64.zip"
|
||||
|
||||
echo "ZIP_NAME=$zipName" >> $env:GITHUB_OUTPUT
|
||||
"ZIP_NAME=$zipName" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
|
||||
|
||||
Write-Host "Looking for distribution directory: $distDir"
|
||||
if (Test-Path $distDir) {
|
||||
@@ -242,16 +249,315 @@ jobs:
|
||||
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-windows-x86_64
|
||||
path: |
|
||||
${{ steps.zip_release.outputs.ZIP_NAME }}
|
||||
retention-days: ${{ github.event_name != 'workflow_call' && 7 || 90 }}
|
||||
retention-days: ${{ inputs.is_test == 'true' && 7 || 90 }}
|
||||
|
||||
- name: Upload build summary
|
||||
if: ${{ github.event_name != 'workflow_call' }}
|
||||
if: ${{ inputs.is_test == 'true' }}
|
||||
run: |
|
||||
Write-Host "## Build Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||
Write-Host "" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "✓ Build test completed successfully!" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Version: ${{ steps.get_version.outputs.VERSION }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Event: ${{ github.event_name }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Ref: ${{ github.ref }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"## Build Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||
"" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"========================================" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"✓ Build test completed successfully!" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Version: ${{ steps.get_version.outputs.VERSION }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Event: ${{ github.event_name }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Ref: ${{ github.ref }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
shell: pwsh
|
||||
|
||||
#
|
||||
# Build macOS
|
||||
#
|
||||
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- name: Download build version of ALVersionInfo.py
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: updated-version-info-for-build
|
||||
path: src/gui/
|
||||
|
||||
- name: Get version info
|
||||
id: get_version
|
||||
run: |
|
||||
is_test="${{ inputs.is_test }}"
|
||||
if [ "$is_test" = "true" ]; then
|
||||
version="test"
|
||||
tag_name="test"
|
||||
echo "✓ Mode: Test Build"
|
||||
else
|
||||
version="${{ inputs.version }}"
|
||||
tag_name="${{ inputs.tag_name }}"
|
||||
|
||||
if [ -z "$version" ]; then
|
||||
version="test"
|
||||
tag_name="test"
|
||||
echo "✓ Mode: Independent Build (No inputs provided)"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "✓ Tag: $tag_name"
|
||||
echo "✓ Version: $version"
|
||||
|
||||
echo "VERSION=$version" >> $GITHUB_OUTPUT
|
||||
echo "TAG_NAME=$tag_name" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Verify 'ALVersionInfo.py' was updated
|
||||
run: |
|
||||
version_info_file="src/gui/ALVersionInfo.py"
|
||||
echo "Verifying $version_info_file content:"
|
||||
echo "========================================"
|
||||
cat "$version_info_file"
|
||||
echo "========================================"
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
ddddocr_path=$(python -c "import ddddocr, os; print(os.path.dirname(ddddocr.__file__))")
|
||||
echo "ddddocr package location: $ddddocr_path"
|
||||
|
||||
init_file="$ddddocr_path/__init__.py"
|
||||
if [ -f "$init_file" ]; then
|
||||
echo "Fixing ddddocr compatibility in: $init_file"
|
||||
# macOS 使用 BSD sed,要求 -i 后跟备份后缀名(空字符串 = 不备份)
|
||||
sed -i '' 's/Image\.ANTIALIAS/Image.Resampling.LANCZOS/g' "$init_file"
|
||||
echo "✓ Fixed: Image.ANTIALIAS -> Image.Resampling.LANCZOS"
|
||||
else
|
||||
echo "✗ ddddocr __init__.py not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p models
|
||||
echo "✓ Created models directory"
|
||||
|
||||
# 多路径 fallback 搜索 ONNX 模型,提升 ddddocr 版本兼容性
|
||||
onnx_source=""
|
||||
onnx_dest="models/common.onnx"
|
||||
candidate_paths=(
|
||||
"$ddddocr_path/common.onnx"
|
||||
"$ddddocr_path/models/common.onnx"
|
||||
"$ddddocr_path/ddddocr/common.onnx"
|
||||
)
|
||||
for candidate in "${candidate_paths[@]}"; do
|
||||
if [ -f "$candidate" ]; then
|
||||
onnx_source="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
# 若以上候选均未命中,回退到全包搜索
|
||||
if [ -z "$onnx_source" ]; then
|
||||
echo "⚠ 未在已知路径找到 ONNX 模型,回退到全包搜索..."
|
||||
onnx_source=$(find "$ddddocr_path" -name "*.onnx" -type f 2>/dev/null | head -1)
|
||||
fi
|
||||
|
||||
if [ -n "$onnx_source" ] && [ -f "$onnx_source" ]; then
|
||||
cp "$onnx_source" "$onnx_dest"
|
||||
echo "✓ ONNX model copied: $onnx_source -> $onnx_dest"
|
||||
else
|
||||
echo "✗ ONNX model not found in ddddocr package"
|
||||
echo " Searched directory: $ddddocr_path"
|
||||
ls -la "$ddddocr_path/" || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -f "$onnx_dest" ]; then
|
||||
file_size=$(du -h "$onnx_dest" | cut -f1)
|
||||
echo "✓ Model file verified: $onnx_dest (Size: $file_size)"
|
||||
else
|
||||
echo "✗ Failed to copy model file"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Compile Qt Resource files
|
||||
run: |
|
||||
cd batchs
|
||||
bash compile_rc.sh
|
||||
|
||||
- name: Compile Qt UI files
|
||||
run: |
|
||||
cd batchs
|
||||
bash compile_ui.sh
|
||||
|
||||
- name: Generate 'Main.spec'
|
||||
env:
|
||||
APP_VERSION: ${{ steps.get_version.outputs.VERSION }}
|
||||
run: |
|
||||
version="$APP_VERSION"
|
||||
exe_name="AutoLibrary-$version"
|
||||
echo "Generating Main.spec for version: $version"
|
||||
echo "App name: $exe_name"
|
||||
|
||||
printf '%s\n' \
|
||||
'# -*- mode: python ; coding: utf-8 -*-' \
|
||||
'' \
|
||||
'a = Analysis(' \
|
||||
" ['src/Main.py']," \
|
||||
' pathex=[],' \
|
||||
' binaries=[],' \
|
||||
' datas=[' \
|
||||
" ('models/common.onnx', 'ddddocr')," \
|
||||
" ('src/gui/resources/icons/AutoLibrary_Logo_64.ico', 'gui/resources/icons')," \
|
||||
' ],' \
|
||||
' hiddenimports=[],' \
|
||||
' hookspath=[],' \
|
||||
' hooksconfig={},' \
|
||||
' runtime_hooks=[],' \
|
||||
' excludes=[],' \
|
||||
' noarchive=False,' \
|
||||
' optimize=0,' \
|
||||
')' \
|
||||
'pyz = PYZ(a.pure)' \
|
||||
'' \
|
||||
'exe = EXE(' \
|
||||
' pyz,' \
|
||||
' a.scripts,' \
|
||||
' [],' \
|
||||
' exclude_binaries=True,' \
|
||||
" name='AutoLibrary'," \
|
||||
' debug=False,' \
|
||||
' bootloader_ignore_signals=False,' \
|
||||
' strip=False,' \
|
||||
' upx=True,' \
|
||||
' upx_exclude=[],' \
|
||||
' runtime_tmpdir=None,' \
|
||||
' console=False,' \
|
||||
' disable_windowed_traceback=False,' \
|
||||
' argv_emulation=False,' \
|
||||
' target_arch=None,' \
|
||||
' codesign_identity=None,' \
|
||||
' entitlements_file=None,' \
|
||||
" icon=['src/gui/resources/icons/AutoLibrary_Logo_64.ico']," \
|
||||
')' \
|
||||
'' \
|
||||
'coll = COLLECT(' \
|
||||
' exe,' \
|
||||
' a.binaries,' \
|
||||
' a.zipfiles,' \
|
||||
' a.datas,' \
|
||||
' strip=False,' \
|
||||
' upx=True,' \
|
||||
' upx_exclude=[],' \
|
||||
" name='${exe_name}'," \
|
||||
')' \
|
||||
'' \
|
||||
'app = BUNDLE(' \
|
||||
' coll,' \
|
||||
" name='AutoLibrary.app'," \
|
||||
" icon='src/gui/resources/icons/AutoLibrary_Logo.icns'," \
|
||||
" bundle_identifier='com.kenanzhu.autolibrary'," \
|
||||
' info_plist={' \
|
||||
" 'NSHighResolutionCapable': 'True'," \
|
||||
" 'CFBundleName': 'AutoLibrary'," \
|
||||
" 'CFBundleDisplayName': 'AutoLibrary'," \
|
||||
" 'CFBundleShortVersionString': '${version}'," \
|
||||
" 'CFBundleVersion': '${version}'," \
|
||||
" 'CFBundleExecutable': 'AutoLibrary'," \
|
||||
" 'NSPrincipalClass': 'NSApplication'," \
|
||||
" 'LSMinimumSystemVersion': '11.0'," \
|
||||
" 'NSRequiresAquaSystemAppearance': 'False'," \
|
||||
" 'NSHumanReadableCopyright': 'Copyright 2025 - 2026 KenanZhu. All rights reserved.'," \
|
||||
' },' \
|
||||
')' \
|
||||
> Main.spec
|
||||
|
||||
echo "✓ Main.spec generated successfully"
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "Generated Main.spec"
|
||||
echo "========================================"
|
||||
cat Main.spec
|
||||
echo "========================================"
|
||||
|
||||
- name: Build with PyInstaller
|
||||
run: |
|
||||
python -m PyInstaller Main.spec
|
||||
|
||||
- name: Create DMG
|
||||
run: |
|
||||
tag_name="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
dmg_name="AutoLibrary.$tag_name-macos-arm64.dmg"
|
||||
app_path="dist/AutoLibrary.app"
|
||||
|
||||
if [ ! -d "$app_path" ]; then
|
||||
echo "✗ App bundle not found: $app_path"
|
||||
echo "Files in dist directory:"
|
||||
ls -la dist/
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Creating DMG from: $app_path"
|
||||
xattr -cr "$app_path" 2>/dev/null || true
|
||||
|
||||
tmp_dmg_dir=$(mktemp -d)
|
||||
cp -R "$app_path" "$tmp_dmg_dir/"
|
||||
ln -s /Applications "$tmp_dmg_dir/Applications"
|
||||
|
||||
hdiutil create \
|
||||
-volname "AutoLibrary $tag_name" \
|
||||
-srcfolder "$tmp_dmg_dir" \
|
||||
-ov \
|
||||
-format UDZO \
|
||||
"$dmg_name"
|
||||
|
||||
rm -rf "$tmp_dmg_dir"
|
||||
|
||||
if [ -f "$dmg_name" ]; then
|
||||
dmg_size=$(du -h "$dmg_name" | cut -f1)
|
||||
echo "✓ DMG created: $dmg_name (Size: $dmg_size)"
|
||||
else
|
||||
echo "✗ Failed to create DMG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✓ Artifacts ready:"
|
||||
echo " - $dmg_name"
|
||||
echo " - $app_path"
|
||||
|
||||
- name: Archive artifacts
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-macos-arm64
|
||||
path: |
|
||||
AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-macos-arm64.dmg
|
||||
dist/AutoLibrary.app/**
|
||||
retention-days: ${{ inputs.is_test == 'true' && 7 || 90 }}
|
||||
|
||||
- name: Upload build summary
|
||||
if: ${{ inputs.is_test == 'true' }}
|
||||
run: |
|
||||
tag_name="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
version="${{ steps.get_version.outputs.VERSION }}"
|
||||
dmg_name="AutoLibrary.$tag_name-macos-arm64.dmg"
|
||||
|
||||
{
|
||||
echo "## Build Summary (macOS)"
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "✓ Build test completed successfully!"
|
||||
echo "- Version: $version"
|
||||
echo "- Tag: $tag_name"
|
||||
echo "- Event: ${{ github.event_name }}"
|
||||
echo "- Ref: ${{ github.ref }}"
|
||||
echo "- DMG: $dmg_name"
|
||||
echo ""
|
||||
echo "### How to test on macOS"
|
||||
echo '1. Download the DMG artifact'
|
||||
echo '2. Open the DMG and drag AutoLibrary.app to /Applications'
|
||||
echo '3. Right-click → Open the app (to bypass Gatekeeper)'
|
||||
} >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -83,7 +83,9 @@ jobs:
|
||||
|
||||
echo "✓ File replaced: $FILE_PATH"
|
||||
echo ""
|
||||
echo "Updated file content ==================="
|
||||
echo "========================================"
|
||||
echo "Updated file content"
|
||||
echo "========================================"
|
||||
cat "$FILE_PATH"
|
||||
echo "========================================"
|
||||
|
||||
@@ -151,3 +153,9 @@ jobs:
|
||||
COMMIT_SHA=$(git rev-parse --short HEAD)
|
||||
echo "commit_sha=$COMMIT_SHA" >> $GITHUB_OUTPUT
|
||||
echo "✓ New commit SHA: $COMMIT_SHA"
|
||||
echo "## Commit Release Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "========================================" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Version: ${{ inputs.version }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Tag: ${{ inputs.tag_name }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Commit SHA: $COMMIT_SHA" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -21,8 +21,10 @@ name: Release
|
||||
# Commits version changes to release branch and creates the release tag.
|
||||
|
||||
# 4. Build:
|
||||
# Compiles the application for Windows platform using PyInstaller, and
|
||||
# archives the built artifacts as 'AutoLibrary.<tag_name>-windows-x86_64.zip'.
|
||||
# Compiles the application for Windows and macOS platforms using PyInstaller, and
|
||||
# archives the built artifacts.
|
||||
# - Windows: AutoLibrary.<tag_name>-windows-x86_64.zip
|
||||
# - macOS: AutoLibrary.<tag_name>-macos-arm64.dmg
|
||||
|
||||
# 5. Release:
|
||||
# Creates GitHub release with generated artifacts and release notes
|
||||
@@ -47,7 +49,7 @@ on:
|
||||
jobs:
|
||||
#
|
||||
# Start :
|
||||
# virtual job that indacates the start of the release process
|
||||
# virtual job that indicates the start of the release process
|
||||
#
|
||||
|
||||
start:
|
||||
@@ -158,7 +160,7 @@ jobs:
|
||||
needs:
|
||||
- update-version
|
||||
- commit-release
|
||||
if: always() && needs.update-version.result == 'success' && needs.commit-release.result == 'success'
|
||||
if: always() && needs.update-version.result == 'success' && (needs.commit-release.result == 'success' || needs.commit-release.result == 'skipped')
|
||||
uses: ./.github/workflows/build.yml
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -181,12 +183,18 @@ jobs:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Download artifacts
|
||||
- name: Download Windows artifacts
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-windows-x86_64
|
||||
path: artifacts/
|
||||
|
||||
- name: Download macOS artifacts
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-macos-arm64
|
||||
path: artifacts/
|
||||
|
||||
- name: Create release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@v2
|
||||
@@ -195,6 +203,7 @@ jobs:
|
||||
name: AutoLibrary ${{ needs.extract-version.outputs.tag_name }}
|
||||
files: |
|
||||
artifacts/AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-windows-x86_64.zip
|
||||
artifacts/AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-macos-arm64.dmg
|
||||
draft: false
|
||||
prerelease: ${{ needs.extract-version.outputs.is_rc == 'true' }}
|
||||
generate_release_notes: true
|
||||
@@ -205,7 +214,7 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# End :
|
||||
# virtual job that indacates the end of the release process
|
||||
# virtual job that indicates the end of the release process
|
||||
#
|
||||
|
||||
end:
|
||||
@@ -227,7 +236,7 @@ jobs:
|
||||
- release
|
||||
- extract-version
|
||||
- commit-release
|
||||
if: ${{ needs.release.result == 'success' && needs.commit-release.result == 'success' }}
|
||||
if: ${{ needs.release.result == 'success' && (needs.commit-release.result == 'success' || needs.commit-release.result == 'skipped') }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -267,9 +276,13 @@ jobs:
|
||||
git checkout ${MAIN_BRANCH}
|
||||
|
||||
# Show branch status before merge
|
||||
echo "=== Branch status before merge ==="
|
||||
echo "========================================"
|
||||
echo "Branch status before merge"
|
||||
echo "========================================"
|
||||
git log --oneline --graph --all -5
|
||||
echo "=== Diff between ${MAIN_BRANCH} and origin/${BRANCH_NAME} ==="
|
||||
echo "========================================"
|
||||
echo "Diff: ${MAIN_BRANCH} vs origin/${BRANCH_NAME}"
|
||||
echo "========================================"
|
||||
git diff ${MAIN_BRANCH} origin/${BRANCH_NAME} --stat || echo "No differences found"
|
||||
|
||||
# Force create a merge commit even if there are no changes
|
||||
@@ -279,7 +292,9 @@ jobs:
|
||||
-m "chore(release): merge ${BRANCH_NAME} to ${MAIN_BRANCH} [auto release commit]"
|
||||
|
||||
# Show merge result
|
||||
echo "=== Merge result ==="
|
||||
echo "========================================"
|
||||
echo "Merge result"
|
||||
echo "========================================"
|
||||
git log --oneline --graph -3
|
||||
|
||||
# Push to main
|
||||
@@ -310,6 +325,7 @@ jobs:
|
||||
|
||||
echo "## Release Cleanup Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "========================================" >> $GITHUB_STEP_SUMMARY
|
||||
echo "✓ Release completed successfully!" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### Actions Performed:" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -128,10 +128,15 @@ jobs:
|
||||
echo "Build version file location: $VER_INFO_BUILDFILE"
|
||||
echo "Commit version file location: $VER_INFO_COMMITFILE"
|
||||
echo ""
|
||||
echo "Build version ALVersionInfo.py content ="
|
||||
echo "========================================"
|
||||
echo "Build version ALVersionInfo.py"
|
||||
echo "========================================"
|
||||
cat "$VER_INFO_BUILDFILE"
|
||||
echo "========================================"
|
||||
echo ""
|
||||
echo "Commit version ALVersionInfo.py content "
|
||||
echo "========================================"
|
||||
echo "Commit version ALVersionInfo.py"
|
||||
echo "========================================"
|
||||
cat "$VER_INFO_COMMITFILE"
|
||||
echo "========================================"
|
||||
|
||||
@@ -140,11 +145,16 @@ jobs:
|
||||
run: |
|
||||
if git diff --quiet src/gui/ALVersionInfo.py; then
|
||||
echo "has_changes=false" >> $GITHUB_OUTPUT
|
||||
echo "! No changes detected in ALVersionInfo.py"
|
||||
echo "⚠ No changes detected in ALVersionInfo.py"
|
||||
else
|
||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||
echo "✓ ALVersionInfo.py has been modified"
|
||||
fi
|
||||
echo "## Update Version Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "========================================" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Version: ${{ steps.get_version.outputs.VERSION }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
- name: Upload modified ALVersionInfo.py ready for build
|
||||
if: steps.check_changes.outputs.has_changes == 'true'
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# AutoLibrary
|
||||
---
|
||||
|
||||

|
||||

|
||||
|
||||
[](https://github.com/KenanZhu/AutoLibrary)
|
||||

|
||||
@@ -17,15 +17,24 @@
|
||||
|
||||
### 功能
|
||||
|
||||
#### 核心特性
|
||||
|
||||
1. 自动预约 - 支持自动预约
|
||||
2. 自动续约 - 支持自动续约
|
||||
3. 自动签到 - 支持自动签到
|
||||
4. 远程签到 - 支持远程签到,无需在图书馆网络环境下即可签到
|
||||
5. 批量操作 - 支持同时预约多个用户,可以指定当前需要跳过的用户,并将用户分成多个组
|
||||
6. 定时任务 - 使用内置定时任务管理,添加定时任务,指定时间后按当前预约信息自动运行,支持设置重复任务
|
||||
7. 驱动管理 - 内置浏览器驱动自动管理,支持自动检测浏览器版本并下载对应驱动,无需手动下载
|
||||
|
||||
*具体操作方法和注意事项请访问我们的 [帮助手册](https://www.autolibrary.kenanzhu.com/manuals)*
|
||||
#### 辅助特性
|
||||
|
||||
1. 批量操作 - 支持同时预约多个用户,可以指定当前需要跳过的用户,并将用户分成多个组
|
||||
2. 定时任务 - 使用内置定时任务管理,添加定时任务,指定时间后按当前预约信息自动运行,支持设置重复任务
|
||||
3. 驱动管理 - 内置浏览器驱动自动管理,支持自动检测浏览器版本并下载对应驱动,无需手动下载
|
||||
4. 自定义主题 - 支持深浅色主题切换,多款应用样式切换,可导入 .altheme 自定义主题一键换肤
|
||||
|
||||
> [!TIP]
|
||||
> 前往 [主题市场](https://www.autolibrary.kenanzhu.com/marketplace) 获取和分享更多自定义主题。
|
||||
|
||||
*具体操作方法和注意事项请访问我们的 [帮助手册](https://manuals.autolibrary.kenanzhu.com)*
|
||||
|
||||
### 如何使用
|
||||
|
||||
@@ -39,7 +48,7 @@
|
||||
|
||||
#### 平台支持 & 编译步骤
|
||||
|
||||
本工具目前仅支持 Windows 平台,由于使用 PySide6 库开发,理论上是可以自行编译并在 Linux 和 macOS 上运行,这里提供简单的编译步骤:
|
||||
本工具目前支持 Windows 和 macOS(Apple Silicon)平台,由于使用 PySide6 库开发,理论上是可以自行编译并在 Linux 和旧架构 macOS 上运行,这里提供简单的编译步骤:
|
||||
|
||||
1. 确保系统安装了 Python 3.13 版本 (推荐,过低或高版本会导致兼容问题)。
|
||||
2. 安装所有依赖库,命令为 `pip install -r requirements.txt` (建议在虚拟环境下操作)。
|
||||
@@ -71,7 +80,7 @@ def classification(self, img: bytes):
|
||||
只要确保处于校园网网络环境内,工具都是可以正常运行的。操作处理速度基本上取决于校园网的网络环境,一般情况下在 3-4 秒(不考虑硬件差异)左右即可完成一个用户的操作,完全满足正常使用需求。
|
||||
|
||||
> [!NOTE]
|
||||
> 工具仅作为正常的预约,签到和续约的图书馆辅助工具,请勿干扰图书馆的正常运行(如故意预约多个座位,或同时预约大量的用户等,对此影响图书馆正常运行本工具概不负责,请在善用工具方便自己的情况下尽量不用影响其他同学的使用)。
|
||||
> 工具仅作为正常的预约,签到和续约的图书馆辅助工具,请勿干扰图书馆的正常运行(如故意预约多个座位,或同时预约大量的用户等)由此影响图书馆正常运行的情况本工具概不负责,请在善用工具方便自己的情况下尽量不用影响其他同学的使用。
|
||||
|
||||
#### 关于批量操作
|
||||
|
||||
@@ -97,13 +106,13 @@ def classification(self, img: bytes):
|
||||
|
||||
#### 会有手机端的版本吗?
|
||||
|
||||
暂时没有考虑,而且也没有足够的时间和能力开发多平台的版本并测试维护,所以暂时只提供 Windows 版本。
|
||||
暂时没有考虑,而且也没有足够的时间和能力开发多平台的版本并测试维护,所以暂时只提供 Windows 和 macOS(Apple Silicon)版本。
|
||||
|
||||
#### 后续会有哪些功能?
|
||||
|
||||
当前版本的功能对于正常使用已经足够,不过后续会着重完善预约时的使用体验,暂时有以下构想:
|
||||
|
||||
- 引入交互预约面板功能,预约时直接在座位分布图中选择可用座位,并按用户分配,无需事先配置预约信息。
|
||||
- ~~引入交互预约面板功能,预约时直接在座位分布图中选择可用座位,并按用户分配,无需事先配置预约信息。~~ (不计划)
|
||||
- ~~优化定时任务管理功能,用户可以在定时任务管理界面设置重复运行的定时任务,如每日预约、每周预约等。~~ (已完成)
|
||||
- 软件的自动更新以及公告栏功能,用户可以自动更新最新版本并获取最新公告事项。
|
||||
|
||||
@@ -111,8 +120,8 @@ def classification(self, img: bytes):
|
||||
|
||||
#### 其他功能建议?
|
||||
|
||||
如果你有其他功能建议,或者遇到了什么功能性,操作上的问题,欢迎提交 Issue 到本项目。
|
||||
如果你有足够的开发能力,欢迎为本项目提交 PR,也可以 Fork 本项目,根据自己的需求进行修改和完善。
|
||||
如果你有其他功能建议,或者遇到了什么功能性,操作上的问题,欢迎提交 [Issue](https://github.com/KenanZhu/AutoLibrary/issues) 到本项目。
|
||||
如果你有足够的开发能力,欢迎为本项目提交 [PR](https://github.com/KenanZhu/AutoLibrary/pulls) ,也可以 Fork 本项目,根据自己的需求进行修改和完善。
|
||||
|
||||
### 联系我
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
This folder is used to store the manuals.
|
||||
|
||||
Our manuals are available at https://manuals.autolibrary.kenanzhu.com
|
||||
@@ -1,3 +0,0 @@
|
||||
This folder is used to store the manuals.
|
||||
|
||||
Our manuals are available at https://www.autolibrary.kenanzhu.com/manuals
|
||||
@@ -0,0 +1,34 @@
|
||||
attrs==26.1.0
|
||||
certifi==2026.2.25
|
||||
cffi==2.0.0
|
||||
charset-normalizer==3.4.6
|
||||
ddddocr==1.0.6
|
||||
flatbuffers==25.12.19
|
||||
h11==0.16.0
|
||||
idna==3.11
|
||||
lupa==2.8
|
||||
numpy==2.4.3
|
||||
onnxruntime==1.24.4
|
||||
outcome==1.3.0.post0
|
||||
packaging==26.0
|
||||
pillow==12.1.1
|
||||
protobuf==7.34.0
|
||||
pybrowsers==1.3.2
|
||||
pycparser==3.0
|
||||
pyinstaller==6.19.0
|
||||
PySide6==6.10.2
|
||||
PySide6_Addons==6.10.2
|
||||
PySide6_Essentials==6.10.2
|
||||
PySocks==1.7.1
|
||||
QtAwesome==1.4.2
|
||||
QtPy==2.4.3
|
||||
requests==2.32.5
|
||||
selenium==4.38.0
|
||||
shiboken6==6.10.2
|
||||
sniffio==1.3.1
|
||||
sortedcontainers==2.4.0
|
||||
trio==0.33.0
|
||||
trio-websocket==0.12.2
|
||||
typing_extensions==4.15.0
|
||||
urllib3==2.6.3
|
||||
wsproto==1.3.2
|
||||
@@ -22,9 +22,8 @@ def main():
|
||||
|
||||
app = QApplication(sys.argv)
|
||||
translator = QTranslator()
|
||||
if translator.load(":/res/trans/translators/qtbase_zh_CN.ts"):
|
||||
if translator.load(":/res/translators/qtbase_zh_CN.ts"):
|
||||
app.installTranslator(translator)
|
||||
app.setStyle('Fusion')
|
||||
app.setApplicationName("AutoLibrary")
|
||||
if not initializeApp():
|
||||
sys.exit(-1)
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from datetime import (
|
||||
date,
|
||||
datetime,
|
||||
)
|
||||
|
||||
from lupa import LuaRuntime as _LuaRuntime
|
||||
|
||||
from autoscript._helpers import (
|
||||
_TYPE_DEFAULT_VAR,
|
||||
_assignPath,
|
||||
_checkDateFormat,
|
||||
_checkTimeFormat,
|
||||
_checkType,
|
||||
_cleanLuaError,
|
||||
_navigatePath,
|
||||
)
|
||||
|
||||
try:
|
||||
from lupa.lua55 import LuaError as _LuaError, LuaSyntaxError as _LuaSyntaxError
|
||||
except ImportError:
|
||||
try:
|
||||
from lupa.lua54 import LuaError as _LuaError, LuaSyntaxError as _LuaSyntaxError
|
||||
except ImportError:
|
||||
_LuaError = Exception
|
||||
_LuaSyntaxError = Exception
|
||||
|
||||
|
||||
__all__ = ["ASEngine"]
|
||||
|
||||
|
||||
class ASEngine:
|
||||
|
||||
@staticmethod
|
||||
def getCurrentDate(
|
||||
) -> str:
|
||||
|
||||
return date.today().isoformat()
|
||||
|
||||
@staticmethod
|
||||
def getCurrentTime(
|
||||
) -> str:
|
||||
|
||||
return datetime.now().strftime("%H:%M")
|
||||
|
||||
@staticmethod
|
||||
def _sandbox(
|
||||
lua,
|
||||
) -> None:
|
||||
|
||||
lua.execute("""
|
||||
io = nil
|
||||
require = nil
|
||||
dofile = nil
|
||||
loadfile = nil
|
||||
load = nil
|
||||
package = nil
|
||||
rawget = nil
|
||||
rawset = nil
|
||||
rawequal = nil
|
||||
getfenv = nil
|
||||
setfenv = nil
|
||||
debug = nil
|
||||
if os then
|
||||
os.execute = nil
|
||||
os.exit = nil
|
||||
os.getenv = nil
|
||||
os.remove = nil
|
||||
os.rename = nil
|
||||
os.tmpname = nil
|
||||
os.setlocale = nil
|
||||
end
|
||||
""")
|
||||
|
||||
@staticmethod
|
||||
def _registerHelpers(
|
||||
lua,
|
||||
) -> None:
|
||||
|
||||
lua.execute("""
|
||||
function date(y, m, d)
|
||||
return os.time({year = y, month = m, day = d})
|
||||
end
|
||||
|
||||
function time(h, m)
|
||||
return h * 60 + m
|
||||
end
|
||||
|
||||
function datenow()
|
||||
local now = os.date("*t")
|
||||
return os.time({year = now.year, month = now.month, day = now.day})
|
||||
end
|
||||
|
||||
function timenow()
|
||||
local now = os.date("*t")
|
||||
return now.hour * 60 + now.min
|
||||
end
|
||||
|
||||
function dateadd(date_val, n)
|
||||
return date_val + n * 86400
|
||||
end
|
||||
|
||||
function timeadd(time_val, n)
|
||||
return (time_val + n * 60) % 1440
|
||||
end
|
||||
|
||||
function strtodate(iso_str)
|
||||
local y, m, d = iso_str:match("(%d+)-(%d+)-(%d+)")
|
||||
return os.time({year = y, month = m, day = d})
|
||||
end
|
||||
|
||||
function strtotime(hm_str)
|
||||
local h, m = hm_str:match("(%d+):(%d+)")
|
||||
return h * 60 + m
|
||||
end
|
||||
|
||||
function datetostr(ts)
|
||||
return os.date("%Y-%m-%d", ts)
|
||||
end
|
||||
|
||||
function timetostr(m)
|
||||
return string.format("%02d:%02d", math.floor(m / 60), m % 60)
|
||||
end
|
||||
""")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
targetVars: list[tuple] = None,
|
||||
):
|
||||
|
||||
self._targetVars: dict[str, dict] = {}
|
||||
self._lua = None
|
||||
|
||||
if targetVars:
|
||||
for item in targetVars:
|
||||
name, varType, keyPath = item[0], item[1], item[2]
|
||||
self.addTargetVar(name, varType, keyPath)
|
||||
|
||||
def _getLua(
|
||||
self,
|
||||
):
|
||||
|
||||
if self._lua is None:
|
||||
self._lua = _LuaRuntime(unpack_returned_tuples=True)
|
||||
self._sandbox(self._lua)
|
||||
self._registerHelpers(self._lua)
|
||||
return self._lua
|
||||
|
||||
def _push(
|
||||
self,
|
||||
targetData: dict,
|
||||
) -> None:
|
||||
|
||||
lua = self._getLua()
|
||||
g = lua.globals()
|
||||
strToDate = g["strtodate"]
|
||||
strToTime = g["strtotime"]
|
||||
|
||||
for varName, info in self._targetVars.items():
|
||||
keyPath = info["keyPath"]
|
||||
vt = info["type"]
|
||||
raw = _navigatePath(targetData, keyPath)
|
||||
if vt == "Date":
|
||||
if not isinstance(raw, str) or not raw.strip():
|
||||
raise ValueError(
|
||||
f"Date 类型变量 '{varName}' 对应的数据为空或不是字符串类型,"
|
||||
f"请检查路径 {keyPath} 的值是否为合法的日期字符串 (YYYY-MM-DD)"
|
||||
)
|
||||
raw = raw.strip()
|
||||
_checkDateFormat(raw, varName)
|
||||
g[varName] = strToDate(raw)
|
||||
elif vt == "Time":
|
||||
if not isinstance(raw, str) or not raw.strip():
|
||||
raise ValueError(
|
||||
f"Time 类型变量 '{varName}' 对应的数据为空或不是字符串类型,"
|
||||
f"请检查路径 {keyPath} 的值是否为合法的时间字符串 (HH:MM)"
|
||||
)
|
||||
raw = raw.strip()
|
||||
_checkTimeFormat(raw, varName)
|
||||
g[varName] = strToTime(raw)
|
||||
else:
|
||||
if raw is None:
|
||||
raw = _TYPE_DEFAULT_VAR.get(vt, False)
|
||||
g[varName] = raw
|
||||
|
||||
def _pull(
|
||||
self,
|
||||
targetData: dict,
|
||||
) -> None:
|
||||
|
||||
lua = self._getLua()
|
||||
g = lua.globals()
|
||||
dateToStr = g["datetostr"]
|
||||
timeToStr = g["timetostr"]
|
||||
|
||||
for varName, info in self._targetVars.items():
|
||||
try:
|
||||
luaVal = g[varName]
|
||||
except KeyError:
|
||||
continue
|
||||
vt = info["type"]
|
||||
if vt == "Date":
|
||||
luaVal = dateToStr(luaVal)
|
||||
elif vt == "Time":
|
||||
luaVal = timeToStr(luaVal)
|
||||
elif vt == "Float" and isinstance(luaVal, int) and not isinstance(luaVal, bool):
|
||||
luaVal = float(luaVal)
|
||||
_checkType(varName, vt, luaVal)
|
||||
_assignPath(targetData, info["keyPath"], luaVal)
|
||||
|
||||
def addTargetVar(
|
||||
self,
|
||||
name: str,
|
||||
varType: str,
|
||||
keyPath: list,
|
||||
) -> None:
|
||||
|
||||
upperName = name.upper().strip()
|
||||
self._targetVars[upperName] = {
|
||||
"type": varType,
|
||||
"keyPath": keyPath,
|
||||
}
|
||||
|
||||
def execute(
|
||||
self,
|
||||
scriptText: str,
|
||||
targetData: dict,
|
||||
) -> None:
|
||||
|
||||
if not scriptText or not scriptText.strip():
|
||||
return
|
||||
try:
|
||||
self._push(targetData)
|
||||
self._getLua().execute(scriptText)
|
||||
self._pull(targetData)
|
||||
except _LuaSyntaxError as e:
|
||||
raise ValueError(
|
||||
f"AutoScript 语法错误: {_cleanLuaError(str(e))}"
|
||||
)
|
||||
except _LuaError as e:
|
||||
raise ValueError(
|
||||
f"AutoScript 运行时错误: {_cleanLuaError(str(e))}"
|
||||
)
|
||||
except ValueError as e:
|
||||
raise ValueError(f"AutoScript 数据错误: {e}")
|
||||
except Exception as e:
|
||||
raise ValueError(f"AutoScript 未知错误: {e}")
|
||||
|
||||
def reset(
|
||||
self,
|
||||
) -> None:
|
||||
|
||||
self._targetVars = {}
|
||||
self._lua = None
|
||||
@@ -0,0 +1,58 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from .ASEngine import ASEngine
|
||||
|
||||
__version__ = "1.0.0" # autoscript version
|
||||
|
||||
_TARGET_VAR_DEFS = [
|
||||
("USERNAME", "String", ["username"], "用户名"),
|
||||
("USER_ENABLE", "Boolean", ["enabled"], "用户启用"),
|
||||
("RESERVE_DATE", "Date", ["reserve_info", "date"], "预约日期"),
|
||||
("RESERVE_BEGIN_TIME", "Time", ["reserve_info", "begin_time", "time"], "预约开始时间"),
|
||||
("RESERVE_END_TIME", "Time", ["reserve_info", "end_time", "time"], "预约结束时间"),
|
||||
]
|
||||
_MOCK_TYPE_VALUES = {
|
||||
"String": "__mock__",
|
||||
"Boolean": True,
|
||||
"Date": "2099-01-01",
|
||||
"Time": "00:00",
|
||||
"Int": 0,
|
||||
"Float": 0.0,
|
||||
}
|
||||
|
||||
|
||||
def createAllVariablesTable(
|
||||
) -> dict:
|
||||
|
||||
return {
|
||||
displayName: (name, varType)
|
||||
for name, varType, _, displayName in _TARGET_VAR_DEFS
|
||||
}
|
||||
|
||||
def createTargetVarDefs(
|
||||
) -> list:
|
||||
|
||||
return list(_TARGET_VAR_DEFS)
|
||||
|
||||
def createMockTargetData(
|
||||
) -> dict:
|
||||
|
||||
data = {}
|
||||
for _, varType, keyPath, _ in _TARGET_VAR_DEFS:
|
||||
d = data
|
||||
for key in keyPath[:-1]:
|
||||
d = d.setdefault(key, {})
|
||||
d[keyPath[-1]] = _MOCK_TYPE_VALUES.get(varType, "")
|
||||
return data
|
||||
|
||||
def createEngine(
|
||||
) -> ASEngine:
|
||||
|
||||
return ASEngine(_TARGET_VAR_DEFS)
|
||||
@@ -0,0 +1,153 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from datetime import (
|
||||
date,
|
||||
datetime,
|
||||
)
|
||||
|
||||
|
||||
_TYPE_DEFAULT_VAR: dict[str, str | int | float | bool] = {
|
||||
"String": "",
|
||||
"Int": 0,
|
||||
"Float": 0.0,
|
||||
"Boolean": False,
|
||||
}
|
||||
|
||||
|
||||
def _navigatePath(
|
||||
data: dict,
|
||||
keyPath: list,
|
||||
default=None,
|
||||
):
|
||||
|
||||
d = data
|
||||
for key in keyPath[:-1]:
|
||||
d = d.get(key, {})
|
||||
if not isinstance(d, dict):
|
||||
return default
|
||||
return d.get(keyPath[-1], default)
|
||||
|
||||
def _assignPath(
|
||||
data: dict,
|
||||
keyPath: list,
|
||||
value,
|
||||
) -> None:
|
||||
|
||||
d = data
|
||||
for key in keyPath[:-1]:
|
||||
d = d.setdefault(key, {})
|
||||
d[keyPath[-1]] = value
|
||||
|
||||
def _checkDateFormat(
|
||||
dateStr: str,
|
||||
varName: str = "",
|
||||
) -> None:
|
||||
|
||||
prefix = f"Date 类型变量 '{varName}' 的" if varName else ""
|
||||
try:
|
||||
date.fromisoformat(dateStr)
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
f"{prefix}值 '{dateStr}' 不是合法的日期格式,"
|
||||
f"应为 YYYY-MM-DD"
|
||||
)
|
||||
|
||||
def _checkTimeFormat(
|
||||
timeStr: str,
|
||||
varName: str = "",
|
||||
) -> None:
|
||||
|
||||
prefix = f"Time 类型变量 '{varName}' 的" if varName else ""
|
||||
try:
|
||||
datetime.strptime(timeStr, "%H:%M")
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
f"{prefix}值 '{timeStr}' 不是合法的时间格式,"
|
||||
f"应为 HH:MM"
|
||||
)
|
||||
|
||||
def _checkType(
|
||||
varName: str,
|
||||
varType: str,
|
||||
value,
|
||||
) -> None:
|
||||
|
||||
if varType == "Date":
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(
|
||||
f"Date 类型变量 '{varName}' 只能接受日期字符串,"
|
||||
f"不能接受 {_pyTypeToASType(value)} 类型"
|
||||
)
|
||||
_checkDateFormat(value, varName)
|
||||
return
|
||||
if varType == "Time":
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(
|
||||
f"Time 类型变量 '{varName}' 只能接受时间字符串,"
|
||||
f"不能接受 {_pyTypeToASType(value)} 类型"
|
||||
)
|
||||
_checkTimeFormat(value, varName)
|
||||
return
|
||||
if varType == "Int":
|
||||
if isinstance(value, bool):
|
||||
raise ValueError(
|
||||
f"Int 类型变量 '{varName}' 不能接受 Boolean 类型的值"
|
||||
)
|
||||
if not isinstance(value, int) and not (isinstance(value, float) and value == int(value)):
|
||||
raise ValueError(
|
||||
f"Int 类型变量 '{varName}' 不能接受 {_pyTypeToASType(value)} 类型的值"
|
||||
)
|
||||
return
|
||||
if varType == "Float":
|
||||
if isinstance(value, bool):
|
||||
raise ValueError(
|
||||
f"Float 类型变量 '{varName}' 不能接受 Boolean 类型的值"
|
||||
)
|
||||
if not isinstance(value, (int, float)):
|
||||
raise ValueError(
|
||||
f"Float 类型变量 '{varName}' 不能接受 {_pyTypeToASType(value)} 类型的值"
|
||||
)
|
||||
return
|
||||
if varType == "Boolean":
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError(
|
||||
f"Boolean 类型变量 '{varName}' 不能接受 {_pyTypeToASType(value)} 类型的值"
|
||||
)
|
||||
return
|
||||
if varType == "String":
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(
|
||||
f"String 类型变量 '{varName}' 不能接受 {_pyTypeToASType(value)} 类型的值"
|
||||
)
|
||||
return
|
||||
|
||||
def _pyTypeToASType(
|
||||
value,
|
||||
) -> str:
|
||||
|
||||
if isinstance(value, bool):
|
||||
return "Boolean"
|
||||
if isinstance(value, int):
|
||||
return "Int"
|
||||
if isinstance(value, float):
|
||||
return "Float"
|
||||
if isinstance(value, str):
|
||||
return "String"
|
||||
return "Unknown"
|
||||
|
||||
def _cleanLuaError(
|
||||
rawMsg: str,
|
||||
) -> str:
|
||||
|
||||
msg = rawMsg.replace('[string "<python>"]:', "").strip()
|
||||
stackIdx = msg.find("stack traceback:")
|
||||
if stackIdx != -1:
|
||||
msg = msg[:stackIdx].strip()
|
||||
return msg
|
||||
@@ -1,37 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import queue
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
|
||||
|
||||
class LibOperator(MsgBase):
|
||||
"""
|
||||
Base abstract class for library operation.
|
||||
|
||||
This class provides the foundation for library-related operations, inheriting
|
||||
message handling and tracing abilities from MsgBase. It serves as an abstract
|
||||
base class that must be subclassed to implement specific library functionality.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
|
||||
def _waitResponseLoad(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
pass
|
||||
@@ -1,141 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import queue
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from base.LibOperator import LibOperator
|
||||
|
||||
|
||||
class LibTimeSelector(LibOperator):
|
||||
"""
|
||||
Base class for time selection operations.
|
||||
|
||||
This class provides common time selection logic for reservation and renewal
|
||||
operations, including time conversion utilities and best time option finding.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
@staticmethod
|
||||
def _timeStrToMins(
|
||||
time_str: str
|
||||
) -> int:
|
||||
|
||||
"""
|
||||
Convert time string "HH:MM" to minutes since midnight.
|
||||
|
||||
Example:
|
||||
"10:00" -> 600
|
||||
"13:30" -> 810
|
||||
"""
|
||||
hour, minute = map(int, time_str.split(":"))
|
||||
return hour*60 + minute
|
||||
|
||||
@staticmethod
|
||||
def _minsToTimeStr(
|
||||
mins: int
|
||||
) -> str:
|
||||
|
||||
"""
|
||||
Convert minutes since midnight to time string "HH:MM".
|
||||
|
||||
Example:
|
||||
600 -> "10:00"
|
||||
810 -> "13:30"
|
||||
"""
|
||||
hour, minute = divmod(int(mins), 60)
|
||||
return f"{hour:02d}:{minute:02d}"
|
||||
|
||||
|
||||
def _formatTimeRelation(
|
||||
self,
|
||||
abs_diff: int,
|
||||
actual_diff: int,
|
||||
time_type: str
|
||||
) -> str:
|
||||
|
||||
"""
|
||||
Format time difference relation string.
|
||||
"""
|
||||
if actual_diff < 0:
|
||||
return f"早了 {abs_diff} 分钟"
|
||||
elif actual_diff > 0:
|
||||
return f"晚了 {abs_diff} 分钟"
|
||||
else:
|
||||
return f"正好等于 {time_type}"
|
||||
|
||||
|
||||
def _findBestTimeOption(
|
||||
self,
|
||||
time_options: list,
|
||||
target_time: int,
|
||||
max_time_diff: int,
|
||||
prefer_earlier: bool,
|
||||
is_reserve: bool = True
|
||||
) -> tuple:
|
||||
"""
|
||||
Find the best time option from available times.
|
||||
|
||||
Args:
|
||||
time_options: List of WebElement time options
|
||||
target_time: Target time in minutes
|
||||
max_time_diff: Maximum acceptable time difference in minutes
|
||||
prefer_earlier: If True, prefer earlier times when diffs are equal
|
||||
is_reserve: If True, parse 'time' attribute; if False, parse 'id' attribute
|
||||
|
||||
Returns:
|
||||
Tuple of (best_time_element, best_time_text, actual_diff, free_times_list)
|
||||
or (None, None, None, []) if no suitable option found
|
||||
"""
|
||||
free_times = []
|
||||
best_time_diff = max_time_diff
|
||||
best_actual_diff = None
|
||||
best_time_opt = None
|
||||
|
||||
for time_opt in time_options:
|
||||
# Parse time value based on context
|
||||
if is_reserve:
|
||||
# Reservation context: parse 'time' attribute
|
||||
time_attr = time_opt.get_attribute("time")
|
||||
if time_attr == "now":
|
||||
now = datetime.now()
|
||||
time_val = now.hour*60 + now.minute
|
||||
elif time_attr and time_attr.isdigit():
|
||||
time_val = int(time_attr)
|
||||
else:
|
||||
continue
|
||||
else:
|
||||
# Renewal context: parse 'id' attribute
|
||||
time_attr = time_opt.get_attribute("id")
|
||||
if not (time_attr and time_attr.isdigit()):
|
||||
continue
|
||||
time_val = int(time_attr)
|
||||
free_times.append(time_opt.text.strip() if not is_reserve else self._minsToTimeStr(time_val))
|
||||
actual_diff = time_val - target_time
|
||||
abs_diff = abs(actual_diff)
|
||||
|
||||
# Update best option if current is better
|
||||
if (abs_diff < best_time_diff or
|
||||
(abs_diff == best_time_diff and
|
||||
((prefer_earlier and actual_diff <= 0) or
|
||||
(not prefer_earlier and actual_diff >= 0)))):
|
||||
best_time_diff = abs_diff
|
||||
best_actual_diff = actual_diff
|
||||
best_time_opt = time_opt
|
||||
if best_time_opt is not None:
|
||||
return (best_time_opt, best_time_opt.text.strip(), best_actual_diff, free_times)
|
||||
return (None, None, None, free_times)
|
||||
@@ -11,7 +11,7 @@ import logging
|
||||
import queue
|
||||
import datetime
|
||||
|
||||
import managers.log.LogManager as LogManager
|
||||
from managers.log.LogManager import getLogger
|
||||
|
||||
|
||||
class MsgBase:
|
||||
@@ -54,11 +54,10 @@ class MsgBase:
|
||||
self._input_queue = input_queue
|
||||
self._output_queue = output_queue
|
||||
try:
|
||||
self._logger = LogManager.getLogger(self._class_name)
|
||||
self._logger = getLogger(self._class_name)
|
||||
except RuntimeError:
|
||||
self._logger = None
|
||||
|
||||
|
||||
def _showMsg(
|
||||
self,
|
||||
msg: str
|
||||
@@ -66,7 +65,6 @@ class MsgBase:
|
||||
|
||||
self._output_queue.put(f"[{self._class_name:<15}] >>> : {msg}")
|
||||
|
||||
|
||||
def _showTrace(
|
||||
self,
|
||||
msg: str,
|
||||
@@ -79,7 +77,6 @@ class MsgBase:
|
||||
if self._logger and not no_log:
|
||||
self._logger.log(level, msg)
|
||||
|
||||
|
||||
def _showLog(
|
||||
self,
|
||||
msg: str,
|
||||
@@ -89,7 +86,6 @@ class MsgBase:
|
||||
if self._logger:
|
||||
self._logger.log(level, msg)
|
||||
|
||||
|
||||
def _waitMsg(
|
||||
self,
|
||||
timeout: float = 1.0
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Base module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- MsgBase: Base class for messages.\
|
||||
- LibOperator: Base class for library operators.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
@@ -10,13 +10,19 @@ See the LICENSE file for details.
|
||||
import os
|
||||
|
||||
from PySide6.QtCore import QStandardPaths, QDir
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from managers.log.LogManager import instance as logInstance
|
||||
from interfaces.ConfigProvider import CfgKey
|
||||
from managers.config.ConfigManager import instance as configInstance
|
||||
from managers.driver.WebDriverManager import instance as webdriverInstance
|
||||
from managers.log.LogManager import instance as logInstance
|
||||
from managers.theme.ThemeManager import(
|
||||
setActiveStyle,
|
||||
instance as themeInstance
|
||||
)
|
||||
|
||||
|
||||
def initializeLogManager(
|
||||
def _initializeLogManager(
|
||||
) -> bool:
|
||||
|
||||
app_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
|
||||
@@ -27,7 +33,7 @@ def initializeLogManager(
|
||||
logInstance(log_dir)
|
||||
return True
|
||||
|
||||
def initializeConfigManager(
|
||||
def _initializeConfigManager(
|
||||
) -> bool:
|
||||
|
||||
logger = logInstance().getLogger("AppInitializer")
|
||||
@@ -49,7 +55,7 @@ def initializeConfigManager(
|
||||
configInstance(new_config_dir)
|
||||
return True
|
||||
|
||||
def initializeWebDriverManager(
|
||||
def _initializeWebDriverManager(
|
||||
) -> bool:
|
||||
|
||||
logger = logInstance().getLogger("AppInitializer")
|
||||
@@ -64,13 +70,43 @@ def initializeWebDriverManager(
|
||||
webdriverInstance(driver_dir)
|
||||
return True
|
||||
|
||||
def _initializeAppearance(
|
||||
):
|
||||
|
||||
logger = logInstance().getLogger("AppInitializer")
|
||||
|
||||
app = QApplication.instance()
|
||||
if not app:
|
||||
return
|
||||
cfg = configInstance()
|
||||
saved_style = cfg.get(CfgKey.GLOBAL.APPEARANCE.STYLE, "Fusion")
|
||||
saved_theme = cfg.get(CfgKey.GLOBAL.APPEARANCE.THEME, "system")
|
||||
saved_custom_theme = cfg.get(CfgKey.GLOBAL.APPEARANCE.CUSTOM_THEME, "")
|
||||
app.setStyle(saved_style)
|
||||
setActiveStyle(saved_style)
|
||||
if saved_custom_theme:
|
||||
try:
|
||||
themeInstance().applyTheme(saved_custom_theme)
|
||||
except Exception:
|
||||
logger.warning("无法应用自定义主题 '%s',回退到默认外观", saved_custom_theme)
|
||||
themeInstance().clearTheme(saved_theme)
|
||||
return
|
||||
themeInstance().clearTheme(saved_theme)
|
||||
|
||||
def initializeApp(
|
||||
) -> bool:
|
||||
"""
|
||||
Initialize the application components
|
||||
|
||||
if not initializeLogManager():
|
||||
Order:
|
||||
LogManager -> ConfigManager -> WebDriverManager -> Appearance
|
||||
"""
|
||||
|
||||
if not _initializeLogManager():
|
||||
return False
|
||||
if not initializeConfigManager():
|
||||
if not _initializeConfigManager():
|
||||
return False
|
||||
if not initializeWebDriverManager():
|
||||
if not _initializeWebDriverManager():
|
||||
return False
|
||||
_initializeAppearance()
|
||||
return True
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Boot module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- AppInitializer: Application initializer class.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
@@ -9,18 +9,23 @@ See the LICENSE file for details.
|
||||
"""
|
||||
import platform
|
||||
|
||||
from PySide6.QtGui import (
|
||||
QIcon, QFont
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog, QApplication
|
||||
)
|
||||
from PySide6.QtCore import (
|
||||
QTimer, Qt
|
||||
Qt,
|
||||
QTimer
|
||||
)
|
||||
from PySide6.QtGui import QIcon
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QDialog,
|
||||
QTabWidget,
|
||||
QTextBrowser
|
||||
)
|
||||
|
||||
from gui.ALVersionInfo import (
|
||||
AL_VERSION, AL_COMMIT_SHA, AL_COMMIT_DATE, AL_BUILD_DATE
|
||||
AL_VERSION,
|
||||
AL_COMMIT_SHA,
|
||||
AL_COMMIT_DATE,
|
||||
AL_BUILD_DATE
|
||||
)
|
||||
from gui.resources.ui.Ui_ALAboutDialog import Ui_ALAboutDialog
|
||||
from gui.resources import ALResource
|
||||
@@ -38,19 +43,28 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
||||
self.modifyUi()
|
||||
self.connectSignals()
|
||||
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.LogoIconLabel.setPixmap(QIcon(":/res/icon/icons/AutoLibrary_32x32.ico").pixmap(48, 48))
|
||||
info_text = self.generateAboutText()
|
||||
self.AboutInfoBrowser.setHtml(info_text)
|
||||
browser_font = self.AboutInfoBrowser.font()
|
||||
browser_font.setFamily("Courier New")
|
||||
self.AboutInfoBrowser.setFont(browser_font)
|
||||
self.AboutInfoBrowser.setTextInteractionFlags(Qt.TextBrowserInteraction)
|
||||
|
||||
self.LogoIconLabel.setPixmap(QIcon(":/res/icons/AutoLibrary_Logo_64.svg").pixmap(48, 48))
|
||||
self.TabWidget = QTabWidget()
|
||||
self.TabWidget.setDocumentMode(True)
|
||||
AboutBrowser = QTextBrowser()
|
||||
AboutBrowser.setHtml(self.generateAboutText())
|
||||
AboutBrowser.setOpenExternalLinks(True)
|
||||
AboutBrowser.setLineWrapMode(QTextBrowser.LineWrapMode.NoWrap)
|
||||
AboutBrowser.setTextInteractionFlags(Qt.TextBrowserInteraction)
|
||||
browser_font = AboutBrowser.font()
|
||||
browser_font.setFamilies(["Courier New", "Consolas", "Menlo", "DejaVu Sans Mono", "monospace"])
|
||||
AboutBrowser.setFont(browser_font)
|
||||
self.TabWidget.addTab(AboutBrowser, "关于")
|
||||
LicenseBrowser = QTextBrowser()
|
||||
LicenseBrowser.setHtml(self.generateLicenseText())
|
||||
LicenseBrowser.setOpenExternalLinks(True)
|
||||
LicenseBrowser.setTextInteractionFlags(Qt.TextBrowserInteraction)
|
||||
self.TabWidget.addTab(LicenseBrowser, "许可证")
|
||||
self.AboutInfoLayout.addWidget(self.TabWidget)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
@@ -58,39 +72,61 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
||||
|
||||
self.CopyButton.clicked.connect(self.copyAboutInfo)
|
||||
|
||||
|
||||
def generateAboutText(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
os_info = self.getOSInfo()
|
||||
run_on = f"{os_info['system']} {os_info['version']} {os_info['architecture']}"
|
||||
selenium_ver = self.getSeleniumVersion()
|
||||
about_text = f"""
|
||||
<h4>Version Information:</h4>
|
||||
Version: {AL_VERSION}<br>
|
||||
<b style="font-size:14px;">VERSION: {AL_VERSION}</b><br>
|
||||
Commit SHA: {AL_COMMIT_SHA}<br>
|
||||
Commit date: {AL_COMMIT_DATE}<br>
|
||||
Build date: {AL_BUILD_DATE}<br>
|
||||
Python version: {platform.python_version()}<br>
|
||||
Qt version: {self.getQtVersion()}<br>
|
||||
|
||||
<h4>System Information:</h4>
|
||||
<br>
|
||||
<b style="font-size:14px;">SYSTEM</b><br>
|
||||
Running on: {run_on}<br>
|
||||
Processor: {platform.processor()}<br>
|
||||
Operating system: {os_info['system']}<br>
|
||||
System version: {os_info['version']}<br>
|
||||
System architecture: {os_info['architecture']}<br>
|
||||
|
||||
<h4>Project Information:</h4>
|
||||
License: MIT License<br>
|
||||
Project repository: <a href="https://www.github.com/KenanZhu/AutoLibrary" style="text-decoration: none;">https://www.github.com/KenanZhu/AutoLibrary</a><br>
|
||||
Project website: <a href="https://www.autolibrary.kenanzhu.com" style="text-decoration: none;">https://www.autolibrary.kenanzhu.com</a><br>
|
||||
|
||||
<h4>Author Information:</h4>
|
||||
Developer: KenanZhu<br>
|
||||
Contact: nanoki_zh@163.com<br>
|
||||
GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;">https://www.github.com/KenanZhu</a><br>
|
||||
<br>
|
||||
<b style="font-size:14px;">DEPENDENCIES</b><br>
|
||||
Python: {platform.python_version()}<br>
|
||||
Qt(PySide6): {self.getQtVersion()}<br>
|
||||
Selenium: {selenium_ver}<br>
|
||||
<br>
|
||||
<b style="font-size:14px;">PROJECT</b><br>
|
||||
Website: <a href="https://www.autolibrary.kenanzhu.com" style="text-decoration:none;">https://www.autolibrary.kenanzhu.com</a><br>
|
||||
Repository: <a href="https://www.github.com/KenanZhu/AutoLibrary" style="text-decoration:none;">https://www.github.com/KenanZhu/AutoLibrary</a><br>
|
||||
<br>
|
||||
<b style="font-size:14px;">AUTHOR</b><br>
|
||||
Developer/Maintainer: KenanZhu<br>
|
||||
Contact: <a href="mailto:nanoki_zh@163.com">nanoki_zh@163.com</a><br>
|
||||
GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration:none;">https://www.github.com/KenanZhu</a><br>
|
||||
"""
|
||||
return about_text
|
||||
|
||||
def generateLicenseText(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return """
|
||||
<b>MIT License</b>
|
||||
<p>Copyright © 2025 - 2026 KenanZhu</p>
|
||||
<p>Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:</p>
|
||||
<p>The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.</p>
|
||||
<p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.</p>"""
|
||||
|
||||
def getOSInfo(
|
||||
self
|
||||
@@ -99,7 +135,6 @@ GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;"
|
||||
system = platform.system()
|
||||
version = platform.version()
|
||||
architecture = platform.architecture()[0]
|
||||
|
||||
if system == "Windows":
|
||||
try:
|
||||
version = platform.win32_ver()[1]
|
||||
@@ -116,14 +151,12 @@ GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;"
|
||||
version = f"{distro.name()} {distro.version()}"
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
return {
|
||||
'system': system,
|
||||
'version': version,
|
||||
'architecture': architecture
|
||||
}
|
||||
|
||||
|
||||
def getQtVersion(
|
||||
self
|
||||
):
|
||||
@@ -134,14 +167,23 @@ GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;"
|
||||
except:
|
||||
return "Unknown"
|
||||
|
||||
def getSeleniumVersion(
|
||||
self
|
||||
):
|
||||
|
||||
try:
|
||||
import selenium
|
||||
return selenium.__version__
|
||||
except Exception:
|
||||
return "Unknown"
|
||||
|
||||
def copyAboutInfo(
|
||||
self
|
||||
):
|
||||
|
||||
about_text = self.AboutInfoBrowser.toPlainText()
|
||||
clipboard = QApplication.clipboard()
|
||||
clipboard.setText(about_text)
|
||||
about_text = self.TabWidget.currentWidget().toPlainText()
|
||||
Clipboard = QApplication.clipboard()
|
||||
Clipboard.setText(about_text)
|
||||
original_text = self.CopyButton.text()
|
||||
self.CopyButton.setText("已复制")
|
||||
QTimer.singleShot(2000, lambda: self.CopyButton.setText(original_text))
|
||||
QTimer.singleShot(2000, lambda: self.CopyButton.setText(original_text))
|
||||
|
||||
@@ -0,0 +1,684 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from copy import deepcopy
|
||||
|
||||
import qtawesome as qta
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QDate,
|
||||
QSize,
|
||||
Qt,
|
||||
QTime,
|
||||
QTimer,
|
||||
Slot
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QColor,
|
||||
QFont,
|
||||
QSyntaxHighlighter,
|
||||
QTextCharFormat,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QComboBox,
|
||||
QDateEdit,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QDoubleSpinBox,
|
||||
QFormLayout,
|
||||
QFrame,
|
||||
QGridLayout,
|
||||
QGroupBox,
|
||||
QHBoxLayout,
|
||||
QHeaderView,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPlainTextEdit,
|
||||
QPushButton,
|
||||
QSpinBox,
|
||||
QSplitter,
|
||||
QStyle,
|
||||
QTabWidget,
|
||||
QTableWidget,
|
||||
QTableWidgetItem,
|
||||
QTimeEdit,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from autoscript import (
|
||||
createAllVariablesTable,
|
||||
createMockTargetData,
|
||||
createTargetVarDefs,
|
||||
createEngine,
|
||||
)
|
||||
|
||||
|
||||
class ALScriptHighlighter(QSyntaxHighlighter):
|
||||
"""
|
||||
Syntax highlighter for Lua-based AutoScript.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._rules = []
|
||||
|
||||
keyword_fmt = QTextCharFormat()
|
||||
keyword_fmt.setForeground(QColor("#569CD6"))
|
||||
keyword_fmt.setFontWeight(QFont.Weight.Bold)
|
||||
for kw in [
|
||||
"if", "elseif", "else", "end", "then",
|
||||
"and", "or", "not",
|
||||
"local", "function", "return", "nil",
|
||||
]:
|
||||
self._rules.append((r"\b" + kw + r"\b", keyword_fmt))
|
||||
bool_fmt = QTextCharFormat()
|
||||
bool_fmt.setForeground(QColor("#4FC1FF"))
|
||||
bool_fmt.setFontWeight(QFont.Weight.Bold)
|
||||
self._rules.append((r"\btrue\b", bool_fmt))
|
||||
self._rules.append((r"\bfalse\b", bool_fmt))
|
||||
cmp_fmt = QTextCharFormat()
|
||||
cmp_fmt.setForeground(QColor("#C586C0"))
|
||||
cmp_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
for op in [r"==", r"~=", r">=", r"<=", r">", r"<"]:
|
||||
self._rules.append((op, cmp_fmt))
|
||||
arith_fmt = QTextCharFormat()
|
||||
arith_fmt.setForeground(QColor("#C586C0"))
|
||||
arith_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
for op in [r"\+", r"-", r"\*", r"/", r"\.\."]:
|
||||
self._rules.append((op, arith_fmt))
|
||||
func_fmt = QTextCharFormat()
|
||||
func_fmt.setForeground(QColor("#DCDCAA"))
|
||||
func_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
for fn in [ "time", "date", "datenow", "timenow", "dateadd", "timeadd"]:
|
||||
self._rules.append((r"\b" + fn + r"\b", func_fmt))
|
||||
var_fmt = QTextCharFormat()
|
||||
var_fmt.setForeground(QColor("#9CDCFE"))
|
||||
var_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
var_names = [name for _, (name, _) in createAllVariablesTable().items()]
|
||||
for var in var_names:
|
||||
self._rules.append((r"\b" + var + r"\b", var_fmt))
|
||||
st_fmt = QTextCharFormat()
|
||||
st_fmt.setForeground(QColor("#CE9178"))
|
||||
st_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((r'"[^"]*"', st_fmt))
|
||||
self._rules.append((r"'[^']*'", st_fmt))
|
||||
num_fmt = QTextCharFormat()
|
||||
num_fmt.setForeground(QColor("#B5CEA8"))
|
||||
num_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((r"\b\d+(?:\.\d+)?\b", num_fmt))
|
||||
comment_fmt = QTextCharFormat()
|
||||
comment_fmt.setForeground(QColor("#6A9955"))
|
||||
comment_fmt.setFontItalic(True)
|
||||
self._rules.append((r"--[^\n]*", comment_fmt))
|
||||
|
||||
def highlightBlock(
|
||||
self,
|
||||
text
|
||||
):
|
||||
|
||||
import re
|
||||
for pattern, fmt in self._rules:
|
||||
for match in re.finditer(pattern, text, re.IGNORECASE):
|
||||
start = match.start()
|
||||
length = match.end() - match.start()
|
||||
self.setFormat(start, length, fmt)
|
||||
|
||||
|
||||
class _DebugResultDialog(QDialog):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
changes: list,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("调试运行结果 - AutoLibrary")
|
||||
self.setMinimumSize(600, 200)
|
||||
DbgLayout = QVBoxLayout(self)
|
||||
DbgTable = QTableWidget(len(changes), 3)
|
||||
DbgTable.setHorizontalHeaderLabels(["目标变量", "原始数据", "运行后数据"])
|
||||
DbgTable.horizontalHeader().setStretchLastSection(True)
|
||||
DbgTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
|
||||
DbgTable.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
||||
for row, (display_name, name, var_type, before_val, after_val) in enumerate(changes):
|
||||
label = f"{display_name}: {name}({var_type})"
|
||||
DbgTable.setItem(row, 0, QTableWidgetItem(label))
|
||||
DbgTable.setItem(row, 1, QTableWidgetItem(str(before_val)))
|
||||
DbgTable.setItem(row, 2, QTableWidgetItem(str(after_val)))
|
||||
DbgLayout.addWidget(DbgTable)
|
||||
DbgBtnBox = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
|
||||
DbgBtnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
DbgBtnBox.accepted.connect(self.accept)
|
||||
DbgLayout.addWidget(DbgBtnBox)
|
||||
|
||||
|
||||
class _TabToSpacesEditor(QPlainTextEdit):
|
||||
|
||||
def keyPressEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
if event.key() == Qt.Key.Key_Tab:
|
||||
self.insertPlainText(" ")
|
||||
return
|
||||
super().keyPressEvent(event)
|
||||
|
||||
|
||||
class ALAutoScriptEditDialog(QDialog):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None,
|
||||
script: str = "",
|
||||
mockData: dict = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._font_size = 21
|
||||
self._mock_widgets = {}
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
self.TextEdit.setPlainText(script)
|
||||
self._high_lighter = ALScriptHighlighter(
|
||||
self.TextEdit.document()
|
||||
)
|
||||
if mockData:
|
||||
self.setMockData(mockData)
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setWindowTitle("AutoScript 编辑 - AutoLibrary")
|
||||
self.setMinimumSize(660, 600)
|
||||
Layout = QVBoxLayout(self)
|
||||
Layout.setSpacing(3)
|
||||
Layout.setContentsMargins(3, 3, 3, 3)
|
||||
ToolbarLayout = QHBoxLayout()
|
||||
self.ZoomInBtn = QPushButton("")
|
||||
self.ZoomInBtn.setIcon(qta.icon("fa6s.plus", color=self._iconColor()))
|
||||
self.ZoomInBtn.setIconSize(QSize(14, 14))
|
||||
self.ZoomInBtn.setFixedSize(25, 25)
|
||||
self.ZoomOutBtn = QPushButton("")
|
||||
self.ZoomOutBtn.setIcon(qta.icon("fa6s.minus", color=self._iconColor()))
|
||||
self.ZoomOutBtn.setIconSize(QSize(14, 14))
|
||||
self.ZoomOutBtn.setFixedSize(25, 25)
|
||||
self.ZoomResetBtn = QPushButton("")
|
||||
self.ZoomResetBtn.setIcon(qta.icon("fa6s.rotate-left", color=self._iconColor()))
|
||||
self.ZoomResetBtn.setIconSize(QSize(14, 14))
|
||||
self.ZoomResetBtn.setFixedSize(25, 25)
|
||||
self.ZoomResetBtn.setToolTip("重置缩放")
|
||||
self.ZoomLabel = QLabel(f"{self._font_size}px")
|
||||
self.ZoomLabel.setFixedHeight(25)
|
||||
self.OrchBtn = QPushButton("编排")
|
||||
self.OrchBtn.setFixedSize(80, 25)
|
||||
self.OrchBtn.setToolTip("可视化生成 AutoScript 代码并插入到光标位置")
|
||||
ToolbarLayout.addWidget(self.OrchBtn)
|
||||
self.DebugBtn = QPushButton("▶ 调试运行")
|
||||
self.DebugBtn.setFixedSize(80, 25)
|
||||
self.DebugBtn.setToolTip("使用右侧模拟数据执行脚本,查看目标变量变化")
|
||||
ToolbarLayout.addWidget(self.DebugBtn)
|
||||
Sep = QFrame()
|
||||
Sep.setFrameShape(QFrame.Shape.VLine)
|
||||
Sep.setFrameShadow(QFrame.Shadow.Sunken)
|
||||
Sep.setFixedWidth(1)
|
||||
ToolbarLayout.addWidget(Sep)
|
||||
ToolbarLayout.addWidget(self.ZoomInBtn)
|
||||
ToolbarLayout.addWidget(self.ZoomOutBtn)
|
||||
ToolbarLayout.addWidget(self.ZoomResetBtn)
|
||||
ToolbarLayout.addWidget(self.ZoomLabel)
|
||||
ToolbarLayout.addStretch()
|
||||
self.CopyBtn = QPushButton("")
|
||||
self.CopyBtn.setIcon(qta.icon("fa6s.copy", color=self._iconColor()))
|
||||
self.CopyBtn.setIconSize(QSize(14, 14))
|
||||
self.CopyBtn.setFixedSize(25, 25)
|
||||
self.CopyBtn.setToolTip("复制脚本")
|
||||
ToolbarLayout.addWidget(self.CopyBtn)
|
||||
Layout.addLayout(ToolbarLayout)
|
||||
self.TextEdit = _TabToSpacesEditor(self)
|
||||
self.TextEdit.setTabStopDistance(40)
|
||||
self.TextEdit.setLineWrapMode(
|
||||
QPlainTextEdit.LineWrapMode.NoWrap
|
||||
)
|
||||
self.TextEdit.setStyleSheet(
|
||||
"QPlainTextEdit {"
|
||||
" font-family: 'Courier New', 'Consolas', monospace;"
|
||||
f" font-size: {self._font_size}px;"
|
||||
"}"
|
||||
)
|
||||
Layout.addWidget(self.TextEdit)
|
||||
self.createButtonPanel(Layout)
|
||||
self.BtnBox = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok |
|
||||
QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setFixedSize(80, 25)
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setFixedSize(80, 25)
|
||||
Layout.addWidget(self.BtnBox)
|
||||
|
||||
def createButtonPanel(
|
||||
self,
|
||||
ParentLayout
|
||||
):
|
||||
|
||||
Splitter = QSplitter(Qt.Orientation.Horizontal)
|
||||
TabWidget = QTabWidget()
|
||||
TabWidget.setMaximumHeight(150)
|
||||
BasicWidget = QWidget()
|
||||
BasicLayout = QGridLayout(BasicWidget)
|
||||
BasicLayout.setSpacing(4)
|
||||
BasicLayout.setContentsMargins(4, 4, 4, 4)
|
||||
BasicLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
control_buttons = [
|
||||
("如果 (if...)", "if then\n \nend"),
|
||||
("再如果 (elseif...)", "elseif then\n "),
|
||||
("否则 (else)", "else"),
|
||||
("结束 (end)", "end"),
|
||||
("跳过 (pass)", "-- pass"),
|
||||
]
|
||||
self.addButtonsToGrid(BasicLayout, control_buttons, 0, 0, 3)
|
||||
assign_buttons = [
|
||||
("赋值 (=)", " = "),
|
||||
]
|
||||
self.addButtonsToGrid(BasicLayout, assign_buttons, 1, 2, 3)
|
||||
TabWidget.addTab(BasicWidget, "基本语法")
|
||||
OperatorWidget = QWidget()
|
||||
OperatorLayout = QGridLayout(OperatorWidget)
|
||||
OperatorLayout.setSpacing(4)
|
||||
OperatorLayout.setContentsMargins(4, 4, 4, 4)
|
||||
OperatorLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
arithmetic_buttons = [
|
||||
("加 (+)", " + "),
|
||||
("减 (-)", " - "),
|
||||
]
|
||||
self.addButtonsToGrid(OperatorLayout, arithmetic_buttons, 0, 0, 3)
|
||||
compare_buttons = [
|
||||
("等于 (==)", " == "),
|
||||
("不等于 (~=)", " ~= "),
|
||||
("大于 (>)", " > "),
|
||||
("小于 (<)", " < "),
|
||||
("大于等于 (>=)", " >= "),
|
||||
("小于等于 (<=)", " <= "),
|
||||
]
|
||||
self.addButtonsToGrid(OperatorLayout, compare_buttons, 1, 0, 3)
|
||||
logic_buttons = [
|
||||
("且 (and)", " and "),
|
||||
("或 (or)", " or "),
|
||||
]
|
||||
self.addButtonsToGrid(OperatorLayout, logic_buttons, 2, 0, 3)
|
||||
TabWidget.addTab(OperatorWidget, "运算符")
|
||||
LiteralWidget = QWidget()
|
||||
LiteralLayout = QGridLayout(LiteralWidget)
|
||||
LiteralLayout.setSpacing(4)
|
||||
LiteralLayout.setContentsMargins(4, 4, 4, 4)
|
||||
LiteralLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
bool_buttons = [
|
||||
("真 (true)", "true"),
|
||||
("假 (false)", "false"),
|
||||
]
|
||||
self.addButtonsToGrid(LiteralLayout, bool_buttons, 0, 0, 3)
|
||||
date_time_buttons = [
|
||||
("日期", 'date(2026, 1, 1)'),
|
||||
("时间", 'time(0, 0)'),
|
||||
]
|
||||
self.addButtonsToGrid(LiteralLayout, date_time_buttons, 1, 0, 3)
|
||||
hint_buttons = [
|
||||
("字符串", '"请输入文本"'),
|
||||
("数字", "123"),
|
||||
("注释", "-- 请输入注释"),
|
||||
]
|
||||
self.addButtonsToGrid(LiteralLayout, hint_buttons, 2, 0, 3)
|
||||
TabWidget.addTab(LiteralWidget, "字面量")
|
||||
VarWidget = QWidget()
|
||||
VarLayout = QGridLayout(VarWidget)
|
||||
VarLayout.setSpacing(4)
|
||||
VarLayout.setContentsMargins(4, 4, 4, 4)
|
||||
VarLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
var_buttons = [
|
||||
(display_name, name) for display_name, (name, _) in createAllVariablesTable().items()
|
||||
]
|
||||
self.addButtonsToGrid(VarLayout, var_buttons, 0, 0, 3)
|
||||
TabWidget.addTab(VarWidget, "变量")
|
||||
FuncWidget = QWidget()
|
||||
FuncLayout = QGridLayout(FuncWidget)
|
||||
FuncLayout.setSpacing(4)
|
||||
FuncLayout.setContentsMargins(4, 4, 4, 4)
|
||||
FuncLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
func_buttons = [
|
||||
("datenow()", "datenow()", "返回当前日期的 Unix 时间戳"),
|
||||
("timenow()", "timenow()", "返回当前时间在一天中的分钟数"),
|
||||
("dateadd(day, n)", "dateadd(, )", "日期偏移: dateadd(日期时间戳, 天数)"),
|
||||
("timeadd(time, n)", "timeadd(, )", "时间偏移: timeadd(分钟数, 分钟数)"),
|
||||
]
|
||||
for i, (text, template, tooltip) in enumerate(func_buttons):
|
||||
Btn = QPushButton(text)
|
||||
Btn.setProperty("template", template)
|
||||
Btn.clicked.connect(self.insertTemplate)
|
||||
Btn.setFixedWidth(100)
|
||||
Btn.setFixedHeight(25)
|
||||
Btn.setToolTip(tooltip)
|
||||
FuncLayout.addWidget(Btn, i // 2, i % 2)
|
||||
TabWidget.addTab(FuncWidget, "工具函数")
|
||||
MockPanel = self.createMockPanel()
|
||||
MockPanel.setMinimumWidth(260)
|
||||
Splitter.addWidget(TabWidget)
|
||||
Splitter.addWidget(MockPanel)
|
||||
Splitter.setStretchFactor(0, 1)
|
||||
Splitter.setStretchFactor(1, 1)
|
||||
Splitter.setSizes([530, 530])
|
||||
ParentLayout.addWidget(Splitter)
|
||||
|
||||
def addButtonsToGrid(
|
||||
self,
|
||||
grid_layout,
|
||||
buttons,
|
||||
start_row,
|
||||
start_col,
|
||||
max_columns
|
||||
):
|
||||
|
||||
col = start_col
|
||||
row = start_row
|
||||
|
||||
for btn_text, template in buttons:
|
||||
Btn = QPushButton(btn_text)
|
||||
Btn.setProperty("template", template)
|
||||
Btn.clicked.connect(self.insertTemplate)
|
||||
Btn.setFixedWidth(100)
|
||||
Btn.setFixedHeight(25)
|
||||
Btn.setToolTip(f"插入: {template}")
|
||||
grid_layout.addWidget(Btn, row, col)
|
||||
col += 1
|
||||
if col >= start_col + max_columns:
|
||||
col = start_col
|
||||
row += 1
|
||||
|
||||
def createMockPanel(
|
||||
self
|
||||
) -> QGroupBox:
|
||||
|
||||
Group = QGroupBox("模拟目标数据")
|
||||
Form = QFormLayout(Group)
|
||||
Form.setSpacing(4)
|
||||
Form.setContentsMargins(5, 10, 5, 5)
|
||||
self._mock_widgets = {}
|
||||
mock_data = createMockTargetData()
|
||||
for name, var_type, key_path, display_name in createTargetVarDefs():
|
||||
d = mock_data
|
||||
for key in key_path:
|
||||
d = d[key]
|
||||
default = d
|
||||
Widget = self.makeMockInput(var_type, default)
|
||||
Label = QLabel(f"{display_name}: {name}({var_type})")
|
||||
Form.addRow(Label, Widget)
|
||||
self._mock_widgets[name] = (Widget, var_type, key_path)
|
||||
return Group
|
||||
|
||||
def makeMockInput(
|
||||
self,
|
||||
var_type: str,
|
||||
default
|
||||
) -> QWidget:
|
||||
|
||||
if var_type == "String":
|
||||
widget = QLineEdit()
|
||||
widget.setText(str(default))
|
||||
return widget
|
||||
if var_type == "Boolean":
|
||||
widget = QComboBox()
|
||||
widget.addItems(["是", "否"])
|
||||
widget.setCurrentIndex(0 if default else 1)
|
||||
return widget
|
||||
if var_type == "Date":
|
||||
widget = QDateEdit()
|
||||
widget.setCalendarPopup(True)
|
||||
widget.setDisplayFormat("yyyy-MM-dd")
|
||||
widget.setDate(QDate.fromString(str(default), "yyyy-MM-dd"))
|
||||
return widget
|
||||
if var_type == "Time":
|
||||
widget = QTimeEdit()
|
||||
widget.setDisplayFormat("HH:mm")
|
||||
widget.setTime(QTime.fromString(str(default), "HH:mm"))
|
||||
return widget
|
||||
if var_type == "Int":
|
||||
widget = QSpinBox()
|
||||
widget.setMinimum(-999999)
|
||||
widget.setMaximum(999999)
|
||||
widget.setValue(int(default) if default else 0)
|
||||
return widget
|
||||
if var_type == "Float":
|
||||
widget = QDoubleSpinBox()
|
||||
widget.setMinimum(-999999.0)
|
||||
widget.setMaximum(999999.0)
|
||||
widget.setDecimals(2)
|
||||
widget.setValue(float(default) if default else 0.0)
|
||||
return widget
|
||||
widget = QLineEdit()
|
||||
widget.setText(str(default))
|
||||
return widget
|
||||
|
||||
def getMockData(
|
||||
self
|
||||
) -> dict:
|
||||
|
||||
data = {}
|
||||
for name, var_type, key_path, _ in createTargetVarDefs():
|
||||
widget, _, _ = self._mock_widgets[name]
|
||||
value = self.getMockValue(widget, var_type)
|
||||
d = data
|
||||
for key in key_path[:-1]:
|
||||
d = d.setdefault(key, {})
|
||||
d[key_path[-1]] = value
|
||||
return data
|
||||
|
||||
def setMockData(
|
||||
self,
|
||||
data: dict
|
||||
):
|
||||
|
||||
if not data:
|
||||
return
|
||||
for name, var_type, key_path, _ in createTargetVarDefs():
|
||||
d = data
|
||||
try:
|
||||
for key in key_path:
|
||||
d = d[key]
|
||||
except (KeyError, TypeError):
|
||||
continue
|
||||
widget, _, _ = self._mock_widgets[name]
|
||||
self.setMockValue(widget, var_type, d)
|
||||
|
||||
def getMockValue(
|
||||
self,
|
||||
widget: QWidget,
|
||||
var_type: str
|
||||
):
|
||||
|
||||
if var_type == "Boolean":
|
||||
return widget.currentIndex() == 0
|
||||
if var_type == "Date":
|
||||
return widget.date().toString("yyyy-MM-dd")
|
||||
if var_type == "Time":
|
||||
return widget.time().toString("HH:mm")
|
||||
if var_type == "Int":
|
||||
return widget.value()
|
||||
if var_type == "Float":
|
||||
return widget.value()
|
||||
return widget.text()
|
||||
|
||||
def setMockValue(
|
||||
self,
|
||||
widget: QWidget,
|
||||
var_type: str,
|
||||
value
|
||||
):
|
||||
|
||||
if var_type == "Boolean":
|
||||
widget.setCurrentIndex(0 if value else 1)
|
||||
elif var_type == "Date":
|
||||
widget.setDate(QDate.fromString(str(value), "yyyy-MM-dd"))
|
||||
elif var_type == "Time":
|
||||
widget.setTime(QTime.fromString(str(value), "HH:mm"))
|
||||
elif var_type == "Int":
|
||||
widget.setValue(int(value))
|
||||
elif var_type == "Float":
|
||||
widget.setValue(float(value))
|
||||
else:
|
||||
widget.setText(str(value))
|
||||
|
||||
def _iconColor(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return QApplication.instance().palette().color(
|
||||
QApplication.instance().palette().ColorRole.WindowText
|
||||
).name()
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.BtnBox.accepted.connect(self.accept)
|
||||
self.BtnBox.rejected.connect(self.reject)
|
||||
self.OrchBtn.clicked.connect(self.onOpenOrchDialog)
|
||||
self.DebugBtn.clicked.connect(self.onDebugRun)
|
||||
self.ZoomInBtn.clicked.connect(self.onZoomIn)
|
||||
self.ZoomOutBtn.clicked.connect(self.onZoomOut)
|
||||
self.ZoomResetBtn.clicked.connect(self.onZoomReset)
|
||||
self.CopyBtn.clicked.connect(self.onCopy)
|
||||
|
||||
def getScript(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self.TextEdit.toPlainText()
|
||||
|
||||
def updateFontSize(
|
||||
self
|
||||
):
|
||||
|
||||
self.TextEdit.setStyleSheet(
|
||||
"QPlainTextEdit {"
|
||||
" font-family: 'Courier New', 'Consolas', monospace;"
|
||||
f" font-size: {self._font_size}px;"
|
||||
"}"
|
||||
)
|
||||
self.ZoomLabel.setText(f"{self._font_size}px")
|
||||
|
||||
@Slot()
|
||||
def insertTemplate(
|
||||
self
|
||||
):
|
||||
|
||||
Btn = self.sender()
|
||||
if not isinstance(Btn, QPushButton):
|
||||
return
|
||||
template = Btn.property("template")
|
||||
if not template:
|
||||
return
|
||||
cursor = self.TextEdit.textCursor()
|
||||
cursor.insertText(template)
|
||||
|
||||
@Slot()
|
||||
def onZoomIn(
|
||||
self
|
||||
):
|
||||
|
||||
self._font_size = min(self._font_size + 2, 40)
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
def onZoomOut(
|
||||
self
|
||||
):
|
||||
|
||||
self._font_size = max(self._font_size - 2, 8)
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
def onZoomReset(
|
||||
self
|
||||
):
|
||||
|
||||
self._font_size = 21
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
def onCopy(
|
||||
self
|
||||
):
|
||||
|
||||
Clipboard = QApplication.clipboard()
|
||||
Clipboard.setText(self.TextEdit.toPlainText())
|
||||
self.CopyBtn.setEnabled(False)
|
||||
QTimer.singleShot(2000, lambda: (
|
||||
self.CopyBtn.setEnabled(True)
|
||||
))
|
||||
|
||||
@Slot()
|
||||
def onOpenOrchDialog(
|
||||
self
|
||||
):
|
||||
|
||||
from gui.ALAutoScriptOrchDialog import ALAutoScriptOrchDialog
|
||||
Dialpg = ALAutoScriptOrchDialog(self)
|
||||
if Dialpg.exec() == QDialog.DialogCode.Accepted:
|
||||
script = Dialpg.getScript()
|
||||
if script:
|
||||
cursor = self.TextEdit.textCursor()
|
||||
cursor.insertText(script)
|
||||
Dialpg.deleteLater()
|
||||
|
||||
@Slot()
|
||||
def onDebugRun(
|
||||
self
|
||||
):
|
||||
|
||||
script = self.TextEdit.toPlainText().strip()
|
||||
if not script:
|
||||
QMessageBox.warning(self, "提示", "脚本内容为空。")
|
||||
return
|
||||
target_data = self.getMockData()
|
||||
before = deepcopy(target_data)
|
||||
try:
|
||||
engine = createEngine()
|
||||
engine.execute(script, target_data)
|
||||
except ValueError as e:
|
||||
QMessageBox.warning(self, "运行错误", str(e))
|
||||
return
|
||||
changes = []
|
||||
for name, var_type, key_path, display_name in createTargetVarDefs():
|
||||
before_val = before
|
||||
after_val = target_data
|
||||
try:
|
||||
for key in key_path:
|
||||
before_val = before_val[key]
|
||||
after_val = after_val[key]
|
||||
except (KeyError, TypeError):
|
||||
continue
|
||||
if before_val != after_val:
|
||||
changes.append((display_name, name, var_type, before_val, after_val))
|
||||
if not changes:
|
||||
QMessageBox.information(self, "调试运行", "目标变量未发生变化。")
|
||||
return
|
||||
Dialpg = _DebugResultDialog(changes, self)
|
||||
Dialpg.exec()
|
||||
Dialpg.deleteLater()
|
||||
@@ -1,884 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
from PySide6.QtCore import QTime, QDate, Slot
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
|
||||
QComboBox, QPushButton, QScrollArea, QTimeEdit,
|
||||
QDateEdit, QLineEdit, QSpinBox, QDoubleSpinBox,
|
||||
QStackedWidget, QFrame, QDialogButtonBox,
|
||||
QGroupBox, QSizePolicy
|
||||
)
|
||||
|
||||
from utils.AutoScriptEngine import AutoScriptEngine
|
||||
|
||||
|
||||
VARIABLE_META = AutoScriptEngine.VARIABLE_META
|
||||
_VAR_COMBO_ITEMS = [
|
||||
(display, varname, vartype)
|
||||
for display, (varname, vartype) in VARIABLE_META.items()
|
||||
]
|
||||
_VAR_COMBO_ITEMS_SET = [
|
||||
(display, varname, vartype)
|
||||
for display, (varname, vartype) in VARIABLE_META.items()
|
||||
if not varname.startswith("CURRENT_")
|
||||
]
|
||||
OP_ITEMS = [
|
||||
("等于", ".EQ."),
|
||||
("不等于", ".NEQ."),
|
||||
("大于", ".BGT."),
|
||||
("小于", ".BLT."),
|
||||
("大于等于", ".BGE."),
|
||||
("小于等于", ".BLE."),
|
||||
]
|
||||
|
||||
|
||||
def _makeVarCombo(
|
||||
) -> QComboBox:
|
||||
|
||||
cb = QComboBox()
|
||||
for display, varname, vartype in _VAR_COMBO_ITEMS:
|
||||
cb.addItem(display, (varname, vartype))
|
||||
cb.setMinimumWidth(120)
|
||||
cb.setFixedHeight(25)
|
||||
return cb
|
||||
|
||||
|
||||
def _makeSetVarCombo(
|
||||
) -> QComboBox:
|
||||
|
||||
cb = QComboBox()
|
||||
for display, varname, vartype in _VAR_COMBO_ITEMS_SET:
|
||||
cb.addItem(display, (varname, vartype))
|
||||
cb.setMinimumWidth(120)
|
||||
cb.setFixedHeight(25)
|
||||
return cb
|
||||
|
||||
|
||||
def _makeOpCombo(
|
||||
) -> QComboBox:
|
||||
|
||||
cb = QComboBox()
|
||||
for display, op in OP_ITEMS:
|
||||
cb.addItem(display, op)
|
||||
cb.setMinimumWidth(80)
|
||||
cb.setFixedHeight(25)
|
||||
return cb
|
||||
|
||||
|
||||
def _makeValueWidget(
|
||||
data_type: str
|
||||
) -> QWidget:
|
||||
|
||||
if data_type == "Time":
|
||||
w = QTimeEdit()
|
||||
w.setDisplayFormat("HH:mm")
|
||||
w.setMinimumWidth(100)
|
||||
w.setFixedHeight(25)
|
||||
elif data_type == "Date":
|
||||
w = QDateEdit()
|
||||
w.setDisplayFormat("yyyy-MM-dd")
|
||||
w.setCalendarPopup(True)
|
||||
w.setMinimumWidth(130)
|
||||
w.setFixedHeight(25)
|
||||
elif data_type == "Integer":
|
||||
w = QSpinBox()
|
||||
w.setMinimum(-999999)
|
||||
w.setMaximum(999999)
|
||||
w.setMinimumWidth(100)
|
||||
w.setFixedHeight(25)
|
||||
elif data_type == "Float":
|
||||
w = QDoubleSpinBox()
|
||||
w.setMinimum(-999999)
|
||||
w.setMaximum(999999)
|
||||
w.setDecimals(2)
|
||||
w.setMinimumWidth(100)
|
||||
w.setFixedHeight(25)
|
||||
elif data_type == "Boolean":
|
||||
w = QComboBox()
|
||||
w.addItem(".TRUE.", ".TRUE.")
|
||||
w.addItem(".FALSE.", ".FALSE.")
|
||||
w.setMinimumWidth(100)
|
||||
w.setFixedHeight(25)
|
||||
else:
|
||||
w = QLineEdit()
|
||||
w.setPlaceholderText("输入值")
|
||||
w.setMinimumWidth(120)
|
||||
w.setFixedHeight(25)
|
||||
return w
|
||||
|
||||
|
||||
def _makeActionValueWidget(
|
||||
data_type: str
|
||||
) -> QWidget:
|
||||
|
||||
if data_type == "Date":
|
||||
w = QComboBox()
|
||||
w.addItem("今天", "today")
|
||||
w.addItem("明天", "tomorrow")
|
||||
w.setFixedHeight(25)
|
||||
w.setMinimumWidth(100)
|
||||
w._is_date_action = True
|
||||
return w
|
||||
|
||||
if data_type == "Time":
|
||||
container = QWidget()
|
||||
layout = QHBoxLayout(container)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.setSpacing(2)
|
||||
modeCombo = QComboBox()
|
||||
modeCombo.addItem("固定时间", "fixed")
|
||||
modeCombo.addItem("相对当前", "relative")
|
||||
modeCombo.setFixedHeight(25)
|
||||
stack = QStackedWidget()
|
||||
timeEdit = QTimeEdit()
|
||||
timeEdit.setDisplayFormat("HH:mm")
|
||||
timeEdit.setFixedHeight(25)
|
||||
spinBox = QSpinBox()
|
||||
spinBox.setRange(0, 23)
|
||||
spinBox.setSuffix("小时")
|
||||
spinBox.setFixedHeight(25)
|
||||
stack.addWidget(timeEdit)
|
||||
stack.addWidget(spinBox)
|
||||
modeCombo.currentIndexChanged.connect(
|
||||
lambda i: stack.setCurrentIndex(i)
|
||||
)
|
||||
layout.addWidget(modeCombo)
|
||||
layout.addWidget(stack)
|
||||
container._modeCombo = modeCombo
|
||||
container._timeEdit = timeEdit
|
||||
container._spinBox = spinBox
|
||||
container._isActionTime = True
|
||||
return container
|
||||
|
||||
return _makeValueWidget(data_type)
|
||||
|
||||
|
||||
def _getValueFromWidget(
|
||||
w: QWidget
|
||||
) -> str:
|
||||
|
||||
if getattr(w, '_isActionTime', False):
|
||||
if w._modeCombo.currentData() == "fixed":
|
||||
return w._timeEdit.time().toString("HH:mm")
|
||||
else:
|
||||
return f"+{w._spinBox.value()}"
|
||||
if isinstance(w, QTimeEdit):
|
||||
return w.time().toString("HH:mm")
|
||||
if isinstance(w, QDateEdit):
|
||||
return w.date().toString("yyyy-MM-dd")
|
||||
if isinstance(w, QComboBox):
|
||||
return w.currentText()
|
||||
if isinstance(w, QSpinBox):
|
||||
return str(w.value())
|
||||
if isinstance(w, QDoubleSpinBox):
|
||||
return str(w.value())
|
||||
if isinstance(w, QLineEdit):
|
||||
return w.text()
|
||||
return ""
|
||||
|
||||
|
||||
def _encodeValueStr(
|
||||
raw_value: str,
|
||||
data_type: str
|
||||
) -> str:
|
||||
|
||||
if data_type == "Time":
|
||||
if raw_value.startswith("+"):
|
||||
return raw_value
|
||||
return f"TIME({raw_value})"
|
||||
elif data_type == "Date":
|
||||
if raw_value == "今天":
|
||||
return "CURRENT_DATE"
|
||||
elif raw_value == "明天":
|
||||
return "CURRENT_DATE + 1"
|
||||
return f"DATE({raw_value})"
|
||||
elif data_type == "Boolean":
|
||||
return raw_value
|
||||
elif data_type == "String":
|
||||
escaped = raw_value.replace("'", "''")
|
||||
return f"'{escaped}'"
|
||||
else:
|
||||
return raw_value
|
||||
|
||||
|
||||
def _setWidgetValue(
|
||||
w: QWidget,
|
||||
vartype: str,
|
||||
expr: str
|
||||
):
|
||||
|
||||
import re
|
||||
s = expr.strip()
|
||||
|
||||
if getattr(w, '_isActionTime', False):
|
||||
timeMatch = re.match(r"TIME\((\d{1,2}:\d{2})\)", s, re.IGNORECASE)
|
||||
if timeMatch:
|
||||
w._modeCombo.setCurrentIndex(0)
|
||||
parts = timeMatch.group(1).split(":")
|
||||
w._timeEdit.setTime(QTime(int(parts[0]), int(parts[1])))
|
||||
return
|
||||
relMatch = re.match(r"^\+(\d+)$", s)
|
||||
if relMatch:
|
||||
w._modeCombo.setCurrentIndex(1)
|
||||
w._spinBox.setValue(int(relMatch.group(1)))
|
||||
return
|
||||
return
|
||||
if getattr(w, '_is_date_action', False) and isinstance(w, QComboBox):
|
||||
if s.upper() in ("CURRENT_DATE", "TODAY"):
|
||||
w.setCurrentIndex(0)
|
||||
elif s.upper() in ("CURRENT_DATE + 1", "TOMORROW"):
|
||||
w.setCurrentIndex(1)
|
||||
else:
|
||||
dateMatch = re.match(
|
||||
r"DATE\((\d{4}-\d{2}-\d{2})\)", s, re.IGNORECASE
|
||||
)
|
||||
if dateMatch:
|
||||
from datetime import datetime, timedelta
|
||||
dateStr = dateMatch.group(1)
|
||||
today = datetime.now().strftime("%Y-%m-%d")
|
||||
tomorrow = (
|
||||
datetime.now() + timedelta(days=1)
|
||||
).strftime("%Y-%m-%d")
|
||||
if dateStr == today:
|
||||
w.setCurrentIndex(0)
|
||||
elif dateStr == tomorrow:
|
||||
w.setCurrentIndex(1)
|
||||
return
|
||||
if vartype == "Time":
|
||||
m = re.match(r"TIME\((\d{1,2}:\d{2})\)", s, re.IGNORECASE)
|
||||
if m and isinstance(w, QTimeEdit):
|
||||
parts = m.group(1).split(":")
|
||||
w.setTime(QTime(int(parts[0]), int(parts[1])))
|
||||
elif vartype == "Date":
|
||||
m = re.match(r"DATE\((\d{4}-\d{2}-\d{2})\)", s, re.IGNORECASE)
|
||||
if m and isinstance(w, QDateEdit):
|
||||
parts = m.group(1).split("-")
|
||||
w.setDate(QDate(int(parts[0]), int(parts[1]), int(parts[2])))
|
||||
elif vartype == "Boolean" and isinstance(w, QComboBox):
|
||||
for i in range(w.count()):
|
||||
if w.itemData(i) == s.upper():
|
||||
w.setCurrentIndex(i)
|
||||
break
|
||||
elif vartype == "Integer" and isinstance(w, QSpinBox):
|
||||
try:
|
||||
w.setValue(int(s))
|
||||
except ValueError:
|
||||
pass
|
||||
elif vartype == "Float" and isinstance(w, QDoubleSpinBox):
|
||||
try:
|
||||
w.setValue(float(s))
|
||||
except ValueError:
|
||||
pass
|
||||
elif isinstance(w, QLineEdit):
|
||||
inner = s
|
||||
if (inner.startswith("'") and inner.endswith("'")) or \
|
||||
(inner.startswith('"') and inner.endswith('"')):
|
||||
inner = inner[1:-1].replace("''", "'")
|
||||
w.setText(inner)
|
||||
|
||||
|
||||
class ActionStepFrame(QFrame):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None
|
||||
):
|
||||
super().__init__(parent)
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
self.onTargetChanged(0)
|
||||
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setFrameShape(QFrame.Shape.StyledPanel)
|
||||
self.setFrameShadow(QFrame.Shadow.Raised)
|
||||
self.setFixedHeight(35)
|
||||
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(2, 2, 2, 2)
|
||||
layout.setSpacing(4)
|
||||
|
||||
self.targetCombo = _makeSetVarCombo()
|
||||
self.valueWidgetStack = QStackedWidget()
|
||||
self.valueWidgetStack.setFixedHeight(25)
|
||||
self.initValueStack()
|
||||
|
||||
setLabel = QLabel("设置")
|
||||
setLabel.setFixedHeight(25)
|
||||
layout.addWidget(setLabel)
|
||||
layout.addWidget(self.targetCombo)
|
||||
toLabel = QLabel("为")
|
||||
toLabel.setFixedHeight(25)
|
||||
layout.addWidget(toLabel)
|
||||
layout.addWidget(self.valueWidgetStack)
|
||||
|
||||
self.deleteBtn = QPushButton("×")
|
||||
self.deleteBtn.setFixedSize(24, 25)
|
||||
self.deleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||
layout.addWidget(self.deleteBtn)
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.targetCombo.currentIndexChanged.connect(self.onTargetChanged)
|
||||
|
||||
|
||||
def initValueStack(
|
||||
self
|
||||
):
|
||||
|
||||
self._valueWidgets = {}
|
||||
for _, _, vartype in _VAR_COMBO_ITEMS:
|
||||
if vartype not in self._valueWidgets:
|
||||
w = _makeActionValueWidget(vartype)
|
||||
self._valueWidgets[vartype] = w
|
||||
self.valueWidgetStack.addWidget(w)
|
||||
self.valueWidgetStack.setCurrentWidget(
|
||||
self._valueWidgets.get("String", self.valueWidgetStack.widget(0))
|
||||
)
|
||||
|
||||
|
||||
def getTarget(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
data = self.targetCombo.currentData()
|
||||
return data[0] if data else ""
|
||||
|
||||
|
||||
def getTargetType(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
data = self.targetCombo.currentData()
|
||||
return data[1] if data else "String"
|
||||
|
||||
|
||||
def getValueRaw(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
currentType = self.getTargetType()
|
||||
w = self._valueWidgets.get(currentType)
|
||||
if w:
|
||||
return _getValueFromWidget(w)
|
||||
return ""
|
||||
|
||||
|
||||
def toScriptLine(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
target = self.getTarget()
|
||||
if not target:
|
||||
return ""
|
||||
rawVal = self.getValueRaw()
|
||||
targetType = self.getTargetType()
|
||||
encoded = _encodeValueStr(rawVal, targetType)
|
||||
if targetType == "Time" and rawVal.startswith("+"):
|
||||
hours = rawVal[1:]
|
||||
return f" {target} .ADD. {hours}"
|
||||
return f" SET {target} = {encoded}"
|
||||
|
||||
|
||||
def loadFromScript(
|
||||
self,
|
||||
targetVar: str,
|
||||
valueExpr: str
|
||||
):
|
||||
|
||||
for idx in range(self.targetCombo.count()):
|
||||
data = self.targetCombo.itemData(idx)
|
||||
if data and data[0] == targetVar:
|
||||
self.targetCombo.setCurrentIndex(idx)
|
||||
break
|
||||
self.setValueFromExpr(valueExpr)
|
||||
|
||||
|
||||
def setValueFromExpr(
|
||||
self,
|
||||
expr: str
|
||||
):
|
||||
|
||||
targetType = self.getTargetType()
|
||||
w = self._valueWidgets.get(targetType)
|
||||
if not w:
|
||||
return
|
||||
_setWidgetValue(w, targetType, expr)
|
||||
|
||||
@Slot(int)
|
||||
def onTargetChanged(
|
||||
self,
|
||||
idx
|
||||
):
|
||||
if idx < 0:
|
||||
return
|
||||
data = self.targetCombo.itemData(idx)
|
||||
if data:
|
||||
_, vartype = data
|
||||
w = self._valueWidgets.get(vartype)
|
||||
if w:
|
||||
self.valueWidgetStack.setCurrentWidget(w)
|
||||
|
||||
|
||||
class ConditionalBlock(QGroupBox):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
blockIndex: int,
|
||||
parent=None
|
||||
):
|
||||
super().__init__(parent)
|
||||
|
||||
self.blockIndex = blockIndex
|
||||
self._actionWidgets = []
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
self.onOperandChanged(0)
|
||||
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setStyleSheet(
|
||||
"QGroupBox { font-weight: bold; border: 1px solid #ccc; "
|
||||
"margin-top: 5px; padding-top: 5px; }"
|
||||
)
|
||||
self.setSizePolicy(
|
||||
QSizePolicy.Policy.Preferred,
|
||||
QSizePolicy.Policy.Fixed
|
||||
)
|
||||
|
||||
mainLayout = QVBoxLayout(self)
|
||||
mainLayout.setSpacing(4)
|
||||
mainLayout.setContentsMargins(5, 5, 5, 5)
|
||||
|
||||
headerLayout = QHBoxLayout()
|
||||
self.typeCombo = QComboBox()
|
||||
self.typeCombo.addItem("IF", "IF")
|
||||
self.typeCombo.addItem("ELSE IF", "ELSE IF")
|
||||
self.typeCombo.addItem("ELSE", "ELSE")
|
||||
if self.blockIndex == 0:
|
||||
self.typeCombo.setEnabled(False)
|
||||
typeLabel = QLabel("类型:")
|
||||
typeLabel.setFixedHeight(25)
|
||||
headerLayout.addWidget(typeLabel)
|
||||
headerLayout.addWidget(self.typeCombo)
|
||||
headerLayout.addStretch()
|
||||
self.deleteBlockBtn = QPushButton("删除此块")
|
||||
self.deleteBlockBtn.setStyleSheet("color: red;")
|
||||
self.deleteBlockBtn.setFixedHeight(25)
|
||||
headerLayout.addWidget(self.deleteBlockBtn)
|
||||
mainLayout.addLayout(headerLayout)
|
||||
|
||||
self.conditionWidget = QWidget()
|
||||
self.conditionWidget.setFixedHeight(60)
|
||||
condLayout = QHBoxLayout(self.conditionWidget)
|
||||
condLayout.setContentsMargins(0, 0, 0, 0)
|
||||
ifLabel = QLabel("如果")
|
||||
ifLabel.setFixedHeight(25)
|
||||
condLayout.addWidget(ifLabel)
|
||||
self.operandCombo = _makeVarCombo()
|
||||
condLayout.addWidget(self.operandCombo)
|
||||
self.opCombo = _makeOpCombo()
|
||||
condLayout.addWidget(self.opCombo)
|
||||
|
||||
self.condValueStack = QStackedWidget()
|
||||
self.condValueStack.setFixedHeight(25)
|
||||
self._condValueWidgets = {}
|
||||
for vartype in ["Time", "Date", "String", "Integer", "Float", "Boolean"]:
|
||||
w = _makeValueWidget(vartype)
|
||||
self._condValueWidgets[vartype] = w
|
||||
self.condValueStack.addWidget(w)
|
||||
self.condValueStack.setCurrentWidget(self._condValueWidgets.get("String"))
|
||||
condLayout.addWidget(self.condValueStack)
|
||||
mainLayout.addWidget(self.conditionWidget)
|
||||
|
||||
self.actionLabel = QLabel("执行步骤:")
|
||||
self.actionLabel.setFixedHeight(25)
|
||||
mainLayout.addWidget(self.actionLabel)
|
||||
|
||||
self.actionsLayout = QVBoxLayout()
|
||||
self.actionsLayout.setSpacing(2)
|
||||
mainLayout.addLayout(self.actionsLayout)
|
||||
|
||||
self.addActionBtn = QPushButton("+ 添加执行步骤")
|
||||
self.addActionBtn.setFixedHeight(25)
|
||||
mainLayout.addWidget(self.addActionBtn)
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.operandCombo.currentIndexChanged.connect(self.onOperandChanged)
|
||||
self.typeCombo.currentIndexChanged.connect(self.onTypeChanged)
|
||||
self.addActionBtn.clicked.connect(self.addActionStep)
|
||||
|
||||
|
||||
def removeActionStep(
|
||||
self,
|
||||
step: ActionStepFrame
|
||||
):
|
||||
|
||||
if step in self._actionWidgets:
|
||||
self._actionWidgets.remove(step)
|
||||
self.actionsLayout.removeWidget(step)
|
||||
step.hide()
|
||||
step.deleteLater()
|
||||
|
||||
|
||||
def getBlockType(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self.typeCombo.currentData()
|
||||
|
||||
|
||||
def toScriptLines(
|
||||
self
|
||||
) -> list:
|
||||
|
||||
blockType = self.getBlockType()
|
||||
lines = []
|
||||
|
||||
if blockType in ("IF", "ELSE IF"):
|
||||
operand = self.operandCombo.currentData()
|
||||
operandName = operand[0] if operand else ""
|
||||
operandType = operand[1] if operand else "String"
|
||||
opSym = self.opCombo.currentData()
|
||||
rawVal = _getValueFromWidget(
|
||||
self._condValueWidgets.get(operandType, QLineEdit())
|
||||
)
|
||||
encodedVal = _encodeValueStr(rawVal, operandType)
|
||||
if blockType == "IF":
|
||||
lines.append(f"IF({operandName} {opSym} {encodedVal}) THEN")
|
||||
else:
|
||||
lines.append(f"ELSE IF({operandName} {opSym} {encodedVal}) THEN")
|
||||
else:
|
||||
lines.append("ELSE")
|
||||
for step in self._actionWidgets:
|
||||
scriptLine = step.toScriptLine()
|
||||
if scriptLine:
|
||||
lines.append(scriptLine)
|
||||
|
||||
return lines
|
||||
|
||||
|
||||
def getConditionSummary(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
bt = self.getBlockType()
|
||||
if bt == "ELSE":
|
||||
return "ELSE"
|
||||
operandData = self.operandCombo.currentData()
|
||||
if not operandData:
|
||||
return bt
|
||||
operandDisplay = self.operandCombo.currentText()
|
||||
opDisplay = self.opCombo.currentText()
|
||||
rawVal = self.getConditionRawValuePreview()
|
||||
return f"{bt} ({operandDisplay} {opDisplay} {rawVal})"
|
||||
|
||||
|
||||
def getConditionRawValuePreview(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
data = self.operandCombo.currentData()
|
||||
if not data:
|
||||
return ""
|
||||
_, vartype = data
|
||||
w = self._condValueWidgets.get(vartype)
|
||||
if w:
|
||||
return _getValueFromWidget(w)
|
||||
return ""
|
||||
|
||||
|
||||
def countActionSteps(
|
||||
self
|
||||
) -> int:
|
||||
|
||||
return len(self._actionWidgets)
|
||||
|
||||
@Slot(int)
|
||||
def onOperandChanged(
|
||||
self,
|
||||
idx
|
||||
):
|
||||
if idx < 0:
|
||||
return
|
||||
data = self.operandCombo.itemData(idx)
|
||||
if data:
|
||||
_, vartype = data
|
||||
w = self._condValueWidgets.get(vartype)
|
||||
if w:
|
||||
self.condValueStack.setCurrentWidget(w)
|
||||
|
||||
@Slot(int)
|
||||
def onTypeChanged(
|
||||
self,
|
||||
idx
|
||||
):
|
||||
isCond = self.typeCombo.currentData() in ("IF", "ELSE IF")
|
||||
self.conditionWidget.setVisible(isCond)
|
||||
self.actionLabel.setText("执行步骤:" if isCond else "ELSE 执行步骤:")
|
||||
|
||||
@Slot()
|
||||
def addActionStep(
|
||||
self
|
||||
):
|
||||
|
||||
step = ActionStepFrame(self)
|
||||
step.deleteBtn.clicked.connect(lambda: self.removeActionStep(step))
|
||||
self._actionWidgets.append(step)
|
||||
self.actionsLayout.addWidget(step)
|
||||
|
||||
|
||||
class ALAutoScriptOrchDialog(QDialog):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
existingScript: str = ""
|
||||
):
|
||||
super().__init__(parent)
|
||||
self._blocks: list[ConditionalBlock] = []
|
||||
|
||||
self.modifyUi()
|
||||
self.connectSignals()
|
||||
|
||||
if existingScript and existingScript.strip():
|
||||
self.loadFromScript(existingScript)
|
||||
else:
|
||||
self.addBlock()
|
||||
self._scrollLayout.addStretch()
|
||||
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setWindowTitle("AutoScript 指令编排 - AutoLibrary")
|
||||
self.setMinimumSize(420, 400)
|
||||
self.setModal(True)
|
||||
mainLayout = QVBoxLayout(self)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setFrameShape(QFrame.Shape.NoFrame)
|
||||
scrollContent = QWidget()
|
||||
self._scrollLayout = QVBoxLayout(scrollContent)
|
||||
self._scrollLayout.setSpacing(5)
|
||||
scroll.setWidget(scrollContent)
|
||||
mainLayout.addWidget(scroll)
|
||||
addBlockLayout = QHBoxLayout()
|
||||
self.addBlockBtn = QPushButton("+ 添加判断块")
|
||||
self.addBlockBtn.setFixedHeight(25)
|
||||
addBlockLayout.addStretch()
|
||||
addBlockLayout.addWidget(self.addBlockBtn)
|
||||
addBlockLayout.addStretch()
|
||||
mainLayout.addLayout(addBlockLayout)
|
||||
self.btnBox = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok |
|
||||
QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
self.btnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.btnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
mainLayout.addWidget(self.btnBox)
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.btnBox.accepted.connect(self.accept)
|
||||
self.btnBox.rejected.connect(self.reject)
|
||||
self.addBlockBtn.clicked.connect(self.addBlock)
|
||||
|
||||
|
||||
def removeBlock(
|
||||
self,
|
||||
block: ConditionalBlock
|
||||
):
|
||||
|
||||
if block in self._blocks:
|
||||
self._blocks.remove(block)
|
||||
self._scrollLayout.removeWidget(block)
|
||||
block.hide()
|
||||
block.deleteLater()
|
||||
|
||||
|
||||
def getScript(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
parts = []
|
||||
for i, block in enumerate(self._blocks):
|
||||
blockType = block.getBlockType()
|
||||
if blockType == "IF" and i > 0:
|
||||
parts.append("ENDIF")
|
||||
lines = block.toScriptLines()
|
||||
parts.extend(lines)
|
||||
if self._blocks and self._blocks[0].getBlockType() == "IF":
|
||||
parts.append("ENDIF")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def getScriptPreview(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
s = self.getScript()
|
||||
if len(s) > 10:
|
||||
return s[:7] + "..."
|
||||
return s
|
||||
|
||||
|
||||
def loadFromScript(
|
||||
self,
|
||||
script: str
|
||||
):
|
||||
|
||||
import re
|
||||
lines = [l.strip() for l in script.split("\n") if l.strip()]
|
||||
if not lines:
|
||||
self.addBlock()
|
||||
return
|
||||
|
||||
currentBlock = None
|
||||
currentBlockType = None
|
||||
actionsBuffer = []
|
||||
|
||||
def flushBlock():
|
||||
nonlocal currentBlock, currentBlockType, actionsBuffer
|
||||
if currentBlock is None:
|
||||
return
|
||||
typeIdxMap = {"IF": 0, "ELSE IF": 1, "ELSE": 2}
|
||||
idx = typeIdxMap.get(currentBlockType, 0)
|
||||
currentBlock.typeCombo.setCurrentIndex(idx)
|
||||
currentBlock.onTypeChanged(idx)
|
||||
for oldStep in list(currentBlock._actionWidgets):
|
||||
currentBlock.removeActionStep(oldStep)
|
||||
for target, valueExpr in actionsBuffer:
|
||||
currentBlock.addActionStep()
|
||||
step = currentBlock._actionWidgets[-1]
|
||||
step.loadFromScript(target, valueExpr)
|
||||
self._blocks.clear()
|
||||
while self._scrollLayout.count():
|
||||
item = self._scrollLayout.takeAt(0)
|
||||
if item.widget():
|
||||
item.widget().deleteLater()
|
||||
for line in lines:
|
||||
upper = line.upper()
|
||||
ifMatch = re.match(r"^IF\((.+)\)\s*THEN\s*$", upper)
|
||||
if ifMatch:
|
||||
flushBlock()
|
||||
currentBlockType = "IF"
|
||||
actionsBuffer = []
|
||||
self.addBlock()
|
||||
currentBlock = self._blocks[-1]
|
||||
self.parseConditionToBlock(currentBlock, ifMatch.group(1))
|
||||
continue
|
||||
elifIfMatch = re.match(r"^ELSE\s+IF\((.+)\)\s*THEN\s*$", upper)
|
||||
if elifIfMatch:
|
||||
flushBlock()
|
||||
currentBlockType = "ELSE IF"
|
||||
actionsBuffer = []
|
||||
self.addBlock()
|
||||
currentBlock = self._blocks[-1]
|
||||
self.parseConditionToBlock(currentBlock, elifIfMatch.group(1))
|
||||
continue
|
||||
if upper == "ELSE":
|
||||
flushBlock()
|
||||
currentBlockType = "ELSE"
|
||||
actionsBuffer = []
|
||||
self.addBlock()
|
||||
currentBlock = self._blocks[-1]
|
||||
currentBlock.conditionWidget.setVisible(False)
|
||||
continue
|
||||
setMatch = re.match(r"^SET\s+(\w+)\s*=\s*(.+)$", line, re.IGNORECASE)
|
||||
if setMatch:
|
||||
target = setMatch.group(1).strip()
|
||||
valueExpr = setMatch.group(2).strip()
|
||||
actionsBuffer.append((target, valueExpr))
|
||||
continue
|
||||
addMatch = re.match(r"^(\w+)\s+\.ADD\.\s+(\d+)$", line, re.IGNORECASE)
|
||||
if addMatch:
|
||||
target = addMatch.group(1).strip()
|
||||
hours = addMatch.group(2).strip()
|
||||
actionsBuffer.append((target, f"+{hours}"))
|
||||
continue
|
||||
if upper in ("ENDIF", "END IF"):
|
||||
flushBlock()
|
||||
currentBlock = None
|
||||
currentBlockType = None
|
||||
actionsBuffer = []
|
||||
continue
|
||||
flushBlock()
|
||||
if not self._blocks:
|
||||
self.addBlock()
|
||||
|
||||
|
||||
def parseConditionToBlock(
|
||||
self,
|
||||
block: ConditionalBlock,
|
||||
condStr: str
|
||||
):
|
||||
|
||||
condStr = condStr.strip()
|
||||
for _, opSym in OP_ITEMS:
|
||||
idx = condStr.upper().find(opSym)
|
||||
if idx >= 0:
|
||||
leftPart = condStr[:idx].strip()
|
||||
rightPart = condStr[idx + len(opSym):].strip()
|
||||
for ci in range(block.operandCombo.count()):
|
||||
data = block.operandCombo.itemData(ci)
|
||||
if data and data[0] == leftPart:
|
||||
block.operandCombo.setCurrentIndex(ci)
|
||||
break
|
||||
for oi in range(block.opCombo.count()):
|
||||
if block.opCombo.itemData(oi) == opSym:
|
||||
block.opCombo.setCurrentIndex(oi)
|
||||
break
|
||||
opData = block.operandCombo.currentData()
|
||||
vartype = opData[1] if opData else "String"
|
||||
w = block._condValueWidgets.get(vartype)
|
||||
if w:
|
||||
_setWidgetValue(w, vartype, rightPart)
|
||||
return
|
||||
|
||||
@Slot()
|
||||
def addBlock(
|
||||
self
|
||||
):
|
||||
|
||||
block = ConditionalBlock(len(self._blocks), self)
|
||||
block.deleteBlockBtn.clicked.connect(lambda: self.removeBlock(block))
|
||||
self._blocks.append(block)
|
||||
block.addActionStep()
|
||||
if self._scrollLayout.count() > 0:
|
||||
lastItem = self._scrollLayout.itemAt(
|
||||
self._scrollLayout.count() - 1
|
||||
)
|
||||
if lastItem and lastItem.spacerItem():
|
||||
self._scrollLayout.insertWidget(
|
||||
self._scrollLayout.count() - 1, block
|
||||
)
|
||||
return
|
||||
self._scrollLayout.addWidget(block)
|
||||
@@ -0,0 +1,10 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from ._dialog import ALAutoScriptOrchDialog
|
||||
@@ -0,0 +1,269 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
"""
|
||||
Conditional block widget for the AutoScript orchestration dialog.
|
||||
"""
|
||||
from PySide6.QtCore import Slot
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QGroupBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QSizePolicy,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from gui.ALAutoScriptOrchDialog._widgets import (
|
||||
ActionStepFrame,
|
||||
ConditionRowFrame,
|
||||
)
|
||||
|
||||
|
||||
class ConditionalBlock(QGroupBox):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
block_index: int,
|
||||
var_mgr = None,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._block_index = block_index
|
||||
self._var_mgr = var_mgr
|
||||
self._action_widgets = []
|
||||
self._condition_rows = []
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
self.addInitialConditionRow()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setUpdatesEnabled(False)
|
||||
self.setStyleSheet(
|
||||
"QGroupBox { "\
|
||||
"font-weight: bold;"\
|
||||
"border: 1px solid #ccc;"\
|
||||
"margin-top: 5px;"\
|
||||
"padding-top: 5px; "\
|
||||
"}"
|
||||
)
|
||||
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
|
||||
MainLayout = QVBoxLayout(self)
|
||||
MainLayout.setSpacing(6)
|
||||
MainLayout.setContentsMargins(8, 8, 8, 8)
|
||||
HeaderLayout = QHBoxLayout()
|
||||
HeaderLayout.setSpacing(8)
|
||||
self.TypeCombo = QComboBox(self)
|
||||
self.TypeCombo.addItem("IF", "IF")
|
||||
self.TypeCombo.addItem("ELSE IF", "ELSE IF")
|
||||
self.TypeCombo.addItem("ELSE", "ELSE")
|
||||
self.TypeCombo.setFixedHeight(25)
|
||||
if self._block_index == 0:
|
||||
self.TypeCombo.setEnabled(False)
|
||||
HeaderLayout.addWidget(QLabel("类型:", self))
|
||||
HeaderLayout.addWidget(self.TypeCombo)
|
||||
HeaderLayout.addStretch()
|
||||
self.DeleteBlockBtn = QPushButton("删除此块", self)
|
||||
self.DeleteBlockBtn.setStyleSheet("color: red;")
|
||||
self.DeleteBlockBtn.setFixedHeight(25)
|
||||
HeaderLayout.addWidget(self.DeleteBlockBtn)
|
||||
MainLayout.addLayout(HeaderLayout)
|
||||
self.ConditionWidget = QWidget(self)
|
||||
self.ConditionWidget.setSizePolicy(
|
||||
QSizePolicy.Preferred, QSizePolicy.Preferred
|
||||
)
|
||||
CondLayout = QVBoxLayout(self.ConditionWidget)
|
||||
CondLayout.setContentsMargins(4, 4, 4, 4)
|
||||
CondLayout.setSpacing(6)
|
||||
self.CondRowsLayout = QVBoxLayout()
|
||||
self.CondRowsLayout.setSpacing(4)
|
||||
CondLayout.addLayout(self.CondRowsLayout)
|
||||
self.AddCondBtn = QPushButton("+ 添加条件", self.ConditionWidget)
|
||||
self.AddCondBtn.setFixedHeight(25)
|
||||
CondLayout.addWidget(self.AddCondBtn)
|
||||
MainLayout.addWidget(self.ConditionWidget)
|
||||
self.ActionLabel = QLabel("执行步骤:", self)
|
||||
self.ActionLabel.setFixedHeight(25)
|
||||
MainLayout.addWidget(self.ActionLabel)
|
||||
self.ActionsLayout = QVBoxLayout()
|
||||
self.ActionsLayout.setSpacing(4)
|
||||
MainLayout.addLayout(self.ActionsLayout)
|
||||
self.AddActionBtn = QPushButton("+ 添加执行步骤", self)
|
||||
self.AddActionBtn.setFixedHeight(25)
|
||||
MainLayout.addWidget(self.AddActionBtn)
|
||||
self.setUpdatesEnabled(True)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.TypeCombo.currentIndexChanged.connect(self.onTypeChanged)
|
||||
self.AddCondBtn.clicked.connect(self.addConditionRow)
|
||||
self.AddActionBtn.clicked.connect(self.addActionStep)
|
||||
|
||||
def addInitialConditionRow(
|
||||
self
|
||||
):
|
||||
|
||||
Row = ConditionRowFrame(
|
||||
self._var_mgr, self._block_index,
|
||||
is_first=True, parent=self
|
||||
)
|
||||
self._condition_rows.append(Row)
|
||||
self.CondRowsLayout.addWidget(Row)
|
||||
|
||||
def addConditionRow(
|
||||
self
|
||||
):
|
||||
|
||||
Row = ConditionRowFrame(
|
||||
self._var_mgr, self._block_index,
|
||||
is_first=False, parent=self
|
||||
)
|
||||
Row.DeleteBtn.clicked.connect(lambda: self.removeConditionRow(Row))
|
||||
self._condition_rows.append(Row)
|
||||
self.CondRowsLayout.addWidget(Row)
|
||||
|
||||
def removeConditionRow(
|
||||
self,
|
||||
row: ConditionRowFrame
|
||||
):
|
||||
|
||||
if row in self._condition_rows and len(self._condition_rows) > 1:
|
||||
self._condition_rows.remove(row)
|
||||
self.CondRowsLayout.removeWidget(row)
|
||||
row.hide()
|
||||
row.deleteLater()
|
||||
|
||||
def addActionStep(
|
||||
self
|
||||
):
|
||||
|
||||
Step = ActionStepFrame(self._var_mgr, self._block_index, parent=self)
|
||||
Step.DeleteBtn.clicked.connect(lambda: self.removeActionStep(Step))
|
||||
self._action_widgets.append(Step)
|
||||
self.ActionsLayout.addWidget(Step)
|
||||
|
||||
def removeActionStep(
|
||||
self,
|
||||
step: ActionStepFrame
|
||||
):
|
||||
|
||||
if step in self._action_widgets:
|
||||
self._action_widgets.remove(step)
|
||||
self.ActionsLayout.removeWidget(step)
|
||||
step.hide()
|
||||
step.deleteLater()
|
||||
|
||||
def getBlockType(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self.TypeCombo.currentData()
|
||||
|
||||
def getConditionRows(
|
||||
self
|
||||
):
|
||||
|
||||
return list(self._condition_rows)
|
||||
|
||||
def getActionSteps(
|
||||
self
|
||||
):
|
||||
|
||||
return list(self._action_widgets)
|
||||
|
||||
def countActionSteps(
|
||||
self
|
||||
) -> int:
|
||||
|
||||
return len(self._action_widgets)
|
||||
|
||||
def toScript(
|
||||
self
|
||||
) -> list:
|
||||
"""
|
||||
Generate Lua script lines for this conditional block.
|
||||
"""
|
||||
|
||||
block_type = self.getBlockType()
|
||||
lines = []
|
||||
if block_type in ("IF", "ELSE IF"):
|
||||
cond_texts = [
|
||||
r.toScript() for r in self._condition_rows if r.toScript()
|
||||
]
|
||||
if not cond_texts:
|
||||
cond_texts = ["true"]
|
||||
if len(cond_texts) == 1:
|
||||
combined = cond_texts[0]
|
||||
else:
|
||||
parts = []
|
||||
for i, ct in enumerate(cond_texts):
|
||||
if i > 0:
|
||||
logic = self._condition_rows[i].getLogic() or "and"
|
||||
parts.append(f" {logic} ")
|
||||
parts.append(f"({ct})")
|
||||
combined = "".join(parts)
|
||||
if block_type == "IF":
|
||||
lines.append(f"if {combined} then")
|
||||
else:
|
||||
lines.append(f"elseif {combined} then")
|
||||
else:
|
||||
lines.append("else")
|
||||
for step in self._action_widgets:
|
||||
script_line = step.toScript()
|
||||
if script_line:
|
||||
lines.append(script_line)
|
||||
return lines
|
||||
|
||||
def refreshVarCombos(
|
||||
self
|
||||
):
|
||||
|
||||
for row in self._condition_rows:
|
||||
row.refreshVarCombos()
|
||||
for step in self._action_widgets:
|
||||
step.refreshVarCombos()
|
||||
|
||||
def setPrevBlockType(
|
||||
self,
|
||||
prev_type: str | None
|
||||
):
|
||||
|
||||
model = self.TypeCombo.model()
|
||||
if model is None:
|
||||
return
|
||||
for data in ("ELSE IF", "ELSE"):
|
||||
idx = self.TypeCombo.findData(data)
|
||||
if idx < 0:
|
||||
continue
|
||||
item = model.item(idx)
|
||||
should_enable = prev_type != "ELSE"
|
||||
item.setEnabled(should_enable)
|
||||
if prev_type == "ELSE" and self.TypeCombo.currentData() in ("ELSE IF", "ELSE"):
|
||||
self.TypeCombo.setCurrentIndex(0)
|
||||
|
||||
@Slot(int)
|
||||
def onTypeChanged(
|
||||
self,
|
||||
idx: int
|
||||
):
|
||||
|
||||
is_cond = self.TypeCombo.currentData() in ("IF", "ELSE IF")
|
||||
self.ConditionWidget.setVisible(is_cond)
|
||||
self.ActionLabel.setText(
|
||||
"执行步骤:" if is_cond else "ELSE 执行步骤:"
|
||||
)
|
||||
@@ -0,0 +1,164 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
"""
|
||||
Orchestration dialog for visually composing AutoScript scripts.
|
||||
"""
|
||||
from PySide6.QtCore import Slot
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QFrame,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QScrollArea,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from gui.ALAutoScriptOrchDialog._helpers import VariableManager
|
||||
from gui.ALAutoScriptOrchDialog._blocks import ConditionalBlock
|
||||
|
||||
|
||||
class ALAutoScriptOrchDialog(QDialog):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._blocks = []
|
||||
self._var_mgr = VariableManager(self)
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
self.addBlock()
|
||||
self.ScrollLayout.addStretch()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setWindowTitle("AutoScript 指令编排 - AutoLibrary")
|
||||
self.setMinimumSize(640, 600)
|
||||
self.setModal(True)
|
||||
MainLayout = QVBoxLayout(self)
|
||||
Scroll = QScrollArea()
|
||||
Scroll.setWidgetResizable(True)
|
||||
Scroll.setFrameShape(QFrame.NoFrame)
|
||||
ScrollContent = QWidget()
|
||||
self.ScrollLayout = QVBoxLayout(ScrollContent)
|
||||
self.ScrollLayout.setSpacing(5)
|
||||
Scroll.setWidget(ScrollContent)
|
||||
MainLayout.addWidget(Scroll)
|
||||
self.AddBlockBtn = QPushButton("+ 添加判断块")
|
||||
self.AddBlockBtn.setFixedHeight(25)
|
||||
MainLayout.addWidget(self.AddBlockBtn)
|
||||
self.BtnBox = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok |
|
||||
QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
MainLayout.addWidget(self.BtnBox)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.BtnBox.accepted.connect(self.onAccept)
|
||||
self.BtnBox.rejected.connect(self.reject)
|
||||
self.AddBlockBtn.clicked.connect(self.addBlock)
|
||||
|
||||
def updateBlockTypeRestrictions(
|
||||
self
|
||||
):
|
||||
|
||||
prevType = None
|
||||
for block in self._blocks:
|
||||
block.setPrevBlockType(prevType)
|
||||
prevType = block.getBlockType()
|
||||
|
||||
def addBlock(
|
||||
self
|
||||
):
|
||||
|
||||
Block = ConditionalBlock(
|
||||
len(self._blocks), self._var_mgr, parent=self
|
||||
)
|
||||
Block.DeleteBlockBtn.clicked.connect(lambda: self.removeBlock(Block))
|
||||
Block.TypeCombo.currentIndexChanged.connect(self.updateBlockTypeRestrictions)
|
||||
Block.addActionStep()
|
||||
self._blocks.append(Block)
|
||||
self.updateBlockTypeRestrictions()
|
||||
if self.ScrollLayout.count() > 0:
|
||||
lastItem = self.ScrollLayout.itemAt(
|
||||
self.ScrollLayout.count() - 1
|
||||
)
|
||||
if lastItem and lastItem.spacerItem():
|
||||
self.ScrollLayout.insertWidget(
|
||||
self.ScrollLayout.count() - 1, Block
|
||||
)
|
||||
return
|
||||
self.ScrollLayout.addWidget(Block)
|
||||
|
||||
def removeBlock(
|
||||
self,
|
||||
block: ConditionalBlock
|
||||
):
|
||||
|
||||
if len(self._blocks) <= 1:
|
||||
QMessageBox.information(self, "提示", "至少保留一个判断块。")
|
||||
return
|
||||
if block in self._blocks:
|
||||
self._blocks.remove(block)
|
||||
self.ScrollLayout.removeWidget(block)
|
||||
block.hide()
|
||||
block.deleteLater()
|
||||
for i, blk in enumerate(self._blocks):
|
||||
blk.blockIndex = i
|
||||
if i == 0:
|
||||
blk.TypeCombo.setEnabled(False)
|
||||
blk.TypeCombo.setCurrentIndex(0)
|
||||
else:
|
||||
blk.TypeCombo.setEnabled(True)
|
||||
blk.refreshVarCombos()
|
||||
self.updateBlockTypeRestrictions()
|
||||
|
||||
def getScript(
|
||||
self
|
||||
) -> str:
|
||||
"""
|
||||
Generate the complete Lua script from all blocks.
|
||||
"""
|
||||
|
||||
parts = []
|
||||
prevType = None
|
||||
for block in self._blocks:
|
||||
blockType = block.getBlockType()
|
||||
if blockType == "IF" and prevType is not None:
|
||||
parts.append("end")
|
||||
lines = block.toScript()
|
||||
parts.extend(lines)
|
||||
prevType = blockType
|
||||
if self._blocks and self._blocks[0].getBlockType() == "IF":
|
||||
parts.append("end")
|
||||
return "\n".join(parts)
|
||||
|
||||
@Slot()
|
||||
def onAccept(
|
||||
self
|
||||
):
|
||||
|
||||
script = self.getScript().strip()
|
||||
if not script:
|
||||
QMessageBox.warning(self, "提示", "脚本内容为空,请添加至少一个操作步骤。")
|
||||
return
|
||||
self.accept()
|
||||
@@ -0,0 +1,535 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
"""
|
||||
Helper utilities and constants for the AutoScript orchestration dialog.
|
||||
"""
|
||||
import re
|
||||
|
||||
from PySide6.QtCore import QObject
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QDateEdit,
|
||||
QDoubleSpinBox,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QSizePolicy,
|
||||
QSpinBox,
|
||||
QStackedWidget,
|
||||
QTimeEdit,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from autoscript import createAllVariablesTable
|
||||
|
||||
VARTYPE_INFOS = [
|
||||
# varType, isArithType
|
||||
("String", False),
|
||||
("Int", True),
|
||||
("Float", True),
|
||||
("Boolean", False),
|
||||
("Date", True),
|
||||
("Time", True),
|
||||
]
|
||||
|
||||
|
||||
def getTypeOrder(
|
||||
) -> list:
|
||||
|
||||
return [t for t, _ in VARTYPE_INFOS]
|
||||
|
||||
def getArithType(
|
||||
var_type: str
|
||||
) -> bool:
|
||||
|
||||
for t, a in VARTYPE_INFOS:
|
||||
if t == var_type:
|
||||
return a
|
||||
|
||||
def getPresetVars(
|
||||
) -> list:
|
||||
|
||||
return [
|
||||
{"name": name.upper(), "type": vtype, "display": display}
|
||||
for display, (name, vtype) in createAllVariablesTable().items()
|
||||
]
|
||||
|
||||
|
||||
COMPARE_OPTIONS = [
|
||||
("等于", "=="),
|
||||
("不等于", "~="),
|
||||
("大于", ">"),
|
||||
("小于", "<"),
|
||||
("大于等于", ">="),
|
||||
("小于等于", "<="),
|
||||
]
|
||||
LOGIC_OPTIONS = [
|
||||
("并且 (and)", "and"),
|
||||
("或者 (or)", "or"),
|
||||
]
|
||||
ACTION_OPTIONS = [
|
||||
("设置为", "set"),
|
||||
("增加", "add"),
|
||||
("减少", "sub"),
|
||||
]
|
||||
DATE_OPTIONS = [
|
||||
("前天", "day_before_yesterday"),
|
||||
("昨天", "yesterday"),
|
||||
("今天", "today"),
|
||||
("明天", "tomorrow"),
|
||||
("后天", "day_after_tomorrow")
|
||||
]
|
||||
DATE_OFFSET_OPTIONS = [
|
||||
("天", "days"),
|
||||
("周", "weeks"),
|
||||
# NOTE: "月" and "年" use fixed day counts (30 / 365), not calendar months/years,
|
||||
# because dateadd() works with second-level offsets (n * 86400).
|
||||
("月", "months"),
|
||||
("年", "years"),
|
||||
]
|
||||
|
||||
|
||||
class _DateInputContainer(QWidget):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(0, 0, 0, 0)
|
||||
Layout.setSpacing(4)
|
||||
self.ModeCombo = QComboBox(self)
|
||||
self.ModeCombo.addItem("相对日期", "relative")
|
||||
self.ModeCombo.addItem("绝对日期", "absolute")
|
||||
self.ModeCombo.setFixedHeight(25)
|
||||
self.Stack = QStackedWidget(self)
|
||||
self.RelCombo = QComboBox(self)
|
||||
for display, data in DATE_OPTIONS:
|
||||
self.RelCombo.addItem(display, data)
|
||||
self.RelCombo.setFixedHeight(25)
|
||||
self.Stack.addWidget(self.RelCombo)
|
||||
self.DateEdit = QDateEdit(self)
|
||||
self.DateEdit.setDisplayFormat("yyyy-MM-dd")
|
||||
self.DateEdit.setCalendarPopup(True)
|
||||
self.DateEdit.setFixedHeight(25)
|
||||
self.Stack.addWidget(self.DateEdit)
|
||||
self.ModeCombo.currentIndexChanged.connect(
|
||||
lambda i: self.Stack.setCurrentIndex(i)
|
||||
)
|
||||
Layout.addWidget(self.ModeCombo)
|
||||
Layout.addWidget(self.Stack)
|
||||
Layout.addStretch()
|
||||
|
||||
def getValue(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
mode = self.ModeCombo.currentData()
|
||||
if mode == "relative":
|
||||
return self.RelCombo.currentText()
|
||||
return self.DateEdit.date().toString("yyyy-MM-dd")
|
||||
|
||||
|
||||
class _TimeInputContainer(QWidget):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.TimeEdit = QTimeEdit(self)
|
||||
self.TimeEdit.setDisplayFormat("HH:mm")
|
||||
self.TimeEdit.setFixedHeight(25)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(0, 0, 0, 0)
|
||||
Layout.addWidget(self.TimeEdit)
|
||||
|
||||
def getValue(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self.TimeEdit.time().toString("HH:mm")
|
||||
|
||||
|
||||
class _DateOffsetContainer(QWidget):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.SpinBox = QSpinBox(self)
|
||||
self.SpinBox.setRange(0, 99999)
|
||||
self.SpinBox.setFixedHeight(25)
|
||||
self.UnitCombo = QComboBox(self)
|
||||
for display, data in DATE_OFFSET_OPTIONS:
|
||||
self.UnitCombo.addItem(display, data)
|
||||
self.UnitCombo.setFixedHeight(25)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(0, 0, 0, 0)
|
||||
Layout.setSpacing(4)
|
||||
Layout.addWidget(self.SpinBox)
|
||||
Layout.addWidget(self.UnitCombo)
|
||||
Layout.addStretch()
|
||||
|
||||
def getValue(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return str(self.getOffsetDays())
|
||||
|
||||
def getOffsetDays(
|
||||
self
|
||||
) -> int:
|
||||
|
||||
val = self.SpinBox.value()
|
||||
unit = self.UnitCombo.currentData()
|
||||
if unit == "weeks":
|
||||
return val*7
|
||||
if unit == "months":
|
||||
return val*30
|
||||
if unit == "years":
|
||||
return val*365
|
||||
return val
|
||||
|
||||
|
||||
class _TimeOffsetContainer(QWidget):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.SpinBox = QSpinBox(self)
|
||||
self.SpinBox.setRange(0, 99999)
|
||||
self.SpinBox.setSuffix(" 小时")
|
||||
self.SpinBox.setFixedHeight(25)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(0, 0, 0, 0)
|
||||
Layout.addWidget(self.SpinBox)
|
||||
|
||||
def getValue(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return str(self.getOffsetHours())
|
||||
|
||||
def getOffsetHours(
|
||||
self
|
||||
) -> int:
|
||||
|
||||
return self.SpinBox.value()
|
||||
|
||||
|
||||
class VariableManager(QObject):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._vars = []
|
||||
self._name_map = {}
|
||||
|
||||
self.initPresetVars()
|
||||
|
||||
def initPresetVars(
|
||||
self
|
||||
):
|
||||
|
||||
for p in getPresetVars():
|
||||
entry = {"name": p["name"], "type": p["type"], "display": p["display"]}
|
||||
self._vars.append(entry)
|
||||
self._name_map[p["name"]] = entry
|
||||
|
||||
def getInfoByName(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
|
||||
return self._name_map.get(name.upper().strip())
|
||||
|
||||
def populateCombo(
|
||||
self,
|
||||
combo: QComboBox
|
||||
):
|
||||
|
||||
current_data = combo.currentData()
|
||||
combo.blockSignals(True)
|
||||
combo.clear()
|
||||
for entry in self._vars:
|
||||
combo.addItem(
|
||||
entry["display"],
|
||||
(entry["name"], entry["type"])
|
||||
)
|
||||
if current_data:
|
||||
for i in range(combo.count()):
|
||||
d = combo.itemData(i)
|
||||
if d and d[0] == current_data[0]:
|
||||
combo.setCurrentIndex(i)
|
||||
break
|
||||
combo.blockSignals(False)
|
||||
|
||||
|
||||
def makeValueWidget(
|
||||
var_type: str,
|
||||
parent: QWidget = None
|
||||
) -> QWidget:
|
||||
|
||||
if var_type == "Int":
|
||||
Widget = QSpinBox(parent)
|
||||
Widget.setRange(-999999, 999999)
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "Float":
|
||||
Widget = QDoubleSpinBox(parent)
|
||||
Widget.setRange(-999999.0, 999999.0)
|
||||
Widget.setDecimals(2)
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "String":
|
||||
Widget = QLineEdit(parent)
|
||||
Widget.setPlaceholderText("输入值")
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(120)
|
||||
return Widget
|
||||
if var_type == "Boolean":
|
||||
Widget = QComboBox(parent)
|
||||
Widget.addItem("是 (true)", "true")
|
||||
Widget.addItem("否 (false)", "false")
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "Date":
|
||||
return _DateInputContainer(parent)
|
||||
if var_type == "Time":
|
||||
return _TimeInputContainer(parent)
|
||||
Widget = QLineEdit(parent)
|
||||
Widget.setPlaceholderText("输入值")
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(120)
|
||||
return Widget
|
||||
|
||||
def makeOffsetWidget(
|
||||
var_type: str,
|
||||
parent: QWidget = None
|
||||
) -> QWidget:
|
||||
|
||||
if var_type == "Int":
|
||||
Widget = QSpinBox(parent)
|
||||
Widget.setRange(-999999, 999999)
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "Float":
|
||||
Widget = QDoubleSpinBox(parent)
|
||||
Widget.setRange(-999999.0, 999999.0)
|
||||
Widget.setDecimals(2)
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "Date":
|
||||
return _DateOffsetContainer(parent)
|
||||
if var_type == "Time":
|
||||
return _TimeOffsetContainer(parent)
|
||||
Widget = QLabel("(不支持该操作)", parent)
|
||||
Widget.setFixedHeight(25)
|
||||
return Widget
|
||||
|
||||
def makeVarRefCombo(
|
||||
parent: QWidget = None
|
||||
) -> QComboBox:
|
||||
|
||||
ComboBox = QComboBox(parent)
|
||||
ComboBox.setFixedHeight(25)
|
||||
ComboBox.setMinimumWidth(120)
|
||||
ComboBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
|
||||
return ComboBox
|
||||
|
||||
def makeComboWidget(
|
||||
items,
|
||||
min_width: int = 80,
|
||||
parent: QWidget = None
|
||||
) -> QComboBox:
|
||||
|
||||
ComboBox = QComboBox(parent)
|
||||
for display, data in items:
|
||||
ComboBox.addItem(display, data)
|
||||
ComboBox.setFixedHeight(25)
|
||||
ComboBox.setMinimumWidth(min_width)
|
||||
return ComboBox
|
||||
|
||||
def makeLabel(
|
||||
text: str,
|
||||
parent: QWidget = None,
|
||||
width: int = None
|
||||
) -> QLabel:
|
||||
|
||||
Label = QLabel(text, parent)
|
||||
Label.setFixedHeight(25)
|
||||
if width:
|
||||
Label.setFixedWidth(width)
|
||||
return Label
|
||||
|
||||
def getValueFromWidget(
|
||||
widget: QWidget
|
||||
) -> str:
|
||||
|
||||
if hasattr(widget, "getValue"):
|
||||
return widget.getValue()
|
||||
if isinstance(widget, QTimeEdit):
|
||||
return widget.time().toString("HH:mm")
|
||||
if isinstance(widget, QDateEdit):
|
||||
return widget.date().toString("yyyy-MM-dd")
|
||||
if isinstance(widget, QComboBox):
|
||||
return widget.currentData() or widget.currentText()
|
||||
if isinstance(widget, QSpinBox):
|
||||
return str(widget.value())
|
||||
if isinstance(widget, QDoubleSpinBox):
|
||||
return str(widget.value())
|
||||
if isinstance(widget, QLineEdit):
|
||||
return widget.text()
|
||||
return ""
|
||||
|
||||
def encodeValueStr(
|
||||
raw_value: str,
|
||||
var_type: str
|
||||
) -> str:
|
||||
"""
|
||||
Encode a raw widget value as a Lua expression.
|
||||
|
||||
Arithmetic expressions (A + B) are passed through for numeric types;
|
||||
Date/Time arithmetic is translated to ``dateadd()`` / ``timeadd()`` calls.
|
||||
"""
|
||||
|
||||
if var_type in ("Date", "Time"):
|
||||
return encodeDateOrTime(str(raw_value), var_type)
|
||||
if isinstance(raw_value, bool):
|
||||
return "true" if raw_value else "false"
|
||||
s = str(raw_value)
|
||||
if isArithExpr(s):
|
||||
return s
|
||||
if var_type == "Boolean":
|
||||
up = s.upper().strip()
|
||||
if up in ("TRUE", "FALSE"):
|
||||
return up.lower()
|
||||
return "true" if raw_value else "false"
|
||||
if var_type == "String":
|
||||
escaped = s.replace("\\", "\\\\").replace('"', '\\"')
|
||||
return f'"{escaped}"'
|
||||
return s
|
||||
|
||||
def encodeDateOrTime(
|
||||
raw_value: str,
|
||||
var_type: str
|
||||
) -> str:
|
||||
"""
|
||||
Translate a date/time widget value into a Lua expression.
|
||||
"""
|
||||
|
||||
s = raw_value.strip()
|
||||
up = s.upper()
|
||||
# Input comes from widget values — single binary expressions only (e.g. "A + 3",
|
||||
# "CURRENT_DATE + 5"). Multi-operator expressions are not produced by the UI.
|
||||
m_arith_spaced = re.match(r'^(.+?)\s+([+-])\s+(.+)$', s)
|
||||
m_arith_nospace = re.match(r'^([A-Za-z_]\w*)([+-])(\d+|[A-Za-z_]\w*)$', s)
|
||||
m_arith = m_arith_spaced or m_arith_nospace
|
||||
if m_arith:
|
||||
left = m_arith.group(1).strip().upper()
|
||||
sign = m_arith.group(2)
|
||||
right = m_arith.group(3).strip()
|
||||
operand = right if sign == "+" else f"-{right}"
|
||||
if left == "CURRENT_DATE":
|
||||
return f"dateadd(datenow(), {operand})"
|
||||
if left == "CURRENT_TIME":
|
||||
return f"timeadd(timenow(), {operand})"
|
||||
if var_type == "Date":
|
||||
return f"dateadd({left}, {operand})"
|
||||
if var_type == "Time":
|
||||
return f"timeadd({left}, {operand})"
|
||||
return f"{left} {sign} {right}"
|
||||
if up == "CURRENT_DATE":
|
||||
return "datenow()"
|
||||
if up == "CURRENT_TIME":
|
||||
return "timenow()"
|
||||
_REL_MAP = {
|
||||
"前天": "dateadd(datenow(), -2)",
|
||||
"昨天": "dateadd(datenow(), -1)",
|
||||
"今天": "datenow()",
|
||||
"明天": "dateadd(datenow(), 1)",
|
||||
"后天": "dateadd(datenow(), 2)",
|
||||
}
|
||||
if s in _REL_MAP:
|
||||
return _REL_MAP[s]
|
||||
if var_type == "Date":
|
||||
m_date = re.match(r"^(\d{4})-(\d{2})-(\d{2})$", s)
|
||||
if m_date:
|
||||
y, m, d = int(m_date.group(1)), int(m_date.group(2)), int(m_date.group(3))
|
||||
return f"date({y}, {m}, {d})"
|
||||
if var_type == "Time":
|
||||
m_time = re.match(r"^(\d{1,2}):(\d{2})$", s)
|
||||
if m_time:
|
||||
h, m = int(m_time.group(1)), int(m_time.group(2))
|
||||
return f"time({h}, {m})"
|
||||
if re.match(r"^[+-]?\d+$", s):
|
||||
return s
|
||||
if re.match(r"^[A-Za-z_]\w*$", s):
|
||||
return s
|
||||
return f'"{s}"'
|
||||
|
||||
# Pre-compiled patterns for detecting arithmetic expressions (A + B / A - B)
|
||||
_RE_ARITH_SPACED = re.compile(r'^(.+?)\s+([+-])\s+(.+)$')
|
||||
_RE_ARITH_NOSPACE = re.compile(r'^([A-Za-z_]\w*)([+-])(\d+|[A-Za-z_]\w*)$')
|
||||
|
||||
def isArithExpr(
|
||||
expr: str
|
||||
) -> bool:
|
||||
"""
|
||||
Return True if expr looks like a two-operand arithmetic expression (A ± B).
|
||||
"""
|
||||
|
||||
s = expr.strip()
|
||||
return bool(_RE_ARITH_SPACED.match(s) or _RE_ARITH_NOSPACE.match(s))
|
||||
@@ -0,0 +1,468 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
"""
|
||||
Widget components for the AutoScript orchestration dialog.
|
||||
"""
|
||||
from PySide6.QtCore import Slot
|
||||
from PySide6.QtWidgets import (
|
||||
QComboBox,
|
||||
QFrame,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QSizePolicy,
|
||||
QStackedWidget
|
||||
)
|
||||
|
||||
from gui.ALAutoScriptOrchDialog._helpers import (
|
||||
ACTION_OPTIONS,
|
||||
COMPARE_OPTIONS,
|
||||
LOGIC_OPTIONS,
|
||||
encodeValueStr,
|
||||
getPresetVars,
|
||||
getTypeOrder,
|
||||
getValueFromWidget,
|
||||
getArithType,
|
||||
makeComboWidget,
|
||||
makeLabel,
|
||||
makeOffsetWidget,
|
||||
makeValueWidget,
|
||||
makeVarRefCombo,
|
||||
)
|
||||
|
||||
|
||||
class ConditionRowFrame(QFrame):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
var_mgr,
|
||||
parent_block_index: int = 0,
|
||||
is_first: bool = False,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._var_mgr = var_mgr
|
||||
self._block_index = parent_block_index
|
||||
self._is_first = is_first
|
||||
self._is_bool_mode = False
|
||||
self._raw_rhs_expr = ""
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setUpdatesEnabled(False)
|
||||
self.setFrameShape(QFrame.StyledPanel)
|
||||
self.setFrameShadow(QFrame.Raised)
|
||||
self.setFixedHeight(32)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(2, 2, 2, 2)
|
||||
Layout.setSpacing(4)
|
||||
if self._is_first:
|
||||
self.LogicCombo = None
|
||||
else:
|
||||
self.LogicCombo = makeComboWidget(LOGIC_OPTIONS, min_width=110, parent=self)
|
||||
Layout.addWidget(self.LogicCombo)
|
||||
self.LeftVarCombo = QComboBox(self)
|
||||
self.LeftVarCombo.setFixedHeight(25)
|
||||
self.LeftVarCombo.setMinimumWidth(120)
|
||||
self.LeftVarCombo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
|
||||
self.populateLeftVarCombo()
|
||||
Layout.addWidget(self.LeftVarCombo)
|
||||
self.OpCombo = makeComboWidget(COMPARE_OPTIONS, min_width=80, parent=self)
|
||||
Layout.addWidget(self.OpCombo)
|
||||
self.CompTypeCombo = makeComboWidget([
|
||||
("特定值", "literal"),
|
||||
("变量", "variable"),
|
||||
], min_width=70, parent=self)
|
||||
Layout.addWidget(self.CompTypeCombo)
|
||||
self.RhsStack = QStackedWidget(self)
|
||||
self.RhsStack.setFixedHeight(25)
|
||||
self.initLiteralStack()
|
||||
self.RhsVarCombo = makeVarRefCombo(self)
|
||||
self.RhsStack.addWidget(self.RhsVarCombo)
|
||||
self.RhsStack.setCurrentIndex(0)
|
||||
Layout.addWidget(self.RhsStack)
|
||||
if not self._is_first:
|
||||
self.DeleteBtn = QPushButton("×", self)
|
||||
self.DeleteBtn.setFixedSize(25, 25)
|
||||
self.DeleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||
Layout.addWidget(self.DeleteBtn)
|
||||
else:
|
||||
self.DeleteBtn = None
|
||||
Layout.addStretch()
|
||||
self.setUpdatesEnabled(True)
|
||||
|
||||
def populateLeftVarCombo(
|
||||
self
|
||||
):
|
||||
|
||||
was_bool = self._is_bool_mode
|
||||
bool_name = None
|
||||
if was_bool:
|
||||
data = self.LeftVarCombo.currentData()
|
||||
if data:
|
||||
bool_name = data[0]
|
||||
self._var_mgr.populateCombo(self.LeftVarCombo)
|
||||
# Append boolean literal sentinels at the end
|
||||
self.LeftVarCombo.insertSeparator(self.LeftVarCombo.count())
|
||||
self.LeftVarCombo.addItem("true", ("true", "Boolean"))
|
||||
self.LeftVarCombo.addItem("false", ("false", "Boolean"))
|
||||
if was_bool and bool_name:
|
||||
for ci in range(self.LeftVarCombo.count()):
|
||||
d = self.LeftVarCombo.itemData(ci)
|
||||
if d and d[0] == bool_name:
|
||||
self.LeftVarCombo.setCurrentIndex(ci)
|
||||
break
|
||||
|
||||
def populateRHSVarCombo(
|
||||
self
|
||||
):
|
||||
|
||||
self._var_mgr.populateCombo(self.RhsVarCombo)
|
||||
|
||||
def initLiteralStack(
|
||||
self
|
||||
):
|
||||
|
||||
self.LiteralStack = QStackedWidget(self)
|
||||
self.LiteralStack.setFixedHeight(25)
|
||||
self.literal_widgets = {}
|
||||
for vt in getTypeOrder():
|
||||
W = makeValueWidget(vt, self.LiteralStack)
|
||||
self.literal_widgets[vt] = W
|
||||
self.LiteralStack.addWidget(W)
|
||||
self.LiteralStack.setCurrentWidget(self.literal_widgets.get("String"))
|
||||
self.RhsStack.addWidget(self.LiteralStack)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.LeftVarCombo.currentIndexChanged.connect(self.onLeftVarChanged)
|
||||
self.CompTypeCombo.currentIndexChanged.connect(self.onCompTypeChanged)
|
||||
|
||||
def getLogic(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self.LogicCombo.currentData() if self.LogicCombo else ""
|
||||
|
||||
def updateRHSLiteralWidget(
|
||||
self,
|
||||
vartype: str
|
||||
):
|
||||
|
||||
if vartype not in self.literal_widgets:
|
||||
vartype = "String"
|
||||
self.LiteralStack.setCurrentWidget(self.literal_widgets[vartype])
|
||||
|
||||
def toScript(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
data = self.LeftVarCombo.currentData()
|
||||
if self._is_bool_mode and data:
|
||||
return data[0]
|
||||
if not data:
|
||||
return ""
|
||||
name, vartype = data
|
||||
# CURRENT_DATE / CURRENT_TIME map to datenow() / timenow()
|
||||
if name == "CURRENT_DATE":
|
||||
name = "datenow()"
|
||||
elif name == "CURRENT_TIME":
|
||||
name = "timenow()"
|
||||
op_sym = self.OpCombo.currentData()
|
||||
if self._raw_rhs_expr:
|
||||
return f"{name} {op_sym} {self._raw_rhs_expr}"
|
||||
is_var_ref = (self.CompTypeCombo.currentData() == "variable")
|
||||
if is_var_ref:
|
||||
rd = self.RhsVarCombo.currentData()
|
||||
if rd:
|
||||
rhs_name = rd[0]
|
||||
if rhs_name == "CURRENT_DATE":
|
||||
rhs_name = "datenow()"
|
||||
elif rhs_name == "CURRENT_TIME":
|
||||
rhs_name = "timenow()"
|
||||
return f"{name} {op_sym} {rhs_name}"
|
||||
rhs_text = self.RhsVarCombo.currentText().strip()
|
||||
if rhs_text:
|
||||
return f"{name} {op_sym} {rhs_text}"
|
||||
return ""
|
||||
w = self.literal_widgets.get(vartype)
|
||||
if w:
|
||||
raw_val = getValueFromWidget(w)
|
||||
encoded = encodeValueStr(raw_val, vartype)
|
||||
return f"{name} {op_sym} {encoded}"
|
||||
return ""
|
||||
|
||||
def refreshVarCombos(
|
||||
self
|
||||
):
|
||||
|
||||
self.populateLeftVarCombo()
|
||||
self.populateRHSVarCombo()
|
||||
|
||||
@Slot(int)
|
||||
def onLeftVarChanged(
|
||||
self,
|
||||
idx
|
||||
):
|
||||
|
||||
self._raw_rhs_expr = ""
|
||||
if idx < 0:
|
||||
return
|
||||
data = self.LeftVarCombo.itemData(idx)
|
||||
if not data:
|
||||
return
|
||||
name, vartype = data
|
||||
is_bool = name in ("true", "false")
|
||||
self._is_bool_mode = is_bool
|
||||
self.OpCombo.setVisible(not is_bool)
|
||||
self.CompTypeCombo.setVisible(not is_bool)
|
||||
self.RhsStack.setVisible(not is_bool)
|
||||
if not is_bool:
|
||||
self.updateRHSLiteralWidget(vartype)
|
||||
|
||||
@Slot(int)
|
||||
def onCompTypeChanged(
|
||||
self,
|
||||
idx
|
||||
):
|
||||
|
||||
self._raw_rhs_expr = ""
|
||||
isVar = (self.CompTypeCombo.currentData() == "variable")
|
||||
self.RhsStack.setCurrentIndex(1 if isVar else 0)
|
||||
if isVar:
|
||||
self.populateRHSVarCombo()
|
||||
|
||||
|
||||
class ActionStepFrame(QFrame):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
var_mgr,
|
||||
parent_block_index: int = 0,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._var_mgr = var_mgr
|
||||
self._block_index = parent_block_index
|
||||
self._current_target_type = "String"
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setUpdatesEnabled(False)
|
||||
self.setFrameShape(QFrame.StyledPanel)
|
||||
self.setFrameShadow(QFrame.Raised)
|
||||
self.setFixedHeight(35)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(2, 2, 2, 2)
|
||||
Layout.setSpacing(4)
|
||||
self.OpTypeCombo = makeComboWidget(ACTION_OPTIONS, min_width=70, parent=self)
|
||||
Layout.addWidget(self.OpTypeCombo)
|
||||
Layout.addWidget(makeLabel("设置", self))
|
||||
self.TargetCombo = QComboBox(self)
|
||||
self.TargetCombo.setFixedHeight(25)
|
||||
self.TargetCombo.setMinimumWidth(120)
|
||||
self.populateTargetCombo()
|
||||
Layout.addWidget(self.TargetCombo)
|
||||
Layout.addWidget(makeLabel("为", self))
|
||||
self.ValueSrcCombo = makeComboWidget([
|
||||
("特定值", "literal"),
|
||||
("变量", "variable"),
|
||||
], min_width=70, parent=self)
|
||||
Layout.addWidget(self.ValueSrcCombo)
|
||||
self.ValueStack = QStackedWidget(self)
|
||||
self.ValueStack.setFixedHeight(25)
|
||||
self.initValueStacks()
|
||||
Layout.addWidget(self.ValueStack)
|
||||
self.ExistingVarCombo = makeVarRefCombo(self)
|
||||
self.ExistingVarCombo.setVisible(False)
|
||||
Layout.addWidget(self.ExistingVarCombo)
|
||||
self.DeleteBtn = QPushButton("×", self)
|
||||
self.DeleteBtn.setFixedSize(25, 25)
|
||||
self.DeleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||
Layout.addWidget(self.DeleteBtn)
|
||||
self.setUpdatesEnabled(True)
|
||||
|
||||
def populateTargetCombo(
|
||||
self
|
||||
):
|
||||
|
||||
self.TargetCombo.blockSignals(True)
|
||||
self.TargetCombo.clear()
|
||||
for p in getPresetVars():
|
||||
if p["name"] in ("CURRENT_TIME", "CURRENT_DATE"):
|
||||
continue
|
||||
info = self._var_mgr.getInfoByName(p["name"])
|
||||
if info:
|
||||
self.TargetCombo.addItem(
|
||||
info["display"],
|
||||
(info["name"], info["type"])
|
||||
)
|
||||
self.TargetCombo.blockSignals(False)
|
||||
|
||||
def initValueStacks(
|
||||
self
|
||||
):
|
||||
|
||||
self.literal_widgets = {}
|
||||
self.offset_widgets = {}
|
||||
for vt in getTypeOrder():
|
||||
self.literal_widgets[vt] = makeValueWidget(vt, self.ValueStack)
|
||||
self.ValueStack.addWidget(self.literal_widgets[vt])
|
||||
if getArithType(vt):
|
||||
self.offset_widgets[vt] = makeOffsetWidget(vt, self.ValueStack)
|
||||
self.ValueStack.addWidget(self.offset_widgets[vt])
|
||||
else:
|
||||
Lbl = QLabel("(不支持该操作)", self.ValueStack)
|
||||
Lbl.setFixedHeight(25)
|
||||
self.offset_widgets[vt] = Lbl
|
||||
self.ValueStack.addWidget(Lbl)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.OpTypeCombo.currentIndexChanged.connect(self.onOpTypeChanged)
|
||||
self.TargetCombo.currentIndexChanged.connect(self.onTargetChanged)
|
||||
self.ValueSrcCombo.currentIndexChanged.connect(self.onValueSrcChanged)
|
||||
|
||||
def getTargetName(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
data = self.TargetCombo.currentData()
|
||||
return data[0] if data else ""
|
||||
|
||||
def updateValueWidget(
|
||||
self
|
||||
):
|
||||
|
||||
op = self.OpTypeCombo.currentData()
|
||||
is_arith = (op in ("add", "sub"))
|
||||
actual_type = self._current_target_type
|
||||
if is_arith and actual_type in self.offset_widgets:
|
||||
self.ValueStack.setCurrentWidget(self.offset_widgets[actual_type])
|
||||
elif actual_type in self.literal_widgets:
|
||||
self.ValueStack.setCurrentWidget(self.literal_widgets[actual_type])
|
||||
else:
|
||||
self.ValueStack.setCurrentWidget(self.literal_widgets.get("String"))
|
||||
|
||||
def toScript(
|
||||
self
|
||||
) -> str:
|
||||
"""
|
||||
Generate a single line of Lua script from the current widget state.
|
||||
"""
|
||||
|
||||
target = self.getTargetName()
|
||||
op = self.OpTypeCombo.currentData()
|
||||
if op == "pass":
|
||||
return " -- pass"
|
||||
if not target:
|
||||
return ""
|
||||
raw_val = self.getValueRaw()
|
||||
vartype = self._current_target_type
|
||||
if op == "set":
|
||||
encoded = encodeValueStr(raw_val, vartype)
|
||||
return f" {target} = {encoded}"
|
||||
elif op == "add":
|
||||
if vartype == "Date" and hasattr(self.ValueStack.currentWidget(), "getOffsetDays"):
|
||||
days = self.ValueStack.currentWidget().getOffsetDays()
|
||||
return f" {target} = dateadd({target}, {days})"
|
||||
if vartype == "Time" and hasattr(self.ValueStack.currentWidget(), "getOffsetHours"):
|
||||
hours = self.ValueStack.currentWidget().getOffsetHours()
|
||||
return f" {target} = timeadd({target}, {hours})"
|
||||
return f" {target} = {target} + {raw_val}"
|
||||
elif op == "sub":
|
||||
if vartype == "Date" and hasattr(self.ValueStack.currentWidget(), "getOffsetDays"):
|
||||
days = self.ValueStack.currentWidget().getOffsetDays()
|
||||
return f" {target} = dateadd({target}, -{days})"
|
||||
if vartype == "Time" and hasattr(self.ValueStack.currentWidget(), "getOffsetHours"):
|
||||
hours = self.ValueStack.currentWidget().getOffsetHours()
|
||||
return f" {target} = timeadd({target}, -{hours})"
|
||||
return f" {target} = {target} - {raw_val}"
|
||||
return ""
|
||||
|
||||
def getValueRaw(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
if self.ValueSrcCombo.currentData() == "variable":
|
||||
data = self.ExistingVarCombo.currentData()
|
||||
return data[0] if data else ""
|
||||
w = self.ValueStack.currentWidget()
|
||||
if w:
|
||||
return getValueFromWidget(w)
|
||||
return ""
|
||||
|
||||
def refreshVarCombos(
|
||||
self
|
||||
):
|
||||
|
||||
current_data = self.TargetCombo.currentData()
|
||||
self.populateTargetCombo()
|
||||
if current_data:
|
||||
for i in range(self.TargetCombo.count()):
|
||||
d = self.TargetCombo.itemData(i)
|
||||
if d and d[0] == current_data[0]:
|
||||
self.TargetCombo.setCurrentIndex(i)
|
||||
break
|
||||
self._var_mgr.populateCombo(self.ExistingVarCombo)
|
||||
|
||||
@Slot(int)
|
||||
def onTargetChanged(
|
||||
self,
|
||||
idx
|
||||
):
|
||||
|
||||
if idx < 0:
|
||||
return
|
||||
data = self.TargetCombo.itemData(idx)
|
||||
if not data:
|
||||
return
|
||||
_, vartype = data
|
||||
self._current_target_type = vartype
|
||||
self.updateValueWidget()
|
||||
self.onValueSrcChanged(self.ValueSrcCombo.currentIndex())
|
||||
|
||||
@Slot(int)
|
||||
def onOpTypeChanged(
|
||||
self,
|
||||
idx
|
||||
):
|
||||
|
||||
self.updateValueWidget()
|
||||
|
||||
@Slot(int)
|
||||
def onValueSrcChanged(
|
||||
self,
|
||||
idx
|
||||
):
|
||||
|
||||
is_var = (self.ValueSrcCombo.currentData() == "variable")
|
||||
self.ValueStack.setVisible(not is_var)
|
||||
self.ExistingVarCombo.setVisible(is_var)
|
||||
if is_var:
|
||||
self._var_mgr.populateCombo(self.ExistingVarCombo)
|
||||
else:
|
||||
self.updateValueWidget()
|
||||
@@ -1,226 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
from PySide6.QtCore import Slot
|
||||
|
||||
from PySide6.QtGui import (
|
||||
QSyntaxHighlighter, QTextCharFormat, QColor, QFont, QIcon
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog, QVBoxLayout, QHBoxLayout, QPlainTextEdit,
|
||||
QDialogButtonBox, QPushButton, QLabel, QApplication, QStyle
|
||||
)
|
||||
|
||||
|
||||
class ALScriptHighlighter(QSyntaxHighlighter):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._rules = []
|
||||
|
||||
keywordFmt = QTextCharFormat()
|
||||
keywordFmt.setForeground(QColor("#316BFF"))
|
||||
keywordFmt.setFontWeight(QFont.Weight.Bold)
|
||||
for kw in ["IF", "ELSE IF", "ELSE", "ENDIF", "END IF",
|
||||
"SET", "PASS", "THEN"]:
|
||||
pattern = r"\b" + kw.replace(" ", r"\s+") + r"\b"
|
||||
self._rules.append((pattern, keywordFmt))
|
||||
literalFmt = QTextCharFormat()
|
||||
literalFmt.setForeground(QColor("#C2185B"))
|
||||
literalFmt.setFontWeight(QFont.Weight.Bold)
|
||||
for lit in [".TRUE.", ".FALSE."]:
|
||||
self._rules.append((r"\b" + lit.replace(".", r"\.") + r"\b", literalFmt))
|
||||
opFmt = QTextCharFormat()
|
||||
opFmt.setForeground(QColor("#9C27B0"))
|
||||
for op in [r"\.EQ\.", r"\.NEQ\.", r"\.BGT\.", r"\.BLT\.",
|
||||
r"\.BGE\.", r"\.BLE\.", r"\.ADD\.", r"\.SUB\."]:
|
||||
self._rules.append((op, opFmt))
|
||||
varFmt = QTextCharFormat()
|
||||
varFmt.setForeground(QColor("#E65100"))
|
||||
for var in ["RESERVE_BEGIN_TIME", "RESERVE_END_TIME",
|
||||
"RESERVE_DATE", "USERNAME", "USER_ENABLE",
|
||||
"PRIORITY", "CURRENT_TIME", "CURRENT_DATE"]:
|
||||
self._rules.append((r"\b" + var + r"\b", varFmt))
|
||||
funcFmt = QTextCharFormat()
|
||||
funcFmt.setForeground(QColor("#2E7D32"))
|
||||
self._rules.append((r"\bTIME\([^)]+\)", funcFmt))
|
||||
self._rules.append((r"\bDATE\([^)]+\)", funcFmt))
|
||||
strFmt = QTextCharFormat()
|
||||
strFmt.setForeground(QColor("#388E3C"))
|
||||
self._rules.append((r"'[^']*'", strFmt))
|
||||
numFmt = QTextCharFormat()
|
||||
numFmt.setForeground(QColor("#D32F2F"))
|
||||
self._rules.append((r"\b\d+\b", numFmt))
|
||||
commentFmt = QTextCharFormat()
|
||||
commentFmt.setForeground(QColor("#999999"))
|
||||
commentFmt.setFontItalic(True)
|
||||
self._rules.append((r"//[^\n]*", commentFmt))
|
||||
|
||||
|
||||
def highlightBlock(
|
||||
self,
|
||||
text
|
||||
):
|
||||
|
||||
import re
|
||||
for pattern, fmt in self._rules:
|
||||
for match in re.finditer(pattern, text, re.IGNORECASE):
|
||||
start = match.start()
|
||||
length = match.end() - match.start()
|
||||
self.setFormat(start, length, fmt)
|
||||
|
||||
|
||||
class ALAutoScriptPreviewDialog(QDialog):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
script: str = ""
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__fontSize = 13
|
||||
|
||||
self.modifyUi()
|
||||
self.connectSignals()
|
||||
|
||||
self._textEdit.setPlainText(script)
|
||||
self._highlighter = ALScriptHighlighter(
|
||||
self._textEdit.document()
|
||||
)
|
||||
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setWindowTitle("AutoScript 预览 - AutoLibrary")
|
||||
self.setMinimumSize(520, 360)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
toolbarLayout = QHBoxLayout()
|
||||
self._zoomInBtn = QPushButton("+")
|
||||
self._zoomInBtn.setFixedSize(30, 25)
|
||||
self._zoomOutBtn = QPushButton("-")
|
||||
self._zoomOutBtn.setFixedSize(30, 25)
|
||||
self._zoomResetBtn = QPushButton(
|
||||
QApplication.style().standardIcon(
|
||||
QStyle.StandardPixmap.SP_BrowserReload
|
||||
), ""
|
||||
)
|
||||
self._zoomResetBtn.setFixedSize(30, 25)
|
||||
self._zoomResetBtn.setToolTip("重置缩放")
|
||||
self._zoomLabel = QLabel(f"{self.__fontSize}px")
|
||||
self._zoomLabel.setFixedHeight(25)
|
||||
toolbarLayout.addWidget(self._zoomInBtn)
|
||||
toolbarLayout.addWidget(self._zoomOutBtn)
|
||||
toolbarLayout.addWidget(self._zoomResetBtn)
|
||||
toolbarLayout.addWidget(self._zoomLabel)
|
||||
toolbarLayout.addStretch()
|
||||
self._copyBtn = QPushButton(
|
||||
QApplication.style().standardIcon(
|
||||
QStyle.StandardPixmap.SP_FileDialogDetailedView
|
||||
), ""
|
||||
)
|
||||
self._copyBtn.setFixedSize(30, 25)
|
||||
self._copyBtn.setToolTip("复制脚本")
|
||||
toolbarLayout.addWidget(self._copyBtn)
|
||||
layout.addLayout(toolbarLayout)
|
||||
self._textEdit = QPlainTextEdit(self)
|
||||
self._textEdit.setReadOnly(True)
|
||||
self._textEdit.setLineWrapMode(
|
||||
QPlainTextEdit.LineWrapMode.NoWrap
|
||||
)
|
||||
self._textEdit.setStyleSheet(
|
||||
"QPlainTextEdit {"
|
||||
" font-family: 'Courier New', 'Consolas', monospace;"
|
||||
" font-size: 13px;"
|
||||
"}"
|
||||
)
|
||||
layout.addWidget(self._textEdit)
|
||||
|
||||
self._btnBox = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Close
|
||||
)
|
||||
self._btnBox.button(
|
||||
QDialogButtonBox.StandardButton.Close
|
||||
).setText("关闭")
|
||||
layout.addWidget(self._btnBox)
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self._btnBox.rejected.connect(self.reject)
|
||||
self._zoomInBtn.clicked.connect(self.onZoomIn)
|
||||
self._zoomOutBtn.clicked.connect(self.onZoomOut)
|
||||
self._zoomResetBtn.clicked.connect(self.onZoomReset)
|
||||
self._copyBtn.clicked.connect(self.onCopy)
|
||||
|
||||
|
||||
def updateFontSize(
|
||||
self
|
||||
):
|
||||
|
||||
font = self._textEdit.font()
|
||||
font.setPointSize(self.__fontSize)
|
||||
self._textEdit.setFont(font)
|
||||
self._textEdit.setStyleSheet(
|
||||
"QPlainTextEdit {"
|
||||
" font-family: 'Courier New', 'Consolas', monospace;"
|
||||
f" font-size: {self.__fontSize}px;"
|
||||
"}"
|
||||
)
|
||||
self._zoomLabel.setText(f"{self.__fontSize}px")
|
||||
|
||||
@Slot()
|
||||
def onZoomIn(
|
||||
self
|
||||
):
|
||||
|
||||
self.__fontSize = min(self.__fontSize + 2, 40)
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
def onZoomOut(
|
||||
self
|
||||
):
|
||||
|
||||
self.__fontSize = max(self.__fontSize - 2, 8)
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
def onZoomReset(
|
||||
self
|
||||
):
|
||||
|
||||
self.__fontSize = 13
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
def onCopy(
|
||||
self
|
||||
):
|
||||
|
||||
clipboard = QApplication.clipboard()
|
||||
clipboard.setText(self._textEdit.toPlainText())
|
||||
original = self._copyBtn.text()
|
||||
self._copyBtn.setText("已复制")
|
||||
self._copyBtn.setEnabled(False)
|
||||
from PySide6.QtCore import QTimer
|
||||
QTimer.singleShot(2000, lambda: (
|
||||
self._copyBtn.setText(original),
|
||||
self._copyBtn.setEnabled(True)
|
||||
))
|
||||
@@ -0,0 +1,352 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt,
|
||||
Signal,
|
||||
Slot,
|
||||
QTimer
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QFont
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QListWidgetItem,
|
||||
QMessageBox,
|
||||
QVBoxLayout,
|
||||
QWidget
|
||||
)
|
||||
|
||||
from gui.ALBulletinWorker import ALBulletinFetchWorker
|
||||
from gui.ALStatusLabel import ALStatusLabel
|
||||
from gui.resources.ui.Ui_ALBulletinDialog import Ui_ALBulletinDialog
|
||||
from managers.bulletin.BulletinManager import instance as bulletinInstance
|
||||
|
||||
|
||||
class ALBulletinItemWidget(QWidget):
|
||||
"""
|
||||
Single bulletin item widget for the bulletin list.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
bulletin: dict[str, Any] = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__bulletin = bulletin.copy() if bulletin else {}
|
||||
self.modifyUi()
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.ItemWidgetLayout = QVBoxLayout()
|
||||
self.ItemWidgetLayout.setSpacing(10)
|
||||
self.ItemWidgetLayout.setContentsMargins(10, 5, 10, 5)
|
||||
self.BulletinTitleLayout = QHBoxLayout()
|
||||
self.BulletinTitleLabel = QLabel(self.__bulletin.get("title", "无标题"))
|
||||
title_font = QFont()
|
||||
title_font.setBold(True)
|
||||
self.BulletinTitleLabel.setFont(title_font)
|
||||
self.BulletinTitleLayout.addWidget(self.BulletinTitleLabel)
|
||||
if self.__bulletin.get("isNew", False):
|
||||
self.NewIndicatorLabel = QLabel("新 !")
|
||||
self.NewIndicatorLabel.setStyleSheet(
|
||||
"color: #DC0000;"\
|
||||
"font-size: 10px;"\
|
||||
"font-weight: bold;"\
|
||||
"font-style: italic;"
|
||||
)
|
||||
self.NewIndicatorLabel.setFixedSize(25, 25)
|
||||
self.BulletinTitleLayout.addWidget(self.NewIndicatorLabel)
|
||||
else:
|
||||
self.NewIndicatorLabel = None
|
||||
if self.__bulletin.get("isEdited", False):
|
||||
self.BulletinIsEditedLabel = QLabel("(已编辑)")
|
||||
self.BulletinIsEditedLabel.setStyleSheet(
|
||||
"color: #FF9800;"\
|
||||
"font-size: 10px;"
|
||||
)
|
||||
self.BulletinTitleLayout.addWidget(self.BulletinIsEditedLabel)
|
||||
self.BulletinTitleLayout.addStretch()
|
||||
self.ItemWidgetLayout.addLayout(self.BulletinTitleLayout)
|
||||
self.BulletinInfoLayout = QHBoxLayout()
|
||||
self.BulletinDateLabel = QLabel()
|
||||
try:
|
||||
raw_dt = self.__bulletin.get("dateTime", "")
|
||||
date_time = datetime.fromisoformat(raw_dt) if raw_dt else datetime.now()
|
||||
except (ValueError, TypeError):
|
||||
date_time = datetime.now()
|
||||
self.BulletinDateLabel.setText(date_time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
self.BulletinDateLabel.setStyleSheet("color: #969696; font-size: 11px;")
|
||||
self.BulletinInfoLayout.addWidget(self.BulletinDateLabel)
|
||||
self.BulletinAuthorLabel = QLabel(self.__bulletin.get("author", "未知"))
|
||||
self.BulletinAuthorLabel.setStyleSheet("color: #969696; font-size: 11px;")
|
||||
self.BulletinInfoLayout.addWidget(self.BulletinAuthorLabel)
|
||||
self.BulletinInfoLayout.addStretch()
|
||||
self.ItemWidgetLayout.addLayout(self.BulletinInfoLayout)
|
||||
self.setLayout(self.ItemWidgetLayout)
|
||||
self.__bulletin = None
|
||||
|
||||
def markAsRead(
|
||||
self
|
||||
):
|
||||
|
||||
if self.NewIndicatorLabel:
|
||||
self.NewIndicatorLabel.hide()
|
||||
|
||||
|
||||
class ALBulletinDialog(QDialog, Ui_ALBulletinDialog):
|
||||
"""
|
||||
Bulletin viewer dialog.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.__sync_timer: QTimer | None = None
|
||||
self.__fetch_worker: ALBulletinFetchWorker | None = None
|
||||
self.__bulletin_mgr = bulletinInstance()
|
||||
|
||||
self.setupUi(self)
|
||||
self.modifyUi()
|
||||
self.connectSignals()
|
||||
self.setupTimer()
|
||||
if self.shouldAutoSync():
|
||||
self.syncBulletin()
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.ALSyncStatusLabel = ALStatusLabel(self)
|
||||
self.ALSyncStatusLabel.setFixedSize(30, 30)
|
||||
self.SyncLayout.replaceWidget(
|
||||
self.SyncStatusPlaceholder, self.ALSyncStatusLabel
|
||||
)
|
||||
title_font = QFont()
|
||||
title_font.setBold(True)
|
||||
title_font.setPointSize(15)
|
||||
self.BulletinTitleLabel.setFont(title_font)
|
||||
self.BulletinDateLabel.setStyleSheet("color: #969696;")
|
||||
self.BulletinAuthorLabel.setStyleSheet("color: #969696;")
|
||||
self.BulletinIsEditedLabel.setStyleSheet("color: #FF9800;")
|
||||
self.BulletinIsEditedLabel.hide()
|
||||
last_time = self.__bulletin_mgr.lastSyncTime()
|
||||
if last_time:
|
||||
self.setLastSyncTime(last_time)
|
||||
self.updateBulletinList(self.__bulletin_mgr.bulletins())
|
||||
|
||||
def shouldAutoSync(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
last = self.__bulletin_mgr.lastSyncTime()
|
||||
if last is None:
|
||||
return True
|
||||
try:
|
||||
last_dt = datetime.fromisoformat(last)
|
||||
interval_min = max(self.__bulletin_mgr.syncInterval()//2, 1)
|
||||
threshold = timedelta(minutes=interval_min)
|
||||
return (datetime.now().astimezone() - last_dt) > threshold
|
||||
except (ValueError, TypeError):
|
||||
return True
|
||||
|
||||
def setLastSyncTime(
|
||||
self,
|
||||
iso_str: str
|
||||
):
|
||||
"""
|
||||
Set last sync time to update the UI status.
|
||||
"""
|
||||
|
||||
try:
|
||||
dt = datetime.fromisoformat(iso_str)
|
||||
self.LastSyncDateTimeEdit.setDateTime(dt)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.BulletinListWidget.itemClicked.connect(self.onBulletinListWidgetItemClicked)
|
||||
self.SyncButton.clicked.connect(self.syncBulletin)
|
||||
|
||||
def setupTimer(
|
||||
self
|
||||
):
|
||||
|
||||
self.__sync_timer = QTimer(self)
|
||||
self.__sync_timer.timeout.connect(self.syncBulletin)
|
||||
self.__sync_timer.start(self.__bulletin_mgr.syncInterval()*60*1000)
|
||||
|
||||
def updateBulletinList(
|
||||
self,
|
||||
bulletins: list[dict]
|
||||
):
|
||||
|
||||
self.BulletinListWidget.clear()
|
||||
sorted_list = sorted(
|
||||
bulletins, key=lambda x: x.get("dateTime", ""), reverse=True
|
||||
)
|
||||
for bulletin in sorted_list:
|
||||
item = QListWidgetItem()
|
||||
item.setData(Qt.UserRole, bulletin)
|
||||
widget = ALBulletinItemWidget(self, bulletin)
|
||||
item.setSizeHint(widget.sizeHint())
|
||||
self.BulletinListWidget.addItem(item)
|
||||
self.BulletinListWidget.setItemWidget(item, widget)
|
||||
|
||||
def showBulletin(
|
||||
self,
|
||||
bulletin: dict
|
||||
):
|
||||
|
||||
self.BulletinTitleLabel.setText(bulletin.get("title", "无标题"))
|
||||
try:
|
||||
raw_dt = bulletin.get("dateTime", "")
|
||||
date_time = datetime.fromisoformat(raw_dt) if raw_dt else datetime.now()
|
||||
except (ValueError, TypeError):
|
||||
date_time = datetime.now()
|
||||
self.BulletinDateLabel.setText(date_time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
self.BulletinAuthorLabel.setText(bulletin.get("author", "未知"))
|
||||
if bulletin.get("isEdited", False):
|
||||
self.BulletinIsEditedLabel.show()
|
||||
else:
|
||||
self.BulletinIsEditedLabel.hide()
|
||||
self.BulletinContentTextBrowser.setHtml(
|
||||
"<div style='font-size: 14px;'>{content}</div>".format(
|
||||
content=bulletin.get("content", "无内容")
|
||||
)
|
||||
)
|
||||
|
||||
def clearBulletin(
|
||||
self
|
||||
):
|
||||
|
||||
self.BulletinTitleLabel.setText("")
|
||||
self.BulletinDateLabel.setText("")
|
||||
self.BulletinAuthorLabel.setText("")
|
||||
self.BulletinContentTextBrowser.setText("")
|
||||
self.BulletinIsEditedLabel.hide()
|
||||
|
||||
def syncBulletin(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__fetch_worker is not None:
|
||||
return
|
||||
self.SyncButton.setEnabled(False)
|
||||
self.SyncButton.setText("同步中...")
|
||||
self.ALSyncStatusLabel.status = ALStatusLabel.Status.RUNNING
|
||||
self.SyncStatusDetailLabel.setText("")
|
||||
self.SyncStatusDetailLabel.setStyleSheet("")
|
||||
params = self.__bulletin_mgr.getSyncDateTimeAndRange()
|
||||
self.__fetch_worker = ALBulletinFetchWorker(
|
||||
self, self.__bulletin_mgr.apiUrl(), params
|
||||
)
|
||||
self.__fetch_worker.fetchWorkerIsFinished.connect(self.onBulletinsFetched)
|
||||
self.__fetch_worker.fetchWorkerFinishedWithError.connect(self.onBulletinsFetchError)
|
||||
self.__fetch_worker.start()
|
||||
|
||||
@Slot(dict)
|
||||
def onBulletinsFetched(
|
||||
self,
|
||||
data: dict
|
||||
):
|
||||
|
||||
worker = self.sender()
|
||||
if worker is not self.__fetch_worker:
|
||||
return
|
||||
worker.fetchWorkerIsFinished.disconnect(self.onBulletinsFetched)
|
||||
worker.fetchWorkerFinishedWithError.disconnect(self.onBulletinsFetchError)
|
||||
worker.wait(2000)
|
||||
worker.deleteLater()
|
||||
self.__fetch_worker = None
|
||||
bulletins = data.get("bulletins", [])
|
||||
delete_ids = data.get("delete_ids", [])
|
||||
merged = self.__bulletin_mgr.updateAndMergeBulletins(bulletins, delete_ids)
|
||||
self.__bulletin_mgr.setLastSyncTime(datetime.now().astimezone().isoformat())
|
||||
self.SyncButton.setEnabled(True)
|
||||
self.SyncButton.setText("同步")
|
||||
self.ALSyncStatusLabel.status = ALStatusLabel.Status.SUCCESS
|
||||
self.SyncStatusDetailLabel.setText("同步成功")
|
||||
self.SyncStatusDetailLabel.setStyleSheet("color: green;")
|
||||
QTimer.singleShot(3000, self, self.clearSyncStatus)
|
||||
|
||||
self.setLastSyncTime(self.__bulletin_mgr.lastSyncTime())
|
||||
self.updateBulletinList(merged)
|
||||
self.clearBulletin()
|
||||
interval_ms = self.__bulletin_mgr.syncInterval()*60*1000
|
||||
if self.__sync_timer:
|
||||
self.__sync_timer.start(interval_ms)
|
||||
|
||||
@Slot(str)
|
||||
def onBulletinsFetchError(
|
||||
self,
|
||||
error_message: str
|
||||
):
|
||||
|
||||
worker = self.sender()
|
||||
if worker is not self.__fetch_worker:
|
||||
return
|
||||
worker.fetchWorkerIsFinished.disconnect(self.onBulletinsFetched)
|
||||
worker.fetchWorkerFinishedWithError.disconnect(self.onBulletinsFetchError)
|
||||
worker.wait(2000)
|
||||
worker.deleteLater()
|
||||
self.__fetch_worker = None
|
||||
self.SyncButton.setEnabled(True)
|
||||
self.SyncButton.setText("重试")
|
||||
self.ALSyncStatusLabel.status = ALStatusLabel.Status.FAILURE
|
||||
self.SyncStatusDetailLabel.setText("同步失败,请检查网络连接")
|
||||
self.SyncStatusDetailLabel.setStyleSheet("color: red;")
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"警告 - AutoLibrary",
|
||||
f"同步失败:{error_message}"
|
||||
)
|
||||
interval_ms = self.__bulletin_mgr.syncInterval()*60*1000
|
||||
if self.__sync_timer:
|
||||
self.__sync_timer.start(interval_ms)
|
||||
|
||||
def clearSyncStatus(
|
||||
self
|
||||
):
|
||||
|
||||
self.ALSyncStatusLabel.status = ALStatusLabel.Status.WAITING
|
||||
self.SyncStatusDetailLabel.setText("")
|
||||
self.SyncStatusDetailLabel.setStyleSheet("")
|
||||
|
||||
@Slot(QListWidgetItem)
|
||||
def onBulletinListWidgetItemClicked(
|
||||
self,
|
||||
item: QListWidgetItem
|
||||
):
|
||||
|
||||
if item is None or item.data(Qt.UserRole) is None:
|
||||
return
|
||||
bulletin = item.data(Qt.UserRole)
|
||||
if bulletin.get("isNew", False):
|
||||
self.__bulletin_mgr.markBulletinAsRead(bulletin["id"])
|
||||
widget = self.BulletinListWidget.itemWidget(item)
|
||||
if widget:
|
||||
widget.markAsRead()
|
||||
item.setData(Qt.UserRole, bulletin)
|
||||
self.showBulletin(bulletin)
|
||||
@@ -0,0 +1,188 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QObject,
|
||||
QTimer,
|
||||
Signal,
|
||||
Slot
|
||||
)
|
||||
|
||||
from gui.ALBulletinWorker import ALBulletinFetchWorker
|
||||
from managers.bulletin.BulletinManager import instance as bulletinInstance
|
||||
|
||||
|
||||
class ALBulletinPoller(QObject):
|
||||
"""
|
||||
Background bulletin poller.
|
||||
|
||||
Owns the periodic poll timer and the ALBulletinFetchWorker
|
||||
lifecycle. Emits signals when new bulletins are detected so
|
||||
the owner can show tray notifications without knowing the
|
||||
fetch / merge details.
|
||||
"""
|
||||
|
||||
newBulletinsDetected = Signal(int)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__timer = QTimer(self)
|
||||
self.__timer.timeout.connect(self.__poll)
|
||||
self.__worker = None
|
||||
self.__dialog_open = False
|
||||
self.__stopped = False
|
||||
self.__mgr = bulletinInstance()
|
||||
|
||||
def start(
|
||||
self
|
||||
):
|
||||
|
||||
self.__stopped = False
|
||||
interval_ms = self.__mgr.syncInterval()*60*1000
|
||||
self.__timer.start(interval_ms)
|
||||
|
||||
def stop(
|
||||
self
|
||||
):
|
||||
|
||||
self.__stopped = True
|
||||
self.__timer.stop()
|
||||
self.__cleanupWorker()
|
||||
|
||||
def restart(
|
||||
self
|
||||
):
|
||||
|
||||
self.stop()
|
||||
self.start()
|
||||
|
||||
def fetchNow(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__worker is not None:
|
||||
return
|
||||
if self.__dialog_open:
|
||||
return
|
||||
self.__doFetch()
|
||||
|
||||
def isPolling(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
return self.__timer.isActive()
|
||||
|
||||
def setDialogOpen(
|
||||
self,
|
||||
open: bool
|
||||
):
|
||||
|
||||
self.__dialog_open = open
|
||||
|
||||
def __disconnectWorker(
|
||||
self,
|
||||
worker: ALBulletinFetchWorker
|
||||
):
|
||||
|
||||
try:
|
||||
worker.fetchWorkerIsFinished.disconnect(self.__onFetched)
|
||||
except (TypeError, RuntimeError):
|
||||
pass
|
||||
try:
|
||||
worker.fetchWorkerFinishedWithError.disconnect(self.__onError)
|
||||
except (TypeError, RuntimeError):
|
||||
pass
|
||||
|
||||
def __cleanupWorker(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__worker is None:
|
||||
return
|
||||
self.__disconnectWorker(self.__worker)
|
||||
self.__worker.wait(500)
|
||||
self.__worker.deleteLater()
|
||||
self.__worker = None
|
||||
|
||||
def __doFetch(
|
||||
self
|
||||
):
|
||||
|
||||
params = self.__mgr.getSyncDateTimeAndRange()
|
||||
self.__worker = ALBulletinFetchWorker(
|
||||
self, self.__mgr.apiUrl(), params
|
||||
)
|
||||
self.__worker.fetchWorkerIsFinished.connect(self.__onFetched)
|
||||
self.__worker.fetchWorkerFinishedWithError.connect(self.__onError)
|
||||
self.__worker.start()
|
||||
|
||||
@Slot()
|
||||
def __poll(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__worker is not None:
|
||||
return
|
||||
if self.__dialog_open:
|
||||
return
|
||||
self.__doFetch()
|
||||
|
||||
@Slot(dict)
|
||||
def __onFetched(
|
||||
self,
|
||||
data: dict
|
||||
):
|
||||
|
||||
worker = self.sender()
|
||||
if worker is not self.__worker:
|
||||
return
|
||||
self.__disconnectWorker(worker)
|
||||
worker.wait(500)
|
||||
worker.deleteLater()
|
||||
self.__worker = None
|
||||
old_ids = {str(b.get("id", "")) for b in self.__mgr.bulletins()}
|
||||
bulletins = data.get("bulletins", [])
|
||||
delete_ids = data.get("delete_ids", [])
|
||||
self.__mgr.updateAndMergeBulletins(bulletins, delete_ids)
|
||||
self.__mgr.setLastSyncTime(datetime.now().astimezone().isoformat())
|
||||
delete_id_set = {str(d) for d in delete_ids}
|
||||
new_ids = {
|
||||
str(b.get("id", ""))
|
||||
for b in bulletins
|
||||
if str(b.get("id", "")) and str(b.get("id", "")) not in old_ids
|
||||
}
|
||||
new_ids -= delete_id_set
|
||||
if new_ids and not self.__dialog_open:
|
||||
self.newBulletinsDetected.emit(len(new_ids))
|
||||
if not self.__stopped:
|
||||
interval_ms = self.__mgr.syncInterval()*60*1000
|
||||
self.__timer.start(interval_ms)
|
||||
|
||||
@Slot(str)
|
||||
def __onError(
|
||||
self,
|
||||
error_message: str
|
||||
):
|
||||
|
||||
worker = self.sender()
|
||||
if worker is not self.__worker:
|
||||
return
|
||||
self.__disconnectWorker(worker)
|
||||
worker.wait(500)
|
||||
worker.deleteLater()
|
||||
self.__worker = None
|
||||
if not self.__stopped:
|
||||
interval_ms = self.__mgr.syncInterval()*60*1000
|
||||
self.__timer.start(interval_ms)
|
||||
@@ -0,0 +1,57 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import requests
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QThread,
|
||||
Signal
|
||||
)
|
||||
|
||||
|
||||
class ALBulletinFetchWorker(QThread):
|
||||
"""
|
||||
Worker thread for fetching bulletins from the server.
|
||||
"""
|
||||
|
||||
fetchWorkerIsFinished = Signal(dict)
|
||||
fetchWorkerFinishedWithError = Signal(str)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
request_url: str = "",
|
||||
params: dict = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__request_url = request_url.rstrip("/") if request_url else ""
|
||||
self.__params = params or {}
|
||||
|
||||
def run(
|
||||
self
|
||||
):
|
||||
|
||||
try:
|
||||
response = requests.get(
|
||||
self.__request_url, params=self.__params, timeout=5
|
||||
)
|
||||
response.raise_for_status()
|
||||
r = response.json()
|
||||
if r.get("code") == 200:
|
||||
data = r.get("data", {})
|
||||
self.fetchWorkerIsFinished.emit(data)
|
||||
else:
|
||||
raise Exception(
|
||||
f"服务器返回错误: [{r.get('code', '未知代码')}] {r.get('msg', '未知错误')}"
|
||||
)
|
||||
except requests.RequestException as e:
|
||||
self.fetchWorkerFinishedWithError.emit(f"获取公告数据时发生网络错误: \n{e}")
|
||||
except Exception as e:
|
||||
self.fetchWorkerFinishedWithError.emit(f"获取公告数据时发生未知错误: \n{e}")
|
||||
@@ -0,0 +1,192 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtGui import QDesktopServices
|
||||
from PySide6.QtCore import QUrl
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QLabel,
|
||||
QVBoxLayout
|
||||
)
|
||||
|
||||
|
||||
class ALCheckUpdateDialog(QDialog):
|
||||
"""
|
||||
Dialog for showing update check result.
|
||||
|
||||
Supports two layouts:
|
||||
- has_update=True : version comparison with green text + action buttons
|
||||
- has_update=False: "already up-to-date" message + close button
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
has_update: bool = False,
|
||||
current_version: str = "",
|
||||
latest_version: str = "",
|
||||
tag_name: str = "",
|
||||
html_url: str = ""
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__has_update = has_update
|
||||
self.__html_url = html_url
|
||||
self.__current_version = current_version
|
||||
self.__latest_version = latest_version
|
||||
self.__tag_name = tag_name
|
||||
|
||||
self.modifyUi()
|
||||
self.connectSignals()
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setWindowTitle("检查更新 - AutoLibrary")
|
||||
self.setMinimumWidth(360)
|
||||
Layout = QVBoxLayout(self)
|
||||
Layout.setSpacing(12)
|
||||
Layout.setContentsMargins(20, 20, 20, 20)
|
||||
if self.__has_update:
|
||||
self.buildUpdateAvailableUi(Layout)
|
||||
else:
|
||||
self.buildUpToDateUi(Layout)
|
||||
|
||||
def buildUpdateAvailableUi(
|
||||
self,
|
||||
layout: QVBoxLayout
|
||||
):
|
||||
|
||||
TitleLabel = QLabel()
|
||||
TitleLabel.setStyleSheet(
|
||||
"font-size: 14px;"
|
||||
"font-weight: bold;"
|
||||
)
|
||||
TitleLabel.setTextFormat(Qt.TextFormat.RichText)
|
||||
TitleLabel.setText(
|
||||
f"检测到新版本: "
|
||||
f"<span>{self.__current_version}</span> "
|
||||
f"<span>></span> "
|
||||
f"<span style='color: green; font-weight: bold;'>{self.__latest_version}</span>"
|
||||
)
|
||||
layout.addWidget(TitleLabel)
|
||||
InfoLabel = QLabel()
|
||||
InfoLabel.setTextFormat(Qt.TextFormat.RichText)
|
||||
InfoLabel.setWordWrap(True)
|
||||
InfoLabel.setText(
|
||||
f"最新版本: <b>{self.__tag_name}</b><br>"
|
||||
)
|
||||
InfoLabel.setOpenExternalLinks(True)
|
||||
layout.addWidget(InfoLabel)
|
||||
layout.addSpacing(8)
|
||||
self.__button_box = QDialogButtonBox()
|
||||
self.__btn_github = self.__button_box.addButton(
|
||||
"前往 GitHub",
|
||||
QDialogButtonBox.ButtonRole.AcceptRole
|
||||
)
|
||||
self.__btn_github.setMinimumWidth(100)
|
||||
self.__btn_github.setMaximumWidth(100)
|
||||
self.__btn_github.setMinimumHeight(25)
|
||||
self.__btn_github.setMaximumHeight(25)
|
||||
self.__btn_download = self.__button_box.addButton(
|
||||
"官网下载",
|
||||
QDialogButtonBox.ButtonRole.ActionRole
|
||||
)
|
||||
self.__btn_download.setMinimumWidth(80)
|
||||
self.__btn_download.setMaximumWidth(80)
|
||||
self.__btn_download.setMinimumHeight(25)
|
||||
self.__btn_download.setMaximumHeight(25)
|
||||
self.__btn_cancel = self.__button_box.addButton(
|
||||
"取消",
|
||||
QDialogButtonBox.ButtonRole.RejectRole
|
||||
)
|
||||
self.__btn_cancel.setMinimumWidth(80)
|
||||
self.__btn_cancel.setMaximumWidth(80)
|
||||
self.__btn_cancel.setMinimumHeight(25)
|
||||
self.__btn_cancel.setMaximumHeight(25)
|
||||
layout.addWidget(self.__button_box)
|
||||
|
||||
def buildUpToDateUi(
|
||||
self,
|
||||
layout: QVBoxLayout
|
||||
):
|
||||
|
||||
TitleLabel = QLabel()
|
||||
TitleLabel.setStyleSheet(
|
||||
"font-size: 14px;"
|
||||
"font-weight: bold;"
|
||||
)
|
||||
TitleLabel.setText(f"已是最新版本 !")
|
||||
layout.addWidget(TitleLabel)
|
||||
InfoLabel = QLabel()
|
||||
InfoLabel.setText(
|
||||
f"当前版本: <b>{self.__current_version}</b><br>"
|
||||
)
|
||||
layout.addWidget(InfoLabel)
|
||||
layout.addStretch()
|
||||
self.__button_box = QDialogButtonBox()
|
||||
self.__btn_close = self.__button_box.addButton(
|
||||
"确定",
|
||||
QDialogButtonBox.ButtonRole.AcceptRole
|
||||
)
|
||||
self.__btn_close.setMinimumWidth(80)
|
||||
self.__btn_close.setMaximumWidth(80)
|
||||
self.__btn_close.setMinimumHeight(25)
|
||||
self.__btn_close.setMaximumHeight(25)
|
||||
layout.addWidget(self.__button_box)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__has_update:
|
||||
self.__btn_github.clicked.connect(self.onGoToGitHub)
|
||||
self.__btn_download.clicked.connect(self.onGoToDownload)
|
||||
self.__btn_cancel.clicked.connect(self.reject)
|
||||
else:
|
||||
self.__btn_close.clicked.connect(self.accept)
|
||||
|
||||
def onGoToGitHub(
|
||||
self
|
||||
):
|
||||
|
||||
QDesktopServices.openUrl(QUrl(self.__html_url))
|
||||
self.accept()
|
||||
|
||||
def onGoToDownload(
|
||||
self
|
||||
):
|
||||
|
||||
QDesktopServices.openUrl(
|
||||
QUrl("https://www.autolibrary.kenanzhu.com/downloads")
|
||||
)
|
||||
self.accept()
|
||||
|
||||
@staticmethod
|
||||
def showResult(
|
||||
parent,
|
||||
has_update: bool,
|
||||
current_version: str,
|
||||
latest_version: str = "",
|
||||
tag_name: str = "",
|
||||
html_url: str = ""
|
||||
):
|
||||
|
||||
dialog = ALCheckUpdateDialog(
|
||||
parent,
|
||||
has_update=has_update,
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
tag_name=tag_name,
|
||||
html_url=html_url
|
||||
)
|
||||
dialog.exec()
|
||||
@@ -0,0 +1,51 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import requests
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QThread,
|
||||
Signal
|
||||
)
|
||||
|
||||
|
||||
class ALCheckUpdateWorker(QThread):
|
||||
"""
|
||||
Worker thread for checking latest release from GitHub API.
|
||||
"""
|
||||
|
||||
checkUpdateWorkerIsFinished = Signal(dict)
|
||||
checkUpdateWorkerFinishedWithError = Signal(str)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__api_url = "https://api.github.com/repos/KenanZhu/AutoLibrary/releases/latest"
|
||||
|
||||
def run(
|
||||
self
|
||||
):
|
||||
|
||||
try:
|
||||
response = requests.get(self.__api_url, timeout=10)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
self.checkUpdateWorkerIsFinished.emit({
|
||||
"tag_name": data.get("tag_name", ""),
|
||||
"name": data.get("name", ""),
|
||||
"html_url": data.get("html_url", ""),
|
||||
"body": data.get("body", ""),
|
||||
})
|
||||
except requests.RequestException as e:
|
||||
self.checkUpdateWorkerFinishedWithError.emit(f"网络请求失败: \n{e}")
|
||||
except Exception as e:
|
||||
self.checkUpdateWorkerFinishedWithError.emit(f"检查更新时发生未知错误: \n{e}")
|
||||
@@ -10,30 +10,50 @@ See the LICENSE file for details.
|
||||
import os
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt, Signal, Slot, QTime, QDate, QDir, QFileInfo
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog, QWidget, QLineEdit, QMessageBox, QFileDialog,
|
||||
QTreeWidgetItem, QMenu, QInputDialog
|
||||
QDate,
|
||||
QDir,
|
||||
QFileInfo,
|
||||
Qt,
|
||||
QTime,
|
||||
Signal,
|
||||
Slot
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QCloseEvent, QAction
|
||||
QAction,
|
||||
QCloseEvent
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QFileDialog,
|
||||
QInputDialog,
|
||||
QLineEdit,
|
||||
QMenu,
|
||||
QMessageBox,
|
||||
QTreeWidgetItem,
|
||||
QWidget
|
||||
)
|
||||
|
||||
import managers.config.ConfigManager as ConfigManager
|
||||
|
||||
from utils.JSONReader import JSONReader
|
||||
from utils.JSONWriter import JSONWriter
|
||||
from utils.ConfigUtils import ConfigUtils
|
||||
|
||||
from gui.resources.ui.Ui_ALConfigWidget import Ui_ALConfigWidget
|
||||
from gui.ALSeatMapSelectDialog import ALSeatMapSelectDialog
|
||||
from gui.ALSeatMapTable import ALSeatMapTable
|
||||
from gui.ALUserTreeWidget import ALUserTreeWidget, ALUserTreeItemType
|
||||
from gui.ALUserTreeWidget import (
|
||||
ALUserTreeItemType,
|
||||
ALUserTreeWidget
|
||||
)
|
||||
from gui.ALWebDriverDownloadDialog import ALWebDriverDownloadDialog
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
from gui.resources.ui.Ui_ALConfigWidget import Ui_ALConfigWidget
|
||||
from interfaces.ConfigProvider import (
|
||||
CfgKey,
|
||||
ConfigProvider
|
||||
)
|
||||
from managers.config.ConfigUtils import ConfigUtils
|
||||
from utils.JSONReader import JSONReader
|
||||
from utils.JSONWriter import JSONWriter
|
||||
|
||||
|
||||
class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
class ALConfigWidget(CenterOnParentMixin, QWidget, Ui_ALConfigWidget):
|
||||
|
||||
configWidgetIsClosed = Signal()
|
||||
|
||||
@@ -43,7 +63,7 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__cfg_mgr = ConfigManager.instance()
|
||||
self.__cfg_mgr: ConfigProvider = ConfigManager.instance()
|
||||
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
||||
self.__config_data = {"run": {}, "user": {}}
|
||||
|
||||
@@ -53,7 +73,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
if not self.initializeConfigs():
|
||||
self.close()
|
||||
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
@@ -69,7 +88,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.initializeFloorRoomMap()
|
||||
self.initializeUserInfoWidget()
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
@@ -93,31 +111,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||
self.CancelButton.clicked.connect(self.onCancelButtonClicked)
|
||||
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
@@ -126,7 +119,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.configWidgetIsClosed.emit()
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
def initializeFloorRoomMap(
|
||||
self
|
||||
):
|
||||
@@ -160,7 +152,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
"五层": ["五层考研"]
|
||||
}
|
||||
|
||||
|
||||
def initializeConfigToWidget(
|
||||
self,
|
||||
which: str,
|
||||
@@ -175,7 +166,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.setUsersToTreeWidget(config_data)
|
||||
self.CurrentUserConfigEdit.setText(self.__config_paths["user"])
|
||||
|
||||
|
||||
def initializeConfig(
|
||||
self,
|
||||
which: str
|
||||
@@ -209,7 +199,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
is_success = False
|
||||
return is_success
|
||||
|
||||
|
||||
def initializeConfigs(
|
||||
self
|
||||
) -> bool:
|
||||
@@ -222,7 +211,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.initializeConfigToWidget(which, self.__config_data[which])
|
||||
return is_success
|
||||
|
||||
|
||||
def defaultRunConfig(
|
||||
self
|
||||
) -> dict:
|
||||
@@ -246,7 +234,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def defaultUserConfig(
|
||||
self
|
||||
) -> dict:
|
||||
@@ -256,7 +243,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def collectRunConfigFromWidget(
|
||||
self
|
||||
) -> dict:
|
||||
@@ -278,7 +264,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
run_config["mode"]["run_mode"] = run_mode
|
||||
return run_config
|
||||
|
||||
|
||||
def setRunConfigToWidget(
|
||||
self,
|
||||
run_config: dict
|
||||
@@ -317,7 +302,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
"文件可能被意外修改或已经损坏\n"
|
||||
)
|
||||
|
||||
|
||||
def initializeUserInfoWidget(
|
||||
self
|
||||
):
|
||||
@@ -342,7 +326,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.MaxRenewTimeDiffSpinBox.setValue(30)
|
||||
self.PreferLateRenewTimeCheckBox.setChecked(False)
|
||||
|
||||
|
||||
def collectUserFromWidget(
|
||||
self
|
||||
) -> dict:
|
||||
@@ -375,7 +358,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
user["reserve_info"]["renew_time"]["prefer_early"] = not self.PreferLateRenewTimeCheckBox.isChecked()
|
||||
return user
|
||||
|
||||
|
||||
def collectUsersFromTreeWidget(
|
||||
self
|
||||
) -> dict:
|
||||
@@ -398,7 +380,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
user_config["groups"].append(group_config)
|
||||
return user_config
|
||||
|
||||
|
||||
def setUserToWidget(
|
||||
self,
|
||||
user: dict
|
||||
@@ -440,7 +421,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
"文件可能被意外修改或已经损坏\n"
|
||||
)
|
||||
|
||||
|
||||
def setUsersToTreeWidget(
|
||||
self,
|
||||
users: dict
|
||||
@@ -482,7 +462,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
finally:
|
||||
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
||||
|
||||
|
||||
def loadRunConfig(
|
||||
self,
|
||||
run_config_path: str
|
||||
@@ -506,7 +485,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def saveRunConfig(
|
||||
self,
|
||||
run_config_path: str,
|
||||
@@ -528,7 +506,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def loadUserConfig(
|
||||
self,
|
||||
user_config_path: str
|
||||
@@ -562,7 +539,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def saveUserConfig(
|
||||
self,
|
||||
user_config_path: str,
|
||||
@@ -584,7 +560,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def saveConfigs(
|
||||
self,
|
||||
run_config_path: str,
|
||||
@@ -607,7 +582,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def loadConfig(
|
||||
self,
|
||||
config_path: str
|
||||
@@ -636,7 +610,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def addGroup(
|
||||
self,
|
||||
group_name: str = ""
|
||||
@@ -653,7 +626,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
||||
return group_item
|
||||
|
||||
|
||||
def delGroup(
|
||||
self,
|
||||
group_item: QTreeWidgetItem = None
|
||||
@@ -666,7 +638,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
index = self.UserTreeWidget.indexOfTopLevelItem(group_item)
|
||||
self.UserTreeWidget.takeTopLevelItem(index)
|
||||
|
||||
|
||||
def addUser(
|
||||
self,
|
||||
group_item: QTreeWidgetItem = None
|
||||
@@ -721,7 +692,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
||||
return user_item
|
||||
|
||||
|
||||
def delUser(
|
||||
self,
|
||||
user_item: QTreeWidgetItem = None
|
||||
@@ -737,7 +707,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
if parent_item.childCount() == 0:
|
||||
self.UserTreeWidget.setCurrentItem(None)
|
||||
|
||||
|
||||
def renameItem(
|
||||
self,
|
||||
item: QTreeWidgetItem,
|
||||
@@ -796,19 +765,19 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
room = self.RoomComboBox.currentText()
|
||||
floor_idx = self.__floor_rmap[floor]
|
||||
room_idx = self.__room_rmap[room]
|
||||
dialog = ALSeatMapSelectDialog(
|
||||
Dialog = ALSeatMapSelectDialog(
|
||||
self,
|
||||
floor,
|
||||
room,
|
||||
ALSeatMapTable[floor_idx][room_idx]
|
||||
)
|
||||
dialog.selectSeats(self.SeatIDEdit.text().split(","))
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
selected_seats = dialog.getSelectedSeats()
|
||||
Dialog.selectSeats(self.SeatIDEdit.text().split(","))
|
||||
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
selected_seats = Dialog.getSelectedSeats()
|
||||
if len(selected_seats) == 0:
|
||||
self.SeatIDEdit.clear()
|
||||
return
|
||||
self.SeatIDEdit.setText(",".join(dialog.getSelectedSeats()))
|
||||
self.SeatIDEdit.setText(",".join(Dialog.getSelectedSeats()))
|
||||
|
||||
@Slot()
|
||||
def onUserTreeWidgetCurrentItemChanged(
|
||||
@@ -861,16 +830,14 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
is_checked = item.checkState(1) == Qt.CheckState.Checked
|
||||
item.setText(1, "" if is_checked else "跳过")
|
||||
|
||||
|
||||
def showTreeMenu(
|
||||
self,
|
||||
menu: QMenu
|
||||
):
|
||||
|
||||
add_group_action = QAction("添加分组", menu)
|
||||
add_group_action.triggered.connect(self.addGroup)
|
||||
menu.addAction(add_group_action)
|
||||
|
||||
AddGroupAction = QAction("添加分组", menu)
|
||||
AddGroupAction.triggered.connect(self.addGroup)
|
||||
menu.addAction(AddGroupAction)
|
||||
|
||||
def showGroupMenu(
|
||||
self,
|
||||
@@ -878,19 +845,18 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
group_item: QTreeWidgetItem = None
|
||||
):
|
||||
|
||||
add_user_action = QAction("添加用户", menu)
|
||||
rename_group_action = QAction("重命名分组", menu)
|
||||
del_group_action = QAction("删除分组", menu)
|
||||
add_user_action.triggered.connect(lambda: self.addUser(group_item))
|
||||
rename_group_action.triggered.connect(lambda: self.renameItem(group_item))
|
||||
del_group_action.triggered.connect(lambda: self.delGroup(group_item))
|
||||
menu.addAction(add_user_action)
|
||||
AddUserAction = QAction("添加用户", menu)
|
||||
RenameGroupAction = QAction("重命名分组", menu)
|
||||
DelGroupAction = QAction("删除分组", menu)
|
||||
AddUserAction.triggered.connect(lambda: self.addUser(group_item))
|
||||
RenameGroupAction.triggered.connect(lambda: self.renameItem(group_item))
|
||||
DelGroupAction.triggered.connect(lambda: self.delGroup(group_item))
|
||||
menu.addAction(AddUserAction)
|
||||
menu.addSeparator()
|
||||
menu.addAction(rename_group_action)
|
||||
menu.addAction(del_group_action)
|
||||
menu.addAction(RenameGroupAction)
|
||||
menu.addAction(DelGroupAction)
|
||||
if group_item.checkState(1) == Qt.CheckState.Unchecked:
|
||||
add_user_action.setEnabled(False)
|
||||
|
||||
AddUserAction.setEnabled(False)
|
||||
|
||||
def showUserMenu(
|
||||
self,
|
||||
@@ -898,12 +864,12 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
user_item: QTreeWidgetItem = None
|
||||
):
|
||||
|
||||
rename_user_action = QAction("重命名用户", menu)
|
||||
del_user_action = QAction("删除用户", menu)
|
||||
rename_user_action.triggered.connect(lambda: self.renameItem(user_item))
|
||||
del_user_action.triggered.connect(lambda: self.delUser(user_item))
|
||||
menu.addAction(rename_user_action)
|
||||
menu.addAction(del_user_action)
|
||||
RenameUserAction = QAction("重命名用户", menu)
|
||||
DelUserAction = QAction("删除用户", menu)
|
||||
RenameUserAction.triggered.connect(lambda: self.renameItem(user_item))
|
||||
DelUserAction.triggered.connect(lambda: self.delUser(user_item))
|
||||
menu.addAction(RenameUserAction)
|
||||
menu.addAction(DelUserAction)
|
||||
|
||||
@Slot()
|
||||
def onUserTreeWidgetContextMenu(
|
||||
@@ -912,14 +878,14 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
):
|
||||
|
||||
current_item = self.UserTreeWidget.itemAt(pos)
|
||||
menu = QMenu(self.UserTreeWidget)
|
||||
Menu = QMenu(self.UserTreeWidget)
|
||||
if current_item is None:
|
||||
self.showTreeMenu(menu)
|
||||
self.showTreeMenu(Menu)
|
||||
elif current_item.type() == ALUserTreeItemType.GROUP.value:
|
||||
self.showGroupMenu(menu, current_item)
|
||||
self.showGroupMenu(Menu, current_item)
|
||||
else:
|
||||
self.showUserMenu(menu, current_item)
|
||||
menu.exec_(self.UserTreeWidget.mapToGlobal(pos))
|
||||
self.showUserMenu(Menu, current_item)
|
||||
Menu.exec_(self.UserTreeWidget.mapToGlobal(pos))
|
||||
|
||||
@Slot()
|
||||
def onAddUserButtonClicked(
|
||||
@@ -951,21 +917,19 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
if browser_driver_path:
|
||||
self.BrowseBrowserDriverEdit.setText(QDir.toNativeSeparators(browser_driver_path))
|
||||
|
||||
|
||||
@Slot()
|
||||
def onAutoDownloadWebDriverButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
dialog = ALWebDriverDownloadDialog(self)
|
||||
dialog.show()
|
||||
dialog.exec_()
|
||||
selected_driver_info = dialog.getSelectedDriverInfo()
|
||||
Dialog = ALWebDriverDownloadDialog(self)
|
||||
Dialog.show()
|
||||
Dialog.exec_()
|
||||
selected_driver_info = Dialog.getSelectedDriverInfo()
|
||||
if selected_driver_info and selected_driver_info.driver_path:
|
||||
self.BrowserTypeComboBox.setCurrentText(selected_driver_info.driver_type.value)
|
||||
self.BrowseBrowserDriverEdit.setText(QDir.toNativeSeparators(str(selected_driver_info.driver_path)))
|
||||
|
||||
|
||||
@Slot()
|
||||
def onBrowseCurrentRunConfigButtonClicked(
|
||||
self
|
||||
@@ -985,13 +949,13 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.setRunConfigToWidget(data)
|
||||
self.__config_paths["run"] = run_config_path
|
||||
self.CurrentRunConfigEdit.setText(run_config_path)
|
||||
paths = self.__cfg_mgr.get(ConfigManager.ConfigType.GLOBAL, "automation.run_path.paths", [])
|
||||
paths = self.__cfg_mgr.get(CfgKey.GLOBAL.AUTOMATION.RUN_PATH.PATHS, [])
|
||||
if run_config_path not in paths:
|
||||
paths.append(run_config_path)
|
||||
index = len(paths) - 1
|
||||
else:
|
||||
index = paths.index(run_config_path)
|
||||
self.__cfg_mgr.set(ConfigManager.ConfigType.GLOBAL, "automation.run_path", {"current": index, "paths": paths})
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.AUTOMATION.RUN_PATH.ROOT, {"current": index, "paths": paths})
|
||||
else:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
@@ -1020,13 +984,13 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.setUsersToTreeWidget(data)
|
||||
self.__config_paths["user"] = user_config_path
|
||||
self.CurrentUserConfigEdit.setText(user_config_path)
|
||||
paths = self.__cfg_mgr.get(ConfigManager.ConfigType.GLOBAL, "automation.user_path.paths", [])
|
||||
paths = self.__cfg_mgr.get(CfgKey.GLOBAL.AUTOMATION.USER_PATH.PATHS, [])
|
||||
if user_config_path not in paths:
|
||||
paths.append(user_config_path)
|
||||
index = len(paths) - 1
|
||||
else:
|
||||
index = paths.index(user_config_path)
|
||||
self.__cfg_mgr.set(ConfigManager.ConfigType.GLOBAL, "automation.user_path", {"current": index, "paths": paths})
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.AUTOMATION.USER_PATH.ROOT, {"current": index, "paths": paths})
|
||||
else:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
@@ -1070,7 +1034,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
):
|
||||
|
||||
msg = ""
|
||||
|
||||
run_config_path = self.ExportRunConfigEdit.text()
|
||||
user_config_path = self.ExportUserConfigEdit.text()
|
||||
if run_config_path:
|
||||
|
||||
@@ -9,103 +9,113 @@ See the LICENSE file for details.
|
||||
"""
|
||||
import queue
|
||||
|
||||
import packaging.version as ver
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt, Signal, Slot, QTimer, QUrl,
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QMainWindow, QMenu, QSystemTrayIcon, QMessageBox
|
||||
QTimer,
|
||||
QUrl,
|
||||
Qt,
|
||||
Slot
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QTextCursor, QCloseEvent, QFont, QIcon, QDesktopServices
|
||||
QCloseEvent,
|
||||
QDesktopServices,
|
||||
QFont,
|
||||
QIcon,
|
||||
QTextCursor
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QMainWindow,
|
||||
QMenu,
|
||||
QMessageBox,
|
||||
QSystemTrayIcon
|
||||
)
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
from utils.ConfigUtils import ConfigUtils
|
||||
|
||||
from gui.resources.ui.Ui_ALMainWindow import Ui_ALMainWindow
|
||||
from gui.resources import ALResource
|
||||
from gui.ALConfigWidget import ALConfigWidget
|
||||
from gui.ALTimerTaskManageWidget import ALTimerTaskManageWidget
|
||||
from gui.ALAboutDialog import ALAboutDialog
|
||||
from gui.ALMainWorkers import TimerTaskWorker, AutoLibWorker
|
||||
from gui.ALBulletinDialog import ALBulletinDialog
|
||||
from gui.ALCheckUpdateWorker import ALCheckUpdateWorker
|
||||
from gui.ALCheckUpdateDialog import ALCheckUpdateDialog
|
||||
from gui.ALConfigWidget import ALConfigWidget
|
||||
from gui.ALSettingsWidget import ALSettingsWidget
|
||||
from gui.ALTimerTaskManageWidget import ALTimerTaskManageWidget
|
||||
from gui.ALMainWorker import AutoLibWorker
|
||||
from gui.ALBulletinPoller import ALBulletinPoller
|
||||
from gui.ALTimerTaskPoller import ALTimerTaskPoller
|
||||
from gui.ALVersionInfo import AL_VERSION
|
||||
from gui.resources import ALResource
|
||||
from gui.resources.ui.Ui_ALMainWindow import Ui_ALMainWindow
|
||||
from managers.bulletin.BulletinManager import instance as bulletinInstance
|
||||
from managers.config.ConfigUtils import ConfigUtils
|
||||
|
||||
|
||||
class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
|
||||
# signal : timer task
|
||||
timerTaskIsRunning = Signal(dict)
|
||||
timerTaskIsExecuted = Signal(dict)
|
||||
timerTaskIsError = Signal(dict)
|
||||
|
||||
def __init__(
|
||||
self
|
||||
):
|
||||
|
||||
MsgBase.__init__(self, queue.Queue(), queue.Queue())
|
||||
QMainWindow.__init__(self)
|
||||
self.__timer_task_queue = queue.Queue()
|
||||
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
||||
self.__alTimerTaskManageWidget = None
|
||||
self.__alConfigWidget = None
|
||||
self.__ALTimerTaskManageWidget = None
|
||||
self.__ALConfigWidget = None
|
||||
self.__ALSettingsWidget = None
|
||||
self.__ALBulletinDialog = None
|
||||
self.__auto_lib_thread = None
|
||||
self.__current_timer_task_thread = None
|
||||
self.__is_running_timer_task = False
|
||||
self.__bulletin_poller = ALBulletinPoller(self)
|
||||
self.__timer_task_poller = ALTimerTaskPoller(
|
||||
self,
|
||||
self._input_queue,
|
||||
self._output_queue,
|
||||
self.__config_paths
|
||||
)
|
||||
self.__notification_type = ""
|
||||
|
||||
self.setupUi(self)
|
||||
self.modifyUi()
|
||||
self.setupTray()
|
||||
self.connectSignals()
|
||||
self.startMsgPolling()
|
||||
self.startTimerTaskPolling()
|
||||
self.__timer_task_poller.start()
|
||||
self.__bulletin_poller.start()
|
||||
if bulletinInstance().autoFetch():
|
||||
QTimer.singleShot(1000, self.__bulletin_poller.fetchNow)
|
||||
self._showLog("主窗口初始化完成")
|
||||
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.icon = QIcon(":/res/icon/icons/AutoLibrary_32x32.ico")
|
||||
self.setWindowIcon(self.icon)
|
||||
self.Icon = QIcon(":/res/icons/AutoLibrary_Logo_64.svg")
|
||||
self.setWindowIcon(self.Icon)
|
||||
self.MessageIOTextEdit.setFont(QFont("Courier New", 10))
|
||||
self.ManualAction.triggered.connect(self.onManualActionTriggered)
|
||||
self.CheckUpdateAction.triggered.connect(self.onCheckUpdateActionTriggered)
|
||||
self.AboutAction.triggered.connect(self.onAboutActionTriggered)
|
||||
|
||||
self.SettingsAction.triggered.connect(self.onSettingsActionTriggered)
|
||||
self.BulletinAction.triggered.connect(self.onBulletinActionTriggered)
|
||||
# initialize timer task widget, but not show it
|
||||
try:
|
||||
self.__alTimerTaskManageWidget = ALTimerTaskManageWidget(self)
|
||||
self.__ALTimerTaskManageWidget = ALTimerTaskManageWidget(self)
|
||||
except Exception as e:
|
||||
QMessageBox.critical(
|
||||
self,
|
||||
"错误 - AutoLibrary",
|
||||
f"初始化定时任务功能失败: \n{e}"
|
||||
)
|
||||
self.__alTimerTaskManageWidget = None
|
||||
self.__ALTimerTaskManageWidget = None
|
||||
self.TimerTaskManageWidgetButton.setEnabled(False)
|
||||
self.TimerTaskManageWidgetButton.setToolTip("定时任务功能初始化失败, 请检查配置文件。")
|
||||
return
|
||||
self.timerTaskIsRunning.connect(self.__alTimerTaskManageWidget.onTimerTaskIsRunning)
|
||||
self.timerTaskIsExecuted.connect(self.__alTimerTaskManageWidget.onTimerTaskIsExecuted)
|
||||
self.timerTaskIsError.connect(self.__alTimerTaskManageWidget.onTimerTaskIsError)
|
||||
self.__alTimerTaskManageWidget.timerTaskIsReady.connect(self.onTimerTaskIsReady)
|
||||
self.__alTimerTaskManageWidget.timerTaskManageWidgetIsClosed.connect(self.onTimerTaskManageWidgetClosed)
|
||||
self.__alTimerTaskManageWidget.setWindowFlags(Qt.WindowType.Window|Qt.WindowType.WindowCloseButtonHint)
|
||||
|
||||
|
||||
def onAboutActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
about_dialog = ALAboutDialog(self)
|
||||
about_dialog.exec()
|
||||
|
||||
|
||||
def onManualActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
url = QUrl("https://www.autolibrary.kenanzhu.com/manuals")
|
||||
QDesktopServices.openUrl(url)
|
||||
|
||||
self.__timer_task_poller.taskRunning.connect(self.onTimerTaskRunning)
|
||||
self.__timer_task_poller.taskFinished.connect(self.onTimerTaskFinished)
|
||||
self.__timer_task_poller.taskRunning.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsRunning)
|
||||
self.__timer_task_poller.taskExecuted.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsExecuted)
|
||||
self.__timer_task_poller.taskError.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsError)
|
||||
self.__ALTimerTaskManageWidget.timerTaskIsReady.connect(self.__timer_task_poller.enqueue)
|
||||
self.__ALTimerTaskManageWidget.timerTaskManageWidgetIsClosed.connect(self.onTimerTaskManageWidgetClosed)
|
||||
self.__ALTimerTaskManageWidget.setWindowFlags(Qt.WindowType.Window|Qt.WindowType.WindowCloseButtonHint)
|
||||
|
||||
def setupTray(
|
||||
self
|
||||
@@ -114,9 +124,8 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
if not QSystemTrayIcon.isSystemTrayAvailable():
|
||||
self._showTrace("操作系统不支持系统托盘功能, 无法创建系统托盘图标", self.TraceLevel.WARNING)
|
||||
return
|
||||
self.TrayIcon = QSystemTrayIcon(self.icon, self)
|
||||
self.TrayIcon = QSystemTrayIcon(self.Icon, self)
|
||||
self.TrayIcon.setToolTip("AutoLibrary")
|
||||
|
||||
self.TrayMenu = QMenu()
|
||||
self.TrayMenu.addAction("显示主窗口", self.showNormal)
|
||||
self.TrayMenu.addAction("显示定时窗口", self.onTimerTaskManageWidgetButtonClicked)
|
||||
@@ -124,16 +133,18 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self.TrayMenu.addSeparator()
|
||||
self.TrayMenu.addAction("退出", self.close)
|
||||
self.TrayIcon.setContextMenu(self.TrayMenu)
|
||||
|
||||
self.TrayIcon.activated.connect(self.onTrayIconActivated)
|
||||
self.TrayIcon.messageClicked.connect(self.onTrayMessageClicked)
|
||||
self.TrayIcon.show()
|
||||
|
||||
|
||||
def hideToTray(
|
||||
self
|
||||
):
|
||||
|
||||
self.hide()
|
||||
self.__notification_type = ""
|
||||
if not hasattr(self, "TrayIcon"):
|
||||
return
|
||||
self.TrayIcon.showMessage(
|
||||
"AutoLibrary",
|
||||
"\n已最小化到托盘",
|
||||
@@ -141,16 +152,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
2000
|
||||
)
|
||||
|
||||
|
||||
def onTrayIconActivated(
|
||||
self,
|
||||
reason: QSystemTrayIcon.ActivationReason
|
||||
):
|
||||
|
||||
if reason == QSystemTrayIcon.DoubleClick:
|
||||
self.showNormal()
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
@@ -161,7 +162,7 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self.StopButton.clicked.connect(self.onStopButtonClicked)
|
||||
self.SendButton.clicked.connect(self.onSendButtonClicked)
|
||||
self.MessageEdit.returnPressed.connect(self.onSendButtonClicked)
|
||||
|
||||
self.__bulletin_poller.newBulletinsDetected.connect(self.onBulletinPollerNewBulletins)
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
@@ -174,21 +175,25 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
return
|
||||
if self.__msg_queue_timer and self.__msg_queue_timer.isActive():
|
||||
self.__msg_queue_timer.stop()
|
||||
if self.__timer_task_timer and self.__timer_task_timer.isActive():
|
||||
self.__timer_task_timer.stop()
|
||||
if self.__is_running_timer_task:
|
||||
self.__current_timer_task_thread.wait(2000)
|
||||
self.__current_timer_task_thread.deleteLater()
|
||||
if self.__alTimerTaskManageWidget:
|
||||
self.__alTimerTaskManageWidget.close()
|
||||
self.__alTimerTaskManageWidget.deleteLater()
|
||||
if self.__alConfigWidget:
|
||||
self.__alConfigWidget.close()
|
||||
if self.__timer_task_poller:
|
||||
self.__timer_task_poller.stop()
|
||||
if self.__ALTimerTaskManageWidget:
|
||||
self.__ALTimerTaskManageWidget.close()
|
||||
self.__ALTimerTaskManageWidget.deleteLater()
|
||||
if self.__ALConfigWidget:
|
||||
self.__ALConfigWidget.close()
|
||||
# the config widget is already deleted in the 'self.onConfigWidgetClosed'
|
||||
if self.__ALSettingsWidget:
|
||||
self.__ALSettingsWidget.close()
|
||||
# the settings widget is already deleted in the 'self.onSettingsWidgetClosed'
|
||||
if self.__ALBulletinDialog:
|
||||
self.__ALBulletinDialog.close()
|
||||
# the bulletin dialog is already deleted in the 'self.onBulletinDialogClosed'
|
||||
if self.__bulletin_poller:
|
||||
self.__bulletin_poller.stop()
|
||||
self._showLog("主窗口关闭")
|
||||
QMainWindow.closeEvent(self, event)
|
||||
|
||||
|
||||
def appendToTextEdit(
|
||||
self,
|
||||
text: str
|
||||
@@ -202,7 +207,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
scrollbar = self.MessageIOTextEdit.verticalScrollBar()
|
||||
scrollbar.setValue(scrollbar.maximum())
|
||||
|
||||
|
||||
def startMsgPolling(
|
||||
self
|
||||
):
|
||||
@@ -211,50 +215,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self.__msg_queue_timer.timeout.connect(self.pollMsgQueue)
|
||||
self.__msg_queue_timer.start(100)
|
||||
|
||||
|
||||
def startTimerTaskPolling(
|
||||
self
|
||||
):
|
||||
|
||||
self.__timer_task_timer = QTimer()
|
||||
self.__timer_task_timer.timeout.connect(self.pollTimerTaskQueue)
|
||||
self.__timer_task_timer.start(500)
|
||||
|
||||
|
||||
def pollTimerTaskQueue(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__is_running_timer_task:
|
||||
return
|
||||
try:
|
||||
while not self.__is_running_timer_task:
|
||||
timer_task = self.__timer_task_queue.get_nowait()
|
||||
self.timerTaskIsRunning.emit(timer_task)
|
||||
self.__timer_task_timer.stop()
|
||||
self.__is_running_timer_task = True
|
||||
self.setControlButtons(None, True, False)
|
||||
if not timer_task["silent"]:
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n已开始执行定时任务: \n{timer_task['name']}",
|
||||
QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self.showNormal()
|
||||
self.__current_timer_task_thread = TimerTaskWorker(
|
||||
timer_task,
|
||||
self._input_queue,
|
||||
self._output_queue,
|
||||
self.__config_paths
|
||||
)
|
||||
self.__current_timer_task_thread.timerTaskWorkerIsFinished.connect(self.onTimerTaskFinished)
|
||||
self.__current_timer_task_thread.start()
|
||||
except queue.Empty:
|
||||
self.__is_running_timer_task = False
|
||||
pass
|
||||
|
||||
|
||||
def setControlButtons(
|
||||
self,
|
||||
config_button_enabled: bool,
|
||||
@@ -282,6 +242,145 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
except queue.Empty:
|
||||
pass
|
||||
|
||||
@Slot(int)
|
||||
def onBulletinPollerNewBulletins(
|
||||
self,
|
||||
count: int
|
||||
):
|
||||
|
||||
if not hasattr(self, "TrayIcon"):
|
||||
return
|
||||
self.__notification_type = "bulletin"
|
||||
self.TrayIcon.showMessage(
|
||||
"公告栏 - AutoLibrary",
|
||||
f"有 {count} 条新公告,点击查看详情。",
|
||||
QSystemTrayIcon.MessageIcon.Information,
|
||||
3000
|
||||
)
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskRunning(
|
||||
self,
|
||||
timer_task: dict
|
||||
):
|
||||
|
||||
self.setControlButtons(None, True, False)
|
||||
self.__notification_type = ""
|
||||
if not hasattr(self, "TrayIcon"):
|
||||
return
|
||||
if not timer_task.get("silent", False):
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n已开始执行定时任务: \n{timer_task['name']}",
|
||||
QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self.showNormal()
|
||||
|
||||
@Slot(bool, dict)
|
||||
def onTimerTaskFinished(
|
||||
self,
|
||||
is_error: bool,
|
||||
timer_task: dict
|
||||
):
|
||||
|
||||
self.setControlButtons(None, False, True)
|
||||
self.__notification_type = ""
|
||||
if not hasattr(self, "TrayIcon"):
|
||||
return
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n定时任务 '{timer_task['name']}' 执行{'失败' if is_error else '完成'}",
|
||||
QSystemTrayIcon.MessageIcon.Warning if is_error else QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self._showTrace(
|
||||
f"定时任务 {timer_task['name']} 执行{'失败' if is_error else '完成'}, uuid: {timer_task['uuid']}"
|
||||
)
|
||||
|
||||
@Slot(dict)
|
||||
def onCheckUpdateIsFinished(
|
||||
self,
|
||||
data: dict
|
||||
):
|
||||
|
||||
worker = self.sender()
|
||||
if worker is not self.__check_update_worker:
|
||||
return
|
||||
worker.checkUpdateWorkerIsFinished.disconnect(self.onCheckUpdateIsFinished)
|
||||
worker.checkUpdateWorkerFinishedWithError.disconnect(self.onCheckUpdateFinishedWithError)
|
||||
worker.wait(3000)
|
||||
worker.deleteLater()
|
||||
self.__check_update_worker = None
|
||||
tag_name = data.get("tag_name", "")
|
||||
html_url = data.get("html_url", "")
|
||||
latest_version = tag_name.lstrip("v")
|
||||
try:
|
||||
local_ver = ver.Version(AL_VERSION)
|
||||
remote_ver = ver.Version(latest_version)
|
||||
except ver.InvalidVersion:
|
||||
self._showTrace("版本号解析失败, 无法比较版本", self.TraceLevel.WARNING)
|
||||
return
|
||||
if remote_ver > local_ver:
|
||||
ALCheckUpdateDialog.showResult(
|
||||
self,
|
||||
has_update=True,
|
||||
current_version=AL_VERSION,
|
||||
latest_version=latest_version,
|
||||
tag_name=tag_name,
|
||||
html_url=html_url
|
||||
)
|
||||
else:
|
||||
ALCheckUpdateDialog.showResult(
|
||||
self,
|
||||
has_update=False,
|
||||
current_version=AL_VERSION
|
||||
)
|
||||
self._showLog("检查更新完成")
|
||||
|
||||
@Slot(str)
|
||||
def onCheckUpdateFinishedWithError(
|
||||
self,
|
||||
error_message: str
|
||||
):
|
||||
|
||||
worker = self.sender()
|
||||
if worker is not self.__check_update_worker:
|
||||
return
|
||||
worker.checkUpdateWorkerIsFinished.disconnect(self.onCheckUpdateIsFinished)
|
||||
worker.checkUpdateWorkerFinishedWithError.disconnect(self.onCheckUpdateFinishedWithError)
|
||||
worker.wait(3000)
|
||||
worker.deleteLater()
|
||||
self.__check_update_worker = None
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"检查更新 - AutoLibrary",
|
||||
f"检查更新失败: \n{error_message}",
|
||||
)
|
||||
self._showLog("检查更新失败")
|
||||
|
||||
@Slot()
|
||||
def onBulletinDialogClosed(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__ALBulletinDialog:
|
||||
self.__ALBulletinDialog.finished.disconnect(self.onBulletinDialogClosed)
|
||||
self.__ALBulletinDialog.deleteLater()
|
||||
self.__ALBulletinDialog = None
|
||||
self.__bulletin_poller.setDialogOpen(False)
|
||||
|
||||
@Slot()
|
||||
def onSettingsWidgetClosed(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__ALSettingsWidget:
|
||||
self.__ALSettingsWidget.settingsWidgetIsClosed.disconnect(self.onSettingsWidgetClosed)
|
||||
self.__ALSettingsWidget.deleteLater()
|
||||
self.__ALSettingsWidget = None
|
||||
self.SettingsAction.setEnabled(True)
|
||||
|
||||
@Slot()
|
||||
def onTimerTaskManageWidgetClosed(
|
||||
self
|
||||
@@ -294,59 +393,106 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self
|
||||
):
|
||||
|
||||
if self.__alConfigWidget:
|
||||
self.__alConfigWidget.configWidgetIsClosed.disconnect(self.onConfigWidgetClosed)
|
||||
self.__alConfigWidget.deleteLater()
|
||||
self.__alConfigWidget = None
|
||||
if self.__ALConfigWidget:
|
||||
self.__ALConfigWidget.configWidgetIsClosed.disconnect(self.onConfigWidgetClosed)
|
||||
self.__ALConfigWidget.deleteLater()
|
||||
self.__ALConfigWidget = None
|
||||
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
||||
self.__timer_task_poller.updateConfigPaths(self.__config_paths)
|
||||
self.setControlButtons(True, None, None)
|
||||
self._showLog("配置窗口已关闭,配置文件路径已更新")
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskIsReady(
|
||||
self,
|
||||
timer_task: dict
|
||||
@Slot()
|
||||
def onBulletinActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
self.__timer_task_queue.put(timer_task)
|
||||
if self.__ALBulletinDialog is None:
|
||||
self.__ALBulletinDialog = ALBulletinDialog(self)
|
||||
self.__ALBulletinDialog.finished.connect(self.onBulletinDialogClosed)
|
||||
self.__bulletin_poller.setDialogOpen(True)
|
||||
self.__ALBulletinDialog.show()
|
||||
self.__ALBulletinDialog.raise_()
|
||||
self.__ALBulletinDialog.activateWindow()
|
||||
self._showLog("打开公告栏窗口")
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskFinished(
|
||||
self,
|
||||
is_error: bool,
|
||||
timer_task: dict
|
||||
@Slot()
|
||||
def onSettingsActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
self.__current_timer_task_thread.wait(1000)
|
||||
self.__current_timer_task_thread.timerTaskWorkerIsFinished.disconnect(self.onTimerTaskFinished)
|
||||
self.__current_timer_task_thread.deleteLater()
|
||||
self.__current_timer_task_thread = None
|
||||
self.setControlButtons(None, False, True)
|
||||
self.__is_running_timer_task = False
|
||||
self.__timer_task_timer.start(500)
|
||||
timer_task["executed"] = True
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n定时任务 '{timer_task['name']}' 执行{'失败' if is_error else '完成'}",
|
||||
QSystemTrayIcon.MessageIcon.Warning if is_error else QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self._showTrace(
|
||||
f"定时任务 {timer_task['name']} 执行{'失败' if is_error else '完成'}, uuid: {timer_task['uuid']}"
|
||||
)
|
||||
if not is_error:
|
||||
self.timerTaskIsExecuted.emit(timer_task)
|
||||
else:
|
||||
self.timerTaskIsError.emit(timer_task)
|
||||
if self.__ALSettingsWidget is None:
|
||||
self.__ALSettingsWidget = ALSettingsWidget(self)
|
||||
self.__ALSettingsWidget.settingsWidgetIsClosed.connect(self.onSettingsWidgetClosed)
|
||||
self.__ALSettingsWidget.openBulletinRequested.connect(self.onBulletinActionTriggered)
|
||||
self.__ALSettingsWidget.show()
|
||||
self.__ALSettingsWidget.raise_()
|
||||
self.__ALSettingsWidget.activateWindow()
|
||||
self.SettingsAction.setEnabled(False)
|
||||
self._showLog("打开全局设置窗口")
|
||||
|
||||
@Slot()
|
||||
def onAboutActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
AboutDialog = ALAboutDialog(self)
|
||||
AboutDialog.exec()
|
||||
|
||||
@Slot()
|
||||
def onManualActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
url = QUrl("https://manuals.autolibrary.kenanzhu.com")
|
||||
QDesktopServices.openUrl(url)
|
||||
|
||||
@Slot()
|
||||
def onCheckUpdateActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
if hasattr(self, '__check_update_worker') and self.__check_update_worker is not None:
|
||||
return
|
||||
self.__check_update_worker = ALCheckUpdateWorker(self)
|
||||
self.__check_update_worker.checkUpdateWorkerIsFinished.connect(self.onCheckUpdateIsFinished)
|
||||
self.__check_update_worker.checkUpdateWorkerFinishedWithError.connect(self.onCheckUpdateFinishedWithError)
|
||||
self.__check_update_worker.start()
|
||||
self._showLog("正在检查更新...")
|
||||
|
||||
@Slot()
|
||||
def onTrayMessageClicked(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__notification_type == "bulletin":
|
||||
self.__notification_type = ""
|
||||
self.onBulletinActionTriggered()
|
||||
|
||||
@Slot(QSystemTrayIcon.ActivationReason)
|
||||
def onTrayIconActivated(
|
||||
self,
|
||||
reason: QSystemTrayIcon.ActivationReason
|
||||
):
|
||||
|
||||
if reason == QSystemTrayIcon.DoubleClick:
|
||||
self.showNormal()
|
||||
|
||||
@Slot()
|
||||
def onTimerTaskManageWidgetButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
self.__alTimerTaskManageWidget.show()
|
||||
self.__alTimerTaskManageWidget.raise_()
|
||||
self.__alTimerTaskManageWidget.activateWindow()
|
||||
if self.__ALTimerTaskManageWidget is None:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"警告 - AutoLibrary",
|
||||
"定时任务功能初始化失败, 请检查配置文件。"
|
||||
)
|
||||
return
|
||||
self.__ALTimerTaskManageWidget.show()
|
||||
self.__ALTimerTaskManageWidget.raise_()
|
||||
self.__ALTimerTaskManageWidget.activateWindow()
|
||||
self.TimerTaskManageWidgetButton.setEnabled(False)
|
||||
self._showLog("打开定时任务管理窗口")
|
||||
|
||||
@@ -355,12 +501,12 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self
|
||||
):
|
||||
|
||||
if self.__alConfigWidget is None:
|
||||
self.__alConfigWidget = ALConfigWidget(self)
|
||||
self.__alConfigWidget.configWidgetIsClosed.connect(self.onConfigWidgetClosed)
|
||||
self.__alConfigWidget.show()
|
||||
self.__alConfigWidget.raise_()
|
||||
self.__alConfigWidget.activateWindow()
|
||||
if self.__ALConfigWidget is None:
|
||||
self.__ALConfigWidget = ALConfigWidget(self)
|
||||
self.__ALConfigWidget.configWidgetIsClosed.connect(self.onConfigWidgetClosed)
|
||||
self.__ALConfigWidget.show()
|
||||
self.__ALConfigWidget.raise_()
|
||||
self.__ALConfigWidget.activateWindow()
|
||||
self.ConfigButton.setEnabled(False)
|
||||
self._showLog("打开配置窗口")
|
||||
|
||||
|
||||
@@ -12,13 +12,14 @@ import time
|
||||
import queue
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Slot, Signal, QThread
|
||||
Signal,
|
||||
QThread,
|
||||
)
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
from operators.AutoLib import AutoLib
|
||||
from pages.AutoLib import AutoLib
|
||||
from utils.JSONReader import JSONReader
|
||||
from utils.AutoScriptEngine import AutoScriptEngine
|
||||
from autoscript import createEngine
|
||||
|
||||
|
||||
class AutoLibWorker(MsgBase, QThread):
|
||||
@@ -30,14 +31,13 @@ class AutoLibWorker(MsgBase, QThread):
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
config_paths: dict
|
||||
config_paths: dict,
|
||||
):
|
||||
|
||||
MsgBase.__init__(self, input_queue, output_queue)
|
||||
QThread.__init__(self)
|
||||
self.__config_paths = config_paths
|
||||
|
||||
|
||||
def checkTimeAvailable(
|
||||
self,
|
||||
) -> bool:
|
||||
@@ -46,13 +46,12 @@ class AutoLibWorker(MsgBase, QThread):
|
||||
if current_time >= "23:30" or current_time <= "07:30":
|
||||
self._showTrace(
|
||||
"当前时间不在图书馆开放时间内, 请在 07:30 - 23:30 之间尝试",
|
||||
self.TraceLevel.WARNING
|
||||
self.TraceLevel.WARNING,
|
||||
)
|
||||
return False
|
||||
self._showLog(f"时间检查通过, 当前时间: {current_time}", self.TraceLevel.INFO)
|
||||
return True
|
||||
|
||||
|
||||
def checkConfigPaths(
|
||||
self,
|
||||
) -> bool:
|
||||
@@ -62,85 +61,113 @@ class AutoLibWorker(MsgBase, QThread):
|
||||
):
|
||||
self._showTrace(
|
||||
"配置文件路径不存在, 请检查配置文件路径是否正确",
|
||||
self.TraceLevel.ERROR
|
||||
self.TraceLevel.ERROR,
|
||||
)
|
||||
return False
|
||||
self._showLog(f"配置文件路径检查通过, 路径: {self.__config_paths}", self.TraceLevel.INFO)
|
||||
self._showLog(
|
||||
f"配置文件路径检查通过, 路径: {self.__config_paths}",
|
||||
self.TraceLevel.INFO,
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def loadConfigs(
|
||||
self
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
self._showTrace(
|
||||
f"正在加载配置文件, 运行配置文件路径: {self.__config_paths["run"]}",
|
||||
no_log=True
|
||||
no_log=True,
|
||||
)
|
||||
self._run_config = JSONReader(self.__config_paths["run"]).data()
|
||||
self._showTrace(
|
||||
f"正在加载配置文件, 用户配置文件路径: {self.__config_paths["user"]}",
|
||||
no_log=True
|
||||
no_log=True,
|
||||
)
|
||||
self._user_config = JSONReader(self.__config_paths["user"]).data()
|
||||
if self._run_config is None or self._user_config is None:
|
||||
self._showTrace(
|
||||
"配置文件加载失败, 请检查配置文件是否正确",
|
||||
self.TraceLevel.ERROR
|
||||
self.TraceLevel.ERROR,
|
||||
)
|
||||
return False
|
||||
if not self._user_config.get("groups"):
|
||||
self._showTrace(
|
||||
"用户配置文件中无有效任务组, 请检查用户配置文件是否正确",
|
||||
self.TraceLevel.WARNING
|
||||
self.TraceLevel.WARNING,
|
||||
)
|
||||
return False
|
||||
self._showLog(
|
||||
f"配置文件加载成功, 任务组数量: {len(self._user_config.get('groups', []))}",
|
||||
self.TraceLevel.INFO
|
||||
f"配置文件加载成功, 任务组数量: {len(self._user_config.get("groups"))}",
|
||||
self.TraceLevel.INFO,
|
||||
)
|
||||
return True
|
||||
|
||||
def _runName(
|
||||
self,
|
||||
) -> str:
|
||||
|
||||
return "常规任务"
|
||||
|
||||
def _beforeCreateAutoLib(
|
||||
self,
|
||||
):
|
||||
|
||||
return
|
||||
|
||||
def _onChecksFailed(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
return True
|
||||
|
||||
def _onFinished(
|
||||
self,
|
||||
):
|
||||
|
||||
self.autoLibWorkerIsFinished.emit()
|
||||
|
||||
def _onError(
|
||||
self,
|
||||
error_msg: str,
|
||||
):
|
||||
|
||||
self._showTrace(error_msg, self.TraceLevel.ERROR)
|
||||
self.autoLibWorkerFinishedWithError.emit()
|
||||
|
||||
def run(
|
||||
self
|
||||
self,
|
||||
):
|
||||
|
||||
auto_lib = None
|
||||
self._showTrace("AutoLibrary 开始运行")
|
||||
if not self.checkTimeAvailable()\
|
||||
or not self.checkConfigPaths():
|
||||
# time or config existence check failed, skip and finish
|
||||
pass
|
||||
self._showTrace(f"{self._runName()} 开始运行")
|
||||
|
||||
if not self.checkTimeAvailable() or not self.checkConfigPaths():
|
||||
if not self._onChecksFailed():
|
||||
return
|
||||
else:
|
||||
try:
|
||||
if not self.loadConfigs():
|
||||
raise Exception("配置文件加载失败")
|
||||
self._beforeCreateAutoLib()
|
||||
auto_lib = AutoLib(
|
||||
self._input_queue,
|
||||
self._output_queue,
|
||||
self._run_config
|
||||
self._run_config,
|
||||
)
|
||||
groups = self._user_config.get("groups")
|
||||
for group in groups:
|
||||
if not group["enabled"]:
|
||||
self._showTrace(f"任务组 {group["name"]} 已跳过", no_log=True)
|
||||
if not group.get("enabled", False):
|
||||
self._showTrace(f"任务组 {group.get("name", "未知")} 已跳过", no_log=True)
|
||||
continue
|
||||
self._showTrace(f"正在运行任务组 {group["name"]}", no_log=True)
|
||||
auto_lib.run(
|
||||
{ "users": group.get("users", []) }
|
||||
)
|
||||
self._showTrace(f"正在运行任务组 {group.get("name", "未知")}", no_log=True)
|
||||
auto_lib.run({"users": group.get("users", [])})
|
||||
except Exception as e:
|
||||
self._showTrace(
|
||||
f"AutoLibrary 运行时发生异常 : {e}",
|
||||
self.TraceLevel.ERROR
|
||||
)
|
||||
self.autoLibWorkerFinishedWithError.emit()
|
||||
self._onError(f"{self._runName()} 运行时发生异常 : {e}")
|
||||
return
|
||||
if auto_lib:
|
||||
auto_lib.close()
|
||||
self._showTrace("AutoLibrary 运行结束")
|
||||
self.autoLibWorkerIsFinished.emit()
|
||||
self._showTrace(f"{self._runName()} 运行结束")
|
||||
self._onFinished()
|
||||
|
||||
|
||||
class TimerTaskWorker(AutoLibWorker):
|
||||
@@ -152,72 +179,54 @@ class TimerTaskWorker(AutoLibWorker):
|
||||
timer_task: dict,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
config_paths: dict
|
||||
config_paths: dict,
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue, config_paths)
|
||||
self.__timer_task = timer_task
|
||||
|
||||
self.autoLibWorkerIsFinished.connect(self.onTimerTaskIsFinished)
|
||||
self.autoLibWorkerFinishedWithError.connect(self.onTimerTaskFinishedWithError)
|
||||
def _runName(
|
||||
self,
|
||||
) -> str:
|
||||
|
||||
return f"定时任务 '{self.__timer_task.get("name", "未知")}'"
|
||||
|
||||
def run(
|
||||
self
|
||||
def _beforeCreateAutoLib(
|
||||
self,
|
||||
):
|
||||
|
||||
self.applyRepeatAutoScript()
|
||||
|
||||
def _onChecksFailed(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
self._showTrace("定时任务跳过执行: 时间或配置文件检查未通过")
|
||||
self.timerTaskWorkerIsFinished.emit(False, self.__timer_task)
|
||||
return False
|
||||
|
||||
def _onFinished(
|
||||
self,
|
||||
):
|
||||
|
||||
self._showTrace(f"定时任务 {self.__timer_task['name']} 开始运行")
|
||||
if not self.checkTimeAvailable() or not self.checkConfigPaths():
|
||||
self._showTrace("定时任务跳过执行 (时间或配置文件检查未通过)")
|
||||
self.timerTaskWorkerIsFinished.emit(False, self.__timer_task)
|
||||
return
|
||||
try:
|
||||
if not self.loadConfigs():
|
||||
raise Exception("配置文件加载失败")
|
||||
self.applyRepeatAutoScript()
|
||||
auto_lib = AutoLib(
|
||||
self._input_queue,
|
||||
self._output_queue,
|
||||
self._run_config
|
||||
)
|
||||
groups = self._user_config.get("groups")
|
||||
for group in groups:
|
||||
if not group["enabled"]:
|
||||
self._showTrace(
|
||||
f"任务组 {group['name']} 已跳过",
|
||||
no_log=True
|
||||
)
|
||||
continue
|
||||
self._showTrace(
|
||||
f"正在运行任务组 {group['name']}",
|
||||
no_log=True
|
||||
)
|
||||
auto_lib.run(
|
||||
{"users": group.get("users", [])}
|
||||
)
|
||||
auto_lib.close()
|
||||
except Exception as e:
|
||||
self._showTrace(
|
||||
f"定时任务 {self.__timer_task['name']} 运行时发生异常: {e}",
|
||||
self.TraceLevel.ERROR
|
||||
)
|
||||
self.timerTaskWorkerIsFinished.emit(True, self.__timer_task)
|
||||
return
|
||||
self._showTrace(f"定时任务 {self.__timer_task['name']} 运行结束")
|
||||
self.timerTaskWorkerIsFinished.emit(False, self.__timer_task)
|
||||
|
||||
def _onError(
|
||||
self,
|
||||
error_msg: str,
|
||||
):
|
||||
|
||||
self._showTrace(error_msg, self.TraceLevel.ERROR)
|
||||
self.timerTaskWorkerIsFinished.emit(True, self.__timer_task)
|
||||
|
||||
def applyRepeatAutoScript(
|
||||
self
|
||||
self,
|
||||
):
|
||||
|
||||
auto_script = self.__timer_task.get("repeat_auto_script", "")
|
||||
if not auto_script or not auto_script.strip():
|
||||
return
|
||||
self._showTrace(
|
||||
f"检测到重复定时任务 AutoScript, 开始执行...",
|
||||
no_log=True
|
||||
)
|
||||
self._showTrace("检测到重复定时任务 AutoScript, 开始执行...", no_log=True)
|
||||
groups = self._user_config.get("groups", [])
|
||||
affected_count = 0
|
||||
for group in groups:
|
||||
@@ -225,34 +234,15 @@ class TimerTaskWorker(AutoLibWorker):
|
||||
continue
|
||||
for user in group.get("users", []):
|
||||
try:
|
||||
AutoScriptEngine.execute(auto_script, user)
|
||||
engine = createEngine()
|
||||
engine.execute(auto_script, user)
|
||||
affected_count += 1
|
||||
except ValueError as e:
|
||||
self._showTrace(
|
||||
f"AutoScript 执行错误 (用户 {user['username']}): {e}",
|
||||
self.TraceLevel.ERROR
|
||||
f"AutoScript 执行错误 (用户 {user.get("username", "未知")}): {e}",
|
||||
self.TraceLevel.ERROR,
|
||||
)
|
||||
self._showLog(
|
||||
f"AutoScript 执行完毕, "
|
||||
f"影响 {affected_count} 个用户",
|
||||
self.TraceLevel.INFO
|
||||
f"AutoScript 执行完毕, 影响 {affected_count} 个用户",
|
||||
self.TraceLevel.INFO,
|
||||
)
|
||||
|
||||
@Slot()
|
||||
def onTimerTaskIsFinished(
|
||||
self
|
||||
):
|
||||
|
||||
self._showTrace(f"定时任务 {self.__timer_task['name']} 运行结束")
|
||||
self.timerTaskWorkerIsFinished.emit(False, self.__timer_task)
|
||||
|
||||
@Slot()
|
||||
def onTimerTaskFinishedWithError(
|
||||
self
|
||||
):
|
||||
|
||||
self._showTrace(
|
||||
f"定时任务 {self.__timer_task['name']} 运行时发生异常",
|
||||
self.TraceLevel.ERROR
|
||||
)
|
||||
self.timerTaskWorkerIsFinished.emit(True, self.__timer_task)
|
||||
@@ -63,14 +63,12 @@ class ALSeatFrame(QFrame):
|
||||
self.toggleSelection()
|
||||
self.clicked.emit(self.__seat_number)
|
||||
|
||||
|
||||
def isSelected(
|
||||
self
|
||||
):
|
||||
|
||||
return self.__is_selected
|
||||
|
||||
|
||||
def toggleSelection(self):
|
||||
|
||||
self.__is_selected = not self.__is_selected
|
||||
|
||||
@@ -8,20 +8,25 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from PySide6.QtCore import (
|
||||
Qt, Slot, Signal
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog, QLabel, QHBoxLayout, QVBoxLayout,
|
||||
QPushButton,
|
||||
Qt,
|
||||
Signal,
|
||||
Slot
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QCloseEvent
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QPushButton,
|
||||
QVBoxLayout
|
||||
)
|
||||
|
||||
from gui.ALSeatMapView import ALSeatMapView
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
|
||||
|
||||
class ALSeatMapSelectDialog(QDialog):
|
||||
class ALSeatMapSelectDialog(CenterOnParentMixin, QDialog):
|
||||
|
||||
seatMapSelectDialogIsClosed = Signal(list)
|
||||
|
||||
@@ -42,7 +47,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
@@ -51,7 +55,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.setMinimumSize(800, 600)
|
||||
self.resize(800, 600)
|
||||
self.setWindowTitle(f"选择楼层座位 - AutoLibrary")
|
||||
|
||||
self.SeatMapWidgetMainLayout = QVBoxLayout(self)
|
||||
self.SeatMapWidgetMainLayout.setContentsMargins(5, 5, 5, 5)
|
||||
self.SeatMapWidgetMainLayout.setSpacing(5)
|
||||
@@ -59,10 +62,8 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.TitleLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.TitleLabel.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
|
||||
self.SeatMapWidgetMainLayout.addWidget(self.TitleLabel)
|
||||
|
||||
self.SeatMapGraphicsView = ALSeatMapView(None, self.__seats_data)
|
||||
self.SeatMapWidgetMainLayout.addWidget(self.SeatMapGraphicsView)
|
||||
|
||||
self.TipsLabel = QLabel(
|
||||
" 点击座位进行选择/取消选择, 最多选择1个座位 \n"
|
||||
" [操作方法: Ctrl+鼠标滚轮缩放 | 滚轮/拖拽/方向键 移动]"
|
||||
@@ -70,7 +71,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.TipsLabel.setAlignment(Qt.AlignmentFlag.AlignLeft)
|
||||
self.TipsLabel.setStyleSheet("color: #666; margin: 5px;")
|
||||
self.SeatMapWidgetMainLayout.addWidget(self.TipsLabel)
|
||||
|
||||
self.ConfirmButton = QPushButton("确认")
|
||||
self.ConfirmButton.setFixedSize(80, 25)
|
||||
self.ConfirmButton.setAutoDefault(True)
|
||||
@@ -85,7 +85,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.SeatMapWidgetControlLayout.addWidget(self.ConfirmButton)
|
||||
self.SeatMapWidgetMainLayout.addLayout(self.SeatMapWidgetControlLayout)
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
@@ -93,31 +92,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||
self.CancelButton.clicked.connect(self.onCancelButtonClicked)
|
||||
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
@@ -131,7 +105,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.seatMapSelectDialogIsClosed.emit(self.getSelectedSeats())
|
||||
super().closeEvent(event)
|
||||
|
||||
|
||||
def selectSeat(
|
||||
self,
|
||||
seat_number: str
|
||||
@@ -139,7 +112,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
|
||||
self.SeatMapGraphicsView.selectSeat(seat_number)
|
||||
|
||||
|
||||
def selectSeats(
|
||||
self,
|
||||
seat_numbers: list[str]
|
||||
@@ -147,14 +119,12 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
|
||||
return self.SeatMapGraphicsView.selectSeats(seat_numbers)
|
||||
|
||||
|
||||
def getSelectedSeats(
|
||||
self
|
||||
) -> list[str]:
|
||||
|
||||
return self.SeatMapGraphicsView.getSelectedSeats()
|
||||
|
||||
|
||||
def clearSelections(
|
||||
self
|
||||
):
|
||||
|
||||
@@ -8,14 +8,21 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from PySide6.QtCore import (
|
||||
Qt, Slot, QEvent
|
||||
Qt,
|
||||
Slot,
|
||||
QEvent
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QFrame, QWidget,
|
||||
QGridLayout, QGraphicsView, QGraphicsScene, QGraphicsItem
|
||||
QFrame,
|
||||
QWidget,
|
||||
QGridLayout,
|
||||
QGraphicsView,
|
||||
QGraphicsScene,
|
||||
QGraphicsItem
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QPainter, QWheelEvent
|
||||
QPainter,
|
||||
QWheelEvent
|
||||
)
|
||||
|
||||
from gui.ALSeatFrame import ALSeatFrame
|
||||
@@ -35,18 +42,6 @@ class ALSeatMapView(QGraphicsView):
|
||||
|
||||
self.setupUi()
|
||||
|
||||
@staticmethod
|
||||
def formatSeatNumber(
|
||||
seat_number: str
|
||||
) -> str:
|
||||
|
||||
if seat_number and not seat_number[-1].isdigit():
|
||||
digits = seat_number[:-1]
|
||||
letter = seat_number[-1]
|
||||
return digits.zfill(3) + letter
|
||||
return seat_number.zfill(3)
|
||||
|
||||
|
||||
def eventFilter(
|
||||
self,
|
||||
watched,
|
||||
@@ -61,7 +56,6 @@ class ALSeatMapView(QGraphicsView):
|
||||
return True
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
|
||||
def zoomGraphicsView(
|
||||
self,
|
||||
event: QWheelEvent
|
||||
@@ -80,7 +74,6 @@ class ALSeatMapView(QGraphicsView):
|
||||
self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
|
||||
self.scale(zoom_factor, zoom_factor)
|
||||
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
@@ -92,15 +85,12 @@ class ALSeatMapView(QGraphicsView):
|
||||
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||
self.viewport().installEventFilter(self)
|
||||
|
||||
self.SeatsContainerWidget = QWidget()
|
||||
self.SeatsContainerLayout = QGridLayout(self.SeatsContainerWidget)
|
||||
self.setupSeatMap()
|
||||
|
||||
self.ContainerProxy = self.SeatMapGraphicsScene.addWidget(self.SeatsContainerWidget)
|
||||
self.ContainerProxy.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, False)
|
||||
|
||||
|
||||
def setupSeatMap(
|
||||
self
|
||||
):
|
||||
@@ -111,21 +101,20 @@ class ALSeatMapView(QGraphicsView):
|
||||
seats_number = [seat.strip() for seat in row.split(",")]
|
||||
for seat_number in seats_number:
|
||||
if seat_number:
|
||||
seat_widget = ALSeatFrame(seat_number)
|
||||
seat_widget.clicked.connect(self.onSeatClicked)
|
||||
self.SeatsContainerLayout.addWidget(seat_widget, row_idx, col_idx)
|
||||
self.__seat_frames[seat_number] = seat_widget
|
||||
SeatWidget = ALSeatFrame(seat_number)
|
||||
SeatWidget.clicked.connect(self.onSeatClicked)
|
||||
self.SeatsContainerLayout.addWidget(SeatWidget, row_idx, col_idx)
|
||||
self.__seat_frames[seat_number] = SeatWidget
|
||||
else:
|
||||
spacer = QFrame()
|
||||
spacer.setFixedSize(20, 30)
|
||||
spacer.setStyleSheet("background-color: transparent; border: none;")
|
||||
self.SeatsContainerLayout.addWidget(spacer, row_idx, col_idx)
|
||||
Spacer = QFrame()
|
||||
Spacer.setFixedSize(20, 30)
|
||||
Spacer.setStyleSheet("background-color: transparent; border: none;")
|
||||
self.SeatsContainerLayout.addWidget(Spacer, row_idx, col_idx)
|
||||
col_idx += 1
|
||||
self.SeatsContainerLayout.setSpacing(20)
|
||||
self.SeatsContainerLayout.setContentsMargins(20, 20, 20, 20)
|
||||
self.SeatsContainerWidget.adjustSize()
|
||||
|
||||
|
||||
def selectSeat(
|
||||
self,
|
||||
seat_number: str
|
||||
@@ -142,7 +131,6 @@ class ALSeatMapView(QGraphicsView):
|
||||
widget.toggleSelection()
|
||||
self.__selected_seats.append(seat_number)
|
||||
|
||||
|
||||
def selectSeats(
|
||||
self,
|
||||
selected_seats: list
|
||||
@@ -152,14 +140,12 @@ class ALSeatMapView(QGraphicsView):
|
||||
for seat_number in selected_seats:
|
||||
self.selectSeat(seat_number)
|
||||
|
||||
|
||||
def getSelectedSeats(
|
||||
self
|
||||
) -> list[str]:
|
||||
|
||||
return self.__selected_seats
|
||||
|
||||
|
||||
def clearSelections(
|
||||
self
|
||||
):
|
||||
@@ -185,4 +171,15 @@ class ALSeatMapView(QGraphicsView):
|
||||
if len(self.__selected_seats) < 1:
|
||||
self.__selected_seats.append(seat_number)
|
||||
else:
|
||||
self.__seat_frames[seat_number].toggleSelection()
|
||||
self.__seat_frames[seat_number].toggleSelection()
|
||||
|
||||
@staticmethod
|
||||
def formatSeatNumber(
|
||||
seat_number: str
|
||||
) -> str:
|
||||
|
||||
if seat_number and not seat_number[-1].isdigit():
|
||||
digits = seat_number[:-1]
|
||||
letter = seat_number[-1]
|
||||
return digits.zfill(3) + letter
|
||||
return seat_number.zfill(3)
|
||||
|
||||
@@ -0,0 +1,562 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import requests
|
||||
import qtawesome as qta
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QProcess,
|
||||
Qt,
|
||||
QTimer,
|
||||
Signal,
|
||||
Slot
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QCloseEvent
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QFileDialog,
|
||||
QMessageBox,
|
||||
QStyleFactory,
|
||||
QWidget
|
||||
)
|
||||
|
||||
import managers.config.ConfigManager as ConfigManager
|
||||
from managers.bulletin.BulletinManager import instance as bulletinInstance
|
||||
from managers.log.LogManager import instance as logInstance
|
||||
from managers.theme.ThemeManager import(
|
||||
getActiveStyle,
|
||||
setActiveStyle,
|
||||
instance as themeInstance
|
||||
)
|
||||
|
||||
from gui.ALBulletinWorker import ALBulletinFetchWorker
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
from gui.resources.ui.Ui_ALSettingsWidget import Ui_ALSettingsWidget
|
||||
from interfaces.ConfigProvider import (
|
||||
CfgKey,
|
||||
ConfigProvider
|
||||
)
|
||||
|
||||
|
||||
def _applyCustomTheme(
|
||||
name: str,
|
||||
fallback_theme: str = "system"
|
||||
) -> bool:
|
||||
|
||||
if not name:
|
||||
themeInstance().clearTheme(fallback_theme)
|
||||
return True
|
||||
try:
|
||||
themeInstance().applyTheme(name)
|
||||
return True
|
||||
except Exception as e:
|
||||
logInstance().getLogger("ALSettingsWidget").warning(
|
||||
f"无法应用自定义主题 '{name}',回退到 {fallback_theme} 外观: {e}"
|
||||
)
|
||||
themeInstance().clearTheme(fallback_theme)
|
||||
return False
|
||||
|
||||
def _themeToReadable(
|
||||
need_theme: str
|
||||
) -> str:
|
||||
|
||||
if need_theme == "dark":
|
||||
return "深色"
|
||||
elif need_theme == "light":
|
||||
return "浅色"
|
||||
elif need_theme == "both":
|
||||
return "所有"
|
||||
else:
|
||||
return "未知"
|
||||
|
||||
def _restartApp(
|
||||
):
|
||||
|
||||
QApplication.instance().quit()
|
||||
QProcess.startDetached(sys.executable, sys.argv)
|
||||
|
||||
|
||||
class ALSettingsWidget(CenterOnParentMixin, QWidget, Ui_ALSettingsWidget):
|
||||
|
||||
settingsWidgetIsClosed = Signal()
|
||||
openBulletinRequested = Signal()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.__cfg_mgr: ConfigProvider = ConfigManager.instance()
|
||||
self.__original_theme: str = ""
|
||||
self.__original_custom_theme: str = ""
|
||||
self.__original_style: str = ""
|
||||
self.__original_bulletin_url: str = ""
|
||||
self.__original_bulletin_auto_fetch: bool = False
|
||||
self.__original_bulletin_sync_interval: int = 10
|
||||
|
||||
self.setupUi(self)
|
||||
self.modifyUi()
|
||||
self.connectSignals()
|
||||
self.loadSettings()
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
):
|
||||
|
||||
if hasattr(self, '__bulletin_test_worker') and self.__bulletin_test_worker is not None:
|
||||
self.__bulletin_test_worker.wait(3000)
|
||||
self.settingsWidgetIsClosed.emit()
|
||||
super().closeEvent(event)
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setWindowFlags(Qt.WindowType.Window)
|
||||
self.setNavigationIcons()
|
||||
color = QApplication.instance().palette().color(
|
||||
QApplication.instance().palette().ColorRole.WindowText
|
||||
).name()
|
||||
self.ImportCustomThemeButton.setIcon(qta.icon("fa6s.plus", color=color))
|
||||
self.ImportCustomThemeButton.setText("")
|
||||
self.RemoveCustomThemeButton.setIcon(qta.icon("fa6s.minus", color=color))
|
||||
self.RemoveCustomThemeButton.setText("")
|
||||
self.CustomThemeInfoLabel.setTextFormat(Qt.TextFormat.RichText)
|
||||
self.CustomThemeInfoLabel.setStyleSheet(
|
||||
"border: 1px solid palette(mid);"\
|
||||
"border-radius: 2px;"\
|
||||
"padding: 5px;"
|
||||
)
|
||||
self.NavigationList.setCurrentRow(0)
|
||||
self.NavigationList.currentRowChanged.connect(self.PageStack.setCurrentIndex)
|
||||
self.populateStyles()
|
||||
self.populateCustomThemes()
|
||||
|
||||
def setNavigationIcons(
|
||||
self
|
||||
):
|
||||
|
||||
app : QApplication | None = QApplication.instance()
|
||||
color = app.palette().color(app.palette().ColorRole.WindowText).name()
|
||||
item0 = self.NavigationList.item(0)
|
||||
if item0:
|
||||
item0.setIcon(qta.icon("fa6s.palette", color=color))
|
||||
item1 = self.NavigationList.item(1)
|
||||
if item1:
|
||||
item1.setIcon(qta.icon("fa6s.bullhorn", color=color))
|
||||
|
||||
def populateStyles(
|
||||
self
|
||||
):
|
||||
|
||||
self.StyleComboBox.clear()
|
||||
self.StyleComboBox.addItems(QStyleFactory.keys())
|
||||
|
||||
def populateCustomThemes(
|
||||
self
|
||||
):
|
||||
|
||||
self.CustomThemeComboBox.blockSignals(True)
|
||||
self.CustomThemeComboBox.clear()
|
||||
self.CustomThemeComboBox.addItem("默认", "")
|
||||
self.__theme_cache = {}
|
||||
themes = themeInstance().listThemes()
|
||||
for t in themes:
|
||||
name = t.get("name", "")
|
||||
file = t.get("file", name)
|
||||
author = t.get("author", "")
|
||||
if name:
|
||||
self.__theme_cache[file] = t
|
||||
self.CustomThemeComboBox.addItem(name, file)
|
||||
self.CustomThemeComboBox.blockSignals(False)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.ImportCustomThemeButton.clicked.connect(self.onImportCustomThemeButtonClicked)
|
||||
self.RemoveCustomThemeButton.clicked.connect(self.onRemoveCustomThemeButtonClicked)
|
||||
self.CustomThemeComboBox.currentIndexChanged.connect(self.onCustomThemeComboBoxChanged)
|
||||
self.ResetCustomThemeButton.clicked.connect(self.onResetCustomThemeButtonClicked)
|
||||
self.BulletinTestButton.clicked.connect(self.onBulletinTestButtonClicked)
|
||||
self.BulletinOpenButton.clicked.connect(self.openBulletinRequested.emit)
|
||||
self.CancelButton.clicked.connect(self.onCancelButtonClicked)
|
||||
self.ApplyButton.clicked.connect(self.onApplyButtonClicked)
|
||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||
|
||||
def loadSettings(
|
||||
self
|
||||
):
|
||||
|
||||
# appearance settings
|
||||
theme = self.__cfg_mgr.get(CfgKey.GLOBAL.APPEARANCE.THEME, "system")
|
||||
style = self.__cfg_mgr.get(CfgKey.GLOBAL.APPEARANCE.STYLE, "Fusion")
|
||||
custom_theme = self.__cfg_mgr.get(CfgKey.GLOBAL.APPEARANCE.CUSTOM_THEME, "")
|
||||
self.__original_theme = theme
|
||||
self.__original_custom_theme = custom_theme
|
||||
self.__original_style = getActiveStyle()
|
||||
if theme == "light":
|
||||
self.LightThemeRadio.setChecked(True)
|
||||
elif theme == "dark":
|
||||
self.DarkThemeRadio.setChecked(True)
|
||||
else:
|
||||
self.SystemThemeRadio.setChecked(True)
|
||||
index = self.StyleComboBox.findText(style)
|
||||
if index < 0:
|
||||
index = 0
|
||||
self.StyleComboBox.setCurrentIndex(index)
|
||||
if custom_theme:
|
||||
idx = self.CustomThemeComboBox.findData(custom_theme)
|
||||
if idx >= 0:
|
||||
self.CustomThemeComboBox.setCurrentIndex(idx)
|
||||
self.updateCustomThemeInfo()
|
||||
self.updateCustomThemeStatus()
|
||||
# bulletin settings
|
||||
bulletin_mgr = bulletinInstance()
|
||||
self.__original_bulletin_url = bulletin_mgr.serverUrl()
|
||||
self.__original_bulletin_auto_fetch = bulletin_mgr.autoFetch()
|
||||
self.__original_bulletin_sync_interval = bulletin_mgr.syncInterval()
|
||||
self.BulletinServerUrlEdit.setText(self.__original_bulletin_url)
|
||||
self.BulletinAutoFetchCheck.setChecked(self.__original_bulletin_auto_fetch)
|
||||
self.BulletinSyncIntervalSpin.setValue(self.__original_bulletin_sync_interval)
|
||||
|
||||
def updateCustomThemeInfo(
|
||||
self
|
||||
):
|
||||
|
||||
file = self.CustomThemeComboBox.currentData()
|
||||
if not file:
|
||||
self.CustomThemeInfoLabel.setText("")
|
||||
return
|
||||
t = self.__theme_cache.get(file)
|
||||
if t:
|
||||
name = t.get("name", "未知")
|
||||
author = t.get("author", "未知作者")
|
||||
need_theme = t.get("need_theme", "both")
|
||||
brief = t.get("brief", "没有相关简介")
|
||||
self.CustomThemeInfoLabel.setText(
|
||||
f"<b>{name}</b> - 适用于 <i>{_themeToReadable(need_theme)}</i> 主题<br>"
|
||||
f"作者:{author}<br><br>"
|
||||
f"{brief}"
|
||||
)
|
||||
else:
|
||||
self.CustomThemeInfoLabel.setText("")
|
||||
|
||||
def updateCustomThemeStatus(
|
||||
self
|
||||
):
|
||||
|
||||
file = self.CustomThemeComboBox.currentData()
|
||||
t = self.__theme_cache.get(file) if file else None
|
||||
name = t.get("name", "") if t else ""
|
||||
if name:
|
||||
self.CustomThemeStatusLabel.setText(f"当前使用 {name} 主题。")
|
||||
else:
|
||||
self.CustomThemeStatusLabel.setText("当前使用 默认 主题。")
|
||||
|
||||
def syncRadioFromNeedTheme(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
|
||||
t = self.__theme_cache.get(name)
|
||||
if t:
|
||||
need_theme = t.get("need_theme", "both")
|
||||
if need_theme == "light":
|
||||
self.LightThemeRadio.setChecked(True)
|
||||
elif need_theme == "dark":
|
||||
self.DarkThemeRadio.setChecked(True)
|
||||
|
||||
def clearBulletinTestStatus(
|
||||
self
|
||||
):
|
||||
|
||||
self.BulletinTestStatusLabel.setText("")
|
||||
self.BulletinTestStatusLabel.setStyleSheet("")
|
||||
|
||||
def collectAppearanceSettings(
|
||||
self
|
||||
) -> tuple[str, str, str]:
|
||||
|
||||
if self.LightThemeRadio.isChecked():
|
||||
theme = "light"
|
||||
elif self.DarkThemeRadio.isChecked():
|
||||
theme = "dark"
|
||||
else:
|
||||
theme = "system"
|
||||
style = self.StyleComboBox.currentText()
|
||||
custom_theme = self.CustomThemeComboBox.currentData() or ""
|
||||
if not custom_theme:
|
||||
custom_theme = ""
|
||||
return theme, style, custom_theme
|
||||
|
||||
def collectBulletinSettings(
|
||||
self
|
||||
) -> tuple[str, bool, int]:
|
||||
|
||||
url = self.BulletinServerUrlEdit.text().strip()
|
||||
auto_fetch = self.BulletinAutoFetchCheck.isChecked()
|
||||
sync_interval = self.BulletinSyncIntervalSpin.value()
|
||||
if sync_interval < 1:
|
||||
sync_interval = 5
|
||||
return url, auto_fetch, sync_interval
|
||||
|
||||
def saveAppearanceSettings(
|
||||
self
|
||||
):
|
||||
|
||||
theme, style, custom_theme = self.collectAppearanceSettings()
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.APPEARANCE.STYLE, style)
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.APPEARANCE.CUSTOM_THEME, custom_theme)
|
||||
setActiveStyle(style)
|
||||
if not _applyCustomTheme(custom_theme, theme):
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.APPEARANCE.CUSTOM_THEME, "")
|
||||
self.syncRadioFromNeedTheme(custom_theme)
|
||||
theme, _, _ = self.collectAppearanceSettings()
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.APPEARANCE.THEME, theme)
|
||||
self.setNavigationIcons()
|
||||
self.updateCustomThemeStatus()
|
||||
self.updateCustomThemeInfo()
|
||||
self.__original_theme = theme
|
||||
self.__original_custom_theme = custom_theme if custom_theme else ""
|
||||
self.__original_style = getActiveStyle()
|
||||
|
||||
def saveBulletinSettings(
|
||||
self
|
||||
):
|
||||
|
||||
url, auto_fetch, sync_interval = self.collectBulletinSettings()
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.BULLETIN.SERVER_URL, url)
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.BULLETIN.AUTO_FETCH, auto_fetch)
|
||||
self.__cfg_mgr.set(CfgKey.GLOBAL.BULLETIN.SYNC_INTERVAL, sync_interval)
|
||||
self.__original_bulletin_url = url
|
||||
self.__original_bulletin_auto_fetch = auto_fetch
|
||||
self.__original_bulletin_sync_interval = sync_interval
|
||||
|
||||
def saveSettings(
|
||||
self
|
||||
):
|
||||
|
||||
self.saveBulletinSettings()
|
||||
self.saveAppearanceSettings()
|
||||
|
||||
def maybeRestart(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
reply = QMessageBox.question(
|
||||
self,
|
||||
"提示 - AutoLibrary",
|
||||
"界面风格已修改,需要重启程序才能生效。是否立即重启?",
|
||||
QMessageBox.Yes | QMessageBox.No,
|
||||
QMessageBox.Yes
|
||||
)
|
||||
if reply == QMessageBox.Yes:
|
||||
_restartApp()
|
||||
return True
|
||||
return False
|
||||
|
||||
@Slot()
|
||||
def onImportCustomThemeButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
file_path, _ = QFileDialog.getOpenFileName(
|
||||
self,
|
||||
"导入主题 - AutoLibrary",
|
||||
"",
|
||||
"主题文件 (*.altheme *.qss);;所有文件 (*)"
|
||||
)
|
||||
if not file_path:
|
||||
return
|
||||
try:
|
||||
file_id = themeInstance().importTheme(file_path)
|
||||
self.populateCustomThemes()
|
||||
idx = self.CustomThemeComboBox.findData(file_id)
|
||||
if idx >= 0:
|
||||
self.CustomThemeComboBox.setCurrentIndex(idx)
|
||||
self.updateCustomThemeInfo()
|
||||
except Exception as e:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"导入失败 - AutoLibrary",
|
||||
f"无法导入主题文件:{e}"
|
||||
)
|
||||
|
||||
@Slot()
|
||||
def onRemoveCustomThemeButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
file = self.CustomThemeComboBox.currentData()
|
||||
if not file:
|
||||
QMessageBox.information(
|
||||
self,
|
||||
"提示 - AutoLibrary",
|
||||
"请先选择一个主题。"
|
||||
)
|
||||
return
|
||||
t = self.__theme_cache.get(file)
|
||||
name = t.get("name", file) if t else file
|
||||
reply = QMessageBox.question(
|
||||
self,
|
||||
"删除主题 - AutoLibrary",
|
||||
f"确定要删除主题 \"{name}\" 吗?",
|
||||
QMessageBox.Yes | QMessageBox.No,
|
||||
QMessageBox.No
|
||||
)
|
||||
if reply != QMessageBox.Yes:
|
||||
return
|
||||
try:
|
||||
themeInstance().removeTheme(file)
|
||||
self.populateCustomThemes()
|
||||
self.CustomThemeComboBox.setCurrentIndex(0)
|
||||
self.updateCustomThemeStatus()
|
||||
self.updateCustomThemeInfo()
|
||||
except Exception as e:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"删除失败 - AutoLibrary",
|
||||
f"无法删除主题:{e}"
|
||||
)
|
||||
|
||||
@Slot()
|
||||
def onCustomThemeComboBoxChanged(
|
||||
self,
|
||||
index: int
|
||||
):
|
||||
|
||||
self.updateCustomThemeInfo()
|
||||
|
||||
@Slot()
|
||||
def onResetCustomThemeButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
self.CustomThemeComboBox.blockSignals(True)
|
||||
if self.__original_custom_theme:
|
||||
idx = self.CustomThemeComboBox.findData(self.__original_custom_theme)
|
||||
if idx >= 0:
|
||||
self.CustomThemeComboBox.setCurrentIndex(idx)
|
||||
else:
|
||||
self.CustomThemeComboBox.setCurrentIndex(0)
|
||||
else:
|
||||
self.CustomThemeComboBox.setCurrentIndex(0)
|
||||
self.CustomThemeComboBox.blockSignals(False)
|
||||
if self.__original_theme == "light":
|
||||
self.LightThemeRadio.setChecked(True)
|
||||
elif self.__original_theme == "dark":
|
||||
self.DarkThemeRadio.setChecked(True)
|
||||
else:
|
||||
self.SystemThemeRadio.setChecked(True)
|
||||
self.updateCustomThemeInfo()
|
||||
self.updateCustomThemeStatus()
|
||||
|
||||
@Slot()
|
||||
def onBulletinTestButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
url = self.BulletinServerUrlEdit.text().strip()
|
||||
if not url:
|
||||
self.BulletinTestStatusLabel.setText("请先输入服务器地址。")
|
||||
self.BulletinTestStatusLabel.setStyleSheet("color: red;")
|
||||
return
|
||||
if hasattr(self, '__bulletin_test_worker') and self.__bulletin_test_worker is not None:
|
||||
return
|
||||
self.BulletinTestButton.setEnabled(False)
|
||||
self.BulletinTestStatusLabel.setText("正在测试连接...")
|
||||
self.BulletinTestStatusLabel.setStyleSheet("")
|
||||
self.__bulletin_test_t0 = time.monotonic()
|
||||
api_url = url.rstrip("/") + "/bulletins"
|
||||
self.__bulletin_test_worker = ALBulletinFetchWorker(
|
||||
self, api_url, {"date": "", "time": "", "range_hour": "1"}
|
||||
)
|
||||
self.__bulletin_test_worker.fetchWorkerIsFinished.connect(
|
||||
self.onBulletinTestIsFinished
|
||||
)
|
||||
self.__bulletin_test_worker.fetchWorkerFinishedWithError.connect(
|
||||
self.onBulletinTestFinishedWithError
|
||||
)
|
||||
self.__bulletin_test_worker.start()
|
||||
|
||||
@Slot(dict)
|
||||
def onBulletinTestIsFinished(
|
||||
self,
|
||||
data: dict
|
||||
):
|
||||
|
||||
self.__bulletin_test_worker.fetchWorkerIsFinished.disconnect(
|
||||
self.onBulletinTestIsFinished
|
||||
)
|
||||
self.__bulletin_test_worker.fetchWorkerFinishedWithError.disconnect(
|
||||
self.onBulletinTestFinishedWithError
|
||||
)
|
||||
self.__bulletin_test_worker.wait(3000)
|
||||
self.__bulletin_test_worker.deleteLater()
|
||||
self.__bulletin_test_worker = None
|
||||
elapsed_ms = (time.monotonic() - self.__bulletin_test_t0) * 1000
|
||||
self.BulletinTestStatusLabel.setText(
|
||||
f"连接成功!响应延迟 {elapsed_ms:.0f} ms"
|
||||
)
|
||||
self.BulletinTestStatusLabel.setStyleSheet("color: green;")
|
||||
self.BulletinTestButton.setEnabled(True)
|
||||
QTimer.singleShot(3000, self, self.clearBulletinTestStatus)
|
||||
|
||||
@Slot(str)
|
||||
def onBulletinTestFinishedWithError(
|
||||
self,
|
||||
error_message: str
|
||||
):
|
||||
|
||||
self.__bulletin_test_worker.fetchWorkerIsFinished.disconnect(
|
||||
self.onBulletinTestIsFinished
|
||||
)
|
||||
self.__bulletin_test_worker.fetchWorkerFinishedWithError.disconnect(
|
||||
self.onBulletinTestFinishedWithError
|
||||
)
|
||||
self.__bulletin_test_worker.wait(3000)
|
||||
self.__bulletin_test_worker.deleteLater()
|
||||
self.__bulletin_test_worker = None
|
||||
self.BulletinTestStatusLabel.setText(f"连接失败:{error_message}")
|
||||
self.BulletinTestStatusLabel.setStyleSheet("color: red;")
|
||||
self.BulletinTestButton.setEnabled(True)
|
||||
|
||||
@Slot()
|
||||
def onCancelButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
self.close()
|
||||
|
||||
@Slot()
|
||||
def onApplyButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
_, style, _ = self.collectAppearanceSettings()
|
||||
style_changed = self.__original_style != style
|
||||
self.saveSettings()
|
||||
if style_changed:
|
||||
self.maybeRestart()
|
||||
|
||||
@Slot()
|
||||
def onConfirmButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
self.onApplyButtonClicked()
|
||||
self.close()
|
||||
@@ -9,14 +9,20 @@ See the LICENSE file for details.
|
||||
"""
|
||||
from enum import Enum
|
||||
|
||||
from PySide6.QtWidgets import (
|
||||
QLabel
|
||||
)
|
||||
from PySide6.QtCore import (
|
||||
Qt, Property, QPropertyAnimation, QEasingCurve
|
||||
Property,
|
||||
QEasingCurve,
|
||||
QPropertyAnimation,
|
||||
Qt
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QPainter, QColor, QConicalGradient, QPalette
|
||||
QColor,
|
||||
QConicalGradient,
|
||||
QPainter,
|
||||
QPalette
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QLabel
|
||||
)
|
||||
|
||||
|
||||
@@ -44,14 +50,12 @@ class ALStatusLabel(QLabel):
|
||||
|
||||
self.setupUi()
|
||||
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setFixedSize(36, 36)
|
||||
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
|
||||
self.RunningAnimation = QPropertyAnimation(self, b"iconAngle")
|
||||
self.RunningAnimation.setDuration(1000)
|
||||
self.RunningAnimation.setStartValue(0)
|
||||
@@ -59,14 +63,12 @@ class ALStatusLabel(QLabel):
|
||||
self.RunningAnimation.setLoopCount(-1)
|
||||
self.RunningAnimation.setEasingCurve(QEasingCurve.Type.Linear)
|
||||
|
||||
|
||||
def isDarkMode(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
return self.palette().color(QPalette.ColorRole.Window).value() < 128
|
||||
|
||||
|
||||
def getMarkColor(
|
||||
self
|
||||
) -> QColor:
|
||||
@@ -111,7 +113,6 @@ class ALStatusLabel(QLabel):
|
||||
self.__icon_angle = value
|
||||
self.update()
|
||||
|
||||
|
||||
def paintEvent(
|
||||
self,
|
||||
event
|
||||
@@ -126,7 +127,6 @@ class ALStatusLabel(QLabel):
|
||||
case self.Status.WAITING:
|
||||
pen = painter.pen()
|
||||
pen.setWidth(2)
|
||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setColor(QColor("#969696")) # grey
|
||||
painter.setPen(pen)
|
||||
@@ -155,7 +155,6 @@ class ALStatusLabel(QLabel):
|
||||
# draw the success green circle
|
||||
pen = painter.pen()
|
||||
pen.setWidth(2)
|
||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setColor(QColor("#4CAF50" if self.isDarkMode() else "#00AF50")) # green
|
||||
painter.setPen(pen)
|
||||
@@ -192,7 +191,6 @@ class ALStatusLabel(QLabel):
|
||||
# draw the warning orange circle
|
||||
pen = painter.pen()
|
||||
pen.setWidth(2)
|
||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setColor(QColor("#FF9800")) # orange
|
||||
painter.setPen(pen)
|
||||
@@ -222,7 +220,6 @@ class ALStatusLabel(QLabel):
|
||||
# draw the failure red circle
|
||||
pen = painter.pen()
|
||||
pen.setWidth(2)
|
||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setColor(QColor("#DC0000")) # red
|
||||
painter.setPen(pen)
|
||||
|
||||
@@ -12,12 +12,25 @@ import uuid
|
||||
from enum import Enum
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from PySide6.QtCore import Slot, QDateTime, QUrl
|
||||
from PySide6.QtCore import (
|
||||
Slot,
|
||||
QDateTime,
|
||||
QUrl
|
||||
)
|
||||
from PySide6.QtGui import QDesktopServices
|
||||
from PySide6.QtWidgets import QLabel, QDialog, QWidget, QSpinBox, QHBoxLayout, QVBoxLayout, QGridLayout, QDateTimeEdit, QGroupBox, QPushButton
|
||||
from PySide6.QtWidgets import (
|
||||
QLabel,
|
||||
QDialog,
|
||||
QWidget,
|
||||
QSpinBox,
|
||||
QHBoxLayout,
|
||||
QVBoxLayout,
|
||||
QDateTimeEdit,
|
||||
QGroupBox,
|
||||
QPushButton
|
||||
)
|
||||
|
||||
from gui.resources.ui.Ui_ALTimerTaskAddDialog import Ui_ALTimerTaskAddDialog
|
||||
from gui.ALAutoScriptOrchDialog import ALAutoScriptOrchDialog
|
||||
from utils.TimerUtils import TimerUtils
|
||||
|
||||
|
||||
@@ -50,7 +63,6 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
if self.__edit_timer_task:
|
||||
self.loadTask(self.__edit_timer_task)
|
||||
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
@@ -58,6 +70,8 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
self.TimerTypeComboBox.setCurrentIndex(0)
|
||||
self.SpecificTimerWidget = QWidget()
|
||||
self.SpecificTimerLayout = QHBoxLayout(self.SpecificTimerWidget)
|
||||
self.SpecificTimerLayout.setContentsMargins(0, 0, 0, 0)
|
||||
self.SpecificTimerLayout.setSpacing(5)
|
||||
self.SpecificTimerLayout.addWidget(QLabel("定时时间:"))
|
||||
self.SpecificDateTimeEdit = QDateTimeEdit()
|
||||
self.SpecificDateTimeEdit.setCalendarPopup(True)
|
||||
@@ -66,9 +80,10 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
self.SpecificDateTimeEdit.setDateTime(QDateTime.currentDateTime().addSecs(60))
|
||||
self.SpecificTimerLayout.addWidget(self.SpecificDateTimeEdit)
|
||||
self.TimerConfigLayout.addWidget(self.SpecificTimerWidget)
|
||||
|
||||
self.RelativeTimerWidget = QWidget()
|
||||
self.RelativeTimerLayout = QHBoxLayout(self.RelativeTimerWidget)
|
||||
self.RelativeTimerLayout.setContentsMargins(0, 0, 0, 0)
|
||||
self.RelativeTimerLayout.setSpacing(5)
|
||||
self.RelativeTimerLayout.addWidget(QLabel("相对时间:"))
|
||||
self.RelativeDaySpinBox = QSpinBox()
|
||||
self.RelativeDaySpinBox.setMinimum(0)
|
||||
@@ -92,26 +107,20 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
self.RelativeTimerLayout.addWidget(self.RelativeSecondSpinBox)
|
||||
self.TimerConfigLayout.addWidget(self.RelativeTimerWidget)
|
||||
self.RelativeTimerWidget.setVisible(False)
|
||||
|
||||
self.AutoScriptGroupBox = QGroupBox("AutoScript 指令")
|
||||
self.AutoScriptLayout = QVBoxLayout(self.AutoScriptGroupBox)
|
||||
self.AutoScriptLayout.setContentsMargins(3, 3, 3, 3)
|
||||
self.AutoScriptLayout.setSpacing(3)
|
||||
autoScriptBtnLayout = QHBoxLayout()
|
||||
self.AutoScriptSetButton = QPushButton("设置指令")
|
||||
self.AutoScriptSetButton.setMinimumHeight(25)
|
||||
self.AutoScriptSetButton.setFixedWidth(130)
|
||||
autoScriptBtnLayout.addWidget(self.AutoScriptSetButton)
|
||||
self.AutoScriptPreviewButton = QPushButton("预览")
|
||||
self.AutoScriptPreviewButton.setMinimumHeight(25)
|
||||
self.AutoScriptPreviewButton.setFixedWidth(60)
|
||||
self.AutoScriptPreviewButton.setEnabled(False)
|
||||
autoScriptBtnLayout.addWidget(self.AutoScriptPreviewButton)
|
||||
autoScriptBtnLayout.addStretch()
|
||||
AutoScriptBtnLayout = QHBoxLayout()
|
||||
self.AutoScriptEditButton = QPushButton("编辑")
|
||||
self.AutoScriptEditButton.setMinimumHeight(25)
|
||||
self.AutoScriptEditButton.setFixedWidth(80)
|
||||
AutoScriptBtnLayout.addWidget(self.AutoScriptEditButton)
|
||||
AutoScriptBtnLayout.addStretch()
|
||||
self.AutoScriptHelpButton = QPushButton("?")
|
||||
self.AutoScriptHelpButton.setFixedSize(20, 20)
|
||||
self.AutoScriptHelpButton.setToolTip(
|
||||
"AutoScript 是一种轻量级 DSL\n"
|
||||
"AutoScript 是一种轻量级 DSL 语言,基于 Lua 实现。\n"
|
||||
"用于在重复定时任务执行前,对用户的预约数据进行预处理\n"
|
||||
"\n"
|
||||
"点击查看完整在线文档"
|
||||
@@ -121,19 +130,19 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
"font-weight: bold; color: #555; }"
|
||||
"QPushButton:hover { background-color: #E0E0E0; }"
|
||||
)
|
||||
autoScriptBtnLayout.addWidget(self.AutoScriptHelpButton)
|
||||
AutoScriptBtnLayout.addWidget(self.AutoScriptHelpButton)
|
||||
self.AutoScriptStatusLabel = QLabel("未设置")
|
||||
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
||||
self.AutoScriptStatusLabel.setFixedHeight(25)
|
||||
autoScriptBtnLayout.addWidget(self.AutoScriptStatusLabel)
|
||||
self.AutoScriptLayout.addLayout(autoScriptBtnLayout)
|
||||
AutoScriptBtnLayout.addWidget(self.AutoScriptStatusLabel)
|
||||
self.AutoScriptLayout.addLayout(AutoScriptBtnLayout)
|
||||
self.ALAddTimerTaskLayout.insertWidget(
|
||||
self.ALAddTimerTaskLayout.indexOf(self.TaskConfigGroupBox) + 1,
|
||||
self.AutoScriptGroupBox
|
||||
)
|
||||
self.AutoScriptGroupBox.setVisible(False)
|
||||
self.__auto_script = ""
|
||||
|
||||
self.__mock_target_data = None
|
||||
|
||||
def loadTask(
|
||||
self,
|
||||
@@ -170,10 +179,11 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
self.__auto_script = auto_script
|
||||
self.AutoScriptStatusLabel.setText("已设置")
|
||||
self.AutoScriptStatusLabel.setStyleSheet("color: #4CAF50;")
|
||||
self.AutoScriptPreviewButton.setEnabled(True)
|
||||
mock_data = task.get("mock_target_data")
|
||||
if mock_data:
|
||||
self.__mock_target_data = mock_data
|
||||
self.ConfirmButton.setText("保存")
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
@@ -182,11 +192,9 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
self.ConfirmButton.clicked.connect(self.accept)
|
||||
self.TimerTypeComboBox.currentIndexChanged.connect(self.onTimerTypeComboBoxIndexChanged)
|
||||
self.RepeatCheckBox.toggled.connect(self.onRepeatCheckBoxToggled)
|
||||
self.AutoScriptSetButton.clicked.connect(self.onSetAutoScript)
|
||||
self.AutoScriptPreviewButton.clicked.connect(self.onPreviewAutoScript)
|
||||
self.AutoScriptEditButton.clicked.connect(self.onPreviewAutoScript)
|
||||
self.AutoScriptHelpButton.clicked.connect(self.onAutoScriptHelp)
|
||||
|
||||
|
||||
def getTimerTask(
|
||||
self
|
||||
) -> dict:
|
||||
@@ -218,6 +226,7 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
task_data["status"] = ALTimerTaskStatus.PENDING
|
||||
task_data["executed"] = False
|
||||
task_data["repeat_auto_script"] = self.__auto_script
|
||||
task_data["mock_target_data"] = self.__mock_target_data
|
||||
else:
|
||||
task_data = {
|
||||
"name": name,
|
||||
@@ -230,6 +239,7 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
"executed": False,
|
||||
"repeat": self.RepeatCheckBox.isChecked(),
|
||||
"repeat_auto_script": self.__auto_script,
|
||||
"mock_target_data": self.__mock_target_data,
|
||||
}
|
||||
|
||||
repeat = self.RepeatCheckBox.isChecked()
|
||||
@@ -291,29 +301,20 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
self.AutoScriptGroupBox.setVisible(checked)
|
||||
|
||||
@Slot()
|
||||
def onSetAutoScript(self):
|
||||
dlg = ALAutoScriptOrchDialog(self, existingScript=self.__auto_script)
|
||||
if dlg.exec() == QDialog.DialogCode.Accepted:
|
||||
script = dlg.getScript()
|
||||
def onPreviewAutoScript(self):
|
||||
from gui.ALAutoScriptEditDialog import ALAutoScriptEditDialog
|
||||
Dlg = ALAutoScriptEditDialog(self, self.__auto_script, self.__mock_target_data)
|
||||
if Dlg.exec() == QDialog.DialogCode.Accepted:
|
||||
script = Dlg.getScript()
|
||||
self.__auto_script = script
|
||||
self.__mock_target_data = Dlg.getMockData()
|
||||
if script:
|
||||
self.AutoScriptStatusLabel.setText("已设置")
|
||||
self.AutoScriptStatusLabel.setStyleSheet("color: #4CAF50;")
|
||||
self.AutoScriptPreviewButton.setEnabled(True)
|
||||
else:
|
||||
self.AutoScriptStatusLabel.setText("未设置")
|
||||
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
||||
self.AutoScriptPreviewButton.setEnabled(False)
|
||||
dlg.deleteLater()
|
||||
|
||||
@Slot()
|
||||
def onPreviewAutoScript(self):
|
||||
if not self.__auto_script:
|
||||
return
|
||||
from gui.ALAutoScriptPrevDialog import ALAutoScriptPreviewDialog
|
||||
dlg = ALAutoScriptPreviewDialog(self, self.__auto_script)
|
||||
dlg.exec()
|
||||
dlg.deleteLater()
|
||||
Dlg.deleteLater()
|
||||
|
||||
@Slot()
|
||||
def onAutoScriptHelp(
|
||||
@@ -321,7 +322,5 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
):
|
||||
|
||||
QDesktopServices.openUrl(
|
||||
QUrl("https://www.autolibrary.kenanzhu.com/manuals/autoscript")
|
||||
QUrl("https://manuals.autolibrary.kenanzhu.com/zh/autoscript")
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -28,22 +28,19 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.__task_data = task_data
|
||||
self.__history = task_data.get("repeat_history", [])
|
||||
|
||||
self.modifyUi()
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
|
||||
|
||||
def modifyUi(
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.setWindowTitle("定时任务执行历史 - AutoLibrary")
|
||||
self.setMinimumSize(300, 300)
|
||||
self.setMaximumSize(500, 400)
|
||||
|
||||
MainLayout = QVBoxLayout(self)
|
||||
InfoLayout = QGridLayout()
|
||||
TaskNameLabel = QLabel(f"任务: {self.__task_data.get('name', '未命名')}")
|
||||
@@ -53,7 +50,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
TaskUUIDLabel.setStyleSheet("color: #969696; font-size: 11px;")
|
||||
InfoLayout.addWidget(TaskUUIDLabel, 1, 0)
|
||||
InfoLayout.setColumnStretch(0, 1)
|
||||
|
||||
if self.__task_data.get("repeat", False):
|
||||
RepeatLabel = QLabel("可重复性任务")
|
||||
RepeatLabel.setStyleSheet("color: #2294FF; font-size: 12px;")
|
||||
@@ -70,7 +66,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
self.HistoryTableWidget.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
|
||||
self.loadHistory()
|
||||
MainLayout.addWidget(self.HistoryTableWidget)
|
||||
|
||||
ButtonLayout = QHBoxLayout()
|
||||
ButtonLayout.addStretch()
|
||||
self.CloseButton = QPushButton("关闭")
|
||||
@@ -83,7 +78,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
ButtonLayout.addWidget(self.CloseButton)
|
||||
MainLayout.addLayout(ButtonLayout)
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
@@ -91,7 +85,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
self.CloseButton.clicked.connect(self.accept)
|
||||
self.ClearHistoryButton.clicked.connect(self.onClearHistoryButtonClicked)
|
||||
|
||||
|
||||
def loadHistory(
|
||||
self
|
||||
):
|
||||
@@ -100,6 +93,11 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
for row, record in enumerate(self.__history):
|
||||
self.addHistoryRow(row, record)
|
||||
|
||||
def getHistory(
|
||||
self
|
||||
) -> list:
|
||||
|
||||
return self.__history
|
||||
|
||||
def addHistoryRow(
|
||||
self,
|
||||
@@ -110,33 +108,26 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
execute_time = record.get("execute_time", "")
|
||||
result = record.get("result", ALTimerTaskStatus.UNKNOWN)
|
||||
duration = record.get("duration", 0)
|
||||
ExecuteTimeItem = QTableWidgetItem(execute_time)
|
||||
ExecuteTimeItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.HistoryTableWidget.setItem(row, 0, ExecuteTimeItem)
|
||||
ResultItem = QTableWidgetItem(result.value)
|
||||
ResultItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
execute_time_item = QTableWidgetItem(execute_time)
|
||||
execute_time_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.HistoryTableWidget.setItem(row, 0, execute_time_item)
|
||||
result_item = QTableWidgetItem(result.value)
|
||||
result_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
match result:
|
||||
case ALTimerTaskStatus.EXECUTED:
|
||||
ResultItem.setForeground(Qt.GlobalColor.green)
|
||||
result_item.setForeground(Qt.GlobalColor.green)
|
||||
case ALTimerTaskStatus.ERROR:
|
||||
ResultItem.setForeground(Qt.GlobalColor.red)
|
||||
result_item.setForeground(Qt.GlobalColor.red)
|
||||
case ALTimerTaskStatus.OUTDATED:
|
||||
ResultItem.setForeground(Qt.GlobalColor.red)
|
||||
result_item.setForeground(Qt.GlobalColor.red)
|
||||
case _:
|
||||
ResultItem.setForeground(Qt.GlobalColor.black)
|
||||
self.HistoryTableWidget.setItem(row, 1, ResultItem)
|
||||
DurationItem = QTableWidgetItem(f"{duration:.2f}")
|
||||
DurationItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.HistoryTableWidget.setItem(row, 2, DurationItem)
|
||||
result_item.setForeground(Qt.GlobalColor.black)
|
||||
self.HistoryTableWidget.setItem(row, 1, result_item)
|
||||
duration_item = QTableWidgetItem(f"{duration:.2f}")
|
||||
duration_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.HistoryTableWidget.setItem(row, 2, duration_item)
|
||||
self.HistoryTableWidget.setRowHeight(row, 25)
|
||||
|
||||
|
||||
def getHistory(
|
||||
self
|
||||
) -> list:
|
||||
|
||||
return self.__history
|
||||
|
||||
@Slot()
|
||||
def onClearHistoryButtonClicked(
|
||||
self
|
||||
@@ -144,4 +135,4 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
|
||||
self.__history.clear()
|
||||
self.HistoryTableWidget.setRowCount(0)
|
||||
self.__task_data["repeat_history"] = self.__history
|
||||
self.__task_data["repeat_history"] = self.__history # = []
|
||||
|
||||
@@ -15,22 +15,41 @@ from enum import Enum
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt, Signal, Slot, QTimer
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog, QWidget, QListWidgetItem, QMessageBox,
|
||||
QHBoxLayout, QVBoxLayout, QLabel, QPushButton, QMenu
|
||||
QTimer,
|
||||
Qt,
|
||||
Signal,
|
||||
Slot
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QCloseEvent, QAction
|
||||
QAction,
|
||||
QCloseEvent
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QListWidgetItem,
|
||||
QMenu,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget
|
||||
)
|
||||
|
||||
import managers.config.ConfigManager as ConfigManager
|
||||
from utils.TimerUtils import TimerUtils
|
||||
|
||||
from gui.resources.ui.Ui_ALTimerTaskManageWidget import Ui_ALTimerTaskManageWidget
|
||||
from gui.ALTimerTaskAddDialog import ALTimerTaskAddDialog, ALTimerTaskStatus
|
||||
from gui.ALTimerTaskAddDialog import (
|
||||
ALTimerTaskAddDialog,
|
||||
ALTimerTaskStatus
|
||||
)
|
||||
from gui.ALTimerTaskHistoryDialog import ALTimerTaskHistoryDialog
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
from gui.resources.ui.Ui_ALTimerTaskManageWidget import Ui_ALTimerTaskManageWidget
|
||||
from interfaces.ConfigProvider import (
|
||||
CfgKey,
|
||||
ConfigProvider
|
||||
)
|
||||
from utils.TimerUtils import TimerUtils
|
||||
|
||||
|
||||
class ALTimerTaskItemWidget(QWidget):
|
||||
@@ -51,7 +70,6 @@ class ALTimerTaskItemWidget(QWidget):
|
||||
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
||||
self.customContextMenuRequested.connect(self.showContextMenu)
|
||||
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
@@ -63,12 +81,12 @@ class ALTimerTaskItemWidget(QWidget):
|
||||
self.TaskInfoLayout = QVBoxLayout()
|
||||
self.TaskInfoLayout.setSpacing(5)
|
||||
TaskNameLabel = QLabel(self.__timer_task["name"])
|
||||
TaskNameLabelFont = TaskNameLabel.font()
|
||||
TaskNameLabelFont.setBold(True)
|
||||
TaskNameLabel.setFont(TaskNameLabelFont)
|
||||
task_name_label_font = TaskNameLabel.font()
|
||||
task_name_label_font.setBold(True)
|
||||
TaskNameLabel.setFont(task_name_label_font)
|
||||
TaskNameLabel.setFixedHeight(25)
|
||||
self.TaskInfoLayout.addWidget(TaskNameLabel)
|
||||
ExecuteTimeStr = self.__timer_task["execute_time"].strftime("%Y-%m-%d %H:%M:%S")
|
||||
execute_time_str = self.__timer_task["execute_time"].strftime("%Y-%m-%d %H:%M:%S")
|
||||
if self.__timer_task.get("repeat", False):
|
||||
repeat_days = self.__timer_task.get("repeat_days", [])
|
||||
repeat_hour = self.__timer_task.get("repeat_hour", 0)
|
||||
@@ -76,14 +94,14 @@ class ALTimerTaskItemWidget(QWidget):
|
||||
repeat_second = self.__timer_task.get("repeat_second", 0)
|
||||
if len(repeat_days) == 7:
|
||||
time_str = f"{repeat_hour:02d}:{repeat_minute:02d}:{repeat_second:02d}"
|
||||
ExecuteTimeLabel = QLabel(f"下次执行时间: {ExecuteTimeStr} (每日 {time_str})")
|
||||
ExecuteTimeLabel = QLabel(f"下次执行时间: {execute_time_str} (每日 {time_str})")
|
||||
else:
|
||||
day_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
|
||||
selected_days = [day_names[d] for d in repeat_days]
|
||||
time_str = f"{repeat_hour:02d}:{repeat_minute:02d}:{repeat_second:02d}"
|
||||
ExecuteTimeLabel = QLabel(f"下次执行时间: {ExecuteTimeStr} (每{','.join(selected_days)} {time_str})")
|
||||
ExecuteTimeLabel = QLabel(f"下次执行时间: {execute_time_str} (每{','.join(selected_days)} {time_str})")
|
||||
else:
|
||||
ExecuteTimeLabel = QLabel(f"执行时间: {ExecuteTimeStr}")
|
||||
ExecuteTimeLabel = QLabel(f"执行时间: {execute_time_str}")
|
||||
ExecuteTimeLabel.setStyleSheet("color: #969696;")
|
||||
ExecuteTimeLabel.setFixedHeight(20)
|
||||
self.TaskInfoLayout.addWidget(ExecuteTimeLabel)
|
||||
@@ -156,23 +174,23 @@ class ALTimerTaskItemWidget(QWidget):
|
||||
pos
|
||||
):
|
||||
|
||||
menu = QMenu(self)
|
||||
edit_action = QAction("编辑", self)
|
||||
edit_action.triggered.connect(
|
||||
Menu = QMenu(self)
|
||||
EditAction = QAction("编辑", self)
|
||||
EditAction.triggered.connect(
|
||||
lambda: self.editRequested.emit(self.__timer_task)
|
||||
)
|
||||
menu.addAction(edit_action)
|
||||
Menu.addAction(EditAction)
|
||||
if self.__timer_task["status"] != ALTimerTaskStatus.RUNNING\
|
||||
and self.__timer_task["status"] != ALTimerTaskStatus.READY:
|
||||
delete_action = QAction("删除", self)
|
||||
delete_action.triggered.connect(
|
||||
DeleteAction = QAction("删除", self)
|
||||
DeleteAction.triggered.connect(
|
||||
lambda: self.__manage_widget.deleteTask(self.__timer_task)
|
||||
)
|
||||
menu.addAction(delete_action)
|
||||
menu.exec(self.mapToGlobal(pos))
|
||||
Menu.addAction(DeleteAction)
|
||||
Menu.exec(self.mapToGlobal(pos))
|
||||
|
||||
|
||||
class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
class ALTimerTaskManageWidget(CenterOnParentMixin, QWidget, Ui_ALTimerTaskManageWidget):
|
||||
|
||||
class SortPolicy(Enum):
|
||||
|
||||
@@ -190,9 +208,9 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__cfg_mgr = ConfigManager.instance()
|
||||
self.__cfg_mgr: ConfigProvider = ConfigManager.instance()
|
||||
self.__timer_tasks = []
|
||||
self.__check_timer = None
|
||||
self.__CheckTimer = None
|
||||
self.__sort_policy = self.SortPolicy.BY_EXECUTE_TIME
|
||||
self.__sort_order = Qt.SortOrder.AscendingOrder
|
||||
|
||||
@@ -202,7 +220,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
if not self.initializeTimerTasks():
|
||||
raise Exception("定时任务配置文件初始化失败 !")
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
@@ -213,15 +230,13 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
self.TimerTaskSortOrderToggleButton.clicked.connect(self.onSortOrderToggleButtonClicked)
|
||||
self.timerTasksChanged.connect(self.onTimerTasksChanged)
|
||||
|
||||
|
||||
def setupTimer(
|
||||
self
|
||||
):
|
||||
|
||||
self.__check_timer = QTimer(self)
|
||||
self.__check_timer.timeout.connect(self.checkTasks)
|
||||
self.__check_timer.start(500)
|
||||
|
||||
self.__CheckTimer = QTimer(self)
|
||||
self.__CheckTimer.timeout.connect(self.checkTasks)
|
||||
self.__CheckTimer.start(500)
|
||||
|
||||
def initializeTimerTasks(
|
||||
self
|
||||
@@ -238,13 +253,12 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def getTimerTasks(
|
||||
self
|
||||
) -> list:
|
||||
|
||||
try:
|
||||
timer_tasks = self.__cfg_mgr.get(ConfigManager.ConfigType.TIMERTASK)
|
||||
timer_tasks = self.__cfg_mgr.get(CfgKey.TIMERTASK.ROOT)
|
||||
if timer_tasks and "timer_tasks" in timer_tasks:
|
||||
for task in timer_tasks["timer_tasks"]:
|
||||
task["added_time"] = datetime.strptime(task["added_time"], "%Y-%m-%d %H:%M:%S")
|
||||
@@ -263,7 +277,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def setTimerTasks(
|
||||
self,
|
||||
timer_tasks: list
|
||||
@@ -277,7 +290,7 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
if "repeat_history" in task:
|
||||
for item in task["repeat_history"]:
|
||||
item["result"] = item["result"].value
|
||||
self.__cfg_mgr.set(ConfigManager.ConfigType.TIMERTASK, "", { "timer_tasks": timer_tasks })
|
||||
self.__cfg_mgr.set(CfgKey.TIMERTASK.ROOT, { "timer_tasks": timer_tasks })
|
||||
return True
|
||||
except Exception as e:
|
||||
QMessageBox.warning(
|
||||
@@ -287,31 +300,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
@@ -321,7 +309,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
self.timerTaskManageWidgetIsClosed.emit()
|
||||
event.ignore()
|
||||
|
||||
|
||||
def sortTimerTasks(
|
||||
self,
|
||||
policy: SortPolicy = SortPolicy.BY_EXECUTE_TIME,
|
||||
@@ -344,7 +331,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
reverse = order is Qt.SortOrder.DescendingOrder
|
||||
)
|
||||
|
||||
|
||||
def updateStat(
|
||||
self
|
||||
):
|
||||
@@ -371,7 +357,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
self.ExecutedTaskLabel.setText(f"已执行:{executed}")
|
||||
self.InvalidTaskLabel.setText(f"无效的:{invalid}")
|
||||
|
||||
|
||||
def updateTimerTaskList(
|
||||
self
|
||||
):
|
||||
@@ -379,41 +364,39 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
self.TimerTasksListWidget.clear()
|
||||
self.sortTimerTasks(self.__sort_policy, self.__sort_order)
|
||||
for timer_task in self.__timer_tasks:
|
||||
item = QListWidgetItem()
|
||||
item.setData(Qt.UserRole, timer_task)
|
||||
widget = ALTimerTaskItemWidget(self, timer_task)
|
||||
widget.DeleteButton.clicked.connect(
|
||||
Item = QListWidgetItem()
|
||||
Item.setData(Qt.UserRole, timer_task)
|
||||
Widget = ALTimerTaskItemWidget(self, timer_task)
|
||||
Widget.DeleteButton.clicked.connect(
|
||||
lambda _, task = timer_task: self.deleteTask(task)
|
||||
)
|
||||
if timer_task.get("repeat", False) and hasattr(widget, "HistoryButton"):
|
||||
widget.HistoryButton.clicked.connect(
|
||||
if timer_task.get("repeat", False) and hasattr(Widget, "HistoryButton"):
|
||||
Widget.HistoryButton.clicked.connect(
|
||||
lambda _, task = timer_task: self.showTaskHistory(task)
|
||||
)
|
||||
widget.editRequested.connect(self.editTask)
|
||||
item.setSizeHint(widget.size())
|
||||
self.TimerTasksListWidget.addItem(item)
|
||||
self.TimerTasksListWidget.setItemWidget(item, widget)
|
||||
|
||||
Widget.editRequested.connect(self.editTask)
|
||||
Item.setSizeHint(Widget.size())
|
||||
self.TimerTasksListWidget.addItem(Item)
|
||||
self.TimerTasksListWidget.setItemWidget(Item, Widget)
|
||||
|
||||
def addTask(
|
||||
self
|
||||
):
|
||||
|
||||
dialog = ALTimerTaskAddDialog(self)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
timer_task = dialog.getTimerTask()
|
||||
Dialog = ALTimerTaskAddDialog(self)
|
||||
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
timer_task = Dialog.getTimerTask()
|
||||
self.__timer_tasks.append(timer_task)
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
def editTask(
|
||||
self,
|
||||
timer_task: dict
|
||||
):
|
||||
|
||||
dialog = ALTimerTaskAddDialog(self, timer_task)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
updated = dialog.getTimerTask()
|
||||
Dialog = ALTimerTaskAddDialog(self, timer_task)
|
||||
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
updated = Dialog.getTimerTask()
|
||||
for i, task in enumerate(self.__timer_tasks):
|
||||
if task["uuid"] == updated["uuid"]:
|
||||
self.__timer_tasks[i] = updated
|
||||
@@ -437,7 +420,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
f"下次执行时间:{datetime.strftime(timer_task["execute_time"], "%Y-%m-%d %H:%M:%S")}\n"
|
||||
f"已记录次数:{history_count}"
|
||||
)
|
||||
|
||||
|
||||
def deleteTask(
|
||||
self,
|
||||
@@ -445,19 +427,19 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
):
|
||||
|
||||
if timer_task["repeat"]: # when delete a repeat task
|
||||
msgbox = QMessageBox(self)
|
||||
msgbox.setIcon(QMessageBox.Icon.Question)
|
||||
msgbox.setWindowTitle("警告 - AutoLibrary")
|
||||
msgbox.setStandardButtons(
|
||||
MsgBox = QMessageBox(self)
|
||||
MsgBox.setIcon(QMessageBox.Icon.Question)
|
||||
MsgBox.setWindowTitle("警告 - AutoLibrary")
|
||||
MsgBox.setStandardButtons(
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||
)
|
||||
msgbox.setText("删除可重复性任务将同时删除所有已执行的记录 !\n是否继续 ?")
|
||||
msgbox.setDetailedText(
|
||||
MsgBox.setText("删除可重复性任务将同时删除所有已执行的记录 !\n是否继续 ?")
|
||||
MsgBox.setDetailedText(
|
||||
"以下可重复性任务将被删除:\n"\
|
||||
"\n"
|
||||
f"{self.getTimerTaskDetailMessage(timer_task)}"
|
||||
)
|
||||
result = msgbox.exec()
|
||||
result = MsgBox.exec()
|
||||
if result != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
task_uuid = timer_task["uuid"]
|
||||
@@ -467,7 +449,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
]
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
def clearAllTasks(
|
||||
self
|
||||
):
|
||||
@@ -503,13 +484,13 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
]
|
||||
repeat_tasks_count = len(repeat_tasks)
|
||||
if repeat_tasks_count > 0:
|
||||
msgbox = QMessageBox(self)
|
||||
msgbox.setIcon(QMessageBox.Icon.Question)
|
||||
msgbox.setWindowTitle("警告 - AutoLibrary")
|
||||
msgbox.setStandardButtons(
|
||||
MsgBox = QMessageBox(self)
|
||||
MsgBox.setIcon(QMessageBox.Icon.Question)
|
||||
MsgBox.setWindowTitle("警告 - AutoLibrary")
|
||||
MsgBox.setStandardButtons(
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||
)
|
||||
msgbox.setText(
|
||||
MsgBox.setText(
|
||||
f"存在 {repeat_tasks_count} 个可重复性任务,\n"
|
||||
"删除可重复性任务将同时删除所有已执行的记录 !\n"
|
||||
"是否继续 ?"
|
||||
@@ -517,29 +498,32 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
delete_msgs = [
|
||||
self.getTimerTaskDetailMessage(x) for x in repeat_tasks
|
||||
]
|
||||
msgbox.setDetailedText(
|
||||
MsgBox.setDetailedText(
|
||||
"以下可重复性任务将被删除:\n"\
|
||||
"\n"
|
||||
f"{"\n\n".join(delete_msgs)}"
|
||||
)
|
||||
result = msgbox.exec()
|
||||
result = MsgBox.exec()
|
||||
if result != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
# clear all tasks
|
||||
self.__timer_tasks.clear()
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
def showTaskHistory(
|
||||
self,
|
||||
task: dict
|
||||
):
|
||||
|
||||
dialog = ALTimerTaskHistoryDialog(self, task)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
# Here we use reference to task data, not copy.
|
||||
# So any change of task data in history dialog will be
|
||||
# reflected in the timer task list
|
||||
# Thus we can emit timerTasksChanged signal to
|
||||
# update config file
|
||||
Dialog = ALTimerTaskHistoryDialog(self, task)
|
||||
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
def checkTasks(
|
||||
self
|
||||
):
|
||||
@@ -613,7 +597,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
break
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
|
||||
def onRepeatTimerTaskIs(
|
||||
self,
|
||||
status: ALTimerTaskStatus,
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import queue
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QObject,
|
||||
QTimer,
|
||||
Signal,
|
||||
Slot
|
||||
)
|
||||
|
||||
from gui.ALMainWorker import TimerTaskWorker
|
||||
|
||||
|
||||
class ALTimerTaskPoller(QObject):
|
||||
|
||||
taskRunning = Signal(dict)
|
||||
taskFinished = Signal(bool, dict)
|
||||
taskExecuted = Signal(dict)
|
||||
taskError = Signal(dict)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent=None,
|
||||
input_queue: queue.Queue = None,
|
||||
output_queue: queue.Queue = None,
|
||||
config_paths: list = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.__input_queue = input_queue or queue.Queue()
|
||||
self.__output_queue = output_queue or queue.Queue()
|
||||
self.__config_paths = config_paths or []
|
||||
self.__task_queue = queue.Queue()
|
||||
self.__timer = QTimer(self)
|
||||
self.__timer.timeout.connect(self.__poll)
|
||||
self.__worker = None
|
||||
self.__stopped = False
|
||||
|
||||
def start(
|
||||
self
|
||||
):
|
||||
|
||||
self.__stopped = False
|
||||
self.__timer.start(500)
|
||||
|
||||
def stop(
|
||||
self
|
||||
):
|
||||
|
||||
self.__stopped = True
|
||||
self.__timer.stop()
|
||||
self.__cleanupWorker()
|
||||
|
||||
def enqueue(
|
||||
self,
|
||||
task: dict
|
||||
):
|
||||
|
||||
self.__task_queue.put(task)
|
||||
|
||||
def isRunning(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
return self.__worker is not None
|
||||
|
||||
def updateConfigPaths(
|
||||
self,
|
||||
config_paths: list
|
||||
):
|
||||
|
||||
self.__config_paths = config_paths
|
||||
|
||||
@Slot()
|
||||
def __poll(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__worker is not None:
|
||||
return
|
||||
try:
|
||||
task = self.__task_queue.get_nowait()
|
||||
except queue.Empty:
|
||||
return
|
||||
self.__timer.stop()
|
||||
self.taskRunning.emit(task)
|
||||
try:
|
||||
self.__worker = TimerTaskWorker(
|
||||
task,
|
||||
self.__input_queue,
|
||||
self.__output_queue,
|
||||
self.__config_paths
|
||||
)
|
||||
self.__worker.timerTaskWorkerIsFinished.connect(self.__onFinished)
|
||||
self.__worker.start()
|
||||
except Exception:
|
||||
self.__worker = None
|
||||
if not self.__stopped:
|
||||
self.__timer.start(500)
|
||||
|
||||
@Slot(bool, dict)
|
||||
def __onFinished(
|
||||
self,
|
||||
is_error: bool,
|
||||
task: dict
|
||||
):
|
||||
|
||||
self.__worker.timerTaskWorkerIsFinished.disconnect(self.__onFinished)
|
||||
self.__worker.wait(1000)
|
||||
self.__worker.deleteLater()
|
||||
self.__worker = None
|
||||
try:
|
||||
self.taskFinished.emit(is_error, task)
|
||||
if not is_error:
|
||||
self.taskExecuted.emit(task)
|
||||
else:
|
||||
self.taskError.emit(task)
|
||||
finally:
|
||||
if not self.__stopped:
|
||||
self.__timer.start(500)
|
||||
|
||||
def __cleanupWorker(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__worker is None:
|
||||
return
|
||||
try:
|
||||
self.__worker.timerTaskWorkerIsFinished.disconnect(self.__onFinished)
|
||||
except (TypeError, RuntimeError):
|
||||
pass
|
||||
self.__worker.wait(500)
|
||||
self.__worker.deleteLater()
|
||||
self.__worker = None
|
||||
@@ -10,14 +10,22 @@ See the LICENSE file for details.
|
||||
from enum import Enum
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt, QSize, QCoreApplication, QRect, QPoint
|
||||
Qt,
|
||||
QSize,
|
||||
QCoreApplication,
|
||||
QRect,
|
||||
QPoint
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractScrollArea, QAbstractItemView,
|
||||
QTreeWidget, QTreeWidgetItem
|
||||
QAbstractScrollArea,
|
||||
QAbstractItemView,
|
||||
QTreeWidget,
|
||||
QTreeWidgetItem
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QDragEnterEvent, QDragMoveEvent, QDropEvent
|
||||
QDragEnterEvent,
|
||||
QDragMoveEvent,
|
||||
QDropEvent
|
||||
)
|
||||
|
||||
|
||||
@@ -39,14 +47,13 @@ class ALUserTreeWidget(QTreeWidget):
|
||||
self.setupUi()
|
||||
self.translateUi()
|
||||
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
__qtreewidgetitem = QTreeWidgetItem()
|
||||
__qtreewidgetitem.setText(0, u"\u5206\u7ec4/\u7528\u6237");
|
||||
self.setHeaderItem(__qtreewidgetitem)
|
||||
__QTreeWidgetItem = QTreeWidgetItem()
|
||||
__QTreeWidgetItem.setText(0, u"\u5206\u7ec4/\u7528\u6237");
|
||||
self.setHeaderItem(__QTreeWidgetItem)
|
||||
self.setObjectName(u"UserTreeWidget")
|
||||
self.setMinimumSize(QSize(230, 0))
|
||||
self.setMaximumSize(QSize(250, 16777215))
|
||||
@@ -70,14 +77,12 @@ class ALUserTreeWidget(QTreeWidget):
|
||||
self.header().setHighlightSections(False)
|
||||
self.header().setProperty(u"showSortIndicator", True)
|
||||
|
||||
|
||||
def translateUi(
|
||||
self
|
||||
):
|
||||
|
||||
___qtreewidgetitem = self.headerItem()
|
||||
___qtreewidgetitem.setText(1, QCoreApplication.translate("ALConfigWidget", u"\u72b6\u6001", None));
|
||||
|
||||
___QTreeWidgetItem = self.headerItem()
|
||||
___QTreeWidgetItem.setText(1, QCoreApplication.translate("ALConfigWidget", u"\u72b6\u6001", None));
|
||||
|
||||
@staticmethod
|
||||
def isDragPositionValid(
|
||||
@@ -90,7 +95,6 @@ class ALUserTreeWidget(QTreeWidget):
|
||||
y_offset < target_rect.height()*0.8)
|
||||
return valid
|
||||
|
||||
|
||||
def dragEnterEvent(
|
||||
self,
|
||||
event: QDragEnterEvent
|
||||
@@ -98,7 +102,6 @@ class ALUserTreeWidget(QTreeWidget):
|
||||
|
||||
super().dragEnterEvent(event)
|
||||
|
||||
|
||||
def dragMoveEvent(
|
||||
self,
|
||||
event: QDragMoveEvent
|
||||
@@ -136,7 +139,6 @@ class ALUserTreeWidget(QTreeWidget):
|
||||
return
|
||||
event.acceptProposedAction()
|
||||
|
||||
|
||||
def dropEvent(
|
||||
self,
|
||||
event: QDropEvent
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
workflow process. Do not edit manually.
|
||||
|
||||
This file is auto-generated during the workflow process.
|
||||
Last updated: 2026-05-09 06:05:13 UTC
|
||||
Last updated: 2026-07-14 02:19:31 UTC
|
||||
"""
|
||||
|
||||
AL_VERSION = "1.3.0"
|
||||
AL_TAG = "v1.3.0"
|
||||
AL_VERSION = "1.4.0"
|
||||
AL_TAG = "v1.4.0"
|
||||
AL_COMMIT_SHA = "local"
|
||||
AL_COMMIT_DATE = "null" # time zone : UTC
|
||||
AL_BUILD_DATE = "null" # time zone : UTC
|
||||
|
||||
@@ -8,26 +8,38 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from PySide6.QtCore import (
|
||||
Qt, Slot, QThread, Signal
|
||||
Qt,
|
||||
Slot,
|
||||
QThread,
|
||||
Signal
|
||||
)
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog, QLabel, QComboBox, QProgressBar,
|
||||
QPushButton, QVBoxLayout, QHBoxLayout,
|
||||
QMessageBox, QFrame, QLineEdit
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
QCloseEvent
|
||||
QDialog,
|
||||
QLabel,
|
||||
QComboBox,
|
||||
QProgressBar,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QHBoxLayout,
|
||||
QMessageBox,
|
||||
QFrame,
|
||||
QLineEdit
|
||||
)
|
||||
from PySide6.QtGui import QCloseEvent
|
||||
|
||||
from managers.driver.WebDriverManager import (
|
||||
instance as webdriver_manager_instance,
|
||||
WebDriverManager, WebDriverInfo, WebDriverType,
|
||||
instance as webdriverInstance,
|
||||
WebDriverManager,
|
||||
WebDriverCtx,
|
||||
WebDriverType,
|
||||
WebDriverStatus
|
||||
)
|
||||
from gui.ALStatusLabel import ALStatusLabel
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
|
||||
|
||||
class DownloadWorker(QThread):
|
||||
@@ -43,12 +55,12 @@ class DownloadWorker(QThread):
|
||||
def __init__(
|
||||
self,
|
||||
driver_manager: WebDriverManager,
|
||||
driver_info: WebDriverInfo
|
||||
driver_ctx: WebDriverCtx
|
||||
):
|
||||
super().__init__()
|
||||
self.__driver_manager = driver_manager
|
||||
self.__driver_info = driver_info
|
||||
self.__driver_path = None
|
||||
self.__driver_ctx = driver_ctx
|
||||
self.__driver_path: Optional[Path] = None
|
||||
self.__cancelled = False
|
||||
self.__cancel_event = threading.Event()
|
||||
|
||||
@@ -70,7 +82,7 @@ class DownloadWorker(QThread):
|
||||
self.downloadCancelled.emit()
|
||||
return
|
||||
self.__driver_path = self.__driver_manager.installDriver(
|
||||
self.__driver_info,
|
||||
self.__driver_ctx,
|
||||
progress_callback=self.onProgress,
|
||||
cancel_event=self.__cancel_event
|
||||
)
|
||||
@@ -113,7 +125,7 @@ class DownloadWorker(QThread):
|
||||
self.wait()
|
||||
|
||||
|
||||
class ALWebDriverDownloadDialog(QDialog):
|
||||
class ALWebDriverDownloadDialog(CenterOnParentMixin, QDialog):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -129,12 +141,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
"""
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.__driver_dir = driver_dir
|
||||
self.__driver_manager: Optional[WebDriverManager] = None
|
||||
self.__confirmed = False
|
||||
self.__selected_driver_info: Optional[WebDriverInfo] = None
|
||||
self.__driver_infos: list[WebDriverInfo] = []
|
||||
self.__selected_driver_ctx: Optional[WebDriverCtx] = None
|
||||
self.__driver_ctxs: list[WebDriverCtx] = []
|
||||
self.__download_thread: Optional[DownloadWorker] = None
|
||||
|
||||
self.setupUi()
|
||||
@@ -142,29 +153,26 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.initializeDriverManager()
|
||||
self.refreshDriverList()
|
||||
|
||||
|
||||
def showEvent(
|
||||
def closeEvent(
|
||||
self,
|
||||
event
|
||||
event: QCloseEvent
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
if self.parent():
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
return result
|
||||
|
||||
if self.__download_thread and self.__download_thread.isRunning():
|
||||
reply = QMessageBox.question(
|
||||
self,
|
||||
"确认关闭 - AutoLibrary",
|
||||
"驱动正在下载中, 确定要取消并关闭对话框吗 ?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||
)
|
||||
if reply == QMessageBox.StandardButton.No:
|
||||
event.ignore()
|
||||
return
|
||||
self.__download_thread.stop()
|
||||
if not self.__confirmed:
|
||||
self.__selected_driver_ctx = None
|
||||
event.accept()
|
||||
super().closeEvent(event)
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
@@ -174,14 +182,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.setMaximumHeight(240)
|
||||
self.setMinimumHeight(240)
|
||||
self.setWindowTitle("浏览器驱动下载 - AutoLibrary")
|
||||
|
||||
self.MainLayout = QVBoxLayout(self)
|
||||
self.MainLayout.setContentsMargins(5, 5, 5, 5)
|
||||
self.MainLayout.setSpacing(5)
|
||||
|
||||
self.BrowserCountLabel = QLabel("检测到 0 个可用浏览器:")
|
||||
self.MainLayout.addWidget(self.BrowserCountLabel)
|
||||
|
||||
self.DriverInfoLayout = QHBoxLayout()
|
||||
self.DriverInfoLayout.setSpacing(5)
|
||||
self.DriverComboBox = QComboBox()
|
||||
@@ -190,7 +195,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.StatusLabel.setFixedSize(32, 32)
|
||||
self.DriverInfoLayout.addWidget(self.StatusLabel)
|
||||
self.MainLayout.addLayout(self.DriverInfoLayout)
|
||||
|
||||
self.DetailLayout = QVBoxLayout()
|
||||
self.DetailLayout.setSpacing(5)
|
||||
self.DetailLayout.setContentsMargins(5, 5, 5, 5)
|
||||
@@ -203,7 +207,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.PathLabel.setText("路径:未安装")
|
||||
self.DetailLayout.addWidget(self.PathLabel)
|
||||
self.MainLayout.addLayout(self.DetailLayout)
|
||||
|
||||
self.Line = QFrame()
|
||||
self.Line.setFrameShape(QFrame.Shape.HLine)
|
||||
self.Line.setFrameShadow(QFrame.Shadow.Sunken)
|
||||
@@ -229,7 +232,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.ConfirmButton = QPushButton("确认")
|
||||
self.ConfirmButton.setFixedSize(80, 25)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
|
||||
self.ControlLayout.addWidget(self.RefreshButton)
|
||||
self.ControlLayout.addWidget(self.DownloadButton)
|
||||
self.ControlLayout.addWidget(self.DeleteButton)
|
||||
@@ -237,7 +239,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.ControlLayout.addWidget(self.ConfirmButton)
|
||||
self.MainLayout.addLayout(self.ControlLayout)
|
||||
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
@@ -249,18 +250,16 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||
self.DriverComboBox.currentIndexChanged.connect(self.onDriverComboBoxChanged)
|
||||
|
||||
|
||||
def initializeDriverManager(
|
||||
self
|
||||
):
|
||||
|
||||
try:
|
||||
self.__driver_manager = webdriver_manager_instance(self.__driver_dir)
|
||||
self.__driver_manager = webdriverInstance(self.__driver_dir)
|
||||
except ValueError as e:
|
||||
QMessageBox.warning(self, "初始化失败", f"WebDriverManager 初始化失败:\n{str(e)}")
|
||||
self.reject()
|
||||
|
||||
|
||||
def refreshDriverList(
|
||||
self
|
||||
):
|
||||
@@ -268,32 +267,116 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
if not self.__driver_manager:
|
||||
return
|
||||
self.__driver_manager.refresh()
|
||||
self.__driver_infos = self.__driver_manager.getDriverInfos()
|
||||
self.__driver_ctxs = self.__driver_manager.getDriverCtxs()
|
||||
self.DriverComboBox.clear()
|
||||
installed = 0
|
||||
installed_idx = 0
|
||||
for i, driver_info in enumerate(self.__driver_infos):
|
||||
if driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
for i, driver_ctx in enumerate(self.__driver_ctxs):
|
||||
display_text = f"{driver_ctx.driver_type.value} - {driver_ctx.browser_version}"
|
||||
if driver_ctx.driver_status == WebDriverStatus.INSTALLED:
|
||||
installed += 1
|
||||
installed_idx = i # get the installed driver index
|
||||
display_text = f"{driver_info.driver_type.value} - {driver_info.browser_version}"
|
||||
display_text += " - 已安装"
|
||||
self.DriverComboBox.addItem(display_text)
|
||||
count = len(self.__driver_infos)
|
||||
self.BrowserCountLabel.setText(f"检测到 {count} 个可用浏览器:")
|
||||
if self.__driver_infos:
|
||||
count = len(self.__driver_ctxs)
|
||||
self.BrowserCountLabel.setText(f"检测到 {count} 个可用浏览器,{installed} 个已安装驱动:")
|
||||
if self.__driver_ctxs:
|
||||
self.DriverComboBox.setCurrentIndex(installed_idx)
|
||||
|
||||
def updateDriverInfoDisplay(
|
||||
self,
|
||||
driver_ctx: WebDriverCtx
|
||||
):
|
||||
|
||||
if driver_ctx.driver_type == WebDriverType.CHROME:
|
||||
driver_type = "Google Chrome"
|
||||
elif driver_ctx.driver_type == WebDriverType.FIREFOX:
|
||||
driver_type = "Mozilla Firefox"
|
||||
elif driver_ctx.driver_type == WebDriverType.EDGE:
|
||||
driver_type = "Microsoft Edge"
|
||||
else:
|
||||
driver_type = "未知"
|
||||
self.BrowserTypeLabel.setText(f"类型:{driver_type}")
|
||||
self.VersionLabel.setText(f"版本:{driver_ctx.driver_version}")
|
||||
if driver_ctx.driver_path:
|
||||
self.PathLabel.setText(str(driver_ctx.driver_path))
|
||||
else:
|
||||
self.PathLabel.setText("未安装")
|
||||
match driver_ctx.driver_status:
|
||||
case WebDriverStatus.NOT_INSTALLED:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.WAITING
|
||||
case WebDriverStatus.INSTALLED:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.SUCCESS
|
||||
case WebDriverStatus.DOWNLOADING:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.RUNNING
|
||||
case WebDriverStatus.ERROR:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.FAILURE
|
||||
|
||||
def updateProgressBarStates(
|
||||
self,
|
||||
driver_ctx: WebDriverCtx
|
||||
):
|
||||
|
||||
if driver_ctx.driver_status == WebDriverStatus.NOT_INSTALLED:
|
||||
self.ProgressBar.setValue(0)
|
||||
self.ProgressText.setText("未安装")
|
||||
elif driver_ctx.driver_status == WebDriverStatus.INSTALLED:
|
||||
self.ProgressBar.setValue(100)
|
||||
self.ProgressText.setText("已安装")
|
||||
elif driver_ctx.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
pass # update by worker thread
|
||||
elif driver_ctx.driver_status == WebDriverStatus.ERROR:
|
||||
self.ProgressBar.setValue(0)
|
||||
self.ProgressText.setText("下载失败")
|
||||
|
||||
def updateButtonStates(
|
||||
self,
|
||||
driver_ctx: WebDriverCtx
|
||||
):
|
||||
|
||||
if driver_ctx.driver_status == WebDriverStatus.NOT_INSTALLED:
|
||||
self.RefreshButton.setEnabled(True)
|
||||
self.DeleteButton.setEnabled(False)
|
||||
self.DownloadButton.setEnabled(True)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
elif driver_ctx.driver_status == WebDriverStatus.INSTALLED:
|
||||
self.RefreshButton.setEnabled(True)
|
||||
self.DownloadButton.setEnabled(False)
|
||||
self.DeleteButton.setEnabled(True)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(True)
|
||||
elif driver_ctx.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
self.RefreshButton.setEnabled(False)
|
||||
self.DownloadButton.setEnabled(False)
|
||||
self.DeleteButton.setEnabled(False)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
elif driver_ctx.driver_status == WebDriverStatus.ERROR:
|
||||
self.RefreshButton.setEnabled(True)
|
||||
self.DownloadButton.setEnabled(True)
|
||||
self.DeleteButton.setEnabled(False)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
|
||||
def getSelectedDriverInfo(
|
||||
self
|
||||
) -> Optional[WebDriverCtx]:
|
||||
|
||||
return self.__selected_driver_ctx
|
||||
|
||||
@Slot(int)
|
||||
def onDriverComboBoxChanged(
|
||||
self,
|
||||
index: int
|
||||
):
|
||||
|
||||
if not self.__driver_infos or index < 0 or index >= len(self.__driver_infos):
|
||||
if not self.__driver_ctxs or index < 0 or index >= len(self.__driver_ctxs):
|
||||
return
|
||||
driver_info = self.__driver_infos[index]
|
||||
self.updateDriverInfoDisplay(driver_info)
|
||||
self.updateProgressBarStates(driver_info)
|
||||
self.updateButtonStates(driver_info)
|
||||
|
||||
driver_ctx = self.__driver_ctxs[index]
|
||||
self.updateDriverInfoDisplay(driver_ctx)
|
||||
self.updateProgressBarStates(driver_ctx)
|
||||
self.updateButtonStates(driver_ctx)
|
||||
|
||||
@Slot()
|
||||
def onRefreshButtonClicked(
|
||||
@@ -302,16 +385,15 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.refreshDriverList()
|
||||
|
||||
|
||||
@Slot()
|
||||
def onDeleteButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if index < 0 or index >= len(self.__driver_infos):
|
||||
if index < 0 or index >= len(self.__driver_ctxs):
|
||||
return
|
||||
driver_info = self.__driver_infos[index]
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
if driver_info.driver_status.name != "INSTALLED":
|
||||
QMessageBox.information(self, "提示 - AutoLibrary", "该驱动未安装, 无需删除")
|
||||
return
|
||||
@@ -337,9 +419,9 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.DriverComboBox.setEnabled(False)
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if index < 0 or index >= len(self.__driver_infos):
|
||||
if index < 0 or index >= len(self.__driver_ctxs):
|
||||
return
|
||||
driver_info = self.__driver_infos[index]
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
if driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
return
|
||||
driver_info.driver_status = WebDriverStatus.DOWNLOADING # we set this only to update
|
||||
@@ -355,7 +437,7 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.__download_thread.downloadFinished.connect(self.onDownloadFinished)
|
||||
self.__download_thread.downloadError.connect(self.onDownloadError)
|
||||
self.__download_thread.downloadCancelled.connect(self.onDownloadCancelled)
|
||||
self.__download_thread.finished.connect(self.__onThreadFinished)
|
||||
self.__download_thread.finished.connect(self.onDownloadThreadFinished)
|
||||
self.__download_thread.start()
|
||||
|
||||
@Slot()
|
||||
@@ -383,9 +465,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.DriverComboBox.setEnabled(True)
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if 0 <= index < len(self.__driver_infos):
|
||||
driver_info = self.__driver_infos[index]
|
||||
if 0 <= index < len(self.__driver_ctxs):
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
||||
current_text = self.DriverComboBox.itemText(index)
|
||||
self.DriverComboBox.setItemText(index, current_text + " - 已安装")
|
||||
self.updateDriverInfoDisplay(driver_info)
|
||||
self.updateProgressBarStates(driver_info)
|
||||
self.updateButtonStates(driver_info)
|
||||
@@ -398,15 +482,14 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.DriverComboBox.setEnabled(True)
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if 0 <= index < len(self.__driver_infos):
|
||||
driver_info = self.__driver_infos[index]
|
||||
if 0 <= index < len(self.__driver_ctxs):
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
driver_info.driver_status = WebDriverStatus.ERROR
|
||||
self.updateDriverInfoDisplay(driver_info)
|
||||
self.updateProgressBarStates(driver_info)
|
||||
self.updateButtonStates(driver_info)
|
||||
QMessageBox.critical(self, "下载失败 - AutoLibrary", error_message)
|
||||
|
||||
|
||||
@Slot()
|
||||
def onDownloadCancelled(
|
||||
self
|
||||
@@ -414,8 +497,8 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.DriverComboBox.setEnabled(True)
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if 0 <= index < len(self.__driver_infos):
|
||||
driver_info = self.__driver_infos[index]
|
||||
if 0 <= index < len(self.__driver_ctxs):
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
self.__driver_manager.cancelDriverDownload(driver_info)
|
||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
self.updateDriverInfoDisplay(driver_info)
|
||||
@@ -423,6 +506,14 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.updateButtonStates(driver_info)
|
||||
self.ProgressText.setText("下载已取消")
|
||||
|
||||
@Slot()
|
||||
def onDownloadThreadFinished(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__download_thread:
|
||||
self.__download_thread.deleteLater()
|
||||
self.__download_thread = None
|
||||
|
||||
@Slot()
|
||||
def onConfirmButtonClicked(
|
||||
@@ -430,16 +521,15 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
):
|
||||
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if index < 0 or index >= len(self.__driver_infos):
|
||||
if index < 0 or index >= len(self.__driver_ctxs):
|
||||
return
|
||||
driver_info = self.__driver_infos[index]
|
||||
if driver_info.driver_status != WebDriverStatus.INSTALLED:
|
||||
driver_ctx = self.__driver_ctxs[index]
|
||||
if driver_ctx.driver_status != WebDriverStatus.INSTALLED:
|
||||
return
|
||||
self.__selected_driver_info = driver_info
|
||||
self.__selected_driver_ctx = driver_ctx
|
||||
self.__confirmed = True
|
||||
self.accept()
|
||||
|
||||
|
||||
@Slot()
|
||||
def onCancelButtonClicked(
|
||||
self
|
||||
@@ -456,121 +546,5 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.__download_thread.cancel()
|
||||
else:
|
||||
self.__confirmed = False
|
||||
self.__selected_driver_info = None
|
||||
self.__selected_driver_ctx = None
|
||||
self.reject()
|
||||
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
):
|
||||
|
||||
if self.__download_thread and self.__download_thread.isRunning():
|
||||
reply = QMessageBox.question(
|
||||
self,
|
||||
"确认关闭 - AutoLibrary",
|
||||
"驱动正在下载中, 确定要取消并关闭对话框吗 ?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||
)
|
||||
if reply == QMessageBox.StandardButton.No:
|
||||
event.ignore()
|
||||
return
|
||||
self.__download_thread.stop()
|
||||
if not self.__confirmed:
|
||||
self.__selected_driver_info = None
|
||||
event.accept()
|
||||
super().closeEvent(event)
|
||||
|
||||
def __onThreadFinished(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__download_thread:
|
||||
self.__download_thread.deleteLater()
|
||||
self.__download_thread = None
|
||||
|
||||
|
||||
def getSelectedDriverInfo(
|
||||
self
|
||||
) -> Optional[WebDriverInfo]:
|
||||
|
||||
return self.__selected_driver_info
|
||||
|
||||
|
||||
def updateDriverInfoDisplay(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
):
|
||||
|
||||
if driver_info.driver_type == WebDriverType.CHROME:
|
||||
driver_type = "Google Chrome"
|
||||
elif driver_info.driver_type == WebDriverType.FIREFOX:
|
||||
driver_type = "Mozilla Firefox"
|
||||
elif driver_info.driver_type == WebDriverType.EDGE:
|
||||
driver_type = "Microsoft Edge"
|
||||
else:
|
||||
driver_type = "未知"
|
||||
self.BrowserTypeLabel.setText(f"类型:{driver_type}")
|
||||
self.VersionLabel.setText(f"版本:{driver_info.driver_version}")
|
||||
if driver_info.driver_path:
|
||||
self.PathLabel.setText(str(driver_info.driver_path))
|
||||
else:
|
||||
self.PathLabel.setText("未安装")
|
||||
match driver_info.driver_status:
|
||||
case WebDriverStatus.NOT_INSTALLED:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.WAITING
|
||||
case WebDriverStatus.INSTALLED:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.SUCCESS
|
||||
case WebDriverStatus.DOWNLOADING:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.RUNNING
|
||||
case WebDriverStatus.ERROR:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.FAILURE
|
||||
|
||||
|
||||
def updateProgressBarStates(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
):
|
||||
|
||||
if driver_info.driver_status == WebDriverStatus.NOT_INSTALLED:
|
||||
self.ProgressBar.setValue(0)
|
||||
self.ProgressText.setText("未安装")
|
||||
elif driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
self.ProgressBar.setValue(100)
|
||||
self.ProgressText.setText("已安装")
|
||||
elif driver_info.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
pass # update by worker thread
|
||||
elif driver_info.driver_status == WebDriverStatus.ERROR:
|
||||
self.ProgressBar.setValue(0)
|
||||
self.ProgressText.setText("下载失败")
|
||||
|
||||
|
||||
def updateButtonStates(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
):
|
||||
|
||||
if driver_info.driver_status == WebDriverStatus.NOT_INSTALLED:
|
||||
self.RefreshButton.setEnabled(True)
|
||||
self.DeleteButton.setEnabled(False)
|
||||
self.DownloadButton.setEnabled(True)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
elif driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
self.RefreshButton.setEnabled(True)
|
||||
self.DownloadButton.setEnabled(False)
|
||||
self.DeleteButton.setEnabled(True)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(True)
|
||||
elif driver_info.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
self.RefreshButton.setEnabled(False)
|
||||
self.DownloadButton.setEnabled(False)
|
||||
self.DeleteButton.setEnabled(False)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
elif driver_info.driver_status == WebDriverStatus.ERROR:
|
||||
self.RefreshButton.setEnabled(True)
|
||||
self.DownloadButton.setEnabled(True)
|
||||
self.DeleteButton.setEnabled(False)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from PySide6.QtGui import QShowEvent
|
||||
|
||||
|
||||
class CenterOnParentMixin:
|
||||
"""
|
||||
Mixin that centres the widget relative to its parent on first show,
|
||||
clamping the position to the screen bounds.
|
||||
|
||||
Usage::
|
||||
|
||||
class MyWidget(CenterOnParentMixin, QWidget, Ui_MyWidget):
|
||||
pass
|
||||
|
||||
class MyDialog(CenterOnParentMixin, QDialog):
|
||||
pass
|
||||
|
||||
The mixin must appear **before** QWidget / QDialog in the base list
|
||||
so that ``super().showEvent(event)`` resolves up the MRO correctly.
|
||||
"""
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event: QShowEvent
|
||||
):
|
||||
|
||||
super().showEvent(event)
|
||||
if self.parent():
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width() // 2)
|
||||
target_pos.setY(target_pos.y() - self.height() // 2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
@@ -1,19 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
GUI module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- ALMainWindow: Main window class.
|
||||
- ALAboutDialog: About dialog class.
|
||||
- ALConfigWidget: Configuration widget class.
|
||||
- ALSeatFrame: Seat frame class.
|
||||
- ALSeatMapView: Seat map view class.
|
||||
- ALSeatMapTable: Seat map table class.
|
||||
- ALSeatMapSelectDialog: Seat map select dialog class.
|
||||
- ALTimerTaskAddDialog: Timer task add dialog class.
|
||||
- ALAutoScriptOrchDialog: AutoScript orchestration dialog class.
|
||||
- ALTimerTaskHistoryDialog: Timer task history dialog class.
|
||||
- ALTimerTaskManageWidget: Timer task manage widget class.
|
||||
- ALUserTreeWidget: User tree widget class.
|
||||
- ALMainWorkers: Main workers class.
|
||||
- ALVersionInfo: Version info class.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
<RCC>
|
||||
<qresource prefix="/res/icon">
|
||||
<file>icons/AutoLibrary_32x32.ico</file>
|
||||
</qresource>
|
||||
<qresource prefix="/res/trans">
|
||||
<qresource prefix="/res">
|
||||
<file>icons/AutoLibrary_Logo_64.svg</file>
|
||||
<file>icons/AutoLibrary_Logo_128.svg</file>
|
||||
|
||||
<file>icons/Copy.svg</file>
|
||||
<file>icons/Reset.svg</file>
|
||||
|
||||
<file>translators/qtbase_zh_CN.qm</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
GUI resources module for the AutoLibrary project.
|
||||
"""
|
||||
|
Before Width: | Height: | Size: 785 KiB |
|
Before Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 173 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 178 KiB |
|
After Width: | Height: | Size: 30 KiB |
@@ -0,0 +1,6 @@
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M13 7H7V5H13V7Z" fill="currentColor"/>
|
||||
<path d="M13 11H7V9H13V11Z" fill="currentColor"/>
|
||||
<path d="M7 15H13V13H7V15Z" fill="currentColor"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M3 19V1H17V5H21V23H7V19H3ZM15 17V3H5V17H15ZM17 7V19H9V21H19V7H17Z" fill="currentColor"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 396 B |
@@ -0,0 +1,3 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M20.817 11.186a8.94 8.94 0 0 0-1.355-3.219 9.053 9.053 0 0 0-2.43-2.43 8.95 8.95 0 0 0-3.219-1.355 9.028 9.028 0 0 0-1.838-.18V2L8 5l3.975 3V6.002c.484-.002.968.044 1.435.14a6.961 6.961 0 0 1 2.502 1.053 7.005 7.005 0 0 1 1.892 1.892A6.967 6.967 0 0 1 19 13a7.032 7.032 0 0 1-.55 2.725 7.11 7.11 0 0 1-.644 1.188 7.2 7.2 0 0 1-.858 1.039 7.028 7.028 0 0 1-3.536 1.907 7.13 7.13 0 0 1-2.822 0 6.961 6.961 0 0 1-2.503-1.054 7.002 7.002 0 0 1-1.89-1.89A6.996 6.996 0 0 1 5 13H3a9.02 9.02 0 0 0 1.539 5.034 9.096 9.096 0 0 0 2.428 2.428A8.95 8.95 0 0 0 12 22a9.09 9.09 0 0 0 1.814-.183 9.014 9.014 0 0 0 3.218-1.355 8.886 8.886 0 0 0 1.331-1.099 9.228 9.228 0 0 0 1.1-1.332A8.952 8.952 0 0 0 21 13a9.09 9.09 0 0 0-.183-1.814z" fill="currentColor"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 866 B |
@@ -0,0 +1,539 @@
|
||||
/*
|
||||
* Copyright (c) 2026 KenanZhu.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is provided "as is", without any warranty of any kind.
|
||||
* You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
* See the LICENSE file for details.
|
||||
*
|
||||
*
|
||||
* AutoLibrary Official Theme : BlueForest
|
||||
*/
|
||||
|
||||
/* ---- Global ---- */
|
||||
QMainWindow::separator {
|
||||
background-color: #1c2840;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
/* ---- Menu Bar ---- */
|
||||
QMenuBar {
|
||||
background-color: #0f1628;
|
||||
border-bottom: 1px solid #1c2840;
|
||||
padding: 2px 5px;
|
||||
color: #d0daf0;
|
||||
}
|
||||
QMenuBar::item {
|
||||
padding: 2px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QMenuBar::item:selected {
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QMenu {
|
||||
background-color: #162038;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
padding: 4px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QMenu::item {
|
||||
padding: 5px 15px 5px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QMenu::item:selected {
|
||||
background-color: #2dd4bf;
|
||||
color: #0f1119;
|
||||
}
|
||||
QMenu::separator {
|
||||
height: 1px;
|
||||
background-color: #253250;
|
||||
margin: 4px 8px;
|
||||
}
|
||||
|
||||
/* ---- Button ---- */
|
||||
QPushButton {
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
color: #d0daf0;
|
||||
padding: 4px 12px;
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QPushButton:hover {
|
||||
background-color: #243458;
|
||||
border-color: #334478;
|
||||
}
|
||||
QPushButton:pressed {
|
||||
background-color: #162038;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QPushButton:disabled {
|
||||
background-color: #162038;
|
||||
color: #5568a0;
|
||||
border-color: #1c2840;
|
||||
}
|
||||
QPushButton[default="true"] {
|
||||
background-color: #2dd4bf;
|
||||
color: #0f1119;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QPushButton[default="true"]:hover {
|
||||
background-color: #3de0cc;
|
||||
}
|
||||
|
||||
/* ---- Input ---- */
|
||||
QLineEdit,
|
||||
QPlainTextEdit,
|
||||
QTextEdit,
|
||||
QSpinBox,
|
||||
QDoubleSpinBox,
|
||||
QDateEdit,
|
||||
QTimeEdit {
|
||||
background-color: #0a1020;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
padding: 4px 8px;
|
||||
color: #d0daf0;
|
||||
selection-background-color: #2dd4bf;
|
||||
selection-color: #0f1119;
|
||||
}
|
||||
QLineEdit:focus,
|
||||
QPlainTextEdit:focus,
|
||||
QTextEdit:focus,
|
||||
QSpinBox:focus,
|
||||
QDoubleSpinBox:focus,
|
||||
QDateEdit:focus,
|
||||
QTimeEdit:focus {
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QPlainTextEdit,
|
||||
QTextEdit {
|
||||
background-color: #0a1020;
|
||||
}
|
||||
QLineEdit:disabled,
|
||||
QPlainTextEdit:disabled,
|
||||
QTextEdit:disabled,
|
||||
QSpinBox:disabled,
|
||||
QDoubleSpinBox:disabled,
|
||||
QDateEdit:disabled,
|
||||
QTimeEdit:disabled {
|
||||
background-color: #162038;
|
||||
color: #5568a0;
|
||||
border-color: #1c2840;
|
||||
}
|
||||
|
||||
/* ---- Spin Button Arrows ---- */
|
||||
QSpinBox::up-button,
|
||||
QDoubleSpinBox::up-button,
|
||||
QDateEdit::up-button,
|
||||
QTimeEdit::up-button {
|
||||
subcontrol-origin: border;
|
||||
subcontrol-position: top right;
|
||||
width: 10px;
|
||||
border-left: 1px solid #253250;
|
||||
border-bottom: 1px solid #253250;
|
||||
border-top-right-radius: 4px;
|
||||
}
|
||||
QSpinBox::up-button:hover,
|
||||
QDoubleSpinBox::up-button:hover,
|
||||
QDateEdit::up-button:hover,
|
||||
QTimeEdit::up-button:hover {
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QSpinBox::up-arrow,
|
||||
QDoubleSpinBox::up-arrow,
|
||||
QDateEdit::up-arrow,
|
||||
QTimeEdit::up-arrow {
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-bottom: 5px solid #7888b8;
|
||||
margin-top: 2px;
|
||||
}
|
||||
QSpinBox::down-button,
|
||||
QDoubleSpinBox::down-button,
|
||||
QDateEdit::down-button,
|
||||
QTimeEdit::down-button {
|
||||
width: 10px;
|
||||
subcontrol-origin: border;
|
||||
subcontrol-position: bottom right;
|
||||
border-left: 1px solid #253250;
|
||||
border-bottom-right-radius: 4px;
|
||||
}
|
||||
QSpinBox::down-button:hover,
|
||||
QDoubleSpinBox::down-button:hover,
|
||||
QDateEdit::down-button:hover,
|
||||
QTimeEdit::down-button:hover {
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QSpinBox::down-arrow,
|
||||
QDoubleSpinBox::down-arrow,
|
||||
QDateEdit::down-arrow,
|
||||
QTimeEdit::down-arrow {
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 5px solid #7888b8;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
QSpinBox::up-button:disabled,
|
||||
QDoubleSpinBox::up-button:disabled,
|
||||
QDateEdit::up-button:disabled,
|
||||
QTimeEdit::up-button:disabled,
|
||||
QSpinBox::down-button:disabled,
|
||||
QDoubleSpinBox::down-button:disabled,
|
||||
QDateEdit::down-button:disabled,
|
||||
QTimeEdit::down-button:disabled {
|
||||
background-color: #162038;
|
||||
}
|
||||
QSpinBox::up-arrow:disabled,
|
||||
QDoubleSpinBox::up-arrow:disabled,
|
||||
QDateEdit::up-arrow:disabled,
|
||||
QTimeEdit::up-arrow:disabled {
|
||||
border-bottom-color: #5568a0;
|
||||
}
|
||||
QSpinBox::down-arrow:disabled,
|
||||
QDoubleSpinBox::down-arrow:disabled,
|
||||
QDateEdit::down-arrow:disabled,
|
||||
QTimeEdit::down-arrow:disabled {
|
||||
border-top-color: #5568a0;
|
||||
}
|
||||
|
||||
/* ---- Combo Box ---- */
|
||||
QComboBox {
|
||||
background-color: #1c2840;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
padding: 4px 10px;
|
||||
color: #d0daf0;
|
||||
}
|
||||
QComboBox:hover {
|
||||
border-color: #334478;
|
||||
}
|
||||
QComboBox:focus {
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QComboBox::drop-down {
|
||||
subcontrol-origin: padding;
|
||||
subcontrol-position: top right;
|
||||
width: 24px;
|
||||
border-left: 1px solid #253250;
|
||||
border-top-right-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
}
|
||||
QComboBox::down-arrow {
|
||||
image: none;
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 6px solid #7888b8;
|
||||
margin-right: 6px;
|
||||
}
|
||||
QComboBox QAbstractItemView {
|
||||
background-color: #162038;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 4px;
|
||||
selection-background-color: #2dd4bf;
|
||||
selection-color: #0f1119;
|
||||
outline: none;
|
||||
}
|
||||
QComboBox:disabled {
|
||||
background-color: #162038;
|
||||
color: #5568a0;
|
||||
border-color: #1c2840;
|
||||
}
|
||||
|
||||
/* ---- Check Box / Radio Button ---- */
|
||||
QCheckBox,
|
||||
QRadioButton {
|
||||
spacing: 5px;
|
||||
color: #d0daf0;
|
||||
}
|
||||
QCheckBox::indicator,
|
||||
QRadioButton::indicator {
|
||||
border-style: solid;
|
||||
border-color: #334478;
|
||||
border-width: 2px;
|
||||
background-color: #0a1020;
|
||||
}
|
||||
QCheckBox::indicator {
|
||||
border-radius: 3px;
|
||||
}
|
||||
QRadioButton::indicator {
|
||||
border-radius: 7px;
|
||||
}
|
||||
QCheckBox::indicator:hover,
|
||||
QRadioButton::indicator:hover {
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QCheckBox::indicator:checked {
|
||||
background-color: #2dd4bf;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QRadioButton::indicator:checked {
|
||||
background-color: #2dd4bf;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QCheckBox::indicator:disabled,
|
||||
QRadioButton::indicator:disabled {
|
||||
border-color: #253250;
|
||||
background-color: #162038;
|
||||
}
|
||||
QCheckBox::indicator:checked:hover,
|
||||
QRadioButton::indicator:checked:hover {
|
||||
border-color: #a0f0e8;
|
||||
}
|
||||
|
||||
/* Tree / List / Table Widget CheckBox Indicator */
|
||||
QTreeWidget::indicator,
|
||||
QListWidget::indicator,
|
||||
QTableWidget::indicator {
|
||||
border: 2px solid #5568a0;
|
||||
border-radius: 3px;
|
||||
background-color: #162038;
|
||||
}
|
||||
QTreeWidget::indicator:hover,
|
||||
QListWidget::indicator:hover,
|
||||
QTableWidget::indicator:hover {
|
||||
border-color: #a0f0e8;
|
||||
}
|
||||
QTreeWidget::indicator:checked,
|
||||
QListWidget::indicator:checked,
|
||||
QTableWidget::indicator:checked {
|
||||
background-color: #2dd4bf;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QTreeWidget::indicator:checked:hover,
|
||||
QListWidget::indicator:checked:hover,
|
||||
QTableWidget::indicator:checked:hover {
|
||||
border-color: #a0f0e8;
|
||||
}
|
||||
QTreeWidget::indicator:disabled,
|
||||
QListWidget::indicator:disabled,
|
||||
QTableWidget::indicator:disabled {
|
||||
background-color: #1c2840;
|
||||
border-color: #334478;
|
||||
}
|
||||
QTreeWidget::indicator:indeterminate,
|
||||
QListWidget::indicator:indeterminate,
|
||||
QTableWidget::indicator:indeterminate {
|
||||
background-color: #2dd4bf;
|
||||
border-color: #a0f0e8;
|
||||
}
|
||||
|
||||
/* ---- Group Box ---- */
|
||||
QGroupBox {
|
||||
margin-top: 5px;
|
||||
padding-top: 15px;
|
||||
color: #b4c2f5;
|
||||
font-weight: bold;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* ---- Tab ---- */
|
||||
QTabWidget::pane {
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
background-color: #0f1a2e;
|
||||
top: -1px;
|
||||
}
|
||||
QTabBar::tab {
|
||||
background-color: #162038;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-bottom: none;
|
||||
border-top-left-radius: 5px;
|
||||
border-top-right-radius: 5px;
|
||||
padding: 6px 16px;
|
||||
margin-right: 2px;
|
||||
color: #7888b8;
|
||||
}
|
||||
QTabBar::tab:selected {
|
||||
background-color: #0f1a2e;
|
||||
color: #2dd4bf;
|
||||
border-bottom: 2px solid #2dd4bf;
|
||||
}
|
||||
|
||||
/* ---- List / Tree ---- */
|
||||
QListWidget,
|
||||
QTreeWidget,
|
||||
QTableWidget {
|
||||
background-color: #0a1020;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
outline: none;
|
||||
color: #d0daf0;
|
||||
alternate-background-color: #101c30;
|
||||
}
|
||||
QListWidget::item,
|
||||
QTreeWidget::item,
|
||||
QTableWidget::item {
|
||||
padding: 5px 5px;
|
||||
}
|
||||
QHeaderView::section {
|
||||
background-color: #0f1628;
|
||||
border-right: 1px solid #253250;
|
||||
border-bottom: 1px solid #253250;
|
||||
padding: 5px 10px;
|
||||
color: #8b9ad0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
/* ---- Scroll Bar ---- */
|
||||
QScrollBar:vertical {
|
||||
background-color: #0f1a2e;
|
||||
width: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:vertical {
|
||||
background-color: #334478;
|
||||
min-height: 30px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:vertical:hover {
|
||||
background-color: #5568a0;
|
||||
}
|
||||
QScrollBar::add-line:vertical,
|
||||
QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QScrollBar:horizontal {
|
||||
background-color: #0f1a2e;
|
||||
height: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:horizontal {
|
||||
background-color: #334478;
|
||||
min-width: 30px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:horizontal:hover {
|
||||
background-color: #5568a0;
|
||||
}
|
||||
QScrollBar::add-line:horizontal,
|
||||
QScrollBar::sub-line:horizontal {
|
||||
width: 0;
|
||||
}
|
||||
|
||||
/* ---- Progress Bar ---- */
|
||||
QProgressBar {
|
||||
background-color: #0a1020;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
height: 10px;
|
||||
text-align: center;
|
||||
color: #d0daf0;
|
||||
}
|
||||
QProgressBar::chunk {
|
||||
background-color: #2dd4bf;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ---- Slider ---- */
|
||||
QSlider::groove:horizontal {
|
||||
background-color: #1c2840;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
QSlider::handle:horizontal {
|
||||
background-color: #2dd4bf;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: -5px 0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QSlider::sub-page:horizontal {
|
||||
background-color: #2dd4bf;
|
||||
border-radius: 3px;
|
||||
}
|
||||
QSlider::handle:horizontal:disabled {
|
||||
background-color: #5568a0;
|
||||
}
|
||||
QSlider::sub-page:horizontal:disabled {
|
||||
background-color: #5568a0;
|
||||
}
|
||||
|
||||
/* ---- Tool Tip ---- */
|
||||
QToolTip {
|
||||
background-color: #1c2840;
|
||||
border-style: solid;
|
||||
border-color: #2dd4bf;
|
||||
border-width: 1px;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
color: #d0daf0;
|
||||
}
|
||||
|
||||
/* ---- Status Bar ---- */
|
||||
QStatusBar {
|
||||
background-color: #0f1628;
|
||||
border-top: 1px solid #1c2840;
|
||||
color: #7888b8;
|
||||
}
|
||||
|
||||
/* ---- Splitter ---- */
|
||||
QSplitter::handle {
|
||||
background-color: #253250;
|
||||
margin: 1px;
|
||||
}
|
||||
QSplitter::handle:horizontal {
|
||||
width: 2px;
|
||||
}
|
||||
QSplitter::handle:vertical {
|
||||
height: 2px;
|
||||
}
|
||||
|
||||
/* ---- Dialog ---- */
|
||||
QDialog {
|
||||
background-color: #0f1a2e;
|
||||
}
|
||||
|
||||
/* ---- Date / Time Editor Drop-down ---- */
|
||||
QDateEdit::drop-down,
|
||||
QTimeEdit::drop-down {
|
||||
subcontrol-origin: padding;
|
||||
subcontrol-position: top right;
|
||||
width: 24px;
|
||||
border-left: 1px solid #253250;
|
||||
}
|
||||
QCalendarWidget {
|
||||
background-color: #162038;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QCalendarWidget QToolButton {
|
||||
color: #d0daf0;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
QCalendarWidget QToolButton:hover {
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QCalendarWidget QMenu {
|
||||
background-color: #162038;
|
||||
}
|
||||
|
||||
/* ---- Frame ---- */
|
||||
QFrame[frameShape="4"], /* HLine */
|
||||
QFrame[frameShape="5"] /* VLine */ {
|
||||
background-color: #253250;
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
/*
|
||||
* Copyright (c) 2026 KenanZhu.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is provided "as is", without any warranty of any kind.
|
||||
* You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
* See the LICENSE file for details.
|
||||
*
|
||||
*
|
||||
* AutoLibrary Official Theme : LightLake
|
||||
*/
|
||||
|
||||
/* ---- Global ---- */
|
||||
QMainWindow::separator {
|
||||
background-color: #c0cdda;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
/* ---- Menu Bar ---- */
|
||||
QMenuBar {
|
||||
background-color: #dce4ee;
|
||||
border-bottom: 1px solid #c0cdda;
|
||||
padding: 2px 5px;
|
||||
color: #1a2740;
|
||||
}
|
||||
QMenuBar::item {
|
||||
padding: 2px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QMenuBar::item:selected {
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QMenu {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #d0d8e4;
|
||||
border-width: 1px;
|
||||
padding: 4px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QMenu::item {
|
||||
padding: 5px 15px 5px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QMenu::item:selected {
|
||||
background-color: #0ea58a;
|
||||
color: #ffffff;
|
||||
}
|
||||
QMenu::separator {
|
||||
height: 1px;
|
||||
background-color: #d0d8e4;
|
||||
margin: 4px 8px;
|
||||
}
|
||||
|
||||
/* ---- Button ---- */
|
||||
QPushButton {
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
color: #1a2740;
|
||||
padding: 4px 12px;
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QPushButton:hover {
|
||||
background-color: #c8d4e2;
|
||||
border-color: #90a4c4;
|
||||
}
|
||||
QPushButton:pressed {
|
||||
background-color: #e2e8f0;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QPushButton:disabled {
|
||||
background-color: #e8ecf2;
|
||||
color: #98a8c0;
|
||||
border-color: #d5dde8;
|
||||
}
|
||||
QPushButton[default="true"] {
|
||||
background-color: #0ea58a;
|
||||
color: #ffffff;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QPushButton[default="true"]:hover {
|
||||
background-color: #14c7a4;
|
||||
}
|
||||
|
||||
/* ---- Input ---- */
|
||||
QLineEdit,
|
||||
QPlainTextEdit,
|
||||
QTextEdit,
|
||||
QSpinBox,
|
||||
QDoubleSpinBox,
|
||||
QDateEdit,
|
||||
QTimeEdit {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
padding: 4px 8px;
|
||||
color: #1a2740;
|
||||
selection-background-color: #0ea58a;
|
||||
selection-color: #ffffff;
|
||||
}
|
||||
QLineEdit:focus,
|
||||
QPlainTextEdit:focus,
|
||||
QTextEdit:focus,
|
||||
QSpinBox:focus,
|
||||
QDoubleSpinBox:focus,
|
||||
QDateEdit:focus,
|
||||
QTimeEdit:focus {
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QPlainTextEdit,
|
||||
QTextEdit {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
QLineEdit:disabled,
|
||||
QPlainTextEdit:disabled,
|
||||
QTextEdit:disabled,
|
||||
QSpinBox:disabled,
|
||||
QDoubleSpinBox:disabled,
|
||||
QDateEdit:disabled,
|
||||
QTimeEdit:disabled {
|
||||
background-color: #e8ecf2;
|
||||
color: #98a8c0;
|
||||
border-color: #d5dde8;
|
||||
}
|
||||
|
||||
/* ---- Spin Button Arrows ---- */
|
||||
QSpinBox::up-button,
|
||||
QDoubleSpinBox::up-button,
|
||||
QDateEdit::up-button,
|
||||
QTimeEdit::up-button {
|
||||
subcontrol-origin: border;
|
||||
subcontrol-position: top right;
|
||||
width: 10px;
|
||||
border-left: 1px solid #c0cdda;
|
||||
border-bottom: 1px solid #c0cdda;
|
||||
border-top-right-radius: 4px;
|
||||
}
|
||||
QSpinBox::up-button:hover,
|
||||
QDoubleSpinBox::up-button:hover,
|
||||
QDateEdit::up-button:hover,
|
||||
QTimeEdit::up-button:hover {
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QSpinBox::up-arrow,
|
||||
QDoubleSpinBox::up-arrow,
|
||||
QDateEdit::up-arrow,
|
||||
QTimeEdit::up-arrow {
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-bottom: 5px solid #6a7898;
|
||||
margin-top: 2px;
|
||||
}
|
||||
QSpinBox::down-button,
|
||||
QDoubleSpinBox::down-button,
|
||||
QDateEdit::down-button,
|
||||
QTimeEdit::down-button {
|
||||
width: 10px;
|
||||
subcontrol-origin: border;
|
||||
subcontrol-position: bottom right;
|
||||
border-left: 1px solid #c0cdda;
|
||||
border-bottom-right-radius: 4px;
|
||||
}
|
||||
QSpinBox::down-button:hover,
|
||||
QDoubleSpinBox::down-button:hover,
|
||||
QDateEdit::down-button:hover,
|
||||
QTimeEdit::down-button:hover {
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QSpinBox::down-arrow,
|
||||
QDoubleSpinBox::down-arrow,
|
||||
QDateEdit::down-arrow,
|
||||
QTimeEdit::down-arrow {
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 5px solid #6a7898;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
QSpinBox::up-button:disabled,
|
||||
QDoubleSpinBox::up-button:disabled,
|
||||
QDateEdit::up-button:disabled,
|
||||
QTimeEdit::up-button:disabled,
|
||||
QSpinBox::down-button:disabled,
|
||||
QDoubleSpinBox::down-button:disabled,
|
||||
QDateEdit::down-button:disabled,
|
||||
QTimeEdit::down-button:disabled {
|
||||
background-color: #e8ecf2;
|
||||
}
|
||||
QSpinBox::up-arrow:disabled,
|
||||
QDoubleSpinBox::up-arrow:disabled,
|
||||
QDateEdit::up-arrow:disabled,
|
||||
QTimeEdit::up-arrow:disabled {
|
||||
border-bottom-color: #98a8c0;
|
||||
}
|
||||
QSpinBox::down-arrow:disabled,
|
||||
QDoubleSpinBox::down-arrow:disabled,
|
||||
QDateEdit::down-arrow:disabled,
|
||||
QTimeEdit::down-arrow:disabled {
|
||||
border-top-color: #98a8c0;
|
||||
}
|
||||
|
||||
/* ---- Combo Box ---- */
|
||||
QComboBox {
|
||||
background-color: #d5dde8;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
padding: 4px 10px;
|
||||
color: #1a2740;
|
||||
}
|
||||
QComboBox:hover {
|
||||
border-color: #90a4c4;
|
||||
}
|
||||
QComboBox:focus {
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QComboBox::drop-down {
|
||||
subcontrol-origin: padding;
|
||||
subcontrol-position: top right;
|
||||
width: 24px;
|
||||
border-left: 1px solid #c0cdda;
|
||||
border-top-right-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
}
|
||||
QComboBox::down-arrow {
|
||||
image: none;
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 6px solid #6a7898;
|
||||
margin-right: 6px;
|
||||
}
|
||||
QComboBox QAbstractItemView {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #d0d8e4;
|
||||
border-width: 1px;
|
||||
border-radius: 4px;
|
||||
selection-background-color: #0ea58a;
|
||||
selection-color: #ffffff;
|
||||
outline: none;
|
||||
}
|
||||
QComboBox:disabled {
|
||||
background-color: #e8ecf2;
|
||||
color: #98a8c0;
|
||||
border-color: #d5dde8;
|
||||
}
|
||||
|
||||
/* ---- Check Box / Radio Button ---- */
|
||||
QCheckBox,
|
||||
QRadioButton {
|
||||
spacing: 5px;
|
||||
color: #1a2740;
|
||||
}
|
||||
QCheckBox::indicator,
|
||||
QRadioButton::indicator {
|
||||
border-style: solid;
|
||||
border-color: #90a4c4;
|
||||
border-width: 2px;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
QCheckBox::indicator {
|
||||
border-radius: 3px;
|
||||
}
|
||||
QRadioButton::indicator {
|
||||
border-radius: 7px;
|
||||
}
|
||||
QCheckBox::indicator:hover,
|
||||
QRadioButton::indicator:hover {
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QCheckBox::indicator:checked {
|
||||
background-color: #0ea58a;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QRadioButton::indicator:checked {
|
||||
background-color: #0ea58a;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QCheckBox::indicator:disabled,
|
||||
QRadioButton::indicator:disabled {
|
||||
border-color: #c0cdda;
|
||||
background-color: #e8ecf2;
|
||||
}
|
||||
QCheckBox::indicator:checked:hover,
|
||||
QRadioButton::indicator:checked:hover {
|
||||
border-color: #14c7a4;
|
||||
}
|
||||
|
||||
/* Tree / List / Table Widget CheckBox Indicator */
|
||||
QTreeWidget::indicator,
|
||||
QListWidget::indicator,
|
||||
QTableWidget::indicator {
|
||||
border: 2px solid #a0b4cc;
|
||||
border-radius: 3px;
|
||||
background-color: #e8ecf2;
|
||||
}
|
||||
QTreeWidget::indicator:hover,
|
||||
QListWidget::indicator:hover,
|
||||
QTableWidget::indicator:hover {
|
||||
border-color: #14c7a4;
|
||||
}
|
||||
QTreeWidget::indicator:checked,
|
||||
QListWidget::indicator:checked,
|
||||
QTableWidget::indicator:checked {
|
||||
background-color: #0ea58a;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QTreeWidget::indicator:checked:hover,
|
||||
QListWidget::indicator:checked:hover,
|
||||
QTableWidget::indicator:checked:hover {
|
||||
border-color: #14c7a4;
|
||||
}
|
||||
QTreeWidget::indicator:disabled,
|
||||
QListWidget::indicator:disabled,
|
||||
QTableWidget::indicator:disabled {
|
||||
background-color: #d5dde8;
|
||||
border-color: #c0cdda;
|
||||
}
|
||||
QTreeWidget::indicator:indeterminate,
|
||||
QListWidget::indicator:indeterminate,
|
||||
QTableWidget::indicator:indeterminate {
|
||||
background-color: #0ea58a;
|
||||
border-color: #14c7a4;
|
||||
}
|
||||
|
||||
/* ---- Group Box ---- */
|
||||
QGroupBox {
|
||||
margin-top: 5px;
|
||||
padding-top: 15px;
|
||||
color: #4a6080;
|
||||
font-weight: bold;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* ---- Tab ---- */
|
||||
QTabWidget::pane {
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
background-color: #f0f4f8;
|
||||
top: -1px;
|
||||
}
|
||||
QTabBar::tab {
|
||||
background-color: #e0e6ee;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-bottom: none;
|
||||
border-top-left-radius: 5px;
|
||||
border-top-right-radius: 5px;
|
||||
padding: 6px 16px;
|
||||
margin-right: 2px;
|
||||
color: #6a7898;
|
||||
}
|
||||
QTabBar::tab:selected {
|
||||
background-color: #f0f4f8;
|
||||
color: #0ea58a;
|
||||
border-bottom: 2px solid #0ea58a;
|
||||
}
|
||||
|
||||
/* ---- List / Tree ---- */
|
||||
QListWidget,
|
||||
QTreeWidget,
|
||||
QTableWidget {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
outline: none;
|
||||
color: #1a2740;
|
||||
alternate-background-color: #f4f7fa;
|
||||
}
|
||||
QListWidget::item,
|
||||
QTreeWidget::item,
|
||||
QTableWidget::item {
|
||||
padding: 5px 5px;
|
||||
}
|
||||
QHeaderView::section {
|
||||
background-color: #dce4ee;
|
||||
border-right: 1px solid #c0cdda;
|
||||
border-bottom: 1px solid #c0cdda;
|
||||
padding: 5px 10px;
|
||||
color: #4a6080;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
/* ---- Scroll Bar ---- */
|
||||
QScrollBar:vertical {
|
||||
background-color: #eef2f6;
|
||||
width: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:vertical {
|
||||
background-color: #a0b4cc;
|
||||
min-height: 30px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:vertical:hover {
|
||||
background-color: #8098b8;
|
||||
}
|
||||
QScrollBar::add-line:vertical,
|
||||
QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QScrollBar:horizontal {
|
||||
background-color: #eef2f6;
|
||||
height: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:horizontal {
|
||||
background-color: #a0b4cc;
|
||||
min-width: 30px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:horizontal:hover {
|
||||
background-color: #8098b8;
|
||||
}
|
||||
QScrollBar::add-line:horizontal,
|
||||
QScrollBar::sub-line:horizontal {
|
||||
width: 0;
|
||||
}
|
||||
|
||||
/* ---- Progress Bar ---- */
|
||||
QProgressBar {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
height: 10px;
|
||||
text-align: center;
|
||||
color: #1a2740;
|
||||
}
|
||||
QProgressBar::chunk {
|
||||
background-color: #0ea58a;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ---- Slider ---- */
|
||||
QSlider::groove:horizontal {
|
||||
background-color: #d5dde8;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
QSlider::handle:horizontal {
|
||||
background-color: #0ea58a;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: -5px 0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QSlider::sub-page:horizontal {
|
||||
background-color: #0ea58a;
|
||||
border-radius: 3px;
|
||||
}
|
||||
QSlider::handle:horizontal:disabled {
|
||||
background-color: #98a8c0;
|
||||
}
|
||||
QSlider::sub-page:horizontal:disabled {
|
||||
background-color: #98a8c0;
|
||||
}
|
||||
|
||||
/* ---- Tool Tip ---- */
|
||||
QToolTip {
|
||||
background-color: #d5dde8;
|
||||
border-style: solid;
|
||||
border-color: #0ea58a;
|
||||
border-width: 1px;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
color: #1a2740;
|
||||
}
|
||||
|
||||
/* ---- Status Bar ---- */
|
||||
QStatusBar {
|
||||
background-color: #e8ecf2;
|
||||
border-top: 1px solid #c0cdda;
|
||||
color: #6a7898;
|
||||
}
|
||||
|
||||
/* ---- Splitter ---- */
|
||||
QSplitter::handle {
|
||||
background-color: #c0cdda;
|
||||
margin: 1px;
|
||||
}
|
||||
QSplitter::handle:horizontal {
|
||||
width: 2px;
|
||||
}
|
||||
QSplitter::handle:vertical {
|
||||
height: 2px;
|
||||
}
|
||||
|
||||
/* ---- Dialog ---- */
|
||||
QDialog {
|
||||
background-color: #f0f4f8;
|
||||
}
|
||||
|
||||
/* ---- Date / Time Editor Drop-down ---- */
|
||||
QDateEdit::drop-down,
|
||||
QTimeEdit::drop-down {
|
||||
subcontrol-origin: padding;
|
||||
subcontrol-position: top right;
|
||||
width: 24px;
|
||||
border-left: 1px solid #c0cdda;
|
||||
}
|
||||
QCalendarWidget {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QCalendarWidget QToolButton {
|
||||
color: #1a2740;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
QCalendarWidget QToolButton:hover {
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QCalendarWidget QMenu {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
/* ---- Frame ---- */
|
||||
QFrame[frameShape="4"], /* HLine */
|
||||
QFrame[frameShape="5"] /* VLine */ {
|
||||
background-color: #c0cdda;
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>800</width>
|
||||
<height>400</height>
|
||||
<height>600</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
@@ -103,53 +103,6 @@
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QFrame" name="AboutInfoSpaceFrame">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>56</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>56</width>
|
||||
<height>16777215</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="lineWidth">
|
||||
<number>0</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QTextBrowser" name="AboutInfoBrowser">
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="verticalScrollBarPolicy">
|
||||
<enum>Qt::ScrollBarPolicy::ScrollBarAlwaysOff</enum>
|
||||
</property>
|
||||
<property name="horizontalScrollBarPolicy">
|
||||
<enum>Qt::ScrollBarPolicy::ScrollBarAlwaysOff</enum>
|
||||
</property>
|
||||
<property name="lineWrapMode">
|
||||
<enum>QTextEdit::LineWrapMode::NoWrap</enum>
|
||||
</property>
|
||||
<property name="openExternalLinks">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="openLinks">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>ALBulletinDialog</class>
|
||||
<widget class="QDialog" name="ALBulletinDialog">
|
||||
<property name="windowModality">
|
||||
<enum>Qt::WindowModality::NonModal</enum>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>640</width>
|
||||
<height>450</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>400</width>
|
||||
<height>450</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>800</width>
|
||||
<height>450</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>公告栏 - AutoLibrary</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="ALBulletinDialogLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="SyncLayout">
|
||||
<property name="spacing">
|
||||
<number>10</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QPushButton" name="SyncButton">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="focusPolicy">
|
||||
<enum>Qt::FocusPolicy::NoFocus</enum>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>同步</string>
|
||||
</property>
|
||||
<property name="autoDefault">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="SyncStatusPlaceholder">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>30</width>
|
||||
<height>30</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>30</width>
|
||||
<height>30</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="SyncStatusDetailLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>200</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QFrame" name="SyncSpaceFrame">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>800</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="lineWidth">
|
||||
<number>0</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="LastSyncTimeLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>50</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>50</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>上次同步:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QDateTimeEdit" name="LastSyncDateTimeEdit">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>130</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>130</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="frame">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="readOnly">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="buttonSymbols">
|
||||
<enum>QAbstractSpinBox::ButtonSymbols::NoButtons</enum>
|
||||
</property>
|
||||
<property name="keyboardTracking">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="displayFormat">
|
||||
<string>yyyy/MM/dd HH:mm:ss</string>
|
||||
</property>
|
||||
<property name="timeSpec">
|
||||
<enum>Qt::TimeSpec::LocalTime</enum>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QSplitter" name="BulletinSplitter">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<widget class="QFrame" name="LeftFrame">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="LeftFrameLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QListWidget" name="BulletinListWidget">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="editTriggers">
|
||||
<set>QAbstractItemView::EditTrigger::NoEditTriggers</set>
|
||||
</property>
|
||||
<property name="selectionMode">
|
||||
<enum>QAbstractItemView::SelectionMode::SingleSelection</enum>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QFrame" name="RightFrame">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="RightFrameLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinTitleLabel">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="BulletinInfoLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinDateLabel">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinAuthorLabel">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinIsEditedLabel">
|
||||
<property name="text">
|
||||
<string>(已编辑)</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="BulletinInfoSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QTextBrowser" name="BulletinContentTextBrowser">
|
||||
<property name="readOnly">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="openExternalLinks">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QDialogButtonBox" name="BulletinDialogButtonBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>16777215</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="standardButtons">
|
||||
<set>QDialogButtonBox::StandardButton::Cancel|QDialogButtonBox::StandardButton::Ok</set>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections>
|
||||
<connection>
|
||||
<sender>BulletinDialogButtonBox</sender>
|
||||
<signal>accepted()</signal>
|
||||
<receiver>ALBulletinDialog</receiver>
|
||||
<slot>accept()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
<x>248</x>
|
||||
<y>254</y>
|
||||
</hint>
|
||||
<hint type="destinationlabel">
|
||||
<x>157</x>
|
||||
<y>274</y>
|
||||
</hint>
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>BulletinDialogButtonBox</sender>
|
||||
<signal>rejected()</signal>
|
||||
<receiver>ALBulletinDialog</receiver>
|
||||
<slot>reject()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
<x>316</x>
|
||||
<y>260</y>
|
||||
</hint>
|
||||
<hint type="destinationlabel">
|
||||
<x>286</x>
|
||||
<y>274</y>
|
||||
</hint>
|
||||
</hints>
|
||||
</connection>
|
||||
</connections>
|
||||
</ui>
|
||||
@@ -1956,13 +1956,13 @@
|
||||
<widget class="QPushButton" name="ExportConfigButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>120</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>120</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
|
||||
@@ -281,6 +281,13 @@ font: 700 9pt;</string>
|
||||
<property name="nativeMenuBar">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<widget class="QMenu" name="ToolsMenu">
|
||||
<property name="title">
|
||||
<string>工具</string>
|
||||
</property>
|
||||
<addaction name="SettingsAction"/>
|
||||
<addaction name="BulletinAction"/>
|
||||
</widget>
|
||||
<widget class="QMenu" name="HelpMenu">
|
||||
<property name="mouseTracking">
|
||||
<bool>true</bool>
|
||||
@@ -289,8 +296,10 @@ font: 700 9pt;</string>
|
||||
<string>帮助</string>
|
||||
</property>
|
||||
<addaction name="ManualAction"/>
|
||||
<addaction name="CheckUpdateAction"/>
|
||||
<addaction name="AboutAction"/>
|
||||
</widget>
|
||||
<addaction name="ToolsMenu"/>
|
||||
<addaction name="HelpMenu"/>
|
||||
</widget>
|
||||
<widget class="QStatusBar" name="StatusBar">
|
||||
@@ -303,11 +312,26 @@ font: 700 9pt;</string>
|
||||
<string>在线手册</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="CheckUpdateAction">
|
||||
<property name="text">
|
||||
<string>检查更新</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="AboutAction">
|
||||
<property name="text">
|
||||
<string>关于</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="SettingsAction">
|
||||
<property name="text">
|
||||
<string>全局设置</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="BulletinAction">
|
||||
<property name="text">
|
||||
<string>公告栏</string>
|
||||
</property>
|
||||
</action>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
|
||||
@@ -0,0 +1,788 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>ALSettingsWidget</class>
|
||||
<widget class="QWidget" name="ALSettingsWidget">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>520</width>
|
||||
<height>420</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>480</width>
|
||||
<height>420</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>580</width>
|
||||
<height>420</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>全局设置 - AutoLibrary</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="ALSettingsWidgetLayout">
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="ContentLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QListWidget" name="NavigationList">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>16777215</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="focusPolicy">
|
||||
<enum>Qt::FocusPolicy::StrongFocus</enum>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="editTriggers">
|
||||
<set>QAbstractItemView::EditTrigger::NoEditTriggers</set>
|
||||
</property>
|
||||
<property name="selectionMode">
|
||||
<enum>QAbstractItemView::SelectionMode::SingleSelection</enum>
|
||||
</property>
|
||||
<property name="iconSize">
|
||||
<size>
|
||||
<width>20</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="currentRow">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<property name="text">
|
||||
<string>外观</string>
|
||||
</property>
|
||||
<property name="icon">
|
||||
<iconset theme="preferences-desktop-color"/>
|
||||
</property>
|
||||
</item>
|
||||
<item>
|
||||
<property name="text">
|
||||
<string>公告</string>
|
||||
</property>
|
||||
<property name="icon">
|
||||
<iconset theme="preferences-desktop-color"/>
|
||||
</property>
|
||||
</item>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QStackedWidget" name="PageStack">
|
||||
<property name="currentIndex">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<widget class="QScrollArea" name="AppearanceScrollArea">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="widgetResizable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<widget class="QWidget" name="AppearancePageContent">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>397</width>
|
||||
<height>434</height>
|
||||
</rect>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="AppearancePageLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="AppearanceGroupBox">
|
||||
<property name="title">
|
||||
<string>主题模式</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="AppearanceGroupBoxLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QRadioButton" name="LightThemeRadio">
|
||||
<property name="text">
|
||||
<string>浅色</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QRadioButton" name="DarkThemeRadio">
|
||||
<property name="text">
|
||||
<string>深色</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QRadioButton" name="SystemThemeRadio">
|
||||
<property name="text">
|
||||
<string>跟随系统</string>
|
||||
</property>
|
||||
<property name="checked">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="InterfaceGroupBox">
|
||||
<property name="title">
|
||||
<string>界面风格</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="InterfaceGroupBoxLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="StyleSelectLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="StyleSelectLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>应用程序样式:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QComboBox" name="StyleComboBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>160</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="StyleHintLabel">
|
||||
<property name="text">
|
||||
<string>更改样式将在下次启动应用程序时生效。</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="CustomThemeGroupBox">
|
||||
<property name="title">
|
||||
<string>自定义外观</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="CustomQssGroupBoxLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="CustomThemeHintLabel">
|
||||
<property name="text">
|
||||
<string>选择一个主题,或导入新的主题文件:</string>
|
||||
</property>
|
||||
<property name="wordWrap">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="CustomThemePathLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QComboBox" name="CustomThemeComboBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>160</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLineEdit" name="CustomThemePathEdit">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="placeholderText">
|
||||
<string>选择或输入 QSS 样式表文件路径...</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="ImportCustomThemeButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>+</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="RemoveCustomThemeButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>-</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="CustomThemeInfoLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>60</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
<property name="textFormat">
|
||||
<enum>Qt::TextFormat::RichText</enum>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignmentFlag::AlignLeading|Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop</set>
|
||||
</property>
|
||||
<property name="wordWrap">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="CustomThemeActionLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QPushButton" name="ResetCustomThemeButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>重置主题</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="CustomThemeActionSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="CustomThemeStatusLabel">
|
||||
<property name="text">
|
||||
<string>当前使用程序 默认 外观。</string>
|
||||
</property>
|
||||
<property name="wordWrap">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="AppearancePageSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Vertical</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>20</width>
|
||||
<height>40</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
<widget class="QScrollArea" name="BulletinScrollArea">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="widgetResizable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<widget class="QWidget" name="BulletinPageContent">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>409</width>
|
||||
<height>383</height>
|
||||
</rect>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="BulletinPageLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="BulletinGroupBox">
|
||||
<property name="title">
|
||||
<string>公告设置</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="BulletinGroupBoxLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="BulletinServerUrlLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinServerUrlLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>服务器地址:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLineEdit" name="BulletinServerUrlEdit">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>200</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="placeholderText">
|
||||
<string>https://api.autolibrary.kenanzhu.com</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QCheckBox" name="BulletinAutoFetchCheck">
|
||||
<property name="text">
|
||||
<string>软件启动时自动获取公告</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="BulletinSyncIntervalLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinSyncIntervalLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>自动同步间隔:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QSpinBox" name="BulletinSyncIntervalSpin">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string> 分钟</string>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<number>1440</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="BulletinSyncIntervalSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="BulletinTestButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>测试连接</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinTestStatusLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>16777215</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
<property name="wordWrap">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="BulletinOpenButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>查看公告栏</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="BulletinPageSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Vertical</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>20</width>
|
||||
<height>40</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="ButtonLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<spacer name="ButtonLeftSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="CancelButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>取消</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="ApplyButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>应用</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="ConfirmButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>确认</string>
|
||||
</property>
|
||||
<property name="default">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
||||
@@ -7,13 +7,13 @@
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>350</width>
|
||||
<height>400</height>
|
||||
<height>500</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>350</width>
|
||||
<height>460</height>
|
||||
<height>500</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Any, Optional, Protocol
|
||||
|
||||
|
||||
class ConfigType(Enum):
|
||||
"""
|
||||
Config type enum. Values represent the default filename.
|
||||
"""
|
||||
|
||||
GLOBAL = "autolibrary.json"
|
||||
BULLETIN = "bulletin.json"
|
||||
TIMERTASK = "timer_task.json"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ConfigPath:
|
||||
"""
|
||||
A typed configuration path that carries both the config file
|
||||
and the dot-separated key in a single object.
|
||||
|
||||
Consumers pass this directly to ConfigProvider.get/set,
|
||||
eliminating the need to import ConfigType separately.
|
||||
"""
|
||||
|
||||
config_type: ConfigType
|
||||
key: str = ""
|
||||
|
||||
|
||||
class CfgKey:
|
||||
"""
|
||||
Type-safe hierarchical configuration key constants.
|
||||
|
||||
Each leaf is a ConfigPath that can be passed directly to
|
||||
``ConfigProvider.get()`` or ``ConfigProvider.set()``.
|
||||
|
||||
Usage::
|
||||
|
||||
CfgKey.GLOBAL.AUTOMATION.RUN_PATH.PATHS
|
||||
# -> ConfigPath(ConfigType.GLOBAL, "automation.run_path.paths")
|
||||
|
||||
config.get(CfgKey.GLOBAL.AUTOMATION.RUN_PATH.PATHS, [])
|
||||
config.set(CfgKey.GLOBAL.AUTOMATION.RUN_PATH.PATHS, value)
|
||||
"""
|
||||
|
||||
class GLOBAL:
|
||||
class AUTOMATION:
|
||||
ROOT = ConfigPath(ConfigType.GLOBAL, "automation")
|
||||
|
||||
class RUN_PATH:
|
||||
ROOT = ConfigPath(ConfigType.GLOBAL, "automation.run_path")
|
||||
CURRENT = ConfigPath(ConfigType.GLOBAL, "automation.run_path.current")
|
||||
PATHS = ConfigPath(ConfigType.GLOBAL, "automation.run_path.paths")
|
||||
|
||||
class USER_PATH:
|
||||
ROOT = ConfigPath(ConfigType.GLOBAL, "automation.user_path")
|
||||
CURRENT = ConfigPath(ConfigType.GLOBAL, "automation.user_path.current")
|
||||
PATHS = ConfigPath(ConfigType.GLOBAL, "automation.user_path.paths")
|
||||
|
||||
class APPEARANCE:
|
||||
ROOT = ConfigPath(ConfigType.GLOBAL, "appearance")
|
||||
THEME = ConfigPath(ConfigType.GLOBAL, "appearance.theme")
|
||||
STYLE = ConfigPath(ConfigType.GLOBAL, "appearance.style")
|
||||
CUSTOM_THEME = ConfigPath(ConfigType.GLOBAL, "appearance.custom_theme")
|
||||
|
||||
class BULLETIN:
|
||||
ROOT = ConfigPath(ConfigType.GLOBAL, "bulletin")
|
||||
AUTO_FETCH = ConfigPath(ConfigType.GLOBAL, "bulletin.auto_fetch")
|
||||
SERVER_URL = ConfigPath(ConfigType.GLOBAL, "bulletin.server_url")
|
||||
SYNC_INTERVAL = ConfigPath(ConfigType.GLOBAL, "bulletin.sync_interval")
|
||||
|
||||
class TIMERTASK:
|
||||
ROOT = ConfigPath(ConfigType.TIMERTASK, "")
|
||||
TIMER_TASKS = ConfigPath(ConfigType.TIMERTASK, "timer_tasks")
|
||||
|
||||
class BULLETIN:
|
||||
ROOT = ConfigPath(ConfigType.BULLETIN, "")
|
||||
BULLETIN = ConfigPath(ConfigType.BULLETIN, "bulletin")
|
||||
LAST_SYNC_TIME = ConfigPath(ConfigType.BULLETIN, "last_sync_time")
|
||||
|
||||
|
||||
class ConfigProvider(Protocol):
|
||||
"""
|
||||
Abstract interface for configuration storage access.
|
||||
|
||||
Concrete implementations (e.g. ConfigManager) conform to
|
||||
this protocol structurally rather than through explicit
|
||||
inheritance.
|
||||
"""
|
||||
|
||||
def get(
|
||||
self,
|
||||
key: ConfigPath,
|
||||
default: Optional[Any] = None
|
||||
) -> Any:
|
||||
"""
|
||||
Retrieve a configuration value.
|
||||
|
||||
Args:
|
||||
key: A ConfigPath object specifying which config file
|
||||
and key to read from.
|
||||
default: Fallback value if the key is not found.
|
||||
|
||||
Returns:
|
||||
The configuration value at the given key path.
|
||||
"""
|
||||
...
|
||||
|
||||
def set(
|
||||
self,
|
||||
key: ConfigPath,
|
||||
value: Any = None
|
||||
) -> None:
|
||||
"""
|
||||
Set a configuration value and persist to disk.
|
||||
|
||||
Args:
|
||||
key: A ConfigPath object specifying which config file
|
||||
and key to write to.
|
||||
value: The value to store.
|
||||
"""
|
||||
...
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -1,8 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Managers module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- ConfigManager: Config manager for managing configuration files.
|
||||
- LogManager: Log manager for logging.
|
||||
- WebDriverManager: Web driver manager for managing web drivers.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import threading
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from interfaces.ConfigProvider import (
|
||||
CfgKey,
|
||||
ConfigProvider
|
||||
)
|
||||
from managers.config.ConfigManager import instance as configInstance
|
||||
|
||||
|
||||
class BulletinManager:
|
||||
"""
|
||||
Bulletin Manager Singleton Class
|
||||
|
||||
Manages bulletin data persistence via ConfigManager and provides
|
||||
merge, read-status and sync-parameter logic. The HTTP fetch and
|
||||
UI concerns are handled by the GUI layer.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self
|
||||
):
|
||||
|
||||
self.__lock = threading.Lock()
|
||||
self.__cfg: ConfigProvider = configInstance()
|
||||
|
||||
def bulletins(
|
||||
self
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Get cached bulletins.
|
||||
|
||||
Returns:
|
||||
list[dict]: Cached bulletin list.
|
||||
"""
|
||||
|
||||
return self.__cfg.get(CfgKey.BULLETIN.BULLETIN, [])
|
||||
|
||||
def setBulletins(
|
||||
self,
|
||||
bulletins: list[dict]
|
||||
):
|
||||
"""
|
||||
Replace the bulletin cache.
|
||||
|
||||
Args:
|
||||
bulletins (list[dict]): Bulletin list to store.
|
||||
"""
|
||||
|
||||
self.__cfg.set(CfgKey.BULLETIN.BULLETIN, bulletins)
|
||||
|
||||
def lastSyncTime(
|
||||
self
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Get last sync time string.
|
||||
|
||||
Returns:
|
||||
Optional[str]: ISO-format last sync time, or None.
|
||||
"""
|
||||
|
||||
return self.__cfg.get(CfgKey.BULLETIN.LAST_SYNC_TIME, None)
|
||||
|
||||
def setLastSyncTime(
|
||||
self,
|
||||
value: Optional[str]
|
||||
):
|
||||
"""
|
||||
Set last sync time.
|
||||
|
||||
Args:
|
||||
value (Optional[str]): ISO-format datetime string.
|
||||
"""
|
||||
|
||||
self.__cfg.set(CfgKey.BULLETIN.LAST_SYNC_TIME, value)
|
||||
|
||||
def autoFetch(
|
||||
self
|
||||
) -> bool:
|
||||
"""
|
||||
Get auto-fetch-on-startup setting.
|
||||
|
||||
Returns:
|
||||
bool: Whether to fetch bulletins on application startup.
|
||||
"""
|
||||
|
||||
return self.__cfg.get(CfgKey.GLOBAL.BULLETIN.AUTO_FETCH, False)
|
||||
|
||||
def serverUrl(
|
||||
self
|
||||
) -> str:
|
||||
"""
|
||||
Get bulletin server URL.
|
||||
|
||||
Returns:
|
||||
str: Server base URL.
|
||||
"""
|
||||
|
||||
return self.__cfg.get(
|
||||
CfgKey.GLOBAL.BULLETIN.SERVER_URL,
|
||||
"https://api.autolibrary.kenanzhu.com"
|
||||
)
|
||||
|
||||
def syncInterval(
|
||||
self
|
||||
) -> int:
|
||||
"""
|
||||
Get auto-sync interval in minutes.
|
||||
|
||||
Values below 1 are clamped upward. Non-integer or missing
|
||||
values fall back to the default of 10 minutes.
|
||||
|
||||
Returns:
|
||||
int: Sync interval (minutes), minimum 1.
|
||||
"""
|
||||
|
||||
interval = self.__cfg.get(CfgKey.GLOBAL.BULLETIN.SYNC_INTERVAL, 10)
|
||||
try:
|
||||
interval = int(interval)
|
||||
except (ValueError, TypeError):
|
||||
return 10
|
||||
if interval < 1:
|
||||
return 5
|
||||
return interval
|
||||
|
||||
def apiUrl(
|
||||
self
|
||||
) -> str:
|
||||
"""
|
||||
Build the full bulletin API endpoint URL.
|
||||
|
||||
Returns:
|
||||
str: Full API URL (base + /bulletins).
|
||||
"""
|
||||
|
||||
base = self.serverUrl().rstrip("/")
|
||||
return f"{base}/bulletins"
|
||||
|
||||
@staticmethod
|
||||
def _ensureAware(
|
||||
dt_value: datetime
|
||||
) -> datetime:
|
||||
|
||||
if dt_value.tzinfo is None:
|
||||
return dt_value.replace(tzinfo=timezone.utc)
|
||||
return dt_value
|
||||
|
||||
@staticmethod
|
||||
def _parseBulletinDateTime(
|
||||
b: dict
|
||||
) -> datetime:
|
||||
|
||||
raw = b.get("dateTime", "")
|
||||
if not raw:
|
||||
raise ValueError("empty dateTime")
|
||||
dt_value = datetime.fromisoformat(raw)
|
||||
return BulletinManager._ensureAware(dt_value)
|
||||
|
||||
def isFirstSync(
|
||||
self
|
||||
) -> bool:
|
||||
"""
|
||||
Check whether this is the first sync.
|
||||
|
||||
Returns:
|
||||
bool: True if no cached bulletins or no last sync time.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
last = self.lastSyncTime()
|
||||
bulletins = self.bulletins()
|
||||
return last is None or not bulletins
|
||||
|
||||
def shouldFullSync(
|
||||
self
|
||||
) -> bool:
|
||||
"""
|
||||
Check whether a full sync is needed.
|
||||
|
||||
A full sync is triggered when the last sync time is more than
|
||||
one hour ago.
|
||||
|
||||
Returns:
|
||||
bool: True if a full sync should be performed.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
last = self.lastSyncTime()
|
||||
if last is None:
|
||||
return True
|
||||
try:
|
||||
last_dt = datetime.fromisoformat(last)
|
||||
last_dt = self._ensureAware(last_dt)
|
||||
now = datetime.now(timezone.utc).astimezone()
|
||||
return (now - last_dt) > timedelta(hours=1)
|
||||
except (ValueError, TypeError):
|
||||
return True
|
||||
|
||||
def getSyncDateTimeAndRange(
|
||||
self
|
||||
) -> dict:
|
||||
"""
|
||||
Calculate the date / time / range_hour query parameters.
|
||||
|
||||
Falls back to a first-sync (7-day window) on any parsing error.
|
||||
|
||||
Returns:
|
||||
dict: Keys "date", "time", "range_hour" for the API request.
|
||||
"""
|
||||
|
||||
now = datetime.now(timezone.utc).astimezone()
|
||||
try:
|
||||
if self.isFirstSync():
|
||||
start_date = now - timedelta(days=7)
|
||||
range_hour = str(24*8)
|
||||
elif self.shouldFullSync():
|
||||
with self.__lock:
|
||||
bulletins = self.bulletins()
|
||||
earliest = min(bulletins, key=self._parseBulletinDateTime)
|
||||
start_date = self._parseBulletinDateTime(earliest)
|
||||
diff = now - start_date
|
||||
range_hour = str(int(diff.total_seconds()/3600) + 1)
|
||||
else:
|
||||
with self.__lock:
|
||||
bulletins = self.bulletins()
|
||||
latest = max(bulletins, key=self._parseBulletinDateTime)
|
||||
start_date = self._parseBulletinDateTime(latest)
|
||||
diff = now - start_date
|
||||
range_hour = str(int(diff.total_seconds()/3600) + 1)
|
||||
except (ValueError, TypeError, KeyError):
|
||||
start_date = now - timedelta(days=7)
|
||||
range_hour = str(24*8)
|
||||
|
||||
return {
|
||||
"date": start_date.strftime("%Y-%m-%d"),
|
||||
"time": start_date.strftime("%H:%M:%S"),
|
||||
"range_hour": range_hour,
|
||||
}
|
||||
|
||||
def updateAndMergeBulletins(
|
||||
self,
|
||||
new_bulletins: list[dict],
|
||||
delete_ids: list[str]
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Merge incoming bulletins into the cache.
|
||||
|
||||
- New bulletins are added with isNew=True.
|
||||
- Existing bulletins keep their current isNew state.
|
||||
- Entries listed in delete_ids are removed.
|
||||
- Bulletins missing an "id" field are skipped.
|
||||
|
||||
Args:
|
||||
new_bulletins (list[dict]): Incoming bulletin list.
|
||||
delete_ids (list[str]): IDs to remove.
|
||||
|
||||
Returns:
|
||||
list[dict]: Merged bulletin list sorted by id.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
delete_set = set(str(d) for d in delete_ids)
|
||||
bulletins_dict = {}
|
||||
for b in self.bulletins():
|
||||
bid = b.get("id")
|
||||
if bid is not None:
|
||||
bulletins_dict[str(bid)] = b
|
||||
for bulletin in new_bulletins:
|
||||
bid = bulletin.get("id")
|
||||
if bid is None:
|
||||
continue
|
||||
bid = str(bid)
|
||||
if bid in delete_set:
|
||||
bulletins_dict.pop(bid, None)
|
||||
continue
|
||||
bulletin["isNew"] = (
|
||||
True
|
||||
if bid not in bulletins_dict
|
||||
else bulletins_dict[bid].get("isNew", True)
|
||||
)
|
||||
bulletins_dict[bid] = bulletin
|
||||
for bid in delete_set:
|
||||
bulletins_dict.pop(bid, None)
|
||||
result = list(bulletins_dict.values())
|
||||
result.sort(key=lambda x: str(x.get("id", "")))
|
||||
self.setBulletins(result)
|
||||
return result
|
||||
|
||||
def markBulletinAsRead(
|
||||
self,
|
||||
bulletin_id: str
|
||||
):
|
||||
"""
|
||||
Mark a bulletin as read by its id.
|
||||
|
||||
Args:
|
||||
bulletin_id (str): The bulletin id.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
bulletins = self.bulletins()
|
||||
for b in bulletins:
|
||||
if str(b.get("id", "")) == str(bulletin_id):
|
||||
b["isNew"] = False
|
||||
self.setBulletins(bulletins)
|
||||
break
|
||||
|
||||
|
||||
# BulletinManager singleton instance.
|
||||
_bulletin_manager_instance = None
|
||||
|
||||
# Singleton instance lock.
|
||||
_instance_lock = threading.Lock()
|
||||
|
||||
|
||||
def instance(
|
||||
) -> BulletinManager:
|
||||
"""
|
||||
Get the BulletinManager singleton instance.
|
||||
|
||||
Returns:
|
||||
BulletinManager: The singleton BulletinManager instance.
|
||||
"""
|
||||
|
||||
global _bulletin_manager_instance
|
||||
with _instance_lock:
|
||||
if _bulletin_manager_instance is None:
|
||||
_bulletin_manager_instance = BulletinManager()
|
||||
return _bulletin_manager_instance
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -7,27 +7,19 @@ This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import copy
|
||||
import os
|
||||
import threading
|
||||
|
||||
from enum import Enum
|
||||
from typing import Any, Optional
|
||||
|
||||
from utils.JSONReader import JSONReader
|
||||
from utils.JSONWriter import JSONWriter
|
||||
from interfaces.ConfigProvider import ConfigType, ConfigPath
|
||||
|
||||
|
||||
# This config manager class only responsible for global and other
|
||||
# unconfigurable config files.
|
||||
|
||||
|
||||
class ConfigType(Enum):
|
||||
"""
|
||||
Config type class. Values represent the default filename.
|
||||
"""
|
||||
GLOBAL = "autolibrary.json" # Global config file.
|
||||
BULLETIN = "bulletin.json" # Bulletin board config file.
|
||||
TIMERTASK = "timer_task.json" # Timer task config file.
|
||||
# config files. NOT include run and user config files.
|
||||
|
||||
|
||||
class ConfigTemplate:
|
||||
@@ -42,7 +34,6 @@ class ConfigTemplate:
|
||||
|
||||
self.__config_type = config_type
|
||||
|
||||
|
||||
def template(
|
||||
self
|
||||
) -> dict:
|
||||
@@ -64,6 +55,16 @@ class ConfigTemplate:
|
||||
"current": 0,
|
||||
"paths": []
|
||||
}
|
||||
},
|
||||
"appearance": {
|
||||
"theme": "system",
|
||||
"style": "Fusion",
|
||||
"custom_theme": ""
|
||||
},
|
||||
"bulletin": {
|
||||
"auto_fetch": False,
|
||||
"server_url": "https://api.autolibrary.kenanzhu.com",
|
||||
"sync_interval": 10
|
||||
}
|
||||
}
|
||||
case ConfigType.BULLETIN:
|
||||
@@ -87,12 +88,11 @@ class ConfigManager:
|
||||
):
|
||||
|
||||
self.__config_dir = os.path.abspath(config_dir)
|
||||
self.__config_lock = threading.Lock()
|
||||
self.__config_data = {}
|
||||
self.__lock = threading.Lock()
|
||||
|
||||
self.initialize()
|
||||
|
||||
|
||||
def initialize(
|
||||
self
|
||||
):
|
||||
@@ -100,7 +100,6 @@ class ConfigManager:
|
||||
for config_type in ConfigType:
|
||||
self.load(config_type)
|
||||
|
||||
|
||||
def load(
|
||||
self,
|
||||
config_type: ConfigType
|
||||
@@ -112,52 +111,47 @@ class ConfigManager:
|
||||
config_data = JSONReader(config_path).data()
|
||||
self.__config_data[config_type.value] = config_data
|
||||
return
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
self.__config_data[config_type.value] = ConfigTemplate(config_type).template()
|
||||
JSONWriter(config_path, self.__config_data[config_type.value])
|
||||
|
||||
|
||||
def get(
|
||||
self,
|
||||
config_type: ConfigType,
|
||||
key: str = "",
|
||||
key: ConfigPath,
|
||||
default: Optional[Any] = None
|
||||
) -> Any:
|
||||
|
||||
with self.__config_lock:
|
||||
config_data = self.__config_data[config_type.value]
|
||||
if key == "":
|
||||
return config_data
|
||||
keys = key.split('.')
|
||||
with self.__lock:
|
||||
config_data = self.__config_data[key.config_type.value]
|
||||
if key.key == "":
|
||||
return copy.deepcopy(config_data)
|
||||
keys = key.key.split('.')
|
||||
for k in keys[:-1]:
|
||||
config_data = config_data.get(k, None)
|
||||
if config_data is None:
|
||||
return default
|
||||
return config_data.get(keys[-1], default)
|
||||
|
||||
return copy.deepcopy(config_data.get(keys[-1], default))
|
||||
|
||||
def set(
|
||||
self,
|
||||
config_type: ConfigType,
|
||||
key: str = "",
|
||||
key: ConfigPath,
|
||||
value: Any = None
|
||||
):
|
||||
|
||||
with self.__config_lock:
|
||||
root_data = self.__config_data[config_type.value]
|
||||
if key == "":
|
||||
self.__config_data[config_type.value] = value
|
||||
with self.__lock:
|
||||
root_data = self.__config_data[key.config_type.value]
|
||||
if key.key == "":
|
||||
self.__config_data[key.config_type.value] = value
|
||||
else:
|
||||
keys = key.split('.')
|
||||
keys = key.key.split('.')
|
||||
config_data = root_data
|
||||
for k in keys[:-1]:
|
||||
if k not in config_data:
|
||||
config_data[k] = {}
|
||||
config_data = config_data[k]
|
||||
config_data[keys[-1]] = value
|
||||
self.save(config_type)
|
||||
|
||||
self.save(key.config_type)
|
||||
|
||||
def save(
|
||||
self,
|
||||
@@ -167,7 +161,6 @@ class ConfigManager:
|
||||
config_path = os.path.join(self.__config_dir, config_type.value)
|
||||
JSONWriter(config_path, self.__config_data[config_type.value])
|
||||
|
||||
|
||||
def configDir(
|
||||
self
|
||||
) -> str:
|
||||
@@ -180,6 +173,7 @@ _config_manager_instance : ConfigManager | None = None
|
||||
|
||||
# Singleton instance of ConfigManager.
|
||||
_instance_lock = threading.Lock()
|
||||
|
||||
def instance(
|
||||
config_dir: str = ""
|
||||
) -> ConfigManager:
|
||||
|
||||
@@ -11,6 +11,8 @@ import os
|
||||
|
||||
import managers.config.ConfigManager as ConfigManager
|
||||
|
||||
from interfaces.ConfigProvider import CfgKey
|
||||
|
||||
class ConfigUtils:
|
||||
"""
|
||||
Config utilities class.
|
||||
@@ -29,7 +31,7 @@ class ConfigUtils:
|
||||
cfg_mgr = ConfigManager.instance() # config manager instance
|
||||
|
||||
config_paths = {"run": "", "user": ""}
|
||||
auto_config = cfg_mgr.get(ConfigManager.ConfigType.GLOBAL, "automation", {})
|
||||
auto_config = cfg_mgr.get(CfgKey.GLOBAL.AUTOMATION.ROOT, {})
|
||||
for cfg_type in ["run", "user"]:
|
||||
paths = auto_config.get(f"{cfg_type}_path", {}).get("paths", [])
|
||||
index = auto_config.get(f"{cfg_type}_path", {}).get("current", 0)
|
||||
@@ -42,5 +44,5 @@ class ConfigUtils:
|
||||
config_paths[cfg_type] = paths[index]
|
||||
data = {"current": index, "paths": paths}
|
||||
auto_config[f"{cfg_type}_path"] = data
|
||||
cfg_mgr.set(ConfigManager.ConfigType.GLOBAL, "automation", auto_config)
|
||||
return config_paths
|
||||
cfg_mgr.set(CfgKey.GLOBAL.AUTOMATION.ROOT, auto_config)
|
||||
return config_paths
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Config managers module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- ConfigManager: Config manager for managing configuration files.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
@@ -41,6 +41,7 @@ class WebBrowserArch(Enum):
|
||||
MACX86_64 = 6
|
||||
MACARM = 7
|
||||
|
||||
|
||||
@dataclass
|
||||
class WebBrowserInfo:
|
||||
"""
|
||||
@@ -70,7 +71,6 @@ class WebBrowserArchDetector:
|
||||
|
||||
pass
|
||||
|
||||
|
||||
def detect(
|
||||
self
|
||||
) -> WebBrowserArch:
|
||||
@@ -123,7 +123,6 @@ class WebBrowserDetector:
|
||||
self.browser_arch = WebBrowserArchDetector().detect()
|
||||
self.browser_infos : list[WebBrowserInfo] = []
|
||||
|
||||
|
||||
def detect(
|
||||
self
|
||||
) -> list[WebBrowserInfo]:
|
||||
|
||||
@@ -95,7 +95,6 @@ class WebDriverName:
|
||||
|
||||
self.driver_type = driver_type
|
||||
|
||||
|
||||
def __str__(
|
||||
self
|
||||
) -> str:
|
||||
@@ -125,7 +124,6 @@ class WebDriverExecName:
|
||||
self.driver_type = driver_type
|
||||
self.arch = arch
|
||||
|
||||
|
||||
def __str__(
|
||||
self
|
||||
) -> str:
|
||||
@@ -183,7 +181,7 @@ class WebDriverFileName:
|
||||
raise ValueError(f"不受支持的 web driver 类型 : {self.driver_type}")
|
||||
|
||||
|
||||
class WebDriverURL:
|
||||
class WebDriverDownloadURL:
|
||||
"""
|
||||
Web driver download URL
|
||||
"""
|
||||
@@ -200,7 +198,6 @@ class WebDriverURL:
|
||||
self.arch = arch
|
||||
self.file_name = str(WebDriverFileName(self.version, self.driver_type, self.arch))
|
||||
|
||||
|
||||
def __str__(
|
||||
self
|
||||
) -> str:
|
||||
@@ -245,36 +242,11 @@ class WebDriverDownloader:
|
||||
self.driver_type = driver_type
|
||||
self.arch = driver_arch
|
||||
self.version = driver_version
|
||||
self.download_url = str(WebDriverURL(self.version, self.driver_type, self.arch))
|
||||
self.download_url = str(WebDriverDownloadURL(self.version, self.driver_type, self.arch))
|
||||
self.download_dir = Path(download_dir)/self.driver_type.value/self.version/self.arch.value
|
||||
self.download_dir.mkdir(mode=0o0755, parents=True, exist_ok=True)
|
||||
self.download_path = self.download_dir/str(WebDriverFileName(self.version, self.driver_type, self.arch))
|
||||
|
||||
|
||||
def download(
|
||||
self,
|
||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
||||
cancel_event: Optional[threading.Event] = None
|
||||
) -> Optional[Path]:
|
||||
|
||||
try:
|
||||
# downlaod file : 0% - 98%
|
||||
if not self._download(progress_callback, cancel_event=cancel_event):
|
||||
return None
|
||||
# verify file : 98% - 99%
|
||||
if not self._verify(progress_callback):
|
||||
progress_callback(0, 100, 0.0, "验证失败")
|
||||
return None
|
||||
# extract file : 99% - 100%
|
||||
driver_path = self._extract(progress_callback)
|
||||
if not driver_path:
|
||||
progress_callback(0, 100, 0.0, "解压失败")
|
||||
return None
|
||||
return driver_path
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
|
||||
def _download(
|
||||
self,
|
||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
||||
@@ -352,7 +324,6 @@ class WebDriverDownloader:
|
||||
continue
|
||||
raise e
|
||||
|
||||
|
||||
def _verify(
|
||||
self,
|
||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None
|
||||
@@ -361,7 +332,6 @@ class WebDriverDownloader:
|
||||
progress_callback(98, 100, 0.0, "验证完成")
|
||||
return True
|
||||
|
||||
|
||||
def _extract(
|
||||
self,
|
||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None
|
||||
@@ -390,6 +360,10 @@ class WebDriverDownloader:
|
||||
break
|
||||
if not driver_file:
|
||||
raise FileNotFoundError(f"未找到 web driver 文件 : {expected_name}")
|
||||
# Ensure executable permissions on Unix systems (zipfile
|
||||
# extraction does not preserve the execute bit).
|
||||
if os.name != 'nt':
|
||||
os.chmod(driver_file, 0o755)
|
||||
progress_callback(100, 100, 0.0, "解压完成")
|
||||
self.download_path.unlink()
|
||||
self._cleanup(driver_file)
|
||||
@@ -397,7 +371,6 @@ class WebDriverDownloader:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _cleanup(
|
||||
self,
|
||||
driver_file: Path
|
||||
@@ -410,6 +383,29 @@ class WebDriverDownloader:
|
||||
else:
|
||||
item.unlink()
|
||||
|
||||
def download(
|
||||
self,
|
||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
||||
cancel_event: Optional[threading.Event] = None
|
||||
) -> Optional[Path]:
|
||||
|
||||
try:
|
||||
# downlaod file : 0% - 98%
|
||||
if not self._download(progress_callback, cancel_event=cancel_event):
|
||||
return None
|
||||
# verify file : 98% - 99%
|
||||
if not self._verify(progress_callback):
|
||||
progress_callback(0, 100, 0.0, "验证失败")
|
||||
return None
|
||||
# extract file : 99% - 100%
|
||||
driver_path = self._extract(progress_callback)
|
||||
if not driver_path:
|
||||
progress_callback(0, 100, 0.0, "解压失败")
|
||||
return None
|
||||
return driver_path
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
|
||||
class ChromeDriverDownloader(WebDriverDownloader):
|
||||
"""
|
||||
|
||||
@@ -8,6 +8,7 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
import packaging.version as ver
|
||||
|
||||
@@ -19,7 +20,7 @@ from managers.driver.WebBrowserDetector import (
|
||||
WebBrowserType, WebBrowserArch, WebBrowserInfo, WebBrowserDetector
|
||||
)
|
||||
from managers.driver.WebDriverDownloader import (
|
||||
WebDriverArch, WebDriverType,
|
||||
WebDriverArch, WebDriverType, WebDriverExecName,
|
||||
ChromeDriverDownloader, FirefoxDriverDownloader, EdgeDriverDownloader
|
||||
)
|
||||
|
||||
@@ -35,9 +36,9 @@ class WebDriverStatus(Enum):
|
||||
ERROR = 3
|
||||
|
||||
|
||||
class WebDriverInfo:
|
||||
class WebDriverCtx:
|
||||
"""
|
||||
Web driver information.
|
||||
Web browser and driver context.
|
||||
|
||||
Attributes:
|
||||
driver_type (WebDriverType): Web driver type
|
||||
@@ -52,8 +53,8 @@ class WebDriverInfo:
|
||||
self
|
||||
):
|
||||
|
||||
self.driver_type = None
|
||||
self.driver_arch = None
|
||||
self.driver_type : Optional[WebDriverType] = None
|
||||
self.driver_arch : Optional[WebDriverArch] = None
|
||||
self.driver_version = ""
|
||||
self.browser_version = ""
|
||||
self.driver_path: Optional[Path] = None
|
||||
@@ -75,13 +76,12 @@ class WebDriverManager:
|
||||
|
||||
self.__driver_dir = os.path.abspath(driver_dir)
|
||||
self.__browser_detector = WebBrowserDetector()
|
||||
self.__driver_infos: list[WebDriverInfo] = []
|
||||
self.__driver_ctxs: list[WebDriverCtx] = []
|
||||
self.__initialized = False
|
||||
self.__lock = threading.Lock()
|
||||
|
||||
self.initialize()
|
||||
|
||||
|
||||
def initialize(
|
||||
self
|
||||
):
|
||||
@@ -93,31 +93,32 @@ class WebDriverManager:
|
||||
self._checkDriverStatus()
|
||||
self.__initialized = True
|
||||
|
||||
|
||||
def _detectBrowsers(
|
||||
self
|
||||
):
|
||||
|
||||
with self.__lock:
|
||||
browser_infos = self.__browser_detector.detect()
|
||||
self.__driver_infos = [
|
||||
self._getDriverInfo(info)
|
||||
self.__driver_ctxs = [
|
||||
self._getDriverCtx(info)
|
||||
for info in browser_infos
|
||||
]
|
||||
|
||||
|
||||
def _checkDriverStatus(
|
||||
self
|
||||
):
|
||||
|
||||
with self.__lock:
|
||||
for driver_info in self.__driver_infos:
|
||||
for driver_info in self.__driver_ctxs:
|
||||
driver_path = self._getDriverPath(driver_info)
|
||||
if driver_path and driver_path.exists() and driver_path.is_file():
|
||||
# Repair missing execute permission on Unix
|
||||
# (zip-extracted drivers from older versions).
|
||||
if os.name != 'nt' and not os.access(str(driver_path), os.X_OK):
|
||||
os.chmod(str(driver_path), 0o755)
|
||||
driver_info.driver_path = driver_path
|
||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
||||
|
||||
|
||||
def _mapWebBrowserTypeToDriver(
|
||||
self,
|
||||
browser_type: WebBrowserType
|
||||
@@ -132,7 +133,6 @@ class WebDriverManager:
|
||||
else:
|
||||
raise ValueError(f"不支持的 Web 浏览器类型 : {browser_type}")
|
||||
|
||||
|
||||
def _mapWebBrowserArchToDriver(
|
||||
self,
|
||||
browser_type: WebBrowserType,
|
||||
@@ -199,8 +199,7 @@ class WebDriverManager:
|
||||
else:
|
||||
raise ValueError(f"不支持的 Web 浏览器类型 : {browser_type}")
|
||||
|
||||
|
||||
def _mapFirefoxDriverVersion(
|
||||
def _mapFirefoxBrowserVersionToDriver(
|
||||
self,
|
||||
version: str
|
||||
) -> str:
|
||||
@@ -240,53 +239,34 @@ class WebDriverManager:
|
||||
except Exception as e:
|
||||
raise ValueError(f"无效的 Firefox 版本格式 : {version}") from e
|
||||
|
||||
|
||||
def _getDriverInfo(
|
||||
def _getDriverCtx(
|
||||
self,
|
||||
browser_info: WebBrowserInfo
|
||||
) -> WebDriverInfo:
|
||||
) -> WebDriverCtx:
|
||||
|
||||
driver_info = WebDriverInfo()
|
||||
driver_info.driver_type = self._mapWebBrowserTypeToDriver(browser_info.browser_type)
|
||||
driver_info.driver_arch = self._mapWebBrowserArchToDriver(browser_info.browser_type, browser_info.browser_arch)
|
||||
driver_ctx = WebDriverCtx()
|
||||
driver_ctx.driver_type = self._mapWebBrowserTypeToDriver(browser_info.browser_type)
|
||||
driver_ctx.driver_arch = self._mapWebBrowserArchToDriver(browser_info.browser_type, browser_info.browser_arch)
|
||||
if browser_info.browser_type == WebBrowserType.FIREFOX:
|
||||
driver_info.driver_version = self._mapFirefoxDriverVersion(browser_info.browser_version)
|
||||
driver_ctx.driver_version = self._mapFirefoxBrowserVersionToDriver(browser_info.browser_version)
|
||||
else:
|
||||
driver_info.driver_version = browser_info.browser_version
|
||||
driver_info.browser_version = browser_info.browser_version
|
||||
return driver_info
|
||||
|
||||
driver_ctx.driver_version = browser_info.browser_version
|
||||
driver_ctx.browser_version = browser_info.browser_version
|
||||
return driver_ctx
|
||||
|
||||
def _getDriverPath(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
driver_ctx: WebDriverCtx
|
||||
) -> Optional[Path]:
|
||||
|
||||
driver_type = driver_info.driver_type
|
||||
driver_arch = driver_info.driver_arch
|
||||
driver_version = driver_info.driver_version
|
||||
if driver_type == WebDriverType.CHROME:
|
||||
driver_name = "chromedriver"
|
||||
elif driver_type == WebDriverType.FIREFOX:
|
||||
driver_name = "geckodriver"
|
||||
elif driver_type == WebDriverType.EDGE:
|
||||
driver_name = "msedgedriver"
|
||||
else:
|
||||
return None
|
||||
is_win = driver_arch in [
|
||||
WebDriverArch.Chrome.WINX86_32,
|
||||
WebDriverArch.Chrome.WINX86_64,
|
||||
WebDriverArch.Firefox.WINX86_32,
|
||||
WebDriverArch.Firefox.WINX86_64,
|
||||
WebDriverArch.Edge.WINX86_32,
|
||||
WebDriverArch.Edge.WINX86_64,
|
||||
]
|
||||
exe_name = f"{driver_name}.exe" if is_win else driver_name
|
||||
driver_type = driver_ctx.driver_type
|
||||
driver_arch = driver_ctx.driver_arch
|
||||
driver_version = driver_ctx.driver_version
|
||||
exe_name = str(WebDriverExecName(driver_type, driver_arch))
|
||||
driver_dir = Path(self.__driver_dir)/driver_type.value/driver_version/driver_arch.value
|
||||
driver_path = driver_dir/exe_name
|
||||
return driver_path
|
||||
|
||||
|
||||
def refresh(
|
||||
self
|
||||
):
|
||||
@@ -294,62 +274,58 @@ class WebDriverManager:
|
||||
self._detectBrowsers()
|
||||
self._checkDriverStatus()
|
||||
|
||||
|
||||
def getDriverInfos(
|
||||
def getDriverCtxs(
|
||||
self
|
||||
) -> list[WebDriverInfo]:
|
||||
) -> list[WebDriverCtx]:
|
||||
|
||||
with self.__lock:
|
||||
return self.__driver_infos.copy()
|
||||
return self.__driver_ctxs.copy()
|
||||
|
||||
|
||||
def getDriverInfo(
|
||||
def getDriverCtx(
|
||||
self,
|
||||
driver_type: WebDriverType
|
||||
) -> list[WebDriverInfo]:
|
||||
) -> list[WebDriverCtx]:
|
||||
|
||||
with self.__lock:
|
||||
return [
|
||||
info
|
||||
for info in self.__driver_infos
|
||||
for info in self.__driver_ctxs
|
||||
if info.driver_type == driver_type
|
||||
]
|
||||
|
||||
|
||||
def getDriverPath(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
driver_info: WebDriverCtx
|
||||
) -> Optional[Path]:
|
||||
|
||||
if driver_info and driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
return driver_info.driver_path
|
||||
return None
|
||||
|
||||
|
||||
def installDriver(
|
||||
self,
|
||||
driver_info: WebDriverInfo,
|
||||
driver_ctx: WebDriverCtx,
|
||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
||||
cancel_event: Optional[threading.Event] = None
|
||||
) -> Optional[Path]:
|
||||
|
||||
with self.__lock:
|
||||
if not driver_info:
|
||||
if not driver_ctx:
|
||||
if progress_callback:
|
||||
progress_callback(0, 0, 0, "未找到浏览器信息")
|
||||
else:
|
||||
raise ValueError("未找到浏览器信息")
|
||||
if driver_info and driver_info.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
if driver_ctx and driver_ctx.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
if progress_callback:
|
||||
progress_callback(0, 0, 0, f"{driver_info.driver_type} 驱动正在下载中")
|
||||
progress_callback(0, 0, 0, f"{driver_ctx.driver_type} 驱动正在下载中")
|
||||
else:
|
||||
raise ValueError(f"{driver_info.driver_type} 驱动正在下载中")
|
||||
raise ValueError(f"{driver_ctx.driver_type} 驱动正在下载中")
|
||||
try:
|
||||
if not driver_info:
|
||||
if not driver_ctx:
|
||||
raise ValueError("未找到浏览器信息")
|
||||
driver_arch = driver_info.driver_arch
|
||||
driver_type = driver_info.driver_type
|
||||
driver_version = driver_info.driver_version
|
||||
driver_arch = driver_ctx.driver_arch
|
||||
driver_type = driver_ctx.driver_type
|
||||
driver_version = driver_ctx.driver_version
|
||||
downloader = None
|
||||
if driver_type == WebDriverType.CHROME:
|
||||
downloader = ChromeDriverDownloader(
|
||||
@@ -375,73 +351,68 @@ class WebDriverManager:
|
||||
else:
|
||||
raise ValueError(f"不支持的 Web Driver 类型")
|
||||
with self.__lock:
|
||||
driver_info.driver_status = WebDriverStatus.DOWNLOADING
|
||||
driver_ctx.driver_status = WebDriverStatus.DOWNLOADING
|
||||
driver_path = downloader.download(progress_callback=progress_callback, cancel_event=cancel_event)
|
||||
with self.__lock:
|
||||
if driver_path:
|
||||
driver_info.driver_path = driver_path
|
||||
driver_info.driver_version = driver_version
|
||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
||||
driver_ctx.driver_path = driver_path
|
||||
driver_ctx.driver_version = driver_version
|
||||
driver_ctx.driver_status = WebDriverStatus.INSTALLED
|
||||
else:
|
||||
driver_info.driver_status = WebDriverStatus.ERROR
|
||||
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||
return driver_path
|
||||
except Exception as e:
|
||||
with self.__lock:
|
||||
driver_info.driver_status = WebDriverStatus.ERROR
|
||||
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||
raise e
|
||||
|
||||
|
||||
def cancelDriverDownload(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
driver_ctx: WebDriverCtx
|
||||
) -> bool:
|
||||
|
||||
import shutil
|
||||
|
||||
try:
|
||||
driver_path = self._getDriverPath(driver_info)
|
||||
driver_path = self._getDriverPath(driver_ctx)
|
||||
if driver_path:
|
||||
download_dir = driver_path.parent
|
||||
if download_dir.exists():
|
||||
shutil.rmtree(download_dir, ignore_errors=True)
|
||||
with self.__lock:
|
||||
driver_info.driver_path = None
|
||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
driver_ctx.driver_path = None
|
||||
driver_ctx.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def uninstallDriver(
|
||||
self,
|
||||
driver_info: WebDriverInfo,
|
||||
driver_ctx: WebDriverCtx,
|
||||
progress_callback: Optional[Callable[[int, int, float, str], None]] = None
|
||||
) -> bool:
|
||||
|
||||
with self.__lock:
|
||||
if not driver_info:
|
||||
if not driver_ctx:
|
||||
if progress_callback:
|
||||
progress_callback(0, 0, 0, "未找到浏览器信息")
|
||||
else:
|
||||
raise ValueError("未找到浏览器信息")
|
||||
if driver_info.driver_status != WebDriverStatus.INSTALLED:
|
||||
if driver_ctx.driver_status != WebDriverStatus.INSTALLED:
|
||||
if progress_callback:
|
||||
progress_callback(0, 0, 0, f"{driver_info.driver_type} 驱动未安装")
|
||||
progress_callback(0, 0, 0, f"{driver_ctx.driver_type} 驱动未安装")
|
||||
else:
|
||||
raise ValueError(f"{driver_info.driver_type} 驱动未安装")
|
||||
raise ValueError(f"{driver_ctx.driver_type} 驱动未安装")
|
||||
try:
|
||||
driver_path = driver_info.driver_path
|
||||
driver_path = driver_ctx.driver_path
|
||||
driver_path.unlink()
|
||||
with self.__lock:
|
||||
driver_info.driver_path = None
|
||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
driver_ctx.driver_path = None
|
||||
driver_ctx.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
return True
|
||||
except Exception:
|
||||
with self.__lock:
|
||||
driver_info.driver_status = WebDriverStatus.ERROR
|
||||
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||
raise
|
||||
|
||||
|
||||
def driverDir(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Driver managers module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- WebBrowserDetector: Web browser detector class.
|
||||
- WebDriverDownloader: Web driver downloader class.
|
||||
- WebDriverManager: Web driver manager class.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
@@ -89,7 +89,6 @@ class LogManager:
|
||||
|
||||
self.initialize()
|
||||
|
||||
|
||||
def initialize(
|
||||
self
|
||||
):
|
||||
@@ -100,17 +99,14 @@ class LogManager:
|
||||
self.__logger = logging.getLogger("AutoLibrary")
|
||||
self.__logger.setLevel(logging.DEBUG)
|
||||
self.__logger.handlers.clear()
|
||||
|
||||
formatter = CallerInfoFormatter(
|
||||
'[%(asctime)s] - [%(name)s] - [%(levelname)s] - [%(filename)s:%(lineno)s] - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setLevel(logging.INFO)
|
||||
console_handler.setFormatter(formatter)
|
||||
self.__logger.addHandler(console_handler)
|
||||
|
||||
all_log_file = os.path.join(self.__log_dir, "all.log")
|
||||
file_handler_all = TimedRotatingFileHandler(
|
||||
all_log_file,
|
||||
@@ -123,7 +119,6 @@ class LogManager:
|
||||
file_handler_all.setLevel(logging.DEBUG)
|
||||
file_handler_all.setFormatter(formatter)
|
||||
self.__logger.addHandler(file_handler_all)
|
||||
|
||||
error_log_file = os.path.join(self.__log_dir, "error.log")
|
||||
file_handler_error = TimedRotatingFileHandler(
|
||||
error_log_file,
|
||||
@@ -136,10 +131,8 @@ class LogManager:
|
||||
file_handler_error.setLevel(logging.ERROR)
|
||||
file_handler_error.setFormatter(formatter)
|
||||
self.__logger.addHandler(file_handler_error)
|
||||
|
||||
self.__initialized = True
|
||||
|
||||
|
||||
def getLogger(
|
||||
self,
|
||||
name: Optional[str] = None
|
||||
@@ -149,7 +142,6 @@ class LogManager:
|
||||
return self.__logger.getChild(name)
|
||||
return self.__logger
|
||||
|
||||
|
||||
def setLevel(
|
||||
self,
|
||||
level: int
|
||||
@@ -158,7 +150,6 @@ class LogManager:
|
||||
if self.__logger:
|
||||
self.__logger.setLevel(level)
|
||||
|
||||
|
||||
def logDir(
|
||||
self
|
||||
) -> str:
|
||||
@@ -171,6 +162,7 @@ _log_manager_instance = None
|
||||
|
||||
# Singleton instance lock.
|
||||
_instance_lock = threading.Lock()
|
||||
|
||||
def instance(
|
||||
log_dir: str = ""
|
||||
) -> LogManager:
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Log managers module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- LogManager: Log manager for logging.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QStyleFactory
|
||||
)
|
||||
|
||||
from interfaces.ConfigProvider import CfgKey
|
||||
from managers.config.ConfigManager import instance as configInstance
|
||||
from managers.log.LogManager import instance as logInstance
|
||||
from utils.ThemeUtils import (
|
||||
readThemeInfo,
|
||||
readThemeQss,
|
||||
validateTheme,
|
||||
wrapQssToAtheme
|
||||
)
|
||||
|
||||
|
||||
# we use Fusion as the default active style name
|
||||
# because it's cross-platform.
|
||||
_active_style_name = "Fusion"
|
||||
|
||||
|
||||
def setActiveStyle(
|
||||
style_name: str
|
||||
):
|
||||
|
||||
global _active_style_name
|
||||
_active_style_name = style_name
|
||||
|
||||
def getActiveStyle(
|
||||
) -> str:
|
||||
|
||||
return _active_style_name
|
||||
|
||||
|
||||
class ThemeManager:
|
||||
"""
|
||||
Theme manager class.
|
||||
|
||||
Manages the themes storage directory, providing import,
|
||||
list, remove, and apply operations for .altheme theme files.
|
||||
|
||||
Args:
|
||||
themes_dir (str): Path to the themes storage directory.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
themes_dir: str
|
||||
):
|
||||
|
||||
self.__themes_dir = os.path.abspath(themes_dir)
|
||||
self.__current_theme_name = ""
|
||||
self.__lock = threading.Lock()
|
||||
|
||||
# directory must exist
|
||||
os.makedirs(self.__themes_dir, exist_ok=True)
|
||||
|
||||
@staticmethod
|
||||
def _colorSchemeFor(
|
||||
theme: str
|
||||
) -> Qt.ColorScheme:
|
||||
"""
|
||||
Map a theme identifier to the corresponding Qt color scheme.
|
||||
"""
|
||||
|
||||
if theme == "dark":
|
||||
return Qt.ColorScheme.Dark
|
||||
elif theme == "light":
|
||||
return Qt.ColorScheme.Light
|
||||
else:
|
||||
return Qt.ColorScheme.Unknown
|
||||
|
||||
def _deleteThemeFile(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
"""
|
||||
Delete a theme file in the themes storage directory.
|
||||
|
||||
The caller must hold self.__lock before invoking this method.
|
||||
|
||||
**This method ONLY deletes the file**.
|
||||
"""
|
||||
|
||||
filepath = os.path.join(self.__themes_dir, name + ".altheme")
|
||||
if os.path.isfile(filepath):
|
||||
os.remove(filepath)
|
||||
|
||||
def _resolveDestPath(
|
||||
self,
|
||||
theme_name: str,
|
||||
author: str
|
||||
) -> str:
|
||||
"""
|
||||
Resolve the destination path for an imported theme.
|
||||
|
||||
If the default {name}.altheme path does not exist, use it directly.
|
||||
If it exists and has a different author, use {name}_{author}.altheme.
|
||||
If it exists and has the same author, raise ValueError.
|
||||
|
||||
Args:
|
||||
theme_name (str): Sanitised theme name.
|
||||
author (str): Theme author string.
|
||||
|
||||
Returns:
|
||||
str: The resolved destination file path.
|
||||
|
||||
Raises:
|
||||
ValueError: If a theme with the same name and author already exists.
|
||||
"""
|
||||
|
||||
default_path = os.path.join(self.__themes_dir, theme_name + ".altheme")
|
||||
if not os.path.exists(default_path):
|
||||
return default_path
|
||||
try:
|
||||
existing_info = validateTheme(default_path)
|
||||
existing_author = existing_info.get("author", "")
|
||||
except Exception:
|
||||
self._deleteThemeFile(theme_name) # caller holds the lock
|
||||
raise ValueError(
|
||||
f"主题 '{theme_name}' 已存在但无法通过验证, 已清理该主题文件"
|
||||
)
|
||||
if existing_author == author:
|
||||
raise ValueError(
|
||||
f"主题名称 '{theme_name}' (作者 '{author}') 已存在"
|
||||
)
|
||||
safe_author = os.path.basename(author) if author else "未知作者"
|
||||
alt_path = os.path.join(
|
||||
self.__themes_dir, f"{theme_name}_{safe_author}.altheme"
|
||||
)
|
||||
if os.path.exists(alt_path):
|
||||
raise ValueError(
|
||||
f"主题名称 '{theme_name}' (作者 '{author}') 已存在"
|
||||
)
|
||||
return alt_path
|
||||
|
||||
def importTheme(
|
||||
self,
|
||||
source_path: str
|
||||
) -> str:
|
||||
"""
|
||||
Import a theme file into the themes directory.
|
||||
|
||||
Supports .altheme (zip archive) and bare .qss files.
|
||||
Bare .qss files are automatically wrapped into .altheme format.
|
||||
For .altheme files, validates that theme.qss exists in the archive
|
||||
and sanitises the theme name to prevent path traversal.
|
||||
|
||||
Args:
|
||||
source_path (str): Path to the .altheme or .qss file.
|
||||
|
||||
Returns:
|
||||
str: The imported theme name.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If source_path does not exist.
|
||||
ValueError: If the file type is unsupported or the .altheme is invalid.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(source_path):
|
||||
raise FileNotFoundError(source_path)
|
||||
base_name, ext = os.path.splitext(os.path.basename(source_path))
|
||||
ext = ext.lower()
|
||||
with self.__lock:
|
||||
if ext == ".qss":
|
||||
dest_path = self._resolveDestPath(base_name, "未知作者")
|
||||
wrapQssToAtheme(source_path, dest_path, "both")
|
||||
return os.path.splitext(os.path.basename(dest_path))[0]
|
||||
elif ext == ".altheme":
|
||||
info = validateTheme(source_path)
|
||||
name = info.get("name", base_name)
|
||||
safe_name = os.path.basename(name)
|
||||
new_author = info.get("author", "")
|
||||
dest_path = self._resolveDestPath(safe_name, new_author)
|
||||
shutil.copy2(source_path, dest_path)
|
||||
return os.path.splitext(os.path.basename(dest_path))[0]
|
||||
else:
|
||||
raise ValueError(f"不支持的文件类型: {ext}")
|
||||
|
||||
def listThemes(
|
||||
self
|
||||
) -> list:
|
||||
"""
|
||||
List all available themes in the themes directory.
|
||||
|
||||
Scans the themes directory for .altheme files and reads
|
||||
their info.json metadata.
|
||||
|
||||
Returns:
|
||||
list[dict]: A list of theme info dictionaries.
|
||||
"""
|
||||
|
||||
themes = []
|
||||
seen_keys = set()
|
||||
if not os.path.isdir(self.__themes_dir):
|
||||
return themes
|
||||
for filename in sorted(os.listdir(self.__themes_dir)):
|
||||
if filename.endswith(".altheme"):
|
||||
filepath = os.path.join(self.__themes_dir, filename)
|
||||
try:
|
||||
info = validateTheme(filepath)
|
||||
name = info.get("name", "")
|
||||
author = info.get("author", "")
|
||||
key = (name, author)
|
||||
if key in seen_keys:
|
||||
logInstance().getLogger("ThemeManager").warning(
|
||||
f"主题名称 '{name}' (作者 '{author}') 重复 (文件 '{filename}') 已跳过"
|
||||
)
|
||||
continue
|
||||
seen_keys.add(key)
|
||||
info["file"] = os.path.splitext(filename)[0]
|
||||
themes.append(info)
|
||||
except Exception as e:
|
||||
logInstance().getLogger("ThemeManager").warning(
|
||||
f"无法读取主题文件 '{filename}',已跳过: {e}"
|
||||
)
|
||||
else:
|
||||
logInstance().getLogger("ThemeManager").warning(
|
||||
f"未知文件类型 '{filename}',已跳过"
|
||||
)
|
||||
return themes
|
||||
|
||||
def removeTheme(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
"""
|
||||
Remove a theme by name.
|
||||
|
||||
If the removed theme is currently active, clears the QSS
|
||||
stylesheet from the application and reverts to the saved
|
||||
colour scheme.
|
||||
|
||||
Args:
|
||||
name (str): The theme name to remove.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
self._deleteThemeFile(name)
|
||||
if self.__current_theme_name == name:
|
||||
self.__current_theme_name = ""
|
||||
saved_theme = configInstance().get(
|
||||
CfgKey.GLOBAL.APPEARANCE.THEME, "system"
|
||||
)
|
||||
self.clearTheme(saved_theme)
|
||||
|
||||
def applyTheme(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
"""
|
||||
Apply a theme by name.
|
||||
|
||||
Extracts the QSS from the .altheme file, applies it to
|
||||
QApplication, and sets the Qt color scheme based on
|
||||
the theme's need_theme metadata.
|
||||
|
||||
Args:
|
||||
name (str): The theme name to apply.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the theme .altheme file does not exist.
|
||||
"""
|
||||
|
||||
filepath = os.path.join(self.__themes_dir, name + ".altheme")
|
||||
if not os.path.isfile(filepath):
|
||||
raise FileNotFoundError(filepath)
|
||||
with self.__lock:
|
||||
info = readThemeInfo(filepath)
|
||||
qss = readThemeQss(filepath)
|
||||
app = QApplication.instance()
|
||||
if app:
|
||||
app.setStyleSheet(qss)
|
||||
need_theme = info.get("need_theme", "both")
|
||||
app.styleHints().setColorScheme(
|
||||
ThemeManager._colorSchemeFor(need_theme)
|
||||
)
|
||||
app.setStyle(QStyleFactory.create(_active_style_name))
|
||||
self.__current_theme_name = name
|
||||
|
||||
def clearTheme(
|
||||
self,
|
||||
theme: str
|
||||
):
|
||||
"""
|
||||
Clear the current QSS stylesheet and apply the given color scheme.
|
||||
|
||||
Args:
|
||||
theme (str): The color scheme to apply after clearing
|
||||
("light", "dark", or "system").
|
||||
"""
|
||||
|
||||
app = QApplication.instance()
|
||||
if not app:
|
||||
return
|
||||
app.setStyleSheet("")
|
||||
app.styleHints().setColorScheme(
|
||||
ThemeManager._colorSchemeFor(theme)
|
||||
)
|
||||
app.setStyle(QStyleFactory.create(_active_style_name))
|
||||
|
||||
def themesDir(
|
||||
self
|
||||
) -> str:
|
||||
"""
|
||||
Get the themes directory path.
|
||||
|
||||
Returns:
|
||||
str: The absolute path to the themes storage directory.
|
||||
"""
|
||||
|
||||
return self.__themes_dir
|
||||
|
||||
|
||||
# ThemeManager singleton instance.
|
||||
_theme_manager_instance = None
|
||||
|
||||
# Singleton instance lock.
|
||||
_instance_lock = threading.Lock()
|
||||
|
||||
|
||||
def instance(
|
||||
themes_dir: str = ""
|
||||
) -> ThemeManager:
|
||||
"""
|
||||
Get the ThemeManager singleton instance.
|
||||
|
||||
On first call, initialises the ThemeManager with the themes
|
||||
directory derived from ConfigManager's config directory.
|
||||
|
||||
Args:
|
||||
themes_dir (str): Optional themes directory path.
|
||||
|
||||
Returns:
|
||||
ThemeManager: The singleton ThemeManager instance.
|
||||
"""
|
||||
|
||||
global _theme_manager_instance
|
||||
with _instance_lock:
|
||||
if _theme_manager_instance is None:
|
||||
if not themes_dir:
|
||||
cfg = configInstance()
|
||||
themes_dir = os.path.join(cfg.configDir(), "themes")
|
||||
_theme_manager_instance = ThemeManager(themes_dir)
|
||||
return _theme_manager_instance
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -1,359 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import queue
|
||||
|
||||
from selenium import webdriver
|
||||
from selenium.common.exceptions import TimeoutException
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.edge.service import Service as EdgeService
|
||||
from selenium.webdriver.chrome.service import Service as ChromeService
|
||||
from selenium.webdriver.firefox.service import Service as FirefoxService
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
from operators.LibChecker import LibChecker
|
||||
from operators.LibLogin import LibLogin
|
||||
from operators.LibLogout import LibLogout
|
||||
from operators.LibReserve import LibReserve
|
||||
from operators.LibCheckin import LibCheckin
|
||||
from operators.LibRenew import LibRenew
|
||||
|
||||
|
||||
class AutoLib(MsgBase):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
run_config: dict
|
||||
):
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__run_config = run_config
|
||||
self.__user_config = None
|
||||
self.__driver = None
|
||||
if not self.__initBrowserDriver():
|
||||
raise Exception("浏览器驱动初始化失败 !")
|
||||
else:
|
||||
if not self.__initDriverUrl():
|
||||
self.close()
|
||||
raise Exception("浏览器驱动URL初始化失败 !")
|
||||
self.__initLibOperators()
|
||||
|
||||
|
||||
def __initBrowserDriver(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
self._showTrace("正在初始化浏览器驱动......", no_log=True)
|
||||
|
||||
web_driver_config = self.__run_config.get("web_driver", None)
|
||||
self.__driver_type = web_driver_config.get("driver_type")
|
||||
match self.__driver_type.lower():
|
||||
case "edge":
|
||||
driver_options = webdriver.EdgeOptions()
|
||||
case "chrome":
|
||||
driver_options = webdriver.ChromeOptions()
|
||||
case "firefox":
|
||||
driver_options = webdriver.FirefoxOptions()
|
||||
case _:
|
||||
self._showTrace(
|
||||
f"不支持的浏览器驱动类型: {self.__driver_type} !",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
return False
|
||||
|
||||
if not web_driver_config:
|
||||
self._showTrace("未配置浏览器驱动参数 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
if web_driver_config.get("headless"):
|
||||
driver_options.add_argument("--headless")
|
||||
driver_options.add_argument("--disable-gpu")
|
||||
driver_options.add_argument("--no-sandbox")
|
||||
driver_options.add_argument("--disable-dev-shm-usage")
|
||||
|
||||
# must be 1920x1080, otherwise the page will cause some elements not accessible
|
||||
driver_options.add_argument("--window-size=1920,1080")
|
||||
|
||||
# omit ssl errors and verbose log level
|
||||
driver_options.add_argument("--ignore-certificate-errors")
|
||||
driver_options.add_argument("--ignore-ssl-errors")
|
||||
driver_options.add_argument("--log-level=OFF")
|
||||
driver_options.add_argument("--silent")
|
||||
|
||||
# set options for chrome and edge
|
||||
if self.__driver_type.lower() in ["edge", "chrome"]:
|
||||
driver_options.add_argument("--remote-allow-origins=*")
|
||||
driver_options.add_experimental_option("excludeSwitches", ["enable-automation"])
|
||||
driver_options.add_experimental_option("useAutomationExtension", False)
|
||||
driver_options.add_argument("--disable-blink-features=AutomationControlled")
|
||||
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "\
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "\
|
||||
"Chrome/120.0.0.0 "\
|
||||
"Safari/537.36"
|
||||
if self.__driver_type.lower() == "edge":
|
||||
user_agent += " Edg/120.0.0.0"
|
||||
# set options for firefox
|
||||
elif self.__driver_type.lower() == "firefox":
|
||||
driver_options.set_preference("dom.webdriver.enabled", False)
|
||||
driver_options.set_preference("useAutomationExtension", False)
|
||||
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) "\
|
||||
"Gecko/20100101 Firefox/120.0"
|
||||
driver_options.add_argument(f"user-agent={user_agent}")
|
||||
|
||||
# init browser driver
|
||||
self.__driver_path = web_driver_config.get("driver_path")
|
||||
if not self.__driver_path:
|
||||
self._showTrace("未配置浏览器驱动路径 !", self.TraceLevel.WARNING)
|
||||
return False
|
||||
self.__driver_path = os.path.abspath(self.__driver_path)
|
||||
try:
|
||||
service = None
|
||||
match self.__driver_type.lower():
|
||||
case "edge":
|
||||
service = EdgeService(executable_path=self.__driver_path)
|
||||
self.__driver = webdriver.Edge(service=service, options=driver_options)
|
||||
case "chrome":
|
||||
service = ChromeService(executable_path=self.__driver_path)
|
||||
self.__driver = webdriver.Chrome(service=service, options=driver_options)
|
||||
case "firefox":
|
||||
self._showTrace(f"Firefox 浏览器驱动初始化略慢, 请耐心等待...", no_log=True)
|
||||
service = FirefoxService(executable_path=self.__driver_path)
|
||||
self.__driver = webdriver.Firefox(service=service, options=driver_options)
|
||||
case _: # actually will not happen, beacuse we have checked it at the initlization
|
||||
# of 'driver_options'
|
||||
raise Exception(f"不支持的浏览器驱动类型: {self.__driver_type} !")
|
||||
self.__driver.implicitly_wait(1)
|
||||
self.__driver.execute_script(
|
||||
"Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
|
||||
)
|
||||
except Exception as e:
|
||||
self._showTrace(f"浏览器驱动初始化失败: {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
self._showTrace(f"浏览器驱动已初始化, 类型: {self.__driver_type}, 路径: {self.__driver_path}")
|
||||
return True
|
||||
|
||||
|
||||
def __initLibOperators(
|
||||
self
|
||||
):
|
||||
|
||||
if not self.__driver:
|
||||
self._showTrace(f"浏览器驱动未初始化, 请先初始化浏览器驱动 !", self.TraceLevel.WARNING)
|
||||
return
|
||||
self.__lib_checker = LibChecker(self._input_queue, self._output_queue, self.__driver)
|
||||
self.__lib_login = LibLogin(self._input_queue, self._output_queue, self.__driver)
|
||||
self.__lib_logout = LibLogout(self._input_queue, self._output_queue, self.__driver)
|
||||
self.__lib_reserve = LibReserve(self._input_queue, self._output_queue, self.__driver)
|
||||
self.__lib_checkin = LibCheckin(self._input_queue, self._output_queue, self.__driver)
|
||||
self.__lib_renew = LibRenew(self._input_queue, self._output_queue, self.__driver)
|
||||
|
||||
|
||||
def __waitResponseLoad(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
# wait for page load
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until( # title contains "首页"
|
||||
EC.title_contains("首页")
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until( # username field presence
|
||||
EC.presence_of_element_located((By.NAME, "username"))
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until( # password field presence
|
||||
EC.presence_of_element_located((By.NAME, "password"))
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until( # captcha field presence
|
||||
EC.presence_of_element_located((By.NAME, "answer"))
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until( # captcha image presence
|
||||
EC.presence_of_element_located((By.ID, "loadImgId"))
|
||||
)
|
||||
return True
|
||||
except:
|
||||
self._showTrace(f"登录页面加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
|
||||
def __initDriverUrl(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
lib_config = self.__run_config.get("library", None)
|
||||
if not lib_config:
|
||||
self._showTrace("未配置图书馆参数 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
url = lib_config.get("host_url") + lib_config.get("login_url")
|
||||
self.__driver.set_page_load_timeout(5)
|
||||
try:
|
||||
self.__driver.get(url)
|
||||
except TimeoutException:
|
||||
self.__driver.execute_script("window.stop();")
|
||||
self._showTrace(
|
||||
f"图书馆登录页面加载超时 ! 请检查网络环境是否正常", self.TraceLevel.ERROR
|
||||
)
|
||||
return False
|
||||
if not self.__waitResponseLoad():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def __run(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
login_config: dict,
|
||||
run_mode_config: dict,
|
||||
reserve_info: dict
|
||||
) -> int:
|
||||
|
||||
# result : -1 - terminate, 0 - success, 1 - failed, 2 - passed
|
||||
result = 2
|
||||
|
||||
# login
|
||||
if not self.__lib_login.login(
|
||||
username,
|
||||
password,
|
||||
login_config.get("max_attempt", 3),
|
||||
login_config.get("auto_captcha", True),
|
||||
):
|
||||
return 1
|
||||
# Here, we collect the run mode from the run config.
|
||||
run_mode = run_mode_config.get("run_mode", 0)
|
||||
run_mode = {
|
||||
"auto_reserve": run_mode&0x1,
|
||||
"auto_checkin": run_mode&0x2,
|
||||
"auto_renewal": run_mode&0x4,
|
||||
}
|
||||
# reserve
|
||||
if run_mode["auto_reserve"]:
|
||||
if self.__lib_checker.canReserve(reserve_info.get("date")):
|
||||
if self.__lib_reserve.reserve(username, reserve_info):
|
||||
result = 0
|
||||
else:
|
||||
result = 1
|
||||
else:
|
||||
self._showTrace(f"用户 {username} 无法预约, 已跳过")
|
||||
result = 2
|
||||
|
||||
# checkin
|
||||
last_result = result
|
||||
if run_mode["auto_checkin"] and last_result != 1:
|
||||
if self.__lib_checker.canCheckin():
|
||||
if self.__lib_checkin.checkin(username):
|
||||
result = 0
|
||||
else:
|
||||
result = 1
|
||||
else:
|
||||
self._showTrace(f"用户 {username} 无法签到, 已跳过")
|
||||
result = 2
|
||||
if last_result == 0: # partly success
|
||||
result = 0
|
||||
|
||||
# renewal
|
||||
last_result = result
|
||||
if run_mode["auto_renewal"] and last_result != 1:
|
||||
can_renew, record = self.__lib_checker.canRenew()
|
||||
if can_renew:
|
||||
if self.__lib_renew.renew(username, record, reserve_info):
|
||||
if self.__lib_checker.postRenewCheck(record):
|
||||
self._showTrace(f"用户 {username} 续约成功 !")
|
||||
result = 0
|
||||
else:
|
||||
if result != 1: # partly success
|
||||
result = 0
|
||||
else:
|
||||
result = 1
|
||||
else:
|
||||
result = 1
|
||||
else:
|
||||
self._showTrace(f"用户 {username} 无法续约, 已跳过")
|
||||
result = 2
|
||||
if last_result == 0: # partly success
|
||||
result = 0
|
||||
|
||||
# logout
|
||||
if not self.__lib_logout.logout(
|
||||
username
|
||||
):
|
||||
# if logout is failed, we must make sure the host to be reloaded
|
||||
# otherwise, the next login may fail
|
||||
if not self.__initDriverUrl():
|
||||
return -1
|
||||
return result
|
||||
|
||||
|
||||
def run(
|
||||
self,
|
||||
user_config: dict
|
||||
):
|
||||
|
||||
self.__user_config = user_config
|
||||
|
||||
user_counter = {"current": 0, "success": 0, "failed": 0, "passed": 0}
|
||||
users = self.__user_config["users"]
|
||||
self._showTrace(f"共发现 {len(users)} 个用户")
|
||||
for user in users:
|
||||
user_counter["current"] += 1
|
||||
self._showTrace(
|
||||
f"正在处理第 {user_counter["current"]}/{len(users)} 个用户: {user["username"]}......",
|
||||
no_log=True
|
||||
)
|
||||
if not user["enabled"]:
|
||||
self._showTrace(f"用户 {user["username"]} 已跳过")
|
||||
user_counter["passed"] += 1
|
||||
continue
|
||||
r = self.__run(
|
||||
username=user["username"],
|
||||
password=user["password"],
|
||||
login_config=self.__run_config["login"],
|
||||
run_mode_config=self.__run_config["mode"],
|
||||
reserve_info=user["reserve_info"],
|
||||
)
|
||||
if r == -1:
|
||||
self._showTrace(
|
||||
f"用户 {user["username"]} 处理过程中页面发生异常, 无法继续操作, 任务已终止 !",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
break
|
||||
elif r == 0:
|
||||
user_counter["success"] += 1
|
||||
elif r == 1:
|
||||
user_counter["failed"] += 1
|
||||
elif r == 2:
|
||||
user_counter["passed"] += 1
|
||||
self._showTrace(f"处理完成, 共计 {user_counter["current"]} 个用户, "\
|
||||
f"成功 {user_counter["success"]} 个用户, "\
|
||||
f"失败 {user_counter["failed"]} 个用户, "\
|
||||
f"跳过 {user_counter["passed"]} 个用户"
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
def close(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
if self.__driver:
|
||||
if self.__driver_type.lower() == "firefox":
|
||||
self._showTrace(
|
||||
f"Firefox 浏览器驱动关闭略慢, 请耐心等待...",
|
||||
no_log=True
|
||||
)
|
||||
self.__driver.quit()
|
||||
self.__driver = None
|
||||
self._showTrace(f"浏览器驱动已关闭")
|
||||
return True
|
||||
else:
|
||||
self._showTrace(f"浏览器驱动未初始化, 无需关闭", no_log=True)
|
||||
return False
|
||||
@@ -1,377 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
import queue
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
from base.LibOperator import LibOperator
|
||||
|
||||
|
||||
class LibChecker(LibOperator):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__driver = driver
|
||||
|
||||
|
||||
def _waitResponseLoad(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def __formatDiffTime(
|
||||
seconds: float
|
||||
) -> str:
|
||||
|
||||
hours = int(seconds//3600)
|
||||
minutes = int(seconds%3600//60)
|
||||
seconds = int(seconds%60)
|
||||
return f"{hours} 时 {minutes} 分 {seconds} 秒"
|
||||
|
||||
|
||||
def __navigateToReserveRecordPage(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable((By.XPATH, "//a[@href='/history?type=SEAT']"))
|
||||
).click()
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CLASS_NAME, "myReserveList"))
|
||||
)
|
||||
except:
|
||||
self._showTrace("加载预约记录页面失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def __decodeReserveTime(
|
||||
self,
|
||||
time_element
|
||||
) -> dict:
|
||||
|
||||
time_str = time_element.text.strip()
|
||||
today = datetime.now().date()
|
||||
if "明天" in time_str:
|
||||
target_date = today + timedelta(days=1)
|
||||
date = target_date.strftime("%Y-%m-%d")
|
||||
elif "今天" in time_str:
|
||||
target_date = today
|
||||
date = target_date.strftime("%Y-%m-%d")
|
||||
elif "昨天" in time_str:
|
||||
target_date = today - timedelta(days=1)
|
||||
date = target_date.strftime("%Y-%m-%d")
|
||||
else:
|
||||
date_match = re.search(r"(\d{4}-\d{1,2}-\d{1,2})", time_str)
|
||||
if date_match:
|
||||
date = date_match.group(1)
|
||||
else:
|
||||
date = ""
|
||||
time_match = re.search(r"(\d{1,2}:\d{2}) -- (\d{1,2}:\d{2})", time_str)
|
||||
if time_match:
|
||||
begin_time = time_match.group(1)
|
||||
end_time = time_match.group(2)
|
||||
else:
|
||||
begin_time = ""
|
||||
end_time = ""
|
||||
return {
|
||||
"date": date,
|
||||
"time": {
|
||||
"begin": begin_time,
|
||||
"end": end_time
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def __decodeReserveInfo(
|
||||
self,
|
||||
info_elements
|
||||
) -> str:
|
||||
|
||||
location = ""
|
||||
status = ""
|
||||
for info in info_elements:
|
||||
if "已预约" in info.text:
|
||||
status = "已预约"
|
||||
elif "使用中" in info.text:
|
||||
status = "使用中"
|
||||
elif "已完成" in info.text:
|
||||
status = "已完成"
|
||||
elif "已结束使用" in info.text:
|
||||
status = "已结束使用"
|
||||
elif "已取消" in info.text:
|
||||
status = "已取消"
|
||||
elif "失约" in info.text:
|
||||
status = "失约"
|
||||
elif "图书馆" in info.text:
|
||||
location = info.text.strip()
|
||||
return {
|
||||
"location": location,
|
||||
"status": status,
|
||||
}
|
||||
|
||||
|
||||
def __decodeReserveRecord(
|
||||
self,
|
||||
reservation
|
||||
) -> dict:
|
||||
|
||||
try:
|
||||
time_element = reservation.find_element(
|
||||
By.CSS_SELECTOR, "dt"
|
||||
)
|
||||
info_elements = reservation.find_elements(
|
||||
By.CSS_SELECTOR, "a"
|
||||
)
|
||||
except:
|
||||
return {
|
||||
"date": "",
|
||||
"time": {"begin": "", "end": ""},
|
||||
"info": {"location": "", "status": ""}
|
||||
}
|
||||
time = self.__decodeReserveTime(time_element)
|
||||
info = self.__decodeReserveInfo(info_elements)
|
||||
return {
|
||||
"date": time["date"],
|
||||
"time": time["time"],
|
||||
"info": info
|
||||
}
|
||||
|
||||
|
||||
def __loadReserveRecords(
|
||||
self
|
||||
) -> list:
|
||||
try:
|
||||
# check if there's any reservation on the date
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CSS_SELECTOR, ".myReserveList > dl"))
|
||||
)
|
||||
reservations = self.__driver.find_elements(
|
||||
By.CSS_SELECTOR, ".myReserveList > dl:not(#moreBlock)"
|
||||
)
|
||||
return reservations
|
||||
except:
|
||||
self._showTrace("加载预约记录失败 !", self.TraceLevel.ERROR)
|
||||
return None
|
||||
|
||||
|
||||
def __showMoreReserveRecords(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
# load new reservations if still not sure
|
||||
try:
|
||||
WebDriverWait(self.__driver, 0.1).until(
|
||||
EC.element_to_be_clickable((By.ID, "moreBtn"))
|
||||
)
|
||||
except:
|
||||
# the reservation is the last one
|
||||
return False
|
||||
try:
|
||||
more_btn = self.__driver.find_element(By.ID, "moreBtn")
|
||||
if more_btn.is_displayed() and more_btn.is_enabled():
|
||||
self.__driver.execute_script("arguments[0].scrollIntoView(true);", more_btn)
|
||||
self.__driver.execute_script("arguments[0].click();", more_btn)
|
||||
return True
|
||||
else:
|
||||
self._showTrace("用户无法加载更多预约记录", self.TraceLevel.WARNING)
|
||||
return False
|
||||
except:
|
||||
self._showTrace("加载更多预约记录失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
|
||||
def __getReserveRecord(
|
||||
self,
|
||||
wanted_date: str,
|
||||
wanted_status: str
|
||||
) -> dict:
|
||||
|
||||
if wanted_date is None:
|
||||
self._showTrace("日期未指定, 无法检查当前预约状态", self.TraceLevel.WARNING)
|
||||
return None
|
||||
self._showTrace(f"正在检查用户在 {wanted_date} 是否有预约状态为 {wanted_status} 的预约记录......", no_log=True)
|
||||
|
||||
checked_count = 0
|
||||
max_check_times = 6 # we only check (4*(6-1)=)20 reservations, the last time cant be checked
|
||||
|
||||
if not self.__navigateToReserveRecordPage():
|
||||
return None
|
||||
for _ in range(max_check_times):
|
||||
reservations = self.__loadReserveRecords()
|
||||
if reservations is None:
|
||||
return None
|
||||
for reservation in reservations[checked_count:]:
|
||||
record = self.__decodeReserveRecord(reservation)
|
||||
checked_count += 1
|
||||
if record is None:
|
||||
continue
|
||||
if record["date"] == "":
|
||||
continue
|
||||
if record["time"] == {"begin": "", "end": ""}:
|
||||
continue
|
||||
# record date is later than the given date, check the next one
|
||||
if datetime.strptime(record["date"], "%Y-%m-%d").date() >\
|
||||
datetime.strptime(wanted_date, "%Y-%m-%d").date():
|
||||
continue
|
||||
# record date is earlier than the given date, so there is no wanted record
|
||||
if datetime.strptime(record["date"], "%Y-%m-%d").date() <\
|
||||
datetime.strptime(wanted_date, "%Y-%m-%d").date():
|
||||
return None
|
||||
if record["info"]["status"] == wanted_status:
|
||||
self._showTrace(
|
||||
f"寻找到用户第 {checked_count} 条状态为 {wanted_status} 的预约记录, "
|
||||
f"详细信息: {record["date"]} "
|
||||
f"{record["time"]["begin"]} - {record["time"]["end"]} {record["info"]["location"]}",
|
||||
no_log=True
|
||||
)
|
||||
return record
|
||||
if not self.__showMoreReserveRecords():
|
||||
break
|
||||
return None
|
||||
|
||||
|
||||
def canReserve(
|
||||
self,
|
||||
date: str
|
||||
) -> bool:
|
||||
|
||||
# no reserved or using record in the given date
|
||||
# then can reserve
|
||||
if self.__getReserveRecord(date, "已预约") is None:
|
||||
if self.__getReserveRecord(date, "使用中") is None:
|
||||
self._showTrace(f"用户在 {date} 可以预约")
|
||||
return True
|
||||
self._showTrace(f"用户在 {date} 有使用中的预约, 无法预约")
|
||||
return False
|
||||
self._showTrace(f"用户在 {date} 已存在有效预约, 无法预约")
|
||||
return False
|
||||
|
||||
|
||||
def canCheckin(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
# only check the current date
|
||||
date = time.strftime("%Y-%m-%d", time.localtime())
|
||||
record = self.__getReserveRecord(date, "已预约")
|
||||
if record is not None:
|
||||
begin_time = record["time"]["begin"]
|
||||
begin_time = datetime.strptime(f"{date} {begin_time}", "%Y-%m-%d %H:%M")
|
||||
time_diff = datetime.now() - begin_time
|
||||
time_diff_seconds = time_diff.total_seconds()
|
||||
# before 30 minutes, cant checkin
|
||||
if time_diff_seconds < -30*60:
|
||||
self._showTrace(
|
||||
f"用户在 {date} 的预约开始时间为 {begin_time}, "
|
||||
f"当前距离预约开始时间还有 {self.__formatDiffTime(abs(time_diff_seconds))}, 无法签到"
|
||||
)
|
||||
return False
|
||||
# before in 30 minutes, can checkin
|
||||
elif -30*60 <= time_diff_seconds < 0:
|
||||
self._showTrace(
|
||||
f"用户在 {date} 的预约开始时间为 {begin_time}, "
|
||||
f"当前距离预约开始时间还有 {self.__formatDiffTime(abs(time_diff_seconds))}, 可以签到"
|
||||
)
|
||||
return True
|
||||
# past less than 30 minutes, can checkin
|
||||
elif 0 <= time_diff_seconds < 30*60 - 5: # spare 5 seconds for the checkin process
|
||||
self._showTrace(
|
||||
f"用户在 {date} 的预约开始时间为 {begin_time}, "
|
||||
f"当前距离预约开始时间已经过去 {self.__formatDiffTime(abs(time_diff_seconds))}, 可以签到"
|
||||
)
|
||||
return True
|
||||
self._showTrace(f"用户在 {date} 没有有效预约记录, 无法签到")
|
||||
return False
|
||||
|
||||
|
||||
def canRenew(
|
||||
self
|
||||
) -> tuple[bool, dict]:
|
||||
|
||||
# only check the current date
|
||||
date = time.strftime("%Y-%m-%d", time.localtime())
|
||||
record = self.__getReserveRecord(date, "使用中")
|
||||
if record is not None:
|
||||
end_time = record["time"]["end"]
|
||||
end_time = datetime.strptime(f"{date} {end_time}", "%Y-%m-%d %H:%M")
|
||||
time_diff = end_time - datetime.now()
|
||||
time_diff_seconds = time_diff.total_seconds()
|
||||
# a using record is definitely after the begin time
|
||||
trace_msg = (
|
||||
f"用户在 {date} 的预约结束时间为 {end_time}, "
|
||||
f"当前距离预约结束时间还有 {self.__formatDiffTime(abs(time_diff_seconds))}"
|
||||
)
|
||||
if abs(time_diff_seconds) < 120*60:
|
||||
self._showTrace(f"{trace_msg}, 可以续约")
|
||||
return True, record
|
||||
else:
|
||||
self._showTrace(f"{trace_msg}, 无法续约")
|
||||
return False, None # we do not need to return the record, because if current
|
||||
# time is not available for renewal, the record is not required
|
||||
self._showTrace(f"用户在 {date} 没有有效预约记录, 无法续约")
|
||||
return False, None
|
||||
|
||||
|
||||
def postRenewCheck(
|
||||
self,
|
||||
record: dict
|
||||
) -> bool:
|
||||
"""
|
||||
Check if the renew operation is successful
|
||||
|
||||
Args:
|
||||
record (dict): The expected record after renewal
|
||||
|
||||
Returns:
|
||||
bool: True if the renew operation is successful, False otherwise
|
||||
"""
|
||||
# because the special circumstance that the renew operation
|
||||
# do not show the success message or anything else,
|
||||
# we need to check the record data to make sure the renew operation is successful.
|
||||
|
||||
# only check the given record date
|
||||
date = record["date"]
|
||||
act_record = self.__getReserveRecord(date, "使用中")
|
||||
if act_record is not None:
|
||||
if act_record["time"]["begin"] == record["time"]["begin"] and\
|
||||
act_record["time"]["end"] == record["time"]["end"]:
|
||||
self._showTrace(f"\n"\
|
||||
f" 续约成功 !\n"\
|
||||
f" 日 期 :{date}\n"\
|
||||
f" 时 间 :{act_record["time"]["begin"]} - {act_record["time"]["end"]}\n"\
|
||||
f" 位 置 :{act_record["info"]["location"]}\n"
|
||||
f" 状 态 :{act_record["info"]["status"]}"
|
||||
)
|
||||
return True
|
||||
else:
|
||||
self._showTrace(f"\n"\
|
||||
f" 续约失败 !\n"\
|
||||
f" 续约后结束时间为 {act_record["time"]["end"]},与预期结束时间 {record["time"]["end"]} 不符 !"
|
||||
)
|
||||
return False
|
||||
self._showTrace(f"用户在 {date} 没有有效预约记录, 无法检查续约结果")
|
||||
return False
|
||||
@@ -1,142 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import time
|
||||
import queue
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
from base.LibOperator import LibOperator
|
||||
|
||||
|
||||
class LibCheckin(LibOperator):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__driver = driver
|
||||
|
||||
|
||||
def _waitResponseLoad(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CLASS_NAME, "ui_dialog"))
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CLASS_NAME, "resultMessage"))
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable((By.CLASS_NAME, "btnOK"))
|
||||
)
|
||||
result_message_element = self.__driver.find_element(
|
||||
By.CLASS_NAME, "resultMessage"
|
||||
)
|
||||
ok_btn = self.__driver.find_element(By.CLASS_NAME, "btnOK")
|
||||
except:
|
||||
self._showTrace("签到时发生未知错误 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
result_message = result_message_element.text
|
||||
if "签到成功" in result_message:
|
||||
try:
|
||||
detail_elements = self.__driver.find_elements(
|
||||
By.CSS_SELECTOR, ".resultMessage dd"
|
||||
)
|
||||
except:
|
||||
pass
|
||||
if detail_elements:
|
||||
details = [element.text for element in detail_elements if element.text.strip()]
|
||||
if len(details) >= 5:
|
||||
self._showTrace(f"\n"\
|
||||
f" 签到成功 !\n"\
|
||||
f" {details[1]}\n"\
|
||||
f" {details[2]}\n"\
|
||||
f" {details[3]}\n"\
|
||||
f" {details[4]}"
|
||||
)
|
||||
else:
|
||||
self._showTrace(f"\n"\
|
||||
" 签到成功 !\n"\
|
||||
" 未获取到签到详情 !"
|
||||
)
|
||||
ok_btn.click()
|
||||
return True
|
||||
else:
|
||||
failure_reason = result_message.replace("签到失败", "").strip()
|
||||
self._showTrace(f"\n"\
|
||||
" 签到失败 !\n"\
|
||||
f" {failure_reason}"
|
||||
)
|
||||
ok_btn.click()
|
||||
return False
|
||||
|
||||
|
||||
def __enableCheckinBtn(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
script = """
|
||||
try {
|
||||
var checkin_btn = document.getElementById('btnCheckIn');
|
||||
if (checkin_btn) {
|
||||
checkin_btn.classList.remove('disabled');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
"""
|
||||
result = self.__driver.execute_script(script)
|
||||
time.sleep(0.1)
|
||||
if result:
|
||||
self._showTrace("签到按钮已启用", no_log=True)
|
||||
else:
|
||||
self._showTrace("签到按钮启用失败", self.TraceLevel.WARNING)
|
||||
return result
|
||||
|
||||
|
||||
def checkin(
|
||||
self,
|
||||
username: str
|
||||
) -> bool:
|
||||
|
||||
if self.__driver is None:
|
||||
self._showTrace("未提供有效 WebDriver 实例 !", self.TraceLevel.WARNING)
|
||||
return False
|
||||
try:
|
||||
checkin_btn = WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable((By.ID, "btnCheckIn"))
|
||||
)
|
||||
except:
|
||||
self._showTrace(f"用户 {username} 签到界面加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
if "disabled" in checkin_btn.get_attribute("class"):
|
||||
self._showTrace("签到按钮不可用, 可能不在场馆内, 正在尝试启用......", no_log=True)
|
||||
if not self.__enableCheckinBtn():
|
||||
self._showTrace(f"签到按钮启用失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
checkin_btn.click()
|
||||
if self._waitResponseLoad():
|
||||
self._showTrace(f"用户 {username} 签到成功 !", no_log=True)
|
||||
return True
|
||||
else:
|
||||
self._showTrace(f"用户 {username} 签到失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
@@ -1,41 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
import queue
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
from base.LibOperator import LibOperator
|
||||
|
||||
|
||||
class LibCheckout(LibOperator):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__driver = driver
|
||||
|
||||
|
||||
def _waitResponseLoad(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
pass
|
||||
@@ -1,215 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import queue
|
||||
import base64
|
||||
|
||||
import ddddocr
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
from base.LibOperator import LibOperator
|
||||
|
||||
|
||||
class LibLogin(LibOperator):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__driver = driver
|
||||
self.__ddddocr = ddddocr.DdddOcr()
|
||||
|
||||
|
||||
def _waitResponseLoad(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
# wait to verify login success
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until( # title contains "自选座位 :: 座位预约系统"
|
||||
EC.title_contains("自选座位 :: 座位预约系统")
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until( # search button presence
|
||||
EC.presence_of_element_located((By.ID, "search"))
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until( # select content presence
|
||||
EC.presence_of_element_located((By.CLASS_NAME, "selectContent"))
|
||||
)
|
||||
return True
|
||||
except:
|
||||
self._showTrace(
|
||||
f"登录页面加载失败 ! : 用户账号或者密码错误/验证码错误, 具体以页面提示为准",
|
||||
self.TraceLevel.ERROR
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def __fillLogInElements(
|
||||
self,
|
||||
username: str,
|
||||
password: str
|
||||
) -> bool:
|
||||
|
||||
# ensure elements presence and fill them
|
||||
try:
|
||||
username_element = self.__driver.find_element(By.NAME, "username")
|
||||
username_element.clear()
|
||||
username_element.send_keys(username)
|
||||
password_element = self.__driver.find_element(By.NAME, "password")
|
||||
password_element.clear()
|
||||
password_element.send_keys(password)
|
||||
except Exception as e:
|
||||
self._showTrace(f"用户名或密码填写失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def __autoRecognizeCaptcha(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
# auto recognize captcha
|
||||
try:
|
||||
captcha_img = self.__driver.find_element(By.ID, "loadImgId")
|
||||
img_src = captcha_img.get_attribute("src")
|
||||
base64_str = img_src.split(',', 1)[1]
|
||||
captcha_img = base64.b64decode(base64_str)
|
||||
captcha_text = self.__ddddocr.classification(captcha_img)
|
||||
captcha_text = ''.join(filter(str.isalnum, captcha_text)).lower()
|
||||
self._showTrace(f"识别到验证码为 : '{captcha_text}'", no_log=True)
|
||||
if len(captcha_text) != 4:
|
||||
self._showLog("识别到的验证码长度不等于 4 个字符 !", self.TraceLevel.WARNING)
|
||||
raise Exception("识别到的验证码长度不等于 4 个字符 !")
|
||||
return captcha_text
|
||||
except Exception as e:
|
||||
self._showTrace(f"验证码识别失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return ""
|
||||
|
||||
|
||||
def __manualRecognizeCaptcha(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
# manual recognize captcha
|
||||
try:
|
||||
self._showMsg("请输入验证码:")
|
||||
captcha_text = self._waitMsg(timeout=15)
|
||||
self._showTrace(f"输入的验证码为 : '{captcha_text}'", no_log=True)
|
||||
if len(captcha_text) != 4:
|
||||
self._showLog("输入的验证码长度不等于 4 个字符 !", self.TraceLevel.WARNING)
|
||||
raise Exception("输入的验证码长度不等于 4 个字符 !")
|
||||
return captcha_text
|
||||
except Exception as e:
|
||||
self._showTrace(f"输入验证码失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return ""
|
||||
|
||||
|
||||
def __refreshCaptcha(
|
||||
self
|
||||
):
|
||||
|
||||
# refresh captcha
|
||||
try:
|
||||
self._showTrace("刷新验证码......", no_log=True)
|
||||
self.__driver.find_element(
|
||||
By.ID, "loadImgId"
|
||||
).click()
|
||||
return True
|
||||
except Exception as e:
|
||||
self._showTrace(f"刷新验证码失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
|
||||
def __solveCaptcha(
|
||||
self,
|
||||
auto_captcha: bool = True
|
||||
) -> str:
|
||||
|
||||
max_attempts = 3 # the possibility of 3 times failed is less than (10%^3)
|
||||
for _ in range(max_attempts):
|
||||
if auto_captcha:
|
||||
captcha_text = self.__autoRecognizeCaptcha()
|
||||
else:
|
||||
self._showTrace(f"用户未配置自动识别验证码, 请手动输入验证码 !", no_log=True)
|
||||
captcha_text = self.__manualRecognizeCaptcha()
|
||||
if captcha_text:
|
||||
return captcha_text
|
||||
else:
|
||||
if not self.__refreshCaptcha():
|
||||
return ""
|
||||
self._showTrace(
|
||||
f"验证码识别失败 {max_attempts} 次, 达到最大尝试次数 !",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
return ""
|
||||
|
||||
|
||||
def __fillCaptchaElement(
|
||||
self,
|
||||
captcha_text: str
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
captcha_element = self.__driver.find_element(By.NAME, "answer")
|
||||
captcha_element.clear()
|
||||
captcha_element.send_keys(captcha_text)
|
||||
return True
|
||||
except Exception as e:
|
||||
self._showTrace(f"验证码填写失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
|
||||
def login(
|
||||
self,
|
||||
username: str,
|
||||
password: str,
|
||||
max_attempts: int = 5,
|
||||
auto_captcha: bool = True
|
||||
) -> bool:
|
||||
|
||||
if self.__driver is None:
|
||||
self._showTrace("未提供有效 WebDriver 实例 !", self.TraceLevel.WARNING)
|
||||
return False
|
||||
# begin login process
|
||||
for attempt in range(max_attempts):
|
||||
self._showTrace(f"用户 {username} 第 {attempt + 1} 次尝试登录......", no_log=True)
|
||||
if not self.__fillLogInElements(
|
||||
username,
|
||||
password,
|
||||
):
|
||||
continue
|
||||
captcha_text = self.__solveCaptcha(auto_captcha)
|
||||
if not captcha_text:
|
||||
continue
|
||||
if not self.__fillCaptchaElement(captcha_text):
|
||||
continue
|
||||
self._showTrace("尝试登录...", no_log=True)
|
||||
try:
|
||||
self.__driver.find_element(
|
||||
By.XPATH,
|
||||
"//input[@type='button' and @value='登录']"
|
||||
).click()
|
||||
except Exception as e:
|
||||
self._showTrace(f"尝试登录失败 ! : {e}")
|
||||
continue
|
||||
if self._waitResponseLoad():
|
||||
self._showTrace(f"用户 {username} 第 {attempt + 1} 次登录成功 !")
|
||||
return True
|
||||
else:
|
||||
self._showTrace(f"用户 {username} 第 {attempt + 1} 次登录失败 !",self.TraceLevel.WARNING)
|
||||
return False
|
||||
@@ -1,55 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import queue
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
|
||||
from base.LibOperator import LibOperator
|
||||
|
||||
|
||||
class LibLogout(LibOperator):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__driver = driver
|
||||
|
||||
|
||||
def _waitResponseLoad(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def logout(
|
||||
self,
|
||||
username: str
|
||||
) -> bool:
|
||||
|
||||
if self.__driver is None:
|
||||
self._showTrace("未提供有效 WebDriver 实例 !", self.TraceLevel.WARNING)
|
||||
return False
|
||||
try:
|
||||
self.__driver.find_element(
|
||||
By.XPATH, "//a[@href='/logout']"
|
||||
).click()
|
||||
self._showTrace(f"用户 {username} 注销成功 !")
|
||||
return True
|
||||
except Exception as e:
|
||||
self._showTrace(f"用户 {username} 注销失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
@@ -1,205 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import queue
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
from base.LibTimeSelector import LibTimeSelector
|
||||
|
||||
|
||||
class LibRenew(LibTimeSelector):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__driver = driver
|
||||
|
||||
|
||||
def _waitResponseLoad(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
self.__driver.refresh()
|
||||
return True
|
||||
|
||||
|
||||
def __waitRenewDialog(
|
||||
self
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.visibility_of_element_located((By.ID, "extendDiv"))
|
||||
)
|
||||
head_message = WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CSS_SELECTOR, "#extendDiv p.messageHead"))
|
||||
)
|
||||
result_message = WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CSS_SELECTOR, "#extendDiv div.resultMessage"))
|
||||
)
|
||||
except:
|
||||
self._showTrace("续约时间选择界面加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
head_message = head_message.text.strip()
|
||||
if "警告" in head_message:
|
||||
result_message = result_message.text.strip()
|
||||
self._showTrace(f"\n"\
|
||||
f" 续约失败 !\n"\
|
||||
f" {result_message}", no_log=True)
|
||||
return False
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_all_elements_located(
|
||||
(By.CSS_SELECTOR, "#extendDiv .renewal_List li")
|
||||
)
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CSS_SELECTOR, "#extendDiv .btnOK"))
|
||||
)
|
||||
except:
|
||||
self._showTrace("续约时间选择界面加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def __selectNearestTime(
|
||||
self,
|
||||
record: dict,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
Select the nearest available renewal time.
|
||||
"""
|
||||
end_time = record["time"]["end"]
|
||||
renew_info = reserve_info["renew_time"]
|
||||
max_diff = renew_info["max_diff"]
|
||||
prefer_earlier = renew_info["prefer_early"]
|
||||
target_renew_mins = self._timeStrToMins(end_time) + renew_info["expect_duration"]*60
|
||||
|
||||
# Validate and adjust target renew time to library closing time
|
||||
if not self.__validateAndAdjustRenewTime(end_time, target_renew_mins):
|
||||
return False
|
||||
renew_ok_btn = self.__driver.find_element(By.CSS_SELECTOR, "#extendDiv .btnOK")
|
||||
renew_time_opts = self.__driver.find_elements(By.CSS_SELECTOR, "#extendDiv .renewal_List li")
|
||||
if not renew_time_opts:
|
||||
self._showTrace("当前未查询到可用续约时间 !", self.TraceLevel.WARNING)
|
||||
return False
|
||||
|
||||
# Find best renewal time option
|
||||
best_opt, best_text, actual_diff, free_times = self._findBestTimeOption(
|
||||
renew_time_opts, target_renew_mins, max_diff, prefer_earlier, is_reserve=False
|
||||
)
|
||||
if best_opt is not None:
|
||||
return self.__confirmRenewal(best_opt, best_text, actual_diff, record, renew_ok_btn)
|
||||
self._showTrace(
|
||||
"无法选择最近的可用续约时间 ! "
|
||||
f"所有可选时间与目标时间相差都超过了 {max_diff} 分钟 !",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
self._showTrace(f"当前可供续约的时间有: {free_times}")
|
||||
return False
|
||||
|
||||
|
||||
def __validateAndAdjustRenewTime(
|
||||
self,
|
||||
end_time: str,
|
||||
target_renew_mins: int
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
Validate and adjust renewal time to library closing time if needed.
|
||||
"""
|
||||
LIBRARY_CLOSE_TIME = 1410 # 23:30 in minutes
|
||||
if target_renew_mins > LIBRARY_CLOSE_TIME:
|
||||
actual_renew_duration = LIBRARY_CLOSE_TIME - self._timeStrToMins(end_time)
|
||||
if actual_renew_duration <= 0:
|
||||
self._showTrace(f"当前结束时间 {end_time} 已接近闭馆时间,无法续约 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
self._showTrace(
|
||||
f"续约时间已调整至闭馆时间 {self._minsToTimeStr(LIBRARY_CLOSE_TIME)},"
|
||||
f"实际续约时长为 {actual_renew_duration//60} 小时 {actual_renew_duration%60} 分钟"
|
||||
)
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def __confirmRenewal(
|
||||
self,
|
||||
best_opt,
|
||||
best_text: str,
|
||||
actual_diff: int,
|
||||
record: dict,
|
||||
ok_btn
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
Confirm the selected renewal time.
|
||||
"""
|
||||
try:
|
||||
best_opt.click()
|
||||
abs_diff = abs(actual_diff)
|
||||
time_relation = self._formatTimeRelation(abs_diff, actual_diff, "续约时间")
|
||||
self._showTrace(
|
||||
f"选择距离期望续约时间最近的 {best_text}, "
|
||||
f"与期望续约时间相比 {time_relation}"
|
||||
)
|
||||
record["time"]["end"] = best_text.strip()
|
||||
ok_btn.click()
|
||||
return True
|
||||
except:
|
||||
self._showTrace("确认续约时发生错误 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
|
||||
def renew(
|
||||
self,
|
||||
username: str,
|
||||
record: dict,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
if self.__driver is None:
|
||||
self._showTrace("未提供有效 WebDriver 实例 !", self.TraceLevel.WARNING)
|
||||
return False
|
||||
try:
|
||||
renew_btn = WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable((By.ID, "btnExtend"))
|
||||
)
|
||||
except:
|
||||
self._showTrace(f"用户 {username} 续约界面加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
if "disabled" in renew_btn.get_attribute("class"):
|
||||
self._showLog(f"用户 {username} 续约按钮不可用, 可能不在场馆内")
|
||||
self._showTrace(f"用户 {username} 续约按钮不可用, 可能不在场馆内, 请连接图书馆网络后重试", no_log=True)
|
||||
return False
|
||||
renew_btn.click()
|
||||
if not self.__waitRenewDialog():
|
||||
self._showTrace(f"用户 {username} 续约失败 !", self.TraceLevel.ERROR)
|
||||
|
||||
# After the renewal, the webpage will display a mask overlay,
|
||||
# so we need to refresh the page for subsequent operations.
|
||||
self.__driver.refresh()
|
||||
return False
|
||||
if not self.__selectNearestTime(record, reserve_info):
|
||||
self._showTrace(f"用户 {username} 续约失败 !", self.TraceLevel.ERROR)
|
||||
self.__driver.refresh()
|
||||
return False
|
||||
if self._waitResponseLoad():
|
||||
return True
|
||||
@@ -1,693 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2025 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import time
|
||||
import queue
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.chrome.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
from base.LibTimeSelector import LibTimeSelector
|
||||
|
||||
|
||||
class LibReserve(LibTimeSelector):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: WebDriver
|
||||
):
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
self.__driver = driver
|
||||
# library floor and room mapping in website
|
||||
self.__floor_map = {
|
||||
"2": "二层",
|
||||
"3": "三层",
|
||||
"4": "四层",
|
||||
"5": "五层"
|
||||
}
|
||||
self.__room_map = {
|
||||
"1": "二层内环",
|
||||
"2": "二层西区",
|
||||
"3": "三层内环",
|
||||
"4": "三层外环",
|
||||
"5": "四层内环",
|
||||
"6": "四层外环",
|
||||
"7": "四层期刊",
|
||||
"8": "五层考研"
|
||||
}
|
||||
|
||||
|
||||
def _waitResponseLoad(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CLASS_NAME, "layoutSeat"))
|
||||
)
|
||||
title_elements = []
|
||||
# reserve failed without title elements, so we need to try
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.CSS_SELECTOR, ".layoutSeat dt"))
|
||||
)
|
||||
title_elements = self.__driver.find_elements(
|
||||
By.CSS_SELECTOR, ".layoutSeat dt"
|
||||
)
|
||||
except:
|
||||
pass
|
||||
content_elements = self.__driver.find_elements(
|
||||
By.CSS_SELECTOR, ".layoutSeat dd"
|
||||
)
|
||||
if not content_elements:
|
||||
self._showTrace("未找到预约结果", self.TraceLevel.WARNING)
|
||||
raise
|
||||
title = title_elements[0].text if title_elements else ""
|
||||
contents = [element.text for element in content_elements if element.text.strip()]
|
||||
for message in contents:
|
||||
if "预约失败" in message or "已有1个有效预约" in message:
|
||||
self._showTrace(f"预约失败 - {"".join(contents)}", self.TraceLevel.ERROR)
|
||||
raise
|
||||
if "预定好了" in title or "预约成功" in title or "操作成功" in title:
|
||||
if len(contents) >= 6:
|
||||
self._showTrace(f"\n"\
|
||||
f" 预约成功 !\n"\
|
||||
f" {contents[1]}\n"\
|
||||
f" {contents[2]}\n"\
|
||||
f" {contents[3]}\n"\
|
||||
f" 签到时间 :{contents[5]}"
|
||||
)
|
||||
else:
|
||||
self._showTrace("\n"\
|
||||
" 预约成功 !\n"\
|
||||
" 未找获取到详细信息"
|
||||
)
|
||||
return True
|
||||
except:
|
||||
self._showTrace(f"预约结果加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
|
||||
def __containRequiredInfo(
|
||||
self,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
# must contain the required infomation
|
||||
# key 'place' is no need to check
|
||||
# because 'place' is only has one possible value '1' or '图书馆'
|
||||
if reserve_info.get("floor") is None: # if existence ?
|
||||
raise ValueError("未指定楼层")
|
||||
if reserve_info["floor"] not in self.__floor_map: # if in the mao ?
|
||||
raise ValueError(f"该楼层 '{reserve_info['floor']}' 不存在")
|
||||
if reserve_info.get("room") is None:
|
||||
raise ValueError("未指定房间")
|
||||
if reserve_info["room"] not in self.__room_map:
|
||||
raise ValueError(f"该房间 '{reserve_info['room']}' 不存在")
|
||||
if reserve_info.get("seat_id") is None:
|
||||
raise ValueError("未指定座位")
|
||||
if reserve_info["seat_id"] == "":
|
||||
raise ValueError("未指定座位号")
|
||||
return True
|
||||
except ValueError as e:
|
||||
self._showTrace(
|
||||
f"预约信息错误 ! : {e}, "\
|
||||
f"由于缺少必要的预约信息, 无法开始预约流程",
|
||||
self.TraceLevel.ERROR
|
||||
)
|
||||
self._showTrace(
|
||||
f"预约信息错误 ! : {e}, "\
|
||||
f"由于缺少必要的预约信息, 无法开始预约流程, 请检查预约信息是否完整",
|
||||
no_log=True
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def __isValidDate(
|
||||
self,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
cur_date_str = time.strftime("%Y-%m-%d", time.localtime())
|
||||
cur_timestamp = time.mktime(time.strptime(cur_date_str, "%Y-%m-%d"))
|
||||
if reserve_info.get("date") is None:
|
||||
reserve_info["date"] = cur_date_str
|
||||
self._showTrace(f"预约日期未指定, 自动设置为当前日期: {cur_date_str}")
|
||||
else:
|
||||
res_timestamp = time.mktime(time.strptime(reserve_info["date"], "%Y-%m-%d"))
|
||||
if res_timestamp < cur_timestamp:
|
||||
self._showTrace(
|
||||
f"预约日期错误 ! :"\
|
||||
f"{reserve_info['date']} 早于当前日期 {cur_date_str}, 自动设置为当前日期",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
reserve_info["date"] = cur_date_str
|
||||
return True
|
||||
|
||||
|
||||
def __isValidBeginTime(
|
||||
self,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
cur_time = time.strftime("%H:%M", time.localtime())
|
||||
if reserve_info.get("begin_time") is None:
|
||||
reserve_info["begin_time"] = {}
|
||||
if "time" not in reserve_info["begin_time"]:
|
||||
reserve_info["begin_time"]["time"] = cur_time
|
||||
self._showTrace(f"开始时间未指定, 自动设置为当前时间: {cur_time}")
|
||||
if "max_diff" not in reserve_info["begin_time"]:
|
||||
reserve_info["begin_time"]["max_diff"] = 30
|
||||
self._showTrace(f"开始时间最大时间差未指定, 自动设置为 30 分钟")
|
||||
if "prefer_early" not in reserve_info["begin_time"]:
|
||||
reserve_info["begin_time"]["prefer_early"] = True
|
||||
self._showTrace(f"是否优先选择更早开始时间未指定, 自动设置为 True")
|
||||
return True
|
||||
|
||||
|
||||
def __isValidExpectDuration(
|
||||
self,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
if reserve_info.get("satisfy_duration") is None:
|
||||
reserve_info["satisfy_duration"] = True
|
||||
self._showTrace("预约满足时长要求未指定, 默认满足")
|
||||
if reserve_info["satisfy_duration"]:
|
||||
if reserve_info.get("expect_duration") is None:
|
||||
reserve_info["expect_duration"] = 4
|
||||
self._showTrace("需要满足预约持续时间, 但未指定, 使用默认时长为 4 小时")
|
||||
return True
|
||||
|
||||
|
||||
def __isValidEndTime(
|
||||
self,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
if reserve_info.get("end_time") is None:
|
||||
reserve_info["end_time"] = {}
|
||||
if "time" not in reserve_info["end_time"]:
|
||||
# here we add the expect duration to the begin time first,
|
||||
# the edge case that the end time is later than 23:30 will
|
||||
# be handled in __finalCheck. so no need to concern about it.
|
||||
end_mins = self._timeStrToMins(reserve_info["begin_time"]["time"])
|
||||
end_mins = end_mins + int(reserve_info["expect_duration"]*60)
|
||||
reserve_info["end_time"] = {
|
||||
"time": self._minsToTimeStr(end_mins),
|
||||
"max_diff": 30,
|
||||
"prefer_early": False
|
||||
}
|
||||
self._showTrace(
|
||||
f"结束时间未指定, 自动设置为开始时间加上期望时长: {reserve_info['end_time']['time']}"
|
||||
)
|
||||
if "max_diff" not in reserve_info["end_time"]:
|
||||
reserve_info["end_time"]["max_diff"] = 30
|
||||
self._showTrace(f"结束时间最大时间差未指定, 自动设置为 30 分钟")
|
||||
if "prefer_early" not in reserve_info["end_time"]:
|
||||
reserve_info["end_time"]["prefer_early"] = False
|
||||
self._showTrace(f"是否优先选择较晚结束时间未指定, 自动设置为 True")
|
||||
return True
|
||||
|
||||
|
||||
def __finalCheck(
|
||||
self,
|
||||
reserve_info: dict
|
||||
):
|
||||
|
||||
begin_time, end_time = reserve_info["begin_time"], reserve_info["end_time"]
|
||||
begin_mins = self._timeStrToMins(begin_time["time"])
|
||||
end_mins = self._timeStrToMins(end_time["time"])
|
||||
|
||||
# if end time is earlier than begin_time, exchange them
|
||||
# except that the user has set the satisfy_duration to True
|
||||
if end_mins < begin_mins and reserve_info["satisfy_duration"] is False:
|
||||
self._showTrace(
|
||||
f"结束时间 {end_time['time']} 早于开始时间 {begin_time['time']}, 尝试交换时间",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
reserve_info["end_time"], reserve_info["begin_time"] = begin_time, end_time
|
||||
begin_time, end_time = end_time, begin_time
|
||||
begin_mins = self._timeStrToMins(begin_time["time"])
|
||||
end_mins = self._timeStrToMins(end_time["time"])
|
||||
|
||||
# ensure the end time is not later than 23:30
|
||||
max_end_mins = self._timeStrToMins("23:30")
|
||||
if end_mins > max_end_mins:
|
||||
self._showTrace(
|
||||
f"结束时间 {end_time['time']} 晚于 23:30, 自动设置为 23:30",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
reserve_info["end_time"]["time"] = "23:30"
|
||||
end_mins = max_end_mins
|
||||
|
||||
# ensure the duration is not longer than 8 hours
|
||||
if reserve_info["satisfy_duration"]:
|
||||
if reserve_info["expect_duration"] > 8:
|
||||
self._showTrace(
|
||||
f"该用户设置了优先满足时长要求, 但是预约期望持续时间 "
|
||||
f"{reserve_info['expect_duration']} 小时 "
|
||||
f"超出最大时长 8 小时, 自动设置为 8 小时",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
reserve_info["expect_duration"] = 8
|
||||
else:
|
||||
if end_mins - begin_mins > 8*60:
|
||||
self._showTrace(
|
||||
f"该用户未设置优先满足时长要求, 但是检查到预约持续时间 "
|
||||
f"{float((end_mins - begin_mins)/60)} 小时 "
|
||||
f"超出最大时长 8 小时, 自动设置为 8 小时",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
reserve_info["end_time"]["time"] = self._minsToTimeStr(begin_mins + 8*60)
|
||||
return True
|
||||
|
||||
|
||||
def __checkReserveInfo(
|
||||
self,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
if not self.__containRequiredInfo(reserve_info):
|
||||
return False
|
||||
if not self.__isValidDate(reserve_info):
|
||||
return False
|
||||
if not self.__isValidBeginTime(reserve_info):
|
||||
return False
|
||||
if not self.__isValidExpectDuration(reserve_info):
|
||||
return False
|
||||
if not self.__isValidEndTime(reserve_info):
|
||||
return False
|
||||
if not self.__finalCheck(reserve_info):
|
||||
return False
|
||||
self._showTrace(
|
||||
f"预约信息检查完成, 准备预约 "
|
||||
f"{reserve_info['date']} "
|
||||
f"{reserve_info['begin_time']['time']} - "
|
||||
f"{reserve_info['end_time']['time']} "
|
||||
f"图书馆 "
|
||||
f"{self.__floor_map[reserve_info['floor']]} "
|
||||
f"{self.__room_map[reserve_info['room']]} "
|
||||
f"的座位 {reserve_info['seat_id']}"
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def __clickElement(
|
||||
self,
|
||||
trigger_locator: tuple,
|
||||
fail_msg: str,
|
||||
success_msg: str,
|
||||
option_locator: tuple = None
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
# click the trigger element
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable(trigger_locator)
|
||||
).click()
|
||||
if option_locator:
|
||||
# select the option element if specified
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable(option_locator)
|
||||
).click()
|
||||
self._showTrace(success_msg)
|
||||
return True
|
||||
except:
|
||||
self._showTrace(fail_msg)
|
||||
return False
|
||||
|
||||
|
||||
def __clickElementByJS(
|
||||
self,
|
||||
trigger_locator_id: str,
|
||||
option_query_selector: str,
|
||||
fail_msg: str,
|
||||
success_msg: str,
|
||||
) -> bool:
|
||||
|
||||
script = f"""
|
||||
try {{
|
||||
var trigger = document.getElementById('{trigger_locator_id}');
|
||||
if (trigger) {{
|
||||
trigger.click();
|
||||
var option = document.querySelector("{option_query_selector}");
|
||||
if (option) {{
|
||||
option.click();
|
||||
return true;
|
||||
}}
|
||||
return false;
|
||||
}}
|
||||
return false;
|
||||
}} catch (e) {{
|
||||
return false;
|
||||
}}
|
||||
"""
|
||||
result = self.__driver.execute_script(script)
|
||||
time.sleep(0.1)
|
||||
if result:
|
||||
self._showTrace(success_msg)
|
||||
else:
|
||||
self._showTrace(fail_msg)
|
||||
return result
|
||||
|
||||
|
||||
def __selectDate(
|
||||
self,
|
||||
date_str: str
|
||||
) -> bool:
|
||||
|
||||
if self.__clickElementByJS(
|
||||
trigger_locator_id="onDate_select",
|
||||
option_query_selector=f"p#options_onDate a[value='{date_str}']",
|
||||
success_msg=f"日期 {date_str} 选择成功 !",
|
||||
fail_msg=f"选择日期失败 ! : {date_str} 不可用"
|
||||
):
|
||||
return True
|
||||
return self.__clickElement(
|
||||
trigger_locator=(By.ID, "onDate_select"),
|
||||
option_locator=(By.XPATH, f"//p[@id='options_onDate']/a[@value='{date_str}']"),
|
||||
success_msg=f"日期 {date_str} 选择成功 !",
|
||||
fail_msg=f"选择日期失败 ! : {date_str} 不可用"
|
||||
)
|
||||
|
||||
|
||||
def __selectPlace(
|
||||
self,
|
||||
place: str
|
||||
) -> bool:
|
||||
|
||||
place = "1" # the library only have this place :)
|
||||
display_place = "图书馆"
|
||||
if self.__clickElementByJS(
|
||||
trigger_locator_id="display_building",
|
||||
option_query_selector=f"p#options_building a[value='{place}']",
|
||||
success_msg=f"预约场所 {display_place} 选择成功 !",
|
||||
fail_msg=f"选择预约场所失败 ! : {display_place} 不可用"
|
||||
):
|
||||
return True
|
||||
return self.__clickElement(
|
||||
trigger_locator=(By.ID, "display_building"),
|
||||
option_locator=(By.XPATH, f"//p[@id='options_building']/a[@value='{place}']"),
|
||||
success_msg=f"预约场所 {display_place} 选择成功 !",
|
||||
fail_msg=f"选择预约场所失败 ! : {display_place} 不可用"
|
||||
)
|
||||
|
||||
|
||||
def __selectFloor(
|
||||
self,
|
||||
floor: str
|
||||
) -> bool:
|
||||
|
||||
display_floor = self.__floor_map.get(floor)
|
||||
if self.__clickElementByJS(
|
||||
trigger_locator_id="floor_select",
|
||||
option_query_selector=f"p#options_floor a[value='{floor}']",
|
||||
success_msg=f"楼层 {display_floor} 选择成功 !",
|
||||
fail_msg=f"选择楼层失败 ! : {display_floor} 不可用"
|
||||
):
|
||||
return True
|
||||
return self.__clickElement(
|
||||
trigger_locator=(By.ID, "floor_select"),
|
||||
option_locator=(By.XPATH, f"//p[@id='options_floor']/a[@value='{floor}']"),
|
||||
success_msg=f"楼层 {display_floor} 选择成功 !",
|
||||
fail_msg=f"选择楼层失败 ! : {display_floor} 不可用"
|
||||
)
|
||||
|
||||
|
||||
def __selectRoom(
|
||||
self,
|
||||
room: str
|
||||
) -> bool:
|
||||
|
||||
display_room = self.__room_map.get(room)
|
||||
# find room
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable((By.ID, "findRoom"))
|
||||
).click()
|
||||
except:
|
||||
self._showTrace("加载房间/区域失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
# select room
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable((By.ID, f"room_{room}"))
|
||||
).click()
|
||||
self._showTrace(f"房间 {display_room} 选择成功 !")
|
||||
return True
|
||||
except:
|
||||
self._showTrace(f"选择房间失败 ! : {display_room} 不可用", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
|
||||
def __selectSeat(
|
||||
self,
|
||||
seat_id: str
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
# wait fot seat layout element to load
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.ID, "seatLayout"))
|
||||
)
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_all_elements_located((By.CSS_SELECTOR, "li[id^='seat_']"))
|
||||
)
|
||||
except:
|
||||
self._showTrace(f"座位加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
try:
|
||||
all_seats = self.__driver.find_elements(
|
||||
By.CSS_SELECTOR, "li[id^='seat_']"
|
||||
)
|
||||
seat_id_upper = seat_id.lstrip('0').upper()
|
||||
for seat in all_seats:
|
||||
if not seat_id_upper == seat.text.lstrip('0'):
|
||||
continue
|
||||
seat_link = seat.find_element(By.TAG_NAME, "a")
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable(seat_link)
|
||||
)
|
||||
seat_link.click()
|
||||
seat_status = seat_link.get_attribute("title")
|
||||
self._showTrace(f"座位 {seat_id} 选择成功 ! : 当前状态 - '{seat_status}'")
|
||||
return True
|
||||
self._showLog(f"座位 {seat_id} 在该楼层区域中不存在", self.TraceLevel.WARNING)
|
||||
self._showTrace(f"座位 {seat_id} 在该楼层区域中不存在, 请检查座位号是否正确", no_log=True)
|
||||
except:
|
||||
self._showTrace(f"座位选择失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
|
||||
def __selectNearestTime(
|
||||
self,
|
||||
time_id: str,
|
||||
time_type: str,
|
||||
target_time: int,
|
||||
max_time_diff: int = 30,
|
||||
prefer_earlier: bool = True
|
||||
) -> int:
|
||||
|
||||
"""
|
||||
Select the nearest available time option.
|
||||
|
||||
Returns:
|
||||
int: The actual selected time value in minutes.
|
||||
"""
|
||||
# Wait for time options to load
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_all_elements_located(
|
||||
(By.CSS_SELECTOR, f"#{time_id} ul li a")
|
||||
)
|
||||
)
|
||||
except:
|
||||
self._showTrace(f"{time_type} 选择失败 ! : 当前未查询到可用时间", self.TraceLevel.ERROR)
|
||||
return -1
|
||||
|
||||
# Find best time option
|
||||
all_time_opts = self.__driver.find_elements(
|
||||
By.CSS_SELECTOR,
|
||||
f"#{time_id} ul li a"
|
||||
)
|
||||
if not all_time_opts:
|
||||
self._showTrace(f"{time_type} 选择失败 ! : 当前未查询到可用时间", self.TraceLevel.ERROR)
|
||||
return -1
|
||||
best_opt, best_text, actual_diff, free_times = self._findBestTimeOption(
|
||||
all_time_opts, target_time, max_time_diff, prefer_earlier, is_reserve=True
|
||||
)
|
||||
if best_opt is not None:
|
||||
best_opt.click()
|
||||
abs_diff = abs(actual_diff)
|
||||
time_relation = self._formatTimeRelation(abs_diff, actual_diff, time_type)
|
||||
target_time += actual_diff
|
||||
self._showTrace(
|
||||
f"选择距离期望 {time_type} 最近的 {best_text}, "
|
||||
f"与期望 {time_type} 相比 {time_relation}"
|
||||
)
|
||||
return target_time
|
||||
self._showTrace(
|
||||
f"无法选择最近的 {time_type} {self._minsToTimeStr(target_time)}, "
|
||||
f"所有可选时间与目标时间相差都超过 {max_time_diff} 分钟", self.TraceLevel.WARNING
|
||||
)
|
||||
self._showTrace(f"当前可供预约的 {time_type} 有: {free_times}")
|
||||
return -1
|
||||
|
||||
|
||||
def __selectSeatTime(
|
||||
self,
|
||||
begin_time: dict,
|
||||
end_time: dict,
|
||||
expect_duration: int = 4,
|
||||
satisfy_duration: bool = True
|
||||
) -> bool:
|
||||
|
||||
"""
|
||||
Select seat begin and end time.
|
||||
"""
|
||||
exp_beg_tm_str = begin_time["time"]
|
||||
exp_end_tm_str = end_time["time"]
|
||||
# Initialize actual time strings for logging
|
||||
act_beg_tm_str = exp_beg_tm_str
|
||||
act_end_tm_str = exp_end_tm_str
|
||||
exp_beg_mins = self._timeStrToMins(exp_beg_tm_str)
|
||||
act_beg_mins = exp_beg_mins
|
||||
exp_end_mins = self._timeStrToMins(exp_end_tm_str)
|
||||
act_end_mins = exp_end_mins
|
||||
|
||||
# Select begin time
|
||||
act_beg_mins = self.__selectNearestTime(
|
||||
time_id="startTime",
|
||||
time_type="开始时间",
|
||||
target_time=exp_beg_mins,
|
||||
max_time_diff=begin_time["max_diff"],
|
||||
prefer_earlier=begin_time["prefer_early"]
|
||||
)
|
||||
if act_beg_mins == -1:
|
||||
return False
|
||||
act_beg_tm_str = self._minsToTimeStr(act_beg_mins)
|
||||
|
||||
# If 'satisfy_duration' is True, select end time based on actual begin time
|
||||
if satisfy_duration:
|
||||
exp_end_mins = int(self.validateAndAdjustEndTime(act_beg_mins, expect_duration))
|
||||
exp_end_tm_str = self._minsToTimeStr(exp_end_mins)
|
||||
self._showTrace(
|
||||
f"需要满足期望预约持续时间: {expect_duration} 小时, "
|
||||
f"根据开始时间 {act_beg_tm_str} 计算结束时间: {exp_end_tm_str}"
|
||||
)
|
||||
|
||||
# Select end time
|
||||
act_end_mins = self.__selectNearestTime(
|
||||
time_id="endTime",
|
||||
time_type="结束时间",
|
||||
target_time=exp_end_mins,
|
||||
max_time_diff=end_time["max_diff"],
|
||||
prefer_earlier=end_time["prefer_early"]
|
||||
)
|
||||
if act_end_mins == -1:
|
||||
return False
|
||||
act_end_tm_str = self._minsToTimeStr(act_end_mins)
|
||||
self._showTrace(
|
||||
f"期望预约时间段: {exp_beg_tm_str} - {exp_end_tm_str}, "
|
||||
f"实际预约时间段: {act_beg_tm_str} - {act_end_tm_str}"
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def validateAndAdjustEndTime(
|
||||
self,
|
||||
begin_mins: int,
|
||||
duration: int
|
||||
) -> int:
|
||||
|
||||
"""
|
||||
Validate and adjust reserve end time to library closing time if needed.
|
||||
"""
|
||||
LIBRARY_CLOSE_TIME = self._timeStrToMins("23:30")
|
||||
expect_end_mins = int(begin_mins + duration*60)
|
||||
if expect_end_mins > LIBRARY_CLOSE_TIME:
|
||||
expect_end_mins = LIBRARY_CLOSE_TIME
|
||||
self._showTrace(
|
||||
f"预约持续时间 {duration} 小时, 超过最大预约时间 23:30, 自动调整为 23:30",
|
||||
self.TraceLevel.WARNING
|
||||
)
|
||||
return expect_end_mins
|
||||
|
||||
|
||||
def reserve(
|
||||
self,
|
||||
username: str,
|
||||
reserve_info: dict
|
||||
) -> bool:
|
||||
|
||||
submit_reserve = False
|
||||
reserve_success = False
|
||||
have_hover_on_page = False
|
||||
|
||||
# reserve info
|
||||
if not self.__checkReserveInfo(reserve_info):
|
||||
return False
|
||||
# map page
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable((By.XPATH, "//a[@href='/map']"))
|
||||
).click()
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.presence_of_element_located((By.ID, "seatLayout"))
|
||||
)
|
||||
except:
|
||||
self._showTrace(f"加载预约选座页面失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
# date, place, floor, room
|
||||
if not self.__selectDate(reserve_info["date"]):
|
||||
return False
|
||||
if not self.__selectPlace(reserve_info["place"]):
|
||||
return False
|
||||
if not self.__selectFloor(reserve_info["floor"]):
|
||||
return False
|
||||
if not self.__selectRoom(reserve_info["room"]):
|
||||
return False
|
||||
else:
|
||||
have_hover_on_page = True
|
||||
# seat selections
|
||||
if not self.__selectSeat(reserve_info["seat_id"]):
|
||||
pass
|
||||
elif not self.__selectSeatTime(
|
||||
begin_time=reserve_info["begin_time"],
|
||||
end_time=reserve_info["end_time"],
|
||||
expect_duration=reserve_info["expect_duration"],
|
||||
satisfy_duration=reserve_info["satisfy_duration"]
|
||||
):
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
WebDriverWait(self.__driver, 2).until(
|
||||
EC.element_to_be_clickable((By.ID, "reserveBtn"))
|
||||
).click()
|
||||
submit_reserve = True
|
||||
if not self._waitResponseLoad():
|
||||
raise
|
||||
reserve_success = True
|
||||
except:
|
||||
self._showTrace(f"预约提交失败 !", self.TraceLevel.ERROR)
|
||||
if not submit_reserve and have_hover_on_page:
|
||||
self.__driver.refresh()
|
||||
if reserve_success:
|
||||
self._showTrace(f"用户 {username} 预约成功 !")
|
||||
else:
|
||||
self._showTrace(f"用户 {username} 预约失败 !", self.TraceLevel.ERROR)
|
||||
return reserve_success
|
||||
@@ -1,13 +0,0 @@
|
||||
"""
|
||||
Operators module for the AutoLibrary project.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- AutoLib: AutoLibrary operator.
|
||||
- LibLogin: Library operator for logging in.
|
||||
- LibLogout: Library operator for logging out.
|
||||
- LibReserve: Library operator for reserving seat.
|
||||
- LibCheckin: Library operator for checking in seat.
|
||||
- LibCheckout: Library operator for checking out seat.
|
||||
- LibChecker: Library operator for checking record status.
|
||||
- LibRenew: Library operator for renewing seat.
|
||||
"""
|
||||