Compare commits
| 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 |
No files matched your search
@@ -7,7 +7,6 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
|
||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
@@ -15,7 +14,6 @@ on:
|
|||||||
- opened
|
- opened
|
||||||
- synchronize
|
- synchronize
|
||||||
- reopened
|
- reopened
|
||||||
# Allow manual trigger for testing
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
#
|
#
|
||||||
@@ -49,11 +47,13 @@ jobs:
|
|||||||
uses: actions/setup-python@v6
|
uses: actions/setup-python@v6
|
||||||
with:
|
with:
|
||||||
python-version: '3.13'
|
python-version: '3.13'
|
||||||
|
cache: 'pip'
|
||||||
|
cache-dependency-path: requirements.txt
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip
|
python -m pip install --upgrade pip
|
||||||
pip install -r requirement.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
- name: Solve ddddocr compatibility and copy model files
|
- name: Solve ddddocr compatibility and copy model files
|
||||||
run: |
|
run: |
|
||||||
@@ -125,7 +125,7 @@ jobs:
|
|||||||
" binaries=[],"
|
" binaries=[],"
|
||||||
" datas=["
|
" datas=["
|
||||||
" ('models\\common.onnx', 'ddddocr'),"
|
" ('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=[],"
|
" hiddenimports=[],"
|
||||||
" hookspath=[],"
|
" hookspath=[],"
|
||||||
@@ -153,7 +153,7 @@ jobs:
|
|||||||
" target_arch=None,"
|
" target_arch=None,"
|
||||||
" codesign_identity=None,"
|
" codesign_identity=None,"
|
||||||
" entitlements_file=None,"
|
" entitlements_file=None,"
|
||||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_32x32.ico'],"
|
" icon=['src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico'],"
|
||||||
")"
|
")"
|
||||||
""
|
""
|
||||||
"coll = COLLECT("
|
"coll = COLLECT("
|
||||||
@@ -169,9 +169,11 @@ jobs:
|
|||||||
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
||||||
|
|
||||||
Write-Host "✓ Main.spec (non-single file) generated successfully"
|
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
|
Get-Content "Main.spec" | Write-Host
|
||||||
Write-Host "==================================`n"
|
Write-Host "========================================`n"
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
|
|
||||||
- name: Build with PyInstaller
|
- name: Build with PyInstaller
|
||||||
@@ -186,7 +188,7 @@ jobs:
|
|||||||
$distDir = "dist/AutoLibrary-$version"
|
$distDir = "dist/AutoLibrary-$version"
|
||||||
$zipName = "AutoLibrary.$tagName-windows-x86_64.zip"
|
$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"
|
Write-Host "Looking for distribution directory: $distDir"
|
||||||
if (Test-Path $distDir) {
|
if (Test-Path $distDir) {
|
||||||
@@ -210,12 +212,283 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload build summary
|
- name: Upload build summary
|
||||||
run: |
|
run: |
|
||||||
Write-Host "## Build Test Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
"## Build Test Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||||
Write-Host "" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
"" | 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
|
"========================================" | 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
|
"✓ Pull request build test completed successfully!" | 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
|
"- Version: ${{ steps.get_version.outputs.VERSION }}" | 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
|
"- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | 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
|
"- Pull Request #${{ github.event.pull_request.number || 'N/A' }}" | 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
|
"- 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
|
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
|
name: Build
|
||||||
|
|
||||||
# This workflow compiles the application for Windows platform using PyInstaller, and
|
# This workflow compiles the application for Windows and macOS platforms using
|
||||||
# archives the built artifacts as 'AutoLibrary.<tag_name>-windows-x86_64.zip'.
|
# 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.
|
# It is triggered when called by the release workflow.
|
||||||
|
|
||||||
@@ -76,20 +79,22 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
$versionInfoFile = "src/gui/ALVersionInfo.py"
|
$versionInfoFile = "src/gui/ALVersionInfo.py"
|
||||||
Write-Host "Verifying $versionInfoFile content:"
|
Write-Host "Verifying $versionInfoFile content:"
|
||||||
Write-Host "=================================="
|
Write-Host "========================================"
|
||||||
Get-Content $versionInfoFile | Write-Host
|
Get-Content $versionInfoFile | Write-Host
|
||||||
Write-Host "=================================="
|
Write-Host "========================================"
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
|
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@v6
|
uses: actions/setup-python@v6
|
||||||
with:
|
with:
|
||||||
python-version: '3.13'
|
python-version: '3.13'
|
||||||
|
cache: 'pip'
|
||||||
|
cache-dependency-path: requirements.txt
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip
|
python -m pip install --upgrade pip
|
||||||
pip install -r requirement.txt
|
pip install -r requirements.txt
|
||||||
|
|
||||||
- name: Solve ddddocr compatibility and copy model files
|
- name: Solve ddddocr compatibility and copy model files
|
||||||
run: |
|
run: |
|
||||||
@@ -161,7 +166,7 @@ jobs:
|
|||||||
" binaries=[],"
|
" binaries=[],"
|
||||||
" datas=["
|
" datas=["
|
||||||
" ('models\\common.onnx', 'ddddocr'),"
|
" ('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=[],"
|
" hiddenimports=[],"
|
||||||
" hookspath=[],"
|
" hookspath=[],"
|
||||||
@@ -189,7 +194,7 @@ jobs:
|
|||||||
" target_arch=None,"
|
" target_arch=None,"
|
||||||
" codesign_identity=None,"
|
" codesign_identity=None,"
|
||||||
" entitlements_file=None,"
|
" entitlements_file=None,"
|
||||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_32x32.ico'],"
|
" icon=['src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico'],"
|
||||||
")"
|
")"
|
||||||
""
|
""
|
||||||
"coll = COLLECT("
|
"coll = COLLECT("
|
||||||
@@ -205,9 +210,11 @@ jobs:
|
|||||||
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
||||||
|
|
||||||
Write-Host "✓ Main.spec (non-single file) generated successfully"
|
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
|
Get-Content "Main.spec" | Write-Host
|
||||||
Write-Host "==================================`n"
|
Write-Host "========================================`n"
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
|
|
||||||
- name: Build with PyInstaller
|
- name: Build with PyInstaller
|
||||||
@@ -222,7 +229,7 @@ jobs:
|
|||||||
$distDir = "dist/AutoLibrary-$version"
|
$distDir = "dist/AutoLibrary-$version"
|
||||||
$zipName = "AutoLibrary.$tagName-windows-x86_64.zip"
|
$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"
|
Write-Host "Looking for distribution directory: $distDir"
|
||||||
if (Test-Path $distDir) {
|
if (Test-Path $distDir) {
|
||||||
@@ -242,16 +249,315 @@ jobs:
|
|||||||
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-windows-x86_64
|
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-windows-x86_64
|
||||||
path: |
|
path: |
|
||||||
${{ steps.zip_release.outputs.ZIP_NAME }}
|
${{ 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
|
- name: Upload build summary
|
||||||
if: ${{ github.event_name != 'workflow_call' }}
|
if: ${{ inputs.is_test == 'true' }}
|
||||||
run: |
|
run: |
|
||||||
Write-Host "## Build Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
"## Build Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||||
Write-Host "" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
"" | 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
|
"========================================" | 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
|
"✓ Build test completed successfully!" | 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
|
"- Version: ${{ steps.get_version.outputs.VERSION }}" | 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
|
"- Tag: ${{ steps.get_version.outputs.TAG_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
|
"- 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
|
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 "✓ File replaced: $FILE_PATH"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Updated file content ==================="
|
echo "========================================"
|
||||||
|
echo "Updated file content"
|
||||||
|
echo "========================================"
|
||||||
cat "$FILE_PATH"
|
cat "$FILE_PATH"
|
||||||
echo "========================================"
|
echo "========================================"
|
||||||
|
|
||||||
@@ -151,3 +153,9 @@ jobs:
|
|||||||
COMMIT_SHA=$(git rev-parse --short HEAD)
|
COMMIT_SHA=$(git rev-parse --short HEAD)
|
||||||
echo "commit_sha=$COMMIT_SHA" >> $GITHUB_OUTPUT
|
echo "commit_sha=$COMMIT_SHA" >> $GITHUB_OUTPUT
|
||||||
echo "✓ New commit SHA: $COMMIT_SHA"
|
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.
|
# Commits version changes to release branch and creates the release tag.
|
||||||
|
|
||||||
# 4. Build:
|
# 4. Build:
|
||||||
# Compiles the application for Windows platform using PyInstaller, and
|
# Compiles the application for Windows and macOS platforms using PyInstaller, and
|
||||||
# archives the built artifacts as 'AutoLibrary.<tag_name>-windows-x86_64.zip'.
|
# archives the built artifacts.
|
||||||
|
# - Windows: AutoLibrary.<tag_name>-windows-x86_64.zip
|
||||||
|
# - macOS: AutoLibrary.<tag_name>-macos-arm64.dmg
|
||||||
|
|
||||||
# 5. Release:
|
# 5. Release:
|
||||||
# Creates GitHub release with generated artifacts and release notes
|
# Creates GitHub release with generated artifacts and release notes
|
||||||
@@ -47,7 +49,7 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
#
|
#
|
||||||
# Start :
|
# Start :
|
||||||
# virtual job that indacates the start of the release process
|
# virtual job that indicates the start of the release process
|
||||||
#
|
#
|
||||||
|
|
||||||
start:
|
start:
|
||||||
@@ -158,7 +160,7 @@ jobs:
|
|||||||
needs:
|
needs:
|
||||||
- update-version
|
- update-version
|
||||||
- commit-release
|
- 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
|
uses: ./.github/workflows/build.yml
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -181,12 +183,18 @@ jobs:
|
|||||||
contents: write
|
contents: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Download artifacts
|
- name: Download Windows artifacts
|
||||||
uses: actions/download-artifact@v6
|
uses: actions/download-artifact@v6
|
||||||
with:
|
with:
|
||||||
name: AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-windows-x86_64
|
name: AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-windows-x86_64
|
||||||
path: artifacts/
|
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
|
- name: Create release
|
||||||
id: create_release
|
id: create_release
|
||||||
uses: softprops/action-gh-release@v2
|
uses: softprops/action-gh-release@v2
|
||||||
@@ -195,6 +203,7 @@ jobs:
|
|||||||
name: AutoLibrary ${{ needs.extract-version.outputs.tag_name }}
|
name: AutoLibrary ${{ needs.extract-version.outputs.tag_name }}
|
||||||
files: |
|
files: |
|
||||||
artifacts/AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-windows-x86_64.zip
|
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
|
draft: false
|
||||||
prerelease: ${{ needs.extract-version.outputs.is_rc == 'true' }}
|
prerelease: ${{ needs.extract-version.outputs.is_rc == 'true' }}
|
||||||
generate_release_notes: true
|
generate_release_notes: true
|
||||||
@@ -205,7 +214,7 @@ jobs:
|
|||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|
||||||
# End :
|
# End :
|
||||||
# virtual job that indacates the end of the release process
|
# virtual job that indicates the end of the release process
|
||||||
#
|
#
|
||||||
|
|
||||||
end:
|
end:
|
||||||
@@ -227,7 +236,7 @@ jobs:
|
|||||||
- release
|
- release
|
||||||
- extract-version
|
- extract-version
|
||||||
- commit-release
|
- 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
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -267,9 +276,13 @@ jobs:
|
|||||||
git checkout ${MAIN_BRANCH}
|
git checkout ${MAIN_BRANCH}
|
||||||
|
|
||||||
# Show branch status before merge
|
# Show branch status before merge
|
||||||
echo "=== Branch status before merge ==="
|
echo "========================================"
|
||||||
|
echo "Branch status before merge"
|
||||||
|
echo "========================================"
|
||||||
git log --oneline --graph --all -5
|
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"
|
git diff ${MAIN_BRANCH} origin/${BRANCH_NAME} --stat || echo "No differences found"
|
||||||
|
|
||||||
# Force create a merge commit even if there are no changes
|
# 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]"
|
-m "chore(release): merge ${BRANCH_NAME} to ${MAIN_BRANCH} [auto release commit]"
|
||||||
|
|
||||||
# Show merge result
|
# Show merge result
|
||||||
echo "=== Merge result ==="
|
echo "========================================"
|
||||||
|
echo "Merge result"
|
||||||
|
echo "========================================"
|
||||||
git log --oneline --graph -3
|
git log --oneline --graph -3
|
||||||
|
|
||||||
# Push to main
|
# Push to main
|
||||||
@@ -310,6 +325,7 @@ jobs:
|
|||||||
|
|
||||||
echo "## Release Cleanup Summary" >> $GITHUB_STEP_SUMMARY
|
echo "## Release Cleanup Summary" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "" >> $GITHUB_STEP_SUMMARY
|
echo "" >> $GITHUB_STEP_SUMMARY
|
||||||
|
echo "========================================" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "✓ Release completed successfully!" >> $GITHUB_STEP_SUMMARY
|
echo "✓ Release completed successfully!" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "" >> $GITHUB_STEP_SUMMARY
|
echo "" >> $GITHUB_STEP_SUMMARY
|
||||||
echo "### Actions Performed:" >> $GITHUB_STEP_SUMMARY
|
echo "### Actions Performed:" >> $GITHUB_STEP_SUMMARY
|
||||||
|
|||||||
@@ -128,10 +128,15 @@ jobs:
|
|||||||
echo "Build version file location: $VER_INFO_BUILDFILE"
|
echo "Build version file location: $VER_INFO_BUILDFILE"
|
||||||
echo "Commit version file location: $VER_INFO_COMMITFILE"
|
echo "Commit version file location: $VER_INFO_COMMITFILE"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Build version ALVersionInfo.py content ="
|
echo "========================================"
|
||||||
|
echo "Build version ALVersionInfo.py"
|
||||||
|
echo "========================================"
|
||||||
cat "$VER_INFO_BUILDFILE"
|
cat "$VER_INFO_BUILDFILE"
|
||||||
|
echo "========================================"
|
||||||
echo ""
|
echo ""
|
||||||
echo "Commit version ALVersionInfo.py content "
|
echo "========================================"
|
||||||
|
echo "Commit version ALVersionInfo.py"
|
||||||
|
echo "========================================"
|
||||||
cat "$VER_INFO_COMMITFILE"
|
cat "$VER_INFO_COMMITFILE"
|
||||||
echo "========================================"
|
echo "========================================"
|
||||||
|
|
||||||
@@ -140,11 +145,16 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
if git diff --quiet src/gui/ALVersionInfo.py; then
|
if git diff --quiet src/gui/ALVersionInfo.py; then
|
||||||
echo "has_changes=false" >> $GITHUB_OUTPUT
|
echo "has_changes=false" >> $GITHUB_OUTPUT
|
||||||
echo "! No changes detected in ALVersionInfo.py"
|
echo "⚠ No changes detected in ALVersionInfo.py"
|
||||||
else
|
else
|
||||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||||
echo "✓ ALVersionInfo.py has been modified"
|
echo "✓ ALVersionInfo.py has been modified"
|
||||||
fi
|
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
|
- name: Upload modified ALVersionInfo.py ready for build
|
||||||
if: steps.check_changes.outputs.has_changes == 'true'
|
if: steps.check_changes.outputs.has_changes == 'true'
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
# AutoLibrary
|
# AutoLibrary
|
||||||
---
|
---
|
||||||
|
|
||||||

|

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

|

|
||||||
@@ -17,15 +17,24 @@
|
|||||||
|
|
||||||
### 功能
|
### 功能
|
||||||
|
|
||||||
|
#### 核心特性
|
||||||
|
|
||||||
1. 自动预约 - 支持自动预约
|
1. 自动预约 - 支持自动预约
|
||||||
2. 自动续约 - 支持自动续约
|
2. 自动续约 - 支持自动续约
|
||||||
3. 自动签到 - 支持自动签到
|
3. 自动签到 - 支持自动签到
|
||||||
4. 远程签到 - 支持远程签到,无需在图书馆网络环境下即可签到
|
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 版本 (推荐,过低或高版本会导致兼容问题)。
|
1. 确保系统安装了 Python 3.13 版本 (推荐,过低或高版本会导致兼容问题)。
|
||||||
2. 安装所有依赖库,命令为 `pip install -r requirements.txt` (建议在虚拟环境下操作)。
|
2. 安装所有依赖库,命令为 `pip install -r requirements.txt` (建议在虚拟环境下操作)。
|
||||||
@@ -71,7 +80,7 @@ def classification(self, img: bytes):
|
|||||||
只要确保处于校园网网络环境内,工具都是可以正常运行的。操作处理速度基本上取决于校园网的网络环境,一般情况下在 3-4 秒(不考虑硬件差异)左右即可完成一个用户的操作,完全满足正常使用需求。
|
只要确保处于校园网网络环境内,工具都是可以正常运行的。操作处理速度基本上取决于校园网的网络环境,一般情况下在 3-4 秒(不考虑硬件差异)左右即可完成一个用户的操作,完全满足正常使用需求。
|
||||||
|
|
||||||
> [!NOTE]
|
> [!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 到本项目。
|
如果你有其他功能建议,或者遇到了什么功能性,操作上的问题,欢迎提交 [Issue](https://github.com/KenanZhu/AutoLibrary/issues) 到本项目。
|
||||||
如果你有足够的开发能力,欢迎为本项目提交 PR,也可以 Fork 本项目,根据自己的需求进行修改和完善。
|
如果你有足够的开发能力,欢迎为本项目提交 [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)
|
app = QApplication(sys.argv)
|
||||||
translator = QTranslator()
|
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.installTranslator(translator)
|
||||||
app.setStyle('Fusion')
|
|
||||||
app.setApplicationName("AutoLibrary")
|
app.setApplicationName("AutoLibrary")
|
||||||
if not initializeApp():
|
if not initializeApp():
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
|
|||||||
@@ -7,593 +7,256 @@ 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.
|
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||||
See the LICENSE file for details.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
import re
|
|
||||||
from datetime import (
|
from datetime import (
|
||||||
datetime,
|
|
||||||
timedelta,
|
|
||||||
date,
|
date,
|
||||||
time
|
datetime,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .ASObject import (
|
from lupa import LuaRuntime as _LuaRuntime
|
||||||
ASObject,
|
|
||||||
_META_VARS,
|
from autoscript._helpers import (
|
||||||
_inferType
|
_TYPE_DEFAULT_VAR,
|
||||||
)
|
_assignPath,
|
||||||
from .ASOperator import ASOperator
|
_checkDateFormat,
|
||||||
from .ASTokenizer import (
|
_checkTimeFormat,
|
||||||
ASTokenizer,
|
_checkType,
|
||||||
NodeVisitor,
|
_cleanLuaError,
|
||||||
Script,
|
_navigatePath,
|
||||||
IfNode,
|
|
||||||
SetNode,
|
|
||||||
OpNode,
|
|
||||||
PassNode,
|
|
||||||
UnrecogNode
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
__all__ = ["execute", "addTargetVar", "splitTopLevel"]
|
from lupa.lua55 import LuaError as _LuaError, LuaSyntaxError as _LuaSyntaxError
|
||||||
|
except ImportError:
|
||||||
|
|
||||||
# Engine state
|
|
||||||
# User-registered target variables (bound to target_data paths)
|
|
||||||
_TARGET_VARS = {}
|
|
||||||
# Free-form script variables (not bound to target_data)
|
|
||||||
_SCRIPT_VARS = {}
|
|
||||||
# Name -> ASObject lookup map built from _META_VARS, _TARGET_VARS, and display names
|
|
||||||
_FIELD_MAP = {}
|
|
||||||
|
|
||||||
|
|
||||||
def _errPos(
|
|
||||||
line: int,
|
|
||||||
message: str
|
|
||||||
) -> str:
|
|
||||||
"""
|
|
||||||
Format an error message with a script line number.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
line (int): The script line number where the error occurred.
|
|
||||||
message (str): The error description.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: A formatted error string like "AutoScript syntax error(line X): message".
|
|
||||||
"""
|
|
||||||
return f"AutoScript 语法错误(第{line}行): {message}"
|
|
||||||
|
|
||||||
|
|
||||||
# Pre-compiled regex patterns for value resolution
|
|
||||||
_RE_TIME = re.compile(r"^TIME\((\d{1,2}):(\d{2})\)$", re.IGNORECASE)
|
|
||||||
_RE_DATE = re.compile(r"^DATE\((\d{4})-(\d{2})-(\d{2})\)$", re.IGNORECASE)
|
|
||||||
_RE_CUR_DATE_OFFSET = re.compile(r"^CURRENT_DATE\s*\+\s*(\d+)$", re.IGNORECASE)
|
|
||||||
_RE_CUR_TIME_OFFSET = re.compile(r"^CURRENT_TIME\s*\+\s*(\d+)$", re.IGNORECASE)
|
|
||||||
|
|
||||||
|
|
||||||
def splitTopLevel(
|
|
||||||
text: str,
|
|
||||||
delimiter: str
|
|
||||||
) -> list:
|
|
||||||
"""
|
|
||||||
Split a condition expression by a delimiter (.AND. / .OR.), respecting parentheses.
|
|
||||||
|
|
||||||
Only splits at the top nesting level; delimiters inside parentheses are ignored.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
text (str): The condition expression to split.
|
|
||||||
delimiter (str): The delimiter string, e.g. ".OR." or ".AND.".
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
list: A list of sub-expression strings (stripped of leading/trailing whitespace).
|
|
||||||
"""
|
|
||||||
|
|
||||||
parts = []
|
|
||||||
depth = 0
|
|
||||||
buf = ""
|
|
||||||
i = 0
|
|
||||||
text_upper = text.upper()
|
|
||||||
delim_upper = delimiter.upper()
|
|
||||||
dlen = len(delim_upper)
|
|
||||||
while i < len(text):
|
|
||||||
if text[i] == "(":
|
|
||||||
depth += 1
|
|
||||||
buf += text[i]
|
|
||||||
elif text[i] == ")":
|
|
||||||
depth -= 1
|
|
||||||
buf += text[i]
|
|
||||||
elif depth == 0 and text_upper[i:i + dlen] == delim_upper:
|
|
||||||
parts.append(buf)
|
|
||||||
buf = ""
|
|
||||||
i += dlen
|
|
||||||
continue
|
|
||||||
else:
|
|
||||||
buf += text[i]
|
|
||||||
i += 1
|
|
||||||
if buf.strip():
|
|
||||||
parts.append(buf)
|
|
||||||
return parts
|
|
||||||
|
|
||||||
|
|
||||||
def _buildFieldMap():
|
|
||||||
"""
|
|
||||||
Rebuild the _FIELD_MAP lookup from _META_VARS and _TARGET_VARS.
|
|
||||||
|
|
||||||
Each variable is registered under both its canonical name (uppercased)
|
|
||||||
and its display_name (if present), so that scripts can refer to either.
|
|
||||||
"""
|
|
||||||
|
|
||||||
_FIELD_MAP.clear()
|
|
||||||
for ch_name, obj in _META_VARS.items():
|
|
||||||
_FIELD_MAP[obj.name.upper()] = obj
|
|
||||||
_FIELD_MAP[ch_name.upper().strip()] = obj
|
|
||||||
for obj in _TARGET_VARS.values():
|
|
||||||
_FIELD_MAP[obj.name.upper()] = obj
|
|
||||||
if obj.display_name:
|
|
||||||
_FIELD_MAP[obj.display_name.upper().strip()] = obj
|
|
||||||
|
|
||||||
|
|
||||||
def _resolveFieldObj(
|
|
||||||
field_name: str
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Resolve a field name to its ASObject by looking up _FIELD_MAP then _SCRIPT_VARS.
|
|
||||||
|
|
||||||
Unlike getting a raw value, this returns the ASObject instance itself,
|
|
||||||
preserving type information for operations and comparisons.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
field_name (str): The field name (case-insensitive).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
ASObject or None: The resolved ASObject, or None if not found.
|
|
||||||
"""
|
|
||||||
|
|
||||||
upper_name = field_name.upper().strip()
|
|
||||||
obj = _FIELD_MAP.get(upper_name)
|
|
||||||
if obj:
|
|
||||||
return obj
|
|
||||||
obj = _SCRIPT_VARS.get(upper_name)
|
|
||||||
if obj:
|
|
||||||
return obj
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _resolveValue(
|
|
||||||
value_str: str,
|
|
||||||
target_data: dict
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Parse and resolve a value string from a script into a Python object.
|
|
||||||
|
|
||||||
Supports the following literal forms:
|
|
||||||
- TIME(hh:mm)
|
|
||||||
- DATE(yyyy-mm-dd)
|
|
||||||
- .TRUE. / .FALSE.
|
|
||||||
- Single/double quoted strings (with escaped single quotes)
|
|
||||||
- CURRENT_DATE + N / CURRENT_TIME + N (relative offsets)
|
|
||||||
- Numeric literals (int / float)
|
|
||||||
- Field references (resolved via _resolveFieldObj)
|
|
||||||
|
|
||||||
Args:
|
|
||||||
value_str (str): The raw value string from the script.
|
|
||||||
target_data (dict): The application data dict.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
The resolved Python value.
|
|
||||||
"""
|
|
||||||
|
|
||||||
s = value_str.strip()
|
|
||||||
m = _RE_TIME.match(s)
|
|
||||||
if m:
|
|
||||||
return time(int(m.group(1)), int(m.group(2)))
|
|
||||||
m = _RE_DATE.match(s)
|
|
||||||
if m:
|
|
||||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
|
||||||
up = s.upper()
|
|
||||||
if up == ".TRUE.":
|
|
||||||
return True
|
|
||||||
if up == ".FALSE.":
|
|
||||||
return False
|
|
||||||
if s.startswith("'") and s.endswith("'"):
|
|
||||||
return s[1:-1].replace("''", "'")
|
|
||||||
if s.startswith('"') and s.endswith('"'):
|
|
||||||
return s[1:-1]
|
|
||||||
m = _RE_CUR_DATE_OFFSET.match(s)
|
|
||||||
if m:
|
|
||||||
days = int(m.group(1))
|
|
||||||
return datetime.now().date() + timedelta(days=days)
|
|
||||||
m = _RE_CUR_TIME_OFFSET.match(s)
|
|
||||||
if m:
|
|
||||||
hours = int(m.group(1))
|
|
||||||
return (datetime.now() + timedelta(hours=hours)).time()
|
|
||||||
try:
|
try:
|
||||||
return int(s)
|
from lupa.lua54 import LuaError as _LuaError, LuaSyntaxError as _LuaSyntaxError
|
||||||
except ValueError:
|
except ImportError:
|
||||||
pass
|
_LuaError = Exception
|
||||||
try:
|
_LuaSyntaxError = Exception
|
||||||
return float(s)
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
obj = _resolveFieldObj(s)
|
|
||||||
if obj:
|
|
||||||
return obj.getValue(target_data)
|
|
||||||
return ""
|
|
||||||
|
|
||||||
|
|
||||||
def _resolveAsObject(
|
__all__ = ["ASEngine"]
|
||||||
expr: str,
|
|
||||||
target_data: dict
|
|
||||||
) -> ASObject:
|
|
||||||
"""
|
|
||||||
Resolve a value expression to an ASObject.
|
|
||||||
|
|
||||||
- If the expression is a registered field name, returns its ASObject directly.
|
|
||||||
- If the expression is a literal (number, string, DATE(), TIME(), bool),
|
|
||||||
creates a temporary ASObject with the inferred type.
|
|
||||||
|
|
||||||
This is the key function that ensures all internal operations work
|
|
||||||
with typed ASObject instances rather than raw Python values.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
expr (str): The raw expression string from the script.
|
|
||||||
target_data (dict): The application data dict.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
ASObject: A registered or temporary ASObject representing the expression value.
|
|
||||||
"""
|
|
||||||
|
|
||||||
s = expr.strip()
|
|
||||||
obj = _resolveFieldObj(s)
|
|
||||||
if obj is not None:
|
|
||||||
return obj
|
|
||||||
value = _resolveValue(s, target_data)
|
|
||||||
inferred = _inferType(value, s)
|
|
||||||
return ASObject._makeTemp(value, inferred)
|
|
||||||
|
|
||||||
|
|
||||||
def _evaluateCondition(
|
class ASEngine:
|
||||||
condition_str: str,
|
|
||||||
target_data: dict,
|
|
||||||
line: int = 0
|
|
||||||
) -> bool:
|
|
||||||
"""
|
|
||||||
Evaluate a condition expression and return a boolean result.
|
|
||||||
|
|
||||||
Supports:
|
@staticmethod
|
||||||
- Boolean literals: .TRUE., .FALSE.
|
def getCurrentDate(
|
||||||
- .AND. / .OR. operators (lowest precedence)
|
) -> str:
|
||||||
- Parenthesised sub-expressions
|
|
||||||
- Comparison operators: .EQ., .NEQ., .BGT., .BLT., .BGE., .BLE.
|
|
||||||
|
|
||||||
All operands are resolved as ASObject instances (via _resolveAsObject)
|
return date.today().isoformat()
|
||||||
and comparisons are delegated to ASOperator.compare().
|
|
||||||
|
|
||||||
Args:
|
@staticmethod
|
||||||
condition_str (str): The raw condition expression from the script.
|
def getCurrentTime(
|
||||||
target_data (dict): The application data dict.
|
) -> str:
|
||||||
|
|
||||||
Returns:
|
return datetime.now().strftime("%H:%M")
|
||||||
bool: The evaluation result.
|
|
||||||
|
|
||||||
Raises:
|
@staticmethod
|
||||||
ValueError: If the expression contains unrecognised tokens or type-mismatched comparisons.
|
def _sandbox(
|
||||||
"""
|
lua,
|
||||||
|
) -> None:
|
||||||
|
|
||||||
s = condition_str.strip()
|
lua.execute("""
|
||||||
if not s:
|
io = nil
|
||||||
return False
|
require = nil
|
||||||
or_parts = splitTopLevel(s, ".OR.")
|
dofile = nil
|
||||||
if len(or_parts) > 1:
|
loadfile = nil
|
||||||
return any(
|
load = nil
|
||||||
_evaluateCondition(p.strip(), target_data, line)
|
package = nil
|
||||||
for p in or_parts
|
rawget = nil
|
||||||
)
|
rawset = nil
|
||||||
and_parts = splitTopLevel(s, ".AND.")
|
rawequal = nil
|
||||||
if len(and_parts) > 1:
|
getfenv = nil
|
||||||
return all(
|
setfenv = nil
|
||||||
_evaluateCondition(p.strip(), target_data, line)
|
debug = nil
|
||||||
for p in and_parts
|
if os then
|
||||||
)
|
os.execute = nil
|
||||||
s = s.strip()
|
os.exit = nil
|
||||||
if s.startswith("(") and s.endswith(")"):
|
os.getenv = nil
|
||||||
return _evaluateCondition(s[1:-1], target_data, line)
|
os.remove = nil
|
||||||
up = s.upper()
|
os.rename = nil
|
||||||
if up == ".TRUE.":
|
os.tmpname = nil
|
||||||
return True
|
os.setlocale = nil
|
||||||
if up == ".FALSE.":
|
end
|
||||||
return False
|
""")
|
||||||
for op in ASOperator._COMPARE:
|
|
||||||
idx = up.find(op.upper())
|
|
||||||
if idx < 0:
|
|
||||||
continue
|
|
||||||
left_raw = s[:idx].strip()
|
|
||||||
right_raw = s[idx + len(op):].strip()
|
|
||||||
try:
|
|
||||||
left_obj = _resolveAsObject(left_raw, target_data)
|
|
||||||
right_obj = _resolveAsObject(right_raw, target_data)
|
|
||||||
return ASOperator.compare(left_obj, right_obj, op, target_data)
|
|
||||||
except ValueError as e:
|
|
||||||
raise ValueError(_errPos(line, str(e)))
|
|
||||||
raise ValueError(
|
|
||||||
_errPos(line, f"无法识别的条件表达式 '{condition_str}'")
|
|
||||||
)
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _registerHelpers(
|
||||||
|
lua,
|
||||||
|
) -> None:
|
||||||
|
|
||||||
def _executeSet(
|
lua.execute("""
|
||||||
line_text: str,
|
function date(y, m, d)
|
||||||
target_data: dict,
|
return os.time({year = y, month = m, day = d})
|
||||||
line: int = 0
|
end
|
||||||
):
|
|
||||||
"""
|
|
||||||
Execute a SET statement to assign a value to a field or script variable.
|
|
||||||
|
|
||||||
Parses the line as "SET field_name = value_expr", resolves the value,
|
function time(h, m)
|
||||||
and assigns it. If the target field does not exist, a new script variable
|
return h * 60 + m
|
||||||
is created with an inferred type.
|
end
|
||||||
|
|
||||||
Args:
|
function datenow()
|
||||||
line (str): The raw SET line from the script.
|
local now = os.date("*t")
|
||||||
target_data (dict): The application data dict.
|
return os.time({year = now.year, month = now.month, day = now.day})
|
||||||
|
end
|
||||||
|
|
||||||
Raises:
|
function timenow()
|
||||||
ValueError: If the value string contains unexpected extra tokens.
|
local now = os.date("*t")
|
||||||
"""
|
return now.hour * 60 + now.min
|
||||||
|
end
|
||||||
|
|
||||||
rest = line_text[3:].strip()
|
function dateadd(date_val, n)
|
||||||
eq_idx = rest.find("=")
|
return date_val + n * 86400
|
||||||
if eq_idx < 0:
|
end
|
||||||
return
|
|
||||||
field_name = rest[:eq_idx].strip()
|
|
||||||
value_str = rest[eq_idx + 1:].strip()
|
|
||||||
if not field_name:
|
|
||||||
return
|
|
||||||
resolved = _resolveValue(value_str, target_data)
|
|
||||||
stripped = value_str.strip()
|
|
||||||
if resolved == "" and stripped not in ("''", '""') and len(stripped.split()) > 1:
|
|
||||||
raise ValueError(_errPos(line, f"SET 值中存在多余内容 '{stripped}'"))
|
|
||||||
upper_name = field_name.upper().strip()
|
|
||||||
obj = _FIELD_MAP.get(upper_name)
|
|
||||||
if not obj:
|
|
||||||
obj = _SCRIPT_VARS.get(upper_name)
|
|
||||||
if obj:
|
|
||||||
try:
|
|
||||||
obj.setValue(resolved, target_data)
|
|
||||||
except ValueError as e:
|
|
||||||
raise ValueError(_errPos(line, str(e)))
|
|
||||||
return
|
|
||||||
inferred_type = _inferType(resolved, stripped)
|
|
||||||
new_var = ASObject(
|
|
||||||
upper_name,
|
|
||||||
inferred_type,
|
|
||||||
read_only=False,
|
|
||||||
is_config=False,
|
|
||||||
default_value=resolved
|
|
||||||
)
|
|
||||||
_SCRIPT_VARS[upper_name] = new_var
|
|
||||||
|
|
||||||
|
function timeadd(time_val, n)
|
||||||
|
return (time_val + n * 60) % 1440
|
||||||
|
end
|
||||||
|
|
||||||
def _executeOperation(
|
function strtodate(iso_str)
|
||||||
line_text: str,
|
local y, m, d = iso_str:match("(%d+)-(%d+)-(%d+)")
|
||||||
target_data: dict,
|
return os.time({year = y, month = m, day = d})
|
||||||
line: int = 0
|
end
|
||||||
):
|
|
||||||
"""
|
|
||||||
Execute a field operation statement: "FIELD .ADD. N" or "FIELD .SUB. N".
|
|
||||||
|
|
||||||
Resolves the left side as a registered ASObject and the right side
|
function strtotime(hm_str)
|
||||||
as a temporary numeric ASObject, then delegates to ASOperator.apply().
|
local h, m = hm_str:match("(%d+):(%d+)")
|
||||||
|
return h * 60 + m
|
||||||
|
end
|
||||||
|
|
||||||
Args:
|
function datetostr(ts)
|
||||||
line (str): The raw operation line from the script (e.g. "RESERVE_DATE .ADD. 1").
|
return os.date("%Y-%m-%d", ts)
|
||||||
target_data (dict): The application data dict.
|
end
|
||||||
|
|
||||||
Raises:
|
function timetostr(m)
|
||||||
ValueError: If the field is unknown, the operand is invalid,
|
return string.format("%02d:%02d", math.floor(m / 60), m % 60)
|
||||||
or the type does not support the operation.
|
end
|
||||||
"""
|
""")
|
||||||
|
|
||||||
parts = line_text.split()
|
|
||||||
if len(parts) < 3:
|
|
||||||
return
|
|
||||||
if len(parts) > 3:
|
|
||||||
raise ValueError(
|
|
||||||
_errPos(line, f"操作语句中存在多余内容 '{' '.join(parts[3:])}'")
|
|
||||||
)
|
|
||||||
field_name = parts[0].upper().strip()
|
|
||||||
op = parts[1].upper().strip()
|
|
||||||
raw_value = parts[2].strip()
|
|
||||||
target = _resolveFieldObj(field_name)
|
|
||||||
if target is None:
|
|
||||||
raise ValueError(_errPos(line, f"未知字段 '{field_name}'"))
|
|
||||||
try:
|
|
||||||
operand = _resolveAsObject(raw_value, target_data)
|
|
||||||
ASOperator.apply(target, operand, op, target_data)
|
|
||||||
except ValueError as e:
|
|
||||||
raise ValueError(_errPos(line, str(e)))
|
|
||||||
|
|
||||||
|
|
||||||
def addTargetVar(
|
|
||||||
name: str,
|
|
||||||
var_type: str,
|
|
||||||
key_path: list,
|
|
||||||
display_name: str = None
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Register a new target variable bound to a path in the application data dict.
|
|
||||||
|
|
||||||
Once registered, the variable can be read, written, and operated on in scripts
|
|
||||||
using its canonical name or display_name.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
name (str): The canonical variable name (e.g. "RESERVE_DATE").
|
|
||||||
var_type (str): The type ("Int", "Float", "Boolean", "Date", "Time", "String").
|
|
||||||
key_path (list): The nested path into target_data, e.g. ["reserve_info", "date"].
|
|
||||||
display_name (str): An optional Chinese alias for use in script conditions.
|
|
||||||
|
|
||||||
Example:
|
|
||||||
>>> addTargetVar("MY_FIELD", "String", ["custom", "field"], display_name="自定义字段")
|
|
||||||
"""
|
|
||||||
|
|
||||||
upper_name = name.upper().strip()
|
|
||||||
obj = ASObject(
|
|
||||||
upper_name,
|
|
||||||
var_type,
|
|
||||||
is_config=True,
|
|
||||||
key_path=key_path,
|
|
||||||
display_name=display_name
|
|
||||||
)
|
|
||||||
_TARGET_VARS[upper_name] = obj
|
|
||||||
|
|
||||||
|
|
||||||
class _EngineExecutor(NodeVisitor):
|
|
||||||
"""
|
|
||||||
AST visitor that executes AutoScript against target_data.
|
|
||||||
Walks the AST and dispatches SET / ADD / SUB operations
|
|
||||||
via visitScript / visitIf / visitSet / visitOp / visitPass / visitUnrecog.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
target_data: dict
|
targetVars: list[tuple] = None,
|
||||||
):
|
):
|
||||||
|
|
||||||
super().__init__()
|
self._targetVars: dict[str, dict] = {}
|
||||||
self._target_data = target_data
|
self._lua = None
|
||||||
self._cur_line = 0
|
|
||||||
|
|
||||||
@property
|
if targetVars:
|
||||||
def _line(self) -> int:
|
for item in targetVars:
|
||||||
"""Return current line number for _errPos calls."""
|
name, varType, keyPath = item[0], item[1], item[2]
|
||||||
|
self.addTargetVar(name, varType, keyPath)
|
||||||
|
|
||||||
return self._cur_line
|
def _getLua(
|
||||||
|
|
||||||
|
|
||||||
def _incLine(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
|
|
||||||
self._cur_line += 1
|
|
||||||
|
|
||||||
|
|
||||||
def visitScript(
|
|
||||||
self,
|
self,
|
||||||
_node: Script
|
|
||||||
):
|
):
|
||||||
|
|
||||||
for child in _node.body:
|
if self._lua is None:
|
||||||
child.accept(self)
|
self._lua = _LuaRuntime(unpack_returned_tuples=True)
|
||||||
|
self._sandbox(self._lua)
|
||||||
|
self._registerHelpers(self._lua)
|
||||||
|
return self._lua
|
||||||
|
|
||||||
|
def _push(
|
||||||
def visitIf(
|
|
||||||
self,
|
self,
|
||||||
_node: IfNode
|
targetData: dict,
|
||||||
):
|
) -> None:
|
||||||
|
|
||||||
self._incLine()
|
lua = self._getLua()
|
||||||
if not _node.closed:
|
g = lua.globals()
|
||||||
raise ValueError(_errPos(self._line, "IF 与 ENDIF / END IF 不匹配"))
|
strToDate = g["strtodate"]
|
||||||
matched = _evaluateCondition(_node.condition, self._target_data, self._line)
|
strToTime = g["strtotime"]
|
||||||
if matched:
|
|
||||||
for child in _node.body:
|
|
||||||
child.accept(self)
|
|
||||||
else:
|
|
||||||
executed = False
|
|
||||||
for elif_node in _node.elif_branches:
|
|
||||||
self._incLine()
|
|
||||||
if _evaluateCondition(elif_node.condition, self._target_data, self._line):
|
|
||||||
for child in elif_node.body:
|
|
||||||
child.accept(self)
|
|
||||||
executed = True
|
|
||||||
break
|
|
||||||
if not executed and _node.else_body:
|
|
||||||
self._incLine()
|
|
||||||
for child in _node.else_body:
|
|
||||||
child.accept(self)
|
|
||||||
|
|
||||||
|
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 visitSet(
|
def _pull(
|
||||||
self,
|
self,
|
||||||
_node: SetNode
|
targetData: dict,
|
||||||
):
|
) -> None:
|
||||||
|
|
||||||
self._incLine()
|
lua = self._getLua()
|
||||||
full_line = f"SET {_node.target} = {_node.value}"
|
g = lua.globals()
|
||||||
_executeSet(full_line, self._target_data, self._line)
|
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 visitOp(
|
def addTargetVar(
|
||||||
self,
|
self,
|
||||||
_node: OpNode
|
name: str,
|
||||||
):
|
varType: str,
|
||||||
|
keyPath: list,
|
||||||
|
) -> None:
|
||||||
|
|
||||||
self._incLine()
|
upperName = name.upper().strip()
|
||||||
op_upper = _node.op_type.upper()
|
self._targetVars[upperName] = {
|
||||||
full_line = f"{_node.target} .{op_upper}. {_node.value}"
|
"type": varType,
|
||||||
_executeOperation(full_line, self._target_data, self._line)
|
"keyPath": keyPath,
|
||||||
|
}
|
||||||
|
|
||||||
|
def execute(
|
||||||
def visitPass(
|
|
||||||
self,
|
self,
|
||||||
_node: PassNode
|
scriptText: str,
|
||||||
):
|
targetData: dict,
|
||||||
|
) -> None:
|
||||||
|
|
||||||
self._incLine()
|
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(
|
||||||
def visitUnrecog(
|
|
||||||
self,
|
self,
|
||||||
_node: UnrecogNode
|
) -> None:
|
||||||
):
|
|
||||||
|
|
||||||
self._incLine()
|
self._targetVars = {}
|
||||||
upper = _node.raw_line.upper().strip()
|
self._lua = None
|
||||||
if upper.startswith("IF"):
|
|
||||||
paren_open = upper.find("(")
|
|
||||||
if paren_open < 0:
|
|
||||||
raise ValueError(_errPos(self._line, "IF 缺少左括号"))
|
|
||||||
depth = 1
|
|
||||||
for ci in range(paren_open + 1, len(upper)):
|
|
||||||
if upper[ci] == "(":
|
|
||||||
depth += 1
|
|
||||||
elif upper[ci] == ")":
|
|
||||||
depth -= 1
|
|
||||||
if depth == 0:
|
|
||||||
remaining = upper[ci + 1:].strip()
|
|
||||||
if remaining and remaining != "THEN":
|
|
||||||
raise ValueError(_errPos(self._line, f"IF 条件后存在多余内容 '{remaining}'"))
|
|
||||||
break
|
|
||||||
if depth > 0:
|
|
||||||
raise ValueError(_errPos(self._line, "IF 缺少右括号"))
|
|
||||||
elif upper.startswith("ELSE IF"):
|
|
||||||
paren_open = upper.find("(")
|
|
||||||
if paren_open < 0:
|
|
||||||
raise ValueError(_errPos(self._line, "ELSE IF 缺少左括号"))
|
|
||||||
_executeOperation(_node.raw_line, self._target_data, self._line)
|
|
||||||
|
|
||||||
|
|
||||||
def execute(
|
|
||||||
script_text: str,
|
|
||||||
target_data: dict
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Execute an AutoScript on the given target data.
|
|
||||||
|
|
||||||
Parses the script into an AST via ASTokenizer.parse(),
|
|
||||||
then walks the tree with a visitor to evaluate conditions
|
|
||||||
and dispatch SET / ADD / SUB operations.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
script_text (str): The AutoScript source code.
|
|
||||||
target_data (dict): The application data dict to read from / write to.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
ValueError: On syntax errors, unbalanced IF/END IF, unknown fields, etc.
|
|
||||||
"""
|
|
||||||
|
|
||||||
_buildFieldMap()
|
|
||||||
if not script_text or not script_text.strip():
|
|
||||||
return
|
|
||||||
ast = ASTokenizer.parse(script_text)
|
|
||||||
if not ast.body:
|
|
||||||
return
|
|
||||||
executor = _EngineExecutor(target_data)
|
|
||||||
ast.accept(executor)
|
|
||||||
@@ -1,259 +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 re
|
|
||||||
from datetime import (
|
|
||||||
datetime,
|
|
||||||
date,
|
|
||||||
time
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"ASObject",
|
|
||||||
"_META_VARS",
|
|
||||||
"_inferType"
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
# Default values for each supported type when no value is present
|
|
||||||
_TYPE_DEFAULTS = {
|
|
||||||
"Int": 0,
|
|
||||||
"Float": 0.0,
|
|
||||||
"Boolean": False,
|
|
||||||
"Date": None,
|
|
||||||
"Time": None,
|
|
||||||
"String": ""
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class ASObject:
|
|
||||||
"""
|
|
||||||
Represents a variable object used throughout the AutoScript engine.
|
|
||||||
|
|
||||||
An ASObject can be a meta variable (read-only, e.g. CURRENT_DATE),
|
|
||||||
a target variable (bound to a config data dict via key_path),
|
|
||||||
or a script variable (free-form, stored internally).
|
|
||||||
|
|
||||||
Args:
|
|
||||||
name (str): The canonical name of the variable (case-insensitive).
|
|
||||||
var_type (str): One of "Int", "Float", "Boolean", "Date", "Time", "String".
|
|
||||||
read_only (bool): Whether the variable is read-only (default: False).
|
|
||||||
is_config (bool): Whether the variable maps to a target_data path (default: False).
|
|
||||||
key_path (list): The nested key path into target_data, e.g. ["reserve_info", "date"].
|
|
||||||
default_value: The fallback value when no target_data value is found.
|
|
||||||
display_name (str): An alias for use in script conditions and assignments.
|
|
||||||
|
|
||||||
Example:
|
|
||||||
>>> obj = ASObject("MY_DATE", "Date", is_config=True,
|
|
||||||
... key_path=["reserve_info", "date"],
|
|
||||||
... display_name="预约日期")
|
|
||||||
>>> obj.getValue({"reserve_info": {"date": "2026-05-01"}})
|
|
||||||
datetime.date(2026, 5, 1)
|
|
||||||
"""
|
|
||||||
|
|
||||||
_TEMP_COUNTER = 0
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
name: str,
|
|
||||||
var_type: str, *,
|
|
||||||
read_only: bool = False,
|
|
||||||
is_config: bool = False,
|
|
||||||
key_path: list = None,
|
|
||||||
default_value=None,
|
|
||||||
display_name: str = None
|
|
||||||
):
|
|
||||||
|
|
||||||
self.name = name
|
|
||||||
self.var_type = var_type
|
|
||||||
self.read_only = read_only
|
|
||||||
self.is_config = is_config
|
|
||||||
self.key_path = key_path or []
|
|
||||||
self._value = default_value
|
|
||||||
self.display_name = display_name
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _makeTemp(
|
|
||||||
cls,
|
|
||||||
value,
|
|
||||||
inferred_type: str
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Create a temporary unnamed ASObject from a literal value.
|
|
||||||
|
|
||||||
Temporary objects are used for inline script literals (e.g. 42,
|
|
||||||
'hello', DATE(2026-01-01)) so they can participate in typed
|
|
||||||
operations alongside registered variables.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
value: The resolved Python value.
|
|
||||||
inferred_type (str): The AutoScript type name.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
ASObject: A temporary, non-config, read-write ASObject.
|
|
||||||
"""
|
|
||||||
|
|
||||||
cls._TEMP_COUNTER += 1
|
|
||||||
return cls(
|
|
||||||
f"__TMP_{cls._TEMP_COUNTER}",
|
|
||||||
inferred_type,
|
|
||||||
read_only=False,
|
|
||||||
is_config=False,
|
|
||||||
default_value=value
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _typeEmpty(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Return the type-appropriate empty / default value.
|
|
||||||
"""
|
|
||||||
|
|
||||||
return _TYPE_DEFAULTS.get(self.var_type, "")
|
|
||||||
|
|
||||||
|
|
||||||
def getValue(
|
|
||||||
self,
|
|
||||||
target_data: dict = None
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Retrieve the current value of this variable.
|
|
||||||
|
|
||||||
For read-only variables (CURRENT_DATE, CURRENT_TIME), returns the
|
|
||||||
live datetime. For config variables, traverses the key_path into
|
|
||||||
target_data and parses Date/Time strings. Otherwise returns the
|
|
||||||
internal _value.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
target_data (dict): The application data dict (required for config vars).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
The resolved value, or a type-appropriate default if missing.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if self.read_only:
|
|
||||||
if self.name == "CURRENT_DATE":
|
|
||||||
return datetime.now().date()
|
|
||||||
if self.name == "CURRENT_TIME":
|
|
||||||
return datetime.now().time()
|
|
||||||
return self._value
|
|
||||||
if self.is_config and target_data is not None and self.key_path:
|
|
||||||
d = target_data
|
|
||||||
for key in self.key_path[:-1]:
|
|
||||||
d = d.get(key, {})
|
|
||||||
if not isinstance(d, dict):
|
|
||||||
return self._typeEmpty()
|
|
||||||
raw = d.get(self.key_path[-1])
|
|
||||||
if raw is None:
|
|
||||||
return self._typeEmpty()
|
|
||||||
if self.var_type == "Date" and isinstance(raw, str):
|
|
||||||
try:
|
|
||||||
return datetime.strptime(raw, "%Y-%m-%d").date()
|
|
||||||
except ValueError:
|
|
||||||
return self._typeEmpty()
|
|
||||||
if self.var_type == "Time" and isinstance(raw, str):
|
|
||||||
try:
|
|
||||||
return datetime.strptime(raw, "%H:%M").time()
|
|
||||||
except ValueError:
|
|
||||||
return self._typeEmpty()
|
|
||||||
return raw
|
|
||||||
return self._value
|
|
||||||
|
|
||||||
|
|
||||||
def setValue(
|
|
||||||
self,
|
|
||||||
value,
|
|
||||||
target_data: dict = None
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Assign a new value to this variable, with type coercion.
|
|
||||||
|
|
||||||
Performs coercion for Boolean (string -> bool), Int, and Float types.
|
|
||||||
For config variables, dates/times are converted back to strings before
|
|
||||||
writing into target_data.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
value: The value to assign.
|
|
||||||
target_data (dict): The application data dict (required for config vars).
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
ValueError: If the variable is read-only or value cannot be coerced.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if self.read_only:
|
|
||||||
raise ValueError(f"不能修改只读变量 '{self.name}'")
|
|
||||||
if self.var_type == "Boolean" and not isinstance(value, bool):
|
|
||||||
value = (str(value).upper() == "TRUE")
|
|
||||||
if self.var_type == "Int" and not isinstance(value, int):
|
|
||||||
try:
|
|
||||||
value = int(value)
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
raise ValueError(f"无法将值 '{value}' 转换为 Int 类型")
|
|
||||||
if self.var_type == "Float" and not isinstance(value, float):
|
|
||||||
try:
|
|
||||||
value = float(value)
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
raise ValueError(f"无法将值 '{value}' 转换为 Float 类型")
|
|
||||||
if self.is_config:
|
|
||||||
if self.var_type == "Date" and isinstance(value, date):
|
|
||||||
value = value.strftime("%Y-%m-%d")
|
|
||||||
if self.var_type == "Time" and isinstance(value, time):
|
|
||||||
value = value.strftime("%H:%M")
|
|
||||||
if self.is_config and target_data is not None and self.key_path:
|
|
||||||
d = target_data
|
|
||||||
for key in self.key_path[:-1]:
|
|
||||||
d = d.setdefault(key, {})
|
|
||||||
d[self.key_path[-1]] = value
|
|
||||||
else:
|
|
||||||
self._value = value
|
|
||||||
|
|
||||||
|
|
||||||
# Built-in read-only meta variables available to all scripts
|
|
||||||
_META_VARS = {
|
|
||||||
"CURRENT_DATE": ASObject("CURRENT_DATE", "Date", read_only=True, display_name="当前日期"),
|
|
||||||
"CURRENT_TIME": ASObject("CURRENT_TIME", "Time", read_only=True, display_name="当前时间"),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _inferType(
|
|
||||||
value,
|
|
||||||
raw_expr: str = None
|
|
||||||
) -> str:
|
|
||||||
"""
|
|
||||||
Infer the ASObject type string from a Python value or raw expression.
|
|
||||||
|
|
||||||
When the Python type is ambiguous (e.g. int can be Int or a component
|
|
||||||
of Date), the raw_expr is used as a hint.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
value: The resolved Python value.
|
|
||||||
raw_expr (str): The original expression string from the script (optional).
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: One of "Boolean", "Int", "Float", "Date", "Time", "String".
|
|
||||||
"""
|
|
||||||
|
|
||||||
if isinstance(value, bool):
|
|
||||||
return "Boolean"
|
|
||||||
if isinstance(value, int):
|
|
||||||
return "Int"
|
|
||||||
if isinstance(value, float):
|
|
||||||
return "Float"
|
|
||||||
if isinstance(value, date):
|
|
||||||
return "Date"
|
|
||||||
if isinstance(value, time):
|
|
||||||
return "Time"
|
|
||||||
if raw_expr:
|
|
||||||
if re.match(r"^DATE\(\d{4}-\d{2}-\d{2}\)$", raw_expr, re.IGNORECASE):
|
|
||||||
return "Date"
|
|
||||||
if re.match(r"^TIME\(\d{1,2}:\d{2}\)$", raw_expr, re.IGNORECASE):
|
|
||||||
return "Time"
|
|
||||||
return "String"
|
|
||||||
@@ -1,78 +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.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
class ParsingObserver:
|
|
||||||
"""
|
|
||||||
Base observer for AutoScript parsing events.
|
|
||||||
|
|
||||||
Subclass and override the relevant methods to react to
|
|
||||||
tokenization / parsing events produced by ASTokenizer.
|
|
||||||
This is the core abstraction that lets pre-check and
|
|
||||||
orchestration modules subscribe to the same parsing pipeline.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def onParseStart(
|
|
||||||
self,
|
|
||||||
script_text: str
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Called when tokenization of a new script begins.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
script_text (str): The full script text being parsed.
|
|
||||||
"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
def onTokenParsed(
|
|
||||||
self,
|
|
||||||
kind: str | None,
|
|
||||||
data,
|
|
||||||
line_num: int,
|
|
||||||
raw_line: str
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Called after each script line has been classified as a token.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
kind (str | None): Token kind (K_IF, K_ELSE_IF, K_ELSE,
|
|
||||||
K_ENDIF, K_SET, K_ADD, K_SUB) or
|
|
||||||
None if unrecognised.
|
|
||||||
data: Token payload — condition string for IF/ELSE IF,
|
|
||||||
(target, value) tuple for SET/ADD/SUB,
|
|
||||||
None for ELSE/ENDIF/unrecognised.
|
|
||||||
line_num (int): 1-based line number.
|
|
||||||
raw_line (str): The stripped raw line text.
|
|
||||||
"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
def onParseComplete(
|
|
||||||
self,
|
|
||||||
statements: list
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Called when flat tokenization is complete.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
statements (list[Stmt]): The list of parsed Stmt objects.
|
|
||||||
"""
|
|
||||||
pass
|
|
||||||
|
|
||||||
def onASTReady(
|
|
||||||
self,
|
|
||||||
ast
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Called when full AST construction is complete (after parse()).
|
|
||||||
|
|
||||||
Args:
|
|
||||||
ast (Script): The root Script AST node.
|
|
||||||
"""
|
|
||||||
pass
|
|
||||||
@@ -1,191 +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 datetime import (
|
|
||||||
datetime,
|
|
||||||
timedelta,
|
|
||||||
date,
|
|
||||||
time
|
|
||||||
)
|
|
||||||
|
|
||||||
from .ASObject import ASObject
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = ["ASOperator", "ARITH_TYPES", "COMPARISON_OPERATORS"]
|
|
||||||
|
|
||||||
|
|
||||||
class ASOperator:
|
|
||||||
"""
|
|
||||||
Centralised type-safe operations for AutoScript engine types.
|
|
||||||
|
|
||||||
All arithmetic (ADD / SUB) and comparison operators are routed through
|
|
||||||
this class, which dispatches to the correct Python-level logic based on
|
|
||||||
the ASObject's var_type. This keeps type-specific branching in one
|
|
||||||
place instead of scattering it across the engine.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
op (str): One of ".ADD.", ".SUB.", ".EQ.", ".NEQ.", ".BGT.",
|
|
||||||
".BLT.", ".BGE.", ".BLE.".
|
|
||||||
|
|
||||||
Example:
|
|
||||||
>>> obj = ASObject("X", "Int", default_value=10)
|
|
||||||
>>> ASOperator.apply(obj, ASObject._makeTemp(5, "Int"), ".ADD.", None)
|
|
||||||
>>> obj.getValue()
|
|
||||||
15
|
|
||||||
>>> ASOperator.compare(
|
|
||||||
... obj,
|
|
||||||
... ASObject._makeTemp(15, "Int"),
|
|
||||||
... ".EQ.", None
|
|
||||||
... )
|
|
||||||
True
|
|
||||||
"""
|
|
||||||
|
|
||||||
_COMPARE = {
|
|
||||||
".EQ." : lambda a, b: a == b,
|
|
||||||
".NEQ.": lambda a, b: a != b,
|
|
||||||
".BGT.": lambda a, b: a > b,
|
|
||||||
".BLT.": lambda a, b: a < b,
|
|
||||||
".BGE.": lambda a, b: a >= b,
|
|
||||||
".BLE.": lambda a, b: a <= b,
|
|
||||||
}
|
|
||||||
_ARITH_TYPES = {"Date", "Time", "Int", "Float"}
|
|
||||||
# Comparison-compatible type groups
|
|
||||||
_COMPATIBLE_GROUPS = [
|
|
||||||
{"String"},
|
|
||||||
{"Boolean"},
|
|
||||||
{"Int", "Float"},
|
|
||||||
{"Date"},
|
|
||||||
{"Time"},
|
|
||||||
]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def apply(
|
|
||||||
cls,
|
|
||||||
target: ASObject,
|
|
||||||
operand: ASObject,
|
|
||||||
op: str,
|
|
||||||
target_data: dict
|
|
||||||
):
|
|
||||||
"""
|
|
||||||
Apply ADD or SUB to a target ASObject, modifying it in place.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
target (ASObject): The variable to modify.
|
|
||||||
operand (ASObject): The operand (numeric value for Date/Time/Int/Float).
|
|
||||||
op (str): ".ADD." or ".SUB.".
|
|
||||||
target_data (dict): Application data dict (passed through to getValue/setValue).
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
ValueError: If the type does not support the operation or values are invalid.
|
|
||||||
"""
|
|
||||||
|
|
||||||
tp = target.var_type
|
|
||||||
op_tp = operand.var_type
|
|
||||||
if tp not in cls._ARITH_TYPES:
|
|
||||||
raise ValueError(f"'{tp}' 类型字段不支持操作运算")
|
|
||||||
if op_tp not in ("Int", "Float"):
|
|
||||||
raise ValueError(f"操作数类型 '{op_tp}' 不能用于运算,需要数值类型 (Int / Float)")
|
|
||||||
if tp in ("Date", "Time") and op_tp != "Int":
|
|
||||||
raise ValueError(f"'{tp}' 类型的加减法操作数必须为 Int 类型,不允许 Float")
|
|
||||||
target_val = target.getValue(target_data)
|
|
||||||
if target_val is None:
|
|
||||||
raise ValueError(f"'{target.name}' 的值为空,无法进行运算")
|
|
||||||
op_name = "ADD" if op == ".ADD." else "SUB" if op == ".SUB." else None
|
|
||||||
if op_name is None:
|
|
||||||
raise ValueError(f"不支持的操作 '{op}'")
|
|
||||||
sign = 1 if op == ".ADD." else -1
|
|
||||||
cls._arithBinary(target, target_val, operand, target_data, sign, op_name)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _arithBinary(
|
|
||||||
cls,
|
|
||||||
target: ASObject,
|
|
||||||
target_val,
|
|
||||||
operand: ASObject,
|
|
||||||
target_data: dict,
|
|
||||||
sign: int,
|
|
||||||
op_name: str = ""
|
|
||||||
):
|
|
||||||
"""Apply arithmetic per type."""
|
|
||||||
|
|
||||||
tp = target.var_type
|
|
||||||
raw_op = operand._value
|
|
||||||
|
|
||||||
if tp == "Date":
|
|
||||||
if not isinstance(target_val, date):
|
|
||||||
raise ValueError(f"'{target.name}' 的值 '{target_val}' 不是有效日期")
|
|
||||||
new_val = target_val + timedelta(days=int(raw_op)) * sign
|
|
||||||
elif tp == "Time":
|
|
||||||
if not isinstance(target_val, time):
|
|
||||||
raise ValueError(f"'{target.name}' 的值 '{target_val}' 不是有效时间")
|
|
||||||
delta = timedelta(hours=int(raw_op)) * sign
|
|
||||||
dt = datetime.combine(datetime.today(), target_val) + delta
|
|
||||||
new_val = dt.time()
|
|
||||||
elif tp == "Int":
|
|
||||||
new_val = int(target_val) + int(raw_op)*sign
|
|
||||||
elif tp == "Float":
|
|
||||||
new_val = float(target_val) + float(raw_op)*sign
|
|
||||||
else:
|
|
||||||
raise ValueError(f"'{tp}' 类型不支持 {op_name} 操作")
|
|
||||||
target.setValue(new_val, target_data)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def compare(
|
|
||||||
cls,
|
|
||||||
left: ASObject,
|
|
||||||
right: ASObject,
|
|
||||||
op: str,
|
|
||||||
target_data: dict
|
|
||||||
) -> bool:
|
|
||||||
"""
|
|
||||||
Compare two ASObjects using the given comparison operator.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
left (ASObject): Left-hand side.
|
|
||||||
right (ASObject): Right-hand side.
|
|
||||||
op (str): One of ".EQ.", ".NEQ.", ".BGT.", ".BLT.", ".BGE.", ".BLE.".
|
|
||||||
target_data (dict): Application data dict.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: The comparison result.
|
|
||||||
|
|
||||||
Raises:
|
|
||||||
ValueError: If the types are incompatible for comparison.
|
|
||||||
"""
|
|
||||||
|
|
||||||
cmp_func = cls._COMPARE.get(op)
|
|
||||||
if cmp_func is None:
|
|
||||||
raise ValueError(f"未知的比较操作 '{op}'")
|
|
||||||
left_tp = left.var_type
|
|
||||||
right_tp = right.var_type
|
|
||||||
if left_tp != right_tp:
|
|
||||||
same_group = any(
|
|
||||||
left_tp in g and right_tp in g
|
|
||||||
for g in cls._COMPATIBLE_GROUPS
|
|
||||||
)
|
|
||||||
if not same_group:
|
|
||||||
raise ValueError(
|
|
||||||
f"类型不兼容: 无法将 '{left.name}' ({left_tp}) "
|
|
||||||
f"与 '{right.name}' ({right_tp}) 进行比较"
|
|
||||||
)
|
|
||||||
left_val = left.getValue(target_data)
|
|
||||||
right_val = right.getValue(target_data)
|
|
||||||
try:
|
|
||||||
return cmp_func(left_val, right_val)
|
|
||||||
except TypeError:
|
|
||||||
raise ValueError(
|
|
||||||
f"无法比较 '{left.name}' ({left.var_type}) "
|
|
||||||
f"与 '{right.name}' ({right.var_type})"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# Public constants
|
|
||||||
# may be used by the GUI orchestration dialog.
|
|
||||||
ARITH_TYPES = ASOperator._ARITH_TYPES
|
|
||||||
COMPARISON_OPERATORS = set(ASOperator._COMPARE.keys())
|
|
||||||
@@ -1,575 +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 re
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"ASTokenizer",
|
|
||||||
"Stmt",
|
|
||||||
"Script",
|
|
||||||
"IfNode",
|
|
||||||
"ElifNode",
|
|
||||||
"SetNode",
|
|
||||||
"OpNode",
|
|
||||||
"PassNode",
|
|
||||||
"UnrecogNode",
|
|
||||||
"NodeVisitor",
|
|
||||||
"LineStrategy"
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
# Token kind constants
|
|
||||||
K_IF = "IF"
|
|
||||||
K_ELSE_IF = "ELSE IF"
|
|
||||||
K_ELSE = "ELSE"
|
|
||||||
K_ENDIF = "ENDIF"
|
|
||||||
K_SET = "SET"
|
|
||||||
K_ADD = "ADD"
|
|
||||||
K_SUB = "SUB"
|
|
||||||
K_PASS = "PASS"
|
|
||||||
|
|
||||||
# Op-type constants
|
|
||||||
OP_SET = "set"
|
|
||||||
OP_ADD = "add"
|
|
||||||
OP_SUB = "sub"
|
|
||||||
|
|
||||||
# Compiled line patterns
|
|
||||||
_RE_IF = re.compile(r"^IF\((.+)\)(?:\s+THEN\s*)?$", re.IGNORECASE)
|
|
||||||
_RE_ELSE_IF = re.compile(r"^ELSE\s+IF\((.+)\)(?:\s+THEN\s*)?$", re.IGNORECASE)
|
|
||||||
_RE_ELSE = re.compile(r"^ELSE\s*$", re.IGNORECASE)
|
|
||||||
_RE_ENDIF = re.compile(r"^(ENDIF|END IF)$", re.IGNORECASE)
|
|
||||||
_RE_SET = re.compile(r"^SET\s+(\w+)\s*=\s*(.+)$", re.IGNORECASE)
|
|
||||||
_RE_ADD = re.compile(r"^(\w+)\s+\.ADD\.\s+(\d+)$", re.IGNORECASE)
|
|
||||||
_RE_SUB = re.compile(r"^(\w+)\s+\.SUB\.\s+(\d+)$", re.IGNORECASE)
|
|
||||||
_RE_PASS = re.compile(r"^\s*PASS\s*$", re.IGNORECASE)
|
|
||||||
|
|
||||||
|
|
||||||
class Script:
|
|
||||||
"""
|
|
||||||
Root AST node for an entire AutoScript.
|
|
||||||
Contains an ordered list of top-level statement nodes.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
body: list = None
|
|
||||||
):
|
|
||||||
|
|
||||||
self.body = body or []
|
|
||||||
|
|
||||||
def accept(
|
|
||||||
self,
|
|
||||||
visitor
|
|
||||||
):
|
|
||||||
|
|
||||||
return visitor.visitScript(self)
|
|
||||||
|
|
||||||
|
|
||||||
class IfNode:
|
|
||||||
"""
|
|
||||||
IF conditional block with optional ELSE IF / ELSE branches.
|
|
||||||
|
|
||||||
Attributes:
|
|
||||||
condition (str): Raw condition expression.
|
|
||||||
body (list): Statements executed when condition is true.
|
|
||||||
elif_branches (list[ElifNode]): ELSE IF branches in order.
|
|
||||||
else_body (list): Statements executed for the ELSE branch.
|
|
||||||
closed (bool): Whether this IF has a matching ENDIF token.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
condition: str = "",
|
|
||||||
body: list = None,
|
|
||||||
elif_branches: list = None,
|
|
||||||
else_body: list = None,
|
|
||||||
closed: bool = True
|
|
||||||
):
|
|
||||||
|
|
||||||
self.condition = condition
|
|
||||||
self.body = body or []
|
|
||||||
self.elif_branches = elif_branches or []
|
|
||||||
self.else_body = else_body or []
|
|
||||||
self.closed = closed
|
|
||||||
|
|
||||||
def accept(
|
|
||||||
self,
|
|
||||||
visitor
|
|
||||||
):
|
|
||||||
|
|
||||||
return visitor.visitIf(self)
|
|
||||||
|
|
||||||
|
|
||||||
class ElifNode:
|
|
||||||
"""
|
|
||||||
ELSE IF branch within an IfNode.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
condition: str = "",
|
|
||||||
body: list = None
|
|
||||||
):
|
|
||||||
|
|
||||||
self.condition = condition
|
|
||||||
self.body = body or []
|
|
||||||
|
|
||||||
|
|
||||||
class SetNode:
|
|
||||||
"""
|
|
||||||
SET assignment statement.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
target: str = "",
|
|
||||||
value: str = ""
|
|
||||||
):
|
|
||||||
|
|
||||||
self.target = target
|
|
||||||
self.value = value
|
|
||||||
|
|
||||||
def accept(
|
|
||||||
self,
|
|
||||||
visitor
|
|
||||||
):
|
|
||||||
|
|
||||||
return visitor.visitSet(self)
|
|
||||||
|
|
||||||
|
|
||||||
class OpNode:
|
|
||||||
"""
|
|
||||||
.ADD. / .SUB. operation statement.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
op_type: str = "",
|
|
||||||
target: str = "",
|
|
||||||
value: str = ""
|
|
||||||
):
|
|
||||||
|
|
||||||
self.op_type = op_type
|
|
||||||
self.target = target
|
|
||||||
self.value = value
|
|
||||||
|
|
||||||
def accept(
|
|
||||||
self,
|
|
||||||
visitor
|
|
||||||
):
|
|
||||||
|
|
||||||
return visitor.visitOp(self)
|
|
||||||
|
|
||||||
|
|
||||||
class PassNode:
|
|
||||||
"""
|
|
||||||
PASS no-op statement.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def accept(
|
|
||||||
self,
|
|
||||||
visitor
|
|
||||||
):
|
|
||||||
|
|
||||||
return visitor.visitPass(self)
|
|
||||||
|
|
||||||
|
|
||||||
class UnrecogNode:
|
|
||||||
"""
|
|
||||||
Unrecognised line preserved for downstream error reporting.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
raw_line: str = ""
|
|
||||||
):
|
|
||||||
|
|
||||||
self.raw_line = raw_line
|
|
||||||
|
|
||||||
def accept(
|
|
||||||
self,
|
|
||||||
visitor
|
|
||||||
):
|
|
||||||
|
|
||||||
return visitor.visitUnrecog(self)
|
|
||||||
|
|
||||||
|
|
||||||
class NodeVisitor:
|
|
||||||
"""
|
|
||||||
Base visitor for the AutoScript AST.
|
|
||||||
|
|
||||||
Subclass and override visit* methods to implement
|
|
||||||
custom traversal logic. Default walks tree depth-first.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def visitScript(
|
|
||||||
self,
|
|
||||||
_node: Script
|
|
||||||
):
|
|
||||||
|
|
||||||
for child in _node.body:
|
|
||||||
child.accept(self)
|
|
||||||
|
|
||||||
def visitIf(
|
|
||||||
self,
|
|
||||||
_node: IfNode
|
|
||||||
):
|
|
||||||
|
|
||||||
for child in _node.body:
|
|
||||||
child.accept(self)
|
|
||||||
for elif_node in _node.elif_branches:
|
|
||||||
for child in elif_node.body:
|
|
||||||
child.accept(self)
|
|
||||||
for child in _node.else_body:
|
|
||||||
child.accept(self)
|
|
||||||
|
|
||||||
def visitSet(
|
|
||||||
self,
|
|
||||||
_node: SetNode
|
|
||||||
):
|
|
||||||
|
|
||||||
pass
|
|
||||||
|
|
||||||
def visitOp(
|
|
||||||
self,
|
|
||||||
_node: OpNode
|
|
||||||
):
|
|
||||||
|
|
||||||
pass
|
|
||||||
|
|
||||||
def visitPass(
|
|
||||||
self,
|
|
||||||
_node: PassNode
|
|
||||||
):
|
|
||||||
|
|
||||||
pass
|
|
||||||
|
|
||||||
def visitUnrecog(
|
|
||||||
self,
|
|
||||||
_node: UnrecogNode
|
|
||||||
):
|
|
||||||
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class LineStrategy:
|
|
||||||
"""
|
|
||||||
Encapsulates a regex pattern and its data-extraction handler.
|
|
||||||
Used by the tokenizer to classify a single line.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
pattern,
|
|
||||||
handler
|
|
||||||
):
|
|
||||||
|
|
||||||
self.pattern = pattern
|
|
||||||
self.handler = handler
|
|
||||||
|
|
||||||
def match(
|
|
||||||
self,
|
|
||||||
line: str
|
|
||||||
):
|
|
||||||
|
|
||||||
m = self.pattern.match(line)
|
|
||||||
if m:
|
|
||||||
return self.handler(m)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
# Strategy instances — one per recognised AutoScript syntax form
|
|
||||||
_LINE_STRATEGIES = [
|
|
||||||
LineStrategy(_RE_IF, lambda m: (K_IF, m.group(1))),
|
|
||||||
LineStrategy(_RE_ELSE_IF, lambda m: (K_ELSE_IF, m.group(1))),
|
|
||||||
LineStrategy(_RE_ELSE, lambda m: (K_ELSE, None)),
|
|
||||||
LineStrategy(_RE_ENDIF, lambda m: (K_ENDIF, None)),
|
|
||||||
LineStrategy(_RE_SET, lambda m: (K_SET, (m.group(1).strip(), m.group(2).strip()))),
|
|
||||||
LineStrategy(_RE_ADD, lambda m: (K_ADD, (m.group(1).strip(), m.group(2).strip()))),
|
|
||||||
LineStrategy(_RE_SUB, lambda m: (K_SUB, (m.group(1).strip(), m.group(2).strip()))),
|
|
||||||
LineStrategy(_RE_PASS, lambda m: (K_PASS, None)),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
class Stmt:
|
|
||||||
"""
|
|
||||||
Flat statement container, backward-compatible with the original
|
|
||||||
tokenize() output and the orchestration dialog's _classifyLine.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
kind: str | None = None,
|
|
||||||
condition: str | None = None,
|
|
||||||
target: str | None = None,
|
|
||||||
value: str | None = None,
|
|
||||||
op_type: str | None = None,
|
|
||||||
raw_line: str = ""
|
|
||||||
):
|
|
||||||
|
|
||||||
self.kind = kind
|
|
||||||
self.condition = condition
|
|
||||||
self.target = target
|
|
||||||
self.value = value
|
|
||||||
self.op_type = op_type
|
|
||||||
self.raw_line = raw_line
|
|
||||||
|
|
||||||
|
|
||||||
class ASTokenizer:
|
|
||||||
"""
|
|
||||||
Tokenizer / parser for the AutoScript DSL.
|
|
||||||
|
|
||||||
Main class-level entry points (engine-facing):
|
|
||||||
- classifyLine(line) — single-line classifier.
|
|
||||||
- tokenize(script) — flat Stmt list.
|
|
||||||
- parse(script) — structured AST (Script root).
|
|
||||||
|
|
||||||
Observer-enabled API (used by pre-check & orchestration):
|
|
||||||
>>> obs = ScriptPrecheckObserver()
|
|
||||||
>>> stmts = ASTokenizer.tokenizeWithObservers(script, [obs])
|
|
||||||
"""
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _notifyObservers(
|
|
||||||
cls,
|
|
||||||
observers: list,
|
|
||||||
method: str,
|
|
||||||
*args
|
|
||||||
):
|
|
||||||
|
|
||||||
for obs in observers:
|
|
||||||
getattr(obs, method)(*args)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _matchLine(
|
|
||||||
cls,
|
|
||||||
stripped: str
|
|
||||||
):
|
|
||||||
|
|
||||||
for strategy in _LINE_STRATEGIES:
|
|
||||||
result = strategy.match(stripped)
|
|
||||||
if result:
|
|
||||||
return result
|
|
||||||
return (None, None)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _buildStmt(
|
|
||||||
cls,
|
|
||||||
stripped: str,
|
|
||||||
kind: str | None,
|
|
||||||
data
|
|
||||||
) -> Stmt:
|
|
||||||
|
|
||||||
stmt = Stmt(kind=kind, raw_line=stripped)
|
|
||||||
if kind == K_IF or kind == K_ELSE_IF:
|
|
||||||
stmt.condition = data
|
|
||||||
elif kind == K_SET:
|
|
||||||
stmt.target, stmt.value = data
|
|
||||||
stmt.op_type = OP_SET
|
|
||||||
elif kind == K_ADD:
|
|
||||||
stmt.target, stmt.value = data
|
|
||||||
stmt.op_type = OP_ADD
|
|
||||||
elif kind == K_SUB:
|
|
||||||
stmt.target, stmt.value = data
|
|
||||||
stmt.op_type = OP_SUB
|
|
||||||
return stmt
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _stripComment(
|
|
||||||
cls,
|
|
||||||
line: str
|
|
||||||
) -> str:
|
|
||||||
|
|
||||||
in_single = False
|
|
||||||
for i, ch in enumerate(line):
|
|
||||||
if ch == "'":
|
|
||||||
in_single = not in_single
|
|
||||||
elif ch == "/" and i + 1 < len(line) and line[i + 1] == "/" and not in_single:
|
|
||||||
return line[:i].rstrip()
|
|
||||||
return line
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _tokenizeImpl(
|
|
||||||
cls,
|
|
||||||
script: str
|
|
||||||
) -> list:
|
|
||||||
|
|
||||||
statements = []
|
|
||||||
for raw_line in script.split("\n"):
|
|
||||||
code = cls._stripComment(raw_line.strip())
|
|
||||||
if not code:
|
|
||||||
continue
|
|
||||||
kind, data = cls._matchLine(code)
|
|
||||||
statements.append(cls._buildStmt(code, kind, data))
|
|
||||||
return statements
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _parseTokens(
|
|
||||||
cls,
|
|
||||||
tokens: list
|
|
||||||
) -> Script:
|
|
||||||
|
|
||||||
body = []
|
|
||||||
i = 0
|
|
||||||
while i < len(tokens):
|
|
||||||
tok = tokens[i]
|
|
||||||
kind = tok.kind
|
|
||||||
|
|
||||||
if kind == K_IF:
|
|
||||||
node, consumed = cls._parseIfBlock(tokens, i)
|
|
||||||
body.append(node)
|
|
||||||
i += consumed
|
|
||||||
elif kind in (K_ELSE_IF, K_ELSE, K_ENDIF):
|
|
||||||
i += 1
|
|
||||||
elif kind == K_SET:
|
|
||||||
body.append(SetNode(target=tok.target, value=tok.value))
|
|
||||||
i += 1
|
|
||||||
elif kind in (K_ADD, K_SUB):
|
|
||||||
body.append(OpNode(
|
|
||||||
op_type=tok.op_type,
|
|
||||||
target=tok.target,
|
|
||||||
value=tok.value
|
|
||||||
))
|
|
||||||
i += 1
|
|
||||||
elif kind == K_PASS:
|
|
||||||
body.append(PassNode())
|
|
||||||
i += 1
|
|
||||||
else:
|
|
||||||
body.append(UnrecogNode(raw_line=tok.raw_line))
|
|
||||||
i += 1
|
|
||||||
return Script(body=body)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def classifyLine(
|
|
||||||
cls,
|
|
||||||
stripped: str
|
|
||||||
):
|
|
||||||
|
|
||||||
kind, data = cls._matchLine(stripped)
|
|
||||||
if kind is None or kind == K_PASS:
|
|
||||||
return None
|
|
||||||
return (kind, data)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def tokenize(
|
|
||||||
cls,
|
|
||||||
script: str
|
|
||||||
) -> list:
|
|
||||||
|
|
||||||
return cls._tokenizeImpl(script)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def parse(
|
|
||||||
cls,
|
|
||||||
script: str
|
|
||||||
) -> Script:
|
|
||||||
|
|
||||||
return cls._parseTokens(cls._tokenizeImpl(script))
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def tokenizeWithObservers(
|
|
||||||
cls,
|
|
||||||
script: str,
|
|
||||||
observers: list
|
|
||||||
) -> list:
|
|
||||||
"""
|
|
||||||
Tokenize and notify observers for each classified line.
|
|
||||||
|
|
||||||
Fires onParseStart, onTokenParsed, and onParseComplete
|
|
||||||
events to each observer. This is the single tokenization
|
|
||||||
pipeline shared by pre-check and orchestration modules.
|
|
||||||
"""
|
|
||||||
|
|
||||||
cls._notifyObservers(observers, "onParseStart", script)
|
|
||||||
statements = []
|
|
||||||
for i, raw_line in enumerate(script.split("\n"), 1):
|
|
||||||
code = cls._stripComment(raw_line.strip())
|
|
||||||
if not code:
|
|
||||||
continue
|
|
||||||
kind, data = cls._matchLine(code)
|
|
||||||
cls._notifyObservers(observers, "onTokenParsed", kind, data, i, code)
|
|
||||||
statements.append(cls._buildStmt(code, kind, data))
|
|
||||||
cls._notifyObservers(observers, "onParseComplete", statements)
|
|
||||||
return statements
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def parseWithObservers(
|
|
||||||
cls,
|
|
||||||
script: str,
|
|
||||||
observers: list
|
|
||||||
) -> Script:
|
|
||||||
"""
|
|
||||||
Parse and notify observers throughout the pipeline.
|
|
||||||
|
|
||||||
Calls tokenizeWithObservers (which fires per-token events),
|
|
||||||
then builds the AST and fires onASTReady.
|
|
||||||
"""
|
|
||||||
|
|
||||||
tokens = cls.tokenizeWithObservers(script, observers)
|
|
||||||
ast = cls._parseTokens(tokens)
|
|
||||||
cls._notifyObservers(observers, "onASTReady", ast)
|
|
||||||
return ast
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _parseIfBlock(
|
|
||||||
cls,
|
|
||||||
tokens: list,
|
|
||||||
start: int
|
|
||||||
):
|
|
||||||
|
|
||||||
first = tokens[start]
|
|
||||||
node = IfNode(condition=first.condition or "")
|
|
||||||
body = []
|
|
||||||
elif_branches = []
|
|
||||||
else_body = []
|
|
||||||
current_target = body
|
|
||||||
i = start + 1
|
|
||||||
|
|
||||||
while i < len(tokens):
|
|
||||||
tok = tokens[i]
|
|
||||||
kind = tok.kind
|
|
||||||
if kind == K_IF:
|
|
||||||
sub_node, consumed = cls._parseIfBlock(tokens, i)
|
|
||||||
current_target.append(sub_node)
|
|
||||||
i += consumed
|
|
||||||
elif kind == K_ELSE_IF:
|
|
||||||
elif_branches.append(ElifNode(condition=tok.condition or ""))
|
|
||||||
current_target = elif_branches[-1].body
|
|
||||||
i += 1
|
|
||||||
elif kind == K_ELSE:
|
|
||||||
else_body = []
|
|
||||||
current_target = else_body
|
|
||||||
i += 1
|
|
||||||
elif kind == K_ENDIF:
|
|
||||||
node.body = body
|
|
||||||
node.elif_branches = elif_branches
|
|
||||||
node.else_body = else_body
|
|
||||||
return (node, i - start + 1)
|
|
||||||
elif kind == K_SET:
|
|
||||||
current_target.append(SetNode(target=tok.target, value=tok.value))
|
|
||||||
i += 1
|
|
||||||
elif kind in (K_ADD, K_SUB):
|
|
||||||
current_target.append(OpNode(
|
|
||||||
op_type=tok.op_type,
|
|
||||||
target=tok.target,
|
|
||||||
value=tok.value
|
|
||||||
))
|
|
||||||
i += 1
|
|
||||||
elif kind == K_PASS:
|
|
||||||
current_target.append(PassNode())
|
|
||||||
i += 1
|
|
||||||
else:
|
|
||||||
current_target.append(UnrecogNode(raw_line=tok.raw_line))
|
|
||||||
i += 1
|
|
||||||
node.body = body
|
|
||||||
node.elif_branches = elif_branches
|
|
||||||
node.else_body = else_body
|
|
||||||
node.closed = False
|
|
||||||
return (node, i - start)
|
|
||||||
@@ -1,62 +1,23 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
AutoScript module for the AutoLibrary project.
|
Copyright (c) 2026 KenanZhu.
|
||||||
A lightweight scripting DSL for preprocessing user reservation data.
|
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 autoscript.ASTokenizer import (
|
from .ASEngine import ASEngine
|
||||||
ASTokenizer,
|
|
||||||
Stmt,
|
|
||||||
ElifNode,
|
|
||||||
Script,
|
|
||||||
IfNode,
|
|
||||||
SetNode,
|
|
||||||
OpNode,
|
|
||||||
)
|
|
||||||
from autoscript.ASEngine import (
|
|
||||||
execute,
|
|
||||||
addTargetVar,
|
|
||||||
splitTopLevel,
|
|
||||||
)
|
|
||||||
from autoscript.ASObject import _META_VARS as META_VARS
|
|
||||||
from autoscript.ASObserver import ParsingObserver
|
|
||||||
|
|
||||||
|
__version__ = "1.0.0" # autoscript version
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"execute",
|
|
||||||
"addTargetVar",
|
|
||||||
"splitTopLevel",
|
|
||||||
"registerDefaultTargetVars",
|
|
||||||
"buildMockTargetData",
|
|
||||||
"META_VARS",
|
|
||||||
"ALL_VARIABLES",
|
|
||||||
"ASTokenizer",
|
|
||||||
"Stmt",
|
|
||||||
"Script",
|
|
||||||
"IfNode",
|
|
||||||
"SetNode",
|
|
||||||
"OpNode",
|
|
||||||
"ElifNode",
|
|
||||||
"ParsingObserver",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
# Key paths into target_data dict for each target variable.
|
|
||||||
# (name, type, key_path, display_name)
|
|
||||||
_TARGET_VAR_DEFS = [
|
_TARGET_VAR_DEFS = [
|
||||||
("USERNAME", "String",["username"], "用户名"),
|
("USERNAME", "String", ["username"], "用户名"),
|
||||||
("USER_ENABLE", "Boolean",["enabled"], "用户启用"),
|
("USER_ENABLE", "Boolean", ["enabled"], "用户启用"),
|
||||||
("RESERVE_DATE", "Date", ["reserve_info", "date"], "预约日期"),
|
("RESERVE_DATE", "Date", ["reserve_info", "date"], "预约日期"),
|
||||||
("RESERVE_BEGIN_TIME", "Time", ["reserve_info", "begin_time", "time"], "预约开始时间"),
|
("RESERVE_BEGIN_TIME", "Time", ["reserve_info", "begin_time", "time"], "预约开始时间"),
|
||||||
("RESERVE_END_TIME", "Time", ["reserve_info", "end_time", "time"], "预约结束时间"),
|
("RESERVE_END_TIME", "Time", ["reserve_info", "end_time", "time"], "预约结束时间"),
|
||||||
]
|
]
|
||||||
|
|
||||||
# All variables (display_name -> (name, type)), derived from target vars + meta vars.
|
|
||||||
ALL_VARIABLES = {
|
|
||||||
display_name: (name, var_type)
|
|
||||||
for name, var_type, _, display_name in _TARGET_VAR_DEFS
|
|
||||||
} | {
|
|
||||||
obj.display_name: (obj.name, obj.var_type)
|
|
||||||
for obj in META_VARS.values()
|
|
||||||
}
|
|
||||||
_MOCK_TYPE_VALUES = {
|
_MOCK_TYPE_VALUES = {
|
||||||
"String": "__mock__",
|
"String": "__mock__",
|
||||||
"Boolean": True,
|
"Boolean": True,
|
||||||
@@ -67,27 +28,31 @@ _MOCK_TYPE_VALUES = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def buildMockTargetData(
|
def createAllVariablesTable(
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""
|
|
||||||
Build a target_data dict filled with type-appropriate mock values
|
return {
|
||||||
for all registered target variables.
|
displayName: (name, varType)
|
||||||
"""
|
for name, varType, _, displayName in _TARGET_VAR_DEFS
|
||||||
|
}
|
||||||
|
|
||||||
|
def createTargetVarDefs(
|
||||||
|
) -> list:
|
||||||
|
|
||||||
|
return list(_TARGET_VAR_DEFS)
|
||||||
|
|
||||||
|
def createMockTargetData(
|
||||||
|
) -> dict:
|
||||||
|
|
||||||
data = {}
|
data = {}
|
||||||
for _, var_type, key_path, _ in _TARGET_VAR_DEFS:
|
for _, varType, keyPath, _ in _TARGET_VAR_DEFS:
|
||||||
d = data
|
d = data
|
||||||
for key in key_path[:-1]:
|
for key in keyPath[:-1]:
|
||||||
d = d.setdefault(key, {})
|
d = d.setdefault(key, {})
|
||||||
d[key_path[-1]] = _MOCK_TYPE_VALUES.get(var_type, "")
|
d[keyPath[-1]] = _MOCK_TYPE_VALUES.get(varType, "")
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
def createEngine(
|
||||||
|
) -> ASEngine:
|
||||||
|
|
||||||
def registerDefaultTargetVars(
|
return ASEngine(_TARGET_VAR_DEFS)
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Register all built-in target variables with the engine.
|
|
||||||
This must be called before any script execution.
|
|
||||||
Calling multiple times is idempotent (re-registers same keys).
|
|
||||||
"""
|
|
||||||
for name, var_type, key_path, display_name in _TARGET_VAR_DEFS:
|
|
||||||
addTargetVar(name, var_type, key_path, display_name)
|
|
||||||
@@ -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 queue
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
import managers.log.LogManager as LogManager
|
from managers.log.LogManager import getLogger
|
||||||
|
|
||||||
|
|
||||||
class MsgBase:
|
class MsgBase:
|
||||||
@@ -54,11 +54,10 @@ class MsgBase:
|
|||||||
self._input_queue = input_queue
|
self._input_queue = input_queue
|
||||||
self._output_queue = output_queue
|
self._output_queue = output_queue
|
||||||
try:
|
try:
|
||||||
self._logger = LogManager.getLogger(self._class_name)
|
self._logger = getLogger(self._class_name)
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
self._logger = None
|
self._logger = None
|
||||||
|
|
||||||
|
|
||||||
def _showMsg(
|
def _showMsg(
|
||||||
self,
|
self,
|
||||||
msg: str
|
msg: str
|
||||||
@@ -66,7 +65,6 @@ class MsgBase:
|
|||||||
|
|
||||||
self._output_queue.put(f"[{self._class_name:<15}] >>> : {msg}")
|
self._output_queue.put(f"[{self._class_name:<15}] >>> : {msg}")
|
||||||
|
|
||||||
|
|
||||||
def _showTrace(
|
def _showTrace(
|
||||||
self,
|
self,
|
||||||
msg: str,
|
msg: str,
|
||||||
@@ -79,7 +77,6 @@ class MsgBase:
|
|||||||
if self._logger and not no_log:
|
if self._logger and not no_log:
|
||||||
self._logger.log(level, msg)
|
self._logger.log(level, msg)
|
||||||
|
|
||||||
|
|
||||||
def _showLog(
|
def _showLog(
|
||||||
self,
|
self,
|
||||||
msg: str,
|
msg: str,
|
||||||
@@ -89,7 +86,6 @@ class MsgBase:
|
|||||||
if self._logger:
|
if self._logger:
|
||||||
self._logger.log(level, msg)
|
self._logger.log(level, msg)
|
||||||
|
|
||||||
|
|
||||||
def _waitMsg(
|
def _waitMsg(
|
||||||
self,
|
self,
|
||||||
timeout: float = 1.0
|
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:
|
This software is provided "as is", without any warranty of any kind.
|
||||||
- MsgBase: Base class for messages.\
|
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||||
- LibOperator: Base class for library operators.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
@@ -10,13 +10,19 @@ See the LICENSE file for details.
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
from PySide6.QtCore import QStandardPaths, QDir
|
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.config.ConfigManager import instance as configInstance
|
||||||
from managers.driver.WebDriverManager import instance as webdriverInstance
|
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:
|
) -> bool:
|
||||||
|
|
||||||
app_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
|
app_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppDataLocation)
|
||||||
@@ -27,7 +33,7 @@ def initializeLogManager(
|
|||||||
logInstance(log_dir)
|
logInstance(log_dir)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def initializeConfigManager(
|
def _initializeConfigManager(
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
|
||||||
logger = logInstance().getLogger("AppInitializer")
|
logger = logInstance().getLogger("AppInitializer")
|
||||||
@@ -49,7 +55,7 @@ def initializeConfigManager(
|
|||||||
configInstance(new_config_dir)
|
configInstance(new_config_dir)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def initializeWebDriverManager(
|
def _initializeWebDriverManager(
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
|
||||||
logger = logInstance().getLogger("AppInitializer")
|
logger = logInstance().getLogger("AppInitializer")
|
||||||
@@ -64,13 +70,43 @@ def initializeWebDriverManager(
|
|||||||
webdriverInstance(driver_dir)
|
webdriverInstance(driver_dir)
|
||||||
return True
|
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(
|
def initializeApp(
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
"""
|
||||||
|
Initialize the application components
|
||||||
|
|
||||||
if not initializeLogManager():
|
Order:
|
||||||
|
LogManager -> ConfigManager -> WebDriverManager -> Appearance
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not _initializeLogManager():
|
||||||
return False
|
return False
|
||||||
if not initializeConfigManager():
|
if not _initializeConfigManager():
|
||||||
return False
|
return False
|
||||||
if not initializeWebDriverManager():
|
if not _initializeWebDriverManager():
|
||||||
return False
|
return False
|
||||||
|
_initializeAppearance()
|
||||||
return True
|
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:
|
This software is provided "as is", without any warranty of any kind.
|
||||||
- AppInitializer: Application initializer class.
|
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
|
import platform
|
||||||
|
|
||||||
from PySide6.QtGui import (
|
|
||||||
QIcon, QFont
|
|
||||||
)
|
|
||||||
from PySide6.QtWidgets import (
|
|
||||||
QDialog, QApplication
|
|
||||||
)
|
|
||||||
from PySide6.QtCore import (
|
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 (
|
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.ui.Ui_ALAboutDialog import Ui_ALAboutDialog
|
||||||
from gui.resources import ALResource
|
from gui.resources import ALResource
|
||||||
@@ -38,19 +43,28 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
|||||||
self.modifyUi()
|
self.modifyUi()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
|
|
||||||
|
|
||||||
def modifyUi(
|
def modifyUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.LogoIconLabel.setPixmap(QIcon(":/res/icon/icons/AutoLibrary_32x32.ico").pixmap(48, 48))
|
self.LogoIconLabel.setPixmap(QIcon(":/res/icons/AutoLibrary_Logo_64.svg").pixmap(48, 48))
|
||||||
info_text = self.generateAboutText()
|
self.TabWidget = QTabWidget()
|
||||||
self.AboutInfoBrowser.setHtml(info_text)
|
self.TabWidget.setDocumentMode(True)
|
||||||
browser_font = self.AboutInfoBrowser.font()
|
AboutBrowser = QTextBrowser()
|
||||||
browser_font.setFamily("Courier New")
|
AboutBrowser.setHtml(self.generateAboutText())
|
||||||
self.AboutInfoBrowser.setFont(browser_font)
|
AboutBrowser.setOpenExternalLinks(True)
|
||||||
self.AboutInfoBrowser.setTextInteractionFlags(Qt.TextBrowserInteraction)
|
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(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
@@ -58,39 +72,61 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
|||||||
|
|
||||||
self.CopyButton.clicked.connect(self.copyAboutInfo)
|
self.CopyButton.clicked.connect(self.copyAboutInfo)
|
||||||
|
|
||||||
|
|
||||||
def generateAboutText(
|
def generateAboutText(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
|
|
||||||
os_info = self.getOSInfo()
|
os_info = self.getOSInfo()
|
||||||
|
run_on = f"{os_info['system']} {os_info['version']} {os_info['architecture']}"
|
||||||
|
selenium_ver = self.getSeleniumVersion()
|
||||||
about_text = f"""
|
about_text = f"""
|
||||||
<h4>Version Information:</h4>
|
<b style="font-size:14px;">VERSION: {AL_VERSION}</b><br>
|
||||||
Version: {AL_VERSION}<br>
|
|
||||||
Commit SHA: {AL_COMMIT_SHA}<br>
|
Commit SHA: {AL_COMMIT_SHA}<br>
|
||||||
Commit date: {AL_COMMIT_DATE}<br>
|
Commit date: {AL_COMMIT_DATE}<br>
|
||||||
Build date: {AL_BUILD_DATE}<br>
|
Build date: {AL_BUILD_DATE}<br>
|
||||||
Python version: {platform.python_version()}<br>
|
<br>
|
||||||
Qt version: {self.getQtVersion()}<br>
|
<b style="font-size:14px;">SYSTEM</b><br>
|
||||||
|
Running on: {run_on}<br>
|
||||||
<h4>System Information:</h4>
|
|
||||||
Processor: {platform.processor()}<br>
|
Processor: {platform.processor()}<br>
|
||||||
Operating system: {os_info['system']}<br>
|
<br>
|
||||||
System version: {os_info['version']}<br>
|
<b style="font-size:14px;">DEPENDENCIES</b><br>
|
||||||
System architecture: {os_info['architecture']}<br>
|
Python: {platform.python_version()}<br>
|
||||||
|
Qt(PySide6): {self.getQtVersion()}<br>
|
||||||
<h4>Project Information:</h4>
|
Selenium: {selenium_ver}<br>
|
||||||
License: MIT License<br>
|
<br>
|
||||||
Project repository: <a href="https://www.github.com/KenanZhu/AutoLibrary" style="text-decoration: none;">https://www.github.com/KenanZhu/AutoLibrary</a><br>
|
<b style="font-size:14px;">PROJECT</b><br>
|
||||||
Project website: <a href="https://www.autolibrary.kenanzhu.com" style="text-decoration: none;">https://www.autolibrary.kenanzhu.com</a><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>
|
||||||
<h4>Author Information:</h4>
|
<br>
|
||||||
Developer: KenanZhu<br>
|
<b style="font-size:14px;">AUTHOR</b><br>
|
||||||
Contact: nanoki_zh@163.com<br>
|
Developer/Maintainer: KenanZhu<br>
|
||||||
GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;">https://www.github.com/KenanZhu</a><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
|
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(
|
def getOSInfo(
|
||||||
self
|
self
|
||||||
@@ -99,7 +135,6 @@ GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;"
|
|||||||
system = platform.system()
|
system = platform.system()
|
||||||
version = platform.version()
|
version = platform.version()
|
||||||
architecture = platform.architecture()[0]
|
architecture = platform.architecture()[0]
|
||||||
|
|
||||||
if system == "Windows":
|
if system == "Windows":
|
||||||
try:
|
try:
|
||||||
version = platform.win32_ver()[1]
|
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()}"
|
version = f"{distro.name()} {distro.version()}"
|
||||||
except ImportError:
|
except ImportError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
return {
|
return {
|
||||||
'system': system,
|
'system': system,
|
||||||
'version': version,
|
'version': version,
|
||||||
'architecture': architecture
|
'architecture': architecture
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def getQtVersion(
|
def getQtVersion(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -134,14 +167,23 @@ GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;"
|
|||||||
except:
|
except:
|
||||||
return "Unknown"
|
return "Unknown"
|
||||||
|
|
||||||
|
def getSeleniumVersion(
|
||||||
|
self
|
||||||
|
):
|
||||||
|
|
||||||
|
try:
|
||||||
|
import selenium
|
||||||
|
return selenium.__version__
|
||||||
|
except Exception:
|
||||||
|
return "Unknown"
|
||||||
|
|
||||||
def copyAboutInfo(
|
def copyAboutInfo(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
about_text = self.AboutInfoBrowser.toPlainText()
|
about_text = self.TabWidget.currentWidget().toPlainText()
|
||||||
clipboard = QApplication.clipboard()
|
Clipboard = QApplication.clipboard()
|
||||||
clipboard.setText(about_text)
|
Clipboard.setText(about_text)
|
||||||
original_text = self.CopyButton.text()
|
original_text = self.CopyButton.text()
|
||||||
self.CopyButton.setText("已复制")
|
self.CopyButton.setText("已复制")
|
||||||
QTimer.singleShot(2000, lambda: self.CopyButton.setText(original_text))
|
QTimer.singleShot(2000, lambda: self.CopyButton.setText(original_text))
|
||||||
@@ -7,7 +7,18 @@ 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.
|
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||||
See the LICENSE file for details.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
from PySide6.QtCore import Qt, Slot
|
from copy import deepcopy
|
||||||
|
|
||||||
|
import qtawesome as qta
|
||||||
|
|
||||||
|
from PySide6.QtCore import (
|
||||||
|
QDate,
|
||||||
|
QSize,
|
||||||
|
Qt,
|
||||||
|
QTime,
|
||||||
|
QTimer,
|
||||||
|
Slot
|
||||||
|
)
|
||||||
from PySide6.QtGui import (
|
from PySide6.QtGui import (
|
||||||
QColor,
|
QColor,
|
||||||
QFont,
|
QFont,
|
||||||
@@ -16,24 +27,45 @@ from PySide6.QtGui import (
|
|||||||
)
|
)
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
QApplication,
|
QApplication,
|
||||||
|
QComboBox,
|
||||||
|
QDateEdit,
|
||||||
QDialog,
|
QDialog,
|
||||||
QDialogButtonBox,
|
QDialogButtonBox,
|
||||||
|
QDoubleSpinBox,
|
||||||
|
QFormLayout,
|
||||||
|
QFrame,
|
||||||
QGridLayout,
|
QGridLayout,
|
||||||
|
QGroupBox,
|
||||||
QHBoxLayout,
|
QHBoxLayout,
|
||||||
|
QHeaderView,
|
||||||
QLabel,
|
QLabel,
|
||||||
|
QLineEdit,
|
||||||
|
QMessageBox,
|
||||||
QPlainTextEdit,
|
QPlainTextEdit,
|
||||||
QPushButton,
|
QPushButton,
|
||||||
|
QSpinBox,
|
||||||
|
QSplitter,
|
||||||
QStyle,
|
QStyle,
|
||||||
QTabWidget,
|
QTabWidget,
|
||||||
|
QTableWidget,
|
||||||
|
QTableWidgetItem,
|
||||||
|
QTimeEdit,
|
||||||
QVBoxLayout,
|
QVBoxLayout,
|
||||||
QWidget,
|
QWidget,
|
||||||
)
|
)
|
||||||
|
|
||||||
from autoscript import ALL_VARIABLES
|
from autoscript import (
|
||||||
|
createAllVariablesTable,
|
||||||
|
createMockTargetData,
|
||||||
|
createTargetVarDefs,
|
||||||
|
createEngine,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class ALScriptHighlighter(QSyntaxHighlighter):
|
class ALScriptHighlighter(QSyntaxHighlighter):
|
||||||
|
"""
|
||||||
|
Syntax highlighter for Lua-based AutoScript.
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -43,48 +75,54 @@ class ALScriptHighlighter(QSyntaxHighlighter):
|
|||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self._rules = []
|
self._rules = []
|
||||||
|
|
||||||
keywordFmt = QTextCharFormat()
|
keyword_fmt = QTextCharFormat()
|
||||||
keywordFmt.setForeground(QColor("#569CD6"))
|
keyword_fmt.setForeground(QColor("#569CD6"))
|
||||||
keywordFmt.setFontWeight(QFont.Weight.Bold)
|
keyword_fmt.setFontWeight(QFont.Weight.Bold)
|
||||||
for kw in ["IF", "ELSE IF", "ELSE", "ENDIF", "END IF",
|
for kw in [
|
||||||
"SET", "PASS", "THEN"]:
|
"if", "elseif", "else", "end", "then",
|
||||||
pattern = r"\b" + kw.replace(" ", r"\s+") + r"\b"
|
"and", "or", "not",
|
||||||
self._rules.append((pattern, keywordFmt))
|
"local", "function", "return", "nil",
|
||||||
opFmt = QTextCharFormat()
|
]:
|
||||||
opFmt.setForeground(QColor("#C586C0"))
|
self._rules.append((r"\b" + kw + r"\b", keyword_fmt))
|
||||||
opFmt.setFontWeight(QFont.Weight.Normal)
|
bool_fmt = QTextCharFormat()
|
||||||
for op in [r"\.EQ\.", r"\.NEQ\.", r"\.BGT\.", r"\.BLT\.",
|
bool_fmt.setForeground(QColor("#4FC1FF"))
|
||||||
r"\.BGE\.", r"\.BLE\.", r"\.ADD\.", r"\.SUB\.",
|
bool_fmt.setFontWeight(QFont.Weight.Bold)
|
||||||
r"\.AND\.", r"\.OR\."]:
|
self._rules.append((r"\btrue\b", bool_fmt))
|
||||||
self._rules.append((op, opFmt))
|
self._rules.append((r"\bfalse\b", bool_fmt))
|
||||||
boolFmt = QTextCharFormat()
|
cmp_fmt = QTextCharFormat()
|
||||||
boolFmt.setForeground(QColor("#4FC1FF"))
|
cmp_fmt.setForeground(QColor("#C586C0"))
|
||||||
boolFmt.setFontWeight(QFont.Weight.Bold)
|
cmp_fmt.setFontWeight(QFont.Weight.Normal)
|
||||||
self._rules.append((r"\.TRUE\.", boolFmt))
|
for op in [r"==", r"~=", r">=", r"<=", r">", r"<"]:
|
||||||
self._rules.append((r"\.FALSE\.", boolFmt))
|
self._rules.append((op, cmp_fmt))
|
||||||
funcFmt = QTextCharFormat()
|
arith_fmt = QTextCharFormat()
|
||||||
funcFmt.setForeground(QColor("#DCDCAA"))
|
arith_fmt.setForeground(QColor("#C586C0"))
|
||||||
funcFmt.setFontWeight(QFont.Weight.Normal)
|
arith_fmt.setFontWeight(QFont.Weight.Normal)
|
||||||
self._rules.append((r"\b(?:DATE|TIME)\b", funcFmt))
|
for op in [r"\+", r"-", r"\*", r"/", r"\.\."]:
|
||||||
varFmt = QTextCharFormat()
|
self._rules.append((op, arith_fmt))
|
||||||
varFmt.setForeground(QColor("#9CDCFE"))
|
func_fmt = QTextCharFormat()
|
||||||
varFmt.setFontWeight(QFont.Weight.Normal)
|
func_fmt.setForeground(QColor("#DCDCAA"))
|
||||||
var_names = [name for _, (name, _) in ALL_VARIABLES.items()]
|
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:
|
for var in var_names:
|
||||||
self._rules.append((r"\b" + var + r"\b", varFmt))
|
self._rules.append((r"\b" + var + r"\b", var_fmt))
|
||||||
strFmt = QTextCharFormat()
|
st_fmt = QTextCharFormat()
|
||||||
strFmt.setForeground(QColor("#CE9178"))
|
st_fmt.setForeground(QColor("#CE9178"))
|
||||||
strFmt.setFontWeight(QFont.Weight.Normal)
|
st_fmt.setFontWeight(QFont.Weight.Normal)
|
||||||
self._rules.append((r"'[^']*'", strFmt))
|
self._rules.append((r'"[^"]*"', st_fmt))
|
||||||
numFmt = QTextCharFormat()
|
self._rules.append((r"'[^']*'", st_fmt))
|
||||||
numFmt.setForeground(QColor("#B5CEA8"))
|
num_fmt = QTextCharFormat()
|
||||||
numFmt.setFontWeight(QFont.Weight.Normal)
|
num_fmt.setForeground(QColor("#B5CEA8"))
|
||||||
self._rules.append((r"\b\d+\b", numFmt))
|
num_fmt.setFontWeight(QFont.Weight.Normal)
|
||||||
commentFmt = QTextCharFormat()
|
self._rules.append((r"\b\d+(?:\.\d+)?\b", num_fmt))
|
||||||
commentFmt.setForeground(QColor("#6A9955"))
|
comment_fmt = QTextCharFormat()
|
||||||
commentFmt.setFontItalic(True)
|
comment_fmt.setForeground(QColor("#6A9955"))
|
||||||
self._rules.append((r"//[^\n]*", commentFmt))
|
comment_fmt.setFontItalic(True)
|
||||||
|
self._rules.append((r"--[^\n]*", comment_fmt))
|
||||||
|
|
||||||
def highlightBlock(
|
def highlightBlock(
|
||||||
self,
|
self,
|
||||||
@@ -99,174 +137,256 @@ class ALScriptHighlighter(QSyntaxHighlighter):
|
|||||||
self.setFormat(start, length, fmt)
|
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):
|
class ALAutoScriptEditDialog(QDialog):
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
parent = None,
|
parent = None,
|
||||||
script: str = ""
|
script: str = "",
|
||||||
|
mockData: dict = None
|
||||||
):
|
):
|
||||||
|
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self._fontSize = 19
|
self._font_size = 21
|
||||||
|
self._mock_widgets = {}
|
||||||
|
|
||||||
self.setupUi()
|
self.setupUi()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
self.textEdit.setPlainText(script)
|
self.TextEdit.setPlainText(script)
|
||||||
self._highlighter = ALScriptHighlighter(
|
self._high_lighter = ALScriptHighlighter(
|
||||||
self.textEdit.document()
|
self.TextEdit.document()
|
||||||
)
|
)
|
||||||
|
if mockData:
|
||||||
|
self.setMockData(mockData)
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.setWindowTitle("AutoScript 编辑 - AutoLibrary")
|
self.setWindowTitle("AutoScript 编辑 - AutoLibrary")
|
||||||
self.setMinimumSize(640, 600)
|
self.setMinimumSize(660, 600)
|
||||||
layout = QVBoxLayout(self)
|
Layout = QVBoxLayout(self)
|
||||||
layout.setSpacing(4)
|
Layout.setSpacing(3)
|
||||||
layout.setContentsMargins(4, 4, 4, 4)
|
Layout.setContentsMargins(3, 3, 3, 3)
|
||||||
toolbarLayout = QHBoxLayout()
|
ToolbarLayout = QHBoxLayout()
|
||||||
self.zoomInBtn = QPushButton("+")
|
self.ZoomInBtn = QPushButton("")
|
||||||
self.zoomInBtn.setFixedSize(25, 25)
|
self.ZoomInBtn.setIcon(qta.icon("fa6s.plus", color=self._iconColor()))
|
||||||
self.zoomOutBtn = QPushButton("-")
|
self.ZoomInBtn.setIconSize(QSize(14, 14))
|
||||||
self.zoomOutBtn.setFixedSize(25, 25)
|
self.ZoomInBtn.setFixedSize(25, 25)
|
||||||
self.zoomResetBtn = QPushButton(
|
self.ZoomOutBtn = QPushButton("")
|
||||||
QApplication.style().standardIcon(
|
self.ZoomOutBtn.setIcon(qta.icon("fa6s.minus", color=self._iconColor()))
|
||||||
QStyle.StandardPixmap.SP_BrowserReload
|
self.ZoomOutBtn.setIconSize(QSize(14, 14))
|
||||||
), ""
|
self.ZoomOutBtn.setFixedSize(25, 25)
|
||||||
)
|
self.ZoomResetBtn = QPushButton("")
|
||||||
self.zoomResetBtn.setFixedSize(25, 25)
|
self.ZoomResetBtn.setIcon(qta.icon("fa6s.rotate-left", color=self._iconColor()))
|
||||||
self.zoomResetBtn.setToolTip("重置缩放")
|
self.ZoomResetBtn.setIconSize(QSize(14, 14))
|
||||||
self.zoomLabel = QLabel(f"{self._fontSize}px")
|
self.ZoomResetBtn.setFixedSize(25, 25)
|
||||||
self.zoomLabel.setFixedHeight(25)
|
self.ZoomResetBtn.setToolTip("重置缩放")
|
||||||
toolbarLayout.addWidget(self.zoomInBtn)
|
self.ZoomLabel = QLabel(f"{self._font_size}px")
|
||||||
toolbarLayout.addWidget(self.zoomOutBtn)
|
self.ZoomLabel.setFixedHeight(25)
|
||||||
toolbarLayout.addWidget(self.zoomResetBtn)
|
self.OrchBtn = QPushButton("编排")
|
||||||
toolbarLayout.addWidget(self.zoomLabel)
|
self.OrchBtn.setFixedSize(80, 25)
|
||||||
toolbarLayout.addStretch()
|
self.OrchBtn.setToolTip("可视化生成 AutoScript 代码并插入到光标位置")
|
||||||
self.copyBtn = QPushButton(
|
ToolbarLayout.addWidget(self.OrchBtn)
|
||||||
QApplication.style().standardIcon(
|
self.DebugBtn = QPushButton("▶ 调试运行")
|
||||||
QStyle.StandardPixmap.SP_FileDialogDetailedView
|
self.DebugBtn.setFixedSize(80, 25)
|
||||||
), ""
|
self.DebugBtn.setToolTip("使用右侧模拟数据执行脚本,查看目标变量变化")
|
||||||
)
|
ToolbarLayout.addWidget(self.DebugBtn)
|
||||||
self.copyBtn.setFixedSize(25, 25)
|
Sep = QFrame()
|
||||||
self.copyBtn.setToolTip("复制脚本")
|
Sep.setFrameShape(QFrame.Shape.VLine)
|
||||||
toolbarLayout.addWidget(self.copyBtn)
|
Sep.setFrameShadow(QFrame.Shadow.Sunken)
|
||||||
layout.addLayout(toolbarLayout)
|
Sep.setFixedWidth(1)
|
||||||
self.textEdit = QPlainTextEdit(self)
|
ToolbarLayout.addWidget(Sep)
|
||||||
self.textEdit.setLineWrapMode(
|
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
|
QPlainTextEdit.LineWrapMode.NoWrap
|
||||||
)
|
)
|
||||||
self.textEdit.setStyleSheet(
|
self.TextEdit.setStyleSheet(
|
||||||
"QPlainTextEdit {"
|
"QPlainTextEdit {"
|
||||||
" font-family: 'Courier New', 'Consolas', monospace;"
|
" font-family: 'Courier New', 'Consolas', monospace;"
|
||||||
f" font-size: {self._fontSize}px;"
|
f" font-size: {self._font_size}px;"
|
||||||
"}"
|
"}"
|
||||||
)
|
)
|
||||||
layout.addWidget(self.textEdit)
|
Layout.addWidget(self.TextEdit)
|
||||||
self._createButtonPanel(layout)
|
self.createButtonPanel(Layout)
|
||||||
self.btnBox = QDialogButtonBox(
|
self.BtnBox = QDialogButtonBox(
|
||||||
QDialogButtonBox.StandardButton.Ok |
|
QDialogButtonBox.StandardButton.Ok |
|
||||||
QDialogButtonBox.StandardButton.Cancel
|
QDialogButtonBox.StandardButton.Cancel
|
||||||
)
|
)
|
||||||
self.btnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||||
self.btnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setFixedSize(80, 25)
|
||||||
layout.addWidget(self.btnBox)
|
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||||
|
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setFixedSize(80, 25)
|
||||||
|
Layout.addWidget(self.BtnBox)
|
||||||
|
|
||||||
|
def createButtonPanel(
|
||||||
def _createButtonPanel(
|
|
||||||
self,
|
self,
|
||||||
parent_layout
|
ParentLayout
|
||||||
):
|
):
|
||||||
|
|
||||||
|
Splitter = QSplitter(Qt.Orientation.Horizontal)
|
||||||
tab_widget = QTabWidget()
|
TabWidget = QTabWidget()
|
||||||
tab_widget.setMaximumHeight(200)
|
TabWidget.setMaximumHeight(150)
|
||||||
basic_widget = QWidget()
|
BasicWidget = QWidget()
|
||||||
basic_layout = QGridLayout(basic_widget)
|
BasicLayout = QGridLayout(BasicWidget)
|
||||||
basic_layout.setSpacing(4)
|
BasicLayout.setSpacing(4)
|
||||||
basic_layout.setContentsMargins(4, 4, 4, 4)
|
BasicLayout.setContentsMargins(4, 4, 4, 4)
|
||||||
basic_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
BasicLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||||
control_buttons = [
|
control_buttons = [
|
||||||
("IF", "IF()\n \nEND IF"),
|
("如果 (if...)", "if then\n \nend"),
|
||||||
("ELSE IF", "ELSE IF()\n "),
|
("再如果 (elseif...)", "elseif then\n "),
|
||||||
("ELSE", "ELSE"),
|
("否则 (else)", "else"),
|
||||||
("END IF", "END IF"),
|
("结束 (end)", "end"),
|
||||||
("PASS", "PASS"),
|
("跳过 (pass)", "-- pass"),
|
||||||
]
|
]
|
||||||
self._addButtonsToGrid(basic_layout, control_buttons, 0, 0, 5)
|
self.addButtonsToGrid(BasicLayout, control_buttons, 0, 0, 3)
|
||||||
|
|
||||||
assign_buttons = [
|
assign_buttons = [
|
||||||
("SET", "SET = "),
|
("赋值 (=)", " = "),
|
||||||
]
|
]
|
||||||
self._addButtonsToGrid(basic_layout, assign_buttons, 0, 5, 1)
|
self.addButtonsToGrid(BasicLayout, assign_buttons, 1, 2, 3)
|
||||||
|
TabWidget.addTab(BasicWidget, "基本语法")
|
||||||
func_buttons = [
|
OperatorWidget = QWidget()
|
||||||
("DATE()", "DATE()"),
|
OperatorLayout = QGridLayout(OperatorWidget)
|
||||||
("TIME()", "TIME()"),
|
OperatorLayout.setSpacing(4)
|
||||||
]
|
OperatorLayout.setContentsMargins(4, 4, 4, 4)
|
||||||
self._addButtonsToGrid(basic_layout, func_buttons, 1, 0, 2)
|
OperatorLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||||
|
|
||||||
tab_widget.addTab(basic_widget, "基本语法")
|
|
||||||
operator_widget = QWidget()
|
|
||||||
operator_layout = QGridLayout(operator_widget)
|
|
||||||
operator_layout.setSpacing(4)
|
|
||||||
operator_layout.setContentsMargins(4, 4, 4, 4)
|
|
||||||
operator_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
|
||||||
arithmetic_buttons = [
|
arithmetic_buttons = [
|
||||||
(".ADD.", ".ADD."),
|
("加 (+)", " + "),
|
||||||
(".SUB.", ".SUB."),
|
("减 (-)", " - "),
|
||||||
]
|
]
|
||||||
self._addButtonsToGrid(operator_layout, arithmetic_buttons, 0, 0, 2)
|
self.addButtonsToGrid(OperatorLayout, arithmetic_buttons, 0, 0, 3)
|
||||||
compare_buttons = [
|
compare_buttons = [
|
||||||
(".EQ.", ".EQ."),
|
("等于 (==)", " == "),
|
||||||
(".NEQ.", ".NEQ."),
|
("不等于 (~=)", " ~= "),
|
||||||
(".BGT.", ".BGT."),
|
("大于 (>)", " > "),
|
||||||
(".BLT.", ".BLT."),
|
("小于 (<)", " < "),
|
||||||
(".BGE.", ".BGE."),
|
("大于等于 (>=)", " >= "),
|
||||||
(".BLE.", ".BLE."),
|
("小于等于 (<=)", " <= "),
|
||||||
]
|
]
|
||||||
self._addButtonsToGrid(operator_layout, compare_buttons, 1, 0, 6)
|
self.addButtonsToGrid(OperatorLayout, compare_buttons, 1, 0, 3)
|
||||||
logic_buttons = [
|
logic_buttons = [
|
||||||
(".AND.", ".AND."),
|
("且 (and)", " and "),
|
||||||
(".OR.", ".OR."),
|
("或 (or)", " or "),
|
||||||
]
|
]
|
||||||
self._addButtonsToGrid(operator_layout, logic_buttons, 2, 0, 2)
|
self.addButtonsToGrid(OperatorLayout, logic_buttons, 2, 0, 3)
|
||||||
tab_widget.addTab(operator_widget, "运算符")
|
TabWidget.addTab(OperatorWidget, "运算符")
|
||||||
literal_widget = QWidget()
|
LiteralWidget = QWidget()
|
||||||
literal_layout = QGridLayout(literal_widget)
|
LiteralLayout = QGridLayout(LiteralWidget)
|
||||||
literal_layout.setSpacing(4)
|
LiteralLayout.setSpacing(4)
|
||||||
literal_layout.setContentsMargins(4, 4, 4, 4)
|
LiteralLayout.setContentsMargins(4, 4, 4, 4)
|
||||||
literal_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
LiteralLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||||
bool_buttons = [
|
bool_buttons = [
|
||||||
(".TRUE.", ".TRUE."),
|
("真 (true)", "true"),
|
||||||
(".FALSE.", ".FALSE."),
|
("假 (false)", "false"),
|
||||||
]
|
]
|
||||||
self._addButtonsToGrid(literal_layout, bool_buttons, 0, 0, 2)
|
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 = [
|
hint_buttons = [
|
||||||
("字符串", "'文本'"),
|
("字符串", '"请输入文本"'),
|
||||||
("数字", "123"),
|
("数字", "123"),
|
||||||
("注释", "// 注释"),
|
("注释", "-- 请输入注释"),
|
||||||
]
|
]
|
||||||
self._addButtonsToGrid(literal_layout, hint_buttons, 1, 0, 3)
|
self.addButtonsToGrid(LiteralLayout, hint_buttons, 2, 0, 3)
|
||||||
tab_widget.addTab(literal_widget, "字面量")
|
TabWidget.addTab(LiteralWidget, "字面量")
|
||||||
var_widget = QWidget()
|
VarWidget = QWidget()
|
||||||
var_layout = QGridLayout(var_widget)
|
VarLayout = QGridLayout(VarWidget)
|
||||||
var_layout.setSpacing(4)
|
VarLayout.setSpacing(4)
|
||||||
var_layout.setContentsMargins(4, 4, 4, 4)
|
VarLayout.setContentsMargins(4, 4, 4, 4)
|
||||||
var_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
VarLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||||
var_buttons = [
|
var_buttons = [
|
||||||
(display_name, name) for display_name, (name, _) in ALL_VARIABLES.items()
|
(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)
|
||||||
|
|
||||||
self._addButtonsToGrid(var_layout, var_buttons, 0, 0, 5)
|
def addButtonsToGrid(
|
||||||
tab_widget.addTab(var_widget, "变量")
|
|
||||||
parent_layout.addWidget(tab_widget)
|
|
||||||
|
|
||||||
|
|
||||||
def _addButtonsToGrid(
|
|
||||||
self,
|
self,
|
||||||
grid_layout,
|
grid_layout,
|
||||||
buttons,
|
buttons,
|
||||||
@@ -279,74 +399,210 @@ class ALAutoScriptEditDialog(QDialog):
|
|||||||
row = start_row
|
row = start_row
|
||||||
|
|
||||||
for btn_text, template in buttons:
|
for btn_text, template in buttons:
|
||||||
btn = QPushButton(btn_text)
|
Btn = QPushButton(btn_text)
|
||||||
btn.setProperty("template", template)
|
Btn.setProperty("template", template)
|
||||||
btn.clicked.connect(self._insertTemplate)
|
Btn.clicked.connect(self.insertTemplate)
|
||||||
btn.setFixedWidth(100)
|
Btn.setFixedWidth(100)
|
||||||
btn.setFixedHeight(30)
|
Btn.setFixedHeight(25)
|
||||||
btn.setToolTip(f"插入: {template}")
|
Btn.setToolTip(f"插入: {template}")
|
||||||
grid_layout.addWidget(btn, row, col)
|
grid_layout.addWidget(Btn, row, col)
|
||||||
|
|
||||||
col += 1
|
col += 1
|
||||||
if col >= start_col + max_columns:
|
if col >= start_col + max_columns:
|
||||||
col = start_col
|
col = start_col
|
||||||
row += 1
|
row += 1
|
||||||
|
|
||||||
@Slot()
|
def createMockPanel(
|
||||||
def _insertTemplate(
|
|
||||||
self
|
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
|
||||||
):
|
):
|
||||||
|
|
||||||
btn = self.sender()
|
if not data:
|
||||||
if not isinstance(btn, QPushButton):
|
|
||||||
return
|
return
|
||||||
template = btn.property("template")
|
for name, var_type, key_path, _ in createTargetVarDefs():
|
||||||
if not template:
|
d = data
|
||||||
return
|
try:
|
||||||
cursor = self.textEdit.textCursor()
|
for key in key_path:
|
||||||
cursor.insertText(template)
|
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(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.btnBox.accepted.connect(self.accept)
|
self.BtnBox.accepted.connect(self.accept)
|
||||||
self.btnBox.rejected.connect(self.reject)
|
self.BtnBox.rejected.connect(self.reject)
|
||||||
self.zoomInBtn.clicked.connect(self.onZoomIn)
|
self.OrchBtn.clicked.connect(self.onOpenOrchDialog)
|
||||||
self.zoomOutBtn.clicked.connect(self.onZoomOut)
|
self.DebugBtn.clicked.connect(self.onDebugRun)
|
||||||
self.zoomResetBtn.clicked.connect(self.onZoomReset)
|
self.ZoomInBtn.clicked.connect(self.onZoomIn)
|
||||||
self.copyBtn.clicked.connect(self.onCopy)
|
self.ZoomOutBtn.clicked.connect(self.onZoomOut)
|
||||||
|
self.ZoomResetBtn.clicked.connect(self.onZoomReset)
|
||||||
|
self.CopyBtn.clicked.connect(self.onCopy)
|
||||||
|
|
||||||
def getScript(
|
def getScript(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
|
|
||||||
return self.textEdit.toPlainText()
|
return self.TextEdit.toPlainText()
|
||||||
|
|
||||||
|
|
||||||
def updateFontSize(
|
def updateFontSize(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
font = self.textEdit.font()
|
self.TextEdit.setStyleSheet(
|
||||||
font.setPointSize(self._fontSize)
|
|
||||||
self.textEdit.setFont(font)
|
|
||||||
self.textEdit.setStyleSheet(
|
|
||||||
"QPlainTextEdit {"
|
"QPlainTextEdit {"
|
||||||
" font-family: 'Courier New', 'Consolas', monospace;"
|
" font-family: 'Courier New', 'Consolas', monospace;"
|
||||||
f" font-size: {self._fontSize}px;"
|
f" font-size: {self._font_size}px;"
|
||||||
"}"
|
"}"
|
||||||
)
|
)
|
||||||
self.zoomLabel.setText(f"{self._fontSize}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()
|
@Slot()
|
||||||
def onZoomIn(
|
def onZoomIn(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self._fontSize = min(self._fontSize + 2, 40)
|
self._font_size = min(self._font_size + 2, 40)
|
||||||
self.updateFontSize()
|
self.updateFontSize()
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
@@ -354,7 +610,7 @@ class ALAutoScriptEditDialog(QDialog):
|
|||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self._fontSize = max(self._fontSize - 2, 8)
|
self._font_size = max(self._font_size - 2, 8)
|
||||||
self.updateFontSize()
|
self.updateFontSize()
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
@@ -362,7 +618,7 @@ class ALAutoScriptEditDialog(QDialog):
|
|||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self._fontSize = 13
|
self._font_size = 21
|
||||||
self.updateFontSize()
|
self.updateFontSize()
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
@@ -370,13 +626,59 @@ class ALAutoScriptEditDialog(QDialog):
|
|||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
clipboard = QApplication.clipboard()
|
Clipboard = QApplication.clipboard()
|
||||||
clipboard.setText(self.textEdit.toPlainText())
|
Clipboard.setText(self.TextEdit.toPlainText())
|
||||||
original = self.copyBtn.text()
|
self.CopyBtn.setEnabled(False)
|
||||||
self.copyBtn.setText("已复制")
|
|
||||||
self.copyBtn.setEnabled(False)
|
|
||||||
from PySide6.QtCore import QTimer
|
|
||||||
QTimer.singleShot(2000, lambda: (
|
QTimer.singleShot(2000, lambda: (
|
||||||
self.copyBtn.setText(original),
|
self.CopyBtn.setEnabled(True)
|
||||||
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,3 +1,10 @@
|
|||||||
from gui.ALAutoScriptOrchDialog._dialog import ALAutoScriptOrchDialog
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
Copyright (c) 2026 KenanZhu.
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
__all__ = ["ALAutoScriptOrchDialog"]
|
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
|
||||||
@@ -1,5 +1,14 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
Conditional block widget for the AutoScript orchestration dialog.
|
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.QtCore import Slot
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
@@ -23,250 +32,238 @@ class ConditionalBlock(QGroupBox):
|
|||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
blockIndex: int,
|
block_index: int,
|
||||||
varMgr = None,
|
var_mgr = None,
|
||||||
parent = None
|
parent = None
|
||||||
):
|
):
|
||||||
|
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self.blockIndex = blockIndex
|
self._block_index = block_index
|
||||||
self._varMgr = varMgr
|
self._var_mgr = var_mgr
|
||||||
self._actionWidgets = []
|
self._action_widgets = []
|
||||||
self._conditionRows = []
|
self._condition_rows = []
|
||||||
|
|
||||||
self.setupUi()
|
self.setupUi()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
self.addInitialConditionRow()
|
self.addInitialConditionRow()
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.setUpdatesEnabled(False)
|
self.setUpdatesEnabled(False)
|
||||||
self.setStyleSheet(
|
self.setStyleSheet(
|
||||||
"QGroupBox { font-weight: bold; border: 1px solid #ccc; "
|
"QGroupBox { "\
|
||||||
"margin-top: 5px; padding-top: 5px; }"
|
"font-weight: bold;"\
|
||||||
|
"border: 1px solid #ccc;"\
|
||||||
|
"margin-top: 5px;"\
|
||||||
|
"padding-top: 5px; "\
|
||||||
|
"}"
|
||||||
)
|
)
|
||||||
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
|
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
|
||||||
mainLayout = QVBoxLayout(self)
|
MainLayout = QVBoxLayout(self)
|
||||||
mainLayout.setSpacing(6)
|
MainLayout.setSpacing(6)
|
||||||
mainLayout.setContentsMargins(8, 8, 8, 8)
|
MainLayout.setContentsMargins(8, 8, 8, 8)
|
||||||
|
HeaderLayout = QHBoxLayout()
|
||||||
headerLayout = QHBoxLayout()
|
HeaderLayout.setSpacing(8)
|
||||||
headerLayout.setSpacing(8)
|
self.TypeCombo = QComboBox(self)
|
||||||
self.typeCombo = QComboBox(self)
|
self.TypeCombo.addItem("IF", "IF")
|
||||||
self.typeCombo.addItem("IF", "IF")
|
self.TypeCombo.addItem("ELSE IF", "ELSE IF")
|
||||||
self.typeCombo.addItem("ELSE IF", "ELSE IF")
|
self.TypeCombo.addItem("ELSE", "ELSE")
|
||||||
self.typeCombo.addItem("ELSE", "ELSE")
|
self.TypeCombo.setFixedHeight(25)
|
||||||
self.typeCombo.setFixedHeight(25)
|
if self._block_index == 0:
|
||||||
if self.blockIndex == 0:
|
self.TypeCombo.setEnabled(False)
|
||||||
self.typeCombo.setEnabled(False)
|
HeaderLayout.addWidget(QLabel("类型:", self))
|
||||||
headerLayout.addWidget(QLabel("类型:", self))
|
HeaderLayout.addWidget(self.TypeCombo)
|
||||||
headerLayout.addWidget(self.typeCombo)
|
HeaderLayout.addStretch()
|
||||||
headerLayout.addStretch()
|
self.DeleteBlockBtn = QPushButton("删除此块", self)
|
||||||
self.deleteBlockBtn = QPushButton("删除此块", self)
|
self.DeleteBlockBtn.setStyleSheet("color: red;")
|
||||||
self.deleteBlockBtn.setStyleSheet("color: red;")
|
self.DeleteBlockBtn.setFixedHeight(25)
|
||||||
self.deleteBlockBtn.setFixedHeight(25)
|
HeaderLayout.addWidget(self.DeleteBlockBtn)
|
||||||
headerLayout.addWidget(self.deleteBlockBtn)
|
MainLayout.addLayout(HeaderLayout)
|
||||||
mainLayout.addLayout(headerLayout)
|
self.ConditionWidget = QWidget(self)
|
||||||
|
self.ConditionWidget.setSizePolicy(
|
||||||
self.conditionWidget = QWidget(self)
|
|
||||||
self.conditionWidget.setSizePolicy(
|
|
||||||
QSizePolicy.Preferred, QSizePolicy.Preferred
|
QSizePolicy.Preferred, QSizePolicy.Preferred
|
||||||
)
|
)
|
||||||
condLayout = QVBoxLayout(self.conditionWidget)
|
CondLayout = QVBoxLayout(self.ConditionWidget)
|
||||||
condLayout.setContentsMargins(4, 4, 4, 4)
|
CondLayout.setContentsMargins(4, 4, 4, 4)
|
||||||
condLayout.setSpacing(6)
|
CondLayout.setSpacing(6)
|
||||||
|
self.CondRowsLayout = QVBoxLayout()
|
||||||
self.condRowsLayout = QVBoxLayout()
|
self.CondRowsLayout.setSpacing(4)
|
||||||
self.condRowsLayout.setSpacing(4)
|
CondLayout.addLayout(self.CondRowsLayout)
|
||||||
condLayout.addLayout(self.condRowsLayout)
|
self.AddCondBtn = QPushButton("+ 添加条件", self.ConditionWidget)
|
||||||
self.addCondBtn = QPushButton("+ 添加条件", self.conditionWidget)
|
self.AddCondBtn.setFixedHeight(25)
|
||||||
self.addCondBtn.setFixedHeight(25)
|
CondLayout.addWidget(self.AddCondBtn)
|
||||||
condLayout.addWidget(self.addCondBtn)
|
MainLayout.addWidget(self.ConditionWidget)
|
||||||
mainLayout.addWidget(self.conditionWidget)
|
self.ActionLabel = QLabel("执行步骤:", self)
|
||||||
self.actionLabel = QLabel("执行步骤:", self)
|
self.ActionLabel.setFixedHeight(25)
|
||||||
self.actionLabel.setFixedHeight(25)
|
MainLayout.addWidget(self.ActionLabel)
|
||||||
mainLayout.addWidget(self.actionLabel)
|
self.ActionsLayout = QVBoxLayout()
|
||||||
self.actionsLayout = QVBoxLayout()
|
self.ActionsLayout.setSpacing(4)
|
||||||
self.actionsLayout.setSpacing(4)
|
MainLayout.addLayout(self.ActionsLayout)
|
||||||
mainLayout.addLayout(self.actionsLayout)
|
self.AddActionBtn = QPushButton("+ 添加执行步骤", self)
|
||||||
self.addActionBtn = QPushButton("+ 添加执行步骤", self)
|
self.AddActionBtn.setFixedHeight(25)
|
||||||
self.addActionBtn.setFixedHeight(25)
|
MainLayout.addWidget(self.AddActionBtn)
|
||||||
mainLayout.addWidget(self.addActionBtn)
|
|
||||||
self.setUpdatesEnabled(True)
|
self.setUpdatesEnabled(True)
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.typeCombo.currentIndexChanged.connect(self.onTypeChanged)
|
self.TypeCombo.currentIndexChanged.connect(self.onTypeChanged)
|
||||||
self.addCondBtn.clicked.connect(self.addConditionRow)
|
self.AddCondBtn.clicked.connect(self.addConditionRow)
|
||||||
self.addActionBtn.clicked.connect(self.addActionStep)
|
self.AddActionBtn.clicked.connect(self.addActionStep)
|
||||||
|
|
||||||
|
|
||||||
def addInitialConditionRow(
|
def addInitialConditionRow(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
row = ConditionRowFrame(
|
Row = ConditionRowFrame(
|
||||||
self._varMgr, self.blockIndex,
|
self._var_mgr, self._block_index,
|
||||||
isFirst=True, parent=self
|
is_first=True, parent=self
|
||||||
)
|
)
|
||||||
self._conditionRows.append(row)
|
self._condition_rows.append(Row)
|
||||||
self.condRowsLayout.addWidget(row)
|
self.CondRowsLayout.addWidget(Row)
|
||||||
|
|
||||||
|
|
||||||
def addConditionRow(
|
def addConditionRow(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
row = ConditionRowFrame(
|
Row = ConditionRowFrame(
|
||||||
self._varMgr, self.blockIndex,
|
self._var_mgr, self._block_index,
|
||||||
isFirst=False, parent=self
|
is_first=False, parent=self
|
||||||
)
|
)
|
||||||
row.deleteBtn.clicked.connect(lambda: self.removeConditionRow(row))
|
Row.DeleteBtn.clicked.connect(lambda: self.removeConditionRow(Row))
|
||||||
self._conditionRows.append(row)
|
self._condition_rows.append(Row)
|
||||||
self.condRowsLayout.addWidget(row)
|
self.CondRowsLayout.addWidget(Row)
|
||||||
|
|
||||||
|
|
||||||
def removeConditionRow(
|
def removeConditionRow(
|
||||||
self,
|
self,
|
||||||
row: ConditionRowFrame
|
row: ConditionRowFrame
|
||||||
):
|
):
|
||||||
|
|
||||||
if row in self._conditionRows and len(self._conditionRows) > 1:
|
if row in self._condition_rows and len(self._condition_rows) > 1:
|
||||||
self._conditionRows.remove(row)
|
self._condition_rows.remove(row)
|
||||||
self.condRowsLayout.removeWidget(row)
|
self.CondRowsLayout.removeWidget(row)
|
||||||
row.hide()
|
row.hide()
|
||||||
row.deleteLater()
|
row.deleteLater()
|
||||||
|
|
||||||
|
|
||||||
def addActionStep(
|
def addActionStep(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
step = ActionStepFrame(self._varMgr, self.blockIndex, parent=self)
|
Step = ActionStepFrame(self._var_mgr, self._block_index, parent=self)
|
||||||
step.deleteBtn.clicked.connect(lambda: self.removeActionStep(step))
|
Step.DeleteBtn.clicked.connect(lambda: self.removeActionStep(Step))
|
||||||
self._actionWidgets.append(step)
|
self._action_widgets.append(Step)
|
||||||
self.actionsLayout.addWidget(step)
|
self.ActionsLayout.addWidget(Step)
|
||||||
|
|
||||||
|
|
||||||
def removeActionStep(
|
def removeActionStep(
|
||||||
self,
|
self,
|
||||||
step: ActionStepFrame
|
step: ActionStepFrame
|
||||||
):
|
):
|
||||||
|
|
||||||
if step in self._actionWidgets:
|
if step in self._action_widgets:
|
||||||
self._actionWidgets.remove(step)
|
self._action_widgets.remove(step)
|
||||||
self.actionsLayout.removeWidget(step)
|
self.ActionsLayout.removeWidget(step)
|
||||||
step.hide()
|
step.hide()
|
||||||
step.deleteLater()
|
step.deleteLater()
|
||||||
|
|
||||||
@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 执行步骤:"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def getBlockType(
|
def getBlockType(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
|
|
||||||
return self.typeCombo.currentData()
|
return self.TypeCombo.currentData()
|
||||||
|
|
||||||
|
|
||||||
def getConditionRows(
|
def getConditionRows(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
return list(self._conditionRows)
|
return list(self._condition_rows)
|
||||||
|
|
||||||
|
|
||||||
def getActionSteps(
|
def getActionSteps(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
return list(self._actionWidgets)
|
return list(self._action_widgets)
|
||||||
|
|
||||||
|
|
||||||
def countActionSteps(
|
def countActionSteps(
|
||||||
self
|
self
|
||||||
) -> int:
|
) -> int:
|
||||||
|
|
||||||
return len(self._actionWidgets)
|
return len(self._action_widgets)
|
||||||
|
|
||||||
|
def toScript(
|
||||||
def toScriptLines(
|
|
||||||
self
|
self
|
||||||
) -> list:
|
) -> list:
|
||||||
|
"""
|
||||||
|
Generate Lua script lines for this conditional block.
|
||||||
|
"""
|
||||||
|
|
||||||
blockType = self.getBlockType()
|
block_type = self.getBlockType()
|
||||||
lines = []
|
lines = []
|
||||||
|
if block_type in ("IF", "ELSE IF"):
|
||||||
if blockType in ("IF", "ELSE IF"):
|
cond_texts = [
|
||||||
condTexts = [
|
r.toScript() for r in self._condition_rows if r.toScript()
|
||||||
r.toConditionText() for r in self._conditionRows if r.toConditionText()
|
|
||||||
]
|
]
|
||||||
if not condTexts:
|
if not cond_texts:
|
||||||
condTexts = [".TRUE."]
|
cond_texts = ["true"]
|
||||||
|
if len(cond_texts) == 1:
|
||||||
if len(condTexts) == 1:
|
combined = cond_texts[0]
|
||||||
combined = condTexts[0]
|
|
||||||
else:
|
else:
|
||||||
parts = []
|
parts = []
|
||||||
for i, ct in enumerate(condTexts):
|
for i, ct in enumerate(cond_texts):
|
||||||
if i > 0:
|
if i > 0:
|
||||||
logic = self._conditionRows[i].getLogic() or ".AND."
|
logic = self._condition_rows[i].getLogic() or "and"
|
||||||
parts.append(f" {logic} ")
|
parts.append(f" {logic} ")
|
||||||
parts.append(f"({ct})")
|
parts.append(f"({ct})")
|
||||||
combined = "".join(parts)
|
combined = "".join(parts)
|
||||||
if blockType == "IF":
|
if block_type == "IF":
|
||||||
lines.append(f"IF({combined}) THEN")
|
lines.append(f"if {combined} then")
|
||||||
else:
|
else:
|
||||||
lines.append(f"ELSE IF({combined}) THEN")
|
lines.append(f"elseif {combined} then")
|
||||||
else:
|
else:
|
||||||
lines.append("ELSE")
|
lines.append("else")
|
||||||
for step in self._actionWidgets:
|
for step in self._action_widgets:
|
||||||
scriptLine = step.toScriptLine()
|
script_line = step.toScript()
|
||||||
if scriptLine:
|
if script_line:
|
||||||
lines.append(scriptLine)
|
lines.append(script_line)
|
||||||
return lines
|
return lines
|
||||||
|
|
||||||
|
|
||||||
def refreshVarCombos(
|
def refreshVarCombos(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
for row in self._conditionRows:
|
for row in self._condition_rows:
|
||||||
row.refreshVarCombos()
|
row.refreshVarCombos()
|
||||||
for step in self._actionWidgets:
|
for step in self._action_widgets:
|
||||||
step.refreshVarCombos()
|
step.refreshVarCombos()
|
||||||
|
|
||||||
|
|
||||||
def setPrevBlockType(
|
def setPrevBlockType(
|
||||||
self,
|
self,
|
||||||
prevType: str | None
|
prev_type: str | None
|
||||||
):
|
):
|
||||||
|
|
||||||
model = self.typeCombo.model()
|
model = self.TypeCombo.model()
|
||||||
if model is None:
|
if model is None:
|
||||||
return
|
return
|
||||||
for data in ("ELSE IF", "ELSE"):
|
for data in ("ELSE IF", "ELSE"):
|
||||||
idx = self.typeCombo.findData(data)
|
idx = self.TypeCombo.findData(data)
|
||||||
if idx < 0:
|
if idx < 0:
|
||||||
continue
|
continue
|
||||||
item = model.item(idx)
|
item = model.item(idx)
|
||||||
shouldEnable = prevType != "ELSE"
|
should_enable = prev_type != "ELSE"
|
||||||
item.setEnabled(shouldEnable)
|
item.setEnabled(should_enable)
|
||||||
if prevType == "ELSE" and self.typeCombo.currentData() in ("ELSE IF", "ELSE"):
|
if prev_type == "ELSE" and self.TypeCombo.currentData() in ("ELSE IF", "ELSE"):
|
||||||
self.typeCombo.setCurrentIndex(0)
|
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 执行步骤:"
|
||||||
|
)
|
||||||
@@ -1,5 +1,14 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
Orchestration dialog for visually composing AutoScript scripts.
|
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.QtCore import Slot
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
@@ -13,41 +22,25 @@ from PySide6.QtWidgets import (
|
|||||||
QWidget,
|
QWidget,
|
||||||
)
|
)
|
||||||
|
|
||||||
from gui.ALAutoScriptOrchDialog._precheck import precheck
|
from gui.ALAutoScriptOrchDialog._helpers import VariableManager
|
||||||
from gui.ALAutoScriptOrchDialog._orchestrate import parseBlocks
|
|
||||||
|
|
||||||
from gui.ALAutoScriptOrchDialog._helpers import (
|
|
||||||
COMPARE_OPERATORS,
|
|
||||||
PRESET_NAMES,
|
|
||||||
VariableManager,
|
|
||||||
findOperatorIn,
|
|
||||||
splitTopLevel,
|
|
||||||
stripOuterParens,
|
|
||||||
)
|
|
||||||
from gui.ALAutoScriptOrchDialog._blocks import ConditionalBlock
|
from gui.ALAutoScriptOrchDialog._blocks import ConditionalBlock
|
||||||
from gui.ALAutoScriptOrchDialog._widgets import ConditionRowFrame
|
|
||||||
|
|
||||||
|
|
||||||
class ALAutoScriptOrchDialog(QDialog):
|
class ALAutoScriptOrchDialog(QDialog):
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
parent = None,
|
parent = None
|
||||||
existingScript: str = ""
|
|
||||||
):
|
):
|
||||||
|
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self._blocks = []
|
self._blocks = []
|
||||||
self._varMgr = VariableManager(self)
|
self._var_mgr = VariableManager(self)
|
||||||
|
|
||||||
self.setupUi()
|
self.setupUi()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
if existingScript and existingScript.strip():
|
self.addBlock()
|
||||||
self.loadFromScript(existingScript)
|
self.ScrollLayout.addStretch()
|
||||||
else:
|
|
||||||
self.addBlock()
|
|
||||||
self.scrollLayout.addStretch()
|
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
@@ -56,37 +49,35 @@ class ALAutoScriptOrchDialog(QDialog):
|
|||||||
self.setWindowTitle("AutoScript 指令编排 - AutoLibrary")
|
self.setWindowTitle("AutoScript 指令编排 - AutoLibrary")
|
||||||
self.setMinimumSize(640, 600)
|
self.setMinimumSize(640, 600)
|
||||||
self.setModal(True)
|
self.setModal(True)
|
||||||
mainLayout = QVBoxLayout(self)
|
MainLayout = QVBoxLayout(self)
|
||||||
scroll = QScrollArea()
|
Scroll = QScrollArea()
|
||||||
scroll.setWidgetResizable(True)
|
Scroll.setWidgetResizable(True)
|
||||||
scroll.setFrameShape(QFrame.NoFrame)
|
Scroll.setFrameShape(QFrame.NoFrame)
|
||||||
scrollContent = QWidget()
|
ScrollContent = QWidget()
|
||||||
self.scrollLayout = QVBoxLayout(scrollContent)
|
self.ScrollLayout = QVBoxLayout(ScrollContent)
|
||||||
self.scrollLayout.setSpacing(5)
|
self.ScrollLayout.setSpacing(5)
|
||||||
scroll.setWidget(scrollContent)
|
Scroll.setWidget(ScrollContent)
|
||||||
mainLayout.addWidget(scroll)
|
MainLayout.addWidget(Scroll)
|
||||||
self.addBlockBtn = QPushButton("+ 添加判断块")
|
self.AddBlockBtn = QPushButton("+ 添加判断块")
|
||||||
self.addBlockBtn.setFixedHeight(25)
|
self.AddBlockBtn.setFixedHeight(25)
|
||||||
mainLayout.addWidget(self.addBlockBtn)
|
MainLayout.addWidget(self.AddBlockBtn)
|
||||||
self.btnBox = QDialogButtonBox(
|
self.BtnBox = QDialogButtonBox(
|
||||||
QDialogButtonBox.StandardButton.Ok |
|
QDialogButtonBox.StandardButton.Ok |
|
||||||
QDialogButtonBox.StandardButton.Cancel
|
QDialogButtonBox.StandardButton.Cancel
|
||||||
)
|
)
|
||||||
self.btnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||||
self.btnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||||
mainLayout.addWidget(self.btnBox)
|
MainLayout.addWidget(self.BtnBox)
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.btnBox.accepted.connect(self.onAccept)
|
self.BtnBox.accepted.connect(self.onAccept)
|
||||||
self.btnBox.rejected.connect(self.reject)
|
self.BtnBox.rejected.connect(self.reject)
|
||||||
self.addBlockBtn.clicked.connect(self.addBlock)
|
self.AddBlockBtn.clicked.connect(self.addBlock)
|
||||||
|
|
||||||
|
def updateBlockTypeRestrictions(
|
||||||
def _updateBlockTypeRestrictions(
|
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
@@ -95,30 +86,28 @@ class ALAutoScriptOrchDialog(QDialog):
|
|||||||
block.setPrevBlockType(prevType)
|
block.setPrevBlockType(prevType)
|
||||||
prevType = block.getBlockType()
|
prevType = block.getBlockType()
|
||||||
|
|
||||||
|
|
||||||
def addBlock(
|
def addBlock(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
block = ConditionalBlock(
|
Block = ConditionalBlock(
|
||||||
len(self._blocks), self._varMgr, parent=self
|
len(self._blocks), self._var_mgr, parent=self
|
||||||
)
|
)
|
||||||
block.deleteBlockBtn.clicked.connect(lambda: self.removeBlock(block))
|
Block.DeleteBlockBtn.clicked.connect(lambda: self.removeBlock(Block))
|
||||||
block.typeCombo.currentIndexChanged.connect(self._updateBlockTypeRestrictions)
|
Block.TypeCombo.currentIndexChanged.connect(self.updateBlockTypeRestrictions)
|
||||||
block.addActionStep()
|
Block.addActionStep()
|
||||||
self._blocks.append(block)
|
self._blocks.append(Block)
|
||||||
self._updateBlockTypeRestrictions()
|
self.updateBlockTypeRestrictions()
|
||||||
if self.scrollLayout.count() > 0:
|
if self.ScrollLayout.count() > 0:
|
||||||
lastItem = self.scrollLayout.itemAt(
|
lastItem = self.ScrollLayout.itemAt(
|
||||||
self.scrollLayout.count() - 1
|
self.ScrollLayout.count() - 1
|
||||||
)
|
)
|
||||||
if lastItem and lastItem.spacerItem():
|
if lastItem and lastItem.spacerItem():
|
||||||
self.scrollLayout.insertWidget(
|
self.ScrollLayout.insertWidget(
|
||||||
self.scrollLayout.count() - 1, block
|
self.ScrollLayout.count() - 1, Block
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
self.scrollLayout.addWidget(block)
|
self.ScrollLayout.addWidget(Block)
|
||||||
|
|
||||||
|
|
||||||
def removeBlock(
|
def removeBlock(
|
||||||
self,
|
self,
|
||||||
@@ -130,35 +119,37 @@ class ALAutoScriptOrchDialog(QDialog):
|
|||||||
return
|
return
|
||||||
if block in self._blocks:
|
if block in self._blocks:
|
||||||
self._blocks.remove(block)
|
self._blocks.remove(block)
|
||||||
self.scrollLayout.removeWidget(block)
|
self.ScrollLayout.removeWidget(block)
|
||||||
block.hide()
|
block.hide()
|
||||||
block.deleteLater()
|
block.deleteLater()
|
||||||
for i, blk in enumerate(self._blocks):
|
for i, blk in enumerate(self._blocks):
|
||||||
blk.blockIndex = i
|
blk.blockIndex = i
|
||||||
if i == 0:
|
if i == 0:
|
||||||
blk.typeCombo.setEnabled(False)
|
blk.TypeCombo.setEnabled(False)
|
||||||
blk.typeCombo.setCurrentIndex(0)
|
blk.TypeCombo.setCurrentIndex(0)
|
||||||
else:
|
else:
|
||||||
blk.typeCombo.setEnabled(True)
|
blk.TypeCombo.setEnabled(True)
|
||||||
blk.refreshVarCombos()
|
blk.refreshVarCombos()
|
||||||
self._updateBlockTypeRestrictions()
|
self.updateBlockTypeRestrictions()
|
||||||
|
|
||||||
|
|
||||||
def getScript(
|
def getScript(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
|
"""
|
||||||
|
Generate the complete Lua script from all blocks.
|
||||||
|
"""
|
||||||
|
|
||||||
parts = []
|
parts = []
|
||||||
prevType = None
|
prevType = None
|
||||||
for block in self._blocks:
|
for block in self._blocks:
|
||||||
blockType = block.getBlockType()
|
blockType = block.getBlockType()
|
||||||
if blockType == "IF" and prevType is not None:
|
if blockType == "IF" and prevType is not None:
|
||||||
parts.append("END IF")
|
parts.append("end")
|
||||||
lines = block.toScriptLines()
|
lines = block.toScript()
|
||||||
parts.extend(lines)
|
parts.extend(lines)
|
||||||
prevType = blockType
|
prevType = blockType
|
||||||
if self._blocks and self._blocks[0].getBlockType() == "IF":
|
if self._blocks and self._blocks[0].getBlockType() == "IF":
|
||||||
parts.append("END IF")
|
parts.append("end")
|
||||||
return "\n".join(parts)
|
return "\n".join(parts)
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
@@ -171,126 +162,3 @@ class ALAutoScriptOrchDialog(QDialog):
|
|||||||
QMessageBox.warning(self, "提示", "脚本内容为空,请添加至少一个操作步骤。")
|
QMessageBox.warning(self, "提示", "脚本内容为空,请添加至少一个操作步骤。")
|
||||||
return
|
return
|
||||||
self.accept()
|
self.accept()
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def precheckScriptForOrchestration(
|
|
||||||
script: str
|
|
||||||
) -> tuple[bool, str]:
|
|
||||||
|
|
||||||
return precheck(script, allowed_vars=PRESET_NAMES)
|
|
||||||
|
|
||||||
def loadFromScript(
|
|
||||||
self,
|
|
||||||
script: str
|
|
||||||
):
|
|
||||||
|
|
||||||
if not script.strip():
|
|
||||||
self.addBlock()
|
|
||||||
return
|
|
||||||
ok, err = self.precheckScriptForOrchestration(script)
|
|
||||||
if not ok:
|
|
||||||
QMessageBox.warning(
|
|
||||||
self, "无法编排",
|
|
||||||
f"脚本检查失败:\n{err}\n\n"
|
|
||||||
"请通过\"编辑\"按钮打开脚本编辑窗口进行修改。"
|
|
||||||
)
|
|
||||||
self.addBlock()
|
|
||||||
return
|
|
||||||
# Structured block data via observer-based parsing — no duplicate logic
|
|
||||||
typeIdxMap = {"IF": 0, "ELSE IF": 1, "ELSE": 2}
|
|
||||||
parsedBlocks = parseBlocks(script)
|
|
||||||
self._blocks.clear()
|
|
||||||
while self.scrollLayout.count():
|
|
||||||
item = self.scrollLayout.takeAt(0)
|
|
||||||
if item.widget():
|
|
||||||
item.widget().deleteLater()
|
|
||||||
try:
|
|
||||||
for blockType, condition, actions in parsedBlocks:
|
|
||||||
self.addBlock()
|
|
||||||
block = self._blocks[-1]
|
|
||||||
idx = typeIdxMap.get(blockType, 0)
|
|
||||||
block.typeCombo.setCurrentIndex(idx)
|
|
||||||
block.onTypeChanged(idx)
|
|
||||||
for oldStep in list(block._actionWidgets):
|
|
||||||
block.removeActionStep(oldStep)
|
|
||||||
for target, valueExpr, opType in actions:
|
|
||||||
block.addActionStep()
|
|
||||||
step = block.getActionSteps()[-1]
|
|
||||||
step.setOpType(opType)
|
|
||||||
step.loadFromScript(target, valueExpr)
|
|
||||||
if blockType in ("IF", "ELSE IF") and condition:
|
|
||||||
self._parseConditions(block, condition)
|
|
||||||
except Exception:
|
|
||||||
self._blocks.clear()
|
|
||||||
while self.scrollLayout.count():
|
|
||||||
item = self.scrollLayout.takeAt(0)
|
|
||||||
if item.widget():
|
|
||||||
item.widget().deleteLater()
|
|
||||||
self._updateBlockTypeRestrictions()
|
|
||||||
if not self._blocks:
|
|
||||||
self.addBlock()
|
|
||||||
|
|
||||||
|
|
||||||
def _parseConditions(
|
|
||||||
self,
|
|
||||||
block: ConditionalBlock,
|
|
||||||
condStr: str
|
|
||||||
):
|
|
||||||
|
|
||||||
s = condStr.strip()
|
|
||||||
if not s:
|
|
||||||
return
|
|
||||||
s = stripOuterParens(s)
|
|
||||||
orParts = splitTopLevel(s, ".OR.")
|
|
||||||
allSubConds = []
|
|
||||||
allLogics = []
|
|
||||||
for pi, part in enumerate(orParts):
|
|
||||||
part = part.strip()
|
|
||||||
if pi > 0:
|
|
||||||
allLogics.append(".OR.")
|
|
||||||
andParts = splitTopLevel(part, ".AND.")
|
|
||||||
for ai, ap in enumerate(andParts):
|
|
||||||
ap = ap.strip()
|
|
||||||
if ai > 0:
|
|
||||||
allLogics.append(".AND.")
|
|
||||||
allSubConds.append(ap)
|
|
||||||
for row in list(block._conditionRows):
|
|
||||||
block.condRowsLayout.removeWidget(row)
|
|
||||||
row.hide()
|
|
||||||
row.deleteLater()
|
|
||||||
block._conditionRows.clear()
|
|
||||||
for i, subCond in enumerate(allSubConds):
|
|
||||||
subCond = subCond.strip()
|
|
||||||
subCond = stripOuterParens(subCond)
|
|
||||||
isFirst = (i == 0)
|
|
||||||
row = ConditionRowFrame(
|
|
||||||
self._varMgr, block.blockIndex,
|
|
||||||
isFirst=isFirst, parent=block
|
|
||||||
)
|
|
||||||
if not isFirst:
|
|
||||||
row.deleteBtn.clicked.connect(
|
|
||||||
lambda _checked=False, r=row: block.removeConditionRow(r)
|
|
||||||
)
|
|
||||||
if i - 1 < len(allLogics):
|
|
||||||
logic = allLogics[i - 1]
|
|
||||||
for li in range(row.logicCombo.count()):
|
|
||||||
if row.logicCombo.itemData(li) == logic:
|
|
||||||
row.logicCombo.setCurrentIndex(li)
|
|
||||||
break
|
|
||||||
block._conditionRows.append(row)
|
|
||||||
block.condRowsLayout.addWidget(row)
|
|
||||||
subUp = subCond.upper()
|
|
||||||
if subUp in (".TRUE.", ".FALSE."):
|
|
||||||
row.loadFromParts(subUp, "", "")
|
|
||||||
else:
|
|
||||||
opSyms = [op for _, op in COMPARE_OPERATORS]
|
|
||||||
result = findOperatorIn(subCond, opSyms)
|
|
||||||
if result:
|
|
||||||
idx, op = result
|
|
||||||
leftPart = subCond[:idx].strip()
|
|
||||||
rightPart = subCond[idx + len(op):].strip()
|
|
||||||
row.loadFromParts(leftPart, op, rightPart)
|
|
||||||
else:
|
|
||||||
row.loadFromParts(subCond, "", "")
|
|
||||||
if not block._conditionRows:
|
|
||||||
block.addInitialConditionRow()
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
"""
|
|
||||||
Orchestration observer for AutoScript scripts.
|
|
||||||
Subscribes to ASTokenizer parsing events to produce a structured
|
|
||||||
block representation for the orchestration dialog UI.
|
|
||||||
"""
|
|
||||||
from autoscript.ASObserver import ParsingObserver
|
|
||||||
from autoscript.ASTokenizer import (
|
|
||||||
ASTokenizer,
|
|
||||||
K_IF,
|
|
||||||
K_ELSE_IF,
|
|
||||||
K_ELSE,
|
|
||||||
K_ENDIF,
|
|
||||||
K_SET,
|
|
||||||
K_ADD,
|
|
||||||
K_SUB,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = ["ScriptOrchObserver", "parseBlocks"]
|
|
||||||
|
|
||||||
|
|
||||||
class ScriptOrchObserver(ParsingObserver):
|
|
||||||
"""
|
|
||||||
Builds an ordered list of (block_type, condition, actions) tuples
|
|
||||||
from tokenization events.
|
|
||||||
|
|
||||||
Each block:
|
|
||||||
(type: str, condition: str | None, actions: list[(target, value_expr, op_type)])
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
|
|
||||||
super().__init__()
|
|
||||||
self._blocks = []
|
|
||||||
self._current_type = None
|
|
||||||
self._current_condition = None
|
|
||||||
self._current_actions = []
|
|
||||||
|
|
||||||
|
|
||||||
def onTokenParsed(
|
|
||||||
self,
|
|
||||||
kind: str | None,
|
|
||||||
data,
|
|
||||||
line_num: int,
|
|
||||||
raw_line: str
|
|
||||||
):
|
|
||||||
|
|
||||||
if kind in (K_IF, K_ELSE_IF, K_ELSE):
|
|
||||||
self._flushCurrentBlock()
|
|
||||||
self._current_type = kind
|
|
||||||
self._current_condition = data if kind != K_ELSE else None
|
|
||||||
self._current_actions = []
|
|
||||||
elif kind in (K_SET, K_ADD, K_SUB):
|
|
||||||
target, value = data
|
|
||||||
if kind == K_SET:
|
|
||||||
self._current_actions.append((target, value, "set"))
|
|
||||||
elif kind == K_ADD:
|
|
||||||
self._current_actions.append((target, f"+{value}", "add"))
|
|
||||||
else:
|
|
||||||
self._current_actions.append((target, f"-{value}", "sub"))
|
|
||||||
elif kind == K_ENDIF:
|
|
||||||
self._flushCurrentBlock()
|
|
||||||
self._current_type = None
|
|
||||||
self._current_condition = None
|
|
||||||
self._current_actions = []
|
|
||||||
|
|
||||||
|
|
||||||
def onParseComplete(
|
|
||||||
self,
|
|
||||||
statements: list
|
|
||||||
):
|
|
||||||
|
|
||||||
self._flushCurrentBlock()
|
|
||||||
|
|
||||||
|
|
||||||
def _flushCurrentBlock(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
|
|
||||||
if self._current_type is not None:
|
|
||||||
self._blocks.append((
|
|
||||||
self._current_type,
|
|
||||||
self._current_condition,
|
|
||||||
list(self._current_actions),
|
|
||||||
))
|
|
||||||
|
|
||||||
@property
|
|
||||||
def blocks(
|
|
||||||
self
|
|
||||||
) -> list:
|
|
||||||
|
|
||||||
return list(self._blocks)
|
|
||||||
|
|
||||||
|
|
||||||
def parseBlocks(
|
|
||||||
script: str
|
|
||||||
) -> list:
|
|
||||||
"""
|
|
||||||
Tokenize a script via observer pipeline and return its
|
|
||||||
structured block representation.
|
|
||||||
"""
|
|
||||||
|
|
||||||
observer = ScriptOrchObserver()
|
|
||||||
ASTokenizer.tokenizeWithObservers(script, [observer])
|
|
||||||
return observer.blocks
|
|
||||||
@@ -1,163 +0,0 @@
|
|||||||
"""
|
|
||||||
Pre-check observer for AutoScript scripts.
|
|
||||||
Subscribes to ASTokenizer parsing events to validate script syntax
|
|
||||||
before it reaches the orchestration dialog, eliminating duplicate parsing.
|
|
||||||
"""
|
|
||||||
from autoscript.ASObserver import ParsingObserver
|
|
||||||
from autoscript.ASTokenizer import (
|
|
||||||
K_IF,
|
|
||||||
K_ELSE_IF,
|
|
||||||
K_ELSE,
|
|
||||||
K_ENDIF,
|
|
||||||
K_SET,
|
|
||||||
K_ADD,
|
|
||||||
K_SUB,
|
|
||||||
ASTokenizer,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = ["ScriptPrecheckObserver", "precheck"]
|
|
||||||
|
|
||||||
|
|
||||||
class ScriptPrecheckObserver(ParsingObserver):
|
|
||||||
"""
|
|
||||||
Validates script syntax and structure during tokenization.
|
|
||||||
|
|
||||||
Checks performed:
|
|
||||||
- IF/ENDIF depth matching
|
|
||||||
- No nested IF blocks (orchestration limitation)
|
|
||||||
- ELSE IF / ELSE appear only inside an IF block
|
|
||||||
- Only allowed variables appear in SET/ADD/SUB targets
|
|
||||||
- No completely unrecognized syntax lines
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
allowed_vars: set = None
|
|
||||||
):
|
|
||||||
|
|
||||||
super().__init__()
|
|
||||||
self._allowed = allowed_vars or set()
|
|
||||||
self._if_depth = 0
|
|
||||||
self.errors = []
|
|
||||||
self._stmts = []
|
|
||||||
|
|
||||||
|
|
||||||
def onTokenParsed(
|
|
||||||
self,
|
|
||||||
kind: str | None,
|
|
||||||
data,
|
|
||||||
line_num: int,
|
|
||||||
raw_line: str
|
|
||||||
):
|
|
||||||
|
|
||||||
if kind == K_IF:
|
|
||||||
self._if_depth += 1
|
|
||||||
if self._if_depth > 1:
|
|
||||||
self.errors.append(
|
|
||||||
f"静态检查:错误(第{line_num}行): 检测到嵌套 IF,编排窗口不支持嵌套条件块。"
|
|
||||||
)
|
|
||||||
elif kind == K_ELSE_IF:
|
|
||||||
if self._if_depth < 1:
|
|
||||||
self.errors.append(
|
|
||||||
f"静态检查:错误(第{line_num}行): ELSE IF 前缺少 IF。"
|
|
||||||
)
|
|
||||||
elif kind == K_ELSE:
|
|
||||||
if self._if_depth < 1:
|
|
||||||
self.errors.append(
|
|
||||||
f"静态检查:错误(第{line_num}行): ELSE 前缺少 IF。"
|
|
||||||
)
|
|
||||||
elif kind == K_ENDIF:
|
|
||||||
self._if_depth -= 1
|
|
||||||
if self._if_depth < 0:
|
|
||||||
self.errors.append(
|
|
||||||
f"静态检查:错误(第{line_num}行): 多余的 ENDIF。"
|
|
||||||
)
|
|
||||||
elif kind is None:
|
|
||||||
self.errors.append(
|
|
||||||
f"静态检查:错误(第{line_num}行): 无法识别的语法 '{raw_line}'。"
|
|
||||||
)
|
|
||||||
elif kind in (K_SET, K_ADD, K_SUB):
|
|
||||||
target = data[0] if isinstance(data, tuple) else ""
|
|
||||||
if self._allowed and target.upper() not in self._allowed:
|
|
||||||
self.errors.append(
|
|
||||||
f"静态检查:错误(第{line_num}行): 目标变量 '{target}' 不是预设变量,"
|
|
||||||
f"编排窗口不支持。"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def onParseComplete(
|
|
||||||
self,
|
|
||||||
statements: list
|
|
||||||
):
|
|
||||||
|
|
||||||
if self._if_depth != 0:
|
|
||||||
self.errors.append(
|
|
||||||
f"静态检查:错误(不适用): IF 与 ENDIF 不匹配。")
|
|
||||||
self._stmts = statements
|
|
||||||
|
|
||||||
@property
|
|
||||||
def valid(
|
|
||||||
self
|
|
||||||
) -> bool:
|
|
||||||
|
|
||||||
return len(self.errors) == 0
|
|
||||||
|
|
||||||
|
|
||||||
def getErrorMessage(
|
|
||||||
self
|
|
||||||
) -> str:
|
|
||||||
|
|
||||||
return self.errors[0] if self.errors else ""
|
|
||||||
|
|
||||||
|
|
||||||
def buildSimplifiedScript(
|
|
||||||
self
|
|
||||||
) -> str:
|
|
||||||
"""Replace all non-control-flow statements with PASS for engine validation."""
|
|
||||||
|
|
||||||
lines = []
|
|
||||||
for stmt in self._stmts:
|
|
||||||
if stmt.kind in (K_IF, K_ELSE_IF, K_ELSE, K_ENDIF):
|
|
||||||
lines.append(stmt.raw_line)
|
|
||||||
else:
|
|
||||||
lines.append("PASS")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
|
|
||||||
def precheck(
|
|
||||||
script: str,
|
|
||||||
allowed_vars: set = None
|
|
||||||
) -> tuple[bool, str]:
|
|
||||||
"""
|
|
||||||
Run the full precheck pipeline on a script.
|
|
||||||
|
|
||||||
Steps:
|
|
||||||
1. Create a ScriptPrecheckObserver and subscribe it to an ASTokenizer.
|
|
||||||
2. Tokenize — the observer validates syntax during token events.
|
|
||||||
3. Replace action lines with PASS and run engine validation
|
|
||||||
with mock target data.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if not script or not script.strip():
|
|
||||||
return True, ""
|
|
||||||
observer = ScriptPrecheckObserver(allowed_vars=allowed_vars)
|
|
||||||
ASTokenizer.tokenizeWithObservers(script, [observer])
|
|
||||||
if not observer.valid:
|
|
||||||
return False, observer.getErrorMessage()
|
|
||||||
simplified = observer.buildSimplifiedScript()
|
|
||||||
if not simplified.strip():
|
|
||||||
return True, ""
|
|
||||||
try:
|
|
||||||
from autoscript import (
|
|
||||||
registerDefaultTargetVars,
|
|
||||||
buildMockTargetData,
|
|
||||||
execute
|
|
||||||
)
|
|
||||||
registerDefaultTargetVars()
|
|
||||||
execute(simplified, buildMockTargetData())
|
|
||||||
except ValueError as e:
|
|
||||||
return False, f"运行时检查: {e}"
|
|
||||||
except Exception:
|
|
||||||
return False, "执行环境异常,请检查 AutoScript 配置。"
|
|
||||||
return True, ""
|
|
||||||
@@ -1,5 +1,14 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
Widget components for the AutoScript orchestration dialog.
|
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.QtCore import Slot
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
@@ -13,21 +22,19 @@ from PySide6.QtWidgets import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
from gui.ALAutoScriptOrchDialog._helpers import (
|
from gui.ALAutoScriptOrchDialog._helpers import (
|
||||||
ACTION_TYPES,
|
ACTION_OPTIONS,
|
||||||
ARITH_TYPES,
|
COMPARE_OPTIONS,
|
||||||
COMPARE_OPERATORS,
|
LOGIC_OPTIONS,
|
||||||
LOGIC_OPERATORS,
|
|
||||||
PRESET_VARIABLES,
|
|
||||||
VAR_TYPE_ORDER,
|
|
||||||
encodeValueStr,
|
encodeValueStr,
|
||||||
|
getPresetVars,
|
||||||
|
getTypeOrder,
|
||||||
getValueFromWidget,
|
getValueFromWidget,
|
||||||
isVarReference,
|
getArithType,
|
||||||
makeComboWidget,
|
makeComboWidget,
|
||||||
makeLabel,
|
makeLabel,
|
||||||
makeOffsetWidget,
|
makeOffsetWidget,
|
||||||
makeValueWidget,
|
makeValueWidget,
|
||||||
makeVarRefCombo,
|
makeVarRefCombo,
|
||||||
setWidgetValue,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -35,22 +42,22 @@ class ConditionRowFrame(QFrame):
|
|||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
varMgr,
|
var_mgr,
|
||||||
parentBlockIndex: int = 0,
|
parent_block_index: int = 0,
|
||||||
isFirst: bool = False,
|
is_first: bool = False,
|
||||||
parent = None
|
parent = None
|
||||||
):
|
):
|
||||||
|
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self._varMgr = varMgr
|
self._var_mgr = var_mgr
|
||||||
self._blockIndex = parentBlockIndex
|
self._block_index = parent_block_index
|
||||||
self._isFirst = isFirst
|
self._is_first = is_first
|
||||||
self._isBoolMode = False
|
self._is_bool_mode = False
|
||||||
|
self._raw_rhs_expr = ""
|
||||||
|
|
||||||
self.setupUi()
|
self.setupUi()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -59,73 +66,153 @@ class ConditionRowFrame(QFrame):
|
|||||||
self.setFrameShape(QFrame.StyledPanel)
|
self.setFrameShape(QFrame.StyledPanel)
|
||||||
self.setFrameShadow(QFrame.Raised)
|
self.setFrameShadow(QFrame.Raised)
|
||||||
self.setFixedHeight(32)
|
self.setFixedHeight(32)
|
||||||
layout = QHBoxLayout(self)
|
Layout = QHBoxLayout(self)
|
||||||
layout.setContentsMargins(2, 2, 2, 2)
|
Layout.setContentsMargins(2, 2, 2, 2)
|
||||||
layout.setSpacing(4)
|
Layout.setSpacing(4)
|
||||||
if self._isFirst:
|
if self._is_first:
|
||||||
self.logicCombo = None
|
self.LogicCombo = None
|
||||||
else:
|
else:
|
||||||
self.logicCombo = makeComboWidget(LOGIC_OPERATORS, min_width=110, parent=self)
|
self.LogicCombo = makeComboWidget(LOGIC_OPTIONS, min_width=110, parent=self)
|
||||||
layout.addWidget(self.logicCombo)
|
Layout.addWidget(self.LogicCombo)
|
||||||
self.leftVarCombo = QComboBox(self)
|
self.LeftVarCombo = QComboBox(self)
|
||||||
self.leftVarCombo.setFixedHeight(25)
|
self.LeftVarCombo.setFixedHeight(25)
|
||||||
self.leftVarCombo.setMinimumWidth(120)
|
self.LeftVarCombo.setMinimumWidth(120)
|
||||||
self.leftVarCombo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
|
self.LeftVarCombo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
|
||||||
self.populateLeftVarCombo()
|
self.populateLeftVarCombo()
|
||||||
layout.addWidget(self.leftVarCombo)
|
Layout.addWidget(self.LeftVarCombo)
|
||||||
self.opCombo = makeComboWidget(COMPARE_OPERATORS, min_width=80, parent=self)
|
self.OpCombo = makeComboWidget(COMPARE_OPTIONS, min_width=80, parent=self)
|
||||||
layout.addWidget(self.opCombo)
|
Layout.addWidget(self.OpCombo)
|
||||||
self._compTypeCombo = makeComboWidget([
|
self.CompTypeCombo = makeComboWidget([
|
||||||
("特定值", "literal"),
|
("特定值", "literal"),
|
||||||
("变量", "variable"),
|
("变量", "variable"),
|
||||||
], min_width=70, parent=self)
|
], min_width=70, parent=self)
|
||||||
layout.addWidget(self._compTypeCombo)
|
Layout.addWidget(self.CompTypeCombo)
|
||||||
self.rhsStack = QStackedWidget(self)
|
self.RhsStack = QStackedWidget(self)
|
||||||
self.rhsStack.setFixedHeight(25)
|
self.RhsStack.setFixedHeight(25)
|
||||||
self.literalStack = QStackedWidget(self)
|
self.initLiteralStack()
|
||||||
self.literalStack.setFixedHeight(25)
|
self.RhsVarCombo = makeVarRefCombo(self)
|
||||||
self.literalWidgets = {}
|
self.RhsStack.addWidget(self.RhsVarCombo)
|
||||||
for vt in VAR_TYPE_ORDER:
|
self.RhsStack.setCurrentIndex(0)
|
||||||
w = makeValueWidget(vt, self.literalStack)
|
Layout.addWidget(self.RhsStack)
|
||||||
self.literalWidgets[vt] = w
|
if not self._is_first:
|
||||||
self.literalStack.addWidget(w)
|
self.DeleteBtn = QPushButton("×", self)
|
||||||
self.literalStack.setCurrentWidget(self.literalWidgets.get("String"))
|
self.DeleteBtn.setFixedSize(25, 25)
|
||||||
self.rhsStack.addWidget(self.literalStack)
|
self.DeleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||||
self.rhsVarCombo = makeVarRefCombo(self)
|
Layout.addWidget(self.DeleteBtn)
|
||||||
self.rhsStack.addWidget(self.rhsVarCombo)
|
|
||||||
self.rhsStack.setCurrentIndex(0)
|
|
||||||
layout.addWidget(self.rhsStack)
|
|
||||||
if not self._isFirst:
|
|
||||||
self.deleteBtn = QPushButton("×", self)
|
|
||||||
self.deleteBtn.setFixedSize(25, 25)
|
|
||||||
self.deleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
|
||||||
layout.addWidget(self.deleteBtn)
|
|
||||||
else:
|
else:
|
||||||
self.deleteBtn = None
|
self.DeleteBtn = None
|
||||||
layout.addStretch()
|
Layout.addStretch()
|
||||||
self.setUpdatesEnabled(True)
|
self.setUpdatesEnabled(True)
|
||||||
|
|
||||||
|
|
||||||
def populateLeftVarCombo(
|
def populateLeftVarCombo(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self._varMgr.populateCombo(self.leftVarCombo)
|
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(
|
||||||
def populateRhsVarCombo(
|
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self._varMgr.populateCombo(self.rhsVarCombo)
|
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(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.leftVarCombo.currentIndexChanged.connect(self.onLeftVarChanged)
|
self.LeftVarCombo.currentIndexChanged.connect(self.onLeftVarChanged)
|
||||||
self._compTypeCombo.currentIndexChanged.connect(self.onCompTypeChanged)
|
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)
|
@Slot(int)
|
||||||
def onLeftVarChanged(
|
def onLeftVarChanged(
|
||||||
@@ -133,23 +220,20 @@ class ConditionRowFrame(QFrame):
|
|||||||
idx
|
idx
|
||||||
):
|
):
|
||||||
|
|
||||||
|
self._raw_rhs_expr = ""
|
||||||
if idx < 0:
|
if idx < 0:
|
||||||
return
|
return
|
||||||
data = self.leftVarCombo.itemData(idx)
|
data = self.LeftVarCombo.itemData(idx)
|
||||||
if not data:
|
if not data:
|
||||||
return
|
return
|
||||||
_, vartype = data
|
name, vartype = data
|
||||||
self.updateRhsLiteralWidget(vartype)
|
is_bool = name in ("true", "false")
|
||||||
|
self._is_bool_mode = is_bool
|
||||||
|
self.OpCombo.setVisible(not is_bool)
|
||||||
def updateRhsLiteralWidget(
|
self.CompTypeCombo.setVisible(not is_bool)
|
||||||
self,
|
self.RhsStack.setVisible(not is_bool)
|
||||||
vartype: str
|
if not is_bool:
|
||||||
):
|
self.updateRHSLiteralWidget(vartype)
|
||||||
|
|
||||||
if vartype not in self.literalWidgets:
|
|
||||||
vartype = "String"
|
|
||||||
self.literalStack.setCurrentWidget(self.literalWidgets[vartype])
|
|
||||||
|
|
||||||
@Slot(int)
|
@Slot(int)
|
||||||
def onCompTypeChanged(
|
def onCompTypeChanged(
|
||||||
@@ -157,118 +241,30 @@ class ConditionRowFrame(QFrame):
|
|||||||
idx
|
idx
|
||||||
):
|
):
|
||||||
|
|
||||||
isVar = (self._compTypeCombo.currentData() == "variable")
|
self._raw_rhs_expr = ""
|
||||||
self.rhsStack.setCurrentIndex(1 if isVar else 0)
|
isVar = (self.CompTypeCombo.currentData() == "variable")
|
||||||
|
self.RhsStack.setCurrentIndex(1 if isVar else 0)
|
||||||
if isVar:
|
if isVar:
|
||||||
self.populateRhsVarCombo()
|
self.populateRHSVarCombo()
|
||||||
|
|
||||||
|
|
||||||
def getLogic(
|
|
||||||
self
|
|
||||||
) -> str:
|
|
||||||
|
|
||||||
return self.logicCombo.currentData() if self.logicCombo else ""
|
|
||||||
|
|
||||||
|
|
||||||
def toConditionText(
|
|
||||||
self
|
|
||||||
) -> str:
|
|
||||||
|
|
||||||
data = self.leftVarCombo.currentData()
|
|
||||||
if not data:
|
|
||||||
return ""
|
|
||||||
name, vartype = data
|
|
||||||
opSym = self.opCombo.currentData()
|
|
||||||
isVarRef = (self._compTypeCombo.currentData() == "variable")
|
|
||||||
if isVarRef:
|
|
||||||
rd = self.rhsVarCombo.currentData()
|
|
||||||
if rd:
|
|
||||||
rhsName = rd[0]
|
|
||||||
return f"{name} {opSym} {rhsName}"
|
|
||||||
rhsText = self.rhsVarCombo.currentText().strip()
|
|
||||||
if rhsText:
|
|
||||||
return f"{name} {opSym} {rhsText}"
|
|
||||||
return ""
|
|
||||||
w = self.literalWidgets.get(vartype)
|
|
||||||
if w:
|
|
||||||
rawVal = getValueFromWidget(w)
|
|
||||||
encoded = encodeValueStr(rawVal, vartype)
|
|
||||||
return f"{name} {opSym} {encoded}"
|
|
||||||
return ""
|
|
||||||
|
|
||||||
|
|
||||||
def loadFromParts(
|
|
||||||
self,
|
|
||||||
operandName: str,
|
|
||||||
opSym: str,
|
|
||||||
valueExpr: str
|
|
||||||
):
|
|
||||||
|
|
||||||
for ci in range(self.leftVarCombo.count()):
|
|
||||||
d = self.leftVarCombo.itemData(ci)
|
|
||||||
if d and d[0] == operandName:
|
|
||||||
self.leftVarCombo.setCurrentIndex(ci)
|
|
||||||
break
|
|
||||||
if opSym:
|
|
||||||
for oi in range(self.opCombo.count()):
|
|
||||||
if self.opCombo.itemData(oi) == opSym:
|
|
||||||
self.opCombo.setCurrentIndex(oi)
|
|
||||||
break
|
|
||||||
if not valueExpr:
|
|
||||||
return
|
|
||||||
up = valueExpr.strip().upper()
|
|
||||||
data = self.leftVarCombo.currentData()
|
|
||||||
vartype = data[1] if data else "String"
|
|
||||||
if isVarReference(valueExpr) or self._isKnownVar(up):
|
|
||||||
self._compTypeCombo.setCurrentIndex(1)
|
|
||||||
self.populateRhsVarCombo()
|
|
||||||
found = self._varMgr.findExactNameEntry(self.rhsVarCombo, up)
|
|
||||||
if found >= 0:
|
|
||||||
self.rhsVarCombo.setCurrentIndex(found)
|
|
||||||
else:
|
|
||||||
self.rhsVarCombo.addItem(up, (up, "String"))
|
|
||||||
self.rhsVarCombo.setCurrentIndex(self.rhsVarCombo.count() - 1)
|
|
||||||
else:
|
|
||||||
self._compTypeCombo.setCurrentIndex(0)
|
|
||||||
w = self.literalWidgets.get(vartype)
|
|
||||||
if w:
|
|
||||||
setWidgetValue(w, vartype, valueExpr)
|
|
||||||
|
|
||||||
|
|
||||||
def _isKnownVar(
|
|
||||||
self,
|
|
||||||
name: str
|
|
||||||
) -> bool:
|
|
||||||
|
|
||||||
return self._varMgr.getInfoByName(name) is not None
|
|
||||||
|
|
||||||
|
|
||||||
def refreshVarCombos(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
|
|
||||||
self.populateLeftVarCombo()
|
|
||||||
self.populateRhsVarCombo()
|
|
||||||
|
|
||||||
|
|
||||||
class ActionStepFrame(QFrame):
|
class ActionStepFrame(QFrame):
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
varMgr,
|
var_mgr,
|
||||||
parentBlockIndex: int = 0,
|
parent_block_index: int = 0,
|
||||||
parent = None
|
parent = None
|
||||||
):
|
):
|
||||||
|
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self._varMgr = varMgr
|
self._var_mgr = var_mgr
|
||||||
self._blockIndex = parentBlockIndex
|
self._block_index = parent_block_index
|
||||||
self._currentTargetType = "String"
|
self._current_target_type = "String"
|
||||||
|
|
||||||
self.setupUi()
|
self.setupUi()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -277,81 +273,161 @@ class ActionStepFrame(QFrame):
|
|||||||
self.setFrameShape(QFrame.StyledPanel)
|
self.setFrameShape(QFrame.StyledPanel)
|
||||||
self.setFrameShadow(QFrame.Raised)
|
self.setFrameShadow(QFrame.Raised)
|
||||||
self.setFixedHeight(35)
|
self.setFixedHeight(35)
|
||||||
layout = QHBoxLayout(self)
|
Layout = QHBoxLayout(self)
|
||||||
layout.setContentsMargins(2, 2, 2, 2)
|
Layout.setContentsMargins(2, 2, 2, 2)
|
||||||
layout.setSpacing(4)
|
Layout.setSpacing(4)
|
||||||
self.opTypeCombo = makeComboWidget(ACTION_TYPES, min_width=70, parent=self)
|
self.OpTypeCombo = makeComboWidget(ACTION_OPTIONS, min_width=70, parent=self)
|
||||||
layout.addWidget(self.opTypeCombo)
|
Layout.addWidget(self.OpTypeCombo)
|
||||||
layout.addWidget(makeLabel("设置", self))
|
Layout.addWidget(makeLabel("设置", self))
|
||||||
self.targetCombo = QComboBox(self)
|
self.TargetCombo = QComboBox(self)
|
||||||
self.targetCombo.setFixedHeight(25)
|
self.TargetCombo.setFixedHeight(25)
|
||||||
self.targetCombo.setMinimumWidth(120)
|
self.TargetCombo.setMinimumWidth(120)
|
||||||
self.buildTargetCombo()
|
self.populateTargetCombo()
|
||||||
layout.addWidget(self.targetCombo)
|
Layout.addWidget(self.TargetCombo)
|
||||||
layout.addWidget(makeLabel("为", self))
|
Layout.addWidget(makeLabel("为", self))
|
||||||
self.valueSrcCombo = makeComboWidget([
|
self.ValueSrcCombo = makeComboWidget([
|
||||||
("特定值", "literal"),
|
("特定值", "literal"),
|
||||||
("变量", "variable"),
|
("变量", "variable"),
|
||||||
], min_width=70, parent=self)
|
], min_width=70, parent=self)
|
||||||
layout.addWidget(self.valueSrcCombo)
|
Layout.addWidget(self.ValueSrcCombo)
|
||||||
self.valueStack = QStackedWidget(self)
|
self.ValueStack = QStackedWidget(self)
|
||||||
self.valueStack.setFixedHeight(25)
|
self.ValueStack.setFixedHeight(25)
|
||||||
self.initValueStacks()
|
self.initValueStacks()
|
||||||
layout.addWidget(self.valueStack)
|
Layout.addWidget(self.ValueStack)
|
||||||
self.existingVarCombo = makeVarRefCombo(self)
|
self.ExistingVarCombo = makeVarRefCombo(self)
|
||||||
self.existingVarCombo.setVisible(False)
|
self.ExistingVarCombo.setVisible(False)
|
||||||
layout.addWidget(self.existingVarCombo)
|
Layout.addWidget(self.ExistingVarCombo)
|
||||||
self.deleteBtn = QPushButton("×", self)
|
self.DeleteBtn = QPushButton("×", self)
|
||||||
self.deleteBtn.setFixedSize(25, 25)
|
self.DeleteBtn.setFixedSize(25, 25)
|
||||||
self.deleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
self.DeleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||||
layout.addWidget(self.deleteBtn)
|
Layout.addWidget(self.DeleteBtn)
|
||||||
self.setUpdatesEnabled(True)
|
self.setUpdatesEnabled(True)
|
||||||
|
|
||||||
|
def populateTargetCombo(
|
||||||
def buildTargetCombo(
|
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.targetCombo.blockSignals(True)
|
self.TargetCombo.blockSignals(True)
|
||||||
self.targetCombo.clear()
|
self.TargetCombo.clear()
|
||||||
for p in PRESET_VARIABLES:
|
for p in getPresetVars():
|
||||||
if p["name"] in ("CURRENT_TIME", "CURRENT_DATE"):
|
if p["name"] in ("CURRENT_TIME", "CURRENT_DATE"):
|
||||||
continue
|
continue
|
||||||
info = self._varMgr.getInfoByName(p["name"])
|
info = self._var_mgr.getInfoByName(p["name"])
|
||||||
if info:
|
if info:
|
||||||
self.targetCombo.addItem(
|
self.TargetCombo.addItem(
|
||||||
info["display"],
|
info["display"],
|
||||||
(info["name"], info["type"])
|
(info["name"], info["type"])
|
||||||
)
|
)
|
||||||
self.targetCombo.blockSignals(False)
|
self.TargetCombo.blockSignals(False)
|
||||||
|
|
||||||
|
|
||||||
def initValueStacks(
|
def initValueStacks(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self._literalWidgets = {}
|
self.literal_widgets = {}
|
||||||
self._offsetWidgets = {}
|
self.offset_widgets = {}
|
||||||
for vt in VAR_TYPE_ORDER:
|
for vt in getTypeOrder():
|
||||||
self._literalWidgets[vt] = makeValueWidget(vt, self.valueStack)
|
self.literal_widgets[vt] = makeValueWidget(vt, self.ValueStack)
|
||||||
self.valueStack.addWidget(self._literalWidgets[vt])
|
self.ValueStack.addWidget(self.literal_widgets[vt])
|
||||||
if vt in ARITH_TYPES:
|
if getArithType(vt):
|
||||||
self._offsetWidgets[vt] = makeOffsetWidget(vt, self.valueStack)
|
self.offset_widgets[vt] = makeOffsetWidget(vt, self.ValueStack)
|
||||||
self.valueStack.addWidget(self._offsetWidgets[vt])
|
self.ValueStack.addWidget(self.offset_widgets[vt])
|
||||||
else:
|
else:
|
||||||
lbl = QLabel("(不支持该操作)", self.valueStack)
|
Lbl = QLabel("(不支持该操作)", self.ValueStack)
|
||||||
lbl.setFixedHeight(25)
|
Lbl.setFixedHeight(25)
|
||||||
self._offsetWidgets[vt] = lbl
|
self.offset_widgets[vt] = Lbl
|
||||||
self.valueStack.addWidget(lbl)
|
self.ValueStack.addWidget(Lbl)
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.opTypeCombo.currentIndexChanged.connect(self.onOpTypeChanged)
|
self.OpTypeCombo.currentIndexChanged.connect(self.onOpTypeChanged)
|
||||||
self.targetCombo.currentIndexChanged.connect(self.onTargetChanged)
|
self.TargetCombo.currentIndexChanged.connect(self.onTargetChanged)
|
||||||
self.valueSrcCombo.currentIndexChanged.connect(self.onValueSrcChanged)
|
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)
|
@Slot(int)
|
||||||
def onTargetChanged(
|
def onTargetChanged(
|
||||||
@@ -361,13 +437,13 @@ class ActionStepFrame(QFrame):
|
|||||||
|
|
||||||
if idx < 0:
|
if idx < 0:
|
||||||
return
|
return
|
||||||
data = self.targetCombo.itemData(idx)
|
data = self.TargetCombo.itemData(idx)
|
||||||
if not data:
|
if not data:
|
||||||
return
|
return
|
||||||
_, vartype = data
|
_, vartype = data
|
||||||
self._currentTargetType = vartype
|
self._current_target_type = vartype
|
||||||
self.updateRHSWidget()
|
self.updateValueWidget()
|
||||||
self.onValueSrcChanged(self.valueSrcCombo.currentIndex())
|
self.onValueSrcChanged(self.ValueSrcCombo.currentIndex())
|
||||||
|
|
||||||
@Slot(int)
|
@Slot(int)
|
||||||
def onOpTypeChanged(
|
def onOpTypeChanged(
|
||||||
@@ -375,22 +451,7 @@ class ActionStepFrame(QFrame):
|
|||||||
idx
|
idx
|
||||||
):
|
):
|
||||||
|
|
||||||
self.updateRHSWidget()
|
self.updateValueWidget()
|
||||||
|
|
||||||
|
|
||||||
def updateRHSWidget(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
|
|
||||||
op = self.opTypeCombo.currentData()
|
|
||||||
isArith = (op in ("add", "sub"))
|
|
||||||
actualType = self._currentTargetType
|
|
||||||
if isArith and actualType in self._offsetWidgets:
|
|
||||||
self.valueStack.setCurrentWidget(self._offsetWidgets[actualType])
|
|
||||||
elif actualType in self._literalWidgets:
|
|
||||||
self.valueStack.setCurrentWidget(self._literalWidgets[actualType])
|
|
||||||
else:
|
|
||||||
self.valueStack.setCurrentWidget(self._literalWidgets.get("String"))
|
|
||||||
|
|
||||||
@Slot(int)
|
@Slot(int)
|
||||||
def onValueSrcChanged(
|
def onValueSrcChanged(
|
||||||
@@ -398,135 +459,10 @@ class ActionStepFrame(QFrame):
|
|||||||
idx
|
idx
|
||||||
):
|
):
|
||||||
|
|
||||||
isVar = (self.valueSrcCombo.currentData() == "variable")
|
is_var = (self.ValueSrcCombo.currentData() == "variable")
|
||||||
self.valueStack.setVisible(not isVar)
|
self.ValueStack.setVisible(not is_var)
|
||||||
self.existingVarCombo.setVisible(isVar)
|
self.ExistingVarCombo.setVisible(is_var)
|
||||||
if isVar:
|
if is_var:
|
||||||
self._varMgr.populateCombo(self.existingVarCombo)
|
self._var_mgr.populateCombo(self.ExistingVarCombo)
|
||||||
else:
|
else:
|
||||||
self.updateRHSWidget()
|
self.updateValueWidget()
|
||||||
|
|
||||||
|
|
||||||
def getTargetName(
|
|
||||||
self
|
|
||||||
) -> str:
|
|
||||||
|
|
||||||
data = self.targetCombo.currentData()
|
|
||||||
return data[0] if data else ""
|
|
||||||
|
|
||||||
|
|
||||||
def toScriptLine(
|
|
||||||
self
|
|
||||||
) -> str:
|
|
||||||
|
|
||||||
target = self.getTargetName()
|
|
||||||
if not target:
|
|
||||||
return ""
|
|
||||||
op = self.opTypeCombo.currentData()
|
|
||||||
rawVal = self._getValueRaw()
|
|
||||||
if op == "set":
|
|
||||||
vartype = self._currentTargetType
|
|
||||||
encoded = encodeValueStr(rawVal, vartype)
|
|
||||||
if vartype == "Time":
|
|
||||||
if rawVal.startswith("+"):
|
|
||||||
return f" {target} .ADD. {rawVal[1:]}"
|
|
||||||
if rawVal.startswith("-"):
|
|
||||||
return f" {target} .SUB. {rawVal[1:]}"
|
|
||||||
return f" SET {target} = {encoded}"
|
|
||||||
elif op == "add":
|
|
||||||
vartype = self._currentTargetType
|
|
||||||
if vartype == "Date" and hasattr(self.valueStack.currentWidget(), "getOffsetDays"):
|
|
||||||
days = self.valueStack.currentWidget().getOffsetDays()
|
|
||||||
return f" {target} .ADD. {days}"
|
|
||||||
if vartype == "Time" and hasattr(self.valueStack.currentWidget(), "getOffsetHours"):
|
|
||||||
hours = self.valueStack.currentWidget().getOffsetHours()
|
|
||||||
return f" {target} .ADD. {hours}"
|
|
||||||
return f" {target} .ADD. {rawVal}"
|
|
||||||
elif op == "sub":
|
|
||||||
vartype = self._currentTargetType
|
|
||||||
if vartype == "Date" and hasattr(self.valueStack.currentWidget(), "getOffsetDays"):
|
|
||||||
days = self.valueStack.currentWidget().getOffsetDays()
|
|
||||||
return f" {target} .SUB. {days}"
|
|
||||||
if vartype == "Time" and hasattr(self.valueStack.currentWidget(), "getOffsetHours"):
|
|
||||||
hours = self.valueStack.currentWidget().getOffsetHours()
|
|
||||||
return f" {target} .SUB. {hours}"
|
|
||||||
return f" {target} .SUB. {rawVal}"
|
|
||||||
return ""
|
|
||||||
|
|
||||||
|
|
||||||
def _getValueRaw(
|
|
||||||
self
|
|
||||||
) -> str:
|
|
||||||
|
|
||||||
if self.valueSrcCombo.currentData() == "variable":
|
|
||||||
return self.existingVarCombo.currentText().strip()
|
|
||||||
w = self.valueStack.currentWidget()
|
|
||||||
if w:
|
|
||||||
return getValueFromWidget(w)
|
|
||||||
return ""
|
|
||||||
|
|
||||||
|
|
||||||
def setOpType(
|
|
||||||
self,
|
|
||||||
opType: str
|
|
||||||
):
|
|
||||||
|
|
||||||
for i in range(self.opTypeCombo.count()):
|
|
||||||
if self.opTypeCombo.itemData(i) == opType:
|
|
||||||
self.opTypeCombo.setCurrentIndex(i)
|
|
||||||
break
|
|
||||||
|
|
||||||
|
|
||||||
def loadFromScript(
|
|
||||||
self,
|
|
||||||
targetVar: str,
|
|
||||||
valueExpr: str
|
|
||||||
):
|
|
||||||
|
|
||||||
targetUp = targetVar.upper().strip()
|
|
||||||
for ci in range(self.targetCombo.count()):
|
|
||||||
d = self.targetCombo.itemData(ci)
|
|
||||||
if d and d[0] == targetUp:
|
|
||||||
self.targetCombo.setCurrentIndex(ci)
|
|
||||||
break
|
|
||||||
self._setValueFromExpr(valueExpr)
|
|
||||||
|
|
||||||
|
|
||||||
def _setValueFromExpr(
|
|
||||||
self,
|
|
||||||
expr: str
|
|
||||||
):
|
|
||||||
|
|
||||||
s = expr.strip()
|
|
||||||
if not s:
|
|
||||||
return
|
|
||||||
up = s.upper()
|
|
||||||
if isVarReference(s):
|
|
||||||
self.valueSrcCombo.setCurrentIndex(1)
|
|
||||||
self._varMgr.populateCombo(self.existingVarCombo)
|
|
||||||
idx = self._varMgr.findExactNameEntry(self.existingVarCombo, up)
|
|
||||||
if idx >= 0:
|
|
||||||
self.existingVarCombo.setCurrentIndex(idx)
|
|
||||||
else:
|
|
||||||
self.existingVarCombo.addItem(up, (up, "String"))
|
|
||||||
self.existingVarCombo.setCurrentIndex(self.existingVarCombo.count() - 1)
|
|
||||||
else:
|
|
||||||
self.valueSrcCombo.setCurrentIndex(0)
|
|
||||||
w = self.valueStack.currentWidget()
|
|
||||||
if w:
|
|
||||||
setWidgetValue(w, self._currentTargetType, expr)
|
|
||||||
|
|
||||||
|
|
||||||
def refreshVarCombos(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
|
|
||||||
currentData = self.targetCombo.currentData()
|
|
||||||
self.buildTargetCombo()
|
|
||||||
if currentData:
|
|
||||||
for i in range(self.targetCombo.count()):
|
|
||||||
d = self.targetCombo.itemData(i)
|
|
||||||
if d and d[0] == currentData[0]:
|
|
||||||
self.targetCombo.setCurrentIndex(i)
|
|
||||||
break
|
|
||||||
self._varMgr.populateCombo(self.existingVarCombo)
|
|
||||||
@@ -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,31 +10,50 @@ See the LICENSE file for details.
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Qt, Signal, Slot, QTime, QDate, QDir, QFileInfo
|
QDate,
|
||||||
)
|
QDir,
|
||||||
from PySide6.QtWidgets import (
|
QFileInfo,
|
||||||
QDialog, QWidget, QLineEdit, QMessageBox, QFileDialog,
|
Qt,
|
||||||
QTreeWidgetItem, QMenu, QInputDialog
|
QTime,
|
||||||
|
Signal,
|
||||||
|
Slot
|
||||||
)
|
)
|
||||||
from PySide6.QtGui import (
|
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
|
import managers.config.ConfigManager as ConfigManager
|
||||||
|
|
||||||
from utils.JSONReader import JSONReader
|
|
||||||
from utils.JSONWriter import JSONWriter
|
|
||||||
from interfaces.ConfigProvider import ConfigProvider, CfgKey
|
|
||||||
from managers.config.ConfigUtils import ConfigUtils
|
|
||||||
|
|
||||||
from gui.resources.ui.Ui_ALConfigWidget import Ui_ALConfigWidget
|
|
||||||
from gui.ALSeatMapSelectDialog import ALSeatMapSelectDialog
|
from gui.ALSeatMapSelectDialog import ALSeatMapSelectDialog
|
||||||
from gui.ALSeatMapTable import ALSeatMapTable
|
from gui.ALSeatMapTable import ALSeatMapTable
|
||||||
from gui.ALUserTreeWidget import ALUserTreeWidget, ALUserTreeItemType
|
from gui.ALUserTreeWidget import (
|
||||||
|
ALUserTreeItemType,
|
||||||
|
ALUserTreeWidget
|
||||||
|
)
|
||||||
from gui.ALWebDriverDownloadDialog import ALWebDriverDownloadDialog
|
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()
|
configWidgetIsClosed = Signal()
|
||||||
|
|
||||||
@@ -54,7 +73,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
if not self.initializeConfigs():
|
if not self.initializeConfigs():
|
||||||
self.close()
|
self.close()
|
||||||
|
|
||||||
|
|
||||||
def modifyUi(
|
def modifyUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -70,7 +88,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
self.initializeFloorRoomMap()
|
self.initializeFloorRoomMap()
|
||||||
self.initializeUserInfoWidget()
|
self.initializeUserInfoWidget()
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -94,31 +111,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||||
self.CancelButton.clicked.connect(self.onCancelButtonClicked)
|
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(
|
def closeEvent(
|
||||||
self,
|
self,
|
||||||
event: QCloseEvent
|
event: QCloseEvent
|
||||||
@@ -127,7 +119,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
self.configWidgetIsClosed.emit()
|
self.configWidgetIsClosed.emit()
|
||||||
super().closeEvent(event)
|
super().closeEvent(event)
|
||||||
|
|
||||||
|
|
||||||
def initializeFloorRoomMap(
|
def initializeFloorRoomMap(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -161,7 +152,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
"五层": ["五层考研"]
|
"五层": ["五层考研"]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def initializeConfigToWidget(
|
def initializeConfigToWidget(
|
||||||
self,
|
self,
|
||||||
which: str,
|
which: str,
|
||||||
@@ -176,7 +166,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
self.setUsersToTreeWidget(config_data)
|
self.setUsersToTreeWidget(config_data)
|
||||||
self.CurrentUserConfigEdit.setText(self.__config_paths["user"])
|
self.CurrentUserConfigEdit.setText(self.__config_paths["user"])
|
||||||
|
|
||||||
|
|
||||||
def initializeConfig(
|
def initializeConfig(
|
||||||
self,
|
self,
|
||||||
which: str
|
which: str
|
||||||
@@ -210,7 +199,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
is_success = False
|
is_success = False
|
||||||
return is_success
|
return is_success
|
||||||
|
|
||||||
|
|
||||||
def initializeConfigs(
|
def initializeConfigs(
|
||||||
self
|
self
|
||||||
) -> bool:
|
) -> bool:
|
||||||
@@ -223,7 +211,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
self.initializeConfigToWidget(which, self.__config_data[which])
|
self.initializeConfigToWidget(which, self.__config_data[which])
|
||||||
return is_success
|
return is_success
|
||||||
|
|
||||||
|
|
||||||
def defaultRunConfig(
|
def defaultRunConfig(
|
||||||
self
|
self
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -247,7 +234,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def defaultUserConfig(
|
def defaultUserConfig(
|
||||||
self
|
self
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -257,7 +243,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def collectRunConfigFromWidget(
|
def collectRunConfigFromWidget(
|
||||||
self
|
self
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -279,7 +264,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
run_config["mode"]["run_mode"] = run_mode
|
run_config["mode"]["run_mode"] = run_mode
|
||||||
return run_config
|
return run_config
|
||||||
|
|
||||||
|
|
||||||
def setRunConfigToWidget(
|
def setRunConfigToWidget(
|
||||||
self,
|
self,
|
||||||
run_config: dict
|
run_config: dict
|
||||||
@@ -318,7 +302,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
"文件可能被意外修改或已经损坏\n"
|
"文件可能被意外修改或已经损坏\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def initializeUserInfoWidget(
|
def initializeUserInfoWidget(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -343,7 +326,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
self.MaxRenewTimeDiffSpinBox.setValue(30)
|
self.MaxRenewTimeDiffSpinBox.setValue(30)
|
||||||
self.PreferLateRenewTimeCheckBox.setChecked(False)
|
self.PreferLateRenewTimeCheckBox.setChecked(False)
|
||||||
|
|
||||||
|
|
||||||
def collectUserFromWidget(
|
def collectUserFromWidget(
|
||||||
self
|
self
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -376,7 +358,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
user["reserve_info"]["renew_time"]["prefer_early"] = not self.PreferLateRenewTimeCheckBox.isChecked()
|
user["reserve_info"]["renew_time"]["prefer_early"] = not self.PreferLateRenewTimeCheckBox.isChecked()
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
def collectUsersFromTreeWidget(
|
def collectUsersFromTreeWidget(
|
||||||
self
|
self
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -399,7 +380,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
user_config["groups"].append(group_config)
|
user_config["groups"].append(group_config)
|
||||||
return user_config
|
return user_config
|
||||||
|
|
||||||
|
|
||||||
def setUserToWidget(
|
def setUserToWidget(
|
||||||
self,
|
self,
|
||||||
user: dict
|
user: dict
|
||||||
@@ -441,7 +421,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
"文件可能被意外修改或已经损坏\n"
|
"文件可能被意外修改或已经损坏\n"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def setUsersToTreeWidget(
|
def setUsersToTreeWidget(
|
||||||
self,
|
self,
|
||||||
users: dict
|
users: dict
|
||||||
@@ -483,7 +462,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
finally:
|
finally:
|
||||||
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
||||||
|
|
||||||
|
|
||||||
def loadRunConfig(
|
def loadRunConfig(
|
||||||
self,
|
self,
|
||||||
run_config_path: str
|
run_config_path: str
|
||||||
@@ -507,7 +485,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def saveRunConfig(
|
def saveRunConfig(
|
||||||
self,
|
self,
|
||||||
run_config_path: str,
|
run_config_path: str,
|
||||||
@@ -529,7 +506,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def loadUserConfig(
|
def loadUserConfig(
|
||||||
self,
|
self,
|
||||||
user_config_path: str
|
user_config_path: str
|
||||||
@@ -563,7 +539,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def saveUserConfig(
|
def saveUserConfig(
|
||||||
self,
|
self,
|
||||||
user_config_path: str,
|
user_config_path: str,
|
||||||
@@ -585,7 +560,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def saveConfigs(
|
def saveConfigs(
|
||||||
self,
|
self,
|
||||||
run_config_path: str,
|
run_config_path: str,
|
||||||
@@ -608,7 +582,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def loadConfig(
|
def loadConfig(
|
||||||
self,
|
self,
|
||||||
config_path: str
|
config_path: str
|
||||||
@@ -637,7 +610,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
except:
|
except:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def addGroup(
|
def addGroup(
|
||||||
self,
|
self,
|
||||||
group_name: str = ""
|
group_name: str = ""
|
||||||
@@ -654,7 +626,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
||||||
return group_item
|
return group_item
|
||||||
|
|
||||||
|
|
||||||
def delGroup(
|
def delGroup(
|
||||||
self,
|
self,
|
||||||
group_item: QTreeWidgetItem = None
|
group_item: QTreeWidgetItem = None
|
||||||
@@ -667,7 +638,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
index = self.UserTreeWidget.indexOfTopLevelItem(group_item)
|
index = self.UserTreeWidget.indexOfTopLevelItem(group_item)
|
||||||
self.UserTreeWidget.takeTopLevelItem(index)
|
self.UserTreeWidget.takeTopLevelItem(index)
|
||||||
|
|
||||||
|
|
||||||
def addUser(
|
def addUser(
|
||||||
self,
|
self,
|
||||||
group_item: QTreeWidgetItem = None
|
group_item: QTreeWidgetItem = None
|
||||||
@@ -722,7 +692,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
self.UserTreeWidget.itemChanged.connect(self.onUserTreeWidgetItemChanged)
|
||||||
return user_item
|
return user_item
|
||||||
|
|
||||||
|
|
||||||
def delUser(
|
def delUser(
|
||||||
self,
|
self,
|
||||||
user_item: QTreeWidgetItem = None
|
user_item: QTreeWidgetItem = None
|
||||||
@@ -738,7 +707,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
if parent_item.childCount() == 0:
|
if parent_item.childCount() == 0:
|
||||||
self.UserTreeWidget.setCurrentItem(None)
|
self.UserTreeWidget.setCurrentItem(None)
|
||||||
|
|
||||||
|
|
||||||
def renameItem(
|
def renameItem(
|
||||||
self,
|
self,
|
||||||
item: QTreeWidgetItem,
|
item: QTreeWidgetItem,
|
||||||
@@ -797,19 +765,19 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
room = self.RoomComboBox.currentText()
|
room = self.RoomComboBox.currentText()
|
||||||
floor_idx = self.__floor_rmap[floor]
|
floor_idx = self.__floor_rmap[floor]
|
||||||
room_idx = self.__room_rmap[room]
|
room_idx = self.__room_rmap[room]
|
||||||
dialog = ALSeatMapSelectDialog(
|
Dialog = ALSeatMapSelectDialog(
|
||||||
self,
|
self,
|
||||||
floor,
|
floor,
|
||||||
room,
|
room,
|
||||||
ALSeatMapTable[floor_idx][room_idx]
|
ALSeatMapTable[floor_idx][room_idx]
|
||||||
)
|
)
|
||||||
dialog.selectSeats(self.SeatIDEdit.text().split(","))
|
Dialog.selectSeats(self.SeatIDEdit.text().split(","))
|
||||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||||
selected_seats = dialog.getSelectedSeats()
|
selected_seats = Dialog.getSelectedSeats()
|
||||||
if len(selected_seats) == 0:
|
if len(selected_seats) == 0:
|
||||||
self.SeatIDEdit.clear()
|
self.SeatIDEdit.clear()
|
||||||
return
|
return
|
||||||
self.SeatIDEdit.setText(",".join(dialog.getSelectedSeats()))
|
self.SeatIDEdit.setText(",".join(Dialog.getSelectedSeats()))
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onUserTreeWidgetCurrentItemChanged(
|
def onUserTreeWidgetCurrentItemChanged(
|
||||||
@@ -862,16 +830,14 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
is_checked = item.checkState(1) == Qt.CheckState.Checked
|
is_checked = item.checkState(1) == Qt.CheckState.Checked
|
||||||
item.setText(1, "" if is_checked else "跳过")
|
item.setText(1, "" if is_checked else "跳过")
|
||||||
|
|
||||||
|
|
||||||
def showTreeMenu(
|
def showTreeMenu(
|
||||||
self,
|
self,
|
||||||
menu: QMenu
|
menu: QMenu
|
||||||
):
|
):
|
||||||
|
|
||||||
add_group_action = QAction("添加分组", menu)
|
AddGroupAction = QAction("添加分组", menu)
|
||||||
add_group_action.triggered.connect(self.addGroup)
|
AddGroupAction.triggered.connect(self.addGroup)
|
||||||
menu.addAction(add_group_action)
|
menu.addAction(AddGroupAction)
|
||||||
|
|
||||||
|
|
||||||
def showGroupMenu(
|
def showGroupMenu(
|
||||||
self,
|
self,
|
||||||
@@ -879,19 +845,18 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
group_item: QTreeWidgetItem = None
|
group_item: QTreeWidgetItem = None
|
||||||
):
|
):
|
||||||
|
|
||||||
add_user_action = QAction("添加用户", menu)
|
AddUserAction = QAction("添加用户", menu)
|
||||||
rename_group_action = QAction("重命名分组", menu)
|
RenameGroupAction = QAction("重命名分组", menu)
|
||||||
del_group_action = QAction("删除分组", menu)
|
DelGroupAction = QAction("删除分组", menu)
|
||||||
add_user_action.triggered.connect(lambda: self.addUser(group_item))
|
AddUserAction.triggered.connect(lambda: self.addUser(group_item))
|
||||||
rename_group_action.triggered.connect(lambda: self.renameItem(group_item))
|
RenameGroupAction.triggered.connect(lambda: self.renameItem(group_item))
|
||||||
del_group_action.triggered.connect(lambda: self.delGroup(group_item))
|
DelGroupAction.triggered.connect(lambda: self.delGroup(group_item))
|
||||||
menu.addAction(add_user_action)
|
menu.addAction(AddUserAction)
|
||||||
menu.addSeparator()
|
menu.addSeparator()
|
||||||
menu.addAction(rename_group_action)
|
menu.addAction(RenameGroupAction)
|
||||||
menu.addAction(del_group_action)
|
menu.addAction(DelGroupAction)
|
||||||
if group_item.checkState(1) == Qt.CheckState.Unchecked:
|
if group_item.checkState(1) == Qt.CheckState.Unchecked:
|
||||||
add_user_action.setEnabled(False)
|
AddUserAction.setEnabled(False)
|
||||||
|
|
||||||
|
|
||||||
def showUserMenu(
|
def showUserMenu(
|
||||||
self,
|
self,
|
||||||
@@ -899,12 +864,12 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
user_item: QTreeWidgetItem = None
|
user_item: QTreeWidgetItem = None
|
||||||
):
|
):
|
||||||
|
|
||||||
rename_user_action = QAction("重命名用户", menu)
|
RenameUserAction = QAction("重命名用户", menu)
|
||||||
del_user_action = QAction("删除用户", menu)
|
DelUserAction = QAction("删除用户", menu)
|
||||||
rename_user_action.triggered.connect(lambda: self.renameItem(user_item))
|
RenameUserAction.triggered.connect(lambda: self.renameItem(user_item))
|
||||||
del_user_action.triggered.connect(lambda: self.delUser(user_item))
|
DelUserAction.triggered.connect(lambda: self.delUser(user_item))
|
||||||
menu.addAction(rename_user_action)
|
menu.addAction(RenameUserAction)
|
||||||
menu.addAction(del_user_action)
|
menu.addAction(DelUserAction)
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onUserTreeWidgetContextMenu(
|
def onUserTreeWidgetContextMenu(
|
||||||
@@ -913,14 +878,14 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
):
|
):
|
||||||
|
|
||||||
current_item = self.UserTreeWidget.itemAt(pos)
|
current_item = self.UserTreeWidget.itemAt(pos)
|
||||||
menu = QMenu(self.UserTreeWidget)
|
Menu = QMenu(self.UserTreeWidget)
|
||||||
if current_item is None:
|
if current_item is None:
|
||||||
self.showTreeMenu(menu)
|
self.showTreeMenu(Menu)
|
||||||
elif current_item.type() == ALUserTreeItemType.GROUP.value:
|
elif current_item.type() == ALUserTreeItemType.GROUP.value:
|
||||||
self.showGroupMenu(menu, current_item)
|
self.showGroupMenu(Menu, current_item)
|
||||||
else:
|
else:
|
||||||
self.showUserMenu(menu, current_item)
|
self.showUserMenu(Menu, current_item)
|
||||||
menu.exec_(self.UserTreeWidget.mapToGlobal(pos))
|
Menu.exec_(self.UserTreeWidget.mapToGlobal(pos))
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onAddUserButtonClicked(
|
def onAddUserButtonClicked(
|
||||||
@@ -952,21 +917,19 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
if browser_driver_path:
|
if browser_driver_path:
|
||||||
self.BrowseBrowserDriverEdit.setText(QDir.toNativeSeparators(browser_driver_path))
|
self.BrowseBrowserDriverEdit.setText(QDir.toNativeSeparators(browser_driver_path))
|
||||||
|
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onAutoDownloadWebDriverButtonClicked(
|
def onAutoDownloadWebDriverButtonClicked(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
dialog = ALWebDriverDownloadDialog(self)
|
Dialog = ALWebDriverDownloadDialog(self)
|
||||||
dialog.show()
|
Dialog.show()
|
||||||
dialog.exec_()
|
Dialog.exec_()
|
||||||
selected_driver_info = dialog.getSelectedDriverInfo()
|
selected_driver_info = Dialog.getSelectedDriverInfo()
|
||||||
if selected_driver_info and selected_driver_info.driver_path:
|
if selected_driver_info and selected_driver_info.driver_path:
|
||||||
self.BrowserTypeComboBox.setCurrentText(selected_driver_info.driver_type.value)
|
self.BrowserTypeComboBox.setCurrentText(selected_driver_info.driver_type.value)
|
||||||
self.BrowseBrowserDriverEdit.setText(QDir.toNativeSeparators(str(selected_driver_info.driver_path)))
|
self.BrowseBrowserDriverEdit.setText(QDir.toNativeSeparators(str(selected_driver_info.driver_path)))
|
||||||
|
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onBrowseCurrentRunConfigButtonClicked(
|
def onBrowseCurrentRunConfigButtonClicked(
|
||||||
self
|
self
|
||||||
@@ -1071,7 +1034,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
|||||||
):
|
):
|
||||||
|
|
||||||
msg = ""
|
msg = ""
|
||||||
|
|
||||||
run_config_path = self.ExportRunConfigEdit.text()
|
run_config_path = self.ExportRunConfigEdit.text()
|
||||||
user_config_path = self.ExportUserConfigEdit.text()
|
user_config_path = self.ExportUserConfigEdit.text()
|
||||||
if run_config_path:
|
if run_config_path:
|
||||||
|
|||||||
@@ -9,103 +9,113 @@ See the LICENSE file for details.
|
|||||||
"""
|
"""
|
||||||
import queue
|
import queue
|
||||||
|
|
||||||
|
import packaging.version as ver
|
||||||
|
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Qt, Signal, Slot, QTimer, QUrl,
|
QTimer,
|
||||||
)
|
QUrl,
|
||||||
from PySide6.QtWidgets import (
|
Qt,
|
||||||
QMainWindow, QMenu, QSystemTrayIcon, QMessageBox
|
Slot
|
||||||
)
|
)
|
||||||
from PySide6.QtGui import (
|
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 base.MsgBase import MsgBase
|
||||||
from managers.config.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.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):
|
class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||||
|
|
||||||
# signal : timer task
|
|
||||||
timerTaskIsRunning = Signal(dict)
|
|
||||||
timerTaskIsExecuted = Signal(dict)
|
|
||||||
timerTaskIsError = Signal(dict)
|
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
MsgBase.__init__(self, queue.Queue(), queue.Queue())
|
MsgBase.__init__(self, queue.Queue(), queue.Queue())
|
||||||
QMainWindow.__init__(self)
|
QMainWindow.__init__(self)
|
||||||
self.__timer_task_queue = queue.Queue()
|
|
||||||
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
||||||
self.__alTimerTaskManageWidget = None
|
self.__ALTimerTaskManageWidget = None
|
||||||
self.__alConfigWidget = None
|
self.__ALConfigWidget = None
|
||||||
|
self.__ALSettingsWidget = None
|
||||||
|
self.__ALBulletinDialog = None
|
||||||
self.__auto_lib_thread = None
|
self.__auto_lib_thread = None
|
||||||
self.__current_timer_task_thread = None
|
self.__bulletin_poller = ALBulletinPoller(self)
|
||||||
self.__is_running_timer_task = False
|
self.__timer_task_poller = ALTimerTaskPoller(
|
||||||
|
self,
|
||||||
|
self._input_queue,
|
||||||
|
self._output_queue,
|
||||||
|
self.__config_paths
|
||||||
|
)
|
||||||
|
self.__notification_type = ""
|
||||||
|
|
||||||
self.setupUi(self)
|
self.setupUi(self)
|
||||||
self.modifyUi()
|
self.modifyUi()
|
||||||
self.setupTray()
|
self.setupTray()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
self.startMsgPolling()
|
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("主窗口初始化完成")
|
self._showLog("主窗口初始化完成")
|
||||||
|
|
||||||
|
|
||||||
def modifyUi(
|
def modifyUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.icon = QIcon(":/res/icon/icons/AutoLibrary_32x32.ico")
|
self.Icon = QIcon(":/res/icons/AutoLibrary_Logo_64.svg")
|
||||||
self.setWindowIcon(self.icon)
|
self.setWindowIcon(self.Icon)
|
||||||
self.MessageIOTextEdit.setFont(QFont("Courier New", 10))
|
self.MessageIOTextEdit.setFont(QFont("Courier New", 10))
|
||||||
self.ManualAction.triggered.connect(self.onManualActionTriggered)
|
self.ManualAction.triggered.connect(self.onManualActionTriggered)
|
||||||
|
self.CheckUpdateAction.triggered.connect(self.onCheckUpdateActionTriggered)
|
||||||
self.AboutAction.triggered.connect(self.onAboutActionTriggered)
|
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
|
# initialize timer task widget, but not show it
|
||||||
try:
|
try:
|
||||||
self.__alTimerTaskManageWidget = ALTimerTaskManageWidget(self)
|
self.__ALTimerTaskManageWidget = ALTimerTaskManageWidget(self)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
QMessageBox.critical(
|
QMessageBox.critical(
|
||||||
self,
|
self,
|
||||||
"错误 - AutoLibrary",
|
"错误 - AutoLibrary",
|
||||||
f"初始化定时任务功能失败: \n{e}"
|
f"初始化定时任务功能失败: \n{e}"
|
||||||
)
|
)
|
||||||
self.__alTimerTaskManageWidget = None
|
self.__ALTimerTaskManageWidget = None
|
||||||
self.TimerTaskManageWidgetButton.setEnabled(False)
|
self.TimerTaskManageWidgetButton.setEnabled(False)
|
||||||
self.TimerTaskManageWidgetButton.setToolTip("定时任务功能初始化失败, 请检查配置文件。")
|
self.TimerTaskManageWidgetButton.setToolTip("定时任务功能初始化失败, 请检查配置文件。")
|
||||||
return
|
return
|
||||||
self.timerTaskIsRunning.connect(self.__alTimerTaskManageWidget.onTimerTaskIsRunning)
|
self.__timer_task_poller.taskRunning.connect(self.onTimerTaskRunning)
|
||||||
self.timerTaskIsExecuted.connect(self.__alTimerTaskManageWidget.onTimerTaskIsExecuted)
|
self.__timer_task_poller.taskFinished.connect(self.onTimerTaskFinished)
|
||||||
self.timerTaskIsError.connect(self.__alTimerTaskManageWidget.onTimerTaskIsError)
|
self.__timer_task_poller.taskRunning.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsRunning)
|
||||||
self.__alTimerTaskManageWidget.timerTaskIsReady.connect(self.onTimerTaskIsReady)
|
self.__timer_task_poller.taskExecuted.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsExecuted)
|
||||||
self.__alTimerTaskManageWidget.timerTaskManageWidgetIsClosed.connect(self.onTimerTaskManageWidgetClosed)
|
self.__timer_task_poller.taskError.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsError)
|
||||||
self.__alTimerTaskManageWidget.setWindowFlags(Qt.WindowType.Window|Qt.WindowType.WindowCloseButtonHint)
|
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 onAboutActionTriggered(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
|
|
||||||
about_dialog = ALAboutDialog(self)
|
|
||||||
about_dialog.exec()
|
|
||||||
|
|
||||||
|
|
||||||
def onManualActionTriggered(
|
|
||||||
self
|
|
||||||
):
|
|
||||||
|
|
||||||
url = QUrl("https://www.autolibrary.kenanzhu.com/manuals")
|
|
||||||
QDesktopServices.openUrl(url)
|
|
||||||
|
|
||||||
|
|
||||||
def setupTray(
|
def setupTray(
|
||||||
self
|
self
|
||||||
@@ -114,9 +124,8 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
if not QSystemTrayIcon.isSystemTrayAvailable():
|
if not QSystemTrayIcon.isSystemTrayAvailable():
|
||||||
self._showTrace("操作系统不支持系统托盘功能, 无法创建系统托盘图标", self.TraceLevel.WARNING)
|
self._showTrace("操作系统不支持系统托盘功能, 无法创建系统托盘图标", self.TraceLevel.WARNING)
|
||||||
return
|
return
|
||||||
self.TrayIcon = QSystemTrayIcon(self.icon, self)
|
self.TrayIcon = QSystemTrayIcon(self.Icon, self)
|
||||||
self.TrayIcon.setToolTip("AutoLibrary")
|
self.TrayIcon.setToolTip("AutoLibrary")
|
||||||
|
|
||||||
self.TrayMenu = QMenu()
|
self.TrayMenu = QMenu()
|
||||||
self.TrayMenu.addAction("显示主窗口", self.showNormal)
|
self.TrayMenu.addAction("显示主窗口", self.showNormal)
|
||||||
self.TrayMenu.addAction("显示定时窗口", self.onTimerTaskManageWidgetButtonClicked)
|
self.TrayMenu.addAction("显示定时窗口", self.onTimerTaskManageWidgetButtonClicked)
|
||||||
@@ -124,16 +133,18 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
self.TrayMenu.addSeparator()
|
self.TrayMenu.addSeparator()
|
||||||
self.TrayMenu.addAction("退出", self.close)
|
self.TrayMenu.addAction("退出", self.close)
|
||||||
self.TrayIcon.setContextMenu(self.TrayMenu)
|
self.TrayIcon.setContextMenu(self.TrayMenu)
|
||||||
|
|
||||||
self.TrayIcon.activated.connect(self.onTrayIconActivated)
|
self.TrayIcon.activated.connect(self.onTrayIconActivated)
|
||||||
|
self.TrayIcon.messageClicked.connect(self.onTrayMessageClicked)
|
||||||
self.TrayIcon.show()
|
self.TrayIcon.show()
|
||||||
|
|
||||||
|
|
||||||
def hideToTray(
|
def hideToTray(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.hide()
|
self.hide()
|
||||||
|
self.__notification_type = ""
|
||||||
|
if not hasattr(self, "TrayIcon"):
|
||||||
|
return
|
||||||
self.TrayIcon.showMessage(
|
self.TrayIcon.showMessage(
|
||||||
"AutoLibrary",
|
"AutoLibrary",
|
||||||
"\n已最小化到托盘",
|
"\n已最小化到托盘",
|
||||||
@@ -141,16 +152,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
2000
|
2000
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def onTrayIconActivated(
|
|
||||||
self,
|
|
||||||
reason: QSystemTrayIcon.ActivationReason
|
|
||||||
):
|
|
||||||
|
|
||||||
if reason == QSystemTrayIcon.DoubleClick:
|
|
||||||
self.showNormal()
|
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -161,7 +162,7 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
self.StopButton.clicked.connect(self.onStopButtonClicked)
|
self.StopButton.clicked.connect(self.onStopButtonClicked)
|
||||||
self.SendButton.clicked.connect(self.onSendButtonClicked)
|
self.SendButton.clicked.connect(self.onSendButtonClicked)
|
||||||
self.MessageEdit.returnPressed.connect(self.onSendButtonClicked)
|
self.MessageEdit.returnPressed.connect(self.onSendButtonClicked)
|
||||||
|
self.__bulletin_poller.newBulletinsDetected.connect(self.onBulletinPollerNewBulletins)
|
||||||
|
|
||||||
def closeEvent(
|
def closeEvent(
|
||||||
self,
|
self,
|
||||||
@@ -174,21 +175,25 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
return
|
return
|
||||||
if self.__msg_queue_timer and self.__msg_queue_timer.isActive():
|
if self.__msg_queue_timer and self.__msg_queue_timer.isActive():
|
||||||
self.__msg_queue_timer.stop()
|
self.__msg_queue_timer.stop()
|
||||||
if self.__timer_task_timer and self.__timer_task_timer.isActive():
|
if self.__timer_task_poller:
|
||||||
self.__timer_task_timer.stop()
|
self.__timer_task_poller.stop()
|
||||||
if self.__is_running_timer_task:
|
if self.__ALTimerTaskManageWidget:
|
||||||
self.__current_timer_task_thread.wait(2000)
|
self.__ALTimerTaskManageWidget.close()
|
||||||
self.__current_timer_task_thread.deleteLater()
|
self.__ALTimerTaskManageWidget.deleteLater()
|
||||||
if self.__alTimerTaskManageWidget:
|
if self.__ALConfigWidget:
|
||||||
self.__alTimerTaskManageWidget.close()
|
self.__ALConfigWidget.close()
|
||||||
self.__alTimerTaskManageWidget.deleteLater()
|
|
||||||
if self.__alConfigWidget:
|
|
||||||
self.__alConfigWidget.close()
|
|
||||||
# the config widget is already deleted in the 'self.onConfigWidgetClosed'
|
# 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("主窗口关闭")
|
self._showLog("主窗口关闭")
|
||||||
QMainWindow.closeEvent(self, event)
|
QMainWindow.closeEvent(self, event)
|
||||||
|
|
||||||
|
|
||||||
def appendToTextEdit(
|
def appendToTextEdit(
|
||||||
self,
|
self,
|
||||||
text: str
|
text: str
|
||||||
@@ -202,7 +207,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
scrollbar = self.MessageIOTextEdit.verticalScrollBar()
|
scrollbar = self.MessageIOTextEdit.verticalScrollBar()
|
||||||
scrollbar.setValue(scrollbar.maximum())
|
scrollbar.setValue(scrollbar.maximum())
|
||||||
|
|
||||||
|
|
||||||
def startMsgPolling(
|
def startMsgPolling(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -211,50 +215,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
self.__msg_queue_timer.timeout.connect(self.pollMsgQueue)
|
self.__msg_queue_timer.timeout.connect(self.pollMsgQueue)
|
||||||
self.__msg_queue_timer.start(100)
|
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(
|
def setControlButtons(
|
||||||
self,
|
self,
|
||||||
config_button_enabled: bool,
|
config_button_enabled: bool,
|
||||||
@@ -282,6 +242,145 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
pass
|
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()
|
@Slot()
|
||||||
def onTimerTaskManageWidgetClosed(
|
def onTimerTaskManageWidgetClosed(
|
||||||
self
|
self
|
||||||
@@ -294,59 +393,106 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
if self.__alConfigWidget:
|
if self.__ALConfigWidget:
|
||||||
self.__alConfigWidget.configWidgetIsClosed.disconnect(self.onConfigWidgetClosed)
|
self.__ALConfigWidget.configWidgetIsClosed.disconnect(self.onConfigWidgetClosed)
|
||||||
self.__alConfigWidget.deleteLater()
|
self.__ALConfigWidget.deleteLater()
|
||||||
self.__alConfigWidget = None
|
self.__ALConfigWidget = None
|
||||||
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
||||||
|
self.__timer_task_poller.updateConfigPaths(self.__config_paths)
|
||||||
self.setControlButtons(True, None, None)
|
self.setControlButtons(True, None, None)
|
||||||
self._showLog("配置窗口已关闭,配置文件路径已更新")
|
self._showLog("配置窗口已关闭,配置文件路径已更新")
|
||||||
|
|
||||||
@Slot(dict)
|
@Slot()
|
||||||
def onTimerTaskIsReady(
|
def onBulletinActionTriggered(
|
||||||
self,
|
self
|
||||||
timer_task: dict
|
|
||||||
):
|
):
|
||||||
|
|
||||||
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)
|
@Slot()
|
||||||
def onTimerTaskFinished(
|
def onSettingsActionTriggered(
|
||||||
self,
|
self
|
||||||
is_error: bool,
|
|
||||||
timer_task: dict
|
|
||||||
):
|
):
|
||||||
|
|
||||||
self.__current_timer_task_thread.wait(1000)
|
if self.__ALSettingsWidget is None:
|
||||||
self.__current_timer_task_thread.timerTaskWorkerIsFinished.disconnect(self.onTimerTaskFinished)
|
self.__ALSettingsWidget = ALSettingsWidget(self)
|
||||||
self.__current_timer_task_thread.deleteLater()
|
self.__ALSettingsWidget.settingsWidgetIsClosed.connect(self.onSettingsWidgetClosed)
|
||||||
self.__current_timer_task_thread = None
|
self.__ALSettingsWidget.openBulletinRequested.connect(self.onBulletinActionTriggered)
|
||||||
self.setControlButtons(None, False, True)
|
self.__ALSettingsWidget.show()
|
||||||
self.__is_running_timer_task = False
|
self.__ALSettingsWidget.raise_()
|
||||||
self.__timer_task_timer.start(500)
|
self.__ALSettingsWidget.activateWindow()
|
||||||
timer_task["executed"] = True
|
self.SettingsAction.setEnabled(False)
|
||||||
self.TrayIcon.showMessage(
|
self._showLog("打开全局设置窗口")
|
||||||
"定时任务 - AutoLibrary",
|
|
||||||
f"\n定时任务 '{timer_task['name']}' 执行{'失败' if is_error else '完成'}",
|
@Slot()
|
||||||
QSystemTrayIcon.MessageIcon.Warning if is_error else QSystemTrayIcon.MessageIcon.Information,
|
def onAboutActionTriggered(
|
||||||
1000
|
self
|
||||||
)
|
):
|
||||||
self._showTrace(
|
|
||||||
f"定时任务 {timer_task['name']} 执行{'失败' if is_error else '完成'}, uuid: {timer_task['uuid']}"
|
AboutDialog = ALAboutDialog(self)
|
||||||
)
|
AboutDialog.exec()
|
||||||
if not is_error:
|
|
||||||
self.timerTaskIsExecuted.emit(timer_task)
|
@Slot()
|
||||||
else:
|
def onManualActionTriggered(
|
||||||
self.timerTaskIsError.emit(timer_task)
|
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()
|
@Slot()
|
||||||
def onTimerTaskManageWidgetButtonClicked(
|
def onTimerTaskManageWidgetButtonClicked(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.__alTimerTaskManageWidget.show()
|
if self.__ALTimerTaskManageWidget is None:
|
||||||
self.__alTimerTaskManageWidget.raise_()
|
QMessageBox.warning(
|
||||||
self.__alTimerTaskManageWidget.activateWindow()
|
self,
|
||||||
|
"警告 - AutoLibrary",
|
||||||
|
"定时任务功能初始化失败, 请检查配置文件。"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
self.__ALTimerTaskManageWidget.show()
|
||||||
|
self.__ALTimerTaskManageWidget.raise_()
|
||||||
|
self.__ALTimerTaskManageWidget.activateWindow()
|
||||||
self.TimerTaskManageWidgetButton.setEnabled(False)
|
self.TimerTaskManageWidgetButton.setEnabled(False)
|
||||||
self._showLog("打开定时任务管理窗口")
|
self._showLog("打开定时任务管理窗口")
|
||||||
|
|
||||||
@@ -355,12 +501,12 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
|||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
if self.__alConfigWidget is None:
|
if self.__ALConfigWidget is None:
|
||||||
self.__alConfigWidget = ALConfigWidget(self)
|
self.__ALConfigWidget = ALConfigWidget(self)
|
||||||
self.__alConfigWidget.configWidgetIsClosed.connect(self.onConfigWidgetClosed)
|
self.__ALConfigWidget.configWidgetIsClosed.connect(self.onConfigWidgetClosed)
|
||||||
self.__alConfigWidget.show()
|
self.__ALConfigWidget.show()
|
||||||
self.__alConfigWidget.raise_()
|
self.__ALConfigWidget.raise_()
|
||||||
self.__alConfigWidget.activateWindow()
|
self.__ALConfigWidget.activateWindow()
|
||||||
self.ConfigButton.setEnabled(False)
|
self.ConfigButton.setEnabled(False)
|
||||||
self._showLog("打开配置窗口")
|
self._showLog("打开配置窗口")
|
||||||
|
|
||||||
|
|||||||
@@ -12,13 +12,14 @@ import time
|
|||||||
import queue
|
import queue
|
||||||
|
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Slot, Signal, QThread
|
Signal,
|
||||||
|
QThread,
|
||||||
)
|
)
|
||||||
|
|
||||||
from base.MsgBase import MsgBase
|
from base.MsgBase import MsgBase
|
||||||
from operators.AutoLib import AutoLib
|
from pages.AutoLib import AutoLib
|
||||||
from utils.JSONReader import JSONReader
|
from utils.JSONReader import JSONReader
|
||||||
from autoscript import execute, registerDefaultTargetVars
|
from autoscript import createEngine
|
||||||
|
|
||||||
|
|
||||||
class AutoLibWorker(MsgBase, QThread):
|
class AutoLibWorker(MsgBase, QThread):
|
||||||
@@ -30,14 +31,13 @@ class AutoLibWorker(MsgBase, QThread):
|
|||||||
self,
|
self,
|
||||||
input_queue: queue.Queue,
|
input_queue: queue.Queue,
|
||||||
output_queue: queue.Queue,
|
output_queue: queue.Queue,
|
||||||
config_paths: dict
|
config_paths: dict,
|
||||||
):
|
):
|
||||||
|
|
||||||
MsgBase.__init__(self, input_queue, output_queue)
|
MsgBase.__init__(self, input_queue, output_queue)
|
||||||
QThread.__init__(self)
|
QThread.__init__(self)
|
||||||
self.__config_paths = config_paths
|
self.__config_paths = config_paths
|
||||||
|
|
||||||
|
|
||||||
def checkTimeAvailable(
|
def checkTimeAvailable(
|
||||||
self,
|
self,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
@@ -46,13 +46,12 @@ class AutoLibWorker(MsgBase, QThread):
|
|||||||
if current_time >= "23:30" or current_time <= "07:30":
|
if current_time >= "23:30" or current_time <= "07:30":
|
||||||
self._showTrace(
|
self._showTrace(
|
||||||
"当前时间不在图书馆开放时间内, 请在 07:30 - 23:30 之间尝试",
|
"当前时间不在图书馆开放时间内, 请在 07:30 - 23:30 之间尝试",
|
||||||
self.TraceLevel.WARNING
|
self.TraceLevel.WARNING,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
self._showLog(f"时间检查通过, 当前时间: {current_time}", self.TraceLevel.INFO)
|
self._showLog(f"时间检查通过, 当前时间: {current_time}", self.TraceLevel.INFO)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def checkConfigPaths(
|
def checkConfigPaths(
|
||||||
self,
|
self,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
@@ -62,85 +61,113 @@ class AutoLibWorker(MsgBase, QThread):
|
|||||||
):
|
):
|
||||||
self._showTrace(
|
self._showTrace(
|
||||||
"配置文件路径不存在, 请检查配置文件路径是否正确",
|
"配置文件路径不存在, 请检查配置文件路径是否正确",
|
||||||
self.TraceLevel.ERROR
|
self.TraceLevel.ERROR,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
self._showLog(f"配置文件路径检查通过, 路径: {self.__config_paths}", self.TraceLevel.INFO)
|
self._showLog(
|
||||||
|
f"配置文件路径检查通过, 路径: {self.__config_paths}",
|
||||||
|
self.TraceLevel.INFO,
|
||||||
|
)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def loadConfigs(
|
def loadConfigs(
|
||||||
self
|
self,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
|
||||||
self._showTrace(
|
self._showTrace(
|
||||||
f"正在加载配置文件, 运行配置文件路径: {self.__config_paths["run"]}",
|
f"正在加载配置文件, 运行配置文件路径: {self.__config_paths["run"]}",
|
||||||
no_log=True
|
no_log=True,
|
||||||
)
|
)
|
||||||
self._run_config = JSONReader(self.__config_paths["run"]).data()
|
self._run_config = JSONReader(self.__config_paths["run"]).data()
|
||||||
self._showTrace(
|
self._showTrace(
|
||||||
f"正在加载配置文件, 用户配置文件路径: {self.__config_paths["user"]}",
|
f"正在加载配置文件, 用户配置文件路径: {self.__config_paths["user"]}",
|
||||||
no_log=True
|
no_log=True,
|
||||||
)
|
)
|
||||||
self._user_config = JSONReader(self.__config_paths["user"]).data()
|
self._user_config = JSONReader(self.__config_paths["user"]).data()
|
||||||
if self._run_config is None or self._user_config is None:
|
if self._run_config is None or self._user_config is None:
|
||||||
self._showTrace(
|
self._showTrace(
|
||||||
"配置文件加载失败, 请检查配置文件是否正确",
|
"配置文件加载失败, 请检查配置文件是否正确",
|
||||||
self.TraceLevel.ERROR
|
self.TraceLevel.ERROR,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
if not self._user_config.get("groups"):
|
if not self._user_config.get("groups"):
|
||||||
self._showTrace(
|
self._showTrace(
|
||||||
"用户配置文件中无有效任务组, 请检查用户配置文件是否正确",
|
"用户配置文件中无有效任务组, 请检查用户配置文件是否正确",
|
||||||
self.TraceLevel.WARNING
|
self.TraceLevel.WARNING,
|
||||||
)
|
)
|
||||||
return False
|
return False
|
||||||
self._showLog(
|
self._showLog(
|
||||||
f"配置文件加载成功, 任务组数量: {len(self._user_config.get('groups', []))}",
|
f"配置文件加载成功, 任务组数量: {len(self._user_config.get("groups"))}",
|
||||||
self.TraceLevel.INFO
|
self.TraceLevel.INFO,
|
||||||
)
|
)
|
||||||
return True
|
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(
|
def run(
|
||||||
self
|
self,
|
||||||
):
|
):
|
||||||
|
|
||||||
auto_lib = None
|
auto_lib = None
|
||||||
self._showTrace("AutoLibrary 开始运行")
|
self._showTrace(f"{self._runName()} 开始运行")
|
||||||
if not self.checkTimeAvailable()\
|
|
||||||
or not self.checkConfigPaths():
|
if not self.checkTimeAvailable() or not self.checkConfigPaths():
|
||||||
# time or config existence check failed, skip and finish
|
if not self._onChecksFailed():
|
||||||
pass
|
return
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
if not self.loadConfigs():
|
if not self.loadConfigs():
|
||||||
raise Exception("配置文件加载失败")
|
raise Exception("配置文件加载失败")
|
||||||
|
self._beforeCreateAutoLib()
|
||||||
auto_lib = AutoLib(
|
auto_lib = AutoLib(
|
||||||
self._input_queue,
|
self._input_queue,
|
||||||
self._output_queue,
|
self._output_queue,
|
||||||
self._run_config
|
self._run_config,
|
||||||
)
|
)
|
||||||
groups = self._user_config.get("groups")
|
groups = self._user_config.get("groups")
|
||||||
for group in groups:
|
for group in groups:
|
||||||
if not group["enabled"]:
|
if not group.get("enabled", False):
|
||||||
self._showTrace(f"任务组 {group["name"]} 已跳过", no_log=True)
|
self._showTrace(f"任务组 {group.get("name", "未知")} 已跳过", no_log=True)
|
||||||
continue
|
continue
|
||||||
self._showTrace(f"正在运行任务组 {group["name"]}", no_log=True)
|
self._showTrace(f"正在运行任务组 {group.get("name", "未知")}", no_log=True)
|
||||||
auto_lib.run(
|
auto_lib.run({"users": group.get("users", [])})
|
||||||
{ "users": group.get("users", []) }
|
|
||||||
)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self._showTrace(
|
self._onError(f"{self._runName()} 运行时发生异常 : {e}")
|
||||||
f"AutoLibrary 运行时发生异常 : {e}",
|
|
||||||
self.TraceLevel.ERROR
|
|
||||||
)
|
|
||||||
self.autoLibWorkerFinishedWithError.emit()
|
|
||||||
return
|
return
|
||||||
if auto_lib:
|
if auto_lib:
|
||||||
auto_lib.close()
|
auto_lib.close()
|
||||||
self._showTrace("AutoLibrary 运行结束")
|
self._showTrace(f"{self._runName()} 运行结束")
|
||||||
self.autoLibWorkerIsFinished.emit()
|
self._onFinished()
|
||||||
|
|
||||||
|
|
||||||
class TimerTaskWorker(AutoLibWorker):
|
class TimerTaskWorker(AutoLibWorker):
|
||||||
@@ -152,72 +179,54 @@ class TimerTaskWorker(AutoLibWorker):
|
|||||||
timer_task: dict,
|
timer_task: dict,
|
||||||
input_queue: queue.Queue,
|
input_queue: queue.Queue,
|
||||||
output_queue: queue.Queue,
|
output_queue: queue.Queue,
|
||||||
config_paths: dict
|
config_paths: dict,
|
||||||
):
|
):
|
||||||
|
|
||||||
super().__init__(input_queue, output_queue, config_paths)
|
super().__init__(input_queue, output_queue, config_paths)
|
||||||
self.__timer_task = timer_task
|
self.__timer_task = timer_task
|
||||||
|
|
||||||
self.autoLibWorkerIsFinished.connect(self.onTimerTaskIsFinished)
|
def _runName(
|
||||||
self.autoLibWorkerFinishedWithError.connect(self.onTimerTaskFinishedWithError)
|
self,
|
||||||
|
) -> str:
|
||||||
|
|
||||||
|
return f"定时任务 '{self.__timer_task.get("name", "未知")}'"
|
||||||
|
|
||||||
def run(
|
def _beforeCreateAutoLib(
|
||||||
self
|
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)
|
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(
|
def applyRepeatAutoScript(
|
||||||
self
|
self,
|
||||||
):
|
):
|
||||||
|
|
||||||
auto_script = self.__timer_task.get("repeat_auto_script", "")
|
auto_script = self.__timer_task.get("repeat_auto_script", "")
|
||||||
if not auto_script or not auto_script.strip():
|
if not auto_script or not auto_script.strip():
|
||||||
return
|
return
|
||||||
self._showTrace(
|
self._showTrace("检测到重复定时任务 AutoScript, 开始执行...", no_log=True)
|
||||||
f"检测到重复定时任务 AutoScript, 开始执行...",
|
|
||||||
no_log=True
|
|
||||||
)
|
|
||||||
groups = self._user_config.get("groups", [])
|
groups = self._user_config.get("groups", [])
|
||||||
affected_count = 0
|
affected_count = 0
|
||||||
for group in groups:
|
for group in groups:
|
||||||
@@ -225,35 +234,15 @@ class TimerTaskWorker(AutoLibWorker):
|
|||||||
continue
|
continue
|
||||||
for user in group.get("users", []):
|
for user in group.get("users", []):
|
||||||
try:
|
try:
|
||||||
registerDefaultTargetVars()
|
engine = createEngine()
|
||||||
execute(auto_script, user)
|
engine.execute(auto_script, user)
|
||||||
affected_count += 1
|
affected_count += 1
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
self._showTrace(
|
self._showTrace(
|
||||||
f"AutoScript 执行错误 (用户 {user['username']}): {e}",
|
f"AutoScript 执行错误 (用户 {user.get("username", "未知")}): {e}",
|
||||||
self.TraceLevel.ERROR
|
self.TraceLevel.ERROR,
|
||||||
)
|
)
|
||||||
self._showLog(
|
self._showLog(
|
||||||
f"AutoScript 执行完毕, "
|
f"AutoScript 执行完毕, 影响 {affected_count} 个用户",
|
||||||
f"影响 {affected_count} 个用户",
|
self.TraceLevel.INFO,
|
||||||
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)
|
|
||||||
@@ -31,7 +31,6 @@ class ALSeatFrame(QFrame):
|
|||||||
|
|
||||||
self.setupUi()
|
self.setupUi()
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -55,7 +54,6 @@ class ALSeatFrame(QFrame):
|
|||||||
self.Label.setAlignment(Qt.AlignCenter)
|
self.Label.setAlignment(Qt.AlignCenter)
|
||||||
self.Label.setGeometry(0, 0, 60, 40)
|
self.Label.setGeometry(0, 0, 60, 40)
|
||||||
|
|
||||||
|
|
||||||
def mousePressEvent(
|
def mousePressEvent(
|
||||||
self,
|
self,
|
||||||
event
|
event
|
||||||
@@ -65,14 +63,12 @@ class ALSeatFrame(QFrame):
|
|||||||
self.toggleSelection()
|
self.toggleSelection()
|
||||||
self.clicked.emit(self.__seat_number)
|
self.clicked.emit(self.__seat_number)
|
||||||
|
|
||||||
|
|
||||||
def isSelected(
|
def isSelected(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
return self.__is_selected
|
return self.__is_selected
|
||||||
|
|
||||||
|
|
||||||
def toggleSelection(self):
|
def toggleSelection(self):
|
||||||
|
|
||||||
self.__is_selected = not self.__is_selected
|
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.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Qt, Slot, Signal
|
Qt,
|
||||||
)
|
Signal,
|
||||||
from PySide6.QtWidgets import (
|
Slot
|
||||||
QDialog, QLabel, QHBoxLayout, QVBoxLayout,
|
|
||||||
QPushButton,
|
|
||||||
)
|
)
|
||||||
from PySide6.QtGui import (
|
from PySide6.QtGui import (
|
||||||
QCloseEvent
|
QCloseEvent
|
||||||
)
|
)
|
||||||
|
from PySide6.QtWidgets import (
|
||||||
|
QDialog,
|
||||||
|
QHBoxLayout,
|
||||||
|
QLabel,
|
||||||
|
QPushButton,
|
||||||
|
QVBoxLayout
|
||||||
|
)
|
||||||
|
|
||||||
from gui.ALSeatMapView import ALSeatMapView
|
from gui.ALSeatMapView import ALSeatMapView
|
||||||
|
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||||
|
|
||||||
|
class ALSeatMapSelectDialog(CenterOnParentMixin, QDialog):
|
||||||
class ALSeatMapSelectDialog(QDialog):
|
|
||||||
|
|
||||||
seatMapSelectDialogIsClosed = Signal(list)
|
seatMapSelectDialogIsClosed = Signal(list)
|
||||||
|
|
||||||
@@ -42,7 +47,6 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
self.setupUi()
|
self.setupUi()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -51,7 +55,6 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
self.setMinimumSize(800, 600)
|
self.setMinimumSize(800, 600)
|
||||||
self.resize(800, 600)
|
self.resize(800, 600)
|
||||||
self.setWindowTitle(f"选择楼层座位 - AutoLibrary")
|
self.setWindowTitle(f"选择楼层座位 - AutoLibrary")
|
||||||
|
|
||||||
self.SeatMapWidgetMainLayout = QVBoxLayout(self)
|
self.SeatMapWidgetMainLayout = QVBoxLayout(self)
|
||||||
self.SeatMapWidgetMainLayout.setContentsMargins(5, 5, 5, 5)
|
self.SeatMapWidgetMainLayout.setContentsMargins(5, 5, 5, 5)
|
||||||
self.SeatMapWidgetMainLayout.setSpacing(5)
|
self.SeatMapWidgetMainLayout.setSpacing(5)
|
||||||
@@ -59,10 +62,8 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
self.TitleLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
self.TitleLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
self.TitleLabel.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
|
self.TitleLabel.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
|
||||||
self.SeatMapWidgetMainLayout.addWidget(self.TitleLabel)
|
self.SeatMapWidgetMainLayout.addWidget(self.TitleLabel)
|
||||||
|
|
||||||
self.SeatMapGraphicsView = ALSeatMapView(None, self.__seats_data)
|
self.SeatMapGraphicsView = ALSeatMapView(None, self.__seats_data)
|
||||||
self.SeatMapWidgetMainLayout.addWidget(self.SeatMapGraphicsView)
|
self.SeatMapWidgetMainLayout.addWidget(self.SeatMapGraphicsView)
|
||||||
|
|
||||||
self.TipsLabel = QLabel(
|
self.TipsLabel = QLabel(
|
||||||
" 点击座位进行选择/取消选择, 最多选择1个座位 \n"
|
" 点击座位进行选择/取消选择, 最多选择1个座位 \n"
|
||||||
" [操作方法: Ctrl+鼠标滚轮缩放 | 滚轮/拖拽/方向键 移动]"
|
" [操作方法: Ctrl+鼠标滚轮缩放 | 滚轮/拖拽/方向键 移动]"
|
||||||
@@ -70,7 +71,6 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
self.TipsLabel.setAlignment(Qt.AlignmentFlag.AlignLeft)
|
self.TipsLabel.setAlignment(Qt.AlignmentFlag.AlignLeft)
|
||||||
self.TipsLabel.setStyleSheet("color: #666; margin: 5px;")
|
self.TipsLabel.setStyleSheet("color: #666; margin: 5px;")
|
||||||
self.SeatMapWidgetMainLayout.addWidget(self.TipsLabel)
|
self.SeatMapWidgetMainLayout.addWidget(self.TipsLabel)
|
||||||
|
|
||||||
self.ConfirmButton = QPushButton("确认")
|
self.ConfirmButton = QPushButton("确认")
|
||||||
self.ConfirmButton.setFixedSize(80, 25)
|
self.ConfirmButton.setFixedSize(80, 25)
|
||||||
self.ConfirmButton.setAutoDefault(True)
|
self.ConfirmButton.setAutoDefault(True)
|
||||||
@@ -85,7 +85,6 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
self.SeatMapWidgetControlLayout.addWidget(self.ConfirmButton)
|
self.SeatMapWidgetControlLayout.addWidget(self.ConfirmButton)
|
||||||
self.SeatMapWidgetMainLayout.addLayout(self.SeatMapWidgetControlLayout)
|
self.SeatMapWidgetMainLayout.addLayout(self.SeatMapWidgetControlLayout)
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -93,31 +92,6 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||||
self.CancelButton.clicked.connect(self.onCancelButtonClicked)
|
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(
|
def closeEvent(
|
||||||
self,
|
self,
|
||||||
event: QCloseEvent
|
event: QCloseEvent
|
||||||
@@ -131,7 +105,6 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
self.seatMapSelectDialogIsClosed.emit(self.getSelectedSeats())
|
self.seatMapSelectDialogIsClosed.emit(self.getSelectedSeats())
|
||||||
super().closeEvent(event)
|
super().closeEvent(event)
|
||||||
|
|
||||||
|
|
||||||
def selectSeat(
|
def selectSeat(
|
||||||
self,
|
self,
|
||||||
seat_number: str
|
seat_number: str
|
||||||
@@ -139,7 +112,6 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
|
|
||||||
self.SeatMapGraphicsView.selectSeat(seat_number)
|
self.SeatMapGraphicsView.selectSeat(seat_number)
|
||||||
|
|
||||||
|
|
||||||
def selectSeats(
|
def selectSeats(
|
||||||
self,
|
self,
|
||||||
seat_numbers: list[str]
|
seat_numbers: list[str]
|
||||||
@@ -147,14 +119,12 @@ class ALSeatMapSelectDialog(QDialog):
|
|||||||
|
|
||||||
return self.SeatMapGraphicsView.selectSeats(seat_numbers)
|
return self.SeatMapGraphicsView.selectSeats(seat_numbers)
|
||||||
|
|
||||||
|
|
||||||
def getSelectedSeats(
|
def getSelectedSeats(
|
||||||
self
|
self
|
||||||
) -> list[str]:
|
) -> list[str]:
|
||||||
|
|
||||||
return self.SeatMapGraphicsView.getSelectedSeats()
|
return self.SeatMapGraphicsView.getSelectedSeats()
|
||||||
|
|
||||||
|
|
||||||
def clearSelections(
|
def clearSelections(
|
||||||
self
|
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.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Qt, Slot, QEvent
|
Qt,
|
||||||
|
Slot,
|
||||||
|
QEvent
|
||||||
)
|
)
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
QFrame, QWidget,
|
QFrame,
|
||||||
QGridLayout, QGraphicsView, QGraphicsScene, QGraphicsItem
|
QWidget,
|
||||||
|
QGridLayout,
|
||||||
|
QGraphicsView,
|
||||||
|
QGraphicsScene,
|
||||||
|
QGraphicsItem
|
||||||
)
|
)
|
||||||
from PySide6.QtGui import (
|
from PySide6.QtGui import (
|
||||||
QPainter, QWheelEvent
|
QPainter,
|
||||||
|
QWheelEvent
|
||||||
)
|
)
|
||||||
|
|
||||||
from gui.ALSeatFrame import ALSeatFrame
|
from gui.ALSeatFrame import ALSeatFrame
|
||||||
@@ -35,18 +42,6 @@ class ALSeatMapView(QGraphicsView):
|
|||||||
|
|
||||||
self.setupUi()
|
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(
|
def eventFilter(
|
||||||
self,
|
self,
|
||||||
watched,
|
watched,
|
||||||
@@ -61,7 +56,6 @@ class ALSeatMapView(QGraphicsView):
|
|||||||
return True
|
return True
|
||||||
return super().eventFilter(watched, event)
|
return super().eventFilter(watched, event)
|
||||||
|
|
||||||
|
|
||||||
def zoomGraphicsView(
|
def zoomGraphicsView(
|
||||||
self,
|
self,
|
||||||
event: QWheelEvent
|
event: QWheelEvent
|
||||||
@@ -80,7 +74,6 @@ class ALSeatMapView(QGraphicsView):
|
|||||||
self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
|
self.setTransformationAnchor(QGraphicsView.ViewportAnchor.AnchorUnderMouse)
|
||||||
self.scale(zoom_factor, zoom_factor)
|
self.scale(zoom_factor, zoom_factor)
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -92,15 +85,12 @@ class ALSeatMapView(QGraphicsView):
|
|||||||
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||||
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||||
self.viewport().installEventFilter(self)
|
self.viewport().installEventFilter(self)
|
||||||
|
|
||||||
self.SeatsContainerWidget = QWidget()
|
self.SeatsContainerWidget = QWidget()
|
||||||
self.SeatsContainerLayout = QGridLayout(self.SeatsContainerWidget)
|
self.SeatsContainerLayout = QGridLayout(self.SeatsContainerWidget)
|
||||||
self.setupSeatMap()
|
self.setupSeatMap()
|
||||||
|
|
||||||
self.ContainerProxy = self.SeatMapGraphicsScene.addWidget(self.SeatsContainerWidget)
|
self.ContainerProxy = self.SeatMapGraphicsScene.addWidget(self.SeatsContainerWidget)
|
||||||
self.ContainerProxy.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, False)
|
self.ContainerProxy.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, False)
|
||||||
|
|
||||||
|
|
||||||
def setupSeatMap(
|
def setupSeatMap(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -111,21 +101,20 @@ class ALSeatMapView(QGraphicsView):
|
|||||||
seats_number = [seat.strip() for seat in row.split(",")]
|
seats_number = [seat.strip() for seat in row.split(",")]
|
||||||
for seat_number in seats_number:
|
for seat_number in seats_number:
|
||||||
if seat_number:
|
if seat_number:
|
||||||
seat_widget = ALSeatFrame(seat_number)
|
SeatWidget = ALSeatFrame(seat_number)
|
||||||
seat_widget.clicked.connect(self.onSeatClicked)
|
SeatWidget.clicked.connect(self.onSeatClicked)
|
||||||
self.SeatsContainerLayout.addWidget(seat_widget, row_idx, col_idx)
|
self.SeatsContainerLayout.addWidget(SeatWidget, row_idx, col_idx)
|
||||||
self.__seat_frames[seat_number] = seat_widget
|
self.__seat_frames[seat_number] = SeatWidget
|
||||||
else:
|
else:
|
||||||
spacer = QFrame()
|
Spacer = QFrame()
|
||||||
spacer.setFixedSize(20, 30)
|
Spacer.setFixedSize(20, 30)
|
||||||
spacer.setStyleSheet("background-color: transparent; border: none;")
|
Spacer.setStyleSheet("background-color: transparent; border: none;")
|
||||||
self.SeatsContainerLayout.addWidget(spacer, row_idx, col_idx)
|
self.SeatsContainerLayout.addWidget(Spacer, row_idx, col_idx)
|
||||||
col_idx += 1
|
col_idx += 1
|
||||||
self.SeatsContainerLayout.setSpacing(20)
|
self.SeatsContainerLayout.setSpacing(20)
|
||||||
self.SeatsContainerLayout.setContentsMargins(20, 20, 20, 20)
|
self.SeatsContainerLayout.setContentsMargins(20, 20, 20, 20)
|
||||||
self.SeatsContainerWidget.adjustSize()
|
self.SeatsContainerWidget.adjustSize()
|
||||||
|
|
||||||
|
|
||||||
def selectSeat(
|
def selectSeat(
|
||||||
self,
|
self,
|
||||||
seat_number: str
|
seat_number: str
|
||||||
@@ -142,7 +131,6 @@ class ALSeatMapView(QGraphicsView):
|
|||||||
widget.toggleSelection()
|
widget.toggleSelection()
|
||||||
self.__selected_seats.append(seat_number)
|
self.__selected_seats.append(seat_number)
|
||||||
|
|
||||||
|
|
||||||
def selectSeats(
|
def selectSeats(
|
||||||
self,
|
self,
|
||||||
selected_seats: list
|
selected_seats: list
|
||||||
@@ -152,14 +140,12 @@ class ALSeatMapView(QGraphicsView):
|
|||||||
for seat_number in selected_seats:
|
for seat_number in selected_seats:
|
||||||
self.selectSeat(seat_number)
|
self.selectSeat(seat_number)
|
||||||
|
|
||||||
|
|
||||||
def getSelectedSeats(
|
def getSelectedSeats(
|
||||||
self
|
self
|
||||||
) -> list[str]:
|
) -> list[str]:
|
||||||
|
|
||||||
return self.__selected_seats
|
return self.__selected_seats
|
||||||
|
|
||||||
|
|
||||||
def clearSelections(
|
def clearSelections(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -185,4 +171,15 @@ class ALSeatMapView(QGraphicsView):
|
|||||||
if len(self.__selected_seats) < 1:
|
if len(self.__selected_seats) < 1:
|
||||||
self.__selected_seats.append(seat_number)
|
self.__selected_seats.append(seat_number)
|
||||||
else:
|
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 enum import Enum
|
||||||
|
|
||||||
from PySide6.QtWidgets import (
|
|
||||||
QLabel
|
|
||||||
)
|
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Qt, Property, QPropertyAnimation, QEasingCurve
|
Property,
|
||||||
|
QEasingCurve,
|
||||||
|
QPropertyAnimation,
|
||||||
|
Qt
|
||||||
)
|
)
|
||||||
from PySide6.QtGui import (
|
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()
|
self.setupUi()
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.setFixedSize(36, 36)
|
self.setFixedSize(36, 36)
|
||||||
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
|
|
||||||
self.RunningAnimation = QPropertyAnimation(self, b"iconAngle")
|
self.RunningAnimation = QPropertyAnimation(self, b"iconAngle")
|
||||||
self.RunningAnimation.setDuration(1000)
|
self.RunningAnimation.setDuration(1000)
|
||||||
self.RunningAnimation.setStartValue(0)
|
self.RunningAnimation.setStartValue(0)
|
||||||
@@ -59,14 +63,12 @@ class ALStatusLabel(QLabel):
|
|||||||
self.RunningAnimation.setLoopCount(-1)
|
self.RunningAnimation.setLoopCount(-1)
|
||||||
self.RunningAnimation.setEasingCurve(QEasingCurve.Type.Linear)
|
self.RunningAnimation.setEasingCurve(QEasingCurve.Type.Linear)
|
||||||
|
|
||||||
|
|
||||||
def isDarkMode(
|
def isDarkMode(
|
||||||
self
|
self
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
|
||||||
return self.palette().color(QPalette.ColorRole.Window).value() < 128
|
return self.palette().color(QPalette.ColorRole.Window).value() < 128
|
||||||
|
|
||||||
|
|
||||||
def getMarkColor(
|
def getMarkColor(
|
||||||
self
|
self
|
||||||
) -> QColor:
|
) -> QColor:
|
||||||
@@ -111,7 +113,6 @@ class ALStatusLabel(QLabel):
|
|||||||
self.__icon_angle = value
|
self.__icon_angle = value
|
||||||
self.update()
|
self.update()
|
||||||
|
|
||||||
|
|
||||||
def paintEvent(
|
def paintEvent(
|
||||||
self,
|
self,
|
||||||
event
|
event
|
||||||
@@ -126,7 +127,6 @@ class ALStatusLabel(QLabel):
|
|||||||
case self.Status.WAITING:
|
case self.Status.WAITING:
|
||||||
pen = painter.pen()
|
pen = painter.pen()
|
||||||
pen.setWidth(2)
|
pen.setWidth(2)
|
||||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
|
||||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||||
pen.setColor(QColor("#969696")) # grey
|
pen.setColor(QColor("#969696")) # grey
|
||||||
painter.setPen(pen)
|
painter.setPen(pen)
|
||||||
@@ -155,7 +155,6 @@ class ALStatusLabel(QLabel):
|
|||||||
# draw the success green circle
|
# draw the success green circle
|
||||||
pen = painter.pen()
|
pen = painter.pen()
|
||||||
pen.setWidth(2)
|
pen.setWidth(2)
|
||||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
|
||||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||||
pen.setColor(QColor("#4CAF50" if self.isDarkMode() else "#00AF50")) # green
|
pen.setColor(QColor("#4CAF50" if self.isDarkMode() else "#00AF50")) # green
|
||||||
painter.setPen(pen)
|
painter.setPen(pen)
|
||||||
@@ -192,7 +191,6 @@ class ALStatusLabel(QLabel):
|
|||||||
# draw the warning orange circle
|
# draw the warning orange circle
|
||||||
pen = painter.pen()
|
pen = painter.pen()
|
||||||
pen.setWidth(2)
|
pen.setWidth(2)
|
||||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
|
||||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||||
pen.setColor(QColor("#FF9800")) # orange
|
pen.setColor(QColor("#FF9800")) # orange
|
||||||
painter.setPen(pen)
|
painter.setPen(pen)
|
||||||
@@ -222,7 +220,6 @@ class ALStatusLabel(QLabel):
|
|||||||
# draw the failure red circle
|
# draw the failure red circle
|
||||||
pen = painter.pen()
|
pen = painter.pen()
|
||||||
pen.setWidth(2)
|
pen.setWidth(2)
|
||||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
|
||||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||||
pen.setColor(QColor("#DC0000")) # red
|
pen.setColor(QColor("#DC0000")) # red
|
||||||
painter.setPen(pen)
|
painter.setPen(pen)
|
||||||
|
|||||||
@@ -12,12 +12,25 @@ import uuid
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
from datetime import datetime, timedelta
|
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.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.resources.ui.Ui_ALTimerTaskAddDialog import Ui_ALTimerTaskAddDialog
|
||||||
from gui.ALAutoScriptOrchDialog import ALAutoScriptOrchDialog
|
|
||||||
from utils.TimerUtils import TimerUtils
|
from utils.TimerUtils import TimerUtils
|
||||||
|
|
||||||
|
|
||||||
@@ -50,7 +63,6 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
if self.__edit_timer_task:
|
if self.__edit_timer_task:
|
||||||
self.loadTask(self.__edit_timer_task)
|
self.loadTask(self.__edit_timer_task)
|
||||||
|
|
||||||
|
|
||||||
def modifyUi(
|
def modifyUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -68,7 +80,6 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
self.SpecificDateTimeEdit.setDateTime(QDateTime.currentDateTime().addSecs(60))
|
self.SpecificDateTimeEdit.setDateTime(QDateTime.currentDateTime().addSecs(60))
|
||||||
self.SpecificTimerLayout.addWidget(self.SpecificDateTimeEdit)
|
self.SpecificTimerLayout.addWidget(self.SpecificDateTimeEdit)
|
||||||
self.TimerConfigLayout.addWidget(self.SpecificTimerWidget)
|
self.TimerConfigLayout.addWidget(self.SpecificTimerWidget)
|
||||||
|
|
||||||
self.RelativeTimerWidget = QWidget()
|
self.RelativeTimerWidget = QWidget()
|
||||||
self.RelativeTimerLayout = QHBoxLayout(self.RelativeTimerWidget)
|
self.RelativeTimerLayout = QHBoxLayout(self.RelativeTimerWidget)
|
||||||
self.RelativeTimerLayout.setContentsMargins(0, 0, 0, 0)
|
self.RelativeTimerLayout.setContentsMargins(0, 0, 0, 0)
|
||||||
@@ -96,25 +107,20 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
self.RelativeTimerLayout.addWidget(self.RelativeSecondSpinBox)
|
self.RelativeTimerLayout.addWidget(self.RelativeSecondSpinBox)
|
||||||
self.TimerConfigLayout.addWidget(self.RelativeTimerWidget)
|
self.TimerConfigLayout.addWidget(self.RelativeTimerWidget)
|
||||||
self.RelativeTimerWidget.setVisible(False)
|
self.RelativeTimerWidget.setVisible(False)
|
||||||
|
|
||||||
self.AutoScriptGroupBox = QGroupBox("AutoScript 指令")
|
self.AutoScriptGroupBox = QGroupBox("AutoScript 指令")
|
||||||
self.AutoScriptLayout = QVBoxLayout(self.AutoScriptGroupBox)
|
self.AutoScriptLayout = QVBoxLayout(self.AutoScriptGroupBox)
|
||||||
self.AutoScriptLayout.setContentsMargins(3, 3, 3, 3)
|
self.AutoScriptLayout.setContentsMargins(3, 3, 3, 3)
|
||||||
self.AutoScriptLayout.setSpacing(3)
|
self.AutoScriptLayout.setSpacing(3)
|
||||||
autoScriptBtnLayout = QHBoxLayout()
|
AutoScriptBtnLayout = QHBoxLayout()
|
||||||
self.AutoScriptSetButton = QPushButton("设置指令")
|
self.AutoScriptEditButton = QPushButton("编辑")
|
||||||
self.AutoScriptSetButton.setMinimumHeight(25)
|
self.AutoScriptEditButton.setMinimumHeight(25)
|
||||||
self.AutoScriptSetButton.setFixedWidth(130)
|
self.AutoScriptEditButton.setFixedWidth(80)
|
||||||
autoScriptBtnLayout.addWidget(self.AutoScriptSetButton)
|
AutoScriptBtnLayout.addWidget(self.AutoScriptEditButton)
|
||||||
self.AutoScriptPreviewButton = QPushButton("编辑")
|
AutoScriptBtnLayout.addStretch()
|
||||||
self.AutoScriptPreviewButton.setMinimumHeight(25)
|
|
||||||
self.AutoScriptPreviewButton.setFixedWidth(60)
|
|
||||||
autoScriptBtnLayout.addWidget(self.AutoScriptPreviewButton)
|
|
||||||
autoScriptBtnLayout.addStretch()
|
|
||||||
self.AutoScriptHelpButton = QPushButton("?")
|
self.AutoScriptHelpButton = QPushButton("?")
|
||||||
self.AutoScriptHelpButton.setFixedSize(20, 20)
|
self.AutoScriptHelpButton.setFixedSize(20, 20)
|
||||||
self.AutoScriptHelpButton.setToolTip(
|
self.AutoScriptHelpButton.setToolTip(
|
||||||
"AutoScript 是一种轻量级 DSL\n"
|
"AutoScript 是一种轻量级 DSL 语言,基于 Lua 实现。\n"
|
||||||
"用于在重复定时任务执行前,对用户的预约数据进行预处理\n"
|
"用于在重复定时任务执行前,对用户的预约数据进行预处理\n"
|
||||||
"\n"
|
"\n"
|
||||||
"点击查看完整在线文档"
|
"点击查看完整在线文档"
|
||||||
@@ -124,19 +130,19 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
"font-weight: bold; color: #555; }"
|
"font-weight: bold; color: #555; }"
|
||||||
"QPushButton:hover { background-color: #E0E0E0; }"
|
"QPushButton:hover { background-color: #E0E0E0; }"
|
||||||
)
|
)
|
||||||
autoScriptBtnLayout.addWidget(self.AutoScriptHelpButton)
|
AutoScriptBtnLayout.addWidget(self.AutoScriptHelpButton)
|
||||||
self.AutoScriptStatusLabel = QLabel("未设置")
|
self.AutoScriptStatusLabel = QLabel("未设置")
|
||||||
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
||||||
self.AutoScriptStatusLabel.setFixedHeight(25)
|
self.AutoScriptStatusLabel.setFixedHeight(25)
|
||||||
autoScriptBtnLayout.addWidget(self.AutoScriptStatusLabel)
|
AutoScriptBtnLayout.addWidget(self.AutoScriptStatusLabel)
|
||||||
self.AutoScriptLayout.addLayout(autoScriptBtnLayout)
|
self.AutoScriptLayout.addLayout(AutoScriptBtnLayout)
|
||||||
self.ALAddTimerTaskLayout.insertWidget(
|
self.ALAddTimerTaskLayout.insertWidget(
|
||||||
self.ALAddTimerTaskLayout.indexOf(self.TaskConfigGroupBox) + 1,
|
self.ALAddTimerTaskLayout.indexOf(self.TaskConfigGroupBox) + 1,
|
||||||
self.AutoScriptGroupBox
|
self.AutoScriptGroupBox
|
||||||
)
|
)
|
||||||
self.AutoScriptGroupBox.setVisible(False)
|
self.AutoScriptGroupBox.setVisible(False)
|
||||||
self.__auto_script = ""
|
self.__auto_script = ""
|
||||||
|
self.__mock_target_data = None
|
||||||
|
|
||||||
def loadTask(
|
def loadTask(
|
||||||
self,
|
self,
|
||||||
@@ -173,9 +179,11 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
self.__auto_script = auto_script
|
self.__auto_script = auto_script
|
||||||
self.AutoScriptStatusLabel.setText("已设置")
|
self.AutoScriptStatusLabel.setText("已设置")
|
||||||
self.AutoScriptStatusLabel.setStyleSheet("color: #4CAF50;")
|
self.AutoScriptStatusLabel.setStyleSheet("color: #4CAF50;")
|
||||||
|
mock_data = task.get("mock_target_data")
|
||||||
|
if mock_data:
|
||||||
|
self.__mock_target_data = mock_data
|
||||||
self.ConfirmButton.setText("保存")
|
self.ConfirmButton.setText("保存")
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -184,11 +192,9 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
self.ConfirmButton.clicked.connect(self.accept)
|
self.ConfirmButton.clicked.connect(self.accept)
|
||||||
self.TimerTypeComboBox.currentIndexChanged.connect(self.onTimerTypeComboBoxIndexChanged)
|
self.TimerTypeComboBox.currentIndexChanged.connect(self.onTimerTypeComboBoxIndexChanged)
|
||||||
self.RepeatCheckBox.toggled.connect(self.onRepeatCheckBoxToggled)
|
self.RepeatCheckBox.toggled.connect(self.onRepeatCheckBoxToggled)
|
||||||
self.AutoScriptSetButton.clicked.connect(self.onSetAutoScript)
|
self.AutoScriptEditButton.clicked.connect(self.onPreviewAutoScript)
|
||||||
self.AutoScriptPreviewButton.clicked.connect(self.onPreviewAutoScript)
|
|
||||||
self.AutoScriptHelpButton.clicked.connect(self.onAutoScriptHelp)
|
self.AutoScriptHelpButton.clicked.connect(self.onAutoScriptHelp)
|
||||||
|
|
||||||
|
|
||||||
def getTimerTask(
|
def getTimerTask(
|
||||||
self
|
self
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -220,6 +226,7 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
task_data["status"] = ALTimerTaskStatus.PENDING
|
task_data["status"] = ALTimerTaskStatus.PENDING
|
||||||
task_data["executed"] = False
|
task_data["executed"] = False
|
||||||
task_data["repeat_auto_script"] = self.__auto_script
|
task_data["repeat_auto_script"] = self.__auto_script
|
||||||
|
task_data["mock_target_data"] = self.__mock_target_data
|
||||||
else:
|
else:
|
||||||
task_data = {
|
task_data = {
|
||||||
"name": name,
|
"name": name,
|
||||||
@@ -232,6 +239,7 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
"executed": False,
|
"executed": False,
|
||||||
"repeat": self.RepeatCheckBox.isChecked(),
|
"repeat": self.RepeatCheckBox.isChecked(),
|
||||||
"repeat_auto_script": self.__auto_script,
|
"repeat_auto_script": self.__auto_script,
|
||||||
|
"mock_target_data": self.__mock_target_data,
|
||||||
}
|
}
|
||||||
|
|
||||||
repeat = self.RepeatCheckBox.isChecked()
|
repeat = self.RepeatCheckBox.isChecked()
|
||||||
@@ -292,34 +300,21 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
self.SunCheckBox.setEnabled(checked)
|
self.SunCheckBox.setEnabled(checked)
|
||||||
self.AutoScriptGroupBox.setVisible(checked)
|
self.AutoScriptGroupBox.setVisible(checked)
|
||||||
|
|
||||||
@Slot()
|
|
||||||
def onSetAutoScript(self):
|
|
||||||
dlg = ALAutoScriptOrchDialog(self, existingScript=self.__auto_script)
|
|
||||||
if dlg.exec() == QDialog.DialogCode.Accepted:
|
|
||||||
script = dlg.getScript()
|
|
||||||
self.__auto_script = script
|
|
||||||
if script:
|
|
||||||
self.AutoScriptStatusLabel.setText("已设置")
|
|
||||||
self.AutoScriptStatusLabel.setStyleSheet("color: #4CAF50;")
|
|
||||||
else:
|
|
||||||
self.AutoScriptStatusLabel.setText("未设置")
|
|
||||||
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
|
||||||
dlg.deleteLater()
|
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onPreviewAutoScript(self):
|
def onPreviewAutoScript(self):
|
||||||
from gui.ALAutoScriptEditDialog import ALAutoScriptEditDialog
|
from gui.ALAutoScriptEditDialog import ALAutoScriptEditDialog
|
||||||
dlg = ALAutoScriptEditDialog(self, self.__auto_script)
|
Dlg = ALAutoScriptEditDialog(self, self.__auto_script, self.__mock_target_data)
|
||||||
if dlg.exec() == QDialog.DialogCode.Accepted:
|
if Dlg.exec() == QDialog.DialogCode.Accepted:
|
||||||
script = dlg.getScript()
|
script = Dlg.getScript()
|
||||||
self.__auto_script = script
|
self.__auto_script = script
|
||||||
|
self.__mock_target_data = Dlg.getMockData()
|
||||||
if script:
|
if script:
|
||||||
self.AutoScriptStatusLabel.setText("已设置")
|
self.AutoScriptStatusLabel.setText("已设置")
|
||||||
self.AutoScriptStatusLabel.setStyleSheet("color: #4CAF50;")
|
self.AutoScriptStatusLabel.setStyleSheet("color: #4CAF50;")
|
||||||
else:
|
else:
|
||||||
self.AutoScriptStatusLabel.setText("未设置")
|
self.AutoScriptStatusLabel.setText("未设置")
|
||||||
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
||||||
dlg.deleteLater()
|
Dlg.deleteLater()
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onAutoScriptHelp(
|
def onAutoScriptHelp(
|
||||||
@@ -327,5 +322,5 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
|||||||
):
|
):
|
||||||
|
|
||||||
QDesktopServices.openUrl(
|
QDesktopServices.openUrl(
|
||||||
QUrl("https://www.autolibrary.kenanzhu.com/manuals/autoscript")
|
QUrl("https://manuals.autolibrary.kenanzhu.com/zh/autoscript")
|
||||||
)
|
)
|
||||||
@@ -34,7 +34,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
self.setupUi()
|
self.setupUi()
|
||||||
self.connectSignals()
|
self.connectSignals()
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -42,7 +41,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
self.setWindowTitle("定时任务执行历史 - AutoLibrary")
|
self.setWindowTitle("定时任务执行历史 - AutoLibrary")
|
||||||
self.setMinimumSize(300, 300)
|
self.setMinimumSize(300, 300)
|
||||||
self.setMaximumSize(500, 400)
|
self.setMaximumSize(500, 400)
|
||||||
|
|
||||||
MainLayout = QVBoxLayout(self)
|
MainLayout = QVBoxLayout(self)
|
||||||
InfoLayout = QGridLayout()
|
InfoLayout = QGridLayout()
|
||||||
TaskNameLabel = QLabel(f"任务: {self.__task_data.get('name', '未命名')}")
|
TaskNameLabel = QLabel(f"任务: {self.__task_data.get('name', '未命名')}")
|
||||||
@@ -52,7 +50,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
TaskUUIDLabel.setStyleSheet("color: #969696; font-size: 11px;")
|
TaskUUIDLabel.setStyleSheet("color: #969696; font-size: 11px;")
|
||||||
InfoLayout.addWidget(TaskUUIDLabel, 1, 0)
|
InfoLayout.addWidget(TaskUUIDLabel, 1, 0)
|
||||||
InfoLayout.setColumnStretch(0, 1)
|
InfoLayout.setColumnStretch(0, 1)
|
||||||
|
|
||||||
if self.__task_data.get("repeat", False):
|
if self.__task_data.get("repeat", False):
|
||||||
RepeatLabel = QLabel("可重复性任务")
|
RepeatLabel = QLabel("可重复性任务")
|
||||||
RepeatLabel.setStyleSheet("color: #2294FF; font-size: 12px;")
|
RepeatLabel.setStyleSheet("color: #2294FF; font-size: 12px;")
|
||||||
@@ -69,7 +66,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
self.HistoryTableWidget.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
|
self.HistoryTableWidget.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
|
||||||
self.loadHistory()
|
self.loadHistory()
|
||||||
MainLayout.addWidget(self.HistoryTableWidget)
|
MainLayout.addWidget(self.HistoryTableWidget)
|
||||||
|
|
||||||
ButtonLayout = QHBoxLayout()
|
ButtonLayout = QHBoxLayout()
|
||||||
ButtonLayout.addStretch()
|
ButtonLayout.addStretch()
|
||||||
self.CloseButton = QPushButton("关闭")
|
self.CloseButton = QPushButton("关闭")
|
||||||
@@ -82,7 +78,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
ButtonLayout.addWidget(self.CloseButton)
|
ButtonLayout.addWidget(self.CloseButton)
|
||||||
MainLayout.addLayout(ButtonLayout)
|
MainLayout.addLayout(ButtonLayout)
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -90,7 +85,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
self.CloseButton.clicked.connect(self.accept)
|
self.CloseButton.clicked.connect(self.accept)
|
||||||
self.ClearHistoryButton.clicked.connect(self.onClearHistoryButtonClicked)
|
self.ClearHistoryButton.clicked.connect(self.onClearHistoryButtonClicked)
|
||||||
|
|
||||||
|
|
||||||
def loadHistory(
|
def loadHistory(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -99,6 +93,11 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
for row, record in enumerate(self.__history):
|
for row, record in enumerate(self.__history):
|
||||||
self.addHistoryRow(row, record)
|
self.addHistoryRow(row, record)
|
||||||
|
|
||||||
|
def getHistory(
|
||||||
|
self
|
||||||
|
) -> list:
|
||||||
|
|
||||||
|
return self.__history
|
||||||
|
|
||||||
def addHistoryRow(
|
def addHistoryRow(
|
||||||
self,
|
self,
|
||||||
@@ -109,33 +108,26 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
execute_time = record.get("execute_time", "")
|
execute_time = record.get("execute_time", "")
|
||||||
result = record.get("result", ALTimerTaskStatus.UNKNOWN)
|
result = record.get("result", ALTimerTaskStatus.UNKNOWN)
|
||||||
duration = record.get("duration", 0)
|
duration = record.get("duration", 0)
|
||||||
ExecuteTimeItem = QTableWidgetItem(execute_time)
|
execute_time_item = QTableWidgetItem(execute_time)
|
||||||
ExecuteTimeItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
execute_time_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
self.HistoryTableWidget.setItem(row, 0, ExecuteTimeItem)
|
self.HistoryTableWidget.setItem(row, 0, execute_time_item)
|
||||||
ResultItem = QTableWidgetItem(result.value)
|
result_item = QTableWidgetItem(result.value)
|
||||||
ResultItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
result_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
match result:
|
match result:
|
||||||
case ALTimerTaskStatus.EXECUTED:
|
case ALTimerTaskStatus.EXECUTED:
|
||||||
ResultItem.setForeground(Qt.GlobalColor.green)
|
result_item.setForeground(Qt.GlobalColor.green)
|
||||||
case ALTimerTaskStatus.ERROR:
|
case ALTimerTaskStatus.ERROR:
|
||||||
ResultItem.setForeground(Qt.GlobalColor.red)
|
result_item.setForeground(Qt.GlobalColor.red)
|
||||||
case ALTimerTaskStatus.OUTDATED:
|
case ALTimerTaskStatus.OUTDATED:
|
||||||
ResultItem.setForeground(Qt.GlobalColor.red)
|
result_item.setForeground(Qt.GlobalColor.red)
|
||||||
case _:
|
case _:
|
||||||
ResultItem.setForeground(Qt.GlobalColor.black)
|
result_item.setForeground(Qt.GlobalColor.black)
|
||||||
self.HistoryTableWidget.setItem(row, 1, ResultItem)
|
self.HistoryTableWidget.setItem(row, 1, result_item)
|
||||||
DurationItem = QTableWidgetItem(f"{duration:.2f}")
|
duration_item = QTableWidgetItem(f"{duration:.2f}")
|
||||||
DurationItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
duration_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||||
self.HistoryTableWidget.setItem(row, 2, DurationItem)
|
self.HistoryTableWidget.setItem(row, 2, duration_item)
|
||||||
self.HistoryTableWidget.setRowHeight(row, 25)
|
self.HistoryTableWidget.setRowHeight(row, 25)
|
||||||
|
|
||||||
|
|
||||||
def getHistory(
|
|
||||||
self
|
|
||||||
) -> list:
|
|
||||||
|
|
||||||
return self.__history
|
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onClearHistoryButtonClicked(
|
def onClearHistoryButtonClicked(
|
||||||
self
|
self
|
||||||
@@ -143,4 +135,4 @@ class ALTimerTaskHistoryDialog(QDialog):
|
|||||||
|
|
||||||
self.__history.clear()
|
self.__history.clear()
|
||||||
self.HistoryTableWidget.setRowCount(0)
|
self.HistoryTableWidget.setRowCount(0)
|
||||||
self.__task_data["repeat_history"] = self.__history
|
self.__task_data["repeat_history"] = self.__history # = []
|
||||||
@@ -15,24 +15,41 @@ from enum import Enum
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Qt, Signal, Slot, QTimer
|
QTimer,
|
||||||
)
|
Qt,
|
||||||
from PySide6.QtWidgets import (
|
Signal,
|
||||||
QDialog, QWidget, QListWidgetItem, QMessageBox,
|
Slot
|
||||||
QHBoxLayout, QVBoxLayout, QLabel, QPushButton, QMenu
|
|
||||||
)
|
)
|
||||||
from PySide6.QtGui import (
|
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
|
import managers.config.ConfigManager as ConfigManager
|
||||||
|
|
||||||
from utils.TimerUtils import TimerUtils
|
from gui.ALTimerTaskAddDialog import (
|
||||||
from interfaces.ConfigProvider import ConfigProvider, CfgKey
|
ALTimerTaskAddDialog,
|
||||||
|
ALTimerTaskStatus
|
||||||
from gui.resources.ui.Ui_ALTimerTaskManageWidget import Ui_ALTimerTaskManageWidget
|
)
|
||||||
from gui.ALTimerTaskAddDialog import ALTimerTaskAddDialog, ALTimerTaskStatus
|
|
||||||
from gui.ALTimerTaskHistoryDialog import ALTimerTaskHistoryDialog
|
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):
|
class ALTimerTaskItemWidget(QWidget):
|
||||||
@@ -53,7 +70,6 @@ class ALTimerTaskItemWidget(QWidget):
|
|||||||
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
|
||||||
self.customContextMenuRequested.connect(self.showContextMenu)
|
self.customContextMenuRequested.connect(self.showContextMenu)
|
||||||
|
|
||||||
|
|
||||||
def modifyUi(
|
def modifyUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -65,12 +81,12 @@ class ALTimerTaskItemWidget(QWidget):
|
|||||||
self.TaskInfoLayout = QVBoxLayout()
|
self.TaskInfoLayout = QVBoxLayout()
|
||||||
self.TaskInfoLayout.setSpacing(5)
|
self.TaskInfoLayout.setSpacing(5)
|
||||||
TaskNameLabel = QLabel(self.__timer_task["name"])
|
TaskNameLabel = QLabel(self.__timer_task["name"])
|
||||||
TaskNameLabelFont = TaskNameLabel.font()
|
task_name_label_font = TaskNameLabel.font()
|
||||||
TaskNameLabelFont.setBold(True)
|
task_name_label_font.setBold(True)
|
||||||
TaskNameLabel.setFont(TaskNameLabelFont)
|
TaskNameLabel.setFont(task_name_label_font)
|
||||||
TaskNameLabel.setFixedHeight(25)
|
TaskNameLabel.setFixedHeight(25)
|
||||||
self.TaskInfoLayout.addWidget(TaskNameLabel)
|
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):
|
if self.__timer_task.get("repeat", False):
|
||||||
repeat_days = self.__timer_task.get("repeat_days", [])
|
repeat_days = self.__timer_task.get("repeat_days", [])
|
||||||
repeat_hour = self.__timer_task.get("repeat_hour", 0)
|
repeat_hour = self.__timer_task.get("repeat_hour", 0)
|
||||||
@@ -78,14 +94,14 @@ class ALTimerTaskItemWidget(QWidget):
|
|||||||
repeat_second = self.__timer_task.get("repeat_second", 0)
|
repeat_second = self.__timer_task.get("repeat_second", 0)
|
||||||
if len(repeat_days) == 7:
|
if len(repeat_days) == 7:
|
||||||
time_str = f"{repeat_hour:02d}:{repeat_minute:02d}:{repeat_second:02d}"
|
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:
|
else:
|
||||||
day_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
|
day_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
|
||||||
selected_days = [day_names[d] for d in repeat_days]
|
selected_days = [day_names[d] for d in repeat_days]
|
||||||
time_str = f"{repeat_hour:02d}:{repeat_minute:02d}:{repeat_second:02d}"
|
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:
|
else:
|
||||||
ExecuteTimeLabel = QLabel(f"执行时间: {ExecuteTimeStr}")
|
ExecuteTimeLabel = QLabel(f"执行时间: {execute_time_str}")
|
||||||
ExecuteTimeLabel.setStyleSheet("color: #969696;")
|
ExecuteTimeLabel.setStyleSheet("color: #969696;")
|
||||||
ExecuteTimeLabel.setFixedHeight(20)
|
ExecuteTimeLabel.setFixedHeight(20)
|
||||||
self.TaskInfoLayout.addWidget(ExecuteTimeLabel)
|
self.TaskInfoLayout.addWidget(ExecuteTimeLabel)
|
||||||
@@ -158,23 +174,23 @@ class ALTimerTaskItemWidget(QWidget):
|
|||||||
pos
|
pos
|
||||||
):
|
):
|
||||||
|
|
||||||
menu = QMenu(self)
|
Menu = QMenu(self)
|
||||||
edit_action = QAction("编辑", self)
|
EditAction = QAction("编辑", self)
|
||||||
edit_action.triggered.connect(
|
EditAction.triggered.connect(
|
||||||
lambda: self.editRequested.emit(self.__timer_task)
|
lambda: self.editRequested.emit(self.__timer_task)
|
||||||
)
|
)
|
||||||
menu.addAction(edit_action)
|
Menu.addAction(EditAction)
|
||||||
if self.__timer_task["status"] != ALTimerTaskStatus.RUNNING\
|
if self.__timer_task["status"] != ALTimerTaskStatus.RUNNING\
|
||||||
and self.__timer_task["status"] != ALTimerTaskStatus.READY:
|
and self.__timer_task["status"] != ALTimerTaskStatus.READY:
|
||||||
delete_action = QAction("删除", self)
|
DeleteAction = QAction("删除", self)
|
||||||
delete_action.triggered.connect(
|
DeleteAction.triggered.connect(
|
||||||
lambda: self.__manage_widget.deleteTask(self.__timer_task)
|
lambda: self.__manage_widget.deleteTask(self.__timer_task)
|
||||||
)
|
)
|
||||||
menu.addAction(delete_action)
|
Menu.addAction(DeleteAction)
|
||||||
menu.exec(self.mapToGlobal(pos))
|
Menu.exec(self.mapToGlobal(pos))
|
||||||
|
|
||||||
|
|
||||||
class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
class ALTimerTaskManageWidget(CenterOnParentMixin, QWidget, Ui_ALTimerTaskManageWidget):
|
||||||
|
|
||||||
class SortPolicy(Enum):
|
class SortPolicy(Enum):
|
||||||
|
|
||||||
@@ -194,7 +210,7 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
self.__cfg_mgr: ConfigProvider = ConfigManager.instance()
|
self.__cfg_mgr: ConfigProvider = ConfigManager.instance()
|
||||||
self.__timer_tasks = []
|
self.__timer_tasks = []
|
||||||
self.__check_timer = None
|
self.__CheckTimer = None
|
||||||
self.__sort_policy = self.SortPolicy.BY_EXECUTE_TIME
|
self.__sort_policy = self.SortPolicy.BY_EXECUTE_TIME
|
||||||
self.__sort_order = Qt.SortOrder.AscendingOrder
|
self.__sort_order = Qt.SortOrder.AscendingOrder
|
||||||
|
|
||||||
@@ -204,7 +220,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
if not self.initializeTimerTasks():
|
if not self.initializeTimerTasks():
|
||||||
raise Exception("定时任务配置文件初始化失败 !")
|
raise Exception("定时任务配置文件初始化失败 !")
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -215,15 +230,13 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
self.TimerTaskSortOrderToggleButton.clicked.connect(self.onSortOrderToggleButtonClicked)
|
self.TimerTaskSortOrderToggleButton.clicked.connect(self.onSortOrderToggleButtonClicked)
|
||||||
self.timerTasksChanged.connect(self.onTimerTasksChanged)
|
self.timerTasksChanged.connect(self.onTimerTasksChanged)
|
||||||
|
|
||||||
|
|
||||||
def setupTimer(
|
def setupTimer(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.__check_timer = QTimer(self)
|
self.__CheckTimer = QTimer(self)
|
||||||
self.__check_timer.timeout.connect(self.checkTasks)
|
self.__CheckTimer.timeout.connect(self.checkTasks)
|
||||||
self.__check_timer.start(500)
|
self.__CheckTimer.start(500)
|
||||||
|
|
||||||
|
|
||||||
def initializeTimerTasks(
|
def initializeTimerTasks(
|
||||||
self
|
self
|
||||||
@@ -240,7 +253,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def getTimerTasks(
|
def getTimerTasks(
|
||||||
self
|
self
|
||||||
) -> list:
|
) -> list:
|
||||||
@@ -265,7 +277,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
)
|
)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def setTimerTasks(
|
def setTimerTasks(
|
||||||
self,
|
self,
|
||||||
timer_tasks: list
|
timer_tasks: list
|
||||||
@@ -289,31 +300,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
)
|
)
|
||||||
return False
|
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(
|
def closeEvent(
|
||||||
self,
|
self,
|
||||||
event: QCloseEvent
|
event: QCloseEvent
|
||||||
@@ -323,7 +309,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
self.timerTaskManageWidgetIsClosed.emit()
|
self.timerTaskManageWidgetIsClosed.emit()
|
||||||
event.ignore()
|
event.ignore()
|
||||||
|
|
||||||
|
|
||||||
def sortTimerTasks(
|
def sortTimerTasks(
|
||||||
self,
|
self,
|
||||||
policy: SortPolicy = SortPolicy.BY_EXECUTE_TIME,
|
policy: SortPolicy = SortPolicy.BY_EXECUTE_TIME,
|
||||||
@@ -346,7 +331,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
reverse = order is Qt.SortOrder.DescendingOrder
|
reverse = order is Qt.SortOrder.DescendingOrder
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def updateStat(
|
def updateStat(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -373,7 +357,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
self.ExecutedTaskLabel.setText(f"已执行:{executed}")
|
self.ExecutedTaskLabel.setText(f"已执行:{executed}")
|
||||||
self.InvalidTaskLabel.setText(f"无效的:{invalid}")
|
self.InvalidTaskLabel.setText(f"无效的:{invalid}")
|
||||||
|
|
||||||
|
|
||||||
def updateTimerTaskList(
|
def updateTimerTaskList(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -381,41 +364,39 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
self.TimerTasksListWidget.clear()
|
self.TimerTasksListWidget.clear()
|
||||||
self.sortTimerTasks(self.__sort_policy, self.__sort_order)
|
self.sortTimerTasks(self.__sort_policy, self.__sort_order)
|
||||||
for timer_task in self.__timer_tasks:
|
for timer_task in self.__timer_tasks:
|
||||||
item = QListWidgetItem()
|
Item = QListWidgetItem()
|
||||||
item.setData(Qt.UserRole, timer_task)
|
Item.setData(Qt.UserRole, timer_task)
|
||||||
widget = ALTimerTaskItemWidget(self, timer_task)
|
Widget = ALTimerTaskItemWidget(self, timer_task)
|
||||||
widget.DeleteButton.clicked.connect(
|
Widget.DeleteButton.clicked.connect(
|
||||||
lambda _, task = timer_task: self.deleteTask(task)
|
lambda _, task = timer_task: self.deleteTask(task)
|
||||||
)
|
)
|
||||||
if timer_task.get("repeat", False) and hasattr(widget, "HistoryButton"):
|
if timer_task.get("repeat", False) and hasattr(Widget, "HistoryButton"):
|
||||||
widget.HistoryButton.clicked.connect(
|
Widget.HistoryButton.clicked.connect(
|
||||||
lambda _, task = timer_task: self.showTaskHistory(task)
|
lambda _, task = timer_task: self.showTaskHistory(task)
|
||||||
)
|
)
|
||||||
widget.editRequested.connect(self.editTask)
|
Widget.editRequested.connect(self.editTask)
|
||||||
item.setSizeHint(widget.size())
|
Item.setSizeHint(Widget.size())
|
||||||
self.TimerTasksListWidget.addItem(item)
|
self.TimerTasksListWidget.addItem(Item)
|
||||||
self.TimerTasksListWidget.setItemWidget(item, widget)
|
self.TimerTasksListWidget.setItemWidget(Item, Widget)
|
||||||
|
|
||||||
|
|
||||||
def addTask(
|
def addTask(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
dialog = ALTimerTaskAddDialog(self)
|
Dialog = ALTimerTaskAddDialog(self)
|
||||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||||
timer_task = dialog.getTimerTask()
|
timer_task = Dialog.getTimerTask()
|
||||||
self.__timer_tasks.append(timer_task)
|
self.__timer_tasks.append(timer_task)
|
||||||
self.timerTasksChanged.emit()
|
self.timerTasksChanged.emit()
|
||||||
|
|
||||||
|
|
||||||
def editTask(
|
def editTask(
|
||||||
self,
|
self,
|
||||||
timer_task: dict
|
timer_task: dict
|
||||||
):
|
):
|
||||||
|
|
||||||
dialog = ALTimerTaskAddDialog(self, timer_task)
|
Dialog = ALTimerTaskAddDialog(self, timer_task)
|
||||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||||
updated = dialog.getTimerTask()
|
updated = Dialog.getTimerTask()
|
||||||
for i, task in enumerate(self.__timer_tasks):
|
for i, task in enumerate(self.__timer_tasks):
|
||||||
if task["uuid"] == updated["uuid"]:
|
if task["uuid"] == updated["uuid"]:
|
||||||
self.__timer_tasks[i] = updated
|
self.__timer_tasks[i] = updated
|
||||||
@@ -440,26 +421,25 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
f"已记录次数:{history_count}"
|
f"已记录次数:{history_count}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def deleteTask(
|
def deleteTask(
|
||||||
self,
|
self,
|
||||||
timer_task: dict
|
timer_task: dict
|
||||||
):
|
):
|
||||||
|
|
||||||
if timer_task["repeat"]: # when delete a repeat task
|
if timer_task["repeat"]: # when delete a repeat task
|
||||||
msgbox = QMessageBox(self)
|
MsgBox = QMessageBox(self)
|
||||||
msgbox.setIcon(QMessageBox.Icon.Question)
|
MsgBox.setIcon(QMessageBox.Icon.Question)
|
||||||
msgbox.setWindowTitle("警告 - AutoLibrary")
|
MsgBox.setWindowTitle("警告 - AutoLibrary")
|
||||||
msgbox.setStandardButtons(
|
MsgBox.setStandardButtons(
|
||||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||||
)
|
)
|
||||||
msgbox.setText("删除可重复性任务将同时删除所有已执行的记录 !\n是否继续 ?")
|
MsgBox.setText("删除可重复性任务将同时删除所有已执行的记录 !\n是否继续 ?")
|
||||||
msgbox.setDetailedText(
|
MsgBox.setDetailedText(
|
||||||
"以下可重复性任务将被删除:\n"\
|
"以下可重复性任务将被删除:\n"\
|
||||||
"\n"
|
"\n"
|
||||||
f"{self.getTimerTaskDetailMessage(timer_task)}"
|
f"{self.getTimerTaskDetailMessage(timer_task)}"
|
||||||
)
|
)
|
||||||
result = msgbox.exec()
|
result = MsgBox.exec()
|
||||||
if result != QMessageBox.StandardButton.Yes:
|
if result != QMessageBox.StandardButton.Yes:
|
||||||
return
|
return
|
||||||
task_uuid = timer_task["uuid"]
|
task_uuid = timer_task["uuid"]
|
||||||
@@ -469,7 +449,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
]
|
]
|
||||||
self.timerTasksChanged.emit()
|
self.timerTasksChanged.emit()
|
||||||
|
|
||||||
|
|
||||||
def clearAllTasks(
|
def clearAllTasks(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -505,13 +484,13 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
]
|
]
|
||||||
repeat_tasks_count = len(repeat_tasks)
|
repeat_tasks_count = len(repeat_tasks)
|
||||||
if repeat_tasks_count > 0:
|
if repeat_tasks_count > 0:
|
||||||
msgbox = QMessageBox(self)
|
MsgBox = QMessageBox(self)
|
||||||
msgbox.setIcon(QMessageBox.Icon.Question)
|
MsgBox.setIcon(QMessageBox.Icon.Question)
|
||||||
msgbox.setWindowTitle("警告 - AutoLibrary")
|
MsgBox.setWindowTitle("警告 - AutoLibrary")
|
||||||
msgbox.setStandardButtons(
|
MsgBox.setStandardButtons(
|
||||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||||
)
|
)
|
||||||
msgbox.setText(
|
MsgBox.setText(
|
||||||
f"存在 {repeat_tasks_count} 个可重复性任务,\n"
|
f"存在 {repeat_tasks_count} 个可重复性任务,\n"
|
||||||
"删除可重复性任务将同时删除所有已执行的记录 !\n"
|
"删除可重复性任务将同时删除所有已执行的记录 !\n"
|
||||||
"是否继续 ?"
|
"是否继续 ?"
|
||||||
@@ -519,29 +498,32 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
delete_msgs = [
|
delete_msgs = [
|
||||||
self.getTimerTaskDetailMessage(x) for x in repeat_tasks
|
self.getTimerTaskDetailMessage(x) for x in repeat_tasks
|
||||||
]
|
]
|
||||||
msgbox.setDetailedText(
|
MsgBox.setDetailedText(
|
||||||
"以下可重复性任务将被删除:\n"\
|
"以下可重复性任务将被删除:\n"\
|
||||||
"\n"
|
"\n"
|
||||||
f"{"\n\n".join(delete_msgs)}"
|
f"{"\n\n".join(delete_msgs)}"
|
||||||
)
|
)
|
||||||
result = msgbox.exec()
|
result = MsgBox.exec()
|
||||||
if result != QMessageBox.StandardButton.Yes:
|
if result != QMessageBox.StandardButton.Yes:
|
||||||
return
|
return
|
||||||
# clear all tasks
|
# clear all tasks
|
||||||
self.__timer_tasks.clear()
|
self.__timer_tasks.clear()
|
||||||
self.timerTasksChanged.emit()
|
self.timerTasksChanged.emit()
|
||||||
|
|
||||||
|
|
||||||
def showTaskHistory(
|
def showTaskHistory(
|
||||||
self,
|
self,
|
||||||
task: dict
|
task: dict
|
||||||
):
|
):
|
||||||
|
|
||||||
dialog = ALTimerTaskHistoryDialog(self, task)
|
# Here we use reference to task data, not copy.
|
||||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
# 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()
|
self.timerTasksChanged.emit()
|
||||||
|
|
||||||
|
|
||||||
def checkTasks(
|
def checkTasks(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -615,7 +597,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
|||||||
break
|
break
|
||||||
self.timerTasksChanged.emit()
|
self.timerTasksChanged.emit()
|
||||||
|
|
||||||
|
|
||||||
def onRepeatTimerTaskIs(
|
def onRepeatTimerTaskIs(
|
||||||
self,
|
self,
|
||||||
status: ALTimerTaskStatus,
|
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 enum import Enum
|
||||||
|
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Qt, QSize, QCoreApplication, QRect, QPoint
|
Qt,
|
||||||
|
QSize,
|
||||||
|
QCoreApplication,
|
||||||
|
QRect,
|
||||||
|
QPoint
|
||||||
)
|
)
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
QAbstractScrollArea, QAbstractItemView,
|
QAbstractScrollArea,
|
||||||
QTreeWidget, QTreeWidgetItem
|
QAbstractItemView,
|
||||||
|
QTreeWidget,
|
||||||
|
QTreeWidgetItem
|
||||||
)
|
)
|
||||||
from PySide6.QtGui import (
|
from PySide6.QtGui import (
|
||||||
QDragEnterEvent, QDragMoveEvent, QDropEvent
|
QDragEnterEvent,
|
||||||
|
QDragMoveEvent,
|
||||||
|
QDropEvent
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -39,14 +47,13 @@ class ALUserTreeWidget(QTreeWidget):
|
|||||||
self.setupUi()
|
self.setupUi()
|
||||||
self.translateUi()
|
self.translateUi()
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
__qtreewidgetitem = QTreeWidgetItem()
|
__QTreeWidgetItem = QTreeWidgetItem()
|
||||||
__qtreewidgetitem.setText(0, u"\u5206\u7ec4/\u7528\u6237");
|
__QTreeWidgetItem.setText(0, u"\u5206\u7ec4/\u7528\u6237");
|
||||||
self.setHeaderItem(__qtreewidgetitem)
|
self.setHeaderItem(__QTreeWidgetItem)
|
||||||
self.setObjectName(u"UserTreeWidget")
|
self.setObjectName(u"UserTreeWidget")
|
||||||
self.setMinimumSize(QSize(230, 0))
|
self.setMinimumSize(QSize(230, 0))
|
||||||
self.setMaximumSize(QSize(250, 16777215))
|
self.setMaximumSize(QSize(250, 16777215))
|
||||||
@@ -70,14 +77,12 @@ class ALUserTreeWidget(QTreeWidget):
|
|||||||
self.header().setHighlightSections(False)
|
self.header().setHighlightSections(False)
|
||||||
self.header().setProperty(u"showSortIndicator", True)
|
self.header().setProperty(u"showSortIndicator", True)
|
||||||
|
|
||||||
|
|
||||||
def translateUi(
|
def translateUi(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
___qtreewidgetitem = self.headerItem()
|
___QTreeWidgetItem = self.headerItem()
|
||||||
___qtreewidgetitem.setText(1, QCoreApplication.translate("ALConfigWidget", u"\u72b6\u6001", None));
|
___QTreeWidgetItem.setText(1, QCoreApplication.translate("ALConfigWidget", u"\u72b6\u6001", None));
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def isDragPositionValid(
|
def isDragPositionValid(
|
||||||
@@ -90,7 +95,6 @@ class ALUserTreeWidget(QTreeWidget):
|
|||||||
y_offset < target_rect.height()*0.8)
|
y_offset < target_rect.height()*0.8)
|
||||||
return valid
|
return valid
|
||||||
|
|
||||||
|
|
||||||
def dragEnterEvent(
|
def dragEnterEvent(
|
||||||
self,
|
self,
|
||||||
event: QDragEnterEvent
|
event: QDragEnterEvent
|
||||||
@@ -98,7 +102,6 @@ class ALUserTreeWidget(QTreeWidget):
|
|||||||
|
|
||||||
super().dragEnterEvent(event)
|
super().dragEnterEvent(event)
|
||||||
|
|
||||||
|
|
||||||
def dragMoveEvent(
|
def dragMoveEvent(
|
||||||
self,
|
self,
|
||||||
event: QDragMoveEvent
|
event: QDragMoveEvent
|
||||||
@@ -136,7 +139,6 @@ class ALUserTreeWidget(QTreeWidget):
|
|||||||
return
|
return
|
||||||
event.acceptProposedAction()
|
event.acceptProposedAction()
|
||||||
|
|
||||||
|
|
||||||
def dropEvent(
|
def dropEvent(
|
||||||
self,
|
self,
|
||||||
event: QDropEvent
|
event: QDropEvent
|
||||||
|
|||||||
@@ -5,11 +5,11 @@
|
|||||||
workflow process. Do not edit manually.
|
workflow process. Do not edit manually.
|
||||||
|
|
||||||
This file is auto-generated during the workflow process.
|
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_VERSION = "1.4.0"
|
||||||
AL_TAG = "v1.3.0"
|
AL_TAG = "v1.4.0"
|
||||||
AL_COMMIT_SHA = "local"
|
AL_COMMIT_SHA = "local"
|
||||||
AL_COMMIT_DATE = "null" # time zone : UTC
|
AL_COMMIT_DATE = "null" # time zone : UTC
|
||||||
AL_BUILD_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.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
import threading
|
import threading
|
||||||
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from PySide6.QtCore import (
|
from PySide6.QtCore import (
|
||||||
Qt, Slot, QThread, Signal
|
Qt,
|
||||||
|
Slot,
|
||||||
|
QThread,
|
||||||
|
Signal
|
||||||
)
|
)
|
||||||
from PySide6.QtWidgets import (
|
from PySide6.QtWidgets import (
|
||||||
QDialog, QLabel, QComboBox, QProgressBar,
|
QDialog,
|
||||||
QPushButton, QVBoxLayout, QHBoxLayout,
|
QLabel,
|
||||||
QMessageBox, QFrame, QLineEdit
|
QComboBox,
|
||||||
)
|
QProgressBar,
|
||||||
from PySide6.QtGui import (
|
QPushButton,
|
||||||
QCloseEvent
|
QVBoxLayout,
|
||||||
|
QHBoxLayout,
|
||||||
|
QMessageBox,
|
||||||
|
QFrame,
|
||||||
|
QLineEdit
|
||||||
)
|
)
|
||||||
|
from PySide6.QtGui import QCloseEvent
|
||||||
|
|
||||||
from managers.driver.WebDriverManager import (
|
from managers.driver.WebDriverManager import (
|
||||||
instance as webdriver_manager_instance,
|
instance as webdriverInstance,
|
||||||
WebDriverManager, WebDriverInfo, WebDriverType,
|
WebDriverManager,
|
||||||
|
WebDriverCtx,
|
||||||
|
WebDriverType,
|
||||||
WebDriverStatus
|
WebDriverStatus
|
||||||
)
|
)
|
||||||
from gui.ALStatusLabel import ALStatusLabel
|
from gui.ALStatusLabel import ALStatusLabel
|
||||||
|
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||||
|
|
||||||
|
|
||||||
class DownloadWorker(QThread):
|
class DownloadWorker(QThread):
|
||||||
@@ -43,12 +55,12 @@ class DownloadWorker(QThread):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
driver_manager: WebDriverManager,
|
driver_manager: WebDriverManager,
|
||||||
driver_info: WebDriverInfo
|
driver_ctx: WebDriverCtx
|
||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.__driver_manager = driver_manager
|
self.__driver_manager = driver_manager
|
||||||
self.__driver_info = driver_info
|
self.__driver_ctx = driver_ctx
|
||||||
self.__driver_path = None
|
self.__driver_path: Optional[Path] = None
|
||||||
self.__cancelled = False
|
self.__cancelled = False
|
||||||
self.__cancel_event = threading.Event()
|
self.__cancel_event = threading.Event()
|
||||||
|
|
||||||
@@ -70,7 +82,7 @@ class DownloadWorker(QThread):
|
|||||||
self.downloadCancelled.emit()
|
self.downloadCancelled.emit()
|
||||||
return
|
return
|
||||||
self.__driver_path = self.__driver_manager.installDriver(
|
self.__driver_path = self.__driver_manager.installDriver(
|
||||||
self.__driver_info,
|
self.__driver_ctx,
|
||||||
progress_callback=self.onProgress,
|
progress_callback=self.onProgress,
|
||||||
cancel_event=self.__cancel_event
|
cancel_event=self.__cancel_event
|
||||||
)
|
)
|
||||||
@@ -113,7 +125,7 @@ class DownloadWorker(QThread):
|
|||||||
self.wait()
|
self.wait()
|
||||||
|
|
||||||
|
|
||||||
class ALWebDriverDownloadDialog(QDialog):
|
class ALWebDriverDownloadDialog(CenterOnParentMixin, QDialog):
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -129,12 +141,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
super().__init__(parent)
|
super().__init__(parent)
|
||||||
|
|
||||||
self.__driver_dir = driver_dir
|
self.__driver_dir = driver_dir
|
||||||
self.__driver_manager: Optional[WebDriverManager] = None
|
self.__driver_manager: Optional[WebDriverManager] = None
|
||||||
self.__confirmed = False
|
self.__confirmed = False
|
||||||
self.__selected_driver_info: Optional[WebDriverInfo] = None
|
self.__selected_driver_ctx: Optional[WebDriverCtx] = None
|
||||||
self.__driver_infos: list[WebDriverInfo] = []
|
self.__driver_ctxs: list[WebDriverCtx] = []
|
||||||
self.__download_thread: Optional[DownloadWorker] = None
|
self.__download_thread: Optional[DownloadWorker] = None
|
||||||
|
|
||||||
self.setupUi()
|
self.setupUi()
|
||||||
@@ -142,29 +153,26 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.initializeDriverManager()
|
self.initializeDriverManager()
|
||||||
self.refreshDriverList()
|
self.refreshDriverList()
|
||||||
|
|
||||||
|
def closeEvent(
|
||||||
def showEvent(
|
|
||||||
self,
|
self,
|
||||||
event
|
event: QCloseEvent
|
||||||
):
|
):
|
||||||
|
|
||||||
result = super().showEvent(event)
|
if self.__download_thread and self.__download_thread.isRunning():
|
||||||
if self.parent():
|
reply = QMessageBox.question(
|
||||||
screen_rect = self.screen().geometry()
|
self,
|
||||||
target_pos = self.parent().geometry().center()
|
"确认关闭 - AutoLibrary",
|
||||||
target_pos.setX(target_pos.x() - self.width()//2)
|
"驱动正在下载中, 确定要取消并关闭对话框吗 ?",
|
||||||
target_pos.setY(target_pos.y() - self.height()//2)
|
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||||
if target_pos.x() < 0:
|
)
|
||||||
target_pos.setX(0)
|
if reply == QMessageBox.StandardButton.No:
|
||||||
if target_pos.x() + self.width() > screen_rect.width():
|
event.ignore()
|
||||||
target_pos.setX(screen_rect.width() - self.width())
|
return
|
||||||
if target_pos.y() < 0:
|
self.__download_thread.stop()
|
||||||
target_pos.setY(0)
|
if not self.__confirmed:
|
||||||
if target_pos.y() + self.height() > screen_rect.height():
|
self.__selected_driver_ctx = None
|
||||||
target_pos.setY(screen_rect.height() - self.height())
|
event.accept()
|
||||||
self.move(target_pos)
|
super().closeEvent(event)
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def setupUi(
|
def setupUi(
|
||||||
self
|
self
|
||||||
@@ -174,14 +182,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.setMaximumHeight(240)
|
self.setMaximumHeight(240)
|
||||||
self.setMinimumHeight(240)
|
self.setMinimumHeight(240)
|
||||||
self.setWindowTitle("浏览器驱动下载 - AutoLibrary")
|
self.setWindowTitle("浏览器驱动下载 - AutoLibrary")
|
||||||
|
|
||||||
self.MainLayout = QVBoxLayout(self)
|
self.MainLayout = QVBoxLayout(self)
|
||||||
self.MainLayout.setContentsMargins(5, 5, 5, 5)
|
self.MainLayout.setContentsMargins(5, 5, 5, 5)
|
||||||
self.MainLayout.setSpacing(5)
|
self.MainLayout.setSpacing(5)
|
||||||
|
|
||||||
self.BrowserCountLabel = QLabel("检测到 0 个可用浏览器:")
|
self.BrowserCountLabel = QLabel("检测到 0 个可用浏览器:")
|
||||||
self.MainLayout.addWidget(self.BrowserCountLabel)
|
self.MainLayout.addWidget(self.BrowserCountLabel)
|
||||||
|
|
||||||
self.DriverInfoLayout = QHBoxLayout()
|
self.DriverInfoLayout = QHBoxLayout()
|
||||||
self.DriverInfoLayout.setSpacing(5)
|
self.DriverInfoLayout.setSpacing(5)
|
||||||
self.DriverComboBox = QComboBox()
|
self.DriverComboBox = QComboBox()
|
||||||
@@ -190,7 +195,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.StatusLabel.setFixedSize(32, 32)
|
self.StatusLabel.setFixedSize(32, 32)
|
||||||
self.DriverInfoLayout.addWidget(self.StatusLabel)
|
self.DriverInfoLayout.addWidget(self.StatusLabel)
|
||||||
self.MainLayout.addLayout(self.DriverInfoLayout)
|
self.MainLayout.addLayout(self.DriverInfoLayout)
|
||||||
|
|
||||||
self.DetailLayout = QVBoxLayout()
|
self.DetailLayout = QVBoxLayout()
|
||||||
self.DetailLayout.setSpacing(5)
|
self.DetailLayout.setSpacing(5)
|
||||||
self.DetailLayout.setContentsMargins(5, 5, 5, 5)
|
self.DetailLayout.setContentsMargins(5, 5, 5, 5)
|
||||||
@@ -203,7 +207,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.PathLabel.setText("路径:未安装")
|
self.PathLabel.setText("路径:未安装")
|
||||||
self.DetailLayout.addWidget(self.PathLabel)
|
self.DetailLayout.addWidget(self.PathLabel)
|
||||||
self.MainLayout.addLayout(self.DetailLayout)
|
self.MainLayout.addLayout(self.DetailLayout)
|
||||||
|
|
||||||
self.Line = QFrame()
|
self.Line = QFrame()
|
||||||
self.Line.setFrameShape(QFrame.Shape.HLine)
|
self.Line.setFrameShape(QFrame.Shape.HLine)
|
||||||
self.Line.setFrameShadow(QFrame.Shadow.Sunken)
|
self.Line.setFrameShadow(QFrame.Shadow.Sunken)
|
||||||
@@ -229,7 +232,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.ConfirmButton = QPushButton("确认")
|
self.ConfirmButton = QPushButton("确认")
|
||||||
self.ConfirmButton.setFixedSize(80, 25)
|
self.ConfirmButton.setFixedSize(80, 25)
|
||||||
self.ConfirmButton.setEnabled(False)
|
self.ConfirmButton.setEnabled(False)
|
||||||
|
|
||||||
self.ControlLayout.addWidget(self.RefreshButton)
|
self.ControlLayout.addWidget(self.RefreshButton)
|
||||||
self.ControlLayout.addWidget(self.DownloadButton)
|
self.ControlLayout.addWidget(self.DownloadButton)
|
||||||
self.ControlLayout.addWidget(self.DeleteButton)
|
self.ControlLayout.addWidget(self.DeleteButton)
|
||||||
@@ -237,7 +239,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.ControlLayout.addWidget(self.ConfirmButton)
|
self.ControlLayout.addWidget(self.ConfirmButton)
|
||||||
self.MainLayout.addLayout(self.ControlLayout)
|
self.MainLayout.addLayout(self.ControlLayout)
|
||||||
|
|
||||||
|
|
||||||
def connectSignals(
|
def connectSignals(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -249,18 +250,16 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||||
self.DriverComboBox.currentIndexChanged.connect(self.onDriverComboBoxChanged)
|
self.DriverComboBox.currentIndexChanged.connect(self.onDriverComboBoxChanged)
|
||||||
|
|
||||||
|
|
||||||
def initializeDriverManager(
|
def initializeDriverManager(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.__driver_manager = webdriver_manager_instance(self.__driver_dir)
|
self.__driver_manager = webdriverInstance(self.__driver_dir)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
QMessageBox.warning(self, "初始化失败", f"WebDriverManager 初始化失败:\n{str(e)}")
|
QMessageBox.warning(self, "初始化失败", f"WebDriverManager 初始化失败:\n{str(e)}")
|
||||||
self.reject()
|
self.reject()
|
||||||
|
|
||||||
|
|
||||||
def refreshDriverList(
|
def refreshDriverList(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -268,32 +267,116 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
if not self.__driver_manager:
|
if not self.__driver_manager:
|
||||||
return
|
return
|
||||||
self.__driver_manager.refresh()
|
self.__driver_manager.refresh()
|
||||||
self.__driver_infos = self.__driver_manager.getDriverInfos()
|
self.__driver_ctxs = self.__driver_manager.getDriverCtxs()
|
||||||
self.DriverComboBox.clear()
|
self.DriverComboBox.clear()
|
||||||
|
installed = 0
|
||||||
installed_idx = 0
|
installed_idx = 0
|
||||||
for i, driver_info in enumerate(self.__driver_infos):
|
for i, driver_ctx in enumerate(self.__driver_ctxs):
|
||||||
if driver_info.driver_status == WebDriverStatus.INSTALLED:
|
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
|
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)
|
self.DriverComboBox.addItem(display_text)
|
||||||
count = len(self.__driver_infos)
|
count = len(self.__driver_ctxs)
|
||||||
self.BrowserCountLabel.setText(f"检测到 {count} 个可用浏览器:")
|
self.BrowserCountLabel.setText(f"检测到 {count} 个可用浏览器,{installed} 个已安装驱动:")
|
||||||
if self.__driver_infos:
|
if self.__driver_ctxs:
|
||||||
self.DriverComboBox.setCurrentIndex(installed_idx)
|
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(
|
def onDriverComboBoxChanged(
|
||||||
self,
|
self,
|
||||||
index: int
|
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
|
return
|
||||||
driver_info = self.__driver_infos[index]
|
driver_ctx = self.__driver_ctxs[index]
|
||||||
self.updateDriverInfoDisplay(driver_info)
|
self.updateDriverInfoDisplay(driver_ctx)
|
||||||
self.updateProgressBarStates(driver_info)
|
self.updateProgressBarStates(driver_ctx)
|
||||||
self.updateButtonStates(driver_info)
|
self.updateButtonStates(driver_ctx)
|
||||||
|
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onRefreshButtonClicked(
|
def onRefreshButtonClicked(
|
||||||
@@ -302,16 +385,15 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
|
|
||||||
self.refreshDriverList()
|
self.refreshDriverList()
|
||||||
|
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onDeleteButtonClicked(
|
def onDeleteButtonClicked(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
index = self.DriverComboBox.currentIndex()
|
index = self.DriverComboBox.currentIndex()
|
||||||
if index < 0 or index >= len(self.__driver_infos):
|
if index < 0 or index >= len(self.__driver_ctxs):
|
||||||
return
|
return
|
||||||
driver_info = self.__driver_infos[index]
|
driver_info = self.__driver_ctxs[index]
|
||||||
if driver_info.driver_status.name != "INSTALLED":
|
if driver_info.driver_status.name != "INSTALLED":
|
||||||
QMessageBox.information(self, "提示 - AutoLibrary", "该驱动未安装, 无需删除")
|
QMessageBox.information(self, "提示 - AutoLibrary", "该驱动未安装, 无需删除")
|
||||||
return
|
return
|
||||||
@@ -337,9 +419,9 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
|
|
||||||
self.DriverComboBox.setEnabled(False)
|
self.DriverComboBox.setEnabled(False)
|
||||||
index = self.DriverComboBox.currentIndex()
|
index = self.DriverComboBox.currentIndex()
|
||||||
if index < 0 or index >= len(self.__driver_infos):
|
if index < 0 or index >= len(self.__driver_ctxs):
|
||||||
return
|
return
|
||||||
driver_info = self.__driver_infos[index]
|
driver_info = self.__driver_ctxs[index]
|
||||||
if driver_info.driver_status == WebDriverStatus.INSTALLED:
|
if driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||||
return
|
return
|
||||||
driver_info.driver_status = WebDriverStatus.DOWNLOADING # we set this only to update
|
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.downloadFinished.connect(self.onDownloadFinished)
|
||||||
self.__download_thread.downloadError.connect(self.onDownloadError)
|
self.__download_thread.downloadError.connect(self.onDownloadError)
|
||||||
self.__download_thread.downloadCancelled.connect(self.onDownloadCancelled)
|
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()
|
self.__download_thread.start()
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
@@ -383,9 +465,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
|
|
||||||
self.DriverComboBox.setEnabled(True)
|
self.DriverComboBox.setEnabled(True)
|
||||||
index = self.DriverComboBox.currentIndex()
|
index = self.DriverComboBox.currentIndex()
|
||||||
if 0 <= index < len(self.__driver_infos):
|
if 0 <= index < len(self.__driver_ctxs):
|
||||||
driver_info = self.__driver_infos[index]
|
driver_info = self.__driver_ctxs[index]
|
||||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
driver_info.driver_status = WebDriverStatus.INSTALLED
|
||||||
|
current_text = self.DriverComboBox.itemText(index)
|
||||||
|
self.DriverComboBox.setItemText(index, current_text + " - 已安装")
|
||||||
self.updateDriverInfoDisplay(driver_info)
|
self.updateDriverInfoDisplay(driver_info)
|
||||||
self.updateProgressBarStates(driver_info)
|
self.updateProgressBarStates(driver_info)
|
||||||
self.updateButtonStates(driver_info)
|
self.updateButtonStates(driver_info)
|
||||||
@@ -398,15 +482,14 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
|
|
||||||
self.DriverComboBox.setEnabled(True)
|
self.DriverComboBox.setEnabled(True)
|
||||||
index = self.DriverComboBox.currentIndex()
|
index = self.DriverComboBox.currentIndex()
|
||||||
if 0 <= index < len(self.__driver_infos):
|
if 0 <= index < len(self.__driver_ctxs):
|
||||||
driver_info = self.__driver_infos[index]
|
driver_info = self.__driver_ctxs[index]
|
||||||
driver_info.driver_status = WebDriverStatus.ERROR
|
driver_info.driver_status = WebDriverStatus.ERROR
|
||||||
self.updateDriverInfoDisplay(driver_info)
|
self.updateDriverInfoDisplay(driver_info)
|
||||||
self.updateProgressBarStates(driver_info)
|
self.updateProgressBarStates(driver_info)
|
||||||
self.updateButtonStates(driver_info)
|
self.updateButtonStates(driver_info)
|
||||||
QMessageBox.critical(self, "下载失败 - AutoLibrary", error_message)
|
QMessageBox.critical(self, "下载失败 - AutoLibrary", error_message)
|
||||||
|
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onDownloadCancelled(
|
def onDownloadCancelled(
|
||||||
self
|
self
|
||||||
@@ -414,8 +497,8 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
|
|
||||||
self.DriverComboBox.setEnabled(True)
|
self.DriverComboBox.setEnabled(True)
|
||||||
index = self.DriverComboBox.currentIndex()
|
index = self.DriverComboBox.currentIndex()
|
||||||
if 0 <= index < len(self.__driver_infos):
|
if 0 <= index < len(self.__driver_ctxs):
|
||||||
driver_info = self.__driver_infos[index]
|
driver_info = self.__driver_ctxs[index]
|
||||||
self.__driver_manager.cancelDriverDownload(driver_info)
|
self.__driver_manager.cancelDriverDownload(driver_info)
|
||||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||||
self.updateDriverInfoDisplay(driver_info)
|
self.updateDriverInfoDisplay(driver_info)
|
||||||
@@ -423,6 +506,14 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.updateButtonStates(driver_info)
|
self.updateButtonStates(driver_info)
|
||||||
self.ProgressText.setText("下载已取消")
|
self.ProgressText.setText("下载已取消")
|
||||||
|
|
||||||
|
@Slot()
|
||||||
|
def onDownloadThreadFinished(
|
||||||
|
self
|
||||||
|
):
|
||||||
|
|
||||||
|
if self.__download_thread:
|
||||||
|
self.__download_thread.deleteLater()
|
||||||
|
self.__download_thread = None
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onConfirmButtonClicked(
|
def onConfirmButtonClicked(
|
||||||
@@ -430,16 +521,15 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
):
|
):
|
||||||
|
|
||||||
index = self.DriverComboBox.currentIndex()
|
index = self.DriverComboBox.currentIndex()
|
||||||
if index < 0 or index >= len(self.__driver_infos):
|
if index < 0 or index >= len(self.__driver_ctxs):
|
||||||
return
|
return
|
||||||
driver_info = self.__driver_infos[index]
|
driver_ctx = self.__driver_ctxs[index]
|
||||||
if driver_info.driver_status != WebDriverStatus.INSTALLED:
|
if driver_ctx.driver_status != WebDriverStatus.INSTALLED:
|
||||||
return
|
return
|
||||||
self.__selected_driver_info = driver_info
|
self.__selected_driver_ctx = driver_ctx
|
||||||
self.__confirmed = True
|
self.__confirmed = True
|
||||||
self.accept()
|
self.accept()
|
||||||
|
|
||||||
|
|
||||||
@Slot()
|
@Slot()
|
||||||
def onCancelButtonClicked(
|
def onCancelButtonClicked(
|
||||||
self
|
self
|
||||||
@@ -456,121 +546,5 @@ class ALWebDriverDownloadDialog(QDialog):
|
|||||||
self.__download_thread.cancel()
|
self.__download_thread.cancel()
|
||||||
else:
|
else:
|
||||||
self.__confirmed = False
|
self.__confirmed = False
|
||||||
self.__selected_driver_info = None
|
self.__selected_driver_ctx = None
|
||||||
self.reject()
|
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:
|
This software is provided "as is", without any warranty of any kind.
|
||||||
- ALMainWindow: Main window class.
|
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||||
- ALAboutDialog: About dialog class.
|
See the LICENSE file for details.
|
||||||
- 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.
|
|
||||||
"""
|
|
||||||
@@ -1,8 +1,11 @@
|
|||||||
<RCC>
|
<RCC>
|
||||||
<qresource prefix="/res/icon">
|
<qresource prefix="/res">
|
||||||
<file>icons/AutoLibrary_32x32.ico</file>
|
<file>icons/AutoLibrary_Logo_64.svg</file>
|
||||||
</qresource>
|
<file>icons/AutoLibrary_Logo_128.svg</file>
|
||||||
<qresource prefix="/res/trans">
|
|
||||||
|
<file>icons/Copy.svg</file>
|
||||||
|
<file>icons/Reset.svg</file>
|
||||||
|
|
||||||
<file>translators/qtbase_zh_CN.qm</file>
|
<file>translators/qtbase_zh_CN.qm</file>
|
||||||
</qresource>
|
</qresource>
|
||||||
</RCC>
|
</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 |
@@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128px" height="128px" viewBox="0 0 128 128" version="1.1">
|
||||||
|
<g id="surface1">
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(15.294118%,36.862746%,56.862748%);fill-opacity:1;" d="M 14.609375 17.722656 C 14.691406 17.722656 14.773438 17.722656 14.855469 17.722656 C 15.125 17.722656 15.394531 17.722656 15.664062 17.726562 C 15.855469 17.726562 16.046875 17.730469 16.238281 17.730469 C 16.824219 17.734375 17.414062 17.742188 18 17.75 C 18.085938 17.75 18.171875 17.753906 18.261719 17.753906 C 29.371094 17.914062 40.535156 19.359375 57.875 27.625 C 57.957031 27.679688 58.039062 27.734375 58.125 27.789062 C 58.90625 28.308594 59.65625 28.855469 60.375 29.460938 C 60.671875 29.65625 60.898438 29.71875 61.25 29.75 C 61.714844 29.507812 62.042969 29.214844 62.402344 28.835938 C 62.839844 28.398438 63.300781 28.023438 63.796875 27.65625 C 63.882812 27.59375 63.96875 27.527344 64.058594 27.460938 C 69.78125 23.273438 76.863281 20.476562 83.71875 18.8125 C 83.808594 18.789062 83.894531 18.769531 83.988281 18.746094 C 85.8125 18.308594 85.8125 18.308594 86.625 18.25 C 86.667969 18.292969 86.707031 18.332031 86.75 18.375 C 86.808594 18.292969 86.867188 18.210938 86.925781 18.128906 C 87.410156 17.75 87.847656 17.804688 88.449219 17.8125 C 88.636719 17.8125 88.636719 17.8125 88.824219 17.8125 C 89.238281 17.808594 89.652344 17.8125 90.0625 17.8125 C 90.359375 17.8125 90.65625 17.8125 90.953125 17.8125 C 91.671875 17.8125 92.394531 17.8125 93.117188 17.816406 C 93.957031 17.816406 94.796875 17.816406 95.636719 17.816406 C 97.132812 17.816406 98.632812 17.820312 100.132812 17.824219 C 101.585938 17.828125 103.039062 17.828125 104.492188 17.828125 C 104.582031 17.828125 104.671875 17.828125 104.765625 17.828125 C 104.855469 17.828125 104.945312 17.828125 105.035156 17.828125 C 106.691406 17.828125 108.347656 17.828125 110 17.832031 C 110.585938 17.832031 111.171875 17.832031 111.757812 17.832031 C 112.546875 17.832031 113.335938 17.835938 114.121094 17.835938 C 114.410156 17.839844 114.703125 17.839844 114.992188 17.839844 C 115.386719 17.839844 115.78125 17.839844 116.175781 17.839844 C 116.347656 17.839844 116.347656 17.839844 116.523438 17.839844 C 116.628906 17.839844 116.734375 17.84375 116.84375 17.84375 C 116.933594 17.84375 117.027344 17.84375 117.121094 17.84375 C 117.550781 17.898438 117.808594 18.046875 118.089844 18.375 C 118.320312 18.917969 118.300781 19.414062 118.296875 20 C 118.296875 20.128906 118.296875 20.253906 118.296875 20.386719 C 118.296875 20.8125 118.296875 21.238281 118.292969 21.664062 C 118.292969 21.96875 118.292969 22.273438 118.296875 22.578125 C 118.296875 23.320312 118.292969 24.0625 118.292969 24.804688 C 118.289062 25.671875 118.289062 26.535156 118.289062 27.402344 C 118.289062 28.941406 118.289062 30.484375 118.285156 32.027344 C 118.28125 33.527344 118.28125 35.023438 118.28125 36.519531 C 118.28125 36.613281 118.28125 36.707031 118.28125 36.800781 C 118.28125 36.988281 118.28125 37.171875 118.28125 37.359375 C 118.28125 37.496094 118.28125 37.496094 118.28125 37.636719 C 118.28125 37.726562 118.28125 37.820312 118.28125 37.914062 C 118.277344 39.339844 118.277344 40.765625 118.277344 42.191406 C 118.277344 42.710938 118.273438 43.226562 118.273438 43.742188 C 118.273438 44.640625 118.273438 45.539062 118.269531 46.433594 C 118.269531 46.734375 118.269531 47.03125 118.269531 47.328125 C 118.269531 47.734375 118.269531 48.140625 118.265625 48.546875 C 118.269531 48.726562 118.269531 48.726562 118.269531 48.910156 C 118.265625 49.015625 118.265625 49.125 118.265625 49.238281 C 118.265625 49.378906 118.265625 49.378906 118.265625 49.519531 C 118.25 49.75 118.25 49.75 118.125 50 C 117.742188 50.132812 117.742188 50.132812 117.25 50.125 C 116.308594 49.523438 115.511719 48.53125 114.726562 47.742188 C 114.492188 47.507812 114.257812 47.273438 114.023438 47.039062 C 112.652344 45.671875 112.652344 45.671875 112.046875 44.945312 C 111.796875 44.664062 111.511719 44.4375 111.222656 44.199219 C 110.816406 43.835938 110.476562 43.414062 110.125 43 C 110.082031 42.957031 110.042969 42.917969 110 42.875 C 110 43.003906 110 43.128906 110 43.261719 C 109.996094 48.882812 109.992188 54.5 109.984375 60.121094 C 109.984375 60.207031 109.984375 60.292969 109.984375 60.378906 C 109.984375 62.226562 109.980469 64.074219 109.976562 65.921875 C 109.976562 66.828125 109.976562 67.734375 109.972656 68.640625 C 109.972656 68.734375 109.972656 68.824219 109.972656 68.914062 C 109.96875 71.839844 109.96875 74.765625 109.964844 77.691406 C 109.964844 80.695312 109.960938 83.699219 109.957031 86.703125 C 109.957031 87.128906 109.953125 87.554688 109.953125 87.976562 C 109.953125 88.101562 109.953125 88.101562 109.953125 88.230469 C 109.953125 89.492188 109.949219 90.753906 109.949219 92.015625 C 109.953125 93.449219 109.949219 94.886719 109.945312 96.320312 C 109.945312 97.054688 109.941406 97.785156 109.945312 98.519531 C 109.945312 99.1875 109.945312 99.859375 109.941406 100.527344 C 109.941406 100.773438 109.941406 101.015625 109.941406 101.257812 C 109.941406 101.585938 109.9414Line truncated
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(99.215686%,93.333334%,87.450981%);fill-opacity:1;" d="M 88.449219 17.8125 C 88.636719 17.8125 88.636719 17.8125 88.824219 17.8125 C 89.238281 17.808594 89.652344 17.8125 90.0625 17.8125 C 90.359375 17.8125 90.65625 17.8125 90.953125 17.8125 C 91.671875 17.8125 92.394531 17.8125 93.117188 17.816406 C 93.957031 17.816406 94.796875 17.816406 95.636719 17.816406 C 97.132812 17.816406 98.632812 17.820312 100.132812 17.824219 C 101.585938 17.828125 103.039062 17.828125 104.492188 17.828125 C 104.582031 17.828125 104.671875 17.828125 104.765625 17.828125 C 104.855469 17.828125 104.945312 17.828125 105.035156 17.828125 C 106.691406 17.828125 108.347656 17.828125 110 17.832031 C 110.585938 17.832031 111.171875 17.832031 111.757812 17.832031 C 112.546875 17.832031 113.335938 17.835938 114.121094 17.835938 C 114.410156 17.839844 114.703125 17.839844 114.992188 17.839844 C 115.386719 17.839844 115.78125 17.839844 116.175781 17.839844 C 116.347656 17.839844 116.347656 17.839844 116.523438 17.839844 C 116.628906 17.839844 116.734375 17.84375 116.84375 17.84375 C 116.980469 17.84375 116.980469 17.84375 117.121094 17.84375 C 117.550781 17.898438 117.808594 18.046875 118.089844 18.375 C 118.320312 18.917969 118.300781 19.414062 118.296875 20 C 118.296875 20.191406 118.296875 20.191406 118.296875 20.386719 C 118.296875 20.8125 118.296875 21.238281 118.292969 21.664062 C 118.292969 21.96875 118.292969 22.273438 118.296875 22.578125 C 118.296875 23.320312 118.292969 24.0625 118.292969 24.804688 C 118.289062 25.671875 118.289062 26.535156 118.289062 27.402344 C 118.289062 28.941406 118.289062 30.484375 118.285156 32.027344 C 118.28125 33.527344 118.28125 35.023438 118.28125 36.519531 C 118.28125 36.613281 118.28125 36.707031 118.28125 36.800781 C 118.28125 36.988281 118.28125 37.171875 118.28125 37.359375 C 118.28125 37.449219 118.28125 37.542969 118.28125 37.636719 C 118.28125 37.773438 118.28125 37.773438 118.28125 37.914062 C 118.277344 39.339844 118.277344 40.765625 118.277344 42.191406 C 118.277344 42.710938 118.273438 43.226562 118.273438 43.742188 C 118.273438 44.640625 118.273438 45.539062 118.269531 46.433594 C 118.269531 46.734375 118.269531 47.03125 118.269531 47.328125 C 118.269531 47.734375 118.269531 48.140625 118.265625 48.546875 C 118.269531 48.726562 118.269531 48.726562 118.269531 48.910156 C 118.265625 49.015625 118.265625 49.125 118.265625 49.238281 C 118.265625 49.378906 118.265625 49.378906 118.265625 49.519531 C 118.25 49.75 118.25 49.75 118.125 50 C 117.742188 50.132812 117.742188 50.132812 117.25 50.125 C 116.308594 49.523438 115.511719 48.53125 114.726562 47.742188 C 114.492188 47.507812 114.257812 47.273438 114.023438 47.039062 C 112.652344 45.671875 112.652344 45.671875 112.046875 44.945312 C 111.796875 44.660156 111.507812 44.433594 111.214844 44.191406 C 110.992188 43.992188 110.808594 43.785156 110.613281 43.558594 C 110.054688 42.910156 109.457031 42.308594 108.851562 41.703125 C 108.742188 41.589844 108.628906 41.476562 108.515625 41.363281 C 108.40625 41.253906 108.300781 41.148438 108.191406 41.035156 C 108.09375 40.9375 107.996094 40.84375 107.898438 40.742188 C 107.566406 40.449219 107.304688 40.257812 106.855469 40.234375 C 105.742188 40.355469 105.175781 40.929688 104.414062 41.710938 C 104.070312 42.054688 103.710938 42.371094 103.339844 42.6875 C 103.160156 42.84375 102.992188 43.011719 102.828125 43.179688 C 102.625 43.375 102.625 43.375 102.375 43.375 C 102.332031 43.5 102.292969 43.621094 102.25 43.75 C 102.054688 43.925781 101.847656 44.089844 101.640625 44.25 C 100.984375 44.773438 100.40625 45.328125 99.820312 45.929688 C 99.464844 46.285156 99.09375 46.613281 98.714844 46.941406 C 98.347656 47.257812 98.011719 47.605469 97.679688 47.957031 C 97.5 48.140625 97.3125 48.320312 97.125 48.5 C 97.042969 48.5 96.960938 48.5 96.875 48.5 C 96.875 48.582031 96.875 48.664062 96.875 48.75 C 96.792969 48.75 96.710938 48.75 96.625 48.75 C 96.601562 48.816406 96.574219 48.886719 96.546875 48.953125 C 96.304688 49.371094 95.960938 49.65625 95.605469 49.972656 C 94.746094 50.757812 93.914062 51.570312 93.089844 52.394531 C 93.027344 52.457031 92.964844 52.515625 92.902344 52.582031 C 92.585938 52.898438 92.265625 53.214844 91.949219 53.535156 C 91.625 53.859375 91.300781 54.183594 90.972656 54.507812 C 90.71875 54.765625 90.464844 55.019531 90.210938 55.273438 C 90.03125 55.449219 89.855469 55.628906 89.675781 55.804688 C 89.117188 56.367188 88.570312 56.9375 88.054688 57.542969 C 87.710938 57.941406 87.328125 58.296875 86.953125 58.664062 C 86.613281 59.011719 86.296875 59.375 85.980469 59.738281 C 85.613281 60.15625 85.230469 60.554688 84.851562 60.953125 C 84.058594 61.792969 83.300781 62.652344 82.558594 63.535156 C 82.304688 63.832031 82.050781 64.128906 81.792969 64.425781 C 80.683594 65.714844 79.617188 67.035156 78.570312 68.375 C 78.359375 68.644531 78.144531 68.917969 77.933594 69.1875 C 77.78125 69.382812 77.628906 69.578125 77.47656Line truncated
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(23.529412%,40.392157%,55.29412%);fill-opacity:1;" d="M 109.5 42.5 C 109.6875 42.625 109.6875 42.625 109.875 42.75 C 109.914062 43.085938 109.925781 43.390625 109.921875 43.726562 C 109.921875 43.828125 109.921875 43.929688 109.921875 44.035156 C 109.921875 44.382812 109.921875 44.730469 109.921875 45.078125 C 109.921875 45.328125 109.921875 45.578125 109.921875 45.828125 C 109.921875 46.515625 109.921875 47.203125 109.917969 47.894531 C 109.917969 48.636719 109.917969 49.378906 109.917969 50.121094 C 109.917969 51.40625 109.917969 52.695312 109.914062 53.980469 C 109.914062 55.332031 109.910156 56.679688 109.910156 58.03125 C 109.910156 58.113281 109.910156 58.199219 109.910156 58.285156 C 109.910156 58.710938 109.910156 59.136719 109.910156 59.5625 C 109.910156 62.582031 109.90625 65.597656 109.902344 68.617188 C 109.898438 71.550781 109.898438 74.484375 109.894531 77.414062 C 109.894531 77.503906 109.894531 77.597656 109.894531 77.6875 C 109.894531 78.597656 109.894531 79.503906 109.894531 80.410156 C 109.894531 82.261719 109.890625 84.109375 109.890625 85.957031 C 109.890625 86.042969 109.890625 86.125 109.890625 86.214844 C 109.886719 91.894531 109.882812 97.570312 109.875 103.25 C 109.792969 103.25 109.710938 103.25 109.625 103.25 C 109.582031 83.203125 109.542969 63.15625 109.5 42.5 Z M 109.5 42.5 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(96.078432%,94.117647%,90.588236%);fill-opacity:1;" d="M 80.5 42.875 C 80.5 43.671875 79.515625 44.359375 78.96875 44.90625 C 78.757812 45.117188 78.546875 45.328125 78.332031 45.539062 C 77.90625 45.964844 77.496094 46.398438 77.105469 46.859375 C 76.789062 47.226562 76.460938 47.582031 76.132812 47.9375 C 76.039062 48.039062 76.039062 48.039062 75.945312 48.144531 C 75.796875 48.304688 75.648438 48.464844 75.5 48.625 C 75.417969 48.582031 75.335938 48.542969 75.25 48.5 C 75.359375 48.382812 75.472656 48.265625 75.585938 48.140625 C 75.734375 47.980469 75.886719 47.820312 76.039062 47.65625 C 76.117188 47.570312 76.199219 47.488281 76.28125 47.398438 C 76.769531 46.875 77.257812 46.34375 77.742188 45.8125 C 78.167969 45.347656 78.597656 44.898438 79.046875 44.457031 C 79.355469 44.140625 79.640625 43.808594 79.929688 43.476562 C 80.109375 43.265625 80.300781 43.070312 80.5 42.875 Z M 80.5 42.875 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(95.294118%,93.725491%,90.980393%);fill-opacity:1;" d="M 86.625 36.875 C 86.625 37.359375 86.433594 37.488281 86.105469 37.816406 C 86.027344 37.890625 85.953125 37.964844 85.875 38.039062 C 85.800781 38.117188 85.722656 38.191406 85.644531 38.269531 C 85.484375 38.429688 85.320312 38.59375 85.15625 38.753906 C 84.90625 39 84.660156 39.246094 84.414062 39.492188 C 84.253906 39.648438 84.097656 39.804688 83.9375 39.960938 C 83.867188 40.035156 83.792969 40.109375 83.714844 40.183594 C 83.367188 40.523438 83.027344 40.847656 82.625 41.125 C 82.542969 41.082031 82.460938 41.042969 82.375 41 C 83.949219 39.402344 83.949219 39.402344 84.726562 38.746094 C 85.386719 38.152344 86 37.507812 86.625 36.875 Z M 86.625 36.875 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(15.294118%,34.509805%,52.156866%);fill-opacity:1;" d="M 91.625 53.875 C 91.707031 53.917969 91.789062 53.957031 91.875 54 C 91.804688 54.070312 91.734375 54.140625 91.660156 54.210938 C 91.117188 54.75 90.59375 55.292969 90.097656 55.875 C 89.710938 56.3125 89.292969 56.71875 88.875 57.125 C 88.832031 57 88.792969 56.878906 88.75 56.75 C 89.699219 55.800781 90.648438 54.851562 91.625 53.875 Z M 91.625 53.875 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(95.686275%,93.725491%,90.588236%);fill-opacity:1;" d="M 89.125 34.5 C 89.207031 34.542969 89.289062 34.582031 89.375 34.625 C 89.054688 34.953125 88.734375 35.28125 88.414062 35.609375 C 88.277344 35.75 88.277344 35.75 88.140625 35.890625 C 88.050781 35.980469 87.964844 36.070312 87.875 36.164062 C 87.792969 36.246094 87.710938 36.328125 87.628906 36.414062 C 87.351562 36.644531 87.09375 36.757812 86.75 36.875 C 86.84375 36.785156 86.9375 36.695312 87.03125 36.601562 C 87.367188 36.269531 87.367188 36.269531 87.601562 35.953125 C 87.917969 35.570312 88.273438 35.265625 88.648438 34.945312 C 88.882812 34.746094 88.882812 34.746094 89.125 34.5 Z M 89.125 34.5 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(94.509804%,92.941177%,91.37255%);fill-opacity:1;" d="M 82.25 41.125 C 82.292969 41.207031 82.332031 41.289062 82.375 41.375 C 81.910156 41.925781 81.464844 42.449219 80.875 42.875 C 80.792969 42.832031 80.710938 42.792969 80.625 42.75 C 80.796875 42.5625 80.796875 42.5625 81 42.375 C 81.082031 42.375 81.164062 42.375 81.25 42.375 C 81.277344 42.308594 81.300781 42.242188 81.328125 42.171875 C 81.574219 41.75 81.898438 41.460938 82.25 41.125 Z M 82.25 41.125 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(95.686275%,93.725491%,90.196079%);fill-opacity:1;" d="M 74.625 49.25 C 74.667969 49.332031 74.707031 49.414062 74.75 49.5 C 74.613281 49.667969 74.476562 49.835938 74.335938 50 C 74.21875 50.140625 74.21875 50.140625 74.101562 50.28125 C 73.875 50.5 73.875 50.5 73.5 50.5 C 73.871094 50.085938 74.242188 49.675781 74.625 49.25 Z M 74.625 49.25 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(23.921569%,40.000001%,55.686277%);fill-opacity:1;" d="M 99.375 46.25 C 99.5 46.292969 99.621094 46.332031 99.75 46.375 C 99.378906 46.703125 99.007812 47.035156 98.625 47.375 C 98.542969 47.332031 98.460938 47.292969 98.375 47.25 C 98.703125 46.921875 99.035156 46.589844 99.375 46.25 Z M 99.375 46.25 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(94.509804%,94.509804%,92.156863%);fill-opacity:1;" d="M 60.625 70.5 C 60.667969 70.5 60.707031 70.5 60.75 70.5 C 60.828125 71.140625 60.550781 71.585938 60.25 72.125 C 60.167969 72.125 60.085938 72.125 60 72.125 C 60.058594 71.949219 60.113281 71.769531 60.171875 71.59375 C 60.21875 71.445312 60.21875 71.445312 60.269531 71.296875 C 60.367188 71.015625 60.488281 70.761719 60.625 70.5 Z M 60.625 70.5 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(20.784314%,38.431373%,55.29412%);fill-opacity:1;" d="M 101.625 44.25 C 101.707031 44.292969 101.789062 44.332031 101.875 44.375 C 101.441406 44.746094 101.441406 44.746094 101 45.125 C 100.917969 45.082031 100.835938 45.042969 100.75 45 C 101.039062 44.753906 101.328125 44.503906 101.625 44.25 Z M 101.625 44.25 "/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 178 KiB |
@@ -0,0 +1,17 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64px" height="64px" viewBox="0 0 64 64" version="1.1">
|
||||||
|
<g id="surface1">
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(15.294118%,36.862746%,56.862748%);fill-opacity:1;" d="M 7.304688 8.859375 C 7.34375 8.859375 7.386719 8.859375 7.429688 8.859375 C 7.5625 8.859375 7.699219 8.863281 7.832031 8.863281 C 7.929688 8.863281 8.023438 8.863281 8.121094 8.863281 C 8.414062 8.867188 8.707031 8.871094 9 8.875 C 9.042969 8.875 9.085938 8.875 9.128906 8.875 C 14.683594 8.957031 20.269531 9.679688 28.9375 13.8125 C 28.980469 13.839844 29.019531 13.867188 29.0625 13.894531 C 29.453125 14.15625 29.828125 14.429688 30.1875 14.730469 C 30.335938 14.828125 30.449219 14.859375 30.625 14.875 C 30.859375 14.753906 31.019531 14.609375 31.203125 14.417969 C 31.417969 14.199219 31.648438 14.011719 31.898438 13.828125 C 31.941406 13.796875 31.984375 13.765625 32.03125 13.730469 C 34.890625 11.636719 38.429688 10.238281 41.859375 9.40625 C 41.902344 9.394531 41.949219 9.382812 41.992188 9.375 C 42.90625 9.152344 42.90625 9.152344 43.3125 9.125 C 43.332031 9.144531 43.355469 9.167969 43.375 9.1875 C 43.402344 9.148438 43.433594 9.105469 43.460938 9.0625 C 43.707031 8.875 43.925781 8.902344 44.226562 8.90625 C 44.316406 8.90625 44.316406 8.90625 44.410156 8.90625 C 44.617188 8.90625 44.824219 8.90625 45.03125 8.90625 C 45.179688 8.90625 45.328125 8.90625 45.476562 8.90625 C 45.835938 8.90625 46.199219 8.90625 46.558594 8.90625 C 46.976562 8.910156 47.398438 8.910156 47.816406 8.910156 C 48.566406 8.910156 49.316406 8.910156 50.066406 8.910156 C 50.792969 8.914062 51.519531 8.914062 52.246094 8.914062 C 52.292969 8.914062 52.335938 8.914062 52.382812 8.914062 C 52.425781 8.914062 52.472656 8.914062 52.519531 8.914062 C 53.347656 8.914062 54.171875 8.914062 55 8.917969 C 55.292969 8.917969 55.585938 8.917969 55.878906 8.917969 C 56.273438 8.917969 56.667969 8.917969 57.0625 8.917969 C 57.207031 8.917969 57.351562 8.917969 57.496094 8.917969 C 57.691406 8.917969 57.890625 8.917969 58.085938 8.921875 C 58.175781 8.921875 58.175781 8.921875 58.261719 8.921875 C 58.316406 8.921875 58.367188 8.921875 58.421875 8.921875 C 58.46875 8.921875 58.511719 8.921875 58.558594 8.921875 C 58.777344 8.949219 58.90625 9.023438 59.046875 9.1875 C 59.160156 9.460938 59.152344 9.707031 59.148438 10 C 59.148438 10.0625 59.148438 10.128906 59.148438 10.191406 C 59.148438 10.40625 59.148438 10.617188 59.148438 10.832031 C 59.148438 10.984375 59.148438 11.136719 59.148438 11.289062 C 59.148438 11.660156 59.148438 12.03125 59.144531 12.402344 C 59.144531 12.835938 59.144531 13.269531 59.144531 13.699219 C 59.144531 14.472656 59.144531 15.242188 59.140625 16.015625 C 59.140625 16.761719 59.140625 17.511719 59.140625 18.261719 C 59.140625 18.304688 59.140625 18.351562 59.140625 18.398438 C 59.140625 18.492188 59.140625 18.585938 59.140625 18.679688 C 59.140625 18.746094 59.140625 18.746094 59.140625 18.816406 C 59.140625 18.863281 59.140625 18.910156 59.140625 18.957031 C 59.140625 19.667969 59.140625 20.382812 59.136719 21.097656 C 59.136719 21.355469 59.136719 21.613281 59.136719 21.871094 C 59.136719 22.320312 59.136719 22.769531 59.136719 23.21875 C 59.136719 23.367188 59.136719 23.515625 59.136719 23.664062 C 59.136719 23.867188 59.132812 24.070312 59.132812 24.273438 C 59.132812 24.363281 59.132812 24.363281 59.132812 24.453125 C 59.132812 24.507812 59.132812 24.5625 59.132812 24.617188 C 59.132812 24.6875 59.132812 24.6875 59.132812 24.761719 C 59.125 24.875 59.125 24.875 59.0625 25 C 58.871094 25.066406 58.871094 25.066406 58.625 25.0625 C 58.15625 24.761719 57.757812 24.265625 57.363281 23.871094 C 57.246094 23.753906 57.128906 23.636719 57.011719 23.519531 C 56.328125 22.835938 56.328125 22.835938 56.023438 22.472656 C 55.898438 22.332031 55.753906 22.21875 55.609375 22.097656 C 55.40625 21.917969 55.238281 21.707031 55.0625 21.5 C 55.042969 21.480469 55.019531 21.457031 55 21.4375 C 55 21.5 55 21.566406 55 21.628906 C 55 24.441406 54.996094 27.25 54.992188 30.0625 C 54.992188 30.101562 54.992188 30.144531 54.992188 30.191406 C 54.992188 31.113281 54.988281 32.039062 54.988281 32.960938 C 54.988281 33.414062 54.988281 33.867188 54.988281 34.320312 C 54.988281 34.367188 54.988281 34.410156 54.988281 34.457031 C 54.984375 35.921875 54.984375 37.382812 54.984375 38.84375 C 54.980469 40.347656 54.980469 41.851562 54.976562 43.351562 C 54.976562 43.5625 54.976562 43.777344 54.976562 43.988281 C 54.976562 44.050781 54.976562 44.050781 54.976562 44.113281 C 54.976562 44.746094 54.976562 45.378906 54.976562 46.007812 C 54.976562 46.726562 54.976562 47.441406 54.972656 48.160156 C 54.972656 48.527344 54.972656 48.894531 54.972656 49.257812 C 54.972656 49.59375 54.972656 49.929688 54.96875 50.265625 C 54.96875 50.386719 54.96875 50.507812 54.972656 50.628906 C 54.972656 50.792969 54.96875 50.957031 54.96875 51.121094 C 54.96875 51.171875 54.96875 51.21875 54.972656 51.265625 C 54.96875 51.484375 54.953125 51.601562 54.820312 51.777344 C 54.652344 51.902344 54.53125 51.917969 54.324219 51.941406 C 54.25 51.949219 54.175781 51.9Line truncated
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(99.215686%,93.333334%,87.450981%);fill-opacity:1;" d="M 44.226562 8.90625 C 44.316406 8.90625 44.316406 8.90625 44.410156 8.90625 C 44.617188 8.90625 44.824219 8.90625 45.03125 8.90625 C 45.179688 8.90625 45.328125 8.90625 45.476562 8.90625 C 45.835938 8.90625 46.199219 8.90625 46.558594 8.90625 C 46.976562 8.910156 47.398438 8.910156 47.816406 8.910156 C 48.566406 8.910156 49.316406 8.910156 50.066406 8.910156 C 50.792969 8.914062 51.519531 8.914062 52.246094 8.914062 C 52.292969 8.914062 52.335938 8.914062 52.382812 8.914062 C 52.425781 8.914062 52.472656 8.914062 52.519531 8.914062 C 53.347656 8.914062 54.171875 8.914062 55 8.917969 C 55.292969 8.917969 55.585938 8.917969 55.878906 8.917969 C 56.273438 8.917969 56.667969 8.917969 57.0625 8.917969 C 57.207031 8.917969 57.351562 8.917969 57.496094 8.917969 C 57.691406 8.917969 57.890625 8.917969 58.085938 8.921875 C 58.175781 8.921875 58.175781 8.921875 58.261719 8.921875 C 58.316406 8.921875 58.367188 8.921875 58.421875 8.921875 C 58.492188 8.921875 58.492188 8.921875 58.558594 8.921875 C 58.777344 8.949219 58.90625 9.023438 59.046875 9.1875 C 59.160156 9.460938 59.152344 9.707031 59.148438 10 C 59.148438 10.09375 59.148438 10.09375 59.148438 10.191406 C 59.148438 10.40625 59.148438 10.617188 59.148438 10.832031 C 59.148438 10.984375 59.148438 11.136719 59.148438 11.289062 C 59.148438 11.660156 59.148438 12.03125 59.144531 12.402344 C 59.144531 12.835938 59.144531 13.269531 59.144531 13.699219 C 59.144531 14.472656 59.144531 15.242188 59.144531 16.015625 C 59.140625 16.761719 59.140625 17.511719 59.140625 18.261719 C 59.140625 18.304688 59.140625 18.351562 59.140625 18.398438 C 59.140625 18.492188 59.140625 18.585938 59.140625 18.679688 C 59.140625 18.726562 59.140625 18.769531 59.140625 18.816406 C 59.140625 18.886719 59.140625 18.886719 59.140625 18.957031 C 59.140625 19.667969 59.140625 20.382812 59.136719 21.097656 C 59.136719 21.355469 59.136719 21.613281 59.136719 21.871094 C 59.136719 22.320312 59.136719 22.769531 59.136719 23.21875 C 59.136719 23.367188 59.136719 23.515625 59.136719 23.664062 C 59.136719 23.867188 59.132812 24.070312 59.132812 24.273438 C 59.132812 24.363281 59.132812 24.363281 59.132812 24.453125 C 59.132812 24.507812 59.132812 24.5625 59.132812 24.617188 C 59.132812 24.6875 59.132812 24.6875 59.132812 24.761719 C 59.125 24.875 59.125 24.875 59.0625 25 C 58.871094 25.066406 58.871094 25.066406 58.625 25.0625 C 58.15625 24.761719 57.757812 24.265625 57.363281 23.871094 C 57.246094 23.753906 57.128906 23.636719 57.011719 23.519531 C 56.328125 22.835938 56.328125 22.835938 56.023438 22.472656 C 55.898438 22.332031 55.753906 22.214844 55.609375 22.097656 C 55.496094 21.996094 55.402344 21.894531 55.308594 21.777344 C 55.027344 21.457031 54.726562 21.152344 54.425781 20.851562 C 54.371094 20.796875 54.316406 20.738281 54.257812 20.679688 C 54.203125 20.628906 54.148438 20.574219 54.09375 20.519531 C 54.046875 20.46875 54 20.421875 53.949219 20.371094 C 53.78125 20.222656 53.652344 20.128906 53.429688 20.117188 C 52.871094 20.179688 52.585938 20.464844 52.207031 20.855469 C 52.035156 21.027344 51.855469 21.183594 51.671875 21.34375 C 51.582031 21.421875 51.496094 21.503906 51.414062 21.589844 C 51.3125 21.6875 51.3125 21.6875 51.1875 21.6875 C 51.167969 21.75 51.144531 21.8125 51.125 21.875 C 51.027344 21.960938 50.925781 22.042969 50.820312 22.125 C 50.492188 22.386719 50.203125 22.664062 49.910156 22.964844 C 49.734375 23.140625 49.546875 23.304688 49.355469 23.46875 C 49.171875 23.628906 49.007812 23.800781 48.839844 23.976562 C 48.75 24.070312 48.65625 24.160156 48.5625 24.25 C 48.519531 24.25 48.480469 24.25 48.4375 24.25 C 48.4375 24.292969 48.4375 24.332031 48.4375 24.375 C 48.394531 24.375 48.355469 24.375 48.3125 24.375 C 48.300781 24.410156 48.289062 24.441406 48.273438 24.476562 C 48.152344 24.683594 47.980469 24.828125 47.804688 24.988281 C 47.375 25.378906 46.957031 25.785156 46.546875 26.195312 C 46.515625 26.226562 46.484375 26.257812 46.453125 26.289062 C 46.292969 26.449219 46.132812 26.609375 45.976562 26.765625 C 45.8125 26.929688 45.648438 27.09375 45.488281 27.253906 C 45.359375 27.382812 45.230469 27.507812 45.105469 27.636719 C 45.015625 27.726562 44.925781 27.8125 44.839844 27.902344 C 44.558594 28.183594 44.285156 28.46875 44.027344 28.773438 C 43.855469 28.96875 43.664062 29.148438 43.476562 29.332031 C 43.308594 29.503906 43.148438 29.6875 42.988281 29.871094 C 42.808594 30.078125 42.617188 30.277344 42.425781 30.476562 C 42.03125 30.894531 41.652344 31.324219 41.277344 31.765625 C 41.152344 31.917969 41.023438 32.0625 40.898438 32.210938 C 40.34375 32.855469 39.808594 33.515625 39.285156 34.1875 C 39.179688 34.324219 39.074219 34.457031 38.96875 34.59375 C 38.890625 34.691406 38.8125 34.789062 38.738281 34.886719 C 38.703125 34.929688 38.667969 34.976562 38.632812 35.023438 C 38.167969 35.617188 37.734375 36.230469 37.320312 36.859375 C 37.234375 36.99218Line truncated
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(23.529412%,40.392157%,55.29412%);fill-opacity:1;" d="M 54.75 21.25 C 54.84375 21.3125 54.84375 21.3125 54.9375 21.375 C 54.957031 21.542969 54.960938 21.695312 54.960938 21.863281 C 54.960938 21.914062 54.960938 21.964844 54.960938 22.019531 C 54.960938 22.191406 54.960938 22.363281 54.960938 22.539062 C 54.960938 22.664062 54.960938 22.789062 54.960938 22.914062 C 54.960938 23.257812 54.960938 23.601562 54.960938 23.945312 C 54.957031 24.316406 54.957031 24.6875 54.957031 25.058594 C 54.957031 25.703125 54.957031 26.347656 54.957031 26.992188 C 54.957031 27.664062 54.957031 28.339844 54.957031 29.015625 C 54.957031 29.058594 54.957031 29.097656 54.957031 29.140625 C 54.957031 29.355469 54.957031 29.566406 54.953125 29.78125 C 54.953125 31.289062 54.953125 32.800781 54.953125 34.308594 C 54.949219 35.773438 54.949219 37.242188 54.949219 38.707031 C 54.949219 38.753906 54.949219 38.796875 54.949219 38.84375 C 54.949219 39.296875 54.945312 39.753906 54.945312 40.207031 C 54.945312 41.128906 54.945312 42.054688 54.945312 42.976562 C 54.945312 43.019531 54.945312 43.0625 54.945312 43.105469 C 54.945312 45.945312 54.941406 48.785156 54.9375 51.625 C 54.894531 51.625 54.855469 51.625 54.8125 51.625 C 54.792969 41.601562 54.769531 31.578125 54.75 21.25 Z M 54.75 21.25 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(96.078432%,94.117647%,90.588236%);fill-opacity:1;" d="M 40.25 21.4375 C 40.25 21.835938 39.757812 22.179688 39.484375 22.453125 C 39.378906 22.558594 39.273438 22.664062 39.167969 22.769531 C 38.953125 22.984375 38.746094 23.199219 38.550781 23.429688 C 38.394531 23.613281 38.230469 23.789062 38.066406 23.96875 C 38.019531 24.019531 38.019531 24.019531 37.972656 24.070312 C 37.898438 24.152344 37.824219 24.230469 37.75 24.3125 C 37.707031 24.292969 37.667969 24.269531 37.625 24.25 C 37.679688 24.191406 37.734375 24.132812 37.792969 24.070312 C 37.867188 23.992188 37.945312 23.910156 38.019531 23.828125 C 38.058594 23.785156 38.097656 23.742188 38.140625 23.699219 C 38.386719 23.4375 38.628906 23.171875 38.871094 22.90625 C 39.082031 22.675781 39.300781 22.449219 39.523438 22.226562 C 39.675781 22.070312 39.820312 21.90625 39.964844 21.738281 C 40.054688 21.632812 40.152344 21.535156 40.25 21.4375 Z M 40.25 21.4375 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(95.294118%,93.725491%,90.980393%);fill-opacity:1;" d="M 43.3125 18.4375 C 43.3125 18.679688 43.214844 18.742188 43.050781 18.910156 C 43.015625 18.945312 42.976562 18.980469 42.9375 19.019531 C 42.898438 19.058594 42.863281 19.097656 42.824219 19.136719 C 42.742188 19.214844 42.660156 19.296875 42.578125 19.375 C 42.453125 19.5 42.332031 19.621094 42.207031 19.746094 C 42.128906 19.824219 42.046875 19.902344 41.96875 19.980469 C 41.933594 20.015625 41.894531 20.054688 41.859375 20.089844 C 41.683594 20.261719 41.511719 20.421875 41.3125 20.5625 C 41.269531 20.542969 41.230469 20.519531 41.1875 20.5 C 41.976562 19.703125 41.976562 19.703125 42.363281 19.371094 C 42.695312 19.074219 43 18.753906 43.3125 18.4375 Z M 43.3125 18.4375 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(15.294118%,34.509805%,52.156866%);fill-opacity:1;" d="M 45.8125 26.9375 C 45.855469 26.957031 45.894531 26.980469 45.9375 27 C 45.902344 27.035156 45.867188 27.070312 45.828125 27.105469 C 45.558594 27.375 45.296875 27.648438 45.046875 27.9375 C 44.855469 28.15625 44.644531 28.359375 44.4375 28.5625 C 44.417969 28.5 44.394531 28.4375 44.375 28.375 C 44.847656 27.902344 45.324219 27.425781 45.8125 26.9375 Z M 45.8125 26.9375 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(95.686275%,93.725491%,90.588236%);fill-opacity:1;" d="M 44.5625 17.25 C 44.605469 17.269531 44.644531 17.292969 44.6875 17.3125 C 44.527344 17.476562 44.367188 17.640625 44.207031 17.804688 C 44.140625 17.875 44.140625 17.875 44.070312 17.945312 C 44.027344 17.992188 43.980469 18.035156 43.9375 18.082031 C 43.898438 18.121094 43.855469 18.164062 43.816406 18.207031 C 43.675781 18.324219 43.546875 18.378906 43.375 18.4375 C 43.421875 18.390625 43.46875 18.347656 43.515625 18.300781 C 43.683594 18.136719 43.683594 18.136719 43.800781 17.976562 C 43.960938 17.785156 44.136719 17.632812 44.324219 17.472656 C 44.441406 17.375 44.441406 17.375 44.5625 17.25 Z M 44.5625 17.25 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(94.509804%,92.941177%,91.37255%);fill-opacity:1;" d="M 41.125 20.5625 C 41.144531 20.605469 41.167969 20.644531 41.1875 20.6875 C 40.953125 20.964844 40.730469 21.222656 40.4375 21.4375 C 40.394531 21.417969 40.355469 21.394531 40.3125 21.375 C 40.398438 21.28125 40.398438 21.28125 40.5 21.1875 C 40.542969 21.1875 40.582031 21.1875 40.625 21.1875 C 40.636719 21.152344 40.652344 21.121094 40.664062 21.085938 C 40.785156 20.875 40.949219 20.730469 41.125 20.5625 Z M 41.125 20.5625 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(95.686275%,93.725491%,90.196079%);fill-opacity:1;" d="M 37.3125 24.625 C 37.332031 24.667969 37.355469 24.707031 37.375 24.75 C 37.308594 24.832031 37.238281 24.917969 37.167969 25 C 37.109375 25.070312 37.109375 25.070312 37.050781 25.140625 C 36.9375 25.25 36.9375 25.25 36.75 25.25 C 36.9375 25.042969 37.121094 24.835938 37.3125 24.625 Z M 37.3125 24.625 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(23.921569%,40.000001%,55.686277%);fill-opacity:1;" d="M 49.6875 23.125 C 49.75 23.144531 49.8125 23.167969 49.875 23.1875 C 49.6875 23.351562 49.503906 23.515625 49.3125 23.6875 C 49.269531 23.667969 49.230469 23.644531 49.1875 23.625 C 49.351562 23.460938 49.515625 23.296875 49.6875 23.125 Z M 49.6875 23.125 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(94.509804%,94.509804%,92.156863%);fill-opacity:1;" d="M 30.3125 35.25 C 30.332031 35.25 30.355469 35.25 30.375 35.25 C 30.414062 35.570312 30.273438 35.792969 30.125 36.0625 C 30.082031 36.0625 30.042969 36.0625 30 36.0625 C 30.027344 35.972656 30.058594 35.886719 30.085938 35.796875 C 30.109375 35.722656 30.109375 35.722656 30.132812 35.648438 C 30.183594 35.507812 30.242188 35.378906 30.3125 35.25 Z M 30.3125 35.25 "/>
|
||||||
|
<path style=" stroke:none;fill-rule:nonzero;fill:rgb(20.784314%,38.431373%,55.29412%);fill-opacity:1;" d="M 50.8125 22.125 C 50.855469 22.144531 50.894531 22.167969 50.9375 22.1875 C 50.722656 22.375 50.722656 22.375 50.5 22.5625 C 50.457031 22.542969 50.417969 22.519531 50.375 22.5 C 50.519531 22.375 50.664062 22.253906 50.8125 22.125 Z M 50.8125 22.125 "/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
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">
|
<property name="maximumSize">
|
||||||
<size>
|
<size>
|
||||||
<width>800</width>
|
<width>800</width>
|
||||||
<height>400</height>
|
<height>600</height>
|
||||||
</size>
|
</size>
|
||||||
</property>
|
</property>
|
||||||
<property name="windowTitle">
|
<property name="windowTitle">
|
||||||
@@ -103,53 +103,6 @@
|
|||||||
<property name="spacing">
|
<property name="spacing">
|
||||||
<number>0</number>
|
<number>0</number>
|
||||||
</property>
|
</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>
|
</layout>
|
||||||
</item>
|
</item>
|
||||||
<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">
|
<widget class="QPushButton" name="ExportConfigButton">
|
||||||
<property name="minimumSize">
|
<property name="minimumSize">
|
||||||
<size>
|
<size>
|
||||||
<width>100</width>
|
<width>120</width>
|
||||||
<height>25</height>
|
<height>25</height>
|
||||||
</size>
|
</size>
|
||||||
</property>
|
</property>
|
||||||
<property name="maximumSize">
|
<property name="maximumSize">
|
||||||
<size>
|
<size>
|
||||||
<width>100</width>
|
<width>120</width>
|
||||||
<height>25</height>
|
<height>25</height>
|
||||||
</size>
|
</size>
|
||||||
</property>
|
</property>
|
||||||
|
|||||||
@@ -281,6 +281,13 @@ font: 700 9pt;</string>
|
|||||||
<property name="nativeMenuBar">
|
<property name="nativeMenuBar">
|
||||||
<bool>true</bool>
|
<bool>true</bool>
|
||||||
</property>
|
</property>
|
||||||
|
<widget class="QMenu" name="ToolsMenu">
|
||||||
|
<property name="title">
|
||||||
|
<string>工具</string>
|
||||||
|
</property>
|
||||||
|
<addaction name="SettingsAction"/>
|
||||||
|
<addaction name="BulletinAction"/>
|
||||||
|
</widget>
|
||||||
<widget class="QMenu" name="HelpMenu">
|
<widget class="QMenu" name="HelpMenu">
|
||||||
<property name="mouseTracking">
|
<property name="mouseTracking">
|
||||||
<bool>true</bool>
|
<bool>true</bool>
|
||||||
@@ -289,8 +296,10 @@ font: 700 9pt;</string>
|
|||||||
<string>帮助</string>
|
<string>帮助</string>
|
||||||
</property>
|
</property>
|
||||||
<addaction name="ManualAction"/>
|
<addaction name="ManualAction"/>
|
||||||
|
<addaction name="CheckUpdateAction"/>
|
||||||
<addaction name="AboutAction"/>
|
<addaction name="AboutAction"/>
|
||||||
</widget>
|
</widget>
|
||||||
|
<addaction name="ToolsMenu"/>
|
||||||
<addaction name="HelpMenu"/>
|
<addaction name="HelpMenu"/>
|
||||||
</widget>
|
</widget>
|
||||||
<widget class="QStatusBar" name="StatusBar">
|
<widget class="QStatusBar" name="StatusBar">
|
||||||
@@ -303,11 +312,26 @@ font: 700 9pt;</string>
|
|||||||
<string>在线手册</string>
|
<string>在线手册</string>
|
||||||
</property>
|
</property>
|
||||||
</action>
|
</action>
|
||||||
|
<action name="CheckUpdateAction">
|
||||||
|
<property name="text">
|
||||||
|
<string>检查更新</string>
|
||||||
|
</property>
|
||||||
|
</action>
|
||||||
<action name="AboutAction">
|
<action name="AboutAction">
|
||||||
<property name="text">
|
<property name="text">
|
||||||
<string>关于</string>
|
<string>关于</string>
|
||||||
</property>
|
</property>
|
||||||
</action>
|
</action>
|
||||||
|
<action name="SettingsAction">
|
||||||
|
<property name="text">
|
||||||
|
<string>全局设置</string>
|
||||||
|
</property>
|
||||||
|
</action>
|
||||||
|
<action name="BulletinAction">
|
||||||
|
<property name="text">
|
||||||
|
<string>公告栏</string>
|
||||||
|
</property>
|
||||||
|
</action>
|
||||||
</widget>
|
</widget>
|
||||||
<resources/>
|
<resources/>
|
||||||
<connections/>
|
<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>
|
<x>0</x>
|
||||||
<y>0</y>
|
<y>0</y>
|
||||||
<width>350</width>
|
<width>350</width>
|
||||||
<height>400</height>
|
<height>500</height>
|
||||||
</rect>
|
</rect>
|
||||||
</property>
|
</property>
|
||||||
<property name="minimumSize">
|
<property name="minimumSize">
|
||||||
<size>
|
<size>
|
||||||
<width>350</width>
|
<width>350</width>
|
||||||
<height>460</height>
|
<height>500</height>
|
||||||
</size>
|
</size>
|
||||||
</property>
|
</property>
|
||||||
<property name="maximumSize">
|
<property name="maximumSize">
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ class ConfigType(Enum):
|
|||||||
"""
|
"""
|
||||||
Config type enum. Values represent the default filename.
|
Config type enum. Values represent the default filename.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
GLOBAL = "autolibrary.json"
|
GLOBAL = "autolibrary.json"
|
||||||
BULLETIN = "bulletin.json"
|
BULLETIN = "bulletin.json"
|
||||||
TIMERTASK = "timer_task.json"
|
TIMERTASK = "timer_task.json"
|
||||||
@@ -30,6 +31,7 @@ class ConfigPath:
|
|||||||
Consumers pass this directly to ConfigProvider.get/set,
|
Consumers pass this directly to ConfigProvider.get/set,
|
||||||
eliminating the need to import ConfigType separately.
|
eliminating the need to import ConfigType separately.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
config_type: ConfigType
|
config_type: ConfigType
|
||||||
key: str = ""
|
key: str = ""
|
||||||
|
|
||||||
@@ -64,6 +66,18 @@ class CfgKey:
|
|||||||
CURRENT = ConfigPath(ConfigType.GLOBAL, "automation.user_path.current")
|
CURRENT = ConfigPath(ConfigType.GLOBAL, "automation.user_path.current")
|
||||||
PATHS = ConfigPath(ConfigType.GLOBAL, "automation.user_path.paths")
|
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:
|
class TIMERTASK:
|
||||||
ROOT = ConfigPath(ConfigType.TIMERTASK, "")
|
ROOT = ConfigPath(ConfigType.TIMERTASK, "")
|
||||||
TIMER_TASKS = ConfigPath(ConfigType.TIMERTASK, "timer_tasks")
|
TIMER_TASKS = ConfigPath(ConfigType.TIMERTASK, "timer_tasks")
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
Interfaces module for the AutoLibrary project.
|
Copyright (c) 2026 KenanZhu.
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
Defines abstract interfaces (Protocols) and shared type definitions
|
This software is provided "as is", without any warranty of any kind.
|
||||||
used across layers to decouple consumers from concrete implementations.
|
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||||
|
See the LICENSE file for details.
|
||||||
Key components:
|
|
||||||
- ConfigProvider: Abstract interface for configuration access.
|
|
||||||
- ConfigType: Enumeration of configuration file types.
|
|
||||||
- ConfigKey: Type-safe hierarchical key constants for config lookups.
|
|
||||||
"""
|
"""
|
||||||
@@ -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:
|
This software is provided "as is", without any warranty of any kind.
|
||||||
- ConfigManager: Config manager for managing configuration files.
|
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||||
- LogManager: Log manager for logging.
|
See the LICENSE file for details.
|
||||||
- WebDriverManager: Web driver manager for managing web drivers.
|
"""
|
||||||
"""
|
|
||||||
@@ -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,6 +7,7 @@ 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.
|
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||||
See the LICENSE file for details.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
|
import copy
|
||||||
import os
|
import os
|
||||||
import threading
|
import threading
|
||||||
|
|
||||||
@@ -18,7 +19,7 @@ from interfaces.ConfigProvider import ConfigType, ConfigPath
|
|||||||
|
|
||||||
|
|
||||||
# This config manager class only responsible for global and other
|
# This config manager class only responsible for global and other
|
||||||
# unconfigurable config files.
|
# config files. NOT include run and user config files.
|
||||||
|
|
||||||
|
|
||||||
class ConfigTemplate:
|
class ConfigTemplate:
|
||||||
@@ -33,7 +34,6 @@ class ConfigTemplate:
|
|||||||
|
|
||||||
self.__config_type = config_type
|
self.__config_type = config_type
|
||||||
|
|
||||||
|
|
||||||
def template(
|
def template(
|
||||||
self
|
self
|
||||||
) -> dict:
|
) -> dict:
|
||||||
@@ -55,6 +55,16 @@ class ConfigTemplate:
|
|||||||
"current": 0,
|
"current": 0,
|
||||||
"paths": []
|
"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:
|
case ConfigType.BULLETIN:
|
||||||
@@ -78,12 +88,11 @@ class ConfigManager:
|
|||||||
):
|
):
|
||||||
|
|
||||||
self.__config_dir = os.path.abspath(config_dir)
|
self.__config_dir = os.path.abspath(config_dir)
|
||||||
self.__config_lock = threading.Lock()
|
|
||||||
self.__config_data = {}
|
self.__config_data = {}
|
||||||
|
self.__lock = threading.Lock()
|
||||||
|
|
||||||
self.initialize()
|
self.initialize()
|
||||||
|
|
||||||
|
|
||||||
def initialize(
|
def initialize(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -91,7 +100,6 @@ class ConfigManager:
|
|||||||
for config_type in ConfigType:
|
for config_type in ConfigType:
|
||||||
self.load(config_type)
|
self.load(config_type)
|
||||||
|
|
||||||
|
|
||||||
def load(
|
def load(
|
||||||
self,
|
self,
|
||||||
config_type: ConfigType
|
config_type: ConfigType
|
||||||
@@ -103,29 +111,27 @@ class ConfigManager:
|
|||||||
config_data = JSONReader(config_path).data()
|
config_data = JSONReader(config_path).data()
|
||||||
self.__config_data[config_type.value] = config_data
|
self.__config_data[config_type.value] = config_data
|
||||||
return
|
return
|
||||||
except:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
self.__config_data[config_type.value] = ConfigTemplate(config_type).template()
|
self.__config_data[config_type.value] = ConfigTemplate(config_type).template()
|
||||||
JSONWriter(config_path, self.__config_data[config_type.value])
|
JSONWriter(config_path, self.__config_data[config_type.value])
|
||||||
|
|
||||||
|
|
||||||
def get(
|
def get(
|
||||||
self,
|
self,
|
||||||
key: ConfigPath,
|
key: ConfigPath,
|
||||||
default: Optional[Any] = None
|
default: Optional[Any] = None
|
||||||
) -> Any:
|
) -> Any:
|
||||||
|
|
||||||
with self.__config_lock:
|
with self.__lock:
|
||||||
config_data = self.__config_data[key.config_type.value]
|
config_data = self.__config_data[key.config_type.value]
|
||||||
if key.key == "":
|
if key.key == "":
|
||||||
return config_data
|
return copy.deepcopy(config_data)
|
||||||
keys = key.key.split('.')
|
keys = key.key.split('.')
|
||||||
for k in keys[:-1]:
|
for k in keys[:-1]:
|
||||||
config_data = config_data.get(k, None)
|
config_data = config_data.get(k, None)
|
||||||
if config_data is None:
|
if config_data is None:
|
||||||
return default
|
return default
|
||||||
return config_data.get(keys[-1], default)
|
return copy.deepcopy(config_data.get(keys[-1], default))
|
||||||
|
|
||||||
|
|
||||||
def set(
|
def set(
|
||||||
self,
|
self,
|
||||||
@@ -133,7 +139,7 @@ class ConfigManager:
|
|||||||
value: Any = None
|
value: Any = None
|
||||||
):
|
):
|
||||||
|
|
||||||
with self.__config_lock:
|
with self.__lock:
|
||||||
root_data = self.__config_data[key.config_type.value]
|
root_data = self.__config_data[key.config_type.value]
|
||||||
if key.key == "":
|
if key.key == "":
|
||||||
self.__config_data[key.config_type.value] = value
|
self.__config_data[key.config_type.value] = value
|
||||||
@@ -147,7 +153,6 @@ class ConfigManager:
|
|||||||
config_data[keys[-1]] = value
|
config_data[keys[-1]] = value
|
||||||
self.save(key.config_type)
|
self.save(key.config_type)
|
||||||
|
|
||||||
|
|
||||||
def save(
|
def save(
|
||||||
self,
|
self,
|
||||||
config_type: ConfigType
|
config_type: ConfigType
|
||||||
@@ -156,7 +161,6 @@ class ConfigManager:
|
|||||||
config_path = os.path.join(self.__config_dir, config_type.value)
|
config_path = os.path.join(self.__config_dir, config_type.value)
|
||||||
JSONWriter(config_path, self.__config_data[config_type.value])
|
JSONWriter(config_path, self.__config_data[config_type.value])
|
||||||
|
|
||||||
|
|
||||||
def configDir(
|
def configDir(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
@@ -169,6 +173,7 @@ _config_manager_instance : ConfigManager | None = None
|
|||||||
|
|
||||||
# Singleton instance of ConfigManager.
|
# Singleton instance of ConfigManager.
|
||||||
_instance_lock = threading.Lock()
|
_instance_lock = threading.Lock()
|
||||||
|
|
||||||
def instance(
|
def instance(
|
||||||
config_dir: str = ""
|
config_dir: str = ""
|
||||||
) -> ConfigManager:
|
) -> ConfigManager:
|
||||||
|
|||||||
@@ -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:
|
This software is provided "as is", without any warranty of any kind.
|
||||||
- ConfigManager: Config manager for managing configuration files.
|
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
|
MACX86_64 = 6
|
||||||
MACARM = 7
|
MACARM = 7
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class WebBrowserInfo:
|
class WebBrowserInfo:
|
||||||
"""
|
"""
|
||||||
@@ -70,7 +71,6 @@ class WebBrowserArchDetector:
|
|||||||
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def detect(
|
def detect(
|
||||||
self
|
self
|
||||||
) -> WebBrowserArch:
|
) -> WebBrowserArch:
|
||||||
@@ -123,7 +123,6 @@ class WebBrowserDetector:
|
|||||||
self.browser_arch = WebBrowserArchDetector().detect()
|
self.browser_arch = WebBrowserArchDetector().detect()
|
||||||
self.browser_infos : list[WebBrowserInfo] = []
|
self.browser_infos : list[WebBrowserInfo] = []
|
||||||
|
|
||||||
|
|
||||||
def detect(
|
def detect(
|
||||||
self
|
self
|
||||||
) -> list[WebBrowserInfo]:
|
) -> list[WebBrowserInfo]:
|
||||||
|
|||||||
@@ -95,7 +95,6 @@ class WebDriverName:
|
|||||||
|
|
||||||
self.driver_type = driver_type
|
self.driver_type = driver_type
|
||||||
|
|
||||||
|
|
||||||
def __str__(
|
def __str__(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
@@ -125,7 +124,6 @@ class WebDriverExecName:
|
|||||||
self.driver_type = driver_type
|
self.driver_type = driver_type
|
||||||
self.arch = arch
|
self.arch = arch
|
||||||
|
|
||||||
|
|
||||||
def __str__(
|
def __str__(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
@@ -183,7 +181,7 @@ class WebDriverFileName:
|
|||||||
raise ValueError(f"不受支持的 web driver 类型 : {self.driver_type}")
|
raise ValueError(f"不受支持的 web driver 类型 : {self.driver_type}")
|
||||||
|
|
||||||
|
|
||||||
class WebDriverURL:
|
class WebDriverDownloadURL:
|
||||||
"""
|
"""
|
||||||
Web driver download URL
|
Web driver download URL
|
||||||
"""
|
"""
|
||||||
@@ -200,7 +198,6 @@ class WebDriverURL:
|
|||||||
self.arch = arch
|
self.arch = arch
|
||||||
self.file_name = str(WebDriverFileName(self.version, self.driver_type, self.arch))
|
self.file_name = str(WebDriverFileName(self.version, self.driver_type, self.arch))
|
||||||
|
|
||||||
|
|
||||||
def __str__(
|
def __str__(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
@@ -245,36 +242,11 @@ class WebDriverDownloader:
|
|||||||
self.driver_type = driver_type
|
self.driver_type = driver_type
|
||||||
self.arch = driver_arch
|
self.arch = driver_arch
|
||||||
self.version = driver_version
|
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 = 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_dir.mkdir(mode=0o0755, parents=True, exist_ok=True)
|
||||||
self.download_path = self.download_dir/str(WebDriverFileName(self.version, self.driver_type, self.arch))
|
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(
|
def _download(
|
||||||
self,
|
self,
|
||||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
||||||
@@ -352,7 +324,6 @@ class WebDriverDownloader:
|
|||||||
continue
|
continue
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
|
||||||
def _verify(
|
def _verify(
|
||||||
self,
|
self,
|
||||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None
|
progress_callback: Optional[Callable[[float, int, float, str], None]] = None
|
||||||
@@ -361,7 +332,6 @@ class WebDriverDownloader:
|
|||||||
progress_callback(98, 100, 0.0, "验证完成")
|
progress_callback(98, 100, 0.0, "验证完成")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def _extract(
|
def _extract(
|
||||||
self,
|
self,
|
||||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None
|
progress_callback: Optional[Callable[[float, int, float, str], None]] = None
|
||||||
@@ -390,6 +360,10 @@ class WebDriverDownloader:
|
|||||||
break
|
break
|
||||||
if not driver_file:
|
if not driver_file:
|
||||||
raise FileNotFoundError(f"未找到 web driver 文件 : {expected_name}")
|
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, "解压完成")
|
progress_callback(100, 100, 0.0, "解压完成")
|
||||||
self.download_path.unlink()
|
self.download_path.unlink()
|
||||||
self._cleanup(driver_file)
|
self._cleanup(driver_file)
|
||||||
@@ -397,7 +371,6 @@ class WebDriverDownloader:
|
|||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _cleanup(
|
def _cleanup(
|
||||||
self,
|
self,
|
||||||
driver_file: Path
|
driver_file: Path
|
||||||
@@ -410,6 +383,29 @@ class WebDriverDownloader:
|
|||||||
else:
|
else:
|
||||||
item.unlink()
|
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):
|
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.
|
See the LICENSE file for details.
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
import threading
|
import threading
|
||||||
import packaging.version as ver
|
import packaging.version as ver
|
||||||
|
|
||||||
@@ -19,7 +20,7 @@ from managers.driver.WebBrowserDetector import (
|
|||||||
WebBrowserType, WebBrowserArch, WebBrowserInfo, WebBrowserDetector
|
WebBrowserType, WebBrowserArch, WebBrowserInfo, WebBrowserDetector
|
||||||
)
|
)
|
||||||
from managers.driver.WebDriverDownloader import (
|
from managers.driver.WebDriverDownloader import (
|
||||||
WebDriverArch, WebDriverType,
|
WebDriverArch, WebDriverType, WebDriverExecName,
|
||||||
ChromeDriverDownloader, FirefoxDriverDownloader, EdgeDriverDownloader
|
ChromeDriverDownloader, FirefoxDriverDownloader, EdgeDriverDownloader
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -35,9 +36,9 @@ class WebDriverStatus(Enum):
|
|||||||
ERROR = 3
|
ERROR = 3
|
||||||
|
|
||||||
|
|
||||||
class WebDriverInfo:
|
class WebDriverCtx:
|
||||||
"""
|
"""
|
||||||
Web driver information.
|
Web browser and driver context.
|
||||||
|
|
||||||
Attributes:
|
Attributes:
|
||||||
driver_type (WebDriverType): Web driver type
|
driver_type (WebDriverType): Web driver type
|
||||||
@@ -52,8 +53,8 @@ class WebDriverInfo:
|
|||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
self.driver_type = None
|
self.driver_type : Optional[WebDriverType] = None
|
||||||
self.driver_arch = None
|
self.driver_arch : Optional[WebDriverArch] = None
|
||||||
self.driver_version = ""
|
self.driver_version = ""
|
||||||
self.browser_version = ""
|
self.browser_version = ""
|
||||||
self.driver_path: Optional[Path] = None
|
self.driver_path: Optional[Path] = None
|
||||||
@@ -75,13 +76,12 @@ class WebDriverManager:
|
|||||||
|
|
||||||
self.__driver_dir = os.path.abspath(driver_dir)
|
self.__driver_dir = os.path.abspath(driver_dir)
|
||||||
self.__browser_detector = WebBrowserDetector()
|
self.__browser_detector = WebBrowserDetector()
|
||||||
self.__driver_infos: list[WebDriverInfo] = []
|
self.__driver_ctxs: list[WebDriverCtx] = []
|
||||||
self.__initialized = False
|
self.__initialized = False
|
||||||
self.__lock = threading.Lock()
|
self.__lock = threading.Lock()
|
||||||
|
|
||||||
self.initialize()
|
self.initialize()
|
||||||
|
|
||||||
|
|
||||||
def initialize(
|
def initialize(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -93,31 +93,32 @@ class WebDriverManager:
|
|||||||
self._checkDriverStatus()
|
self._checkDriverStatus()
|
||||||
self.__initialized = True
|
self.__initialized = True
|
||||||
|
|
||||||
|
|
||||||
def _detectBrowsers(
|
def _detectBrowsers(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
browser_infos = self.__browser_detector.detect()
|
browser_infos = self.__browser_detector.detect()
|
||||||
self.__driver_infos = [
|
self.__driver_ctxs = [
|
||||||
self._getDriverInfo(info)
|
self._getDriverCtx(info)
|
||||||
for info in browser_infos
|
for info in browser_infos
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def _checkDriverStatus(
|
def _checkDriverStatus(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
|
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
for driver_info in self.__driver_infos:
|
for driver_info in self.__driver_ctxs:
|
||||||
driver_path = self._getDriverPath(driver_info)
|
driver_path = self._getDriverPath(driver_info)
|
||||||
if driver_path and driver_path.exists() and driver_path.is_file():
|
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_path = driver_path
|
||||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
driver_info.driver_status = WebDriverStatus.INSTALLED
|
||||||
|
|
||||||
|
|
||||||
def _mapWebBrowserTypeToDriver(
|
def _mapWebBrowserTypeToDriver(
|
||||||
self,
|
self,
|
||||||
browser_type: WebBrowserType
|
browser_type: WebBrowserType
|
||||||
@@ -132,7 +133,6 @@ class WebDriverManager:
|
|||||||
else:
|
else:
|
||||||
raise ValueError(f"不支持的 Web 浏览器类型 : {browser_type}")
|
raise ValueError(f"不支持的 Web 浏览器类型 : {browser_type}")
|
||||||
|
|
||||||
|
|
||||||
def _mapWebBrowserArchToDriver(
|
def _mapWebBrowserArchToDriver(
|
||||||
self,
|
self,
|
||||||
browser_type: WebBrowserType,
|
browser_type: WebBrowserType,
|
||||||
@@ -199,8 +199,7 @@ class WebDriverManager:
|
|||||||
else:
|
else:
|
||||||
raise ValueError(f"不支持的 Web 浏览器类型 : {browser_type}")
|
raise ValueError(f"不支持的 Web 浏览器类型 : {browser_type}")
|
||||||
|
|
||||||
|
def _mapFirefoxBrowserVersionToDriver(
|
||||||
def _mapFirefoxDriverVersion(
|
|
||||||
self,
|
self,
|
||||||
version: str
|
version: str
|
||||||
) -> str:
|
) -> str:
|
||||||
@@ -240,53 +239,34 @@ class WebDriverManager:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise ValueError(f"无效的 Firefox 版本格式 : {version}") from e
|
raise ValueError(f"无效的 Firefox 版本格式 : {version}") from e
|
||||||
|
|
||||||
|
def _getDriverCtx(
|
||||||
def _getDriverInfo(
|
|
||||||
self,
|
self,
|
||||||
browser_info: WebBrowserInfo
|
browser_info: WebBrowserInfo
|
||||||
) -> WebDriverInfo:
|
) -> WebDriverCtx:
|
||||||
|
|
||||||
driver_info = WebDriverInfo()
|
driver_ctx = WebDriverCtx()
|
||||||
driver_info.driver_type = self._mapWebBrowserTypeToDriver(browser_info.browser_type)
|
driver_ctx.driver_type = self._mapWebBrowserTypeToDriver(browser_info.browser_type)
|
||||||
driver_info.driver_arch = self._mapWebBrowserArchToDriver(browser_info.browser_type, browser_info.browser_arch)
|
driver_ctx.driver_arch = self._mapWebBrowserArchToDriver(browser_info.browser_type, browser_info.browser_arch)
|
||||||
if browser_info.browser_type == WebBrowserType.FIREFOX:
|
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:
|
else:
|
||||||
driver_info.driver_version = browser_info.browser_version
|
driver_ctx.driver_version = browser_info.browser_version
|
||||||
driver_info.browser_version = browser_info.browser_version
|
driver_ctx.browser_version = browser_info.browser_version
|
||||||
return driver_info
|
return driver_ctx
|
||||||
|
|
||||||
|
|
||||||
def _getDriverPath(
|
def _getDriverPath(
|
||||||
self,
|
self,
|
||||||
driver_info: WebDriverInfo
|
driver_ctx: WebDriverCtx
|
||||||
) -> Optional[Path]:
|
) -> Optional[Path]:
|
||||||
|
|
||||||
driver_type = driver_info.driver_type
|
driver_type = driver_ctx.driver_type
|
||||||
driver_arch = driver_info.driver_arch
|
driver_arch = driver_ctx.driver_arch
|
||||||
driver_version = driver_info.driver_version
|
driver_version = driver_ctx.driver_version
|
||||||
if driver_type == WebDriverType.CHROME:
|
exe_name = str(WebDriverExecName(driver_type, driver_arch))
|
||||||
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_dir = Path(self.__driver_dir)/driver_type.value/driver_version/driver_arch.value
|
driver_dir = Path(self.__driver_dir)/driver_type.value/driver_version/driver_arch.value
|
||||||
driver_path = driver_dir/exe_name
|
driver_path = driver_dir/exe_name
|
||||||
return driver_path
|
return driver_path
|
||||||
|
|
||||||
|
|
||||||
def refresh(
|
def refresh(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -294,62 +274,58 @@ class WebDriverManager:
|
|||||||
self._detectBrowsers()
|
self._detectBrowsers()
|
||||||
self._checkDriverStatus()
|
self._checkDriverStatus()
|
||||||
|
|
||||||
|
def getDriverCtxs(
|
||||||
def getDriverInfos(
|
|
||||||
self
|
self
|
||||||
) -> list[WebDriverInfo]:
|
) -> list[WebDriverCtx]:
|
||||||
|
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
return self.__driver_infos.copy()
|
return self.__driver_ctxs.copy()
|
||||||
|
|
||||||
|
def getDriverCtx(
|
||||||
def getDriverInfo(
|
|
||||||
self,
|
self,
|
||||||
driver_type: WebDriverType
|
driver_type: WebDriverType
|
||||||
) -> list[WebDriverInfo]:
|
) -> list[WebDriverCtx]:
|
||||||
|
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
return [
|
return [
|
||||||
info
|
info
|
||||||
for info in self.__driver_infos
|
for info in self.__driver_ctxs
|
||||||
if info.driver_type == driver_type
|
if info.driver_type == driver_type
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def getDriverPath(
|
def getDriverPath(
|
||||||
self,
|
self,
|
||||||
driver_info: WebDriverInfo
|
driver_info: WebDriverCtx
|
||||||
) -> Optional[Path]:
|
) -> Optional[Path]:
|
||||||
|
|
||||||
if driver_info and driver_info.driver_status == WebDriverStatus.INSTALLED:
|
if driver_info and driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||||
return driver_info.driver_path
|
return driver_info.driver_path
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def installDriver(
|
def installDriver(
|
||||||
self,
|
self,
|
||||||
driver_info: WebDriverInfo,
|
driver_ctx: WebDriverCtx,
|
||||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
||||||
cancel_event: Optional[threading.Event] = None
|
cancel_event: Optional[threading.Event] = None
|
||||||
) -> Optional[Path]:
|
) -> Optional[Path]:
|
||||||
|
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
if not driver_info:
|
if not driver_ctx:
|
||||||
if progress_callback:
|
if progress_callback:
|
||||||
progress_callback(0, 0, 0, "未找到浏览器信息")
|
progress_callback(0, 0, 0, "未找到浏览器信息")
|
||||||
else:
|
else:
|
||||||
raise ValueError("未找到浏览器信息")
|
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:
|
if progress_callback:
|
||||||
progress_callback(0, 0, 0, f"{driver_info.driver_type} 驱动正在下载中")
|
progress_callback(0, 0, 0, f"{driver_ctx.driver_type} 驱动正在下载中")
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"{driver_info.driver_type} 驱动正在下载中")
|
raise ValueError(f"{driver_ctx.driver_type} 驱动正在下载中")
|
||||||
try:
|
try:
|
||||||
if not driver_info:
|
if not driver_ctx:
|
||||||
raise ValueError("未找到浏览器信息")
|
raise ValueError("未找到浏览器信息")
|
||||||
driver_arch = driver_info.driver_arch
|
driver_arch = driver_ctx.driver_arch
|
||||||
driver_type = driver_info.driver_type
|
driver_type = driver_ctx.driver_type
|
||||||
driver_version = driver_info.driver_version
|
driver_version = driver_ctx.driver_version
|
||||||
downloader = None
|
downloader = None
|
||||||
if driver_type == WebDriverType.CHROME:
|
if driver_type == WebDriverType.CHROME:
|
||||||
downloader = ChromeDriverDownloader(
|
downloader = ChromeDriverDownloader(
|
||||||
@@ -375,73 +351,68 @@ class WebDriverManager:
|
|||||||
else:
|
else:
|
||||||
raise ValueError(f"不支持的 Web Driver 类型")
|
raise ValueError(f"不支持的 Web Driver 类型")
|
||||||
with self.__lock:
|
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)
|
driver_path = downloader.download(progress_callback=progress_callback, cancel_event=cancel_event)
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
if driver_path:
|
if driver_path:
|
||||||
driver_info.driver_path = driver_path
|
driver_ctx.driver_path = driver_path
|
||||||
driver_info.driver_version = driver_version
|
driver_ctx.driver_version = driver_version
|
||||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
driver_ctx.driver_status = WebDriverStatus.INSTALLED
|
||||||
else:
|
else:
|
||||||
driver_info.driver_status = WebDriverStatus.ERROR
|
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||||
return driver_path
|
return driver_path
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
driver_info.driver_status = WebDriverStatus.ERROR
|
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||||
raise e
|
raise e
|
||||||
|
|
||||||
|
|
||||||
def cancelDriverDownload(
|
def cancelDriverDownload(
|
||||||
self,
|
self,
|
||||||
driver_info: WebDriverInfo
|
driver_ctx: WebDriverCtx
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
|
||||||
import shutil
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
driver_path = self._getDriverPath(driver_info)
|
driver_path = self._getDriverPath(driver_ctx)
|
||||||
if driver_path:
|
if driver_path:
|
||||||
download_dir = driver_path.parent
|
download_dir = driver_path.parent
|
||||||
if download_dir.exists():
|
if download_dir.exists():
|
||||||
shutil.rmtree(download_dir, ignore_errors=True)
|
shutil.rmtree(download_dir, ignore_errors=True)
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
driver_info.driver_path = None
|
driver_ctx.driver_path = None
|
||||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
driver_ctx.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def uninstallDriver(
|
def uninstallDriver(
|
||||||
self,
|
self,
|
||||||
driver_info: WebDriverInfo,
|
driver_ctx: WebDriverCtx,
|
||||||
progress_callback: Optional[Callable[[int, int, float, str], None]] = None
|
progress_callback: Optional[Callable[[int, int, float, str], None]] = None
|
||||||
) -> bool:
|
) -> bool:
|
||||||
|
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
if not driver_info:
|
if not driver_ctx:
|
||||||
if progress_callback:
|
if progress_callback:
|
||||||
progress_callback(0, 0, 0, "未找到浏览器信息")
|
progress_callback(0, 0, 0, "未找到浏览器信息")
|
||||||
else:
|
else:
|
||||||
raise ValueError("未找到浏览器信息")
|
raise ValueError("未找到浏览器信息")
|
||||||
if driver_info.driver_status != WebDriverStatus.INSTALLED:
|
if driver_ctx.driver_status != WebDriverStatus.INSTALLED:
|
||||||
if progress_callback:
|
if progress_callback:
|
||||||
progress_callback(0, 0, 0, f"{driver_info.driver_type} 驱动未安装")
|
progress_callback(0, 0, 0, f"{driver_ctx.driver_type} 驱动未安装")
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"{driver_info.driver_type} 驱动未安装")
|
raise ValueError(f"{driver_ctx.driver_type} 驱动未安装")
|
||||||
try:
|
try:
|
||||||
driver_path = driver_info.driver_path
|
driver_path = driver_ctx.driver_path
|
||||||
driver_path.unlink()
|
driver_path.unlink()
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
driver_info.driver_path = None
|
driver_ctx.driver_path = None
|
||||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
driver_ctx.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
with self.__lock:
|
with self.__lock:
|
||||||
driver_info.driver_status = WebDriverStatus.ERROR
|
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
def driverDir(
|
def driverDir(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> 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:
|
This software is provided "as is", without any warranty of any kind.
|
||||||
- WebBrowserDetector: Web browser detector class.
|
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||||
- WebDriverDownloader: Web driver downloader class.
|
See the LICENSE file for details.
|
||||||
- WebDriverManager: Web driver manager class.
|
"""
|
||||||
"""
|
|
||||||
@@ -89,7 +89,6 @@ class LogManager:
|
|||||||
|
|
||||||
self.initialize()
|
self.initialize()
|
||||||
|
|
||||||
|
|
||||||
def initialize(
|
def initialize(
|
||||||
self
|
self
|
||||||
):
|
):
|
||||||
@@ -100,17 +99,14 @@ class LogManager:
|
|||||||
self.__logger = logging.getLogger("AutoLibrary")
|
self.__logger = logging.getLogger("AutoLibrary")
|
||||||
self.__logger.setLevel(logging.DEBUG)
|
self.__logger.setLevel(logging.DEBUG)
|
||||||
self.__logger.handlers.clear()
|
self.__logger.handlers.clear()
|
||||||
|
|
||||||
formatter = CallerInfoFormatter(
|
formatter = CallerInfoFormatter(
|
||||||
'[%(asctime)s] - [%(name)s] - [%(levelname)s] - [%(filename)s:%(lineno)s] - %(message)s',
|
'[%(asctime)s] - [%(name)s] - [%(levelname)s] - [%(filename)s:%(lineno)s] - %(message)s',
|
||||||
datefmt='%Y-%m-%d %H:%M:%S'
|
datefmt='%Y-%m-%d %H:%M:%S'
|
||||||
)
|
)
|
||||||
|
|
||||||
console_handler = logging.StreamHandler()
|
console_handler = logging.StreamHandler()
|
||||||
console_handler.setLevel(logging.INFO)
|
console_handler.setLevel(logging.INFO)
|
||||||
console_handler.setFormatter(formatter)
|
console_handler.setFormatter(formatter)
|
||||||
self.__logger.addHandler(console_handler)
|
self.__logger.addHandler(console_handler)
|
||||||
|
|
||||||
all_log_file = os.path.join(self.__log_dir, "all.log")
|
all_log_file = os.path.join(self.__log_dir, "all.log")
|
||||||
file_handler_all = TimedRotatingFileHandler(
|
file_handler_all = TimedRotatingFileHandler(
|
||||||
all_log_file,
|
all_log_file,
|
||||||
@@ -123,7 +119,6 @@ class LogManager:
|
|||||||
file_handler_all.setLevel(logging.DEBUG)
|
file_handler_all.setLevel(logging.DEBUG)
|
||||||
file_handler_all.setFormatter(formatter)
|
file_handler_all.setFormatter(formatter)
|
||||||
self.__logger.addHandler(file_handler_all)
|
self.__logger.addHandler(file_handler_all)
|
||||||
|
|
||||||
error_log_file = os.path.join(self.__log_dir, "error.log")
|
error_log_file = os.path.join(self.__log_dir, "error.log")
|
||||||
file_handler_error = TimedRotatingFileHandler(
|
file_handler_error = TimedRotatingFileHandler(
|
||||||
error_log_file,
|
error_log_file,
|
||||||
@@ -136,10 +131,8 @@ class LogManager:
|
|||||||
file_handler_error.setLevel(logging.ERROR)
|
file_handler_error.setLevel(logging.ERROR)
|
||||||
file_handler_error.setFormatter(formatter)
|
file_handler_error.setFormatter(formatter)
|
||||||
self.__logger.addHandler(file_handler_error)
|
self.__logger.addHandler(file_handler_error)
|
||||||
|
|
||||||
self.__initialized = True
|
self.__initialized = True
|
||||||
|
|
||||||
|
|
||||||
def getLogger(
|
def getLogger(
|
||||||
self,
|
self,
|
||||||
name: Optional[str] = None
|
name: Optional[str] = None
|
||||||
@@ -149,7 +142,6 @@ class LogManager:
|
|||||||
return self.__logger.getChild(name)
|
return self.__logger.getChild(name)
|
||||||
return self.__logger
|
return self.__logger
|
||||||
|
|
||||||
|
|
||||||
def setLevel(
|
def setLevel(
|
||||||
self,
|
self,
|
||||||
level: int
|
level: int
|
||||||
@@ -158,7 +150,6 @@ class LogManager:
|
|||||||
if self.__logger:
|
if self.__logger:
|
||||||
self.__logger.setLevel(level)
|
self.__logger.setLevel(level)
|
||||||
|
|
||||||
|
|
||||||
def logDir(
|
def logDir(
|
||||||
self
|
self
|
||||||
) -> str:
|
) -> str:
|
||||||
@@ -171,6 +162,7 @@ _log_manager_instance = None
|
|||||||
|
|
||||||
# Singleton instance lock.
|
# Singleton instance lock.
|
||||||
_instance_lock = threading.Lock()
|
_instance_lock = threading.Lock()
|
||||||
|
|
||||||
def instance(
|
def instance(
|
||||||
log_dir: str = ""
|
log_dir: str = ""
|
||||||
) -> LogManager:
|
) -> 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:
|
This software is provided "as is", without any warranty of any kind.
|
||||||
- LogManager: Log manager for logging.
|
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
|
|
||||||