Compare commits
84
Commits
f7167c13f4
...
v1.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4d838a9d0 | ||
|
|
70f78c2a6f | ||
|
|
e40e7767c7 | ||
|
|
1b6c170d6c | ||
|
|
30a7a8e996 | ||
|
|
d59ecc3090 | ||
|
|
7685f6a616 | ||
|
|
ed8dec70a6 | ||
|
|
dfa9ae1a0c | ||
|
|
06740776a9 | ||
|
|
c8f9ae752f | ||
|
|
89c1e33257 | ||
|
|
862f86827a | ||
|
|
ed98623cda | ||
|
|
ab51c72a11 | ||
|
|
2fe4584129 | ||
|
|
92c5fa0dfb | ||
|
|
05ad9ba0b3 | ||
|
|
0069d5274b | ||
|
|
6a9c662287 | ||
|
|
d7fff16991 | ||
|
|
db345f9efc | ||
|
|
133433f2d8 | ||
|
|
6f32923865 | ||
|
|
a716e5b945 | ||
|
|
588718f9c5 | ||
|
|
0ba76babc6 | ||
|
|
dc7e5d8cd8 | ||
|
|
818acd4efc | ||
|
|
308a1dfcf3 | ||
|
|
c250fa4a6e | ||
|
|
8f8e3e4ba7 | ||
|
|
88a74a7a47 | ||
|
|
5552af1345 | ||
|
|
6d05d4c7cb | ||
|
|
01f4ccaa0e | ||
|
|
f9175371dc | ||
|
|
8e1b28f3fe | ||
|
|
57f1cfb3f2 | ||
|
|
007b4dc2ef | ||
|
|
0bad34d7a8 | ||
|
|
61d1b44402 | ||
|
|
72301c63fd | ||
|
|
609850ab60 | ||
|
|
8e14d45b71 | ||
|
|
f6ef9af39d | ||
|
|
72dce83c55 | ||
|
|
67f297b434 | ||
|
|
86f0761eed | ||
|
|
79e5b43498 | ||
|
|
b56d2c203e | ||
|
|
44dbde3355 | ||
|
|
62f8ec3d91 | ||
|
|
2d77cbec79 | ||
|
|
10d731518a | ||
|
|
9fdb6f7652 | ||
|
|
ef903ee817 | ||
|
|
d6e8eef8c8 | ||
|
|
e893752c25 | ||
|
|
1cfd7382be | ||
|
|
1d9e41ab86 | ||
|
|
645f07b4d2 | ||
|
|
732f104c5c | ||
|
|
a2bc1881bc | ||
|
|
c1004ed2bc | ||
|
|
38489191f5 | ||
|
|
35253dadbb | ||
|
|
c0b6e0899c | ||
|
|
9c1772b186 | ||
|
|
05b93799d4 | ||
|
|
c337904010 | ||
|
|
779aad13b8 | ||
|
|
f3360423e5 | ||
|
|
bea12d5f0c | ||
|
|
b24f39456e | ||
|
|
bb63ee6f03 | ||
|
|
3ebebe015f | ||
|
|
02b3a62868 | ||
|
|
d7e19dcd52 | ||
|
|
59c06b3a19 | ||
|
|
b78fd2d1e4 | ||
|
|
2aace40a26 | ||
|
|
df7ad92f7f | ||
|
|
910e3e3224 |
No files matched your search
@@ -7,7 +7,6 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
@@ -15,7 +14,6 @@ on:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
# Allow manual trigger for testing
|
||||
workflow_dispatch:
|
||||
|
||||
#
|
||||
@@ -49,11 +47,13 @@ jobs:
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirement.txt
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
@@ -125,7 +125,7 @@ jobs:
|
||||
" binaries=[],"
|
||||
" datas=["
|
||||
" ('models\\common.onnx', 'ddddocr'),"
|
||||
" ('src\\gui\\resources\\icons\\AutoLibrary_32x32.ico', 'gui\\resources\\icons'),"
|
||||
" ('src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico', 'gui\\resources\\icons'),"
|
||||
" ],"
|
||||
" hiddenimports=[],"
|
||||
" hookspath=[],"
|
||||
@@ -153,7 +153,7 @@ jobs:
|
||||
" target_arch=None,"
|
||||
" codesign_identity=None,"
|
||||
" entitlements_file=None,"
|
||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_32x32.ico'],"
|
||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico'],"
|
||||
")"
|
||||
""
|
||||
"coll = COLLECT("
|
||||
@@ -169,9 +169,11 @@ jobs:
|
||||
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
||||
|
||||
Write-Host "✓ Main.spec (non-single file) generated successfully"
|
||||
Write-Host "`nGenerated Main.spec ============"
|
||||
Write-Host "`n========================================"
|
||||
Write-Host "Generated Main.spec"
|
||||
Write-Host "========================================"
|
||||
Get-Content "Main.spec" | Write-Host
|
||||
Write-Host "==================================`n"
|
||||
Write-Host "========================================`n"
|
||||
shell: pwsh
|
||||
|
||||
- name: Build with PyInstaller
|
||||
@@ -186,7 +188,7 @@ jobs:
|
||||
$distDir = "dist/AutoLibrary-$version"
|
||||
$zipName = "AutoLibrary.$tagName-windows-x86_64.zip"
|
||||
|
||||
echo "ZIP_NAME=$zipName" >> $env:GITHUB_OUTPUT
|
||||
"ZIP_NAME=$zipName" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
|
||||
|
||||
Write-Host "Looking for distribution directory: $distDir"
|
||||
if (Test-Path $distDir) {
|
||||
@@ -210,12 +212,283 @@ jobs:
|
||||
|
||||
- name: Upload build summary
|
||||
run: |
|
||||
Write-Host "## Build Test Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||
Write-Host "" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "✓ Pull request build test completed successfully!" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Version: ${{ steps.get_version.outputs.VERSION }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Pull Request #${{ github.event.pull_request.number }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Branch: ${{ github.event.pull_request.head.ref }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Event: ${{ github.event_name }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"## Build Test Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||
"" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"========================================" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"✓ Pull request build test completed successfully!" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Version: ${{ steps.get_version.outputs.VERSION }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Pull Request #${{ github.event.pull_request.number || 'N/A' }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Branch: ${{ github.event.pull_request.head.ref || github.ref }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Event: ${{ github.event_name }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
shell: pwsh
|
||||
|
||||
#
|
||||
# Build macOS
|
||||
#
|
||||
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- name: Get version info
|
||||
id: get_version
|
||||
run: |
|
||||
version="pr-test"
|
||||
tag_name="pr-test"
|
||||
echo "✓ Mode: Pull Request Test Build"
|
||||
echo "✓ Tag: $tag_name"
|
||||
echo "✓ Version: $version"
|
||||
echo "VERSION=$version" >> $GITHUB_OUTPUT
|
||||
echo "TAG_NAME=$tag_name" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
ddddocr_path=$(python -c "import ddddocr, os; print(os.path.dirname(ddddocr.__file__))")
|
||||
echo "ddddocr package location: $ddddocr_path"
|
||||
|
||||
init_file="$ddddocr_path/__init__.py"
|
||||
if [ -f "$init_file" ]; then
|
||||
echo "Fixing ddddocr compatibility in: $init_file"
|
||||
# macOS 使用 BSD sed,要求 -i 后跟备份后缀名(空字符串 = 不备份)
|
||||
sed -i '' 's/Image\.ANTIALIAS/Image.Resampling.LANCZOS/g' "$init_file"
|
||||
echo "✓ Fixed: Image.ANTIALIAS -> Image.Resampling.LANCZOS"
|
||||
else
|
||||
echo "✗ ddddocr __init__.py not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p models
|
||||
echo "✓ Created models directory"
|
||||
|
||||
# 多路径 fallback 搜索 ONNX 模型,提升 ddddocr 版本兼容性
|
||||
onnx_source=""
|
||||
onnx_dest="models/common.onnx"
|
||||
candidate_paths=(
|
||||
"$ddddocr_path/common.onnx"
|
||||
"$ddddocr_path/models/common.onnx"
|
||||
"$ddddocr_path/ddddocr/common.onnx"
|
||||
)
|
||||
for candidate in "${candidate_paths[@]}"; do
|
||||
if [ -f "$candidate" ]; then
|
||||
onnx_source="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
# 若以上候选均未命中,回退到全包搜索
|
||||
if [ -z "$onnx_source" ]; then
|
||||
echo "⚠ 未在已知路径找到 ONNX 模型,回退到全包搜索..."
|
||||
onnx_source=$(find "$ddddocr_path" -name "*.onnx" -type f 2>/dev/null | head -1)
|
||||
fi
|
||||
|
||||
if [ -n "$onnx_source" ] && [ -f "$onnx_source" ]; then
|
||||
cp "$onnx_source" "$onnx_dest"
|
||||
echo "✓ ONNX model copied: $onnx_source -> $onnx_dest"
|
||||
else
|
||||
echo "✗ ONNX model not found in ddddocr package"
|
||||
echo " Searched directory: $ddddocr_path"
|
||||
ls -la "$ddddocr_path/" || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -f "$onnx_dest" ]; then
|
||||
file_size=$(du -h "$onnx_dest" | cut -f1)
|
||||
echo "✓ Model file verified: $onnx_dest (Size: $file_size)"
|
||||
else
|
||||
echo "✗ Failed to copy model file"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Compile Qt Resource files
|
||||
run: |
|
||||
cd batchs
|
||||
bash compile_rc.sh
|
||||
|
||||
- name: Compile Qt UI files
|
||||
run: |
|
||||
cd batchs
|
||||
bash compile_ui.sh
|
||||
|
||||
- name: Generate 'Main.spec'
|
||||
env:
|
||||
APP_VERSION: ${{ steps.get_version.outputs.VERSION }}
|
||||
run: |
|
||||
version="$APP_VERSION"
|
||||
exe_name="AutoLibrary-$version"
|
||||
echo "Generating Main.spec for version: $version"
|
||||
echo "App name: $exe_name"
|
||||
|
||||
printf '%s\n' \
|
||||
'# -*- mode: python ; coding: utf-8 -*-' \
|
||||
'' \
|
||||
'a = Analysis(' \
|
||||
" ['src/Main.py']," \
|
||||
' pathex=[],' \
|
||||
' binaries=[],' \
|
||||
' datas=[' \
|
||||
" ('models/common.onnx', 'ddddocr')," \
|
||||
" ('src/gui/resources/icons/AutoLibrary_Logo_64.ico', 'gui/resources/icons')," \
|
||||
' ],' \
|
||||
' hiddenimports=[],' \
|
||||
' hookspath=[],' \
|
||||
' hooksconfig={},' \
|
||||
' runtime_hooks=[],' \
|
||||
' excludes=[],' \
|
||||
' noarchive=False,' \
|
||||
' optimize=0,' \
|
||||
')' \
|
||||
'pyz = PYZ(a.pure)' \
|
||||
'' \
|
||||
'exe = EXE(' \
|
||||
' pyz,' \
|
||||
' a.scripts,' \
|
||||
' [],' \
|
||||
' exclude_binaries=True,' \
|
||||
" name='AutoLibrary'," \
|
||||
' debug=False,' \
|
||||
' bootloader_ignore_signals=False,' \
|
||||
' strip=False,' \
|
||||
' upx=True,' \
|
||||
' upx_exclude=[],' \
|
||||
' runtime_tmpdir=None,' \
|
||||
' console=False,' \
|
||||
' disable_windowed_traceback=False,' \
|
||||
' argv_emulation=False,' \
|
||||
' target_arch=None,' \
|
||||
' codesign_identity=None,' \
|
||||
' entitlements_file=None,' \
|
||||
" icon=['src/gui/resources/icons/AutoLibrary_Logo_64.ico']," \
|
||||
')' \
|
||||
'' \
|
||||
'coll = COLLECT(' \
|
||||
' exe,' \
|
||||
' a.binaries,' \
|
||||
' a.zipfiles,' \
|
||||
' a.datas,' \
|
||||
' strip=False,' \
|
||||
' upx=True,' \
|
||||
' upx_exclude=[],' \
|
||||
" name='${exe_name}'," \
|
||||
')' \
|
||||
'' \
|
||||
'app = BUNDLE(' \
|
||||
' coll,' \
|
||||
" name='AutoLibrary.app'," \
|
||||
" icon='src/gui/resources/icons/AutoLibrary_Logo.icns'," \
|
||||
" bundle_identifier='com.kenanzhu.autolibrary'," \
|
||||
' info_plist={' \
|
||||
" 'NSHighResolutionCapable': 'True'," \
|
||||
" 'CFBundleName': 'AutoLibrary'," \
|
||||
" 'CFBundleDisplayName': 'AutoLibrary'," \
|
||||
" 'CFBundleShortVersionString': '${version}'," \
|
||||
" 'CFBundleVersion': '${version}'," \
|
||||
" 'CFBundleExecutable': 'AutoLibrary'," \
|
||||
" 'NSPrincipalClass': 'NSApplication'," \
|
||||
" 'LSMinimumSystemVersion': '11.0'," \
|
||||
" 'NSRequiresAquaSystemAppearance': 'False'," \
|
||||
" 'NSHumanReadableCopyright': 'Copyright 2025 - 2026 KenanZhu. All rights reserved.'," \
|
||||
' },' \
|
||||
')' \
|
||||
> Main.spec
|
||||
|
||||
echo "✓ Main.spec generated successfully"
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "Generated Main.spec"
|
||||
echo "========================================"
|
||||
cat Main.spec
|
||||
echo "========================================"
|
||||
|
||||
- name: Build with PyInstaller
|
||||
run: |
|
||||
python -m PyInstaller Main.spec
|
||||
|
||||
- name: Create DMG
|
||||
run: |
|
||||
tag_name="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
dmg_name="AutoLibrary.$tag_name-macos-arm64.dmg"
|
||||
app_path="dist/AutoLibrary.app"
|
||||
|
||||
if [ ! -d "$app_path" ]; then
|
||||
echo "✗ App bundle not found: $app_path"
|
||||
echo "Files in dist directory:"
|
||||
ls -la dist/
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Creating DMG from: $app_path"
|
||||
xattr -cr "$app_path" 2>/dev/null || true
|
||||
|
||||
tmp_dmg_dir=$(mktemp -d)
|
||||
cp -R "$app_path" "$tmp_dmg_dir/"
|
||||
ln -s /Applications "$tmp_dmg_dir/Applications"
|
||||
|
||||
hdiutil create \
|
||||
-volname "AutoLibrary $tag_name" \
|
||||
-srcfolder "$tmp_dmg_dir" \
|
||||
-ov \
|
||||
-format UDZO \
|
||||
"$dmg_name"
|
||||
|
||||
rm -rf "$tmp_dmg_dir"
|
||||
|
||||
if [ -f "$dmg_name" ]; then
|
||||
dmg_size=$(du -h "$dmg_name" | cut -f1)
|
||||
echo "✓ DMG created: $dmg_name (Size: $dmg_size)"
|
||||
else
|
||||
echo "✗ Failed to create DMG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✓ Artifacts ready:"
|
||||
echo " - $dmg_name"
|
||||
echo " - $app_path"
|
||||
|
||||
- name: Archive artifacts
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-macos-arm64
|
||||
path: |
|
||||
AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-macos-arm64.dmg
|
||||
dist/AutoLibrary.app/**
|
||||
retention-days: 7
|
||||
|
||||
- name: Upload build summary
|
||||
run: |
|
||||
tag_name="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
version="${{ steps.get_version.outputs.VERSION }}"
|
||||
dmg_name="AutoLibrary.$tag_name-macos-arm64.dmg"
|
||||
|
||||
{
|
||||
echo "## Build Test Summary (macOS)"
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "✓ Pull request build test completed successfully!"
|
||||
echo "- Version: $version"
|
||||
echo "- Tag: $tag_name"
|
||||
echo "- Pull Request #${{ github.event.pull_request.number || 'N/A' }}"
|
||||
echo "- Branch: ${{ github.event.pull_request.head.ref || github.ref }}"
|
||||
echo "- Event: ${{ github.event_name }}"
|
||||
echo "- DMG: $dmg_name"
|
||||
echo ""
|
||||
echo "### How to test on macOS"
|
||||
echo '1. Download the DMG artifact'
|
||||
echo '2. Open the DMG and drag AutoLibrary.app to /Applications'
|
||||
echo '3. Right-click → Open the app (to bypass Gatekeeper)'
|
||||
} >> $GITHUB_STEP_SUMMARY
|
||||
+325
-19
@@ -1,7 +1,10 @@
|
||||
name: Build
|
||||
|
||||
# This workflow compiles the application for Windows platform using PyInstaller, and
|
||||
# archives the built artifacts as 'AutoLibrary.<tag_name>-windows-x86_64.zip'.
|
||||
# This workflow compiles the application for Windows and macOS platforms using
|
||||
# PyInstaller, and archives the built artifacts.
|
||||
#
|
||||
# - Windows: AutoLibrary.<tag_name>-windows-x86_64.zip
|
||||
# - macOS: AutoLibrary.<tag_name>-macos-arm64.dmg
|
||||
#
|
||||
# It is triggered when called by the release workflow.
|
||||
|
||||
@@ -76,20 +79,22 @@ jobs:
|
||||
run: |
|
||||
$versionInfoFile = "src/gui/ALVersionInfo.py"
|
||||
Write-Host "Verifying $versionInfoFile content:"
|
||||
Write-Host "=================================="
|
||||
Write-Host "========================================"
|
||||
Get-Content $versionInfoFile | Write-Host
|
||||
Write-Host "=================================="
|
||||
Write-Host "========================================"
|
||||
shell: pwsh
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirement.txt
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
@@ -161,7 +166,7 @@ jobs:
|
||||
" binaries=[],"
|
||||
" datas=["
|
||||
" ('models\\common.onnx', 'ddddocr'),"
|
||||
" ('src\\gui\\resources\\icons\\AutoLibrary_32x32.ico', 'gui\\resources\\icons'),"
|
||||
" ('src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico', 'gui\\resources\\icons'),"
|
||||
" ],"
|
||||
" hiddenimports=[],"
|
||||
" hookspath=[],"
|
||||
@@ -189,7 +194,7 @@ jobs:
|
||||
" target_arch=None,"
|
||||
" codesign_identity=None,"
|
||||
" entitlements_file=None,"
|
||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_32x32.ico'],"
|
||||
" icon=['src\\gui\\resources\\icons\\AutoLibrary_Logo_64.ico'],"
|
||||
")"
|
||||
""
|
||||
"coll = COLLECT("
|
||||
@@ -205,9 +210,11 @@ jobs:
|
||||
$specLines | Out-File -FilePath "Main.spec" -Encoding UTF8
|
||||
|
||||
Write-Host "✓ Main.spec (non-single file) generated successfully"
|
||||
Write-Host "`nGenerated Main.spec ============"
|
||||
Write-Host "`n========================================"
|
||||
Write-Host "Generated Main.spec"
|
||||
Write-Host "========================================"
|
||||
Get-Content "Main.spec" | Write-Host
|
||||
Write-Host "==================================`n"
|
||||
Write-Host "========================================`n"
|
||||
shell: pwsh
|
||||
|
||||
- name: Build with PyInstaller
|
||||
@@ -222,7 +229,7 @@ jobs:
|
||||
$distDir = "dist/AutoLibrary-$version"
|
||||
$zipName = "AutoLibrary.$tagName-windows-x86_64.zip"
|
||||
|
||||
echo "ZIP_NAME=$zipName" >> $env:GITHUB_OUTPUT
|
||||
"ZIP_NAME=$zipName" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
|
||||
|
||||
Write-Host "Looking for distribution directory: $distDir"
|
||||
if (Test-Path $distDir) {
|
||||
@@ -242,16 +249,315 @@ jobs:
|
||||
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-windows-x86_64
|
||||
path: |
|
||||
${{ steps.zip_release.outputs.ZIP_NAME }}
|
||||
retention-days: ${{ github.event_name != 'workflow_call' && 7 || 90 }}
|
||||
retention-days: ${{ inputs.is_test == 'true' && 7 || 90 }}
|
||||
|
||||
- name: Upload build summary
|
||||
if: ${{ github.event_name != 'workflow_call' }}
|
||||
if: ${{ inputs.is_test == 'true' }}
|
||||
run: |
|
||||
Write-Host "## Build Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||
Write-Host "" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "✓ Build test completed successfully!" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Version: ${{ steps.get_version.outputs.VERSION }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Event: ${{ github.event_name }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
Write-Host "- Ref: ${{ github.ref }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"## Build Summary" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8
|
||||
"" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"========================================" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"✓ Build test completed successfully!" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Version: ${{ steps.get_version.outputs.VERSION }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Event: ${{ github.event_name }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
"- Ref: ${{ github.ref }}" | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Encoding utf8 -Append
|
||||
shell: pwsh
|
||||
|
||||
#
|
||||
# Build macOS
|
||||
#
|
||||
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.ref }}
|
||||
|
||||
- name: Download build version of ALVersionInfo.py
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: updated-version-info-for-build
|
||||
path: src/gui/
|
||||
|
||||
- name: Get version info
|
||||
id: get_version
|
||||
run: |
|
||||
is_test="${{ inputs.is_test }}"
|
||||
if [ "$is_test" = "true" ]; then
|
||||
version="test"
|
||||
tag_name="test"
|
||||
echo "✓ Mode: Test Build"
|
||||
else
|
||||
version="${{ inputs.version }}"
|
||||
tag_name="${{ inputs.tag_name }}"
|
||||
|
||||
if [ -z "$version" ]; then
|
||||
version="test"
|
||||
tag_name="test"
|
||||
echo "✓ Mode: Independent Build (No inputs provided)"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "✓ Tag: $tag_name"
|
||||
echo "✓ Version: $version"
|
||||
|
||||
echo "VERSION=$version" >> $GITHUB_OUTPUT
|
||||
echo "TAG_NAME=$tag_name" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Verify 'ALVersionInfo.py' was updated
|
||||
run: |
|
||||
version_info_file="src/gui/ALVersionInfo.py"
|
||||
echo "Verifying $version_info_file content:"
|
||||
echo "========================================"
|
||||
cat "$version_info_file"
|
||||
echo "========================================"
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.13'
|
||||
cache: 'pip'
|
||||
cache-dependency-path: requirements.txt
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r requirements.txt
|
||||
|
||||
- name: Solve ddddocr compatibility and copy model files
|
||||
run: |
|
||||
ddddocr_path=$(python -c "import ddddocr, os; print(os.path.dirname(ddddocr.__file__))")
|
||||
echo "ddddocr package location: $ddddocr_path"
|
||||
|
||||
init_file="$ddddocr_path/__init__.py"
|
||||
if [ -f "$init_file" ]; then
|
||||
echo "Fixing ddddocr compatibility in: $init_file"
|
||||
# macOS 使用 BSD sed,要求 -i 后跟备份后缀名(空字符串 = 不备份)
|
||||
sed -i '' 's/Image\.ANTIALIAS/Image.Resampling.LANCZOS/g' "$init_file"
|
||||
echo "✓ Fixed: Image.ANTIALIAS -> Image.Resampling.LANCZOS"
|
||||
else
|
||||
echo "✗ ddddocr __init__.py not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p models
|
||||
echo "✓ Created models directory"
|
||||
|
||||
# 多路径 fallback 搜索 ONNX 模型,提升 ddddocr 版本兼容性
|
||||
onnx_source=""
|
||||
onnx_dest="models/common.onnx"
|
||||
candidate_paths=(
|
||||
"$ddddocr_path/common.onnx"
|
||||
"$ddddocr_path/models/common.onnx"
|
||||
"$ddddocr_path/ddddocr/common.onnx"
|
||||
)
|
||||
for candidate in "${candidate_paths[@]}"; do
|
||||
if [ -f "$candidate" ]; then
|
||||
onnx_source="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
# 若以上候选均未命中,回退到全包搜索
|
||||
if [ -z "$onnx_source" ]; then
|
||||
echo "⚠ 未在已知路径找到 ONNX 模型,回退到全包搜索..."
|
||||
onnx_source=$(find "$ddddocr_path" -name "*.onnx" -type f 2>/dev/null | head -1)
|
||||
fi
|
||||
|
||||
if [ -n "$onnx_source" ] && [ -f "$onnx_source" ]; then
|
||||
cp "$onnx_source" "$onnx_dest"
|
||||
echo "✓ ONNX model copied: $onnx_source -> $onnx_dest"
|
||||
else
|
||||
echo "✗ ONNX model not found in ddddocr package"
|
||||
echo " Searched directory: $ddddocr_path"
|
||||
ls -la "$ddddocr_path/" || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -f "$onnx_dest" ]; then
|
||||
file_size=$(du -h "$onnx_dest" | cut -f1)
|
||||
echo "✓ Model file verified: $onnx_dest (Size: $file_size)"
|
||||
else
|
||||
echo "✗ Failed to copy model file"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Compile Qt Resource files
|
||||
run: |
|
||||
cd batchs
|
||||
bash compile_rc.sh
|
||||
|
||||
- name: Compile Qt UI files
|
||||
run: |
|
||||
cd batchs
|
||||
bash compile_ui.sh
|
||||
|
||||
- name: Generate 'Main.spec'
|
||||
env:
|
||||
APP_VERSION: ${{ steps.get_version.outputs.VERSION }}
|
||||
run: |
|
||||
version="$APP_VERSION"
|
||||
exe_name="AutoLibrary-$version"
|
||||
echo "Generating Main.spec for version: $version"
|
||||
echo "App name: $exe_name"
|
||||
|
||||
printf '%s\n' \
|
||||
'# -*- mode: python ; coding: utf-8 -*-' \
|
||||
'' \
|
||||
'a = Analysis(' \
|
||||
" ['src/Main.py']," \
|
||||
' pathex=[],' \
|
||||
' binaries=[],' \
|
||||
' datas=[' \
|
||||
" ('models/common.onnx', 'ddddocr')," \
|
||||
" ('src/gui/resources/icons/AutoLibrary_Logo_64.ico', 'gui/resources/icons')," \
|
||||
' ],' \
|
||||
' hiddenimports=[],' \
|
||||
' hookspath=[],' \
|
||||
' hooksconfig={},' \
|
||||
' runtime_hooks=[],' \
|
||||
' excludes=[],' \
|
||||
' noarchive=False,' \
|
||||
' optimize=0,' \
|
||||
')' \
|
||||
'pyz = PYZ(a.pure)' \
|
||||
'' \
|
||||
'exe = EXE(' \
|
||||
' pyz,' \
|
||||
' a.scripts,' \
|
||||
' [],' \
|
||||
' exclude_binaries=True,' \
|
||||
" name='AutoLibrary'," \
|
||||
' debug=False,' \
|
||||
' bootloader_ignore_signals=False,' \
|
||||
' strip=False,' \
|
||||
' upx=True,' \
|
||||
' upx_exclude=[],' \
|
||||
' runtime_tmpdir=None,' \
|
||||
' console=False,' \
|
||||
' disable_windowed_traceback=False,' \
|
||||
' argv_emulation=False,' \
|
||||
' target_arch=None,' \
|
||||
' codesign_identity=None,' \
|
||||
' entitlements_file=None,' \
|
||||
" icon=['src/gui/resources/icons/AutoLibrary_Logo_64.ico']," \
|
||||
')' \
|
||||
'' \
|
||||
'coll = COLLECT(' \
|
||||
' exe,' \
|
||||
' a.binaries,' \
|
||||
' a.zipfiles,' \
|
||||
' a.datas,' \
|
||||
' strip=False,' \
|
||||
' upx=True,' \
|
||||
' upx_exclude=[],' \
|
||||
" name='${exe_name}'," \
|
||||
')' \
|
||||
'' \
|
||||
'app = BUNDLE(' \
|
||||
' coll,' \
|
||||
" name='AutoLibrary.app'," \
|
||||
" icon='src/gui/resources/icons/AutoLibrary_Logo.icns'," \
|
||||
" bundle_identifier='com.kenanzhu.autolibrary'," \
|
||||
' info_plist={' \
|
||||
" 'NSHighResolutionCapable': 'True'," \
|
||||
" 'CFBundleName': 'AutoLibrary'," \
|
||||
" 'CFBundleDisplayName': 'AutoLibrary'," \
|
||||
" 'CFBundleShortVersionString': '${version}'," \
|
||||
" 'CFBundleVersion': '${version}'," \
|
||||
" 'CFBundleExecutable': 'AutoLibrary'," \
|
||||
" 'NSPrincipalClass': 'NSApplication'," \
|
||||
" 'LSMinimumSystemVersion': '11.0'," \
|
||||
" 'NSRequiresAquaSystemAppearance': 'False'," \
|
||||
" 'NSHumanReadableCopyright': 'Copyright 2025 - 2026 KenanZhu. All rights reserved.'," \
|
||||
' },' \
|
||||
')' \
|
||||
> Main.spec
|
||||
|
||||
echo "✓ Main.spec generated successfully"
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "Generated Main.spec"
|
||||
echo "========================================"
|
||||
cat Main.spec
|
||||
echo "========================================"
|
||||
|
||||
- name: Build with PyInstaller
|
||||
run: |
|
||||
python -m PyInstaller Main.spec
|
||||
|
||||
- name: Create DMG
|
||||
run: |
|
||||
tag_name="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
dmg_name="AutoLibrary.$tag_name-macos-arm64.dmg"
|
||||
app_path="dist/AutoLibrary.app"
|
||||
|
||||
if [ ! -d "$app_path" ]; then
|
||||
echo "✗ App bundle not found: $app_path"
|
||||
echo "Files in dist directory:"
|
||||
ls -la dist/
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Creating DMG from: $app_path"
|
||||
xattr -cr "$app_path" 2>/dev/null || true
|
||||
|
||||
tmp_dmg_dir=$(mktemp -d)
|
||||
cp -R "$app_path" "$tmp_dmg_dir/"
|
||||
ln -s /Applications "$tmp_dmg_dir/Applications"
|
||||
|
||||
hdiutil create \
|
||||
-volname "AutoLibrary $tag_name" \
|
||||
-srcfolder "$tmp_dmg_dir" \
|
||||
-ov \
|
||||
-format UDZO \
|
||||
"$dmg_name"
|
||||
|
||||
rm -rf "$tmp_dmg_dir"
|
||||
|
||||
if [ -f "$dmg_name" ]; then
|
||||
dmg_size=$(du -h "$dmg_name" | cut -f1)
|
||||
echo "✓ DMG created: $dmg_name (Size: $dmg_size)"
|
||||
else
|
||||
echo "✗ Failed to create DMG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✓ Artifacts ready:"
|
||||
echo " - $dmg_name"
|
||||
echo " - $app_path"
|
||||
|
||||
- name: Archive artifacts
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-macos-arm64
|
||||
path: |
|
||||
AutoLibrary.${{ steps.get_version.outputs.TAG_NAME }}-macos-arm64.dmg
|
||||
dist/AutoLibrary.app/**
|
||||
retention-days: ${{ inputs.is_test == 'true' && 7 || 90 }}
|
||||
|
||||
- name: Upload build summary
|
||||
if: ${{ inputs.is_test == 'true' }}
|
||||
run: |
|
||||
tag_name="${{ steps.get_version.outputs.TAG_NAME }}"
|
||||
version="${{ steps.get_version.outputs.VERSION }}"
|
||||
dmg_name="AutoLibrary.$tag_name-macos-arm64.dmg"
|
||||
|
||||
{
|
||||
echo "## Build Summary (macOS)"
|
||||
echo ""
|
||||
echo "========================================"
|
||||
echo "✓ Build test completed successfully!"
|
||||
echo "- Version: $version"
|
||||
echo "- Tag: $tag_name"
|
||||
echo "- Event: ${{ github.event_name }}"
|
||||
echo "- Ref: ${{ github.ref }}"
|
||||
echo "- DMG: $dmg_name"
|
||||
echo ""
|
||||
echo "### How to test on macOS"
|
||||
echo '1. Download the DMG artifact'
|
||||
echo '2. Open the DMG and drag AutoLibrary.app to /Applications'
|
||||
echo '3. Right-click → Open the app (to bypass Gatekeeper)'
|
||||
} >> $GITHUB_STEP_SUMMARY
|
||||
@@ -83,7 +83,9 @@ jobs:
|
||||
|
||||
echo "✓ File replaced: $FILE_PATH"
|
||||
echo ""
|
||||
echo "Updated file content ==================="
|
||||
echo "========================================"
|
||||
echo "Updated file content"
|
||||
echo "========================================"
|
||||
cat "$FILE_PATH"
|
||||
echo "========================================"
|
||||
|
||||
@@ -151,3 +153,9 @@ jobs:
|
||||
COMMIT_SHA=$(git rev-parse --short HEAD)
|
||||
echo "commit_sha=$COMMIT_SHA" >> $GITHUB_OUTPUT
|
||||
echo "✓ New commit SHA: $COMMIT_SHA"
|
||||
echo "## Commit Release Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "========================================" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Version: ${{ inputs.version }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Tag: ${{ inputs.tag_name }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Commit SHA: $COMMIT_SHA" >> $GITHUB_STEP_SUMMARY
|
||||
@@ -21,8 +21,10 @@ name: Release
|
||||
# Commits version changes to release branch and creates the release tag.
|
||||
|
||||
# 4. Build:
|
||||
# Compiles the application for Windows platform using PyInstaller, and
|
||||
# archives the built artifacts as 'AutoLibrary.<tag_name>-windows-x86_64.zip'.
|
||||
# Compiles the application for Windows and macOS platforms using PyInstaller, and
|
||||
# archives the built artifacts.
|
||||
# - Windows: AutoLibrary.<tag_name>-windows-x86_64.zip
|
||||
# - macOS: AutoLibrary.<tag_name>-macos-arm64.dmg
|
||||
|
||||
# 5. Release:
|
||||
# Creates GitHub release with generated artifacts and release notes
|
||||
@@ -47,7 +49,7 @@ on:
|
||||
jobs:
|
||||
#
|
||||
# Start :
|
||||
# virtual job that indacates the start of the release process
|
||||
# virtual job that indicates the start of the release process
|
||||
#
|
||||
|
||||
start:
|
||||
@@ -158,7 +160,7 @@ jobs:
|
||||
needs:
|
||||
- update-version
|
||||
- commit-release
|
||||
if: always() && needs.update-version.result == 'success' && needs.commit-release.result == 'success'
|
||||
if: always() && needs.update-version.result == 'success' && (needs.commit-release.result == 'success' || needs.commit-release.result == 'skipped')
|
||||
uses: ./.github/workflows/build.yml
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -181,12 +183,18 @@ jobs:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- name: Download artifacts
|
||||
- name: Download Windows artifacts
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-windows-x86_64
|
||||
path: artifacts/
|
||||
|
||||
- name: Download macOS artifacts
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-macos-arm64
|
||||
path: artifacts/
|
||||
|
||||
- name: Create release
|
||||
id: create_release
|
||||
uses: softprops/action-gh-release@v2
|
||||
@@ -195,6 +203,7 @@ jobs:
|
||||
name: AutoLibrary ${{ needs.extract-version.outputs.tag_name }}
|
||||
files: |
|
||||
artifacts/AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-windows-x86_64.zip
|
||||
artifacts/AutoLibrary.${{ needs.extract-version.outputs.tag_name }}-macos-arm64.dmg
|
||||
draft: false
|
||||
prerelease: ${{ needs.extract-version.outputs.is_rc == 'true' }}
|
||||
generate_release_notes: true
|
||||
@@ -205,7 +214,7 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# End :
|
||||
# virtual job that indacates the end of the release process
|
||||
# virtual job that indicates the end of the release process
|
||||
#
|
||||
|
||||
end:
|
||||
@@ -227,7 +236,7 @@ jobs:
|
||||
- release
|
||||
- extract-version
|
||||
- commit-release
|
||||
if: ${{ needs.release.result == 'success' && needs.commit-release.result == 'success' }}
|
||||
if: ${{ needs.release.result == 'success' && (needs.commit-release.result == 'success' || needs.commit-release.result == 'skipped') }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -267,9 +276,13 @@ jobs:
|
||||
git checkout ${MAIN_BRANCH}
|
||||
|
||||
# Show branch status before merge
|
||||
echo "=== Branch status before merge ==="
|
||||
echo "========================================"
|
||||
echo "Branch status before merge"
|
||||
echo "========================================"
|
||||
git log --oneline --graph --all -5
|
||||
echo "=== Diff between ${MAIN_BRANCH} and origin/${BRANCH_NAME} ==="
|
||||
echo "========================================"
|
||||
echo "Diff: ${MAIN_BRANCH} vs origin/${BRANCH_NAME}"
|
||||
echo "========================================"
|
||||
git diff ${MAIN_BRANCH} origin/${BRANCH_NAME} --stat || echo "No differences found"
|
||||
|
||||
# Force create a merge commit even if there are no changes
|
||||
@@ -279,7 +292,9 @@ jobs:
|
||||
-m "chore(release): merge ${BRANCH_NAME} to ${MAIN_BRANCH} [auto release commit]"
|
||||
|
||||
# Show merge result
|
||||
echo "=== Merge result ==="
|
||||
echo "========================================"
|
||||
echo "Merge result"
|
||||
echo "========================================"
|
||||
git log --oneline --graph -3
|
||||
|
||||
# Push to main
|
||||
@@ -310,6 +325,7 @@ jobs:
|
||||
|
||||
echo "## Release Cleanup Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "========================================" >> $GITHUB_STEP_SUMMARY
|
||||
echo "✓ Release completed successfully!" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "### Actions Performed:" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
@@ -128,10 +128,15 @@ jobs:
|
||||
echo "Build version file location: $VER_INFO_BUILDFILE"
|
||||
echo "Commit version file location: $VER_INFO_COMMITFILE"
|
||||
echo ""
|
||||
echo "Build version ALVersionInfo.py content ="
|
||||
echo "========================================"
|
||||
echo "Build version ALVersionInfo.py"
|
||||
echo "========================================"
|
||||
cat "$VER_INFO_BUILDFILE"
|
||||
echo "========================================"
|
||||
echo ""
|
||||
echo "Commit version ALVersionInfo.py content "
|
||||
echo "========================================"
|
||||
echo "Commit version ALVersionInfo.py"
|
||||
echo "========================================"
|
||||
cat "$VER_INFO_COMMITFILE"
|
||||
echo "========================================"
|
||||
|
||||
@@ -140,11 +145,16 @@ jobs:
|
||||
run: |
|
||||
if git diff --quiet src/gui/ALVersionInfo.py; then
|
||||
echo "has_changes=false" >> $GITHUB_OUTPUT
|
||||
echo "! No changes detected in ALVersionInfo.py"
|
||||
echo "⚠ No changes detected in ALVersionInfo.py"
|
||||
else
|
||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
||||
echo "✓ ALVersionInfo.py has been modified"
|
||||
fi
|
||||
echo "## Update Version Summary" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "========================================" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Version: ${{ steps.get_version.outputs.VERSION }}" >> $GITHUB_STEP_SUMMARY
|
||||
echo "- Tag: ${{ steps.get_version.outputs.TAG_NAME }}" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
- name: Upload modified ALVersionInfo.py ready for build
|
||||
if: steps.check_changes.outputs.has_changes == 'true'
|
||||
|
||||
File renamed without changes.
+19
-10
@@ -17,15 +17,24 @@
|
||||
|
||||
### 功能
|
||||
|
||||
#### 核心特性
|
||||
|
||||
1. 自动预约 - 支持自动预约
|
||||
2. 自动续约 - 支持自动续约
|
||||
3. 自动签到 - 支持自动签到
|
||||
4. 远程签到 - 支持远程签到,无需在图书馆网络环境下即可签到
|
||||
5. 批量操作 - 支持同时预约多个用户,可以指定当前需要跳过的用户,并将用户分成多个组
|
||||
6. 定时任务 - 使用内置定时任务管理,添加定时任务,指定时间后按当前预约信息自动运行,支持设置重复任务
|
||||
7. 驱动管理 - 内置浏览器驱动自动管理,支持自动检测浏览器版本并下载对应驱动,无需手动下载
|
||||
|
||||
*具体操作方法和注意事项请访问我们的 [帮助手册](https://www.autolibrary.kenanzhu.com/manuals)*
|
||||
#### 辅助特性
|
||||
|
||||
1. 批量操作 - 支持同时预约多个用户,可以指定当前需要跳过的用户,并将用户分成多个组
|
||||
2. 定时任务 - 使用内置定时任务管理,添加定时任务,指定时间后按当前预约信息自动运行,支持设置重复任务
|
||||
3. 驱动管理 - 内置浏览器驱动自动管理,支持自动检测浏览器版本并下载对应驱动,无需手动下载
|
||||
4. 自定义主题 - 支持深浅色主题切换,多款应用样式切换,可导入 .altheme 自定义主题一键换肤
|
||||
|
||||
> [!TIP]
|
||||
> 前往 [主题市场](https://www.autolibrary.kenanzhu.com/marketplace) 获取和分享更多自定义主题。
|
||||
|
||||
*具体操作方法和注意事项请访问我们的 [帮助手册](https://manuals.autolibrary.kenanzhu.com)*
|
||||
|
||||
### 如何使用
|
||||
|
||||
@@ -39,7 +48,7 @@
|
||||
|
||||
#### 平台支持 & 编译步骤
|
||||
|
||||
本工具目前仅支持 Windows 平台,由于使用 PySide6 库开发,理论上是可以自行编译并在 Linux 和 macOS 上运行,这里提供简单的编译步骤:
|
||||
本工具目前支持 Windows 和 macOS(Apple Silicon)平台,由于使用 PySide6 库开发,理论上是可以自行编译并在 Linux 和旧架构 macOS 上运行,这里提供简单的编译步骤:
|
||||
|
||||
1. 确保系统安装了 Python 3.13 版本 (推荐,过低或高版本会导致兼容问题)。
|
||||
2. 安装所有依赖库,命令为 `pip install -r requirements.txt` (建议在虚拟环境下操作)。
|
||||
@@ -71,7 +80,7 @@ def classification(self, img: bytes):
|
||||
只要确保处于校园网网络环境内,工具都是可以正常运行的。操作处理速度基本上取决于校园网的网络环境,一般情况下在 3-4 秒(不考虑硬件差异)左右即可完成一个用户的操作,完全满足正常使用需求。
|
||||
|
||||
> [!NOTE]
|
||||
> 工具仅作为正常的预约,签到和续约的图书馆辅助工具,请勿干扰图书馆的正常运行(如故意预约多个座位,或同时预约大量的用户等,对此影响图书馆正常运行本工具概不负责,请在善用工具方便自己的情况下尽量不用影响其他同学的使用)。
|
||||
> 工具仅作为正常的预约,签到和续约的图书馆辅助工具,请勿干扰图书馆的正常运行(如故意预约多个座位,或同时预约大量的用户等)由此影响图书馆正常运行的情况本工具概不负责,请在善用工具方便自己的情况下尽量不用影响其他同学的使用。
|
||||
|
||||
#### 关于批量操作
|
||||
|
||||
@@ -97,13 +106,13 @@ def classification(self, img: bytes):
|
||||
|
||||
#### 会有手机端的版本吗?
|
||||
|
||||
暂时没有考虑,而且也没有足够的时间和能力开发多平台的版本并测试维护,所以暂时只提供 Windows 版本。
|
||||
暂时没有考虑,而且也没有足够的时间和能力开发多平台的版本并测试维护,所以暂时只提供 Windows 和 macOS(Apple Silicon)版本。
|
||||
|
||||
#### 后续会有哪些功能?
|
||||
|
||||
当前版本的功能对于正常使用已经足够,不过后续会着重完善预约时的使用体验,暂时有以下构想:
|
||||
|
||||
- 引入交互预约面板功能,预约时直接在座位分布图中选择可用座位,并按用户分配,无需事先配置预约信息。
|
||||
- ~~引入交互预约面板功能,预约时直接在座位分布图中选择可用座位,并按用户分配,无需事先配置预约信息。~~ (不计划)
|
||||
- ~~优化定时任务管理功能,用户可以在定时任务管理界面设置重复运行的定时任务,如每日预约、每周预约等。~~ (已完成)
|
||||
- 软件的自动更新以及公告栏功能,用户可以自动更新最新版本并获取最新公告事项。
|
||||
|
||||
@@ -111,8 +120,8 @@ def classification(self, img: bytes):
|
||||
|
||||
#### 其他功能建议?
|
||||
|
||||
如果你有其他功能建议,或者遇到了什么功能性,操作上的问题,欢迎提交 Issue 到本项目。
|
||||
如果你有足够的开发能力,欢迎为本项目提交 PR,也可以 Fork 本项目,根据自己的需求进行修改和完善。
|
||||
如果你有其他功能建议,或者遇到了什么功能性,操作上的问题,欢迎提交 [Issue](https://github.com/KenanZhu/AutoLibrary/issues) 到本项目。
|
||||
如果你有足够的开发能力,欢迎为本项目提交 [PR](https://github.com/KenanZhu/AutoLibrary/pulls) ,也可以 Fork 本项目,根据自己的需求进行修改和完善。
|
||||
|
||||
### 联系我
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -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
|
||||
File renamed without changes.
Binary file not shown.
@@ -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
|
||||
@@ -24,7 +24,6 @@ def main():
|
||||
translator = QTranslator()
|
||||
if translator.load(":/res/translators/qtbase_zh_CN.ts"):
|
||||
app.installTranslator(translator)
|
||||
app.setStyle("Fusion")
|
||||
app.setApplicationName("AutoLibrary")
|
||||
if not initializeApp():
|
||||
sys.exit(-1)
|
||||
|
||||
@@ -7,17 +7,9 @@ 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.ASEngine import ASEngine
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ASEngine",
|
||||
"createEngine",
|
||||
"createMockTargetData",
|
||||
"createAllVariablesTable",
|
||||
"createTargetVarDefs",
|
||||
]
|
||||
from .ASEngine import ASEngine
|
||||
|
||||
__version__ = "1.0.0" # autoscript version
|
||||
|
||||
_TARGET_VAR_DEFS = [
|
||||
("USERNAME", "String", ["username"], "用户名"),
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ import logging
|
||||
import queue
|
||||
import datetime
|
||||
|
||||
import managers.log.LogManager as LogManager
|
||||
from managers.log.LogManager import getLogger
|
||||
|
||||
|
||||
class MsgBase:
|
||||
@@ -54,7 +54,7 @@ class MsgBase:
|
||||
self._input_queue = input_queue
|
||||
self._output_queue = output_queue
|
||||
try:
|
||||
self._logger = LogManager.getLogger(self._class_name)
|
||||
self._logger = getLogger(self._class_name)
|
||||
except RuntimeError:
|
||||
self._logger = None
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Base module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- MsgBase: Base class for messages.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -10,10 +10,16 @@ See the LICENSE file for details.
|
||||
import os
|
||||
|
||||
from PySide6.QtCore import QStandardPaths, QDir
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from managers.log.LogManager import instance as logInstance
|
||||
from interfaces.ConfigProvider import CfgKey
|
||||
from managers.config.ConfigManager import instance as configInstance
|
||||
from managers.driver.WebDriverManager import instance as webdriverInstance
|
||||
from managers.log.LogManager import instance as logInstance
|
||||
from managers.theme.ThemeManager import(
|
||||
setActiveStyle,
|
||||
instance as themeInstance
|
||||
)
|
||||
|
||||
|
||||
def _initializeLogManager(
|
||||
@@ -64,13 +70,36 @@ def _initializeWebDriverManager(
|
||||
webdriverInstance(driver_dir)
|
||||
return True
|
||||
|
||||
def _initializeAppearance(
|
||||
):
|
||||
|
||||
logger = logInstance().getLogger("AppInitializer")
|
||||
|
||||
app = QApplication.instance()
|
||||
if not app:
|
||||
return
|
||||
cfg = configInstance()
|
||||
saved_style = cfg.get(CfgKey.GLOBAL.APPEARANCE.STYLE, "Fusion")
|
||||
saved_theme = cfg.get(CfgKey.GLOBAL.APPEARANCE.THEME, "system")
|
||||
saved_custom_theme = cfg.get(CfgKey.GLOBAL.APPEARANCE.CUSTOM_THEME, "")
|
||||
app.setStyle(saved_style)
|
||||
setActiveStyle(saved_style)
|
||||
if saved_custom_theme:
|
||||
try:
|
||||
themeInstance().applyTheme(saved_custom_theme)
|
||||
except Exception:
|
||||
logger.warning("无法应用自定义主题 '%s',回退到默认外观", saved_custom_theme)
|
||||
themeInstance().clearTheme(saved_theme)
|
||||
return
|
||||
themeInstance().clearTheme(saved_theme)
|
||||
|
||||
def initializeApp(
|
||||
) -> bool:
|
||||
"""
|
||||
Initialize the application components
|
||||
|
||||
Order:
|
||||
LogManager -> ConfigManager -> WebDriverManager
|
||||
LogManager -> ConfigManager -> WebDriverManager -> Appearance
|
||||
"""
|
||||
|
||||
if not _initializeLogManager():
|
||||
@@ -79,4 +108,5 @@ def initializeApp(
|
||||
return False
|
||||
if not _initializeWebDriverManager():
|
||||
return False
|
||||
_initializeAppearance()
|
||||
return True
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Boot module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- AppInitializer: Application initializer class.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
+81
-33
@@ -16,11 +16,16 @@ from PySide6.QtCore import (
|
||||
from PySide6.QtGui import QIcon
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QDialog
|
||||
QDialog,
|
||||
QTabWidget,
|
||||
QTextBrowser
|
||||
)
|
||||
|
||||
from gui.ALVersionInfo import (
|
||||
AL_VERSION, AL_COMMIT_SHA, AL_COMMIT_DATE, AL_BUILD_DATE
|
||||
AL_VERSION,
|
||||
AL_COMMIT_SHA,
|
||||
AL_COMMIT_DATE,
|
||||
AL_BUILD_DATE
|
||||
)
|
||||
from gui.resources.ui.Ui_ALAboutDialog import Ui_ALAboutDialog
|
||||
from gui.resources import ALResource
|
||||
@@ -43,12 +48,23 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
||||
):
|
||||
|
||||
self.LogoIconLabel.setPixmap(QIcon(":/res/icons/AutoLibrary_Logo_64.svg").pixmap(48, 48))
|
||||
info_text = self.generateAboutText()
|
||||
self.AboutInfoBrowser.setHtml(info_text)
|
||||
browser_font = self.AboutInfoBrowser.font()
|
||||
browser_font.setFamily("Courier New")
|
||||
self.AboutInfoBrowser.setFont(browser_font)
|
||||
self.AboutInfoBrowser.setTextInteractionFlags(Qt.TextBrowserInteraction)
|
||||
self.TabWidget = QTabWidget()
|
||||
self.TabWidget.setDocumentMode(True)
|
||||
AboutBrowser = QTextBrowser()
|
||||
AboutBrowser.setHtml(self.generateAboutText())
|
||||
AboutBrowser.setOpenExternalLinks(True)
|
||||
AboutBrowser.setLineWrapMode(QTextBrowser.LineWrapMode.NoWrap)
|
||||
AboutBrowser.setTextInteractionFlags(Qt.TextBrowserInteraction)
|
||||
browser_font = AboutBrowser.font()
|
||||
browser_font.setFamilies(["Courier New", "Consolas", "Menlo", "DejaVu Sans Mono", "monospace"])
|
||||
AboutBrowser.setFont(browser_font)
|
||||
self.TabWidget.addTab(AboutBrowser, "关于")
|
||||
LicenseBrowser = QTextBrowser()
|
||||
LicenseBrowser.setHtml(self.generateLicenseText())
|
||||
LicenseBrowser.setOpenExternalLinks(True)
|
||||
LicenseBrowser.setTextInteractionFlags(Qt.TextBrowserInteraction)
|
||||
self.TabWidget.addTab(LicenseBrowser, "许可证")
|
||||
self.AboutInfoLayout.addWidget(self.TabWidget)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
@@ -61,33 +77,57 @@ class ALAboutDialog(QDialog, Ui_ALAboutDialog):
|
||||
) -> str:
|
||||
|
||||
os_info = self.getOSInfo()
|
||||
run_on = f"{os_info['system']} {os_info['version']} {os_info['architecture']}"
|
||||
selenium_ver = self.getSeleniumVersion()
|
||||
about_text = f"""
|
||||
<h4>Version Information:</h4>
|
||||
Version: {AL_VERSION}<br>
|
||||
<b style="font-size:14px;">VERSION: {AL_VERSION}</b><br>
|
||||
Commit SHA: {AL_COMMIT_SHA}<br>
|
||||
Commit date: {AL_COMMIT_DATE}<br>
|
||||
Build date: {AL_BUILD_DATE}<br>
|
||||
Python version: {platform.python_version()}<br>
|
||||
Qt version: {self.getQtVersion()}<br>
|
||||
|
||||
<h4>System Information:</h4>
|
||||
<br>
|
||||
<b style="font-size:14px;">SYSTEM</b><br>
|
||||
Running on: {run_on}<br>
|
||||
Processor: {platform.processor()}<br>
|
||||
Operating system: {os_info['system']}<br>
|
||||
System version: {os_info['version']}<br>
|
||||
System architecture: {os_info['architecture']}<br>
|
||||
|
||||
<h4>Project Information:</h4>
|
||||
License: MIT License<br>
|
||||
Project repository: <a href="https://www.github.com/KenanZhu/AutoLibrary" style="text-decoration: none;">https://www.github.com/KenanZhu/AutoLibrary</a><br>
|
||||
Project website: <a href="https://www.autolibrary.kenanzhu.com" style="text-decoration: none;">https://www.autolibrary.kenanzhu.com</a><br>
|
||||
|
||||
<h4>Author Information:</h4>
|
||||
Developer: KenanZhu<br>
|
||||
Contact: nanoki_zh@163.com<br>
|
||||
GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;">https://www.github.com/KenanZhu</a><br>
|
||||
<br>
|
||||
<b style="font-size:14px;">DEPENDENCIES</b><br>
|
||||
Python: {platform.python_version()}<br>
|
||||
Qt(PySide6): {self.getQtVersion()}<br>
|
||||
Selenium: {selenium_ver}<br>
|
||||
<br>
|
||||
<b style="font-size:14px;">PROJECT</b><br>
|
||||
Website: <a href="https://www.autolibrary.kenanzhu.com" style="text-decoration:none;">https://www.autolibrary.kenanzhu.com</a><br>
|
||||
Repository: <a href="https://www.github.com/KenanZhu/AutoLibrary" style="text-decoration:none;">https://www.github.com/KenanZhu/AutoLibrary</a><br>
|
||||
<br>
|
||||
<b style="font-size:14px;">AUTHOR</b><br>
|
||||
Developer/Maintainer: KenanZhu<br>
|
||||
Contact: <a href="mailto:nanoki_zh@163.com">nanoki_zh@163.com</a><br>
|
||||
GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration:none;">https://www.github.com/KenanZhu</a><br>
|
||||
"""
|
||||
return about_text
|
||||
|
||||
def generateLicenseText(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return """
|
||||
<b>MIT License</b>
|
||||
<p>Copyright © 2025 - 2026 KenanZhu</p>
|
||||
<p>Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:</p>
|
||||
<p>The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.</p>
|
||||
<p>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.</p>"""
|
||||
|
||||
def getOSInfo(
|
||||
self
|
||||
):
|
||||
@@ -95,7 +135,6 @@ GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;"
|
||||
system = platform.system()
|
||||
version = platform.version()
|
||||
architecture = platform.architecture()[0]
|
||||
|
||||
if system == "Windows":
|
||||
try:
|
||||
version = platform.win32_ver()[1]
|
||||
@@ -112,7 +151,6 @@ GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;"
|
||||
version = f"{distro.name()} {distro.version()}"
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
return {
|
||||
'system': system,
|
||||
'version': version,
|
||||
@@ -129,13 +167,23 @@ GitHub: <a href="https://www.github.com/KenanZhu" style="text-decoration: none;"
|
||||
except:
|
||||
return "Unknown"
|
||||
|
||||
def getSeleniumVersion(
|
||||
self
|
||||
):
|
||||
|
||||
try:
|
||||
import selenium
|
||||
return selenium.__version__
|
||||
except Exception:
|
||||
return "Unknown"
|
||||
|
||||
def copyAboutInfo(
|
||||
self
|
||||
):
|
||||
|
||||
about_text = self.AboutInfoBrowser.toPlainText()
|
||||
clipboard = QApplication.clipboard()
|
||||
clipboard.setText(about_text)
|
||||
about_text = self.TabWidget.currentWidget().toPlainText()
|
||||
Clipboard = QApplication.clipboard()
|
||||
Clipboard.setText(about_text)
|
||||
original_text = self.CopyButton.text()
|
||||
self.CopyButton.setText("已复制")
|
||||
QTimer.singleShot(2000, lambda: self.CopyButton.setText(original_text))
|
||||
QTimer.singleShot(2000, lambda: self.CopyButton.setText(original_text))
|
||||
+276
-261
@@ -9,6 +9,8 @@ See the LICENSE file for details.
|
||||
"""
|
||||
from copy import deepcopy
|
||||
|
||||
import qtawesome as qta
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QDate,
|
||||
QSize,
|
||||
@@ -20,7 +22,6 @@ from PySide6.QtCore import (
|
||||
from PySide6.QtGui import (
|
||||
QColor,
|
||||
QFont,
|
||||
QIcon,
|
||||
QSyntaxHighlighter,
|
||||
QTextCharFormat,
|
||||
)
|
||||
@@ -74,54 +75,54 @@ class ALScriptHighlighter(QSyntaxHighlighter):
|
||||
super().__init__(parent)
|
||||
self._rules = []
|
||||
|
||||
keywordFmt = QTextCharFormat()
|
||||
keywordFmt.setForeground(QColor("#569CD6"))
|
||||
keywordFmt.setFontWeight(QFont.Weight.Bold)
|
||||
keyword_fmt = QTextCharFormat()
|
||||
keyword_fmt.setForeground(QColor("#569CD6"))
|
||||
keyword_fmt.setFontWeight(QFont.Weight.Bold)
|
||||
for kw in [
|
||||
"if", "elseif", "else", "end", "then",
|
||||
"and", "or", "not",
|
||||
"local", "function", "return", "nil",
|
||||
]:
|
||||
self._rules.append((r"\b" + kw + r"\b", keywordFmt))
|
||||
boolFmt = QTextCharFormat()
|
||||
boolFmt.setForeground(QColor("#4FC1FF"))
|
||||
boolFmt.setFontWeight(QFont.Weight.Bold)
|
||||
self._rules.append((r"\btrue\b", boolFmt))
|
||||
self._rules.append((r"\bfalse\b", boolFmt))
|
||||
cmpFmt = QTextCharFormat()
|
||||
cmpFmt.setForeground(QColor("#C586C0"))
|
||||
cmpFmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((r"\b" + kw + r"\b", keyword_fmt))
|
||||
bool_fmt = QTextCharFormat()
|
||||
bool_fmt.setForeground(QColor("#4FC1FF"))
|
||||
bool_fmt.setFontWeight(QFont.Weight.Bold)
|
||||
self._rules.append((r"\btrue\b", bool_fmt))
|
||||
self._rules.append((r"\bfalse\b", bool_fmt))
|
||||
cmp_fmt = QTextCharFormat()
|
||||
cmp_fmt.setForeground(QColor("#C586C0"))
|
||||
cmp_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
for op in [r"==", r"~=", r">=", r"<=", r">", r"<"]:
|
||||
self._rules.append((op, cmpFmt))
|
||||
arithFmt = QTextCharFormat()
|
||||
arithFmt.setForeground(QColor("#C586C0"))
|
||||
arithFmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((op, cmp_fmt))
|
||||
arith_fmt = QTextCharFormat()
|
||||
arith_fmt.setForeground(QColor("#C586C0"))
|
||||
arith_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
for op in [r"\+", r"-", r"\*", r"/", r"\.\."]:
|
||||
self._rules.append((op, arithFmt))
|
||||
funcFmt = QTextCharFormat()
|
||||
funcFmt.setForeground(QColor("#DCDCAA"))
|
||||
funcFmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((op, arith_fmt))
|
||||
func_fmt = QTextCharFormat()
|
||||
func_fmt.setForeground(QColor("#DCDCAA"))
|
||||
func_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
for fn in [ "time", "date", "datenow", "timenow", "dateadd", "timeadd"]:
|
||||
self._rules.append((r"\b" + fn + r"\b", funcFmt))
|
||||
varFmt = QTextCharFormat()
|
||||
varFmt.setForeground(QColor("#9CDCFE"))
|
||||
varFmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((r"\b" + fn + r"\b", func_fmt))
|
||||
var_fmt = QTextCharFormat()
|
||||
var_fmt.setForeground(QColor("#9CDCFE"))
|
||||
var_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
var_names = [name for _, (name, _) in createAllVariablesTable().items()]
|
||||
for var in var_names:
|
||||
self._rules.append((r"\b" + var + r"\b", varFmt))
|
||||
strFmt = QTextCharFormat()
|
||||
strFmt.setForeground(QColor("#CE9178"))
|
||||
strFmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((r'"[^"]*"', strFmt))
|
||||
self._rules.append((r"'[^']*'", strFmt))
|
||||
numFmt = QTextCharFormat()
|
||||
numFmt.setForeground(QColor("#B5CEA8"))
|
||||
numFmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((r"\b\d+(?:\.\d+)?\b", numFmt))
|
||||
commentFmt = QTextCharFormat()
|
||||
commentFmt.setForeground(QColor("#6A9955"))
|
||||
commentFmt.setFontItalic(True)
|
||||
self._rules.append((r"--[^\n]*", commentFmt))
|
||||
self._rules.append((r"\b" + var + r"\b", var_fmt))
|
||||
st_fmt = QTextCharFormat()
|
||||
st_fmt.setForeground(QColor("#CE9178"))
|
||||
st_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((r'"[^"]*"', st_fmt))
|
||||
self._rules.append((r"'[^']*'", st_fmt))
|
||||
num_fmt = QTextCharFormat()
|
||||
num_fmt.setForeground(QColor("#B5CEA8"))
|
||||
num_fmt.setFontWeight(QFont.Weight.Normal)
|
||||
self._rules.append((r"\b\d+(?:\.\d+)?\b", num_fmt))
|
||||
comment_fmt = QTextCharFormat()
|
||||
comment_fmt.setForeground(QColor("#6A9955"))
|
||||
comment_fmt.setFontItalic(True)
|
||||
self._rules.append((r"--[^\n]*", comment_fmt))
|
||||
|
||||
def highlightBlock(
|
||||
self,
|
||||
@@ -147,22 +148,22 @@ class _DebugResultDialog(QDialog):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("调试运行结果 - AutoLibrary")
|
||||
self.setMinimumSize(600, 200)
|
||||
layout = QVBoxLayout(self)
|
||||
table = QTableWidget(len(changes), 3)
|
||||
table.setHorizontalHeaderLabels(["目标变量", "原始数据", "运行后数据"])
|
||||
table.horizontalHeader().setStretchLastSection(True)
|
||||
table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
|
||||
table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
||||
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})"
|
||||
table.setItem(row, 0, QTableWidgetItem(label))
|
||||
table.setItem(row, 1, QTableWidgetItem(str(before_val)))
|
||||
table.setItem(row, 2, QTableWidgetItem(str(after_val)))
|
||||
layout.addWidget(table)
|
||||
btnBox = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok)
|
||||
btnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
btnBox.accepted.connect(self.accept)
|
||||
layout.addWidget(btnBox)
|
||||
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):
|
||||
@@ -188,14 +189,14 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._fontSize = 21
|
||||
self._mockWidgets = {}
|
||||
self._font_size = 21
|
||||
self._mock_widgets = {}
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
self.textEdit.setPlainText(script)
|
||||
self._highlighter = ALScriptHighlighter(
|
||||
self.textEdit.document()
|
||||
self.TextEdit.setPlainText(script)
|
||||
self._high_lighter = ALScriptHighlighter(
|
||||
self.TextEdit.document()
|
||||
)
|
||||
if mockData:
|
||||
self.setMockData(mockData)
|
||||
@@ -206,104 +207,110 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
|
||||
self.setWindowTitle("AutoScript 编辑 - AutoLibrary")
|
||||
self.setMinimumSize(660, 600)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setSpacing(3)
|
||||
layout.setContentsMargins(3, 3, 3, 3)
|
||||
toolbarLayout = QHBoxLayout()
|
||||
self.zoomInBtn = QPushButton("+")
|
||||
self.zoomInBtn.setFixedSize(25, 25)
|
||||
self.zoomOutBtn = QPushButton("-")
|
||||
self.zoomOutBtn.setFixedSize(25, 25)
|
||||
self.zoomResetBtn = QPushButton("")
|
||||
self.zoomResetBtn.setIcon(QIcon(":/res/icons/Reset.svg"))
|
||||
self.zoomResetBtn.setIconSize(QSize(20, 20))
|
||||
self.zoomResetBtn.setFixedSize(25, 25)
|
||||
self.zoomResetBtn.setToolTip("重置缩放")
|
||||
self.zoomLabel = QLabel(f"{self._fontSize}px")
|
||||
self.zoomLabel.setFixedHeight(25)
|
||||
self.orchBtn = QPushButton("编排")
|
||||
self.orchBtn.setFixedHeight(25)
|
||||
self.orchBtn.setToolTip("可视化生成 AutoScript 代码并插入到光标位置")
|
||||
toolbarLayout.addWidget(self.orchBtn)
|
||||
self.debugBtn = QPushButton("▶ 调试运行")
|
||||
self.debugBtn.setFixedHeight(25)
|
||||
self.debugBtn.setToolTip("使用右侧模拟数据执行脚本,查看目标变量变化")
|
||||
toolbarLayout.addWidget(self.debugBtn)
|
||||
sep = QFrame()
|
||||
sep.setFrameShape(QFrame.Shape.VLine)
|
||||
sep.setFrameShadow(QFrame.Shadow.Sunken)
|
||||
sep.setFixedWidth(1)
|
||||
toolbarLayout.addWidget(sep)
|
||||
toolbarLayout.addWidget(self.zoomInBtn)
|
||||
toolbarLayout.addWidget(self.zoomOutBtn)
|
||||
toolbarLayout.addWidget(self.zoomResetBtn)
|
||||
toolbarLayout.addWidget(self.zoomLabel)
|
||||
toolbarLayout.addStretch()
|
||||
self.copyBtn = QPushButton("")
|
||||
self.copyBtn.setIcon(QIcon(":/res/icons/Copy.svg"))
|
||||
self.copyBtn.setIconSize(QSize(20, 20))
|
||||
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(
|
||||
Layout = QVBoxLayout(self)
|
||||
Layout.setSpacing(3)
|
||||
Layout.setContentsMargins(3, 3, 3, 3)
|
||||
ToolbarLayout = QHBoxLayout()
|
||||
self.ZoomInBtn = QPushButton("")
|
||||
self.ZoomInBtn.setIcon(qta.icon("fa6s.plus", color=self._iconColor()))
|
||||
self.ZoomInBtn.setIconSize(QSize(14, 14))
|
||||
self.ZoomInBtn.setFixedSize(25, 25)
|
||||
self.ZoomOutBtn = QPushButton("")
|
||||
self.ZoomOutBtn.setIcon(qta.icon("fa6s.minus", color=self._iconColor()))
|
||||
self.ZoomOutBtn.setIconSize(QSize(14, 14))
|
||||
self.ZoomOutBtn.setFixedSize(25, 25)
|
||||
self.ZoomResetBtn = QPushButton("")
|
||||
self.ZoomResetBtn.setIcon(qta.icon("fa6s.rotate-left", color=self._iconColor()))
|
||||
self.ZoomResetBtn.setIconSize(QSize(14, 14))
|
||||
self.ZoomResetBtn.setFixedSize(25, 25)
|
||||
self.ZoomResetBtn.setToolTip("重置缩放")
|
||||
self.ZoomLabel = QLabel(f"{self._font_size}px")
|
||||
self.ZoomLabel.setFixedHeight(25)
|
||||
self.OrchBtn = QPushButton("编排")
|
||||
self.OrchBtn.setFixedSize(80, 25)
|
||||
self.OrchBtn.setToolTip("可视化生成 AutoScript 代码并插入到光标位置")
|
||||
ToolbarLayout.addWidget(self.OrchBtn)
|
||||
self.DebugBtn = QPushButton("▶ 调试运行")
|
||||
self.DebugBtn.setFixedSize(80, 25)
|
||||
self.DebugBtn.setToolTip("使用右侧模拟数据执行脚本,查看目标变量变化")
|
||||
ToolbarLayout.addWidget(self.DebugBtn)
|
||||
Sep = QFrame()
|
||||
Sep.setFrameShape(QFrame.Shape.VLine)
|
||||
Sep.setFrameShadow(QFrame.Shadow.Sunken)
|
||||
Sep.setFixedWidth(1)
|
||||
ToolbarLayout.addWidget(Sep)
|
||||
ToolbarLayout.addWidget(self.ZoomInBtn)
|
||||
ToolbarLayout.addWidget(self.ZoomOutBtn)
|
||||
ToolbarLayout.addWidget(self.ZoomResetBtn)
|
||||
ToolbarLayout.addWidget(self.ZoomLabel)
|
||||
ToolbarLayout.addStretch()
|
||||
self.CopyBtn = QPushButton("")
|
||||
self.CopyBtn.setIcon(qta.icon("fa6s.copy", color=self._iconColor()))
|
||||
self.CopyBtn.setIconSize(QSize(14, 14))
|
||||
self.CopyBtn.setFixedSize(25, 25)
|
||||
self.CopyBtn.setToolTip("复制脚本")
|
||||
ToolbarLayout.addWidget(self.CopyBtn)
|
||||
Layout.addLayout(ToolbarLayout)
|
||||
self.TextEdit = _TabToSpacesEditor(self)
|
||||
self.TextEdit.setTabStopDistance(40)
|
||||
self.TextEdit.setLineWrapMode(
|
||||
QPlainTextEdit.LineWrapMode.NoWrap
|
||||
)
|
||||
self.textEdit.setStyleSheet(
|
||||
self.TextEdit.setStyleSheet(
|
||||
"QPlainTextEdit {"
|
||||
" font-family: 'Courier New', 'Consolas', monospace;"
|
||||
f" font-size: {self._fontSize}px;"
|
||||
f" font-size: {self._font_size}px;"
|
||||
"}"
|
||||
)
|
||||
layout.addWidget(self.textEdit)
|
||||
self.createButtonPanel(layout)
|
||||
self.btnBox = QDialogButtonBox(
|
||||
Layout.addWidget(self.TextEdit)
|
||||
self.createButtonPanel(Layout)
|
||||
self.BtnBox = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok |
|
||||
QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
self.btnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.btnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
layout.addWidget(self.btnBox)
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setFixedSize(80, 25)
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setFixedSize(80, 25)
|
||||
Layout.addWidget(self.BtnBox)
|
||||
|
||||
def createButtonPanel(
|
||||
self,
|
||||
parent_layout
|
||||
ParentLayout
|
||||
):
|
||||
|
||||
splitter = QSplitter(Qt.Orientation.Horizontal)
|
||||
tabWidget = QTabWidget()
|
||||
tabWidget.setMaximumHeight(150)
|
||||
basicWidget = QWidget()
|
||||
basicLayout = QGridLayout(basicWidget)
|
||||
basicLayout.setSpacing(4)
|
||||
basicLayout.setContentsMargins(4, 4, 4, 4)
|
||||
basicLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
controlButtons = [
|
||||
Splitter = QSplitter(Qt.Orientation.Horizontal)
|
||||
TabWidget = QTabWidget()
|
||||
TabWidget.setMaximumHeight(150)
|
||||
BasicWidget = QWidget()
|
||||
BasicLayout = QGridLayout(BasicWidget)
|
||||
BasicLayout.setSpacing(4)
|
||||
BasicLayout.setContentsMargins(4, 4, 4, 4)
|
||||
BasicLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
control_buttons = [
|
||||
("如果 (if...)", "if then\n \nend"),
|
||||
("再如果 (elseif...)", "elseif then\n "),
|
||||
("否则 (else)", "else"),
|
||||
("结束 (end)", "end"),
|
||||
("跳过 (pass)", "-- pass"),
|
||||
]
|
||||
self.addButtonsToGrid(basicLayout, controlButtons, 0, 0, 3)
|
||||
assignButtons = [
|
||||
self.addButtonsToGrid(BasicLayout, control_buttons, 0, 0, 3)
|
||||
assign_buttons = [
|
||||
("赋值 (=)", " = "),
|
||||
]
|
||||
self.addButtonsToGrid(basicLayout, assignButtons, 1, 2, 3)
|
||||
tabWidget.addTab(basicWidget, "基本语法")
|
||||
operatorWidget = QWidget()
|
||||
operatorLayout = QGridLayout(operatorWidget)
|
||||
operatorLayout.setSpacing(4)
|
||||
operatorLayout.setContentsMargins(4, 4, 4, 4)
|
||||
operatorLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
arithmeticButtons = [
|
||||
self.addButtonsToGrid(BasicLayout, assign_buttons, 1, 2, 3)
|
||||
TabWidget.addTab(BasicWidget, "基本语法")
|
||||
OperatorWidget = QWidget()
|
||||
OperatorLayout = QGridLayout(OperatorWidget)
|
||||
OperatorLayout.setSpacing(4)
|
||||
OperatorLayout.setContentsMargins(4, 4, 4, 4)
|
||||
OperatorLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
arithmetic_buttons = [
|
||||
("加 (+)", " + "),
|
||||
("减 (-)", " - "),
|
||||
]
|
||||
self.addButtonsToGrid(operatorLayout, arithmeticButtons, 0, 0, 3)
|
||||
compareButtons = [
|
||||
self.addButtonsToGrid(OperatorLayout, arithmetic_buttons, 0, 0, 3)
|
||||
compare_buttons = [
|
||||
("等于 (==)", " == "),
|
||||
("不等于 (~=)", " ~= "),
|
||||
("大于 (>)", " > "),
|
||||
@@ -311,73 +318,73 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
("大于等于 (>=)", " >= "),
|
||||
("小于等于 (<=)", " <= "),
|
||||
]
|
||||
self.addButtonsToGrid(operatorLayout, compareButtons, 1, 0, 3)
|
||||
self.addButtonsToGrid(OperatorLayout, compare_buttons, 1, 0, 3)
|
||||
logic_buttons = [
|
||||
("且 (and)", " and "),
|
||||
("或 (or)", " or "),
|
||||
]
|
||||
self.addButtonsToGrid(operatorLayout, logic_buttons, 2, 0, 3)
|
||||
tabWidget.addTab(operatorWidget, "运算符")
|
||||
literalWidget = QWidget()
|
||||
literalLayout = QGridLayout(literalWidget)
|
||||
literalLayout.setSpacing(4)
|
||||
literalLayout.setContentsMargins(4, 4, 4, 4)
|
||||
literalLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
self.addButtonsToGrid(OperatorLayout, logic_buttons, 2, 0, 3)
|
||||
TabWidget.addTab(OperatorWidget, "运算符")
|
||||
LiteralWidget = QWidget()
|
||||
LiteralLayout = QGridLayout(LiteralWidget)
|
||||
LiteralLayout.setSpacing(4)
|
||||
LiteralLayout.setContentsMargins(4, 4, 4, 4)
|
||||
LiteralLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
bool_buttons = [
|
||||
("真 (true)", "true"),
|
||||
("假 (false)", "false"),
|
||||
]
|
||||
self.addButtonsToGrid(literalLayout, bool_buttons, 0, 0, 3)
|
||||
dateTimeButtons = [
|
||||
self.addButtonsToGrid(LiteralLayout, bool_buttons, 0, 0, 3)
|
||||
date_time_buttons = [
|
||||
("日期", 'date(2026, 1, 1)'),
|
||||
("时间", 'time(0, 0)'),
|
||||
]
|
||||
self.addButtonsToGrid(literalLayout, dateTimeButtons, 1, 0, 3)
|
||||
hintButtons = [
|
||||
self.addButtonsToGrid(LiteralLayout, date_time_buttons, 1, 0, 3)
|
||||
hint_buttons = [
|
||||
("字符串", '"请输入文本"'),
|
||||
("数字", "123"),
|
||||
("注释", "-- 请输入注释"),
|
||||
]
|
||||
self.addButtonsToGrid(literalLayout, hintButtons, 2, 0, 3)
|
||||
tabWidget.addTab(literalWidget, "字面量")
|
||||
varWidget = QWidget()
|
||||
varLayout = QGridLayout(varWidget)
|
||||
varLayout.setSpacing(4)
|
||||
varLayout.setContentsMargins(4, 4, 4, 4)
|
||||
varLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
varButtons = [
|
||||
self.addButtonsToGrid(LiteralLayout, hint_buttons, 2, 0, 3)
|
||||
TabWidget.addTab(LiteralWidget, "字面量")
|
||||
VarWidget = QWidget()
|
||||
VarLayout = QGridLayout(VarWidget)
|
||||
VarLayout.setSpacing(4)
|
||||
VarLayout.setContentsMargins(4, 4, 4, 4)
|
||||
VarLayout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
|
||||
var_buttons = [
|
||||
(display_name, name) for display_name, (name, _) in createAllVariablesTable().items()
|
||||
]
|
||||
self.addButtonsToGrid(varLayout, varButtons, 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)
|
||||
funcButtons = [
|
||||
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(funcButtons):
|
||||
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])
|
||||
parent_layout.addWidget(splitter)
|
||||
for i, (text, template, tooltip) in enumerate(func_buttons):
|
||||
Btn = QPushButton(text)
|
||||
Btn.setProperty("template", template)
|
||||
Btn.clicked.connect(self.insertTemplate)
|
||||
Btn.setFixedWidth(100)
|
||||
Btn.setFixedHeight(25)
|
||||
Btn.setToolTip(tooltip)
|
||||
FuncLayout.addWidget(Btn, i // 2, i % 2)
|
||||
TabWidget.addTab(FuncWidget, "工具函数")
|
||||
MockPanel = self.createMockPanel()
|
||||
MockPanel.setMinimumWidth(260)
|
||||
Splitter.addWidget(TabWidget)
|
||||
Splitter.addWidget(MockPanel)
|
||||
Splitter.setStretchFactor(0, 1)
|
||||
Splitter.setStretchFactor(1, 1)
|
||||
Splitter.setSizes([530, 530])
|
||||
ParentLayout.addWidget(Splitter)
|
||||
|
||||
def addButtonsToGrid(
|
||||
self,
|
||||
@@ -392,13 +399,13 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
row = start_row
|
||||
|
||||
for btn_text, template in buttons:
|
||||
btn = QPushButton(btn_text)
|
||||
btn.setProperty("template", template)
|
||||
btn.clicked.connect(self.insertTemplate)
|
||||
btn.setFixedWidth(100)
|
||||
btn.setFixedHeight(25)
|
||||
btn.setToolTip(f"插入: {template}")
|
||||
grid_layout.addWidget(btn, row, col)
|
||||
Btn = QPushButton(btn_text)
|
||||
Btn.setProperty("template", template)
|
||||
Btn.clicked.connect(self.insertTemplate)
|
||||
Btn.setFixedWidth(100)
|
||||
Btn.setFixedHeight(25)
|
||||
Btn.setToolTip(f"插入: {template}")
|
||||
grid_layout.addWidget(Btn, row, col)
|
||||
col += 1
|
||||
if col >= start_col + max_columns:
|
||||
col = start_col
|
||||
@@ -408,22 +415,22 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
self
|
||||
) -> QGroupBox:
|
||||
|
||||
group = QGroupBox("模拟目标数据")
|
||||
form = QFormLayout(group)
|
||||
form.setSpacing(4)
|
||||
form.setContentsMargins(5, 10, 5, 5)
|
||||
self._mockWidgets = {}
|
||||
mockData = createMockTargetData()
|
||||
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 = mockData
|
||||
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._mockWidgets[name] = (widget, var_type, key_path)
|
||||
return group
|
||||
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,
|
||||
@@ -432,49 +439,49 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
) -> QWidget:
|
||||
|
||||
if var_type == "String":
|
||||
w = QLineEdit()
|
||||
w.setText(str(default))
|
||||
return w
|
||||
widget = QLineEdit()
|
||||
widget.setText(str(default))
|
||||
return widget
|
||||
if var_type == "Boolean":
|
||||
w = QComboBox()
|
||||
w.addItems(["是", "否"])
|
||||
w.setCurrentIndex(0 if default else 1)
|
||||
return w
|
||||
widget = QComboBox()
|
||||
widget.addItems(["是", "否"])
|
||||
widget.setCurrentIndex(0 if default else 1)
|
||||
return widget
|
||||
if var_type == "Date":
|
||||
w = QDateEdit()
|
||||
w.setCalendarPopup(True)
|
||||
w.setDisplayFormat("yyyy-MM-dd")
|
||||
w.setDate(QDate.fromString(str(default), "yyyy-MM-dd"))
|
||||
return w
|
||||
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":
|
||||
w = QTimeEdit()
|
||||
w.setDisplayFormat("HH:mm")
|
||||
w.setTime(QTime.fromString(str(default), "HH:mm"))
|
||||
return w
|
||||
widget = QTimeEdit()
|
||||
widget.setDisplayFormat("HH:mm")
|
||||
widget.setTime(QTime.fromString(str(default), "HH:mm"))
|
||||
return widget
|
||||
if var_type == "Int":
|
||||
w = QSpinBox()
|
||||
w.setMinimum(-999999)
|
||||
w.setMaximum(999999)
|
||||
w.setValue(int(default) if default else 0)
|
||||
return w
|
||||
widget = QSpinBox()
|
||||
widget.setMinimum(-999999)
|
||||
widget.setMaximum(999999)
|
||||
widget.setValue(int(default) if default else 0)
|
||||
return widget
|
||||
if var_type == "Float":
|
||||
w = QDoubleSpinBox()
|
||||
w.setMinimum(-999999.0)
|
||||
w.setMaximum(999999.0)
|
||||
w.setDecimals(2)
|
||||
w.setValue(float(default) if default else 0.0)
|
||||
return w
|
||||
w = QLineEdit()
|
||||
w.setText(str(default))
|
||||
return w
|
||||
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, display_name in createTargetVarDefs():
|
||||
widget, _, _ = self._mockWidgets[name]
|
||||
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]:
|
||||
@@ -489,14 +496,14 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
|
||||
if not data:
|
||||
return
|
||||
for name, var_type, key_path, display_name in createTargetVarDefs():
|
||||
for name, var_type, key_path, _ in createTargetVarDefs():
|
||||
d = data
|
||||
try:
|
||||
for key in key_path:
|
||||
d = d[key]
|
||||
except (KeyError, TypeError):
|
||||
continue
|
||||
widget, _, _ = self._mockWidgets[name]
|
||||
widget, _, _ = self._mock_widgets[name]
|
||||
self.setMockValue(widget, var_type, d)
|
||||
|
||||
def getMockValue(
|
||||
@@ -537,49 +544,57 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
else:
|
||||
widget.setText(str(value))
|
||||
|
||||
def _iconColor(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return QApplication.instance().palette().color(
|
||||
QApplication.instance().palette().ColorRole.WindowText
|
||||
).name()
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.btnBox.accepted.connect(self.accept)
|
||||
self.btnBox.rejected.connect(self.reject)
|
||||
self.orchBtn.clicked.connect(self.onOpenOrchDialog)
|
||||
self.debugBtn.clicked.connect(self.onDebugRun)
|
||||
self.zoomInBtn.clicked.connect(self.onZoomIn)
|
||||
self.zoomOutBtn.clicked.connect(self.onZoomOut)
|
||||
self.zoomResetBtn.clicked.connect(self.onZoomReset)
|
||||
self.copyBtn.clicked.connect(self.onCopy)
|
||||
self.BtnBox.accepted.connect(self.accept)
|
||||
self.BtnBox.rejected.connect(self.reject)
|
||||
self.OrchBtn.clicked.connect(self.onOpenOrchDialog)
|
||||
self.DebugBtn.clicked.connect(self.onDebugRun)
|
||||
self.ZoomInBtn.clicked.connect(self.onZoomIn)
|
||||
self.ZoomOutBtn.clicked.connect(self.onZoomOut)
|
||||
self.ZoomResetBtn.clicked.connect(self.onZoomReset)
|
||||
self.CopyBtn.clicked.connect(self.onCopy)
|
||||
|
||||
def getScript(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self.textEdit.toPlainText()
|
||||
return self.TextEdit.toPlainText()
|
||||
|
||||
def updateFontSize(
|
||||
self
|
||||
):
|
||||
|
||||
self.textEdit.setStyleSheet(
|
||||
self.TextEdit.setStyleSheet(
|
||||
"QPlainTextEdit {"
|
||||
" 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):
|
||||
Btn = self.sender()
|
||||
if not isinstance(Btn, QPushButton):
|
||||
return
|
||||
template = btn.property("template")
|
||||
template = Btn.property("template")
|
||||
if not template:
|
||||
return
|
||||
cursor = self.textEdit.textCursor()
|
||||
cursor = self.TextEdit.textCursor()
|
||||
cursor.insertText(template)
|
||||
|
||||
@Slot()
|
||||
@@ -587,7 +602,7 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
self
|
||||
):
|
||||
|
||||
self._fontSize = min(self._fontSize + 2, 40)
|
||||
self._font_size = min(self._font_size + 2, 40)
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
@@ -595,7 +610,7 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
self
|
||||
):
|
||||
|
||||
self._fontSize = max(self._fontSize - 2, 8)
|
||||
self._font_size = max(self._font_size - 2, 8)
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
@@ -603,7 +618,7 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
self
|
||||
):
|
||||
|
||||
self._fontSize = 21
|
||||
self._font_size = 21
|
||||
self.updateFontSize()
|
||||
|
||||
@Slot()
|
||||
@@ -611,11 +626,11 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
self
|
||||
):
|
||||
|
||||
clipboard = QApplication.clipboard()
|
||||
clipboard.setText(self.textEdit.toPlainText())
|
||||
self.copyBtn.setEnabled(False)
|
||||
Clipboard = QApplication.clipboard()
|
||||
Clipboard.setText(self.TextEdit.toPlainText())
|
||||
self.CopyBtn.setEnabled(False)
|
||||
QTimer.singleShot(2000, lambda: (
|
||||
self.copyBtn.setEnabled(True)
|
||||
self.CopyBtn.setEnabled(True)
|
||||
))
|
||||
|
||||
@Slot()
|
||||
@@ -624,20 +639,20 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
):
|
||||
|
||||
from gui.ALAutoScriptOrchDialog import ALAutoScriptOrchDialog
|
||||
dlg = ALAutoScriptOrchDialog(self)
|
||||
if dlg.exec() == QDialog.DialogCode.Accepted:
|
||||
script = dlg.getScript()
|
||||
Dialpg = ALAutoScriptOrchDialog(self)
|
||||
if Dialpg.exec() == QDialog.DialogCode.Accepted:
|
||||
script = Dialpg.getScript()
|
||||
if script:
|
||||
cursor = self.textEdit.textCursor()
|
||||
cursor = self.TextEdit.textCursor()
|
||||
cursor.insertText(script)
|
||||
dlg.deleteLater()
|
||||
Dialpg.deleteLater()
|
||||
|
||||
@Slot()
|
||||
def onDebugRun(
|
||||
self
|
||||
):
|
||||
|
||||
script = self.textEdit.toPlainText().strip()
|
||||
script = self.TextEdit.toPlainText().strip()
|
||||
if not script:
|
||||
QMessageBox.warning(self, "提示", "脚本内容为空。")
|
||||
return
|
||||
@@ -664,6 +679,6 @@ class ALAutoScriptEditDialog(QDialog):
|
||||
if not changes:
|
||||
QMessageBox.information(self, "调试运行", "目标变量未发生变化。")
|
||||
return
|
||||
dlg = _DebugResultDialog(changes, self)
|
||||
dlg.exec()
|
||||
dlg.deleteLater()
|
||||
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
|
||||
@@ -32,16 +32,16 @@ class ConditionalBlock(QGroupBox):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
blockIndex: int,
|
||||
varMgr = None,
|
||||
block_index: int,
|
||||
var_mgr = None,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self.blockIndex = blockIndex
|
||||
self._varMgr = varMgr
|
||||
self._actionWidgets = []
|
||||
self._conditionRows = []
|
||||
self._block_index = block_index
|
||||
self._var_mgr = var_mgr
|
||||
self._action_widgets = []
|
||||
self._condition_rows = []
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
@@ -53,94 +53,98 @@ class ConditionalBlock(QGroupBox):
|
||||
|
||||
self.setUpdatesEnabled(False)
|
||||
self.setStyleSheet(
|
||||
"QGroupBox { font-weight: bold; border: 1px solid #ccc; "
|
||||
"margin-top: 5px; padding-top: 5px; }"
|
||||
"QGroupBox { "\
|
||||
"font-weight: bold;"\
|
||||
"border: 1px solid #ccc;"\
|
||||
"margin-top: 5px;"\
|
||||
"padding-top: 5px; "\
|
||||
"}"
|
||||
)
|
||||
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
|
||||
mainLayout = QVBoxLayout(self)
|
||||
mainLayout.setSpacing(6)
|
||||
mainLayout.setContentsMargins(8, 8, 8, 8)
|
||||
headerLayout = QHBoxLayout()
|
||||
headerLayout.setSpacing(8)
|
||||
self.typeCombo = QComboBox(self)
|
||||
self.typeCombo.addItem("IF", "IF")
|
||||
self.typeCombo.addItem("ELSE IF", "ELSE IF")
|
||||
self.typeCombo.addItem("ELSE", "ELSE")
|
||||
self.typeCombo.setFixedHeight(25)
|
||||
if self.blockIndex == 0:
|
||||
self.typeCombo.setEnabled(False)
|
||||
headerLayout.addWidget(QLabel("类型:", self))
|
||||
headerLayout.addWidget(self.typeCombo)
|
||||
headerLayout.addStretch()
|
||||
self.deleteBlockBtn = QPushButton("删除此块", self)
|
||||
self.deleteBlockBtn.setStyleSheet("color: red;")
|
||||
self.deleteBlockBtn.setFixedHeight(25)
|
||||
headerLayout.addWidget(self.deleteBlockBtn)
|
||||
mainLayout.addLayout(headerLayout)
|
||||
self.conditionWidget = QWidget(self)
|
||||
self.conditionWidget.setSizePolicy(
|
||||
MainLayout = QVBoxLayout(self)
|
||||
MainLayout.setSpacing(6)
|
||||
MainLayout.setContentsMargins(8, 8, 8, 8)
|
||||
HeaderLayout = QHBoxLayout()
|
||||
HeaderLayout.setSpacing(8)
|
||||
self.TypeCombo = QComboBox(self)
|
||||
self.TypeCombo.addItem("IF", "IF")
|
||||
self.TypeCombo.addItem("ELSE IF", "ELSE IF")
|
||||
self.TypeCombo.addItem("ELSE", "ELSE")
|
||||
self.TypeCombo.setFixedHeight(25)
|
||||
if self._block_index == 0:
|
||||
self.TypeCombo.setEnabled(False)
|
||||
HeaderLayout.addWidget(QLabel("类型:", self))
|
||||
HeaderLayout.addWidget(self.TypeCombo)
|
||||
HeaderLayout.addStretch()
|
||||
self.DeleteBlockBtn = QPushButton("删除此块", self)
|
||||
self.DeleteBlockBtn.setStyleSheet("color: red;")
|
||||
self.DeleteBlockBtn.setFixedHeight(25)
|
||||
HeaderLayout.addWidget(self.DeleteBlockBtn)
|
||||
MainLayout.addLayout(HeaderLayout)
|
||||
self.ConditionWidget = QWidget(self)
|
||||
self.ConditionWidget.setSizePolicy(
|
||||
QSizePolicy.Preferred, QSizePolicy.Preferred
|
||||
)
|
||||
condLayout = QVBoxLayout(self.conditionWidget)
|
||||
condLayout.setContentsMargins(4, 4, 4, 4)
|
||||
condLayout.setSpacing(6)
|
||||
self.condRowsLayout = QVBoxLayout()
|
||||
self.condRowsLayout.setSpacing(4)
|
||||
condLayout.addLayout(self.condRowsLayout)
|
||||
self.addCondBtn = QPushButton("+ 添加条件", self.conditionWidget)
|
||||
self.addCondBtn.setFixedHeight(25)
|
||||
condLayout.addWidget(self.addCondBtn)
|
||||
mainLayout.addWidget(self.conditionWidget)
|
||||
self.actionLabel = QLabel("执行步骤:", self)
|
||||
self.actionLabel.setFixedHeight(25)
|
||||
mainLayout.addWidget(self.actionLabel)
|
||||
self.actionsLayout = QVBoxLayout()
|
||||
self.actionsLayout.setSpacing(4)
|
||||
mainLayout.addLayout(self.actionsLayout)
|
||||
self.addActionBtn = QPushButton("+ 添加执行步骤", self)
|
||||
self.addActionBtn.setFixedHeight(25)
|
||||
mainLayout.addWidget(self.addActionBtn)
|
||||
CondLayout = QVBoxLayout(self.ConditionWidget)
|
||||
CondLayout.setContentsMargins(4, 4, 4, 4)
|
||||
CondLayout.setSpacing(6)
|
||||
self.CondRowsLayout = QVBoxLayout()
|
||||
self.CondRowsLayout.setSpacing(4)
|
||||
CondLayout.addLayout(self.CondRowsLayout)
|
||||
self.AddCondBtn = QPushButton("+ 添加条件", self.ConditionWidget)
|
||||
self.AddCondBtn.setFixedHeight(25)
|
||||
CondLayout.addWidget(self.AddCondBtn)
|
||||
MainLayout.addWidget(self.ConditionWidget)
|
||||
self.ActionLabel = QLabel("执行步骤:", self)
|
||||
self.ActionLabel.setFixedHeight(25)
|
||||
MainLayout.addWidget(self.ActionLabel)
|
||||
self.ActionsLayout = QVBoxLayout()
|
||||
self.ActionsLayout.setSpacing(4)
|
||||
MainLayout.addLayout(self.ActionsLayout)
|
||||
self.AddActionBtn = QPushButton("+ 添加执行步骤", self)
|
||||
self.AddActionBtn.setFixedHeight(25)
|
||||
MainLayout.addWidget(self.AddActionBtn)
|
||||
self.setUpdatesEnabled(True)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.typeCombo.currentIndexChanged.connect(self.onTypeChanged)
|
||||
self.addCondBtn.clicked.connect(self.addConditionRow)
|
||||
self.addActionBtn.clicked.connect(self.addActionStep)
|
||||
self.TypeCombo.currentIndexChanged.connect(self.onTypeChanged)
|
||||
self.AddCondBtn.clicked.connect(self.addConditionRow)
|
||||
self.AddActionBtn.clicked.connect(self.addActionStep)
|
||||
|
||||
def addInitialConditionRow(
|
||||
self
|
||||
):
|
||||
|
||||
row = ConditionRowFrame(
|
||||
self._varMgr, self.blockIndex,
|
||||
isFirst=True, parent=self
|
||||
Row = ConditionRowFrame(
|
||||
self._var_mgr, self._block_index,
|
||||
is_first=True, parent=self
|
||||
)
|
||||
self._conditionRows.append(row)
|
||||
self.condRowsLayout.addWidget(row)
|
||||
self._condition_rows.append(Row)
|
||||
self.CondRowsLayout.addWidget(Row)
|
||||
|
||||
def addConditionRow(
|
||||
self
|
||||
):
|
||||
|
||||
row = ConditionRowFrame(
|
||||
self._varMgr, self.blockIndex,
|
||||
isFirst=False, parent=self
|
||||
Row = ConditionRowFrame(
|
||||
self._var_mgr, self._block_index,
|
||||
is_first=False, parent=self
|
||||
)
|
||||
row.deleteBtn.clicked.connect(lambda: self.removeConditionRow(row))
|
||||
self._conditionRows.append(row)
|
||||
self.condRowsLayout.addWidget(row)
|
||||
Row.DeleteBtn.clicked.connect(lambda: self.removeConditionRow(Row))
|
||||
self._condition_rows.append(Row)
|
||||
self.CondRowsLayout.addWidget(Row)
|
||||
|
||||
def removeConditionRow(
|
||||
self,
|
||||
row: ConditionRowFrame
|
||||
):
|
||||
|
||||
if row in self._conditionRows and len(self._conditionRows) > 1:
|
||||
self._conditionRows.remove(row)
|
||||
self.condRowsLayout.removeWidget(row)
|
||||
if row in self._condition_rows and len(self._condition_rows) > 1:
|
||||
self._condition_rows.remove(row)
|
||||
self.CondRowsLayout.removeWidget(row)
|
||||
row.hide()
|
||||
row.deleteLater()
|
||||
|
||||
@@ -148,19 +152,19 @@ class ConditionalBlock(QGroupBox):
|
||||
self
|
||||
):
|
||||
|
||||
step = ActionStepFrame(self._varMgr, self.blockIndex, parent=self)
|
||||
step.deleteBtn.clicked.connect(lambda: self.removeActionStep(step))
|
||||
self._actionWidgets.append(step)
|
||||
self.actionsLayout.addWidget(step)
|
||||
Step = ActionStepFrame(self._var_mgr, self._block_index, parent=self)
|
||||
Step.DeleteBtn.clicked.connect(lambda: self.removeActionStep(Step))
|
||||
self._action_widgets.append(Step)
|
||||
self.ActionsLayout.addWidget(Step)
|
||||
|
||||
def removeActionStep(
|
||||
self,
|
||||
step: ActionStepFrame
|
||||
):
|
||||
|
||||
if step in self._actionWidgets:
|
||||
self._actionWidgets.remove(step)
|
||||
self.actionsLayout.removeWidget(step)
|
||||
if step in self._action_widgets:
|
||||
self._action_widgets.remove(step)
|
||||
self.ActionsLayout.removeWidget(step)
|
||||
step.hide()
|
||||
step.deleteLater()
|
||||
|
||||
@@ -168,25 +172,25 @@ class ConditionalBlock(QGroupBox):
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self.typeCombo.currentData()
|
||||
return self.TypeCombo.currentData()
|
||||
|
||||
def getConditionRows(
|
||||
self
|
||||
):
|
||||
|
||||
return list(self._conditionRows)
|
||||
return list(self._condition_rows)
|
||||
|
||||
def getActionSteps(
|
||||
self
|
||||
):
|
||||
|
||||
return list(self._actionWidgets)
|
||||
return list(self._action_widgets)
|
||||
|
||||
def countActionSteps(
|
||||
self
|
||||
) -> int:
|
||||
|
||||
return len(self._actionWidgets)
|
||||
return len(self._action_widgets)
|
||||
|
||||
def toScript(
|
||||
self
|
||||
@@ -195,71 +199,71 @@ class ConditionalBlock(QGroupBox):
|
||||
Generate Lua script lines for this conditional block.
|
||||
"""
|
||||
|
||||
blockType = self.getBlockType()
|
||||
block_type = self.getBlockType()
|
||||
lines = []
|
||||
if blockType in ("IF", "ELSE IF"):
|
||||
condTexts = [
|
||||
r.toScript() for r in self._conditionRows if r.toScript()
|
||||
if block_type in ("IF", "ELSE IF"):
|
||||
cond_texts = [
|
||||
r.toScript() for r in self._condition_rows if r.toScript()
|
||||
]
|
||||
if not condTexts:
|
||||
condTexts = ["true"]
|
||||
if len(condTexts) == 1:
|
||||
combined = condTexts[0]
|
||||
if not cond_texts:
|
||||
cond_texts = ["true"]
|
||||
if len(cond_texts) == 1:
|
||||
combined = cond_texts[0]
|
||||
else:
|
||||
parts = []
|
||||
for i, ct in enumerate(condTexts):
|
||||
for i, ct in enumerate(cond_texts):
|
||||
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"({ct})")
|
||||
combined = "".join(parts)
|
||||
if blockType == "IF":
|
||||
if block_type == "IF":
|
||||
lines.append(f"if {combined} then")
|
||||
else:
|
||||
lines.append(f"elseif {combined} then")
|
||||
else:
|
||||
lines.append("else")
|
||||
for step in self._actionWidgets:
|
||||
scriptLine = step.toScript()
|
||||
if scriptLine:
|
||||
lines.append(scriptLine)
|
||||
for step in self._action_widgets:
|
||||
script_line = step.toScript()
|
||||
if script_line:
|
||||
lines.append(script_line)
|
||||
return lines
|
||||
|
||||
def refreshVarCombos(
|
||||
self
|
||||
):
|
||||
|
||||
for row in self._conditionRows:
|
||||
for row in self._condition_rows:
|
||||
row.refreshVarCombos()
|
||||
for step in self._actionWidgets:
|
||||
for step in self._action_widgets:
|
||||
step.refreshVarCombos()
|
||||
|
||||
def setPrevBlockType(
|
||||
self,
|
||||
prevType: str | None
|
||||
prev_type: str | None
|
||||
):
|
||||
|
||||
model = self.typeCombo.model()
|
||||
model = self.TypeCombo.model()
|
||||
if model is None:
|
||||
return
|
||||
for data in ("ELSE IF", "ELSE"):
|
||||
idx = self.typeCombo.findData(data)
|
||||
idx = self.TypeCombo.findData(data)
|
||||
if idx < 0:
|
||||
continue
|
||||
item = model.item(idx)
|
||||
shouldEnable = prevType != "ELSE"
|
||||
item.setEnabled(shouldEnable)
|
||||
if prevType == "ELSE" and self.typeCombo.currentData() in ("ELSE IF", "ELSE"):
|
||||
self.typeCombo.setCurrentIndex(0)
|
||||
should_enable = prev_type != "ELSE"
|
||||
item.setEnabled(should_enable)
|
||||
if prev_type == "ELSE" and self.TypeCombo.currentData() in ("ELSE IF", "ELSE"):
|
||||
self.TypeCombo.setCurrentIndex(0)
|
||||
|
||||
@Slot(int)
|
||||
def onTypeChanged(
|
||||
self,
|
||||
_idx
|
||||
idx: int
|
||||
):
|
||||
|
||||
isCond = self.typeCombo.currentData() in ("IF", "ELSE IF")
|
||||
self.conditionWidget.setVisible(isCond)
|
||||
self.actionLabel.setText(
|
||||
"执行步骤:" if isCond else "ELSE 执行步骤:"
|
||||
is_cond = self.TypeCombo.currentData() in ("IF", "ELSE IF")
|
||||
self.ConditionWidget.setVisible(is_cond)
|
||||
self.ActionLabel.setText(
|
||||
"执行步骤:" if is_cond else "ELSE 执行步骤:"
|
||||
)
|
||||
@@ -35,12 +35,12 @@ class ALAutoScriptOrchDialog(QDialog):
|
||||
|
||||
super().__init__(parent)
|
||||
self._blocks = []
|
||||
self._varMgr = VariableManager(self)
|
||||
self._var_mgr = VariableManager(self)
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
self.addBlock()
|
||||
self.scrollLayout.addStretch()
|
||||
self.ScrollLayout.addStretch()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
@@ -49,33 +49,33 @@ class ALAutoScriptOrchDialog(QDialog):
|
||||
self.setWindowTitle("AutoScript 指令编排 - AutoLibrary")
|
||||
self.setMinimumSize(640, 600)
|
||||
self.setModal(True)
|
||||
mainLayout = QVBoxLayout(self)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setFrameShape(QFrame.NoFrame)
|
||||
scrollContent = QWidget()
|
||||
self.scrollLayout = QVBoxLayout(scrollContent)
|
||||
self.scrollLayout.setSpacing(5)
|
||||
scroll.setWidget(scrollContent)
|
||||
mainLayout.addWidget(scroll)
|
||||
self.addBlockBtn = QPushButton("+ 添加判断块")
|
||||
self.addBlockBtn.setFixedHeight(25)
|
||||
mainLayout.addWidget(self.addBlockBtn)
|
||||
self.btnBox = QDialogButtonBox(
|
||||
MainLayout = QVBoxLayout(self)
|
||||
Scroll = QScrollArea()
|
||||
Scroll.setWidgetResizable(True)
|
||||
Scroll.setFrameShape(QFrame.NoFrame)
|
||||
ScrollContent = QWidget()
|
||||
self.ScrollLayout = QVBoxLayout(ScrollContent)
|
||||
self.ScrollLayout.setSpacing(5)
|
||||
Scroll.setWidget(ScrollContent)
|
||||
MainLayout.addWidget(Scroll)
|
||||
self.AddBlockBtn = QPushButton("+ 添加判断块")
|
||||
self.AddBlockBtn.setFixedHeight(25)
|
||||
MainLayout.addWidget(self.AddBlockBtn)
|
||||
self.BtnBox = QDialogButtonBox(
|
||||
QDialogButtonBox.StandardButton.Ok |
|
||||
QDialogButtonBox.StandardButton.Cancel
|
||||
)
|
||||
self.btnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.btnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
mainLayout.addWidget(self.btnBox)
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Ok).setText("确定")
|
||||
self.BtnBox.button(QDialogButtonBox.StandardButton.Cancel).setText("取消")
|
||||
MainLayout.addWidget(self.BtnBox)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.btnBox.accepted.connect(self.onAccept)
|
||||
self.btnBox.rejected.connect(self.reject)
|
||||
self.addBlockBtn.clicked.connect(self.addBlock)
|
||||
self.BtnBox.accepted.connect(self.onAccept)
|
||||
self.BtnBox.rejected.connect(self.reject)
|
||||
self.AddBlockBtn.clicked.connect(self.addBlock)
|
||||
|
||||
def updateBlockTypeRestrictions(
|
||||
self
|
||||
@@ -90,24 +90,24 @@ class ALAutoScriptOrchDialog(QDialog):
|
||||
self
|
||||
):
|
||||
|
||||
block = ConditionalBlock(
|
||||
len(self._blocks), self._varMgr, parent=self
|
||||
Block = ConditionalBlock(
|
||||
len(self._blocks), self._var_mgr, parent=self
|
||||
)
|
||||
block.deleteBlockBtn.clicked.connect(lambda: self.removeBlock(block))
|
||||
block.typeCombo.currentIndexChanged.connect(self.updateBlockTypeRestrictions)
|
||||
block.addActionStep()
|
||||
self._blocks.append(block)
|
||||
Block.DeleteBlockBtn.clicked.connect(lambda: self.removeBlock(Block))
|
||||
Block.TypeCombo.currentIndexChanged.connect(self.updateBlockTypeRestrictions)
|
||||
Block.addActionStep()
|
||||
self._blocks.append(Block)
|
||||
self.updateBlockTypeRestrictions()
|
||||
if self.scrollLayout.count() > 0:
|
||||
lastItem = self.scrollLayout.itemAt(
|
||||
self.scrollLayout.count() - 1
|
||||
if self.ScrollLayout.count() > 0:
|
||||
lastItem = self.ScrollLayout.itemAt(
|
||||
self.ScrollLayout.count() - 1
|
||||
)
|
||||
if lastItem and lastItem.spacerItem():
|
||||
self.scrollLayout.insertWidget(
|
||||
self.scrollLayout.count() - 1, block
|
||||
self.ScrollLayout.insertWidget(
|
||||
self.ScrollLayout.count() - 1, Block
|
||||
)
|
||||
return
|
||||
self.scrollLayout.addWidget(block)
|
||||
self.ScrollLayout.addWidget(Block)
|
||||
|
||||
def removeBlock(
|
||||
self,
|
||||
@@ -119,16 +119,16 @@ class ALAutoScriptOrchDialog(QDialog):
|
||||
return
|
||||
if block in self._blocks:
|
||||
self._blocks.remove(block)
|
||||
self.scrollLayout.removeWidget(block)
|
||||
self.ScrollLayout.removeWidget(block)
|
||||
block.hide()
|
||||
block.deleteLater()
|
||||
for i, blk in enumerate(self._blocks):
|
||||
blk.blockIndex = i
|
||||
if i == 0:
|
||||
blk.typeCombo.setEnabled(False)
|
||||
blk.typeCombo.setCurrentIndex(0)
|
||||
blk.TypeCombo.setEnabled(False)
|
||||
blk.TypeCombo.setCurrentIndex(0)
|
||||
else:
|
||||
blk.typeCombo.setEnabled(True)
|
||||
blk.TypeCombo.setEnabled(True)
|
||||
blk.refreshVarCombos()
|
||||
self.updateBlockTypeRestrictions()
|
||||
|
||||
|
||||
@@ -46,11 +46,11 @@ def getTypeOrder(
|
||||
return [t for t, _ in VARTYPE_INFOS]
|
||||
|
||||
def getArithType(
|
||||
varType: str
|
||||
var_type: str
|
||||
) -> bool:
|
||||
|
||||
for t, a in VARTYPE_INFOS:
|
||||
if t == varType:
|
||||
if t == var_type:
|
||||
return a
|
||||
|
||||
def getPresetVars(
|
||||
@@ -104,45 +104,46 @@ class _DateInputContainer(QWidget):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.setSpacing(4)
|
||||
self._modeCombo = QComboBox(self)
|
||||
self._modeCombo.addItem("相对日期", "relative")
|
||||
self._modeCombo.addItem("绝对日期", "absolute")
|
||||
self._modeCombo.setFixedHeight(25)
|
||||
self._stack = QStackedWidget(self)
|
||||
self._relCombo = QComboBox(self)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(0, 0, 0, 0)
|
||||
Layout.setSpacing(4)
|
||||
self.ModeCombo = QComboBox(self)
|
||||
self.ModeCombo.addItem("相对日期", "relative")
|
||||
self.ModeCombo.addItem("绝对日期", "absolute")
|
||||
self.ModeCombo.setFixedHeight(25)
|
||||
self.Stack = QStackedWidget(self)
|
||||
self.RelCombo = QComboBox(self)
|
||||
for display, data in DATE_OPTIONS:
|
||||
self._relCombo.addItem(display, data)
|
||||
self._relCombo.setFixedHeight(25)
|
||||
self._stack.addWidget(self._relCombo)
|
||||
self._dateEdit = QDateEdit(self)
|
||||
self._dateEdit.setDisplayFormat("yyyy-MM-dd")
|
||||
self._dateEdit.setCalendarPopup(True)
|
||||
self._dateEdit.setFixedHeight(25)
|
||||
self._stack.addWidget(self._dateEdit)
|
||||
self._modeCombo.currentIndexChanged.connect(
|
||||
lambda i: self._stack.setCurrentIndex(i)
|
||||
self.RelCombo.addItem(display, data)
|
||||
self.RelCombo.setFixedHeight(25)
|
||||
self.Stack.addWidget(self.RelCombo)
|
||||
self.DateEdit = QDateEdit(self)
|
||||
self.DateEdit.setDisplayFormat("yyyy-MM-dd")
|
||||
self.DateEdit.setCalendarPopup(True)
|
||||
self.DateEdit.setFixedHeight(25)
|
||||
self.Stack.addWidget(self.DateEdit)
|
||||
self.ModeCombo.currentIndexChanged.connect(
|
||||
lambda i: self.Stack.setCurrentIndex(i)
|
||||
)
|
||||
layout.addWidget(self._modeCombo)
|
||||
layout.addWidget(self._stack)
|
||||
layout.addStretch()
|
||||
Layout.addWidget(self.ModeCombo)
|
||||
Layout.addWidget(self.Stack)
|
||||
Layout.addStretch()
|
||||
|
||||
def getValue(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
mode = self._modeCombo.currentData()
|
||||
mode = self.ModeCombo.currentData()
|
||||
if mode == "relative":
|
||||
return self._relCombo.currentText()
|
||||
return self._dateEdit.date().toString("yyyy-MM-dd")
|
||||
return self.RelCombo.currentText()
|
||||
return self.DateEdit.date().toString("yyyy-MM-dd")
|
||||
|
||||
|
||||
class _TimeInputContainer(QWidget):
|
||||
@@ -153,19 +154,25 @@ class _TimeInputContainer(QWidget):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._timeEdit = QTimeEdit(self)
|
||||
self._timeEdit.setDisplayFormat("HH:mm")
|
||||
self._timeEdit.setFixedHeight(25)
|
||||
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self._timeEdit)
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.TimeEdit = QTimeEdit(self)
|
||||
self.TimeEdit.setDisplayFormat("HH:mm")
|
||||
self.TimeEdit.setFixedHeight(25)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(0, 0, 0, 0)
|
||||
Layout.addWidget(self.TimeEdit)
|
||||
|
||||
def getValue(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self._timeEdit.time().toString("HH:mm")
|
||||
return self.TimeEdit.time().toString("HH:mm")
|
||||
|
||||
|
||||
class _DateOffsetContainer(QWidget):
|
||||
@@ -176,20 +183,26 @@ class _DateOffsetContainer(QWidget):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._spinBox = QSpinBox(self)
|
||||
self._spinBox.setRange(0, 99999)
|
||||
self._spinBox.setFixedHeight(25)
|
||||
self._unitCombo = QComboBox(self)
|
||||
for display, data in DATE_OFFSET_OPTIONS:
|
||||
self._unitCombo.addItem(display, data)
|
||||
self._unitCombo.setFixedHeight(25)
|
||||
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.setSpacing(4)
|
||||
layout.addWidget(self._spinBox)
|
||||
layout.addWidget(self._unitCombo)
|
||||
layout.addStretch()
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.SpinBox = QSpinBox(self)
|
||||
self.SpinBox.setRange(0, 99999)
|
||||
self.SpinBox.setFixedHeight(25)
|
||||
self.UnitCombo = QComboBox(self)
|
||||
for display, data in DATE_OFFSET_OPTIONS:
|
||||
self.UnitCombo.addItem(display, data)
|
||||
self.UnitCombo.setFixedHeight(25)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(0, 0, 0, 0)
|
||||
Layout.setSpacing(4)
|
||||
Layout.addWidget(self.SpinBox)
|
||||
Layout.addWidget(self.UnitCombo)
|
||||
Layout.addStretch()
|
||||
|
||||
def getValue(
|
||||
self
|
||||
@@ -201,8 +214,8 @@ class _DateOffsetContainer(QWidget):
|
||||
self
|
||||
) -> int:
|
||||
|
||||
val = self._spinBox.value()
|
||||
unit = self._unitCombo.currentData()
|
||||
val = self.SpinBox.value()
|
||||
unit = self.UnitCombo.currentData()
|
||||
if unit == "weeks":
|
||||
return val*7
|
||||
if unit == "months":
|
||||
@@ -220,14 +233,20 @@ class _TimeOffsetContainer(QWidget):
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._spinBox = QSpinBox(self)
|
||||
self._spinBox.setRange(0, 99999)
|
||||
self._spinBox.setSuffix(" 小时")
|
||||
self._spinBox.setFixedHeight(25)
|
||||
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
layout.addWidget(self._spinBox)
|
||||
self.setupUi()
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.SpinBox = QSpinBox(self)
|
||||
self.SpinBox.setRange(0, 99999)
|
||||
self.SpinBox.setSuffix(" 小时")
|
||||
self.SpinBox.setFixedHeight(25)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(0, 0, 0, 0)
|
||||
Layout.addWidget(self.SpinBox)
|
||||
|
||||
def getValue(
|
||||
self
|
||||
@@ -239,7 +258,7 @@ class _TimeOffsetContainer(QWidget):
|
||||
self
|
||||
) -> int:
|
||||
|
||||
return self._spinBox.value()
|
||||
return self.SpinBox.value()
|
||||
|
||||
|
||||
class VariableManager(QObject):
|
||||
@@ -251,7 +270,7 @@ class VariableManager(QObject):
|
||||
|
||||
super().__init__(parent)
|
||||
self._vars = []
|
||||
self._nameMap = {}
|
||||
self._name_map = {}
|
||||
|
||||
self.initPresetVars()
|
||||
|
||||
@@ -262,21 +281,21 @@ class VariableManager(QObject):
|
||||
for p in getPresetVars():
|
||||
entry = {"name": p["name"], "type": p["type"], "display": p["display"]}
|
||||
self._vars.append(entry)
|
||||
self._nameMap[p["name"]] = entry
|
||||
self._name_map[p["name"]] = entry
|
||||
|
||||
def getInfoByName(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
|
||||
return self._nameMap.get(name.upper().strip())
|
||||
return self._name_map.get(name.upper().strip())
|
||||
|
||||
def populateCombo(
|
||||
self,
|
||||
combo: QComboBox
|
||||
):
|
||||
|
||||
currentData = combo.currentData()
|
||||
current_data = combo.currentData()
|
||||
combo.blockSignals(True)
|
||||
combo.clear()
|
||||
for entry in self._vars:
|
||||
@@ -284,10 +303,10 @@ class VariableManager(QObject):
|
||||
entry["display"],
|
||||
(entry["name"], entry["type"])
|
||||
)
|
||||
if currentData:
|
||||
if current_data:
|
||||
for i in range(combo.count()):
|
||||
d = combo.itemData(i)
|
||||
if d and d[0] == currentData[0]:
|
||||
if d and d[0] == current_data[0]:
|
||||
combo.setCurrentIndex(i)
|
||||
break
|
||||
combo.blockSignals(False)
|
||||
@@ -299,40 +318,40 @@ def makeValueWidget(
|
||||
) -> QWidget:
|
||||
|
||||
if var_type == "Int":
|
||||
w = QSpinBox(parent)
|
||||
w.setRange(-999999, 999999)
|
||||
w.setFixedHeight(25)
|
||||
w.setMinimumWidth(100)
|
||||
return w
|
||||
Widget = QSpinBox(parent)
|
||||
Widget.setRange(-999999, 999999)
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "Float":
|
||||
w = QDoubleSpinBox(parent)
|
||||
w.setRange(-999999.0, 999999.0)
|
||||
w.setDecimals(2)
|
||||
w.setFixedHeight(25)
|
||||
w.setMinimumWidth(100)
|
||||
return w
|
||||
Widget = QDoubleSpinBox(parent)
|
||||
Widget.setRange(-999999.0, 999999.0)
|
||||
Widget.setDecimals(2)
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "String":
|
||||
w = QLineEdit(parent)
|
||||
w.setPlaceholderText("输入值")
|
||||
w.setFixedHeight(25)
|
||||
w.setMinimumWidth(120)
|
||||
return w
|
||||
Widget = QLineEdit(parent)
|
||||
Widget.setPlaceholderText("输入值")
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(120)
|
||||
return Widget
|
||||
if var_type == "Boolean":
|
||||
w = QComboBox(parent)
|
||||
w.addItem("是 (true)", "true")
|
||||
w.addItem("否 (false)", "false")
|
||||
w.setFixedHeight(25)
|
||||
w.setMinimumWidth(100)
|
||||
return w
|
||||
Widget = QComboBox(parent)
|
||||
Widget.addItem("是 (true)", "true")
|
||||
Widget.addItem("否 (false)", "false")
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "Date":
|
||||
return _DateInputContainer(parent)
|
||||
if var_type == "Time":
|
||||
return _TimeInputContainer(parent)
|
||||
w = QLineEdit(parent)
|
||||
w.setPlaceholderText("输入值")
|
||||
w.setFixedHeight(25)
|
||||
w.setMinimumWidth(120)
|
||||
return w
|
||||
Widget = QLineEdit(parent)
|
||||
Widget.setPlaceholderText("输入值")
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(120)
|
||||
return Widget
|
||||
|
||||
def makeOffsetWidget(
|
||||
var_type: str,
|
||||
@@ -340,35 +359,35 @@ def makeOffsetWidget(
|
||||
) -> QWidget:
|
||||
|
||||
if var_type == "Int":
|
||||
w = QSpinBox(parent)
|
||||
w.setRange(-999999, 999999)
|
||||
w.setFixedHeight(25)
|
||||
w.setMinimumWidth(100)
|
||||
return w
|
||||
Widget = QSpinBox(parent)
|
||||
Widget.setRange(-999999, 999999)
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "Float":
|
||||
w = QDoubleSpinBox(parent)
|
||||
w.setRange(-999999.0, 999999.0)
|
||||
w.setDecimals(2)
|
||||
w.setFixedHeight(25)
|
||||
w.setMinimumWidth(100)
|
||||
return w
|
||||
Widget = QDoubleSpinBox(parent)
|
||||
Widget.setRange(-999999.0, 999999.0)
|
||||
Widget.setDecimals(2)
|
||||
Widget.setFixedHeight(25)
|
||||
Widget.setMinimumWidth(100)
|
||||
return Widget
|
||||
if var_type == "Date":
|
||||
return _DateOffsetContainer(parent)
|
||||
if var_type == "Time":
|
||||
return _TimeOffsetContainer(parent)
|
||||
w = QLabel("(不支持该操作)", parent)
|
||||
w.setFixedHeight(25)
|
||||
return w
|
||||
Widget = QLabel("(不支持该操作)", parent)
|
||||
Widget.setFixedHeight(25)
|
||||
return Widget
|
||||
|
||||
def makeVarRefCombo(
|
||||
parent: QWidget = None
|
||||
) -> QComboBox:
|
||||
|
||||
cb = QComboBox(parent)
|
||||
cb.setFixedHeight(25)
|
||||
cb.setMinimumWidth(120)
|
||||
cb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
|
||||
return cb
|
||||
ComboBox = QComboBox(parent)
|
||||
ComboBox.setFixedHeight(25)
|
||||
ComboBox.setMinimumWidth(120)
|
||||
ComboBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
|
||||
return ComboBox
|
||||
|
||||
def makeComboWidget(
|
||||
items,
|
||||
@@ -376,12 +395,12 @@ def makeComboWidget(
|
||||
parent: QWidget = None
|
||||
) -> QComboBox:
|
||||
|
||||
cb = QComboBox(parent)
|
||||
ComboBox = QComboBox(parent)
|
||||
for display, data in items:
|
||||
cb.addItem(display, data)
|
||||
cb.setFixedHeight(25)
|
||||
cb.setMinimumWidth(min_width)
|
||||
return cb
|
||||
ComboBox.addItem(display, data)
|
||||
ComboBox.setFixedHeight(25)
|
||||
ComboBox.setMinimumWidth(min_width)
|
||||
return ComboBox
|
||||
|
||||
def makeLabel(
|
||||
text: str,
|
||||
@@ -389,30 +408,30 @@ def makeLabel(
|
||||
width: int = None
|
||||
) -> QLabel:
|
||||
|
||||
lbl = QLabel(text, parent)
|
||||
lbl.setFixedHeight(25)
|
||||
Label = QLabel(text, parent)
|
||||
Label.setFixedHeight(25)
|
||||
if width:
|
||||
lbl.setFixedWidth(width)
|
||||
return lbl
|
||||
Label.setFixedWidth(width)
|
||||
return Label
|
||||
|
||||
def getValueFromWidget(
|
||||
w: QWidget
|
||||
widget: QWidget
|
||||
) -> str:
|
||||
|
||||
if hasattr(w, "getValue"):
|
||||
return w.getValue()
|
||||
if isinstance(w, QTimeEdit):
|
||||
return w.time().toString("HH:mm")
|
||||
if isinstance(w, QDateEdit):
|
||||
return w.date().toString("yyyy-MM-dd")
|
||||
if isinstance(w, QComboBox):
|
||||
return w.currentData() or w.currentText()
|
||||
if isinstance(w, QSpinBox):
|
||||
return str(w.value())
|
||||
if isinstance(w, QDoubleSpinBox):
|
||||
return str(w.value())
|
||||
if isinstance(w, QLineEdit):
|
||||
return w.text()
|
||||
if hasattr(widget, "getValue"):
|
||||
return widget.getValue()
|
||||
if isinstance(widget, QTimeEdit):
|
||||
return widget.time().toString("HH:mm")
|
||||
if isinstance(widget, QDateEdit):
|
||||
return widget.date().toString("yyyy-MM-dd")
|
||||
if isinstance(widget, QComboBox):
|
||||
return widget.currentData() or widget.currentText()
|
||||
if isinstance(widget, QSpinBox):
|
||||
return str(widget.value())
|
||||
if isinstance(widget, QDoubleSpinBox):
|
||||
return str(widget.value())
|
||||
if isinstance(widget, QLineEdit):
|
||||
return widget.text()
|
||||
return ""
|
||||
|
||||
def encodeValueStr(
|
||||
|
||||
@@ -42,18 +42,18 @@ class ConditionRowFrame(QFrame):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
varMgr,
|
||||
parentBlockIndex: int = 0,
|
||||
isFirst: bool = False,
|
||||
var_mgr,
|
||||
parent_block_index: int = 0,
|
||||
is_first: bool = False,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._varMgr = varMgr
|
||||
self._blockIndex = parentBlockIndex
|
||||
self._isFirst = isFirst
|
||||
self._isBoolMode = False
|
||||
self._rawRhsExpr = ""
|
||||
self._var_mgr = var_mgr
|
||||
self._block_index = parent_block_index
|
||||
self._is_first = is_first
|
||||
self._is_bool_mode = False
|
||||
self._raw_rhs_expr = ""
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
@@ -66,114 +66,114 @@ class ConditionRowFrame(QFrame):
|
||||
self.setFrameShape(QFrame.StyledPanel)
|
||||
self.setFrameShadow(QFrame.Raised)
|
||||
self.setFixedHeight(32)
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(2, 2, 2, 2)
|
||||
layout.setSpacing(4)
|
||||
if self._isFirst:
|
||||
self.logicCombo = None
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(2, 2, 2, 2)
|
||||
Layout.setSpacing(4)
|
||||
if self._is_first:
|
||||
self.LogicCombo = None
|
||||
else:
|
||||
self.logicCombo = makeComboWidget(LOGIC_OPTIONS, min_width=110, parent=self)
|
||||
layout.addWidget(self.logicCombo)
|
||||
self.leftVarCombo = QComboBox(self)
|
||||
self.leftVarCombo.setFixedHeight(25)
|
||||
self.leftVarCombo.setMinimumWidth(120)
|
||||
self.leftVarCombo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
|
||||
self.LogicCombo = makeComboWidget(LOGIC_OPTIONS, min_width=110, parent=self)
|
||||
Layout.addWidget(self.LogicCombo)
|
||||
self.LeftVarCombo = QComboBox(self)
|
||||
self.LeftVarCombo.setFixedHeight(25)
|
||||
self.LeftVarCombo.setMinimumWidth(120)
|
||||
self.LeftVarCombo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
|
||||
self.populateLeftVarCombo()
|
||||
layout.addWidget(self.leftVarCombo)
|
||||
self.opCombo = makeComboWidget(COMPARE_OPTIONS, min_width=80, parent=self)
|
||||
layout.addWidget(self.opCombo)
|
||||
self._compTypeCombo = makeComboWidget([
|
||||
Layout.addWidget(self.LeftVarCombo)
|
||||
self.OpCombo = makeComboWidget(COMPARE_OPTIONS, min_width=80, parent=self)
|
||||
Layout.addWidget(self.OpCombo)
|
||||
self.CompTypeCombo = makeComboWidget([
|
||||
("特定值", "literal"),
|
||||
("变量", "variable"),
|
||||
], min_width=70, parent=self)
|
||||
layout.addWidget(self._compTypeCombo)
|
||||
self.rhsStack = QStackedWidget(self)
|
||||
self.rhsStack.setFixedHeight(25)
|
||||
Layout.addWidget(self.CompTypeCombo)
|
||||
self.RhsStack = QStackedWidget(self)
|
||||
self.RhsStack.setFixedHeight(25)
|
||||
self.initLiteralStack()
|
||||
self.rhsVarCombo = makeVarRefCombo(self)
|
||||
self.rhsStack.addWidget(self.rhsVarCombo)
|
||||
self.rhsStack.setCurrentIndex(0)
|
||||
layout.addWidget(self.rhsStack)
|
||||
if not self._isFirst:
|
||||
self.deleteBtn = QPushButton("×", self)
|
||||
self.deleteBtn.setFixedSize(25, 25)
|
||||
self.deleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||
layout.addWidget(self.deleteBtn)
|
||||
self.RhsVarCombo = makeVarRefCombo(self)
|
||||
self.RhsStack.addWidget(self.RhsVarCombo)
|
||||
self.RhsStack.setCurrentIndex(0)
|
||||
Layout.addWidget(self.RhsStack)
|
||||
if not self._is_first:
|
||||
self.DeleteBtn = QPushButton("×", self)
|
||||
self.DeleteBtn.setFixedSize(25, 25)
|
||||
self.DeleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||
Layout.addWidget(self.DeleteBtn)
|
||||
else:
|
||||
self.deleteBtn = None
|
||||
layout.addStretch()
|
||||
self.DeleteBtn = None
|
||||
Layout.addStretch()
|
||||
self.setUpdatesEnabled(True)
|
||||
|
||||
def populateLeftVarCombo(
|
||||
self
|
||||
):
|
||||
|
||||
wasBool = self._isBoolMode
|
||||
boolName = None
|
||||
if wasBool:
|
||||
data = self.leftVarCombo.currentData()
|
||||
was_bool = self._is_bool_mode
|
||||
bool_name = None
|
||||
if was_bool:
|
||||
data = self.LeftVarCombo.currentData()
|
||||
if data:
|
||||
boolName = data[0]
|
||||
self._varMgr.populateCombo(self.leftVarCombo)
|
||||
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 wasBool and boolName:
|
||||
for ci in range(self.leftVarCombo.count()):
|
||||
d = self.leftVarCombo.itemData(ci)
|
||||
if d and d[0] == boolName:
|
||||
self.leftVarCombo.setCurrentIndex(ci)
|
||||
self.LeftVarCombo.insertSeparator(self.LeftVarCombo.count())
|
||||
self.LeftVarCombo.addItem("true", ("true", "Boolean"))
|
||||
self.LeftVarCombo.addItem("false", ("false", "Boolean"))
|
||||
if was_bool and bool_name:
|
||||
for ci in range(self.LeftVarCombo.count()):
|
||||
d = self.LeftVarCombo.itemData(ci)
|
||||
if d and d[0] == bool_name:
|
||||
self.LeftVarCombo.setCurrentIndex(ci)
|
||||
break
|
||||
|
||||
def populateRHSVarCombo(
|
||||
self
|
||||
):
|
||||
|
||||
self._varMgr.populateCombo(self.rhsVarCombo)
|
||||
self._var_mgr.populateCombo(self.RhsVarCombo)
|
||||
|
||||
def initLiteralStack(
|
||||
self
|
||||
):
|
||||
|
||||
self.literalStack = QStackedWidget(self)
|
||||
self.literalStack.setFixedHeight(25)
|
||||
self._literalWidgets = {}
|
||||
self.LiteralStack = QStackedWidget(self)
|
||||
self.LiteralStack.setFixedHeight(25)
|
||||
self.literal_widgets = {}
|
||||
for vt in getTypeOrder():
|
||||
w = makeValueWidget(vt, self.literalStack)
|
||||
self._literalWidgets[vt] = w
|
||||
self.literalStack.addWidget(w)
|
||||
self.literalStack.setCurrentWidget(self._literalWidgets.get("String"))
|
||||
self.rhsStack.addWidget(self.literalStack)
|
||||
W = makeValueWidget(vt, self.LiteralStack)
|
||||
self.literal_widgets[vt] = W
|
||||
self.LiteralStack.addWidget(W)
|
||||
self.LiteralStack.setCurrentWidget(self.literal_widgets.get("String"))
|
||||
self.RhsStack.addWidget(self.LiteralStack)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.leftVarCombo.currentIndexChanged.connect(self.onLeftVarChanged)
|
||||
self._compTypeCombo.currentIndexChanged.connect(self.onCompTypeChanged)
|
||||
self.LeftVarCombo.currentIndexChanged.connect(self.onLeftVarChanged)
|
||||
self.CompTypeCombo.currentIndexChanged.connect(self.onCompTypeChanged)
|
||||
|
||||
def getLogic(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
return self.logicCombo.currentData() if self.logicCombo else ""
|
||||
return self.LogicCombo.currentData() if self.LogicCombo else ""
|
||||
|
||||
def updateRHSLiteralWidget(
|
||||
self,
|
||||
vartype: str
|
||||
):
|
||||
|
||||
if vartype not in self._literalWidgets:
|
||||
if vartype not in self.literal_widgets:
|
||||
vartype = "String"
|
||||
self.literalStack.setCurrentWidget(self._literalWidgets[vartype])
|
||||
self.LiteralStack.setCurrentWidget(self.literal_widgets[vartype])
|
||||
|
||||
def toScript(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
data = self.leftVarCombo.currentData()
|
||||
if self._isBoolMode and data:
|
||||
data = self.LeftVarCombo.currentData()
|
||||
if self._is_bool_mode and data:
|
||||
return data[0]
|
||||
if not data:
|
||||
return ""
|
||||
@@ -183,28 +183,28 @@ class ConditionRowFrame(QFrame):
|
||||
name = "datenow()"
|
||||
elif name == "CURRENT_TIME":
|
||||
name = "timenow()"
|
||||
opSym = self.opCombo.currentData()
|
||||
if self._rawRhsExpr:
|
||||
return f"{name} {opSym} {self._rawRhsExpr}"
|
||||
isVarRef = (self._compTypeCombo.currentData() == "variable")
|
||||
if isVarRef:
|
||||
rd = self.rhsVarCombo.currentData()
|
||||
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:
|
||||
rhsName = rd[0]
|
||||
if rhsName == "CURRENT_DATE":
|
||||
rhsName = "datenow()"
|
||||
elif rhsName == "CURRENT_TIME":
|
||||
rhsName = "timenow()"
|
||||
return f"{name} {opSym} {rhsName}"
|
||||
rhsText = self.rhsVarCombo.currentText().strip()
|
||||
if rhsText:
|
||||
return f"{name} {opSym} {rhsText}"
|
||||
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._literalWidgets.get(vartype)
|
||||
w = self.literal_widgets.get(vartype)
|
||||
if w:
|
||||
rawVal = getValueFromWidget(w)
|
||||
encoded = encodeValueStr(rawVal, vartype)
|
||||
return f"{name} {opSym} {encoded}"
|
||||
raw_val = getValueFromWidget(w)
|
||||
encoded = encodeValueStr(raw_val, vartype)
|
||||
return f"{name} {op_sym} {encoded}"
|
||||
return ""
|
||||
|
||||
def refreshVarCombos(
|
||||
@@ -220,19 +220,19 @@ class ConditionRowFrame(QFrame):
|
||||
idx
|
||||
):
|
||||
|
||||
self._rawRhsExpr = ""
|
||||
self._raw_rhs_expr = ""
|
||||
if idx < 0:
|
||||
return
|
||||
data = self.leftVarCombo.itemData(idx)
|
||||
data = self.LeftVarCombo.itemData(idx)
|
||||
if not data:
|
||||
return
|
||||
name, vartype = data
|
||||
isBool = name in ("true", "false")
|
||||
self._isBoolMode = isBool
|
||||
self.opCombo.setVisible(not isBool)
|
||||
self._compTypeCombo.setVisible(not isBool)
|
||||
self.rhsStack.setVisible(not isBool)
|
||||
if not isBool:
|
||||
is_bool = name in ("true", "false")
|
||||
self._is_bool_mode = is_bool
|
||||
self.OpCombo.setVisible(not is_bool)
|
||||
self.CompTypeCombo.setVisible(not is_bool)
|
||||
self.RhsStack.setVisible(not is_bool)
|
||||
if not is_bool:
|
||||
self.updateRHSLiteralWidget(vartype)
|
||||
|
||||
@Slot(int)
|
||||
@@ -241,9 +241,9 @@ class ConditionRowFrame(QFrame):
|
||||
idx
|
||||
):
|
||||
|
||||
self._rawRhsExpr = ""
|
||||
isVar = (self._compTypeCombo.currentData() == "variable")
|
||||
self.rhsStack.setCurrentIndex(1 if isVar else 0)
|
||||
self._raw_rhs_expr = ""
|
||||
isVar = (self.CompTypeCombo.currentData() == "variable")
|
||||
self.RhsStack.setCurrentIndex(1 if isVar else 0)
|
||||
if isVar:
|
||||
self.populateRHSVarCombo()
|
||||
|
||||
@@ -252,15 +252,15 @@ class ActionStepFrame(QFrame):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
varMgr,
|
||||
parentBlockIndex: int = 0,
|
||||
var_mgr,
|
||||
parent_block_index: int = 0,
|
||||
parent = None
|
||||
):
|
||||
|
||||
super().__init__(parent)
|
||||
self._varMgr = varMgr
|
||||
self._blockIndex = parentBlockIndex
|
||||
self._currentTargetType = "String"
|
||||
self._var_mgr = var_mgr
|
||||
self._block_index = parent_block_index
|
||||
self._current_target_type = "String"
|
||||
|
||||
self.setupUi()
|
||||
self.connectSignals()
|
||||
@@ -273,99 +273,99 @@ class ActionStepFrame(QFrame):
|
||||
self.setFrameShape(QFrame.StyledPanel)
|
||||
self.setFrameShadow(QFrame.Raised)
|
||||
self.setFixedHeight(35)
|
||||
layout = QHBoxLayout(self)
|
||||
layout.setContentsMargins(2, 2, 2, 2)
|
||||
layout.setSpacing(4)
|
||||
self.opTypeCombo = makeComboWidget(ACTION_OPTIONS, min_width=70, parent=self)
|
||||
layout.addWidget(self.opTypeCombo)
|
||||
layout.addWidget(makeLabel("设置", self))
|
||||
self.targetCombo = QComboBox(self)
|
||||
self.targetCombo.setFixedHeight(25)
|
||||
self.targetCombo.setMinimumWidth(120)
|
||||
Layout = QHBoxLayout(self)
|
||||
Layout.setContentsMargins(2, 2, 2, 2)
|
||||
Layout.setSpacing(4)
|
||||
self.OpTypeCombo = makeComboWidget(ACTION_OPTIONS, min_width=70, parent=self)
|
||||
Layout.addWidget(self.OpTypeCombo)
|
||||
Layout.addWidget(makeLabel("设置", self))
|
||||
self.TargetCombo = QComboBox(self)
|
||||
self.TargetCombo.setFixedHeight(25)
|
||||
self.TargetCombo.setMinimumWidth(120)
|
||||
self.populateTargetCombo()
|
||||
layout.addWidget(self.targetCombo)
|
||||
layout.addWidget(makeLabel("为", self))
|
||||
self.valueSrcCombo = makeComboWidget([
|
||||
Layout.addWidget(self.TargetCombo)
|
||||
Layout.addWidget(makeLabel("为", self))
|
||||
self.ValueSrcCombo = makeComboWidget([
|
||||
("特定值", "literal"),
|
||||
("变量", "variable"),
|
||||
], min_width=70, parent=self)
|
||||
layout.addWidget(self.valueSrcCombo)
|
||||
self.valueStack = QStackedWidget(self)
|
||||
self.valueStack.setFixedHeight(25)
|
||||
Layout.addWidget(self.ValueSrcCombo)
|
||||
self.ValueStack = QStackedWidget(self)
|
||||
self.ValueStack.setFixedHeight(25)
|
||||
self.initValueStacks()
|
||||
layout.addWidget(self.valueStack)
|
||||
self.existingVarCombo = makeVarRefCombo(self)
|
||||
self.existingVarCombo.setVisible(False)
|
||||
layout.addWidget(self.existingVarCombo)
|
||||
self.deleteBtn = QPushButton("×", self)
|
||||
self.deleteBtn.setFixedSize(25, 25)
|
||||
self.deleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||
layout.addWidget(self.deleteBtn)
|
||||
Layout.addWidget(self.ValueStack)
|
||||
self.ExistingVarCombo = makeVarRefCombo(self)
|
||||
self.ExistingVarCombo.setVisible(False)
|
||||
Layout.addWidget(self.ExistingVarCombo)
|
||||
self.DeleteBtn = QPushButton("×", self)
|
||||
self.DeleteBtn.setFixedSize(25, 25)
|
||||
self.DeleteBtn.setStyleSheet("color: red; font-weight: bold;")
|
||||
Layout.addWidget(self.DeleteBtn)
|
||||
self.setUpdatesEnabled(True)
|
||||
|
||||
def populateTargetCombo(
|
||||
self
|
||||
):
|
||||
|
||||
self.targetCombo.blockSignals(True)
|
||||
self.targetCombo.clear()
|
||||
self.TargetCombo.blockSignals(True)
|
||||
self.TargetCombo.clear()
|
||||
for p in getPresetVars():
|
||||
if p["name"] in ("CURRENT_TIME", "CURRENT_DATE"):
|
||||
continue
|
||||
info = self._varMgr.getInfoByName(p["name"])
|
||||
info = self._var_mgr.getInfoByName(p["name"])
|
||||
if info:
|
||||
self.targetCombo.addItem(
|
||||
self.TargetCombo.addItem(
|
||||
info["display"],
|
||||
(info["name"], info["type"])
|
||||
)
|
||||
self.targetCombo.blockSignals(False)
|
||||
self.TargetCombo.blockSignals(False)
|
||||
|
||||
def initValueStacks(
|
||||
self
|
||||
):
|
||||
|
||||
self._literalWidgets = {}
|
||||
self._offsetWidgets = {}
|
||||
self.literal_widgets = {}
|
||||
self.offset_widgets = {}
|
||||
for vt in getTypeOrder():
|
||||
self._literalWidgets[vt] = makeValueWidget(vt, self.valueStack)
|
||||
self.valueStack.addWidget(self._literalWidgets[vt])
|
||||
self.literal_widgets[vt] = makeValueWidget(vt, self.ValueStack)
|
||||
self.ValueStack.addWidget(self.literal_widgets[vt])
|
||||
if getArithType(vt):
|
||||
self._offsetWidgets[vt] = makeOffsetWidget(vt, self.valueStack)
|
||||
self.valueStack.addWidget(self._offsetWidgets[vt])
|
||||
self.offset_widgets[vt] = makeOffsetWidget(vt, self.ValueStack)
|
||||
self.ValueStack.addWidget(self.offset_widgets[vt])
|
||||
else:
|
||||
lbl = QLabel("(不支持该操作)", self.valueStack)
|
||||
lbl.setFixedHeight(25)
|
||||
self._offsetWidgets[vt] = lbl
|
||||
self.valueStack.addWidget(lbl)
|
||||
Lbl = QLabel("(不支持该操作)", self.ValueStack)
|
||||
Lbl.setFixedHeight(25)
|
||||
self.offset_widgets[vt] = Lbl
|
||||
self.ValueStack.addWidget(Lbl)
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
|
||||
self.opTypeCombo.currentIndexChanged.connect(self.onOpTypeChanged)
|
||||
self.targetCombo.currentIndexChanged.connect(self.onTargetChanged)
|
||||
self.valueSrcCombo.currentIndexChanged.connect(self.onValueSrcChanged)
|
||||
self.OpTypeCombo.currentIndexChanged.connect(self.onOpTypeChanged)
|
||||
self.TargetCombo.currentIndexChanged.connect(self.onTargetChanged)
|
||||
self.ValueSrcCombo.currentIndexChanged.connect(self.onValueSrcChanged)
|
||||
|
||||
def getTargetName(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
data = self.targetCombo.currentData()
|
||||
data = self.TargetCombo.currentData()
|
||||
return data[0] if data else ""
|
||||
|
||||
def updateValueWidget(
|
||||
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])
|
||||
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._literalWidgets.get("String"))
|
||||
self.ValueStack.setCurrentWidget(self.literal_widgets.get("String"))
|
||||
|
||||
def toScript(
|
||||
self
|
||||
@@ -375,42 +375,42 @@ class ActionStepFrame(QFrame):
|
||||
"""
|
||||
|
||||
target = self.getTargetName()
|
||||
op = self.opTypeCombo.currentData()
|
||||
op = self.OpTypeCombo.currentData()
|
||||
if op == "pass":
|
||||
return " -- pass"
|
||||
if not target:
|
||||
return ""
|
||||
rawVal = self.getValueRaw()
|
||||
vartype = self._currentTargetType
|
||||
raw_val = self.getValueRaw()
|
||||
vartype = self._current_target_type
|
||||
if op == "set":
|
||||
encoded = encodeValueStr(rawVal, vartype)
|
||||
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()
|
||||
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()
|
||||
if vartype == "Time" and hasattr(self.ValueStack.currentWidget(), "getOffsetHours"):
|
||||
hours = self.ValueStack.currentWidget().getOffsetHours()
|
||||
return f" {target} = timeadd({target}, {hours})"
|
||||
return f" {target} = {target} + {rawVal}"
|
||||
return f" {target} = {target} + {raw_val}"
|
||||
elif op == "sub":
|
||||
if vartype == "Date" and hasattr(self.valueStack.currentWidget(), "getOffsetDays"):
|
||||
days = self.valueStack.currentWidget().getOffsetDays()
|
||||
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()
|
||||
if vartype == "Time" and hasattr(self.ValueStack.currentWidget(), "getOffsetHours"):
|
||||
hours = self.ValueStack.currentWidget().getOffsetHours()
|
||||
return f" {target} = timeadd({target}, -{hours})"
|
||||
return f" {target} = {target} - {rawVal}"
|
||||
return f" {target} = {target} - {raw_val}"
|
||||
return ""
|
||||
|
||||
def getValueRaw(
|
||||
self
|
||||
) -> str:
|
||||
|
||||
if self.valueSrcCombo.currentData() == "variable":
|
||||
data = self.existingVarCombo.currentData()
|
||||
if self.ValueSrcCombo.currentData() == "variable":
|
||||
data = self.ExistingVarCombo.currentData()
|
||||
return data[0] if data else ""
|
||||
w = self.valueStack.currentWidget()
|
||||
w = self.ValueStack.currentWidget()
|
||||
if w:
|
||||
return getValueFromWidget(w)
|
||||
return ""
|
||||
@@ -419,15 +419,15 @@ class ActionStepFrame(QFrame):
|
||||
self
|
||||
):
|
||||
|
||||
currentData = self.targetCombo.currentData()
|
||||
current_data = self.TargetCombo.currentData()
|
||||
self.populateTargetCombo()
|
||||
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)
|
||||
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._varMgr.populateCombo(self.existingVarCombo)
|
||||
self._var_mgr.populateCombo(self.ExistingVarCombo)
|
||||
|
||||
@Slot(int)
|
||||
def onTargetChanged(
|
||||
@@ -437,13 +437,13 @@ class ActionStepFrame(QFrame):
|
||||
|
||||
if idx < 0:
|
||||
return
|
||||
data = self.targetCombo.itemData(idx)
|
||||
data = self.TargetCombo.itemData(idx)
|
||||
if not data:
|
||||
return
|
||||
_, vartype = data
|
||||
self._currentTargetType = vartype
|
||||
self._current_target_type = vartype
|
||||
self.updateValueWidget()
|
||||
self.onValueSrcChanged(self.valueSrcCombo.currentIndex())
|
||||
self.onValueSrcChanged(self.ValueSrcCombo.currentIndex())
|
||||
|
||||
@Slot(int)
|
||||
def onOpTypeChanged(
|
||||
@@ -459,10 +459,10 @@ class ActionStepFrame(QFrame):
|
||||
idx
|
||||
):
|
||||
|
||||
isVar = (self.valueSrcCombo.currentData() == "variable")
|
||||
self.valueStack.setVisible(not isVar)
|
||||
self.existingVarCombo.setVisible(isVar)
|
||||
if isVar:
|
||||
self._varMgr.populateCombo(self.existingVarCombo)
|
||||
is_var = (self.ValueSrcCombo.currentData() == "variable")
|
||||
self.ValueStack.setVisible(not is_var)
|
||||
self.ExistingVarCombo.setVisible(is_var)
|
||||
if is_var:
|
||||
self._var_mgr.populateCombo(self.ExistingVarCombo)
|
||||
else:
|
||||
self.updateValueWidget()
|
||||
@@ -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}")
|
||||
+35
-58
@@ -42,6 +42,7 @@ from gui.ALUserTreeWidget import (
|
||||
ALUserTreeWidget
|
||||
)
|
||||
from gui.ALWebDriverDownloadDialog import ALWebDriverDownloadDialog
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
from gui.resources.ui.Ui_ALConfigWidget import Ui_ALConfigWidget
|
||||
from interfaces.ConfigProvider import (
|
||||
CfgKey,
|
||||
@@ -52,7 +53,7 @@ from utils.JSONReader import JSONReader
|
||||
from utils.JSONWriter import JSONWriter
|
||||
|
||||
|
||||
class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
class ALConfigWidget(CenterOnParentMixin, QWidget, Ui_ALConfigWidget):
|
||||
|
||||
configWidgetIsClosed = Signal()
|
||||
|
||||
@@ -110,29 +111,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||
self.CancelButton.clicked.connect(self.onCancelButtonClicked)
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
|
||||
return result
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
@@ -787,19 +765,19 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
room = self.RoomComboBox.currentText()
|
||||
floor_idx = self.__floor_rmap[floor]
|
||||
room_idx = self.__room_rmap[room]
|
||||
dialog = ALSeatMapSelectDialog(
|
||||
Dialog = ALSeatMapSelectDialog(
|
||||
self,
|
||||
floor,
|
||||
room,
|
||||
ALSeatMapTable[floor_idx][room_idx]
|
||||
)
|
||||
dialog.selectSeats(self.SeatIDEdit.text().split(","))
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
selected_seats = dialog.getSelectedSeats()
|
||||
Dialog.selectSeats(self.SeatIDEdit.text().split(","))
|
||||
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
selected_seats = Dialog.getSelectedSeats()
|
||||
if len(selected_seats) == 0:
|
||||
self.SeatIDEdit.clear()
|
||||
return
|
||||
self.SeatIDEdit.setText(",".join(dialog.getSelectedSeats()))
|
||||
self.SeatIDEdit.setText(",".join(Dialog.getSelectedSeats()))
|
||||
|
||||
@Slot()
|
||||
def onUserTreeWidgetCurrentItemChanged(
|
||||
@@ -857,9 +835,9 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
menu: QMenu
|
||||
):
|
||||
|
||||
add_group_action = QAction("添加分组", menu)
|
||||
add_group_action.triggered.connect(self.addGroup)
|
||||
menu.addAction(add_group_action)
|
||||
AddGroupAction = QAction("添加分组", menu)
|
||||
AddGroupAction.triggered.connect(self.addGroup)
|
||||
menu.addAction(AddGroupAction)
|
||||
|
||||
def showGroupMenu(
|
||||
self,
|
||||
@@ -867,18 +845,18 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
group_item: QTreeWidgetItem = None
|
||||
):
|
||||
|
||||
add_user_action = QAction("添加用户", menu)
|
||||
rename_group_action = QAction("重命名分组", menu)
|
||||
del_group_action = QAction("删除分组", menu)
|
||||
add_user_action.triggered.connect(lambda: self.addUser(group_item))
|
||||
rename_group_action.triggered.connect(lambda: self.renameItem(group_item))
|
||||
del_group_action.triggered.connect(lambda: self.delGroup(group_item))
|
||||
menu.addAction(add_user_action)
|
||||
AddUserAction = QAction("添加用户", menu)
|
||||
RenameGroupAction = QAction("重命名分组", menu)
|
||||
DelGroupAction = QAction("删除分组", menu)
|
||||
AddUserAction.triggered.connect(lambda: self.addUser(group_item))
|
||||
RenameGroupAction.triggered.connect(lambda: self.renameItem(group_item))
|
||||
DelGroupAction.triggered.connect(lambda: self.delGroup(group_item))
|
||||
menu.addAction(AddUserAction)
|
||||
menu.addSeparator()
|
||||
menu.addAction(rename_group_action)
|
||||
menu.addAction(del_group_action)
|
||||
menu.addAction(RenameGroupAction)
|
||||
menu.addAction(DelGroupAction)
|
||||
if group_item.checkState(1) == Qt.CheckState.Unchecked:
|
||||
add_user_action.setEnabled(False)
|
||||
AddUserAction.setEnabled(False)
|
||||
|
||||
def showUserMenu(
|
||||
self,
|
||||
@@ -886,12 +864,12 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
user_item: QTreeWidgetItem = None
|
||||
):
|
||||
|
||||
rename_user_action = QAction("重命名用户", menu)
|
||||
del_user_action = QAction("删除用户", menu)
|
||||
rename_user_action.triggered.connect(lambda: self.renameItem(user_item))
|
||||
del_user_action.triggered.connect(lambda: self.delUser(user_item))
|
||||
menu.addAction(rename_user_action)
|
||||
menu.addAction(del_user_action)
|
||||
RenameUserAction = QAction("重命名用户", menu)
|
||||
DelUserAction = QAction("删除用户", menu)
|
||||
RenameUserAction.triggered.connect(lambda: self.renameItem(user_item))
|
||||
DelUserAction.triggered.connect(lambda: self.delUser(user_item))
|
||||
menu.addAction(RenameUserAction)
|
||||
menu.addAction(DelUserAction)
|
||||
|
||||
@Slot()
|
||||
def onUserTreeWidgetContextMenu(
|
||||
@@ -900,14 +878,14 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
):
|
||||
|
||||
current_item = self.UserTreeWidget.itemAt(pos)
|
||||
menu = QMenu(self.UserTreeWidget)
|
||||
Menu = QMenu(self.UserTreeWidget)
|
||||
if current_item is None:
|
||||
self.showTreeMenu(menu)
|
||||
self.showTreeMenu(Menu)
|
||||
elif current_item.type() == ALUserTreeItemType.GROUP.value:
|
||||
self.showGroupMenu(menu, current_item)
|
||||
self.showGroupMenu(Menu, current_item)
|
||||
else:
|
||||
self.showUserMenu(menu, current_item)
|
||||
menu.exec_(self.UserTreeWidget.mapToGlobal(pos))
|
||||
self.showUserMenu(Menu, current_item)
|
||||
Menu.exec_(self.UserTreeWidget.mapToGlobal(pos))
|
||||
|
||||
@Slot()
|
||||
def onAddUserButtonClicked(
|
||||
@@ -944,10 +922,10 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
self
|
||||
):
|
||||
|
||||
dialog = ALWebDriverDownloadDialog(self)
|
||||
dialog.show()
|
||||
dialog.exec_()
|
||||
selected_driver_info = dialog.getSelectedDriverInfo()
|
||||
Dialog = ALWebDriverDownloadDialog(self)
|
||||
Dialog.show()
|
||||
Dialog.exec_()
|
||||
selected_driver_info = Dialog.getSelectedDriverInfo()
|
||||
if selected_driver_info and selected_driver_info.driver_path:
|
||||
self.BrowserTypeComboBox.setCurrentText(selected_driver_info.driver_type.value)
|
||||
self.BrowseBrowserDriverEdit.setText(QDir.toNativeSeparators(str(selected_driver_info.driver_path)))
|
||||
@@ -1056,7 +1034,6 @@ class ALConfigWidget(QWidget, Ui_ALConfigWidget):
|
||||
):
|
||||
|
||||
msg = ""
|
||||
|
||||
run_config_path = self.ExportRunConfigEdit.text()
|
||||
user_config_path = self.ExportUserConfigEdit.text()
|
||||
if run_config_path:
|
||||
|
||||
+293
-147
@@ -9,11 +9,12 @@ See the LICENSE file for details.
|
||||
"""
|
||||
import queue
|
||||
|
||||
import packaging.version as ver
|
||||
|
||||
from PySide6.QtCore import (
|
||||
QTimer,
|
||||
QUrl,
|
||||
Qt,
|
||||
Signal,
|
||||
Slot
|
||||
)
|
||||
from PySide6.QtGui import (
|
||||
@@ -32,89 +33,89 @@ from PySide6.QtWidgets import (
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
from gui.ALAboutDialog import ALAboutDialog
|
||||
from gui.ALBulletinDialog import ALBulletinDialog
|
||||
from gui.ALCheckUpdateWorker import ALCheckUpdateWorker
|
||||
from gui.ALCheckUpdateDialog import ALCheckUpdateDialog
|
||||
from gui.ALConfigWidget import ALConfigWidget
|
||||
from gui.ALMainWorkers import (
|
||||
AutoLibWorker,
|
||||
TimerTaskWorker
|
||||
)
|
||||
from gui.ALSettingsWidget import ALSettingsWidget
|
||||
from gui.ALTimerTaskManageWidget import ALTimerTaskManageWidget
|
||||
from gui.ALMainWorker import AutoLibWorker
|
||||
from gui.ALBulletinPoller import ALBulletinPoller
|
||||
from gui.ALTimerTaskPoller import ALTimerTaskPoller
|
||||
from gui.ALVersionInfo import AL_VERSION
|
||||
from gui.resources import ALResource
|
||||
from gui.resources.ui.Ui_ALMainWindow import Ui_ALMainWindow
|
||||
from managers.bulletin.BulletinManager import instance as bulletinInstance
|
||||
from managers.config.ConfigUtils import ConfigUtils
|
||||
|
||||
|
||||
class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
|
||||
# signal : timer task
|
||||
timerTaskIsRunning = Signal(dict)
|
||||
timerTaskIsExecuted = Signal(dict)
|
||||
timerTaskIsError = Signal(dict)
|
||||
|
||||
def __init__(
|
||||
self
|
||||
):
|
||||
|
||||
MsgBase.__init__(self, queue.Queue(), queue.Queue())
|
||||
QMainWindow.__init__(self)
|
||||
self.__timer_task_queue = queue.Queue()
|
||||
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
||||
self.__alTimerTaskManageWidget = None
|
||||
self.__alConfigWidget = None
|
||||
self.__ALTimerTaskManageWidget = None
|
||||
self.__ALConfigWidget = None
|
||||
self.__ALSettingsWidget = None
|
||||
self.__ALBulletinDialog = None
|
||||
self.__auto_lib_thread = None
|
||||
self.__current_timer_task_thread = None
|
||||
self.__is_running_timer_task = False
|
||||
self.__bulletin_poller = ALBulletinPoller(self)
|
||||
self.__timer_task_poller = ALTimerTaskPoller(
|
||||
self,
|
||||
self._input_queue,
|
||||
self._output_queue,
|
||||
self.__config_paths
|
||||
)
|
||||
self.__notification_type = ""
|
||||
|
||||
self.setupUi(self)
|
||||
self.modifyUi()
|
||||
self.setupTray()
|
||||
self.connectSignals()
|
||||
self.startMsgPolling()
|
||||
self.startTimerTaskPolling()
|
||||
self.__timer_task_poller.start()
|
||||
self.__bulletin_poller.start()
|
||||
if bulletinInstance().autoFetch():
|
||||
QTimer.singleShot(1000, self.__bulletin_poller.fetchNow)
|
||||
self._showLog("主窗口初始化完成")
|
||||
|
||||
def modifyUi(
|
||||
self
|
||||
):
|
||||
|
||||
self.icon = QIcon(":/res/icons/AutoLibrary_Logo_64.svg")
|
||||
self.setWindowIcon(self.icon)
|
||||
self.Icon = QIcon(":/res/icons/AutoLibrary_Logo_64.svg")
|
||||
self.setWindowIcon(self.Icon)
|
||||
self.MessageIOTextEdit.setFont(QFont("Courier New", 10))
|
||||
self.ManualAction.triggered.connect(self.onManualActionTriggered)
|
||||
self.CheckUpdateAction.triggered.connect(self.onCheckUpdateActionTriggered)
|
||||
self.AboutAction.triggered.connect(self.onAboutActionTriggered)
|
||||
|
||||
self.SettingsAction.triggered.connect(self.onSettingsActionTriggered)
|
||||
self.BulletinAction.triggered.connect(self.onBulletinActionTriggered)
|
||||
# initialize timer task widget, but not show it
|
||||
try:
|
||||
self.__alTimerTaskManageWidget = ALTimerTaskManageWidget(self)
|
||||
self.__ALTimerTaskManageWidget = ALTimerTaskManageWidget(self)
|
||||
except Exception as e:
|
||||
QMessageBox.critical(
|
||||
self,
|
||||
"错误 - AutoLibrary",
|
||||
f"初始化定时任务功能失败: \n{e}"
|
||||
)
|
||||
self.__alTimerTaskManageWidget = None
|
||||
self.__ALTimerTaskManageWidget = None
|
||||
self.TimerTaskManageWidgetButton.setEnabled(False)
|
||||
self.TimerTaskManageWidgetButton.setToolTip("定时任务功能初始化失败, 请检查配置文件。")
|
||||
return
|
||||
self.timerTaskIsRunning.connect(self.__alTimerTaskManageWidget.onTimerTaskIsRunning)
|
||||
self.timerTaskIsExecuted.connect(self.__alTimerTaskManageWidget.onTimerTaskIsExecuted)
|
||||
self.timerTaskIsError.connect(self.__alTimerTaskManageWidget.onTimerTaskIsError)
|
||||
self.__alTimerTaskManageWidget.timerTaskIsReady.connect(self.onTimerTaskIsReady)
|
||||
self.__alTimerTaskManageWidget.timerTaskManageWidgetIsClosed.connect(self.onTimerTaskManageWidgetClosed)
|
||||
self.__alTimerTaskManageWidget.setWindowFlags(Qt.WindowType.Window|Qt.WindowType.WindowCloseButtonHint)
|
||||
|
||||
def onAboutActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
about_dialog = ALAboutDialog(self)
|
||||
about_dialog.exec()
|
||||
|
||||
def onManualActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
url = QUrl("https://www.autolibrary.kenanzhu.com/manuals")
|
||||
QDesktopServices.openUrl(url)
|
||||
self.__timer_task_poller.taskRunning.connect(self.onTimerTaskRunning)
|
||||
self.__timer_task_poller.taskFinished.connect(self.onTimerTaskFinished)
|
||||
self.__timer_task_poller.taskRunning.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsRunning)
|
||||
self.__timer_task_poller.taskExecuted.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsExecuted)
|
||||
self.__timer_task_poller.taskError.connect(self.__ALTimerTaskManageWidget.onTimerTaskIsError)
|
||||
self.__ALTimerTaskManageWidget.timerTaskIsReady.connect(self.__timer_task_poller.enqueue)
|
||||
self.__ALTimerTaskManageWidget.timerTaskManageWidgetIsClosed.connect(self.onTimerTaskManageWidgetClosed)
|
||||
self.__ALTimerTaskManageWidget.setWindowFlags(Qt.WindowType.Window|Qt.WindowType.WindowCloseButtonHint)
|
||||
|
||||
def setupTray(
|
||||
self
|
||||
@@ -123,9 +124,8 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
if not QSystemTrayIcon.isSystemTrayAvailable():
|
||||
self._showTrace("操作系统不支持系统托盘功能, 无法创建系统托盘图标", self.TraceLevel.WARNING)
|
||||
return
|
||||
self.TrayIcon = QSystemTrayIcon(self.icon, self)
|
||||
self.TrayIcon = QSystemTrayIcon(self.Icon, self)
|
||||
self.TrayIcon.setToolTip("AutoLibrary")
|
||||
|
||||
self.TrayMenu = QMenu()
|
||||
self.TrayMenu.addAction("显示主窗口", self.showNormal)
|
||||
self.TrayMenu.addAction("显示定时窗口", self.onTimerTaskManageWidgetButtonClicked)
|
||||
@@ -133,8 +133,8 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self.TrayMenu.addSeparator()
|
||||
self.TrayMenu.addAction("退出", self.close)
|
||||
self.TrayIcon.setContextMenu(self.TrayMenu)
|
||||
|
||||
self.TrayIcon.activated.connect(self.onTrayIconActivated)
|
||||
self.TrayIcon.messageClicked.connect(self.onTrayMessageClicked)
|
||||
self.TrayIcon.show()
|
||||
|
||||
def hideToTray(
|
||||
@@ -142,6 +142,9 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
):
|
||||
|
||||
self.hide()
|
||||
self.__notification_type = ""
|
||||
if not hasattr(self, "TrayIcon"):
|
||||
return
|
||||
self.TrayIcon.showMessage(
|
||||
"AutoLibrary",
|
||||
"\n已最小化到托盘",
|
||||
@@ -149,14 +152,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
2000
|
||||
)
|
||||
|
||||
def onTrayIconActivated(
|
||||
self,
|
||||
reason: QSystemTrayIcon.ActivationReason
|
||||
):
|
||||
|
||||
if reason == QSystemTrayIcon.DoubleClick:
|
||||
self.showNormal()
|
||||
|
||||
def connectSignals(
|
||||
self
|
||||
):
|
||||
@@ -167,6 +162,7 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self.StopButton.clicked.connect(self.onStopButtonClicked)
|
||||
self.SendButton.clicked.connect(self.onSendButtonClicked)
|
||||
self.MessageEdit.returnPressed.connect(self.onSendButtonClicked)
|
||||
self.__bulletin_poller.newBulletinsDetected.connect(self.onBulletinPollerNewBulletins)
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
@@ -179,17 +175,22 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
return
|
||||
if self.__msg_queue_timer and self.__msg_queue_timer.isActive():
|
||||
self.__msg_queue_timer.stop()
|
||||
if self.__timer_task_timer and self.__timer_task_timer.isActive():
|
||||
self.__timer_task_timer.stop()
|
||||
if self.__is_running_timer_task:
|
||||
self.__current_timer_task_thread.wait(2000)
|
||||
self.__current_timer_task_thread.deleteLater()
|
||||
if self.__alTimerTaskManageWidget:
|
||||
self.__alTimerTaskManageWidget.close()
|
||||
self.__alTimerTaskManageWidget.deleteLater()
|
||||
if self.__alConfigWidget:
|
||||
self.__alConfigWidget.close()
|
||||
if self.__timer_task_poller:
|
||||
self.__timer_task_poller.stop()
|
||||
if self.__ALTimerTaskManageWidget:
|
||||
self.__ALTimerTaskManageWidget.close()
|
||||
self.__ALTimerTaskManageWidget.deleteLater()
|
||||
if self.__ALConfigWidget:
|
||||
self.__ALConfigWidget.close()
|
||||
# the config widget is already deleted in the 'self.onConfigWidgetClosed'
|
||||
if self.__ALSettingsWidget:
|
||||
self.__ALSettingsWidget.close()
|
||||
# the settings widget is already deleted in the 'self.onSettingsWidgetClosed'
|
||||
if self.__ALBulletinDialog:
|
||||
self.__ALBulletinDialog.close()
|
||||
# the bulletin dialog is already deleted in the 'self.onBulletinDialogClosed'
|
||||
if self.__bulletin_poller:
|
||||
self.__bulletin_poller.stop()
|
||||
self._showLog("主窗口关闭")
|
||||
QMainWindow.closeEvent(self, event)
|
||||
|
||||
@@ -214,47 +215,6 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self.__msg_queue_timer.timeout.connect(self.pollMsgQueue)
|
||||
self.__msg_queue_timer.start(100)
|
||||
|
||||
def startTimerTaskPolling(
|
||||
self
|
||||
):
|
||||
|
||||
self.__timer_task_timer = QTimer()
|
||||
self.__timer_task_timer.timeout.connect(self.pollTimerTaskQueue)
|
||||
self.__timer_task_timer.start(500)
|
||||
|
||||
def pollTimerTaskQueue(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__is_running_timer_task:
|
||||
return
|
||||
try:
|
||||
while not self.__is_running_timer_task:
|
||||
timer_task = self.__timer_task_queue.get_nowait()
|
||||
self.timerTaskIsRunning.emit(timer_task)
|
||||
self.__timer_task_timer.stop()
|
||||
self.__is_running_timer_task = True
|
||||
self.setControlButtons(None, True, False)
|
||||
if not timer_task["silent"]:
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n已开始执行定时任务: \n{timer_task['name']}",
|
||||
QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self.showNormal()
|
||||
self.__current_timer_task_thread = TimerTaskWorker(
|
||||
timer_task,
|
||||
self._input_queue,
|
||||
self._output_queue,
|
||||
self.__config_paths
|
||||
)
|
||||
self.__current_timer_task_thread.timerTaskWorkerIsFinished.connect(self.onTimerTaskFinished)
|
||||
self.__current_timer_task_thread.start()
|
||||
except queue.Empty:
|
||||
self.__is_running_timer_task = False
|
||||
pass
|
||||
|
||||
def setControlButtons(
|
||||
self,
|
||||
config_button_enabled: bool,
|
||||
@@ -282,6 +242,145 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
except queue.Empty:
|
||||
pass
|
||||
|
||||
@Slot(int)
|
||||
def onBulletinPollerNewBulletins(
|
||||
self,
|
||||
count: int
|
||||
):
|
||||
|
||||
if not hasattr(self, "TrayIcon"):
|
||||
return
|
||||
self.__notification_type = "bulletin"
|
||||
self.TrayIcon.showMessage(
|
||||
"公告栏 - AutoLibrary",
|
||||
f"有 {count} 条新公告,点击查看详情。",
|
||||
QSystemTrayIcon.MessageIcon.Information,
|
||||
3000
|
||||
)
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskRunning(
|
||||
self,
|
||||
timer_task: dict
|
||||
):
|
||||
|
||||
self.setControlButtons(None, True, False)
|
||||
self.__notification_type = ""
|
||||
if not hasattr(self, "TrayIcon"):
|
||||
return
|
||||
if not timer_task.get("silent", False):
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n已开始执行定时任务: \n{timer_task['name']}",
|
||||
QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self.showNormal()
|
||||
|
||||
@Slot(bool, dict)
|
||||
def onTimerTaskFinished(
|
||||
self,
|
||||
is_error: bool,
|
||||
timer_task: dict
|
||||
):
|
||||
|
||||
self.setControlButtons(None, False, True)
|
||||
self.__notification_type = ""
|
||||
if not hasattr(self, "TrayIcon"):
|
||||
return
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n定时任务 '{timer_task['name']}' 执行{'失败' if is_error else '完成'}",
|
||||
QSystemTrayIcon.MessageIcon.Warning if is_error else QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self._showTrace(
|
||||
f"定时任务 {timer_task['name']} 执行{'失败' if is_error else '完成'}, uuid: {timer_task['uuid']}"
|
||||
)
|
||||
|
||||
@Slot(dict)
|
||||
def onCheckUpdateIsFinished(
|
||||
self,
|
||||
data: dict
|
||||
):
|
||||
|
||||
worker = self.sender()
|
||||
if worker is not self.__check_update_worker:
|
||||
return
|
||||
worker.checkUpdateWorkerIsFinished.disconnect(self.onCheckUpdateIsFinished)
|
||||
worker.checkUpdateWorkerFinishedWithError.disconnect(self.onCheckUpdateFinishedWithError)
|
||||
worker.wait(3000)
|
||||
worker.deleteLater()
|
||||
self.__check_update_worker = None
|
||||
tag_name = data.get("tag_name", "")
|
||||
html_url = data.get("html_url", "")
|
||||
latest_version = tag_name.lstrip("v")
|
||||
try:
|
||||
local_ver = ver.Version(AL_VERSION)
|
||||
remote_ver = ver.Version(latest_version)
|
||||
except ver.InvalidVersion:
|
||||
self._showTrace("版本号解析失败, 无法比较版本", self.TraceLevel.WARNING)
|
||||
return
|
||||
if remote_ver > local_ver:
|
||||
ALCheckUpdateDialog.showResult(
|
||||
self,
|
||||
has_update=True,
|
||||
current_version=AL_VERSION,
|
||||
latest_version=latest_version,
|
||||
tag_name=tag_name,
|
||||
html_url=html_url
|
||||
)
|
||||
else:
|
||||
ALCheckUpdateDialog.showResult(
|
||||
self,
|
||||
has_update=False,
|
||||
current_version=AL_VERSION
|
||||
)
|
||||
self._showLog("检查更新完成")
|
||||
|
||||
@Slot(str)
|
||||
def onCheckUpdateFinishedWithError(
|
||||
self,
|
||||
error_message: str
|
||||
):
|
||||
|
||||
worker = self.sender()
|
||||
if worker is not self.__check_update_worker:
|
||||
return
|
||||
worker.checkUpdateWorkerIsFinished.disconnect(self.onCheckUpdateIsFinished)
|
||||
worker.checkUpdateWorkerFinishedWithError.disconnect(self.onCheckUpdateFinishedWithError)
|
||||
worker.wait(3000)
|
||||
worker.deleteLater()
|
||||
self.__check_update_worker = None
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"检查更新 - AutoLibrary",
|
||||
f"检查更新失败: \n{error_message}",
|
||||
)
|
||||
self._showLog("检查更新失败")
|
||||
|
||||
@Slot()
|
||||
def onBulletinDialogClosed(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__ALBulletinDialog:
|
||||
self.__ALBulletinDialog.finished.disconnect(self.onBulletinDialogClosed)
|
||||
self.__ALBulletinDialog.deleteLater()
|
||||
self.__ALBulletinDialog = None
|
||||
self.__bulletin_poller.setDialogOpen(False)
|
||||
|
||||
@Slot()
|
||||
def onSettingsWidgetClosed(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__ALSettingsWidget:
|
||||
self.__ALSettingsWidget.settingsWidgetIsClosed.disconnect(self.onSettingsWidgetClosed)
|
||||
self.__ALSettingsWidget.deleteLater()
|
||||
self.__ALSettingsWidget = None
|
||||
self.SettingsAction.setEnabled(True)
|
||||
|
||||
@Slot()
|
||||
def onTimerTaskManageWidgetClosed(
|
||||
self
|
||||
@@ -294,59 +393,106 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self
|
||||
):
|
||||
|
||||
if self.__alConfigWidget:
|
||||
self.__alConfigWidget.configWidgetIsClosed.disconnect(self.onConfigWidgetClosed)
|
||||
self.__alConfigWidget.deleteLater()
|
||||
self.__alConfigWidget = None
|
||||
if self.__ALConfigWidget:
|
||||
self.__ALConfigWidget.configWidgetIsClosed.disconnect(self.onConfigWidgetClosed)
|
||||
self.__ALConfigWidget.deleteLater()
|
||||
self.__ALConfigWidget = None
|
||||
self.__config_paths = ConfigUtils.getAutomationConfigPaths()
|
||||
self.__timer_task_poller.updateConfigPaths(self.__config_paths)
|
||||
self.setControlButtons(True, None, None)
|
||||
self._showLog("配置窗口已关闭,配置文件路径已更新")
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskIsReady(
|
||||
self,
|
||||
timer_task: dict
|
||||
@Slot()
|
||||
def onBulletinActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
self.__timer_task_queue.put(timer_task)
|
||||
if self.__ALBulletinDialog is None:
|
||||
self.__ALBulletinDialog = ALBulletinDialog(self)
|
||||
self.__ALBulletinDialog.finished.connect(self.onBulletinDialogClosed)
|
||||
self.__bulletin_poller.setDialogOpen(True)
|
||||
self.__ALBulletinDialog.show()
|
||||
self.__ALBulletinDialog.raise_()
|
||||
self.__ALBulletinDialog.activateWindow()
|
||||
self._showLog("打开公告栏窗口")
|
||||
|
||||
@Slot(dict)
|
||||
def onTimerTaskFinished(
|
||||
self,
|
||||
is_error: bool,
|
||||
timer_task: dict
|
||||
@Slot()
|
||||
def onSettingsActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
self.__current_timer_task_thread.wait(1000)
|
||||
self.__current_timer_task_thread.timerTaskWorkerIsFinished.disconnect(self.onTimerTaskFinished)
|
||||
self.__current_timer_task_thread.deleteLater()
|
||||
self.__current_timer_task_thread = None
|
||||
self.setControlButtons(None, False, True)
|
||||
self.__is_running_timer_task = False
|
||||
self.__timer_task_timer.start(500)
|
||||
timer_task["executed"] = True
|
||||
self.TrayIcon.showMessage(
|
||||
"定时任务 - AutoLibrary",
|
||||
f"\n定时任务 '{timer_task['name']}' 执行{'失败' if is_error else '完成'}",
|
||||
QSystemTrayIcon.MessageIcon.Warning if is_error else QSystemTrayIcon.MessageIcon.Information,
|
||||
1000
|
||||
)
|
||||
self._showTrace(
|
||||
f"定时任务 {timer_task['name']} 执行{'失败' if is_error else '完成'}, uuid: {timer_task['uuid']}"
|
||||
)
|
||||
if not is_error:
|
||||
self.timerTaskIsExecuted.emit(timer_task)
|
||||
else:
|
||||
self.timerTaskIsError.emit(timer_task)
|
||||
if self.__ALSettingsWidget is None:
|
||||
self.__ALSettingsWidget = ALSettingsWidget(self)
|
||||
self.__ALSettingsWidget.settingsWidgetIsClosed.connect(self.onSettingsWidgetClosed)
|
||||
self.__ALSettingsWidget.openBulletinRequested.connect(self.onBulletinActionTriggered)
|
||||
self.__ALSettingsWidget.show()
|
||||
self.__ALSettingsWidget.raise_()
|
||||
self.__ALSettingsWidget.activateWindow()
|
||||
self.SettingsAction.setEnabled(False)
|
||||
self._showLog("打开全局设置窗口")
|
||||
|
||||
@Slot()
|
||||
def onAboutActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
AboutDialog = ALAboutDialog(self)
|
||||
AboutDialog.exec()
|
||||
|
||||
@Slot()
|
||||
def onManualActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
url = QUrl("https://manuals.autolibrary.kenanzhu.com")
|
||||
QDesktopServices.openUrl(url)
|
||||
|
||||
@Slot()
|
||||
def onCheckUpdateActionTriggered(
|
||||
self
|
||||
):
|
||||
|
||||
if hasattr(self, '__check_update_worker') and self.__check_update_worker is not None:
|
||||
return
|
||||
self.__check_update_worker = ALCheckUpdateWorker(self)
|
||||
self.__check_update_worker.checkUpdateWorkerIsFinished.connect(self.onCheckUpdateIsFinished)
|
||||
self.__check_update_worker.checkUpdateWorkerFinishedWithError.connect(self.onCheckUpdateFinishedWithError)
|
||||
self.__check_update_worker.start()
|
||||
self._showLog("正在检查更新...")
|
||||
|
||||
@Slot()
|
||||
def onTrayMessageClicked(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__notification_type == "bulletin":
|
||||
self.__notification_type = ""
|
||||
self.onBulletinActionTriggered()
|
||||
|
||||
@Slot(QSystemTrayIcon.ActivationReason)
|
||||
def onTrayIconActivated(
|
||||
self,
|
||||
reason: QSystemTrayIcon.ActivationReason
|
||||
):
|
||||
|
||||
if reason == QSystemTrayIcon.DoubleClick:
|
||||
self.showNormal()
|
||||
|
||||
@Slot()
|
||||
def onTimerTaskManageWidgetButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
self.__alTimerTaskManageWidget.show()
|
||||
self.__alTimerTaskManageWidget.raise_()
|
||||
self.__alTimerTaskManageWidget.activateWindow()
|
||||
if self.__ALTimerTaskManageWidget is None:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"警告 - AutoLibrary",
|
||||
"定时任务功能初始化失败, 请检查配置文件。"
|
||||
)
|
||||
return
|
||||
self.__ALTimerTaskManageWidget.show()
|
||||
self.__ALTimerTaskManageWidget.raise_()
|
||||
self.__ALTimerTaskManageWidget.activateWindow()
|
||||
self.TimerTaskManageWidgetButton.setEnabled(False)
|
||||
self._showLog("打开定时任务管理窗口")
|
||||
|
||||
@@ -355,12 +501,12 @@ class ALMainWindow(MsgBase, QMainWindow, Ui_ALMainWindow):
|
||||
self
|
||||
):
|
||||
|
||||
if self.__alConfigWidget is None:
|
||||
self.__alConfigWidget = ALConfigWidget(self)
|
||||
self.__alConfigWidget.configWidgetIsClosed.connect(self.onConfigWidgetClosed)
|
||||
self.__alConfigWidget.show()
|
||||
self.__alConfigWidget.raise_()
|
||||
self.__alConfigWidget.activateWindow()
|
||||
if self.__ALConfigWidget is None:
|
||||
self.__ALConfigWidget = ALConfigWidget(self)
|
||||
self.__ALConfigWidget.configWidgetIsClosed.connect(self.onConfigWidgetClosed)
|
||||
self.__ALConfigWidget.show()
|
||||
self.__ALConfigWidget.raise_()
|
||||
self.__ALConfigWidget.activateWindow()
|
||||
self.ConfigButton.setEnabled(False)
|
||||
self._showLog("打开配置窗口")
|
||||
|
||||
|
||||
File renamed without changes.
@@ -24,9 +24,9 @@ from PySide6.QtWidgets import (
|
||||
)
|
||||
|
||||
from gui.ALSeatMapView import ALSeatMapView
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
|
||||
|
||||
class ALSeatMapSelectDialog(QDialog):
|
||||
class ALSeatMapSelectDialog(CenterOnParentMixin, QDialog):
|
||||
|
||||
seatMapSelectDialogIsClosed = Signal(list)
|
||||
|
||||
@@ -55,7 +55,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.setMinimumSize(800, 600)
|
||||
self.resize(800, 600)
|
||||
self.setWindowTitle(f"选择楼层座位 - AutoLibrary")
|
||||
|
||||
self.SeatMapWidgetMainLayout = QVBoxLayout(self)
|
||||
self.SeatMapWidgetMainLayout.setContentsMargins(5, 5, 5, 5)
|
||||
self.SeatMapWidgetMainLayout.setSpacing(5)
|
||||
@@ -63,10 +62,8 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.TitleLabel.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.TitleLabel.setStyleSheet("font-size: 16px; font-weight: bold; margin: 10px;")
|
||||
self.SeatMapWidgetMainLayout.addWidget(self.TitleLabel)
|
||||
|
||||
self.SeatMapGraphicsView = ALSeatMapView(None, self.__seats_data)
|
||||
self.SeatMapWidgetMainLayout.addWidget(self.SeatMapGraphicsView)
|
||||
|
||||
self.TipsLabel = QLabel(
|
||||
" 点击座位进行选择/取消选择, 最多选择1个座位 \n"
|
||||
" [操作方法: Ctrl+鼠标滚轮缩放 | 滚轮/拖拽/方向键 移动]"
|
||||
@@ -74,7 +71,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.TipsLabel.setAlignment(Qt.AlignmentFlag.AlignLeft)
|
||||
self.TipsLabel.setStyleSheet("color: #666; margin: 5px;")
|
||||
self.SeatMapWidgetMainLayout.addWidget(self.TipsLabel)
|
||||
|
||||
self.ConfirmButton = QPushButton("确认")
|
||||
self.ConfirmButton.setFixedSize(80, 25)
|
||||
self.ConfirmButton.setAutoDefault(True)
|
||||
@@ -96,29 +92,6 @@ class ALSeatMapSelectDialog(QDialog):
|
||||
self.ConfirmButton.clicked.connect(self.onConfirmButtonClicked)
|
||||
self.CancelButton.clicked.connect(self.onCancelButtonClicked)
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
|
||||
return result
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
|
||||
@@ -85,11 +85,9 @@ class ALSeatMapView(QGraphicsView):
|
||||
self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||
self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
|
||||
self.viewport().installEventFilter(self)
|
||||
|
||||
self.SeatsContainerWidget = QWidget()
|
||||
self.SeatsContainerLayout = QGridLayout(self.SeatsContainerWidget)
|
||||
self.setupSeatMap()
|
||||
|
||||
self.ContainerProxy = self.SeatMapGraphicsScene.addWidget(self.SeatsContainerWidget)
|
||||
self.ContainerProxy.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, False)
|
||||
|
||||
@@ -103,15 +101,15 @@ class ALSeatMapView(QGraphicsView):
|
||||
seats_number = [seat.strip() for seat in row.split(",")]
|
||||
for seat_number in seats_number:
|
||||
if seat_number:
|
||||
seat_widget = ALSeatFrame(seat_number)
|
||||
seat_widget.clicked.connect(self.onSeatClicked)
|
||||
self.SeatsContainerLayout.addWidget(seat_widget, row_idx, col_idx)
|
||||
self.__seat_frames[seat_number] = seat_widget
|
||||
SeatWidget = ALSeatFrame(seat_number)
|
||||
SeatWidget.clicked.connect(self.onSeatClicked)
|
||||
self.SeatsContainerLayout.addWidget(SeatWidget, row_idx, col_idx)
|
||||
self.__seat_frames[seat_number] = SeatWidget
|
||||
else:
|
||||
spacer = QFrame()
|
||||
spacer.setFixedSize(20, 30)
|
||||
spacer.setStyleSheet("background-color: transparent; border: none;")
|
||||
self.SeatsContainerLayout.addWidget(spacer, row_idx, col_idx)
|
||||
Spacer = QFrame()
|
||||
Spacer.setFixedSize(20, 30)
|
||||
Spacer.setStyleSheet("background-color: transparent; border: none;")
|
||||
self.SeatsContainerLayout.addWidget(Spacer, row_idx, col_idx)
|
||||
col_idx += 1
|
||||
self.SeatsContainerLayout.setSpacing(20)
|
||||
self.SeatsContainerLayout.setContentsMargins(20, 20, 20, 20)
|
||||
|
||||
@@ -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()
|
||||
@@ -56,7 +56,6 @@ class ALStatusLabel(QLabel):
|
||||
|
||||
self.setFixedSize(36, 36)
|
||||
self.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
|
||||
self.RunningAnimation = QPropertyAnimation(self, b"iconAngle")
|
||||
self.RunningAnimation.setDuration(1000)
|
||||
self.RunningAnimation.setStartValue(0)
|
||||
@@ -128,7 +127,6 @@ class ALStatusLabel(QLabel):
|
||||
case self.Status.WAITING:
|
||||
pen = painter.pen()
|
||||
pen.setWidth(2)
|
||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setColor(QColor("#969696")) # grey
|
||||
painter.setPen(pen)
|
||||
@@ -157,7 +155,6 @@ class ALStatusLabel(QLabel):
|
||||
# draw the success green circle
|
||||
pen = painter.pen()
|
||||
pen.setWidth(2)
|
||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setColor(QColor("#4CAF50" if self.isDarkMode() else "#00AF50")) # green
|
||||
painter.setPen(pen)
|
||||
@@ -194,7 +191,6 @@ class ALStatusLabel(QLabel):
|
||||
# draw the warning orange circle
|
||||
pen = painter.pen()
|
||||
pen.setWidth(2)
|
||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setColor(QColor("#FF9800")) # orange
|
||||
painter.setPen(pen)
|
||||
@@ -224,7 +220,6 @@ class ALStatusLabel(QLabel):
|
||||
# draw the failure red circle
|
||||
pen = painter.pen()
|
||||
pen.setWidth(2)
|
||||
pen.setBrush(Qt.BrushStyle.NoBrush)
|
||||
pen.setCapStyle(Qt.PenCapStyle.RoundCap)
|
||||
pen.setColor(QColor("#DC0000")) # red
|
||||
painter.setPen(pen)
|
||||
|
||||
@@ -80,7 +80,6 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
self.SpecificDateTimeEdit.setDateTime(QDateTime.currentDateTime().addSecs(60))
|
||||
self.SpecificTimerLayout.addWidget(self.SpecificDateTimeEdit)
|
||||
self.TimerConfigLayout.addWidget(self.SpecificTimerWidget)
|
||||
|
||||
self.RelativeTimerWidget = QWidget()
|
||||
self.RelativeTimerLayout = QHBoxLayout(self.RelativeTimerWidget)
|
||||
self.RelativeTimerLayout.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -108,17 +107,16 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
self.RelativeTimerLayout.addWidget(self.RelativeSecondSpinBox)
|
||||
self.TimerConfigLayout.addWidget(self.RelativeTimerWidget)
|
||||
self.RelativeTimerWidget.setVisible(False)
|
||||
|
||||
self.AutoScriptGroupBox = QGroupBox("AutoScript 指令")
|
||||
self.AutoScriptLayout = QVBoxLayout(self.AutoScriptGroupBox)
|
||||
self.AutoScriptLayout.setContentsMargins(3, 3, 3, 3)
|
||||
self.AutoScriptLayout.setSpacing(3)
|
||||
autoScriptBtnLayout = QHBoxLayout()
|
||||
AutoScriptBtnLayout = QHBoxLayout()
|
||||
self.AutoScriptEditButton = QPushButton("编辑")
|
||||
self.AutoScriptEditButton.setMinimumHeight(25)
|
||||
self.AutoScriptEditButton.setFixedWidth(80)
|
||||
autoScriptBtnLayout.addWidget(self.AutoScriptEditButton)
|
||||
autoScriptBtnLayout.addStretch()
|
||||
AutoScriptBtnLayout.addWidget(self.AutoScriptEditButton)
|
||||
AutoScriptBtnLayout.addStretch()
|
||||
self.AutoScriptHelpButton = QPushButton("?")
|
||||
self.AutoScriptHelpButton.setFixedSize(20, 20)
|
||||
self.AutoScriptHelpButton.setToolTip(
|
||||
@@ -132,12 +130,12 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
"font-weight: bold; color: #555; }"
|
||||
"QPushButton:hover { background-color: #E0E0E0; }"
|
||||
)
|
||||
autoScriptBtnLayout.addWidget(self.AutoScriptHelpButton)
|
||||
AutoScriptBtnLayout.addWidget(self.AutoScriptHelpButton)
|
||||
self.AutoScriptStatusLabel = QLabel("未设置")
|
||||
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
||||
self.AutoScriptStatusLabel.setFixedHeight(25)
|
||||
autoScriptBtnLayout.addWidget(self.AutoScriptStatusLabel)
|
||||
self.AutoScriptLayout.addLayout(autoScriptBtnLayout)
|
||||
AutoScriptBtnLayout.addWidget(self.AutoScriptStatusLabel)
|
||||
self.AutoScriptLayout.addLayout(AutoScriptBtnLayout)
|
||||
self.ALAddTimerTaskLayout.insertWidget(
|
||||
self.ALAddTimerTaskLayout.indexOf(self.TaskConfigGroupBox) + 1,
|
||||
self.AutoScriptGroupBox
|
||||
@@ -305,18 +303,18 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
@Slot()
|
||||
def onPreviewAutoScript(self):
|
||||
from gui.ALAutoScriptEditDialog import ALAutoScriptEditDialog
|
||||
dlg = ALAutoScriptEditDialog(self, self.__auto_script, self.__mock_target_data)
|
||||
if dlg.exec() == QDialog.DialogCode.Accepted:
|
||||
script = dlg.getScript()
|
||||
Dlg = ALAutoScriptEditDialog(self, self.__auto_script, self.__mock_target_data)
|
||||
if Dlg.exec() == QDialog.DialogCode.Accepted:
|
||||
script = Dlg.getScript()
|
||||
self.__auto_script = script
|
||||
self.__mock_target_data = dlg.getMockData()
|
||||
self.__mock_target_data = Dlg.getMockData()
|
||||
if script:
|
||||
self.AutoScriptStatusLabel.setText("已设置")
|
||||
self.AutoScriptStatusLabel.setStyleSheet("color: #4CAF50;")
|
||||
else:
|
||||
self.AutoScriptStatusLabel.setText("未设置")
|
||||
self.AutoScriptStatusLabel.setStyleSheet("color: #969696;")
|
||||
dlg.deleteLater()
|
||||
Dlg.deleteLater()
|
||||
|
||||
@Slot()
|
||||
def onAutoScriptHelp(
|
||||
@@ -324,5 +322,5 @@ class ALTimerTaskAddDialog(QDialog, Ui_ALTimerTaskAddDialog):
|
||||
):
|
||||
|
||||
QDesktopServices.openUrl(
|
||||
QUrl("https://www.autolibrary.kenanzhu.com/manuals/autoscript")
|
||||
QUrl("https://manuals.autolibrary.kenanzhu.com/zh/autoscript")
|
||||
)
|
||||
@@ -41,7 +41,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
self.setWindowTitle("定时任务执行历史 - AutoLibrary")
|
||||
self.setMinimumSize(300, 300)
|
||||
self.setMaximumSize(500, 400)
|
||||
|
||||
MainLayout = QVBoxLayout(self)
|
||||
InfoLayout = QGridLayout()
|
||||
TaskNameLabel = QLabel(f"任务: {self.__task_data.get('name', '未命名')}")
|
||||
@@ -51,7 +50,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
TaskUUIDLabel.setStyleSheet("color: #969696; font-size: 11px;")
|
||||
InfoLayout.addWidget(TaskUUIDLabel, 1, 0)
|
||||
InfoLayout.setColumnStretch(0, 1)
|
||||
|
||||
if self.__task_data.get("repeat", False):
|
||||
RepeatLabel = QLabel("可重复性任务")
|
||||
RepeatLabel.setStyleSheet("color: #2294FF; font-size: 12px;")
|
||||
@@ -68,7 +66,6 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
self.HistoryTableWidget.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
|
||||
self.loadHistory()
|
||||
MainLayout.addWidget(self.HistoryTableWidget)
|
||||
|
||||
ButtonLayout = QHBoxLayout()
|
||||
ButtonLayout.addStretch()
|
||||
self.CloseButton = QPushButton("关闭")
|
||||
@@ -111,24 +108,24 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
execute_time = record.get("execute_time", "")
|
||||
result = record.get("result", ALTimerTaskStatus.UNKNOWN)
|
||||
duration = record.get("duration", 0)
|
||||
ExecuteTimeItem = QTableWidgetItem(execute_time)
|
||||
ExecuteTimeItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.HistoryTableWidget.setItem(row, 0, ExecuteTimeItem)
|
||||
ResultItem = QTableWidgetItem(result.value)
|
||||
ResultItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
execute_time_item = QTableWidgetItem(execute_time)
|
||||
execute_time_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.HistoryTableWidget.setItem(row, 0, execute_time_item)
|
||||
result_item = QTableWidgetItem(result.value)
|
||||
result_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
match result:
|
||||
case ALTimerTaskStatus.EXECUTED:
|
||||
ResultItem.setForeground(Qt.GlobalColor.green)
|
||||
result_item.setForeground(Qt.GlobalColor.green)
|
||||
case ALTimerTaskStatus.ERROR:
|
||||
ResultItem.setForeground(Qt.GlobalColor.red)
|
||||
result_item.setForeground(Qt.GlobalColor.red)
|
||||
case ALTimerTaskStatus.OUTDATED:
|
||||
ResultItem.setForeground(Qt.GlobalColor.red)
|
||||
result_item.setForeground(Qt.GlobalColor.red)
|
||||
case _:
|
||||
ResultItem.setForeground(Qt.GlobalColor.black)
|
||||
self.HistoryTableWidget.setItem(row, 1, ResultItem)
|
||||
DurationItem = QTableWidgetItem(f"{duration:.2f}")
|
||||
DurationItem.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.HistoryTableWidget.setItem(row, 2, DurationItem)
|
||||
result_item.setForeground(Qt.GlobalColor.black)
|
||||
self.HistoryTableWidget.setItem(row, 1, result_item)
|
||||
duration_item = QTableWidgetItem(f"{duration:.2f}")
|
||||
duration_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.HistoryTableWidget.setItem(row, 2, duration_item)
|
||||
self.HistoryTableWidget.setRowHeight(row, 25)
|
||||
|
||||
@Slot()
|
||||
@@ -138,4 +135,4 @@ class ALTimerTaskHistoryDialog(QDialog):
|
||||
|
||||
self.__history.clear()
|
||||
self.HistoryTableWidget.setRowCount(0)
|
||||
self.__task_data["repeat_history"] = self.__history
|
||||
self.__task_data["repeat_history"] = self.__history # = []
|
||||
@@ -43,6 +43,7 @@ from gui.ALTimerTaskAddDialog import (
|
||||
ALTimerTaskStatus
|
||||
)
|
||||
from gui.ALTimerTaskHistoryDialog import ALTimerTaskHistoryDialog
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
from gui.resources.ui.Ui_ALTimerTaskManageWidget import Ui_ALTimerTaskManageWidget
|
||||
from interfaces.ConfigProvider import (
|
||||
CfgKey,
|
||||
@@ -80,12 +81,12 @@ class ALTimerTaskItemWidget(QWidget):
|
||||
self.TaskInfoLayout = QVBoxLayout()
|
||||
self.TaskInfoLayout.setSpacing(5)
|
||||
TaskNameLabel = QLabel(self.__timer_task["name"])
|
||||
TaskNameLabelFont = TaskNameLabel.font()
|
||||
TaskNameLabelFont.setBold(True)
|
||||
TaskNameLabel.setFont(TaskNameLabelFont)
|
||||
task_name_label_font = TaskNameLabel.font()
|
||||
task_name_label_font.setBold(True)
|
||||
TaskNameLabel.setFont(task_name_label_font)
|
||||
TaskNameLabel.setFixedHeight(25)
|
||||
self.TaskInfoLayout.addWidget(TaskNameLabel)
|
||||
ExecuteTimeStr = self.__timer_task["execute_time"].strftime("%Y-%m-%d %H:%M:%S")
|
||||
execute_time_str = self.__timer_task["execute_time"].strftime("%Y-%m-%d %H:%M:%S")
|
||||
if self.__timer_task.get("repeat", False):
|
||||
repeat_days = self.__timer_task.get("repeat_days", [])
|
||||
repeat_hour = self.__timer_task.get("repeat_hour", 0)
|
||||
@@ -93,14 +94,14 @@ class ALTimerTaskItemWidget(QWidget):
|
||||
repeat_second = self.__timer_task.get("repeat_second", 0)
|
||||
if len(repeat_days) == 7:
|
||||
time_str = f"{repeat_hour:02d}:{repeat_minute:02d}:{repeat_second:02d}"
|
||||
ExecuteTimeLabel = QLabel(f"下次执行时间: {ExecuteTimeStr} (每日 {time_str})")
|
||||
ExecuteTimeLabel = QLabel(f"下次执行时间: {execute_time_str} (每日 {time_str})")
|
||||
else:
|
||||
day_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
|
||||
selected_days = [day_names[d] for d in repeat_days]
|
||||
time_str = f"{repeat_hour:02d}:{repeat_minute:02d}:{repeat_second:02d}"
|
||||
ExecuteTimeLabel = QLabel(f"下次执行时间: {ExecuteTimeStr} (每{','.join(selected_days)} {time_str})")
|
||||
ExecuteTimeLabel = QLabel(f"下次执行时间: {execute_time_str} (每{','.join(selected_days)} {time_str})")
|
||||
else:
|
||||
ExecuteTimeLabel = QLabel(f"执行时间: {ExecuteTimeStr}")
|
||||
ExecuteTimeLabel = QLabel(f"执行时间: {execute_time_str}")
|
||||
ExecuteTimeLabel.setStyleSheet("color: #969696;")
|
||||
ExecuteTimeLabel.setFixedHeight(20)
|
||||
self.TaskInfoLayout.addWidget(ExecuteTimeLabel)
|
||||
@@ -173,23 +174,23 @@ class ALTimerTaskItemWidget(QWidget):
|
||||
pos
|
||||
):
|
||||
|
||||
menu = QMenu(self)
|
||||
edit_action = QAction("编辑", self)
|
||||
edit_action.triggered.connect(
|
||||
Menu = QMenu(self)
|
||||
EditAction = QAction("编辑", self)
|
||||
EditAction.triggered.connect(
|
||||
lambda: self.editRequested.emit(self.__timer_task)
|
||||
)
|
||||
menu.addAction(edit_action)
|
||||
Menu.addAction(EditAction)
|
||||
if self.__timer_task["status"] != ALTimerTaskStatus.RUNNING\
|
||||
and self.__timer_task["status"] != ALTimerTaskStatus.READY:
|
||||
delete_action = QAction("删除", self)
|
||||
delete_action.triggered.connect(
|
||||
DeleteAction = QAction("删除", self)
|
||||
DeleteAction.triggered.connect(
|
||||
lambda: self.__manage_widget.deleteTask(self.__timer_task)
|
||||
)
|
||||
menu.addAction(delete_action)
|
||||
menu.exec(self.mapToGlobal(pos))
|
||||
Menu.addAction(DeleteAction)
|
||||
Menu.exec(self.mapToGlobal(pos))
|
||||
|
||||
|
||||
class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
class ALTimerTaskManageWidget(CenterOnParentMixin, QWidget, Ui_ALTimerTaskManageWidget):
|
||||
|
||||
class SortPolicy(Enum):
|
||||
|
||||
@@ -209,7 +210,7 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
super().__init__(parent)
|
||||
self.__cfg_mgr: ConfigProvider = ConfigManager.instance()
|
||||
self.__timer_tasks = []
|
||||
self.__check_timer = None
|
||||
self.__CheckTimer = None
|
||||
self.__sort_policy = self.SortPolicy.BY_EXECUTE_TIME
|
||||
self.__sort_order = Qt.SortOrder.AscendingOrder
|
||||
|
||||
@@ -233,9 +234,9 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
self
|
||||
):
|
||||
|
||||
self.__check_timer = QTimer(self)
|
||||
self.__check_timer.timeout.connect(self.checkTasks)
|
||||
self.__check_timer.start(500)
|
||||
self.__CheckTimer = QTimer(self)
|
||||
self.__CheckTimer.timeout.connect(self.checkTasks)
|
||||
self.__CheckTimer.start(500)
|
||||
|
||||
def initializeTimerTasks(
|
||||
self
|
||||
@@ -299,29 +300,6 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
)
|
||||
return False
|
||||
|
||||
def showEvent(
|
||||
self,
|
||||
event
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
|
||||
return result
|
||||
|
||||
def closeEvent(
|
||||
self,
|
||||
event: QCloseEvent
|
||||
@@ -386,28 +364,28 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
self.TimerTasksListWidget.clear()
|
||||
self.sortTimerTasks(self.__sort_policy, self.__sort_order)
|
||||
for timer_task in self.__timer_tasks:
|
||||
item = QListWidgetItem()
|
||||
item.setData(Qt.UserRole, timer_task)
|
||||
widget = ALTimerTaskItemWidget(self, timer_task)
|
||||
widget.DeleteButton.clicked.connect(
|
||||
Item = QListWidgetItem()
|
||||
Item.setData(Qt.UserRole, timer_task)
|
||||
Widget = ALTimerTaskItemWidget(self, timer_task)
|
||||
Widget.DeleteButton.clicked.connect(
|
||||
lambda _, task = timer_task: self.deleteTask(task)
|
||||
)
|
||||
if timer_task.get("repeat", False) and hasattr(widget, "HistoryButton"):
|
||||
widget.HistoryButton.clicked.connect(
|
||||
if timer_task.get("repeat", False) and hasattr(Widget, "HistoryButton"):
|
||||
Widget.HistoryButton.clicked.connect(
|
||||
lambda _, task = timer_task: self.showTaskHistory(task)
|
||||
)
|
||||
widget.editRequested.connect(self.editTask)
|
||||
item.setSizeHint(widget.size())
|
||||
self.TimerTasksListWidget.addItem(item)
|
||||
self.TimerTasksListWidget.setItemWidget(item, widget)
|
||||
Widget.editRequested.connect(self.editTask)
|
||||
Item.setSizeHint(Widget.size())
|
||||
self.TimerTasksListWidget.addItem(Item)
|
||||
self.TimerTasksListWidget.setItemWidget(Item, Widget)
|
||||
|
||||
def addTask(
|
||||
self
|
||||
):
|
||||
|
||||
dialog = ALTimerTaskAddDialog(self)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
timer_task = dialog.getTimerTask()
|
||||
Dialog = ALTimerTaskAddDialog(self)
|
||||
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
timer_task = Dialog.getTimerTask()
|
||||
self.__timer_tasks.append(timer_task)
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
@@ -416,9 +394,9 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
timer_task: dict
|
||||
):
|
||||
|
||||
dialog = ALTimerTaskAddDialog(self, timer_task)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
updated = dialog.getTimerTask()
|
||||
Dialog = ALTimerTaskAddDialog(self, timer_task)
|
||||
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
updated = Dialog.getTimerTask()
|
||||
for i, task in enumerate(self.__timer_tasks):
|
||||
if task["uuid"] == updated["uuid"]:
|
||||
self.__timer_tasks[i] = updated
|
||||
@@ -449,19 +427,19 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
):
|
||||
|
||||
if timer_task["repeat"]: # when delete a repeat task
|
||||
msgbox = QMessageBox(self)
|
||||
msgbox.setIcon(QMessageBox.Icon.Question)
|
||||
msgbox.setWindowTitle("警告 - AutoLibrary")
|
||||
msgbox.setStandardButtons(
|
||||
MsgBox = QMessageBox(self)
|
||||
MsgBox.setIcon(QMessageBox.Icon.Question)
|
||||
MsgBox.setWindowTitle("警告 - AutoLibrary")
|
||||
MsgBox.setStandardButtons(
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||
)
|
||||
msgbox.setText("删除可重复性任务将同时删除所有已执行的记录 !\n是否继续 ?")
|
||||
msgbox.setDetailedText(
|
||||
MsgBox.setText("删除可重复性任务将同时删除所有已执行的记录 !\n是否继续 ?")
|
||||
MsgBox.setDetailedText(
|
||||
"以下可重复性任务将被删除:\n"\
|
||||
"\n"
|
||||
f"{self.getTimerTaskDetailMessage(timer_task)}"
|
||||
)
|
||||
result = msgbox.exec()
|
||||
result = MsgBox.exec()
|
||||
if result != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
task_uuid = timer_task["uuid"]
|
||||
@@ -506,13 +484,13 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
]
|
||||
repeat_tasks_count = len(repeat_tasks)
|
||||
if repeat_tasks_count > 0:
|
||||
msgbox = QMessageBox(self)
|
||||
msgbox.setIcon(QMessageBox.Icon.Question)
|
||||
msgbox.setWindowTitle("警告 - AutoLibrary")
|
||||
msgbox.setStandardButtons(
|
||||
MsgBox = QMessageBox(self)
|
||||
MsgBox.setIcon(QMessageBox.Icon.Question)
|
||||
MsgBox.setWindowTitle("警告 - AutoLibrary")
|
||||
MsgBox.setStandardButtons(
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||
)
|
||||
msgbox.setText(
|
||||
MsgBox.setText(
|
||||
f"存在 {repeat_tasks_count} 个可重复性任务,\n"
|
||||
"删除可重复性任务将同时删除所有已执行的记录 !\n"
|
||||
"是否继续 ?"
|
||||
@@ -520,12 +498,12 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
delete_msgs = [
|
||||
self.getTimerTaskDetailMessage(x) for x in repeat_tasks
|
||||
]
|
||||
msgbox.setDetailedText(
|
||||
MsgBox.setDetailedText(
|
||||
"以下可重复性任务将被删除:\n"\
|
||||
"\n"
|
||||
f"{"\n\n".join(delete_msgs)}"
|
||||
)
|
||||
result = msgbox.exec()
|
||||
result = MsgBox.exec()
|
||||
if result != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
# clear all tasks
|
||||
@@ -537,8 +515,13 @@ class ALTimerTaskManageWidget(QWidget, Ui_ALTimerTaskManageWidget):
|
||||
task: dict
|
||||
):
|
||||
|
||||
dialog = ALTimerTaskHistoryDialog(self, task)
|
||||
if dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
# Here we use reference to task data, not copy.
|
||||
# So any change of task data in history dialog will be
|
||||
# reflected in the timer task list
|
||||
# Thus we can emit timerTasksChanged signal to
|
||||
# update config file
|
||||
Dialog = ALTimerTaskHistoryDialog(self, task)
|
||||
if Dialog.exec() == QDialog.DialogCode.Accepted:
|
||||
self.timerTasksChanged.emit()
|
||||
|
||||
def checkTasks(
|
||||
|
||||
@@ -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
|
||||
@@ -51,9 +51,9 @@ class ALUserTreeWidget(QTreeWidget):
|
||||
self
|
||||
):
|
||||
|
||||
__qtreewidgetitem = QTreeWidgetItem()
|
||||
__qtreewidgetitem.setText(0, u"\u5206\u7ec4/\u7528\u6237");
|
||||
self.setHeaderItem(__qtreewidgetitem)
|
||||
__QTreeWidgetItem = QTreeWidgetItem()
|
||||
__QTreeWidgetItem.setText(0, u"\u5206\u7ec4/\u7528\u6237");
|
||||
self.setHeaderItem(__QTreeWidgetItem)
|
||||
self.setObjectName(u"UserTreeWidget")
|
||||
self.setMinimumSize(QSize(230, 0))
|
||||
self.setMaximumSize(QSize(250, 16777215))
|
||||
@@ -81,8 +81,8 @@ class ALUserTreeWidget(QTreeWidget):
|
||||
self
|
||||
):
|
||||
|
||||
___qtreewidgetitem = self.headerItem()
|
||||
___qtreewidgetitem.setText(1, QCoreApplication.translate("ALConfigWidget", u"\u72b6\u6001", None));
|
||||
___QTreeWidgetItem = self.headerItem()
|
||||
___QTreeWidgetItem.setText(1, QCoreApplication.translate("ALConfigWidget", u"\u72b6\u6001", None));
|
||||
|
||||
@staticmethod
|
||||
def isDragPositionValid(
|
||||
|
||||
@@ -5,11 +5,11 @@
|
||||
workflow process. Do not edit manually.
|
||||
|
||||
This file is auto-generated during the workflow process.
|
||||
Last updated: 2026-05-09 06:05:13 UTC
|
||||
Last updated: 2026-07-14 02:19:31 UTC
|
||||
"""
|
||||
|
||||
AL_VERSION = "1.3.0"
|
||||
AL_TAG = "v1.3.0"
|
||||
AL_VERSION = "1.4.0"
|
||||
AL_TAG = "v1.4.0"
|
||||
AL_COMMIT_SHA = "local"
|
||||
AL_COMMIT_DATE = "null" # time zone : UTC
|
||||
AL_BUILD_DATE = "null" # time zone : UTC
|
||||
|
||||
@@ -8,6 +8,7 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from PySide6.QtCore import (
|
||||
@@ -33,11 +34,12 @@ from PySide6.QtGui import QCloseEvent
|
||||
from managers.driver.WebDriverManager import (
|
||||
instance as webdriverInstance,
|
||||
WebDriverManager,
|
||||
WebDriverInfo,
|
||||
WebDriverCtx,
|
||||
WebDriverType,
|
||||
WebDriverStatus
|
||||
)
|
||||
from gui.ALStatusLabel import ALStatusLabel
|
||||
from gui.ALWidgetMixin import CenterOnParentMixin
|
||||
|
||||
|
||||
class DownloadWorker(QThread):
|
||||
@@ -53,12 +55,12 @@ class DownloadWorker(QThread):
|
||||
def __init__(
|
||||
self,
|
||||
driver_manager: WebDriverManager,
|
||||
driver_info: WebDriverInfo
|
||||
driver_ctx: WebDriverCtx
|
||||
):
|
||||
super().__init__()
|
||||
self.__driver_manager = driver_manager
|
||||
self.__driver_info = driver_info
|
||||
self.__driver_path = None
|
||||
self.__driver_ctx = driver_ctx
|
||||
self.__driver_path: Optional[Path] = None
|
||||
self.__cancelled = False
|
||||
self.__cancel_event = threading.Event()
|
||||
|
||||
@@ -80,7 +82,7 @@ class DownloadWorker(QThread):
|
||||
self.downloadCancelled.emit()
|
||||
return
|
||||
self.__driver_path = self.__driver_manager.installDriver(
|
||||
self.__driver_info,
|
||||
self.__driver_ctx,
|
||||
progress_callback=self.onProgress,
|
||||
cancel_event=self.__cancel_event
|
||||
)
|
||||
@@ -123,7 +125,7 @@ class DownloadWorker(QThread):
|
||||
self.wait()
|
||||
|
||||
|
||||
class ALWebDriverDownloadDialog(QDialog):
|
||||
class ALWebDriverDownloadDialog(CenterOnParentMixin, QDialog):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -139,12 +141,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
"""
|
||||
|
||||
super().__init__(parent)
|
||||
|
||||
self.__driver_dir = driver_dir
|
||||
self.__driver_manager: Optional[WebDriverManager] = None
|
||||
self.__confirmed = False
|
||||
self.__selected_driver_info: Optional[WebDriverInfo] = None
|
||||
self.__driver_infos: list[WebDriverInfo] = []
|
||||
self.__selected_driver_ctx: Optional[WebDriverCtx] = None
|
||||
self.__driver_ctxs: list[WebDriverCtx] = []
|
||||
self.__download_thread: Optional[DownloadWorker] = None
|
||||
|
||||
self.setupUi()
|
||||
@@ -152,27 +153,26 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.initializeDriverManager()
|
||||
self.refreshDriverList()
|
||||
|
||||
def showEvent(
|
||||
def closeEvent(
|
||||
self,
|
||||
event
|
||||
event: QCloseEvent
|
||||
):
|
||||
|
||||
result = super().showEvent(event)
|
||||
if self.parent():
|
||||
screen_rect = self.screen().geometry()
|
||||
target_pos = self.parent().geometry().center()
|
||||
target_pos.setX(target_pos.x() - self.width()//2)
|
||||
target_pos.setY(target_pos.y() - self.height()//2)
|
||||
if target_pos.x() < 0:
|
||||
target_pos.setX(0)
|
||||
if target_pos.x() + self.width() > screen_rect.width():
|
||||
target_pos.setX(screen_rect.width() - self.width())
|
||||
if target_pos.y() < 0:
|
||||
target_pos.setY(0)
|
||||
if target_pos.y() + self.height() > screen_rect.height():
|
||||
target_pos.setY(screen_rect.height() - self.height())
|
||||
self.move(target_pos)
|
||||
return result
|
||||
if self.__download_thread and self.__download_thread.isRunning():
|
||||
reply = QMessageBox.question(
|
||||
self,
|
||||
"确认关闭 - AutoLibrary",
|
||||
"驱动正在下载中, 确定要取消并关闭对话框吗 ?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
|
||||
)
|
||||
if reply == QMessageBox.StandardButton.No:
|
||||
event.ignore()
|
||||
return
|
||||
self.__download_thread.stop()
|
||||
if not self.__confirmed:
|
||||
self.__selected_driver_ctx = None
|
||||
event.accept()
|
||||
super().closeEvent(event)
|
||||
|
||||
def setupUi(
|
||||
self
|
||||
@@ -182,14 +182,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.setMaximumHeight(240)
|
||||
self.setMinimumHeight(240)
|
||||
self.setWindowTitle("浏览器驱动下载 - AutoLibrary")
|
||||
|
||||
self.MainLayout = QVBoxLayout(self)
|
||||
self.MainLayout.setContentsMargins(5, 5, 5, 5)
|
||||
self.MainLayout.setSpacing(5)
|
||||
|
||||
self.BrowserCountLabel = QLabel("检测到 0 个可用浏览器:")
|
||||
self.MainLayout.addWidget(self.BrowserCountLabel)
|
||||
|
||||
self.DriverInfoLayout = QHBoxLayout()
|
||||
self.DriverInfoLayout.setSpacing(5)
|
||||
self.DriverComboBox = QComboBox()
|
||||
@@ -198,7 +195,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.StatusLabel.setFixedSize(32, 32)
|
||||
self.DriverInfoLayout.addWidget(self.StatusLabel)
|
||||
self.MainLayout.addLayout(self.DriverInfoLayout)
|
||||
|
||||
self.DetailLayout = QVBoxLayout()
|
||||
self.DetailLayout.setSpacing(5)
|
||||
self.DetailLayout.setContentsMargins(5, 5, 5, 5)
|
||||
@@ -211,7 +207,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.PathLabel.setText("路径:未安装")
|
||||
self.DetailLayout.addWidget(self.PathLabel)
|
||||
self.MainLayout.addLayout(self.DetailLayout)
|
||||
|
||||
self.Line = QFrame()
|
||||
self.Line.setFrameShape(QFrame.Shape.HLine)
|
||||
self.Line.setFrameShadow(QFrame.Shadow.Sunken)
|
||||
@@ -237,7 +232,6 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.ConfirmButton = QPushButton("确认")
|
||||
self.ConfirmButton.setFixedSize(80, 25)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
|
||||
self.ControlLayout.addWidget(self.RefreshButton)
|
||||
self.ControlLayout.addWidget(self.DownloadButton)
|
||||
self.ControlLayout.addWidget(self.DeleteButton)
|
||||
@@ -273,89 +267,42 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
if not self.__driver_manager:
|
||||
return
|
||||
self.__driver_manager.refresh()
|
||||
self.__driver_infos = self.__driver_manager.getDriverInfos()
|
||||
self.__driver_ctxs = self.__driver_manager.getDriverCtxs()
|
||||
self.DriverComboBox.clear()
|
||||
installed = 0
|
||||
installed_idx = 0
|
||||
for i, driver_info in enumerate(self.__driver_infos):
|
||||
display_text = f"{driver_info.driver_type.value} - {driver_info.browser_version}"
|
||||
if driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
for i, driver_ctx in enumerate(self.__driver_ctxs):
|
||||
display_text = f"{driver_ctx.driver_type.value} - {driver_ctx.browser_version}"
|
||||
if driver_ctx.driver_status == WebDriverStatus.INSTALLED:
|
||||
installed += 1
|
||||
installed_idx = i # get the installed driver index
|
||||
display_text += " : 已安装"
|
||||
display_text += " - 已安装"
|
||||
self.DriverComboBox.addItem(display_text)
|
||||
count = len(self.__driver_infos)
|
||||
count = len(self.__driver_ctxs)
|
||||
self.BrowserCountLabel.setText(f"检测到 {count} 个可用浏览器,{installed} 个已安装驱动:")
|
||||
if self.__driver_infos:
|
||||
if self.__driver_ctxs:
|
||||
self.DriverComboBox.setCurrentIndex(installed_idx)
|
||||
|
||||
def onDriverComboBoxChanged(
|
||||
self,
|
||||
index: int
|
||||
):
|
||||
|
||||
if not self.__driver_infos or index < 0 or index >= len(self.__driver_infos):
|
||||
return
|
||||
driver_info = self.__driver_infos[index]
|
||||
self.updateDriverInfoDisplay(driver_info)
|
||||
self.updateProgressBarStates(driver_info)
|
||||
self.updateButtonStates(driver_info)
|
||||
|
||||
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
|
||||
driver_ctx: WebDriverCtx
|
||||
):
|
||||
|
||||
if driver_info.driver_type == WebDriverType.CHROME:
|
||||
if driver_ctx.driver_type == WebDriverType.CHROME:
|
||||
driver_type = "Google Chrome"
|
||||
elif driver_info.driver_type == WebDriverType.FIREFOX:
|
||||
elif driver_ctx.driver_type == WebDriverType.FIREFOX:
|
||||
driver_type = "Mozilla Firefox"
|
||||
elif driver_info.driver_type == WebDriverType.EDGE:
|
||||
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_info.driver_version}")
|
||||
if driver_info.driver_path:
|
||||
self.PathLabel.setText(str(driver_info.driver_path))
|
||||
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_info.driver_status:
|
||||
match driver_ctx.driver_status:
|
||||
case WebDriverStatus.NOT_INSTALLED:
|
||||
self.StatusLabel.status = ALStatusLabel.Status.WAITING
|
||||
case WebDriverStatus.INSTALLED:
|
||||
@@ -367,51 +314,70 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
def updateProgressBarStates(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
driver_ctx: WebDriverCtx
|
||||
):
|
||||
|
||||
if driver_info.driver_status == WebDriverStatus.NOT_INSTALLED:
|
||||
if driver_ctx.driver_status == WebDriverStatus.NOT_INSTALLED:
|
||||
self.ProgressBar.setValue(0)
|
||||
self.ProgressText.setText("未安装")
|
||||
elif driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
elif driver_ctx.driver_status == WebDriverStatus.INSTALLED:
|
||||
self.ProgressBar.setValue(100)
|
||||
self.ProgressText.setText("已安装")
|
||||
elif driver_info.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
elif driver_ctx.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
pass # update by worker thread
|
||||
elif driver_info.driver_status == WebDriverStatus.ERROR:
|
||||
elif driver_ctx.driver_status == WebDriverStatus.ERROR:
|
||||
self.ProgressBar.setValue(0)
|
||||
self.ProgressText.setText("下载失败")
|
||||
|
||||
def updateButtonStates(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
driver_ctx: WebDriverCtx
|
||||
):
|
||||
|
||||
if driver_info.driver_status == WebDriverStatus.NOT_INSTALLED:
|
||||
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_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
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_info.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
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_info.driver_status == WebDriverStatus.ERROR:
|
||||
elif driver_ctx.driver_status == WebDriverStatus.ERROR:
|
||||
self.RefreshButton.setEnabled(True)
|
||||
self.DownloadButton.setEnabled(True)
|
||||
self.DeleteButton.setEnabled(False)
|
||||
self.CancelButton.setEnabled(True)
|
||||
self.ConfirmButton.setEnabled(False)
|
||||
|
||||
def getSelectedDriverInfo(
|
||||
self
|
||||
) -> Optional[WebDriverCtx]:
|
||||
|
||||
return self.__selected_driver_ctx
|
||||
|
||||
@Slot(int)
|
||||
def onDriverComboBoxChanged(
|
||||
self,
|
||||
index: int
|
||||
):
|
||||
|
||||
if not self.__driver_ctxs or index < 0 or index >= len(self.__driver_ctxs):
|
||||
return
|
||||
driver_ctx = self.__driver_ctxs[index]
|
||||
self.updateDriverInfoDisplay(driver_ctx)
|
||||
self.updateProgressBarStates(driver_ctx)
|
||||
self.updateButtonStates(driver_ctx)
|
||||
|
||||
@Slot()
|
||||
def onRefreshButtonClicked(
|
||||
self
|
||||
@@ -425,9 +391,9 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
):
|
||||
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if index < 0 or index >= len(self.__driver_infos):
|
||||
if index < 0 or index >= len(self.__driver_ctxs):
|
||||
return
|
||||
driver_info = self.__driver_infos[index]
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
if driver_info.driver_status.name != "INSTALLED":
|
||||
QMessageBox.information(self, "提示 - AutoLibrary", "该驱动未安装, 无需删除")
|
||||
return
|
||||
@@ -453,9 +419,9 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.DriverComboBox.setEnabled(False)
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if index < 0 or index >= len(self.__driver_infos):
|
||||
if index < 0 or index >= len(self.__driver_ctxs):
|
||||
return
|
||||
driver_info = self.__driver_infos[index]
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
if driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
return
|
||||
driver_info.driver_status = WebDriverStatus.DOWNLOADING # we set this only to update
|
||||
@@ -471,7 +437,7 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.__download_thread.downloadFinished.connect(self.onDownloadFinished)
|
||||
self.__download_thread.downloadError.connect(self.onDownloadError)
|
||||
self.__download_thread.downloadCancelled.connect(self.onDownloadCancelled)
|
||||
self.__download_thread.finished.connect(self.onThreadFinished)
|
||||
self.__download_thread.finished.connect(self.onDownloadThreadFinished)
|
||||
self.__download_thread.start()
|
||||
|
||||
@Slot()
|
||||
@@ -499,9 +465,11 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.DriverComboBox.setEnabled(True)
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if 0 <= index < len(self.__driver_infos):
|
||||
driver_info = self.__driver_infos[index]
|
||||
if 0 <= index < len(self.__driver_ctxs):
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
||||
current_text = self.DriverComboBox.itemText(index)
|
||||
self.DriverComboBox.setItemText(index, current_text + " - 已安装")
|
||||
self.updateDriverInfoDisplay(driver_info)
|
||||
self.updateProgressBarStates(driver_info)
|
||||
self.updateButtonStates(driver_info)
|
||||
@@ -514,8 +482,8 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.DriverComboBox.setEnabled(True)
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if 0 <= index < len(self.__driver_infos):
|
||||
driver_info = self.__driver_infos[index]
|
||||
if 0 <= index < len(self.__driver_ctxs):
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
driver_info.driver_status = WebDriverStatus.ERROR
|
||||
self.updateDriverInfoDisplay(driver_info)
|
||||
self.updateProgressBarStates(driver_info)
|
||||
@@ -529,8 +497,8 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
|
||||
self.DriverComboBox.setEnabled(True)
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if 0 <= index < len(self.__driver_infos):
|
||||
driver_info = self.__driver_infos[index]
|
||||
if 0 <= index < len(self.__driver_ctxs):
|
||||
driver_info = self.__driver_ctxs[index]
|
||||
self.__driver_manager.cancelDriverDownload(driver_info)
|
||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
self.updateDriverInfoDisplay(driver_info)
|
||||
@@ -538,18 +506,27 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.updateButtonStates(driver_info)
|
||||
self.ProgressText.setText("下载已取消")
|
||||
|
||||
@Slot()
|
||||
def onDownloadThreadFinished(
|
||||
self
|
||||
):
|
||||
|
||||
if self.__download_thread:
|
||||
self.__download_thread.deleteLater()
|
||||
self.__download_thread = None
|
||||
|
||||
@Slot()
|
||||
def onConfirmButtonClicked(
|
||||
self
|
||||
):
|
||||
|
||||
index = self.DriverComboBox.currentIndex()
|
||||
if index < 0 or index >= len(self.__driver_infos):
|
||||
if index < 0 or index >= len(self.__driver_ctxs):
|
||||
return
|
||||
driver_info = self.__driver_infos[index]
|
||||
if driver_info.driver_status != WebDriverStatus.INSTALLED:
|
||||
driver_ctx = self.__driver_ctxs[index]
|
||||
if driver_ctx.driver_status != WebDriverStatus.INSTALLED:
|
||||
return
|
||||
self.__selected_driver_info = driver_info
|
||||
self.__selected_driver_ctx = driver_ctx
|
||||
self.__confirmed = True
|
||||
self.accept()
|
||||
|
||||
@@ -569,5 +546,5 @@ class ALWebDriverDownloadDialog(QDialog):
|
||||
self.__download_thread.cancel()
|
||||
else:
|
||||
self.__confirmed = False
|
||||
self.__selected_driver_info = None
|
||||
self.__selected_driver_ctx = None
|
||||
self.reject()
|
||||
@@ -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)
|
||||
+7
-17
@@ -1,19 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
GUI module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- ALMainWindow: Main window class.
|
||||
- ALAboutDialog: About dialog class.
|
||||
- ALConfigWidget: Configuration widget class.
|
||||
- ALSeatFrame: Seat frame class.
|
||||
- ALSeatMapView: Seat map view class.
|
||||
- ALSeatMapTable: Seat map table class.
|
||||
- ALSeatMapSelectDialog: Seat map select dialog class.
|
||||
- ALTimerTaskAddDialog: Timer task add dialog class.
|
||||
- ALAutoScriptOrchDialog: AutoScript orchestration dialog class.
|
||||
- ALTimerTaskHistoryDialog: Timer task history dialog class.
|
||||
- ALTimerTaskManageWidget: Timer task manage widget class.
|
||||
- ALUserTreeWidget: User tree widget class.
|
||||
- ALMainWorkers: Main workers class.
|
||||
- ALVersionInfo: Version info class.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -1,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.
|
||||
"""
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 173 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 178 KiB |
@@ -0,0 +1,539 @@
|
||||
/*
|
||||
* Copyright (c) 2026 KenanZhu.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is provided "as is", without any warranty of any kind.
|
||||
* You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
* See the LICENSE file for details.
|
||||
*
|
||||
*
|
||||
* AutoLibrary Official Theme : BlueForest
|
||||
*/
|
||||
|
||||
/* ---- Global ---- */
|
||||
QMainWindow::separator {
|
||||
background-color: #1c2840;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
/* ---- Menu Bar ---- */
|
||||
QMenuBar {
|
||||
background-color: #0f1628;
|
||||
border-bottom: 1px solid #1c2840;
|
||||
padding: 2px 5px;
|
||||
color: #d0daf0;
|
||||
}
|
||||
QMenuBar::item {
|
||||
padding: 2px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QMenuBar::item:selected {
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QMenu {
|
||||
background-color: #162038;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
padding: 4px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QMenu::item {
|
||||
padding: 5px 15px 5px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QMenu::item:selected {
|
||||
background-color: #2dd4bf;
|
||||
color: #0f1119;
|
||||
}
|
||||
QMenu::separator {
|
||||
height: 1px;
|
||||
background-color: #253250;
|
||||
margin: 4px 8px;
|
||||
}
|
||||
|
||||
/* ---- Button ---- */
|
||||
QPushButton {
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
color: #d0daf0;
|
||||
padding: 4px 12px;
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QPushButton:hover {
|
||||
background-color: #243458;
|
||||
border-color: #334478;
|
||||
}
|
||||
QPushButton:pressed {
|
||||
background-color: #162038;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QPushButton:disabled {
|
||||
background-color: #162038;
|
||||
color: #5568a0;
|
||||
border-color: #1c2840;
|
||||
}
|
||||
QPushButton[default="true"] {
|
||||
background-color: #2dd4bf;
|
||||
color: #0f1119;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QPushButton[default="true"]:hover {
|
||||
background-color: #3de0cc;
|
||||
}
|
||||
|
||||
/* ---- Input ---- */
|
||||
QLineEdit,
|
||||
QPlainTextEdit,
|
||||
QTextEdit,
|
||||
QSpinBox,
|
||||
QDoubleSpinBox,
|
||||
QDateEdit,
|
||||
QTimeEdit {
|
||||
background-color: #0a1020;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
padding: 4px 8px;
|
||||
color: #d0daf0;
|
||||
selection-background-color: #2dd4bf;
|
||||
selection-color: #0f1119;
|
||||
}
|
||||
QLineEdit:focus,
|
||||
QPlainTextEdit:focus,
|
||||
QTextEdit:focus,
|
||||
QSpinBox:focus,
|
||||
QDoubleSpinBox:focus,
|
||||
QDateEdit:focus,
|
||||
QTimeEdit:focus {
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QPlainTextEdit,
|
||||
QTextEdit {
|
||||
background-color: #0a1020;
|
||||
}
|
||||
QLineEdit:disabled,
|
||||
QPlainTextEdit:disabled,
|
||||
QTextEdit:disabled,
|
||||
QSpinBox:disabled,
|
||||
QDoubleSpinBox:disabled,
|
||||
QDateEdit:disabled,
|
||||
QTimeEdit:disabled {
|
||||
background-color: #162038;
|
||||
color: #5568a0;
|
||||
border-color: #1c2840;
|
||||
}
|
||||
|
||||
/* ---- Spin Button Arrows ---- */
|
||||
QSpinBox::up-button,
|
||||
QDoubleSpinBox::up-button,
|
||||
QDateEdit::up-button,
|
||||
QTimeEdit::up-button {
|
||||
subcontrol-origin: border;
|
||||
subcontrol-position: top right;
|
||||
width: 10px;
|
||||
border-left: 1px solid #253250;
|
||||
border-bottom: 1px solid #253250;
|
||||
border-top-right-radius: 4px;
|
||||
}
|
||||
QSpinBox::up-button:hover,
|
||||
QDoubleSpinBox::up-button:hover,
|
||||
QDateEdit::up-button:hover,
|
||||
QTimeEdit::up-button:hover {
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QSpinBox::up-arrow,
|
||||
QDoubleSpinBox::up-arrow,
|
||||
QDateEdit::up-arrow,
|
||||
QTimeEdit::up-arrow {
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-bottom: 5px solid #7888b8;
|
||||
margin-top: 2px;
|
||||
}
|
||||
QSpinBox::down-button,
|
||||
QDoubleSpinBox::down-button,
|
||||
QDateEdit::down-button,
|
||||
QTimeEdit::down-button {
|
||||
width: 10px;
|
||||
subcontrol-origin: border;
|
||||
subcontrol-position: bottom right;
|
||||
border-left: 1px solid #253250;
|
||||
border-bottom-right-radius: 4px;
|
||||
}
|
||||
QSpinBox::down-button:hover,
|
||||
QDoubleSpinBox::down-button:hover,
|
||||
QDateEdit::down-button:hover,
|
||||
QTimeEdit::down-button:hover {
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QSpinBox::down-arrow,
|
||||
QDoubleSpinBox::down-arrow,
|
||||
QDateEdit::down-arrow,
|
||||
QTimeEdit::down-arrow {
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 5px solid #7888b8;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
QSpinBox::up-button:disabled,
|
||||
QDoubleSpinBox::up-button:disabled,
|
||||
QDateEdit::up-button:disabled,
|
||||
QTimeEdit::up-button:disabled,
|
||||
QSpinBox::down-button:disabled,
|
||||
QDoubleSpinBox::down-button:disabled,
|
||||
QDateEdit::down-button:disabled,
|
||||
QTimeEdit::down-button:disabled {
|
||||
background-color: #162038;
|
||||
}
|
||||
QSpinBox::up-arrow:disabled,
|
||||
QDoubleSpinBox::up-arrow:disabled,
|
||||
QDateEdit::up-arrow:disabled,
|
||||
QTimeEdit::up-arrow:disabled {
|
||||
border-bottom-color: #5568a0;
|
||||
}
|
||||
QSpinBox::down-arrow:disabled,
|
||||
QDoubleSpinBox::down-arrow:disabled,
|
||||
QDateEdit::down-arrow:disabled,
|
||||
QTimeEdit::down-arrow:disabled {
|
||||
border-top-color: #5568a0;
|
||||
}
|
||||
|
||||
/* ---- Combo Box ---- */
|
||||
QComboBox {
|
||||
background-color: #1c2840;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
padding: 4px 10px;
|
||||
color: #d0daf0;
|
||||
}
|
||||
QComboBox:hover {
|
||||
border-color: #334478;
|
||||
}
|
||||
QComboBox:focus {
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QComboBox::drop-down {
|
||||
subcontrol-origin: padding;
|
||||
subcontrol-position: top right;
|
||||
width: 24px;
|
||||
border-left: 1px solid #253250;
|
||||
border-top-right-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
}
|
||||
QComboBox::down-arrow {
|
||||
image: none;
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 6px solid #7888b8;
|
||||
margin-right: 6px;
|
||||
}
|
||||
QComboBox QAbstractItemView {
|
||||
background-color: #162038;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 4px;
|
||||
selection-background-color: #2dd4bf;
|
||||
selection-color: #0f1119;
|
||||
outline: none;
|
||||
}
|
||||
QComboBox:disabled {
|
||||
background-color: #162038;
|
||||
color: #5568a0;
|
||||
border-color: #1c2840;
|
||||
}
|
||||
|
||||
/* ---- Check Box / Radio Button ---- */
|
||||
QCheckBox,
|
||||
QRadioButton {
|
||||
spacing: 5px;
|
||||
color: #d0daf0;
|
||||
}
|
||||
QCheckBox::indicator,
|
||||
QRadioButton::indicator {
|
||||
border-style: solid;
|
||||
border-color: #334478;
|
||||
border-width: 2px;
|
||||
background-color: #0a1020;
|
||||
}
|
||||
QCheckBox::indicator {
|
||||
border-radius: 3px;
|
||||
}
|
||||
QRadioButton::indicator {
|
||||
border-radius: 7px;
|
||||
}
|
||||
QCheckBox::indicator:hover,
|
||||
QRadioButton::indicator:hover {
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QCheckBox::indicator:checked {
|
||||
background-color: #2dd4bf;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QRadioButton::indicator:checked {
|
||||
background-color: #2dd4bf;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QCheckBox::indicator:disabled,
|
||||
QRadioButton::indicator:disabled {
|
||||
border-color: #253250;
|
||||
background-color: #162038;
|
||||
}
|
||||
QCheckBox::indicator:checked:hover,
|
||||
QRadioButton::indicator:checked:hover {
|
||||
border-color: #a0f0e8;
|
||||
}
|
||||
|
||||
/* Tree / List / Table Widget CheckBox Indicator */
|
||||
QTreeWidget::indicator,
|
||||
QListWidget::indicator,
|
||||
QTableWidget::indicator {
|
||||
border: 2px solid #5568a0;
|
||||
border-radius: 3px;
|
||||
background-color: #162038;
|
||||
}
|
||||
QTreeWidget::indicator:hover,
|
||||
QListWidget::indicator:hover,
|
||||
QTableWidget::indicator:hover {
|
||||
border-color: #a0f0e8;
|
||||
}
|
||||
QTreeWidget::indicator:checked,
|
||||
QListWidget::indicator:checked,
|
||||
QTableWidget::indicator:checked {
|
||||
background-color: #2dd4bf;
|
||||
border-color: #2dd4bf;
|
||||
}
|
||||
QTreeWidget::indicator:checked:hover,
|
||||
QListWidget::indicator:checked:hover,
|
||||
QTableWidget::indicator:checked:hover {
|
||||
border-color: #a0f0e8;
|
||||
}
|
||||
QTreeWidget::indicator:disabled,
|
||||
QListWidget::indicator:disabled,
|
||||
QTableWidget::indicator:disabled {
|
||||
background-color: #1c2840;
|
||||
border-color: #334478;
|
||||
}
|
||||
QTreeWidget::indicator:indeterminate,
|
||||
QListWidget::indicator:indeterminate,
|
||||
QTableWidget::indicator:indeterminate {
|
||||
background-color: #2dd4bf;
|
||||
border-color: #a0f0e8;
|
||||
}
|
||||
|
||||
/* ---- Group Box ---- */
|
||||
QGroupBox {
|
||||
margin-top: 5px;
|
||||
padding-top: 15px;
|
||||
color: #b4c2f5;
|
||||
font-weight: bold;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* ---- Tab ---- */
|
||||
QTabWidget::pane {
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
background-color: #0f1a2e;
|
||||
top: -1px;
|
||||
}
|
||||
QTabBar::tab {
|
||||
background-color: #162038;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-bottom: none;
|
||||
border-top-left-radius: 5px;
|
||||
border-top-right-radius: 5px;
|
||||
padding: 6px 16px;
|
||||
margin-right: 2px;
|
||||
color: #7888b8;
|
||||
}
|
||||
QTabBar::tab:selected {
|
||||
background-color: #0f1a2e;
|
||||
color: #2dd4bf;
|
||||
border-bottom: 2px solid #2dd4bf;
|
||||
}
|
||||
|
||||
/* ---- List / Tree ---- */
|
||||
QListWidget,
|
||||
QTreeWidget,
|
||||
QTableWidget {
|
||||
background-color: #0a1020;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
outline: none;
|
||||
color: #d0daf0;
|
||||
alternate-background-color: #101c30;
|
||||
}
|
||||
QListWidget::item,
|
||||
QTreeWidget::item,
|
||||
QTableWidget::item {
|
||||
padding: 5px 5px;
|
||||
}
|
||||
QHeaderView::section {
|
||||
background-color: #0f1628;
|
||||
border-right: 1px solid #253250;
|
||||
border-bottom: 1px solid #253250;
|
||||
padding: 5px 10px;
|
||||
color: #8b9ad0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
/* ---- Scroll Bar ---- */
|
||||
QScrollBar:vertical {
|
||||
background-color: #0f1a2e;
|
||||
width: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:vertical {
|
||||
background-color: #334478;
|
||||
min-height: 30px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:vertical:hover {
|
||||
background-color: #5568a0;
|
||||
}
|
||||
QScrollBar::add-line:vertical,
|
||||
QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QScrollBar:horizontal {
|
||||
background-color: #0f1a2e;
|
||||
height: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:horizontal {
|
||||
background-color: #334478;
|
||||
min-width: 30px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:horizontal:hover {
|
||||
background-color: #5568a0;
|
||||
}
|
||||
QScrollBar::add-line:horizontal,
|
||||
QScrollBar::sub-line:horizontal {
|
||||
width: 0;
|
||||
}
|
||||
|
||||
/* ---- Progress Bar ---- */
|
||||
QProgressBar {
|
||||
background-color: #0a1020;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
height: 10px;
|
||||
text-align: center;
|
||||
color: #d0daf0;
|
||||
}
|
||||
QProgressBar::chunk {
|
||||
background-color: #2dd4bf;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ---- Slider ---- */
|
||||
QSlider::groove:horizontal {
|
||||
background-color: #1c2840;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
QSlider::handle:horizontal {
|
||||
background-color: #2dd4bf;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: -5px 0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QSlider::sub-page:horizontal {
|
||||
background-color: #2dd4bf;
|
||||
border-radius: 3px;
|
||||
}
|
||||
QSlider::handle:horizontal:disabled {
|
||||
background-color: #5568a0;
|
||||
}
|
||||
QSlider::sub-page:horizontal:disabled {
|
||||
background-color: #5568a0;
|
||||
}
|
||||
|
||||
/* ---- Tool Tip ---- */
|
||||
QToolTip {
|
||||
background-color: #1c2840;
|
||||
border-style: solid;
|
||||
border-color: #2dd4bf;
|
||||
border-width: 1px;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
color: #d0daf0;
|
||||
}
|
||||
|
||||
/* ---- Status Bar ---- */
|
||||
QStatusBar {
|
||||
background-color: #0f1628;
|
||||
border-top: 1px solid #1c2840;
|
||||
color: #7888b8;
|
||||
}
|
||||
|
||||
/* ---- Splitter ---- */
|
||||
QSplitter::handle {
|
||||
background-color: #253250;
|
||||
margin: 1px;
|
||||
}
|
||||
QSplitter::handle:horizontal {
|
||||
width: 2px;
|
||||
}
|
||||
QSplitter::handle:vertical {
|
||||
height: 2px;
|
||||
}
|
||||
|
||||
/* ---- Dialog ---- */
|
||||
QDialog {
|
||||
background-color: #0f1a2e;
|
||||
}
|
||||
|
||||
/* ---- Date / Time Editor Drop-down ---- */
|
||||
QDateEdit::drop-down,
|
||||
QTimeEdit::drop-down {
|
||||
subcontrol-origin: padding;
|
||||
subcontrol-position: top right;
|
||||
width: 24px;
|
||||
border-left: 1px solid #253250;
|
||||
}
|
||||
QCalendarWidget {
|
||||
background-color: #162038;
|
||||
border-style: solid;
|
||||
border-color: #253250;
|
||||
border-width: 1px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QCalendarWidget QToolButton {
|
||||
color: #d0daf0;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
QCalendarWidget QToolButton:hover {
|
||||
background-color: #1c2840;
|
||||
}
|
||||
QCalendarWidget QMenu {
|
||||
background-color: #162038;
|
||||
}
|
||||
|
||||
/* ---- Frame ---- */
|
||||
QFrame[frameShape="4"], /* HLine */
|
||||
QFrame[frameShape="5"] /* VLine */ {
|
||||
background-color: #253250;
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
/*
|
||||
* Copyright (c) 2026 KenanZhu.
|
||||
* All rights reserved.
|
||||
*
|
||||
* This software is provided "as is", without any warranty of any kind.
|
||||
* You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
* See the LICENSE file for details.
|
||||
*
|
||||
*
|
||||
* AutoLibrary Official Theme : LightLake
|
||||
*/
|
||||
|
||||
/* ---- Global ---- */
|
||||
QMainWindow::separator {
|
||||
background-color: #c0cdda;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
/* ---- Menu Bar ---- */
|
||||
QMenuBar {
|
||||
background-color: #dce4ee;
|
||||
border-bottom: 1px solid #c0cdda;
|
||||
padding: 2px 5px;
|
||||
color: #1a2740;
|
||||
}
|
||||
QMenuBar::item {
|
||||
padding: 2px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QMenuBar::item:selected {
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QMenu {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #d0d8e4;
|
||||
border-width: 1px;
|
||||
padding: 4px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QMenu::item {
|
||||
padding: 5px 15px 5px 10px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
QMenu::item:selected {
|
||||
background-color: #0ea58a;
|
||||
color: #ffffff;
|
||||
}
|
||||
QMenu::separator {
|
||||
height: 1px;
|
||||
background-color: #d0d8e4;
|
||||
margin: 4px 8px;
|
||||
}
|
||||
|
||||
/* ---- Button ---- */
|
||||
QPushButton {
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
color: #1a2740;
|
||||
padding: 4px 12px;
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QPushButton:hover {
|
||||
background-color: #c8d4e2;
|
||||
border-color: #90a4c4;
|
||||
}
|
||||
QPushButton:pressed {
|
||||
background-color: #e2e8f0;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QPushButton:disabled {
|
||||
background-color: #e8ecf2;
|
||||
color: #98a8c0;
|
||||
border-color: #d5dde8;
|
||||
}
|
||||
QPushButton[default="true"] {
|
||||
background-color: #0ea58a;
|
||||
color: #ffffff;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QPushButton[default="true"]:hover {
|
||||
background-color: #14c7a4;
|
||||
}
|
||||
|
||||
/* ---- Input ---- */
|
||||
QLineEdit,
|
||||
QPlainTextEdit,
|
||||
QTextEdit,
|
||||
QSpinBox,
|
||||
QDoubleSpinBox,
|
||||
QDateEdit,
|
||||
QTimeEdit {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
padding: 4px 8px;
|
||||
color: #1a2740;
|
||||
selection-background-color: #0ea58a;
|
||||
selection-color: #ffffff;
|
||||
}
|
||||
QLineEdit:focus,
|
||||
QPlainTextEdit:focus,
|
||||
QTextEdit:focus,
|
||||
QSpinBox:focus,
|
||||
QDoubleSpinBox:focus,
|
||||
QDateEdit:focus,
|
||||
QTimeEdit:focus {
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QPlainTextEdit,
|
||||
QTextEdit {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
QLineEdit:disabled,
|
||||
QPlainTextEdit:disabled,
|
||||
QTextEdit:disabled,
|
||||
QSpinBox:disabled,
|
||||
QDoubleSpinBox:disabled,
|
||||
QDateEdit:disabled,
|
||||
QTimeEdit:disabled {
|
||||
background-color: #e8ecf2;
|
||||
color: #98a8c0;
|
||||
border-color: #d5dde8;
|
||||
}
|
||||
|
||||
/* ---- Spin Button Arrows ---- */
|
||||
QSpinBox::up-button,
|
||||
QDoubleSpinBox::up-button,
|
||||
QDateEdit::up-button,
|
||||
QTimeEdit::up-button {
|
||||
subcontrol-origin: border;
|
||||
subcontrol-position: top right;
|
||||
width: 10px;
|
||||
border-left: 1px solid #c0cdda;
|
||||
border-bottom: 1px solid #c0cdda;
|
||||
border-top-right-radius: 4px;
|
||||
}
|
||||
QSpinBox::up-button:hover,
|
||||
QDoubleSpinBox::up-button:hover,
|
||||
QDateEdit::up-button:hover,
|
||||
QTimeEdit::up-button:hover {
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QSpinBox::up-arrow,
|
||||
QDoubleSpinBox::up-arrow,
|
||||
QDateEdit::up-arrow,
|
||||
QTimeEdit::up-arrow {
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-bottom: 5px solid #6a7898;
|
||||
margin-top: 2px;
|
||||
}
|
||||
QSpinBox::down-button,
|
||||
QDoubleSpinBox::down-button,
|
||||
QDateEdit::down-button,
|
||||
QTimeEdit::down-button {
|
||||
width: 10px;
|
||||
subcontrol-origin: border;
|
||||
subcontrol-position: bottom right;
|
||||
border-left: 1px solid #c0cdda;
|
||||
border-bottom-right-radius: 4px;
|
||||
}
|
||||
QSpinBox::down-button:hover,
|
||||
QDoubleSpinBox::down-button:hover,
|
||||
QDateEdit::down-button:hover,
|
||||
QTimeEdit::down-button:hover {
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QSpinBox::down-arrow,
|
||||
QDoubleSpinBox::down-arrow,
|
||||
QDateEdit::down-arrow,
|
||||
QTimeEdit::down-arrow {
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 5px solid #6a7898;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
QSpinBox::up-button:disabled,
|
||||
QDoubleSpinBox::up-button:disabled,
|
||||
QDateEdit::up-button:disabled,
|
||||
QTimeEdit::up-button:disabled,
|
||||
QSpinBox::down-button:disabled,
|
||||
QDoubleSpinBox::down-button:disabled,
|
||||
QDateEdit::down-button:disabled,
|
||||
QTimeEdit::down-button:disabled {
|
||||
background-color: #e8ecf2;
|
||||
}
|
||||
QSpinBox::up-arrow:disabled,
|
||||
QDoubleSpinBox::up-arrow:disabled,
|
||||
QDateEdit::up-arrow:disabled,
|
||||
QTimeEdit::up-arrow:disabled {
|
||||
border-bottom-color: #98a8c0;
|
||||
}
|
||||
QSpinBox::down-arrow:disabled,
|
||||
QDoubleSpinBox::down-arrow:disabled,
|
||||
QDateEdit::down-arrow:disabled,
|
||||
QTimeEdit::down-arrow:disabled {
|
||||
border-top-color: #98a8c0;
|
||||
}
|
||||
|
||||
/* ---- Combo Box ---- */
|
||||
QComboBox {
|
||||
background-color: #d5dde8;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
padding: 4px 10px;
|
||||
color: #1a2740;
|
||||
}
|
||||
QComboBox:hover {
|
||||
border-color: #90a4c4;
|
||||
}
|
||||
QComboBox:focus {
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QComboBox::drop-down {
|
||||
subcontrol-origin: padding;
|
||||
subcontrol-position: top right;
|
||||
width: 24px;
|
||||
border-left: 1px solid #c0cdda;
|
||||
border-top-right-radius: 5px;
|
||||
border-bottom-right-radius: 5px;
|
||||
}
|
||||
QComboBox::down-arrow {
|
||||
image: none;
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 6px solid #6a7898;
|
||||
margin-right: 6px;
|
||||
}
|
||||
QComboBox QAbstractItemView {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #d0d8e4;
|
||||
border-width: 1px;
|
||||
border-radius: 4px;
|
||||
selection-background-color: #0ea58a;
|
||||
selection-color: #ffffff;
|
||||
outline: none;
|
||||
}
|
||||
QComboBox:disabled {
|
||||
background-color: #e8ecf2;
|
||||
color: #98a8c0;
|
||||
border-color: #d5dde8;
|
||||
}
|
||||
|
||||
/* ---- Check Box / Radio Button ---- */
|
||||
QCheckBox,
|
||||
QRadioButton {
|
||||
spacing: 5px;
|
||||
color: #1a2740;
|
||||
}
|
||||
QCheckBox::indicator,
|
||||
QRadioButton::indicator {
|
||||
border-style: solid;
|
||||
border-color: #90a4c4;
|
||||
border-width: 2px;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
QCheckBox::indicator {
|
||||
border-radius: 3px;
|
||||
}
|
||||
QRadioButton::indicator {
|
||||
border-radius: 7px;
|
||||
}
|
||||
QCheckBox::indicator:hover,
|
||||
QRadioButton::indicator:hover {
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QCheckBox::indicator:checked {
|
||||
background-color: #0ea58a;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QRadioButton::indicator:checked {
|
||||
background-color: #0ea58a;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QCheckBox::indicator:disabled,
|
||||
QRadioButton::indicator:disabled {
|
||||
border-color: #c0cdda;
|
||||
background-color: #e8ecf2;
|
||||
}
|
||||
QCheckBox::indicator:checked:hover,
|
||||
QRadioButton::indicator:checked:hover {
|
||||
border-color: #14c7a4;
|
||||
}
|
||||
|
||||
/* Tree / List / Table Widget CheckBox Indicator */
|
||||
QTreeWidget::indicator,
|
||||
QListWidget::indicator,
|
||||
QTableWidget::indicator {
|
||||
border: 2px solid #a0b4cc;
|
||||
border-radius: 3px;
|
||||
background-color: #e8ecf2;
|
||||
}
|
||||
QTreeWidget::indicator:hover,
|
||||
QListWidget::indicator:hover,
|
||||
QTableWidget::indicator:hover {
|
||||
border-color: #14c7a4;
|
||||
}
|
||||
QTreeWidget::indicator:checked,
|
||||
QListWidget::indicator:checked,
|
||||
QTableWidget::indicator:checked {
|
||||
background-color: #0ea58a;
|
||||
border-color: #0ea58a;
|
||||
}
|
||||
QTreeWidget::indicator:checked:hover,
|
||||
QListWidget::indicator:checked:hover,
|
||||
QTableWidget::indicator:checked:hover {
|
||||
border-color: #14c7a4;
|
||||
}
|
||||
QTreeWidget::indicator:disabled,
|
||||
QListWidget::indicator:disabled,
|
||||
QTableWidget::indicator:disabled {
|
||||
background-color: #d5dde8;
|
||||
border-color: #c0cdda;
|
||||
}
|
||||
QTreeWidget::indicator:indeterminate,
|
||||
QListWidget::indicator:indeterminate,
|
||||
QTableWidget::indicator:indeterminate {
|
||||
background-color: #0ea58a;
|
||||
border-color: #14c7a4;
|
||||
}
|
||||
|
||||
/* ---- Group Box ---- */
|
||||
QGroupBox {
|
||||
margin-top: 5px;
|
||||
padding-top: 15px;
|
||||
color: #4a6080;
|
||||
font-weight: bold;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* ---- Tab ---- */
|
||||
QTabWidget::pane {
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
background-color: #f0f4f8;
|
||||
top: -1px;
|
||||
}
|
||||
QTabBar::tab {
|
||||
background-color: #e0e6ee;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-bottom: none;
|
||||
border-top-left-radius: 5px;
|
||||
border-top-right-radius: 5px;
|
||||
padding: 6px 16px;
|
||||
margin-right: 2px;
|
||||
color: #6a7898;
|
||||
}
|
||||
QTabBar::tab:selected {
|
||||
background-color: #f0f4f8;
|
||||
color: #0ea58a;
|
||||
border-bottom: 2px solid #0ea58a;
|
||||
}
|
||||
|
||||
/* ---- List / Tree ---- */
|
||||
QListWidget,
|
||||
QTreeWidget,
|
||||
QTableWidget {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
outline: none;
|
||||
color: #1a2740;
|
||||
alternate-background-color: #f4f7fa;
|
||||
}
|
||||
QListWidget::item,
|
||||
QTreeWidget::item,
|
||||
QTableWidget::item {
|
||||
padding: 5px 5px;
|
||||
}
|
||||
QHeaderView::section {
|
||||
background-color: #dce4ee;
|
||||
border-right: 1px solid #c0cdda;
|
||||
border-bottom: 1px solid #c0cdda;
|
||||
padding: 5px 10px;
|
||||
color: #4a6080;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
/* ---- Scroll Bar ---- */
|
||||
QScrollBar:vertical {
|
||||
background-color: #eef2f6;
|
||||
width: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:vertical {
|
||||
background-color: #a0b4cc;
|
||||
min-height: 30px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:vertical:hover {
|
||||
background-color: #8098b8;
|
||||
}
|
||||
QScrollBar::add-line:vertical,
|
||||
QScrollBar::sub-line:vertical {
|
||||
height: 0;
|
||||
}
|
||||
QScrollBar:horizontal {
|
||||
background-color: #eef2f6;
|
||||
height: 10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:horizontal {
|
||||
background-color: #a0b4cc;
|
||||
min-width: 30px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
QScrollBar::handle:horizontal:hover {
|
||||
background-color: #8098b8;
|
||||
}
|
||||
QScrollBar::add-line:horizontal,
|
||||
QScrollBar::sub-line:horizontal {
|
||||
width: 0;
|
||||
}
|
||||
|
||||
/* ---- Progress Bar ---- */
|
||||
QProgressBar {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 5px;
|
||||
height: 10px;
|
||||
text-align: center;
|
||||
color: #1a2740;
|
||||
}
|
||||
QProgressBar::chunk {
|
||||
background-color: #0ea58a;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ---- Slider ---- */
|
||||
QSlider::groove:horizontal {
|
||||
background-color: #d5dde8;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
QSlider::handle:horizontal {
|
||||
background-color: #0ea58a;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: -5px 0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
QSlider::sub-page:horizontal {
|
||||
background-color: #0ea58a;
|
||||
border-radius: 3px;
|
||||
}
|
||||
QSlider::handle:horizontal:disabled {
|
||||
background-color: #98a8c0;
|
||||
}
|
||||
QSlider::sub-page:horizontal:disabled {
|
||||
background-color: #98a8c0;
|
||||
}
|
||||
|
||||
/* ---- Tool Tip ---- */
|
||||
QToolTip {
|
||||
background-color: #d5dde8;
|
||||
border-style: solid;
|
||||
border-color: #0ea58a;
|
||||
border-width: 1px;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
color: #1a2740;
|
||||
}
|
||||
|
||||
/* ---- Status Bar ---- */
|
||||
QStatusBar {
|
||||
background-color: #e8ecf2;
|
||||
border-top: 1px solid #c0cdda;
|
||||
color: #6a7898;
|
||||
}
|
||||
|
||||
/* ---- Splitter ---- */
|
||||
QSplitter::handle {
|
||||
background-color: #c0cdda;
|
||||
margin: 1px;
|
||||
}
|
||||
QSplitter::handle:horizontal {
|
||||
width: 2px;
|
||||
}
|
||||
QSplitter::handle:vertical {
|
||||
height: 2px;
|
||||
}
|
||||
|
||||
/* ---- Dialog ---- */
|
||||
QDialog {
|
||||
background-color: #f0f4f8;
|
||||
}
|
||||
|
||||
/* ---- Date / Time Editor Drop-down ---- */
|
||||
QDateEdit::drop-down,
|
||||
QTimeEdit::drop-down {
|
||||
subcontrol-origin: padding;
|
||||
subcontrol-position: top right;
|
||||
width: 24px;
|
||||
border-left: 1px solid #c0cdda;
|
||||
}
|
||||
QCalendarWidget {
|
||||
background-color: #ffffff;
|
||||
border-style: solid;
|
||||
border-color: #c0cdda;
|
||||
border-width: 1px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
QCalendarWidget QToolButton {
|
||||
color: #1a2740;
|
||||
border-radius: 4px;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
QCalendarWidget QToolButton:hover {
|
||||
background-color: #d5dde8;
|
||||
}
|
||||
QCalendarWidget QMenu {
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
/* ---- Frame ---- */
|
||||
QFrame[frameShape="4"], /* HLine */
|
||||
QFrame[frameShape="5"] /* VLine */ {
|
||||
background-color: #c0cdda;
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>800</width>
|
||||
<height>400</height>
|
||||
<height>600</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
@@ -103,53 +103,6 @@
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QFrame" name="AboutInfoSpaceFrame">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>56</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>56</width>
|
||||
<height>16777215</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="lineWidth">
|
||||
<number>0</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QTextBrowser" name="AboutInfoBrowser">
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="verticalScrollBarPolicy">
|
||||
<enum>Qt::ScrollBarPolicy::ScrollBarAlwaysOff</enum>
|
||||
</property>
|
||||
<property name="horizontalScrollBarPolicy">
|
||||
<enum>Qt::ScrollBarPolicy::ScrollBarAlwaysOff</enum>
|
||||
</property>
|
||||
<property name="lineWrapMode">
|
||||
<enum>QTextEdit::LineWrapMode::NoWrap</enum>
|
||||
</property>
|
||||
<property name="openExternalLinks">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="openLinks">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>ALBulletinDialog</class>
|
||||
<widget class="QDialog" name="ALBulletinDialog">
|
||||
<property name="windowModality">
|
||||
<enum>Qt::WindowModality::NonModal</enum>
|
||||
</property>
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>640</width>
|
||||
<height>450</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>400</width>
|
||||
<height>450</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>800</width>
|
||||
<height>450</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>公告栏 - AutoLibrary</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="ALBulletinDialogLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="SyncLayout">
|
||||
<property name="spacing">
|
||||
<number>10</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QPushButton" name="SyncButton">
|
||||
<property name="enabled">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="focusPolicy">
|
||||
<enum>Qt::FocusPolicy::NoFocus</enum>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>同步</string>
|
||||
</property>
|
||||
<property name="autoDefault">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="SyncStatusPlaceholder">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>30</width>
|
||||
<height>30</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>30</width>
|
||||
<height>30</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="SyncStatusDetailLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>200</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QFrame" name="SyncSpaceFrame">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>800</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<property name="lineWidth">
|
||||
<number>0</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="LastSyncTimeLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>50</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>50</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>上次同步:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QDateTimeEdit" name="LastSyncDateTimeEdit">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>130</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>130</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="frame">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="readOnly">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="buttonSymbols">
|
||||
<enum>QAbstractSpinBox::ButtonSymbols::NoButtons</enum>
|
||||
</property>
|
||||
<property name="keyboardTracking">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="displayFormat">
|
||||
<string>yyyy/MM/dd HH:mm:ss</string>
|
||||
</property>
|
||||
<property name="timeSpec">
|
||||
<enum>Qt::TimeSpec::LocalTime</enum>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QSplitter" name="BulletinSplitter">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<widget class="QFrame" name="LeftFrame">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="LeftFrameLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QListWidget" name="BulletinListWidget">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="editTriggers">
|
||||
<set>QAbstractItemView::EditTrigger::NoEditTriggers</set>
|
||||
</property>
|
||||
<property name="selectionMode">
|
||||
<enum>QAbstractItemView::SelectionMode::SingleSelection</enum>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<widget class="QFrame" name="RightFrame">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="frameShadow">
|
||||
<enum>QFrame::Shadow::Plain</enum>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="RightFrameLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinTitleLabel">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="BulletinInfoLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinDateLabel">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinAuthorLabel">
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinIsEditedLabel">
|
||||
<property name="text">
|
||||
<string>(已编辑)</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="BulletinInfoSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QTextBrowser" name="BulletinContentTextBrowser">
|
||||
<property name="readOnly">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<property name="openExternalLinks">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QDialogButtonBox" name="BulletinDialogButtonBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>16777215</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="standardButtons">
|
||||
<set>QDialogButtonBox::StandardButton::Cancel|QDialogButtonBox::StandardButton::Ok</set>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections>
|
||||
<connection>
|
||||
<sender>BulletinDialogButtonBox</sender>
|
||||
<signal>accepted()</signal>
|
||||
<receiver>ALBulletinDialog</receiver>
|
||||
<slot>accept()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
<x>248</x>
|
||||
<y>254</y>
|
||||
</hint>
|
||||
<hint type="destinationlabel">
|
||||
<x>157</x>
|
||||
<y>274</y>
|
||||
</hint>
|
||||
</hints>
|
||||
</connection>
|
||||
<connection>
|
||||
<sender>BulletinDialogButtonBox</sender>
|
||||
<signal>rejected()</signal>
|
||||
<receiver>ALBulletinDialog</receiver>
|
||||
<slot>reject()</slot>
|
||||
<hints>
|
||||
<hint type="sourcelabel">
|
||||
<x>316</x>
|
||||
<y>260</y>
|
||||
</hint>
|
||||
<hint type="destinationlabel">
|
||||
<x>286</x>
|
||||
<y>274</y>
|
||||
</hint>
|
||||
</hints>
|
||||
</connection>
|
||||
</connections>
|
||||
</ui>
|
||||
@@ -1956,13 +1956,13 @@
|
||||
<widget class="QPushButton" name="ExportConfigButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>120</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<width>120</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
|
||||
@@ -281,6 +281,13 @@ font: 700 9pt;</string>
|
||||
<property name="nativeMenuBar">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<widget class="QMenu" name="ToolsMenu">
|
||||
<property name="title">
|
||||
<string>工具</string>
|
||||
</property>
|
||||
<addaction name="SettingsAction"/>
|
||||
<addaction name="BulletinAction"/>
|
||||
</widget>
|
||||
<widget class="QMenu" name="HelpMenu">
|
||||
<property name="mouseTracking">
|
||||
<bool>true</bool>
|
||||
@@ -289,8 +296,10 @@ font: 700 9pt;</string>
|
||||
<string>帮助</string>
|
||||
</property>
|
||||
<addaction name="ManualAction"/>
|
||||
<addaction name="CheckUpdateAction"/>
|
||||
<addaction name="AboutAction"/>
|
||||
</widget>
|
||||
<addaction name="ToolsMenu"/>
|
||||
<addaction name="HelpMenu"/>
|
||||
</widget>
|
||||
<widget class="QStatusBar" name="StatusBar">
|
||||
@@ -303,11 +312,26 @@ font: 700 9pt;</string>
|
||||
<string>在线手册</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="CheckUpdateAction">
|
||||
<property name="text">
|
||||
<string>检查更新</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="AboutAction">
|
||||
<property name="text">
|
||||
<string>关于</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="SettingsAction">
|
||||
<property name="text">
|
||||
<string>全局设置</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="BulletinAction">
|
||||
<property name="text">
|
||||
<string>公告栏</string>
|
||||
</property>
|
||||
</action>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
|
||||
@@ -0,0 +1,788 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>ALSettingsWidget</class>
|
||||
<widget class="QWidget" name="ALSettingsWidget">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>520</width>
|
||||
<height>420</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>480</width>
|
||||
<height>420</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>580</width>
|
||||
<height>420</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>全局设置 - AutoLibrary</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="ALSettingsWidgetLayout">
|
||||
<property name="spacing">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="ContentLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QListWidget" name="NavigationList">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>0</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>16777215</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="focusPolicy">
|
||||
<enum>Qt::FocusPolicy::StrongFocus</enum>
|
||||
</property>
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="editTriggers">
|
||||
<set>QAbstractItemView::EditTrigger::NoEditTriggers</set>
|
||||
</property>
|
||||
<property name="selectionMode">
|
||||
<enum>QAbstractItemView::SelectionMode::SingleSelection</enum>
|
||||
</property>
|
||||
<property name="iconSize">
|
||||
<size>
|
||||
<width>20</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="currentRow">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<item>
|
||||
<property name="text">
|
||||
<string>外观</string>
|
||||
</property>
|
||||
<property name="icon">
|
||||
<iconset theme="preferences-desktop-color"/>
|
||||
</property>
|
||||
</item>
|
||||
<item>
|
||||
<property name="text">
|
||||
<string>公告</string>
|
||||
</property>
|
||||
<property name="icon">
|
||||
<iconset theme="preferences-desktop-color"/>
|
||||
</property>
|
||||
</item>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QStackedWidget" name="PageStack">
|
||||
<property name="currentIndex">
|
||||
<number>0</number>
|
||||
</property>
|
||||
<widget class="QScrollArea" name="AppearanceScrollArea">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="widgetResizable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<widget class="QWidget" name="AppearancePageContent">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>397</width>
|
||||
<height>434</height>
|
||||
</rect>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="AppearancePageLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="AppearanceGroupBox">
|
||||
<property name="title">
|
||||
<string>主题模式</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="AppearanceGroupBoxLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QRadioButton" name="LightThemeRadio">
|
||||
<property name="text">
|
||||
<string>浅色</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QRadioButton" name="DarkThemeRadio">
|
||||
<property name="text">
|
||||
<string>深色</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QRadioButton" name="SystemThemeRadio">
|
||||
<property name="text">
|
||||
<string>跟随系统</string>
|
||||
</property>
|
||||
<property name="checked">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="InterfaceGroupBox">
|
||||
<property name="title">
|
||||
<string>界面风格</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="InterfaceGroupBoxLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="StyleSelectLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="StyleSelectLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>应用程序样式:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QComboBox" name="StyleComboBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>160</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="StyleHintLabel">
|
||||
<property name="text">
|
||||
<string>更改样式将在下次启动应用程序时生效。</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="CustomThemeGroupBox">
|
||||
<property name="title">
|
||||
<string>自定义外观</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="CustomQssGroupBoxLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="CustomThemeHintLabel">
|
||||
<property name="text">
|
||||
<string>选择一个主题,或导入新的主题文件:</string>
|
||||
</property>
|
||||
<property name="wordWrap">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="CustomThemePathLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QComboBox" name="CustomThemeComboBox">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>160</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLineEdit" name="CustomThemePathEdit">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="visible">
|
||||
<bool>false</bool>
|
||||
</property>
|
||||
<property name="placeholderText">
|
||||
<string>选择或输入 QSS 样式表文件路径...</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="ImportCustomThemeButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>+</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="RemoveCustomThemeButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>25</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>-</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="CustomThemeInfoLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>60</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
<property name="textFormat">
|
||||
<enum>Qt::TextFormat::RichText</enum>
|
||||
</property>
|
||||
<property name="alignment">
|
||||
<set>Qt::AlignmentFlag::AlignLeading|Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignTop</set>
|
||||
</property>
|
||||
<property name="wordWrap">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="CustomThemeActionLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QPushButton" name="ResetCustomThemeButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>重置主题</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="CustomThemeActionSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="CustomThemeStatusLabel">
|
||||
<property name="text">
|
||||
<string>当前使用程序 默认 外观。</string>
|
||||
</property>
|
||||
<property name="wordWrap">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="AppearancePageSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Vertical</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>20</width>
|
||||
<height>40</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
<widget class="QScrollArea" name="BulletinScrollArea">
|
||||
<property name="frameShape">
|
||||
<enum>QFrame::Shape::NoFrame</enum>
|
||||
</property>
|
||||
<property name="widgetResizable">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
<widget class="QWidget" name="BulletinPageContent">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>409</width>
|
||||
<height>383</height>
|
||||
</rect>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="BulletinPageLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QGroupBox" name="BulletinGroupBox">
|
||||
<property name="title">
|
||||
<string>公告设置</string>
|
||||
</property>
|
||||
<layout class="QVBoxLayout" name="BulletinGroupBoxLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="BulletinServerUrlLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinServerUrlLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>服务器地址:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLineEdit" name="BulletinServerUrlEdit">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>200</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="placeholderText">
|
||||
<string>https://api.autolibrary.kenanzhu.com</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QCheckBox" name="BulletinAutoFetchCheck">
|
||||
<property name="text">
|
||||
<string>软件启动时自动获取公告</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="BulletinSyncIntervalLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinSyncIntervalLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>自动同步间隔:</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QSpinBox" name="BulletinSyncIntervalSpin">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="suffix">
|
||||
<string> 分钟</string>
|
||||
</property>
|
||||
<property name="minimum">
|
||||
<number>1</number>
|
||||
</property>
|
||||
<property name="maximum">
|
||||
<number>1440</number>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="BulletinSyncIntervalSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="BulletinTestButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>测试连接</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QLabel" name="BulletinTestStatusLabel">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>0</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>16777215</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string/>
|
||||
</property>
|
||||
<property name="wordWrap">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="BulletinOpenButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>100</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>查看公告栏</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<spacer name="BulletinPageSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Vertical</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>20</width>
|
||||
<height>40</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
</widget>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
<item>
|
||||
<layout class="QHBoxLayout" name="ButtonLayout">
|
||||
<property name="spacing">
|
||||
<number>5</number>
|
||||
</property>
|
||||
<property name="leftMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="topMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="rightMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<property name="bottomMargin">
|
||||
<number>3</number>
|
||||
</property>
|
||||
<item>
|
||||
<spacer name="ButtonLeftSpacer">
|
||||
<property name="orientation">
|
||||
<enum>Qt::Orientation::Horizontal</enum>
|
||||
</property>
|
||||
<property name="sizeHint" stdset="0">
|
||||
<size>
|
||||
<width>40</width>
|
||||
<height>20</height>
|
||||
</size>
|
||||
</property>
|
||||
</spacer>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="CancelButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>取消</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="ApplyButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>应用</string>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
<item>
|
||||
<widget class="QPushButton" name="ConfirmButton">
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
<size>
|
||||
<width>80</width>
|
||||
<height>25</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="text">
|
||||
<string>确认</string>
|
||||
</property>
|
||||
<property name="default">
|
||||
<bool>true</bool>
|
||||
</property>
|
||||
</widget>
|
||||
</item>
|
||||
</layout>
|
||||
</item>
|
||||
</layout>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
||||
@@ -7,13 +7,13 @@
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>350</width>
|
||||
<height>400</height>
|
||||
<height>500</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="minimumSize">
|
||||
<size>
|
||||
<width>350</width>
|
||||
<height>460</height>
|
||||
<height>500</height>
|
||||
</size>
|
||||
</property>
|
||||
<property name="maximumSize">
|
||||
|
||||
@@ -66,6 +66,18 @@ class CfgKey:
|
||||
CURRENT = ConfigPath(ConfigType.GLOBAL, "automation.user_path.current")
|
||||
PATHS = ConfigPath(ConfigType.GLOBAL, "automation.user_path.paths")
|
||||
|
||||
class APPEARANCE:
|
||||
ROOT = ConfigPath(ConfigType.GLOBAL, "appearance")
|
||||
THEME = ConfigPath(ConfigType.GLOBAL, "appearance.theme")
|
||||
STYLE = ConfigPath(ConfigType.GLOBAL, "appearance.style")
|
||||
CUSTOM_THEME = ConfigPath(ConfigType.GLOBAL, "appearance.custom_theme")
|
||||
|
||||
class BULLETIN:
|
||||
ROOT = ConfigPath(ConfigType.GLOBAL, "bulletin")
|
||||
AUTO_FETCH = ConfigPath(ConfigType.GLOBAL, "bulletin.auto_fetch")
|
||||
SERVER_URL = ConfigPath(ConfigType.GLOBAL, "bulletin.server_url")
|
||||
SYNC_INTERVAL = ConfigPath(ConfigType.GLOBAL, "bulletin.sync_interval")
|
||||
|
||||
class TIMERTASK:
|
||||
ROOT = ConfigPath(ConfigType.TIMERTASK, "")
|
||||
TIMER_TASKS = ConfigPath(ConfigType.TIMERTASK, "timer_tasks")
|
||||
|
||||
@@ -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
|
||||
used across layers to decouple consumers from concrete implementations.
|
||||
|
||||
Key components:
|
||||
- ConfigProvider: Abstract interface for configuration access.
|
||||
- ConfigType: Enumeration of configuration file types.
|
||||
- ConfigKey: Type-safe hierarchical key constants for config lookups.
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -1,8 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Managers module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- ConfigManager: Config manager for managing configuration files.
|
||||
- LogManager: Log manager for logging.
|
||||
- WebDriverManager: Web driver manager for managing web drivers.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -0,0 +1,340 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import threading
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional
|
||||
|
||||
from interfaces.ConfigProvider import (
|
||||
CfgKey,
|
||||
ConfigProvider
|
||||
)
|
||||
from managers.config.ConfigManager import instance as configInstance
|
||||
|
||||
|
||||
class BulletinManager:
|
||||
"""
|
||||
Bulletin Manager Singleton Class
|
||||
|
||||
Manages bulletin data persistence via ConfigManager and provides
|
||||
merge, read-status and sync-parameter logic. The HTTP fetch and
|
||||
UI concerns are handled by the GUI layer.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self
|
||||
):
|
||||
|
||||
self.__lock = threading.Lock()
|
||||
self.__cfg: ConfigProvider = configInstance()
|
||||
|
||||
def bulletins(
|
||||
self
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Get cached bulletins.
|
||||
|
||||
Returns:
|
||||
list[dict]: Cached bulletin list.
|
||||
"""
|
||||
|
||||
return self.__cfg.get(CfgKey.BULLETIN.BULLETIN, [])
|
||||
|
||||
def setBulletins(
|
||||
self,
|
||||
bulletins: list[dict]
|
||||
):
|
||||
"""
|
||||
Replace the bulletin cache.
|
||||
|
||||
Args:
|
||||
bulletins (list[dict]): Bulletin list to store.
|
||||
"""
|
||||
|
||||
self.__cfg.set(CfgKey.BULLETIN.BULLETIN, bulletins)
|
||||
|
||||
def lastSyncTime(
|
||||
self
|
||||
) -> Optional[str]:
|
||||
"""
|
||||
Get last sync time string.
|
||||
|
||||
Returns:
|
||||
Optional[str]: ISO-format last sync time, or None.
|
||||
"""
|
||||
|
||||
return self.__cfg.get(CfgKey.BULLETIN.LAST_SYNC_TIME, None)
|
||||
|
||||
def setLastSyncTime(
|
||||
self,
|
||||
value: Optional[str]
|
||||
):
|
||||
"""
|
||||
Set last sync time.
|
||||
|
||||
Args:
|
||||
value (Optional[str]): ISO-format datetime string.
|
||||
"""
|
||||
|
||||
self.__cfg.set(CfgKey.BULLETIN.LAST_SYNC_TIME, value)
|
||||
|
||||
def autoFetch(
|
||||
self
|
||||
) -> bool:
|
||||
"""
|
||||
Get auto-fetch-on-startup setting.
|
||||
|
||||
Returns:
|
||||
bool: Whether to fetch bulletins on application startup.
|
||||
"""
|
||||
|
||||
return self.__cfg.get(CfgKey.GLOBAL.BULLETIN.AUTO_FETCH, False)
|
||||
|
||||
def serverUrl(
|
||||
self
|
||||
) -> str:
|
||||
"""
|
||||
Get bulletin server URL.
|
||||
|
||||
Returns:
|
||||
str: Server base URL.
|
||||
"""
|
||||
|
||||
return self.__cfg.get(
|
||||
CfgKey.GLOBAL.BULLETIN.SERVER_URL,
|
||||
"https://api.autolibrary.kenanzhu.com"
|
||||
)
|
||||
|
||||
def syncInterval(
|
||||
self
|
||||
) -> int:
|
||||
"""
|
||||
Get auto-sync interval in minutes.
|
||||
|
||||
Values below 1 are clamped upward. Non-integer or missing
|
||||
values fall back to the default of 10 minutes.
|
||||
|
||||
Returns:
|
||||
int: Sync interval (minutes), minimum 1.
|
||||
"""
|
||||
|
||||
interval = self.__cfg.get(CfgKey.GLOBAL.BULLETIN.SYNC_INTERVAL, 10)
|
||||
try:
|
||||
interval = int(interval)
|
||||
except (ValueError, TypeError):
|
||||
return 10
|
||||
if interval < 1:
|
||||
return 5
|
||||
return interval
|
||||
|
||||
def apiUrl(
|
||||
self
|
||||
) -> str:
|
||||
"""
|
||||
Build the full bulletin API endpoint URL.
|
||||
|
||||
Returns:
|
||||
str: Full API URL (base + /bulletins).
|
||||
"""
|
||||
|
||||
base = self.serverUrl().rstrip("/")
|
||||
return f"{base}/bulletins"
|
||||
|
||||
@staticmethod
|
||||
def _ensureAware(
|
||||
dt_value: datetime
|
||||
) -> datetime:
|
||||
|
||||
if dt_value.tzinfo is None:
|
||||
return dt_value.replace(tzinfo=timezone.utc)
|
||||
return dt_value
|
||||
|
||||
@staticmethod
|
||||
def _parseBulletinDateTime(
|
||||
b: dict
|
||||
) -> datetime:
|
||||
|
||||
raw = b.get("dateTime", "")
|
||||
if not raw:
|
||||
raise ValueError("empty dateTime")
|
||||
dt_value = datetime.fromisoformat(raw)
|
||||
return BulletinManager._ensureAware(dt_value)
|
||||
|
||||
def isFirstSync(
|
||||
self
|
||||
) -> bool:
|
||||
"""
|
||||
Check whether this is the first sync.
|
||||
|
||||
Returns:
|
||||
bool: True if no cached bulletins or no last sync time.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
last = self.lastSyncTime()
|
||||
bulletins = self.bulletins()
|
||||
return last is None or not bulletins
|
||||
|
||||
def shouldFullSync(
|
||||
self
|
||||
) -> bool:
|
||||
"""
|
||||
Check whether a full sync is needed.
|
||||
|
||||
A full sync is triggered when the last sync time is more than
|
||||
one hour ago.
|
||||
|
||||
Returns:
|
||||
bool: True if a full sync should be performed.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
last = self.lastSyncTime()
|
||||
if last is None:
|
||||
return True
|
||||
try:
|
||||
last_dt = datetime.fromisoformat(last)
|
||||
last_dt = self._ensureAware(last_dt)
|
||||
now = datetime.now(timezone.utc).astimezone()
|
||||
return (now - last_dt) > timedelta(hours=1)
|
||||
except (ValueError, TypeError):
|
||||
return True
|
||||
|
||||
def getSyncDateTimeAndRange(
|
||||
self
|
||||
) -> dict:
|
||||
"""
|
||||
Calculate the date / time / range_hour query parameters.
|
||||
|
||||
Falls back to a first-sync (7-day window) on any parsing error.
|
||||
|
||||
Returns:
|
||||
dict: Keys "date", "time", "range_hour" for the API request.
|
||||
"""
|
||||
|
||||
now = datetime.now(timezone.utc).astimezone()
|
||||
try:
|
||||
if self.isFirstSync():
|
||||
start_date = now - timedelta(days=7)
|
||||
range_hour = str(24*8)
|
||||
elif self.shouldFullSync():
|
||||
with self.__lock:
|
||||
bulletins = self.bulletins()
|
||||
earliest = min(bulletins, key=self._parseBulletinDateTime)
|
||||
start_date = self._parseBulletinDateTime(earliest)
|
||||
diff = now - start_date
|
||||
range_hour = str(int(diff.total_seconds()/3600) + 1)
|
||||
else:
|
||||
with self.__lock:
|
||||
bulletins = self.bulletins()
|
||||
latest = max(bulletins, key=self._parseBulletinDateTime)
|
||||
start_date = self._parseBulletinDateTime(latest)
|
||||
diff = now - start_date
|
||||
range_hour = str(int(diff.total_seconds()/3600) + 1)
|
||||
except (ValueError, TypeError, KeyError):
|
||||
start_date = now - timedelta(days=7)
|
||||
range_hour = str(24*8)
|
||||
|
||||
return {
|
||||
"date": start_date.strftime("%Y-%m-%d"),
|
||||
"time": start_date.strftime("%H:%M:%S"),
|
||||
"range_hour": range_hour,
|
||||
}
|
||||
|
||||
def updateAndMergeBulletins(
|
||||
self,
|
||||
new_bulletins: list[dict],
|
||||
delete_ids: list[str]
|
||||
) -> list[dict]:
|
||||
"""
|
||||
Merge incoming bulletins into the cache.
|
||||
|
||||
- New bulletins are added with isNew=True.
|
||||
- Existing bulletins keep their current isNew state.
|
||||
- Entries listed in delete_ids are removed.
|
||||
- Bulletins missing an "id" field are skipped.
|
||||
|
||||
Args:
|
||||
new_bulletins (list[dict]): Incoming bulletin list.
|
||||
delete_ids (list[str]): IDs to remove.
|
||||
|
||||
Returns:
|
||||
list[dict]: Merged bulletin list sorted by id.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
delete_set = set(str(d) for d in delete_ids)
|
||||
bulletins_dict = {}
|
||||
for b in self.bulletins():
|
||||
bid = b.get("id")
|
||||
if bid is not None:
|
||||
bulletins_dict[str(bid)] = b
|
||||
for bulletin in new_bulletins:
|
||||
bid = bulletin.get("id")
|
||||
if bid is None:
|
||||
continue
|
||||
bid = str(bid)
|
||||
if bid in delete_set:
|
||||
bulletins_dict.pop(bid, None)
|
||||
continue
|
||||
bulletin["isNew"] = (
|
||||
True
|
||||
if bid not in bulletins_dict
|
||||
else bulletins_dict[bid].get("isNew", True)
|
||||
)
|
||||
bulletins_dict[bid] = bulletin
|
||||
for bid in delete_set:
|
||||
bulletins_dict.pop(bid, None)
|
||||
result = list(bulletins_dict.values())
|
||||
result.sort(key=lambda x: str(x.get("id", "")))
|
||||
self.setBulletins(result)
|
||||
return result
|
||||
|
||||
def markBulletinAsRead(
|
||||
self,
|
||||
bulletin_id: str
|
||||
):
|
||||
"""
|
||||
Mark a bulletin as read by its id.
|
||||
|
||||
Args:
|
||||
bulletin_id (str): The bulletin id.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
bulletins = self.bulletins()
|
||||
for b in bulletins:
|
||||
if str(b.get("id", "")) == str(bulletin_id):
|
||||
b["isNew"] = False
|
||||
self.setBulletins(bulletins)
|
||||
break
|
||||
|
||||
|
||||
# BulletinManager singleton instance.
|
||||
_bulletin_manager_instance = None
|
||||
|
||||
# Singleton instance lock.
|
||||
_instance_lock = threading.Lock()
|
||||
|
||||
|
||||
def instance(
|
||||
) -> BulletinManager:
|
||||
"""
|
||||
Get the BulletinManager singleton instance.
|
||||
|
||||
Returns:
|
||||
BulletinManager: The singleton BulletinManager instance.
|
||||
"""
|
||||
|
||||
global _bulletin_manager_instance
|
||||
with _instance_lock:
|
||||
if _bulletin_manager_instance is None:
|
||||
_bulletin_manager_instance = BulletinManager()
|
||||
return _bulletin_manager_instance
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -7,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.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import copy
|
||||
import os
|
||||
import threading
|
||||
|
||||
@@ -18,7 +19,7 @@ from interfaces.ConfigProvider import ConfigType, ConfigPath
|
||||
|
||||
|
||||
# This config manager class only responsible for global and other
|
||||
# unconfigurable config files.
|
||||
# config files. NOT include run and user config files.
|
||||
|
||||
|
||||
class ConfigTemplate:
|
||||
@@ -54,6 +55,16 @@ class ConfigTemplate:
|
||||
"current": 0,
|
||||
"paths": []
|
||||
}
|
||||
},
|
||||
"appearance": {
|
||||
"theme": "system",
|
||||
"style": "Fusion",
|
||||
"custom_theme": ""
|
||||
},
|
||||
"bulletin": {
|
||||
"auto_fetch": False,
|
||||
"server_url": "https://api.autolibrary.kenanzhu.com",
|
||||
"sync_interval": 10
|
||||
}
|
||||
}
|
||||
case ConfigType.BULLETIN:
|
||||
@@ -77,8 +88,8 @@ class ConfigManager:
|
||||
):
|
||||
|
||||
self.__config_dir = os.path.abspath(config_dir)
|
||||
self.__config_lock = threading.Lock()
|
||||
self.__config_data = {}
|
||||
self.__lock = threading.Lock()
|
||||
|
||||
self.initialize()
|
||||
|
||||
@@ -100,7 +111,7 @@ class ConfigManager:
|
||||
config_data = JSONReader(config_path).data()
|
||||
self.__config_data[config_type.value] = config_data
|
||||
return
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
self.__config_data[config_type.value] = ConfigTemplate(config_type).template()
|
||||
JSONWriter(config_path, self.__config_data[config_type.value])
|
||||
@@ -111,16 +122,16 @@ class ConfigManager:
|
||||
default: Optional[Any] = None
|
||||
) -> Any:
|
||||
|
||||
with self.__config_lock:
|
||||
with self.__lock:
|
||||
config_data = self.__config_data[key.config_type.value]
|
||||
if key.key == "":
|
||||
return config_data
|
||||
return copy.deepcopy(config_data)
|
||||
keys = key.key.split('.')
|
||||
for k in keys[:-1]:
|
||||
config_data = config_data.get(k, None)
|
||||
if config_data is None:
|
||||
return default
|
||||
return config_data.get(keys[-1], default)
|
||||
return copy.deepcopy(config_data.get(keys[-1], default))
|
||||
|
||||
def set(
|
||||
self,
|
||||
@@ -128,7 +139,7 @@ class ConfigManager:
|
||||
value: Any = None
|
||||
):
|
||||
|
||||
with self.__config_lock:
|
||||
with self.__lock:
|
||||
root_data = self.__config_data[key.config_type.value]
|
||||
if key.key == "":
|
||||
self.__config_data[key.config_type.value] = value
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Config managers module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- ConfigManager: Config manager for managing configuration files.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -181,7 +181,7 @@ class WebDriverFileName:
|
||||
raise ValueError(f"不受支持的 web driver 类型 : {self.driver_type}")
|
||||
|
||||
|
||||
class WebDriverURL:
|
||||
class WebDriverDownloadURL:
|
||||
"""
|
||||
Web driver download URL
|
||||
"""
|
||||
@@ -242,7 +242,7 @@ class WebDriverDownloader:
|
||||
self.driver_type = driver_type
|
||||
self.arch = driver_arch
|
||||
self.version = driver_version
|
||||
self.download_url = str(WebDriverURL(self.version, self.driver_type, self.arch))
|
||||
self.download_url = str(WebDriverDownloadURL(self.version, self.driver_type, self.arch))
|
||||
self.download_dir = Path(download_dir)/self.driver_type.value/self.version/self.arch.value
|
||||
self.download_dir.mkdir(mode=0o0755, parents=True, exist_ok=True)
|
||||
self.download_path = self.download_dir/str(WebDriverFileName(self.version, self.driver_type, self.arch))
|
||||
@@ -360,6 +360,10 @@ class WebDriverDownloader:
|
||||
break
|
||||
if not driver_file:
|
||||
raise FileNotFoundError(f"未找到 web driver 文件 : {expected_name}")
|
||||
# Ensure executable permissions on Unix systems (zipfile
|
||||
# extraction does not preserve the execute bit).
|
||||
if os.name != 'nt':
|
||||
os.chmod(driver_file, 0o755)
|
||||
progress_callback(100, 100, 0.0, "解压完成")
|
||||
self.download_path.unlink()
|
||||
self._cleanup(driver_file)
|
||||
|
||||
@@ -8,6 +8,7 @@ You may use, modify, and distribute this file under the terms of the MIT License
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
import packaging.version as ver
|
||||
|
||||
@@ -19,7 +20,7 @@ from managers.driver.WebBrowserDetector import (
|
||||
WebBrowserType, WebBrowserArch, WebBrowserInfo, WebBrowserDetector
|
||||
)
|
||||
from managers.driver.WebDriverDownloader import (
|
||||
WebDriverArch, WebDriverType,
|
||||
WebDriverArch, WebDriverType, WebDriverExecName,
|
||||
ChromeDriverDownloader, FirefoxDriverDownloader, EdgeDriverDownloader
|
||||
)
|
||||
|
||||
@@ -35,9 +36,9 @@ class WebDriverStatus(Enum):
|
||||
ERROR = 3
|
||||
|
||||
|
||||
class WebDriverInfo:
|
||||
class WebDriverCtx:
|
||||
"""
|
||||
Web driver information.
|
||||
Web browser and driver context.
|
||||
|
||||
Attributes:
|
||||
driver_type (WebDriverType): Web driver type
|
||||
@@ -52,8 +53,8 @@ class WebDriverInfo:
|
||||
self
|
||||
):
|
||||
|
||||
self.driver_type = None
|
||||
self.driver_arch = None
|
||||
self.driver_type : Optional[WebDriverType] = None
|
||||
self.driver_arch : Optional[WebDriverArch] = None
|
||||
self.driver_version = ""
|
||||
self.browser_version = ""
|
||||
self.driver_path: Optional[Path] = None
|
||||
@@ -75,7 +76,7 @@ class WebDriverManager:
|
||||
|
||||
self.__driver_dir = os.path.abspath(driver_dir)
|
||||
self.__browser_detector = WebBrowserDetector()
|
||||
self.__driver_infos: list[WebDriverInfo] = []
|
||||
self.__driver_ctxs: list[WebDriverCtx] = []
|
||||
self.__initialized = False
|
||||
self.__lock = threading.Lock()
|
||||
|
||||
@@ -98,8 +99,8 @@ class WebDriverManager:
|
||||
|
||||
with self.__lock:
|
||||
browser_infos = self.__browser_detector.detect()
|
||||
self.__driver_infos = [
|
||||
self._getDriverInfo(info)
|
||||
self.__driver_ctxs = [
|
||||
self._getDriverCtx(info)
|
||||
for info in browser_infos
|
||||
]
|
||||
|
||||
@@ -108,9 +109,13 @@ class WebDriverManager:
|
||||
):
|
||||
|
||||
with self.__lock:
|
||||
for driver_info in self.__driver_infos:
|
||||
for driver_info in self.__driver_ctxs:
|
||||
driver_path = self._getDriverPath(driver_info)
|
||||
if driver_path and driver_path.exists() and driver_path.is_file():
|
||||
# Repair missing execute permission on Unix
|
||||
# (zip-extracted drivers from older versions).
|
||||
if os.name != 'nt' and not os.access(str(driver_path), os.X_OK):
|
||||
os.chmod(str(driver_path), 0o755)
|
||||
driver_info.driver_path = driver_path
|
||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
||||
|
||||
@@ -194,7 +199,7 @@ class WebDriverManager:
|
||||
else:
|
||||
raise ValueError(f"不支持的 Web 浏览器类型 : {browser_type}")
|
||||
|
||||
def _mapFirefoxDriverVersion(
|
||||
def _mapFirefoxBrowserVersionToDriver(
|
||||
self,
|
||||
version: str
|
||||
) -> str:
|
||||
@@ -234,46 +239,30 @@ class WebDriverManager:
|
||||
except Exception as e:
|
||||
raise ValueError(f"无效的 Firefox 版本格式 : {version}") from e
|
||||
|
||||
def _getDriverInfo(
|
||||
def _getDriverCtx(
|
||||
self,
|
||||
browser_info: WebBrowserInfo
|
||||
) -> WebDriverInfo:
|
||||
) -> WebDriverCtx:
|
||||
|
||||
driver_info = WebDriverInfo()
|
||||
driver_info.driver_type = self._mapWebBrowserTypeToDriver(browser_info.browser_type)
|
||||
driver_info.driver_arch = self._mapWebBrowserArchToDriver(browser_info.browser_type, browser_info.browser_arch)
|
||||
driver_ctx = WebDriverCtx()
|
||||
driver_ctx.driver_type = self._mapWebBrowserTypeToDriver(browser_info.browser_type)
|
||||
driver_ctx.driver_arch = self._mapWebBrowserArchToDriver(browser_info.browser_type, browser_info.browser_arch)
|
||||
if browser_info.browser_type == WebBrowserType.FIREFOX:
|
||||
driver_info.driver_version = self._mapFirefoxDriverVersion(browser_info.browser_version)
|
||||
driver_ctx.driver_version = self._mapFirefoxBrowserVersionToDriver(browser_info.browser_version)
|
||||
else:
|
||||
driver_info.driver_version = browser_info.browser_version
|
||||
driver_info.browser_version = browser_info.browser_version
|
||||
return driver_info
|
||||
driver_ctx.driver_version = browser_info.browser_version
|
||||
driver_ctx.browser_version = browser_info.browser_version
|
||||
return driver_ctx
|
||||
|
||||
def _getDriverPath(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
driver_ctx: WebDriverCtx
|
||||
) -> Optional[Path]:
|
||||
|
||||
driver_type = driver_info.driver_type
|
||||
driver_arch = driver_info.driver_arch
|
||||
driver_version = driver_info.driver_version
|
||||
if driver_type == WebDriverType.CHROME:
|
||||
driver_name = "chromedriver"
|
||||
elif driver_type == WebDriverType.FIREFOX:
|
||||
driver_name = "geckodriver"
|
||||
elif driver_type == WebDriverType.EDGE:
|
||||
driver_name = "msedgedriver"
|
||||
else:
|
||||
return None
|
||||
is_win = driver_arch in [
|
||||
WebDriverArch.Chrome.WINX86_32,
|
||||
WebDriverArch.Chrome.WINX86_64,
|
||||
WebDriverArch.Firefox.WINX86_32,
|
||||
WebDriverArch.Firefox.WINX86_64,
|
||||
WebDriverArch.Edge.WINX86_32,
|
||||
WebDriverArch.Edge.WINX86_64,
|
||||
]
|
||||
exe_name = f"{driver_name}.exe" if is_win else driver_name
|
||||
driver_type = driver_ctx.driver_type
|
||||
driver_arch = driver_ctx.driver_arch
|
||||
driver_version = driver_ctx.driver_version
|
||||
exe_name = str(WebDriverExecName(driver_type, driver_arch))
|
||||
driver_dir = Path(self.__driver_dir)/driver_type.value/driver_version/driver_arch.value
|
||||
driver_path = driver_dir/exe_name
|
||||
return driver_path
|
||||
@@ -285,28 +274,28 @@ class WebDriverManager:
|
||||
self._detectBrowsers()
|
||||
self._checkDriverStatus()
|
||||
|
||||
def getDriverInfos(
|
||||
def getDriverCtxs(
|
||||
self
|
||||
) -> list[WebDriverInfo]:
|
||||
) -> list[WebDriverCtx]:
|
||||
|
||||
with self.__lock:
|
||||
return self.__driver_infos.copy()
|
||||
return self.__driver_ctxs.copy()
|
||||
|
||||
def getDriverInfo(
|
||||
def getDriverCtx(
|
||||
self,
|
||||
driver_type: WebDriverType
|
||||
) -> list[WebDriverInfo]:
|
||||
) -> list[WebDriverCtx]:
|
||||
|
||||
with self.__lock:
|
||||
return [
|
||||
info
|
||||
for info in self.__driver_infos
|
||||
for info in self.__driver_ctxs
|
||||
if info.driver_type == driver_type
|
||||
]
|
||||
|
||||
def getDriverPath(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
driver_info: WebDriverCtx
|
||||
) -> Optional[Path]:
|
||||
|
||||
if driver_info and driver_info.driver_status == WebDriverStatus.INSTALLED:
|
||||
@@ -315,28 +304,28 @@ class WebDriverManager:
|
||||
|
||||
def installDriver(
|
||||
self,
|
||||
driver_info: WebDriverInfo,
|
||||
driver_ctx: WebDriverCtx,
|
||||
progress_callback: Optional[Callable[[float, int, float, str], None]] = None,
|
||||
cancel_event: Optional[threading.Event] = None
|
||||
) -> Optional[Path]:
|
||||
|
||||
with self.__lock:
|
||||
if not driver_info:
|
||||
if not driver_ctx:
|
||||
if progress_callback:
|
||||
progress_callback(0, 0, 0, "未找到浏览器信息")
|
||||
else:
|
||||
raise ValueError("未找到浏览器信息")
|
||||
if driver_info and driver_info.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
if driver_ctx and driver_ctx.driver_status == WebDriverStatus.DOWNLOADING:
|
||||
if progress_callback:
|
||||
progress_callback(0, 0, 0, f"{driver_info.driver_type} 驱动正在下载中")
|
||||
progress_callback(0, 0, 0, f"{driver_ctx.driver_type} 驱动正在下载中")
|
||||
else:
|
||||
raise ValueError(f"{driver_info.driver_type} 驱动正在下载中")
|
||||
raise ValueError(f"{driver_ctx.driver_type} 驱动正在下载中")
|
||||
try:
|
||||
if not driver_info:
|
||||
if not driver_ctx:
|
||||
raise ValueError("未找到浏览器信息")
|
||||
driver_arch = driver_info.driver_arch
|
||||
driver_type = driver_info.driver_type
|
||||
driver_version = driver_info.driver_version
|
||||
driver_arch = driver_ctx.driver_arch
|
||||
driver_type = driver_ctx.driver_type
|
||||
driver_version = driver_ctx.driver_version
|
||||
downloader = None
|
||||
if driver_type == WebDriverType.CHROME:
|
||||
downloader = ChromeDriverDownloader(
|
||||
@@ -362,68 +351,66 @@ class WebDriverManager:
|
||||
else:
|
||||
raise ValueError(f"不支持的 Web Driver 类型")
|
||||
with self.__lock:
|
||||
driver_info.driver_status = WebDriverStatus.DOWNLOADING
|
||||
driver_ctx.driver_status = WebDriverStatus.DOWNLOADING
|
||||
driver_path = downloader.download(progress_callback=progress_callback, cancel_event=cancel_event)
|
||||
with self.__lock:
|
||||
if driver_path:
|
||||
driver_info.driver_path = driver_path
|
||||
driver_info.driver_version = driver_version
|
||||
driver_info.driver_status = WebDriverStatus.INSTALLED
|
||||
driver_ctx.driver_path = driver_path
|
||||
driver_ctx.driver_version = driver_version
|
||||
driver_ctx.driver_status = WebDriverStatus.INSTALLED
|
||||
else:
|
||||
driver_info.driver_status = WebDriverStatus.ERROR
|
||||
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||
return driver_path
|
||||
except Exception as e:
|
||||
with self.__lock:
|
||||
driver_info.driver_status = WebDriverStatus.ERROR
|
||||
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||
raise e
|
||||
|
||||
def cancelDriverDownload(
|
||||
self,
|
||||
driver_info: WebDriverInfo
|
||||
driver_ctx: WebDriverCtx
|
||||
) -> bool:
|
||||
|
||||
import shutil
|
||||
|
||||
try:
|
||||
driver_path = self._getDriverPath(driver_info)
|
||||
driver_path = self._getDriverPath(driver_ctx)
|
||||
if driver_path:
|
||||
download_dir = driver_path.parent
|
||||
if download_dir.exists():
|
||||
shutil.rmtree(download_dir, ignore_errors=True)
|
||||
with self.__lock:
|
||||
driver_info.driver_path = None
|
||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
driver_ctx.driver_path = None
|
||||
driver_ctx.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def uninstallDriver(
|
||||
self,
|
||||
driver_info: WebDriverInfo,
|
||||
driver_ctx: WebDriverCtx,
|
||||
progress_callback: Optional[Callable[[int, int, float, str], None]] = None
|
||||
) -> bool:
|
||||
|
||||
with self.__lock:
|
||||
if not driver_info:
|
||||
if not driver_ctx:
|
||||
if progress_callback:
|
||||
progress_callback(0, 0, 0, "未找到浏览器信息")
|
||||
else:
|
||||
raise ValueError("未找到浏览器信息")
|
||||
if driver_info.driver_status != WebDriverStatus.INSTALLED:
|
||||
if driver_ctx.driver_status != WebDriverStatus.INSTALLED:
|
||||
if progress_callback:
|
||||
progress_callback(0, 0, 0, f"{driver_info.driver_type} 驱动未安装")
|
||||
progress_callback(0, 0, 0, f"{driver_ctx.driver_type} 驱动未安装")
|
||||
else:
|
||||
raise ValueError(f"{driver_info.driver_type} 驱动未安装")
|
||||
raise ValueError(f"{driver_ctx.driver_type} 驱动未安装")
|
||||
try:
|
||||
driver_path = driver_info.driver_path
|
||||
driver_path = driver_ctx.driver_path
|
||||
driver_path.unlink()
|
||||
with self.__lock:
|
||||
driver_info.driver_path = None
|
||||
driver_info.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
driver_ctx.driver_path = None
|
||||
driver_ctx.driver_status = WebDriverStatus.NOT_INSTALLED
|
||||
return True
|
||||
except Exception:
|
||||
with self.__lock:
|
||||
driver_info.driver_status = WebDriverStatus.ERROR
|
||||
driver_ctx.driver_status = WebDriverStatus.ERROR
|
||||
raise
|
||||
|
||||
def driverDir(
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Driver managers module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- WebBrowserDetector: Web browser detector class.
|
||||
- WebDriverDownloader: Web driver downloader class.
|
||||
- WebDriverManager: Web driver manager class.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -99,17 +99,14 @@ class LogManager:
|
||||
self.__logger = logging.getLogger("AutoLibrary")
|
||||
self.__logger.setLevel(logging.DEBUG)
|
||||
self.__logger.handlers.clear()
|
||||
|
||||
formatter = CallerInfoFormatter(
|
||||
'[%(asctime)s] - [%(name)s] - [%(levelname)s] - [%(filename)s:%(lineno)s] - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setLevel(logging.INFO)
|
||||
console_handler.setFormatter(formatter)
|
||||
self.__logger.addHandler(console_handler)
|
||||
|
||||
all_log_file = os.path.join(self.__log_dir, "all.log")
|
||||
file_handler_all = TimedRotatingFileHandler(
|
||||
all_log_file,
|
||||
@@ -122,7 +119,6 @@ class LogManager:
|
||||
file_handler_all.setLevel(logging.DEBUG)
|
||||
file_handler_all.setFormatter(formatter)
|
||||
self.__logger.addHandler(file_handler_all)
|
||||
|
||||
error_log_file = os.path.join(self.__log_dir, "error.log")
|
||||
file_handler_error = TimedRotatingFileHandler(
|
||||
error_log_file,
|
||||
@@ -135,7 +131,6 @@ class LogManager:
|
||||
file_handler_error.setLevel(logging.ERROR)
|
||||
file_handler_error.setFormatter(formatter)
|
||||
self.__logger.addHandler(file_handler_error)
|
||||
|
||||
self.__initialized = True
|
||||
|
||||
def getLogger(
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Log managers module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- LogManager: Log manager for logging.
|
||||
"""
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
@@ -0,0 +1,359 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import (
|
||||
QApplication,
|
||||
QStyleFactory
|
||||
)
|
||||
|
||||
from interfaces.ConfigProvider import CfgKey
|
||||
from managers.config.ConfigManager import instance as configInstance
|
||||
from managers.log.LogManager import instance as logInstance
|
||||
from utils.ThemeUtils import (
|
||||
readThemeInfo,
|
||||
readThemeQss,
|
||||
validateTheme,
|
||||
wrapQssToAtheme
|
||||
)
|
||||
|
||||
|
||||
# we use Fusion as the default active style name
|
||||
# because it's cross-platform.
|
||||
_active_style_name = "Fusion"
|
||||
|
||||
|
||||
def setActiveStyle(
|
||||
style_name: str
|
||||
):
|
||||
|
||||
global _active_style_name
|
||||
_active_style_name = style_name
|
||||
|
||||
def getActiveStyle(
|
||||
) -> str:
|
||||
|
||||
return _active_style_name
|
||||
|
||||
|
||||
class ThemeManager:
|
||||
"""
|
||||
Theme manager class.
|
||||
|
||||
Manages the themes storage directory, providing import,
|
||||
list, remove, and apply operations for .altheme theme files.
|
||||
|
||||
Args:
|
||||
themes_dir (str): Path to the themes storage directory.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
themes_dir: str
|
||||
):
|
||||
|
||||
self.__themes_dir = os.path.abspath(themes_dir)
|
||||
self.__current_theme_name = ""
|
||||
self.__lock = threading.Lock()
|
||||
|
||||
# directory must exist
|
||||
os.makedirs(self.__themes_dir, exist_ok=True)
|
||||
|
||||
@staticmethod
|
||||
def _colorSchemeFor(
|
||||
theme: str
|
||||
) -> Qt.ColorScheme:
|
||||
"""
|
||||
Map a theme identifier to the corresponding Qt color scheme.
|
||||
"""
|
||||
|
||||
if theme == "dark":
|
||||
return Qt.ColorScheme.Dark
|
||||
elif theme == "light":
|
||||
return Qt.ColorScheme.Light
|
||||
else:
|
||||
return Qt.ColorScheme.Unknown
|
||||
|
||||
def _deleteThemeFile(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
"""
|
||||
Delete a theme file in the themes storage directory.
|
||||
|
||||
The caller must hold self.__lock before invoking this method.
|
||||
|
||||
**This method ONLY deletes the file**.
|
||||
"""
|
||||
|
||||
filepath = os.path.join(self.__themes_dir, name + ".altheme")
|
||||
if os.path.isfile(filepath):
|
||||
os.remove(filepath)
|
||||
|
||||
def _resolveDestPath(
|
||||
self,
|
||||
theme_name: str,
|
||||
author: str
|
||||
) -> str:
|
||||
"""
|
||||
Resolve the destination path for an imported theme.
|
||||
|
||||
If the default {name}.altheme path does not exist, use it directly.
|
||||
If it exists and has a different author, use {name}_{author}.altheme.
|
||||
If it exists and has the same author, raise ValueError.
|
||||
|
||||
Args:
|
||||
theme_name (str): Sanitised theme name.
|
||||
author (str): Theme author string.
|
||||
|
||||
Returns:
|
||||
str: The resolved destination file path.
|
||||
|
||||
Raises:
|
||||
ValueError: If a theme with the same name and author already exists.
|
||||
"""
|
||||
|
||||
default_path = os.path.join(self.__themes_dir, theme_name + ".altheme")
|
||||
if not os.path.exists(default_path):
|
||||
return default_path
|
||||
try:
|
||||
existing_info = validateTheme(default_path)
|
||||
existing_author = existing_info.get("author", "")
|
||||
except Exception:
|
||||
self._deleteThemeFile(theme_name) # caller holds the lock
|
||||
raise ValueError(
|
||||
f"主题 '{theme_name}' 已存在但无法通过验证, 已清理该主题文件"
|
||||
)
|
||||
if existing_author == author:
|
||||
raise ValueError(
|
||||
f"主题名称 '{theme_name}' (作者 '{author}') 已存在"
|
||||
)
|
||||
safe_author = os.path.basename(author) if author else "未知作者"
|
||||
alt_path = os.path.join(
|
||||
self.__themes_dir, f"{theme_name}_{safe_author}.altheme"
|
||||
)
|
||||
if os.path.exists(alt_path):
|
||||
raise ValueError(
|
||||
f"主题名称 '{theme_name}' (作者 '{author}') 已存在"
|
||||
)
|
||||
return alt_path
|
||||
|
||||
def importTheme(
|
||||
self,
|
||||
source_path: str
|
||||
) -> str:
|
||||
"""
|
||||
Import a theme file into the themes directory.
|
||||
|
||||
Supports .altheme (zip archive) and bare .qss files.
|
||||
Bare .qss files are automatically wrapped into .altheme format.
|
||||
For .altheme files, validates that theme.qss exists in the archive
|
||||
and sanitises the theme name to prevent path traversal.
|
||||
|
||||
Args:
|
||||
source_path (str): Path to the .altheme or .qss file.
|
||||
|
||||
Returns:
|
||||
str: The imported theme name.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If source_path does not exist.
|
||||
ValueError: If the file type is unsupported or the .altheme is invalid.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(source_path):
|
||||
raise FileNotFoundError(source_path)
|
||||
base_name, ext = os.path.splitext(os.path.basename(source_path))
|
||||
ext = ext.lower()
|
||||
with self.__lock:
|
||||
if ext == ".qss":
|
||||
dest_path = self._resolveDestPath(base_name, "未知作者")
|
||||
wrapQssToAtheme(source_path, dest_path, "both")
|
||||
return os.path.splitext(os.path.basename(dest_path))[0]
|
||||
elif ext == ".altheme":
|
||||
info = validateTheme(source_path)
|
||||
name = info.get("name", base_name)
|
||||
safe_name = os.path.basename(name)
|
||||
new_author = info.get("author", "")
|
||||
dest_path = self._resolveDestPath(safe_name, new_author)
|
||||
shutil.copy2(source_path, dest_path)
|
||||
return os.path.splitext(os.path.basename(dest_path))[0]
|
||||
else:
|
||||
raise ValueError(f"不支持的文件类型: {ext}")
|
||||
|
||||
def listThemes(
|
||||
self
|
||||
) -> list:
|
||||
"""
|
||||
List all available themes in the themes directory.
|
||||
|
||||
Scans the themes directory for .altheme files and reads
|
||||
their info.json metadata.
|
||||
|
||||
Returns:
|
||||
list[dict]: A list of theme info dictionaries.
|
||||
"""
|
||||
|
||||
themes = []
|
||||
seen_keys = set()
|
||||
if not os.path.isdir(self.__themes_dir):
|
||||
return themes
|
||||
for filename in sorted(os.listdir(self.__themes_dir)):
|
||||
if filename.endswith(".altheme"):
|
||||
filepath = os.path.join(self.__themes_dir, filename)
|
||||
try:
|
||||
info = validateTheme(filepath)
|
||||
name = info.get("name", "")
|
||||
author = info.get("author", "")
|
||||
key = (name, author)
|
||||
if key in seen_keys:
|
||||
logInstance().getLogger("ThemeManager").warning(
|
||||
f"主题名称 '{name}' (作者 '{author}') 重复 (文件 '{filename}') 已跳过"
|
||||
)
|
||||
continue
|
||||
seen_keys.add(key)
|
||||
info["file"] = os.path.splitext(filename)[0]
|
||||
themes.append(info)
|
||||
except Exception as e:
|
||||
logInstance().getLogger("ThemeManager").warning(
|
||||
f"无法读取主题文件 '{filename}',已跳过: {e}"
|
||||
)
|
||||
else:
|
||||
logInstance().getLogger("ThemeManager").warning(
|
||||
f"未知文件类型 '{filename}',已跳过"
|
||||
)
|
||||
return themes
|
||||
|
||||
def removeTheme(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
"""
|
||||
Remove a theme by name.
|
||||
|
||||
If the removed theme is currently active, clears the QSS
|
||||
stylesheet from the application and reverts to the saved
|
||||
colour scheme.
|
||||
|
||||
Args:
|
||||
name (str): The theme name to remove.
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
self._deleteThemeFile(name)
|
||||
if self.__current_theme_name == name:
|
||||
self.__current_theme_name = ""
|
||||
saved_theme = configInstance().get(
|
||||
CfgKey.GLOBAL.APPEARANCE.THEME, "system"
|
||||
)
|
||||
self.clearTheme(saved_theme)
|
||||
|
||||
def applyTheme(
|
||||
self,
|
||||
name: str
|
||||
):
|
||||
"""
|
||||
Apply a theme by name.
|
||||
|
||||
Extracts the QSS from the .altheme file, applies it to
|
||||
QApplication, and sets the Qt color scheme based on
|
||||
the theme's need_theme metadata.
|
||||
|
||||
Args:
|
||||
name (str): The theme name to apply.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the theme .altheme file does not exist.
|
||||
"""
|
||||
|
||||
filepath = os.path.join(self.__themes_dir, name + ".altheme")
|
||||
if not os.path.isfile(filepath):
|
||||
raise FileNotFoundError(filepath)
|
||||
with self.__lock:
|
||||
info = readThemeInfo(filepath)
|
||||
qss = readThemeQss(filepath)
|
||||
app = QApplication.instance()
|
||||
if app:
|
||||
app.setStyleSheet(qss)
|
||||
need_theme = info.get("need_theme", "both")
|
||||
app.styleHints().setColorScheme(
|
||||
ThemeManager._colorSchemeFor(need_theme)
|
||||
)
|
||||
app.setStyle(QStyleFactory.create(_active_style_name))
|
||||
self.__current_theme_name = name
|
||||
|
||||
def clearTheme(
|
||||
self,
|
||||
theme: str
|
||||
):
|
||||
"""
|
||||
Clear the current QSS stylesheet and apply the given color scheme.
|
||||
|
||||
Args:
|
||||
theme (str): The color scheme to apply after clearing
|
||||
("light", "dark", or "system").
|
||||
"""
|
||||
|
||||
app = QApplication.instance()
|
||||
if not app:
|
||||
return
|
||||
app.setStyleSheet("")
|
||||
app.styleHints().setColorScheme(
|
||||
ThemeManager._colorSchemeFor(theme)
|
||||
)
|
||||
app.setStyle(QStyleFactory.create(_active_style_name))
|
||||
|
||||
def themesDir(
|
||||
self
|
||||
) -> str:
|
||||
"""
|
||||
Get the themes directory path.
|
||||
|
||||
Returns:
|
||||
str: The absolute path to the themes storage directory.
|
||||
"""
|
||||
|
||||
return self.__themes_dir
|
||||
|
||||
|
||||
# ThemeManager singleton instance.
|
||||
_theme_manager_instance = None
|
||||
|
||||
# Singleton instance lock.
|
||||
_instance_lock = threading.Lock()
|
||||
|
||||
|
||||
def instance(
|
||||
themes_dir: str = ""
|
||||
) -> ThemeManager:
|
||||
"""
|
||||
Get the ThemeManager singleton instance.
|
||||
|
||||
On first call, initialises the ThemeManager with the themes
|
||||
directory derived from ConfigManager's config directory.
|
||||
|
||||
Args:
|
||||
themes_dir (str): Optional themes directory path.
|
||||
|
||||
Returns:
|
||||
ThemeManager: The singleton ThemeManager instance.
|
||||
"""
|
||||
|
||||
global _theme_manager_instance
|
||||
with _instance_lock:
|
||||
if _theme_manager_instance is None:
|
||||
if not themes_dir:
|
||||
cfg = configInstance()
|
||||
themes_dir = os.path.join(cfg.configDir(), "themes")
|
||||
_theme_manager_instance = ThemeManager(themes_dir)
|
||||
return _theme_manager_instance
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
This software is provided "as is", without any warranty of any kind.
|
||||
You may use, modify, and distribute this file under the terms of the MIT License.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
+25
-21
@@ -10,6 +10,7 @@ See the LICENSE file for details.
|
||||
import os
|
||||
import queue
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.remote.webdriver import WebDriver
|
||||
from selenium.common.exceptions import (
|
||||
TimeoutException,
|
||||
WebDriverException,
|
||||
@@ -37,11 +38,11 @@ class AutoLib(MsgBase):
|
||||
output_queue: queue.Queue,
|
||||
run_config: dict,
|
||||
) -> None:
|
||||
super().__init__(input_queue, output_queue)
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
self.__run_config: dict = run_config
|
||||
self.__user_config: dict | None = None
|
||||
self.__driver = None
|
||||
self.__driver: WebDriver | None = None
|
||||
self.__driver_type: str = ""
|
||||
self.__driver_path: str = ""
|
||||
self.__login_page: LoginPage = None
|
||||
@@ -58,7 +59,7 @@ class AutoLib(MsgBase):
|
||||
else:
|
||||
if not self.__initDriverUrl():
|
||||
self.close()
|
||||
raise Exception("浏览器驱动URL初始化失败 !")
|
||||
raise Exception("浏览器驱动 URL 初始化失败 !")
|
||||
self.__initPagesServices()
|
||||
self.__initPagesFlows()
|
||||
|
||||
@@ -67,9 +68,10 @@ class AutoLib(MsgBase):
|
||||
) -> bool:
|
||||
|
||||
self._showTrace("正在初始化浏览器驱动......", no_log=True)
|
||||
web_driver_config: dict = self.__run_config.get("web_driver", None)
|
||||
self.__driver_type = web_driver_config.get("driver_type", "none")
|
||||
match self.__driver_type.lower():
|
||||
driver_config: dict = self.__run_config.get("web_driver", None)
|
||||
self.__driver_type = driver_config.get("driver_type", "none")
|
||||
self.__driver_type = self.__driver_type.lower()
|
||||
match self.__driver_type:
|
||||
case "edge":
|
||||
driver_options = webdriver.EdgeOptions()
|
||||
case "chrome":
|
||||
@@ -82,10 +84,10 @@ class AutoLib(MsgBase):
|
||||
self.TraceLevel.WARNING,
|
||||
)
|
||||
return False
|
||||
if not web_driver_config:
|
||||
if not driver_config:
|
||||
self._showTrace("未配置浏览器驱动参数 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
if web_driver_config.get("headless", False):
|
||||
if driver_config.get("headless", False):
|
||||
driver_options.add_argument("--headless")
|
||||
driver_options.add_argument("--disable-gpu")
|
||||
driver_options.add_argument("--no-sandbox")
|
||||
@@ -110,11 +112,11 @@ class AutoLib(MsgBase):
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "\
|
||||
"Chrome/120.0.0.0 "\
|
||||
"Safari/537.36"
|
||||
if self.__driver_type.lower() == "edge":
|
||||
if self.__driver_type == "edge":
|
||||
user_agent += " Edg/120.0.0.0"
|
||||
|
||||
# set options for firefox
|
||||
elif self.__driver_type.lower() == "firefox":
|
||||
elif self.__driver_type == "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) "\
|
||||
@@ -122,14 +124,14 @@ class AutoLib(MsgBase):
|
||||
driver_options.add_argument(f"user-agent={user_agent}")
|
||||
|
||||
# init browser driver
|
||||
self.__driver_path = web_driver_config.get("driver_path", "")
|
||||
self.__driver_path = driver_config.get("driver_path", "")
|
||||
if not self.__driver_path:
|
||||
self._showTrace("未配置浏览器驱动路径 !", self.TraceLevel.WARNING)
|
||||
return False
|
||||
try:
|
||||
self.__driver_path = os.path.abspath(self.__driver_path)
|
||||
service = None
|
||||
match self.__driver_type.lower():
|
||||
match self.__driver_type:
|
||||
case "edge":
|
||||
service = EdgeService(executable_path=self.__driver_path)
|
||||
self.__driver = webdriver.Edge(service=service, options=driver_options)
|
||||
@@ -149,9 +151,6 @@ class AutoLib(MsgBase):
|
||||
except WebDriverException as e:
|
||||
self._showTrace(f"浏览器驱动初始化失败: {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
except Exception as e:
|
||||
self._showTrace(f"浏览器驱动初始化失败: {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
self._showTrace(f"浏览器驱动已初始化, 类型: {self.__driver_type}, 路径: {self.__driver_path}")
|
||||
return True
|
||||
|
||||
@@ -164,7 +163,7 @@ class AutoLib(MsgBase):
|
||||
self._showTrace("未配置图书馆参数 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
url: str = lib_config.get("host_url") + lib_config.get("login_url")
|
||||
self.__login_page = LoginPage(self.__driver, tracer=self._showTrace)
|
||||
self.__login_page = LoginPage(self._input_queue, self._output_queue, self.__driver)
|
||||
self.__driver.set_page_load_timeout(5)
|
||||
try:
|
||||
self.__driver.get(url)
|
||||
@@ -236,6 +235,7 @@ class AutoLib(MsgBase):
|
||||
|
||||
# result : -1 - terminate, 0 - success, 1 - failed, 2 - passed
|
||||
result: int = 2
|
||||
|
||||
# login
|
||||
auto_captcha: bool = login_config.get("auto_captcha", True)
|
||||
if not self.__login_page.login(
|
||||
@@ -252,10 +252,11 @@ class AutoLib(MsgBase):
|
||||
"auto_checkin": run_mode_raw & 0x2,
|
||||
"auto_renewal": run_mode_raw & 0x4,
|
||||
}
|
||||
|
||||
# reserve
|
||||
if run_mode["auto_reserve"]:
|
||||
if self.__record_checker.canReserve(self.__shell, reserve_info["date"]):
|
||||
if self.__reserve_checker.check(reserve_info):
|
||||
if self.__reserve_checker.check(reserve_info):
|
||||
if self.__record_checker.canReserve(self.__shell, reserve_info["date"]):
|
||||
ctx = ReserveContext(
|
||||
username=username,
|
||||
date=reserve_info["date"],
|
||||
@@ -276,10 +277,10 @@ class AutoLib(MsgBase):
|
||||
else:
|
||||
result = 1
|
||||
else:
|
||||
result = 1
|
||||
self._showTrace(f"用户 {username} 无法预约, 已跳过")
|
||||
result = 2
|
||||
else:
|
||||
self._showTrace(f"用户 {username} 无法预约, 已跳过")
|
||||
result = 2
|
||||
result = 1
|
||||
|
||||
# checkin
|
||||
last_result: int = result
|
||||
@@ -320,8 +321,11 @@ class AutoLib(MsgBase):
|
||||
|
||||
# logout
|
||||
if not self.__shell.logout():
|
||||
self._showTrace(f"用户 {username} 退出登录失败, 尝试直接重载页面")
|
||||
if not self.__initDriverUrl():
|
||||
self._showTrace(f"用户 {username} 重载页面失败, 无法继续操作, 该任务已终止 !")
|
||||
return -1
|
||||
self._showTrace(f"用户 {username} 已退出登录")
|
||||
return result
|
||||
|
||||
def run(
|
||||
|
||||
+28
-42
@@ -7,7 +7,8 @@ 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 typing import Callable, Optional
|
||||
import queue
|
||||
from typing import Callable
|
||||
|
||||
from selenium.common.exceptions import (
|
||||
ElementNotInteractableException,
|
||||
@@ -19,8 +20,10 @@ from selenium.webdriver.remote.webdriver import WebDriver
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
|
||||
class LoginPage:
|
||||
|
||||
class LoginPage(MsgBase):
|
||||
|
||||
USERNAME_INPUT = (By.NAME, "username")
|
||||
PASSWORD_INPUT = (By.NAME, "password")
|
||||
@@ -36,22 +39,13 @@ class LoginPage:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
input_queue: queue.Queue,
|
||||
output_queue: queue.Queue,
|
||||
driver: WebDriver,
|
||||
tracer: Optional[Callable[..., None]] = None,
|
||||
) -> None:
|
||||
|
||||
super().__init__(input_queue, output_queue)
|
||||
self._driver: WebDriver = driver
|
||||
self._tracer: Optional[Callable[..., None]] = tracer
|
||||
|
||||
def _trace(
|
||||
self,
|
||||
msg: str,
|
||||
level: int = 20,
|
||||
no_log: bool = False,
|
||||
) -> None:
|
||||
|
||||
if self._tracer:
|
||||
self._tracer(msg, level, no_log)
|
||||
|
||||
def navigate(
|
||||
self,
|
||||
@@ -85,9 +79,7 @@ class LoginPage:
|
||||
EC.presence_of_element_located(self.CAPTCHA_IMG)
|
||||
)
|
||||
return True
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
return False
|
||||
except Exception:
|
||||
except TimeoutException:
|
||||
return False
|
||||
|
||||
def fillCredentials(
|
||||
@@ -104,17 +96,21 @@ class LoginPage:
|
||||
el.clear()
|
||||
el.send_keys(password)
|
||||
return True
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
return False
|
||||
except Exception:
|
||||
except (NoSuchElementException, ElementNotInteractableException):
|
||||
return False
|
||||
|
||||
def getCaptchaImageSrc(
|
||||
self,
|
||||
) -> str:
|
||||
) -> str | None:
|
||||
|
||||
captcha_el = self._driver.find_element(*self.CAPTCHA_IMG)
|
||||
return captcha_el.get_attribute("src")
|
||||
# return 'None' if captcha image element is not found.
|
||||
# But the 'get_attribute("src")' also return 'None' if there's no attribute with
|
||||
# that name, which is not what we want.
|
||||
try:
|
||||
captcha_el = self._driver.find_element(*self.CAPTCHA_IMG)
|
||||
return captcha_el.get_attribute("src")
|
||||
except NoSuchElementException:
|
||||
return None
|
||||
|
||||
def refreshCaptcha(
|
||||
self,
|
||||
@@ -123,10 +119,7 @@ class LoginPage:
|
||||
try:
|
||||
self._driver.find_element(*self.CAPTCHA_IMG).click()
|
||||
return True
|
||||
except (NoSuchElementException, TimeoutException,
|
||||
ElementNotInteractableException):
|
||||
return False
|
||||
except Exception:
|
||||
except (NoSuchElementException, ElementNotInteractableException):
|
||||
return False
|
||||
|
||||
def fillCaptcha(
|
||||
@@ -139,9 +132,7 @@ class LoginPage:
|
||||
el.clear()
|
||||
el.send_keys(captcha_text)
|
||||
return True
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
return False
|
||||
except Exception:
|
||||
except (NoSuchElementException, ElementNotInteractableException):
|
||||
return False
|
||||
|
||||
def clickLogin(
|
||||
@@ -151,10 +142,7 @@ class LoginPage:
|
||||
try:
|
||||
self._driver.find_element(*self.LOGIN_BUTTON).click()
|
||||
return True
|
||||
except (NoSuchElementException, TimeoutException,
|
||||
ElementNotInteractableException):
|
||||
return False
|
||||
except Exception:
|
||||
except (NoSuchElementException, ElementNotInteractableException):
|
||||
return False
|
||||
|
||||
def waitLoginSuccess(
|
||||
@@ -172,9 +160,7 @@ class LoginPage:
|
||||
EC.presence_of_element_located(self.SUCCESS_INDICATOR_CONTENT)
|
||||
)
|
||||
return True
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
return False
|
||||
except Exception:
|
||||
except TimeoutException:
|
||||
return False
|
||||
|
||||
def stopPageLoad(
|
||||
@@ -193,7 +179,7 @@ class LoginPage:
|
||||
) -> bool:
|
||||
|
||||
for attempt in range(max_attempts):
|
||||
self._trace(
|
||||
self._showTrace(
|
||||
f"用户 {username} 第 {attempt + 1} 次尝试登录......",
|
||||
no_log=True,
|
||||
)
|
||||
@@ -204,16 +190,16 @@ class LoginPage:
|
||||
continue
|
||||
if not self.fillCaptcha(captcha_text):
|
||||
continue
|
||||
self._trace("尝试登录...", no_log=True)
|
||||
self._showTrace("尝试登录...", no_log=True)
|
||||
if not self.clickLogin():
|
||||
continue
|
||||
if self.waitLoginSuccess():
|
||||
self._trace(f"用户 {username} 第 {attempt + 1} 次登录成功 !")
|
||||
self._showTrace(f"用户 {username} 第 {attempt + 1} 次登录成功 !")
|
||||
return True
|
||||
else:
|
||||
self._trace(
|
||||
self._showTrace(
|
||||
"登录页面加载失败 ! : "
|
||||
"用户账号或者密码错误/验证码错误, 具体以页面提示为准",
|
||||
level=40,
|
||||
level=self.TraceLevel.ERROR,
|
||||
)
|
||||
return False
|
||||
+40
-29
@@ -14,8 +14,10 @@ from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.remote.webdriver import WebDriver
|
||||
from selenium.common.exceptions import (
|
||||
ElementNotInteractableException,
|
||||
NoSuchElementException,
|
||||
TimeoutException,
|
||||
WebDriverException,
|
||||
)
|
||||
|
||||
from pages.ReserveView import ReserveView
|
||||
@@ -38,6 +40,15 @@ class MainShell:
|
||||
|
||||
self._driver = driver
|
||||
|
||||
def _clickTab(
|
||||
self,
|
||||
locator: tuple,
|
||||
) -> None:
|
||||
|
||||
WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(locator)
|
||||
).click()
|
||||
|
||||
def gotoReserveView(
|
||||
self,
|
||||
) -> ReserveView:
|
||||
@@ -65,9 +76,7 @@ class MainShell:
|
||||
try:
|
||||
self._driver.find_element(*self.TAB_LOGOUT).click()
|
||||
return True
|
||||
except NoSuchElementException:
|
||||
return False
|
||||
except Exception:
|
||||
except (NoSuchElementException, ElementNotInteractableException):
|
||||
return False
|
||||
|
||||
def waitCheckinButton(
|
||||
@@ -81,8 +90,6 @@ class MainShell:
|
||||
return True
|
||||
except TimeoutException:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def waitExtendButton(
|
||||
self,
|
||||
@@ -95,40 +102,50 @@ class MainShell:
|
||||
return True
|
||||
except TimeoutException:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def isCheckinButtonDisabled(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
btn = self._driver.find_element(*self.BTN_CHECKIN)
|
||||
return "disabled" in btn.get_attribute("class")
|
||||
try:
|
||||
btn = self._driver.find_element(*self.BTN_CHECKIN)
|
||||
return "disabled" in btn.get_attribute("class")
|
||||
except NoSuchElementException:
|
||||
return True
|
||||
|
||||
def isExtendButtonDisabled(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
btn = self._driver.find_element(*self.BTN_EXTEND)
|
||||
return "disabled" in btn.get_attribute("class")
|
||||
try:
|
||||
btn = self._driver.find_element(*self.BTN_EXTEND)
|
||||
return "disabled" in btn.get_attribute("class")
|
||||
except NoSuchElementException:
|
||||
return True
|
||||
|
||||
def clickCheckinButton(
|
||||
self,
|
||||
) -> None:
|
||||
|
||||
btn = WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(self.BTN_CHECKIN)
|
||||
)
|
||||
btn.click()
|
||||
try:
|
||||
btn = WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(self.BTN_CHECKIN)
|
||||
)
|
||||
btn.click()
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
return
|
||||
|
||||
def clickExtendButton(
|
||||
self,
|
||||
) -> None:
|
||||
|
||||
btn = WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(self.BTN_EXTEND)
|
||||
)
|
||||
btn.click()
|
||||
try:
|
||||
btn = WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(self.BTN_EXTEND)
|
||||
)
|
||||
btn.click()
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
return
|
||||
|
||||
def enableCheckinButtonByJS(
|
||||
self,
|
||||
@@ -154,13 +171,7 @@ class MainShell:
|
||||
self,
|
||||
) -> None:
|
||||
|
||||
self._driver.refresh()
|
||||
|
||||
def _clickTab(
|
||||
self,
|
||||
locator: tuple,
|
||||
) -> None:
|
||||
|
||||
WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(locator)
|
||||
).click()
|
||||
try:
|
||||
self._driver.refresh()
|
||||
except (TimeoutException, WebDriverException):
|
||||
return
|
||||
@@ -44,8 +44,6 @@ class RecordsView:
|
||||
return self._driver.find_elements(*self.RECORDS_LIST)
|
||||
except TimeoutException:
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def getRecordTimeElement(
|
||||
self,
|
||||
@@ -71,8 +69,6 @@ class RecordsView:
|
||||
)
|
||||
except TimeoutException:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
try:
|
||||
more_btn = self._driver.find_element(*self.MORE_BTN)
|
||||
if more_btn.is_displayed() and more_btn.is_enabled():
|
||||
@@ -82,8 +78,6 @@ class RecordsView:
|
||||
return False
|
||||
except (NoSuchElementException, StaleElementReferenceException):
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def getRecordText(
|
||||
self,
|
||||
|
||||
+48
-55
@@ -53,6 +53,50 @@ class ReserveView:
|
||||
|
||||
self._driver = driver
|
||||
|
||||
def _clickOptionByJS(
|
||||
self,
|
||||
trigger_id: str,
|
||||
option_css: str,
|
||||
) -> bool:
|
||||
|
||||
script = f"""
|
||||
try {{
|
||||
var trigger = document.getElementById('{trigger_id}');
|
||||
if (trigger) {{
|
||||
trigger.click();
|
||||
var option = document.querySelector("{option_css}");
|
||||
if (option) {{
|
||||
option.click();
|
||||
return true;
|
||||
}}
|
||||
return false;
|
||||
}}
|
||||
return false;
|
||||
}} catch (e) {{
|
||||
return false;
|
||||
}}
|
||||
"""
|
||||
result = self._driver.execute_script(script)
|
||||
time.sleep(0.1)
|
||||
return result
|
||||
|
||||
def _clickOption(
|
||||
self,
|
||||
trigger: tuple,
|
||||
option: tuple,
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(trigger)
|
||||
).click()
|
||||
WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(option)
|
||||
).click()
|
||||
return True
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
return False
|
||||
|
||||
def selectDate(
|
||||
self,
|
||||
date_str: str,
|
||||
@@ -109,21 +153,15 @@ class ReserveView:
|
||||
).click()
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable((By.ID, self.ROOM_BTN_FMT.format(room=room)))
|
||||
).click()
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
return SeatMapDialog(self._driver)
|
||||
except (TimeoutException):
|
||||
return None
|
||||
except Exception:
|
||||
except TimeoutException:
|
||||
return None
|
||||
|
||||
def submitReserve(
|
||||
@@ -137,57 +175,12 @@ class ReserveView:
|
||||
return True
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def refresh(
|
||||
self,
|
||||
) -> None:
|
||||
|
||||
self._driver.refresh()
|
||||
|
||||
def _clickOptionByJS(
|
||||
self,
|
||||
trigger_id: str,
|
||||
option_css: str,
|
||||
) -> bool:
|
||||
|
||||
script = f"""
|
||||
try {{
|
||||
var trigger = document.getElementById('{trigger_id}');
|
||||
if (trigger) {{
|
||||
trigger.click();
|
||||
var option = document.querySelector("{option_css}");
|
||||
if (option) {{
|
||||
option.click();
|
||||
return true;
|
||||
}}
|
||||
return false;
|
||||
}}
|
||||
return false;
|
||||
}} catch (e) {{
|
||||
return false;
|
||||
}}
|
||||
"""
|
||||
result = self._driver.execute_script(script)
|
||||
time.sleep(0.1)
|
||||
return result
|
||||
|
||||
def _clickOption(
|
||||
self,
|
||||
trigger: tuple,
|
||||
option: tuple,
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(trigger)
|
||||
).click()
|
||||
WebDriverWait(self._driver, 2).until(
|
||||
EC.element_to_be_clickable(option)
|
||||
).click()
|
||||
return True
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
self._driver.refresh()
|
||||
except TimeoutException:
|
||||
return
|
||||
+10
-23
@@ -7,26 +7,13 @@ 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 pages.AutoLib import AutoLib
|
||||
from pages.LoginPage import LoginPage
|
||||
from pages.MainShell import MainShell
|
||||
from pages.ReserveView import ReserveView
|
||||
from pages.RecordsView import RecordsView
|
||||
from pages.components.SeatMapDialog import SeatMapDialog
|
||||
from pages.components.TimeSelectDialog import TimeSelectDialog
|
||||
from pages.components.ReserveResultDialog import ReserveResultDialog
|
||||
from pages.components.CheckinResultDialog import CheckinResultDialog
|
||||
from pages.components.RenewDialog import RenewDialog
|
||||
|
||||
__all__ = [
|
||||
"AutoLib",
|
||||
"LoginPage",
|
||||
"MainShell",
|
||||
"ReserveView",
|
||||
"RecordsView",
|
||||
"SeatMapDialog",
|
||||
"TimeSelectDialog",
|
||||
"ReserveResultDialog",
|
||||
"CheckinResultDialog",
|
||||
"RenewDialog",
|
||||
]
|
||||
from .AutoLib import AutoLib
|
||||
from .LoginPage import LoginPage
|
||||
from .MainShell import MainShell
|
||||
from .ReserveView import ReserveView
|
||||
from .RecordsView import RecordsView
|
||||
from .components.SeatMapDialog import SeatMapDialog
|
||||
from .components.TimeSelectDialog import TimeSelectDialog
|
||||
from .components.ReserveResultDialog import ReserveResultDialog
|
||||
from .components.CheckinResultDialog import CheckinResultDialog
|
||||
from .components.RenewDialog import RenewDialog
|
||||
@@ -45,9 +45,8 @@ class CheckinResultDialog(Dialog):
|
||||
self._waitPresence(self.RESULT_MSG)
|
||||
el = self._find(*self.RESULT_MSG)
|
||||
return el.text
|
||||
except (TimeoutException, NoSuchElementException, StaleElementReferenceException):
|
||||
return ""
|
||||
except Exception:
|
||||
except (TimeoutException, NoSuchElementException,
|
||||
StaleElementReferenceException):
|
||||
return ""
|
||||
|
||||
def getDetails(
|
||||
@@ -59,8 +58,6 @@ class CheckinResultDialog(Dialog):
|
||||
return [el.text for el in elements if el.text.strip()]
|
||||
except (NoSuchElementException, StaleElementReferenceException):
|
||||
return []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def clickOk(
|
||||
self,
|
||||
@@ -69,7 +66,5 @@ class CheckinResultDialog(Dialog):
|
||||
try:
|
||||
self._waitClickable(self.OK_BTN).click()
|
||||
return True
|
||||
except (NoSuchElementException, TimeoutException, ElementNotInteractableException):
|
||||
return False
|
||||
except Exception:
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
return False
|
||||
@@ -10,6 +10,7 @@ See the LICENSE file for details.
|
||||
from selenium.common.exceptions import (
|
||||
ElementNotInteractableException,
|
||||
NoSuchElementException,
|
||||
StaleElementReferenceException,
|
||||
TimeoutException,
|
||||
)
|
||||
from selenium.webdriver.common.by import By
|
||||
@@ -50,9 +51,7 @@ class RenewDialog(Dialog):
|
||||
self._waitVisible(self.ROOT)
|
||||
self._waitPresence(self.MESSAGE_HEAD)
|
||||
self._waitPresence(self.RESULT_MSG)
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
return False
|
||||
except Exception:
|
||||
except TimeoutException:
|
||||
return False
|
||||
head_msg = self._find(*self.MESSAGE_HEAD).text.strip()
|
||||
if "警告" in head_msg:
|
||||
@@ -60,9 +59,7 @@ class RenewDialog(Dialog):
|
||||
try:
|
||||
self._waitAllPresence(self.TIME_OPTS)
|
||||
self._waitPresence(self.OK_BTN)
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
return False
|
||||
except Exception:
|
||||
except TimeoutException:
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -70,13 +67,19 @@ class RenewDialog(Dialog):
|
||||
self,
|
||||
) -> str:
|
||||
|
||||
return self._find(*self.MESSAGE_HEAD).text.strip()
|
||||
try:
|
||||
return self._find(*self.MESSAGE_HEAD).text.strip()
|
||||
except (NoSuchElementException, StaleElementReferenceException):
|
||||
return ""
|
||||
|
||||
def getResultMessage(
|
||||
self,
|
||||
) -> str:
|
||||
|
||||
return self._find(*self.RESULT_MSG).text.strip()
|
||||
try:
|
||||
return self._find(*self.RESULT_MSG).text.strip()
|
||||
except (NoSuchElementException, StaleElementReferenceException):
|
||||
return ""
|
||||
|
||||
def getTimeOptions(
|
||||
self,
|
||||
@@ -101,7 +104,10 @@ class RenewDialog(Dialog):
|
||||
prefer_earlier,
|
||||
)
|
||||
if result.selected_index >= 0:
|
||||
all_time_opts[result.selected_index].click()
|
||||
try:
|
||||
all_time_opts[result.selected_index].click()
|
||||
except (ElementNotInteractableException, StaleElementReferenceException):
|
||||
return TimeSelectionResult(free_times=result.free_times)
|
||||
return result
|
||||
|
||||
def getOkButton(
|
||||
@@ -117,8 +123,5 @@ class RenewDialog(Dialog):
|
||||
try:
|
||||
self._find(*self.OK_BTN).click()
|
||||
return True
|
||||
except (NoSuchElementException, TimeoutException,
|
||||
ElementNotInteractableException):
|
||||
return False
|
||||
except Exception:
|
||||
except (NoSuchElementException, ElementNotInteractableException):
|
||||
return False
|
||||
@@ -45,8 +45,6 @@ class ReserveResultDialog(Dialog):
|
||||
return self._find(*self._titleLocator()).text
|
||||
except (NoSuchElementException, StaleElementReferenceException):
|
||||
return ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
def isSuccess(
|
||||
self,
|
||||
@@ -77,5 +75,3 @@ class ReserveResultDialog(Dialog):
|
||||
return [el.text for el in elements if el.text.strip()]
|
||||
except (NoSuchElementException, StaleElementReferenceException):
|
||||
return []
|
||||
except Exception:
|
||||
return []
|
||||
@@ -43,9 +43,7 @@ class SeatMapDialog(Dialog):
|
||||
|
||||
try:
|
||||
self._waitAllPresence(self.SEAT_ITEMS)
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
return None
|
||||
except Exception:
|
||||
except TimeoutException:
|
||||
return None
|
||||
try:
|
||||
seat_el = self._find(By.ID, f"seat_{int(seat_id):03d}")
|
||||
@@ -58,8 +56,6 @@ class SeatMapDialog(Dialog):
|
||||
except (NoSuchElementException, ValueError, TimeoutException,
|
||||
ElementNotInteractableException, StaleElementReferenceException):
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
all_seats = self._findAll(*self.SEAT_ITEMS)
|
||||
seat_id_upper = seat_id.lstrip('0').upper()
|
||||
@@ -76,5 +72,3 @@ class SeatMapDialog(Dialog):
|
||||
except (NoSuchElementException, TimeoutException,
|
||||
ElementNotInteractableException, StaleElementReferenceException):
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
@@ -13,7 +13,8 @@ import logging
|
||||
from typing import TYPE_CHECKING, Callable, Optional
|
||||
|
||||
from selenium.common.exceptions import (
|
||||
NoSuchElementException,
|
||||
ElementNotInteractableException,
|
||||
StaleElementReferenceException,
|
||||
TimeoutException,
|
||||
)
|
||||
from selenium.webdriver.common.by import By
|
||||
@@ -106,9 +107,7 @@ class TimeSelectDialog(Dialog):
|
||||
self._waitAllPresence(
|
||||
(By.CSS_SELECTOR, f"#{time_id} ul li a")
|
||||
)
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
return []
|
||||
except Exception:
|
||||
except TimeoutException:
|
||||
return []
|
||||
return self._findAll(
|
||||
By.CSS_SELECTOR,
|
||||
@@ -133,7 +132,10 @@ class TimeSelectDialog(Dialog):
|
||||
prefer_earlier,
|
||||
)
|
||||
if result.selected_index >= 0:
|
||||
all_time_opts[result.selected_index].click()
|
||||
try:
|
||||
all_time_opts[result.selected_index].click()
|
||||
except (ElementNotInteractableException, StaleElementReferenceException):
|
||||
return TimeSelectionResult(free_times=result.free_times)
|
||||
return result
|
||||
|
||||
def selectTimeRange(
|
||||
|
||||
@@ -7,16 +7,8 @@ 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 pages.components.SeatMapDialog import SeatMapDialog
|
||||
from pages.components.TimeSelectDialog import TimeSelectDialog
|
||||
from pages.components.ReserveResultDialog import ReserveResultDialog
|
||||
from pages.components.CheckinResultDialog import CheckinResultDialog
|
||||
from pages.components.RenewDialog import RenewDialog
|
||||
|
||||
__all__ = [
|
||||
"SeatMapDialog",
|
||||
"TimeSelectDialog",
|
||||
"ReserveResultDialog",
|
||||
"CheckinResultDialog",
|
||||
"RenewDialog",
|
||||
]
|
||||
from .SeatMapDialog import SeatMapDialog
|
||||
from .TimeSelectDialog import TimeSelectDialog
|
||||
from .ReserveResultDialog import ReserveResultDialog
|
||||
from .CheckinResultDialog import CheckinResultDialog
|
||||
from .RenewDialog import RenewDialog
|
||||
@@ -10,6 +10,7 @@ See the LICENSE file for details.
|
||||
import queue
|
||||
|
||||
from selenium.common.exceptions import (
|
||||
ElementNotInteractableException,
|
||||
NoSuchElementException,
|
||||
TimeoutException,
|
||||
)
|
||||
@@ -34,7 +35,7 @@ class CheckinFlow(MsgBase):
|
||||
self._driver: WebDriver = driver
|
||||
self._shell: MainShell = shell
|
||||
|
||||
def execute(
|
||||
def _ensureCheckinButton(
|
||||
self,
|
||||
username: str,
|
||||
) -> bool:
|
||||
@@ -48,7 +49,13 @@ class CheckinFlow(MsgBase):
|
||||
self._showTrace(f"签到按钮启用失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
self._showTrace("签到按钮已启用")
|
||||
self._shell.clickCheckinButton()
|
||||
return True
|
||||
|
||||
def _processCheckinDialog(
|
||||
self,
|
||||
username: str,
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
with CheckinResultDialog(self._driver) as dialog:
|
||||
result_msg = dialog.getResultMessage()
|
||||
@@ -83,9 +90,16 @@ class CheckinFlow(MsgBase):
|
||||
dialog.clickOk()
|
||||
self._showTrace(f"用户 {username} 签到失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
except (NoSuchElementException, TimeoutException):
|
||||
except (TimeoutException, NoSuchElementException, ElementNotInteractableException):
|
||||
self._showTrace("签到时发生未知错误 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
except Exception:
|
||||
self._showTrace("签到时发生未知错误 !", self.TraceLevel.ERROR)
|
||||
|
||||
def execute(
|
||||
self,
|
||||
username: str,
|
||||
) -> bool:
|
||||
|
||||
if not self._ensureCheckinButton(username):
|
||||
return False
|
||||
self._shell.clickCheckinButton()
|
||||
return self._processCheckinDialog(username)
|
||||
@@ -39,19 +39,45 @@ class RenewFlow(MsgBase):
|
||||
self._driver: WebDriver = driver
|
||||
self._shell: MainShell = shell
|
||||
|
||||
def execute(
|
||||
def _validateRenewTime(
|
||||
self,
|
||||
username: str,
|
||||
record: dict,
|
||||
renew_info: dict,
|
||||
end_time: str,
|
||||
target_renew_mins: int,
|
||||
) -> bool:
|
||||
|
||||
max_diff = renew_info.get("max_diff", 30)
|
||||
prefer_earlier = renew_info.get("prefer_early", True)
|
||||
if target_renew_mins > self.LIBRARY_CLOSE_MINS:
|
||||
actual_renew_duration = self.LIBRARY_CLOSE_MINS - timeStrToMins(end_time)
|
||||
if actual_renew_duration <= 0:
|
||||
self._showTrace(
|
||||
f"当前结束时间 {end_time} 已接近闭馆时间,无法续约 !", self.TraceLevel.ERROR
|
||||
)
|
||||
return False
|
||||
self._showTrace(
|
||||
f"续约时间已调整至闭馆时间 "
|
||||
f"{minsToTimeStr(self.LIBRARY_CLOSE_MINS)},"
|
||||
f"实际续约时长为 "
|
||||
f"{actual_renew_duration // 60} 小时 "
|
||||
f"{actual_renew_duration % 60} 分钟"
|
||||
)
|
||||
return True
|
||||
|
||||
def _computeRenewTarget(
|
||||
self,
|
||||
record: dict,
|
||||
renew_info: dict,
|
||||
):
|
||||
|
||||
end_time = record["time"]["end"]
|
||||
target_renew_mins = timeStrToMins(end_time) + renew_info.get("expect_duration", 2) * 60
|
||||
if not self._validateRenewTime(end_time, target_renew_mins):
|
||||
return False
|
||||
return None
|
||||
return target_renew_mins
|
||||
|
||||
def _ensureExtendButton(
|
||||
self,
|
||||
username: str,
|
||||
) -> bool:
|
||||
|
||||
if not self._shell.waitExtendButton():
|
||||
self._showTrace(f"用户 {username} 续约界面加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
@@ -61,7 +87,17 @@ class RenewFlow(MsgBase):
|
||||
f"请连接图书馆网络后重试"
|
||||
)
|
||||
return False
|
||||
self._shell.clickExtendButton()
|
||||
return True
|
||||
|
||||
def _processRenewDialog(
|
||||
self,
|
||||
username: str,
|
||||
record: dict,
|
||||
target_renew_mins: int,
|
||||
max_diff: int,
|
||||
prefer_earlier: bool,
|
||||
) -> bool:
|
||||
|
||||
try:
|
||||
with RenewDialog(self._driver) as dialog:
|
||||
if not dialog.waitUntilReady():
|
||||
@@ -106,37 +142,26 @@ class RenewFlow(MsgBase):
|
||||
self._showTrace(f"当前可供续约的时间有: {result.free_times}")
|
||||
self._shell.refresh()
|
||||
return False
|
||||
except (NoSuchElementException, TimeoutException) as e:
|
||||
self._showTrace(f"用户 {username} 续约失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
self._shell.refresh()
|
||||
return False
|
||||
except (ElementNotInteractableException) as e:
|
||||
self._showTrace(f"用户 {username} 续约失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
self._shell.refresh()
|
||||
return False
|
||||
except Exception as e:
|
||||
except (NoSuchElementException, TimeoutException, ElementNotInteractableException) as e:
|
||||
self._showTrace(f"用户 {username} 续约失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
self._shell.refresh()
|
||||
return False
|
||||
|
||||
def _validateRenewTime(
|
||||
def execute(
|
||||
self,
|
||||
end_time: str,
|
||||
target_renew_mins: int,
|
||||
username: str,
|
||||
record: dict,
|
||||
renew_info: dict,
|
||||
) -> bool:
|
||||
|
||||
if target_renew_mins > self.LIBRARY_CLOSE_MINS:
|
||||
actual_renew_duration = self.LIBRARY_CLOSE_MINS - timeStrToMins(end_time)
|
||||
if actual_renew_duration <= 0:
|
||||
self._showTrace(
|
||||
f"当前结束时间 {end_time} 已接近闭馆时间,无法续约 !", self.TraceLevel.ERROR
|
||||
)
|
||||
return False
|
||||
self._showTrace(
|
||||
f"续约时间已调整至闭馆时间 "
|
||||
f"{minsToTimeStr(self.LIBRARY_CLOSE_MINS)},"
|
||||
f"实际续约时长为 "
|
||||
f"{actual_renew_duration // 60} 小时 "
|
||||
f"{actual_renew_duration % 60} 分钟"
|
||||
)
|
||||
return True
|
||||
max_diff = renew_info.get("max_diff", 30)
|
||||
prefer_earlier = renew_info.get("prefer_early", True)
|
||||
target_renew_mins = self._computeRenewTarget(record, renew_info)
|
||||
if target_renew_mins is None:
|
||||
return False
|
||||
if not self._ensureExtendButton(username):
|
||||
return False
|
||||
self._shell.clickExtendButton()
|
||||
return self._processRenewDialog(
|
||||
username, record, target_renew_mins, max_diff, prefer_earlier,
|
||||
)
|
||||
+104
-41
@@ -12,7 +12,6 @@ from dataclasses import dataclass
|
||||
|
||||
from selenium.common.exceptions import (
|
||||
ElementNotInteractableException,
|
||||
NoSuchElementException,
|
||||
TimeoutException,
|
||||
)
|
||||
from selenium.webdriver.remote.webdriver import WebDriver
|
||||
@@ -23,6 +22,7 @@ from pages.strategies.TimeSelectMaker import TimeSelectMaker
|
||||
from pages.ReserveView import ReserveView
|
||||
from pages.components.ReserveResultDialog import ReserveResultDialog
|
||||
from pages.components.TimeSelectDialog import TimeSelectDialog
|
||||
from pages.components.SeatMapDialog import SeatMapDialog
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -59,43 +59,105 @@ class ReserveFlow(MsgBase):
|
||||
self._driver: WebDriver = driver
|
||||
self._shell: MainShell = shell
|
||||
|
||||
def execute(
|
||||
def _loadReserveView(
|
||||
self,
|
||||
) -> ReserveView | None:
|
||||
|
||||
try:
|
||||
return self._shell.gotoReserveView()
|
||||
except (TimeoutException, ElementNotInteractableException) as e:
|
||||
self._showTrace(f"加载预约选座页面失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return None
|
||||
|
||||
def _selectDate(
|
||||
self,
|
||||
view: ReserveView,
|
||||
ctx: ReserveContext,
|
||||
) -> bool:
|
||||
|
||||
submit_reserve = False
|
||||
reserve_success = False
|
||||
have_hover_on_page = False
|
||||
|
||||
try:
|
||||
view = self._shell.gotoReserveView()
|
||||
except (NoSuchElementException, TimeoutException) as e:
|
||||
self._showTrace(f"加载预约选座页面失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
except Exception as e:
|
||||
self._showTrace(f"加载预约选座页面失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return False
|
||||
if not view.selectDate(ctx.date):
|
||||
self._showTrace(f"选择日期失败 ! : {ctx.date} 不可用", self.TraceLevel.ERROR)
|
||||
return False
|
||||
self._showTrace(f"日期 {ctx.date} 选择成功 !")
|
||||
return True
|
||||
|
||||
def _selectPlace(
|
||||
self,
|
||||
view: ReserveView,
|
||||
) -> bool:
|
||||
|
||||
if not view.selectPlace("1"):
|
||||
self._showTrace("选择预约场所失败 ! : 图书馆 不可用", self.TraceLevel.ERROR)
|
||||
return False
|
||||
self._showTrace("预约场所 图书馆 选择成功 !")
|
||||
return True
|
||||
|
||||
def _selectFloor(
|
||||
self,
|
||||
view: ReserveView,
|
||||
ctx: ReserveContext,
|
||||
) -> bool:
|
||||
|
||||
if not view.selectFloor(ctx.floor):
|
||||
display_floor = ReserveView.FLOOR_MAP.get(ctx.floor, ctx.floor)
|
||||
self._showTrace(f"选择楼层失败 ! : {display_floor} 不可用", self.TraceLevel.ERROR)
|
||||
return False
|
||||
self._showTrace(f"楼层 {ReserveView.FLOOR_MAP.get(ctx.floor)} 选择成功 !")
|
||||
return True
|
||||
|
||||
def _selectRoom(
|
||||
self,
|
||||
view: ReserveView,
|
||||
ctx: ReserveContext,
|
||||
):
|
||||
|
||||
seat_map = view.selectRoom(ctx.room)
|
||||
if seat_map is None:
|
||||
display_room = ReserveView.ROOM_MAP.get(ctx.room, ctx.room)
|
||||
self._showTrace(f"选择房间失败 ! : {display_room} 不可用", self.TraceLevel.ERROR)
|
||||
return False
|
||||
return None
|
||||
self._showTrace(f"房间 {ReserveView.ROOM_MAP.get(ctx.room)} 选择成功 !")
|
||||
have_hover_on_page = True
|
||||
return seat_map
|
||||
|
||||
def _processReserveResult(
|
||||
self,
|
||||
) -> bool:
|
||||
|
||||
with ReserveResultDialog(self._driver) as result:
|
||||
if result.isFailure():
|
||||
self._showTrace("预约失败", self.TraceLevel.ERROR)
|
||||
elif result.isSuccess():
|
||||
details = result.getDetailTexts()
|
||||
if len(details) >= 6:
|
||||
self._showTrace(
|
||||
f"\n"
|
||||
f" 预约成功 !\n"
|
||||
f" {details[1]}\n"
|
||||
f" {details[2]}\n"
|
||||
f" {details[3]}\n"
|
||||
f" 签到时间 :{details[5]}"
|
||||
)
|
||||
else:
|
||||
self._showTrace(
|
||||
"\n"
|
||||
" 预约成功 !\n"
|
||||
" 未找获取到详细信息"
|
||||
)
|
||||
return True
|
||||
else:
|
||||
self._showTrace("预约结果加载失败 !", self.TraceLevel.ERROR)
|
||||
return False
|
||||
|
||||
def _selectSeatAndSubmit(
|
||||
self,
|
||||
view: ReserveView,
|
||||
seat_map: SeatMapDialog,
|
||||
ctx: ReserveContext,
|
||||
) -> tuple[bool, bool]:
|
||||
|
||||
submit_reserve = False
|
||||
reserve_success = False
|
||||
|
||||
seat_status = seat_map.selectSeat(ctx.seat_id)
|
||||
if seat_status is None:
|
||||
self._showTrace(
|
||||
@@ -115,33 +177,34 @@ class ReserveFlow(MsgBase):
|
||||
try:
|
||||
view.submitReserve()
|
||||
submit_reserve = True
|
||||
with ReserveResultDialog(self._driver) as result:
|
||||
if result.isFailure():
|
||||
self._showTrace("预约失败", self.TraceLevel.ERROR)
|
||||
elif result.isSuccess():
|
||||
details = result.getDetailTexts()
|
||||
if len(details) >= 6:
|
||||
self._showTrace(
|
||||
f"\n"
|
||||
f" 预约成功 !\n"
|
||||
f" {details[1]}\n"
|
||||
f" {details[2]}\n"
|
||||
f" {details[3]}\n"
|
||||
f" 签到时间 :{details[5]}"
|
||||
)
|
||||
else:
|
||||
self._showTrace(
|
||||
"\n"
|
||||
" 预约成功 !\n"
|
||||
" 未找获取到详细信息"
|
||||
)
|
||||
reserve_success = True
|
||||
else:
|
||||
self._showTrace("预约结果加载失败 !", self.TraceLevel.ERROR)
|
||||
reserve_success = self._processReserveResult()
|
||||
except (TimeoutException, ElementNotInteractableException):
|
||||
self._showTrace("预约提交失败 !", self.TraceLevel.ERROR)
|
||||
except Exception:
|
||||
self._showTrace("预约提交失败 !", self.TraceLevel.ERROR)
|
||||
return submit_reserve, reserve_success
|
||||
|
||||
def execute(
|
||||
self,
|
||||
ctx: ReserveContext,
|
||||
) -> bool:
|
||||
|
||||
# reserve flow pipeline:
|
||||
# date > place > floor > room > seat (begin/end time) > submit > result
|
||||
view = self._loadReserveView()
|
||||
if view is None:
|
||||
return False
|
||||
if not self._selectDate(view, ctx):
|
||||
return False
|
||||
if not self._selectPlace(view):
|
||||
return False
|
||||
if not self._selectFloor(view, ctx):
|
||||
return False
|
||||
seat_map = self._selectRoom(view, ctx)
|
||||
if seat_map is None:
|
||||
return False
|
||||
have_hover_on_page = True
|
||||
submit_reserve, reserve_success = self._selectSeatAndSubmit(
|
||||
view, seat_map, ctx,
|
||||
)
|
||||
if not submit_reserve and have_hover_on_page:
|
||||
view.refresh()
|
||||
if reserve_success:
|
||||
|
||||
@@ -7,12 +7,6 @@ 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 pages.flows.ReserveFlow import ReserveFlow
|
||||
from pages.flows.CheckinFlow import CheckinFlow
|
||||
from pages.flows.RenewFlow import RenewFlow
|
||||
|
||||
__all__ = [
|
||||
"ReserveFlow",
|
||||
"CheckinFlow",
|
||||
"RenewFlow",
|
||||
]
|
||||
from .ReserveFlow import ReserveFlow
|
||||
from .CheckinFlow import CheckinFlow
|
||||
from .RenewFlow import RenewFlow
|
||||
@@ -9,11 +9,5 @@ See the LICENSE file for details.
|
||||
"""
|
||||
from pages.strategies.TimeSelectMaker import (
|
||||
minsToTimeStr,
|
||||
timeStrToMins
|
||||
timeStrToMins,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"minsToTimeStr",
|
||||
"timeStrToMins",
|
||||
]
|
||||
@@ -11,11 +11,6 @@ import base64
|
||||
import queue
|
||||
|
||||
import ddddocr
|
||||
from selenium.common.exceptions import (
|
||||
NoSuchElementException,
|
||||
TimeoutException,
|
||||
)
|
||||
|
||||
from base.MsgBase import MsgBase
|
||||
from pages.LoginPage import LoginPage
|
||||
|
||||
@@ -38,6 +33,9 @@ class CaptchaSolver(MsgBase):
|
||||
|
||||
try:
|
||||
img_src = login_page.getCaptchaImageSrc()
|
||||
if img_src is None:
|
||||
self._showTrace("验证码图片元素定位时发生错误 !", self.TraceLevel.ERROR)
|
||||
return ""
|
||||
base64_str = img_src.split(',', 1)[1]
|
||||
captcha_img = base64.b64decode(base64_str)
|
||||
captcha_text = self._ocr.classification(captcha_img)
|
||||
@@ -45,15 +43,9 @@ class CaptchaSolver(MsgBase):
|
||||
self._showTrace(f"识别到验证码为 : '{captcha_text}'", 20, no_log=True)
|
||||
if len(captcha_text) != 4:
|
||||
self._showLog("识别到的验证码长度不等于 4 个字符 !", self.TraceLevel.WARNING)
|
||||
raise Exception("识别到的验证码长度不等于 4 个字符 !")
|
||||
return ""
|
||||
return captcha_text
|
||||
except (NoSuchElementException, TimeoutException) as e:
|
||||
self._showTrace(f"验证码识别失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return ""
|
||||
except (ValueError, OSError) as e:
|
||||
self._showTrace(f"验证码识别失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return ""
|
||||
except Exception as e:
|
||||
except ValueError as e:
|
||||
self._showTrace(f"验证码识别失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return ""
|
||||
|
||||
@@ -61,20 +53,13 @@ class CaptchaSolver(MsgBase):
|
||||
self,
|
||||
) -> str:
|
||||
|
||||
try:
|
||||
self._showMsg("请输入验证码:")
|
||||
captcha_text = self._waitMsg(timeout=15)
|
||||
self._showTrace(f"输入的验证码为 : '{captcha_text}'", 20, no_log=True)
|
||||
if len(captcha_text) != 4:
|
||||
self._showLog("输入的验证码长度不等于 4 个字符 !", self.TraceLevel.WARNING)
|
||||
raise Exception("输入的验证码长度不等于 4 个字符 !")
|
||||
return captcha_text
|
||||
except ValueError as e:
|
||||
self._showTrace(f"输入验证码失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
return ""
|
||||
except Exception as e:
|
||||
self._showTrace(f"输入验证码失败 ! : {e}", self.TraceLevel.ERROR)
|
||||
self._showMsg("请输入验证码:")
|
||||
captcha_text = self._waitMsg(timeout=15)
|
||||
self._showTrace(f"输入的验证码为 : '{captcha_text}'", 20, no_log=True)
|
||||
if len(captcha_text) != 4:
|
||||
self._showLog("输入的验证码长度不等于 4 个字符 !", self.TraceLevel.WARNING)
|
||||
return ""
|
||||
return captcha_text
|
||||
|
||||
def solveCaptcha(
|
||||
self,
|
||||
|
||||
@@ -112,20 +112,21 @@ class RecordChecker(MsgBase):
|
||||
try:
|
||||
time_element = records_view.getRecordTimeElement(reservation)
|
||||
info_elements = records_view.getRecordInfoElements(reservation)
|
||||
except (NoSuchElementException, TimeoutException, StaleElementReferenceException):
|
||||
except (NoSuchElementException, StaleElementReferenceException):
|
||||
return {
|
||||
"date": "",
|
||||
"time": {"begin": "", "end": ""},
|
||||
"info": {"location": "", "status": ""},
|
||||
}
|
||||
except Exception:
|
||||
try:
|
||||
time_data = self._decodeReserveTime(time_element)
|
||||
info_data = self._decodeReserveInfo(info_elements)
|
||||
except StaleElementReferenceException:
|
||||
return {
|
||||
"date": "",
|
||||
"time": {"begin": "", "end": ""},
|
||||
"info": {"location": "", "status": ""},
|
||||
}
|
||||
time_data = self._decodeReserveTime(time_element)
|
||||
info_data = self._decodeReserveInfo(info_elements)
|
||||
return {
|
||||
"date": time_data["date"],
|
||||
"time": time_data["time"],
|
||||
@@ -152,7 +153,10 @@ class RecordChecker(MsgBase):
|
||||
|
||||
records_view = shell.gotoRecordsView()
|
||||
for _ in range(max_check_times):
|
||||
reservations = records_view.loadRecords()
|
||||
try:
|
||||
reservations = records_view.loadRecords()
|
||||
except TimeoutException:
|
||||
reservations = None
|
||||
if reservations is None:
|
||||
return None
|
||||
for reservation in reservations[checked_count:]:
|
||||
|
||||
@@ -88,11 +88,22 @@ class ReserveChecker(MsgBase):
|
||||
) -> bool:
|
||||
|
||||
cur_time = time.strftime("%H:%M", time.localtime())
|
||||
cur_date = time.strftime("%Y-%m-%d", time.localtime())
|
||||
if reserve_info.get("begin_time") is None:
|
||||
reserve_info["begin_time"] = {}
|
||||
if "time" not in reserve_info["begin_time"]:
|
||||
reserve_info["begin_time"]["time"] = cur_time
|
||||
self._showTrace(f"开始时间未指定, 自动设置为当前时间: {cur_time}")
|
||||
elif reserve_info.get("date") == cur_date:
|
||||
begin_mins = timeStrToMins(reserve_info["begin_time"]["time"])
|
||||
cur_mins = timeStrToMins(cur_time)
|
||||
if begin_mins < cur_mins:
|
||||
self._showTrace(
|
||||
f"开始时间 {reserve_info['begin_time']['time']} 已过当前时间 {cur_time}, "
|
||||
f"自动调整为当前时间",
|
||||
self.TraceLevel.WARNING,
|
||||
)
|
||||
reserve_info["begin_time"]["time"] = cur_time
|
||||
if "max_diff" not in reserve_info["begin_time"]:
|
||||
reserve_info["begin_time"]["max_diff"] = 30
|
||||
self._showTrace("开始时间最大时间差未指定, 自动设置为 30 分钟")
|
||||
|
||||
@@ -7,12 +7,6 @@ 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 pages.services.CaptchaSolver import CaptchaSolver
|
||||
from pages.services.ReserveChecker import ReserveChecker
|
||||
from pages.services.RecordChecker import RecordChecker
|
||||
|
||||
__all__ = [
|
||||
"CaptchaSolver",
|
||||
"ReserveChecker",
|
||||
"RecordChecker",
|
||||
]
|
||||
from .CaptchaSolver import CaptchaSolver
|
||||
from .ReserveChecker import ReserveChecker
|
||||
from .RecordChecker import RecordChecker
|
||||
File renamed without changes.
@@ -7,7 +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.
|
||||
See the LICENSE file for details.
|
||||
"""
|
||||
from pages.strategies.TimeSelectMaker import (
|
||||
from .TimeSelectMaker import (
|
||||
TimeSelectMaker,
|
||||
TimeDecisionMaker,
|
||||
TimeOptionReader,
|
||||
@@ -17,14 +17,3 @@ from pages.strategies.TimeSelectMaker import (
|
||||
TimeSelectionResult,
|
||||
TimeRangeResult,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"TimeSelectMaker",
|
||||
"TimeDecisionMaker",
|
||||
"TimeOptionReader",
|
||||
"ReserveTimeReader",
|
||||
"RenewTimeReader",
|
||||
"TimeOption",
|
||||
"TimeSelectionResult",
|
||||
"TimeRangeResult",
|
||||
]
|
||||
@@ -0,0 +1,194 @@
|
||||
# -*- 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 json
|
||||
import os
|
||||
import zipfile
|
||||
|
||||
|
||||
def packTheme(
|
||||
qss_path: str,
|
||||
info: dict,
|
||||
output_path: str
|
||||
):
|
||||
"""
|
||||
Pack a .qss file and info dict into a .altheme file.
|
||||
|
||||
The .altheme file is a zip archive containing info.json and theme.qss.
|
||||
|
||||
Args:
|
||||
qss_path (str): Path to the .qss stylesheet file.
|
||||
info (dict): Theme metadata dict with keys name, author, need_theme, brief.
|
||||
output_path (str): Destination path for the .altheme file.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If qss_path does not exist.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(qss_path):
|
||||
raise FileNotFoundError(qss_path)
|
||||
with zipfile.ZipFile(output_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr("info.json", json.dumps(info, ensure_ascii=False, indent=4))
|
||||
zf.write(qss_path, "theme.qss")
|
||||
|
||||
def unpackTheme(
|
||||
altheme_path: str,
|
||||
output_dir: str
|
||||
):
|
||||
"""
|
||||
Extract a .altheme file to a directory.
|
||||
|
||||
Performs Zip Slip validation before extraction.
|
||||
|
||||
Args:
|
||||
altheme_path (str): Path to the .altheme file.
|
||||
output_dir (str): Directory to extract contents into.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If altheme_path does not exist.
|
||||
ValueError: If a zip entry contains an unsafe path.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(altheme_path):
|
||||
raise FileNotFoundError(altheme_path)
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
with zipfile.ZipFile(altheme_path, "r") as zf:
|
||||
for name in zf.namelist():
|
||||
if name.startswith("/") or ".." in name:
|
||||
raise ValueError(f"不安全的 .altheme 入口: {name}")
|
||||
zf.extractall(output_dir)
|
||||
|
||||
def readThemeInfo(
|
||||
altheme_path: str
|
||||
) -> dict:
|
||||
"""
|
||||
Read and validate the info.json metadata from a .altheme file.
|
||||
|
||||
Verifies that all required fields (name, author, need_theme, brief)
|
||||
are present with valid values.
|
||||
|
||||
Args:
|
||||
altheme_path (str): Path to the .altheme file.
|
||||
|
||||
Returns:
|
||||
dict: The validated theme metadata dictionary.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If altheme_path does not exist.
|
||||
ValueError: If info.json is missing or any field is invalid.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(altheme_path):
|
||||
raise FileNotFoundError(altheme_path)
|
||||
with zipfile.ZipFile(altheme_path, "r") as zf:
|
||||
if "info.json" not in zf.namelist():
|
||||
raise ValueError("无效的 .altheme: 缺少 info.json")
|
||||
with zf.open("info.json") as fh:
|
||||
try:
|
||||
info = json.loads(fh.read().decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
||||
raise ValueError(f"无效的 .altheme: info.json 解析失败 — {e}")
|
||||
if "name" not in info or not isinstance(info.get("name"), str) or not info["name"].strip():
|
||||
raise ValueError("无效的 .altheme: info.json 缺少有效的 'name' 字段")
|
||||
# reject blank author so that info.json does not drift from the
|
||||
# "未知作者" filename fallback used by wrapQssToAtheme
|
||||
if ("author" not in info or not isinstance(info.get("author"), str)
|
||||
or not info["author"].strip()):
|
||||
raise ValueError("无效的 .altheme: info.json 缺少有效的 'author' 字段")
|
||||
need_theme = info.get("need_theme", "both")
|
||||
if need_theme not in ("light", "dark", "both"):
|
||||
raise ValueError(
|
||||
f"无效的 .altheme: need_theme 值 '{need_theme}' 无效, "
|
||||
f"应为 'light'、'dark' 或 'both'"
|
||||
)
|
||||
if "brief" not in info or not isinstance(info.get("brief"), str):
|
||||
raise ValueError("无效的 .altheme: info.json 缺少有效的 'brief' 字段")
|
||||
return info
|
||||
|
||||
def readThemeQss(
|
||||
altheme_path: str
|
||||
) -> str:
|
||||
"""
|
||||
Read the theme.qss content from a .altheme archive.
|
||||
|
||||
Args:
|
||||
altheme_path (str): Path to the .altheme file.
|
||||
|
||||
Returns:
|
||||
str: The non-empty QSS stylesheet content.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If altheme_path does not exist.
|
||||
ValueError: If theme.qss is missing or empty.
|
||||
"""
|
||||
|
||||
if not os.path.isfile(altheme_path):
|
||||
raise FileNotFoundError(altheme_path)
|
||||
with zipfile.ZipFile(altheme_path, "r") as zf:
|
||||
if "theme.qss" not in zf.namelist():
|
||||
raise ValueError("无效的 .altheme: 缺少 theme.qss")
|
||||
qss = zf.read("theme.qss").decode("utf-8")
|
||||
if not qss.strip():
|
||||
raise ValueError("无效的 .altheme: theme.qss 为空")
|
||||
return qss
|
||||
|
||||
def validateTheme(
|
||||
altheme_path: str
|
||||
) -> dict:
|
||||
"""
|
||||
Fully validate a .altheme file and return its metadata.
|
||||
|
||||
Delegates info validation to readThemeInfo and QSS validation
|
||||
to readThemeQss, then additionally checks that theme.qss is
|
||||
non-empty.
|
||||
|
||||
Args:
|
||||
altheme_path (str): Path to the .altheme file.
|
||||
|
||||
Returns:
|
||||
dict: The validated theme metadata dictionary.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If altheme_path does not exist.
|
||||
ValueError: If validation fails for any reason.
|
||||
"""
|
||||
|
||||
info = readThemeInfo(altheme_path)
|
||||
readThemeQss(altheme_path) # validates existence and non-empty
|
||||
return info
|
||||
|
||||
def wrapQssToAtheme(
|
||||
qss_path: str,
|
||||
output_path: str,
|
||||
current_theme: str
|
||||
):
|
||||
"""
|
||||
Wrap a bare .qss file into a .altheme file with auto-generated metadata.
|
||||
|
||||
The generated info.json uses the filename as the theme name
|
||||
and sets default values for author and brief.
|
||||
|
||||
Args:
|
||||
qss_path (str): Path to the bare .qss stylesheet file.
|
||||
output_path (str): Destination path for the .altheme file.
|
||||
current_theme (str): The need_theme value to embed in metadata
|
||||
("light", "dark", or "both").
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If qss_path does not exist.
|
||||
"""
|
||||
|
||||
filename = os.path.splitext(os.path.basename(qss_path))[0]
|
||||
info = {
|
||||
"name": filename,
|
||||
"author": "未知作者",
|
||||
"need_theme": current_theme,
|
||||
"brief": "没有相关简介"
|
||||
}
|
||||
packTheme(qss_path, info, output_path)
|
||||
@@ -1,8 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Utils module for the AutoLibrary project.
|
||||
Copyright (c) 2026 KenanZhu.
|
||||
All rights reserved.
|
||||
|
||||
Here are the classes and modules in this package:
|
||||
- TimerUtils: Timer utils class for the AutoLibrary project.
|
||||
- JSONReader: JSON reader class for the AutoLibrary project.
|
||||
- JSONWriter: JSON writer class for the AutoLibrary project.
|
||||
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.
|
||||
"""
|
||||
File renamed without changes.
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user