diff --git a/.coveragerc b/.coveragerc deleted file mode 100644 index 114761242..000000000 --- a/.coveragerc +++ /dev/null @@ -1,11 +0,0 @@ -[run] -timid = True -branch = True -source = src -omit = - cq_editor/__main__.py - cq_editor/widgets/pyhighlight.py - -[report] -exclude_lines = - if __name__ == .__main__.: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 index f4e73e2dd..000000000 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: Build Executables - -on: - release: - types: [published] - workflow_dispatch: - -jobs: - build: - strategy: - fail-fast: false - matrix: - include: - - os: ubuntu-22.04 - artifact: CQ-editor-linux-x86_64 - - os: windows-2025-vs2026 - artifact: CQ-editor-windows-x86_64.exe - - os: macos-latest - artifact: CQ-editor-macos-arm64 - - runs-on: ${{ matrix.os }} - - steps: - - uses: actions/checkout@v5 - - - uses: actions/setup-python@v6 - with: - python-version: '3.13' - - - name: Install Linux system dependencies - if: runner.os == 'Linux' - run: sudo apt install -y libgl1 libegl1 - - - name: Install dependencies - run: | - pip install . - pip install pyinstaller - - - name: Build executable - run: pyinstaller pyinstaller.spec - - - name: Upload artifact - uses: actions/upload-artifact@v6 - with: - name: ${{ matrix.artifact }} - path: dist/CQ-editor* - - - name: Upload to release - if: github.event_name == 'release' - uses: softprops/action-gh-release@v2 - with: - files: dist/CQ-editor* - diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..8e18bcb55 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,141 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +jobs: + packaging: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: Validate release packaging + run: python -m unittest discover -s tests/packaging -p "test_*.py" + + rust: + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, windows-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + + - uses: Swatinem/rust-cache@v2 + + - name: Install Linux system dependencies + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libgtk-3-dev + + - name: Format + run: cargo fmt --all -- --check + + - name: Lint + run: cargo clippy --locked --all-targets --all-features -- -D warnings + + - name: Test + run: cargo test --locked + env: + # The rendering tests draw on WARP, the software adapter every + # Windows has; elsewhere they skip when no adapter is found. + CQ_EDITOR_REQUIRE_GPU: ${{ runner.os == 'Windows' && '1' || '' }} + + worker: + name: Worker (${{ matrix.name }}) + continue-on-error: ${{ matrix.experimental }} + runs-on: ubuntu-22.04 + strategy: + fail-fast: false + matrix: + include: + - name: Python 3.11 / CadQuery 2.7 / OCP 7.8 + python: "3.11" + cadquery: "cadquery==2.7.0" + ocp: "cadquery-ocp==7.8.1.1.post1" + expected_cadquery: "2.7.0" + expected_ocp: "7.8.1.1" + experimental: false + - name: Python 3.11 / CadQuery 2.8 / OCP 7.9 + python: "3.11" + cadquery: "cadquery==2.8.0" + ocp: "cadquery-ocp==7.9.3.1.1" + expected_cadquery: "2.8.0" + expected_ocp: "7.9.3.1.1" + experimental: false + - name: Python 3.12 / CadQuery 2.8 / OCP 7.9 + python: "3.12" + cadquery: "cadquery==2.8.0" + ocp: "cadquery-ocp==7.9.3.1.1" + expected_cadquery: "2.8.0" + expected_ocp: "7.9.3.1.1" + experimental: false + - name: Python 3.13 / CadQuery 2.8 / OCP 7.9 + python: "3.13" + cadquery: "cadquery==2.8.0" + ocp: "cadquery-ocp==7.9.3.1.1" + expected_cadquery: "2.8.0" + expected_ocp: "7.9.3.1.1" + experimental: false + - name: Python 3.14 / CadQuery 2.8 / OCP 7.9 + python: "3.14" + cadquery: "cadquery==2.8.0" + ocp: "cadquery-ocp==7.9.3.1.1" + expected_cadquery: "2.8.0" + expected_ocp: "7.9.3.1.1" + experimental: false + - name: Python 3.12 / CadQuery master / OCP 8.0 + python: "3.12" + cadquery: "cadquery @ git+https://github.com/CadQuery/cadquery.git@master" + ocp: "cadquery-ocp==8.0.1.1.0" + expected_cadquery: "2.9.0.dev" + expected_ocp: "8.0.1.1" + experimental: true + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + cache: pip + cache-dependency-path: worker/pyproject.toml + + - name: Install dependencies + run: | + python -m pip install "${{ matrix.cadquery }}" "${{ matrix.ocp }}" jedi pytest black coverage ruff mypy==2.4.0 + python -m pip install --no-deps --editable worker + + - name: Check supported dependencies + if: ${{ !matrix.experimental }} + run: python -m pip check + + - name: Report environment + run: python -c "from cq_worker.environment import summary; print(summary())" + + - name: Format + run: black --check worker tests/worker tests/packaging packaging/constructor/prepare_macos_icon.py + + - name: Lint + run: ruff check --isolated --select E4,E7,E9,F worker tests/worker tests/packaging packaging/constructor/prepare_macos_icon.py + + - name: Type check worker + run: mypy --config-file worker/pyproject.toml worker/cq_worker + + - name: Test + run: | + python -m coverage run --branch --source worker/cq_worker -m pytest tests/worker + python -m coverage report --show-missing --fail-under=85 + env: + PYTHONPATH: worker + CQ_EDITOR_EXPECT_CADQUERY: ${{ matrix.expected_cadquery }} + CQ_EDITOR_EXPECT_OCP: ${{ matrix.expected_ocp }} diff --git a/.github/workflows/constructor.yml b/.github/workflows/constructor.yml deleted file mode 100644 index 6cd8ed53d..000000000 --- a/.github/workflows/constructor.yml +++ /dev/null @@ -1,100 +0,0 @@ -# Set this workflow up to run on pushes to the main branch -name: Constructor -on: - push: - branches: - - master - -jobs: - constructor-linux: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Set up Conda - uses: conda-incubator/setup-miniconda@v3 - with: - miniconda-version: "latest" - activate-environment: constructor - - - name: Create Conda environment - shell: bash -el {0} - run: | - conda install -c conda-forge constructor conda-libmamba-solver - mkdir out && cd out && constructor ../conda - - - name: Upload Constructor output - uses: actions/upload-artifact@v4 - with: - name: CQ-editor-master-Linux-x86_64 - path: out/*.* - constructor-windows: - runs-on: windows-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Set up Conda - uses: conda-incubator/setup-miniconda@v3 - with: - miniconda-version: "latest" - activate-environment: constructor - - - name: Create Conda environment - shell: bash -el {0} - run: | - conda install -c conda-forge constructor conda-libmamba-solver - mkdir out && cd out && constructor ../conda - - - name: Upload Constructor output - uses: actions/upload-artifact@v4 - with: - name: CQ-editor-master-Windows-x86_64 - path: out/*.* - constructor-macos-arm64: - runs-on: macos-14 - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Set up Conda - uses: conda-incubator/setup-miniconda@v3 - with: - miniconda-version: "latest" - activate-environment: constructor - - - name: Create Conda environment - shell: bash -el {0} - run: | - conda install -c conda-forge constructor conda-libmamba-solver - mkdir out && cd out && constructor ../conda - - - name: Upload Constructor output - uses: actions/upload-artifact@v4 - with: - name: CQ-editor-master-MacOSX-ARM64 - path: out/*.* - constructor-macos-x86_64: - runs-on: macos-15-intel - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Set up Conda - uses: conda-incubator/setup-miniconda@v3 - with: - miniconda-version: "latest" - activate-environment: constructor - - - name: Create Conda environment - shell: bash -el {0} - run: | - conda install -c conda-forge constructor conda-libmamba-solver - mkdir out && cd out && constructor ../conda - - - name: Upload Constructor output - uses: actions/upload-artifact@v4 - with: - name: CQ-editor-master-MacOSX-x86_64 - path: out/*.* diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml deleted file mode 100644 index 6a7446815..000000000 --- a/.github/workflows/lint.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Lint - -on: [push, pull_request] - -jobs: - lint: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.11' - - run: | - python -m pip install --upgrade pip - python -m pip install -e .[dev] - black --diff --check . --exclude "(icons_res.py|examples/)" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000..a2aef79a2 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,260 @@ +name: Build release installers + +on: + push: + tags: + - "*" + workflow_dispatch: + +permissions: + contents: read + +jobs: + release-contract: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: Validate release metadata and packaging + run: python -m unittest discover -s tests/packaging -p "test_*.py" + + - name: Require the tag to match the project version + if: github.event_name == 'push' + shell: bash + run: | + version=$(python -c "import tomllib; print(tomllib.load(open('Cargo.toml', 'rb'))['package']['version'])") + test "$GITHUB_REF_NAME" = "$version" || { + echo "Tag $GITHUB_REF_NAME does not match Cargo version $version" >&2 + exit 1 + } + + build-installer: + needs: release-contract + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-22.04 + platform: linux-x86_64 + - os: windows-latest + platform: windows-x86_64 + - os: macos-15 + platform: macos-arm64 + - os: macos-15-intel + platform: macos-x86_64 + + name: Installer (${{ matrix.platform }}) + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@stable + + - uses: Swatinem/rust-cache@v2 + + - name: Install Linux build dependencies + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y libxkbcommon-dev libgtk-3-dev + + - name: Build native editor + run: cargo build --locked --release + env: + CQ_EDITOR_REQUIRE_RESOURCES: "1" + + # 0.9.0 follows the unsigned 0.8.0 release while certificates are obtained. + # Later tags still require signing and notarization before publication. + - name: Sign native editor (Windows) + if: runner.os == 'Windows' && github.ref_name != '0.9.0' + shell: pwsh + env: + CQ_WINDOWS_PFX_BASE64: ${{ secrets.WINDOWS_SIGNING_PFX_BASE64 }} + CQ_WINDOWS_PFX_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PFX_PASSWORD }} + run: ./packaging/sign_windows.ps1 target/release/cq-editor.exe + + - name: Prepare Developer ID identities (macOS) + if: runner.os == 'macOS' && github.ref_name != '0.9.0' + shell: bash + env: + CQ_MAC_APP_CERT_BASE64: ${{ secrets.MACOS_APPLICATION_P12_BASE64 }} + CQ_MAC_APP_CERT_PASSWORD: ${{ secrets.MACOS_APPLICATION_P12_PASSWORD }} + CQ_MAC_INSTALLER_CERT_BASE64: ${{ secrets.MACOS_INSTALLER_P12_BASE64 }} + CQ_MAC_INSTALLER_CERT_PASSWORD: ${{ secrets.MACOS_INSTALLER_P12_PASSWORD }} + CQ_MAC_APPLICATION_IDENTITY: ${{ secrets.MACOS_APPLICATION_IDENTITY }} + CQ_MAC_INSTALLER_IDENTITY: ${{ secrets.MACOS_INSTALLER_IDENTITY }} + run: bash packaging/prepare_macos_signing.sh + + - name: Sign native editor (macOS) + if: runner.os == 'macOS' && github.ref_name != '0.9.0' + shell: bash + env: + CQ_MAC_APPLICATION_IDENTITY: ${{ secrets.MACOS_APPLICATION_IDENTITY }} + run: | + codesign --force --options runtime --timestamp --sign "$CQ_MAC_APPLICATION_IDENTITY" target/release/cq-editor + codesign --verify --strict --verbose=2 target/release/cq-editor + + - name: Set up installer toolchain + uses: conda-incubator/setup-miniconda@v3 + with: + miniforge-version: latest + activate-environment: constructor-build + python-version: "3.12" + channels: conda-forge + channel-priority: strict + + - name: Install pinned constructor + shell: bash -el {0} + run: conda install --yes constructor=3.17.3 conda-libmamba-solver pillow + + - name: Prepare macOS application icon + if: runner.os == 'macOS' + shell: bash -el {0} + run: | + iconset=packaging/constructor/generated/cq-editor.iconset + python packaging/constructor/prepare_macos_icon.py assets/icons/cadquery_logo_dark.ico "$iconset" + iconutil -c icns "$iconset" -o packaging/constructor/generated/cq-editor.icns + + - name: Build installer + shell: bash -el {0} + env: + CQ_MAC_APPLICATION_IDENTITY: ${{ runner.os == 'macOS' && github.ref_name != '0.9.0' && secrets.MACOS_APPLICATION_IDENTITY || '' }} + CQ_MAC_INSTALLER_IDENTITY: ${{ runner.os == 'macOS' && github.ref_name != '0.9.0' && secrets.MACOS_INSTALLER_IDENTITY || '' }} + run: | + mkdir dist + cd dist + constructor ../packaging/constructor + + - name: Name build manifests for the platform + shell: bash + run: | + mv dist/info.json "dist/cq-editor-${{ matrix.platform }}-info.json" + mv dist/lockfile.base.txt "dist/cq-editor-${{ matrix.platform }}-lockfile.txt" + mv dist/licenses.json "dist/cq-editor-${{ matrix.platform }}-licenses.json" + mv dist/pkg-list.base.txt "dist/cq-editor-${{ matrix.platform }}-packages.txt" + + - name: Sign installer (Windows) + if: runner.os == 'Windows' && github.ref_name != '0.9.0' + shell: pwsh + env: + CQ_WINDOWS_PFX_BASE64: ${{ secrets.WINDOWS_SIGNING_PFX_BASE64 }} + CQ_WINDOWS_PFX_PASSWORD: ${{ secrets.WINDOWS_SIGNING_PFX_PASSWORD }} + run: | + $installers = @(Get-ChildItem -LiteralPath dist -Filter *.exe -File) + if ($installers.Count -ne 1) { throw 'Expected exactly one Windows installer.' } + ./packaging/sign_windows.ps1 $installers[0].FullName + + - name: Notarize and staple installer (macOS) + if: runner.os == 'macOS' && github.ref_name != '0.9.0' + shell: bash + env: + CQ_MAC_NOTARY_KEY_BASE64: ${{ secrets.MACOS_NOTARY_KEY_P8_BASE64 }} + CQ_MAC_NOTARY_KEY_ID: ${{ secrets.MACOS_NOTARY_KEY_ID }} + CQ_MAC_NOTARY_ISSUER_ID: ${{ secrets.MACOS_NOTARY_ISSUER_ID }} + run: bash packaging/notarize_macos.sh + + - name: Smoke test installed runtime (Linux) + if: runner.os == 'Linux' + shell: bash + run: | + installer=$(find dist -maxdepth 1 -name '*.sh' -print -quit) + test -n "$installer" + prefix="$RUNNER_TEMP/cq-editor-smoke" + bash "$installer" -b -p "$prefix" + "$prefix/bin/python3" -c "import sys, cadquery, OCP, jedi; assert sys.version_info[:3] == (3, 12, 15); assert cadquery.__version__ == '2.8.0'; assert OCP.__version__.startswith('7.9.3.1'); assert jedi.__version__ == '0.19.2'" + "$prefix/bin/cq-editor" --help + + - name: Smoke test installed runtime (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + $installer = (Get-ChildItem dist -Filter *.exe | Select-Object -First 1).FullName + if (-not $installer) { throw "Windows installer was not created" } + $prefix = Join-Path $env:RUNNER_TEMP "cq-editor-smoke" + $installLog = Join-Path $env:RUNNER_TEMP "cq-editor-install.log" + $installError = Join-Path $env:RUNNER_TEMP "cq-editor-install-error.log" + $install = Start-Process -FilePath $installer -ArgumentList @("/S", "/InstallationType=JustMe", "/D=$prefix") -NoNewWindow -RedirectStandardOutput $installLog -RedirectStandardError $installError -Wait -PassThru + Get-Content $installLog + Get-Content $installError + if ($install.ExitCode -ne 0) { throw "Installer exited with $($install.ExitCode)" } + & "$prefix\python.exe" -c "import sys, cadquery, OCP, jedi; assert sys.version_info[:3] == (3, 12, 15); assert cadquery.__version__ == '2.8.0'; assert OCP.__version__.startswith('7.9.3.1'); assert jedi.__version__ == '0.19.2'" + if ($LASTEXITCODE -ne 0) { throw "Bundled Python runtime failed" } + $help = Start-Process -FilePath "$prefix\cq-editor.exe" -ArgumentList "--help" -RedirectStandardOutput "$env:RUNNER_TEMP\cq-editor-help.txt" -Wait -PassThru + if ($help.ExitCode -ne 0) { throw "Installed editor exited with $($help.ExitCode)" } + $shortcut = Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\CQ-editor\CQ-editor.lnk" + if (-not (Test-Path $shortcut)) { throw "Start menu shortcut was not created" } + $association = reg.exe query "HKCU\Software\Classes\.py\OpenWithProgids" + if (($association -join "`n") -notmatch "cq-editor.AssocFile.py") { throw "Open With registration was not created" } + $uninstall = Start-Process -FilePath "$prefix\Uninstall-CQ-editor.exe" -ArgumentList @("/S", "/Q") -NoNewWindow -Wait -PassThru + if ($uninstall.ExitCode -ne 0) { throw "Uninstaller exited with $($uninstall.ExitCode)" } + if (Test-Path $prefix) { throw "Uninstaller left the installation behind" } + if (Test-Path $shortcut) { throw "Uninstaller left the Start menu shortcut behind" } + $remainingAssociation = reg.exe query "HKCU\Software\Classes\.py\OpenWithProgids" + if (($remainingAssociation -join "`n") -match "cq-editor.AssocFile.py") { throw "Uninstaller left the Open With registration behind" } + + - name: Smoke test installed runtime (macOS) + if: runner.os == 'macOS' + shell: bash + run: | + package=$(find dist -maxdepth 1 -name '*.pkg' -print -quit) + test -n "$package" + installer -pkg "$package" -target CurrentUserHomeDirectory + prefix="$HOME/Library/CQ-editor" + "$prefix/bin/python3" -c "import sys, cadquery, OCP, jedi; assert sys.version_info[:3] == (3, 12, 15); assert cadquery.__version__ == '2.8.0'; assert OCP.__version__.startswith('7.9.3.1'); assert jedi.__version__ == '0.19.2'" + "$prefix/bin/cq-editor" --help + test -d "$HOME/Applications/CQ-editor.app" + + - name: Upload installer and build manifest + uses: actions/upload-artifact@v6 + with: + name: cq-editor-${{ matrix.platform }} + path: dist/ + if-no-files-found: error + retention-days: 30 + + - name: Remove temporary macOS signing keychain + if: always() && runner.os == 'macOS' + shell: bash + run: | + keychain="$RUNNER_TEMP/cq-editor-signing.keychain-db" + if test -f "$keychain"; then security delete-keychain "$keychain"; fi + + publish-release: + if: github.event_name == 'push' + needs: build-installer + runs-on: ubuntu-22.04 + permissions: + contents: write + steps: + - name: Download verified installers + uses: actions/download-artifact@v6 + with: + pattern: cq-editor-* + path: release-assets + + - name: Create checksums + shell: bash + run: | + : > release-assets/SHA256SUMS.txt + while IFS= read -r file; do + checksum=$(sha256sum "$file" | cut -d ' ' -f 1) + printf '%s %s\n' "$checksum" "$(basename "$file")" >> release-assets/SHA256SUMS.txt + done < <(find release-assets -type f \( -name '*.exe' -o -name '*.pkg' -o -name '*.sh' \) | sort) + test "$(wc -l < release-assets/SHA256SUMS.txt)" -eq 4 + + - name: Publish GitHub release + uses: softprops/action-gh-release@v2 + with: + name: CQ-editor ${{ github.ref_name }} + body: ${{ github.ref_name == '0.9.0' && 'Windows and macOS installers for 0.9.0 are unsigned, as in 0.8.0. Verify downloaded files with SHA256SUMS.txt before installing.' || '' }} + generate_release_notes: true + fail_on_unmatched_files: true + files: | + release-assets/**/*.exe + release-assets/**/*.pkg + release-assets/**/*.sh + release-assets/**/*lockfile* + release-assets/**/*info.json + release-assets/SHA256SUMS.txt diff --git a/.github/workflows/test_linux.yml b/.github/workflows/test_linux.yml deleted file mode 100644 index c8b904cc7..000000000 --- a/.github/workflows/test_linux.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Test Linux - -on: [push, pull_request] - -jobs: - test-linux: - name: Test Linux - runs-on: ubuntu-22.04 - steps: - - name: "Check out the repo" - uses: actions/checkout@v3 - with: - submodules: true - - uses: actions/setup-python@v4 - with: - python-version: '3.11' - - - name: Install system dependencies - run: | - sudo apt update && sudo apt install -y \ - xvfb xauth \ - libgl1 libglx-mesa0 libgl1-mesa-dri libglu1-mesa libegl1-mesa mesa-utils libopengl0 \ - libx11-6 libx11-xcb1 libxext6 libxrender1 libsm6 libice6 libxxf86vm1 libxdamage1 libxfixes3 \ - libxcb-glx0 libxcb-dri2-0 libxcb-dri3-0 libxcb-present0 libxcb-shape0 libxcb-shm0 libxcb-sync1 \ - libxcb-xfixes0 libxkbcommon-x11-0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 \ - libxcb-randr0 libxcb-render-util0 libxcb-xinerama0 \ - fontconfig fonts-dejavu-core - sudo fc-cache -f - - - name: Install packages - run: | - pip install -e . - pip install .[test] - pip list - - - name: Run tests - env: - LIBGL_ALWAYS_SOFTWARE: "1" - MESA_LOADER_DRIVER_OVERRIDE: "swrast" - GALLIUM_DRIVER: "llvmpipe" - LIBGL_DRIVERS_PATH: "/usr/lib/x86_64-linux-gnu/dri" - QT_OPENGL: "software" - QT_QPA_PLATFORM: "xcb" - uses: coactions/setup-xvfb@v1.0.1 - with: - run: pytest diff --git a/.gitignore b/.gitignore index 894a44cc0..3dff98107 100644 --- a/.gitignore +++ b/.gitignore @@ -84,6 +84,9 @@ celerybeat-schedule # Environments .env .venv +.venv311/ +.venv311_27/ +.python/ env/ venv/ ENV/ @@ -102,3 +105,6 @@ venv.bak/ # mypy .mypy_cache/ + +# Rust +/target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 000000000..da13acdd6 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,4403 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "accesskit" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +dependencies = [ + "enumn", + "serde", + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e8c61bee90b42a772d39d06a740207dc71a4e780004ace1db8d99fb1baaa954" +dependencies = [ + "accesskit", + "accesskit_consumer 0.36.0", + "atspi-common", + "phf 0.13.1", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.35.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53cf47daed85312e763fbf85ceca136e0d7abc68e0a7e12abe11f48172bc3b10" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25e0d7e25d06f4dc21d1774d67146e9e80d6789216cbd4d1e88185b0095dba60" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_consumer" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_macos" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +dependencies = [ + "accesskit", + "accesskit_consumer 0.38.0", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b016ca8db0ea0ea2ceff29a9d6240391492d960716aa471967c00e8cc8cb197c" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eff7009f1a532e917d66970a1e80c965140c6cfbbabbdde3d64e5431e6c78e21" +dependencies = [ + "accesskit", + "accesskit_consumer 0.35.0", + "hashbrown 0.16.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fe9a94394896352cc4660ca2288bd4ef883d83238853c038b44070c8f134313" +dependencies = [ + "accesskit", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "raw-window-handle", + "winit", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "serde", + "version_check", + "zerocopy", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "image", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "x11rb", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.5", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.5", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.5", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.5", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop 0.13.0", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" +dependencies = [ + "calloop 0.14.5", + "rustix 1.1.5", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "cq-editor" +version = "0.9.0" +dependencies = [ + "base64", + "bytemuck", + "chrono", + "eframe", + "egui", + "egui-phosphor", + "egui_dock", + "egui_extras", + "glam", + "image", + "log", + "naga", + "open", + "png", + "rfd", + "same-file", + "serde", + "serde_json", + "tempfile", + "windows-sys 0.61.2", + "winit", + "winresource", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "libc", + "objc2 0.6.5", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "duplicate" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e92f10a49176cbffacaedabfaa11d51db1ea0f80a83c26e1873b43cd1742c24" +dependencies = [ + "heck", + "proc-macro2", + "proc-macro2-diagnostics", +] + +[[package]] +name = "ecolor" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0656a7530b9e2841ee7a5f983965bdd9840c32f4012f759cfd44b912cced6b34" +dependencies = [ + "bytemuck", + "emath", + "serde", +] + +[[package]] +name = "eframe" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55ad41fac6e3149abb4866e93df37dbd33baa95db525c3368c944584e95a5dc2" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "egui-wgpu", + "egui-winit", + "egui_glow", + "glutin", + "glutin-winit", + "image", + "js-sys", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "pollster 1.0.1", + "profiling", + "raw-window-handle", + "ron", + "serde", + "static_assertions", + "wasm-bindgen", + "web-sys", + "web-time", + "wgpu", + "windows-sys 0.61.2", + "winit", +] + +[[package]] +name = "egui" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc938cc27cd911415e1e4d151bc56ff9df063d8db081374e87aeb805ea74b2ba" +dependencies = [ + "accesskit", + "ahash", + "bitflags 2.13.2", + "emath", + "epaint", + "itertools", + "log", + "nohash-hasher", + "profiling", + "ron", + "serde", + "smallvec", + "unicode-segmentation", + "web-sys", +] + +[[package]] +name = "egui-phosphor" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f4299551488dddaa8f757727e1eb4ffdaf277ffe6e30b413403468f5ecf4634" +dependencies = [ + "egui", +] + +[[package]] +name = "egui-wgpu" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cef1f6d1bba40b09a4d0d62cb822b81030922cfbf65c5373398c3a3caafc5bd" +dependencies = [ + "ahash", + "bytemuck", + "document-features", + "egui", + "epaint", + "log", + "profiling", + "thiserror 2.0.21", + "type-map", + "web-time", + "wgpu", + "winit", +] + +[[package]] +name = "egui-winit" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98466000559d66ba4db786a30448b01483946add4188e7f10f522a27b4fb89cc" +dependencies = [ + "accesskit_winit", + "arboard", + "bytemuck", + "egui", + "log", + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "objc2-ui-kit 0.3.2", + "profiling", + "raw-window-handle", + "serde", + "smithay-clipboard", + "web-time", + "winit", +] + +[[package]] +name = "egui_dock" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d9f668eb59ff0ab130c8bce71a513135e1d3017fb3103fb8758e9eea99d759f" +dependencies = [ + "duplicate", + "egui", + "paste", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "egui_extras" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05cbdc785020861553f230f23d330ba1fb72613b9d8e0e457f3bdc8ba6db6dcf" +dependencies = [ + "ahash", + "egui", + "enum-map", + "itertools", + "log", + "mime_guess2", + "profiling", +] + +[[package]] +name = "egui_glow" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "606ed4167daf341e5753d703285c4c1d562324b2c07aa8f405cd7d066fe58f3b" +dependencies = [ + "bytemuck", + "egui", + "glow", + "log", + "profiling", + "winit", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "emath" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52c8d4141cf0f60fb2f7aefaf352d3ffa5171ef0ab09731c64391801e95e48f1" +dependencies = [ + "bytemuck", + "serde", +] + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enum-map" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6866f3bfdf8207509a033af1a75a7b08abda06bbaaeae6669323fd5a097df2e9" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumn" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "epaint" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ec0308dc23130fc1a7d4623a8534c2ed069c6dc84e258ee4f3de99615aa1a3" +dependencies = [ + "ahash", + "bytemuck", + "ecolor", + "emath", + "epaint_default_fonts", + "font-types", + "harfrust", + "log", + "nohash-hasher", + "parking_lot", + "profiling", + "self_cell", + "serde", + "skrifa", + "smallvec", + "unicode-general-category", + "unicode-segmentation", + "vello_cpu", +] + +[[package]] +name = "epaint_default_fonts" +version = "0.36.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773fa9c96dd0dbef887e39d0ed6177f141cce4d68e6041df77570aa3702dfa13" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "fearless_simd" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", + "serde", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.5", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glam" +version = "0.34.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc148d4ddd3930c52f9e5ae79b89805c6f07e9ff417e7b083e0348cea60a5aba" +dependencies = [ + "bytemuck", + "serde_core", +] + +[[package]] +name = "glifo" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed4a1bb24121291d27230c1b1b44e07d6a9b28cefdb32fe1581dfb84e14f940a" +dependencies = [ + "bytemuck", + "foldhash", + "hashbrown 0.17.1", + "log", + "peniko", + "skrifa", + "smallvec", + "vello_common", +] + +[[package]] +name = "glow" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29038e1c483364cc6bb3cf78feee1816002e127c331a1eec55a4d202b9e1adb5" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "is-docker" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" +dependencies = [ + "once_cell", +] + +[[package]] +name = "is-wsl" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" +dependencies = [ + "is-docker", + "once_cell", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "khronos-egl" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" +dependencies = [ + "libc", + "libloading", + "pkg-config", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess2" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1706dc14a2e140dec0a7a07109d9a3d5890b81e85bd6c60b906b249a77adf0ca" +dependencies = [ + "mime", + "phf 0.11.3", + "phf_shared 0.11.3", + "unicase", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "open" +version = "5.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" +dependencies = [ + "is-wsl", + "libc", +] + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c860fd3227ca4ac3cc032e2cd20cba3f02ccdf4b610538f8ee6584d56bb62e96" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo", + "linebender_resource_handle", + "smallvec", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_macros 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + +[[package]] +name = "phf_macros" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", + "syn 2.0.119", + "unicase", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher", + "unicase", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "pollster" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc6355899e1c9462875b6757c79f3caa011a1fdae12bbb1a2e72dd1f234f8336" + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "pollster 0.4.0", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "ron" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81116b9531d61eabc41aeb228e4b6b2435bcca3233b98cf3b3077d4e6e9debb3" +dependencies = [ + "bitflags 2.13.2", + "once_cell", + "serde", + "serde_derive", + "typeid", + "unicode-ident", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit 0.19.2", + "tiny-skia", +] + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +dependencies = [ + "serde", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.13.0", + "calloop-wayland-source 0.3.0", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-client-toolkit" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0512da38f5e2b31201a93524adb8d3136276fa4fe4aafab4e1f727a82b534cc0" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.14.5", + "calloop-wayland-source 0.4.1", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 1.1.5", + "thiserror 2.0.21", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-experimental", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smithay-clipboard" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" +dependencies = [ + "libc", + "smithay-client-toolkit 0.20.0", + "wayland-backend", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "type-map" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" +dependencies = [ + "rustc-hash 2.1.3", +] + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "vello_common" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e9aed918117e8152c9eddfd8362d73c465c23f26c44786aa331707b8a64fa2" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "log", + "peniko", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_cpu" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac7349e1f55f6b801c7c277958df4ea53e7f20f21e8014910ad888b2ecda93ea" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.1", + "vello_common", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.5", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.5", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-experimental" +version = "20250721.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40a1f863128dcaaec790d7b4b396cc9b9a7a079e878e18c47e6c2d2c5a8dcbb1" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "js-sys", + "log", + "naga", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-wasm", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98b86cf4abf524a902dd35f18ca6a3f08fc2ae9847c8f10b48e30491b1f0b86" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-wasm" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d260ca2ca8adc654f513a869bf3cac0b47f5b8d3f87803d6942015f8de597aae" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "glow", + "glutin_wgl_sys", + "gpu-allocator", + "hashbrown 0.17.1", + "js-sys", + "khronos-egl", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "ndk-sys", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wasm-bindgen", + "wayland-sys", + "web-sys", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", + "windows-result", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", + "web-sys", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop 0.13.0", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "smithay-client-toolkit 0.19.2", + "smol_str", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "winresource" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" +dependencies = [ + "toml", + "version_check", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.5", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 000000000..48501ea82 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,79 @@ +[package] +name = "cq-editor" +version = "0.9.0" +edition = "2024" +rust-version = "1.88" +description = "Cross-platform CadQuery 3D viewer and script editor" +license = "Apache-2.0" +repository = "https://github.com/igors93/CQ-editor" +keywords = ["cadquery", "cad", "engineering", "design"] +# Python example scripts live in `examples/`; they are not Cargo examples. +autoexamples = false + +[dependencies] +# The defaults without "links": its `webbrowser` dependency needs shlwapi, +# which the self-contained Windows GNU toolchain lacks. Links are opened +# with `open` instead (see `app::open_url`). +eframe = { version = "0.36", default-features = false, features = [ + "accesskit", + "default_fonts", + "persistence", + "wayland", + "web_screen_reader", + "wgpu", + "x11", +] } +# eframe's "winit/default", which a dependency list cannot name. +winit = "0.30" +egui = "0.36" +egui_dock = { version = "0.21", features = ["serde"] } +egui_extras = { version = "0.36" } +egui-phosphor = "0.14" +glam = { version = "0.34", features = ["bytemuck", "serde"] } +bytemuck = { version = "1", features = ["derive"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +base64 = "0.23" +rfd = "0.17" +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "ico"] } +# Animated PNG for turntable exports (already a dependency of `image`). +png = "0.18" +log = { version = "0.4", features = ["std"] } +open = "5" +chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } +tempfile = "3.27" +# Whether two paths name one file: a rename that only changes the case. +same-file = "1" + +[target.'cfg(windows)'.build-dependencies] +# Icon and version information of the .exe (see build.rs). +winresource = "0.1" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = [ + "Win32_Storage_FileSystem", + "Win32_System_Console", +] } + +[dev-dependencies] +# wgpu's own WGSL front end: the tests validate the shaders without a GPU. +naga = { version = "30.0.1", features = ["wgsl-in"] } + +[profile.dev] +# Line tables keep panic backtraces useful at a fraction of full debug info's size. +debug = "line-tables-only" + +[profile.dev.package."*"] +# Dependencies (wgpu, egui, image) are much faster optimized, even in debug +# builds, and their debug info would take gigabytes of disk. +opt-level = 2 +debug = false + +[profile.release] +# Whole-program optimization: with one codegen unit and fat LTO the optimizer +# sees wgpu, naga, egui and the editor at once, inlines across crates and drops +# code no path reaches. The binary is smaller and no slower (opt-level stays +# 3); only release builds take longer. +lto = "fat" +codegen-units = 1 +strip = true diff --git a/README.md b/README.md index b007f2608..7058af2fc 100644 --- a/README.md +++ b/README.md @@ -1,55 +1,183 @@ -# CQ-editor +

CQ-editor

-[![Build status](https://ci.appveyor.com/api/projects/status/g98rs7la393mgy91/branch/master?svg=true)](https://ci.appveyor.com/project/adam-urbanczyk/cq-editor/branch/master) -[![codecov](https://codecov.io/gh/CadQuery/CQ-editor/branch/master/graph/badge.svg)](https://codecov.io/gh/CadQuery/CQ-editor) -[![Build Status](https://dev.azure.com/cadquery/CQ-editor/_apis/build/status/CadQuery.CQ-editor?branchName=master)](https://dev.azure.com/cadquery/CQ-editor/_build/latest?definitionId=3&branchName=master) -[![DOI](https://img.shields.io/badge/DOI-10.5281%2Fzenodo.3955112-blue.svg)](https://doi.org/10.5281/zenodo.3955112) -[![Patreon](https://badgen.net/badge/icon/patreon?icon=patreon&label)](https://www.patreon.com/jmwright) -[![Liberapay](https://badgen.net/badge/icon/liberapay?icon=liberapay&label)](https://liberapay.com/jmwright) +

+ The code editor and 3D viewer for CadQuery.
+ Write Python, press F5, see your model. On Linux, Windows and macOS. +

-CadQuery GUI editor based on PyQT that supports Linux, Windows and Mac. +

+ CI + DOI + License: Apache-2.0 + Patreon + Liberapay +

-![CQ-editor screenshot](https://github.com/CadQuery/CQ-editor/raw/master/screenshots/screenshot4.png) -Additional screenshots are available in [the wiki](https://github.com/CadQuery/CQ-editor/wiki#screenshots). +

+ + + CQ-editor with a CadQuery script on the left and the rendered model on the right + +

+ +CadQuery models are Python programs: parametric, versionable and easy to +share. CQ-editor is the IDE built around that idea. You get an editor for +your script, a fast 3D view of the result, and the tools to understand how +the model was built: a debugger, a stack inspector and an interactive +console. Your code stays the single source of truth. ## Notable features -* Automatic code reloading - you can use your favourite editor -* OCCT based -* Navigation cube with rotation arrows - * Always shows the current camera orientation - * Click faces, edges or corners for one-click animated reorientation -* Graphical debugger for CadQuery scripts - * Step through script and watch how your model changes -* CadQuery object stack inspector - * Visual inspection of current workplane and selected items - * Insight into evolution of the model -* Export to various formats - * STL - * STEP +* **Automatic code reloading**: keep using your favorite editor; CQ-editor + re-runs the script on every save, and never silently overwrites unsaved + edits. +* **GPU-accelerated 3D view** with anti-aliasing, smooth camera animations, + zoom at the mouse pointer, and turntable or trackball orbiting. +* **Navigation cube** with rotation arrows + * always shows the current camera orientation; + * click faces, edges or corners for one-click animated reorientation. +* **Precise selection** of faces, edges and vertices, with stable topological + ids (*Selected Face 6 of bracket*). +* **Graphical debugger** for CadQuery scripts + * step through the script (over, in, out) and watch the model change. +* **CadQuery object stack inspector** + * visual inspection of the current workplane and selected items; + * insight into the evolution of the model. +* **Export** to STEP (assemblies keep names and colors), STL and BREP. +* **Python console** that shares the variables of the last run. +* **Multi-file projects**: every file in a tab, a Project panel with the + folder's files, and a main script that F5 renders while you edit its + modules. +* **Robust by design**: scripts run in a separate Python process, so a long + or crashing script never freezes or takes down the editor. Saves are + atomic, and unsaved work is recovered after a crash. +* **Light and dark themes**, dockable panels that remember their layout. + + + + + + + + + + + + + + + + + + + + + + +
Debugger paused at a breakpointCQ Inspector overlaying a construction stepA picked face with its exact measurements and CadQuery selector
Step through a scriptInspect how a model was builtSelect, measure and get the selector
A ball valve cut by the section planeA quadcopter assembly in the exploded viewThe Parameters panel editing a twisted vase
Cut the model with a section planeExplode assembliesTune parameters with sliders
+ +## Quick start + +1. **Download the installer** for your computer from the + [releases page](https://github.com/igors93/CQ-editor/releases): + + * Windows: `CQ-editor-0.9.0-Windows-x86_64.exe`; + * macOS: the Apple Silicon or Intel `.pkg`; + * Linux: the `.sh` installer (`chmod +x` it, then run it). + + Python, CadQuery and code completion are already included. Each release + publishes SHA-256 checksums, and CI installs and starts every artifact + before it is published. + +2. **Launch CQ-editor** from the application menu. On Windows and Linux you + can also choose CQ-editor from **Open with** for a `.py` file. + +3. **Press F5.** Scripts are plain CadQuery; `show_object` decides what is + displayed: + + ```python + import cadquery as cq + + result = cq.Workplane("XY").box(40, 30, 12).edges("|Z").fillet(3) + show_object(result, name="block", options={"color": "steelblue"}) + ``` + +New to CadQuery or CQ-editor? The [10-minute tour](docs/getting-started/first-model.md) +models a bracket step by step, and **File > Examples** has nine commented +scripts. ## Documentation -Documentation is available in [the wiki](https://github.com/CadQuery/CQ-editor/wiki). Topics covered are the following. +Everything is in the [`docs/`](docs/README.md) folder: + +* [Installation](docs/getting-started/installation.md): requirements, how Python is found, where files are stored +* [Your first model](docs/getting-started/first-model.md): a guided tour +* [User guide](docs/README.md#user-guide): [interface](docs/user-guide/interface.md), [writing scripts](docs/user-guide/scripting.md), [3D view](docs/user-guide/viewer.md), [editor](docs/user-guide/editor.md), [projects](docs/user-guide/projects.md), [debugging](docs/user-guide/debugging.md), [console](docs/user-guide/console.md), [exporting](docs/user-guide/exporting.md), [preferences](docs/user-guide/preferences.md), [shortcuts](docs/user-guide/shortcuts.md), [troubleshooting](docs/user-guide/troubleshooting.md) +* [Development](docs/README.md#development): [architecture](docs/development/architecture.md), [worker protocol](docs/development/protocol.md), [building](docs/development/building.md), [testing](docs/development/testing.md), [CadQuery/OCP compatibility](docs/development/dependency-compatibility.md), [contributing](docs/development/contributing.md) +* [Roadmap](docs/roadmap.md) and [changelog](docs/changelog.md) + +## How it works + +The interface is a native Rust application built with +[egui](https://github.com/emilk/egui) and [wgpu](https://wgpu.rs). CadQuery +runs in a separate Python process, the *worker*. The worker executes +scripts, meshes the shapes and sends them to the interface. Its sources are +embedded in the executable. Release installers also carry a private, tested +Python/CadQuery environment; source builds can use any compatible environment +selected with `--python` or in Preferences. + +``` +┌──────────────────────────────┐ JSON lines ┌─────────────────────────────┐ +│ cq-editor (Rust) │ ──────────────► │ python -m cq_worker │ +│ editor, 3D view, panels │ stdin/stdout │ runs scripts with CadQuery, │ +│ │ ◄────────────── │ meshes, debugger, export │ +└──────────────────────────────┘ └─────────────────────────────┘ +``` -* [Installation](https://github.com/CadQuery/CQ-editor/wiki/Installation) -* [Usage](https://github.com/CadQuery/CQ-editor/wiki/Usage) -* [Configuration](https://github.com/CadQuery/CQ-editor/wiki/Configuration) +Scripts written for the original PyQt CQ-editor keep working: same +`show_object` options, same script namespace, same execution settings. See +[Architecture](docs/development/architecture.md) for the details. GUI +equivalence, deliberate changes and the remaining stereo and rich-console +gaps are tracked in the +[compatibility matrix](docs/development/compatibility.md); they are not +silently treated as equivalent. ## Getting Help -For general questions and discussion about CQ-editor, please create a [GitHub Discussion](https://github.com/CadQuery/CQ-editor/discussions). +For general questions and discussion about CQ-editor, please create a +[GitHub Discussion](https://github.com/igors93/CQ-editor/discussions). For +CadQuery itself, see the [CadQuery documentation](https://cadquery.readthedocs.io/en/latest/). ## Reporting a Bug -If you believe that you have found a bug in CQ-editor, please ensure the following. +If you believe that you have found a bug in CQ-editor, please make sure that: + +* you are using the latest CQ-editor release; +* you have searched the [issue tracker](https://github.com/igors93/CQ-editor/issues) + and the [roadmap](docs/roadmap.md#1-bugs-and-problems) to make sure the bug + is not already known. + +Then file a [new issue](https://github.com/igors93/CQ-editor/issues/new) +with: + +* the operating system and its version (on Linux, the distribution and its + version); +* how CQ-editor was installed (release download or built from source, and + which commit); +* the Python and CadQuery versions (shown in the status bar and in *Help > + About*); +* the steps to reproduce the bug, ideally with a small script; +* the relevant lines from the Log panel or, after a crash, from the log file + `logs/cq-editor.log` in the [application data + folder](docs/getting-started/installation.md#where-cq-editor-keeps-its-files). + +## Contributing -* You are not running a CQ-editor fork, as these are not always synchronized with the latest updates in this project. -* You have searched the [issue tracker](https://github.com/CadQuery/CQ-editor/issues) to make sure that the bug is not already known. +Contributions are welcome. Start with [Contributing](docs/development/contributing.md) +and pick something from the [roadmap](docs/roadmap.md). -If you have already checked those things, please file a [new issue](https://github.com/CadQuery/CQ-editor/issues/new) with the following information. +## License -* Operating System (type, version, etc) - If running Linux, please include the distribution and the version. -* How CQ-editor was installed. -* Python version of your environment (unless you are running a pre-built package). -* Steps to reproduce the bug. +CQ-editor is licensed under the [Apache License 2.0](LICENSE). The bundled +Inter and JetBrains Mono fonts are under the SIL Open Font License 1.1 (see +[`assets/fonts`](assets/fonts/README.md)). diff --git a/assets/fonts/Inter-LICENSE.txt b/assets/fonts/Inter-LICENSE.txt new file mode 100644 index 000000000..9b2ca37b3 --- /dev/null +++ b/assets/fonts/Inter-LICENSE.txt @@ -0,0 +1,92 @@ +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION AND CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/Inter-Regular.ttf b/assets/fonts/Inter-Regular.ttf new file mode 100644 index 000000000..6d53192d9 Binary files /dev/null and b/assets/fonts/Inter-Regular.ttf differ diff --git a/assets/fonts/Inter-SemiBold.ttf b/assets/fonts/Inter-SemiBold.ttf new file mode 100644 index 000000000..663ee5432 Binary files /dev/null and b/assets/fonts/Inter-SemiBold.ttf differ diff --git a/assets/fonts/JetBrainsMono-LICENSE.txt b/assets/fonts/JetBrainsMono-LICENSE.txt new file mode 100644 index 000000000..675d198b7 --- /dev/null +++ b/assets/fonts/JetBrainsMono-LICENSE.txt @@ -0,0 +1,93 @@ +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/JetBrainsMono-Regular.ttf b/assets/fonts/JetBrainsMono-Regular.ttf new file mode 100644 index 000000000..b4e2da416 Binary files /dev/null and b/assets/fonts/JetBrainsMono-Regular.ttf differ diff --git a/assets/fonts/README.md b/assets/fonts/README.md new file mode 100644 index 000000000..4ef463ae1 --- /dev/null +++ b/assets/fonts/README.md @@ -0,0 +1,11 @@ +# Fonts + +Latin subsets of the user interface fonts, embedded in the executable: + +| File | Font | License | +| --- | --- | --- | +| `Inter-Regular.ttf`, `Inter-SemiBold.ttf` | [Inter](https://rsms.me/inter/) | SIL Open Font License 1.1, see `Inter-LICENSE.txt` | +| `JetBrainsMono-Regular.ttf` | [JetBrains Mono](https://www.jetbrains.com/lp/mono/) | SIL Open Font License 1.1, see `JetBrainsMono-LICENSE.txt` | + +The subsets come from [Fontsource](https://fontsource.org). Characters +outside them fall back to egui's built-in fonts. diff --git a/assets/icons/cadquery_logo_dark.ico b/assets/icons/cadquery_logo_dark.ico new file mode 100644 index 000000000..d48952146 Binary files /dev/null and b/assets/icons/cadquery_logo_dark.ico differ diff --git a/icons/cadquery_logo_dark.svg b/assets/icons/cadquery_logo_dark.svg similarity index 100% rename from icons/cadquery_logo_dark.svg rename to assets/icons/cadquery_logo_dark.svg diff --git a/azure-pipelines.yml b/azure-pipelines.yml deleted file mode 100644 index f245eef53..000000000 --- a/azure-pipelines.yml +++ /dev/null @@ -1,123 +0,0 @@ -trigger: - branches: - include: - - master - - refs/tags/* - exclude: - - refs/tags/nightly - -pr: -- master - -# resources: -# repositories: -# - repository: templates -# type: github -# name: jmwright/conda-packages -# endpoint: CadQuery - -parameters: - - name: minor - type: object - default: - - 11 - - name: location - type: string - default: 'conda' - -stages: -- stage: build_conda_package - jobs: - - ${{ each minor in parameters.minor }}: - - job: Linux_3_${{ minor }} - timeoutInMinutes: 360 - - pool: - vmImage: ubuntu-latest - - steps: - - # this step is needed for OCC to find fonts - - bash: | - sudo apt-get -q -y install gsfonts xfonts-utils && \ - sudo mkfontscale /usr/share/fonts/type1/gsfonts/ && \ - sudo mkfontdir /usr/share/fonts/type1/gsfonts/ - condition: eq( variables['Agent.OS'], 'Linux' ) - displayName: 'Help OCC find fonts' - - # Ubunut install opengl items - - ${{ if contains('ubuntu-latest', 'Ubuntu') }}: - - bash: | - sudo apt-get update && \ - sudo apt-get -q -y install libglu1-mesa-dev freeglut3-dev mesa-common-dev - displayName: 'Install OpenGL headers' - - # install conda for mac - - bash: brew install miniforge && ls /usr/local/Caskroom/miniforge/base/bin - displayName: 'MacOS install miniforge' - condition: eq( variables['Agent.OS'], 'Darwin' ) - - #activate conda - - bash: echo "##vso[task.prependpath]/usr/local/Caskroom/miniforge/base/bin" - condition: eq( variables['Agent.OS'], 'Darwin' ) - displayName: 'Add conda to PATH - OSX' - - - bash: echo "##vso[task.prependpath]$CONDA/bin" - condition: eq( variables['Agent.OS'], 'Linux' ) - displayName: 'Add conda to PATH - Linux' - - - powershell: Write-Host "##vso[task.prependpath]$env:CONDA\Scripts" - condition: eq( variables['Agent.OS'], 'Windows_NT' ) - displayName: 'Add conda to PATH - Windows' - - - powershell: Write-Host "##vso[task.prependpath]$env:CONDA\Library\bin" - condition: eq( variables['Agent.OS'], 'Windows_NT' ) - displayName: 'Add condabin to PATH - Windows' - - # install mamba - - bash: | - conda config --set anaconda_upload yes --set always_yes yes --set solver libmamba && \ - conda config --add channels conda-forge && \ - conda install -c conda-forge -q mamba micromamba conda-devenv libsolv conda-libmamba-solver && \ - env && \ - conda info && \ - conda list - displayName: 'Install mamba, boa; report config and info' - - - bash: conda create --yes --quiet --name build_env -c conda-forge conda-build conda-verify libarchive python=3.12 anaconda-client - displayName: Create Anaconda environment - - - bash: | - cd ${{ parameters.location }} && \ - conda run -n build_env conda-build -c conda-forge -c cadquery --output-folder . . && \ - full_path=$(conda run -n build_env conda-build --output -c conda-forge -c cadquery --output-folder . . ) && \ - echo $full_path && \ - base_name=$(basename $full_path) && \ - split_name=($(IFS=-; tmp=($base_name); echo ${tmp[@]})) && \ - package_name=${split_name[@]: 0 : ${#split_name[@]} - 2} && \ - package_name=${package_name/ /-} && \ - version_name=${split_name[-2]} && \ - echo "Removing $base_name" && \ - conda run -n build_env anaconda -v -t $TOKEN remove --force "cadquery/$package_name/$version_name" && \ - echo "Uploading $full_path" && \ - conda run -n build_env anaconda -v -t $TOKEN upload -u cadquery --force $full_path && \ - cd .. - displayName: 'Run conda build' - failOnStderr: false - condition: ne(variables['Build.Reason'], 'PullRequest') - env: - PYTHON_VERSION: 3.${{ minor }} - PACKAGE_VERSION: $(Build.SourceBranchName) - TOKEN: $(anaconda.TOKEN) - - - bash: | - cd ${{ parameters.location }} && \ - conda run -n build_env conda-build -c conda-forge -c cadquery . && \ - cd .. - displayName: 'Run conda build without upload' - failOnStderr: false - condition: eq(variables['Build.Reason'], 'PullRequest') - env: - PYTHON_VERSION: 3.${{ minor }} - PACKAGE_VERSION: $(Build.SourceBranchName) - TOKEN: $(anaconda.TOKEN) diff --git a/build.rs b/build.rs new file mode 100644 index 000000000..7dcdd5bf5 --- /dev/null +++ b/build.rs @@ -0,0 +1,84 @@ +//! Embeds the Python worker package and the example scripts into the binary, +//! so a release build keeps its worker in sync. Installers bundle the matching +//! Python/CadQuery environment; development and portable builds may use one +//! supplied by the user. + +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use std::{env, fs}; + +fn main() { + let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + let worker = root.join("worker").join("cq_worker"); + let examples = root.join("examples"); + + let mut out = String::from("// @generated by build.rs\n\n"); + write_table(&mut out, "WORKER_FILES", &worker, "cq_worker/"); + write_table(&mut out, "EXAMPLES", &examples, ""); + + let path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("embedded.rs"); + fs::write(path, out).unwrap(); + + println!("cargo:rerun-if-changed=worker/cq_worker"); + println!("cargo:rerun-if-changed=examples"); + windows_resources(); +} + +/// Embeds the icon and version information into the Windows executable, so +/// Explorer shows them (the window icon is set at run time). This needs the +/// resource compiler of the toolchain: `rc.exe` from the Windows SDK, or +/// `windres` from MinGW-w64 binutils. Without it the build succeeds with a +/// warning and a plain executable, unless `CQ_EDITOR_REQUIRE_RESOURCES` is +/// set (release builds), which turns the warning into an error. +fn windows_resources() { + const ICON: &str = "assets/icons/cadquery_logo_dark.ico"; + println!("cargo:rerun-if-changed={ICON}"); + println!("cargo:rerun-if-env-changed=CQ_EDITOR_REQUIRE_RESOURCES"); + #[cfg(windows)] + if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + let mut resource = winresource::WindowsResource::new(); + resource + .set_icon(ICON) + .set("ProductName", "CQ-editor") + // Explorer and the Task Manager show it as the program's name. + .set("FileDescription", "CQ-editor") + .set("OriginalFilename", "cq-editor.exe") + .set("LegalCopyright", "Apache License 2.0"); + if let Err(error) = resource.compile() { + let message = format!( + "The executable has no icon or version information: the resource \ + compiler failed ({error}). Install the Windows SDK, or MinGW-w64 \ + binutils (windres) with gcc on PATH." + ); + if env::var_os("CQ_EDITOR_REQUIRE_RESOURCES").is_some() { + panic!("{message}"); + } + println!("cargo:warning={message}"); + } + } +} + +/// Emits `pub const NAME: &[(&str, &str)]` with every `.py` file of `dir`, +/// sorted by file name, as (prefix + file name, contents). +fn write_table(out: &mut String, name: &str, dir: &Path, prefix: &str) { + let mut files: Vec = fs::read_dir(dir) + .unwrap_or_else(|err| panic!("cannot read {}: {err}", dir.display())) + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "py")) + .collect(); + files.sort(); + + writeln!(out, "pub const {name}: &[(&str, &str)] = &[").unwrap(); + for file in files { + let file_name = file.file_name().unwrap().to_string_lossy(); + writeln!( + out, + " ({:?}, include_str!({:?})),", + format!("{prefix}{file_name}"), + file.display().to_string() + ) + .unwrap(); + println!("cargo:rerun-if-changed={}", file.display()); + } + writeln!(out, "];\n").unwrap(); +} diff --git a/bundle.py b/bundle.py deleted file mode 100644 index abb6aeb33..000000000 --- a/bundle.py +++ /dev/null @@ -1,24 +0,0 @@ -from sys import platform -from path import Path -from os import system -from shutil import make_archive -from cq_editor import __version__ as version - -out_p = Path("dist/CQ-editor") -out_p.rmtree_p() - -build_p = Path("build") -build_p.rmtree_p() - -system("pyinstaller pyinstaller.spec") - -if platform == "linux": - with out_p: - p = Path(".").glob("libpython*")[0] - p.symlink(p.split(".so")[0] + ".so") - - make_archive(f"CQ-editor-{version}-linux64", "bztar", out_p / "..", "CQ-editor") - -elif platform == "win32": - - make_archive(f"CQ-editor-{version}-win64", "zip", out_p / "..", "CQ-editor") diff --git a/changes.md b/changes.md deleted file mode 100644 index c1ab3dced..000000000 --- a/changes.md +++ /dev/null @@ -1,23 +0,0 @@ -# Release 0.5.0 - -* Implemented a dark theme and tweaked it to work better with icons (#490) -* Fixed bug causing the cursor to jump when autoreload was enabled (#496) -* Added a max line length indicator (#495) -* Mentioned work-around for Linux-Wayland users in the readme (#497) -* Fixed bug where dragging over an object while rotating would select the object (#498) -* Changed alpha setting in `show_object` to be consistent with other CadQuery alpha settings (#499) -* Added ability to clear the Log View and Console (#500) -* Started preserving undo history across saves (#501) -* Updated run.sh script to find the real path to the executable (#505) - -# Release 0.4.0 - -* Updated version pins in order to fix some issues, including segfaults on Python 3.12 -* Changed to forcing UTF-8 when saving (#480) -* Added `Toggle Comment` Edit menu item with a `Ctrl+/` hotkey (#481) -* Fixed the case where long exceptions would force the window to expand (#481) -* Add stdout redirect so that print statements could be used and passed to log viewer (#481) -* Improvements in stdout redirect method (#483 and #485) -* Fixed preferences drop downs not populating (#484) -* Fixed double-render calls on saves in some cases (#486) -* Added a lint check to CI and linted codebase (#487) diff --git a/collect_icons.py b/collect_icons.py deleted file mode 100644 index 3f8b6b204..000000000 --- a/collect_icons.py +++ /dev/null @@ -1,29 +0,0 @@ -from glob import glob -from subprocess import call -from os import remove - -TEMPLATE = """ - - {} - -""" - -ITEM_TEMPLATE = "{}" - -QRC_OUT = "icons.qrc" -RES_OUT = "src/icons_res.py" -TOOL = "pyrcc5" - -items = [] - -for i in glob("icons/*.svg"): - items.append(ITEM_TEMPLATE.format(i)) - - -qrc_text = TEMPLATE.format("\n".join(items)) - -with open(QRC_OUT, "w") as f: - f.write(qrc_text) - -call([TOOL, QRC_OUT, "-o", RES_OUT]) -remove(QRC_OUT) diff --git a/conda/construct.yaml b/conda/construct.yaml deleted file mode 100644 index 3955a7b8e..000000000 --- a/conda/construct.yaml +++ /dev/null @@ -1,24 +0,0 @@ -name: CQ-editor -company: Cadquery -version: master -icon_image: ../icons/cadquery_logo_dark.ico -license_file: ../LICENSE -register_python: False -initialize_conda: False -keep_pkgs: False - -channels: - - conda-forge - - cadquery - -specs: - - cq-editor=master - - cadquery=master - - nomkl - - mamba - -menu_packages: [] - -extra_files: - - run.sh # [unix] - - run.bat # [win] diff --git a/conda/meta.yaml b/conda/meta.yaml deleted file mode 100644 index 423d2076b..000000000 --- a/conda/meta.yaml +++ /dev/null @@ -1,37 +0,0 @@ -package: - name: cq-editor - version: {{ environ.get('PACKAGE_VERSION') }} - -source: - path: .. - -build: - string: {{ GIT_DESCRIBE_TAG }}_{{ GIT_BUILD_STR }} - noarch: python - script: python setup.py install --single-version-externally-managed --record=record.txt - entry_points: - - cq-editor = cq_editor.__main__:main - - CQ-editor = cq_editor.__main__:main -requirements: - build: - - python >=3.10 - - setuptools - - run: - - python >=3.10 - - cadquery=master - - ocp - - logbook - - pyqt=5.* - - pyqtgraph - - qtawesome=1.4.0 - - path - - logbook - - requests - - qtconsole >=5.5.1,<5.7.0 -test: - imports: - - cq_editor - -about: -summary: GUI for CadQuery 2 diff --git a/conda/run.bat b/conda/run.bat deleted file mode 100644 index 1fcd35c44..000000000 --- a/conda/run.bat +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -start /B condabin\mamba.bat run -n base python Scripts\cq-editor-script.py diff --git a/conda/run.sh b/conda/run.sh deleted file mode 100755 index 9ecccbc06..000000000 --- a/conda/run.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -exec $(dirname $(realpath "$0"))/bin/cq-editor diff --git a/cq_editor/__init__.py b/cq_editor/__init__.py deleted file mode 100644 index 8dee4bf82..000000000 --- a/cq_editor/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from ._version import __version__ diff --git a/cq_editor/__main__.py b/cq_editor/__main__.py deleted file mode 100644 index 217de2e4d..000000000 --- a/cq_editor/__main__.py +++ /dev/null @@ -1,46 +0,0 @@ -import os -import sys -import argparse - -from PyQt5.QtWidgets import QApplication - -NAME = "CQ-editor" - -# Reorder QT_QPA_PLATFORM so Qt reaches a Wayland plugin only after everything -# else has failed to load, defaulting to xcb. OCCT does not yet support Wayland. -if sys.platform == "linux": - # Desktops such as COSMIC export QT_QPA_PLATFORM="wayland;xcb" session-wide, - # we want to respect this config as far as possible, without using wayland. - plugins = (os.environ.get("QT_QPA_PLATFORM") or "xcb").split(";") - os.environ["QT_QPA_PLATFORM"] = ";".join( - sorted(plugins, key=lambda plugin: plugin.startswith("wayland")) - ) - -# need to initialize QApp here, otherwise svg icons do not work on windows -app = QApplication(sys.argv, applicationName=NAME) - -from .main_window import MainWindow - - -def main(): - - parser = argparse.ArgumentParser(description=NAME) - parser.add_argument("filename", nargs="?", default=None) - - args = parser.parse_args(app.arguments()[1:]) - - # sys.exit(app.exec_()) - - try: - win = MainWindow(filename=args.filename if args.filename else None) - win.show() - app.exec_() - except Exception as e: - import traceback - - traceback.print_exc() - - -if __name__ == "__main__": - - main() diff --git a/cq_editor/_version.py b/cq_editor/_version.py deleted file mode 100644 index 82d720c51..000000000 --- a/cq_editor/_version.py +++ /dev/null @@ -1 +0,0 @@ -__version__ = "0.8.dev0" diff --git a/cq_editor/cq_utils.py b/cq_editor/cq_utils.py deleted file mode 100644 index 95632ab6d..000000000 --- a/cq_editor/cq_utils.py +++ /dev/null @@ -1,238 +0,0 @@ -import cadquery as cq -from cadquery.occ_impl.assembly import toCAF - -from typing import List, Union -from importlib import reload -from types import SimpleNamespace - -from OCP.XCAFPrs import XCAFPrs_AISObject -from OCP.TopoDS import TopoDS_Shape -from OCP.AIS import AIS_InteractiveObject, AIS_Shape -from OCP.Quantity import ( - Quantity_TOC_RGB as TOC_RGB, - Quantity_Color, - Quantity_NOC_GOLD as GOLD, -) -from OCP.Graphic3d import Graphic3d_NOM_JADE, Graphic3d_MaterialAspect -from OCP.Prs3d import Prs3d_LineAspect -from OCP.Aspect import Aspect_TOL_SOLID - -from PyQt5.QtGui import QColor - -DEFAULT_FACE_COLOR = Quantity_Color(GOLD) -DEFAULT_MATERIAL = Graphic3d_MaterialAspect(Graphic3d_NOM_JADE) - - -def is_cq_obj(obj): - - from cadquery import Workplane, Shape, Assembly, Sketch - - return isinstance(obj, (Workplane, Shape, Assembly, Sketch)) - - -def find_cq_objects(results: dict): - - return { - k: SimpleNamespace(shape=v, options={}) - for k, v in results.items() - if is_cq_obj(v) - } - - -def to_compound( - obj: Union[cq.Workplane, List[cq.Workplane], cq.Shape, List[cq.Shape], cq.Sketch], -): - - vals = [] - - if isinstance(obj, cq.Workplane): - vals.extend(obj.vals()) - elif isinstance(obj, cq.Shape): - vals.append(obj) - elif isinstance(obj, list) and not obj: - pass # an empty list produces an empty compound (see #600) - elif isinstance(obj, list) and isinstance(obj[0], cq.Workplane): - for o in obj: - vals.extend(o.vals()) - elif isinstance(obj, list) and isinstance(obj[0], cq.Shape): - vals.extend(obj) - elif isinstance(obj, TopoDS_Shape): - vals.append(cq.Shape.cast(obj)) - elif isinstance(obj, list) and isinstance(obj[0], TopoDS_Shape): - vals.extend(cq.Shape.cast(o) for o in obj) - elif isinstance(obj, cq.Sketch): - vals.extend(obj) - else: - raise ValueError(f"Invalid type {type(obj)}") - - return cq.Compound.makeCompound(vals) - - -def to_workplane(obj: cq.Shape): - - rv = cq.Workplane("XY") - rv.objects = [ - obj, - ] - - return rv - - -def make_AIS( - obj: Union[ - cq.Workplane, - List[cq.Workplane], - cq.Shape, - List[cq.Shape], - cq.Assembly, - AIS_InteractiveObject, - ], - options={}, -): - - shape = None - - if isinstance(obj, cq.Assembly): - label, shape = toCAF(obj) - ais = XCAFPrs_AISObject(label) - elif isinstance(obj, AIS_InteractiveObject): - ais = obj - else: - shape = to_compound(obj) - ais = AIS_Shape(shape.wrapped) - - set_material(ais, DEFAULT_MATERIAL) - set_color(ais, DEFAULT_FACE_COLOR) - - if "alpha" in options: - set_transparency(ais, options["alpha"]) - if "color" in options: - set_color(ais, to_occ_color(options["color"])) - if "rgba" in options: - r, g, b, a = options["rgba"] - set_color(ais, to_occ_color((r, g, b))) - set_transparency(ais, a) - if "edgecolor" in options: - set_edge_color(ais, to_occ_color(options["edgecolor"])) - - return ais, shape - - -def export( - obj: Union[cq.Workplane, List[cq.Workplane]], type: str, file, precision=1e-1 -): - - comp = to_compound(obj) - - if type == "stl": - comp.exportStl(file, tolerance=precision) - elif type == "step": - comp.exportStep(file) - elif type == "brep": - comp.exportBrep(file) - - -def to_occ_color(color) -> Quantity_Color: - - if not isinstance(color, QColor): - if isinstance(color, tuple): - if isinstance(color[0], int): - color = QColor(*color) - elif isinstance(color[0], float): - color = QColor.fromRgbF(*color) - else: - raise ValueError("Unknown color format") - else: - color = QColor(color) - - return Quantity_Color(color.redF(), color.greenF(), color.blueF(), TOC_RGB) - - -def get_occ_color(obj: Union[AIS_InteractiveObject, Quantity_Color]) -> QColor: - - if isinstance(obj, AIS_InteractiveObject): - color = Quantity_Color() - obj.Color(color) - else: - color = obj - - return QColor.fromRgbF(color.Red(), color.Green(), color.Blue()) - - -def set_color(ais: AIS_Shape, color: Quantity_Color) -> AIS_Shape: - - drawer = ais.Attributes() - drawer.SetupOwnShadingAspect() - drawer.ShadingAspect().SetColor(color) - - return ais - - -def set_edge_color(ais: AIS_Shape, color: Quantity_Color) -> AIS_Shape: - """ - Sets edge color to a non-default independently of face color. - """ - - drawer = ais.Attributes() - drawer.SetFaceBoundaryDraw(True) - face_boundary_aspect = drawer.FaceBoundaryAspect() - if face_boundary_aspect is None: - face_boundary_aspect = Prs3d_LineAspect(color, Aspect_TOL_SOLID, 2.0) - drawer.SetFaceBoundaryAspect(face_boundary_aspect) - face_boundary_aspect.SetColor(color) - - return ais - - -def set_material(ais: AIS_Shape, material: Graphic3d_MaterialAspect) -> AIS_Shape: - - drawer = ais.Attributes() - drawer.SetupOwnShadingAspect() - drawer.ShadingAspect().SetMaterial(material) - - return ais - - -def set_transparency(ais: AIS_Shape, alpha: float) -> AIS_Shape: - - drawer = ais.Attributes() - drawer.SetupOwnShadingAspect() - drawer.ShadingAspect().SetTransparency(1.0 - alpha) - - return ais - - -def reload_cq(): - - # NB: order of reloads is important - reload(cq.types) - reload(cq.occ_impl.geom) - reload(cq.occ_impl.shapes) - reload(cq.occ_impl.shapes) - reload(cq.occ_impl.importers.dxf) - reload(cq.occ_impl.importers) - reload(cq.occ_impl.solver) - reload(cq.occ_impl.assembly) - reload(cq.occ_impl.sketch_solver) - reload(cq.hull) - reload(cq.selectors) - reload(cq.sketch) - reload(cq.occ_impl.exporters.svg) - reload(cq.cq) - reload(cq.occ_impl.exporters.dxf) - reload(cq.occ_impl.exporters.amf) - reload(cq.occ_impl.exporters.json) - # reload(cq.occ_impl.exporters.assembly) - reload(cq.occ_impl.exporters) - reload(cq.assembly) - reload(cq) - - -def is_obj_empty(obj: Union[cq.Workplane, cq.Shape]) -> bool: - - rv = False - - if isinstance(obj, cq.Workplane): - rv = True if isinstance(obj.val(), cq.Vector) else False - - return rv diff --git a/cq_editor/cqe_run.py b/cq_editor/cqe_run.py deleted file mode 100644 index 622bd9ef6..000000000 --- a/cq_editor/cqe_run.py +++ /dev/null @@ -1,12 +0,0 @@ -import os, sys, asyncio - -if "CASROOT" in os.environ: - del os.environ["CASROOT"] - -if sys.platform == "win32": - asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) - -from cq_editor.__main__ import main - -if __name__ == "__main__": - main() diff --git a/cq_editor/icons.py b/cq_editor/icons.py deleted file mode 100644 index 6b6440b1d..000000000 --- a/cq_editor/icons.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Created on Fri May 25 14:47:10 2018 - -@author: adam -""" - -from PyQt5.QtGui import QIcon - -from . import icons_res - -_icons = {"app": QIcon(":/images/icons/cadquery_logo_dark.svg")} - -import qtawesome as qta - -_icons_specs = { - "new": (("fa5.file",), {}), - "open": (("fa5.folder-open",), {}), - # borrowed from spider-ide - "autoreload": [ - ("fa5s.redo-alt", "fa5.clock"), - { - "options": [ - {"scale_factor": 0.75, "offset": (-0.1, -0.1)}, - {"scale_factor": 0.5, "offset": (0.25, 0.25)}, - ] - }, - ], - "save": (("fa5.save",), {}), - "save_as": ( - ("fa5.save", "fa5s.pencil-alt"), - { - "options": [ - { - "scale_factor": 1, - }, - {"scale_factor": 0.8, "offset": (0.2, 0.2)}, - ] - }, - ), - "run": (("fa5s.play",), {}), - "debug": (("fa5s.bug",), {}), - "delete": (("fa5s.trash",), {}), - "delete-many": ( - ( - "fa5s.trash", - "fa5s.trash", - ), - { - "options": [ - {"scale_factor": 0.8, "offset": (0.2, 0.2), "color": "gray"}, - {"scale_factor": 0.8}, - ] - }, - ), - "help": (("fa5s.life-ring",), {}), - "about": (("fa5s.info",), {}), - "preferences": (("fa5s.cogs",), {}), - "inspect": ( - ("fa5s.cubes", "fa5s.search"), - {"options": [{"scale_factor": 0.8, "offset": (0, 0), "color": "gray"}, {}]}, - ), - "screenshot": (("fa5s.camera",), {}), - "screenshot-save": ( - ("fa5.save", "fa5s.camera"), - { - "options": [ - {"scale_factor": 0.8}, - {"scale_factor": 0.8, "offset": (0.2, 0.2)}, - ] - }, - ), - "toggle-comment": (("fa5s.hashtag",), {}), - "search": (("fa5s.search",), {}), - "arrow-step-over": (("fa5s.step-forward",), {}), - "arrow-step-in": (("fa5s.angle-down",), {}), - "arrow-continue": (("fa5s.arrow-right",), {}), - "clear": (("fa5s.eraser",), {}), - "clear-2": (("fa5s.broom",), {}), -} - - -def icon(name): - - if name in _icons: - return _icons[name] - - args, kwargs = _icons_specs[name] - - return qta.icon(*args, **kwargs) diff --git a/cq_editor/icons_res.py b/cq_editor/icons_res.py deleted file mode 100644 index b7f3f8932..000000000 --- a/cq_editor/icons_res.py +++ /dev/null @@ -1,9123 +0,0 @@ -# -*- coding: utf-8 -*- - -# Resource object code -# -# Created by: The Resource Compiler for PyQt5 (Qt v5.6.2) -# -# WARNING! All changes made in this file will be lost! - -from PyQt5 import QtCore - -qt_resource_data = b"\ -\x00\x00\x4e\x4c\ -\x3c\ -\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ -\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ -\x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ -\x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ -\x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ -\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ -\x3c\x73\x76\x67\x20\x69\x64\x3d\x22\x73\x76\x67\x32\x22\x20\x78\ -\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\ -\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\x39\ -\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\x2d\x73\x79\x6e\x74\x61\ -\x78\x2d\x6e\x73\x23\x22\x20\x78\x6d\x6c\x6e\x73\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x68\x65\x69\x67\x68\x74\ -\x3d\x22\x32\x33\x2e\x39\x39\x34\x22\x20\x77\x69\x64\x74\x68\x3d\ -\x22\x32\x30\x2e\x39\x36\x31\x22\x20\x76\x65\x72\x73\x69\x6f\x6e\ -\x3d\x22\x31\x2e\x31\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\x3d\ -\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\x65\ -\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\x22\ -\x20\x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x31\x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x76\x69\x65\x77\ -\x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x30\x2e\x39\x36\x30\x37\ -\x38\x34\x20\x32\x33\x2e\x39\x39\x33\x35\x39\x31\x22\x20\x78\x6d\ -\x6c\x6e\x73\x3a\x64\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\ -\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\ -\x6e\x74\x73\x2f\x31\x2e\x31\x2f\x22\x3e\x0a\x20\x3c\x6d\x65\x74\ -\x61\x64\x61\x74\x61\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ -\x74\x61\x37\x22\x3e\x0a\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\ -\x3e\x0a\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x20\x72\x64\ -\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\ -\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\ -\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\ -\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ -\x65\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\ -\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\ -\x6c\x49\x6d\x61\x67\x65\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x64\ -\x63\x3a\x74\x69\x74\x6c\x65\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x63\ -\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x3c\x2f\x72\x64\x66\x3a\ -\x52\x44\x46\x3e\x0a\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ -\x3e\x0a\x20\x3c\x67\x20\x69\x64\x3d\x22\x6c\x61\x79\x65\x72\x31\ -\x22\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x74\x72\x61\ -\x6e\x73\x6c\x61\x74\x65\x28\x2d\x31\x35\x30\x37\x2e\x36\x20\x35\ -\x36\x36\x2e\x38\x34\x29\x22\x3e\x0a\x20\x20\x3c\x67\x20\x66\x69\ -\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\ -\x36\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x3e\ -\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x33\x36\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\ -\x2e\x33\x2d\x35\x35\x33\x2e\x32\x39\x63\x30\x2d\x34\x2e\x33\x34\ -\x33\x31\x20\x30\x2e\x30\x31\x31\x2d\x35\x2e\x34\x32\x34\x33\x20\ -\x30\x2e\x30\x36\x2d\x35\x2e\x34\x32\x34\x33\x20\x30\x2e\x30\x36\ -\x31\x20\x30\x20\x38\x2e\x33\x34\x31\x39\x20\x31\x2e\x38\x31\x33\ -\x32\x20\x38\x2e\x33\x35\x35\x39\x20\x31\x2e\x38\x32\x39\x37\x20\ -\x30\x20\x30\x20\x30\x2e\x30\x32\x34\x20\x30\x2e\x36\x32\x30\x34\ -\x33\x20\x30\x2e\x30\x34\x32\x20\x31\x2e\x33\x36\x37\x33\x6c\x30\ -\x2e\x30\x33\x34\x20\x31\x2e\x33\x35\x37\x39\x2d\x34\x2e\x32\x34\ -\x35\x38\x20\x33\x2e\x31\x34\x36\x39\x2d\x34\x2e\x32\x34\x35\x39\ -\x20\x33\x2e\x31\x34\x36\x39\x76\x2d\x35\x2e\x34\x32\x34\x33\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x35\x33\x38\x22\x20\x64\x3d\x22\x6d\x31\ -\x35\x31\x32\x2e\x38\x2d\x35\x35\x38\x2e\x36\x34\x63\x2d\x32\x2e\ -\x31\x37\x39\x34\x2d\x30\x2e\x34\x36\x37\x31\x33\x2d\x33\x2e\x39\ -\x39\x35\x32\x2d\x30\x2e\x38\x35\x36\x31\x33\x2d\x34\x2e\x30\x33\ -\x35\x2d\x30\x2e\x38\x36\x34\x35\x35\x2d\x30\x2e\x30\x33\x39\x2d\ -\x30\x2e\x30\x31\x30\x37\x20\x31\x2e\x37\x32\x39\x34\x2d\x31\x2e\ -\x33\x38\x32\x39\x20\x33\x2e\x39\x33\x31\x34\x2d\x33\x2e\x30\x35\ -\x34\x36\x20\x32\x2e\x32\x30\x32\x32\x2d\x31\x2e\x36\x37\x31\x36\ -\x20\x34\x2e\x30\x31\x31\x39\x2d\x33\x2e\x30\x33\x31\x36\x20\x34\ -\x2e\x30\x32\x31\x36\x2d\x33\x2e\x30\x32\x32\x32\x20\x30\x2e\x30\ -\x32\x31\x20\x30\x2e\x30\x31\x39\x32\x20\x30\x2e\x31\x36\x39\x31\ -\x20\x36\x2e\x33\x37\x38\x37\x20\x30\x2e\x31\x36\x39\x34\x20\x37\ -\x2e\x32\x34\x31\x31\x20\x30\x2e\x30\x30\x30\x32\x20\x30\x2e\x34\ -\x31\x38\x38\x39\x2d\x30\x2e\x30\x31\x34\x20\x30\x2e\x35\x35\x38\ -\x34\x37\x2d\x30\x2e\x30\x36\x32\x20\x30\x2e\x35\x35\x34\x36\x34\ -\x2d\x30\x2e\x30\x33\x35\x20\x30\x2d\x31\x2e\x38\x34\x35\x36\x2d\ -\x30\x2e\x33\x38\x37\x33\x31\x2d\x34\x2e\x30\x32\x35\x33\x2d\x30\ -\x2e\x38\x35\x34\x34\x33\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x30\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x35\x39\x2e\x34\x2d\x35\x34\x35\ -\x2e\x34\x33\x63\x2d\x33\x2e\x33\x32\x36\x32\x2d\x30\x2e\x39\x32\ -\x33\x32\x33\x2d\x36\x2e\x31\x37\x37\x38\x2d\x31\x2e\x37\x31\x33\ -\x33\x2d\x36\x2e\x33\x33\x36\x38\x2d\x31\x2e\x37\x35\x35\x37\x2d\ -\x30\x2e\x32\x37\x38\x31\x2d\x30\x2e\x30\x37\x34\x34\x2d\x30\x2e\ -\x31\x32\x30\x39\x2d\x30\x2e\x32\x30\x32\x37\x39\x20\x34\x2e\x30\ -\x31\x35\x31\x2d\x33\x2e\x32\x38\x38\x37\x20\x32\x2e\x33\x36\x37\ -\x36\x2d\x31\x2e\x37\x36\x36\x35\x20\x34\x2e\x33\x37\x30\x31\x2d\ -\x33\x2e\x32\x30\x35\x39\x20\x34\x2e\x34\x35\x30\x32\x2d\x33\x2e\ -\x31\x39\x38\x35\x20\x30\x2e\x30\x38\x20\x30\x2e\x30\x31\x30\x38\ -\x20\x31\x2e\x30\x33\x33\x34\x20\x30\x2e\x32\x37\x35\x34\x32\x20\ -\x32\x2e\x31\x31\x38\x38\x20\x30\x2e\x35\x39\x35\x38\x37\x20\x31\ -\x2e\x30\x38\x35\x34\x20\x30\x2e\x33\x32\x30\x35\x37\x20\x31\x2e\ -\x39\x38\x38\x39\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x32\x2e\x30\ -\x30\x37\x38\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x30\x2e\x30\x31\ -\x39\x20\x30\x20\x30\x2e\x30\x33\x35\x20\x31\x2e\x39\x36\x39\x39\ -\x20\x30\x2e\x30\x33\x35\x20\x34\x2e\x33\x37\x37\x35\x20\x30\x20\ -\x33\x2e\x34\x34\x31\x31\x2d\x30\x2e\x30\x32\x36\x20\x34\x2e\x33\ -\x37\x36\x33\x2d\x30\x2e\x31\x32\x30\x39\x20\x34\x2e\x33\x37\x31\ -\x35\x2d\x30\x2e\x30\x36\x36\x20\x30\x2d\x32\x2e\x38\x34\x32\x34\ -\x2d\x30\x2e\x37\x36\x31\x32\x37\x2d\x36\x2e\x31\x36\x38\x35\x2d\ -\x31\x2e\x36\x38\x34\x36\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x32\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\x2e\x39\x2d\x35\x34\x38\ -\x2e\x30\x39\x63\x30\x2d\x32\x2e\x31\x37\x33\x35\x20\x30\x2e\x30\ -\x32\x2d\x33\x2e\x39\x35\x31\x38\x20\x30\x2e\x30\x34\x37\x2d\x33\ -\x2e\x39\x35\x31\x38\x20\x30\x2e\x31\x30\x36\x31\x20\x30\x20\x35\ -\x2e\x32\x33\x37\x20\x31\x2e\x35\x30\x34\x31\x20\x35\x2e\x32\x38\ -\x32\x36\x20\x31\x2e\x35\x34\x38\x37\x20\x30\x2e\x30\x33\x35\x20\ -\x30\x2e\x30\x33\x35\x2d\x34\x2e\x34\x39\x35\x20\x35\x2e\x34\x34\ -\x35\x32\x2d\x35\x2e\x32\x34\x32\x20\x36\x2e\x32\x35\x39\x33\x2d\ -\x30\x2e\x30\x34\x38\x20\x30\x2e\x30\x35\x33\x2d\x30\x2e\x30\x38\ -\x38\x2d\x31\x2e\x36\x36\x39\x35\x2d\x30\x2e\x30\x38\x38\x2d\x33\ -\x2e\x38\x35\x36\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\x35\x35\x33\x2e\ -\x38\x2d\x31\x2e\x37\x38\x30\x33\x2d\x30\x2e\x35\x33\x32\x39\x76\ -\x2d\x31\x2e\x31\x37\x38\x37\x63\x30\x2d\x31\x2e\x31\x36\x31\x37\ -\x20\x30\x2d\x31\x2e\x31\x37\x38\x20\x30\x2e\x32\x30\x35\x34\x2d\ -\x31\x2e\x31\x32\x35\x32\x20\x30\x2e\x31\x31\x32\x38\x20\x30\x2e\ -\x30\x32\x39\x39\x20\x30\x2e\x39\x34\x36\x20\x30\x2e\x32\x31\x35\ -\x38\x38\x20\x31\x2e\x38\x35\x31\x36\x20\x30\x2e\x34\x31\x33\x39\ -\x31\x6c\x31\x2e\x36\x34\x36\x31\x20\x30\x2e\x33\x36\x30\x32\x39\ -\x76\x31\x2e\x33\x30\x36\x33\x63\x30\x20\x30\x2e\x37\x31\x38\x34\ -\x36\x2d\x30\x2e\x30\x33\x32\x20\x31\x2e\x33\x30\x32\x34\x2d\x30\ -\x2e\x30\x37\x32\x20\x31\x2e\x32\x39\x37\x38\x2d\x30\x2e\x30\x33\ -\x39\x20\x30\x2d\x30\x2e\x38\x37\x32\x33\x2d\x30\x2e\x32\x34\x38\ -\x33\x32\x2d\x31\x2e\x38\x35\x31\x36\x2d\x30\x2e\x35\x34\x31\x35\ -\x32\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x31\x30\x2e\x38\x2d\x35\x35\x32\x2e\x31\x38\x2d\x32\ -\x2e\x36\x38\x31\x31\x2d\x30\x2e\x37\x38\x35\x33\x34\x76\x2d\x31\ -\x2e\x36\x35\x39\x33\x2d\x31\x2e\x36\x35\x39\x33\x6c\x32\x2e\x36\ -\x31\x37\x32\x2d\x32\x2e\x38\x38\x36\x33\x63\x31\x2e\x34\x33\x39\ -\x34\x2d\x31\x2e\x35\x38\x37\x35\x20\x32\x2e\x36\x37\x37\x34\x2d\ -\x32\x2e\x39\x34\x36\x38\x20\x32\x2e\x37\x35\x30\x39\x2d\x33\x2e\ -\x30\x32\x30\x36\x20\x30\x2e\x31\x31\x36\x32\x2d\x30\x2e\x31\x31\ -\x36\x36\x34\x20\x30\x2e\x31\x33\x33\x38\x20\x30\x2e\x35\x38\x33\ -\x37\x39\x20\x30\x2e\x31\x33\x33\x38\x20\x35\x2e\x33\x33\x39\x39\ -\x20\x30\x20\x33\x2e\x30\x31\x30\x38\x20\x30\x2e\x31\x30\x30\x33\ -\x20\x35\x2e\x35\x30\x32\x34\x20\x30\x2e\x30\x36\x31\x20\x35\x2e\ -\x34\x39\x37\x36\x2d\x30\x2e\x30\x33\x39\x20\x30\x2d\x31\x2e\x34\ -\x30\x38\x2d\x30\x2e\x33\x39\x34\x36\x34\x2d\x32\x2e\x38\x38\x32\ -\x34\x2d\x30\x2e\x38\x32\x36\x35\x39\x7a\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x39\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\ -\x35\x35\x37\x2e\x31\x34\x2d\x31\x2e\x37\x31\x34\x37\x2d\x30\x2e\ -\x33\x39\x33\x38\x33\x2d\x30\x2e\x30\x35\x38\x2d\x32\x2e\x32\x32\ -\x36\x34\x63\x2d\x30\x2e\x30\x39\x36\x2d\x33\x2e\x37\x34\x33\x32\ -\x2d\x30\x2e\x32\x31\x38\x33\x2d\x35\x2e\x39\x33\x31\x39\x2d\x30\ -\x2e\x31\x31\x34\x37\x2d\x35\x2e\x39\x33\x31\x39\x20\x30\x2e\x31\ -\x33\x35\x20\x30\x20\x39\x2e\x34\x39\x39\x35\x20\x32\x2e\x32\x35\ -\x31\x39\x20\x39\x2e\x37\x30\x33\x31\x20\x32\x2e\x33\x33\x36\x37\ -\x20\x30\x2e\x31\x34\x32\x35\x20\x30\x2e\x30\x35\x39\x34\x2d\x30\ -\x2e\x32\x39\x37\x33\x20\x30\x2e\x35\x39\x35\x36\x39\x2d\x32\x2e\ -\x37\x32\x35\x32\x20\x33\x2e\x33\x32\x35\x31\x2d\x32\x2e\x33\x31\ -\x31\x39\x20\x32\x2e\x35\x39\x39\x2d\x32\x2e\x39\x34\x33\x32\x20\ -\x33\x2e\x32\x35\x37\x34\x2d\x33\x2e\x31\x33\x35\x39\x20\x33\x2e\ -\x32\x36\x39\x32\x2d\x30\x2e\x31\x33\x32\x36\x20\x30\x2e\x30\x31\ -\x30\x34\x2d\x31\x2e\x30\x31\x32\x38\x2d\x30\x2e\x31\x36\x32\x32\ -\x35\x2d\x31\x2e\x39\x35\x36\x2d\x30\x2e\x33\x37\x38\x38\x32\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x67\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\ -\x35\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x36\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x32\ -\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\ -\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\ -\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x34\x39\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x33\ -\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\ -\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x39\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x30\x2e\x38\x35\x39\x20\x33\x2e\x30\x33\x30\ -\x34\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x32\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x38\x2e\x39\x2d\ -\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\ -\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\ -\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ -\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x32\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\ -\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\ -\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x33\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\ -\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x34\x31\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x34\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\ -\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\ -\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x35\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\ -\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x37\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x36\x2e\x39\x2d\x35\x36\x36\x2e\ -\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\ -\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x38\x31\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x37\x2e\x32\x2d\x35\x35\x33\x2e\ -\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x3e\x0a\ -\x20\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x30\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x35\ -\x36\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\ -\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\ -\x37\x33\x32\x2e\x31\x2d\x35\x30\x37\x2e\x36\x34\x20\x31\x33\x38\ -\x2e\x35\x36\x2d\x38\x30\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\ -\x2d\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x2d\x31\x33\x38\x2e\x35\ -\x36\x2d\x38\x30\x76\x31\x36\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x35\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x37\x33\x32\x2e\x31\x2d\x33\x34\x37\x2e\x36\x34\x20\ -\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x38\x37\x30\x2e\x36\x2d\x32\x36\x37\x2e\x36\x34\x20\x31\x33\ -\x38\x2e\x35\x36\x2d\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x32\x36\x32\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x35\x38\x37\ -\x2e\x36\x34\x76\x31\x36\x30\x6c\x2d\x31\x33\x38\x2e\x35\x36\x20\ -\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x34\x22\x20\ -\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x34\x32\x37\x2e\x36\ -\x34\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x36\x36\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x2d\x38\x30\x20\x38\x30\ -\x20\x38\x30\x20\x38\x30\x20\x38\x30\x2d\x38\x30\x7a\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x37\x30\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x37\x32\x37\x2e\x36\x34\x76\x38\x30\x6c\x38\x30\ -\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x32\x37\x32\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x36\x34\ -\x37\x2e\x36\x34\x2d\x38\x30\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x37\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x76\x38\x30\x6c\x2d\ -\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x37\ -\x36\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x38\x30\x37\x2e\ -\x36\x34\x20\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x30\x22\x20\x64\x3d\x22\x6d\x32\x32\x35\x32\x2e\x39\ -\x2d\x39\x36\x37\x2e\x36\x34\x2d\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x76\x31\x36\x30\x6c\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x38\x32\x22\x20\x64\x3d\ -\x22\x6d\x32\x30\x38\x38\x2e\x31\x2d\x39\x30\x37\x2e\x36\x34\x2d\ -\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\ -\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x39\x32\x33\x2e\x32\x2d\x39\x36\x37\x2e\x36\x34\x76\x31\x36\x30\ -\x6c\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x32\x38\x36\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\ -\x2e\x31\x2d\x31\x30\x32\x37\x2e\x36\x76\x31\x36\x30\x6c\x2d\x31\ -\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x38\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\x2e\x31\ -\x2d\x38\x36\x37\x2e\x36\x34\x20\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x3c\x67\x20\x73\ -\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\ -\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x33\x32\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x31\x38\x38\x2e\x31\x2d\x33\x34\x31\x2e\x36\x37\x20\x31\x35\ -\x33\x2e\x33\x31\x2d\x37\x31\x2e\x34\x38\x38\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x2d\x31\x35\x33\x2e\x33\x31\ -\x20\x37\x31\x2e\x34\x38\x38\x2d\x31\x35\x33\x2e\x33\x31\x2d\x38\ -\x38\x2e\x35\x31\x32\x76\x31\x36\x30\x6c\x31\x35\x33\x2e\x33\x31\ -\x20\x38\x38\x2e\x35\x31\x32\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x39\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\x33\x31\ -\x2d\x37\x31\x2e\x34\x38\x38\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x34\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x34\x31\x33\x2e\x31\x36\x76\x31\x36\x30\x6c\x2d\ -\x31\x35\x33\x2e\x33\x31\x20\x37\x31\x2e\x34\x38\x38\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x32\x36\x22\x20\x64\x3d\x22\x6d\x31\x33\ -\x34\x31\x2e\x34\x2d\x32\x35\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\ -\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x20\x69\x64\ -\x3d\x22\x69\x6d\x61\x67\x65\x34\x33\x33\x36\x22\x20\x73\x74\x79\ -\x6c\x65\x3d\x22\x69\x6d\x61\x67\x65\x2d\x72\x65\x6e\x64\x65\x72\ -\x69\x6e\x67\x3a\x6f\x70\x74\x69\x6d\x69\x7a\x65\x53\x70\x65\x65\ -\x64\x22\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\ -\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\ -\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\ -\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x52\x38\ -\x41\x41\x41\x41\x70\x43\x41\x59\x41\x41\x41\x41\x4d\x41\x79\x31\ -\x4a\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\ -\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x48\x69\x68\x4a\x52\x45\x46\ -\x55\x20\x65\x4a\x7a\x74\x6e\x58\x64\x34\x56\x46\x58\x36\x78\x7a\ -\x2f\x54\x61\x7a\x4b\x54\x6d\x55\x6b\x6a\x6a\x59\x54\x51\x51\x69\ -\x67\x4b\x32\x43\x6c\x57\x31\x72\x35\x59\x31\x37\x4a\x69\x58\x63\ -\x74\x61\x31\x72\x61\x75\x5a\x58\x55\x74\x61\x2f\x6e\x70\x36\x75\ -\x34\x71\x72\x67\x58\x64\x74\x61\x30\x67\x43\x77\x49\x57\x20\x6d\ -\x6f\x41\x46\x6b\x43\x49\x6c\x51\x41\x67\x51\x45\x6b\x68\x49\x53\ -\x47\x2f\x54\x35\x39\x62\x66\x48\x78\x4d\x69\x4a\x59\x48\x41\x44\ -\x50\x43\x48\x38\x33\x6d\x65\x50\x44\x79\x5a\x4f\x2b\x66\x65\x62\ -\x30\x35\x35\x7a\x7a\x6e\x76\x2b\x39\x36\x44\x35\x73\x55\x58\x58\ -\x6c\x42\x4a\x6b\x43\x42\x42\x67\x6d\x4f\x4d\x20\x50\x69\x4d\x7a\ -\x34\x33\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x66\x55\x46\x2b\ -\x2f\x76\x48\x57\x6b\x43\x42\x42\x67\x6c\x38\x67\x65\x72\x66\x62\ -\x66\x62\x77\x31\x4a\x45\x69\x51\x34\x42\x65\x49\x50\x6a\x6b\x35\ -\x2b\x58\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x76\x64\x56\x71\ -\x50\x64\x34\x61\x45\x69\x52\x49\x20\x38\x41\x74\x45\x62\x7a\x41\ -\x59\x59\x72\x71\x42\x4a\x4d\x76\x38\x38\x36\x74\x76\x6d\x4c\x31\ -\x36\x50\x58\x6b\x65\x4e\x34\x4e\x7a\x4d\x68\x6d\x63\x6e\x55\x6d\ -\x2f\x6a\x48\x52\x79\x33\x43\x6b\x34\x62\x66\x45\x7a\x62\x6b\x32\ -\x4e\x44\x57\x54\x6e\x35\x42\x47\x4a\x68\x4f\x4e\x32\x7a\x34\x72\ -\x36\x52\x6e\x34\x6f\x20\x4b\x79\x66\x50\x34\x79\x4c\x4c\x6e\x55\ -\x4b\x47\x30\x30\x47\x79\x31\x52\x4b\x33\x2b\x78\x38\x75\x4e\x53\ -\x31\x74\x31\x44\x53\x33\x6b\x75\x5a\x49\x4a\x74\x32\x5a\x6a\x4d\ -\x31\x73\x4f\x6d\x35\x61\x41\x46\x5a\x73\x72\x65\x43\x37\x7a\x56\ -\x76\x4a\x38\x37\x6a\x4a\x54\x2f\x65\x51\x6b\x65\x49\x6b\x7a\x5a\ -\x47\x4d\x20\x78\x52\x68\x62\x76\x39\x6d\x66\x6f\x39\x47\x32\x4b\ -\x37\x5a\x57\x38\x4e\x58\x61\x44\x65\x53\x6e\x65\x52\x69\x51\x6d\ -\x55\x47\x4b\x33\x55\x5a\x75\x71\x6f\x73\x6b\x69\x7a\x6c\x75\x7a\ -\x7a\x68\x63\x50\x63\x65\x69\x4c\x6e\x76\x4c\x6b\x6f\x31\x6c\x7a\ -\x46\x75\x2f\x69\x56\x79\x33\x6d\x33\x34\x5a\x71\x66\x52\x78\x20\ -\x70\x35\x44\x75\x53\x4d\x4b\x54\x6c\x49\x52\x4f\x70\x34\x33\x62\ -\x63\x33\x70\x71\x57\x33\x30\x73\x4e\x32\x31\x6f\x37\x2b\x44\x78\ -\x54\x32\x61\x69\x4e\x78\x69\x35\x61\x50\x53\x4a\x58\x44\x76\x2b\ -\x4e\x45\x71\x72\x61\x79\x69\x74\x72\x6d\x58\x42\x68\x69\x33\x73\ -\x61\x6d\x70\x42\x72\x39\x57\x53\x35\x58\x49\x77\x20\x73\x45\x38\ -\x6d\x52\x54\x6d\x5a\x46\x47\x61\x6b\x34\x55\x36\x32\x59\x7a\x63\ -\x66\x6e\x77\x36\x77\x42\x31\x6c\x52\x2b\x47\x4c\x31\x65\x6c\x36\ -\x66\x75\x34\x51\x42\x57\x52\x6e\x73\x62\x47\x36\x6a\x75\x71\x6d\ -\x46\x68\x76\x59\x4f\x6a\x46\x6f\x64\x47\x63\x35\x6b\x63\x6c\x50\ -\x64\x46\x47\x61\x6d\x4d\x69\x41\x7a\x20\x67\x33\x52\x6e\x4d\x6b\ -\x6b\x57\x4d\x31\x61\x54\x45\x59\x31\x47\x45\x33\x63\x39\x6b\x69\ -\x7a\x7a\x78\x55\x38\x6c\x50\x44\x5a\x6a\x4c\x71\x30\x36\x45\x79\ -\x5a\x46\x77\x6f\x61\x4d\x78\x32\x4b\x68\x77\x4a\x4e\x43\x51\x61\ -\x71\x62\x2f\x44\x51\x50\x2b\x52\x6d\x70\x35\x48\x6c\x63\x58\x56\ -\x70\x4d\x4d\x55\x34\x65\x20\x50\x52\x45\x57\x52\x4e\x35\x64\x2b\ -\x44\x31\x66\x72\x39\x76\x49\x4f\x53\x4f\x4b\x61\x51\x38\x4c\x7a\ -\x46\x68\x56\x51\x6c\x31\x72\x47\x38\x30\x64\x50\x6d\x77\x57\x45\ -\x2b\x6e\x4a\x79\x57\x53\x37\x6e\x66\x54\x50\x54\x4b\x4d\x67\x50\ -\x59\x32\x4d\x46\x41\x63\x4f\x71\x2b\x57\x34\x47\x38\x77\x39\x32\ -\x71\x66\x2f\x20\x2b\x42\x4e\x31\x51\x5a\x47\x2b\x41\x34\x70\x70\ -\x57\x37\x6d\x56\x6b\x4b\x38\x64\x67\x79\x70\x69\x30\x65\x6e\x49\ -\x64\x6a\x6b\x59\x6d\x70\x31\x4a\x75\x6a\x4f\x4a\x51\x64\x6c\x39\ -\x4b\x45\x68\x50\x78\x57\x59\x79\x34\x6b\x71\x79\x48\x7a\x55\x39\ -\x30\x35\x61\x76\x78\x6d\x34\x78\x38\x2b\x75\x54\x52\x78\x37\x58\ -\x20\x75\x76\x53\x48\x77\x72\x7a\x32\x78\x55\x4c\x65\x58\x4c\x79\ -\x55\x6b\x58\x6e\x5a\x6a\x4f\x78\x66\x79\x4a\x71\x71\x57\x6d\x61\ -\x76\x32\x55\x42\x64\x61\x7a\x74\x68\x51\x63\x52\x74\x74\x35\x48\ -\x68\x54\x43\x59\x2f\x33\x55\x4e\x42\x65\x69\x72\x35\x61\x61\x6d\ -\x34\x6b\x71\x79\x6b\x4f\x5a\x4c\x6a\x31\x76\x38\x31\x20\x33\x6f\ -\x37\x32\x49\x38\x72\x7a\x57\x56\x4f\x78\x6b\x38\x63\x2b\x2b\x5a\ -\x79\x37\x4c\x6a\x79\x58\x38\x30\x63\x4e\x5a\x2b\x58\x57\x37\x56\ -\x77\x77\x61\x73\x51\x2b\x33\x31\x45\x55\x68\x59\x5a\x32\x4c\x39\ -\x56\x4e\x4c\x57\x79\x70\x32\x63\x32\x6d\x71\x68\x6f\x32\x56\x64\ -\x65\x77\x73\x36\x47\x52\x6d\x58\x2b\x38\x20\x69\x32\x79\x33\x36\ -\x37\x43\x65\x47\x61\x2f\x5a\x4d\x52\x67\x52\x65\x47\x72\x71\x62\ -\x4e\x70\x43\x59\x5a\x36\x2b\x35\x6a\x4c\x4b\x61\x6e\x59\x7a\x38\ -\x64\x52\x52\x51\x4e\x51\x6f\x4e\x58\x74\x39\x31\x4c\x61\x30\x55\ -\x64\x58\x59\x7a\x4c\x62\x61\x4f\x72\x62\x57\x31\x72\x4f\x37\x74\ -\x51\x31\x76\x4d\x45\x69\x53\x20\x32\x63\x53\x37\x64\x30\x34\x69\ -\x78\x57\x36\x4c\x53\x63\x50\x65\x64\x41\x53\x43\x50\x50\x48\x70\ -\x4c\x4c\x37\x61\x55\x55\x39\x79\x30\x51\x68\x55\x67\x78\x46\x52\ -\x6c\x6f\x68\x49\x49\x75\x46\x51\x6b\x45\x67\x77\x67\x42\x41\x4b\ -\x51\x43\x67\x45\x34\x53\x41\x47\x55\x63\x42\x6a\x30\x4a\x4a\x6d\ -\x4d\x6e\x4a\x79\x20\x59\x56\x39\x65\x76\x50\x35\x79\x39\x44\x70\ -\x64\x33\x50\x54\x55\x74\x58\x62\x77\x38\x49\x66\x54\x36\x4e\x65\ -\x6e\x44\x35\x65\x65\x63\x69\x49\x66\x4c\x56\x37\x4b\x6c\x48\x74\ -\x76\x36\x37\x6f\x75\x53\x68\x49\x4e\x37\x56\x37\x71\x32\x74\x71\ -\x70\x62\x6d\x70\x68\x57\x32\x30\x64\x46\x58\x57\x4e\x56\x4e\x51\ -\x33\x20\x30\x4e\x6a\x65\x7a\x76\x38\x65\x2f\x6a\x33\x5a\x37\x70\ -\x54\x44\x65\x6d\x61\x38\x32\x6e\x5a\x76\x37\x62\x38\x39\x38\x33\ -\x52\x75\x66\x6d\x38\x6d\x76\x37\x72\x73\x52\x76\x78\x43\x47\x48\ -\x38\x6b\x54\x48\x76\x41\x52\x33\x4e\x62\x43\x32\x30\x64\x72\x62\ -\x53\x33\x74\x2b\x4a\x72\x62\x79\x58\x6b\x62\x55\x63\x4a\x20\x42\ -\x55\x6a\x58\x4b\x73\x7a\x37\x38\x77\x50\x30\x54\x66\x50\x45\x70\ -\x4b\x45\x6e\x50\x54\x65\x64\x4f\x35\x62\x5a\x4b\x39\x62\x77\x78\ -\x4e\x57\x2f\x37\x72\x72\x65\x55\x31\x33\x75\x61\x47\x69\x6b\x76\ -\x71\x33\x74\x69\x4f\x72\x79\x59\x47\x79\x74\x72\x65\x50\x75\x39\ -\x7a\x35\x6c\x68\x32\x4c\x45\x31\x69\x65\x58\x20\x6b\x31\x51\x66\ -\x55\x78\x2b\x2b\x71\x2b\x75\x36\x71\x71\x70\x34\x51\x32\x45\x61\ -\x32\x74\x71\x70\x61\x32\x32\x6e\x6f\x72\x36\x52\x37\x58\x55\x4e\ -\x6c\x4f\x32\x71\x5a\x58\x46\x4a\x4b\x51\x75\x66\x65\x6f\x6a\x42\ -\x4f\x5a\x6d\x48\x39\x63\x79\x34\x72\x58\x77\x6b\x57\x65\x59\x2f\ -\x53\x35\x59\x78\x61\x33\x55\x4a\x20\x37\x39\x33\x33\x4f\x77\x5a\ -\x6c\x5a\x37\x4b\x39\x72\x6f\x46\x2f\x66\x2f\x50\x39\x41\x63\x5a\ -\x48\x71\x39\x57\x53\x36\x58\x4b\x53\x36\x58\x4a\x79\x38\x73\x42\ -\x2b\x68\x45\x57\x52\x33\x37\x30\x2b\x68\x52\x56\x62\x79\x6d\x6e\ -\x32\x2b\x67\x2f\x62\x2b\x4d\x53\x44\x44\x56\x55\x31\x50\x50\x4c\ -\x52\x64\x4b\x34\x2f\x20\x63\x77\x79\x33\x54\x54\x69\x54\x6e\x59\ -\x33\x4e\x66\x4c\x78\x6b\x61\x5a\x66\x78\x30\x57\x6d\x31\x70\x44\ -\x73\x64\x70\x44\x73\x64\x6e\x4e\x69\x76\x4c\x78\x42\x74\x45\x45\ -\x56\x56\x2b\x64\x76\x6e\x58\x2f\x4f\x6e\x2f\x30\x7a\x46\x47\x77\ -\x7a\x46\x78\x66\x69\x6f\x71\x73\x71\x79\x73\x75\x33\x38\x34\x65\ -\x4f\x5a\x20\x6d\x50\x4f\x48\x4d\x50\x79\x73\x55\x55\x69\x4b\x67\ -\x69\x68\x4c\x68\x43\x57\x52\x6b\x43\x67\x51\x4e\x4a\x6f\x49\x57\ -\x6d\x7a\x34\x68\x54\x42\x68\x55\x55\x41\x46\x52\x46\x57\x6c\x54\ -\x6c\x57\x70\x4b\x79\x38\x6a\x73\x4b\x47\x4d\x73\x43\x42\x69\x74\ -\x38\x52\x75\x66\x46\x52\x56\x5a\x57\x46\x4a\x4b\x53\x2f\x4e\x20\ -\x6d\x73\x64\x54\x31\x31\x7a\x4f\x42\x61\x4f\x47\x30\x39\x54\x68\ -\x34\x36\x6f\x78\x70\x2b\x7a\x7a\x50\x59\x4e\x65\x54\x37\x62\x48\ -\x52\x62\x62\x48\x78\x65\x6a\x2b\x42\x51\x41\x45\x49\x78\x47\x75\ -\x65\x58\x6b\x79\x33\x35\x61\x56\x45\x34\x78\x45\x59\x74\x59\x53\ -\x44\x2b\x30\x37\x47\x35\x74\x52\x46\x42\x6b\x56\x20\x46\x55\x56\ -\x52\x6b\x42\x55\x46\x74\x46\x71\x4d\x4e\x6a\x73\x57\x76\x51\x37\ -\x4a\x5a\x6b\x64\x78\x70\x79\x4b\x48\x41\x67\x52\x4b\x53\x39\x6a\ -\x64\x32\x6b\x78\x45\x46\x49\x2b\x61\x6e\x76\x5a\x41\x73\x4b\x74\ -\x50\x37\x61\x47\x37\x75\x74\x77\x7a\x54\x6c\x61\x56\x56\x38\x61\ -\x74\x4c\x6b\x56\x4a\x34\x73\x4e\x76\x20\x66\x2b\x53\x76\x58\x79\ -\x79\x69\x33\x2b\x69\x78\x6a\x4d\x7a\x75\x53\x33\x74\x7a\x41\x30\ -\x70\x7a\x78\x7a\x37\x66\x30\x32\x67\x30\x4f\x4b\x77\x57\x48\x46\ -\x59\x4c\x41\x37\x49\x79\x47\x54\x64\x30\x4d\x43\x46\x42\x34\x4a\ -\x5a\x2f\x76\x49\x74\x4f\x70\x30\x4e\x52\x34\x35\x65\x54\x66\x46\ -\x6a\x47\x70\x38\x58\x6e\x20\x35\x36\x6c\x70\x73\x7a\x47\x62\x7a\ -\x4d\x78\x35\x34\x67\x45\x63\x6e\x66\x36\x63\x62\x4c\x65\x4c\x4a\ -\x36\x36\x2b\x39\x4b\x42\x6c\x4a\x56\x6e\x6d\x6d\x55\x38\x2f\x52\ -\x36\x50\x52\x4d\x50\x48\x55\x55\x53\x6a\x4b\x73\x55\x32\x73\x46\ -\x69\x57\x5a\x44\x37\x35\x62\x7a\x68\x65\x72\x53\x33\x6a\x39\x39\ -\x68\x73\x5a\x20\x55\x5a\x43\x48\x52\x71\x4f\x68\x6a\x38\x76\x4a\ -\x30\x39\x64\x64\x66\x73\x6a\x79\x55\x2b\x5a\x2f\x79\x2b\x77\x56\ -\x61\x7a\x68\x6a\x79\x45\x42\x30\x63\x56\x68\x6c\x42\x4d\x49\x52\ -\x58\x76\x74\x69\x49\x54\x4d\x32\x56\x54\x4c\x69\x72\x49\x6b\x6b\ -\x70\x62\x69\x52\x46\x49\x58\x49\x48\x71\x4d\x6a\x52\x4e\x42\x72\ -\x20\x74\x57\x6a\x51\x6f\x4b\x6f\x67\x4b\x54\x4b\x53\x4c\x43\x4d\ -\x71\x4d\x71\x67\x71\x6d\x71\x6f\x4b\x72\x69\x6b\x71\x59\x46\x76\ -\x4e\x37\x72\x6a\x73\x7a\x2f\x32\x68\x4d\x4b\x2f\x4d\x6d\x55\x39\ -\x46\x59\x77\x76\x2f\x65\x2f\x51\x2b\x63\x6a\x78\x75\x4e\x42\x6f\ -\x4e\x49\x55\x46\x67\x35\x64\x62\x74\x6e\x48\x66\x43\x20\x30\x42\ -\x37\x4c\x43\x70\x4c\x45\x2f\x56\x4d\x2b\x59\x56\x47\x44\x46\x36\ -\x50\x4c\x67\x2f\x6b\x6f\x62\x51\x56\x37\x6f\x69\x66\x74\x42\x70\ -\x30\x4f\x55\x52\x4a\x6f\x44\x77\x57\x6a\x64\x53\x70\x47\x43\x49\ -\x6b\x69\x59\x55\x6b\x6b\x49\x6b\x6c\x45\x4f\x6c\x65\x58\x6b\x63\ -\x70\x74\x59\x44\x53\x69\x53\x58\x62\x45\x20\x52\x58\x74\x50\x65\ -\x6c\x70\x38\x66\x6a\x35\x61\x73\x76\x53\x41\x53\x58\x70\x76\x39\ -\x68\x34\x6e\x34\x34\x63\x4f\x6a\x6f\x75\x65\x58\x63\x32\x74\x50\ -\x50\x72\x4a\x54\x4d\x70\x38\x43\x68\x4f\x75\x75\x67\x57\x72\x4c\ -\x51\x6c\x5a\x55\x64\x41\x47\x41\x38\x69\x48\x47\x49\x65\x69\x4a\ -\x50\x48\x59\x68\x35\x2b\x52\x20\x35\x6b\x78\x6d\x7a\x4a\x42\x42\ -\x63\x66\x56\x50\x39\x62\x72\x58\x62\x71\x6d\x70\x34\x39\x72\x58\ -\x33\x6d\x46\x4d\x63\x52\x47\x54\x37\x35\x6a\x55\x5a\x58\x67\x41\ -\x4f\x6f\x4a\x42\x6e\x70\x38\x2b\x35\x36\x44\x6c\x2f\x7a\x56\x33\ -\x45\x65\x73\x71\x64\x2f\x4c\x47\x48\x54\x64\x69\x4d\x75\x68\x52\ -\x56\x4f\x58\x49\x20\x56\x52\x38\x6d\x37\x59\x45\x67\x74\x2f\x2f\ -\x72\x41\x37\x62\x58\x4e\x7a\x50\x6a\x73\x54\x39\x77\x51\x72\x2b\ -\x2b\x58\x66\x76\x57\x56\x70\x2b\x66\x70\x7a\x2f\x39\x2f\x4b\x44\ -\x6c\x70\x79\x39\x64\x79\x5a\x51\x46\x53\x2f\x6a\x30\x6a\x33\x65\ -\x54\x5a\x44\x47\x6a\x6a\x58\x48\x50\x75\x37\x32\x75\x67\x63\x74\ -\x66\x20\x65\x59\x76\x76\x57\x68\x55\x75\x75\x50\x77\x6d\x42\x76\ -\x59\x74\x4a\x44\x50\x5a\x69\x64\x74\x71\x4a\x38\x6c\x6b\x78\x6d\ -\x6f\x77\x59\x74\x49\x62\x4d\x4f\x6a\x30\x36\x4c\x56\x61\x64\x46\ -\x6f\x4e\x57\x6f\x33\x6d\x35\x37\x31\x32\x54\x54\x55\x54\x30\x6c\ -\x4e\x34\x2b\x36\x36\x62\x55\x52\x57\x56\x57\x48\x66\x67\x20\x4f\ -\x78\x71\x61\x2b\x4d\x31\x72\x37\x2b\x42\x78\x4f\x70\x6e\x36\x38\ -\x4f\x2f\x4a\x54\x66\x56\x30\x50\x55\x74\x57\x46\x42\x72\x62\x76\ -\x51\x63\x74\x2f\x2b\x4c\x30\x4c\x2f\x69\x73\x64\x41\x63\x70\x51\ -\x34\x5a\x6a\x30\x47\x72\x52\x61\x75\x50\x6e\x72\x44\x77\x55\x42\ -\x39\x4e\x75\x30\x4f\x75\x51\x4a\x49\x6d\x32\x20\x6b\x4a\x2b\x4f\ -\x55\x41\x42\x76\x4f\x49\x78\x66\x43\x42\x4d\x51\x49\x70\x32\x47\ -\x53\x43\x43\x77\x63\x7a\x74\x53\x4f\x41\x78\x35\x42\x61\x41\x6f\ -\x4d\x57\x73\x2f\x6d\x4a\x35\x73\x74\x34\x74\x6e\x72\x72\x76\x69\ -\x6f\x4f\x58\x33\x48\x69\x63\x61\x4e\x44\x48\x72\x6d\x62\x64\x32\ -\x49\x78\x65\x2b\x4e\x42\x6d\x76\x20\x75\x34\x41\x4c\x4a\x31\x35\ -\x50\x51\x55\x59\x4f\x36\x55\x6b\x4f\x6e\x42\x59\x72\x46\x71\x50\ -\x70\x6b\x43\x75\x5a\x6c\x32\x5a\x38\x53\x58\x31\x62\x42\x79\x39\ -\x4d\x75\x68\x70\x4a\x6c\x6a\x45\x61\x34\x72\x65\x39\x37\x39\x58\ -\x4b\x35\x39\x4d\x66\x56\x76\x4c\x43\x7a\x4b\x2f\x35\x35\x4b\x48\ -\x66\x63\x2b\x71\x67\x20\x77\x67\x4d\x63\x54\x6c\x61\x54\x69\x5a\ -\x50\x36\x39\x2b\x75\x32\x72\x4b\x71\x71\x7a\x46\x69\x2b\x6d\x6b\ -\x2b\x2f\x57\x38\x36\x58\x54\x7a\x37\x55\x4f\x58\x69\x31\x30\x53\ -\x58\x77\x4d\x65\x43\x62\x6b\x6c\x49\x65\x2f\x76\x42\x2f\x50\x48\ -\x7a\x35\x52\x64\x78\x32\x33\x76\x67\x44\x47\x74\x4e\x6d\x4e\x6a\ -\x4e\x2b\x20\x36\x4f\x42\x75\x79\x36\x71\x71\x79\x74\x77\x31\x4a\ -\x54\x77\x37\x62\x52\x5a\x7a\x6e\x6e\x69\x41\x33\x46\x51\x33\x69\ -\x71\x4b\x69\x30\x78\x37\x35\x63\x48\x2f\x39\x71\x30\x57\x38\x4e\ -\x75\x38\x37\x52\x70\x30\x33\x6b\x62\x7a\x63\x41\x76\x52\x36\x41\ -\x37\x4b\x69\x49\x4d\x6b\x79\x67\x69\x77\x69\x79\x4e\x4c\x50\x20\ -\x50\x35\x4b\x30\x7a\x2b\x2b\x53\x4c\x45\x4e\x64\x44\x65\x4f\x53\ -\x6a\x45\x7a\x37\x34\x39\x33\x59\x7a\x4e\x48\x4f\x6f\x39\x55\x63\ -\x65\x51\x65\x64\x2b\x73\x4e\x4b\x6e\x70\x6f\x32\x68\x7a\x66\x75\ -\x6d\x4d\x54\x45\x55\x30\x63\x64\x30\x4c\x59\x5a\x4b\x51\x36\x75\ -\x48\x58\x39\x61\x74\x32\x56\x56\x56\x65\x58\x39\x20\x68\x64\x2f\ -\x78\x32\x70\x4b\x56\x35\x4a\x78\x32\x4a\x6c\x35\x52\x51\x4b\x38\ -\x42\x58\x51\x78\x36\x44\x6f\x65\x70\x50\x36\x7a\x6b\x72\x7a\x4f\ -\x2f\x5a\x73\x6f\x39\x74\x33\x48\x32\x38\x4b\x49\x44\x74\x42\x74\ -\x30\x4f\x6d\x52\x5a\x6f\x69\x58\x67\x52\x35\x42\x2b\x33\x73\x6f\ -\x47\x68\x41\x68\x42\x49\x59\x4a\x33\x20\x31\x77\x34\x69\x4c\x59\ -\x30\x77\x73\x42\x69\x30\x57\x72\x53\x6f\x78\x44\x4b\x76\x48\x45\ -\x70\x50\x55\x34\x65\x58\x68\x39\x37\x2f\x4c\x37\x4f\x66\x65\x4f\ -\x43\x41\x73\x74\x32\x4e\x45\x31\x6d\x52\x59\x36\x72\x4c\x76\x30\ -\x79\x64\x7a\x56\x76\x66\x72\x75\x44\x30\x38\x36\x38\x67\x4e\x79\ -\x63\x66\x57\x56\x55\x4a\x20\x43\x68\x46\x6b\x56\x53\x45\x6b\x43\ -\x6b\x52\x6b\x43\x58\x6f\x59\x68\x34\x71\x71\x38\x75\x36\x38\x78\ -\x58\x79\x2f\x61\x51\x73\x7a\x48\x2f\x38\x44\x46\x71\x4d\x52\x57\ -\x5a\x46\x69\x36\x6d\x76\x37\x30\x79\x76\x6a\x38\x2f\x37\x69\x70\ -\x65\x53\x6d\x65\x6e\x6a\x77\x76\x55\x39\x77\x32\x71\x30\x55\x35\ -\x57\x51\x78\x20\x75\x6e\x38\x42\x77\x77\x76\x79\x79\x48\x41\x36\ -\x4d\x42\x6b\x4d\x36\x48\x71\x77\x30\x45\x73\x32\x62\x4f\x62\x35\ -\x7a\x32\x59\x7a\x36\x34\x6e\x37\x75\x79\x49\x4a\x4f\x71\x33\x32\ -\x6b\x4d\x75\x39\x65\x50\x48\x43\x72\x50\x6e\x6f\x55\x6a\x4c\x34\ -\x35\x2f\x79\x6c\x76\x4c\x39\x6f\x47\x63\x50\x79\x2b\x6c\x43\x63\ -\x20\x6d\x38\x30\x70\x41\x77\x76\x4a\x54\x58\x56\x68\x4e\x42\x69\ -\x49\x69\x46\x4c\x33\x32\x6a\x65\x57\x38\x61\x63\x50\x70\x76\x48\ -\x5a\x49\x2f\x65\x53\x6e\x35\x45\x47\x52\x46\x63\x43\x50\x66\x32\ -\x74\x76\x65\x47\x2f\x50\x36\x79\x6b\x4b\x43\x75\x64\x48\x61\x73\ -\x57\x73\x32\x50\x44\x4b\x71\x77\x4f\x4e\x36\x36\x30\x20\x50\x74\ -\x68\x53\x58\x47\x41\x77\x49\x41\x42\x42\x49\x54\x70\x41\x39\x6a\ -\x68\x4a\x2f\x5a\x45\x49\x51\x55\x46\x41\x61\x61\x78\x6a\x75\x42\ -\x70\x68\x2b\x70\x38\x65\x49\x64\x6c\x71\x51\x5a\x51\x6b\x64\x44\ -\x6f\x74\x32\x68\x69\x4d\x34\x62\x2b\x58\x4c\x4f\x4f\x30\x77\x66\ -\x33\x35\x2b\x2b\x78\x35\x76\x44\x70\x72\x20\x4c\x6f\x56\x39\x30\ -\x68\x6d\x57\x6c\x38\x50\x4a\x41\x77\x76\x70\x6d\x35\x35\x4b\x57\ -\x42\x42\x34\x2f\x72\x4d\x35\x66\x50\x48\x6b\x67\x77\x65\x55\x6e\ -\x62\x31\x69\x44\x59\x2f\x2f\x62\x79\x35\x44\x78\x31\x2b\x41\x58\ -\x31\x56\x51\x68\x41\x68\x36\x51\x4b\x65\x4c\x66\x7a\x53\x77\x4f\ -\x39\x35\x62\x76\x49\x79\x38\x20\x56\x41\x39\x2f\x2f\x6e\x67\x36\ -\x66\x35\x74\x31\x59\x4c\x2f\x55\x36\x62\x51\x6f\x73\x6b\x52\x4c\ -\x77\x49\x65\x6f\x79\x46\x45\x48\x76\x74\x68\x70\x67\x42\x70\x32\ -\x45\x36\x36\x70\x67\x73\x48\x46\x30\x4c\x6d\x4e\x6a\x72\x62\x71\ -\x6b\x57\x73\x2f\x6c\x42\x36\x72\x32\x63\x52\x5a\x77\x34\x71\x36\ -\x4c\x64\x76\x64\x20\x4f\x4a\x46\x6b\x4a\x61\x61\x36\x2f\x47\x72\ -\x74\x52\x69\x77\x70\x48\x74\x59\x75\x2f\x59\x62\x31\x47\x67\x33\ -\x4a\x44\x69\x64\x4f\x54\x7a\x72\x4a\x37\x6a\x52\x4d\x53\x51\x36\ -\x38\x76\x67\x34\x63\x33\x52\x67\x66\x56\x56\x58\x35\x33\x39\x4b\ -\x56\x66\x4c\x68\x6b\x4b\x56\x2f\x38\x2b\x63\x47\x75\x79\x4c\x51\ -\x6b\x20\x78\x7a\x62\x78\x37\x6b\x2b\x76\x6a\x49\x38\x6e\x32\x63\ -\x37\x6b\x4f\x32\x38\x6d\x49\x38\x58\x42\x31\x74\x6f\x36\x64\x6a\ -\x59\x30\x38\x58\x33\x70\x56\x6a\x37\x35\x64\x6a\x6e\x56\x54\x53\ -\x32\x34\x6b\x32\x78\x73\x32\x31\x31\x50\x70\x73\x76\x4a\x36\x50\ -\x34\x46\x39\x45\x33\x7a\x6f\x4e\x56\x71\x32\x56\x53\x31\x20\x69\ -\x2f\x75\x6e\x66\x4d\x7a\x37\x39\x2f\x32\x4f\x33\x4e\x53\x66\x49\ -\x77\x68\x61\x72\x65\x61\x59\x2b\x58\x7a\x73\x56\x67\x74\x44\x7a\ -\x37\x69\x45\x56\x4a\x63\x48\x76\x39\x39\x4c\x59\x31\x4d\x39\x30\ -\x79\x71\x71\x2b\x4d\x63\x50\x4d\x78\x42\x38\x62\x61\x53\x5a\x64\ -\x54\x53\x30\x64\x57\x44\x55\x36\x78\x69\x61\x20\x6c\x38\x50\x6f\ -\x41\x66\x32\x77\x6d\x6f\x79\x73\x72\x64\x6a\x4a\x41\x31\x4d\x2b\ -\x35\x72\x31\x37\x62\x6d\x56\x51\x39\x73\x2f\x65\x66\x55\x57\x56\ -\x59\x39\x70\x32\x5a\x58\x74\x63\x76\x48\x33\x33\x4c\x58\x69\x53\ -\x6b\x39\x6a\x52\x30\x45\x54\x35\x37\x6e\x70\x57\x62\x61\x74\x67\ -\x30\x2b\x59\x79\x4e\x75\x78\x75\x20\x77\x71\x74\x6f\x4d\x44\x69\ -\x63\x61\x4f\x78\x4a\x53\x46\x59\x62\x49\x5a\x32\x57\x69\x43\x53\ -\x68\x74\x44\x5a\x54\x47\x47\x68\x6e\x78\x6c\x4d\x50\x6b\x75\x70\ -\x49\x41\x6b\x43\x51\x6f\x6a\x4e\x6a\x4c\x48\x70\x63\x53\x54\x5a\ -\x65\x76\x66\x56\x36\x73\x74\x77\x70\x31\x4c\x65\x31\x55\x31\x48\ -\x58\x79\x4c\x72\x4b\x20\x4b\x74\x36\x5a\x76\x35\x68\x74\x74\x58\ -\x57\x45\x52\x59\x6d\x77\x49\x50\x44\x50\x4c\x2b\x5a\x54\x6e\x4a\ -\x66\x44\x4b\x51\x50\x37\x59\x54\x57\x5a\x2b\x48\x46\x4c\x4f\x66\ -\x66\x2b\x5a\x7a\x6f\x6a\x7a\x72\x6f\x49\x32\x57\x7a\x47\x36\x2f\ -\x63\x68\x4b\x51\x70\x36\x72\x53\x59\x6d\x34\x33\x77\x34\x65\x4a\ -\x4a\x74\x20\x76\x48\x6e\x58\x4c\x61\x51\x37\x6b\x37\x76\x76\x6c\ -\x38\x6c\x32\x6d\x74\x76\x61\x43\x46\x5a\x75\x51\x35\x4f\x55\x6a\ -\x47\x51\x77\x45\x4a\x45\x6b\x77\x6d\x30\x74\x53\x4a\x58\x6c\x4d\ -\x4c\x41\x49\x39\x44\x2f\x37\x4d\x48\x51\x51\x30\x38\x72\x6e\x55\ -\x48\x70\x53\x48\x55\x6e\x6b\x70\x58\x6d\x59\x39\x73\x4f\x4b\x20\ -\x58\x6f\x30\x54\x4a\x63\x61\x4a\x7a\x6d\x77\x30\x34\x4f\x34\x2f\ -\x46\x49\x63\x6e\x44\x56\x55\x55\x69\x50\x68\x39\x74\x4c\x61\x31\ -\x55\x4c\x31\x70\x4c\x53\x46\x66\x4f\x33\x49\x34\x6a\x45\x73\x48\ -\x7a\x30\x32\x62\x78\x61\x6a\x43\x41\x6b\x37\x6f\x6c\x30\x65\x61\ -\x49\x35\x6b\x6c\x47\x38\x74\x34\x61\x63\x61\x58\x20\x66\x50\x62\ -\x49\x50\x66\x75\x6b\x48\x73\x51\x36\x38\x65\x35\x50\x72\x34\x79\ -\x50\x32\x57\x41\x6b\x4a\x41\x69\x59\x44\x41\x61\x47\x39\x63\x31\ -\x6c\x57\x4e\x39\x63\x4c\x6a\x6c\x35\x4a\x47\x72\x6e\x66\x72\x47\ -\x71\x71\x5a\x6c\x50\x76\x6c\x33\x4f\x75\x6f\x6f\x71\x70\x69\x7a\ -\x34\x6c\x6a\x61\x66\x48\x34\x38\x6a\x20\x6d\x5a\x72\x6d\x56\x74\ -\x36\x34\x34\x34\x59\x44\x50\x50\x77\x36\x72\x52\x62\x35\x47\x50\ -\x6c\x38\x7a\x41\x59\x6a\x76\x6c\x41\x41\x55\x38\x53\x4f\x78\x6d\ -\x44\x45\x6d\x5a\x47\x46\x79\x5a\x31\x4b\x35\x71\x42\x68\x42\x49\ -\x51\x77\x37\x58\x34\x76\x32\x6f\x71\x74\x2f\x47\x56\x35\x4b\x66\ -\x34\x76\x6c\x79\x44\x37\x20\x66\x65\x51\x37\x37\x49\x69\x52\x43\ -\x42\x2f\x38\x34\x58\x5a\x47\x39\x53\x2f\x59\x5a\x2f\x6b\x73\x53\ -\x72\x45\x31\x67\x4e\x31\x73\x78\x42\x73\x4d\x6b\x5a\x66\x6d\x6f\ -\x54\x67\x76\x6d\x2b\x4b\x38\x62\x48\x35\x39\x79\x73\x69\x75\x36\ -\x36\x75\x32\x56\x66\x44\x45\x52\x39\x4d\x5a\x30\x7a\x2b\x44\x46\ -\x56\x75\x33\x20\x55\x39\x48\x63\x79\x67\x35\x2f\x69\x41\x77\x64\ -\x7a\x48\x72\x71\x49\x66\x70\x31\x72\x73\x43\x69\x57\x69\x54\x30\ -\x75\x74\x68\x38\x4c\x43\x61\x39\x67\x62\x41\x67\x6f\x74\x4e\x71\ -\x79\x58\x4b\x37\x79\x48\x4b\x37\x47\x46\x73\x38\x71\x4b\x74\x74\ -\x61\x31\x76\x62\x75\x50\x72\x46\x31\x39\x46\x71\x4e\x48\x79\x34\ -\x20\x36\x41\x63\x65\x2f\x57\x42\x71\x39\x50\x4e\x32\x50\x36\x4d\ -\x6e\x58\x49\x48\x4a\x36\x61\x4c\x4a\x37\x30\x56\x53\x5a\x41\x52\ -\x5a\x77\x6f\x4a\x36\x7a\x49\x7a\x50\x48\x75\x30\x39\x39\x63\x75\ -\x64\x6a\x63\x32\x63\x39\x71\x66\x6e\x61\x47\x79\x6f\x52\x61\x6e\ -\x59\x41\x70\x49\x59\x4e\x54\x61\x69\x43\x50\x30\x48\x20\x67\x33\ -\x6e\x66\x5a\x46\x4b\x39\x52\x68\x50\x54\x4e\x75\x64\x51\x65\x6a\ -\x5a\x56\x31\x58\x44\x72\x36\x2b\x2b\x53\x37\x6e\x54\x30\x61\x70\ -\x7a\x49\x73\x68\x78\x54\x58\x56\x70\x4e\x42\x6e\x62\x35\x4f\x67\ -\x67\x61\x6a\x57\x69\x31\x57\x72\x51\x47\x41\x32\x70\x61\x42\x71\ -\x62\x55\x4e\x48\x53\x79\x51\x74\x6a\x58\x20\x67\x61\x74\x32\x4f\ -\x33\x31\x63\x4b\x55\x78\x66\x74\x70\x4b\x2f\x66\x6a\x59\x4c\x58\ -\x79\x68\x4d\x59\x34\x65\x58\x75\x58\x39\x35\x6d\x48\x36\x5a\x36\ -\x66\x76\x71\x55\x57\x4c\x54\x73\x7a\x2b\x39\x4d\x7a\x35\x36\x50\ -\x57\x48\x68\x77\x42\x44\x6b\x6e\x6b\x47\x5a\x6c\x2b\x70\x68\x79\ -\x59\x62\x4e\x66\x50\x37\x34\x20\x2f\x64\x6a\x4e\x4a\x6a\x6f\x43\ -\x51\x61\x71\x62\x57\x72\x6a\x37\x72\x51\x38\x59\x57\x7a\x7a\x34\ -\x67\x4c\x32\x76\x54\x71\x75\x4e\x61\x38\x6a\x75\x59\x46\x67\x4e\ -\x4f\x72\x7a\x42\x41\x49\x5a\x77\x45\x41\x30\x67\x4b\x51\x71\x43\ -\x4c\x42\x45\x53\x42\x55\x4b\x69\x69\x43\x44\x4c\x74\x4f\x34\x73\ -\x78\x33\x58\x79\x20\x57\x4b\x53\x4d\x50\x76\x6a\x44\x49\x63\x71\ -\x46\x43\x49\x57\x37\x4b\x37\x73\x69\x59\x6e\x75\x6a\x4b\x47\x70\ -\x4d\x30\x61\x55\x6b\x69\x78\x6c\x66\x4b\x4c\x54\x50\x5a\x33\x73\ -\x2f\x77\x35\x56\x6b\x70\x79\x41\x7a\x6e\x53\x65\x76\x6d\x59\x69\ -\x71\x71\x76\x6a\x44\x59\x54\x35\x59\x39\x41\x4d\x4e\x37\x56\x36\ -\x4b\x20\x63\x72\x4c\x32\x4b\x53\x66\x49\x4d\x76\x6f\x59\x4f\x34\ -\x4e\x4a\x72\x2b\x38\x32\x76\x4c\x78\x48\x6b\x39\x4e\x71\x35\x64\ -\x52\x42\x2f\x62\x6e\x37\x6f\x76\x4d\x41\x69\x49\x67\x69\x4e\x63\ -\x32\x74\x6a\x48\x74\x75\x4d\x70\x6c\x39\x63\x6d\x6e\x75\x33\x4e\ -\x49\x49\x55\x6a\x52\x79\x6c\x48\x51\x4d\x56\x7a\x36\x48\x20\x30\ -\x74\x34\x33\x7a\x59\x50\x4e\x5a\x6b\x58\x4a\x79\x67\x57\x74\x44\ -\x6d\x51\x5a\x77\x6b\x48\x59\x57\x51\x6e\x64\x76\x46\x5a\x6b\x30\ -\x47\x70\x69\x32\x73\x49\x65\x53\x73\x2f\x67\x6e\x44\x36\x38\x65\ -\x2f\x65\x74\x44\x4d\x76\x50\x52\x56\x58\x56\x51\x34\x34\x54\x4b\ -\x63\x61\x56\x52\x70\x4c\x5a\x54\x48\x76\x41\x20\x68\x38\x39\x6f\ -\x37\x46\x72\x52\x71\x59\x43\x71\x67\x71\x49\x71\x4b\x4f\x45\x67\ -\x51\x2b\x30\x32\x62\x6a\x35\x33\x48\x44\x65\x66\x4f\x77\x35\x4a\ -\x6c\x70\x6d\x2f\x64\x69\x4d\x7a\x6c\x71\x39\x69\x57\x4e\x2f\x63\ -\x41\x2b\x34\x6e\x79\x66\x46\x64\x2b\x66\x54\x71\x54\x6d\x61\x54\ -\x6f\x56\x76\x6a\x73\x77\x65\x4e\x20\x52\x73\x4e\x4e\x35\x34\x7a\ -\x46\x6f\x4e\x4f\x69\x30\x57\x68\x77\x32\x6d\x33\x30\x79\x30\x78\ -\x48\x52\x59\x33\x2b\x70\x66\x73\x2f\x56\x4b\x4e\x42\x4f\x55\x59\ -\x4f\x5a\x37\x4e\x42\x6a\x7a\x63\x55\x6f\x43\x4d\x55\x70\x44\x30\ -\x63\x78\x42\x73\x4f\x34\x51\x75\x48\x43\x45\x53\x69\x45\x59\x2b\ -\x49\x49\x6d\x50\x4e\x20\x4c\x53\x44\x53\x36\x64\x79\x56\x55\x63\ -\x46\x6f\x52\x4e\x56\x6f\x6f\x76\x72\x33\x51\x31\x61\x55\x6d\x4a\ -\x78\x75\x54\x70\x75\x56\x4e\x6e\x2b\x77\x78\x2b\x74\x39\x58\x43\ -\x6e\x63\x65\x50\x59\x59\x49\x46\x71\x76\x53\x52\x59\x4c\x47\x53\ -\x6b\x4f\x4e\x42\x6f\x4f\x36\x4a\x79\x69\x4a\x47\x48\x51\x78\x35\ -\x53\x6b\x20\x6a\x74\x47\x67\x49\x33\x79\x51\x33\x42\x61\x54\x77\ -\x63\x41\x4a\x2f\x66\x4b\x36\x5a\x6d\x2b\x54\x77\x55\x42\x47\x69\ -\x68\x4f\x4e\x47\x74\x30\x57\x43\x4c\x49\x55\x39\x61\x4e\x49\x41\ -\x68\x46\x52\x78\x4b\x69\x4e\x62\x52\x73\x59\x54\x2b\x30\x61\x6a\ -\x51\x61\x7a\x58\x67\x2b\x4b\x47\x74\x31\x50\x36\x66\x56\x67\x20\ -\x73\x6b\x53\x64\x72\x4e\x31\x6f\x4e\x4d\x52\x6f\x4f\x41\x2b\x6c\ -\x4a\x78\x51\x52\x75\x50\x75\x74\x44\x31\x42\x56\x74\x56\x66\x6a\ -\x52\x46\x62\x55\x6d\x4f\x72\x53\x61\x62\x4f\x69\x45\x53\x56\x6b\ -\x53\x55\x61\x55\x5a\x41\x52\x4a\x52\x70\x52\x6c\x4a\x45\x58\x75\ -\x6d\x76\x79\x6c\x76\x63\x61\x68\x58\x71\x66\x44\x20\x6e\x57\x78\ -\x48\x73\x33\x64\x6b\x64\x53\x2b\x69\x77\x5a\x5a\x6a\x76\x75\x30\ -\x79\x45\x42\x4b\x45\x48\x71\x2b\x72\x71\x73\x71\x47\x48\x64\x57\ -\x63\x55\x54\x53\x51\x76\x4d\x37\x73\x55\x4c\x31\x4f\x68\x36\x79\ -\x6f\x33\x64\x56\x70\x64\x4f\x56\x7a\x6a\x48\x77\x2b\x4e\x71\x4d\ -\x52\x58\x7a\x43\x41\x4e\x68\x7a\x73\x20\x30\x69\x72\x4b\x30\x53\ -\x31\x43\x52\x42\x4c\x78\x4e\x6a\x66\x67\x71\x36\x71\x45\x67\x41\ -\x38\x78\x79\x51\x47\x79\x42\x42\x5a\x72\x64\x4c\x42\x31\x49\x31\ -\x46\x52\x6c\x4a\x67\x36\x68\x4e\x74\x75\x6f\x39\x6e\x62\x63\x2b\ -\x6a\x36\x6d\x2f\x57\x62\x75\x4f\x66\x74\x44\x31\x6a\x34\x37\x4b\ -\x4e\x38\x75\x58\x6f\x64\x20\x5a\x77\x38\x66\x67\x71\x72\x53\x37\ -\x59\x77\x71\x53\x4c\x47\x48\x50\x73\x32\x47\x67\x30\x38\x73\x32\ -\x33\x62\x58\x38\x66\x78\x6e\x63\x78\x68\x56\x57\x4d\x43\x6d\x36\ -\x6c\x32\x4d\x4b\x52\x71\x49\x7a\x52\x79\x4e\x78\x41\x54\x46\x61\ -\x4e\x51\x6f\x2b\x71\x2b\x41\x70\x4d\x67\x59\x4e\x5a\x71\x34\x52\ -\x6b\x52\x69\x20\x30\x54\x35\x6a\x32\x53\x6f\x51\x42\x66\x72\x57\ -\x56\x46\x41\x64\x45\x56\x46\x73\x79\x64\x45\x56\x6a\x36\x70\x45\ -\x42\x2f\x74\x2b\x37\x57\x6a\x55\x61\x6d\x50\x7a\x73\x52\x78\x43\ -\x7a\x36\x49\x4e\x6d\x39\x6c\x63\x33\x30\x54\x52\x66\x55\x38\x79\ -\x49\x69\x65\x44\x6b\x77\x59\x55\x4d\x4b\x78\x76\x44\x70\x4b\x73\ -\x20\x52\x4b\x4f\x57\x2b\x33\x31\x66\x6c\x75\x58\x59\x4a\x6a\x71\ -\x72\x46\x57\x4e\x7a\x42\x49\x32\x71\x52\x55\x4a\x46\x30\x71\x68\ -\x30\x44\x54\x74\x56\x67\x64\x32\x37\x36\x4e\x41\x71\x6e\x50\x33\ -\x34\x38\x30\x79\x2b\x38\x30\x59\x32\x56\x64\x55\x67\x4b\x77\x71\ -\x69\x4a\x48\x63\x5a\x79\x48\x33\x30\x48\x49\x39\x6f\x20\x6c\x39\ -\x31\x6b\x77\x68\x2f\x75\x4f\x65\x33\x39\x72\x62\x6d\x4c\x57\x4c\ -\x53\x68\x6c\x4d\x74\x4f\x47\x38\x30\x7a\x55\x7a\x39\x6e\x66\x50\ -\x46\x67\x7a\x68\x6b\x78\x42\x46\x47\x57\x6b\x56\x55\x46\x33\x58\ -\x37\x56\x71\x74\x55\x65\x75\x31\x43\x37\x7a\x57\x54\x45\x31\x78\ -\x47\x41\x55\x4e\x54\x34\x4b\x4b\x71\x4b\x20\x72\x4d\x69\x49\x73\ -\x6f\x53\x2f\x75\x5a\x47\x77\x45\x49\x48\x63\x76\x67\x68\x61\x4c\ -\x57\x72\x41\x42\x36\x33\x4e\x6b\x4a\x46\x46\x59\x30\x73\x72\x50\ -\x32\x7a\x65\x69\x73\x74\x75\x49\x79\x50\x46\x53\x55\x36\x71\x47\ -\x36\x31\x47\x67\x78\x53\x6a\x38\x58\x48\x5a\x37\x54\x52\x37\x2f\ -\x51\x64\x38\x4c\x73\x6b\x79\x20\x58\x2f\x32\x30\x6e\x69\x78\x33\ -\x43\x67\x75\x65\x2f\x52\x4d\x35\x71\x53\x37\x53\x6e\x51\x37\x71\ -\x32\x74\x70\x5a\x56\x31\x6e\x46\x56\x36\x74\x4c\x6d\x48\x54\x57\ -\x57\x47\x61\x74\x2b\x49\x6e\x4c\x54\x78\x75\x4e\x78\x35\x46\x4d\ -\x52\x79\x43\x49\x51\x52\x75\x62\x38\x62\x45\x61\x6a\x64\x31\x6d\ -\x30\x53\x71\x71\x20\x69\x69\x38\x59\x34\x72\x30\x46\x33\x2f\x48\ -\x71\x72\x64\x64\x68\x4d\x35\x76\x59\x73\x47\x4d\x58\x36\x51\x34\ -\x48\x62\x38\x39\x62\x6a\x43\x68\x4c\x31\x4e\x62\x73\x70\x4b\x36\ -\x6c\x6b\x61\x44\x4e\x52\x6a\x41\x63\x52\x46\x58\x56\x61\x4b\x67\ -\x39\x6a\x68\x47\x52\x49\x39\x45\x75\x53\x6a\x4a\x62\x61\x33\x66\ -\x6a\x20\x44\x59\x57\x5a\x39\x2f\x51\x6a\x32\x43\x30\x6d\x61\x70\ -\x76\x62\x57\x4c\x32\x39\x6b\x68\x56\x62\x4b\x2f\x68\x33\x65\x52\ -\x6e\x32\x37\x5a\x74\x70\x31\x78\x70\x51\x37\x45\x6c\x67\x54\x77\ -\x4b\x54\x43\x5a\x4e\x4f\x47\x39\x4d\x32\x74\x6b\x63\x39\x73\x73\ -\x79\x55\x2b\x55\x74\x34\x5a\x63\x46\x79\x54\x72\x2f\x6b\x20\x4f\ -\x6b\x53\x4e\x68\x6f\x72\x57\x4a\x6e\x37\x63\x55\x49\x31\x76\x38\ -\x57\x72\x38\x4e\x64\x57\x63\x2f\x74\x6a\x7a\x6a\x4d\x37\x50\x35\ -\x64\x52\x42\x68\x5a\x7a\x59\x4c\x35\x39\x4d\x6c\x37\x4e\x7a\x32\ -\x33\x58\x6b\x64\x57\x6b\x31\x47\x54\x43\x71\x6f\x4e\x64\x71\x6b\ -\x56\x51\x31\x2b\x6f\x4f\x4b\x4a\x49\x6c\x51\x20\x56\x63\x36\x39\ -\x70\x77\x7a\x6e\x69\x61\x73\x75\x4a\x53\x79\x49\x57\x45\x78\x47\ -\x76\x6c\x71\x39\x6e\x71\x59\x4f\x48\x2f\x50\x58\x62\x75\x43\x36\ -\x56\x39\x37\x6b\x75\x64\x39\x65\x79\x62\x72\x4b\x4b\x73\x59\x55\ -\x44\x53\x44\x4a\x59\x6f\x6c\x47\x75\x2b\x49\x59\x79\x65\x79\x56\ -\x38\x62\x47\x5a\x54\x66\x68\x44\x20\x42\x78\x6f\x66\x58\x79\x6a\ -\x4d\x6b\x67\x32\x62\x79\x55\x39\x50\x35\x5a\x76\x6e\x48\x6f\x75\ -\x6d\x5a\x64\x75\x73\x68\x41\x57\x52\x65\x57\x73\x32\x73\x4b\x75\ -\x70\x68\x64\x4b\x71\x47\x75\x61\x73\x57\x73\x74\x31\x34\x30\x36\ -\x6a\x49\x43\x4d\x4e\x62\x57\x66\x53\x33\x4c\x46\x4b\x63\x4c\x61\ -\x61\x6a\x66\x6a\x71\x20\x57\x31\x48\x32\x57\x76\x6c\x49\x69\x6b\ -\x4b\x6f\x76\x68\x62\x2f\x72\x68\x33\x6f\x69\x34\x59\x68\x71\x47\ -\x70\x30\x70\x57\x4f\x78\x67\x6a\x73\x56\x56\x42\x57\x37\x33\x55\ -\x37\x2f\x7a\x41\x79\x2b\x33\x62\x69\x5a\x4f\x53\x76\x58\x4d\x6e\ -\x70\x41\x50\x2f\x37\x31\x39\x54\x66\x6f\x64\x62\x48\x4e\x6a\x75\ -\x34\x6b\x20\x47\x2b\x75\x72\x64\x78\x2f\x77\x2b\x61\x4b\x53\x55\ -\x6a\x37\x39\x37\x6b\x66\x65\x76\x2b\x38\x32\x72\x4b\x62\x6f\x79\ -\x34\x54\x58\x6e\x33\x6b\x36\x41\x42\x61\x6a\x67\x63\x62\x32\x44\ -\x6a\x4a\x64\x54\x67\x6f\x79\x30\x67\x68\x45\x42\x4e\x36\x65\x4e\ -\x6f\x75\x6c\x6d\x37\x63\x78\x49\x44\x50\x74\x67\x48\x73\x64\x20\ -\x44\x6c\x61\x7a\x6b\x55\x44\x34\x77\x41\x48\x7a\x31\x74\x66\x66\ -\x73\x4c\x61\x79\x69\x6e\x66\x75\x76\x71\x58\x4c\x32\x4f\x37\x4a\ -\x42\x42\x2f\x56\x50\x35\x38\x2b\x64\x7a\x36\x4f\x58\x34\x6a\x51\ -\x56\x46\x65\x44\x37\x45\x34\x6c\x55\x72\x6f\x65\x58\x42\x36\x4d\ -\x65\x6c\x31\x63\x33\x34\x67\x2b\x45\x75\x32\x76\x20\x7a\x5a\x35\ -\x4c\x56\x57\x4d\x7a\x62\x39\x77\x78\x36\x57\x66\x66\x6c\x63\x33\ -\x47\x6b\x4c\x78\x73\x4a\x70\x30\x31\x68\x70\x2f\x4b\x4b\x35\x6e\ -\x78\x36\x4c\x31\x55\x31\x6a\x65\x78\x61\x6c\x73\x46\x4b\x38\x73\ -\x72\x57\x62\x6d\x6a\x48\x4c\x74\x52\x6a\x30\x46\x2f\x35\x4d\x61\ -\x38\x4f\x7a\x30\x52\x55\x65\x54\x78\x20\x6a\x36\x59\x7a\x62\x33\ -\x73\x44\x5a\x31\x35\x38\x4c\x57\x46\x56\x78\x52\x63\x4a\x59\x55\ -\x76\x78\x34\x4c\x48\x61\x4d\x47\x62\x6c\x30\x4e\x48\x53\x79\x45\ -\x5a\x6e\x4a\x71\x75\x71\x6d\x35\x6c\x63\x57\x6f\x6b\x75\x34\x43\ -\x66\x48\x70\x43\x50\x4e\x59\x6f\x71\x70\x4c\x69\x31\x47\x49\x79\ -\x61\x4e\x42\x6f\x76\x4f\x20\x67\x4b\x67\x6f\x69\x4b\x70\x43\x4f\ -\x42\x4a\x45\x57\x31\x6e\x47\x43\x35\x64\x4e\x34\x4a\x36\x4c\x4a\ -\x2b\x77\x7a\x6b\x54\x34\x34\x38\x51\x49\x32\x56\x65\x32\x69\x66\ -\x48\x63\x39\x7a\x39\x39\x77\x46\x53\x61\x44\x6e\x6e\x55\x56\x4f\ -\x37\x47\x5a\x6a\x4d\x78\x59\x76\x68\x71\x62\x79\x59\x67\x2b\x78\ -\x73\x6c\x75\x20\x62\x33\x71\x33\x38\x72\x47\x59\x38\x4f\x31\x6e\ -\x66\x4d\x4b\x43\x79\x41\x76\x54\x35\x35\x43\x62\x36\x75\x62\x32\ -\x58\x35\x33\x56\x31\x63\x69\x44\x73\x76\x73\x41\x4d\x44\x77\x2f\ -\x6c\x38\x6c\x66\x4c\x79\x54\x4c\x34\x32\x4a\x51\x64\x68\x38\x43\ -\x45\x59\x46\x72\x58\x70\x35\x4d\x74\x73\x65\x46\x51\x61\x38\x2f\ -\x20\x5a\x69\x73\x66\x75\x38\x6c\x4d\x49\x42\x68\x45\x44\x41\x55\ -\x41\x55\x45\x57\x52\x53\x48\x6b\x5a\x35\x50\x52\x46\x47\x56\x68\ -\x4d\x70\x44\x73\x64\x47\x67\x30\x47\x76\x59\x35\x55\x52\x78\x4b\ -\x33\x6e\x33\x39\x32\x39\x4e\x30\x75\x4a\x5a\x70\x77\x57\x4a\x79\ -\x56\x45\x56\x4f\x48\x38\x43\x54\x62\x61\x66\x62\x36\x20\x75\x70\ -\x61\x31\x48\x59\x45\x67\x39\x37\x33\x7a\x45\x51\x39\x64\x64\x69\ -\x48\x2f\x66\x65\x69\x75\x62\x69\x4e\x58\x4a\x6f\x4d\x42\x52\x56\ -\x56\x4a\x73\x64\x76\x34\x7a\x64\x68\x54\x41\x63\x68\x4c\x64\x58\ -\x50\x78\x73\x33\x2f\x6a\x77\x55\x76\x4f\x4f\x32\x49\x74\x45\x4b\ -\x30\x66\x2f\x31\x34\x44\x70\x69\x4d\x51\x20\x5a\x50\x72\x53\x6c\ -\x5a\x77\x30\x6f\x4a\x41\x62\x7a\x78\x6e\x62\x62\x64\x61\x4c\x32\ -\x57\x68\x45\x56\x6d\x51\x55\x71\x77\x33\x62\x67\x43\x4c\x71\x66\ -\x52\x32\x6f\x51\x34\x5a\x44\x78\x56\x61\x75\x4f\x58\x2f\x73\x4d\ -\x58\x4d\x34\x37\x36\x2b\x39\x78\x65\x66\x6e\x62\x35\x39\x2f\x7a\ -\x65\x38\x76\x50\x43\x66\x71\x20\x6c\x2b\x70\x6d\x68\x52\x72\x39\ -\x54\x43\x55\x6a\x78\x55\x6c\x65\x57\x69\x70\x6e\x44\x69\x74\x43\ -\x56\x68\x54\x75\x6e\x2f\x49\x78\x42\x61\x6d\x75\x6d\x45\x34\x4a\ -\x36\x45\x37\x50\x54\x66\x39\x34\x6c\x79\x61\x54\x6d\x33\x45\x58\ -\x58\x45\x6c\x49\x46\x42\x43\x45\x4d\x49\x49\x73\x49\x53\x71\x64\ -\x2f\x68\x64\x5a\x20\x42\x6b\x41\x32\x47\x4d\x48\x70\x41\x71\x63\ -\x4c\x57\x56\x48\x59\x75\x62\x57\x55\x4f\x38\x61\x66\x47\x71\x4d\ -\x50\x53\x6f\x38\x5a\x63\x42\x67\x4d\x43\x49\x71\x43\x74\x37\x30\ -\x56\x77\x2b\x35\x79\x33\x72\x76\x6e\x4a\x69\x61\x63\x4f\x4c\x54\ -\x62\x2b\x74\x48\x72\x64\x47\x67\x30\x30\x44\x63\x39\x46\x59\x42\ -\x6e\x20\x72\x37\x2b\x43\x73\x43\x44\x79\x7a\x79\x38\x57\x38\x4d\ -\x68\x6c\x46\x38\x54\x6b\x6b\x44\x2f\x67\x57\x62\x33\x35\x6b\x74\ -\x31\x6b\x77\x72\x75\x58\x38\x56\x6c\x63\x55\x73\x72\x37\x33\x33\ -\x7a\x50\x35\x44\x73\x6d\x6b\x57\x79\x31\x39\x4e\x6a\x49\x69\x68\ -\x71\x4e\x37\x6c\x7a\x64\x2b\x57\x4c\x69\x66\x2b\x36\x2f\x20\x6e\ -\x5a\x72\x6d\x56\x6d\x35\x34\x39\x53\x30\x75\x48\x64\x6e\x7a\x75\ -\x30\x4c\x78\x78\x47\x6f\x32\x45\x68\x48\x43\x43\x4a\x45\x77\x68\ -\x45\x4f\x6f\x6f\x67\x68\x4a\x79\x57\x41\x77\x48\x44\x53\x66\x62\ -\x47\x39\x66\x6c\x55\x61\x6a\x59\x56\x48\x4a\x4a\x75\x70\x61\x32\ -\x6e\x6a\x35\x2b\x73\x74\x69\x30\x75\x4f\x79\x20\x32\x32\x6a\x78\ -\x52\x62\x64\x64\x74\x53\x32\x74\x4e\x48\x58\x34\x4f\x47\x74\x34\ -\x45\x59\x4f\x79\x4d\x33\x73\x4d\x6d\x5a\x76\x32\x53\x34\x53\x55\ -\x46\x59\x56\x6e\x70\x73\x33\x69\x38\x6c\x4e\x4f\x70\x48\x43\x2f\ -\x63\x4f\x6a\x68\x45\x70\x32\x74\x6f\x32\x33\x72\x44\x51\x5a\x35\ -\x66\x2b\x46\x33\x4a\x4e\x73\x73\x20\x6e\x4e\x41\x76\x37\x36\x41\ -\x64\x58\x31\x45\x55\x76\x4a\x30\x4f\x66\x45\x45\x53\x6f\x61\x4f\ -\x4e\x73\x39\x4e\x64\x54\x44\x71\x7a\x2b\x32\x7a\x6f\x6f\x38\x48\ -\x65\x32\x70\x73\x37\x66\x48\x79\x33\x71\x59\x7a\x69\x76\x47\x77\ -\x79\x55\x70\x77\x48\x31\x36\x36\x79\x54\x37\x52\x31\x30\x66\x70\ -\x53\x4b\x6e\x59\x33\x20\x38\x50\x53\x56\x46\x38\x56\x4e\x7a\x35\ -\x5a\x64\x75\x37\x6e\x70\x6a\x66\x63\x77\x35\x68\x55\x7a\x61\x50\ -\x41\x77\x66\x4a\x48\x77\x58\x75\x2b\x58\x43\x59\x52\x46\x67\x62\ -\x41\x6b\x45\x70\x59\x6b\x46\x46\x56\x46\x55\x65\x53\x66\x62\x39\ -\x54\x63\x79\x42\x6c\x70\x44\x6e\x35\x33\x33\x72\x69\x59\x39\x4a\ -\x6a\x31\x20\x42\x6b\x77\x61\x53\x44\x45\x5a\x71\x61\x76\x62\x68\ -\x61\x75\x39\x6a\x6b\x2b\x66\x75\x49\x38\x68\x75\x64\x6b\x39\x48\ -\x6f\x75\x68\x31\x2b\x6d\x51\x35\x48\x30\x6e\x35\x4c\x66\x6d\x4c\ -\x71\x4a\x76\x71\x6f\x76\x78\x51\x77\x62\x47\x70\x47\x64\x2f\x65\ -\x6d\x56\x57\x37\x57\x59\x7a\x2f\x6e\x41\x59\x53\x5a\x61\x5a\x20\ -\x76\x57\x49\x4e\x4b\x76\x44\x69\x70\x4b\x74\x78\x32\x4b\x77\x48\ -\x50\x64\x74\x44\x56\x64\x53\x75\x4b\x41\x6c\x45\x4f\x2b\x7a\x39\ -\x55\x7a\x37\x6d\x7a\x67\x6e\x6a\x4b\x4d\x37\x4e\x36\x72\x46\x63\ -\x50\x4c\x47\x62\x54\x43\x44\x4c\x71\x4d\x45\x41\x36\x72\x62\x4e\ -\x30\x59\x68\x48\x57\x73\x59\x68\x73\x38\x6d\x55\x20\x76\x62\x53\ -\x33\x65\x48\x30\x38\x4e\x32\x30\x57\x7a\x31\x31\x7a\x61\x63\x78\ -\x48\x56\x31\x68\x4e\x4a\x67\x4c\x68\x61\x43\x37\x46\x74\x61\x2b\ -\x38\x53\x55\x51\x55\x75\x65\x47\x73\x4d\x51\x65\x39\x72\x39\x6c\ -\x67\x32\x4d\x66\x68\x2f\x4f\x57\x71\x64\x56\x51\x33\x4e\x48\x4c\ -\x54\x6d\x57\x66\x45\x70\x41\x58\x32\x20\x2b\x50\x4d\x69\x4c\x43\ -\x34\x70\x35\x64\x71\x58\x33\x2b\x54\x57\x43\x65\x4f\x35\x2b\x5a\ -\x78\x78\x68\x35\x78\x78\x5a\x55\x57\x68\x49\x78\x54\x43\x48\x77\ -\x6d\x6a\x69\x69\x4b\x65\x70\x6a\x70\x65\x2f\x75\x31\x6c\x63\x54\ -\x33\x61\x34\x31\x44\x73\x30\x62\x36\x2b\x73\x6f\x6f\x72\x58\x76\ -\x77\x48\x70\x77\x37\x75\x20\x7a\x37\x58\x6a\x54\x6a\x75\x6b\x64\ -\x76\x55\x6f\x74\x65\x30\x65\x50\x64\x2b\x58\x62\x75\x47\x53\x6c\ -\x79\x61\x6a\x4c\x54\x77\x42\x64\x33\x35\x2f\x32\x6b\x50\x42\x36\ -\x50\x74\x6c\x34\x53\x44\x65\x63\x42\x68\x66\x4a\x49\x79\x2f\x36\ -\x2f\x32\x79\x43\x4b\x72\x4b\x7a\x2b\x4d\x6b\x45\x73\x62\x52\x57\ -\x4d\x76\x66\x20\x4a\x6c\x30\x64\x65\x31\x38\x7a\x47\x39\x47\x71\ -\x45\x72\x36\x36\x4b\x76\x49\x31\x41\x65\x59\x39\x2b\x51\x44\x46\ -\x65\x54\x6b\x48\x48\x62\x4e\x36\x72\x62\x5a\x72\x4e\x51\x5a\x51\ -\x73\x71\x4f\x61\x6d\x63\x74\x58\x38\x64\x68\x6c\x46\x38\x61\x6b\ -\x70\x54\x74\x36\x5a\x33\x79\x73\x5a\x6c\x70\x39\x66\x6a\x35\x65\ -\x20\x73\x6f\x78\x6c\x5a\x64\x73\x34\x6f\x32\x67\x41\x32\x5a\x35\ -\x44\x48\x34\x65\x68\x71\x45\x72\x58\x43\x69\x49\x69\x69\x74\x7a\ -\x37\x39\x6b\x65\x4d\x48\x56\x54\x49\x78\x4a\x4e\x50\x6a\x45\x6e\ -\x30\x34\x57\x41\x7a\x6d\x36\x47\x78\x48\x6f\x51\x49\x44\x42\x6b\ -\x65\x39\x65\x76\x30\x41\x6b\x56\x56\x4f\x33\x4d\x69\x20\x56\x42\ -\x37\x2f\x61\x44\x71\x2f\x4f\x58\x31\x30\x7a\x4b\x73\x4d\x41\x4a\ -\x4e\x42\x54\x32\x31\x4c\x57\x7a\x51\x76\x36\x72\x45\x2f\x63\x4e\ -\x4b\x41\x37\x74\x2b\x4a\x32\x37\x66\x4d\x7a\x79\x75\x66\x75\x74\ -\x5a\x32\x6e\x70\x33\x36\x4f\x53\x39\x63\x66\x30\x56\x4d\x2f\x6f\ -\x6b\x39\x32\x4d\x78\x6d\x46\x71\x7a\x62\x20\x69\x44\x76\x5a\x7a\ -\x6a\x76\x33\x33\x49\x4c\x64\x62\x4f\x37\x56\x59\x56\x47\x4b\x49\ -\x74\x4d\x52\x44\x69\x49\x71\x4d\x72\x72\x71\x53\x70\x36\x2b\x35\ -\x4e\x79\x34\x31\x4d\x2f\x68\x59\x44\x4f\x62\x6d\x62\x75\x6d\x42\ -\x46\x6c\x52\x2b\x4f\x69\x42\x4f\x38\x6c\x4d\x63\x66\x61\x71\x33\ -\x4a\x35\x2b\x47\x65\x2b\x32\x20\x74\x5a\x6e\x4e\x7a\x46\x72\x78\ -\x45\x78\x50\x2f\x2f\x6a\x37\x32\x45\x30\x35\x48\x6c\x2b\x4b\x6d\ -\x4a\x65\x43\x6e\x4a\x65\x69\x6e\x4a\x52\x69\x67\x4c\x52\x6a\x6f\ -\x66\x4d\x45\x31\x69\x43\x38\x63\x4e\x64\x79\x42\x53\x49\x53\x75\ -\x73\x4b\x71\x71\x6f\x71\x6e\x63\x78\x70\x4f\x58\x54\x6d\x42\x77\ -\x39\x75\x47\x64\x20\x6d\x64\x4d\x64\x79\x56\x59\x4c\x35\x64\x75\ -\x33\x63\x4b\x4c\x48\x7a\x4f\x65\x50\x33\x6b\x64\x57\x4c\x38\x34\ -\x46\x30\x75\x74\x30\x58\x65\x48\x33\x73\x43\x42\x77\x37\x7a\x73\ -\x66\x38\x76\x54\x56\x6c\x2b\x4b\x77\x78\x66\x39\x30\x7a\x31\x34\ -\x5a\x6e\x32\x53\x7a\x6d\x59\x2b\x58\x4c\x4b\x4e\x66\x5a\x68\x71\ -\x50\x20\x58\x6e\x6b\x4a\x78\x6c\x37\x6d\x6c\x69\x69\x64\x6a\x6c\ -\x78\x46\x55\x58\x6a\x36\x30\x38\x39\x4a\x74\x68\x68\x6a\x58\x6b\ -\x6f\x65\x4c\x72\x6d\x70\x4c\x72\x4c\x4e\x42\x6e\x54\x4e\x6a\x64\ -\x44\x52\x44\x6f\x4c\x51\x62\x55\x37\x46\x2f\x71\x69\x64\x32\x75\ -\x65\x75\x4b\x61\x47\x68\x72\x59\x32\x72\x7a\x78\x67\x64\x20\x46\ -\x7a\x31\x4a\x5a\x6a\x4e\x6e\x44\x4f\x72\x50\x79\x7a\x4f\x2f\x34\ -\x74\x6d\x70\x73\x35\x69\x33\x5a\x67\x50\x4e\x48\x62\x36\x44\x35\ -\x6a\x32\x5a\x6a\x64\x48\x6b\x74\x59\x67\x6f\x63\x76\x2b\x55\x6a\ -\x33\x6e\x67\x34\x6e\x50\x4a\x63\x76\x56\x75\x6f\x42\x32\x4b\x33\ -\x46\x51\x58\x32\x32\x76\x72\x65\x47\x76\x75\x20\x59\x74\x5a\x58\ -\x56\x74\x48\x6b\x39\x66\x55\x71\x41\x56\x52\x56\x56\x63\x4b\x69\ -\x41\x4b\x33\x4e\x58\x4a\x44\x6c\x69\x56\x76\x39\x48\x41\x35\x37\ -\x74\x4c\x2f\x2b\x35\x51\x49\x32\x56\x75\x33\x71\x74\x58\x62\x6c\ -\x4b\x4c\x56\x74\x54\x6d\x6f\x4b\x32\x32\x72\x72\x55\x45\x77\x57\ -\x57\x6c\x75\x61\x61\x47\x35\x76\x20\x6f\x54\x58\x6f\x70\x7a\x58\ -\x6f\x70\x79\x33\x6f\x70\x79\x30\x55\x6f\x4c\x30\x7a\x35\x38\x7a\ -\x62\x61\x58\x78\x45\x57\x61\x4a\x72\x2f\x39\x2f\x55\x77\x4e\x6c\ -\x5a\x71\x66\x78\x32\x33\x43\x6b\x48\x66\x55\x35\x76\x4f\x57\x31\ -\x67\x49\x56\x65\x63\x63\x69\x4b\x62\x71\x71\x71\x35\x39\x35\x30\ -\x50\x6d\x62\x35\x30\x20\x4a\x58\x57\x74\x37\x51\x64\x73\x71\x2f\ -\x5a\x47\x72\x34\x75\x75\x66\x42\x52\x46\x34\x66\x6e\x70\x63\x78\ -\x68\x58\x31\x4a\x39\x52\x68\x58\x33\x6a\x6f\x75\x65\x41\x5a\x2f\ -\x58\x6d\x53\x30\x55\x35\x66\x58\x6a\x32\x6d\x6f\x6e\x38\x66\x64\ -\x62\x58\x31\x4c\x56\x37\x79\x55\x39\x50\x34\x39\x77\x52\x78\x5a\ -\x77\x35\x20\x72\x49\x6a\x63\x56\x48\x65\x50\x4d\x2b\x57\x65\x51\ -\x37\x6a\x65\x58\x66\x41\x74\x32\x32\x76\x72\x6d\x48\x7a\x62\x74\ -\x63\x66\x4d\x47\x62\x6d\x48\x34\x74\x77\x73\x56\x72\x7a\x34\x4f\ -\x47\x73\x71\x64\x72\x4b\x67\x70\x4a\x51\x46\x6d\x37\x65\x7a\x50\ -\x52\x42\x42\x54\x58\x46\x42\x69\x67\x65\x4d\x78\x6d\x36\x33\x20\ -\x59\x49\x71\x71\x30\x74\x6a\x68\x35\x53\x2f\x2f\x6e\x63\x6d\x48\ -\x39\x39\x37\x53\x61\x34\x4e\x37\x4b\x49\x77\x47\x50\x53\x39\x50\ -\x75\x70\x4b\x4f\x59\x49\x69\x31\x46\x54\x75\x5a\x75\x33\x6f\x4e\ -\x4c\x30\x79\x66\x6a\x54\x73\x35\x69\x51\x6b\x6e\x44\x75\x4f\x69\ -\x30\x53\x65\x51\x35\x55\x37\x5a\x70\x30\x35\x4e\x20\x6e\x65\x38\ -\x6b\x66\x62\x42\x6f\x4b\x52\x61\x44\x6a\x6f\x74\x48\x39\x33\x77\ -\x65\x7a\x4f\x46\x53\x6e\x4a\x76\x46\x30\x75\x63\x66\x5a\x55\x33\ -\x46\x54\x72\x35\x65\x74\x59\x62\x6e\x50\x35\x74\x44\x75\x74\x50\ -\x42\x2b\x53\x4f\x48\x63\x66\x36\x6f\x45\x66\x52\x78\x64\x65\x2b\ -\x34\x52\x56\x56\x42\x69\x4a\x44\x53\x20\x55\x4d\x76\x2f\x50\x58\ -\x56\x2f\x33\x4f\x72\x6e\x63\x4c\x58\x2f\x32\x4e\x6d\x32\x68\x36\ -\x4e\x64\x56\x56\x55\x61\x32\x6a\x76\x69\x33\x72\x5a\x44\x63\x37\ -\x4e\x5a\x39\x74\x66\x48\x57\x4c\x6d\x39\x6b\x76\x6e\x72\x4e\x72\ -\x46\x77\x32\x54\x6f\x43\x52\x67\x74\x47\x54\x7a\x6f\x36\x64\x79\ -\x71\x4b\x30\x59\x41\x67\x20\x79\x55\x52\x6b\x45\x55\x6d\x57\x39\ -\x30\x30\x6a\x69\x34\x53\x78\x31\x65\x33\x69\x74\x57\x63\x65\x78\ -\x47\x77\x30\x78\x6b\x56\x50\x5a\x6f\x71\x44\x4b\x58\x66\x64\x69\ -\x43\x38\x55\x5a\x74\x32\x4f\x61\x68\x5a\x76\x4b\x4f\x4f\x31\x32\ -\x56\x2b\x54\x62\x4c\x56\x78\x7a\x6f\x68\x69\x4c\x6a\x6e\x70\x42\ -\x50\x72\x33\x20\x79\x64\x69\x6e\x6a\x6e\x52\x61\x48\x62\x4b\x69\ -\x73\x4c\x79\x73\x6e\x4f\x38\x32\x6c\x6a\x48\x7a\x6a\x33\x63\x64\ -\x6c\x57\x4f\x44\x34\x51\x69\x4f\x55\x5a\x56\x6c\x68\x55\x32\x37\ -\x61\x6c\x6d\x38\x73\x59\x79\x6c\x5a\x64\x73\x4a\x69\x53\x49\x6a\ -\x43\x76\x49\x59\x58\x7a\x79\x59\x6b\x59\x58\x35\x35\x4b\x58\x39\ -\x20\x66\x48\x35\x4a\x30\x56\x31\x2f\x35\x4d\x47\x4a\x46\x7a\x44\ -\x31\x32\x2b\x58\x38\x39\x2f\x37\x62\x59\x71\x37\x55\x65\x42\x32\ -\x31\x75\x57\x31\x33\x50\x66\x50\x58\x6c\x66\x4c\x4e\x68\x73\x32\ -\x73\x61\x57\x7a\x44\x61\x37\x5a\x43\x69\x68\x76\x73\x39\x6d\x67\ -\x61\x50\x75\x41\x71\x58\x63\x63\x5a\x2f\x66\x4f\x35\x20\x5a\x47\ -\x51\x78\x56\x35\x31\x2b\x55\x6b\x7a\x50\x36\x77\x30\x56\x39\x59\ -\x30\x73\x58\x46\x2f\x4b\x67\x67\x31\x6c\x4b\x4b\x72\x4b\x4b\x51\ -\x4d\x4c\x2b\x64\x58\x49\x34\x59\x77\x6f\x79\x45\x57\x44\x68\x67\ -\x47\x33\x50\x30\x52\x2b\x75\x70\x75\x70\x44\x39\x77\x52\x31\x30\ -\x50\x35\x75\x32\x4e\x50\x2f\x53\x7a\x61\x20\x57\x49\x5a\x47\x71\ -\x32\x58\x4d\x6b\x49\x47\x63\x64\x38\x4a\x51\x52\x68\x54\x6b\x59\ -\x65\x6c\x73\x51\x39\x4d\x31\x64\x36\x42\x61\x37\x66\x7a\x72\x69\ -\x67\x6c\x78\x71\x5a\x39\x34\x74\x2b\x33\x42\x74\x41\x2b\x38\x34\ -\x79\x47\x47\x35\x2b\x63\x78\x59\x64\x69\x67\x6f\x39\x36\x32\x4b\ -\x37\x5a\x57\x73\x4c\x42\x6b\x20\x4d\x30\x73\x32\x62\x57\x46\x6a\ -\x71\x35\x64\x49\x6b\x69\x4d\x61\x31\x62\x49\x6e\x52\x64\x2b\x6d\ -\x56\x32\x54\x59\x73\x42\x61\x64\x32\x63\x79\x72\x6c\x35\x7a\x4e\ -\x54\x57\x66\x46\x37\x73\x63\x37\x46\x4e\x56\x4e\x4c\x53\x77\x6f\ -\x4b\x57\x58\x2b\x2b\x6c\x4a\x38\x6f\x51\x69\x6a\x2b\x75\x64\x7a\ -\x77\x61\x67\x52\x20\x6a\x43\x72\x4d\x52\x36\x76\x56\x4d\x75\x61\ -\x52\x5a\x33\x48\x61\x72\x4c\x77\x36\x36\x61\x72\x44\x50\x6a\x4b\ -\x31\x4f\x33\x70\x71\x32\x79\x4d\x2b\x77\x78\x6d\x69\x44\x75\x51\ -\x32\x66\x35\x42\x4e\x75\x32\x72\x35\x66\x6e\x4d\x35\x4a\x54\x74\ -\x33\x67\x55\x62\x44\x71\x50\x37\x35\x6a\x42\x39\x61\x78\x42\x55\ -\x76\x20\x2f\x49\x4f\x69\x37\x45\x77\x2b\x75\x4f\x64\x57\x4d\x6c\ -\x32\x4f\x6f\x2f\x5a\x48\x48\x43\x6d\x79\x72\x46\x44\x66\x34\x65\ -\x58\x48\x4c\x65\x58\x4d\x4b\x79\x6c\x6a\x61\x57\x55\x56\x6a\x52\ -\x6f\x44\x6b\x69\x4d\x46\x54\x66\x6b\x57\x4c\x68\x38\x31\x6c\x48\ -\x66\x75\x6e\x48\x52\x4d\x6e\x61\x69\x4b\x6f\x74\x44\x6b\x20\x39\ -\x62\x47\x36\x66\x43\x63\x4c\x4e\x32\x36\x6d\x6f\x72\x36\x4a\x76\ -\x75\x6d\x70\x54\x50\x31\x2b\x42\x54\x4d\x66\x2b\x54\x31\x6a\x69\ -\x77\x59\x63\x4d\x79\x31\x37\x31\x38\x2b\x69\x54\x56\x75\x70\x62\ -\x6d\x35\x68\x61\x46\x34\x75\x45\x30\x34\x63\x78\x70\x55\x76\x76\ -\x63\x37\x46\x49\x34\x66\x78\x37\x6c\x33\x78\x20\x71\x5a\x2b\x6a\ -\x32\x62\x62\x37\x61\x2f\x2f\x4e\x2f\x37\x33\x42\x68\x53\x4f\x48\ -\x38\x63\x36\x64\x4e\x78\x79\x7a\x74\x68\x55\x6c\x6d\x5a\x71\x57\ -\x56\x72\x37\x5a\x73\x4a\x6e\x35\x4a\x57\x57\x73\x72\x61\x6d\x6e\ -\x56\x57\x64\x41\x63\x61\x54\x41\x39\x69\x33\x38\x61\x76\x67\x51\ -\x50\x72\x6e\x76\x6c\x70\x68\x66\x20\x6c\x7a\x6b\x63\x46\x45\x57\ -\x68\x78\x52\x64\x67\x62\x65\x56\x4f\x35\x71\x2f\x66\x54\x46\x6c\ -\x74\x48\x65\x6c\x4f\x4a\x37\x4e\x57\x2f\x4d\x52\x4c\x4e\x31\x7a\ -\x42\x37\x65\x65\x4e\x6a\x38\x74\x7a\x6a\x6f\x72\x78\x36\x59\x36\ -\x61\x35\x6c\x62\x57\x37\x61\x6a\x6d\x2b\x38\x33\x6c\x37\x47\x68\ -\x73\x34\x72\x6c\x72\x20\x4a\x75\x35\x7a\x4a\x45\x55\x73\x48\x49\ -\x33\x2f\x58\x6d\x56\x76\x66\x4b\x45\x77\x61\x79\x75\x72\x57\x4c\ -\x53\x78\x6a\x4b\x32\x31\x64\x62\x77\x79\x36\x57\x70\x79\x65\x75\ -\x46\x59\x50\x35\x71\x45\x49\x69\x4b\x6c\x75\x32\x72\x77\x68\x73\ -\x4b\x4d\x48\x7a\x4c\x77\x6d\x4a\x34\x53\x75\x44\x39\x48\x73\x33\ -\x35\x2b\x20\x61\x57\x33\x62\x31\x4f\x48\x6a\x70\x2b\x30\x37\x57\ -\x56\x43\x79\x69\x62\x4c\x61\x4f\x74\x36\x38\x37\x58\x6f\x4b\x4d\ -\x6d\x4a\x4c\x47\x49\x32\x56\x69\x43\x69\x79\x65\x64\x64\x75\x56\ -\x70\x58\x76\x59\x4e\x4b\x5a\x70\x32\x4f\x4f\x30\x35\x47\x70\x78\ -\x38\x7a\x34\x4a\x45\x69\x51\x49\x45\x46\x76\x4f\x48\x37\x54\x20\ -\x61\x49\x49\x45\x43\x58\x37\x52\x4a\x49\x78\x50\x67\x67\x51\x4a\ -\x6a\x67\x73\x4a\x34\x35\x4d\x67\x51\x59\x4c\x6a\x51\x73\x4c\x34\ -\x4a\x45\x69\x51\x34\x4c\x69\x51\x4d\x44\x34\x4a\x45\x69\x51\x34\ -\x4c\x69\x53\x4d\x54\x34\x49\x45\x43\x59\x34\x4c\x43\x65\x4f\x54\ -\x49\x45\x47\x43\x34\x30\x4c\x43\x2b\x43\x52\x49\x20\x6b\x4f\x43\ -\x34\x6b\x44\x41\x2b\x43\x52\x49\x6b\x4f\x43\x34\x6b\x6a\x45\x2b\ -\x43\x42\x41\x6d\x4f\x43\x2f\x38\x50\x32\x32\x63\x47\x79\x2b\x42\ -\x2f\x69\x58\x30\x41\x41\x41\x41\x41\x53\x55\x56\x4f\x52\x4b\x35\ -\x43\x59\x49\x49\x3d\x20\x22\x20\x68\x65\x69\x67\x68\x74\x3d\x22\ -\x34\x31\x22\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x38\x37\x22\x20\ -\x79\x3d\x22\x2d\x36\x35\x35\x2e\x33\x37\x22\x20\x78\x3d\x22\x31\ -\x32\x39\x39\x2e\x37\x22\x20\x70\x72\x65\x73\x65\x72\x76\x65\x41\ -\x73\x70\x65\x63\x74\x52\x61\x74\x69\x6f\x3d\x22\x6e\x6f\x6e\x65\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\ -\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x33\x33\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\ -\x2d\x35\x39\x31\x2e\x38\x33\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x34\x37\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x35\x36\x36\x2e\x35\x39\ -\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x20\x32\x35\ -\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x33\x34\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\ -\x32\x2d\x35\x39\x31\x2e\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\ -\x38\x2e\x34\x35\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x33\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x35\x38\x2e\ -\x31\x34\x76\x33\x32\x6c\x2d\x33\x31\x2e\x35\x34\x37\x2d\x38\x2e\ -\x34\x35\x33\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x32\ -\x36\x2e\x31\x34\x20\x32\x35\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\ -\x33\x38\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x37\ -\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x39\x31\ -\x2e\x38\x33\x76\x33\x32\x6c\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x39\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x35\x39\x2e\ -\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x36\x31\x22\x20\x64\x3d\x22\x6d\x31\ -\x32\x33\x36\x2e\x36\x2d\x36\x35\x36\x2e\x32\x38\x2d\x31\x32\x2e\ -\x36\x31\x39\x20\x31\x32\x2e\x36\x31\x39\x76\x31\x36\x6c\x31\x38\ -\x2e\x39\x32\x38\x20\x35\x2e\x30\x37\x31\x38\x76\x2d\x31\x36\x6c\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x36\x33\x22\x20\x64\x3d\x22\x6d\x31\x32\ -\x34\x33\x2d\x36\x32\x32\x2e\x35\x39\x20\x31\x32\x2e\x36\x31\x39\ -\x2d\x31\x32\x2e\x36\x31\x39\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x36\x33\x38\x2e\ -\x35\x39\x20\x31\x32\x2e\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\ -\x76\x31\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x37\x22\x20\x64\ -\x3d\x22\x6d\x31\x32\x35\x35\x2e\x36\x2d\x36\x35\x31\x2e\x32\x31\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x76\x31\ -\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x32\x32\x34\x2d\x36\x32\x37\x2e\x36\x36\x20\x31\x32\x2e\ -\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\x20\x31\x38\x2e\x39\x32\ -\x38\x20\x35\x2e\x30\x37\x31\x38\x22\x2f\x3e\x0a\x20\x20\x20\x3c\ -\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x31\ -\x22\x20\x64\x3d\x22\x6d\x31\x33\x33\x38\x2e\x31\x2d\x35\x35\x39\ -\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\ -\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\ -\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\ -\x37\x33\x22\x20\x64\x3d\x22\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\ -\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\ -\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\ -\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x37\x37\x22\x20\x64\x3d\x22\x6d\x31\ -\x33\x35\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\ -\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\ -\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x31\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x36\x36\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x20\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3d\x22\ -\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\x69\x6c\x6c\x2d\x6f\x70\ -\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\x37\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\ -\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x31\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x32\x30\x22\x20\x64\x3d\x22\x6d\x31\x33\x38\x36\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x36\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x32\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x32\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x20\x66\x69\x6c\x6c\x2d\ -\x72\x75\x6c\x65\x3d\x22\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\ -\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\ -\x36\x36\x37\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\ -\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\ -\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\ -\x6c\x3d\x22\x23\x30\x30\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\ -\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x34\x34\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x38\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x38\x30\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x30\x22\x20\ -\x64\x3d\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x35\x36\x2e\x34\ -\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\ -\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\ -\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x34\x34\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x30\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x30\x22\x20\x66\x69\x6c\ -\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\ -\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x39\x34\x2e\x32\x2d\x35\x35\x30\x2e\x34\x36\ -\x20\x30\x2e\x30\x30\x31\x2d\x35\x2e\x38\x36\x36\x36\x20\x32\x2e\ -\x36\x35\x32\x31\x2d\x32\x2e\x39\x37\x30\x35\x63\x31\x2e\x34\x35\ -\x38\x37\x2d\x31\x2e\x36\x33\x33\x38\x20\x32\x2e\x36\x37\x38\x37\ -\x2d\x32\x2e\x39\x39\x38\x31\x20\x32\x2e\x37\x31\x31\x32\x2d\x33\ -\x2e\x30\x33\x31\x39\x20\x30\x2e\x30\x33\x35\x2d\x30\x2e\x30\x33\ -\x36\x38\x20\x30\x2e\x30\x35\x39\x20\x32\x2e\x31\x37\x30\x39\x20\ -\x30\x2e\x30\x35\x39\x20\x35\x2e\x35\x38\x35\x39\x76\x35\x2e\x36\ -\x34\x37\x32\x6c\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\ -\x31\x34\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\x31\x34\ -\x76\x2d\x35\x2e\x38\x36\x36\x38\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\ -\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\ -\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\ -\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ -\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x34\x38\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x39\ -\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\ -\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\ -\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x34\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x34\x30\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\ -\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\ -\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\ -\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x31\x34\x2d\x35\x36\x33\x2e\x35\ -\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x39\x30\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x37\x2e\x37\x2d\x35\ -\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\ -\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x30\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x30\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\ -\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\ -\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x30\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x31\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\ -\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x32\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x35\x32\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x36\x35\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\ -\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\ -\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\ -\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x31\x36\x22\x20\x64\x3d\x22\x6d\x31\x34\x37\x32\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x31\x38\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\ -\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\ -\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\ -\x67\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x32\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x36\x2e\x39\x2d\x35\x36\x36\ -\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\ -\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x36\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x37\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\ -\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\x2e\x31\x2d\x35\x35\x39\x2e\ -\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\ -\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\ -\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x33\ -\x30\x22\x20\x64\x3d\x22\x6d\x31\x35\x32\x31\x2e\x37\x2d\x35\x35\ -\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\ -\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\ -\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x35\ -\x32\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x35\x33\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x35\x32\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\ -\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x3c\ -\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ -\x00\x00\x4e\x4c\ -\x3c\ -\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ -\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ -\x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ -\x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ -\x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ -\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ -\x3c\x73\x76\x67\x20\x69\x64\x3d\x22\x73\x76\x67\x32\x22\x20\x78\ -\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\ -\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\x39\ -\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\x2d\x73\x79\x6e\x74\x61\ -\x78\x2d\x6e\x73\x23\x22\x20\x78\x6d\x6c\x6e\x73\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x68\x65\x69\x67\x68\x74\ -\x3d\x22\x32\x33\x2e\x39\x39\x34\x22\x20\x77\x69\x64\x74\x68\x3d\ -\x22\x32\x30\x2e\x39\x36\x31\x22\x20\x76\x65\x72\x73\x69\x6f\x6e\ -\x3d\x22\x31\x2e\x31\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\x3d\ -\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\x65\ -\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\x22\ -\x20\x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x31\x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x76\x69\x65\x77\ -\x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x30\x2e\x39\x36\x30\x37\ -\x38\x34\x20\x32\x33\x2e\x39\x39\x33\x35\x39\x31\x22\x20\x78\x6d\ -\x6c\x6e\x73\x3a\x64\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\ -\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\ -\x6e\x74\x73\x2f\x31\x2e\x31\x2f\x22\x3e\x0a\x20\x3c\x6d\x65\x74\ -\x61\x64\x61\x74\x61\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ -\x74\x61\x37\x22\x3e\x0a\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\ -\x3e\x0a\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x20\x72\x64\ -\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\ -\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\ -\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\ -\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ -\x65\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\ -\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\ -\x6c\x49\x6d\x61\x67\x65\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x64\ -\x63\x3a\x74\x69\x74\x6c\x65\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x63\ -\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x3c\x2f\x72\x64\x66\x3a\ -\x52\x44\x46\x3e\x0a\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ -\x3e\x0a\x20\x3c\x67\x20\x69\x64\x3d\x22\x6c\x61\x79\x65\x72\x31\ -\x22\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x74\x72\x61\ -\x6e\x73\x6c\x61\x74\x65\x28\x2d\x31\x33\x36\x35\x2e\x36\x20\x35\ -\x36\x36\x2e\x38\x34\x29\x22\x3e\x0a\x20\x20\x3c\x67\x20\x66\x69\ -\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\ -\x36\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x3e\ -\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x33\x36\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\ -\x2e\x33\x2d\x35\x35\x33\x2e\x32\x39\x63\x30\x2d\x34\x2e\x33\x34\ -\x33\x31\x20\x30\x2e\x30\x31\x31\x2d\x35\x2e\x34\x32\x34\x33\x20\ -\x30\x2e\x30\x36\x2d\x35\x2e\x34\x32\x34\x33\x20\x30\x2e\x30\x36\ -\x31\x20\x30\x20\x38\x2e\x33\x34\x31\x39\x20\x31\x2e\x38\x31\x33\ -\x32\x20\x38\x2e\x33\x35\x35\x39\x20\x31\x2e\x38\x32\x39\x37\x20\ -\x30\x20\x30\x20\x30\x2e\x30\x32\x34\x20\x30\x2e\x36\x32\x30\x34\ -\x33\x20\x30\x2e\x30\x34\x32\x20\x31\x2e\x33\x36\x37\x33\x6c\x30\ -\x2e\x30\x33\x34\x20\x31\x2e\x33\x35\x37\x39\x2d\x34\x2e\x32\x34\ -\x35\x38\x20\x33\x2e\x31\x34\x36\x39\x2d\x34\x2e\x32\x34\x35\x39\ -\x20\x33\x2e\x31\x34\x36\x39\x76\x2d\x35\x2e\x34\x32\x34\x33\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x35\x33\x38\x22\x20\x64\x3d\x22\x6d\x31\ -\x35\x31\x32\x2e\x38\x2d\x35\x35\x38\x2e\x36\x34\x63\x2d\x32\x2e\ -\x31\x37\x39\x34\x2d\x30\x2e\x34\x36\x37\x31\x33\x2d\x33\x2e\x39\ -\x39\x35\x32\x2d\x30\x2e\x38\x35\x36\x31\x33\x2d\x34\x2e\x30\x33\ -\x35\x2d\x30\x2e\x38\x36\x34\x35\x35\x2d\x30\x2e\x30\x33\x39\x2d\ -\x30\x2e\x30\x31\x30\x37\x20\x31\x2e\x37\x32\x39\x34\x2d\x31\x2e\ -\x33\x38\x32\x39\x20\x33\x2e\x39\x33\x31\x34\x2d\x33\x2e\x30\x35\ -\x34\x36\x20\x32\x2e\x32\x30\x32\x32\x2d\x31\x2e\x36\x37\x31\x36\ -\x20\x34\x2e\x30\x31\x31\x39\x2d\x33\x2e\x30\x33\x31\x36\x20\x34\ -\x2e\x30\x32\x31\x36\x2d\x33\x2e\x30\x32\x32\x32\x20\x30\x2e\x30\ -\x32\x31\x20\x30\x2e\x30\x31\x39\x32\x20\x30\x2e\x31\x36\x39\x31\ -\x20\x36\x2e\x33\x37\x38\x37\x20\x30\x2e\x31\x36\x39\x34\x20\x37\ -\x2e\x32\x34\x31\x31\x20\x30\x2e\x30\x30\x30\x32\x20\x30\x2e\x34\ -\x31\x38\x38\x39\x2d\x30\x2e\x30\x31\x34\x20\x30\x2e\x35\x35\x38\ -\x34\x37\x2d\x30\x2e\x30\x36\x32\x20\x30\x2e\x35\x35\x34\x36\x34\ -\x2d\x30\x2e\x30\x33\x35\x20\x30\x2d\x31\x2e\x38\x34\x35\x36\x2d\ -\x30\x2e\x33\x38\x37\x33\x31\x2d\x34\x2e\x30\x32\x35\x33\x2d\x30\ -\x2e\x38\x35\x34\x34\x33\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x30\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x35\x39\x2e\x34\x2d\x35\x34\x35\ -\x2e\x34\x33\x63\x2d\x33\x2e\x33\x32\x36\x32\x2d\x30\x2e\x39\x32\ -\x33\x32\x33\x2d\x36\x2e\x31\x37\x37\x38\x2d\x31\x2e\x37\x31\x33\ -\x33\x2d\x36\x2e\x33\x33\x36\x38\x2d\x31\x2e\x37\x35\x35\x37\x2d\ -\x30\x2e\x32\x37\x38\x31\x2d\x30\x2e\x30\x37\x34\x34\x2d\x30\x2e\ -\x31\x32\x30\x39\x2d\x30\x2e\x32\x30\x32\x37\x39\x20\x34\x2e\x30\ -\x31\x35\x31\x2d\x33\x2e\x32\x38\x38\x37\x20\x32\x2e\x33\x36\x37\ -\x36\x2d\x31\x2e\x37\x36\x36\x35\x20\x34\x2e\x33\x37\x30\x31\x2d\ -\x33\x2e\x32\x30\x35\x39\x20\x34\x2e\x34\x35\x30\x32\x2d\x33\x2e\ -\x31\x39\x38\x35\x20\x30\x2e\x30\x38\x20\x30\x2e\x30\x31\x30\x38\ -\x20\x31\x2e\x30\x33\x33\x34\x20\x30\x2e\x32\x37\x35\x34\x32\x20\ -\x32\x2e\x31\x31\x38\x38\x20\x30\x2e\x35\x39\x35\x38\x37\x20\x31\ -\x2e\x30\x38\x35\x34\x20\x30\x2e\x33\x32\x30\x35\x37\x20\x31\x2e\ -\x39\x38\x38\x39\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x32\x2e\x30\ -\x30\x37\x38\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x30\x2e\x30\x31\ -\x39\x20\x30\x20\x30\x2e\x30\x33\x35\x20\x31\x2e\x39\x36\x39\x39\ -\x20\x30\x2e\x30\x33\x35\x20\x34\x2e\x33\x37\x37\x35\x20\x30\x20\ -\x33\x2e\x34\x34\x31\x31\x2d\x30\x2e\x30\x32\x36\x20\x34\x2e\x33\ -\x37\x36\x33\x2d\x30\x2e\x31\x32\x30\x39\x20\x34\x2e\x33\x37\x31\ -\x35\x2d\x30\x2e\x30\x36\x36\x20\x30\x2d\x32\x2e\x38\x34\x32\x34\ -\x2d\x30\x2e\x37\x36\x31\x32\x37\x2d\x36\x2e\x31\x36\x38\x35\x2d\ -\x31\x2e\x36\x38\x34\x36\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x32\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\x2e\x39\x2d\x35\x34\x38\ -\x2e\x30\x39\x63\x30\x2d\x32\x2e\x31\x37\x33\x35\x20\x30\x2e\x30\ -\x32\x2d\x33\x2e\x39\x35\x31\x38\x20\x30\x2e\x30\x34\x37\x2d\x33\ -\x2e\x39\x35\x31\x38\x20\x30\x2e\x31\x30\x36\x31\x20\x30\x20\x35\ -\x2e\x32\x33\x37\x20\x31\x2e\x35\x30\x34\x31\x20\x35\x2e\x32\x38\ -\x32\x36\x20\x31\x2e\x35\x34\x38\x37\x20\x30\x2e\x30\x33\x35\x20\ -\x30\x2e\x30\x33\x35\x2d\x34\x2e\x34\x39\x35\x20\x35\x2e\x34\x34\ -\x35\x32\x2d\x35\x2e\x32\x34\x32\x20\x36\x2e\x32\x35\x39\x33\x2d\ -\x30\x2e\x30\x34\x38\x20\x30\x2e\x30\x35\x33\x2d\x30\x2e\x30\x38\ -\x38\x2d\x31\x2e\x36\x36\x39\x35\x2d\x30\x2e\x30\x38\x38\x2d\x33\ -\x2e\x38\x35\x36\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\x35\x35\x33\x2e\ -\x38\x2d\x31\x2e\x37\x38\x30\x33\x2d\x30\x2e\x35\x33\x32\x39\x76\ -\x2d\x31\x2e\x31\x37\x38\x37\x63\x30\x2d\x31\x2e\x31\x36\x31\x37\ -\x20\x30\x2d\x31\x2e\x31\x37\x38\x20\x30\x2e\x32\x30\x35\x34\x2d\ -\x31\x2e\x31\x32\x35\x32\x20\x30\x2e\x31\x31\x32\x38\x20\x30\x2e\ -\x30\x32\x39\x39\x20\x30\x2e\x39\x34\x36\x20\x30\x2e\x32\x31\x35\ -\x38\x38\x20\x31\x2e\x38\x35\x31\x36\x20\x30\x2e\x34\x31\x33\x39\ -\x31\x6c\x31\x2e\x36\x34\x36\x31\x20\x30\x2e\x33\x36\x30\x32\x39\ -\x76\x31\x2e\x33\x30\x36\x33\x63\x30\x20\x30\x2e\x37\x31\x38\x34\ -\x36\x2d\x30\x2e\x30\x33\x32\x20\x31\x2e\x33\x30\x32\x34\x2d\x30\ -\x2e\x30\x37\x32\x20\x31\x2e\x32\x39\x37\x38\x2d\x30\x2e\x30\x33\ -\x39\x20\x30\x2d\x30\x2e\x38\x37\x32\x33\x2d\x30\x2e\x32\x34\x38\ -\x33\x32\x2d\x31\x2e\x38\x35\x31\x36\x2d\x30\x2e\x35\x34\x31\x35\ -\x32\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x31\x30\x2e\x38\x2d\x35\x35\x32\x2e\x31\x38\x2d\x32\ -\x2e\x36\x38\x31\x31\x2d\x30\x2e\x37\x38\x35\x33\x34\x76\x2d\x31\ -\x2e\x36\x35\x39\x33\x2d\x31\x2e\x36\x35\x39\x33\x6c\x32\x2e\x36\ -\x31\x37\x32\x2d\x32\x2e\x38\x38\x36\x33\x63\x31\x2e\x34\x33\x39\ -\x34\x2d\x31\x2e\x35\x38\x37\x35\x20\x32\x2e\x36\x37\x37\x34\x2d\ -\x32\x2e\x39\x34\x36\x38\x20\x32\x2e\x37\x35\x30\x39\x2d\x33\x2e\ -\x30\x32\x30\x36\x20\x30\x2e\x31\x31\x36\x32\x2d\x30\x2e\x31\x31\ -\x36\x36\x34\x20\x30\x2e\x31\x33\x33\x38\x20\x30\x2e\x35\x38\x33\ -\x37\x39\x20\x30\x2e\x31\x33\x33\x38\x20\x35\x2e\x33\x33\x39\x39\ -\x20\x30\x20\x33\x2e\x30\x31\x30\x38\x20\x30\x2e\x31\x30\x30\x33\ -\x20\x35\x2e\x35\x30\x32\x34\x20\x30\x2e\x30\x36\x31\x20\x35\x2e\ -\x34\x39\x37\x36\x2d\x30\x2e\x30\x33\x39\x20\x30\x2d\x31\x2e\x34\ -\x30\x38\x2d\x30\x2e\x33\x39\x34\x36\x34\x2d\x32\x2e\x38\x38\x32\ -\x34\x2d\x30\x2e\x38\x32\x36\x35\x39\x7a\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x39\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\ -\x35\x35\x37\x2e\x31\x34\x2d\x31\x2e\x37\x31\x34\x37\x2d\x30\x2e\ -\x33\x39\x33\x38\x33\x2d\x30\x2e\x30\x35\x38\x2d\x32\x2e\x32\x32\ -\x36\x34\x63\x2d\x30\x2e\x30\x39\x36\x2d\x33\x2e\x37\x34\x33\x32\ -\x2d\x30\x2e\x32\x31\x38\x33\x2d\x35\x2e\x39\x33\x31\x39\x2d\x30\ -\x2e\x31\x31\x34\x37\x2d\x35\x2e\x39\x33\x31\x39\x20\x30\x2e\x31\ -\x33\x35\x20\x30\x20\x39\x2e\x34\x39\x39\x35\x20\x32\x2e\x32\x35\ -\x31\x39\x20\x39\x2e\x37\x30\x33\x31\x20\x32\x2e\x33\x33\x36\x37\ -\x20\x30\x2e\x31\x34\x32\x35\x20\x30\x2e\x30\x35\x39\x34\x2d\x30\ -\x2e\x32\x39\x37\x33\x20\x30\x2e\x35\x39\x35\x36\x39\x2d\x32\x2e\ -\x37\x32\x35\x32\x20\x33\x2e\x33\x32\x35\x31\x2d\x32\x2e\x33\x31\ -\x31\x39\x20\x32\x2e\x35\x39\x39\x2d\x32\x2e\x39\x34\x33\x32\x20\ -\x33\x2e\x32\x35\x37\x34\x2d\x33\x2e\x31\x33\x35\x39\x20\x33\x2e\ -\x32\x36\x39\x32\x2d\x30\x2e\x31\x33\x32\x36\x20\x30\x2e\x30\x31\ -\x30\x34\x2d\x31\x2e\x30\x31\x32\x38\x2d\x30\x2e\x31\x36\x32\x32\ -\x35\x2d\x31\x2e\x39\x35\x36\x2d\x30\x2e\x33\x37\x38\x38\x32\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x67\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\ -\x35\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x36\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x32\ -\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\ -\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\ -\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x34\x39\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x33\ -\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\ -\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x39\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x30\x2e\x38\x35\x39\x20\x33\x2e\x30\x33\x30\ -\x34\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x32\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x38\x2e\x39\x2d\ -\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\ -\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\ -\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ -\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x32\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\ -\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\ -\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x33\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\ -\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x34\x31\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x34\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\ -\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\ -\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x35\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\ -\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x37\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x36\x2e\x39\x2d\x35\x36\x36\x2e\ -\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\ -\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x38\x31\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x37\x2e\x32\x2d\x35\x35\x33\x2e\ -\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x3e\x0a\ -\x20\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x30\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x35\ -\x36\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\ -\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\ -\x37\x33\x32\x2e\x31\x2d\x35\x30\x37\x2e\x36\x34\x20\x31\x33\x38\ -\x2e\x35\x36\x2d\x38\x30\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\ -\x2d\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x2d\x31\x33\x38\x2e\x35\ -\x36\x2d\x38\x30\x76\x31\x36\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x35\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x37\x33\x32\x2e\x31\x2d\x33\x34\x37\x2e\x36\x34\x20\ -\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x38\x37\x30\x2e\x36\x2d\x32\x36\x37\x2e\x36\x34\x20\x31\x33\ -\x38\x2e\x35\x36\x2d\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x32\x36\x32\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x35\x38\x37\ -\x2e\x36\x34\x76\x31\x36\x30\x6c\x2d\x31\x33\x38\x2e\x35\x36\x20\ -\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x34\x22\x20\ -\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x34\x32\x37\x2e\x36\ -\x34\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x36\x36\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x2d\x38\x30\x20\x38\x30\ -\x20\x38\x30\x20\x38\x30\x20\x38\x30\x2d\x38\x30\x7a\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x37\x30\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x37\x32\x37\x2e\x36\x34\x76\x38\x30\x6c\x38\x30\ -\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x32\x37\x32\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x36\x34\ -\x37\x2e\x36\x34\x2d\x38\x30\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x37\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x76\x38\x30\x6c\x2d\ -\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x37\ -\x36\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x38\x30\x37\x2e\ -\x36\x34\x20\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x30\x22\x20\x64\x3d\x22\x6d\x32\x32\x35\x32\x2e\x39\ -\x2d\x39\x36\x37\x2e\x36\x34\x2d\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x76\x31\x36\x30\x6c\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x38\x32\x22\x20\x64\x3d\ -\x22\x6d\x32\x30\x38\x38\x2e\x31\x2d\x39\x30\x37\x2e\x36\x34\x2d\ -\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\ -\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x39\x32\x33\x2e\x32\x2d\x39\x36\x37\x2e\x36\x34\x76\x31\x36\x30\ -\x6c\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x32\x38\x36\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\ -\x2e\x31\x2d\x31\x30\x32\x37\x2e\x36\x76\x31\x36\x30\x6c\x2d\x31\ -\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x38\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\x2e\x31\ -\x2d\x38\x36\x37\x2e\x36\x34\x20\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x3c\x67\x20\x73\ -\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\ -\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x33\x32\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x31\x38\x38\x2e\x31\x2d\x33\x34\x31\x2e\x36\x37\x20\x31\x35\ -\x33\x2e\x33\x31\x2d\x37\x31\x2e\x34\x38\x38\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x2d\x31\x35\x33\x2e\x33\x31\ -\x20\x37\x31\x2e\x34\x38\x38\x2d\x31\x35\x33\x2e\x33\x31\x2d\x38\ -\x38\x2e\x35\x31\x32\x76\x31\x36\x30\x6c\x31\x35\x33\x2e\x33\x31\ -\x20\x38\x38\x2e\x35\x31\x32\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x39\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\x33\x31\ -\x2d\x37\x31\x2e\x34\x38\x38\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x34\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x34\x31\x33\x2e\x31\x36\x76\x31\x36\x30\x6c\x2d\ -\x31\x35\x33\x2e\x33\x31\x20\x37\x31\x2e\x34\x38\x38\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x32\x36\x22\x20\x64\x3d\x22\x6d\x31\x33\ -\x34\x31\x2e\x34\x2d\x32\x35\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\ -\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x20\x69\x64\ -\x3d\x22\x69\x6d\x61\x67\x65\x34\x33\x33\x36\x22\x20\x73\x74\x79\ -\x6c\x65\x3d\x22\x69\x6d\x61\x67\x65\x2d\x72\x65\x6e\x64\x65\x72\ -\x69\x6e\x67\x3a\x6f\x70\x74\x69\x6d\x69\x7a\x65\x53\x70\x65\x65\ -\x64\x22\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\ -\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\ -\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\ -\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x52\x38\ -\x41\x41\x41\x41\x70\x43\x41\x59\x41\x41\x41\x41\x4d\x41\x79\x31\ -\x4a\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\ -\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x48\x69\x68\x4a\x52\x45\x46\ -\x55\x20\x65\x4a\x7a\x74\x6e\x58\x64\x34\x56\x46\x58\x36\x78\x7a\ -\x2f\x54\x61\x7a\x4b\x54\x6d\x55\x6b\x6a\x6a\x59\x54\x51\x51\x69\ -\x67\x4b\x32\x43\x6c\x57\x31\x72\x35\x59\x31\x37\x4a\x69\x58\x63\ -\x74\x61\x31\x72\x61\x75\x5a\x58\x55\x74\x61\x2f\x6e\x70\x36\x75\ -\x34\x71\x72\x67\x58\x64\x74\x61\x30\x67\x43\x77\x49\x57\x20\x6d\ -\x6f\x41\x46\x6b\x43\x49\x6c\x51\x41\x67\x51\x45\x6b\x68\x49\x53\ -\x47\x2f\x54\x35\x39\x62\x66\x48\x78\x4d\x69\x4a\x59\x48\x41\x44\ -\x50\x43\x48\x38\x33\x6d\x65\x50\x44\x79\x5a\x4f\x2b\x66\x65\x62\ -\x30\x35\x35\x7a\x7a\x6e\x76\x2b\x39\x36\x44\x35\x73\x55\x58\x58\ -\x6c\x42\x4a\x6b\x43\x42\x42\x67\x6d\x4f\x4d\x20\x50\x69\x4d\x7a\ -\x34\x33\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x66\x55\x46\x2b\ -\x2f\x76\x48\x57\x6b\x43\x42\x42\x67\x6c\x38\x67\x65\x72\x66\x62\ -\x66\x62\x77\x31\x4a\x45\x69\x51\x34\x42\x65\x49\x50\x6a\x6b\x35\ -\x2b\x58\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x76\x64\x56\x71\ -\x50\x64\x34\x61\x45\x69\x52\x49\x20\x38\x41\x74\x45\x62\x7a\x41\ -\x59\x59\x72\x71\x42\x4a\x4d\x76\x38\x38\x36\x74\x76\x6d\x4c\x31\ -\x36\x50\x58\x6b\x65\x4e\x34\x4e\x7a\x4d\x68\x6d\x63\x6e\x55\x6d\ -\x2f\x6a\x48\x52\x79\x33\x43\x6b\x34\x62\x66\x45\x7a\x62\x6b\x32\ -\x4e\x44\x57\x54\x6e\x35\x42\x47\x4a\x68\x4f\x4e\x32\x7a\x34\x72\ -\x36\x52\x6e\x34\x6f\x20\x4b\x79\x66\x50\x34\x79\x4c\x4c\x6e\x55\ -\x4b\x47\x30\x30\x47\x79\x31\x52\x4b\x33\x2b\x78\x38\x75\x4e\x53\ -\x31\x74\x31\x44\x53\x33\x6b\x75\x5a\x49\x4a\x74\x32\x5a\x6a\x4d\ -\x31\x73\x4f\x6d\x35\x61\x41\x46\x5a\x73\x72\x65\x43\x37\x7a\x56\ -\x76\x4a\x38\x37\x6a\x4a\x54\x2f\x65\x51\x6b\x65\x49\x6b\x7a\x5a\ -\x47\x4d\x20\x78\x52\x68\x62\x76\x39\x6d\x66\x6f\x39\x47\x32\x4b\ -\x37\x5a\x57\x38\x4e\x58\x61\x44\x65\x53\x6e\x65\x52\x69\x51\x6d\ -\x55\x47\x4b\x33\x55\x5a\x75\x71\x6f\x73\x6b\x69\x7a\x6c\x75\x7a\ -\x7a\x68\x63\x50\x63\x65\x69\x4c\x6e\x76\x4c\x6b\x6f\x31\x6c\x7a\ -\x46\x75\x2f\x69\x56\x79\x33\x6d\x33\x34\x5a\x71\x66\x52\x78\x20\ -\x70\x35\x44\x75\x53\x4d\x4b\x54\x6c\x49\x52\x4f\x70\x34\x33\x62\ -\x63\x33\x70\x71\x57\x33\x30\x73\x4e\x32\x31\x6f\x37\x2b\x44\x78\ -\x54\x32\x61\x69\x4e\x78\x69\x35\x61\x50\x53\x4a\x58\x44\x76\x2b\ -\x4e\x45\x71\x72\x61\x79\x69\x74\x72\x6d\x58\x42\x68\x69\x33\x73\ -\x61\x6d\x70\x42\x72\x39\x57\x53\x35\x58\x49\x77\x20\x73\x45\x38\ -\x6d\x52\x54\x6d\x5a\x46\x47\x61\x6b\x34\x55\x36\x32\x59\x7a\x63\ -\x66\x6e\x77\x36\x77\x42\x31\x6c\x52\x2b\x47\x4c\x31\x65\x6c\x36\ -\x66\x75\x34\x51\x42\x57\x52\x6e\x73\x62\x47\x36\x6a\x75\x71\x6d\ -\x46\x68\x76\x59\x4f\x6a\x46\x6f\x64\x47\x63\x35\x6b\x63\x6c\x50\ -\x64\x46\x47\x61\x6d\x4d\x69\x41\x7a\x20\x67\x33\x52\x6e\x4d\x6b\ -\x6b\x57\x4d\x31\x61\x54\x45\x59\x31\x47\x45\x33\x63\x39\x6b\x69\ -\x7a\x7a\x78\x55\x38\x6c\x50\x44\x5a\x6a\x4c\x71\x30\x36\x45\x79\ -\x5a\x46\x77\x6f\x61\x4d\x78\x32\x4b\x68\x77\x4a\x4e\x43\x51\x61\ -\x71\x62\x2f\x44\x51\x50\x2b\x52\x6d\x70\x35\x48\x6c\x63\x58\x56\ -\x70\x4d\x4d\x55\x34\x65\x20\x50\x52\x45\x57\x52\x4e\x35\x64\x2b\ -\x44\x31\x66\x72\x39\x76\x49\x4f\x53\x4f\x4b\x61\x51\x38\x4c\x7a\ -\x46\x68\x56\x51\x6c\x31\x72\x47\x38\x30\x64\x50\x6d\x77\x57\x45\ -\x2b\x6e\x4a\x79\x57\x53\x37\x6e\x66\x54\x50\x54\x4b\x4d\x67\x50\ -\x59\x32\x4d\x46\x41\x63\x4f\x71\x2b\x57\x34\x47\x38\x77\x39\x32\ -\x71\x66\x2f\x20\x2b\x42\x4e\x31\x51\x5a\x47\x2b\x41\x34\x70\x70\ -\x57\x37\x6d\x56\x6b\x4b\x38\x64\x67\x79\x70\x69\x30\x65\x6e\x49\ -\x64\x6a\x6b\x59\x6d\x70\x31\x4a\x75\x6a\x4f\x4a\x51\x64\x6c\x39\ -\x4b\x45\x68\x50\x78\x57\x59\x79\x34\x6b\x71\x79\x48\x7a\x55\x39\ -\x30\x35\x61\x76\x78\x6d\x34\x78\x38\x2b\x75\x54\x52\x78\x37\x58\ -\x20\x75\x76\x53\x48\x77\x72\x7a\x32\x78\x55\x4c\x65\x58\x4c\x79\ -\x55\x6b\x58\x6e\x5a\x6a\x4f\x78\x66\x79\x4a\x71\x71\x57\x6d\x61\ -\x76\x32\x55\x42\x64\x61\x7a\x74\x68\x51\x63\x52\x74\x74\x35\x48\ -\x68\x54\x43\x59\x2f\x33\x55\x4e\x42\x65\x69\x72\x35\x61\x61\x6d\ -\x34\x6b\x71\x79\x6b\x4f\x5a\x4c\x6a\x31\x76\x38\x31\x20\x33\x6f\ -\x37\x32\x49\x38\x72\x7a\x57\x56\x4f\x78\x6b\x38\x63\x2b\x2b\x5a\ -\x79\x37\x4c\x6a\x79\x58\x38\x30\x63\x4e\x5a\x2b\x58\x57\x37\x56\ -\x77\x77\x61\x73\x51\x2b\x33\x31\x45\x55\x68\x59\x5a\x32\x4c\x39\ -\x56\x4e\x4c\x57\x79\x70\x32\x63\x32\x6d\x71\x68\x6f\x32\x56\x64\ -\x65\x77\x73\x36\x47\x52\x6d\x58\x2b\x38\x20\x69\x32\x79\x33\x36\ -\x37\x43\x65\x47\x61\x2f\x5a\x4d\x52\x67\x52\x65\x47\x72\x71\x62\ -\x4e\x70\x43\x59\x5a\x36\x2b\x35\x6a\x4c\x4b\x61\x6e\x59\x7a\x38\ -\x64\x52\x52\x51\x4e\x51\x6f\x4e\x58\x74\x39\x31\x4c\x61\x30\x55\ -\x64\x58\x59\x7a\x4c\x62\x61\x4f\x72\x62\x57\x31\x72\x4f\x37\x74\ -\x51\x31\x76\x4d\x45\x69\x53\x20\x32\x63\x53\x37\x64\x30\x34\x69\ -\x78\x57\x36\x4c\x53\x63\x50\x65\x64\x41\x53\x43\x50\x50\x48\x70\ -\x4c\x4c\x37\x61\x55\x55\x39\x79\x30\x51\x68\x55\x67\x78\x46\x52\ -\x6c\x6f\x68\x49\x49\x75\x46\x51\x6b\x45\x67\x77\x67\x42\x41\x4b\ -\x51\x43\x67\x45\x34\x53\x41\x47\x55\x63\x42\x6a\x30\x4a\x4a\x6d\ -\x4d\x6e\x4a\x79\x20\x59\x56\x39\x65\x76\x50\x35\x79\x39\x44\x70\ -\x64\x33\x50\x54\x55\x74\x58\x62\x77\x38\x49\x66\x54\x36\x4e\x65\ -\x6e\x44\x35\x65\x65\x63\x69\x49\x66\x4c\x56\x37\x4b\x6c\x48\x74\ -\x76\x36\x37\x6f\x75\x53\x68\x49\x4e\x37\x56\x37\x71\x32\x74\x71\ -\x70\x62\x6d\x70\x68\x57\x32\x30\x64\x46\x58\x57\x4e\x56\x4e\x51\ -\x33\x20\x30\x4e\x6a\x65\x7a\x76\x38\x65\x2f\x6a\x33\x5a\x37\x70\ -\x54\x44\x65\x6d\x61\x38\x32\x6e\x5a\x76\x37\x62\x38\x39\x38\x33\ -\x52\x75\x66\x6d\x38\x6d\x76\x37\x72\x73\x52\x76\x78\x43\x47\x48\ -\x38\x6b\x54\x48\x76\x41\x52\x33\x4e\x62\x43\x32\x30\x64\x72\x62\ -\x53\x33\x74\x2b\x4a\x72\x62\x79\x58\x6b\x62\x55\x63\x4a\x20\x42\ -\x55\x6a\x58\x4b\x73\x7a\x37\x38\x77\x50\x30\x54\x66\x50\x45\x70\ -\x4b\x45\x6e\x50\x54\x65\x64\x4f\x35\x62\x5a\x4b\x39\x62\x77\x78\ -\x4e\x57\x2f\x37\x72\x72\x65\x55\x31\x33\x75\x61\x47\x69\x6b\x76\ -\x71\x33\x74\x69\x4f\x72\x79\x59\x47\x79\x74\x72\x65\x50\x75\x39\ -\x7a\x35\x6c\x68\x32\x4c\x45\x31\x69\x65\x58\x20\x6b\x31\x51\x66\ -\x55\x78\x2b\x2b\x71\x2b\x75\x36\x71\x71\x70\x34\x51\x32\x45\x61\ -\x32\x74\x71\x70\x61\x32\x32\x6e\x6f\x72\x36\x52\x37\x58\x55\x4e\ -\x6c\x4f\x32\x71\x5a\x58\x46\x4a\x4b\x51\x75\x66\x65\x6f\x6a\x42\ -\x4f\x5a\x6d\x48\x39\x63\x79\x34\x72\x58\x77\x6b\x57\x65\x59\x2f\ -\x53\x35\x59\x78\x61\x33\x55\x4a\x20\x37\x39\x33\x33\x4f\x77\x5a\ -\x6c\x5a\x37\x4b\x39\x72\x6f\x46\x2f\x66\x2f\x50\x39\x41\x63\x5a\ -\x48\x71\x39\x57\x53\x36\x58\x4b\x53\x36\x58\x4a\x79\x38\x73\x42\ -\x2b\x68\x45\x57\x52\x33\x37\x30\x2b\x68\x52\x56\x62\x79\x6d\x6e\ -\x32\x2b\x67\x2f\x62\x2b\x4d\x53\x44\x44\x56\x55\x31\x50\x50\x4c\ -\x52\x64\x4b\x34\x2f\x20\x63\x77\x79\x33\x54\x54\x69\x54\x6e\x59\ -\x33\x4e\x66\x4c\x78\x6b\x61\x5a\x66\x78\x30\x57\x6d\x31\x70\x44\ -\x73\x64\x70\x44\x73\x64\x6e\x4e\x69\x76\x4c\x78\x42\x74\x45\x45\ -\x56\x56\x2b\x64\x76\x6e\x58\x2f\x4f\x6e\x2f\x30\x7a\x46\x47\x77\ -\x7a\x46\x78\x66\x69\x6f\x71\x73\x71\x79\x73\x75\x33\x38\x34\x65\ -\x4f\x5a\x20\x6d\x50\x4f\x48\x4d\x50\x79\x73\x55\x55\x69\x4b\x67\ -\x69\x68\x4c\x68\x43\x57\x52\x6b\x43\x67\x51\x4e\x4a\x6f\x49\x57\ -\x6d\x7a\x34\x68\x54\x42\x68\x55\x55\x41\x46\x52\x46\x57\x6c\x54\ -\x6c\x57\x70\x4b\x79\x38\x6a\x73\x4b\x47\x4d\x73\x43\x42\x69\x74\ -\x38\x52\x75\x66\x46\x52\x56\x5a\x57\x46\x4a\x4b\x53\x2f\x4e\x20\ -\x6d\x73\x64\x54\x31\x31\x7a\x4f\x42\x61\x4f\x47\x30\x39\x54\x68\ -\x34\x36\x6f\x78\x70\x2b\x7a\x7a\x50\x59\x4e\x65\x54\x37\x62\x48\ -\x52\x62\x62\x48\x78\x65\x6a\x2b\x42\x51\x41\x45\x49\x78\x47\x75\ -\x65\x58\x6b\x79\x33\x35\x61\x56\x45\x34\x78\x45\x59\x74\x59\x53\ -\x44\x2b\x30\x37\x47\x35\x74\x52\x46\x42\x6b\x56\x20\x46\x55\x56\ -\x52\x6b\x42\x55\x46\x74\x46\x71\x4d\x4e\x6a\x73\x57\x76\x51\x37\ -\x4a\x5a\x6b\x64\x78\x70\x79\x4b\x48\x41\x67\x52\x4b\x53\x39\x6a\ -\x64\x32\x6b\x78\x45\x46\x49\x2b\x61\x6e\x76\x5a\x41\x73\x4b\x74\ -\x50\x37\x61\x47\x37\x75\x74\x77\x7a\x54\x6c\x61\x56\x56\x38\x61\ -\x74\x4c\x6b\x56\x4a\x34\x73\x4e\x76\x20\x66\x2b\x53\x76\x58\x79\ -\x79\x69\x33\x2b\x69\x78\x6a\x4d\x7a\x75\x53\x33\x74\x7a\x41\x30\ -\x70\x7a\x78\x7a\x37\x66\x30\x32\x67\x30\x4f\x4b\x77\x57\x48\x46\ -\x59\x4c\x41\x37\x49\x79\x47\x54\x64\x30\x4d\x43\x46\x42\x34\x4a\ -\x5a\x2f\x76\x49\x74\x4f\x70\x30\x4e\x52\x34\x35\x65\x54\x66\x46\ -\x6a\x47\x70\x38\x58\x6e\x20\x35\x36\x6c\x70\x73\x7a\x47\x62\x7a\ -\x4d\x78\x35\x34\x67\x45\x63\x6e\x66\x36\x63\x62\x4c\x65\x4c\x4a\ -\x36\x36\x2b\x39\x4b\x42\x6c\x4a\x56\x6e\x6d\x6d\x55\x38\x2f\x52\ -\x36\x50\x52\x4d\x50\x48\x55\x55\x53\x6a\x4b\x73\x55\x32\x73\x46\ -\x69\x57\x5a\x44\x37\x35\x62\x7a\x68\x65\x72\x53\x33\x6a\x39\x39\ -\x68\x73\x5a\x20\x55\x5a\x43\x48\x52\x71\x4f\x68\x6a\x38\x76\x4a\ -\x30\x39\x64\x64\x66\x73\x6a\x79\x55\x2b\x5a\x2f\x79\x2b\x77\x56\ -\x61\x7a\x68\x6a\x79\x45\x42\x30\x63\x56\x68\x6c\x42\x4d\x49\x52\ -\x58\x76\x74\x69\x49\x54\x4d\x32\x56\x54\x4c\x69\x72\x49\x6b\x6b\ -\x70\x62\x69\x52\x46\x49\x58\x49\x48\x71\x4d\x6a\x52\x4e\x42\x72\ -\x20\x74\x57\x6a\x51\x6f\x4b\x6f\x67\x4b\x54\x4b\x53\x4c\x43\x4d\ -\x71\x4d\x71\x67\x71\x6d\x71\x6f\x4b\x72\x69\x6b\x71\x59\x46\x76\ -\x4e\x37\x72\x6a\x73\x7a\x2f\x32\x68\x4d\x4b\x2f\x4d\x6d\x55\x39\ -\x46\x59\x77\x76\x2f\x65\x2f\x51\x2b\x63\x6a\x78\x75\x4e\x42\x6f\ -\x4e\x49\x55\x46\x67\x35\x64\x62\x74\x6e\x48\x66\x43\x20\x30\x42\ -\x37\x4c\x43\x70\x4c\x45\x2f\x56\x4d\x2b\x59\x56\x47\x44\x46\x36\ -\x50\x4c\x67\x2f\x6b\x6f\x62\x51\x56\x37\x6f\x69\x66\x74\x42\x70\ -\x30\x4f\x55\x52\x4a\x6f\x44\x77\x57\x6a\x64\x53\x70\x47\x43\x49\ -\x6b\x69\x59\x55\x6b\x6b\x49\x6b\x6c\x45\x4f\x6c\x65\x58\x6b\x63\ -\x70\x74\x59\x44\x53\x69\x53\x58\x62\x45\x20\x52\x58\x74\x50\x65\ -\x6c\x70\x38\x66\x6a\x35\x61\x73\x76\x53\x41\x53\x58\x70\x76\x39\ -\x68\x34\x6e\x34\x34\x63\x4f\x6a\x6f\x75\x65\x58\x63\x32\x74\x50\ -\x50\x72\x4a\x54\x4d\x70\x38\x43\x68\x4f\x75\x75\x67\x57\x72\x4c\ -\x51\x6c\x5a\x55\x64\x41\x47\x41\x38\x69\x48\x47\x49\x65\x69\x4a\ -\x50\x48\x59\x68\x35\x2b\x52\x20\x35\x6b\x78\x6d\x7a\x4a\x42\x42\ -\x63\x66\x56\x50\x39\x62\x72\x58\x62\x71\x6d\x70\x34\x39\x72\x58\ -\x33\x6d\x46\x4d\x63\x52\x47\x54\x37\x35\x6a\x55\x5a\x58\x67\x41\ -\x4f\x6f\x4a\x42\x6e\x70\x38\x2b\x35\x36\x44\x6c\x2f\x7a\x56\x33\ -\x45\x65\x73\x71\x64\x2f\x4c\x47\x48\x54\x64\x69\x4d\x75\x68\x52\ -\x56\x4f\x58\x49\x20\x56\x52\x38\x6d\x37\x59\x45\x67\x74\x2f\x2f\ -\x72\x41\x37\x62\x58\x4e\x7a\x50\x6a\x73\x54\x39\x77\x51\x72\x2b\ -\x2b\x58\x66\x76\x57\x56\x70\x2b\x66\x70\x7a\x2f\x39\x2f\x4b\x44\ -\x6c\x70\x79\x39\x64\x79\x5a\x51\x46\x53\x2f\x6a\x30\x6a\x33\x65\ -\x54\x5a\x44\x47\x6a\x6a\x58\x48\x50\x75\x37\x32\x75\x67\x63\x74\ -\x66\x20\x65\x59\x76\x76\x57\x68\x55\x75\x75\x50\x77\x6d\x42\x76\ -\x59\x74\x4a\x44\x50\x5a\x69\x64\x74\x71\x4a\x38\x6c\x6b\x78\x6d\ -\x6f\x77\x59\x74\x49\x62\x4d\x4f\x6a\x30\x36\x4c\x56\x61\x64\x46\ -\x6f\x4e\x57\x6f\x33\x6d\x35\x37\x31\x32\x54\x54\x55\x54\x30\x6c\ -\x4e\x34\x2b\x36\x36\x62\x55\x52\x57\x56\x57\x48\x66\x67\x20\x4f\ -\x78\x71\x61\x2b\x4d\x31\x72\x37\x2b\x42\x78\x4f\x70\x6e\x36\x38\ -\x4f\x2f\x4a\x54\x66\x56\x30\x50\x55\x74\x57\x46\x42\x72\x62\x76\ -\x51\x63\x74\x2f\x2b\x4c\x30\x4c\x2f\x69\x73\x64\x41\x63\x70\x51\ -\x34\x5a\x6a\x30\x47\x72\x52\x61\x75\x50\x6e\x72\x44\x77\x55\x42\ -\x39\x4e\x75\x30\x4f\x75\x51\x4a\x49\x6d\x32\x20\x6b\x4a\x2b\x4f\ -\x55\x41\x42\x76\x4f\x49\x78\x66\x43\x42\x4d\x51\x49\x70\x32\x47\ -\x53\x43\x43\x77\x63\x7a\x74\x53\x4f\x41\x78\x35\x42\x61\x41\x6f\ -\x4d\x57\x73\x2f\x6d\x4a\x35\x73\x74\x34\x74\x6e\x72\x72\x76\x69\ -\x6f\x4f\x58\x33\x48\x69\x63\x61\x4e\x44\x48\x72\x6d\x62\x64\x32\ -\x49\x78\x65\x2b\x4e\x42\x6d\x76\x20\x75\x34\x41\x4c\x4a\x31\x35\ -\x50\x51\x55\x59\x4f\x36\x55\x6b\x4f\x6e\x42\x59\x72\x46\x71\x50\ -\x70\x6b\x43\x75\x5a\x6c\x32\x5a\x38\x53\x58\x31\x62\x42\x79\x39\ -\x4d\x75\x68\x70\x4a\x6c\x6a\x45\x61\x34\x72\x65\x39\x37\x39\x58\ -\x4b\x35\x39\x4d\x66\x56\x76\x4c\x43\x7a\x4b\x2f\x35\x35\x4b\x48\ -\x66\x63\x2b\x71\x67\x20\x77\x67\x4d\x63\x54\x6c\x61\x54\x69\x5a\ -\x50\x36\x39\x2b\x75\x32\x72\x4b\x71\x71\x7a\x46\x69\x2b\x6d\x6b\ -\x2b\x2f\x57\x38\x36\x58\x54\x7a\x37\x55\x4f\x58\x69\x31\x30\x53\ -\x58\x77\x4d\x65\x43\x62\x6b\x6c\x49\x65\x2f\x76\x42\x2f\x50\x48\ -\x7a\x35\x52\x64\x78\x32\x33\x76\x67\x44\x47\x74\x4e\x6d\x4e\x6a\ -\x4e\x2b\x20\x36\x4f\x42\x75\x79\x36\x71\x71\x79\x74\x77\x31\x4a\ -\x54\x77\x37\x62\x52\x5a\x7a\x6e\x6e\x69\x41\x33\x46\x51\x33\x69\ -\x71\x4b\x69\x30\x78\x37\x35\x63\x48\x2f\x39\x71\x30\x57\x38\x4e\ -\x75\x38\x37\x52\x70\x30\x33\x6b\x62\x7a\x63\x41\x76\x52\x36\x41\ -\x37\x4b\x69\x49\x4d\x6b\x79\x67\x69\x77\x69\x79\x4e\x4c\x50\x20\ -\x50\x35\x4b\x30\x7a\x2b\x2b\x53\x4c\x45\x4e\x64\x44\x65\x4f\x53\ -\x6a\x45\x7a\x37\x34\x39\x33\x59\x7a\x4e\x48\x4f\x6f\x39\x55\x63\ -\x65\x51\x65\x64\x2b\x73\x4e\x4b\x6e\x70\x6f\x32\x68\x7a\x66\x75\ -\x6d\x4d\x54\x45\x55\x30\x63\x64\x30\x4c\x59\x5a\x4b\x51\x36\x75\ -\x48\x58\x39\x61\x74\x32\x56\x56\x56\x65\x58\x39\x20\x68\x64\x2f\ -\x78\x32\x70\x4b\x56\x35\x4a\x78\x32\x4a\x6c\x35\x52\x51\x4b\x38\ -\x42\x58\x51\x78\x36\x44\x6f\x65\x70\x50\x36\x7a\x6b\x72\x7a\x4f\ -\x2f\x5a\x73\x6f\x39\x74\x33\x48\x32\x38\x4b\x49\x44\x74\x42\x74\ -\x30\x4f\x6d\x52\x5a\x6f\x69\x58\x67\x52\x35\x42\x2b\x33\x73\x6f\ -\x47\x68\x41\x68\x42\x49\x59\x4a\x33\x20\x31\x77\x34\x69\x4c\x59\ -\x30\x77\x73\x42\x69\x30\x57\x72\x53\x6f\x78\x44\x4b\x76\x48\x45\ -\x70\x50\x55\x34\x65\x58\x68\x39\x37\x2f\x4c\x37\x4f\x66\x65\x4f\ -\x43\x41\x73\x74\x32\x4e\x45\x31\x6d\x52\x59\x36\x72\x4c\x76\x30\ -\x79\x64\x7a\x56\x76\x66\x72\x75\x44\x30\x38\x36\x38\x67\x4e\x79\ -\x63\x66\x57\x56\x55\x4a\x20\x43\x68\x46\x6b\x56\x53\x45\x6b\x43\ -\x6b\x52\x6b\x43\x58\x6f\x59\x68\x34\x71\x71\x38\x75\x36\x38\x78\ -\x58\x79\x2f\x61\x51\x73\x7a\x48\x2f\x38\x44\x46\x71\x4d\x52\x57\ -\x5a\x46\x69\x36\x6d\x76\x37\x30\x79\x76\x6a\x38\x2f\x37\x69\x70\ -\x65\x53\x6d\x65\x6e\x6a\x77\x76\x55\x39\x77\x32\x71\x30\x55\x35\ -\x57\x51\x78\x20\x75\x6e\x38\x42\x77\x77\x76\x79\x79\x48\x41\x36\ -\x4d\x42\x6b\x4d\x36\x48\x71\x77\x30\x45\x73\x32\x62\x4f\x62\x35\ -\x7a\x32\x59\x7a\x36\x34\x6e\x37\x75\x79\x49\x4a\x4f\x71\x33\x32\ -\x6b\x4d\x75\x39\x65\x50\x48\x43\x72\x50\x6e\x6f\x55\x6a\x4c\x34\ -\x35\x2f\x79\x6c\x76\x4c\x39\x6f\x47\x63\x50\x79\x2b\x6c\x43\x63\ -\x20\x6d\x38\x30\x70\x41\x77\x76\x4a\x54\x58\x56\x68\x4e\x42\x69\ -\x49\x69\x46\x4c\x33\x32\x6a\x65\x57\x38\x61\x63\x50\x70\x76\x48\ -\x5a\x49\x2f\x65\x53\x6e\x35\x45\x47\x52\x46\x63\x43\x50\x66\x32\ -\x74\x76\x65\x47\x2f\x50\x36\x79\x6b\x4b\x43\x75\x64\x48\x61\x73\ -\x57\x73\x32\x50\x44\x4b\x71\x77\x4f\x4e\x36\x36\x30\x20\x50\x74\ -\x68\x53\x58\x47\x41\x77\x49\x41\x42\x42\x49\x54\x70\x41\x39\x6a\ -\x68\x4a\x2f\x5a\x45\x49\x51\x55\x46\x41\x61\x61\x78\x6a\x75\x42\ -\x70\x68\x2b\x70\x38\x65\x49\x64\x6c\x71\x51\x5a\x51\x6b\x64\x44\ -\x6f\x74\x32\x68\x69\x4d\x34\x62\x2b\x58\x4c\x4f\x4f\x30\x77\x66\ -\x33\x35\x2b\x2b\x78\x35\x76\x44\x70\x72\x20\x4c\x6f\x56\x39\x30\ -\x68\x6d\x57\x6c\x38\x50\x4a\x41\x77\x76\x70\x6d\x35\x35\x4b\x57\ -\x42\x42\x34\x2f\x72\x4d\x35\x66\x50\x48\x6b\x67\x77\x65\x55\x6e\ -\x62\x31\x69\x44\x59\x2f\x2f\x62\x79\x35\x44\x78\x31\x2b\x41\x58\ -\x31\x56\x51\x68\x41\x68\x36\x51\x4b\x65\x4c\x66\x7a\x53\x77\x4f\ -\x39\x35\x62\x76\x49\x79\x38\x20\x56\x41\x39\x2f\x2f\x6e\x67\x36\ -\x66\x35\x74\x31\x59\x4c\x2f\x55\x36\x62\x51\x6f\x73\x6b\x52\x4c\ -\x77\x49\x65\x6f\x79\x46\x45\x48\x76\x74\x68\x70\x67\x42\x70\x32\ -\x45\x36\x36\x70\x67\x73\x48\x46\x30\x4c\x6d\x4e\x6a\x72\x62\x71\ -\x6b\x57\x73\x2f\x6c\x42\x36\x72\x32\x63\x52\x5a\x77\x34\x71\x36\ -\x4c\x64\x76\x64\x20\x4f\x4a\x46\x6b\x4a\x61\x61\x36\x2f\x47\x72\ -\x74\x52\x69\x77\x70\x48\x74\x59\x75\x2f\x59\x62\x31\x47\x67\x33\ -\x4a\x44\x69\x64\x4f\x54\x7a\x72\x4a\x37\x6a\x52\x4d\x53\x51\x36\ -\x38\x76\x67\x34\x63\x33\x52\x67\x66\x56\x56\x58\x35\x33\x39\x4b\ -\x56\x66\x4c\x68\x6b\x4b\x56\x2f\x38\x2b\x63\x47\x75\x79\x4c\x51\ -\x6b\x20\x78\x7a\x62\x78\x37\x6b\x2b\x76\x6a\x49\x38\x6e\x32\x63\ -\x37\x6b\x4f\x32\x38\x6d\x49\x38\x58\x42\x31\x74\x6f\x36\x64\x6a\ -\x59\x30\x38\x58\x33\x70\x56\x6a\x37\x35\x64\x6a\x6e\x56\x54\x53\ -\x32\x34\x6b\x32\x78\x73\x32\x31\x31\x50\x70\x73\x76\x4a\x36\x50\ -\x34\x46\x39\x45\x33\x7a\x6f\x4e\x56\x71\x32\x56\x53\x31\x20\x69\ -\x2f\x75\x6e\x66\x4d\x7a\x37\x39\x2f\x32\x4f\x33\x4e\x53\x66\x49\ -\x77\x68\x61\x72\x65\x61\x59\x2b\x58\x7a\x73\x56\x67\x74\x44\x7a\ -\x37\x69\x45\x56\x4a\x63\x48\x76\x39\x39\x4c\x59\x31\x4d\x39\x30\ -\x79\x71\x71\x2b\x4d\x63\x50\x4d\x78\x42\x38\x62\x61\x53\x5a\x64\ -\x54\x53\x30\x64\x57\x44\x55\x36\x78\x69\x61\x20\x6c\x38\x50\x6f\ -\x41\x66\x32\x77\x6d\x6f\x79\x73\x72\x64\x6a\x4a\x41\x31\x4d\x2b\ -\x35\x72\x31\x37\x62\x6d\x56\x51\x39\x73\x2f\x65\x66\x55\x57\x56\ -\x59\x39\x70\x32\x5a\x58\x74\x63\x76\x48\x33\x33\x4c\x58\x69\x53\ -\x6b\x39\x6a\x52\x30\x45\x54\x35\x37\x6e\x70\x57\x62\x61\x74\x67\ -\x30\x2b\x59\x79\x4e\x75\x78\x75\x20\x77\x71\x74\x6f\x4d\x44\x69\ -\x63\x61\x4f\x78\x4a\x53\x46\x59\x62\x49\x5a\x32\x57\x69\x43\x53\ -\x68\x74\x44\x5a\x54\x47\x47\x68\x6e\x78\x6c\x4d\x50\x6b\x75\x70\ -\x49\x41\x6b\x43\x51\x6f\x6a\x4e\x6a\x4c\x48\x70\x63\x53\x54\x5a\ -\x65\x76\x66\x56\x36\x73\x74\x77\x70\x31\x4c\x65\x31\x55\x31\x48\ -\x58\x79\x4c\x72\x4b\x20\x4b\x74\x36\x5a\x76\x35\x68\x74\x74\x58\ -\x57\x45\x52\x59\x6d\x77\x49\x50\x44\x50\x4c\x2b\x5a\x54\x6e\x4a\ -\x66\x44\x4b\x51\x50\x37\x59\x54\x57\x5a\x2b\x48\x46\x4c\x4f\x66\ -\x66\x2b\x5a\x7a\x6f\x6a\x7a\x72\x6f\x49\x32\x57\x7a\x47\x36\x2f\ -\x63\x68\x4b\x51\x70\x36\x72\x53\x59\x6d\x34\x33\x77\x34\x65\x4a\ -\x4a\x74\x20\x76\x48\x6e\x58\x4c\x61\x51\x37\x6b\x37\x76\x76\x6c\ -\x38\x6c\x32\x6d\x74\x76\x61\x43\x46\x5a\x75\x51\x35\x4f\x55\x6a\ -\x47\x51\x77\x45\x4a\x45\x6b\x77\x6d\x30\x74\x53\x4a\x58\x6c\x4d\ -\x4c\x41\x49\x39\x44\x2f\x37\x4d\x48\x51\x51\x30\x38\x72\x6e\x55\ -\x48\x70\x53\x48\x55\x6e\x6b\x70\x58\x6d\x59\x39\x73\x4f\x4b\x20\ -\x58\x6f\x30\x54\x4a\x63\x61\x4a\x7a\x6d\x77\x30\x34\x4f\x34\x2f\ -\x46\x49\x63\x6e\x44\x56\x55\x55\x69\x50\x68\x39\x74\x4c\x61\x31\ -\x55\x4c\x31\x70\x4c\x53\x46\x66\x4f\x33\x49\x34\x6a\x45\x73\x48\ -\x7a\x30\x32\x62\x78\x61\x6a\x43\x41\x6b\x37\x6f\x6c\x30\x65\x61\ -\x49\x35\x6b\x6c\x47\x38\x74\x34\x61\x63\x61\x58\x20\x66\x50\x62\ -\x49\x50\x66\x75\x6b\x48\x73\x51\x36\x38\x65\x35\x50\x72\x34\x79\ -\x50\x32\x57\x41\x6b\x4a\x41\x69\x59\x44\x41\x61\x47\x39\x63\x31\ -\x6c\x57\x4e\x39\x63\x4c\x6a\x6c\x35\x4a\x47\x72\x6e\x66\x72\x47\ -\x71\x71\x5a\x6c\x50\x76\x6c\x33\x4f\x75\x6f\x6f\x71\x70\x69\x7a\ -\x34\x6c\x6a\x61\x66\x48\x34\x38\x6a\x20\x6d\x5a\x72\x6d\x56\x74\ -\x36\x34\x34\x34\x59\x44\x50\x50\x77\x36\x72\x52\x62\x35\x47\x50\ -\x6c\x38\x7a\x41\x59\x6a\x76\x6c\x41\x41\x55\x38\x53\x4f\x78\x6d\ -\x44\x45\x6d\x5a\x47\x46\x79\x5a\x31\x4b\x35\x71\x42\x68\x42\x49\ -\x51\x77\x37\x58\x34\x76\x32\x6f\x71\x74\x2f\x47\x56\x35\x4b\x66\ -\x34\x76\x6c\x79\x44\x37\x20\x66\x65\x51\x37\x37\x49\x69\x52\x43\ -\x42\x2f\x38\x34\x58\x5a\x47\x39\x53\x2f\x59\x5a\x2f\x6b\x73\x53\ -\x72\x45\x31\x67\x4e\x31\x73\x78\x42\x73\x4d\x6b\x5a\x66\x6d\x6f\ -\x54\x67\x76\x6d\x2b\x4b\x38\x62\x48\x35\x39\x79\x73\x69\x75\x36\ -\x36\x75\x32\x56\x66\x44\x45\x52\x39\x4d\x5a\x30\x7a\x2b\x44\x46\ -\x56\x75\x33\x20\x55\x39\x48\x63\x79\x67\x35\x2f\x69\x41\x77\x64\ -\x7a\x48\x72\x71\x49\x66\x70\x31\x72\x73\x43\x69\x57\x69\x54\x30\ -\x75\x74\x68\x38\x4c\x43\x61\x39\x67\x62\x41\x67\x6f\x74\x4e\x71\ -\x79\x58\x4b\x37\x79\x48\x4b\x37\x47\x46\x73\x38\x71\x4b\x74\x74\ -\x61\x31\x76\x62\x75\x50\x72\x46\x31\x39\x46\x71\x4e\x48\x79\x34\ -\x20\x36\x41\x63\x65\x2f\x57\x42\x71\x39\x50\x4e\x32\x50\x36\x4d\ -\x6e\x58\x49\x48\x4a\x36\x61\x4c\x4a\x37\x30\x56\x53\x5a\x41\x52\ -\x5a\x77\x6f\x4a\x36\x7a\x49\x7a\x50\x48\x75\x30\x39\x39\x63\x75\ -\x64\x6a\x63\x32\x63\x39\x71\x66\x6e\x61\x47\x79\x6f\x52\x61\x6e\ -\x59\x41\x70\x49\x59\x4e\x54\x61\x69\x43\x50\x30\x48\x20\x67\x33\ -\x6e\x66\x5a\x46\x4b\x39\x52\x68\x50\x54\x4e\x75\x64\x51\x65\x6a\ -\x5a\x56\x31\x58\x44\x72\x36\x2b\x2b\x53\x37\x6e\x54\x30\x61\x70\ -\x7a\x49\x73\x68\x78\x54\x58\x56\x70\x4e\x42\x6e\x62\x35\x4f\x67\ -\x67\x61\x6a\x57\x69\x31\x57\x72\x51\x47\x41\x32\x70\x61\x42\x71\ -\x62\x55\x4e\x48\x53\x79\x51\x74\x6a\x58\x20\x67\x61\x74\x32\x4f\ -\x33\x31\x63\x4b\x55\x78\x66\x74\x70\x4b\x2f\x66\x6a\x59\x4c\x58\ -\x79\x68\x4d\x59\x34\x65\x58\x75\x58\x39\x35\x6d\x48\x36\x5a\x36\ -\x66\x76\x71\x55\x57\x4c\x54\x73\x7a\x2b\x39\x4d\x7a\x35\x36\x50\ -\x57\x48\x68\x77\x42\x44\x6b\x6e\x6b\x47\x5a\x6c\x2b\x70\x68\x79\ -\x59\x62\x4e\x66\x50\x37\x34\x20\x2f\x64\x6a\x4e\x4a\x6a\x6f\x43\ -\x51\x61\x71\x62\x57\x72\x6a\x37\x72\x51\x38\x59\x57\x7a\x7a\x34\ -\x67\x4c\x32\x76\x54\x71\x75\x4e\x61\x38\x6a\x75\x59\x46\x67\x4e\ -\x4f\x72\x7a\x42\x41\x49\x5a\x77\x45\x41\x30\x67\x4b\x51\x71\x43\ -\x4c\x42\x45\x53\x42\x55\x4b\x69\x69\x43\x44\x4c\x74\x4f\x34\x73\ -\x78\x33\x58\x79\x20\x57\x4b\x53\x4d\x50\x76\x6a\x44\x49\x63\x71\ -\x46\x43\x49\x57\x37\x4b\x37\x73\x69\x59\x6e\x75\x6a\x4b\x47\x70\ -\x4d\x30\x61\x55\x6b\x69\x78\x6c\x66\x4b\x4c\x54\x50\x5a\x33\x73\ -\x2f\x77\x35\x56\x6b\x70\x79\x41\x7a\x6e\x53\x65\x76\x6d\x59\x69\ -\x71\x71\x76\x6a\x44\x59\x54\x35\x59\x39\x41\x4d\x4e\x37\x56\x36\ -\x4b\x20\x63\x72\x4c\x32\x4b\x53\x66\x49\x4d\x76\x6f\x59\x4f\x34\ -\x4e\x4a\x72\x2b\x38\x32\x76\x4c\x78\x48\x6b\x39\x4e\x71\x35\x64\ -\x52\x42\x2f\x62\x6e\x37\x6f\x76\x4d\x41\x69\x49\x67\x69\x4e\x63\ -\x32\x74\x6a\x48\x74\x75\x4d\x70\x6c\x39\x63\x6d\x6e\x75\x33\x4e\ -\x49\x49\x55\x6a\x52\x79\x6c\x48\x51\x4d\x56\x7a\x36\x48\x20\x30\ -\x74\x34\x33\x7a\x59\x50\x4e\x5a\x6b\x58\x4a\x79\x67\x57\x74\x44\ -\x6d\x51\x5a\x77\x6b\x48\x59\x57\x51\x6e\x64\x76\x46\x5a\x6b\x30\ -\x47\x70\x69\x32\x73\x49\x65\x53\x73\x2f\x67\x6e\x44\x36\x38\x65\ -\x2f\x65\x74\x44\x4d\x76\x50\x52\x56\x58\x56\x51\x34\x34\x54\x4b\ -\x63\x61\x56\x52\x70\x4c\x5a\x54\x48\x76\x41\x20\x68\x38\x39\x6f\ -\x37\x46\x72\x52\x71\x59\x43\x71\x67\x71\x49\x71\x4b\x4f\x45\x67\ -\x51\x2b\x30\x32\x62\x6a\x35\x33\x48\x44\x65\x66\x4f\x77\x35\x4a\ -\x6c\x70\x6d\x2f\x64\x69\x4d\x7a\x6c\x71\x39\x69\x57\x4e\x2f\x63\ -\x41\x2b\x34\x6e\x79\x66\x46\x64\x2b\x66\x54\x71\x54\x6d\x61\x54\ -\x6f\x56\x76\x6a\x73\x77\x65\x4e\x20\x52\x73\x4e\x4e\x35\x34\x7a\ -\x46\x6f\x4e\x4f\x69\x30\x57\x68\x77\x32\x6d\x33\x30\x79\x30\x78\ -\x48\x52\x59\x33\x2b\x70\x66\x73\x2f\x56\x4b\x4e\x42\x4f\x55\x59\ -\x4f\x5a\x37\x4e\x42\x6a\x7a\x63\x55\x6f\x43\x4d\x55\x70\x44\x30\ -\x63\x78\x42\x73\x4f\x34\x51\x75\x48\x43\x45\x53\x69\x45\x59\x2b\ -\x49\x49\x6d\x50\x4e\x20\x4c\x53\x44\x53\x36\x64\x79\x56\x55\x63\ -\x46\x6f\x52\x4e\x56\x6f\x6f\x76\x72\x33\x51\x31\x61\x55\x6d\x4a\ -\x78\x75\x54\x70\x75\x56\x4e\x6e\x2b\x77\x78\x2b\x74\x39\x58\x43\ -\x6e\x63\x65\x50\x59\x59\x49\x46\x71\x76\x53\x52\x59\x4c\x47\x53\ -\x6b\x4f\x4e\x42\x6f\x4f\x36\x4a\x79\x69\x4a\x47\x48\x51\x78\x35\ -\x53\x6b\x20\x6a\x74\x47\x67\x49\x33\x79\x51\x33\x42\x61\x54\x77\ -\x63\x41\x4a\x2f\x66\x4b\x36\x5a\x6d\x2b\x54\x77\x55\x42\x47\x69\ -\x68\x4f\x4e\x47\x74\x30\x57\x43\x4c\x49\x55\x39\x61\x4e\x49\x41\ -\x68\x46\x52\x78\x4b\x69\x4e\x62\x52\x73\x59\x54\x2b\x30\x61\x6a\ -\x51\x61\x7a\x58\x67\x2b\x4b\x47\x74\x31\x50\x36\x66\x56\x67\x20\ -\x73\x6b\x53\x64\x72\x4e\x31\x6f\x4e\x4d\x52\x6f\x4f\x41\x2b\x6c\ -\x4a\x78\x51\x52\x75\x50\x75\x74\x44\x31\x42\x56\x74\x56\x66\x6a\ -\x52\x46\x62\x55\x6d\x4f\x72\x53\x61\x62\x4f\x69\x45\x53\x56\x6b\ -\x53\x55\x61\x55\x5a\x41\x52\x4a\x52\x70\x52\x6c\x4a\x45\x58\x75\ -\x6d\x76\x79\x6c\x76\x63\x61\x68\x58\x71\x66\x44\x20\x6e\x57\x78\ -\x48\x73\x33\x64\x6b\x64\x53\x2b\x69\x77\x5a\x5a\x6a\x76\x75\x30\ -\x79\x45\x42\x4b\x45\x48\x71\x2b\x72\x71\x73\x71\x47\x48\x64\x57\ -\x63\x55\x54\x53\x51\x76\x4d\x37\x73\x55\x4c\x31\x4f\x68\x36\x79\ -\x6f\x33\x64\x56\x70\x64\x4f\x56\x7a\x6a\x48\x77\x2b\x4e\x71\x4d\ -\x52\x58\x7a\x43\x41\x4e\x68\x7a\x73\x20\x30\x69\x72\x4b\x30\x53\ -\x31\x43\x52\x42\x4c\x78\x4e\x6a\x66\x67\x71\x36\x71\x45\x67\x41\ -\x38\x78\x79\x51\x47\x79\x42\x42\x5a\x72\x64\x4c\x42\x31\x49\x31\ -\x46\x52\x6c\x4a\x67\x36\x68\x4e\x74\x75\x6f\x39\x6e\x62\x63\x2b\ -\x6a\x36\x6d\x2f\x57\x62\x75\x4f\x66\x74\x44\x31\x6a\x34\x37\x4b\ -\x4e\x38\x75\x58\x6f\x64\x20\x5a\x77\x38\x66\x67\x71\x72\x53\x37\ -\x59\x77\x71\x53\x4c\x47\x48\x50\x73\x32\x47\x67\x30\x38\x73\x32\ -\x33\x62\x58\x38\x66\x78\x6e\x63\x78\x68\x56\x57\x4d\x43\x6d\x36\ -\x6c\x32\x4d\x4b\x52\x71\x49\x7a\x52\x79\x4e\x78\x41\x54\x46\x61\ -\x4e\x51\x6f\x2b\x71\x2b\x41\x70\x4d\x67\x59\x4e\x5a\x71\x34\x52\ -\x6b\x52\x69\x20\x30\x54\x35\x6a\x32\x53\x6f\x51\x42\x66\x72\x57\ -\x56\x46\x41\x64\x45\x56\x46\x73\x79\x64\x45\x56\x6a\x36\x70\x45\ -\x42\x2f\x74\x2b\x37\x57\x6a\x55\x61\x6d\x50\x7a\x73\x52\x78\x43\ -\x7a\x36\x49\x4e\x6d\x39\x6c\x63\x33\x30\x54\x52\x66\x55\x38\x79\ -\x49\x69\x65\x44\x6b\x77\x59\x55\x4d\x4b\x78\x76\x44\x70\x4b\x73\ -\x20\x52\x4b\x4f\x57\x2b\x33\x31\x66\x6c\x75\x58\x59\x4a\x6a\x71\ -\x72\x46\x57\x4e\x7a\x42\x49\x32\x71\x52\x55\x4a\x46\x30\x71\x68\ -\x30\x44\x54\x74\x56\x67\x64\x32\x37\x36\x4e\x41\x71\x6e\x50\x33\ -\x34\x38\x30\x79\x2b\x38\x30\x59\x32\x56\x64\x55\x67\x4b\x77\x71\ -\x69\x4a\x48\x63\x5a\x79\x48\x33\x30\x48\x49\x39\x6f\x20\x6c\x39\ -\x31\x6b\x77\x68\x2f\x75\x4f\x65\x33\x39\x72\x62\x6d\x4c\x57\x4c\ -\x53\x68\x6c\x4d\x74\x4f\x47\x38\x30\x7a\x55\x7a\x39\x6e\x66\x50\ -\x46\x67\x7a\x68\x6b\x78\x42\x46\x47\x57\x6b\x56\x55\x46\x33\x58\ -\x37\x56\x71\x74\x55\x65\x75\x31\x43\x37\x7a\x57\x54\x45\x31\x78\ -\x47\x41\x55\x4e\x54\x34\x4b\x4b\x71\x4b\x20\x72\x4d\x69\x49\x73\ -\x6f\x53\x2f\x75\x5a\x47\x77\x45\x49\x48\x63\x76\x67\x68\x61\x4c\ -\x57\x72\x41\x42\x36\x33\x4e\x6b\x4a\x46\x46\x59\x30\x73\x72\x50\ -\x32\x7a\x65\x69\x73\x74\x75\x49\x79\x50\x46\x53\x55\x36\x71\x47\ -\x36\x31\x47\x67\x78\x53\x6a\x38\x58\x48\x5a\x37\x54\x52\x37\x2f\ -\x51\x64\x38\x4c\x73\x6b\x79\x20\x58\x2f\x32\x30\x6e\x69\x78\x33\ -\x43\x67\x75\x65\x2f\x52\x4d\x35\x71\x53\x37\x53\x6e\x51\x37\x71\ -\x32\x74\x70\x5a\x56\x31\x6e\x46\x56\x36\x74\x4c\x6d\x48\x54\x57\ -\x57\x47\x61\x74\x2b\x49\x6e\x4c\x54\x78\x75\x4e\x78\x35\x46\x4d\ -\x52\x79\x43\x49\x51\x52\x75\x62\x38\x62\x45\x61\x6a\x64\x31\x6d\ -\x30\x53\x71\x71\x20\x69\x69\x38\x59\x34\x72\x30\x46\x33\x2f\x48\ -\x71\x72\x64\x64\x68\x4d\x35\x76\x59\x73\x47\x4d\x58\x36\x51\x34\ -\x48\x62\x38\x39\x62\x6a\x43\x68\x4c\x31\x4e\x62\x73\x70\x4b\x36\ -\x6c\x6b\x61\x44\x4e\x52\x6a\x41\x63\x52\x46\x58\x56\x61\x4b\x67\ -\x39\x6a\x68\x47\x52\x49\x39\x45\x75\x53\x6a\x4a\x62\x61\x33\x66\ -\x6a\x20\x44\x59\x57\x5a\x39\x2f\x51\x6a\x32\x43\x30\x6d\x61\x70\ -\x76\x62\x57\x4c\x32\x39\x6b\x68\x56\x62\x4b\x2f\x68\x33\x65\x52\ -\x6e\x32\x37\x5a\x74\x70\x31\x78\x70\x51\x37\x45\x6c\x67\x54\x77\ -\x4b\x54\x43\x5a\x4e\x4f\x47\x39\x4d\x32\x74\x6b\x63\x39\x73\x73\ -\x79\x55\x2b\x55\x74\x34\x5a\x63\x46\x79\x54\x72\x2f\x6b\x20\x4f\ -\x6b\x53\x4e\x68\x6f\x72\x57\x4a\x6e\x37\x63\x55\x49\x31\x76\x38\ -\x57\x72\x38\x4e\x64\x57\x63\x2f\x74\x6a\x7a\x6a\x4d\x37\x50\x35\ -\x64\x52\x42\x68\x5a\x7a\x59\x4c\x35\x39\x4d\x6c\x37\x4e\x7a\x32\ -\x33\x58\x6b\x64\x57\x6b\x31\x47\x54\x43\x71\x6f\x4e\x64\x71\x6b\ -\x56\x51\x31\x2b\x6f\x4f\x4b\x4a\x49\x6c\x51\x20\x56\x63\x36\x39\ -\x70\x77\x7a\x6e\x69\x61\x73\x75\x4a\x53\x79\x49\x57\x45\x78\x47\ -\x76\x6c\x71\x39\x6e\x71\x59\x4f\x48\x2f\x50\x58\x62\x75\x43\x36\ -\x56\x39\x37\x6b\x75\x64\x39\x65\x79\x62\x72\x4b\x4b\x73\x59\x55\ -\x44\x53\x44\x4a\x59\x6f\x6c\x47\x75\x2b\x49\x59\x79\x65\x79\x56\ -\x38\x62\x47\x5a\x54\x66\x68\x44\x20\x42\x78\x6f\x66\x58\x79\x6a\ -\x4d\x6b\x67\x32\x62\x79\x55\x39\x50\x35\x5a\x76\x6e\x48\x6f\x75\ -\x6d\x5a\x64\x75\x73\x68\x41\x57\x52\x65\x57\x73\x32\x73\x4b\x75\ -\x70\x68\x64\x4b\x71\x47\x75\x61\x73\x57\x73\x74\x31\x34\x30\x36\ -\x6a\x49\x43\x4d\x4e\x62\x57\x66\x53\x33\x4c\x46\x4b\x63\x4c\x61\ -\x61\x6a\x66\x6a\x71\x20\x57\x31\x48\x32\x57\x76\x6c\x49\x69\x6b\ -\x4b\x6f\x76\x68\x62\x2f\x72\x68\x33\x6f\x69\x34\x59\x68\x71\x47\ -\x70\x30\x70\x57\x4f\x78\x67\x6a\x73\x56\x56\x42\x57\x37\x33\x55\ -\x37\x2f\x7a\x41\x79\x2b\x33\x62\x69\x5a\x4f\x53\x76\x58\x4d\x6e\ -\x70\x41\x50\x2f\x37\x31\x39\x54\x66\x6f\x64\x62\x48\x4e\x6a\x75\ -\x34\x6b\x20\x47\x2b\x75\x72\x64\x78\x2f\x77\x2b\x61\x4b\x53\x55\ -\x6a\x37\x39\x37\x6b\x66\x65\x76\x2b\x38\x32\x72\x4b\x62\x6f\x79\ -\x34\x54\x58\x6e\x33\x6b\x36\x41\x42\x61\x6a\x67\x63\x62\x32\x44\ -\x6a\x4a\x64\x54\x67\x6f\x79\x30\x67\x68\x45\x42\x4e\x36\x65\x4e\ -\x6f\x75\x6c\x6d\x37\x63\x78\x49\x44\x50\x74\x67\x48\x73\x64\x20\ -\x44\x6c\x61\x7a\x6b\x55\x44\x34\x77\x41\x48\x7a\x31\x74\x66\x66\ -\x73\x4c\x61\x79\x69\x6e\x66\x75\x76\x71\x58\x4c\x32\x4f\x37\x4a\ -\x42\x42\x2f\x56\x50\x35\x38\x2b\x64\x7a\x36\x4f\x58\x34\x6a\x51\ -\x56\x46\x65\x44\x37\x45\x34\x6c\x55\x72\x6f\x65\x58\x42\x36\x4d\ -\x65\x6c\x31\x63\x33\x34\x67\x2b\x45\x75\x32\x76\x20\x7a\x5a\x35\ -\x4c\x56\x57\x4d\x7a\x62\x39\x77\x78\x36\x57\x66\x66\x6c\x63\x33\ -\x47\x6b\x4c\x78\x73\x4a\x70\x30\x31\x68\x70\x2f\x4b\x4b\x35\x6e\ -\x78\x36\x4c\x31\x55\x31\x6a\x65\x78\x61\x6c\x73\x46\x4b\x38\x73\ -\x72\x57\x62\x6d\x6a\x48\x4c\x74\x52\x6a\x30\x46\x2f\x35\x4d\x61\ -\x38\x4f\x7a\x30\x52\x55\x65\x54\x78\x20\x6a\x36\x59\x7a\x62\x33\ -\x73\x44\x5a\x31\x35\x38\x4c\x57\x46\x56\x78\x52\x63\x4a\x59\x55\ -\x76\x78\x34\x4c\x48\x61\x4d\x47\x62\x6c\x30\x4e\x48\x53\x79\x45\ -\x5a\x6e\x4a\x71\x75\x71\x6d\x35\x6c\x63\x57\x6f\x6b\x75\x34\x43\ -\x66\x48\x70\x43\x50\x4e\x59\x6f\x71\x70\x4c\x69\x31\x47\x49\x79\ -\x61\x4e\x42\x6f\x76\x4f\x20\x67\x4b\x67\x6f\x69\x4b\x70\x43\x4f\ -\x42\x4a\x45\x57\x31\x6e\x47\x43\x35\x64\x4e\x34\x4a\x36\x4c\x4a\ -\x2b\x77\x7a\x6b\x54\x34\x34\x38\x51\x49\x32\x56\x65\x32\x69\x66\ -\x48\x63\x39\x7a\x39\x39\x77\x46\x53\x61\x44\x6e\x6e\x55\x56\x4f\ -\x37\x47\x5a\x6a\x4d\x78\x59\x76\x68\x71\x62\x79\x59\x67\x2b\x78\ -\x73\x6c\x75\x20\x62\x33\x71\x33\x38\x72\x47\x59\x38\x4f\x31\x6e\ -\x66\x4d\x4b\x43\x79\x41\x76\x54\x35\x35\x43\x62\x36\x75\x62\x32\ -\x58\x35\x33\x56\x31\x63\x69\x44\x73\x76\x73\x41\x4d\x44\x77\x2f\ -\x6c\x38\x6c\x66\x4c\x79\x54\x4c\x34\x32\x4a\x51\x64\x68\x38\x43\ -\x45\x59\x46\x72\x58\x70\x35\x4d\x74\x73\x65\x46\x51\x61\x38\x2f\ -\x20\x5a\x69\x73\x66\x75\x38\x6c\x4d\x49\x42\x68\x45\x44\x41\x55\ -\x41\x55\x45\x57\x52\x53\x48\x6b\x5a\x35\x50\x52\x46\x47\x56\x68\ -\x4d\x70\x44\x73\x64\x47\x67\x30\x47\x76\x59\x35\x55\x52\x78\x4b\ -\x33\x6e\x33\x39\x32\x39\x4e\x30\x75\x4a\x5a\x70\x77\x57\x4a\x79\ -\x56\x45\x56\x4f\x48\x38\x43\x54\x62\x61\x66\x62\x36\x20\x75\x70\ -\x61\x31\x48\x59\x45\x67\x39\x37\x33\x7a\x45\x51\x39\x64\x64\x69\ -\x48\x2f\x66\x65\x69\x75\x62\x69\x4e\x58\x4a\x6f\x4d\x42\x52\x56\ -\x56\x4a\x73\x64\x76\x34\x7a\x64\x68\x54\x41\x63\x68\x4c\x64\x58\ -\x50\x78\x73\x33\x2f\x6a\x77\x55\x76\x4f\x4f\x32\x49\x74\x45\x4b\ -\x30\x66\x2f\x31\x34\x44\x70\x69\x4d\x51\x20\x5a\x50\x72\x53\x6c\ -\x5a\x77\x30\x6f\x4a\x41\x62\x7a\x78\x6e\x62\x62\x64\x61\x4c\x32\ -\x57\x68\x45\x56\x6d\x51\x55\x71\x77\x33\x62\x67\x43\x4c\x71\x66\ -\x52\x32\x6f\x51\x34\x5a\x44\x78\x56\x61\x75\x4f\x58\x2f\x73\x4d\ -\x58\x4d\x34\x37\x36\x2b\x39\x78\x65\x66\x6e\x62\x35\x39\x2f\x7a\ -\x65\x38\x76\x50\x43\x66\x71\x20\x6c\x2b\x70\x6d\x68\x52\x72\x39\ -\x54\x43\x55\x6a\x78\x55\x6c\x65\x57\x69\x70\x6e\x44\x69\x74\x43\ -\x56\x68\x54\x75\x6e\x2f\x49\x78\x42\x61\x6d\x75\x6d\x45\x34\x4a\ -\x36\x45\x37\x50\x54\x66\x39\x34\x6c\x79\x61\x54\x6d\x33\x45\x58\ -\x58\x45\x6c\x49\x46\x42\x43\x45\x4d\x49\x49\x73\x49\x53\x71\x64\ -\x2f\x68\x64\x5a\x20\x42\x6b\x41\x32\x47\x4d\x48\x70\x41\x71\x63\ -\x4c\x57\x56\x48\x59\x75\x62\x57\x55\x4f\x38\x61\x66\x47\x71\x4d\ -\x50\x53\x6f\x38\x5a\x63\x42\x67\x4d\x43\x49\x71\x43\x74\x37\x30\ -\x56\x77\x2b\x35\x79\x33\x72\x76\x6e\x4a\x69\x61\x63\x4f\x4c\x54\ -\x62\x2b\x74\x48\x72\x64\x47\x67\x30\x30\x44\x63\x39\x46\x59\x42\ -\x6e\x20\x72\x37\x2b\x43\x73\x43\x44\x79\x7a\x79\x38\x57\x38\x4d\ -\x68\x6c\x46\x38\x54\x6b\x6b\x44\x2f\x67\x57\x62\x33\x35\x6b\x74\ -\x31\x6b\x77\x72\x75\x58\x38\x56\x6c\x63\x55\x73\x72\x37\x33\x33\ -\x7a\x50\x35\x44\x73\x6d\x6b\x57\x79\x31\x39\x4e\x6a\x49\x69\x68\ -\x71\x4e\x37\x6c\x7a\x64\x2b\x57\x4c\x69\x66\x2b\x36\x2f\x20\x6e\ -\x5a\x72\x6d\x56\x6d\x35\x34\x39\x53\x30\x75\x48\x64\x6e\x7a\x75\ -\x30\x4c\x78\x78\x47\x6f\x32\x45\x68\x48\x43\x43\x4a\x45\x77\x68\ -\x45\x4f\x6f\x6f\x67\x68\x4a\x79\x57\x41\x77\x48\x44\x53\x66\x62\ -\x47\x39\x66\x6c\x55\x61\x6a\x59\x56\x48\x4a\x4a\x75\x70\x61\x32\ -\x6e\x6a\x35\x2b\x73\x74\x69\x30\x75\x4f\x79\x20\x32\x32\x6a\x78\ -\x52\x62\x64\x64\x74\x53\x32\x74\x4e\x48\x58\x34\x4f\x47\x74\x34\ -\x45\x59\x4f\x79\x4d\x33\x73\x4d\x6d\x5a\x76\x32\x53\x34\x53\x55\ -\x46\x59\x56\x6e\x70\x73\x33\x69\x38\x6c\x4e\x4f\x70\x48\x43\x2f\ -\x63\x4f\x6a\x68\x45\x70\x32\x74\x6f\x32\x33\x72\x44\x51\x5a\x35\ -\x66\x2b\x46\x33\x4a\x4e\x73\x73\x20\x6e\x4e\x41\x76\x37\x36\x41\ -\x64\x58\x31\x45\x55\x76\x4a\x30\x4f\x66\x45\x45\x53\x6f\x61\x4f\ -\x4e\x73\x39\x4e\x64\x54\x44\x71\x7a\x2b\x32\x7a\x6f\x6f\x38\x48\ -\x65\x32\x70\x73\x37\x66\x48\x79\x33\x71\x59\x7a\x69\x76\x47\x77\ -\x79\x55\x70\x77\x48\x31\x36\x36\x79\x54\x37\x52\x31\x30\x66\x70\ -\x53\x4b\x6e\x59\x33\x20\x38\x50\x53\x56\x46\x38\x56\x4e\x7a\x35\ -\x5a\x64\x75\x37\x6e\x70\x6a\x66\x63\x77\x35\x68\x55\x7a\x61\x50\ -\x41\x77\x66\x4a\x48\x77\x58\x75\x2b\x58\x43\x59\x52\x46\x67\x62\ -\x41\x6b\x45\x70\x59\x6b\x46\x46\x56\x46\x55\x65\x53\x66\x62\x39\ -\x54\x63\x79\x42\x6c\x70\x44\x6e\x35\x33\x33\x72\x69\x59\x39\x4a\ -\x6a\x31\x20\x42\x6b\x77\x61\x53\x44\x45\x5a\x71\x61\x76\x62\x68\ -\x61\x75\x39\x6a\x6b\x2b\x66\x75\x49\x38\x68\x75\x64\x6b\x39\x48\ -\x6f\x75\x68\x31\x2b\x6d\x51\x35\x48\x30\x6e\x35\x4c\x66\x6d\x4c\ -\x71\x4a\x76\x71\x6f\x76\x78\x51\x77\x62\x47\x70\x47\x64\x2f\x65\ -\x6d\x56\x57\x37\x57\x59\x7a\x2f\x6e\x41\x59\x53\x5a\x61\x5a\x20\ -\x76\x57\x49\x4e\x4b\x76\x44\x69\x70\x4b\x74\x78\x32\x4b\x77\x48\ -\x50\x64\x74\x44\x56\x64\x53\x75\x4b\x41\x6c\x45\x4f\x2b\x7a\x39\ -\x55\x7a\x37\x6d\x7a\x67\x6e\x6a\x4b\x4d\x37\x4e\x36\x72\x46\x63\ -\x50\x4c\x47\x62\x54\x43\x44\x4c\x71\x4d\x45\x41\x36\x72\x62\x4e\ -\x30\x59\x68\x48\x57\x73\x59\x68\x73\x38\x6d\x55\x20\x76\x62\x53\ -\x33\x65\x48\x30\x38\x4e\x32\x30\x57\x7a\x31\x31\x7a\x61\x63\x78\ -\x48\x56\x31\x68\x4e\x4a\x67\x4c\x68\x61\x43\x37\x46\x74\x61\x2b\ -\x38\x53\x55\x51\x55\x75\x65\x47\x73\x4d\x51\x65\x39\x72\x39\x6c\ -\x67\x32\x4d\x66\x68\x2f\x4f\x57\x71\x64\x56\x51\x33\x4e\x48\x4c\ -\x54\x6d\x57\x66\x45\x70\x41\x58\x32\x20\x2b\x50\x4d\x69\x4c\x43\ -\x34\x70\x35\x64\x71\x58\x33\x2b\x54\x57\x43\x65\x4f\x35\x2b\x5a\ -\x78\x78\x68\x35\x78\x78\x5a\x55\x57\x68\x49\x78\x54\x43\x48\x77\ -\x6d\x6a\x69\x69\x4b\x65\x70\x6a\x70\x65\x2f\x75\x31\x6c\x63\x54\ -\x33\x61\x34\x31\x44\x73\x30\x62\x36\x2b\x73\x6f\x6f\x72\x58\x76\ -\x77\x48\x70\x77\x37\x75\x20\x7a\x37\x58\x6a\x54\x6a\x75\x6b\x64\ -\x76\x55\x6f\x74\x65\x30\x65\x50\x64\x2b\x58\x62\x75\x47\x53\x6c\ -\x79\x61\x6a\x4c\x54\x77\x42\x64\x33\x35\x2f\x32\x6b\x50\x42\x36\ -\x50\x74\x6c\x34\x53\x44\x65\x63\x42\x68\x66\x4a\x49\x79\x2f\x36\ -\x2f\x32\x79\x43\x4b\x72\x4b\x7a\x2b\x4d\x6b\x45\x73\x62\x52\x57\ -\x4d\x76\x66\x20\x4a\x6c\x30\x64\x65\x31\x38\x7a\x47\x39\x47\x71\ -\x45\x72\x36\x36\x4b\x76\x49\x31\x41\x65\x59\x39\x2b\x51\x44\x46\ -\x65\x54\x6b\x48\x48\x62\x4e\x36\x72\x62\x5a\x72\x4e\x51\x5a\x51\ -\x73\x71\x4f\x61\x6d\x63\x74\x58\x38\x64\x68\x6c\x46\x38\x61\x6b\ -\x70\x54\x74\x36\x5a\x33\x79\x73\x5a\x6c\x70\x39\x66\x6a\x35\x65\ -\x20\x73\x6f\x78\x6c\x5a\x64\x73\x34\x6f\x32\x67\x41\x32\x5a\x35\ -\x44\x48\x34\x65\x68\x71\x45\x72\x58\x43\x69\x49\x69\x69\x74\x7a\ -\x37\x39\x6b\x65\x4d\x48\x56\x54\x49\x78\x4a\x4e\x50\x6a\x45\x6e\ -\x30\x34\x57\x41\x7a\x6d\x36\x47\x78\x48\x6f\x51\x49\x44\x42\x6b\ -\x65\x39\x65\x76\x30\x41\x6b\x56\x56\x4f\x33\x4d\x69\x20\x56\x42\ -\x37\x2f\x61\x44\x71\x2f\x4f\x58\x31\x30\x7a\x4b\x73\x4d\x41\x4a\ -\x4e\x42\x54\x32\x31\x4c\x57\x7a\x51\x76\x36\x72\x45\x2f\x63\x4e\ -\x4b\x41\x37\x74\x2b\x4a\x32\x37\x66\x4d\x7a\x79\x75\x66\x75\x74\ -\x5a\x32\x6e\x70\x33\x36\x4f\x53\x39\x63\x66\x30\x56\x4d\x2f\x6f\ -\x6b\x39\x32\x4d\x78\x6d\x46\x71\x7a\x62\x20\x69\x44\x76\x5a\x7a\ -\x6a\x76\x33\x33\x49\x4c\x64\x62\x4f\x37\x56\x59\x56\x47\x4b\x49\ -\x74\x4d\x52\x44\x69\x49\x71\x4d\x72\x72\x71\x53\x70\x36\x2b\x35\ -\x4e\x79\x34\x31\x4d\x2f\x68\x59\x44\x4f\x62\x6d\x62\x75\x6d\x42\ -\x46\x6c\x52\x2b\x4f\x69\x42\x4f\x38\x6c\x4d\x63\x66\x61\x71\x33\ -\x4a\x35\x2b\x47\x65\x2b\x32\x20\x74\x5a\x6e\x4e\x7a\x46\x72\x78\ -\x45\x78\x50\x2f\x2f\x6a\x37\x32\x45\x30\x35\x48\x6c\x2b\x4b\x6d\ -\x4a\x65\x43\x6e\x4a\x65\x69\x6e\x4a\x52\x69\x67\x4c\x52\x6a\x6f\ -\x66\x4d\x45\x31\x69\x43\x38\x63\x4e\x64\x79\x42\x53\x49\x53\x75\ -\x73\x4b\x71\x71\x6f\x71\x6e\x63\x78\x70\x4f\x58\x54\x6d\x42\x77\ -\x39\x75\x47\x64\x20\x6d\x64\x4d\x64\x79\x56\x59\x4c\x35\x64\x75\ -\x33\x63\x4b\x4c\x48\x7a\x4f\x65\x50\x33\x6b\x64\x57\x4c\x38\x34\ -\x46\x30\x75\x74\x30\x58\x65\x48\x33\x73\x43\x42\x77\x37\x7a\x73\ -\x66\x38\x76\x54\x56\x6c\x2b\x4b\x77\x78\x66\x39\x30\x7a\x31\x34\ -\x5a\x6e\x32\x53\x7a\x6d\x59\x2b\x58\x4c\x4b\x4e\x66\x5a\x68\x71\ -\x50\x20\x58\x6e\x6b\x4a\x78\x6c\x37\x6d\x6c\x69\x69\x64\x6a\x6c\ -\x78\x46\x55\x58\x6a\x36\x30\x38\x39\x4a\x74\x68\x68\x6a\x58\x6b\ -\x6f\x65\x4c\x72\x6d\x70\x4c\x72\x4c\x4e\x42\x6e\x54\x4e\x6a\x64\ -\x44\x52\x44\x6f\x4c\x51\x62\x55\x37\x46\x2f\x71\x69\x64\x32\x75\ -\x65\x75\x4b\x61\x47\x68\x72\x59\x32\x72\x7a\x78\x67\x64\x20\x46\ -\x7a\x31\x4a\x5a\x6a\x4e\x6e\x44\x4f\x72\x50\x79\x7a\x4f\x2f\x34\ -\x74\x6d\x70\x73\x35\x69\x33\x5a\x67\x50\x4e\x48\x62\x36\x44\x35\ -\x6a\x32\x5a\x6a\x64\x48\x6b\x74\x59\x67\x6f\x63\x76\x2b\x55\x6a\ -\x33\x6e\x67\x34\x6e\x50\x4a\x63\x76\x56\x75\x6f\x42\x32\x4b\x33\ -\x46\x51\x58\x32\x32\x76\x72\x65\x47\x76\x75\x20\x59\x74\x5a\x58\ -\x56\x74\x48\x6b\x39\x66\x55\x71\x41\x56\x52\x56\x56\x63\x4b\x69\ -\x41\x4b\x33\x4e\x58\x4a\x44\x6c\x69\x56\x76\x39\x48\x41\x35\x37\ -\x74\x4c\x2f\x2b\x35\x51\x49\x32\x56\x75\x33\x71\x74\x58\x62\x6c\ -\x4b\x4c\x56\x74\x54\x6d\x6f\x4b\x32\x32\x72\x72\x55\x45\x77\x57\ -\x57\x6c\x75\x61\x61\x47\x35\x76\x20\x6f\x54\x58\x6f\x70\x7a\x58\ -\x6f\x70\x79\x33\x6f\x70\x79\x30\x55\x6f\x4c\x30\x7a\x35\x38\x7a\ -\x62\x61\x58\x78\x45\x57\x61\x4a\x72\x2f\x39\x2f\x55\x77\x4e\x6c\ -\x5a\x71\x66\x78\x32\x33\x43\x6b\x48\x66\x55\x35\x76\x4f\x57\x31\ -\x67\x49\x56\x65\x63\x63\x69\x4b\x62\x71\x71\x71\x35\x39\x35\x30\ -\x50\x6d\x62\x35\x30\x20\x4a\x58\x57\x74\x37\x51\x64\x73\x71\x2f\ -\x5a\x47\x72\x34\x75\x75\x66\x42\x52\x46\x34\x66\x6e\x70\x63\x78\ -\x68\x58\x31\x4a\x39\x52\x68\x58\x33\x6a\x6f\x75\x65\x41\x5a\x2f\ -\x58\x6d\x53\x30\x55\x35\x66\x58\x6a\x32\x6d\x6f\x6e\x38\x66\x64\ -\x62\x58\x31\x4c\x56\x37\x79\x55\x39\x50\x34\x39\x77\x52\x78\x5a\ -\x77\x35\x20\x72\x49\x6a\x63\x56\x48\x65\x50\x4d\x2b\x57\x65\x51\ -\x37\x6a\x65\x58\x66\x41\x74\x32\x32\x76\x72\x6d\x48\x7a\x62\x74\ -\x63\x66\x4d\x47\x62\x6d\x48\x34\x74\x77\x73\x56\x72\x7a\x34\x4f\ -\x47\x73\x71\x64\x72\x4b\x67\x70\x4a\x51\x46\x6d\x37\x65\x7a\x50\ -\x52\x42\x42\x54\x58\x46\x42\x69\x67\x65\x4d\x78\x6d\x36\x33\x20\ -\x59\x49\x71\x71\x30\x74\x6a\x68\x35\x53\x2f\x2f\x6e\x63\x6d\x48\ -\x39\x39\x37\x53\x61\x34\x4e\x37\x4b\x49\x77\x47\x50\x53\x39\x50\ -\x75\x70\x4b\x4f\x59\x49\x69\x31\x46\x54\x75\x5a\x75\x33\x6f\x4e\ -\x4c\x30\x79\x66\x6a\x54\x73\x35\x69\x51\x6b\x6e\x44\x75\x4f\x69\ -\x30\x53\x65\x51\x35\x55\x37\x5a\x70\x30\x35\x4e\x20\x6e\x65\x38\ -\x6b\x66\x62\x42\x6f\x4b\x52\x61\x44\x6a\x6f\x74\x48\x39\x33\x77\ -\x65\x7a\x4f\x46\x53\x6e\x4a\x76\x46\x30\x75\x63\x66\x5a\x55\x33\ -\x46\x54\x72\x35\x65\x74\x59\x62\x6e\x50\x35\x74\x44\x75\x74\x50\ -\x42\x2b\x53\x4f\x48\x63\x66\x36\x6f\x45\x66\x52\x78\x64\x65\x2b\ -\x34\x52\x56\x56\x42\x69\x4a\x44\x53\x20\x55\x4d\x76\x2f\x50\x58\ -\x56\x2f\x33\x4f\x72\x6e\x63\x4c\x58\x2f\x32\x4e\x6d\x32\x68\x36\ -\x4e\x64\x56\x56\x55\x61\x32\x6a\x76\x69\x33\x72\x5a\x44\x63\x37\ -\x4e\x5a\x39\x74\x66\x48\x57\x4c\x6d\x39\x6b\x76\x6e\x72\x4e\x72\ -\x46\x77\x32\x54\x6f\x43\x52\x67\x74\x47\x54\x7a\x6f\x36\x64\x79\ -\x71\x4b\x30\x59\x41\x67\x20\x79\x55\x52\x6b\x45\x55\x6d\x57\x39\ -\x30\x30\x6a\x69\x34\x53\x78\x31\x65\x33\x69\x74\x57\x63\x65\x78\ -\x47\x77\x30\x78\x6b\x56\x50\x5a\x6f\x71\x44\x4b\x58\x66\x64\x69\ -\x43\x38\x55\x5a\x74\x32\x4f\x61\x68\x5a\x76\x4b\x4f\x4f\x31\x32\ -\x56\x2b\x54\x62\x4c\x56\x78\x7a\x6f\x68\x69\x4c\x6a\x6e\x70\x42\ -\x50\x72\x33\x20\x79\x64\x69\x6e\x6a\x6e\x52\x61\x48\x62\x4b\x69\ -\x73\x4c\x79\x73\x6e\x4f\x38\x32\x6c\x6a\x48\x7a\x6a\x33\x63\x64\ -\x6c\x57\x4f\x44\x34\x51\x69\x4f\x55\x5a\x56\x6c\x68\x55\x32\x37\ -\x61\x6c\x6d\x38\x73\x59\x79\x6c\x5a\x64\x73\x4a\x69\x53\x49\x6a\ -\x43\x76\x49\x59\x58\x7a\x79\x59\x6b\x59\x58\x35\x35\x4b\x58\x39\ -\x20\x66\x48\x35\x4a\x30\x56\x31\x2f\x35\x4d\x47\x4a\x46\x7a\x44\ -\x31\x32\x2b\x58\x38\x39\x2f\x37\x62\x59\x71\x37\x55\x65\x42\x32\ -\x31\x75\x57\x31\x33\x50\x66\x50\x58\x6c\x66\x4c\x4e\x68\x73\x32\ -\x73\x61\x57\x7a\x44\x61\x37\x5a\x43\x69\x68\x76\x73\x39\x6d\x67\ -\x61\x50\x75\x41\x71\x58\x63\x63\x5a\x2f\x66\x4f\x35\x20\x5a\x47\ -\x51\x78\x56\x35\x31\x2b\x55\x6b\x7a\x50\x36\x77\x30\x56\x39\x59\ -\x30\x73\x58\x46\x2f\x4b\x67\x67\x31\x6c\x4b\x4b\x72\x4b\x4b\x51\ -\x4d\x4c\x2b\x64\x58\x49\x34\x59\x77\x6f\x79\x45\x57\x44\x68\x67\ -\x47\x33\x50\x30\x52\x2b\x75\x70\x75\x70\x44\x39\x77\x52\x31\x30\ -\x50\x35\x75\x32\x4e\x50\x2f\x53\x7a\x61\x20\x57\x49\x5a\x47\x71\ -\x32\x58\x4d\x6b\x49\x47\x63\x64\x38\x4a\x51\x52\x68\x54\x6b\x59\ -\x65\x6c\x73\x51\x39\x4d\x31\x64\x36\x42\x61\x37\x66\x7a\x72\x69\ -\x67\x6c\x78\x71\x5a\x39\x34\x74\x2b\x33\x42\x74\x41\x2b\x38\x34\ -\x79\x47\x47\x35\x2b\x63\x78\x59\x64\x69\x67\x6f\x39\x36\x32\x4b\ -\x37\x5a\x57\x73\x4c\x42\x6b\x20\x4d\x30\x73\x32\x62\x57\x46\x6a\ -\x71\x35\x64\x49\x6b\x69\x4d\x61\x31\x62\x49\x6e\x52\x64\x2b\x6d\ -\x56\x32\x54\x59\x73\x42\x61\x64\x32\x63\x79\x72\x6c\x35\x7a\x4e\ -\x54\x57\x66\x46\x37\x73\x63\x37\x46\x4e\x56\x4e\x4c\x53\x77\x6f\ -\x4b\x57\x58\x2b\x2b\x6c\x4a\x38\x6f\x51\x69\x6a\x2b\x75\x64\x7a\ -\x77\x61\x67\x52\x20\x6a\x43\x72\x4d\x52\x36\x76\x56\x4d\x75\x61\ -\x52\x5a\x33\x48\x61\x72\x4c\x77\x36\x36\x61\x72\x44\x50\x6a\x4b\ -\x31\x4f\x33\x70\x71\x32\x79\x4d\x2b\x77\x78\x6d\x69\x44\x75\x51\ -\x32\x66\x35\x42\x4e\x75\x32\x72\x35\x66\x6e\x4d\x35\x4a\x54\x74\ -\x33\x67\x55\x62\x44\x71\x50\x37\x35\x6a\x42\x39\x61\x78\x42\x55\ -\x76\x20\x2f\x49\x4f\x69\x37\x45\x77\x2b\x75\x4f\x64\x57\x4d\x6c\ -\x32\x4f\x6f\x2f\x5a\x48\x48\x43\x6d\x79\x72\x46\x44\x66\x34\x65\ -\x58\x48\x4c\x65\x58\x4d\x4b\x79\x6c\x6a\x61\x57\x55\x56\x6a\x52\ -\x6f\x44\x6b\x69\x4d\x46\x54\x66\x6b\x57\x4c\x68\x38\x31\x6c\x48\ -\x66\x75\x6e\x48\x52\x4d\x6e\x61\x69\x4b\x6f\x74\x44\x6b\x20\x39\ -\x62\x47\x36\x66\x43\x63\x4c\x4e\x32\x36\x6d\x6f\x72\x36\x4a\x76\ -\x75\x6d\x70\x54\x50\x31\x2b\x42\x54\x4d\x66\x2b\x54\x31\x6a\x69\ -\x77\x59\x63\x4d\x79\x31\x37\x31\x38\x2b\x69\x54\x56\x75\x70\x62\ -\x6d\x35\x68\x61\x46\x34\x75\x45\x30\x34\x63\x78\x70\x55\x76\x76\ -\x63\x37\x46\x49\x34\x66\x78\x37\x6c\x33\x78\x20\x71\x5a\x2b\x6a\ -\x32\x62\x62\x37\x61\x2f\x2f\x4e\x2f\x37\x33\x42\x68\x53\x4f\x48\ -\x38\x63\x36\x64\x4e\x78\x79\x7a\x74\x68\x55\x6c\x6d\x5a\x71\x57\ -\x56\x72\x37\x5a\x73\x4a\x6e\x35\x4a\x57\x57\x73\x72\x61\x6d\x6e\ -\x56\x57\x64\x41\x63\x61\x54\x41\x39\x69\x33\x38\x61\x76\x67\x51\ -\x50\x72\x6e\x76\x6c\x70\x68\x66\x20\x6c\x7a\x6b\x63\x46\x45\x57\ -\x68\x78\x52\x64\x67\x62\x65\x56\x4f\x35\x71\x2f\x66\x54\x46\x6c\ -\x74\x48\x65\x6c\x4f\x4a\x37\x4e\x57\x2f\x4d\x52\x4c\x4e\x31\x7a\ -\x42\x37\x65\x65\x4e\x6a\x38\x74\x7a\x6a\x6f\x72\x78\x36\x59\x36\ -\x61\x35\x6c\x62\x57\x37\x61\x6a\x6d\x2b\x38\x33\x6c\x37\x47\x68\ -\x73\x34\x72\x6c\x72\x20\x4a\x75\x35\x7a\x4a\x45\x55\x73\x48\x49\ -\x33\x2f\x58\x6d\x56\x76\x66\x4b\x45\x77\x61\x79\x75\x72\x57\x4c\ -\x53\x78\x6a\x4b\x32\x31\x64\x62\x77\x79\x36\x57\x70\x79\x65\x75\ -\x46\x59\x50\x35\x71\x45\x49\x69\x4b\x6c\x75\x32\x72\x77\x68\x73\ -\x4b\x4d\x48\x7a\x4c\x77\x6d\x4a\x34\x53\x75\x44\x39\x48\x73\x33\ -\x35\x2b\x20\x61\x57\x33\x62\x31\x4f\x48\x6a\x70\x2b\x30\x37\x57\ -\x56\x43\x79\x69\x62\x4c\x61\x4f\x74\x36\x38\x37\x58\x6f\x4b\x4d\ -\x6d\x4a\x4c\x47\x49\x32\x56\x69\x43\x69\x79\x65\x64\x64\x75\x56\ -\x70\x58\x76\x59\x4e\x4b\x5a\x70\x32\x4f\x4f\x30\x35\x47\x70\x78\ -\x38\x7a\x34\x4a\x45\x69\x51\x49\x45\x46\x76\x4f\x48\x37\x54\x20\ -\x61\x49\x49\x45\x43\x58\x37\x52\x4a\x49\x78\x50\x67\x67\x51\x4a\ -\x6a\x67\x73\x4a\x34\x35\x4d\x67\x51\x59\x4c\x6a\x51\x73\x4c\x34\ -\x4a\x45\x69\x51\x34\x4c\x69\x51\x4d\x44\x34\x4a\x45\x69\x51\x34\ -\x4c\x69\x53\x4d\x54\x34\x49\x45\x43\x59\x34\x4c\x43\x65\x4f\x54\ -\x49\x45\x47\x43\x34\x30\x4c\x43\x2b\x43\x52\x49\x20\x6b\x4f\x43\ -\x34\x6b\x44\x41\x2b\x43\x52\x49\x6b\x4f\x43\x34\x6b\x6a\x45\x2b\ -\x43\x42\x41\x6d\x4f\x43\x2f\x38\x50\x32\x32\x63\x47\x79\x2b\x42\ -\x2f\x69\x58\x30\x41\x41\x41\x41\x41\x53\x55\x56\x4f\x52\x4b\x35\ -\x43\x59\x49\x49\x3d\x20\x22\x20\x68\x65\x69\x67\x68\x74\x3d\x22\ -\x34\x31\x22\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x38\x37\x22\x20\ -\x79\x3d\x22\x2d\x36\x35\x35\x2e\x33\x37\x22\x20\x78\x3d\x22\x31\ -\x32\x39\x39\x2e\x37\x22\x20\x70\x72\x65\x73\x65\x72\x76\x65\x41\ -\x73\x70\x65\x63\x74\x52\x61\x74\x69\x6f\x3d\x22\x6e\x6f\x6e\x65\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\ -\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x33\x33\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\ -\x2d\x35\x39\x31\x2e\x38\x33\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x34\x37\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x35\x36\x36\x2e\x35\x39\ -\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x20\x32\x35\ -\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x33\x34\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\ -\x32\x2d\x35\x39\x31\x2e\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\ -\x38\x2e\x34\x35\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x33\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x35\x38\x2e\ -\x31\x34\x76\x33\x32\x6c\x2d\x33\x31\x2e\x35\x34\x37\x2d\x38\x2e\ -\x34\x35\x33\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x32\ -\x36\x2e\x31\x34\x20\x32\x35\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\ -\x33\x38\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x37\ -\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x39\x31\ -\x2e\x38\x33\x76\x33\x32\x6c\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x39\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x35\x39\x2e\ -\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x36\x31\x22\x20\x64\x3d\x22\x6d\x31\ -\x32\x33\x36\x2e\x36\x2d\x36\x35\x36\x2e\x32\x38\x2d\x31\x32\x2e\ -\x36\x31\x39\x20\x31\x32\x2e\x36\x31\x39\x76\x31\x36\x6c\x31\x38\ -\x2e\x39\x32\x38\x20\x35\x2e\x30\x37\x31\x38\x76\x2d\x31\x36\x6c\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x36\x33\x22\x20\x64\x3d\x22\x6d\x31\x32\ -\x34\x33\x2d\x36\x32\x32\x2e\x35\x39\x20\x31\x32\x2e\x36\x31\x39\ -\x2d\x31\x32\x2e\x36\x31\x39\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x36\x33\x38\x2e\ -\x35\x39\x20\x31\x32\x2e\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\ -\x76\x31\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x37\x22\x20\x64\ -\x3d\x22\x6d\x31\x32\x35\x35\x2e\x36\x2d\x36\x35\x31\x2e\x32\x31\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x76\x31\ -\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x32\x32\x34\x2d\x36\x32\x37\x2e\x36\x36\x20\x31\x32\x2e\ -\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\x20\x31\x38\x2e\x39\x32\ -\x38\x20\x35\x2e\x30\x37\x31\x38\x22\x2f\x3e\x0a\x20\x20\x20\x3c\ -\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x31\ -\x22\x20\x64\x3d\x22\x6d\x31\x33\x33\x38\x2e\x31\x2d\x35\x35\x39\ -\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\ -\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\ -\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\ -\x37\x33\x22\x20\x64\x3d\x22\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\ -\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\ -\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\ -\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x37\x37\x22\x20\x64\x3d\x22\x6d\x31\ -\x33\x35\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\ -\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\ -\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x31\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x36\x36\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x20\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3d\x22\ -\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\x69\x6c\x6c\x2d\x6f\x70\ -\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\x37\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\ -\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x31\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x32\x30\x22\x20\x64\x3d\x22\x6d\x31\x33\x38\x36\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x36\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x32\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x32\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x20\x66\x69\x6c\x6c\x2d\ -\x72\x75\x6c\x65\x3d\x22\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\ -\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\ -\x36\x36\x37\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\ -\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\ -\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\ -\x6c\x3d\x22\x23\x30\x30\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\ -\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x34\x34\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x38\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x38\x30\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x30\x22\x20\ -\x64\x3d\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x35\x36\x2e\x34\ -\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\ -\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\ -\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x34\x34\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x30\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x30\x22\x20\x66\x69\x6c\ -\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\ -\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x39\x34\x2e\x32\x2d\x35\x35\x30\x2e\x34\x36\ -\x20\x30\x2e\x30\x30\x31\x2d\x35\x2e\x38\x36\x36\x36\x20\x32\x2e\ -\x36\x35\x32\x31\x2d\x32\x2e\x39\x37\x30\x35\x63\x31\x2e\x34\x35\ -\x38\x37\x2d\x31\x2e\x36\x33\x33\x38\x20\x32\x2e\x36\x37\x38\x37\ -\x2d\x32\x2e\x39\x39\x38\x31\x20\x32\x2e\x37\x31\x31\x32\x2d\x33\ -\x2e\x30\x33\x31\x39\x20\x30\x2e\x30\x33\x35\x2d\x30\x2e\x30\x33\ -\x36\x38\x20\x30\x2e\x30\x35\x39\x20\x32\x2e\x31\x37\x30\x39\x20\ -\x30\x2e\x30\x35\x39\x20\x35\x2e\x35\x38\x35\x39\x76\x35\x2e\x36\ -\x34\x37\x32\x6c\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\ -\x31\x34\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\x31\x34\ -\x76\x2d\x35\x2e\x38\x36\x36\x38\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\ -\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\ -\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\ -\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ -\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x34\x38\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x39\ -\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\ -\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\ -\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x34\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x34\x30\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\ -\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\ -\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\ -\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x31\x34\x2d\x35\x36\x33\x2e\x35\ -\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x39\x30\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x37\x2e\x37\x2d\x35\ -\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\ -\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x30\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x30\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\ -\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\ -\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x30\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x31\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\ -\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x32\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x35\x32\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x36\x35\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\ -\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\ -\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\ -\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x31\x36\x22\x20\x64\x3d\x22\x6d\x31\x34\x37\x32\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x31\x38\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\ -\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\ -\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\ -\x67\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x32\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x36\x2e\x39\x2d\x35\x36\x36\ -\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\ -\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x36\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x37\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\ -\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\x2e\x31\x2d\x35\x35\x39\x2e\ -\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\ -\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\ -\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x33\ -\x30\x22\x20\x64\x3d\x22\x6d\x31\x35\x32\x31\x2e\x37\x2d\x35\x35\ -\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\ -\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\ -\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x35\ -\x32\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x35\x33\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x35\x32\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\ -\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x3c\ -\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ -\x00\x00\x4e\x4c\ -\x3c\ -\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ -\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ -\x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ -\x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ -\x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ -\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ -\x3c\x73\x76\x67\x20\x69\x64\x3d\x22\x73\x76\x67\x32\x22\x20\x78\ -\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\ -\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\x39\ -\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\x2d\x73\x79\x6e\x74\x61\ -\x78\x2d\x6e\x73\x23\x22\x20\x78\x6d\x6c\x6e\x73\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x68\x65\x69\x67\x68\x74\ -\x3d\x22\x32\x33\x2e\x39\x39\x34\x22\x20\x77\x69\x64\x74\x68\x3d\ -\x22\x32\x30\x2e\x39\x36\x31\x22\x20\x76\x65\x72\x73\x69\x6f\x6e\ -\x3d\x22\x31\x2e\x31\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\x3d\ -\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\x65\ -\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\x22\ -\x20\x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x31\x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x76\x69\x65\x77\ -\x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x30\x2e\x39\x36\x30\x37\ -\x38\x34\x20\x32\x33\x2e\x39\x39\x33\x35\x39\x31\x22\x20\x78\x6d\ -\x6c\x6e\x73\x3a\x64\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\ -\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\ -\x6e\x74\x73\x2f\x31\x2e\x31\x2f\x22\x3e\x0a\x20\x3c\x6d\x65\x74\ -\x61\x64\x61\x74\x61\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ -\x74\x61\x37\x22\x3e\x0a\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\ -\x3e\x0a\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x20\x72\x64\ -\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\ -\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\ -\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\ -\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ -\x65\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\ -\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\ -\x6c\x49\x6d\x61\x67\x65\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x64\ -\x63\x3a\x74\x69\x74\x6c\x65\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x63\ -\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x3c\x2f\x72\x64\x66\x3a\ -\x52\x44\x46\x3e\x0a\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ -\x3e\x0a\x20\x3c\x67\x20\x69\x64\x3d\x22\x6c\x61\x79\x65\x72\x31\ -\x22\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x74\x72\x61\ -\x6e\x73\x6c\x61\x74\x65\x28\x2d\x31\x33\x39\x33\x2e\x36\x20\x35\ -\x36\x36\x2e\x38\x34\x29\x22\x3e\x0a\x20\x20\x3c\x67\x20\x66\x69\ -\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\ -\x36\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x3e\ -\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x33\x36\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\ -\x2e\x33\x2d\x35\x35\x33\x2e\x32\x39\x63\x30\x2d\x34\x2e\x33\x34\ -\x33\x31\x20\x30\x2e\x30\x31\x31\x2d\x35\x2e\x34\x32\x34\x33\x20\ -\x30\x2e\x30\x36\x2d\x35\x2e\x34\x32\x34\x33\x20\x30\x2e\x30\x36\ -\x31\x20\x30\x20\x38\x2e\x33\x34\x31\x39\x20\x31\x2e\x38\x31\x33\ -\x32\x20\x38\x2e\x33\x35\x35\x39\x20\x31\x2e\x38\x32\x39\x37\x20\ -\x30\x20\x30\x20\x30\x2e\x30\x32\x34\x20\x30\x2e\x36\x32\x30\x34\ -\x33\x20\x30\x2e\x30\x34\x32\x20\x31\x2e\x33\x36\x37\x33\x6c\x30\ -\x2e\x30\x33\x34\x20\x31\x2e\x33\x35\x37\x39\x2d\x34\x2e\x32\x34\ -\x35\x38\x20\x33\x2e\x31\x34\x36\x39\x2d\x34\x2e\x32\x34\x35\x39\ -\x20\x33\x2e\x31\x34\x36\x39\x76\x2d\x35\x2e\x34\x32\x34\x33\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x35\x33\x38\x22\x20\x64\x3d\x22\x6d\x31\ -\x35\x31\x32\x2e\x38\x2d\x35\x35\x38\x2e\x36\x34\x63\x2d\x32\x2e\ -\x31\x37\x39\x34\x2d\x30\x2e\x34\x36\x37\x31\x33\x2d\x33\x2e\x39\ -\x39\x35\x32\x2d\x30\x2e\x38\x35\x36\x31\x33\x2d\x34\x2e\x30\x33\ -\x35\x2d\x30\x2e\x38\x36\x34\x35\x35\x2d\x30\x2e\x30\x33\x39\x2d\ -\x30\x2e\x30\x31\x30\x37\x20\x31\x2e\x37\x32\x39\x34\x2d\x31\x2e\ -\x33\x38\x32\x39\x20\x33\x2e\x39\x33\x31\x34\x2d\x33\x2e\x30\x35\ -\x34\x36\x20\x32\x2e\x32\x30\x32\x32\x2d\x31\x2e\x36\x37\x31\x36\ -\x20\x34\x2e\x30\x31\x31\x39\x2d\x33\x2e\x30\x33\x31\x36\x20\x34\ -\x2e\x30\x32\x31\x36\x2d\x33\x2e\x30\x32\x32\x32\x20\x30\x2e\x30\ -\x32\x31\x20\x30\x2e\x30\x31\x39\x32\x20\x30\x2e\x31\x36\x39\x31\ -\x20\x36\x2e\x33\x37\x38\x37\x20\x30\x2e\x31\x36\x39\x34\x20\x37\ -\x2e\x32\x34\x31\x31\x20\x30\x2e\x30\x30\x30\x32\x20\x30\x2e\x34\ -\x31\x38\x38\x39\x2d\x30\x2e\x30\x31\x34\x20\x30\x2e\x35\x35\x38\ -\x34\x37\x2d\x30\x2e\x30\x36\x32\x20\x30\x2e\x35\x35\x34\x36\x34\ -\x2d\x30\x2e\x30\x33\x35\x20\x30\x2d\x31\x2e\x38\x34\x35\x36\x2d\ -\x30\x2e\x33\x38\x37\x33\x31\x2d\x34\x2e\x30\x32\x35\x33\x2d\x30\ -\x2e\x38\x35\x34\x34\x33\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x30\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x35\x39\x2e\x34\x2d\x35\x34\x35\ -\x2e\x34\x33\x63\x2d\x33\x2e\x33\x32\x36\x32\x2d\x30\x2e\x39\x32\ -\x33\x32\x33\x2d\x36\x2e\x31\x37\x37\x38\x2d\x31\x2e\x37\x31\x33\ -\x33\x2d\x36\x2e\x33\x33\x36\x38\x2d\x31\x2e\x37\x35\x35\x37\x2d\ -\x30\x2e\x32\x37\x38\x31\x2d\x30\x2e\x30\x37\x34\x34\x2d\x30\x2e\ -\x31\x32\x30\x39\x2d\x30\x2e\x32\x30\x32\x37\x39\x20\x34\x2e\x30\ -\x31\x35\x31\x2d\x33\x2e\x32\x38\x38\x37\x20\x32\x2e\x33\x36\x37\ -\x36\x2d\x31\x2e\x37\x36\x36\x35\x20\x34\x2e\x33\x37\x30\x31\x2d\ -\x33\x2e\x32\x30\x35\x39\x20\x34\x2e\x34\x35\x30\x32\x2d\x33\x2e\ -\x31\x39\x38\x35\x20\x30\x2e\x30\x38\x20\x30\x2e\x30\x31\x30\x38\ -\x20\x31\x2e\x30\x33\x33\x34\x20\x30\x2e\x32\x37\x35\x34\x32\x20\ -\x32\x2e\x31\x31\x38\x38\x20\x30\x2e\x35\x39\x35\x38\x37\x20\x31\ -\x2e\x30\x38\x35\x34\x20\x30\x2e\x33\x32\x30\x35\x37\x20\x31\x2e\ -\x39\x38\x38\x39\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x32\x2e\x30\ -\x30\x37\x38\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x30\x2e\x30\x31\ -\x39\x20\x30\x20\x30\x2e\x30\x33\x35\x20\x31\x2e\x39\x36\x39\x39\ -\x20\x30\x2e\x30\x33\x35\x20\x34\x2e\x33\x37\x37\x35\x20\x30\x20\ -\x33\x2e\x34\x34\x31\x31\x2d\x30\x2e\x30\x32\x36\x20\x34\x2e\x33\ -\x37\x36\x33\x2d\x30\x2e\x31\x32\x30\x39\x20\x34\x2e\x33\x37\x31\ -\x35\x2d\x30\x2e\x30\x36\x36\x20\x30\x2d\x32\x2e\x38\x34\x32\x34\ -\x2d\x30\x2e\x37\x36\x31\x32\x37\x2d\x36\x2e\x31\x36\x38\x35\x2d\ -\x31\x2e\x36\x38\x34\x36\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x32\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\x2e\x39\x2d\x35\x34\x38\ -\x2e\x30\x39\x63\x30\x2d\x32\x2e\x31\x37\x33\x35\x20\x30\x2e\x30\ -\x32\x2d\x33\x2e\x39\x35\x31\x38\x20\x30\x2e\x30\x34\x37\x2d\x33\ -\x2e\x39\x35\x31\x38\x20\x30\x2e\x31\x30\x36\x31\x20\x30\x20\x35\ -\x2e\x32\x33\x37\x20\x31\x2e\x35\x30\x34\x31\x20\x35\x2e\x32\x38\ -\x32\x36\x20\x31\x2e\x35\x34\x38\x37\x20\x30\x2e\x30\x33\x35\x20\ -\x30\x2e\x30\x33\x35\x2d\x34\x2e\x34\x39\x35\x20\x35\x2e\x34\x34\ -\x35\x32\x2d\x35\x2e\x32\x34\x32\x20\x36\x2e\x32\x35\x39\x33\x2d\ -\x30\x2e\x30\x34\x38\x20\x30\x2e\x30\x35\x33\x2d\x30\x2e\x30\x38\ -\x38\x2d\x31\x2e\x36\x36\x39\x35\x2d\x30\x2e\x30\x38\x38\x2d\x33\ -\x2e\x38\x35\x36\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\x35\x35\x33\x2e\ -\x38\x2d\x31\x2e\x37\x38\x30\x33\x2d\x30\x2e\x35\x33\x32\x39\x76\ -\x2d\x31\x2e\x31\x37\x38\x37\x63\x30\x2d\x31\x2e\x31\x36\x31\x37\ -\x20\x30\x2d\x31\x2e\x31\x37\x38\x20\x30\x2e\x32\x30\x35\x34\x2d\ -\x31\x2e\x31\x32\x35\x32\x20\x30\x2e\x31\x31\x32\x38\x20\x30\x2e\ -\x30\x32\x39\x39\x20\x30\x2e\x39\x34\x36\x20\x30\x2e\x32\x31\x35\ -\x38\x38\x20\x31\x2e\x38\x35\x31\x36\x20\x30\x2e\x34\x31\x33\x39\ -\x31\x6c\x31\x2e\x36\x34\x36\x31\x20\x30\x2e\x33\x36\x30\x32\x39\ -\x76\x31\x2e\x33\x30\x36\x33\x63\x30\x20\x30\x2e\x37\x31\x38\x34\ -\x36\x2d\x30\x2e\x30\x33\x32\x20\x31\x2e\x33\x30\x32\x34\x2d\x30\ -\x2e\x30\x37\x32\x20\x31\x2e\x32\x39\x37\x38\x2d\x30\x2e\x30\x33\ -\x39\x20\x30\x2d\x30\x2e\x38\x37\x32\x33\x2d\x30\x2e\x32\x34\x38\ -\x33\x32\x2d\x31\x2e\x38\x35\x31\x36\x2d\x30\x2e\x35\x34\x31\x35\ -\x32\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x31\x30\x2e\x38\x2d\x35\x35\x32\x2e\x31\x38\x2d\x32\ -\x2e\x36\x38\x31\x31\x2d\x30\x2e\x37\x38\x35\x33\x34\x76\x2d\x31\ -\x2e\x36\x35\x39\x33\x2d\x31\x2e\x36\x35\x39\x33\x6c\x32\x2e\x36\ -\x31\x37\x32\x2d\x32\x2e\x38\x38\x36\x33\x63\x31\x2e\x34\x33\x39\ -\x34\x2d\x31\x2e\x35\x38\x37\x35\x20\x32\x2e\x36\x37\x37\x34\x2d\ -\x32\x2e\x39\x34\x36\x38\x20\x32\x2e\x37\x35\x30\x39\x2d\x33\x2e\ -\x30\x32\x30\x36\x20\x30\x2e\x31\x31\x36\x32\x2d\x30\x2e\x31\x31\ -\x36\x36\x34\x20\x30\x2e\x31\x33\x33\x38\x20\x30\x2e\x35\x38\x33\ -\x37\x39\x20\x30\x2e\x31\x33\x33\x38\x20\x35\x2e\x33\x33\x39\x39\ -\x20\x30\x20\x33\x2e\x30\x31\x30\x38\x20\x30\x2e\x31\x30\x30\x33\ -\x20\x35\x2e\x35\x30\x32\x34\x20\x30\x2e\x30\x36\x31\x20\x35\x2e\ -\x34\x39\x37\x36\x2d\x30\x2e\x30\x33\x39\x20\x30\x2d\x31\x2e\x34\ -\x30\x38\x2d\x30\x2e\x33\x39\x34\x36\x34\x2d\x32\x2e\x38\x38\x32\ -\x34\x2d\x30\x2e\x38\x32\x36\x35\x39\x7a\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x39\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\ -\x35\x35\x37\x2e\x31\x34\x2d\x31\x2e\x37\x31\x34\x37\x2d\x30\x2e\ -\x33\x39\x33\x38\x33\x2d\x30\x2e\x30\x35\x38\x2d\x32\x2e\x32\x32\ -\x36\x34\x63\x2d\x30\x2e\x30\x39\x36\x2d\x33\x2e\x37\x34\x33\x32\ -\x2d\x30\x2e\x32\x31\x38\x33\x2d\x35\x2e\x39\x33\x31\x39\x2d\x30\ -\x2e\x31\x31\x34\x37\x2d\x35\x2e\x39\x33\x31\x39\x20\x30\x2e\x31\ -\x33\x35\x20\x30\x20\x39\x2e\x34\x39\x39\x35\x20\x32\x2e\x32\x35\ -\x31\x39\x20\x39\x2e\x37\x30\x33\x31\x20\x32\x2e\x33\x33\x36\x37\ -\x20\x30\x2e\x31\x34\x32\x35\x20\x30\x2e\x30\x35\x39\x34\x2d\x30\ -\x2e\x32\x39\x37\x33\x20\x30\x2e\x35\x39\x35\x36\x39\x2d\x32\x2e\ -\x37\x32\x35\x32\x20\x33\x2e\x33\x32\x35\x31\x2d\x32\x2e\x33\x31\ -\x31\x39\x20\x32\x2e\x35\x39\x39\x2d\x32\x2e\x39\x34\x33\x32\x20\ -\x33\x2e\x32\x35\x37\x34\x2d\x33\x2e\x31\x33\x35\x39\x20\x33\x2e\ -\x32\x36\x39\x32\x2d\x30\x2e\x31\x33\x32\x36\x20\x30\x2e\x30\x31\ -\x30\x34\x2d\x31\x2e\x30\x31\x32\x38\x2d\x30\x2e\x31\x36\x32\x32\ -\x35\x2d\x31\x2e\x39\x35\x36\x2d\x30\x2e\x33\x37\x38\x38\x32\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x67\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\ -\x35\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x36\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x32\ -\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\ -\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\ -\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x34\x39\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x33\ -\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\ -\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x39\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x30\x2e\x38\x35\x39\x20\x33\x2e\x30\x33\x30\ -\x34\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x32\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x38\x2e\x39\x2d\ -\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\ -\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\ -\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ -\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x32\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\ -\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\ -\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x33\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\ -\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x34\x31\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x34\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\ -\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\ -\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x35\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\ -\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x37\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x36\x2e\x39\x2d\x35\x36\x36\x2e\ -\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\ -\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x38\x31\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x37\x2e\x32\x2d\x35\x35\x33\x2e\ -\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x3e\x0a\ -\x20\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x30\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x35\ -\x36\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\ -\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\ -\x37\x33\x32\x2e\x31\x2d\x35\x30\x37\x2e\x36\x34\x20\x31\x33\x38\ -\x2e\x35\x36\x2d\x38\x30\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\ -\x2d\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x2d\x31\x33\x38\x2e\x35\ -\x36\x2d\x38\x30\x76\x31\x36\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x35\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x37\x33\x32\x2e\x31\x2d\x33\x34\x37\x2e\x36\x34\x20\ -\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x38\x37\x30\x2e\x36\x2d\x32\x36\x37\x2e\x36\x34\x20\x31\x33\ -\x38\x2e\x35\x36\x2d\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x32\x36\x32\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x35\x38\x37\ -\x2e\x36\x34\x76\x31\x36\x30\x6c\x2d\x31\x33\x38\x2e\x35\x36\x20\ -\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x34\x22\x20\ -\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x34\x32\x37\x2e\x36\ -\x34\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x36\x36\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x2d\x38\x30\x20\x38\x30\ -\x20\x38\x30\x20\x38\x30\x20\x38\x30\x2d\x38\x30\x7a\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x37\x30\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x37\x32\x37\x2e\x36\x34\x76\x38\x30\x6c\x38\x30\ -\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x32\x37\x32\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x36\x34\ -\x37\x2e\x36\x34\x2d\x38\x30\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x37\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x76\x38\x30\x6c\x2d\ -\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x37\ -\x36\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x38\x30\x37\x2e\ -\x36\x34\x20\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x30\x22\x20\x64\x3d\x22\x6d\x32\x32\x35\x32\x2e\x39\ -\x2d\x39\x36\x37\x2e\x36\x34\x2d\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x76\x31\x36\x30\x6c\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x38\x32\x22\x20\x64\x3d\ -\x22\x6d\x32\x30\x38\x38\x2e\x31\x2d\x39\x30\x37\x2e\x36\x34\x2d\ -\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\ -\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x39\x32\x33\x2e\x32\x2d\x39\x36\x37\x2e\x36\x34\x76\x31\x36\x30\ -\x6c\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x32\x38\x36\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\ -\x2e\x31\x2d\x31\x30\x32\x37\x2e\x36\x76\x31\x36\x30\x6c\x2d\x31\ -\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x38\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\x2e\x31\ -\x2d\x38\x36\x37\x2e\x36\x34\x20\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x3c\x67\x20\x73\ -\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\ -\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x33\x32\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x31\x38\x38\x2e\x31\x2d\x33\x34\x31\x2e\x36\x37\x20\x31\x35\ -\x33\x2e\x33\x31\x2d\x37\x31\x2e\x34\x38\x38\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x2d\x31\x35\x33\x2e\x33\x31\ -\x20\x37\x31\x2e\x34\x38\x38\x2d\x31\x35\x33\x2e\x33\x31\x2d\x38\ -\x38\x2e\x35\x31\x32\x76\x31\x36\x30\x6c\x31\x35\x33\x2e\x33\x31\ -\x20\x38\x38\x2e\x35\x31\x32\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x39\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\x33\x31\ -\x2d\x37\x31\x2e\x34\x38\x38\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x34\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x34\x31\x33\x2e\x31\x36\x76\x31\x36\x30\x6c\x2d\ -\x31\x35\x33\x2e\x33\x31\x20\x37\x31\x2e\x34\x38\x38\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x32\x36\x22\x20\x64\x3d\x22\x6d\x31\x33\ -\x34\x31\x2e\x34\x2d\x32\x35\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\ -\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x20\x69\x64\ -\x3d\x22\x69\x6d\x61\x67\x65\x34\x33\x33\x36\x22\x20\x73\x74\x79\ -\x6c\x65\x3d\x22\x69\x6d\x61\x67\x65\x2d\x72\x65\x6e\x64\x65\x72\ -\x69\x6e\x67\x3a\x6f\x70\x74\x69\x6d\x69\x7a\x65\x53\x70\x65\x65\ -\x64\x22\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\ -\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\ -\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\ -\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x52\x38\ -\x41\x41\x41\x41\x70\x43\x41\x59\x41\x41\x41\x41\x4d\x41\x79\x31\ -\x4a\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\ -\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x48\x69\x68\x4a\x52\x45\x46\ -\x55\x20\x65\x4a\x7a\x74\x6e\x58\x64\x34\x56\x46\x58\x36\x78\x7a\ -\x2f\x54\x61\x7a\x4b\x54\x6d\x55\x6b\x6a\x6a\x59\x54\x51\x51\x69\ -\x67\x4b\x32\x43\x6c\x57\x31\x72\x35\x59\x31\x37\x4a\x69\x58\x63\ -\x74\x61\x31\x72\x61\x75\x5a\x58\x55\x74\x61\x2f\x6e\x70\x36\x75\ -\x34\x71\x72\x67\x58\x64\x74\x61\x30\x67\x43\x77\x49\x57\x20\x6d\ -\x6f\x41\x46\x6b\x43\x49\x6c\x51\x41\x67\x51\x45\x6b\x68\x49\x53\ -\x47\x2f\x54\x35\x39\x62\x66\x48\x78\x4d\x69\x4a\x59\x48\x41\x44\ -\x50\x43\x48\x38\x33\x6d\x65\x50\x44\x79\x5a\x4f\x2b\x66\x65\x62\ -\x30\x35\x35\x7a\x7a\x6e\x76\x2b\x39\x36\x44\x35\x73\x55\x58\x58\ -\x6c\x42\x4a\x6b\x43\x42\x42\x67\x6d\x4f\x4d\x20\x50\x69\x4d\x7a\ -\x34\x33\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x66\x55\x46\x2b\ -\x2f\x76\x48\x57\x6b\x43\x42\x42\x67\x6c\x38\x67\x65\x72\x66\x62\ -\x66\x62\x77\x31\x4a\x45\x69\x51\x34\x42\x65\x49\x50\x6a\x6b\x35\ -\x2b\x58\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x76\x64\x56\x71\ -\x50\x64\x34\x61\x45\x69\x52\x49\x20\x38\x41\x74\x45\x62\x7a\x41\ -\x59\x59\x72\x71\x42\x4a\x4d\x76\x38\x38\x36\x74\x76\x6d\x4c\x31\ -\x36\x50\x58\x6b\x65\x4e\x34\x4e\x7a\x4d\x68\x6d\x63\x6e\x55\x6d\ -\x2f\x6a\x48\x52\x79\x33\x43\x6b\x34\x62\x66\x45\x7a\x62\x6b\x32\ -\x4e\x44\x57\x54\x6e\x35\x42\x47\x4a\x68\x4f\x4e\x32\x7a\x34\x72\ -\x36\x52\x6e\x34\x6f\x20\x4b\x79\x66\x50\x34\x79\x4c\x4c\x6e\x55\ -\x4b\x47\x30\x30\x47\x79\x31\x52\x4b\x33\x2b\x78\x38\x75\x4e\x53\ -\x31\x74\x31\x44\x53\x33\x6b\x75\x5a\x49\x4a\x74\x32\x5a\x6a\x4d\ -\x31\x73\x4f\x6d\x35\x61\x41\x46\x5a\x73\x72\x65\x43\x37\x7a\x56\ -\x76\x4a\x38\x37\x6a\x4a\x54\x2f\x65\x51\x6b\x65\x49\x6b\x7a\x5a\ -\x47\x4d\x20\x78\x52\x68\x62\x76\x39\x6d\x66\x6f\x39\x47\x32\x4b\ -\x37\x5a\x57\x38\x4e\x58\x61\x44\x65\x53\x6e\x65\x52\x69\x51\x6d\ -\x55\x47\x4b\x33\x55\x5a\x75\x71\x6f\x73\x6b\x69\x7a\x6c\x75\x7a\ -\x7a\x68\x63\x50\x63\x65\x69\x4c\x6e\x76\x4c\x6b\x6f\x31\x6c\x7a\ -\x46\x75\x2f\x69\x56\x79\x33\x6d\x33\x34\x5a\x71\x66\x52\x78\x20\ -\x70\x35\x44\x75\x53\x4d\x4b\x54\x6c\x49\x52\x4f\x70\x34\x33\x62\ -\x63\x33\x70\x71\x57\x33\x30\x73\x4e\x32\x31\x6f\x37\x2b\x44\x78\ -\x54\x32\x61\x69\x4e\x78\x69\x35\x61\x50\x53\x4a\x58\x44\x76\x2b\ -\x4e\x45\x71\x72\x61\x79\x69\x74\x72\x6d\x58\x42\x68\x69\x33\x73\ -\x61\x6d\x70\x42\x72\x39\x57\x53\x35\x58\x49\x77\x20\x73\x45\x38\ -\x6d\x52\x54\x6d\x5a\x46\x47\x61\x6b\x34\x55\x36\x32\x59\x7a\x63\ -\x66\x6e\x77\x36\x77\x42\x31\x6c\x52\x2b\x47\x4c\x31\x65\x6c\x36\ -\x66\x75\x34\x51\x42\x57\x52\x6e\x73\x62\x47\x36\x6a\x75\x71\x6d\ -\x46\x68\x76\x59\x4f\x6a\x46\x6f\x64\x47\x63\x35\x6b\x63\x6c\x50\ -\x64\x46\x47\x61\x6d\x4d\x69\x41\x7a\x20\x67\x33\x52\x6e\x4d\x6b\ -\x6b\x57\x4d\x31\x61\x54\x45\x59\x31\x47\x45\x33\x63\x39\x6b\x69\ -\x7a\x7a\x78\x55\x38\x6c\x50\x44\x5a\x6a\x4c\x71\x30\x36\x45\x79\ -\x5a\x46\x77\x6f\x61\x4d\x78\x32\x4b\x68\x77\x4a\x4e\x43\x51\x61\ -\x71\x62\x2f\x44\x51\x50\x2b\x52\x6d\x70\x35\x48\x6c\x63\x58\x56\ -\x70\x4d\x4d\x55\x34\x65\x20\x50\x52\x45\x57\x52\x4e\x35\x64\x2b\ -\x44\x31\x66\x72\x39\x76\x49\x4f\x53\x4f\x4b\x61\x51\x38\x4c\x7a\ -\x46\x68\x56\x51\x6c\x31\x72\x47\x38\x30\x64\x50\x6d\x77\x57\x45\ -\x2b\x6e\x4a\x79\x57\x53\x37\x6e\x66\x54\x50\x54\x4b\x4d\x67\x50\ -\x59\x32\x4d\x46\x41\x63\x4f\x71\x2b\x57\x34\x47\x38\x77\x39\x32\ -\x71\x66\x2f\x20\x2b\x42\x4e\x31\x51\x5a\x47\x2b\x41\x34\x70\x70\ -\x57\x37\x6d\x56\x6b\x4b\x38\x64\x67\x79\x70\x69\x30\x65\x6e\x49\ -\x64\x6a\x6b\x59\x6d\x70\x31\x4a\x75\x6a\x4f\x4a\x51\x64\x6c\x39\ -\x4b\x45\x68\x50\x78\x57\x59\x79\x34\x6b\x71\x79\x48\x7a\x55\x39\ -\x30\x35\x61\x76\x78\x6d\x34\x78\x38\x2b\x75\x54\x52\x78\x37\x58\ -\x20\x75\x76\x53\x48\x77\x72\x7a\x32\x78\x55\x4c\x65\x58\x4c\x79\ -\x55\x6b\x58\x6e\x5a\x6a\x4f\x78\x66\x79\x4a\x71\x71\x57\x6d\x61\ -\x76\x32\x55\x42\x64\x61\x7a\x74\x68\x51\x63\x52\x74\x74\x35\x48\ -\x68\x54\x43\x59\x2f\x33\x55\x4e\x42\x65\x69\x72\x35\x61\x61\x6d\ -\x34\x6b\x71\x79\x6b\x4f\x5a\x4c\x6a\x31\x76\x38\x31\x20\x33\x6f\ -\x37\x32\x49\x38\x72\x7a\x57\x56\x4f\x78\x6b\x38\x63\x2b\x2b\x5a\ -\x79\x37\x4c\x6a\x79\x58\x38\x30\x63\x4e\x5a\x2b\x58\x57\x37\x56\ -\x77\x77\x61\x73\x51\x2b\x33\x31\x45\x55\x68\x59\x5a\x32\x4c\x39\ -\x56\x4e\x4c\x57\x79\x70\x32\x63\x32\x6d\x71\x68\x6f\x32\x56\x64\ -\x65\x77\x73\x36\x47\x52\x6d\x58\x2b\x38\x20\x69\x32\x79\x33\x36\ -\x37\x43\x65\x47\x61\x2f\x5a\x4d\x52\x67\x52\x65\x47\x72\x71\x62\ -\x4e\x70\x43\x59\x5a\x36\x2b\x35\x6a\x4c\x4b\x61\x6e\x59\x7a\x38\ -\x64\x52\x52\x51\x4e\x51\x6f\x4e\x58\x74\x39\x31\x4c\x61\x30\x55\ -\x64\x58\x59\x7a\x4c\x62\x61\x4f\x72\x62\x57\x31\x72\x4f\x37\x74\ -\x51\x31\x76\x4d\x45\x69\x53\x20\x32\x63\x53\x37\x64\x30\x34\x69\ -\x78\x57\x36\x4c\x53\x63\x50\x65\x64\x41\x53\x43\x50\x50\x48\x70\ -\x4c\x4c\x37\x61\x55\x55\x39\x79\x30\x51\x68\x55\x67\x78\x46\x52\ -\x6c\x6f\x68\x49\x49\x75\x46\x51\x6b\x45\x67\x77\x67\x42\x41\x4b\ -\x51\x43\x67\x45\x34\x53\x41\x47\x55\x63\x42\x6a\x30\x4a\x4a\x6d\ -\x4d\x6e\x4a\x79\x20\x59\x56\x39\x65\x76\x50\x35\x79\x39\x44\x70\ -\x64\x33\x50\x54\x55\x74\x58\x62\x77\x38\x49\x66\x54\x36\x4e\x65\ -\x6e\x44\x35\x65\x65\x63\x69\x49\x66\x4c\x56\x37\x4b\x6c\x48\x74\ -\x76\x36\x37\x6f\x75\x53\x68\x49\x4e\x37\x56\x37\x71\x32\x74\x71\ -\x70\x62\x6d\x70\x68\x57\x32\x30\x64\x46\x58\x57\x4e\x56\x4e\x51\ -\x33\x20\x30\x4e\x6a\x65\x7a\x76\x38\x65\x2f\x6a\x33\x5a\x37\x70\ -\x54\x44\x65\x6d\x61\x38\x32\x6e\x5a\x76\x37\x62\x38\x39\x38\x33\ -\x52\x75\x66\x6d\x38\x6d\x76\x37\x72\x73\x52\x76\x78\x43\x47\x48\ -\x38\x6b\x54\x48\x76\x41\x52\x33\x4e\x62\x43\x32\x30\x64\x72\x62\ -\x53\x33\x74\x2b\x4a\x72\x62\x79\x58\x6b\x62\x55\x63\x4a\x20\x42\ -\x55\x6a\x58\x4b\x73\x7a\x37\x38\x77\x50\x30\x54\x66\x50\x45\x70\ -\x4b\x45\x6e\x50\x54\x65\x64\x4f\x35\x62\x5a\x4b\x39\x62\x77\x78\ -\x4e\x57\x2f\x37\x72\x72\x65\x55\x31\x33\x75\x61\x47\x69\x6b\x76\ -\x71\x33\x74\x69\x4f\x72\x79\x59\x47\x79\x74\x72\x65\x50\x75\x39\ -\x7a\x35\x6c\x68\x32\x4c\x45\x31\x69\x65\x58\x20\x6b\x31\x51\x66\ -\x55\x78\x2b\x2b\x71\x2b\x75\x36\x71\x71\x70\x34\x51\x32\x45\x61\ -\x32\x74\x71\x70\x61\x32\x32\x6e\x6f\x72\x36\x52\x37\x58\x55\x4e\ -\x6c\x4f\x32\x71\x5a\x58\x46\x4a\x4b\x51\x75\x66\x65\x6f\x6a\x42\ -\x4f\x5a\x6d\x48\x39\x63\x79\x34\x72\x58\x77\x6b\x57\x65\x59\x2f\ -\x53\x35\x59\x78\x61\x33\x55\x4a\x20\x37\x39\x33\x33\x4f\x77\x5a\ -\x6c\x5a\x37\x4b\x39\x72\x6f\x46\x2f\x66\x2f\x50\x39\x41\x63\x5a\ -\x48\x71\x39\x57\x53\x36\x58\x4b\x53\x36\x58\x4a\x79\x38\x73\x42\ -\x2b\x68\x45\x57\x52\x33\x37\x30\x2b\x68\x52\x56\x62\x79\x6d\x6e\ -\x32\x2b\x67\x2f\x62\x2b\x4d\x53\x44\x44\x56\x55\x31\x50\x50\x4c\ -\x52\x64\x4b\x34\x2f\x20\x63\x77\x79\x33\x54\x54\x69\x54\x6e\x59\ -\x33\x4e\x66\x4c\x78\x6b\x61\x5a\x66\x78\x30\x57\x6d\x31\x70\x44\ -\x73\x64\x70\x44\x73\x64\x6e\x4e\x69\x76\x4c\x78\x42\x74\x45\x45\ -\x56\x56\x2b\x64\x76\x6e\x58\x2f\x4f\x6e\x2f\x30\x7a\x46\x47\x77\ -\x7a\x46\x78\x66\x69\x6f\x71\x73\x71\x79\x73\x75\x33\x38\x34\x65\ -\x4f\x5a\x20\x6d\x50\x4f\x48\x4d\x50\x79\x73\x55\x55\x69\x4b\x67\ -\x69\x68\x4c\x68\x43\x57\x52\x6b\x43\x67\x51\x4e\x4a\x6f\x49\x57\ -\x6d\x7a\x34\x68\x54\x42\x68\x55\x55\x41\x46\x52\x46\x57\x6c\x54\ -\x6c\x57\x70\x4b\x79\x38\x6a\x73\x4b\x47\x4d\x73\x43\x42\x69\x74\ -\x38\x52\x75\x66\x46\x52\x56\x5a\x57\x46\x4a\x4b\x53\x2f\x4e\x20\ -\x6d\x73\x64\x54\x31\x31\x7a\x4f\x42\x61\x4f\x47\x30\x39\x54\x68\ -\x34\x36\x6f\x78\x70\x2b\x7a\x7a\x50\x59\x4e\x65\x54\x37\x62\x48\ -\x52\x62\x62\x48\x78\x65\x6a\x2b\x42\x51\x41\x45\x49\x78\x47\x75\ -\x65\x58\x6b\x79\x33\x35\x61\x56\x45\x34\x78\x45\x59\x74\x59\x53\ -\x44\x2b\x30\x37\x47\x35\x74\x52\x46\x42\x6b\x56\x20\x46\x55\x56\ -\x52\x6b\x42\x55\x46\x74\x46\x71\x4d\x4e\x6a\x73\x57\x76\x51\x37\ -\x4a\x5a\x6b\x64\x78\x70\x79\x4b\x48\x41\x67\x52\x4b\x53\x39\x6a\ -\x64\x32\x6b\x78\x45\x46\x49\x2b\x61\x6e\x76\x5a\x41\x73\x4b\x74\ -\x50\x37\x61\x47\x37\x75\x74\x77\x7a\x54\x6c\x61\x56\x56\x38\x61\ -\x74\x4c\x6b\x56\x4a\x34\x73\x4e\x76\x20\x66\x2b\x53\x76\x58\x79\ -\x79\x69\x33\x2b\x69\x78\x6a\x4d\x7a\x75\x53\x33\x74\x7a\x41\x30\ -\x70\x7a\x78\x7a\x37\x66\x30\x32\x67\x30\x4f\x4b\x77\x57\x48\x46\ -\x59\x4c\x41\x37\x49\x79\x47\x54\x64\x30\x4d\x43\x46\x42\x34\x4a\ -\x5a\x2f\x76\x49\x74\x4f\x70\x30\x4e\x52\x34\x35\x65\x54\x66\x46\ -\x6a\x47\x70\x38\x58\x6e\x20\x35\x36\x6c\x70\x73\x7a\x47\x62\x7a\ -\x4d\x78\x35\x34\x67\x45\x63\x6e\x66\x36\x63\x62\x4c\x65\x4c\x4a\ -\x36\x36\x2b\x39\x4b\x42\x6c\x4a\x56\x6e\x6d\x6d\x55\x38\x2f\x52\ -\x36\x50\x52\x4d\x50\x48\x55\x55\x53\x6a\x4b\x73\x55\x32\x73\x46\ -\x69\x57\x5a\x44\x37\x35\x62\x7a\x68\x65\x72\x53\x33\x6a\x39\x39\ -\x68\x73\x5a\x20\x55\x5a\x43\x48\x52\x71\x4f\x68\x6a\x38\x76\x4a\ -\x30\x39\x64\x64\x66\x73\x6a\x79\x55\x2b\x5a\x2f\x79\x2b\x77\x56\ -\x61\x7a\x68\x6a\x79\x45\x42\x30\x63\x56\x68\x6c\x42\x4d\x49\x52\ -\x58\x76\x74\x69\x49\x54\x4d\x32\x56\x54\x4c\x69\x72\x49\x6b\x6b\ -\x70\x62\x69\x52\x46\x49\x58\x49\x48\x71\x4d\x6a\x52\x4e\x42\x72\ -\x20\x74\x57\x6a\x51\x6f\x4b\x6f\x67\x4b\x54\x4b\x53\x4c\x43\x4d\ -\x71\x4d\x71\x67\x71\x6d\x71\x6f\x4b\x72\x69\x6b\x71\x59\x46\x76\ -\x4e\x37\x72\x6a\x73\x7a\x2f\x32\x68\x4d\x4b\x2f\x4d\x6d\x55\x39\ -\x46\x59\x77\x76\x2f\x65\x2f\x51\x2b\x63\x6a\x78\x75\x4e\x42\x6f\ -\x4e\x49\x55\x46\x67\x35\x64\x62\x74\x6e\x48\x66\x43\x20\x30\x42\ -\x37\x4c\x43\x70\x4c\x45\x2f\x56\x4d\x2b\x59\x56\x47\x44\x46\x36\ -\x50\x4c\x67\x2f\x6b\x6f\x62\x51\x56\x37\x6f\x69\x66\x74\x42\x70\ -\x30\x4f\x55\x52\x4a\x6f\x44\x77\x57\x6a\x64\x53\x70\x47\x43\x49\ -\x6b\x69\x59\x55\x6b\x6b\x49\x6b\x6c\x45\x4f\x6c\x65\x58\x6b\x63\ -\x70\x74\x59\x44\x53\x69\x53\x58\x62\x45\x20\x52\x58\x74\x50\x65\ -\x6c\x70\x38\x66\x6a\x35\x61\x73\x76\x53\x41\x53\x58\x70\x76\x39\ -\x68\x34\x6e\x34\x34\x63\x4f\x6a\x6f\x75\x65\x58\x63\x32\x74\x50\ -\x50\x72\x4a\x54\x4d\x70\x38\x43\x68\x4f\x75\x75\x67\x57\x72\x4c\ -\x51\x6c\x5a\x55\x64\x41\x47\x41\x38\x69\x48\x47\x49\x65\x69\x4a\ -\x50\x48\x59\x68\x35\x2b\x52\x20\x35\x6b\x78\x6d\x7a\x4a\x42\x42\ -\x63\x66\x56\x50\x39\x62\x72\x58\x62\x71\x6d\x70\x34\x39\x72\x58\ -\x33\x6d\x46\x4d\x63\x52\x47\x54\x37\x35\x6a\x55\x5a\x58\x67\x41\ -\x4f\x6f\x4a\x42\x6e\x70\x38\x2b\x35\x36\x44\x6c\x2f\x7a\x56\x33\ -\x45\x65\x73\x71\x64\x2f\x4c\x47\x48\x54\x64\x69\x4d\x75\x68\x52\ -\x56\x4f\x58\x49\x20\x56\x52\x38\x6d\x37\x59\x45\x67\x74\x2f\x2f\ -\x72\x41\x37\x62\x58\x4e\x7a\x50\x6a\x73\x54\x39\x77\x51\x72\x2b\ -\x2b\x58\x66\x76\x57\x56\x70\x2b\x66\x70\x7a\x2f\x39\x2f\x4b\x44\ -\x6c\x70\x79\x39\x64\x79\x5a\x51\x46\x53\x2f\x6a\x30\x6a\x33\x65\ -\x54\x5a\x44\x47\x6a\x6a\x58\x48\x50\x75\x37\x32\x75\x67\x63\x74\ -\x66\x20\x65\x59\x76\x76\x57\x68\x55\x75\x75\x50\x77\x6d\x42\x76\ -\x59\x74\x4a\x44\x50\x5a\x69\x64\x74\x71\x4a\x38\x6c\x6b\x78\x6d\ -\x6f\x77\x59\x74\x49\x62\x4d\x4f\x6a\x30\x36\x4c\x56\x61\x64\x46\ -\x6f\x4e\x57\x6f\x33\x6d\x35\x37\x31\x32\x54\x54\x55\x54\x30\x6c\ -\x4e\x34\x2b\x36\x36\x62\x55\x52\x57\x56\x57\x48\x66\x67\x20\x4f\ -\x78\x71\x61\x2b\x4d\x31\x72\x37\x2b\x42\x78\x4f\x70\x6e\x36\x38\ -\x4f\x2f\x4a\x54\x66\x56\x30\x50\x55\x74\x57\x46\x42\x72\x62\x76\ -\x51\x63\x74\x2f\x2b\x4c\x30\x4c\x2f\x69\x73\x64\x41\x63\x70\x51\ -\x34\x5a\x6a\x30\x47\x72\x52\x61\x75\x50\x6e\x72\x44\x77\x55\x42\ -\x39\x4e\x75\x30\x4f\x75\x51\x4a\x49\x6d\x32\x20\x6b\x4a\x2b\x4f\ -\x55\x41\x42\x76\x4f\x49\x78\x66\x43\x42\x4d\x51\x49\x70\x32\x47\ -\x53\x43\x43\x77\x63\x7a\x74\x53\x4f\x41\x78\x35\x42\x61\x41\x6f\ -\x4d\x57\x73\x2f\x6d\x4a\x35\x73\x74\x34\x74\x6e\x72\x72\x76\x69\ -\x6f\x4f\x58\x33\x48\x69\x63\x61\x4e\x44\x48\x72\x6d\x62\x64\x32\ -\x49\x78\x65\x2b\x4e\x42\x6d\x76\x20\x75\x34\x41\x4c\x4a\x31\x35\ -\x50\x51\x55\x59\x4f\x36\x55\x6b\x4f\x6e\x42\x59\x72\x46\x71\x50\ -\x70\x6b\x43\x75\x5a\x6c\x32\x5a\x38\x53\x58\x31\x62\x42\x79\x39\ -\x4d\x75\x68\x70\x4a\x6c\x6a\x45\x61\x34\x72\x65\x39\x37\x39\x58\ -\x4b\x35\x39\x4d\x66\x56\x76\x4c\x43\x7a\x4b\x2f\x35\x35\x4b\x48\ -\x66\x63\x2b\x71\x67\x20\x77\x67\x4d\x63\x54\x6c\x61\x54\x69\x5a\ -\x50\x36\x39\x2b\x75\x32\x72\x4b\x71\x71\x7a\x46\x69\x2b\x6d\x6b\ -\x2b\x2f\x57\x38\x36\x58\x54\x7a\x37\x55\x4f\x58\x69\x31\x30\x53\ -\x58\x77\x4d\x65\x43\x62\x6b\x6c\x49\x65\x2f\x76\x42\x2f\x50\x48\ -\x7a\x35\x52\x64\x78\x32\x33\x76\x67\x44\x47\x74\x4e\x6d\x4e\x6a\ -\x4e\x2b\x20\x36\x4f\x42\x75\x79\x36\x71\x71\x79\x74\x77\x31\x4a\ -\x54\x77\x37\x62\x52\x5a\x7a\x6e\x6e\x69\x41\x33\x46\x51\x33\x69\ -\x71\x4b\x69\x30\x78\x37\x35\x63\x48\x2f\x39\x71\x30\x57\x38\x4e\ -\x75\x38\x37\x52\x70\x30\x33\x6b\x62\x7a\x63\x41\x76\x52\x36\x41\ -\x37\x4b\x69\x49\x4d\x6b\x79\x67\x69\x77\x69\x79\x4e\x4c\x50\x20\ -\x50\x35\x4b\x30\x7a\x2b\x2b\x53\x4c\x45\x4e\x64\x44\x65\x4f\x53\ -\x6a\x45\x7a\x37\x34\x39\x33\x59\x7a\x4e\x48\x4f\x6f\x39\x55\x63\ -\x65\x51\x65\x64\x2b\x73\x4e\x4b\x6e\x70\x6f\x32\x68\x7a\x66\x75\ -\x6d\x4d\x54\x45\x55\x30\x63\x64\x30\x4c\x59\x5a\x4b\x51\x36\x75\ -\x48\x58\x39\x61\x74\x32\x56\x56\x56\x65\x58\x39\x20\x68\x64\x2f\ -\x78\x32\x70\x4b\x56\x35\x4a\x78\x32\x4a\x6c\x35\x52\x51\x4b\x38\ -\x42\x58\x51\x78\x36\x44\x6f\x65\x70\x50\x36\x7a\x6b\x72\x7a\x4f\ -\x2f\x5a\x73\x6f\x39\x74\x33\x48\x32\x38\x4b\x49\x44\x74\x42\x74\ -\x30\x4f\x6d\x52\x5a\x6f\x69\x58\x67\x52\x35\x42\x2b\x33\x73\x6f\ -\x47\x68\x41\x68\x42\x49\x59\x4a\x33\x20\x31\x77\x34\x69\x4c\x59\ -\x30\x77\x73\x42\x69\x30\x57\x72\x53\x6f\x78\x44\x4b\x76\x48\x45\ -\x70\x50\x55\x34\x65\x58\x68\x39\x37\x2f\x4c\x37\x4f\x66\x65\x4f\ -\x43\x41\x73\x74\x32\x4e\x45\x31\x6d\x52\x59\x36\x72\x4c\x76\x30\ -\x79\x64\x7a\x56\x76\x66\x72\x75\x44\x30\x38\x36\x38\x67\x4e\x79\ -\x63\x66\x57\x56\x55\x4a\x20\x43\x68\x46\x6b\x56\x53\x45\x6b\x43\ -\x6b\x52\x6b\x43\x58\x6f\x59\x68\x34\x71\x71\x38\x75\x36\x38\x78\ -\x58\x79\x2f\x61\x51\x73\x7a\x48\x2f\x38\x44\x46\x71\x4d\x52\x57\ -\x5a\x46\x69\x36\x6d\x76\x37\x30\x79\x76\x6a\x38\x2f\x37\x69\x70\ -\x65\x53\x6d\x65\x6e\x6a\x77\x76\x55\x39\x77\x32\x71\x30\x55\x35\ -\x57\x51\x78\x20\x75\x6e\x38\x42\x77\x77\x76\x79\x79\x48\x41\x36\ -\x4d\x42\x6b\x4d\x36\x48\x71\x77\x30\x45\x73\x32\x62\x4f\x62\x35\ -\x7a\x32\x59\x7a\x36\x34\x6e\x37\x75\x79\x49\x4a\x4f\x71\x33\x32\ -\x6b\x4d\x75\x39\x65\x50\x48\x43\x72\x50\x6e\x6f\x55\x6a\x4c\x34\ -\x35\x2f\x79\x6c\x76\x4c\x39\x6f\x47\x63\x50\x79\x2b\x6c\x43\x63\ -\x20\x6d\x38\x30\x70\x41\x77\x76\x4a\x54\x58\x56\x68\x4e\x42\x69\ -\x49\x69\x46\x4c\x33\x32\x6a\x65\x57\x38\x61\x63\x50\x70\x76\x48\ -\x5a\x49\x2f\x65\x53\x6e\x35\x45\x47\x52\x46\x63\x43\x50\x66\x32\ -\x74\x76\x65\x47\x2f\x50\x36\x79\x6b\x4b\x43\x75\x64\x48\x61\x73\ -\x57\x73\x32\x50\x44\x4b\x71\x77\x4f\x4e\x36\x36\x30\x20\x50\x74\ -\x68\x53\x58\x47\x41\x77\x49\x41\x42\x42\x49\x54\x70\x41\x39\x6a\ -\x68\x4a\x2f\x5a\x45\x49\x51\x55\x46\x41\x61\x61\x78\x6a\x75\x42\ -\x70\x68\x2b\x70\x38\x65\x49\x64\x6c\x71\x51\x5a\x51\x6b\x64\x44\ -\x6f\x74\x32\x68\x69\x4d\x34\x62\x2b\x58\x4c\x4f\x4f\x30\x77\x66\ -\x33\x35\x2b\x2b\x78\x35\x76\x44\x70\x72\x20\x4c\x6f\x56\x39\x30\ -\x68\x6d\x57\x6c\x38\x50\x4a\x41\x77\x76\x70\x6d\x35\x35\x4b\x57\ -\x42\x42\x34\x2f\x72\x4d\x35\x66\x50\x48\x6b\x67\x77\x65\x55\x6e\ -\x62\x31\x69\x44\x59\x2f\x2f\x62\x79\x35\x44\x78\x31\x2b\x41\x58\ -\x31\x56\x51\x68\x41\x68\x36\x51\x4b\x65\x4c\x66\x7a\x53\x77\x4f\ -\x39\x35\x62\x76\x49\x79\x38\x20\x56\x41\x39\x2f\x2f\x6e\x67\x36\ -\x66\x35\x74\x31\x59\x4c\x2f\x55\x36\x62\x51\x6f\x73\x6b\x52\x4c\ -\x77\x49\x65\x6f\x79\x46\x45\x48\x76\x74\x68\x70\x67\x42\x70\x32\ -\x45\x36\x36\x70\x67\x73\x48\x46\x30\x4c\x6d\x4e\x6a\x72\x62\x71\ -\x6b\x57\x73\x2f\x6c\x42\x36\x72\x32\x63\x52\x5a\x77\x34\x71\x36\ -\x4c\x64\x76\x64\x20\x4f\x4a\x46\x6b\x4a\x61\x61\x36\x2f\x47\x72\ -\x74\x52\x69\x77\x70\x48\x74\x59\x75\x2f\x59\x62\x31\x47\x67\x33\ -\x4a\x44\x69\x64\x4f\x54\x7a\x72\x4a\x37\x6a\x52\x4d\x53\x51\x36\ -\x38\x76\x67\x34\x63\x33\x52\x67\x66\x56\x56\x58\x35\x33\x39\x4b\ -\x56\x66\x4c\x68\x6b\x4b\x56\x2f\x38\x2b\x63\x47\x75\x79\x4c\x51\ -\x6b\x20\x78\x7a\x62\x78\x37\x6b\x2b\x76\x6a\x49\x38\x6e\x32\x63\ -\x37\x6b\x4f\x32\x38\x6d\x49\x38\x58\x42\x31\x74\x6f\x36\x64\x6a\ -\x59\x30\x38\x58\x33\x70\x56\x6a\x37\x35\x64\x6a\x6e\x56\x54\x53\ -\x32\x34\x6b\x32\x78\x73\x32\x31\x31\x50\x70\x73\x76\x4a\x36\x50\ -\x34\x46\x39\x45\x33\x7a\x6f\x4e\x56\x71\x32\x56\x53\x31\x20\x69\ -\x2f\x75\x6e\x66\x4d\x7a\x37\x39\x2f\x32\x4f\x33\x4e\x53\x66\x49\ -\x77\x68\x61\x72\x65\x61\x59\x2b\x58\x7a\x73\x56\x67\x74\x44\x7a\ -\x37\x69\x45\x56\x4a\x63\x48\x76\x39\x39\x4c\x59\x31\x4d\x39\x30\ -\x79\x71\x71\x2b\x4d\x63\x50\x4d\x78\x42\x38\x62\x61\x53\x5a\x64\ -\x54\x53\x30\x64\x57\x44\x55\x36\x78\x69\x61\x20\x6c\x38\x50\x6f\ -\x41\x66\x32\x77\x6d\x6f\x79\x73\x72\x64\x6a\x4a\x41\x31\x4d\x2b\ -\x35\x72\x31\x37\x62\x6d\x56\x51\x39\x73\x2f\x65\x66\x55\x57\x56\ -\x59\x39\x70\x32\x5a\x58\x74\x63\x76\x48\x33\x33\x4c\x58\x69\x53\ -\x6b\x39\x6a\x52\x30\x45\x54\x35\x37\x6e\x70\x57\x62\x61\x74\x67\ -\x30\x2b\x59\x79\x4e\x75\x78\x75\x20\x77\x71\x74\x6f\x4d\x44\x69\ -\x63\x61\x4f\x78\x4a\x53\x46\x59\x62\x49\x5a\x32\x57\x69\x43\x53\ -\x68\x74\x44\x5a\x54\x47\x47\x68\x6e\x78\x6c\x4d\x50\x6b\x75\x70\ -\x49\x41\x6b\x43\x51\x6f\x6a\x4e\x6a\x4c\x48\x70\x63\x53\x54\x5a\ -\x65\x76\x66\x56\x36\x73\x74\x77\x70\x31\x4c\x65\x31\x55\x31\x48\ -\x58\x79\x4c\x72\x4b\x20\x4b\x74\x36\x5a\x76\x35\x68\x74\x74\x58\ -\x57\x45\x52\x59\x6d\x77\x49\x50\x44\x50\x4c\x2b\x5a\x54\x6e\x4a\ -\x66\x44\x4b\x51\x50\x37\x59\x54\x57\x5a\x2b\x48\x46\x4c\x4f\x66\ -\x66\x2b\x5a\x7a\x6f\x6a\x7a\x72\x6f\x49\x32\x57\x7a\x47\x36\x2f\ -\x63\x68\x4b\x51\x70\x36\x72\x53\x59\x6d\x34\x33\x77\x34\x65\x4a\ -\x4a\x74\x20\x76\x48\x6e\x58\x4c\x61\x51\x37\x6b\x37\x76\x76\x6c\ -\x38\x6c\x32\x6d\x74\x76\x61\x43\x46\x5a\x75\x51\x35\x4f\x55\x6a\ -\x47\x51\x77\x45\x4a\x45\x6b\x77\x6d\x30\x74\x53\x4a\x58\x6c\x4d\ -\x4c\x41\x49\x39\x44\x2f\x37\x4d\x48\x51\x51\x30\x38\x72\x6e\x55\ -\x48\x70\x53\x48\x55\x6e\x6b\x70\x58\x6d\x59\x39\x73\x4f\x4b\x20\ -\x58\x6f\x30\x54\x4a\x63\x61\x4a\x7a\x6d\x77\x30\x34\x4f\x34\x2f\ -\x46\x49\x63\x6e\x44\x56\x55\x55\x69\x50\x68\x39\x74\x4c\x61\x31\ -\x55\x4c\x31\x70\x4c\x53\x46\x66\x4f\x33\x49\x34\x6a\x45\x73\x48\ -\x7a\x30\x32\x62\x78\x61\x6a\x43\x41\x6b\x37\x6f\x6c\x30\x65\x61\ -\x49\x35\x6b\x6c\x47\x38\x74\x34\x61\x63\x61\x58\x20\x66\x50\x62\ -\x49\x50\x66\x75\x6b\x48\x73\x51\x36\x38\x65\x35\x50\x72\x34\x79\ -\x50\x32\x57\x41\x6b\x4a\x41\x69\x59\x44\x41\x61\x47\x39\x63\x31\ -\x6c\x57\x4e\x39\x63\x4c\x6a\x6c\x35\x4a\x47\x72\x6e\x66\x72\x47\ -\x71\x71\x5a\x6c\x50\x76\x6c\x33\x4f\x75\x6f\x6f\x71\x70\x69\x7a\ -\x34\x6c\x6a\x61\x66\x48\x34\x38\x6a\x20\x6d\x5a\x72\x6d\x56\x74\ -\x36\x34\x34\x34\x59\x44\x50\x50\x77\x36\x72\x52\x62\x35\x47\x50\ -\x6c\x38\x7a\x41\x59\x6a\x76\x6c\x41\x41\x55\x38\x53\x4f\x78\x6d\ -\x44\x45\x6d\x5a\x47\x46\x79\x5a\x31\x4b\x35\x71\x42\x68\x42\x49\ -\x51\x77\x37\x58\x34\x76\x32\x6f\x71\x74\x2f\x47\x56\x35\x4b\x66\ -\x34\x76\x6c\x79\x44\x37\x20\x66\x65\x51\x37\x37\x49\x69\x52\x43\ -\x42\x2f\x38\x34\x58\x5a\x47\x39\x53\x2f\x59\x5a\x2f\x6b\x73\x53\ -\x72\x45\x31\x67\x4e\x31\x73\x78\x42\x73\x4d\x6b\x5a\x66\x6d\x6f\ -\x54\x67\x76\x6d\x2b\x4b\x38\x62\x48\x35\x39\x79\x73\x69\x75\x36\ -\x36\x75\x32\x56\x66\x44\x45\x52\x39\x4d\x5a\x30\x7a\x2b\x44\x46\ -\x56\x75\x33\x20\x55\x39\x48\x63\x79\x67\x35\x2f\x69\x41\x77\x64\ -\x7a\x48\x72\x71\x49\x66\x70\x31\x72\x73\x43\x69\x57\x69\x54\x30\ -\x75\x74\x68\x38\x4c\x43\x61\x39\x67\x62\x41\x67\x6f\x74\x4e\x71\ -\x79\x58\x4b\x37\x79\x48\x4b\x37\x47\x46\x73\x38\x71\x4b\x74\x74\ -\x61\x31\x76\x62\x75\x50\x72\x46\x31\x39\x46\x71\x4e\x48\x79\x34\ -\x20\x36\x41\x63\x65\x2f\x57\x42\x71\x39\x50\x4e\x32\x50\x36\x4d\ -\x6e\x58\x49\x48\x4a\x36\x61\x4c\x4a\x37\x30\x56\x53\x5a\x41\x52\ -\x5a\x77\x6f\x4a\x36\x7a\x49\x7a\x50\x48\x75\x30\x39\x39\x63\x75\ -\x64\x6a\x63\x32\x63\x39\x71\x66\x6e\x61\x47\x79\x6f\x52\x61\x6e\ -\x59\x41\x70\x49\x59\x4e\x54\x61\x69\x43\x50\x30\x48\x20\x67\x33\ -\x6e\x66\x5a\x46\x4b\x39\x52\x68\x50\x54\x4e\x75\x64\x51\x65\x6a\ -\x5a\x56\x31\x58\x44\x72\x36\x2b\x2b\x53\x37\x6e\x54\x30\x61\x70\ -\x7a\x49\x73\x68\x78\x54\x58\x56\x70\x4e\x42\x6e\x62\x35\x4f\x67\ -\x67\x61\x6a\x57\x69\x31\x57\x72\x51\x47\x41\x32\x70\x61\x42\x71\ -\x62\x55\x4e\x48\x53\x79\x51\x74\x6a\x58\x20\x67\x61\x74\x32\x4f\ -\x33\x31\x63\x4b\x55\x78\x66\x74\x70\x4b\x2f\x66\x6a\x59\x4c\x58\ -\x79\x68\x4d\x59\x34\x65\x58\x75\x58\x39\x35\x6d\x48\x36\x5a\x36\ -\x66\x76\x71\x55\x57\x4c\x54\x73\x7a\x2b\x39\x4d\x7a\x35\x36\x50\ -\x57\x48\x68\x77\x42\x44\x6b\x6e\x6b\x47\x5a\x6c\x2b\x70\x68\x79\ -\x59\x62\x4e\x66\x50\x37\x34\x20\x2f\x64\x6a\x4e\x4a\x6a\x6f\x43\ -\x51\x61\x71\x62\x57\x72\x6a\x37\x72\x51\x38\x59\x57\x7a\x7a\x34\ -\x67\x4c\x32\x76\x54\x71\x75\x4e\x61\x38\x6a\x75\x59\x46\x67\x4e\ -\x4f\x72\x7a\x42\x41\x49\x5a\x77\x45\x41\x30\x67\x4b\x51\x71\x43\ -\x4c\x42\x45\x53\x42\x55\x4b\x69\x69\x43\x44\x4c\x74\x4f\x34\x73\ -\x78\x33\x58\x79\x20\x57\x4b\x53\x4d\x50\x76\x6a\x44\x49\x63\x71\ -\x46\x43\x49\x57\x37\x4b\x37\x73\x69\x59\x6e\x75\x6a\x4b\x47\x70\ -\x4d\x30\x61\x55\x6b\x69\x78\x6c\x66\x4b\x4c\x54\x50\x5a\x33\x73\ -\x2f\x77\x35\x56\x6b\x70\x79\x41\x7a\x6e\x53\x65\x76\x6d\x59\x69\ -\x71\x71\x76\x6a\x44\x59\x54\x35\x59\x39\x41\x4d\x4e\x37\x56\x36\ -\x4b\x20\x63\x72\x4c\x32\x4b\x53\x66\x49\x4d\x76\x6f\x59\x4f\x34\ -\x4e\x4a\x72\x2b\x38\x32\x76\x4c\x78\x48\x6b\x39\x4e\x71\x35\x64\ -\x52\x42\x2f\x62\x6e\x37\x6f\x76\x4d\x41\x69\x49\x67\x69\x4e\x63\ -\x32\x74\x6a\x48\x74\x75\x4d\x70\x6c\x39\x63\x6d\x6e\x75\x33\x4e\ -\x49\x49\x55\x6a\x52\x79\x6c\x48\x51\x4d\x56\x7a\x36\x48\x20\x30\ -\x74\x34\x33\x7a\x59\x50\x4e\x5a\x6b\x58\x4a\x79\x67\x57\x74\x44\ -\x6d\x51\x5a\x77\x6b\x48\x59\x57\x51\x6e\x64\x76\x46\x5a\x6b\x30\ -\x47\x70\x69\x32\x73\x49\x65\x53\x73\x2f\x67\x6e\x44\x36\x38\x65\ -\x2f\x65\x74\x44\x4d\x76\x50\x52\x56\x58\x56\x51\x34\x34\x54\x4b\ -\x63\x61\x56\x52\x70\x4c\x5a\x54\x48\x76\x41\x20\x68\x38\x39\x6f\ -\x37\x46\x72\x52\x71\x59\x43\x71\x67\x71\x49\x71\x4b\x4f\x45\x67\ -\x51\x2b\x30\x32\x62\x6a\x35\x33\x48\x44\x65\x66\x4f\x77\x35\x4a\ -\x6c\x70\x6d\x2f\x64\x69\x4d\x7a\x6c\x71\x39\x69\x57\x4e\x2f\x63\ -\x41\x2b\x34\x6e\x79\x66\x46\x64\x2b\x66\x54\x71\x54\x6d\x61\x54\ -\x6f\x56\x76\x6a\x73\x77\x65\x4e\x20\x52\x73\x4e\x4e\x35\x34\x7a\ -\x46\x6f\x4e\x4f\x69\x30\x57\x68\x77\x32\x6d\x33\x30\x79\x30\x78\ -\x48\x52\x59\x33\x2b\x70\x66\x73\x2f\x56\x4b\x4e\x42\x4f\x55\x59\ -\x4f\x5a\x37\x4e\x42\x6a\x7a\x63\x55\x6f\x43\x4d\x55\x70\x44\x30\ -\x63\x78\x42\x73\x4f\x34\x51\x75\x48\x43\x45\x53\x69\x45\x59\x2b\ -\x49\x49\x6d\x50\x4e\x20\x4c\x53\x44\x53\x36\x64\x79\x56\x55\x63\ -\x46\x6f\x52\x4e\x56\x6f\x6f\x76\x72\x33\x51\x31\x61\x55\x6d\x4a\ -\x78\x75\x54\x70\x75\x56\x4e\x6e\x2b\x77\x78\x2b\x74\x39\x58\x43\ -\x6e\x63\x65\x50\x59\x59\x49\x46\x71\x76\x53\x52\x59\x4c\x47\x53\ -\x6b\x4f\x4e\x42\x6f\x4f\x36\x4a\x79\x69\x4a\x47\x48\x51\x78\x35\ -\x53\x6b\x20\x6a\x74\x47\x67\x49\x33\x79\x51\x33\x42\x61\x54\x77\ -\x63\x41\x4a\x2f\x66\x4b\x36\x5a\x6d\x2b\x54\x77\x55\x42\x47\x69\ -\x68\x4f\x4e\x47\x74\x30\x57\x43\x4c\x49\x55\x39\x61\x4e\x49\x41\ -\x68\x46\x52\x78\x4b\x69\x4e\x62\x52\x73\x59\x54\x2b\x30\x61\x6a\ -\x51\x61\x7a\x58\x67\x2b\x4b\x47\x74\x31\x50\x36\x66\x56\x67\x20\ -\x73\x6b\x53\x64\x72\x4e\x31\x6f\x4e\x4d\x52\x6f\x4f\x41\x2b\x6c\ -\x4a\x78\x51\x52\x75\x50\x75\x74\x44\x31\x42\x56\x74\x56\x66\x6a\ -\x52\x46\x62\x55\x6d\x4f\x72\x53\x61\x62\x4f\x69\x45\x53\x56\x6b\ -\x53\x55\x61\x55\x5a\x41\x52\x4a\x52\x70\x52\x6c\x4a\x45\x58\x75\ -\x6d\x76\x79\x6c\x76\x63\x61\x68\x58\x71\x66\x44\x20\x6e\x57\x78\ -\x48\x73\x33\x64\x6b\x64\x53\x2b\x69\x77\x5a\x5a\x6a\x76\x75\x30\ -\x79\x45\x42\x4b\x45\x48\x71\x2b\x72\x71\x73\x71\x47\x48\x64\x57\ -\x63\x55\x54\x53\x51\x76\x4d\x37\x73\x55\x4c\x31\x4f\x68\x36\x79\ -\x6f\x33\x64\x56\x70\x64\x4f\x56\x7a\x6a\x48\x77\x2b\x4e\x71\x4d\ -\x52\x58\x7a\x43\x41\x4e\x68\x7a\x73\x20\x30\x69\x72\x4b\x30\x53\ -\x31\x43\x52\x42\x4c\x78\x4e\x6a\x66\x67\x71\x36\x71\x45\x67\x41\ -\x38\x78\x79\x51\x47\x79\x42\x42\x5a\x72\x64\x4c\x42\x31\x49\x31\ -\x46\x52\x6c\x4a\x67\x36\x68\x4e\x74\x75\x6f\x39\x6e\x62\x63\x2b\ -\x6a\x36\x6d\x2f\x57\x62\x75\x4f\x66\x74\x44\x31\x6a\x34\x37\x4b\ -\x4e\x38\x75\x58\x6f\x64\x20\x5a\x77\x38\x66\x67\x71\x72\x53\x37\ -\x59\x77\x71\x53\x4c\x47\x48\x50\x73\x32\x47\x67\x30\x38\x73\x32\ -\x33\x62\x58\x38\x66\x78\x6e\x63\x78\x68\x56\x57\x4d\x43\x6d\x36\ -\x6c\x32\x4d\x4b\x52\x71\x49\x7a\x52\x79\x4e\x78\x41\x54\x46\x61\ -\x4e\x51\x6f\x2b\x71\x2b\x41\x70\x4d\x67\x59\x4e\x5a\x71\x34\x52\ -\x6b\x52\x69\x20\x30\x54\x35\x6a\x32\x53\x6f\x51\x42\x66\x72\x57\ -\x56\x46\x41\x64\x45\x56\x46\x73\x79\x64\x45\x56\x6a\x36\x70\x45\ -\x42\x2f\x74\x2b\x37\x57\x6a\x55\x61\x6d\x50\x7a\x73\x52\x78\x43\ -\x7a\x36\x49\x4e\x6d\x39\x6c\x63\x33\x30\x54\x52\x66\x55\x38\x79\ -\x49\x69\x65\x44\x6b\x77\x59\x55\x4d\x4b\x78\x76\x44\x70\x4b\x73\ -\x20\x52\x4b\x4f\x57\x2b\x33\x31\x66\x6c\x75\x58\x59\x4a\x6a\x71\ -\x72\x46\x57\x4e\x7a\x42\x49\x32\x71\x52\x55\x4a\x46\x30\x71\x68\ -\x30\x44\x54\x74\x56\x67\x64\x32\x37\x36\x4e\x41\x71\x6e\x50\x33\ -\x34\x38\x30\x79\x2b\x38\x30\x59\x32\x56\x64\x55\x67\x4b\x77\x71\ -\x69\x4a\x48\x63\x5a\x79\x48\x33\x30\x48\x49\x39\x6f\x20\x6c\x39\ -\x31\x6b\x77\x68\x2f\x75\x4f\x65\x33\x39\x72\x62\x6d\x4c\x57\x4c\ -\x53\x68\x6c\x4d\x74\x4f\x47\x38\x30\x7a\x55\x7a\x39\x6e\x66\x50\ -\x46\x67\x7a\x68\x6b\x78\x42\x46\x47\x57\x6b\x56\x55\x46\x33\x58\ -\x37\x56\x71\x74\x55\x65\x75\x31\x43\x37\x7a\x57\x54\x45\x31\x78\ -\x47\x41\x55\x4e\x54\x34\x4b\x4b\x71\x4b\x20\x72\x4d\x69\x49\x73\ -\x6f\x53\x2f\x75\x5a\x47\x77\x45\x49\x48\x63\x76\x67\x68\x61\x4c\ -\x57\x72\x41\x42\x36\x33\x4e\x6b\x4a\x46\x46\x59\x30\x73\x72\x50\ -\x32\x7a\x65\x69\x73\x74\x75\x49\x79\x50\x46\x53\x55\x36\x71\x47\ -\x36\x31\x47\x67\x78\x53\x6a\x38\x58\x48\x5a\x37\x54\x52\x37\x2f\ -\x51\x64\x38\x4c\x73\x6b\x79\x20\x58\x2f\x32\x30\x6e\x69\x78\x33\ -\x43\x67\x75\x65\x2f\x52\x4d\x35\x71\x53\x37\x53\x6e\x51\x37\x71\ -\x32\x74\x70\x5a\x56\x31\x6e\x46\x56\x36\x74\x4c\x6d\x48\x54\x57\ -\x57\x47\x61\x74\x2b\x49\x6e\x4c\x54\x78\x75\x4e\x78\x35\x46\x4d\ -\x52\x79\x43\x49\x51\x52\x75\x62\x38\x62\x45\x61\x6a\x64\x31\x6d\ -\x30\x53\x71\x71\x20\x69\x69\x38\x59\x34\x72\x30\x46\x33\x2f\x48\ -\x71\x72\x64\x64\x68\x4d\x35\x76\x59\x73\x47\x4d\x58\x36\x51\x34\ -\x48\x62\x38\x39\x62\x6a\x43\x68\x4c\x31\x4e\x62\x73\x70\x4b\x36\ -\x6c\x6b\x61\x44\x4e\x52\x6a\x41\x63\x52\x46\x58\x56\x61\x4b\x67\ -\x39\x6a\x68\x47\x52\x49\x39\x45\x75\x53\x6a\x4a\x62\x61\x33\x66\ -\x6a\x20\x44\x59\x57\x5a\x39\x2f\x51\x6a\x32\x43\x30\x6d\x61\x70\ -\x76\x62\x57\x4c\x32\x39\x6b\x68\x56\x62\x4b\x2f\x68\x33\x65\x52\ -\x6e\x32\x37\x5a\x74\x70\x31\x78\x70\x51\x37\x45\x6c\x67\x54\x77\ -\x4b\x54\x43\x5a\x4e\x4f\x47\x39\x4d\x32\x74\x6b\x63\x39\x73\x73\ -\x79\x55\x2b\x55\x74\x34\x5a\x63\x46\x79\x54\x72\x2f\x6b\x20\x4f\ -\x6b\x53\x4e\x68\x6f\x72\x57\x4a\x6e\x37\x63\x55\x49\x31\x76\x38\ -\x57\x72\x38\x4e\x64\x57\x63\x2f\x74\x6a\x7a\x6a\x4d\x37\x50\x35\ -\x64\x52\x42\x68\x5a\x7a\x59\x4c\x35\x39\x4d\x6c\x37\x4e\x7a\x32\ -\x33\x58\x6b\x64\x57\x6b\x31\x47\x54\x43\x71\x6f\x4e\x64\x71\x6b\ -\x56\x51\x31\x2b\x6f\x4f\x4b\x4a\x49\x6c\x51\x20\x56\x63\x36\x39\ -\x70\x77\x7a\x6e\x69\x61\x73\x75\x4a\x53\x79\x49\x57\x45\x78\x47\ -\x76\x6c\x71\x39\x6e\x71\x59\x4f\x48\x2f\x50\x58\x62\x75\x43\x36\ -\x56\x39\x37\x6b\x75\x64\x39\x65\x79\x62\x72\x4b\x4b\x73\x59\x55\ -\x44\x53\x44\x4a\x59\x6f\x6c\x47\x75\x2b\x49\x59\x79\x65\x79\x56\ -\x38\x62\x47\x5a\x54\x66\x68\x44\x20\x42\x78\x6f\x66\x58\x79\x6a\ -\x4d\x6b\x67\x32\x62\x79\x55\x39\x50\x35\x5a\x76\x6e\x48\x6f\x75\ -\x6d\x5a\x64\x75\x73\x68\x41\x57\x52\x65\x57\x73\x32\x73\x4b\x75\ -\x70\x68\x64\x4b\x71\x47\x75\x61\x73\x57\x73\x74\x31\x34\x30\x36\ -\x6a\x49\x43\x4d\x4e\x62\x57\x66\x53\x33\x4c\x46\x4b\x63\x4c\x61\ -\x61\x6a\x66\x6a\x71\x20\x57\x31\x48\x32\x57\x76\x6c\x49\x69\x6b\ -\x4b\x6f\x76\x68\x62\x2f\x72\x68\x33\x6f\x69\x34\x59\x68\x71\x47\ -\x70\x30\x70\x57\x4f\x78\x67\x6a\x73\x56\x56\x42\x57\x37\x33\x55\ -\x37\x2f\x7a\x41\x79\x2b\x33\x62\x69\x5a\x4f\x53\x76\x58\x4d\x6e\ -\x70\x41\x50\x2f\x37\x31\x39\x54\x66\x6f\x64\x62\x48\x4e\x6a\x75\ -\x34\x6b\x20\x47\x2b\x75\x72\x64\x78\x2f\x77\x2b\x61\x4b\x53\x55\ -\x6a\x37\x39\x37\x6b\x66\x65\x76\x2b\x38\x32\x72\x4b\x62\x6f\x79\ -\x34\x54\x58\x6e\x33\x6b\x36\x41\x42\x61\x6a\x67\x63\x62\x32\x44\ -\x6a\x4a\x64\x54\x67\x6f\x79\x30\x67\x68\x45\x42\x4e\x36\x65\x4e\ -\x6f\x75\x6c\x6d\x37\x63\x78\x49\x44\x50\x74\x67\x48\x73\x64\x20\ -\x44\x6c\x61\x7a\x6b\x55\x44\x34\x77\x41\x48\x7a\x31\x74\x66\x66\ -\x73\x4c\x61\x79\x69\x6e\x66\x75\x76\x71\x58\x4c\x32\x4f\x37\x4a\ -\x42\x42\x2f\x56\x50\x35\x38\x2b\x64\x7a\x36\x4f\x58\x34\x6a\x51\ -\x56\x46\x65\x44\x37\x45\x34\x6c\x55\x72\x6f\x65\x58\x42\x36\x4d\ -\x65\x6c\x31\x63\x33\x34\x67\x2b\x45\x75\x32\x76\x20\x7a\x5a\x35\ -\x4c\x56\x57\x4d\x7a\x62\x39\x77\x78\x36\x57\x66\x66\x6c\x63\x33\ -\x47\x6b\x4c\x78\x73\x4a\x70\x30\x31\x68\x70\x2f\x4b\x4b\x35\x6e\ -\x78\x36\x4c\x31\x55\x31\x6a\x65\x78\x61\x6c\x73\x46\x4b\x38\x73\ -\x72\x57\x62\x6d\x6a\x48\x4c\x74\x52\x6a\x30\x46\x2f\x35\x4d\x61\ -\x38\x4f\x7a\x30\x52\x55\x65\x54\x78\x20\x6a\x36\x59\x7a\x62\x33\ -\x73\x44\x5a\x31\x35\x38\x4c\x57\x46\x56\x78\x52\x63\x4a\x59\x55\ -\x76\x78\x34\x4c\x48\x61\x4d\x47\x62\x6c\x30\x4e\x48\x53\x79\x45\ -\x5a\x6e\x4a\x71\x75\x71\x6d\x35\x6c\x63\x57\x6f\x6b\x75\x34\x43\ -\x66\x48\x70\x43\x50\x4e\x59\x6f\x71\x70\x4c\x69\x31\x47\x49\x79\ -\x61\x4e\x42\x6f\x76\x4f\x20\x67\x4b\x67\x6f\x69\x4b\x70\x43\x4f\ -\x42\x4a\x45\x57\x31\x6e\x47\x43\x35\x64\x4e\x34\x4a\x36\x4c\x4a\ -\x2b\x77\x7a\x6b\x54\x34\x34\x38\x51\x49\x32\x56\x65\x32\x69\x66\ -\x48\x63\x39\x7a\x39\x39\x77\x46\x53\x61\x44\x6e\x6e\x55\x56\x4f\ -\x37\x47\x5a\x6a\x4d\x78\x59\x76\x68\x71\x62\x79\x59\x67\x2b\x78\ -\x73\x6c\x75\x20\x62\x33\x71\x33\x38\x72\x47\x59\x38\x4f\x31\x6e\ -\x66\x4d\x4b\x43\x79\x41\x76\x54\x35\x35\x43\x62\x36\x75\x62\x32\ -\x58\x35\x33\x56\x31\x63\x69\x44\x73\x76\x73\x41\x4d\x44\x77\x2f\ -\x6c\x38\x6c\x66\x4c\x79\x54\x4c\x34\x32\x4a\x51\x64\x68\x38\x43\ -\x45\x59\x46\x72\x58\x70\x35\x4d\x74\x73\x65\x46\x51\x61\x38\x2f\ -\x20\x5a\x69\x73\x66\x75\x38\x6c\x4d\x49\x42\x68\x45\x44\x41\x55\ -\x41\x55\x45\x57\x52\x53\x48\x6b\x5a\x35\x50\x52\x46\x47\x56\x68\ -\x4d\x70\x44\x73\x64\x47\x67\x30\x47\x76\x59\x35\x55\x52\x78\x4b\ -\x33\x6e\x33\x39\x32\x39\x4e\x30\x75\x4a\x5a\x70\x77\x57\x4a\x79\ -\x56\x45\x56\x4f\x48\x38\x43\x54\x62\x61\x66\x62\x36\x20\x75\x70\ -\x61\x31\x48\x59\x45\x67\x39\x37\x33\x7a\x45\x51\x39\x64\x64\x69\ -\x48\x2f\x66\x65\x69\x75\x62\x69\x4e\x58\x4a\x6f\x4d\x42\x52\x56\ -\x56\x4a\x73\x64\x76\x34\x7a\x64\x68\x54\x41\x63\x68\x4c\x64\x58\ -\x50\x78\x73\x33\x2f\x6a\x77\x55\x76\x4f\x4f\x32\x49\x74\x45\x4b\ -\x30\x66\x2f\x31\x34\x44\x70\x69\x4d\x51\x20\x5a\x50\x72\x53\x6c\ -\x5a\x77\x30\x6f\x4a\x41\x62\x7a\x78\x6e\x62\x62\x64\x61\x4c\x32\ -\x57\x68\x45\x56\x6d\x51\x55\x71\x77\x33\x62\x67\x43\x4c\x71\x66\ -\x52\x32\x6f\x51\x34\x5a\x44\x78\x56\x61\x75\x4f\x58\x2f\x73\x4d\ -\x58\x4d\x34\x37\x36\x2b\x39\x78\x65\x66\x6e\x62\x35\x39\x2f\x7a\ -\x65\x38\x76\x50\x43\x66\x71\x20\x6c\x2b\x70\x6d\x68\x52\x72\x39\ -\x54\x43\x55\x6a\x78\x55\x6c\x65\x57\x69\x70\x6e\x44\x69\x74\x43\ -\x56\x68\x54\x75\x6e\x2f\x49\x78\x42\x61\x6d\x75\x6d\x45\x34\x4a\ -\x36\x45\x37\x50\x54\x66\x39\x34\x6c\x79\x61\x54\x6d\x33\x45\x58\ -\x58\x45\x6c\x49\x46\x42\x43\x45\x4d\x49\x49\x73\x49\x53\x71\x64\ -\x2f\x68\x64\x5a\x20\x42\x6b\x41\x32\x47\x4d\x48\x70\x41\x71\x63\ -\x4c\x57\x56\x48\x59\x75\x62\x57\x55\x4f\x38\x61\x66\x47\x71\x4d\ -\x50\x53\x6f\x38\x5a\x63\x42\x67\x4d\x43\x49\x71\x43\x74\x37\x30\ -\x56\x77\x2b\x35\x79\x33\x72\x76\x6e\x4a\x69\x61\x63\x4f\x4c\x54\ -\x62\x2b\x74\x48\x72\x64\x47\x67\x30\x30\x44\x63\x39\x46\x59\x42\ -\x6e\x20\x72\x37\x2b\x43\x73\x43\x44\x79\x7a\x79\x38\x57\x38\x4d\ -\x68\x6c\x46\x38\x54\x6b\x6b\x44\x2f\x67\x57\x62\x33\x35\x6b\x74\ -\x31\x6b\x77\x72\x75\x58\x38\x56\x6c\x63\x55\x73\x72\x37\x33\x33\ -\x7a\x50\x35\x44\x73\x6d\x6b\x57\x79\x31\x39\x4e\x6a\x49\x69\x68\ -\x71\x4e\x37\x6c\x7a\x64\x2b\x57\x4c\x69\x66\x2b\x36\x2f\x20\x6e\ -\x5a\x72\x6d\x56\x6d\x35\x34\x39\x53\x30\x75\x48\x64\x6e\x7a\x75\ -\x30\x4c\x78\x78\x47\x6f\x32\x45\x68\x48\x43\x43\x4a\x45\x77\x68\ -\x45\x4f\x6f\x6f\x67\x68\x4a\x79\x57\x41\x77\x48\x44\x53\x66\x62\ -\x47\x39\x66\x6c\x55\x61\x6a\x59\x56\x48\x4a\x4a\x75\x70\x61\x32\ -\x6e\x6a\x35\x2b\x73\x74\x69\x30\x75\x4f\x79\x20\x32\x32\x6a\x78\ -\x52\x62\x64\x64\x74\x53\x32\x74\x4e\x48\x58\x34\x4f\x47\x74\x34\ -\x45\x59\x4f\x79\x4d\x33\x73\x4d\x6d\x5a\x76\x32\x53\x34\x53\x55\ -\x46\x59\x56\x6e\x70\x73\x33\x69\x38\x6c\x4e\x4f\x70\x48\x43\x2f\ -\x63\x4f\x6a\x68\x45\x70\x32\x74\x6f\x32\x33\x72\x44\x51\x5a\x35\ -\x66\x2b\x46\x33\x4a\x4e\x73\x73\x20\x6e\x4e\x41\x76\x37\x36\x41\ -\x64\x58\x31\x45\x55\x76\x4a\x30\x4f\x66\x45\x45\x53\x6f\x61\x4f\ -\x4e\x73\x39\x4e\x64\x54\x44\x71\x7a\x2b\x32\x7a\x6f\x6f\x38\x48\ -\x65\x32\x70\x73\x37\x66\x48\x79\x33\x71\x59\x7a\x69\x76\x47\x77\ -\x79\x55\x70\x77\x48\x31\x36\x36\x79\x54\x37\x52\x31\x30\x66\x70\ -\x53\x4b\x6e\x59\x33\x20\x38\x50\x53\x56\x46\x38\x56\x4e\x7a\x35\ -\x5a\x64\x75\x37\x6e\x70\x6a\x66\x63\x77\x35\x68\x55\x7a\x61\x50\ -\x41\x77\x66\x4a\x48\x77\x58\x75\x2b\x58\x43\x59\x52\x46\x67\x62\ -\x41\x6b\x45\x70\x59\x6b\x46\x46\x56\x46\x55\x65\x53\x66\x62\x39\ -\x54\x63\x79\x42\x6c\x70\x44\x6e\x35\x33\x33\x72\x69\x59\x39\x4a\ -\x6a\x31\x20\x42\x6b\x77\x61\x53\x44\x45\x5a\x71\x61\x76\x62\x68\ -\x61\x75\x39\x6a\x6b\x2b\x66\x75\x49\x38\x68\x75\x64\x6b\x39\x48\ -\x6f\x75\x68\x31\x2b\x6d\x51\x35\x48\x30\x6e\x35\x4c\x66\x6d\x4c\ -\x71\x4a\x76\x71\x6f\x76\x78\x51\x77\x62\x47\x70\x47\x64\x2f\x65\ -\x6d\x56\x57\x37\x57\x59\x7a\x2f\x6e\x41\x59\x53\x5a\x61\x5a\x20\ -\x76\x57\x49\x4e\x4b\x76\x44\x69\x70\x4b\x74\x78\x32\x4b\x77\x48\ -\x50\x64\x74\x44\x56\x64\x53\x75\x4b\x41\x6c\x45\x4f\x2b\x7a\x39\ -\x55\x7a\x37\x6d\x7a\x67\x6e\x6a\x4b\x4d\x37\x4e\x36\x72\x46\x63\ -\x50\x4c\x47\x62\x54\x43\x44\x4c\x71\x4d\x45\x41\x36\x72\x62\x4e\ -\x30\x59\x68\x48\x57\x73\x59\x68\x73\x38\x6d\x55\x20\x76\x62\x53\ -\x33\x65\x48\x30\x38\x4e\x32\x30\x57\x7a\x31\x31\x7a\x61\x63\x78\ -\x48\x56\x31\x68\x4e\x4a\x67\x4c\x68\x61\x43\x37\x46\x74\x61\x2b\ -\x38\x53\x55\x51\x55\x75\x65\x47\x73\x4d\x51\x65\x39\x72\x39\x6c\ -\x67\x32\x4d\x66\x68\x2f\x4f\x57\x71\x64\x56\x51\x33\x4e\x48\x4c\ -\x54\x6d\x57\x66\x45\x70\x41\x58\x32\x20\x2b\x50\x4d\x69\x4c\x43\ -\x34\x70\x35\x64\x71\x58\x33\x2b\x54\x57\x43\x65\x4f\x35\x2b\x5a\ -\x78\x78\x68\x35\x78\x78\x5a\x55\x57\x68\x49\x78\x54\x43\x48\x77\ -\x6d\x6a\x69\x69\x4b\x65\x70\x6a\x70\x65\x2f\x75\x31\x6c\x63\x54\ -\x33\x61\x34\x31\x44\x73\x30\x62\x36\x2b\x73\x6f\x6f\x72\x58\x76\ -\x77\x48\x70\x77\x37\x75\x20\x7a\x37\x58\x6a\x54\x6a\x75\x6b\x64\ -\x76\x55\x6f\x74\x65\x30\x65\x50\x64\x2b\x58\x62\x75\x47\x53\x6c\ -\x79\x61\x6a\x4c\x54\x77\x42\x64\x33\x35\x2f\x32\x6b\x50\x42\x36\ -\x50\x74\x6c\x34\x53\x44\x65\x63\x42\x68\x66\x4a\x49\x79\x2f\x36\ -\x2f\x32\x79\x43\x4b\x72\x4b\x7a\x2b\x4d\x6b\x45\x73\x62\x52\x57\ -\x4d\x76\x66\x20\x4a\x6c\x30\x64\x65\x31\x38\x7a\x47\x39\x47\x71\ -\x45\x72\x36\x36\x4b\x76\x49\x31\x41\x65\x59\x39\x2b\x51\x44\x46\ -\x65\x54\x6b\x48\x48\x62\x4e\x36\x72\x62\x5a\x72\x4e\x51\x5a\x51\ -\x73\x71\x4f\x61\x6d\x63\x74\x58\x38\x64\x68\x6c\x46\x38\x61\x6b\ -\x70\x54\x74\x36\x5a\x33\x79\x73\x5a\x6c\x70\x39\x66\x6a\x35\x65\ -\x20\x73\x6f\x78\x6c\x5a\x64\x73\x34\x6f\x32\x67\x41\x32\x5a\x35\ -\x44\x48\x34\x65\x68\x71\x45\x72\x58\x43\x69\x49\x69\x69\x74\x7a\ -\x37\x39\x6b\x65\x4d\x48\x56\x54\x49\x78\x4a\x4e\x50\x6a\x45\x6e\ -\x30\x34\x57\x41\x7a\x6d\x36\x47\x78\x48\x6f\x51\x49\x44\x42\x6b\ -\x65\x39\x65\x76\x30\x41\x6b\x56\x56\x4f\x33\x4d\x69\x20\x56\x42\ -\x37\x2f\x61\x44\x71\x2f\x4f\x58\x31\x30\x7a\x4b\x73\x4d\x41\x4a\ -\x4e\x42\x54\x32\x31\x4c\x57\x7a\x51\x76\x36\x72\x45\x2f\x63\x4e\ -\x4b\x41\x37\x74\x2b\x4a\x32\x37\x66\x4d\x7a\x79\x75\x66\x75\x74\ -\x5a\x32\x6e\x70\x33\x36\x4f\x53\x39\x63\x66\x30\x56\x4d\x2f\x6f\ -\x6b\x39\x32\x4d\x78\x6d\x46\x71\x7a\x62\x20\x69\x44\x76\x5a\x7a\ -\x6a\x76\x33\x33\x49\x4c\x64\x62\x4f\x37\x56\x59\x56\x47\x4b\x49\ -\x74\x4d\x52\x44\x69\x49\x71\x4d\x72\x72\x71\x53\x70\x36\x2b\x35\ -\x4e\x79\x34\x31\x4d\x2f\x68\x59\x44\x4f\x62\x6d\x62\x75\x6d\x42\ -\x46\x6c\x52\x2b\x4f\x69\x42\x4f\x38\x6c\x4d\x63\x66\x61\x71\x33\ -\x4a\x35\x2b\x47\x65\x2b\x32\x20\x74\x5a\x6e\x4e\x7a\x46\x72\x78\ -\x45\x78\x50\x2f\x2f\x6a\x37\x32\x45\x30\x35\x48\x6c\x2b\x4b\x6d\ -\x4a\x65\x43\x6e\x4a\x65\x69\x6e\x4a\x52\x69\x67\x4c\x52\x6a\x6f\ -\x66\x4d\x45\x31\x69\x43\x38\x63\x4e\x64\x79\x42\x53\x49\x53\x75\ -\x73\x4b\x71\x71\x6f\x71\x6e\x63\x78\x70\x4f\x58\x54\x6d\x42\x77\ -\x39\x75\x47\x64\x20\x6d\x64\x4d\x64\x79\x56\x59\x4c\x35\x64\x75\ -\x33\x63\x4b\x4c\x48\x7a\x4f\x65\x50\x33\x6b\x64\x57\x4c\x38\x34\ -\x46\x30\x75\x74\x30\x58\x65\x48\x33\x73\x43\x42\x77\x37\x7a\x73\ -\x66\x38\x76\x54\x56\x6c\x2b\x4b\x77\x78\x66\x39\x30\x7a\x31\x34\ -\x5a\x6e\x32\x53\x7a\x6d\x59\x2b\x58\x4c\x4b\x4e\x66\x5a\x68\x71\ -\x50\x20\x58\x6e\x6b\x4a\x78\x6c\x37\x6d\x6c\x69\x69\x64\x6a\x6c\ -\x78\x46\x55\x58\x6a\x36\x30\x38\x39\x4a\x74\x68\x68\x6a\x58\x6b\ -\x6f\x65\x4c\x72\x6d\x70\x4c\x72\x4c\x4e\x42\x6e\x54\x4e\x6a\x64\ -\x44\x52\x44\x6f\x4c\x51\x62\x55\x37\x46\x2f\x71\x69\x64\x32\x75\ -\x65\x75\x4b\x61\x47\x68\x72\x59\x32\x72\x7a\x78\x67\x64\x20\x46\ -\x7a\x31\x4a\x5a\x6a\x4e\x6e\x44\x4f\x72\x50\x79\x7a\x4f\x2f\x34\ -\x74\x6d\x70\x73\x35\x69\x33\x5a\x67\x50\x4e\x48\x62\x36\x44\x35\ -\x6a\x32\x5a\x6a\x64\x48\x6b\x74\x59\x67\x6f\x63\x76\x2b\x55\x6a\ -\x33\x6e\x67\x34\x6e\x50\x4a\x63\x76\x56\x75\x6f\x42\x32\x4b\x33\ -\x46\x51\x58\x32\x32\x76\x72\x65\x47\x76\x75\x20\x59\x74\x5a\x58\ -\x56\x74\x48\x6b\x39\x66\x55\x71\x41\x56\x52\x56\x56\x63\x4b\x69\ -\x41\x4b\x33\x4e\x58\x4a\x44\x6c\x69\x56\x76\x39\x48\x41\x35\x37\ -\x74\x4c\x2f\x2b\x35\x51\x49\x32\x56\x75\x33\x71\x74\x58\x62\x6c\ -\x4b\x4c\x56\x74\x54\x6d\x6f\x4b\x32\x32\x72\x72\x55\x45\x77\x57\ -\x57\x6c\x75\x61\x61\x47\x35\x76\x20\x6f\x54\x58\x6f\x70\x7a\x58\ -\x6f\x70\x79\x33\x6f\x70\x79\x30\x55\x6f\x4c\x30\x7a\x35\x38\x7a\ -\x62\x61\x58\x78\x45\x57\x61\x4a\x72\x2f\x39\x2f\x55\x77\x4e\x6c\ -\x5a\x71\x66\x78\x32\x33\x43\x6b\x48\x66\x55\x35\x76\x4f\x57\x31\ -\x67\x49\x56\x65\x63\x63\x69\x4b\x62\x71\x71\x71\x35\x39\x35\x30\ -\x50\x6d\x62\x35\x30\x20\x4a\x58\x57\x74\x37\x51\x64\x73\x71\x2f\ -\x5a\x47\x72\x34\x75\x75\x66\x42\x52\x46\x34\x66\x6e\x70\x63\x78\ -\x68\x58\x31\x4a\x39\x52\x68\x58\x33\x6a\x6f\x75\x65\x41\x5a\x2f\ -\x58\x6d\x53\x30\x55\x35\x66\x58\x6a\x32\x6d\x6f\x6e\x38\x66\x64\ -\x62\x58\x31\x4c\x56\x37\x79\x55\x39\x50\x34\x39\x77\x52\x78\x5a\ -\x77\x35\x20\x72\x49\x6a\x63\x56\x48\x65\x50\x4d\x2b\x57\x65\x51\ -\x37\x6a\x65\x58\x66\x41\x74\x32\x32\x76\x72\x6d\x48\x7a\x62\x74\ -\x63\x66\x4d\x47\x62\x6d\x48\x34\x74\x77\x73\x56\x72\x7a\x34\x4f\ -\x47\x73\x71\x64\x72\x4b\x67\x70\x4a\x51\x46\x6d\x37\x65\x7a\x50\ -\x52\x42\x42\x54\x58\x46\x42\x69\x67\x65\x4d\x78\x6d\x36\x33\x20\ -\x59\x49\x71\x71\x30\x74\x6a\x68\x35\x53\x2f\x2f\x6e\x63\x6d\x48\ -\x39\x39\x37\x53\x61\x34\x4e\x37\x4b\x49\x77\x47\x50\x53\x39\x50\ -\x75\x70\x4b\x4f\x59\x49\x69\x31\x46\x54\x75\x5a\x75\x33\x6f\x4e\ -\x4c\x30\x79\x66\x6a\x54\x73\x35\x69\x51\x6b\x6e\x44\x75\x4f\x69\ -\x30\x53\x65\x51\x35\x55\x37\x5a\x70\x30\x35\x4e\x20\x6e\x65\x38\ -\x6b\x66\x62\x42\x6f\x4b\x52\x61\x44\x6a\x6f\x74\x48\x39\x33\x77\ -\x65\x7a\x4f\x46\x53\x6e\x4a\x76\x46\x30\x75\x63\x66\x5a\x55\x33\ -\x46\x54\x72\x35\x65\x74\x59\x62\x6e\x50\x35\x74\x44\x75\x74\x50\ -\x42\x2b\x53\x4f\x48\x63\x66\x36\x6f\x45\x66\x52\x78\x64\x65\x2b\ -\x34\x52\x56\x56\x42\x69\x4a\x44\x53\x20\x55\x4d\x76\x2f\x50\x58\ -\x56\x2f\x33\x4f\x72\x6e\x63\x4c\x58\x2f\x32\x4e\x6d\x32\x68\x36\ -\x4e\x64\x56\x56\x55\x61\x32\x6a\x76\x69\x33\x72\x5a\x44\x63\x37\ -\x4e\x5a\x39\x74\x66\x48\x57\x4c\x6d\x39\x6b\x76\x6e\x72\x4e\x72\ -\x46\x77\x32\x54\x6f\x43\x52\x67\x74\x47\x54\x7a\x6f\x36\x64\x79\ -\x71\x4b\x30\x59\x41\x67\x20\x79\x55\x52\x6b\x45\x55\x6d\x57\x39\ -\x30\x30\x6a\x69\x34\x53\x78\x31\x65\x33\x69\x74\x57\x63\x65\x78\ -\x47\x77\x30\x78\x6b\x56\x50\x5a\x6f\x71\x44\x4b\x58\x66\x64\x69\ -\x43\x38\x55\x5a\x74\x32\x4f\x61\x68\x5a\x76\x4b\x4f\x4f\x31\x32\ -\x56\x2b\x54\x62\x4c\x56\x78\x7a\x6f\x68\x69\x4c\x6a\x6e\x70\x42\ -\x50\x72\x33\x20\x79\x64\x69\x6e\x6a\x6e\x52\x61\x48\x62\x4b\x69\ -\x73\x4c\x79\x73\x6e\x4f\x38\x32\x6c\x6a\x48\x7a\x6a\x33\x63\x64\ -\x6c\x57\x4f\x44\x34\x51\x69\x4f\x55\x5a\x56\x6c\x68\x55\x32\x37\ -\x61\x6c\x6d\x38\x73\x59\x79\x6c\x5a\x64\x73\x4a\x69\x53\x49\x6a\ -\x43\x76\x49\x59\x58\x7a\x79\x59\x6b\x59\x58\x35\x35\x4b\x58\x39\ -\x20\x66\x48\x35\x4a\x30\x56\x31\x2f\x35\x4d\x47\x4a\x46\x7a\x44\ -\x31\x32\x2b\x58\x38\x39\x2f\x37\x62\x59\x71\x37\x55\x65\x42\x32\ -\x31\x75\x57\x31\x33\x50\x66\x50\x58\x6c\x66\x4c\x4e\x68\x73\x32\ -\x73\x61\x57\x7a\x44\x61\x37\x5a\x43\x69\x68\x76\x73\x39\x6d\x67\ -\x61\x50\x75\x41\x71\x58\x63\x63\x5a\x2f\x66\x4f\x35\x20\x5a\x47\ -\x51\x78\x56\x35\x31\x2b\x55\x6b\x7a\x50\x36\x77\x30\x56\x39\x59\ -\x30\x73\x58\x46\x2f\x4b\x67\x67\x31\x6c\x4b\x4b\x72\x4b\x4b\x51\ -\x4d\x4c\x2b\x64\x58\x49\x34\x59\x77\x6f\x79\x45\x57\x44\x68\x67\ -\x47\x33\x50\x30\x52\x2b\x75\x70\x75\x70\x44\x39\x77\x52\x31\x30\ -\x50\x35\x75\x32\x4e\x50\x2f\x53\x7a\x61\x20\x57\x49\x5a\x47\x71\ -\x32\x58\x4d\x6b\x49\x47\x63\x64\x38\x4a\x51\x52\x68\x54\x6b\x59\ -\x65\x6c\x73\x51\x39\x4d\x31\x64\x36\x42\x61\x37\x66\x7a\x72\x69\ -\x67\x6c\x78\x71\x5a\x39\x34\x74\x2b\x33\x42\x74\x41\x2b\x38\x34\ -\x79\x47\x47\x35\x2b\x63\x78\x59\x64\x69\x67\x6f\x39\x36\x32\x4b\ -\x37\x5a\x57\x73\x4c\x42\x6b\x20\x4d\x30\x73\x32\x62\x57\x46\x6a\ -\x71\x35\x64\x49\x6b\x69\x4d\x61\x31\x62\x49\x6e\x52\x64\x2b\x6d\ -\x56\x32\x54\x59\x73\x42\x61\x64\x32\x63\x79\x72\x6c\x35\x7a\x4e\ -\x54\x57\x66\x46\x37\x73\x63\x37\x46\x4e\x56\x4e\x4c\x53\x77\x6f\ -\x4b\x57\x58\x2b\x2b\x6c\x4a\x38\x6f\x51\x69\x6a\x2b\x75\x64\x7a\ -\x77\x61\x67\x52\x20\x6a\x43\x72\x4d\x52\x36\x76\x56\x4d\x75\x61\ -\x52\x5a\x33\x48\x61\x72\x4c\x77\x36\x36\x61\x72\x44\x50\x6a\x4b\ -\x31\x4f\x33\x70\x71\x32\x79\x4d\x2b\x77\x78\x6d\x69\x44\x75\x51\ -\x32\x66\x35\x42\x4e\x75\x32\x72\x35\x66\x6e\x4d\x35\x4a\x54\x74\ -\x33\x67\x55\x62\x44\x71\x50\x37\x35\x6a\x42\x39\x61\x78\x42\x55\ -\x76\x20\x2f\x49\x4f\x69\x37\x45\x77\x2b\x75\x4f\x64\x57\x4d\x6c\ -\x32\x4f\x6f\x2f\x5a\x48\x48\x43\x6d\x79\x72\x46\x44\x66\x34\x65\ -\x58\x48\x4c\x65\x58\x4d\x4b\x79\x6c\x6a\x61\x57\x55\x56\x6a\x52\ -\x6f\x44\x6b\x69\x4d\x46\x54\x66\x6b\x57\x4c\x68\x38\x31\x6c\x48\ -\x66\x75\x6e\x48\x52\x4d\x6e\x61\x69\x4b\x6f\x74\x44\x6b\x20\x39\ -\x62\x47\x36\x66\x43\x63\x4c\x4e\x32\x36\x6d\x6f\x72\x36\x4a\x76\ -\x75\x6d\x70\x54\x50\x31\x2b\x42\x54\x4d\x66\x2b\x54\x31\x6a\x69\ -\x77\x59\x63\x4d\x79\x31\x37\x31\x38\x2b\x69\x54\x56\x75\x70\x62\ -\x6d\x35\x68\x61\x46\x34\x75\x45\x30\x34\x63\x78\x70\x55\x76\x76\ -\x63\x37\x46\x49\x34\x66\x78\x37\x6c\x33\x78\x20\x71\x5a\x2b\x6a\ -\x32\x62\x62\x37\x61\x2f\x2f\x4e\x2f\x37\x33\x42\x68\x53\x4f\x48\ -\x38\x63\x36\x64\x4e\x78\x79\x7a\x74\x68\x55\x6c\x6d\x5a\x71\x57\ -\x56\x72\x37\x5a\x73\x4a\x6e\x35\x4a\x57\x57\x73\x72\x61\x6d\x6e\ -\x56\x57\x64\x41\x63\x61\x54\x41\x39\x69\x33\x38\x61\x76\x67\x51\ -\x50\x72\x6e\x76\x6c\x70\x68\x66\x20\x6c\x7a\x6b\x63\x46\x45\x57\ -\x68\x78\x52\x64\x67\x62\x65\x56\x4f\x35\x71\x2f\x66\x54\x46\x6c\ -\x74\x48\x65\x6c\x4f\x4a\x37\x4e\x57\x2f\x4d\x52\x4c\x4e\x31\x7a\ -\x42\x37\x65\x65\x4e\x6a\x38\x74\x7a\x6a\x6f\x72\x78\x36\x59\x36\ -\x61\x35\x6c\x62\x57\x37\x61\x6a\x6d\x2b\x38\x33\x6c\x37\x47\x68\ -\x73\x34\x72\x6c\x72\x20\x4a\x75\x35\x7a\x4a\x45\x55\x73\x48\x49\ -\x33\x2f\x58\x6d\x56\x76\x66\x4b\x45\x77\x61\x79\x75\x72\x57\x4c\ -\x53\x78\x6a\x4b\x32\x31\x64\x62\x77\x79\x36\x57\x70\x79\x65\x75\ -\x46\x59\x50\x35\x71\x45\x49\x69\x4b\x6c\x75\x32\x72\x77\x68\x73\ -\x4b\x4d\x48\x7a\x4c\x77\x6d\x4a\x34\x53\x75\x44\x39\x48\x73\x33\ -\x35\x2b\x20\x61\x57\x33\x62\x31\x4f\x48\x6a\x70\x2b\x30\x37\x57\ -\x56\x43\x79\x69\x62\x4c\x61\x4f\x74\x36\x38\x37\x58\x6f\x4b\x4d\ -\x6d\x4a\x4c\x47\x49\x32\x56\x69\x43\x69\x79\x65\x64\x64\x75\x56\ -\x70\x58\x76\x59\x4e\x4b\x5a\x70\x32\x4f\x4f\x30\x35\x47\x70\x78\ -\x38\x7a\x34\x4a\x45\x69\x51\x49\x45\x46\x76\x4f\x48\x37\x54\x20\ -\x61\x49\x49\x45\x43\x58\x37\x52\x4a\x49\x78\x50\x67\x67\x51\x4a\ -\x6a\x67\x73\x4a\x34\x35\x4d\x67\x51\x59\x4c\x6a\x51\x73\x4c\x34\ -\x4a\x45\x69\x51\x34\x4c\x69\x51\x4d\x44\x34\x4a\x45\x69\x51\x34\ -\x4c\x69\x53\x4d\x54\x34\x49\x45\x43\x59\x34\x4c\x43\x65\x4f\x54\ -\x49\x45\x47\x43\x34\x30\x4c\x43\x2b\x43\x52\x49\x20\x6b\x4f\x43\ -\x34\x6b\x44\x41\x2b\x43\x52\x49\x6b\x4f\x43\x34\x6b\x6a\x45\x2b\ -\x43\x42\x41\x6d\x4f\x43\x2f\x38\x50\x32\x32\x63\x47\x79\x2b\x42\ -\x2f\x69\x58\x30\x41\x41\x41\x41\x41\x53\x55\x56\x4f\x52\x4b\x35\ -\x43\x59\x49\x49\x3d\x20\x22\x20\x68\x65\x69\x67\x68\x74\x3d\x22\ -\x34\x31\x22\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x38\x37\x22\x20\ -\x79\x3d\x22\x2d\x36\x35\x35\x2e\x33\x37\x22\x20\x78\x3d\x22\x31\ -\x32\x39\x39\x2e\x37\x22\x20\x70\x72\x65\x73\x65\x72\x76\x65\x41\ -\x73\x70\x65\x63\x74\x52\x61\x74\x69\x6f\x3d\x22\x6e\x6f\x6e\x65\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\ -\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x33\x33\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\ -\x2d\x35\x39\x31\x2e\x38\x33\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x34\x37\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x35\x36\x36\x2e\x35\x39\ -\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x20\x32\x35\ -\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x33\x34\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\ -\x32\x2d\x35\x39\x31\x2e\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\ -\x38\x2e\x34\x35\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x33\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x35\x38\x2e\ -\x31\x34\x76\x33\x32\x6c\x2d\x33\x31\x2e\x35\x34\x37\x2d\x38\x2e\ -\x34\x35\x33\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x32\ -\x36\x2e\x31\x34\x20\x32\x35\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\ -\x33\x38\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x37\ -\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x39\x31\ -\x2e\x38\x33\x76\x33\x32\x6c\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x39\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x35\x39\x2e\ -\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x36\x31\x22\x20\x64\x3d\x22\x6d\x31\ -\x32\x33\x36\x2e\x36\x2d\x36\x35\x36\x2e\x32\x38\x2d\x31\x32\x2e\ -\x36\x31\x39\x20\x31\x32\x2e\x36\x31\x39\x76\x31\x36\x6c\x31\x38\ -\x2e\x39\x32\x38\x20\x35\x2e\x30\x37\x31\x38\x76\x2d\x31\x36\x6c\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x36\x33\x22\x20\x64\x3d\x22\x6d\x31\x32\ -\x34\x33\x2d\x36\x32\x32\x2e\x35\x39\x20\x31\x32\x2e\x36\x31\x39\ -\x2d\x31\x32\x2e\x36\x31\x39\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x36\x33\x38\x2e\ -\x35\x39\x20\x31\x32\x2e\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\ -\x76\x31\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x37\x22\x20\x64\ -\x3d\x22\x6d\x31\x32\x35\x35\x2e\x36\x2d\x36\x35\x31\x2e\x32\x31\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x76\x31\ -\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x32\x32\x34\x2d\x36\x32\x37\x2e\x36\x36\x20\x31\x32\x2e\ -\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\x20\x31\x38\x2e\x39\x32\ -\x38\x20\x35\x2e\x30\x37\x31\x38\x22\x2f\x3e\x0a\x20\x20\x20\x3c\ -\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x31\ -\x22\x20\x64\x3d\x22\x6d\x31\x33\x33\x38\x2e\x31\x2d\x35\x35\x39\ -\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\ -\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\ -\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\ -\x37\x33\x22\x20\x64\x3d\x22\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\ -\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\ -\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\ -\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x37\x37\x22\x20\x64\x3d\x22\x6d\x31\ -\x33\x35\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\ -\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\ -\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x31\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x36\x36\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x20\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3d\x22\ -\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\x69\x6c\x6c\x2d\x6f\x70\ -\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\x37\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\ -\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x31\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x32\x30\x22\x20\x64\x3d\x22\x6d\x31\x33\x38\x36\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x36\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x32\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x32\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x20\x66\x69\x6c\x6c\x2d\ -\x72\x75\x6c\x65\x3d\x22\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\ -\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\ -\x36\x36\x37\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\ -\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\ -\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\ -\x6c\x3d\x22\x23\x30\x30\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\ -\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x34\x34\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x38\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x38\x30\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x30\x22\x20\ -\x64\x3d\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x35\x36\x2e\x34\ -\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\ -\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\ -\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x34\x34\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x30\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x30\x22\x20\x66\x69\x6c\ -\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\ -\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x39\x34\x2e\x32\x2d\x35\x35\x30\x2e\x34\x36\ -\x20\x30\x2e\x30\x30\x31\x2d\x35\x2e\x38\x36\x36\x36\x20\x32\x2e\ -\x36\x35\x32\x31\x2d\x32\x2e\x39\x37\x30\x35\x63\x31\x2e\x34\x35\ -\x38\x37\x2d\x31\x2e\x36\x33\x33\x38\x20\x32\x2e\x36\x37\x38\x37\ -\x2d\x32\x2e\x39\x39\x38\x31\x20\x32\x2e\x37\x31\x31\x32\x2d\x33\ -\x2e\x30\x33\x31\x39\x20\x30\x2e\x30\x33\x35\x2d\x30\x2e\x30\x33\ -\x36\x38\x20\x30\x2e\x30\x35\x39\x20\x32\x2e\x31\x37\x30\x39\x20\ -\x30\x2e\x30\x35\x39\x20\x35\x2e\x35\x38\x35\x39\x76\x35\x2e\x36\ -\x34\x37\x32\x6c\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\ -\x31\x34\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\x31\x34\ -\x76\x2d\x35\x2e\x38\x36\x36\x38\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\ -\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\ -\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\ -\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ -\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x34\x38\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x39\ -\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\ -\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\ -\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x34\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x34\x30\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\ -\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\ -\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\ -\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x31\x34\x2d\x35\x36\x33\x2e\x35\ -\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x39\x30\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x37\x2e\x37\x2d\x35\ -\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\ -\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x30\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x30\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\ -\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\ -\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x30\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x31\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\ -\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x32\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x35\x32\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x36\x35\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\ -\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\ -\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\ -\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x31\x36\x22\x20\x64\x3d\x22\x6d\x31\x34\x37\x32\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x31\x38\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\ -\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\ -\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\ -\x67\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x32\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x36\x2e\x39\x2d\x35\x36\x36\ -\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\ -\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x36\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x37\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\ -\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\x2e\x31\x2d\x35\x35\x39\x2e\ -\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\ -\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\ -\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x33\ -\x30\x22\x20\x64\x3d\x22\x6d\x31\x35\x32\x31\x2e\x37\x2d\x35\x35\ -\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\ -\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\ -\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x35\ -\x32\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x35\x33\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x35\x32\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\ -\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x3c\ -\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ -\x00\x00\x4e\x4c\ -\x3c\ -\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ -\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ -\x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ -\x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ -\x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ -\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ -\x3c\x73\x76\x67\x20\x69\x64\x3d\x22\x73\x76\x67\x32\x22\x20\x78\ -\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\ -\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\x39\ -\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\x2d\x73\x79\x6e\x74\x61\ -\x78\x2d\x6e\x73\x23\x22\x20\x78\x6d\x6c\x6e\x73\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x68\x65\x69\x67\x68\x74\ -\x3d\x22\x32\x33\x2e\x39\x39\x34\x22\x20\x77\x69\x64\x74\x68\x3d\ -\x22\x32\x30\x2e\x39\x36\x31\x22\x20\x76\x65\x72\x73\x69\x6f\x6e\ -\x3d\x22\x31\x2e\x31\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\x3d\ -\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\x65\ -\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\x22\ -\x20\x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x31\x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x76\x69\x65\x77\ -\x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x30\x2e\x39\x36\x30\x37\ -\x38\x34\x20\x32\x33\x2e\x39\x39\x33\x35\x39\x31\x22\x20\x78\x6d\ -\x6c\x6e\x73\x3a\x64\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\ -\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\ -\x6e\x74\x73\x2f\x31\x2e\x31\x2f\x22\x3e\x0a\x20\x3c\x6d\x65\x74\ -\x61\x64\x61\x74\x61\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ -\x74\x61\x37\x22\x3e\x0a\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\ -\x3e\x0a\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x20\x72\x64\ -\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\ -\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\ -\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\ -\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ -\x65\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\ -\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\ -\x6c\x49\x6d\x61\x67\x65\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x64\ -\x63\x3a\x74\x69\x74\x6c\x65\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x63\ -\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x3c\x2f\x72\x64\x66\x3a\ -\x52\x44\x46\x3e\x0a\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ -\x3e\x0a\x20\x3c\x67\x20\x69\x64\x3d\x22\x6c\x61\x79\x65\x72\x31\ -\x22\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x74\x72\x61\ -\x6e\x73\x6c\x61\x74\x65\x28\x2d\x31\x34\x35\x31\x2e\x36\x20\x35\ -\x36\x36\x2e\x38\x34\x29\x22\x3e\x0a\x20\x20\x3c\x67\x20\x66\x69\ -\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\ -\x36\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x3e\ -\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x33\x36\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\ -\x2e\x33\x2d\x35\x35\x33\x2e\x32\x39\x63\x30\x2d\x34\x2e\x33\x34\ -\x33\x31\x20\x30\x2e\x30\x31\x31\x2d\x35\x2e\x34\x32\x34\x33\x20\ -\x30\x2e\x30\x36\x2d\x35\x2e\x34\x32\x34\x33\x20\x30\x2e\x30\x36\ -\x31\x20\x30\x20\x38\x2e\x33\x34\x31\x39\x20\x31\x2e\x38\x31\x33\ -\x32\x20\x38\x2e\x33\x35\x35\x39\x20\x31\x2e\x38\x32\x39\x37\x20\ -\x30\x20\x30\x20\x30\x2e\x30\x32\x34\x20\x30\x2e\x36\x32\x30\x34\ -\x33\x20\x30\x2e\x30\x34\x32\x20\x31\x2e\x33\x36\x37\x33\x6c\x30\ -\x2e\x30\x33\x34\x20\x31\x2e\x33\x35\x37\x39\x2d\x34\x2e\x32\x34\ -\x35\x38\x20\x33\x2e\x31\x34\x36\x39\x2d\x34\x2e\x32\x34\x35\x39\ -\x20\x33\x2e\x31\x34\x36\x39\x76\x2d\x35\x2e\x34\x32\x34\x33\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x35\x33\x38\x22\x20\x64\x3d\x22\x6d\x31\ -\x35\x31\x32\x2e\x38\x2d\x35\x35\x38\x2e\x36\x34\x63\x2d\x32\x2e\ -\x31\x37\x39\x34\x2d\x30\x2e\x34\x36\x37\x31\x33\x2d\x33\x2e\x39\ -\x39\x35\x32\x2d\x30\x2e\x38\x35\x36\x31\x33\x2d\x34\x2e\x30\x33\ -\x35\x2d\x30\x2e\x38\x36\x34\x35\x35\x2d\x30\x2e\x30\x33\x39\x2d\ -\x30\x2e\x30\x31\x30\x37\x20\x31\x2e\x37\x32\x39\x34\x2d\x31\x2e\ -\x33\x38\x32\x39\x20\x33\x2e\x39\x33\x31\x34\x2d\x33\x2e\x30\x35\ -\x34\x36\x20\x32\x2e\x32\x30\x32\x32\x2d\x31\x2e\x36\x37\x31\x36\ -\x20\x34\x2e\x30\x31\x31\x39\x2d\x33\x2e\x30\x33\x31\x36\x20\x34\ -\x2e\x30\x32\x31\x36\x2d\x33\x2e\x30\x32\x32\x32\x20\x30\x2e\x30\ -\x32\x31\x20\x30\x2e\x30\x31\x39\x32\x20\x30\x2e\x31\x36\x39\x31\ -\x20\x36\x2e\x33\x37\x38\x37\x20\x30\x2e\x31\x36\x39\x34\x20\x37\ -\x2e\x32\x34\x31\x31\x20\x30\x2e\x30\x30\x30\x32\x20\x30\x2e\x34\ -\x31\x38\x38\x39\x2d\x30\x2e\x30\x31\x34\x20\x30\x2e\x35\x35\x38\ -\x34\x37\x2d\x30\x2e\x30\x36\x32\x20\x30\x2e\x35\x35\x34\x36\x34\ -\x2d\x30\x2e\x30\x33\x35\x20\x30\x2d\x31\x2e\x38\x34\x35\x36\x2d\ -\x30\x2e\x33\x38\x37\x33\x31\x2d\x34\x2e\x30\x32\x35\x33\x2d\x30\ -\x2e\x38\x35\x34\x34\x33\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x30\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x35\x39\x2e\x34\x2d\x35\x34\x35\ -\x2e\x34\x33\x63\x2d\x33\x2e\x33\x32\x36\x32\x2d\x30\x2e\x39\x32\ -\x33\x32\x33\x2d\x36\x2e\x31\x37\x37\x38\x2d\x31\x2e\x37\x31\x33\ -\x33\x2d\x36\x2e\x33\x33\x36\x38\x2d\x31\x2e\x37\x35\x35\x37\x2d\ -\x30\x2e\x32\x37\x38\x31\x2d\x30\x2e\x30\x37\x34\x34\x2d\x30\x2e\ -\x31\x32\x30\x39\x2d\x30\x2e\x32\x30\x32\x37\x39\x20\x34\x2e\x30\ -\x31\x35\x31\x2d\x33\x2e\x32\x38\x38\x37\x20\x32\x2e\x33\x36\x37\ -\x36\x2d\x31\x2e\x37\x36\x36\x35\x20\x34\x2e\x33\x37\x30\x31\x2d\ -\x33\x2e\x32\x30\x35\x39\x20\x34\x2e\x34\x35\x30\x32\x2d\x33\x2e\ -\x31\x39\x38\x35\x20\x30\x2e\x30\x38\x20\x30\x2e\x30\x31\x30\x38\ -\x20\x31\x2e\x30\x33\x33\x34\x20\x30\x2e\x32\x37\x35\x34\x32\x20\ -\x32\x2e\x31\x31\x38\x38\x20\x30\x2e\x35\x39\x35\x38\x37\x20\x31\ -\x2e\x30\x38\x35\x34\x20\x30\x2e\x33\x32\x30\x35\x37\x20\x31\x2e\ -\x39\x38\x38\x39\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x32\x2e\x30\ -\x30\x37\x38\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x30\x2e\x30\x31\ -\x39\x20\x30\x20\x30\x2e\x30\x33\x35\x20\x31\x2e\x39\x36\x39\x39\ -\x20\x30\x2e\x30\x33\x35\x20\x34\x2e\x33\x37\x37\x35\x20\x30\x20\ -\x33\x2e\x34\x34\x31\x31\x2d\x30\x2e\x30\x32\x36\x20\x34\x2e\x33\ -\x37\x36\x33\x2d\x30\x2e\x31\x32\x30\x39\x20\x34\x2e\x33\x37\x31\ -\x35\x2d\x30\x2e\x30\x36\x36\x20\x30\x2d\x32\x2e\x38\x34\x32\x34\ -\x2d\x30\x2e\x37\x36\x31\x32\x37\x2d\x36\x2e\x31\x36\x38\x35\x2d\ -\x31\x2e\x36\x38\x34\x36\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x32\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\x2e\x39\x2d\x35\x34\x38\ -\x2e\x30\x39\x63\x30\x2d\x32\x2e\x31\x37\x33\x35\x20\x30\x2e\x30\ -\x32\x2d\x33\x2e\x39\x35\x31\x38\x20\x30\x2e\x30\x34\x37\x2d\x33\ -\x2e\x39\x35\x31\x38\x20\x30\x2e\x31\x30\x36\x31\x20\x30\x20\x35\ -\x2e\x32\x33\x37\x20\x31\x2e\x35\x30\x34\x31\x20\x35\x2e\x32\x38\ -\x32\x36\x20\x31\x2e\x35\x34\x38\x37\x20\x30\x2e\x30\x33\x35\x20\ -\x30\x2e\x30\x33\x35\x2d\x34\x2e\x34\x39\x35\x20\x35\x2e\x34\x34\ -\x35\x32\x2d\x35\x2e\x32\x34\x32\x20\x36\x2e\x32\x35\x39\x33\x2d\ -\x30\x2e\x30\x34\x38\x20\x30\x2e\x30\x35\x33\x2d\x30\x2e\x30\x38\ -\x38\x2d\x31\x2e\x36\x36\x39\x35\x2d\x30\x2e\x30\x38\x38\x2d\x33\ -\x2e\x38\x35\x36\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\x35\x35\x33\x2e\ -\x38\x2d\x31\x2e\x37\x38\x30\x33\x2d\x30\x2e\x35\x33\x32\x39\x76\ -\x2d\x31\x2e\x31\x37\x38\x37\x63\x30\x2d\x31\x2e\x31\x36\x31\x37\ -\x20\x30\x2d\x31\x2e\x31\x37\x38\x20\x30\x2e\x32\x30\x35\x34\x2d\ -\x31\x2e\x31\x32\x35\x32\x20\x30\x2e\x31\x31\x32\x38\x20\x30\x2e\ -\x30\x32\x39\x39\x20\x30\x2e\x39\x34\x36\x20\x30\x2e\x32\x31\x35\ -\x38\x38\x20\x31\x2e\x38\x35\x31\x36\x20\x30\x2e\x34\x31\x33\x39\ -\x31\x6c\x31\x2e\x36\x34\x36\x31\x20\x30\x2e\x33\x36\x30\x32\x39\ -\x76\x31\x2e\x33\x30\x36\x33\x63\x30\x20\x30\x2e\x37\x31\x38\x34\ -\x36\x2d\x30\x2e\x30\x33\x32\x20\x31\x2e\x33\x30\x32\x34\x2d\x30\ -\x2e\x30\x37\x32\x20\x31\x2e\x32\x39\x37\x38\x2d\x30\x2e\x30\x33\ -\x39\x20\x30\x2d\x30\x2e\x38\x37\x32\x33\x2d\x30\x2e\x32\x34\x38\ -\x33\x32\x2d\x31\x2e\x38\x35\x31\x36\x2d\x30\x2e\x35\x34\x31\x35\ -\x32\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x31\x30\x2e\x38\x2d\x35\x35\x32\x2e\x31\x38\x2d\x32\ -\x2e\x36\x38\x31\x31\x2d\x30\x2e\x37\x38\x35\x33\x34\x76\x2d\x31\ -\x2e\x36\x35\x39\x33\x2d\x31\x2e\x36\x35\x39\x33\x6c\x32\x2e\x36\ -\x31\x37\x32\x2d\x32\x2e\x38\x38\x36\x33\x63\x31\x2e\x34\x33\x39\ -\x34\x2d\x31\x2e\x35\x38\x37\x35\x20\x32\x2e\x36\x37\x37\x34\x2d\ -\x32\x2e\x39\x34\x36\x38\x20\x32\x2e\x37\x35\x30\x39\x2d\x33\x2e\ -\x30\x32\x30\x36\x20\x30\x2e\x31\x31\x36\x32\x2d\x30\x2e\x31\x31\ -\x36\x36\x34\x20\x30\x2e\x31\x33\x33\x38\x20\x30\x2e\x35\x38\x33\ -\x37\x39\x20\x30\x2e\x31\x33\x33\x38\x20\x35\x2e\x33\x33\x39\x39\ -\x20\x30\x20\x33\x2e\x30\x31\x30\x38\x20\x30\x2e\x31\x30\x30\x33\ -\x20\x35\x2e\x35\x30\x32\x34\x20\x30\x2e\x30\x36\x31\x20\x35\x2e\ -\x34\x39\x37\x36\x2d\x30\x2e\x30\x33\x39\x20\x30\x2d\x31\x2e\x34\ -\x30\x38\x2d\x30\x2e\x33\x39\x34\x36\x34\x2d\x32\x2e\x38\x38\x32\ -\x34\x2d\x30\x2e\x38\x32\x36\x35\x39\x7a\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x39\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\ -\x35\x35\x37\x2e\x31\x34\x2d\x31\x2e\x37\x31\x34\x37\x2d\x30\x2e\ -\x33\x39\x33\x38\x33\x2d\x30\x2e\x30\x35\x38\x2d\x32\x2e\x32\x32\ -\x36\x34\x63\x2d\x30\x2e\x30\x39\x36\x2d\x33\x2e\x37\x34\x33\x32\ -\x2d\x30\x2e\x32\x31\x38\x33\x2d\x35\x2e\x39\x33\x31\x39\x2d\x30\ -\x2e\x31\x31\x34\x37\x2d\x35\x2e\x39\x33\x31\x39\x20\x30\x2e\x31\ -\x33\x35\x20\x30\x20\x39\x2e\x34\x39\x39\x35\x20\x32\x2e\x32\x35\ -\x31\x39\x20\x39\x2e\x37\x30\x33\x31\x20\x32\x2e\x33\x33\x36\x37\ -\x20\x30\x2e\x31\x34\x32\x35\x20\x30\x2e\x30\x35\x39\x34\x2d\x30\ -\x2e\x32\x39\x37\x33\x20\x30\x2e\x35\x39\x35\x36\x39\x2d\x32\x2e\ -\x37\x32\x35\x32\x20\x33\x2e\x33\x32\x35\x31\x2d\x32\x2e\x33\x31\ -\x31\x39\x20\x32\x2e\x35\x39\x39\x2d\x32\x2e\x39\x34\x33\x32\x20\ -\x33\x2e\x32\x35\x37\x34\x2d\x33\x2e\x31\x33\x35\x39\x20\x33\x2e\ -\x32\x36\x39\x32\x2d\x30\x2e\x31\x33\x32\x36\x20\x30\x2e\x30\x31\ -\x30\x34\x2d\x31\x2e\x30\x31\x32\x38\x2d\x30\x2e\x31\x36\x32\x32\ -\x35\x2d\x31\x2e\x39\x35\x36\x2d\x30\x2e\x33\x37\x38\x38\x32\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x67\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\ -\x35\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x36\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x32\ -\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\ -\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\ -\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x34\x39\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x33\ -\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\ -\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x39\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x30\x2e\x38\x35\x39\x20\x33\x2e\x30\x33\x30\ -\x34\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x32\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x38\x2e\x39\x2d\ -\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\ -\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\ -\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ -\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x32\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\ -\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\ -\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x33\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\ -\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x34\x31\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x34\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\ -\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\ -\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x35\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\ -\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x37\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x36\x2e\x39\x2d\x35\x36\x36\x2e\ -\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\ -\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x38\x31\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x37\x2e\x32\x2d\x35\x35\x33\x2e\ -\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x3e\x0a\ -\x20\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x30\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x35\ -\x36\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\ -\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\ -\x37\x33\x32\x2e\x31\x2d\x35\x30\x37\x2e\x36\x34\x20\x31\x33\x38\ -\x2e\x35\x36\x2d\x38\x30\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\ -\x2d\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x2d\x31\x33\x38\x2e\x35\ -\x36\x2d\x38\x30\x76\x31\x36\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x35\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x37\x33\x32\x2e\x31\x2d\x33\x34\x37\x2e\x36\x34\x20\ -\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x38\x37\x30\x2e\x36\x2d\x32\x36\x37\x2e\x36\x34\x20\x31\x33\ -\x38\x2e\x35\x36\x2d\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x32\x36\x32\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x35\x38\x37\ -\x2e\x36\x34\x76\x31\x36\x30\x6c\x2d\x31\x33\x38\x2e\x35\x36\x20\ -\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x34\x22\x20\ -\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x34\x32\x37\x2e\x36\ -\x34\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x36\x36\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x2d\x38\x30\x20\x38\x30\ -\x20\x38\x30\x20\x38\x30\x20\x38\x30\x2d\x38\x30\x7a\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x37\x30\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x37\x32\x37\x2e\x36\x34\x76\x38\x30\x6c\x38\x30\ -\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x32\x37\x32\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x36\x34\ -\x37\x2e\x36\x34\x2d\x38\x30\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x37\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x76\x38\x30\x6c\x2d\ -\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x37\ -\x36\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x38\x30\x37\x2e\ -\x36\x34\x20\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x30\x22\x20\x64\x3d\x22\x6d\x32\x32\x35\x32\x2e\x39\ -\x2d\x39\x36\x37\x2e\x36\x34\x2d\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x76\x31\x36\x30\x6c\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x38\x32\x22\x20\x64\x3d\ -\x22\x6d\x32\x30\x38\x38\x2e\x31\x2d\x39\x30\x37\x2e\x36\x34\x2d\ -\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\ -\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x39\x32\x33\x2e\x32\x2d\x39\x36\x37\x2e\x36\x34\x76\x31\x36\x30\ -\x6c\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x32\x38\x36\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\ -\x2e\x31\x2d\x31\x30\x32\x37\x2e\x36\x76\x31\x36\x30\x6c\x2d\x31\ -\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x38\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\x2e\x31\ -\x2d\x38\x36\x37\x2e\x36\x34\x20\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x3c\x67\x20\x73\ -\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\ -\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x33\x32\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x31\x38\x38\x2e\x31\x2d\x33\x34\x31\x2e\x36\x37\x20\x31\x35\ -\x33\x2e\x33\x31\x2d\x37\x31\x2e\x34\x38\x38\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x2d\x31\x35\x33\x2e\x33\x31\ -\x20\x37\x31\x2e\x34\x38\x38\x2d\x31\x35\x33\x2e\x33\x31\x2d\x38\ -\x38\x2e\x35\x31\x32\x76\x31\x36\x30\x6c\x31\x35\x33\x2e\x33\x31\ -\x20\x38\x38\x2e\x35\x31\x32\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x39\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\x33\x31\ -\x2d\x37\x31\x2e\x34\x38\x38\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x34\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x34\x31\x33\x2e\x31\x36\x76\x31\x36\x30\x6c\x2d\ -\x31\x35\x33\x2e\x33\x31\x20\x37\x31\x2e\x34\x38\x38\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x32\x36\x22\x20\x64\x3d\x22\x6d\x31\x33\ -\x34\x31\x2e\x34\x2d\x32\x35\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\ -\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x20\x69\x64\ -\x3d\x22\x69\x6d\x61\x67\x65\x34\x33\x33\x36\x22\x20\x73\x74\x79\ -\x6c\x65\x3d\x22\x69\x6d\x61\x67\x65\x2d\x72\x65\x6e\x64\x65\x72\ -\x69\x6e\x67\x3a\x6f\x70\x74\x69\x6d\x69\x7a\x65\x53\x70\x65\x65\ -\x64\x22\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\ -\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\ -\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\ -\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x52\x38\ -\x41\x41\x41\x41\x70\x43\x41\x59\x41\x41\x41\x41\x4d\x41\x79\x31\ -\x4a\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\ -\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x48\x69\x68\x4a\x52\x45\x46\ -\x55\x20\x65\x4a\x7a\x74\x6e\x58\x64\x34\x56\x46\x58\x36\x78\x7a\ -\x2f\x54\x61\x7a\x4b\x54\x6d\x55\x6b\x6a\x6a\x59\x54\x51\x51\x69\ -\x67\x4b\x32\x43\x6c\x57\x31\x72\x35\x59\x31\x37\x4a\x69\x58\x63\ -\x74\x61\x31\x72\x61\x75\x5a\x58\x55\x74\x61\x2f\x6e\x70\x36\x75\ -\x34\x71\x72\x67\x58\x64\x74\x61\x30\x67\x43\x77\x49\x57\x20\x6d\ -\x6f\x41\x46\x6b\x43\x49\x6c\x51\x41\x67\x51\x45\x6b\x68\x49\x53\ -\x47\x2f\x54\x35\x39\x62\x66\x48\x78\x4d\x69\x4a\x59\x48\x41\x44\ -\x50\x43\x48\x38\x33\x6d\x65\x50\x44\x79\x5a\x4f\x2b\x66\x65\x62\ -\x30\x35\x35\x7a\x7a\x6e\x76\x2b\x39\x36\x44\x35\x73\x55\x58\x58\ -\x6c\x42\x4a\x6b\x43\x42\x42\x67\x6d\x4f\x4d\x20\x50\x69\x4d\x7a\ -\x34\x33\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x66\x55\x46\x2b\ -\x2f\x76\x48\x57\x6b\x43\x42\x42\x67\x6c\x38\x67\x65\x72\x66\x62\ -\x66\x62\x77\x31\x4a\x45\x69\x51\x34\x42\x65\x49\x50\x6a\x6b\x35\ -\x2b\x58\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x76\x64\x56\x71\ -\x50\x64\x34\x61\x45\x69\x52\x49\x20\x38\x41\x74\x45\x62\x7a\x41\ -\x59\x59\x72\x71\x42\x4a\x4d\x76\x38\x38\x36\x74\x76\x6d\x4c\x31\ -\x36\x50\x58\x6b\x65\x4e\x34\x4e\x7a\x4d\x68\x6d\x63\x6e\x55\x6d\ -\x2f\x6a\x48\x52\x79\x33\x43\x6b\x34\x62\x66\x45\x7a\x62\x6b\x32\ -\x4e\x44\x57\x54\x6e\x35\x42\x47\x4a\x68\x4f\x4e\x32\x7a\x34\x72\ -\x36\x52\x6e\x34\x6f\x20\x4b\x79\x66\x50\x34\x79\x4c\x4c\x6e\x55\ -\x4b\x47\x30\x30\x47\x79\x31\x52\x4b\x33\x2b\x78\x38\x75\x4e\x53\ -\x31\x74\x31\x44\x53\x33\x6b\x75\x5a\x49\x4a\x74\x32\x5a\x6a\x4d\ -\x31\x73\x4f\x6d\x35\x61\x41\x46\x5a\x73\x72\x65\x43\x37\x7a\x56\ -\x76\x4a\x38\x37\x6a\x4a\x54\x2f\x65\x51\x6b\x65\x49\x6b\x7a\x5a\ -\x47\x4d\x20\x78\x52\x68\x62\x76\x39\x6d\x66\x6f\x39\x47\x32\x4b\ -\x37\x5a\x57\x38\x4e\x58\x61\x44\x65\x53\x6e\x65\x52\x69\x51\x6d\ -\x55\x47\x4b\x33\x55\x5a\x75\x71\x6f\x73\x6b\x69\x7a\x6c\x75\x7a\ -\x7a\x68\x63\x50\x63\x65\x69\x4c\x6e\x76\x4c\x6b\x6f\x31\x6c\x7a\ -\x46\x75\x2f\x69\x56\x79\x33\x6d\x33\x34\x5a\x71\x66\x52\x78\x20\ -\x70\x35\x44\x75\x53\x4d\x4b\x54\x6c\x49\x52\x4f\x70\x34\x33\x62\ -\x63\x33\x70\x71\x57\x33\x30\x73\x4e\x32\x31\x6f\x37\x2b\x44\x78\ -\x54\x32\x61\x69\x4e\x78\x69\x35\x61\x50\x53\x4a\x58\x44\x76\x2b\ -\x4e\x45\x71\x72\x61\x79\x69\x74\x72\x6d\x58\x42\x68\x69\x33\x73\ -\x61\x6d\x70\x42\x72\x39\x57\x53\x35\x58\x49\x77\x20\x73\x45\x38\ -\x6d\x52\x54\x6d\x5a\x46\x47\x61\x6b\x34\x55\x36\x32\x59\x7a\x63\ -\x66\x6e\x77\x36\x77\x42\x31\x6c\x52\x2b\x47\x4c\x31\x65\x6c\x36\ -\x66\x75\x34\x51\x42\x57\x52\x6e\x73\x62\x47\x36\x6a\x75\x71\x6d\ -\x46\x68\x76\x59\x4f\x6a\x46\x6f\x64\x47\x63\x35\x6b\x63\x6c\x50\ -\x64\x46\x47\x61\x6d\x4d\x69\x41\x7a\x20\x67\x33\x52\x6e\x4d\x6b\ -\x6b\x57\x4d\x31\x61\x54\x45\x59\x31\x47\x45\x33\x63\x39\x6b\x69\ -\x7a\x7a\x78\x55\x38\x6c\x50\x44\x5a\x6a\x4c\x71\x30\x36\x45\x79\ -\x5a\x46\x77\x6f\x61\x4d\x78\x32\x4b\x68\x77\x4a\x4e\x43\x51\x61\ -\x71\x62\x2f\x44\x51\x50\x2b\x52\x6d\x70\x35\x48\x6c\x63\x58\x56\ -\x70\x4d\x4d\x55\x34\x65\x20\x50\x52\x45\x57\x52\x4e\x35\x64\x2b\ -\x44\x31\x66\x72\x39\x76\x49\x4f\x53\x4f\x4b\x61\x51\x38\x4c\x7a\ -\x46\x68\x56\x51\x6c\x31\x72\x47\x38\x30\x64\x50\x6d\x77\x57\x45\ -\x2b\x6e\x4a\x79\x57\x53\x37\x6e\x66\x54\x50\x54\x4b\x4d\x67\x50\ -\x59\x32\x4d\x46\x41\x63\x4f\x71\x2b\x57\x34\x47\x38\x77\x39\x32\ -\x71\x66\x2f\x20\x2b\x42\x4e\x31\x51\x5a\x47\x2b\x41\x34\x70\x70\ -\x57\x37\x6d\x56\x6b\x4b\x38\x64\x67\x79\x70\x69\x30\x65\x6e\x49\ -\x64\x6a\x6b\x59\x6d\x70\x31\x4a\x75\x6a\x4f\x4a\x51\x64\x6c\x39\ -\x4b\x45\x68\x50\x78\x57\x59\x79\x34\x6b\x71\x79\x48\x7a\x55\x39\ -\x30\x35\x61\x76\x78\x6d\x34\x78\x38\x2b\x75\x54\x52\x78\x37\x58\ -\x20\x75\x76\x53\x48\x77\x72\x7a\x32\x78\x55\x4c\x65\x58\x4c\x79\ -\x55\x6b\x58\x6e\x5a\x6a\x4f\x78\x66\x79\x4a\x71\x71\x57\x6d\x61\ -\x76\x32\x55\x42\x64\x61\x7a\x74\x68\x51\x63\x52\x74\x74\x35\x48\ -\x68\x54\x43\x59\x2f\x33\x55\x4e\x42\x65\x69\x72\x35\x61\x61\x6d\ -\x34\x6b\x71\x79\x6b\x4f\x5a\x4c\x6a\x31\x76\x38\x31\x20\x33\x6f\ -\x37\x32\x49\x38\x72\x7a\x57\x56\x4f\x78\x6b\x38\x63\x2b\x2b\x5a\ -\x79\x37\x4c\x6a\x79\x58\x38\x30\x63\x4e\x5a\x2b\x58\x57\x37\x56\ -\x77\x77\x61\x73\x51\x2b\x33\x31\x45\x55\x68\x59\x5a\x32\x4c\x39\ -\x56\x4e\x4c\x57\x79\x70\x32\x63\x32\x6d\x71\x68\x6f\x32\x56\x64\ -\x65\x77\x73\x36\x47\x52\x6d\x58\x2b\x38\x20\x69\x32\x79\x33\x36\ -\x37\x43\x65\x47\x61\x2f\x5a\x4d\x52\x67\x52\x65\x47\x72\x71\x62\ -\x4e\x70\x43\x59\x5a\x36\x2b\x35\x6a\x4c\x4b\x61\x6e\x59\x7a\x38\ -\x64\x52\x52\x51\x4e\x51\x6f\x4e\x58\x74\x39\x31\x4c\x61\x30\x55\ -\x64\x58\x59\x7a\x4c\x62\x61\x4f\x72\x62\x57\x31\x72\x4f\x37\x74\ -\x51\x31\x76\x4d\x45\x69\x53\x20\x32\x63\x53\x37\x64\x30\x34\x69\ -\x78\x57\x36\x4c\x53\x63\x50\x65\x64\x41\x53\x43\x50\x50\x48\x70\ -\x4c\x4c\x37\x61\x55\x55\x39\x79\x30\x51\x68\x55\x67\x78\x46\x52\ -\x6c\x6f\x68\x49\x49\x75\x46\x51\x6b\x45\x67\x77\x67\x42\x41\x4b\ -\x51\x43\x67\x45\x34\x53\x41\x47\x55\x63\x42\x6a\x30\x4a\x4a\x6d\ -\x4d\x6e\x4a\x79\x20\x59\x56\x39\x65\x76\x50\x35\x79\x39\x44\x70\ -\x64\x33\x50\x54\x55\x74\x58\x62\x77\x38\x49\x66\x54\x36\x4e\x65\ -\x6e\x44\x35\x65\x65\x63\x69\x49\x66\x4c\x56\x37\x4b\x6c\x48\x74\ -\x76\x36\x37\x6f\x75\x53\x68\x49\x4e\x37\x56\x37\x71\x32\x74\x71\ -\x70\x62\x6d\x70\x68\x57\x32\x30\x64\x46\x58\x57\x4e\x56\x4e\x51\ -\x33\x20\x30\x4e\x6a\x65\x7a\x76\x38\x65\x2f\x6a\x33\x5a\x37\x70\ -\x54\x44\x65\x6d\x61\x38\x32\x6e\x5a\x76\x37\x62\x38\x39\x38\x33\ -\x52\x75\x66\x6d\x38\x6d\x76\x37\x72\x73\x52\x76\x78\x43\x47\x48\ -\x38\x6b\x54\x48\x76\x41\x52\x33\x4e\x62\x43\x32\x30\x64\x72\x62\ -\x53\x33\x74\x2b\x4a\x72\x62\x79\x58\x6b\x62\x55\x63\x4a\x20\x42\ -\x55\x6a\x58\x4b\x73\x7a\x37\x38\x77\x50\x30\x54\x66\x50\x45\x70\ -\x4b\x45\x6e\x50\x54\x65\x64\x4f\x35\x62\x5a\x4b\x39\x62\x77\x78\ -\x4e\x57\x2f\x37\x72\x72\x65\x55\x31\x33\x75\x61\x47\x69\x6b\x76\ -\x71\x33\x74\x69\x4f\x72\x79\x59\x47\x79\x74\x72\x65\x50\x75\x39\ -\x7a\x35\x6c\x68\x32\x4c\x45\x31\x69\x65\x58\x20\x6b\x31\x51\x66\ -\x55\x78\x2b\x2b\x71\x2b\x75\x36\x71\x71\x70\x34\x51\x32\x45\x61\ -\x32\x74\x71\x70\x61\x32\x32\x6e\x6f\x72\x36\x52\x37\x58\x55\x4e\ -\x6c\x4f\x32\x71\x5a\x58\x46\x4a\x4b\x51\x75\x66\x65\x6f\x6a\x42\ -\x4f\x5a\x6d\x48\x39\x63\x79\x34\x72\x58\x77\x6b\x57\x65\x59\x2f\ -\x53\x35\x59\x78\x61\x33\x55\x4a\x20\x37\x39\x33\x33\x4f\x77\x5a\ -\x6c\x5a\x37\x4b\x39\x72\x6f\x46\x2f\x66\x2f\x50\x39\x41\x63\x5a\ -\x48\x71\x39\x57\x53\x36\x58\x4b\x53\x36\x58\x4a\x79\x38\x73\x42\ -\x2b\x68\x45\x57\x52\x33\x37\x30\x2b\x68\x52\x56\x62\x79\x6d\x6e\ -\x32\x2b\x67\x2f\x62\x2b\x4d\x53\x44\x44\x56\x55\x31\x50\x50\x4c\ -\x52\x64\x4b\x34\x2f\x20\x63\x77\x79\x33\x54\x54\x69\x54\x6e\x59\ -\x33\x4e\x66\x4c\x78\x6b\x61\x5a\x66\x78\x30\x57\x6d\x31\x70\x44\ -\x73\x64\x70\x44\x73\x64\x6e\x4e\x69\x76\x4c\x78\x42\x74\x45\x45\ -\x56\x56\x2b\x64\x76\x6e\x58\x2f\x4f\x6e\x2f\x30\x7a\x46\x47\x77\ -\x7a\x46\x78\x66\x69\x6f\x71\x73\x71\x79\x73\x75\x33\x38\x34\x65\ -\x4f\x5a\x20\x6d\x50\x4f\x48\x4d\x50\x79\x73\x55\x55\x69\x4b\x67\ -\x69\x68\x4c\x68\x43\x57\x52\x6b\x43\x67\x51\x4e\x4a\x6f\x49\x57\ -\x6d\x7a\x34\x68\x54\x42\x68\x55\x55\x41\x46\x52\x46\x57\x6c\x54\ -\x6c\x57\x70\x4b\x79\x38\x6a\x73\x4b\x47\x4d\x73\x43\x42\x69\x74\ -\x38\x52\x75\x66\x46\x52\x56\x5a\x57\x46\x4a\x4b\x53\x2f\x4e\x20\ -\x6d\x73\x64\x54\x31\x31\x7a\x4f\x42\x61\x4f\x47\x30\x39\x54\x68\ -\x34\x36\x6f\x78\x70\x2b\x7a\x7a\x50\x59\x4e\x65\x54\x37\x62\x48\ -\x52\x62\x62\x48\x78\x65\x6a\x2b\x42\x51\x41\x45\x49\x78\x47\x75\ -\x65\x58\x6b\x79\x33\x35\x61\x56\x45\x34\x78\x45\x59\x74\x59\x53\ -\x44\x2b\x30\x37\x47\x35\x74\x52\x46\x42\x6b\x56\x20\x46\x55\x56\ -\x52\x6b\x42\x55\x46\x74\x46\x71\x4d\x4e\x6a\x73\x57\x76\x51\x37\ -\x4a\x5a\x6b\x64\x78\x70\x79\x4b\x48\x41\x67\x52\x4b\x53\x39\x6a\ -\x64\x32\x6b\x78\x45\x46\x49\x2b\x61\x6e\x76\x5a\x41\x73\x4b\x74\ -\x50\x37\x61\x47\x37\x75\x74\x77\x7a\x54\x6c\x61\x56\x56\x38\x61\ -\x74\x4c\x6b\x56\x4a\x34\x73\x4e\x76\x20\x66\x2b\x53\x76\x58\x79\ -\x79\x69\x33\x2b\x69\x78\x6a\x4d\x7a\x75\x53\x33\x74\x7a\x41\x30\ -\x70\x7a\x78\x7a\x37\x66\x30\x32\x67\x30\x4f\x4b\x77\x57\x48\x46\ -\x59\x4c\x41\x37\x49\x79\x47\x54\x64\x30\x4d\x43\x46\x42\x34\x4a\ -\x5a\x2f\x76\x49\x74\x4f\x70\x30\x4e\x52\x34\x35\x65\x54\x66\x46\ -\x6a\x47\x70\x38\x58\x6e\x20\x35\x36\x6c\x70\x73\x7a\x47\x62\x7a\ -\x4d\x78\x35\x34\x67\x45\x63\x6e\x66\x36\x63\x62\x4c\x65\x4c\x4a\ -\x36\x36\x2b\x39\x4b\x42\x6c\x4a\x56\x6e\x6d\x6d\x55\x38\x2f\x52\ -\x36\x50\x52\x4d\x50\x48\x55\x55\x53\x6a\x4b\x73\x55\x32\x73\x46\ -\x69\x57\x5a\x44\x37\x35\x62\x7a\x68\x65\x72\x53\x33\x6a\x39\x39\ -\x68\x73\x5a\x20\x55\x5a\x43\x48\x52\x71\x4f\x68\x6a\x38\x76\x4a\ -\x30\x39\x64\x64\x66\x73\x6a\x79\x55\x2b\x5a\x2f\x79\x2b\x77\x56\ -\x61\x7a\x68\x6a\x79\x45\x42\x30\x63\x56\x68\x6c\x42\x4d\x49\x52\ -\x58\x76\x74\x69\x49\x54\x4d\x32\x56\x54\x4c\x69\x72\x49\x6b\x6b\ -\x70\x62\x69\x52\x46\x49\x58\x49\x48\x71\x4d\x6a\x52\x4e\x42\x72\ -\x20\x74\x57\x6a\x51\x6f\x4b\x6f\x67\x4b\x54\x4b\x53\x4c\x43\x4d\ -\x71\x4d\x71\x67\x71\x6d\x71\x6f\x4b\x72\x69\x6b\x71\x59\x46\x76\ -\x4e\x37\x72\x6a\x73\x7a\x2f\x32\x68\x4d\x4b\x2f\x4d\x6d\x55\x39\ -\x46\x59\x77\x76\x2f\x65\x2f\x51\x2b\x63\x6a\x78\x75\x4e\x42\x6f\ -\x4e\x49\x55\x46\x67\x35\x64\x62\x74\x6e\x48\x66\x43\x20\x30\x42\ -\x37\x4c\x43\x70\x4c\x45\x2f\x56\x4d\x2b\x59\x56\x47\x44\x46\x36\ -\x50\x4c\x67\x2f\x6b\x6f\x62\x51\x56\x37\x6f\x69\x66\x74\x42\x70\ -\x30\x4f\x55\x52\x4a\x6f\x44\x77\x57\x6a\x64\x53\x70\x47\x43\x49\ -\x6b\x69\x59\x55\x6b\x6b\x49\x6b\x6c\x45\x4f\x6c\x65\x58\x6b\x63\ -\x70\x74\x59\x44\x53\x69\x53\x58\x62\x45\x20\x52\x58\x74\x50\x65\ -\x6c\x70\x38\x66\x6a\x35\x61\x73\x76\x53\x41\x53\x58\x70\x76\x39\ -\x68\x34\x6e\x34\x34\x63\x4f\x6a\x6f\x75\x65\x58\x63\x32\x74\x50\ -\x50\x72\x4a\x54\x4d\x70\x38\x43\x68\x4f\x75\x75\x67\x57\x72\x4c\ -\x51\x6c\x5a\x55\x64\x41\x47\x41\x38\x69\x48\x47\x49\x65\x69\x4a\ -\x50\x48\x59\x68\x35\x2b\x52\x20\x35\x6b\x78\x6d\x7a\x4a\x42\x42\ -\x63\x66\x56\x50\x39\x62\x72\x58\x62\x71\x6d\x70\x34\x39\x72\x58\ -\x33\x6d\x46\x4d\x63\x52\x47\x54\x37\x35\x6a\x55\x5a\x58\x67\x41\ -\x4f\x6f\x4a\x42\x6e\x70\x38\x2b\x35\x36\x44\x6c\x2f\x7a\x56\x33\ -\x45\x65\x73\x71\x64\x2f\x4c\x47\x48\x54\x64\x69\x4d\x75\x68\x52\ -\x56\x4f\x58\x49\x20\x56\x52\x38\x6d\x37\x59\x45\x67\x74\x2f\x2f\ -\x72\x41\x37\x62\x58\x4e\x7a\x50\x6a\x73\x54\x39\x77\x51\x72\x2b\ -\x2b\x58\x66\x76\x57\x56\x70\x2b\x66\x70\x7a\x2f\x39\x2f\x4b\x44\ -\x6c\x70\x79\x39\x64\x79\x5a\x51\x46\x53\x2f\x6a\x30\x6a\x33\x65\ -\x54\x5a\x44\x47\x6a\x6a\x58\x48\x50\x75\x37\x32\x75\x67\x63\x74\ -\x66\x20\x65\x59\x76\x76\x57\x68\x55\x75\x75\x50\x77\x6d\x42\x76\ -\x59\x74\x4a\x44\x50\x5a\x69\x64\x74\x71\x4a\x38\x6c\x6b\x78\x6d\ -\x6f\x77\x59\x74\x49\x62\x4d\x4f\x6a\x30\x36\x4c\x56\x61\x64\x46\ -\x6f\x4e\x57\x6f\x33\x6d\x35\x37\x31\x32\x54\x54\x55\x54\x30\x6c\ -\x4e\x34\x2b\x36\x36\x62\x55\x52\x57\x56\x57\x48\x66\x67\x20\x4f\ -\x78\x71\x61\x2b\x4d\x31\x72\x37\x2b\x42\x78\x4f\x70\x6e\x36\x38\ -\x4f\x2f\x4a\x54\x66\x56\x30\x50\x55\x74\x57\x46\x42\x72\x62\x76\ -\x51\x63\x74\x2f\x2b\x4c\x30\x4c\x2f\x69\x73\x64\x41\x63\x70\x51\ -\x34\x5a\x6a\x30\x47\x72\x52\x61\x75\x50\x6e\x72\x44\x77\x55\x42\ -\x39\x4e\x75\x30\x4f\x75\x51\x4a\x49\x6d\x32\x20\x6b\x4a\x2b\x4f\ -\x55\x41\x42\x76\x4f\x49\x78\x66\x43\x42\x4d\x51\x49\x70\x32\x47\ -\x53\x43\x43\x77\x63\x7a\x74\x53\x4f\x41\x78\x35\x42\x61\x41\x6f\ -\x4d\x57\x73\x2f\x6d\x4a\x35\x73\x74\x34\x74\x6e\x72\x72\x76\x69\ -\x6f\x4f\x58\x33\x48\x69\x63\x61\x4e\x44\x48\x72\x6d\x62\x64\x32\ -\x49\x78\x65\x2b\x4e\x42\x6d\x76\x20\x75\x34\x41\x4c\x4a\x31\x35\ -\x50\x51\x55\x59\x4f\x36\x55\x6b\x4f\x6e\x42\x59\x72\x46\x71\x50\ -\x70\x6b\x43\x75\x5a\x6c\x32\x5a\x38\x53\x58\x31\x62\x42\x79\x39\ -\x4d\x75\x68\x70\x4a\x6c\x6a\x45\x61\x34\x72\x65\x39\x37\x39\x58\ -\x4b\x35\x39\x4d\x66\x56\x76\x4c\x43\x7a\x4b\x2f\x35\x35\x4b\x48\ -\x66\x63\x2b\x71\x67\x20\x77\x67\x4d\x63\x54\x6c\x61\x54\x69\x5a\ -\x50\x36\x39\x2b\x75\x32\x72\x4b\x71\x71\x7a\x46\x69\x2b\x6d\x6b\ -\x2b\x2f\x57\x38\x36\x58\x54\x7a\x37\x55\x4f\x58\x69\x31\x30\x53\ -\x58\x77\x4d\x65\x43\x62\x6b\x6c\x49\x65\x2f\x76\x42\x2f\x50\x48\ -\x7a\x35\x52\x64\x78\x32\x33\x76\x67\x44\x47\x74\x4e\x6d\x4e\x6a\ -\x4e\x2b\x20\x36\x4f\x42\x75\x79\x36\x71\x71\x79\x74\x77\x31\x4a\ -\x54\x77\x37\x62\x52\x5a\x7a\x6e\x6e\x69\x41\x33\x46\x51\x33\x69\ -\x71\x4b\x69\x30\x78\x37\x35\x63\x48\x2f\x39\x71\x30\x57\x38\x4e\ -\x75\x38\x37\x52\x70\x30\x33\x6b\x62\x7a\x63\x41\x76\x52\x36\x41\ -\x37\x4b\x69\x49\x4d\x6b\x79\x67\x69\x77\x69\x79\x4e\x4c\x50\x20\ -\x50\x35\x4b\x30\x7a\x2b\x2b\x53\x4c\x45\x4e\x64\x44\x65\x4f\x53\ -\x6a\x45\x7a\x37\x34\x39\x33\x59\x7a\x4e\x48\x4f\x6f\x39\x55\x63\ -\x65\x51\x65\x64\x2b\x73\x4e\x4b\x6e\x70\x6f\x32\x68\x7a\x66\x75\ -\x6d\x4d\x54\x45\x55\x30\x63\x64\x30\x4c\x59\x5a\x4b\x51\x36\x75\ -\x48\x58\x39\x61\x74\x32\x56\x56\x56\x65\x58\x39\x20\x68\x64\x2f\ -\x78\x32\x70\x4b\x56\x35\x4a\x78\x32\x4a\x6c\x35\x52\x51\x4b\x38\ -\x42\x58\x51\x78\x36\x44\x6f\x65\x70\x50\x36\x7a\x6b\x72\x7a\x4f\ -\x2f\x5a\x73\x6f\x39\x74\x33\x48\x32\x38\x4b\x49\x44\x74\x42\x74\ -\x30\x4f\x6d\x52\x5a\x6f\x69\x58\x67\x52\x35\x42\x2b\x33\x73\x6f\ -\x47\x68\x41\x68\x42\x49\x59\x4a\x33\x20\x31\x77\x34\x69\x4c\x59\ -\x30\x77\x73\x42\x69\x30\x57\x72\x53\x6f\x78\x44\x4b\x76\x48\x45\ -\x70\x50\x55\x34\x65\x58\x68\x39\x37\x2f\x4c\x37\x4f\x66\x65\x4f\ -\x43\x41\x73\x74\x32\x4e\x45\x31\x6d\x52\x59\x36\x72\x4c\x76\x30\ -\x79\x64\x7a\x56\x76\x66\x72\x75\x44\x30\x38\x36\x38\x67\x4e\x79\ -\x63\x66\x57\x56\x55\x4a\x20\x43\x68\x46\x6b\x56\x53\x45\x6b\x43\ -\x6b\x52\x6b\x43\x58\x6f\x59\x68\x34\x71\x71\x38\x75\x36\x38\x78\ -\x58\x79\x2f\x61\x51\x73\x7a\x48\x2f\x38\x44\x46\x71\x4d\x52\x57\ -\x5a\x46\x69\x36\x6d\x76\x37\x30\x79\x76\x6a\x38\x2f\x37\x69\x70\ -\x65\x53\x6d\x65\x6e\x6a\x77\x76\x55\x39\x77\x32\x71\x30\x55\x35\ -\x57\x51\x78\x20\x75\x6e\x38\x42\x77\x77\x76\x79\x79\x48\x41\x36\ -\x4d\x42\x6b\x4d\x36\x48\x71\x77\x30\x45\x73\x32\x62\x4f\x62\x35\ -\x7a\x32\x59\x7a\x36\x34\x6e\x37\x75\x79\x49\x4a\x4f\x71\x33\x32\ -\x6b\x4d\x75\x39\x65\x50\x48\x43\x72\x50\x6e\x6f\x55\x6a\x4c\x34\ -\x35\x2f\x79\x6c\x76\x4c\x39\x6f\x47\x63\x50\x79\x2b\x6c\x43\x63\ -\x20\x6d\x38\x30\x70\x41\x77\x76\x4a\x54\x58\x56\x68\x4e\x42\x69\ -\x49\x69\x46\x4c\x33\x32\x6a\x65\x57\x38\x61\x63\x50\x70\x76\x48\ -\x5a\x49\x2f\x65\x53\x6e\x35\x45\x47\x52\x46\x63\x43\x50\x66\x32\ -\x74\x76\x65\x47\x2f\x50\x36\x79\x6b\x4b\x43\x75\x64\x48\x61\x73\ -\x57\x73\x32\x50\x44\x4b\x71\x77\x4f\x4e\x36\x36\x30\x20\x50\x74\ -\x68\x53\x58\x47\x41\x77\x49\x41\x42\x42\x49\x54\x70\x41\x39\x6a\ -\x68\x4a\x2f\x5a\x45\x49\x51\x55\x46\x41\x61\x61\x78\x6a\x75\x42\ -\x70\x68\x2b\x70\x38\x65\x49\x64\x6c\x71\x51\x5a\x51\x6b\x64\x44\ -\x6f\x74\x32\x68\x69\x4d\x34\x62\x2b\x58\x4c\x4f\x4f\x30\x77\x66\ -\x33\x35\x2b\x2b\x78\x35\x76\x44\x70\x72\x20\x4c\x6f\x56\x39\x30\ -\x68\x6d\x57\x6c\x38\x50\x4a\x41\x77\x76\x70\x6d\x35\x35\x4b\x57\ -\x42\x42\x34\x2f\x72\x4d\x35\x66\x50\x48\x6b\x67\x77\x65\x55\x6e\ -\x62\x31\x69\x44\x59\x2f\x2f\x62\x79\x35\x44\x78\x31\x2b\x41\x58\ -\x31\x56\x51\x68\x41\x68\x36\x51\x4b\x65\x4c\x66\x7a\x53\x77\x4f\ -\x39\x35\x62\x76\x49\x79\x38\x20\x56\x41\x39\x2f\x2f\x6e\x67\x36\ -\x66\x35\x74\x31\x59\x4c\x2f\x55\x36\x62\x51\x6f\x73\x6b\x52\x4c\ -\x77\x49\x65\x6f\x79\x46\x45\x48\x76\x74\x68\x70\x67\x42\x70\x32\ -\x45\x36\x36\x70\x67\x73\x48\x46\x30\x4c\x6d\x4e\x6a\x72\x62\x71\ -\x6b\x57\x73\x2f\x6c\x42\x36\x72\x32\x63\x52\x5a\x77\x34\x71\x36\ -\x4c\x64\x76\x64\x20\x4f\x4a\x46\x6b\x4a\x61\x61\x36\x2f\x47\x72\ -\x74\x52\x69\x77\x70\x48\x74\x59\x75\x2f\x59\x62\x31\x47\x67\x33\ -\x4a\x44\x69\x64\x4f\x54\x7a\x72\x4a\x37\x6a\x52\x4d\x53\x51\x36\ -\x38\x76\x67\x34\x63\x33\x52\x67\x66\x56\x56\x58\x35\x33\x39\x4b\ -\x56\x66\x4c\x68\x6b\x4b\x56\x2f\x38\x2b\x63\x47\x75\x79\x4c\x51\ -\x6b\x20\x78\x7a\x62\x78\x37\x6b\x2b\x76\x6a\x49\x38\x6e\x32\x63\ -\x37\x6b\x4f\x32\x38\x6d\x49\x38\x58\x42\x31\x74\x6f\x36\x64\x6a\ -\x59\x30\x38\x58\x33\x70\x56\x6a\x37\x35\x64\x6a\x6e\x56\x54\x53\ -\x32\x34\x6b\x32\x78\x73\x32\x31\x31\x50\x70\x73\x76\x4a\x36\x50\ -\x34\x46\x39\x45\x33\x7a\x6f\x4e\x56\x71\x32\x56\x53\x31\x20\x69\ -\x2f\x75\x6e\x66\x4d\x7a\x37\x39\x2f\x32\x4f\x33\x4e\x53\x66\x49\ -\x77\x68\x61\x72\x65\x61\x59\x2b\x58\x7a\x73\x56\x67\x74\x44\x7a\ -\x37\x69\x45\x56\x4a\x63\x48\x76\x39\x39\x4c\x59\x31\x4d\x39\x30\ -\x79\x71\x71\x2b\x4d\x63\x50\x4d\x78\x42\x38\x62\x61\x53\x5a\x64\ -\x54\x53\x30\x64\x57\x44\x55\x36\x78\x69\x61\x20\x6c\x38\x50\x6f\ -\x41\x66\x32\x77\x6d\x6f\x79\x73\x72\x64\x6a\x4a\x41\x31\x4d\x2b\ -\x35\x72\x31\x37\x62\x6d\x56\x51\x39\x73\x2f\x65\x66\x55\x57\x56\ -\x59\x39\x70\x32\x5a\x58\x74\x63\x76\x48\x33\x33\x4c\x58\x69\x53\ -\x6b\x39\x6a\x52\x30\x45\x54\x35\x37\x6e\x70\x57\x62\x61\x74\x67\ -\x30\x2b\x59\x79\x4e\x75\x78\x75\x20\x77\x71\x74\x6f\x4d\x44\x69\ -\x63\x61\x4f\x78\x4a\x53\x46\x59\x62\x49\x5a\x32\x57\x69\x43\x53\ -\x68\x74\x44\x5a\x54\x47\x47\x68\x6e\x78\x6c\x4d\x50\x6b\x75\x70\ -\x49\x41\x6b\x43\x51\x6f\x6a\x4e\x6a\x4c\x48\x70\x63\x53\x54\x5a\ -\x65\x76\x66\x56\x36\x73\x74\x77\x70\x31\x4c\x65\x31\x55\x31\x48\ -\x58\x79\x4c\x72\x4b\x20\x4b\x74\x36\x5a\x76\x35\x68\x74\x74\x58\ -\x57\x45\x52\x59\x6d\x77\x49\x50\x44\x50\x4c\x2b\x5a\x54\x6e\x4a\ -\x66\x44\x4b\x51\x50\x37\x59\x54\x57\x5a\x2b\x48\x46\x4c\x4f\x66\ -\x66\x2b\x5a\x7a\x6f\x6a\x7a\x72\x6f\x49\x32\x57\x7a\x47\x36\x2f\ -\x63\x68\x4b\x51\x70\x36\x72\x53\x59\x6d\x34\x33\x77\x34\x65\x4a\ -\x4a\x74\x20\x76\x48\x6e\x58\x4c\x61\x51\x37\x6b\x37\x76\x76\x6c\ -\x38\x6c\x32\x6d\x74\x76\x61\x43\x46\x5a\x75\x51\x35\x4f\x55\x6a\ -\x47\x51\x77\x45\x4a\x45\x6b\x77\x6d\x30\x74\x53\x4a\x58\x6c\x4d\ -\x4c\x41\x49\x39\x44\x2f\x37\x4d\x48\x51\x51\x30\x38\x72\x6e\x55\ -\x48\x70\x53\x48\x55\x6e\x6b\x70\x58\x6d\x59\x39\x73\x4f\x4b\x20\ -\x58\x6f\x30\x54\x4a\x63\x61\x4a\x7a\x6d\x77\x30\x34\x4f\x34\x2f\ -\x46\x49\x63\x6e\x44\x56\x55\x55\x69\x50\x68\x39\x74\x4c\x61\x31\ -\x55\x4c\x31\x70\x4c\x53\x46\x66\x4f\x33\x49\x34\x6a\x45\x73\x48\ -\x7a\x30\x32\x62\x78\x61\x6a\x43\x41\x6b\x37\x6f\x6c\x30\x65\x61\ -\x49\x35\x6b\x6c\x47\x38\x74\x34\x61\x63\x61\x58\x20\x66\x50\x62\ -\x49\x50\x66\x75\x6b\x48\x73\x51\x36\x38\x65\x35\x50\x72\x34\x79\ -\x50\x32\x57\x41\x6b\x4a\x41\x69\x59\x44\x41\x61\x47\x39\x63\x31\ -\x6c\x57\x4e\x39\x63\x4c\x6a\x6c\x35\x4a\x47\x72\x6e\x66\x72\x47\ -\x71\x71\x5a\x6c\x50\x76\x6c\x33\x4f\x75\x6f\x6f\x71\x70\x69\x7a\ -\x34\x6c\x6a\x61\x66\x48\x34\x38\x6a\x20\x6d\x5a\x72\x6d\x56\x74\ -\x36\x34\x34\x34\x59\x44\x50\x50\x77\x36\x72\x52\x62\x35\x47\x50\ -\x6c\x38\x7a\x41\x59\x6a\x76\x6c\x41\x41\x55\x38\x53\x4f\x78\x6d\ -\x44\x45\x6d\x5a\x47\x46\x79\x5a\x31\x4b\x35\x71\x42\x68\x42\x49\ -\x51\x77\x37\x58\x34\x76\x32\x6f\x71\x74\x2f\x47\x56\x35\x4b\x66\ -\x34\x76\x6c\x79\x44\x37\x20\x66\x65\x51\x37\x37\x49\x69\x52\x43\ -\x42\x2f\x38\x34\x58\x5a\x47\x39\x53\x2f\x59\x5a\x2f\x6b\x73\x53\ -\x72\x45\x31\x67\x4e\x31\x73\x78\x42\x73\x4d\x6b\x5a\x66\x6d\x6f\ -\x54\x67\x76\x6d\x2b\x4b\x38\x62\x48\x35\x39\x79\x73\x69\x75\x36\ -\x36\x75\x32\x56\x66\x44\x45\x52\x39\x4d\x5a\x30\x7a\x2b\x44\x46\ -\x56\x75\x33\x20\x55\x39\x48\x63\x79\x67\x35\x2f\x69\x41\x77\x64\ -\x7a\x48\x72\x71\x49\x66\x70\x31\x72\x73\x43\x69\x57\x69\x54\x30\ -\x75\x74\x68\x38\x4c\x43\x61\x39\x67\x62\x41\x67\x6f\x74\x4e\x71\ -\x79\x58\x4b\x37\x79\x48\x4b\x37\x47\x46\x73\x38\x71\x4b\x74\x74\ -\x61\x31\x76\x62\x75\x50\x72\x46\x31\x39\x46\x71\x4e\x48\x79\x34\ -\x20\x36\x41\x63\x65\x2f\x57\x42\x71\x39\x50\x4e\x32\x50\x36\x4d\ -\x6e\x58\x49\x48\x4a\x36\x61\x4c\x4a\x37\x30\x56\x53\x5a\x41\x52\ -\x5a\x77\x6f\x4a\x36\x7a\x49\x7a\x50\x48\x75\x30\x39\x39\x63\x75\ -\x64\x6a\x63\x32\x63\x39\x71\x66\x6e\x61\x47\x79\x6f\x52\x61\x6e\ -\x59\x41\x70\x49\x59\x4e\x54\x61\x69\x43\x50\x30\x48\x20\x67\x33\ -\x6e\x66\x5a\x46\x4b\x39\x52\x68\x50\x54\x4e\x75\x64\x51\x65\x6a\ -\x5a\x56\x31\x58\x44\x72\x36\x2b\x2b\x53\x37\x6e\x54\x30\x61\x70\ -\x7a\x49\x73\x68\x78\x54\x58\x56\x70\x4e\x42\x6e\x62\x35\x4f\x67\ -\x67\x61\x6a\x57\x69\x31\x57\x72\x51\x47\x41\x32\x70\x61\x42\x71\ -\x62\x55\x4e\x48\x53\x79\x51\x74\x6a\x58\x20\x67\x61\x74\x32\x4f\ -\x33\x31\x63\x4b\x55\x78\x66\x74\x70\x4b\x2f\x66\x6a\x59\x4c\x58\ -\x79\x68\x4d\x59\x34\x65\x58\x75\x58\x39\x35\x6d\x48\x36\x5a\x36\ -\x66\x76\x71\x55\x57\x4c\x54\x73\x7a\x2b\x39\x4d\x7a\x35\x36\x50\ -\x57\x48\x68\x77\x42\x44\x6b\x6e\x6b\x47\x5a\x6c\x2b\x70\x68\x79\ -\x59\x62\x4e\x66\x50\x37\x34\x20\x2f\x64\x6a\x4e\x4a\x6a\x6f\x43\ -\x51\x61\x71\x62\x57\x72\x6a\x37\x72\x51\x38\x59\x57\x7a\x7a\x34\ -\x67\x4c\x32\x76\x54\x71\x75\x4e\x61\x38\x6a\x75\x59\x46\x67\x4e\ -\x4f\x72\x7a\x42\x41\x49\x5a\x77\x45\x41\x30\x67\x4b\x51\x71\x43\ -\x4c\x42\x45\x53\x42\x55\x4b\x69\x69\x43\x44\x4c\x74\x4f\x34\x73\ -\x78\x33\x58\x79\x20\x57\x4b\x53\x4d\x50\x76\x6a\x44\x49\x63\x71\ -\x46\x43\x49\x57\x37\x4b\x37\x73\x69\x59\x6e\x75\x6a\x4b\x47\x70\ -\x4d\x30\x61\x55\x6b\x69\x78\x6c\x66\x4b\x4c\x54\x50\x5a\x33\x73\ -\x2f\x77\x35\x56\x6b\x70\x79\x41\x7a\x6e\x53\x65\x76\x6d\x59\x69\ -\x71\x71\x76\x6a\x44\x59\x54\x35\x59\x39\x41\x4d\x4e\x37\x56\x36\ -\x4b\x20\x63\x72\x4c\x32\x4b\x53\x66\x49\x4d\x76\x6f\x59\x4f\x34\ -\x4e\x4a\x72\x2b\x38\x32\x76\x4c\x78\x48\x6b\x39\x4e\x71\x35\x64\ -\x52\x42\x2f\x62\x6e\x37\x6f\x76\x4d\x41\x69\x49\x67\x69\x4e\x63\ -\x32\x74\x6a\x48\x74\x75\x4d\x70\x6c\x39\x63\x6d\x6e\x75\x33\x4e\ -\x49\x49\x55\x6a\x52\x79\x6c\x48\x51\x4d\x56\x7a\x36\x48\x20\x30\ -\x74\x34\x33\x7a\x59\x50\x4e\x5a\x6b\x58\x4a\x79\x67\x57\x74\x44\ -\x6d\x51\x5a\x77\x6b\x48\x59\x57\x51\x6e\x64\x76\x46\x5a\x6b\x30\ -\x47\x70\x69\x32\x73\x49\x65\x53\x73\x2f\x67\x6e\x44\x36\x38\x65\ -\x2f\x65\x74\x44\x4d\x76\x50\x52\x56\x58\x56\x51\x34\x34\x54\x4b\ -\x63\x61\x56\x52\x70\x4c\x5a\x54\x48\x76\x41\x20\x68\x38\x39\x6f\ -\x37\x46\x72\x52\x71\x59\x43\x71\x67\x71\x49\x71\x4b\x4f\x45\x67\ -\x51\x2b\x30\x32\x62\x6a\x35\x33\x48\x44\x65\x66\x4f\x77\x35\x4a\ -\x6c\x70\x6d\x2f\x64\x69\x4d\x7a\x6c\x71\x39\x69\x57\x4e\x2f\x63\ -\x41\x2b\x34\x6e\x79\x66\x46\x64\x2b\x66\x54\x71\x54\x6d\x61\x54\ -\x6f\x56\x76\x6a\x73\x77\x65\x4e\x20\x52\x73\x4e\x4e\x35\x34\x7a\ -\x46\x6f\x4e\x4f\x69\x30\x57\x68\x77\x32\x6d\x33\x30\x79\x30\x78\ -\x48\x52\x59\x33\x2b\x70\x66\x73\x2f\x56\x4b\x4e\x42\x4f\x55\x59\ -\x4f\x5a\x37\x4e\x42\x6a\x7a\x63\x55\x6f\x43\x4d\x55\x70\x44\x30\ -\x63\x78\x42\x73\x4f\x34\x51\x75\x48\x43\x45\x53\x69\x45\x59\x2b\ -\x49\x49\x6d\x50\x4e\x20\x4c\x53\x44\x53\x36\x64\x79\x56\x55\x63\ -\x46\x6f\x52\x4e\x56\x6f\x6f\x76\x72\x33\x51\x31\x61\x55\x6d\x4a\ -\x78\x75\x54\x70\x75\x56\x4e\x6e\x2b\x77\x78\x2b\x74\x39\x58\x43\ -\x6e\x63\x65\x50\x59\x59\x49\x46\x71\x76\x53\x52\x59\x4c\x47\x53\ -\x6b\x4f\x4e\x42\x6f\x4f\x36\x4a\x79\x69\x4a\x47\x48\x51\x78\x35\ -\x53\x6b\x20\x6a\x74\x47\x67\x49\x33\x79\x51\x33\x42\x61\x54\x77\ -\x63\x41\x4a\x2f\x66\x4b\x36\x5a\x6d\x2b\x54\x77\x55\x42\x47\x69\ -\x68\x4f\x4e\x47\x74\x30\x57\x43\x4c\x49\x55\x39\x61\x4e\x49\x41\ -\x68\x46\x52\x78\x4b\x69\x4e\x62\x52\x73\x59\x54\x2b\x30\x61\x6a\ -\x51\x61\x7a\x58\x67\x2b\x4b\x47\x74\x31\x50\x36\x66\x56\x67\x20\ -\x73\x6b\x53\x64\x72\x4e\x31\x6f\x4e\x4d\x52\x6f\x4f\x41\x2b\x6c\ -\x4a\x78\x51\x52\x75\x50\x75\x74\x44\x31\x42\x56\x74\x56\x66\x6a\ -\x52\x46\x62\x55\x6d\x4f\x72\x53\x61\x62\x4f\x69\x45\x53\x56\x6b\ -\x53\x55\x61\x55\x5a\x41\x52\x4a\x52\x70\x52\x6c\x4a\x45\x58\x75\ -\x6d\x76\x79\x6c\x76\x63\x61\x68\x58\x71\x66\x44\x20\x6e\x57\x78\ -\x48\x73\x33\x64\x6b\x64\x53\x2b\x69\x77\x5a\x5a\x6a\x76\x75\x30\ -\x79\x45\x42\x4b\x45\x48\x71\x2b\x72\x71\x73\x71\x47\x48\x64\x57\ -\x63\x55\x54\x53\x51\x76\x4d\x37\x73\x55\x4c\x31\x4f\x68\x36\x79\ -\x6f\x33\x64\x56\x70\x64\x4f\x56\x7a\x6a\x48\x77\x2b\x4e\x71\x4d\ -\x52\x58\x7a\x43\x41\x4e\x68\x7a\x73\x20\x30\x69\x72\x4b\x30\x53\ -\x31\x43\x52\x42\x4c\x78\x4e\x6a\x66\x67\x71\x36\x71\x45\x67\x41\ -\x38\x78\x79\x51\x47\x79\x42\x42\x5a\x72\x64\x4c\x42\x31\x49\x31\ -\x46\x52\x6c\x4a\x67\x36\x68\x4e\x74\x75\x6f\x39\x6e\x62\x63\x2b\ -\x6a\x36\x6d\x2f\x57\x62\x75\x4f\x66\x74\x44\x31\x6a\x34\x37\x4b\ -\x4e\x38\x75\x58\x6f\x64\x20\x5a\x77\x38\x66\x67\x71\x72\x53\x37\ -\x59\x77\x71\x53\x4c\x47\x48\x50\x73\x32\x47\x67\x30\x38\x73\x32\ -\x33\x62\x58\x38\x66\x78\x6e\x63\x78\x68\x56\x57\x4d\x43\x6d\x36\ -\x6c\x32\x4d\x4b\x52\x71\x49\x7a\x52\x79\x4e\x78\x41\x54\x46\x61\ -\x4e\x51\x6f\x2b\x71\x2b\x41\x70\x4d\x67\x59\x4e\x5a\x71\x34\x52\ -\x6b\x52\x69\x20\x30\x54\x35\x6a\x32\x53\x6f\x51\x42\x66\x72\x57\ -\x56\x46\x41\x64\x45\x56\x46\x73\x79\x64\x45\x56\x6a\x36\x70\x45\ -\x42\x2f\x74\x2b\x37\x57\x6a\x55\x61\x6d\x50\x7a\x73\x52\x78\x43\ -\x7a\x36\x49\x4e\x6d\x39\x6c\x63\x33\x30\x54\x52\x66\x55\x38\x79\ -\x49\x69\x65\x44\x6b\x77\x59\x55\x4d\x4b\x78\x76\x44\x70\x4b\x73\ -\x20\x52\x4b\x4f\x57\x2b\x33\x31\x66\x6c\x75\x58\x59\x4a\x6a\x71\ -\x72\x46\x57\x4e\x7a\x42\x49\x32\x71\x52\x55\x4a\x46\x30\x71\x68\ -\x30\x44\x54\x74\x56\x67\x64\x32\x37\x36\x4e\x41\x71\x6e\x50\x33\ -\x34\x38\x30\x79\x2b\x38\x30\x59\x32\x56\x64\x55\x67\x4b\x77\x71\ -\x69\x4a\x48\x63\x5a\x79\x48\x33\x30\x48\x49\x39\x6f\x20\x6c\x39\ -\x31\x6b\x77\x68\x2f\x75\x4f\x65\x33\x39\x72\x62\x6d\x4c\x57\x4c\ -\x53\x68\x6c\x4d\x74\x4f\x47\x38\x30\x7a\x55\x7a\x39\x6e\x66\x50\ -\x46\x67\x7a\x68\x6b\x78\x42\x46\x47\x57\x6b\x56\x55\x46\x33\x58\ -\x37\x56\x71\x74\x55\x65\x75\x31\x43\x37\x7a\x57\x54\x45\x31\x78\ -\x47\x41\x55\x4e\x54\x34\x4b\x4b\x71\x4b\x20\x72\x4d\x69\x49\x73\ -\x6f\x53\x2f\x75\x5a\x47\x77\x45\x49\x48\x63\x76\x67\x68\x61\x4c\ -\x57\x72\x41\x42\x36\x33\x4e\x6b\x4a\x46\x46\x59\x30\x73\x72\x50\ -\x32\x7a\x65\x69\x73\x74\x75\x49\x79\x50\x46\x53\x55\x36\x71\x47\ -\x36\x31\x47\x67\x78\x53\x6a\x38\x58\x48\x5a\x37\x54\x52\x37\x2f\ -\x51\x64\x38\x4c\x73\x6b\x79\x20\x58\x2f\x32\x30\x6e\x69\x78\x33\ -\x43\x67\x75\x65\x2f\x52\x4d\x35\x71\x53\x37\x53\x6e\x51\x37\x71\ -\x32\x74\x70\x5a\x56\x31\x6e\x46\x56\x36\x74\x4c\x6d\x48\x54\x57\ -\x57\x47\x61\x74\x2b\x49\x6e\x4c\x54\x78\x75\x4e\x78\x35\x46\x4d\ -\x52\x79\x43\x49\x51\x52\x75\x62\x38\x62\x45\x61\x6a\x64\x31\x6d\ -\x30\x53\x71\x71\x20\x69\x69\x38\x59\x34\x72\x30\x46\x33\x2f\x48\ -\x71\x72\x64\x64\x68\x4d\x35\x76\x59\x73\x47\x4d\x58\x36\x51\x34\ -\x48\x62\x38\x39\x62\x6a\x43\x68\x4c\x31\x4e\x62\x73\x70\x4b\x36\ -\x6c\x6b\x61\x44\x4e\x52\x6a\x41\x63\x52\x46\x58\x56\x61\x4b\x67\ -\x39\x6a\x68\x47\x52\x49\x39\x45\x75\x53\x6a\x4a\x62\x61\x33\x66\ -\x6a\x20\x44\x59\x57\x5a\x39\x2f\x51\x6a\x32\x43\x30\x6d\x61\x70\ -\x76\x62\x57\x4c\x32\x39\x6b\x68\x56\x62\x4b\x2f\x68\x33\x65\x52\ -\x6e\x32\x37\x5a\x74\x70\x31\x78\x70\x51\x37\x45\x6c\x67\x54\x77\ -\x4b\x54\x43\x5a\x4e\x4f\x47\x39\x4d\x32\x74\x6b\x63\x39\x73\x73\ -\x79\x55\x2b\x55\x74\x34\x5a\x63\x46\x79\x54\x72\x2f\x6b\x20\x4f\ -\x6b\x53\x4e\x68\x6f\x72\x57\x4a\x6e\x37\x63\x55\x49\x31\x76\x38\ -\x57\x72\x38\x4e\x64\x57\x63\x2f\x74\x6a\x7a\x6a\x4d\x37\x50\x35\ -\x64\x52\x42\x68\x5a\x7a\x59\x4c\x35\x39\x4d\x6c\x37\x4e\x7a\x32\ -\x33\x58\x6b\x64\x57\x6b\x31\x47\x54\x43\x71\x6f\x4e\x64\x71\x6b\ -\x56\x51\x31\x2b\x6f\x4f\x4b\x4a\x49\x6c\x51\x20\x56\x63\x36\x39\ -\x70\x77\x7a\x6e\x69\x61\x73\x75\x4a\x53\x79\x49\x57\x45\x78\x47\ -\x76\x6c\x71\x39\x6e\x71\x59\x4f\x48\x2f\x50\x58\x62\x75\x43\x36\ -\x56\x39\x37\x6b\x75\x64\x39\x65\x79\x62\x72\x4b\x4b\x73\x59\x55\ -\x44\x53\x44\x4a\x59\x6f\x6c\x47\x75\x2b\x49\x59\x79\x65\x79\x56\ -\x38\x62\x47\x5a\x54\x66\x68\x44\x20\x42\x78\x6f\x66\x58\x79\x6a\ -\x4d\x6b\x67\x32\x62\x79\x55\x39\x50\x35\x5a\x76\x6e\x48\x6f\x75\ -\x6d\x5a\x64\x75\x73\x68\x41\x57\x52\x65\x57\x73\x32\x73\x4b\x75\ -\x70\x68\x64\x4b\x71\x47\x75\x61\x73\x57\x73\x74\x31\x34\x30\x36\ -\x6a\x49\x43\x4d\x4e\x62\x57\x66\x53\x33\x4c\x46\x4b\x63\x4c\x61\ -\x61\x6a\x66\x6a\x71\x20\x57\x31\x48\x32\x57\x76\x6c\x49\x69\x6b\ -\x4b\x6f\x76\x68\x62\x2f\x72\x68\x33\x6f\x69\x34\x59\x68\x71\x47\ -\x70\x30\x70\x57\x4f\x78\x67\x6a\x73\x56\x56\x42\x57\x37\x33\x55\ -\x37\x2f\x7a\x41\x79\x2b\x33\x62\x69\x5a\x4f\x53\x76\x58\x4d\x6e\ -\x70\x41\x50\x2f\x37\x31\x39\x54\x66\x6f\x64\x62\x48\x4e\x6a\x75\ -\x34\x6b\x20\x47\x2b\x75\x72\x64\x78\x2f\x77\x2b\x61\x4b\x53\x55\ -\x6a\x37\x39\x37\x6b\x66\x65\x76\x2b\x38\x32\x72\x4b\x62\x6f\x79\ -\x34\x54\x58\x6e\x33\x6b\x36\x41\x42\x61\x6a\x67\x63\x62\x32\x44\ -\x6a\x4a\x64\x54\x67\x6f\x79\x30\x67\x68\x45\x42\x4e\x36\x65\x4e\ -\x6f\x75\x6c\x6d\x37\x63\x78\x49\x44\x50\x74\x67\x48\x73\x64\x20\ -\x44\x6c\x61\x7a\x6b\x55\x44\x34\x77\x41\x48\x7a\x31\x74\x66\x66\ -\x73\x4c\x61\x79\x69\x6e\x66\x75\x76\x71\x58\x4c\x32\x4f\x37\x4a\ -\x42\x42\x2f\x56\x50\x35\x38\x2b\x64\x7a\x36\x4f\x58\x34\x6a\x51\ -\x56\x46\x65\x44\x37\x45\x34\x6c\x55\x72\x6f\x65\x58\x42\x36\x4d\ -\x65\x6c\x31\x63\x33\x34\x67\x2b\x45\x75\x32\x76\x20\x7a\x5a\x35\ -\x4c\x56\x57\x4d\x7a\x62\x39\x77\x78\x36\x57\x66\x66\x6c\x63\x33\ -\x47\x6b\x4c\x78\x73\x4a\x70\x30\x31\x68\x70\x2f\x4b\x4b\x35\x6e\ -\x78\x36\x4c\x31\x55\x31\x6a\x65\x78\x61\x6c\x73\x46\x4b\x38\x73\ -\x72\x57\x62\x6d\x6a\x48\x4c\x74\x52\x6a\x30\x46\x2f\x35\x4d\x61\ -\x38\x4f\x7a\x30\x52\x55\x65\x54\x78\x20\x6a\x36\x59\x7a\x62\x33\ -\x73\x44\x5a\x31\x35\x38\x4c\x57\x46\x56\x78\x52\x63\x4a\x59\x55\ -\x76\x78\x34\x4c\x48\x61\x4d\x47\x62\x6c\x30\x4e\x48\x53\x79\x45\ -\x5a\x6e\x4a\x71\x75\x71\x6d\x35\x6c\x63\x57\x6f\x6b\x75\x34\x43\ -\x66\x48\x70\x43\x50\x4e\x59\x6f\x71\x70\x4c\x69\x31\x47\x49\x79\ -\x61\x4e\x42\x6f\x76\x4f\x20\x67\x4b\x67\x6f\x69\x4b\x70\x43\x4f\ -\x42\x4a\x45\x57\x31\x6e\x47\x43\x35\x64\x4e\x34\x4a\x36\x4c\x4a\ -\x2b\x77\x7a\x6b\x54\x34\x34\x38\x51\x49\x32\x56\x65\x32\x69\x66\ -\x48\x63\x39\x7a\x39\x39\x77\x46\x53\x61\x44\x6e\x6e\x55\x56\x4f\ -\x37\x47\x5a\x6a\x4d\x78\x59\x76\x68\x71\x62\x79\x59\x67\x2b\x78\ -\x73\x6c\x75\x20\x62\x33\x71\x33\x38\x72\x47\x59\x38\x4f\x31\x6e\ -\x66\x4d\x4b\x43\x79\x41\x76\x54\x35\x35\x43\x62\x36\x75\x62\x32\ -\x58\x35\x33\x56\x31\x63\x69\x44\x73\x76\x73\x41\x4d\x44\x77\x2f\ -\x6c\x38\x6c\x66\x4c\x79\x54\x4c\x34\x32\x4a\x51\x64\x68\x38\x43\ -\x45\x59\x46\x72\x58\x70\x35\x4d\x74\x73\x65\x46\x51\x61\x38\x2f\ -\x20\x5a\x69\x73\x66\x75\x38\x6c\x4d\x49\x42\x68\x45\x44\x41\x55\ -\x41\x55\x45\x57\x52\x53\x48\x6b\x5a\x35\x50\x52\x46\x47\x56\x68\ -\x4d\x70\x44\x73\x64\x47\x67\x30\x47\x76\x59\x35\x55\x52\x78\x4b\ -\x33\x6e\x33\x39\x32\x39\x4e\x30\x75\x4a\x5a\x70\x77\x57\x4a\x79\ -\x56\x45\x56\x4f\x48\x38\x43\x54\x62\x61\x66\x62\x36\x20\x75\x70\ -\x61\x31\x48\x59\x45\x67\x39\x37\x33\x7a\x45\x51\x39\x64\x64\x69\ -\x48\x2f\x66\x65\x69\x75\x62\x69\x4e\x58\x4a\x6f\x4d\x42\x52\x56\ -\x56\x4a\x73\x64\x76\x34\x7a\x64\x68\x54\x41\x63\x68\x4c\x64\x58\ -\x50\x78\x73\x33\x2f\x6a\x77\x55\x76\x4f\x4f\x32\x49\x74\x45\x4b\ -\x30\x66\x2f\x31\x34\x44\x70\x69\x4d\x51\x20\x5a\x50\x72\x53\x6c\ -\x5a\x77\x30\x6f\x4a\x41\x62\x7a\x78\x6e\x62\x62\x64\x61\x4c\x32\ -\x57\x68\x45\x56\x6d\x51\x55\x71\x77\x33\x62\x67\x43\x4c\x71\x66\ -\x52\x32\x6f\x51\x34\x5a\x44\x78\x56\x61\x75\x4f\x58\x2f\x73\x4d\ -\x58\x4d\x34\x37\x36\x2b\x39\x78\x65\x66\x6e\x62\x35\x39\x2f\x7a\ -\x65\x38\x76\x50\x43\x66\x71\x20\x6c\x2b\x70\x6d\x68\x52\x72\x39\ -\x54\x43\x55\x6a\x78\x55\x6c\x65\x57\x69\x70\x6e\x44\x69\x74\x43\ -\x56\x68\x54\x75\x6e\x2f\x49\x78\x42\x61\x6d\x75\x6d\x45\x34\x4a\ -\x36\x45\x37\x50\x54\x66\x39\x34\x6c\x79\x61\x54\x6d\x33\x45\x58\ -\x58\x45\x6c\x49\x46\x42\x43\x45\x4d\x49\x49\x73\x49\x53\x71\x64\ -\x2f\x68\x64\x5a\x20\x42\x6b\x41\x32\x47\x4d\x48\x70\x41\x71\x63\ -\x4c\x57\x56\x48\x59\x75\x62\x57\x55\x4f\x38\x61\x66\x47\x71\x4d\ -\x50\x53\x6f\x38\x5a\x63\x42\x67\x4d\x43\x49\x71\x43\x74\x37\x30\ -\x56\x77\x2b\x35\x79\x33\x72\x76\x6e\x4a\x69\x61\x63\x4f\x4c\x54\ -\x62\x2b\x74\x48\x72\x64\x47\x67\x30\x30\x44\x63\x39\x46\x59\x42\ -\x6e\x20\x72\x37\x2b\x43\x73\x43\x44\x79\x7a\x79\x38\x57\x38\x4d\ -\x68\x6c\x46\x38\x54\x6b\x6b\x44\x2f\x67\x57\x62\x33\x35\x6b\x74\ -\x31\x6b\x77\x72\x75\x58\x38\x56\x6c\x63\x55\x73\x72\x37\x33\x33\ -\x7a\x50\x35\x44\x73\x6d\x6b\x57\x79\x31\x39\x4e\x6a\x49\x69\x68\ -\x71\x4e\x37\x6c\x7a\x64\x2b\x57\x4c\x69\x66\x2b\x36\x2f\x20\x6e\ -\x5a\x72\x6d\x56\x6d\x35\x34\x39\x53\x30\x75\x48\x64\x6e\x7a\x75\ -\x30\x4c\x78\x78\x47\x6f\x32\x45\x68\x48\x43\x43\x4a\x45\x77\x68\ -\x45\x4f\x6f\x6f\x67\x68\x4a\x79\x57\x41\x77\x48\x44\x53\x66\x62\ -\x47\x39\x66\x6c\x55\x61\x6a\x59\x56\x48\x4a\x4a\x75\x70\x61\x32\ -\x6e\x6a\x35\x2b\x73\x74\x69\x30\x75\x4f\x79\x20\x32\x32\x6a\x78\ -\x52\x62\x64\x64\x74\x53\x32\x74\x4e\x48\x58\x34\x4f\x47\x74\x34\ -\x45\x59\x4f\x79\x4d\x33\x73\x4d\x6d\x5a\x76\x32\x53\x34\x53\x55\ -\x46\x59\x56\x6e\x70\x73\x33\x69\x38\x6c\x4e\x4f\x70\x48\x43\x2f\ -\x63\x4f\x6a\x68\x45\x70\x32\x74\x6f\x32\x33\x72\x44\x51\x5a\x35\ -\x66\x2b\x46\x33\x4a\x4e\x73\x73\x20\x6e\x4e\x41\x76\x37\x36\x41\ -\x64\x58\x31\x45\x55\x76\x4a\x30\x4f\x66\x45\x45\x53\x6f\x61\x4f\ -\x4e\x73\x39\x4e\x64\x54\x44\x71\x7a\x2b\x32\x7a\x6f\x6f\x38\x48\ -\x65\x32\x70\x73\x37\x66\x48\x79\x33\x71\x59\x7a\x69\x76\x47\x77\ -\x79\x55\x70\x77\x48\x31\x36\x36\x79\x54\x37\x52\x31\x30\x66\x70\ -\x53\x4b\x6e\x59\x33\x20\x38\x50\x53\x56\x46\x38\x56\x4e\x7a\x35\ -\x5a\x64\x75\x37\x6e\x70\x6a\x66\x63\x77\x35\x68\x55\x7a\x61\x50\ -\x41\x77\x66\x4a\x48\x77\x58\x75\x2b\x58\x43\x59\x52\x46\x67\x62\ -\x41\x6b\x45\x70\x59\x6b\x46\x46\x56\x46\x55\x65\x53\x66\x62\x39\ -\x54\x63\x79\x42\x6c\x70\x44\x6e\x35\x33\x33\x72\x69\x59\x39\x4a\ -\x6a\x31\x20\x42\x6b\x77\x61\x53\x44\x45\x5a\x71\x61\x76\x62\x68\ -\x61\x75\x39\x6a\x6b\x2b\x66\x75\x49\x38\x68\x75\x64\x6b\x39\x48\ -\x6f\x75\x68\x31\x2b\x6d\x51\x35\x48\x30\x6e\x35\x4c\x66\x6d\x4c\ -\x71\x4a\x76\x71\x6f\x76\x78\x51\x77\x62\x47\x70\x47\x64\x2f\x65\ -\x6d\x56\x57\x37\x57\x59\x7a\x2f\x6e\x41\x59\x53\x5a\x61\x5a\x20\ -\x76\x57\x49\x4e\x4b\x76\x44\x69\x70\x4b\x74\x78\x32\x4b\x77\x48\ -\x50\x64\x74\x44\x56\x64\x53\x75\x4b\x41\x6c\x45\x4f\x2b\x7a\x39\ -\x55\x7a\x37\x6d\x7a\x67\x6e\x6a\x4b\x4d\x37\x4e\x36\x72\x46\x63\ -\x50\x4c\x47\x62\x54\x43\x44\x4c\x71\x4d\x45\x41\x36\x72\x62\x4e\ -\x30\x59\x68\x48\x57\x73\x59\x68\x73\x38\x6d\x55\x20\x76\x62\x53\ -\x33\x65\x48\x30\x38\x4e\x32\x30\x57\x7a\x31\x31\x7a\x61\x63\x78\ -\x48\x56\x31\x68\x4e\x4a\x67\x4c\x68\x61\x43\x37\x46\x74\x61\x2b\ -\x38\x53\x55\x51\x55\x75\x65\x47\x73\x4d\x51\x65\x39\x72\x39\x6c\ -\x67\x32\x4d\x66\x68\x2f\x4f\x57\x71\x64\x56\x51\x33\x4e\x48\x4c\ -\x54\x6d\x57\x66\x45\x70\x41\x58\x32\x20\x2b\x50\x4d\x69\x4c\x43\ -\x34\x70\x35\x64\x71\x58\x33\x2b\x54\x57\x43\x65\x4f\x35\x2b\x5a\ -\x78\x78\x68\x35\x78\x78\x5a\x55\x57\x68\x49\x78\x54\x43\x48\x77\ -\x6d\x6a\x69\x69\x4b\x65\x70\x6a\x70\x65\x2f\x75\x31\x6c\x63\x54\ -\x33\x61\x34\x31\x44\x73\x30\x62\x36\x2b\x73\x6f\x6f\x72\x58\x76\ -\x77\x48\x70\x77\x37\x75\x20\x7a\x37\x58\x6a\x54\x6a\x75\x6b\x64\ -\x76\x55\x6f\x74\x65\x30\x65\x50\x64\x2b\x58\x62\x75\x47\x53\x6c\ -\x79\x61\x6a\x4c\x54\x77\x42\x64\x33\x35\x2f\x32\x6b\x50\x42\x36\ -\x50\x74\x6c\x34\x53\x44\x65\x63\x42\x68\x66\x4a\x49\x79\x2f\x36\ -\x2f\x32\x79\x43\x4b\x72\x4b\x7a\x2b\x4d\x6b\x45\x73\x62\x52\x57\ -\x4d\x76\x66\x20\x4a\x6c\x30\x64\x65\x31\x38\x7a\x47\x39\x47\x71\ -\x45\x72\x36\x36\x4b\x76\x49\x31\x41\x65\x59\x39\x2b\x51\x44\x46\ -\x65\x54\x6b\x48\x48\x62\x4e\x36\x72\x62\x5a\x72\x4e\x51\x5a\x51\ -\x73\x71\x4f\x61\x6d\x63\x74\x58\x38\x64\x68\x6c\x46\x38\x61\x6b\ -\x70\x54\x74\x36\x5a\x33\x79\x73\x5a\x6c\x70\x39\x66\x6a\x35\x65\ -\x20\x73\x6f\x78\x6c\x5a\x64\x73\x34\x6f\x32\x67\x41\x32\x5a\x35\ -\x44\x48\x34\x65\x68\x71\x45\x72\x58\x43\x69\x49\x69\x69\x74\x7a\ -\x37\x39\x6b\x65\x4d\x48\x56\x54\x49\x78\x4a\x4e\x50\x6a\x45\x6e\ -\x30\x34\x57\x41\x7a\x6d\x36\x47\x78\x48\x6f\x51\x49\x44\x42\x6b\ -\x65\x39\x65\x76\x30\x41\x6b\x56\x56\x4f\x33\x4d\x69\x20\x56\x42\ -\x37\x2f\x61\x44\x71\x2f\x4f\x58\x31\x30\x7a\x4b\x73\x4d\x41\x4a\ -\x4e\x42\x54\x32\x31\x4c\x57\x7a\x51\x76\x36\x72\x45\x2f\x63\x4e\ -\x4b\x41\x37\x74\x2b\x4a\x32\x37\x66\x4d\x7a\x79\x75\x66\x75\x74\ -\x5a\x32\x6e\x70\x33\x36\x4f\x53\x39\x63\x66\x30\x56\x4d\x2f\x6f\ -\x6b\x39\x32\x4d\x78\x6d\x46\x71\x7a\x62\x20\x69\x44\x76\x5a\x7a\ -\x6a\x76\x33\x33\x49\x4c\x64\x62\x4f\x37\x56\x59\x56\x47\x4b\x49\ -\x74\x4d\x52\x44\x69\x49\x71\x4d\x72\x72\x71\x53\x70\x36\x2b\x35\ -\x4e\x79\x34\x31\x4d\x2f\x68\x59\x44\x4f\x62\x6d\x62\x75\x6d\x42\ -\x46\x6c\x52\x2b\x4f\x69\x42\x4f\x38\x6c\x4d\x63\x66\x61\x71\x33\ -\x4a\x35\x2b\x47\x65\x2b\x32\x20\x74\x5a\x6e\x4e\x7a\x46\x72\x78\ -\x45\x78\x50\x2f\x2f\x6a\x37\x32\x45\x30\x35\x48\x6c\x2b\x4b\x6d\ -\x4a\x65\x43\x6e\x4a\x65\x69\x6e\x4a\x52\x69\x67\x4c\x52\x6a\x6f\ -\x66\x4d\x45\x31\x69\x43\x38\x63\x4e\x64\x79\x42\x53\x49\x53\x75\ -\x73\x4b\x71\x71\x6f\x71\x6e\x63\x78\x70\x4f\x58\x54\x6d\x42\x77\ -\x39\x75\x47\x64\x20\x6d\x64\x4d\x64\x79\x56\x59\x4c\x35\x64\x75\ -\x33\x63\x4b\x4c\x48\x7a\x4f\x65\x50\x33\x6b\x64\x57\x4c\x38\x34\ -\x46\x30\x75\x74\x30\x58\x65\x48\x33\x73\x43\x42\x77\x37\x7a\x73\ -\x66\x38\x76\x54\x56\x6c\x2b\x4b\x77\x78\x66\x39\x30\x7a\x31\x34\ -\x5a\x6e\x32\x53\x7a\x6d\x59\x2b\x58\x4c\x4b\x4e\x66\x5a\x68\x71\ -\x50\x20\x58\x6e\x6b\x4a\x78\x6c\x37\x6d\x6c\x69\x69\x64\x6a\x6c\ -\x78\x46\x55\x58\x6a\x36\x30\x38\x39\x4a\x74\x68\x68\x6a\x58\x6b\ -\x6f\x65\x4c\x72\x6d\x70\x4c\x72\x4c\x4e\x42\x6e\x54\x4e\x6a\x64\ -\x44\x52\x44\x6f\x4c\x51\x62\x55\x37\x46\x2f\x71\x69\x64\x32\x75\ -\x65\x75\x4b\x61\x47\x68\x72\x59\x32\x72\x7a\x78\x67\x64\x20\x46\ -\x7a\x31\x4a\x5a\x6a\x4e\x6e\x44\x4f\x72\x50\x79\x7a\x4f\x2f\x34\ -\x74\x6d\x70\x73\x35\x69\x33\x5a\x67\x50\x4e\x48\x62\x36\x44\x35\ -\x6a\x32\x5a\x6a\x64\x48\x6b\x74\x59\x67\x6f\x63\x76\x2b\x55\x6a\ -\x33\x6e\x67\x34\x6e\x50\x4a\x63\x76\x56\x75\x6f\x42\x32\x4b\x33\ -\x46\x51\x58\x32\x32\x76\x72\x65\x47\x76\x75\x20\x59\x74\x5a\x58\ -\x56\x74\x48\x6b\x39\x66\x55\x71\x41\x56\x52\x56\x56\x63\x4b\x69\ -\x41\x4b\x33\x4e\x58\x4a\x44\x6c\x69\x56\x76\x39\x48\x41\x35\x37\ -\x74\x4c\x2f\x2b\x35\x51\x49\x32\x56\x75\x33\x71\x74\x58\x62\x6c\ -\x4b\x4c\x56\x74\x54\x6d\x6f\x4b\x32\x32\x72\x72\x55\x45\x77\x57\ -\x57\x6c\x75\x61\x61\x47\x35\x76\x20\x6f\x54\x58\x6f\x70\x7a\x58\ -\x6f\x70\x79\x33\x6f\x70\x79\x30\x55\x6f\x4c\x30\x7a\x35\x38\x7a\ -\x62\x61\x58\x78\x45\x57\x61\x4a\x72\x2f\x39\x2f\x55\x77\x4e\x6c\ -\x5a\x71\x66\x78\x32\x33\x43\x6b\x48\x66\x55\x35\x76\x4f\x57\x31\ -\x67\x49\x56\x65\x63\x63\x69\x4b\x62\x71\x71\x71\x35\x39\x35\x30\ -\x50\x6d\x62\x35\x30\x20\x4a\x58\x57\x74\x37\x51\x64\x73\x71\x2f\ -\x5a\x47\x72\x34\x75\x75\x66\x42\x52\x46\x34\x66\x6e\x70\x63\x78\ -\x68\x58\x31\x4a\x39\x52\x68\x58\x33\x6a\x6f\x75\x65\x41\x5a\x2f\ -\x58\x6d\x53\x30\x55\x35\x66\x58\x6a\x32\x6d\x6f\x6e\x38\x66\x64\ -\x62\x58\x31\x4c\x56\x37\x79\x55\x39\x50\x34\x39\x77\x52\x78\x5a\ -\x77\x35\x20\x72\x49\x6a\x63\x56\x48\x65\x50\x4d\x2b\x57\x65\x51\ -\x37\x6a\x65\x58\x66\x41\x74\x32\x32\x76\x72\x6d\x48\x7a\x62\x74\ -\x63\x66\x4d\x47\x62\x6d\x48\x34\x74\x77\x73\x56\x72\x7a\x34\x4f\ -\x47\x73\x71\x64\x72\x4b\x67\x70\x4a\x51\x46\x6d\x37\x65\x7a\x50\ -\x52\x42\x42\x54\x58\x46\x42\x69\x67\x65\x4d\x78\x6d\x36\x33\x20\ -\x59\x49\x71\x71\x30\x74\x6a\x68\x35\x53\x2f\x2f\x6e\x63\x6d\x48\ -\x39\x39\x37\x53\x61\x34\x4e\x37\x4b\x49\x77\x47\x50\x53\x39\x50\ -\x75\x70\x4b\x4f\x59\x49\x69\x31\x46\x54\x75\x5a\x75\x33\x6f\x4e\ -\x4c\x30\x79\x66\x6a\x54\x73\x35\x69\x51\x6b\x6e\x44\x75\x4f\x69\ -\x30\x53\x65\x51\x35\x55\x37\x5a\x70\x30\x35\x4e\x20\x6e\x65\x38\ -\x6b\x66\x62\x42\x6f\x4b\x52\x61\x44\x6a\x6f\x74\x48\x39\x33\x77\ -\x65\x7a\x4f\x46\x53\x6e\x4a\x76\x46\x30\x75\x63\x66\x5a\x55\x33\ -\x46\x54\x72\x35\x65\x74\x59\x62\x6e\x50\x35\x74\x44\x75\x74\x50\ -\x42\x2b\x53\x4f\x48\x63\x66\x36\x6f\x45\x66\x52\x78\x64\x65\x2b\ -\x34\x52\x56\x56\x42\x69\x4a\x44\x53\x20\x55\x4d\x76\x2f\x50\x58\ -\x56\x2f\x33\x4f\x72\x6e\x63\x4c\x58\x2f\x32\x4e\x6d\x32\x68\x36\ -\x4e\x64\x56\x56\x55\x61\x32\x6a\x76\x69\x33\x72\x5a\x44\x63\x37\ -\x4e\x5a\x39\x74\x66\x48\x57\x4c\x6d\x39\x6b\x76\x6e\x72\x4e\x72\ -\x46\x77\x32\x54\x6f\x43\x52\x67\x74\x47\x54\x7a\x6f\x36\x64\x79\ -\x71\x4b\x30\x59\x41\x67\x20\x79\x55\x52\x6b\x45\x55\x6d\x57\x39\ -\x30\x30\x6a\x69\x34\x53\x78\x31\x65\x33\x69\x74\x57\x63\x65\x78\ -\x47\x77\x30\x78\x6b\x56\x50\x5a\x6f\x71\x44\x4b\x58\x66\x64\x69\ -\x43\x38\x55\x5a\x74\x32\x4f\x61\x68\x5a\x76\x4b\x4f\x4f\x31\x32\ -\x56\x2b\x54\x62\x4c\x56\x78\x7a\x6f\x68\x69\x4c\x6a\x6e\x70\x42\ -\x50\x72\x33\x20\x79\x64\x69\x6e\x6a\x6e\x52\x61\x48\x62\x4b\x69\ -\x73\x4c\x79\x73\x6e\x4f\x38\x32\x6c\x6a\x48\x7a\x6a\x33\x63\x64\ -\x6c\x57\x4f\x44\x34\x51\x69\x4f\x55\x5a\x56\x6c\x68\x55\x32\x37\ -\x61\x6c\x6d\x38\x73\x59\x79\x6c\x5a\x64\x73\x4a\x69\x53\x49\x6a\ -\x43\x76\x49\x59\x58\x7a\x79\x59\x6b\x59\x58\x35\x35\x4b\x58\x39\ -\x20\x66\x48\x35\x4a\x30\x56\x31\x2f\x35\x4d\x47\x4a\x46\x7a\x44\ -\x31\x32\x2b\x58\x38\x39\x2f\x37\x62\x59\x71\x37\x55\x65\x42\x32\ -\x31\x75\x57\x31\x33\x50\x66\x50\x58\x6c\x66\x4c\x4e\x68\x73\x32\ -\x73\x61\x57\x7a\x44\x61\x37\x5a\x43\x69\x68\x76\x73\x39\x6d\x67\ -\x61\x50\x75\x41\x71\x58\x63\x63\x5a\x2f\x66\x4f\x35\x20\x5a\x47\ -\x51\x78\x56\x35\x31\x2b\x55\x6b\x7a\x50\x36\x77\x30\x56\x39\x59\ -\x30\x73\x58\x46\x2f\x4b\x67\x67\x31\x6c\x4b\x4b\x72\x4b\x4b\x51\ -\x4d\x4c\x2b\x64\x58\x49\x34\x59\x77\x6f\x79\x45\x57\x44\x68\x67\ -\x47\x33\x50\x30\x52\x2b\x75\x70\x75\x70\x44\x39\x77\x52\x31\x30\ -\x50\x35\x75\x32\x4e\x50\x2f\x53\x7a\x61\x20\x57\x49\x5a\x47\x71\ -\x32\x58\x4d\x6b\x49\x47\x63\x64\x38\x4a\x51\x52\x68\x54\x6b\x59\ -\x65\x6c\x73\x51\x39\x4d\x31\x64\x36\x42\x61\x37\x66\x7a\x72\x69\ -\x67\x6c\x78\x71\x5a\x39\x34\x74\x2b\x33\x42\x74\x41\x2b\x38\x34\ -\x79\x47\x47\x35\x2b\x63\x78\x59\x64\x69\x67\x6f\x39\x36\x32\x4b\ -\x37\x5a\x57\x73\x4c\x42\x6b\x20\x4d\x30\x73\x32\x62\x57\x46\x6a\ -\x71\x35\x64\x49\x6b\x69\x4d\x61\x31\x62\x49\x6e\x52\x64\x2b\x6d\ -\x56\x32\x54\x59\x73\x42\x61\x64\x32\x63\x79\x72\x6c\x35\x7a\x4e\ -\x54\x57\x66\x46\x37\x73\x63\x37\x46\x4e\x56\x4e\x4c\x53\x77\x6f\ -\x4b\x57\x58\x2b\x2b\x6c\x4a\x38\x6f\x51\x69\x6a\x2b\x75\x64\x7a\ -\x77\x61\x67\x52\x20\x6a\x43\x72\x4d\x52\x36\x76\x56\x4d\x75\x61\ -\x52\x5a\x33\x48\x61\x72\x4c\x77\x36\x36\x61\x72\x44\x50\x6a\x4b\ -\x31\x4f\x33\x70\x71\x32\x79\x4d\x2b\x77\x78\x6d\x69\x44\x75\x51\ -\x32\x66\x35\x42\x4e\x75\x32\x72\x35\x66\x6e\x4d\x35\x4a\x54\x74\ -\x33\x67\x55\x62\x44\x71\x50\x37\x35\x6a\x42\x39\x61\x78\x42\x55\ -\x76\x20\x2f\x49\x4f\x69\x37\x45\x77\x2b\x75\x4f\x64\x57\x4d\x6c\ -\x32\x4f\x6f\x2f\x5a\x48\x48\x43\x6d\x79\x72\x46\x44\x66\x34\x65\ -\x58\x48\x4c\x65\x58\x4d\x4b\x79\x6c\x6a\x61\x57\x55\x56\x6a\x52\ -\x6f\x44\x6b\x69\x4d\x46\x54\x66\x6b\x57\x4c\x68\x38\x31\x6c\x48\ -\x66\x75\x6e\x48\x52\x4d\x6e\x61\x69\x4b\x6f\x74\x44\x6b\x20\x39\ -\x62\x47\x36\x66\x43\x63\x4c\x4e\x32\x36\x6d\x6f\x72\x36\x4a\x76\ -\x75\x6d\x70\x54\x50\x31\x2b\x42\x54\x4d\x66\x2b\x54\x31\x6a\x69\ -\x77\x59\x63\x4d\x79\x31\x37\x31\x38\x2b\x69\x54\x56\x75\x70\x62\ -\x6d\x35\x68\x61\x46\x34\x75\x45\x30\x34\x63\x78\x70\x55\x76\x76\ -\x63\x37\x46\x49\x34\x66\x78\x37\x6c\x33\x78\x20\x71\x5a\x2b\x6a\ -\x32\x62\x62\x37\x61\x2f\x2f\x4e\x2f\x37\x33\x42\x68\x53\x4f\x48\ -\x38\x63\x36\x64\x4e\x78\x79\x7a\x74\x68\x55\x6c\x6d\x5a\x71\x57\ -\x56\x72\x37\x5a\x73\x4a\x6e\x35\x4a\x57\x57\x73\x72\x61\x6d\x6e\ -\x56\x57\x64\x41\x63\x61\x54\x41\x39\x69\x33\x38\x61\x76\x67\x51\ -\x50\x72\x6e\x76\x6c\x70\x68\x66\x20\x6c\x7a\x6b\x63\x46\x45\x57\ -\x68\x78\x52\x64\x67\x62\x65\x56\x4f\x35\x71\x2f\x66\x54\x46\x6c\ -\x74\x48\x65\x6c\x4f\x4a\x37\x4e\x57\x2f\x4d\x52\x4c\x4e\x31\x7a\ -\x42\x37\x65\x65\x4e\x6a\x38\x74\x7a\x6a\x6f\x72\x78\x36\x59\x36\ -\x61\x35\x6c\x62\x57\x37\x61\x6a\x6d\x2b\x38\x33\x6c\x37\x47\x68\ -\x73\x34\x72\x6c\x72\x20\x4a\x75\x35\x7a\x4a\x45\x55\x73\x48\x49\ -\x33\x2f\x58\x6d\x56\x76\x66\x4b\x45\x77\x61\x79\x75\x72\x57\x4c\ -\x53\x78\x6a\x4b\x32\x31\x64\x62\x77\x79\x36\x57\x70\x79\x65\x75\ -\x46\x59\x50\x35\x71\x45\x49\x69\x4b\x6c\x75\x32\x72\x77\x68\x73\ -\x4b\x4d\x48\x7a\x4c\x77\x6d\x4a\x34\x53\x75\x44\x39\x48\x73\x33\ -\x35\x2b\x20\x61\x57\x33\x62\x31\x4f\x48\x6a\x70\x2b\x30\x37\x57\ -\x56\x43\x79\x69\x62\x4c\x61\x4f\x74\x36\x38\x37\x58\x6f\x4b\x4d\ -\x6d\x4a\x4c\x47\x49\x32\x56\x69\x43\x69\x79\x65\x64\x64\x75\x56\ -\x70\x58\x76\x59\x4e\x4b\x5a\x70\x32\x4f\x4f\x30\x35\x47\x70\x78\ -\x38\x7a\x34\x4a\x45\x69\x51\x49\x45\x46\x76\x4f\x48\x37\x54\x20\ -\x61\x49\x49\x45\x43\x58\x37\x52\x4a\x49\x78\x50\x67\x67\x51\x4a\ -\x6a\x67\x73\x4a\x34\x35\x4d\x67\x51\x59\x4c\x6a\x51\x73\x4c\x34\ -\x4a\x45\x69\x51\x34\x4c\x69\x51\x4d\x44\x34\x4a\x45\x69\x51\x34\ -\x4c\x69\x53\x4d\x54\x34\x49\x45\x43\x59\x34\x4c\x43\x65\x4f\x54\ -\x49\x45\x47\x43\x34\x30\x4c\x43\x2b\x43\x52\x49\x20\x6b\x4f\x43\ -\x34\x6b\x44\x41\x2b\x43\x52\x49\x6b\x4f\x43\x34\x6b\x6a\x45\x2b\ -\x43\x42\x41\x6d\x4f\x43\x2f\x38\x50\x32\x32\x63\x47\x79\x2b\x42\ -\x2f\x69\x58\x30\x41\x41\x41\x41\x41\x53\x55\x56\x4f\x52\x4b\x35\ -\x43\x59\x49\x49\x3d\x20\x22\x20\x68\x65\x69\x67\x68\x74\x3d\x22\ -\x34\x31\x22\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x38\x37\x22\x20\ -\x79\x3d\x22\x2d\x36\x35\x35\x2e\x33\x37\x22\x20\x78\x3d\x22\x31\ -\x32\x39\x39\x2e\x37\x22\x20\x70\x72\x65\x73\x65\x72\x76\x65\x41\ -\x73\x70\x65\x63\x74\x52\x61\x74\x69\x6f\x3d\x22\x6e\x6f\x6e\x65\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\ -\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x33\x33\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\ -\x2d\x35\x39\x31\x2e\x38\x33\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x34\x37\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x35\x36\x36\x2e\x35\x39\ -\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x20\x32\x35\ -\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x33\x34\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\ -\x32\x2d\x35\x39\x31\x2e\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\ -\x38\x2e\x34\x35\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x33\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x35\x38\x2e\ -\x31\x34\x76\x33\x32\x6c\x2d\x33\x31\x2e\x35\x34\x37\x2d\x38\x2e\ -\x34\x35\x33\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x32\ -\x36\x2e\x31\x34\x20\x32\x35\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\ -\x33\x38\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x37\ -\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x39\x31\ -\x2e\x38\x33\x76\x33\x32\x6c\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x39\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x35\x39\x2e\ -\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x36\x31\x22\x20\x64\x3d\x22\x6d\x31\ -\x32\x33\x36\x2e\x36\x2d\x36\x35\x36\x2e\x32\x38\x2d\x31\x32\x2e\ -\x36\x31\x39\x20\x31\x32\x2e\x36\x31\x39\x76\x31\x36\x6c\x31\x38\ -\x2e\x39\x32\x38\x20\x35\x2e\x30\x37\x31\x38\x76\x2d\x31\x36\x6c\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x36\x33\x22\x20\x64\x3d\x22\x6d\x31\x32\ -\x34\x33\x2d\x36\x32\x32\x2e\x35\x39\x20\x31\x32\x2e\x36\x31\x39\ -\x2d\x31\x32\x2e\x36\x31\x39\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x36\x33\x38\x2e\ -\x35\x39\x20\x31\x32\x2e\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\ -\x76\x31\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x37\x22\x20\x64\ -\x3d\x22\x6d\x31\x32\x35\x35\x2e\x36\x2d\x36\x35\x31\x2e\x32\x31\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x76\x31\ -\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x32\x32\x34\x2d\x36\x32\x37\x2e\x36\x36\x20\x31\x32\x2e\ -\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\x20\x31\x38\x2e\x39\x32\ -\x38\x20\x35\x2e\x30\x37\x31\x38\x22\x2f\x3e\x0a\x20\x20\x20\x3c\ -\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x31\ -\x22\x20\x64\x3d\x22\x6d\x31\x33\x33\x38\x2e\x31\x2d\x35\x35\x39\ -\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\ -\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\ -\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\ -\x37\x33\x22\x20\x64\x3d\x22\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\ -\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\ -\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\ -\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x37\x37\x22\x20\x64\x3d\x22\x6d\x31\ -\x33\x35\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\ -\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\ -\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x31\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x36\x36\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x20\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3d\x22\ -\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\x69\x6c\x6c\x2d\x6f\x70\ -\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\x37\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\ -\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x31\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x32\x30\x22\x20\x64\x3d\x22\x6d\x31\x33\x38\x36\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x36\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x32\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x32\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x20\x66\x69\x6c\x6c\x2d\ -\x72\x75\x6c\x65\x3d\x22\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\ -\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\ -\x36\x36\x37\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\ -\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\ -\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\ -\x6c\x3d\x22\x23\x30\x30\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\ -\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x34\x34\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x38\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x38\x30\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x30\x22\x20\ -\x64\x3d\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x35\x36\x2e\x34\ -\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\ -\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\ -\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x34\x34\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x30\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x30\x22\x20\x66\x69\x6c\ -\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\ -\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x39\x34\x2e\x32\x2d\x35\x35\x30\x2e\x34\x36\ -\x20\x30\x2e\x30\x30\x31\x2d\x35\x2e\x38\x36\x36\x36\x20\x32\x2e\ -\x36\x35\x32\x31\x2d\x32\x2e\x39\x37\x30\x35\x63\x31\x2e\x34\x35\ -\x38\x37\x2d\x31\x2e\x36\x33\x33\x38\x20\x32\x2e\x36\x37\x38\x37\ -\x2d\x32\x2e\x39\x39\x38\x31\x20\x32\x2e\x37\x31\x31\x32\x2d\x33\ -\x2e\x30\x33\x31\x39\x20\x30\x2e\x30\x33\x35\x2d\x30\x2e\x30\x33\ -\x36\x38\x20\x30\x2e\x30\x35\x39\x20\x32\x2e\x31\x37\x30\x39\x20\ -\x30\x2e\x30\x35\x39\x20\x35\x2e\x35\x38\x35\x39\x76\x35\x2e\x36\ -\x34\x37\x32\x6c\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\ -\x31\x34\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\x31\x34\ -\x76\x2d\x35\x2e\x38\x36\x36\x38\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\ -\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\ -\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\ -\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ -\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x34\x38\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x39\ -\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\ -\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\ -\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x34\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x34\x30\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\ -\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\ -\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\ -\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x31\x34\x2d\x35\x36\x33\x2e\x35\ -\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x39\x30\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x37\x2e\x37\x2d\x35\ -\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\ -\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x30\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x30\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\ -\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\ -\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x30\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x31\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\ -\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x32\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x35\x32\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x36\x35\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\ -\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\ -\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\ -\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x31\x36\x22\x20\x64\x3d\x22\x6d\x31\x34\x37\x32\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x31\x38\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\ -\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\ -\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\ -\x67\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x32\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x36\x2e\x39\x2d\x35\x36\x36\ -\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\ -\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x36\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x37\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\ -\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\x2e\x31\x2d\x35\x35\x39\x2e\ -\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\ -\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\ -\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x33\ -\x30\x22\x20\x64\x3d\x22\x6d\x31\x35\x32\x31\x2e\x37\x2d\x35\x35\ -\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\ -\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\ -\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x35\ -\x32\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x35\x33\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x35\x32\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\ -\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x3c\ -\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ -\x00\x00\x0f\x7d\ -\x3c\ -\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ -\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ -\x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ -\x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ -\x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ -\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ -\x0a\x3c\x73\x76\x67\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x64\ -\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\ -\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\x6e\x74\x73\x2f\x31\ -\x2e\x31\x2f\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\ -\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\ -\x65\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\ -\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\ -\x67\x2f\x31\x39\x39\x39\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\ -\x2d\x73\x79\x6e\x74\x61\x78\x2d\x6e\x73\x23\x22\x0a\x20\x20\x20\ -\x78\x6d\x6c\x6e\x73\x3a\x73\x76\x67\x3d\x22\x68\x74\x74\x70\x3a\ -\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x32\x30\x30\ -\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3d\ -\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\ -\x72\x67\x2f\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x0a\x20\x20\x20\ -\x78\x6d\x6c\x6e\x73\x3a\x73\x6f\x64\x69\x70\x6f\x64\x69\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2e\ -\x73\x6f\x75\x72\x63\x65\x66\x6f\x72\x67\x65\x2e\x6e\x65\x74\x2f\ -\x44\x54\x44\x2f\x73\x6f\x64\x69\x70\x6f\x64\x69\x2d\x30\x2e\x64\ -\x74\x64\x22\x0a\x20\x20\x20\x78\x6d\x6c\x6e\x73\x3a\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\ -\x77\x2e\x69\x6e\x6b\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x6e\ -\x61\x6d\x65\x73\x70\x61\x63\x65\x73\x2f\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x22\x0a\x20\x20\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x36\ -\x2e\x37\x33\x31\x31\x31\x35\x6d\x6d\x22\x0a\x20\x20\x20\x68\x65\ -\x69\x67\x68\x74\x3d\x22\x32\x34\x2e\x33\x37\x35\x35\x35\x39\x6d\ -\x6d\x22\x0a\x20\x20\x20\x76\x69\x65\x77\x42\x6f\x78\x3d\x22\x30\ -\x20\x30\x20\x39\x34\x2e\x37\x31\x36\x35\x35\x20\x38\x36\x2e\x33\ -\x37\x30\x30\x39\x22\x0a\x20\x20\x20\x69\x64\x3d\x22\x73\x76\x67\ -\x35\x34\x39\x35\x22\x0a\x20\x20\x20\x76\x65\x72\x73\x69\x6f\x6e\ -\x3d\x22\x31\x2e\x31\x22\x0a\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x3a\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x30\x2e\x39\x31\ -\x20\x72\x31\x33\x37\x32\x35\x22\x0a\x20\x20\x20\x73\x6f\x64\x69\ -\x70\x6f\x64\x69\x3a\x64\x6f\x63\x6e\x61\x6d\x65\x3d\x22\x63\x61\ -\x64\x71\x75\x65\x72\x79\x5f\x6c\x6f\x67\x6f\x5f\x64\x61\x72\x6b\ -\x2e\x73\x76\x67\x22\x3e\x0a\x20\x20\x3c\x64\x65\x66\x73\x0a\x20\ -\x20\x20\x20\x20\x69\x64\x3d\x22\x64\x65\x66\x73\x35\x34\x39\x37\ -\x22\x20\x2f\x3e\x0a\x20\x20\x3c\x73\x6f\x64\x69\x70\x6f\x64\x69\ -\x3a\x6e\x61\x6d\x65\x64\x76\x69\x65\x77\x0a\x20\x20\x20\x20\x20\ -\x69\x64\x3d\x22\x62\x61\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x70\ -\x61\x67\x65\x63\x6f\x6c\x6f\x72\x3d\x22\x23\x66\x66\x66\x66\x66\ -\x66\x22\x0a\x20\x20\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x63\x6f\ -\x6c\x6f\x72\x3d\x22\x23\x36\x36\x36\x36\x36\x36\x22\x0a\x20\x20\ -\x20\x20\x20\x62\x6f\x72\x64\x65\x72\x6f\x70\x61\x63\x69\x74\x79\ -\x3d\x22\x31\x2e\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ -\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x6f\x70\x61\x63\x69\x74\x79\ -\x3d\x22\x30\x2e\x30\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\ -\x63\x61\x70\x65\x3a\x70\x61\x67\x65\x73\x68\x61\x64\x6f\x77\x3d\ -\x22\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\ -\x65\x3a\x7a\x6f\x6f\x6d\x3d\x22\x34\x2e\x33\x37\x30\x39\x33\x36\ -\x32\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ -\x3a\x63\x78\x3d\x22\x34\x37\x2e\x33\x35\x38\x32\x37\x35\x22\x0a\ -\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x79\ -\x3d\x22\x34\x33\x2e\x31\x38\x35\x30\x34\x35\x22\x0a\x20\x20\x20\ -\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x64\x6f\x63\x75\x6d\ -\x65\x6e\x74\x2d\x75\x6e\x69\x74\x73\x3d\x22\x70\x78\x22\x0a\x20\ -\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x63\x75\x72\ -\x72\x65\x6e\x74\x2d\x6c\x61\x79\x65\x72\x3d\x22\x6c\x61\x79\x65\ -\x72\x31\x22\x0a\x20\x20\x20\x20\x20\x73\x68\x6f\x77\x67\x72\x69\ -\x64\x3d\x22\x66\x61\x6c\x73\x65\x22\x0a\x20\x20\x20\x20\x20\x66\ -\x69\x74\x2d\x6d\x61\x72\x67\x69\x6e\x2d\x74\x6f\x70\x3d\x22\x30\ -\x22\x0a\x20\x20\x20\x20\x20\x66\x69\x74\x2d\x6d\x61\x72\x67\x69\ -\x6e\x2d\x6c\x65\x66\x74\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\ -\x66\x69\x74\x2d\x6d\x61\x72\x67\x69\x6e\x2d\x72\x69\x67\x68\x74\ -\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x66\x69\x74\x2d\x6d\x61\ -\x72\x67\x69\x6e\x2d\x62\x6f\x74\x74\x6f\x6d\x3d\x22\x30\x22\x0a\ -\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\ -\x6e\x64\x6f\x77\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x38\x35\x35\ -\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ -\x77\x69\x6e\x64\x6f\x77\x2d\x68\x65\x69\x67\x68\x74\x3d\x22\x31\ -\x30\x35\x36\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x3a\x77\x69\x6e\x64\x6f\x77\x2d\x78\x3d\x22\x36\x35\x22\ -\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\ -\x69\x6e\x64\x6f\x77\x2d\x79\x3d\x22\x32\x34\x22\x0a\x20\x20\x20\ -\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\x77\x69\x6e\x64\x6f\ -\x77\x2d\x6d\x61\x78\x69\x6d\x69\x7a\x65\x64\x3d\x22\x31\x22\x20\ -\x2f\x3e\x0a\x20\x20\x3c\x6d\x65\x74\x61\x64\x61\x74\x61\x0a\x20\ -\x20\x20\x20\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\x74\x61\ -\x35\x35\x30\x30\x22\x3e\x0a\x20\x20\x20\x20\x3c\x72\x64\x66\x3a\ -\x52\x44\x46\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x63\x63\x3a\x57\ -\x6f\x72\x6b\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x72\x64\x66\ -\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\x20\ -\x20\x20\x20\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\ -\x61\x67\x65\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\ -\x66\x6f\x72\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\ -\x3c\x64\x63\x3a\x74\x79\x70\x65\x0a\x20\x20\x20\x20\x20\x20\x20\ -\x20\x20\x20\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\ -\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\ -\x67\x2f\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\ -\x69\x6c\x6c\x49\x6d\x61\x67\x65\x22\x20\x2f\x3e\x0a\x20\x20\x20\ -\x20\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x69\x74\x6c\x65\x20\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x2f\x63\x63\x3a\x57\x6f\x72\ -\x6b\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x72\x64\x66\x3a\x52\x44\x46\ -\x3e\x0a\x20\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\x3e\x0a\ -\x20\x20\x3c\x67\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\ -\x70\x65\x3a\x6c\x61\x62\x65\x6c\x3d\x22\x4c\x61\x79\x65\x72\x20\ -\x31\x22\x0a\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\ -\x3a\x67\x72\x6f\x75\x70\x6d\x6f\x64\x65\x3d\x22\x6c\x61\x79\x65\ -\x72\x22\x0a\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x6c\x61\x79\x65\ -\x72\x31\x22\x0a\x20\x20\x20\x20\x20\x74\x72\x61\x6e\x73\x66\x6f\ -\x72\x6d\x3d\x22\x74\x72\x61\x6e\x73\x6c\x61\x74\x65\x28\x2d\x32\ -\x38\x34\x2e\x30\x37\x30\x33\x2c\x2d\x34\x37\x37\x2e\x37\x34\x38\ -\x35\x39\x29\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x0a\ -\x20\x20\x20\x20\x20\x20\x20\x69\x6e\x6b\x73\x63\x61\x70\x65\x3a\ -\x63\x6f\x6e\x6e\x65\x63\x74\x6f\x72\x2d\x63\x75\x72\x76\x61\x74\ -\x75\x72\x65\x3d\x22\x30\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x73\ -\x74\x79\x6c\x65\x3d\x22\x66\x69\x6c\x6c\x3a\x23\x32\x39\x38\x30\ -\x62\x39\x3b\x66\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\ -\x31\x3b\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3a\x65\x76\x65\x6e\ -\x6f\x64\x64\x3b\x73\x74\x72\x6f\x6b\x65\x3a\x23\x32\x39\x38\x30\ -\x62\x39\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3a\ -\x33\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3a\x62\x75\x74\x74\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3a\x72\x6f\x75\x6e\x64\x3b\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x22\x0a\x20\x20\ -\x20\x20\x20\x20\x20\x64\x3d\x22\x6d\x20\x32\x38\x35\x2e\x35\x37\ -\x30\x33\x2c\x34\x37\x39\x2e\x32\x34\x38\x35\x39\x20\x39\x31\x2e\ -\x37\x31\x36\x35\x35\x2c\x30\x20\x30\x2c\x38\x33\x2e\x33\x37\x30\ -\x30\x39\x20\x2d\x39\x31\x2e\x37\x31\x36\x35\x35\x2c\x30\x20\x7a\ -\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x32\x36\x36\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x67\ -\x0a\x20\x20\x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\ -\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\x6f\x72\x6d\x61\x6c\ -\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\x74\x3a\x6e\x6f\x72\ -\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x34\x30\ -\x70\x78\x3b\x6c\x69\x6e\x65\x2d\x68\x65\x69\x67\x68\x74\x3a\x31\ -\x32\x35\x25\x3b\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\x3a\ -\x73\x61\x6e\x73\x2d\x73\x65\x72\x69\x66\x3b\x6c\x65\x74\x74\x65\ -\x72\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x77\x6f\ -\x72\x64\x2d\x73\x70\x61\x63\x69\x6e\x67\x3a\x30\x70\x78\x3b\x66\ -\x69\x6c\x6c\x3a\x23\x30\x30\x30\x30\x30\x30\x3b\x66\x69\x6c\x6c\ -\x2d\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x3b\x73\x74\x72\x6f\x6b\ -\x65\x3a\x6e\x6f\x6e\x65\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3a\x31\x70\x78\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ -\x69\x6e\x65\x63\x61\x70\x3a\x62\x75\x74\x74\x3b\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3a\x6d\x69\x74\x65\ -\x72\x3b\x73\x74\x72\x6f\x6b\x65\x2d\x6f\x70\x61\x63\x69\x74\x79\ -\x3a\x31\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\x22\x74\ -\x65\x78\x74\x34\x38\x37\x33\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x64\ -\x3d\x22\x6d\x20\x33\x31\x33\x2e\x34\x33\x32\x39\x38\x2c\x35\x32\ -\x39\x2e\x33\x37\x37\x30\x31\x20\x71\x20\x32\x2e\x37\x33\x34\x33\ -\x38\x2c\x30\x20\x34\x2e\x34\x34\x33\x33\x36\x2c\x2d\x31\x2e\x35\ -\x30\x33\x39\x20\x31\x2e\x37\x30\x38\x39\x39\x2c\x2d\x31\x2e\x35\ -\x30\x33\x39\x31\x20\x31\x2e\x37\x37\x37\x33\x35\x2c\x2d\x33\x2e\ -\x39\x39\x39\x30\x33\x20\x6c\x20\x39\x2e\x32\x36\x32\x36\x39\x2c\ -\x30\x20\x71\x20\x2d\x30\x2e\x30\x33\x34\x32\x2c\x33\x2e\x37\x35\ -\x39\x37\x37\x20\x2d\x32\x2e\x30\x35\x30\x37\x38\x2c\x36\x2e\x39\ -\x30\x34\x33\x20\x2d\x32\x2e\x30\x31\x36\x36\x2c\x33\x2e\x31\x31\ -\x30\x33\x35\x20\x2d\x35\x2e\x35\x33\x37\x31\x31\x2c\x34\x2e\x38\ -\x35\x33\x35\x32\x20\x2d\x33\x2e\x34\x38\x36\x33\x33\x2c\x31\x2e\ -\x37\x30\x38\x39\x38\x20\x2d\x37\x2e\x37\x32\x34\x36\x31\x2c\x31\ -\x2e\x37\x30\x38\x39\x38\x20\x2d\x37\x2e\x39\x32\x39\x36\x39\x2c\ -\x30\x20\x2d\x31\x32\x2e\x35\x30\x39\x37\x36\x2c\x2d\x35\x2e\x30\ -\x32\x34\x34\x31\x20\x2d\x34\x2e\x35\x38\x30\x30\x38\x2c\x2d\x35\ -\x2e\x30\x35\x38\x36\x20\x2d\x34\x2e\x35\x38\x30\x30\x38\x2c\x2d\ -\x31\x33\x2e\x39\x34\x35\x33\x32\x20\x6c\x20\x30\x2c\x2d\x30\x2e\ -\x36\x34\x39\x34\x31\x20\x71\x20\x30\x2c\x2d\x38\x2e\x35\x34\x34\ -\x39\x32\x20\x34\x2e\x35\x34\x35\x39\x2c\x2d\x31\x33\x2e\x36\x33\ -\x37\x36\x39\x20\x34\x2e\x35\x34\x35\x38\x39\x2c\x2d\x35\x2e\x30\ -\x39\x32\x37\x38\x20\x31\x32\x2e\x34\x37\x35\x35\x38\x2c\x2d\x35\ -\x2e\x30\x39\x32\x37\x38\x20\x36\x2e\x39\x33\x38\x34\x38\x2c\x30\ -\x20\x31\x31\x2e\x31\x30\x38\x34\x2c\x33\x2e\x39\x36\x34\x38\x35\ -\x20\x34\x2e\x32\x30\x34\x31\x2c\x33\x2e\x39\x33\x30\x36\x36\x20\ -\x34\x2e\x32\x37\x32\x34\x36\x2c\x31\x30\x2e\x34\x39\x33\x31\x36\ -\x20\x6c\x20\x2d\x39\x2e\x32\x36\x32\x36\x39\x2c\x30\x20\x71\x20\ -\x2d\x30\x2e\x30\x36\x38\x34\x2c\x2d\x32\x2e\x38\x37\x31\x30\x39\ -\x20\x2d\x31\x2e\x37\x37\x37\x33\x35\x2c\x2d\x34\x2e\x36\x34\x38\ -\x34\x34\x20\x2d\x31\x2e\x37\x30\x38\x39\x38\x2c\x2d\x31\x2e\x38\ -\x31\x31\x35\x32\x20\x2d\x34\x2e\x35\x31\x31\x37\x32\x2c\x2d\x31\ -\x2e\x38\x31\x31\x35\x32\x20\x2d\x33\x2e\x34\x35\x32\x31\x34\x2c\ -\x30\x20\x2d\x35\x2e\x32\x32\x39\x34\x39\x2c\x32\x2e\x35\x32\x39\ -\x33\x20\x2d\x31\x2e\x37\x34\x33\x31\x36\x2c\x32\x2e\x34\x39\x35\ -\x31\x31\x20\x2d\x31\x2e\x37\x34\x33\x31\x36\x2c\x38\x2e\x31\x33\ -\x34\x37\x36\x20\x6c\x20\x30\x2c\x31\x2e\x30\x32\x35\x33\x39\x20\ -\x71\x20\x30\x2c\x35\x2e\x37\x30\x38\x30\x31\x20\x31\x2e\x37\x34\ -\x33\x31\x36\x2c\x38\x2e\x32\x30\x33\x31\x33\x20\x31\x2e\x37\x34\ -\x33\x31\x37\x2c\x32\x2e\x34\x39\x35\x31\x31\x20\x35\x2e\x32\x39\ -\x37\x38\x35\x2c\x32\x2e\x34\x39\x35\x31\x31\x20\x7a\x22\x0a\x20\ -\x20\x20\x20\x20\x20\x20\x20\x20\x73\x74\x79\x6c\x65\x3d\x22\x66\ -\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\x3a\x6e\x6f\x72\x6d\x61\x6c\ -\x3b\x66\x6f\x6e\x74\x2d\x76\x61\x72\x69\x61\x6e\x74\x3a\x6e\x6f\ -\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x77\x65\x69\x67\x68\x74\ -\x3a\x62\x6f\x6c\x64\x3b\x66\x6f\x6e\x74\x2d\x73\x74\x72\x65\x74\ -\x63\x68\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x73\ -\x69\x7a\x65\x3a\x37\x30\x70\x78\x3b\x66\x6f\x6e\x74\x2d\x66\x61\ -\x6d\x69\x6c\x79\x3a\x52\x6f\x62\x6f\x74\x6f\x3b\x2d\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2d\x66\x6f\x6e\x74\x2d\x73\x70\x65\x63\x69\ -\x66\x69\x63\x61\x74\x69\x6f\x6e\x3a\x27\x52\x6f\x62\x6f\x74\x6f\ -\x20\x42\x6f\x6c\x64\x27\x3b\x66\x69\x6c\x6c\x3a\x23\x66\x66\x66\ -\x66\x66\x66\x3b\x66\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\ -\x3a\x31\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x34\x31\x22\x20\x2f\x3e\x0a\x20\x20\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x0a\x20\x20\x20\x20\x20\x20\ -\x20\x20\x20\x64\x3d\x22\x6d\x20\x33\x33\x33\x2e\x30\x31\x37\x39\ -\x34\x2c\x35\x31\x37\x2e\x38\x32\x34\x32\x38\x20\x71\x20\x30\x2c\ -\x2d\x38\x2e\x37\x31\x35\x38\x32\x20\x33\x2e\x38\x36\x32\x33\x31\ -\x2c\x2d\x31\x33\x2e\x37\x37\x34\x34\x31\x20\x33\x2e\x38\x39\x36\ -\x34\x38\x2c\x2d\x35\x2e\x30\x35\x38\x36\x20\x31\x30\x2e\x36\x36\ -\x34\x30\x36\x2c\x2d\x35\x2e\x30\x35\x38\x36\x20\x35\x2e\x39\x34\ -\x37\x32\x37\x2c\x30\x20\x39\x2e\x34\x36\x37\x37\x37\x2c\x34\x2e\ -\x35\x34\x35\x39\x20\x6c\x20\x30\x2e\x36\x34\x39\x34\x32\x2c\x2d\ -\x33\x2e\x38\x36\x32\x33\x20\x38\x2e\x36\x38\x31\x36\x34\x2c\x30\ -\x20\x30\x2c\x35\x31\x2e\x32\x30\x31\x31\x37\x20\x2d\x39\x2e\x39\ -\x31\x32\x31\x31\x2c\x30\x20\x30\x2c\x2d\x31\x37\x2e\x33\x39\x37\ -\x34\x36\x20\x71\x20\x2d\x33\x2e\x34\x31\x37\x39\x37\x2c\x33\x2e\ -\x38\x36\x32\x33\x20\x2d\x38\x2e\x39\x35\x35\x30\x38\x2c\x33\x2e\ -\x38\x36\x32\x33\x20\x2d\x36\x2e\x35\x39\x36\x36\x38\x2c\x30\x20\ -\x2d\x31\x30\x2e\x35\x32\x37\x33\x34\x2c\x2d\x35\x2e\x31\x32\x36\ -\x39\x35\x20\x2d\x33\x2e\x39\x33\x30\x36\x37\x2c\x2d\x35\x2e\x31\ -\x32\x36\x39\x35\x20\x2d\x33\x2e\x39\x33\x30\x36\x37\x2c\x2d\x31\ -\x34\x2e\x33\x38\x39\x36\x35\x20\x7a\x20\x6d\x20\x39\x2e\x38\x37\ -\x37\x39\x33\x2c\x30\x2e\x37\x31\x37\x37\x37\x20\x71\x20\x30\x2c\ -\x35\x2e\x32\x39\x37\x38\x35\x20\x31\x2e\x38\x34\x35\x37\x31\x2c\ -\x38\x2e\x30\x36\x36\x34\x31\x20\x31\x2e\x38\x37\x39\x38\x38\x2c\ -\x32\x2e\x37\x36\x38\x35\x35\x20\x35\x2e\x32\x36\x33\x36\x37\x2c\ -\x32\x2e\x37\x36\x38\x35\x35\x20\x34\x2e\x35\x34\x35\x39\x2c\x30\ -\x20\x36\x2e\x34\x32\x35\x37\x38\x2c\x2d\x33\x2e\x36\x32\x33\x30\ -\x34\x20\x6c\x20\x30\x2c\x2d\x31\x35\x2e\x32\x37\x38\x33\x32\x20\ -\x71\x20\x2d\x31\x2e\x38\x34\x35\x37\x2c\x2d\x33\x2e\x34\x38\x36\ -\x33\x33\x20\x2d\x36\x2e\x33\x35\x37\x34\x32\x2c\x2d\x33\x2e\x34\ -\x38\x36\x33\x33\x20\x2d\x33\x2e\x34\x31\x37\x39\x37\x2c\x30\x20\ -\x2d\x35\x2e\x32\x39\x37\x38\x35\x2c\x32\x2e\x37\x36\x38\x35\x35\ -\x20\x2d\x31\x2e\x38\x37\x39\x38\x39\x2c\x32\x2e\x37\x36\x38\x35\ -\x36\x20\x2d\x31\x2e\x38\x37\x39\x38\x39\x2c\x38\x2e\x37\x38\x34\ -\x31\x38\x20\x7a\x22\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x73\ -\x74\x79\x6c\x65\x3d\x22\x66\x6f\x6e\x74\x2d\x73\x74\x79\x6c\x65\ -\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\x2d\x76\x61\x72\ -\x69\x61\x6e\x74\x3a\x6e\x6f\x72\x6d\x61\x6c\x3b\x66\x6f\x6e\x74\ -\x2d\x77\x65\x69\x67\x68\x74\x3a\x62\x6f\x6c\x64\x3b\x66\x6f\x6e\ -\x74\x2d\x73\x74\x72\x65\x74\x63\x68\x3a\x6e\x6f\x72\x6d\x61\x6c\ -\x3b\x66\x6f\x6e\x74\x2d\x73\x69\x7a\x65\x3a\x37\x30\x70\x78\x3b\ -\x66\x6f\x6e\x74\x2d\x66\x61\x6d\x69\x6c\x79\x3a\x52\x6f\x62\x6f\ -\x74\x6f\x3b\x2d\x69\x6e\x6b\x73\x63\x61\x70\x65\x2d\x66\x6f\x6e\ -\x74\x2d\x73\x70\x65\x63\x69\x66\x69\x63\x61\x74\x69\x6f\x6e\x3a\ -\x27\x52\x6f\x62\x6f\x74\x6f\x20\x42\x6f\x6c\x64\x27\x3b\x66\x69\ -\x6c\x6c\x3a\x23\x66\x66\x66\x66\x66\x66\x3b\x66\x69\x6c\x6c\x2d\ -\x6f\x70\x61\x63\x69\x74\x79\x3a\x31\x22\x0a\x20\x20\x20\x20\x20\ -\x20\x20\x20\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x34\x33\ -\x22\x20\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\ -\x3c\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ -\x00\x00\x4e\x4c\ -\x3c\ -\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ -\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ -\x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ -\x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ -\x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ -\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ -\x3c\x73\x76\x67\x20\x69\x64\x3d\x22\x73\x76\x67\x32\x22\x20\x78\ -\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\ -\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\x39\ -\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\x2d\x73\x79\x6e\x74\x61\ -\x78\x2d\x6e\x73\x23\x22\x20\x78\x6d\x6c\x6e\x73\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x68\x65\x69\x67\x68\x74\ -\x3d\x22\x32\x33\x2e\x39\x39\x34\x22\x20\x77\x69\x64\x74\x68\x3d\ -\x22\x32\x30\x2e\x39\x36\x31\x22\x20\x76\x65\x72\x73\x69\x6f\x6e\ -\x3d\x22\x31\x2e\x31\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\x3d\ -\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\x65\ -\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\x22\ -\x20\x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x31\x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x76\x69\x65\x77\ -\x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x30\x2e\x39\x36\x30\x37\ -\x38\x32\x20\x32\x33\x2e\x39\x39\x33\x35\x39\x31\x22\x20\x78\x6d\ -\x6c\x6e\x73\x3a\x64\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\ -\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\ -\x6e\x74\x73\x2f\x31\x2e\x31\x2f\x22\x3e\x0a\x20\x3c\x6d\x65\x74\ -\x61\x64\x61\x74\x61\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ -\x74\x61\x37\x22\x3e\x0a\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\ -\x3e\x0a\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x20\x72\x64\ -\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\ -\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\ -\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\ -\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ -\x65\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\ -\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\ -\x6c\x49\x6d\x61\x67\x65\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x64\ -\x63\x3a\x74\x69\x74\x6c\x65\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x63\ -\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x3c\x2f\x72\x64\x66\x3a\ -\x52\x44\x46\x3e\x0a\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ -\x3e\x0a\x20\x3c\x67\x20\x69\x64\x3d\x22\x6c\x61\x79\x65\x72\x31\ -\x22\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x74\x72\x61\ -\x6e\x73\x6c\x61\x74\x65\x28\x2d\x31\x34\x37\x39\x2e\x36\x20\x35\ -\x36\x36\x2e\x38\x34\x29\x22\x3e\x0a\x20\x20\x3c\x67\x20\x66\x69\ -\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\ -\x36\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x3e\ -\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x33\x36\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\ -\x2e\x33\x2d\x35\x35\x33\x2e\x32\x39\x63\x30\x2d\x34\x2e\x33\x34\ -\x33\x31\x20\x30\x2e\x30\x31\x31\x2d\x35\x2e\x34\x32\x34\x33\x20\ -\x30\x2e\x30\x36\x2d\x35\x2e\x34\x32\x34\x33\x20\x30\x2e\x30\x36\ -\x31\x20\x30\x20\x38\x2e\x33\x34\x31\x39\x20\x31\x2e\x38\x31\x33\ -\x32\x20\x38\x2e\x33\x35\x35\x39\x20\x31\x2e\x38\x32\x39\x37\x20\ -\x30\x20\x30\x20\x30\x2e\x30\x32\x34\x20\x30\x2e\x36\x32\x30\x34\ -\x33\x20\x30\x2e\x30\x34\x32\x20\x31\x2e\x33\x36\x37\x33\x6c\x30\ -\x2e\x30\x33\x34\x20\x31\x2e\x33\x35\x37\x39\x2d\x34\x2e\x32\x34\ -\x35\x38\x20\x33\x2e\x31\x34\x36\x39\x2d\x34\x2e\x32\x34\x35\x39\ -\x20\x33\x2e\x31\x34\x36\x39\x76\x2d\x35\x2e\x34\x32\x34\x33\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x35\x33\x38\x22\x20\x64\x3d\x22\x6d\x31\ -\x35\x31\x32\x2e\x38\x2d\x35\x35\x38\x2e\x36\x34\x63\x2d\x32\x2e\ -\x31\x37\x39\x34\x2d\x30\x2e\x34\x36\x37\x31\x33\x2d\x33\x2e\x39\ -\x39\x35\x32\x2d\x30\x2e\x38\x35\x36\x31\x33\x2d\x34\x2e\x30\x33\ -\x35\x2d\x30\x2e\x38\x36\x34\x35\x35\x2d\x30\x2e\x30\x33\x39\x2d\ -\x30\x2e\x30\x31\x30\x37\x20\x31\x2e\x37\x32\x39\x34\x2d\x31\x2e\ -\x33\x38\x32\x39\x20\x33\x2e\x39\x33\x31\x34\x2d\x33\x2e\x30\x35\ -\x34\x36\x20\x32\x2e\x32\x30\x32\x32\x2d\x31\x2e\x36\x37\x31\x36\ -\x20\x34\x2e\x30\x31\x31\x39\x2d\x33\x2e\x30\x33\x31\x36\x20\x34\ -\x2e\x30\x32\x31\x36\x2d\x33\x2e\x30\x32\x32\x32\x20\x30\x2e\x30\ -\x32\x31\x20\x30\x2e\x30\x31\x39\x32\x20\x30\x2e\x31\x36\x39\x31\ -\x20\x36\x2e\x33\x37\x38\x37\x20\x30\x2e\x31\x36\x39\x34\x20\x37\ -\x2e\x32\x34\x31\x31\x20\x30\x2e\x30\x30\x30\x32\x20\x30\x2e\x34\ -\x31\x38\x38\x39\x2d\x30\x2e\x30\x31\x34\x20\x30\x2e\x35\x35\x38\ -\x34\x37\x2d\x30\x2e\x30\x36\x32\x20\x30\x2e\x35\x35\x34\x36\x34\ -\x2d\x30\x2e\x30\x33\x35\x20\x30\x2d\x31\x2e\x38\x34\x35\x36\x2d\ -\x30\x2e\x33\x38\x37\x33\x31\x2d\x34\x2e\x30\x32\x35\x33\x2d\x30\ -\x2e\x38\x35\x34\x34\x33\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x30\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x35\x39\x2e\x34\x2d\x35\x34\x35\ -\x2e\x34\x33\x63\x2d\x33\x2e\x33\x32\x36\x32\x2d\x30\x2e\x39\x32\ -\x33\x32\x33\x2d\x36\x2e\x31\x37\x37\x38\x2d\x31\x2e\x37\x31\x33\ -\x33\x2d\x36\x2e\x33\x33\x36\x38\x2d\x31\x2e\x37\x35\x35\x37\x2d\ -\x30\x2e\x32\x37\x38\x31\x2d\x30\x2e\x30\x37\x34\x34\x2d\x30\x2e\ -\x31\x32\x30\x39\x2d\x30\x2e\x32\x30\x32\x37\x39\x20\x34\x2e\x30\ -\x31\x35\x31\x2d\x33\x2e\x32\x38\x38\x37\x20\x32\x2e\x33\x36\x37\ -\x36\x2d\x31\x2e\x37\x36\x36\x35\x20\x34\x2e\x33\x37\x30\x31\x2d\ -\x33\x2e\x32\x30\x35\x39\x20\x34\x2e\x34\x35\x30\x32\x2d\x33\x2e\ -\x31\x39\x38\x35\x20\x30\x2e\x30\x38\x20\x30\x2e\x30\x31\x30\x38\ -\x20\x31\x2e\x30\x33\x33\x34\x20\x30\x2e\x32\x37\x35\x34\x32\x20\ -\x32\x2e\x31\x31\x38\x38\x20\x30\x2e\x35\x39\x35\x38\x37\x20\x31\ -\x2e\x30\x38\x35\x34\x20\x30\x2e\x33\x32\x30\x35\x37\x20\x31\x2e\ -\x39\x38\x38\x39\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x32\x2e\x30\ -\x30\x37\x38\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x30\x2e\x30\x31\ -\x39\x20\x30\x20\x30\x2e\x30\x33\x35\x20\x31\x2e\x39\x36\x39\x39\ -\x20\x30\x2e\x30\x33\x35\x20\x34\x2e\x33\x37\x37\x35\x20\x30\x20\ -\x33\x2e\x34\x34\x31\x31\x2d\x30\x2e\x30\x32\x36\x20\x34\x2e\x33\ -\x37\x36\x33\x2d\x30\x2e\x31\x32\x30\x39\x20\x34\x2e\x33\x37\x31\ -\x35\x2d\x30\x2e\x30\x36\x36\x20\x30\x2d\x32\x2e\x38\x34\x32\x34\ -\x2d\x30\x2e\x37\x36\x31\x32\x37\x2d\x36\x2e\x31\x36\x38\x35\x2d\ -\x31\x2e\x36\x38\x34\x36\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x32\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\x2e\x39\x2d\x35\x34\x38\ -\x2e\x30\x39\x63\x30\x2d\x32\x2e\x31\x37\x33\x35\x20\x30\x2e\x30\ -\x32\x2d\x33\x2e\x39\x35\x31\x38\x20\x30\x2e\x30\x34\x37\x2d\x33\ -\x2e\x39\x35\x31\x38\x20\x30\x2e\x31\x30\x36\x31\x20\x30\x20\x35\ -\x2e\x32\x33\x37\x20\x31\x2e\x35\x30\x34\x31\x20\x35\x2e\x32\x38\ -\x32\x36\x20\x31\x2e\x35\x34\x38\x37\x20\x30\x2e\x30\x33\x35\x20\ -\x30\x2e\x30\x33\x35\x2d\x34\x2e\x34\x39\x35\x20\x35\x2e\x34\x34\ -\x35\x32\x2d\x35\x2e\x32\x34\x32\x20\x36\x2e\x32\x35\x39\x33\x2d\ -\x30\x2e\x30\x34\x38\x20\x30\x2e\x30\x35\x33\x2d\x30\x2e\x30\x38\ -\x38\x2d\x31\x2e\x36\x36\x39\x35\x2d\x30\x2e\x30\x38\x38\x2d\x33\ -\x2e\x38\x35\x36\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\x35\x35\x33\x2e\ -\x38\x2d\x31\x2e\x37\x38\x30\x33\x2d\x30\x2e\x35\x33\x32\x39\x76\ -\x2d\x31\x2e\x31\x37\x38\x37\x63\x30\x2d\x31\x2e\x31\x36\x31\x37\ -\x20\x30\x2d\x31\x2e\x31\x37\x38\x20\x30\x2e\x32\x30\x35\x34\x2d\ -\x31\x2e\x31\x32\x35\x32\x20\x30\x2e\x31\x31\x32\x38\x20\x30\x2e\ -\x30\x32\x39\x39\x20\x30\x2e\x39\x34\x36\x20\x30\x2e\x32\x31\x35\ -\x38\x38\x20\x31\x2e\x38\x35\x31\x36\x20\x30\x2e\x34\x31\x33\x39\ -\x31\x6c\x31\x2e\x36\x34\x36\x31\x20\x30\x2e\x33\x36\x30\x32\x39\ -\x76\x31\x2e\x33\x30\x36\x33\x63\x30\x20\x30\x2e\x37\x31\x38\x34\ -\x36\x2d\x30\x2e\x30\x33\x32\x20\x31\x2e\x33\x30\x32\x34\x2d\x30\ -\x2e\x30\x37\x32\x20\x31\x2e\x32\x39\x37\x38\x2d\x30\x2e\x30\x33\ -\x39\x20\x30\x2d\x30\x2e\x38\x37\x32\x33\x2d\x30\x2e\x32\x34\x38\ -\x33\x32\x2d\x31\x2e\x38\x35\x31\x36\x2d\x30\x2e\x35\x34\x31\x35\ -\x32\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x31\x30\x2e\x38\x2d\x35\x35\x32\x2e\x31\x38\x2d\x32\ -\x2e\x36\x38\x31\x31\x2d\x30\x2e\x37\x38\x35\x33\x34\x76\x2d\x31\ -\x2e\x36\x35\x39\x33\x2d\x31\x2e\x36\x35\x39\x33\x6c\x32\x2e\x36\ -\x31\x37\x32\x2d\x32\x2e\x38\x38\x36\x33\x63\x31\x2e\x34\x33\x39\ -\x34\x2d\x31\x2e\x35\x38\x37\x35\x20\x32\x2e\x36\x37\x37\x34\x2d\ -\x32\x2e\x39\x34\x36\x38\x20\x32\x2e\x37\x35\x30\x39\x2d\x33\x2e\ -\x30\x32\x30\x36\x20\x30\x2e\x31\x31\x36\x32\x2d\x30\x2e\x31\x31\ -\x36\x36\x34\x20\x30\x2e\x31\x33\x33\x38\x20\x30\x2e\x35\x38\x33\ -\x37\x39\x20\x30\x2e\x31\x33\x33\x38\x20\x35\x2e\x33\x33\x39\x39\ -\x20\x30\x20\x33\x2e\x30\x31\x30\x38\x20\x30\x2e\x31\x30\x30\x33\ -\x20\x35\x2e\x35\x30\x32\x34\x20\x30\x2e\x30\x36\x31\x20\x35\x2e\ -\x34\x39\x37\x36\x2d\x30\x2e\x30\x33\x39\x20\x30\x2d\x31\x2e\x34\ -\x30\x38\x2d\x30\x2e\x33\x39\x34\x36\x34\x2d\x32\x2e\x38\x38\x32\ -\x34\x2d\x30\x2e\x38\x32\x36\x35\x39\x7a\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x39\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\ -\x35\x35\x37\x2e\x31\x34\x2d\x31\x2e\x37\x31\x34\x37\x2d\x30\x2e\ -\x33\x39\x33\x38\x33\x2d\x30\x2e\x30\x35\x38\x2d\x32\x2e\x32\x32\ -\x36\x34\x63\x2d\x30\x2e\x30\x39\x36\x2d\x33\x2e\x37\x34\x33\x32\ -\x2d\x30\x2e\x32\x31\x38\x33\x2d\x35\x2e\x39\x33\x31\x39\x2d\x30\ -\x2e\x31\x31\x34\x37\x2d\x35\x2e\x39\x33\x31\x39\x20\x30\x2e\x31\ -\x33\x35\x20\x30\x20\x39\x2e\x34\x39\x39\x35\x20\x32\x2e\x32\x35\ -\x31\x39\x20\x39\x2e\x37\x30\x33\x31\x20\x32\x2e\x33\x33\x36\x37\ -\x20\x30\x2e\x31\x34\x32\x35\x20\x30\x2e\x30\x35\x39\x34\x2d\x30\ -\x2e\x32\x39\x37\x33\x20\x30\x2e\x35\x39\x35\x36\x39\x2d\x32\x2e\ -\x37\x32\x35\x32\x20\x33\x2e\x33\x32\x35\x31\x2d\x32\x2e\x33\x31\ -\x31\x39\x20\x32\x2e\x35\x39\x39\x2d\x32\x2e\x39\x34\x33\x32\x20\ -\x33\x2e\x32\x35\x37\x34\x2d\x33\x2e\x31\x33\x35\x39\x20\x33\x2e\ -\x32\x36\x39\x32\x2d\x30\x2e\x31\x33\x32\x36\x20\x30\x2e\x30\x31\ -\x30\x34\x2d\x31\x2e\x30\x31\x32\x38\x2d\x30\x2e\x31\x36\x32\x32\ -\x35\x2d\x31\x2e\x39\x35\x36\x2d\x30\x2e\x33\x37\x38\x38\x32\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x67\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\ -\x35\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x36\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x32\ -\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\ -\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\ -\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x34\x39\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x33\ -\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\ -\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x39\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x30\x2e\x38\x35\x39\x20\x33\x2e\x30\x33\x30\ -\x34\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x32\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x38\x2e\x39\x2d\ -\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\ -\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\ -\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ -\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x32\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\ -\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\ -\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x33\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\ -\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x34\x31\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x34\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\ -\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\ -\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x35\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\ -\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x37\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x36\x2e\x39\x2d\x35\x36\x36\x2e\ -\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\ -\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x38\x31\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x37\x2e\x32\x2d\x35\x35\x33\x2e\ -\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x3e\x0a\ -\x20\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x30\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x35\ -\x36\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\ -\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\ -\x37\x33\x32\x2e\x31\x2d\x35\x30\x37\x2e\x36\x34\x20\x31\x33\x38\ -\x2e\x35\x36\x2d\x38\x30\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\ -\x2d\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x2d\x31\x33\x38\x2e\x35\ -\x36\x2d\x38\x30\x76\x31\x36\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x35\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x37\x33\x32\x2e\x31\x2d\x33\x34\x37\x2e\x36\x34\x20\ -\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x38\x37\x30\x2e\x36\x2d\x32\x36\x37\x2e\x36\x34\x20\x31\x33\ -\x38\x2e\x35\x36\x2d\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x32\x36\x32\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x35\x38\x37\ -\x2e\x36\x34\x76\x31\x36\x30\x6c\x2d\x31\x33\x38\x2e\x35\x36\x20\ -\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x34\x22\x20\ -\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x34\x32\x37\x2e\x36\ -\x34\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x36\x36\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x2d\x38\x30\x20\x38\x30\ -\x20\x38\x30\x20\x38\x30\x20\x38\x30\x2d\x38\x30\x7a\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x37\x30\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x37\x32\x37\x2e\x36\x34\x76\x38\x30\x6c\x38\x30\ -\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x32\x37\x32\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x36\x34\ -\x37\x2e\x36\x34\x2d\x38\x30\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x37\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x76\x38\x30\x6c\x2d\ -\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x37\ -\x36\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x38\x30\x37\x2e\ -\x36\x34\x20\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x30\x22\x20\x64\x3d\x22\x6d\x32\x32\x35\x32\x2e\x39\ -\x2d\x39\x36\x37\x2e\x36\x34\x2d\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x76\x31\x36\x30\x6c\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x38\x32\x22\x20\x64\x3d\ -\x22\x6d\x32\x30\x38\x38\x2e\x31\x2d\x39\x30\x37\x2e\x36\x34\x2d\ -\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\ -\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x39\x32\x33\x2e\x32\x2d\x39\x36\x37\x2e\x36\x34\x76\x31\x36\x30\ -\x6c\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x32\x38\x36\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\ -\x2e\x31\x2d\x31\x30\x32\x37\x2e\x36\x76\x31\x36\x30\x6c\x2d\x31\ -\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x38\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\x2e\x31\ -\x2d\x38\x36\x37\x2e\x36\x34\x20\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x3c\x67\x20\x73\ -\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\ -\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x33\x32\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x31\x38\x38\x2e\x31\x2d\x33\x34\x31\x2e\x36\x37\x20\x31\x35\ -\x33\x2e\x33\x31\x2d\x37\x31\x2e\x34\x38\x38\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x2d\x31\x35\x33\x2e\x33\x31\ -\x20\x37\x31\x2e\x34\x38\x38\x2d\x31\x35\x33\x2e\x33\x31\x2d\x38\ -\x38\x2e\x35\x31\x32\x76\x31\x36\x30\x6c\x31\x35\x33\x2e\x33\x31\ -\x20\x38\x38\x2e\x35\x31\x32\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x39\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\x33\x31\ -\x2d\x37\x31\x2e\x34\x38\x38\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x34\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x34\x31\x33\x2e\x31\x36\x76\x31\x36\x30\x6c\x2d\ -\x31\x35\x33\x2e\x33\x31\x20\x37\x31\x2e\x34\x38\x38\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x32\x36\x22\x20\x64\x3d\x22\x6d\x31\x33\ -\x34\x31\x2e\x34\x2d\x32\x35\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\ -\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x20\x69\x64\ -\x3d\x22\x69\x6d\x61\x67\x65\x34\x33\x33\x36\x22\x20\x73\x74\x79\ -\x6c\x65\x3d\x22\x69\x6d\x61\x67\x65\x2d\x72\x65\x6e\x64\x65\x72\ -\x69\x6e\x67\x3a\x6f\x70\x74\x69\x6d\x69\x7a\x65\x53\x70\x65\x65\ -\x64\x22\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\ -\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\ -\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\ -\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x52\x38\ -\x41\x41\x41\x41\x70\x43\x41\x59\x41\x41\x41\x41\x4d\x41\x79\x31\ -\x4a\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\ -\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x48\x69\x68\x4a\x52\x45\x46\ -\x55\x20\x65\x4a\x7a\x74\x6e\x58\x64\x34\x56\x46\x58\x36\x78\x7a\ -\x2f\x54\x61\x7a\x4b\x54\x6d\x55\x6b\x6a\x6a\x59\x54\x51\x51\x69\ -\x67\x4b\x32\x43\x6c\x57\x31\x72\x35\x59\x31\x37\x4a\x69\x58\x63\ -\x74\x61\x31\x72\x61\x75\x5a\x58\x55\x74\x61\x2f\x6e\x70\x36\x75\ -\x34\x71\x72\x67\x58\x64\x74\x61\x30\x67\x43\x77\x49\x57\x20\x6d\ -\x6f\x41\x46\x6b\x43\x49\x6c\x51\x41\x67\x51\x45\x6b\x68\x49\x53\ -\x47\x2f\x54\x35\x39\x62\x66\x48\x78\x4d\x69\x4a\x59\x48\x41\x44\ -\x50\x43\x48\x38\x33\x6d\x65\x50\x44\x79\x5a\x4f\x2b\x66\x65\x62\ -\x30\x35\x35\x7a\x7a\x6e\x76\x2b\x39\x36\x44\x35\x73\x55\x58\x58\ -\x6c\x42\x4a\x6b\x43\x42\x42\x67\x6d\x4f\x4d\x20\x50\x69\x4d\x7a\ -\x34\x33\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x66\x55\x46\x2b\ -\x2f\x76\x48\x57\x6b\x43\x42\x42\x67\x6c\x38\x67\x65\x72\x66\x62\ -\x66\x62\x77\x31\x4a\x45\x69\x51\x34\x42\x65\x49\x50\x6a\x6b\x35\ -\x2b\x58\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x76\x64\x56\x71\ -\x50\x64\x34\x61\x45\x69\x52\x49\x20\x38\x41\x74\x45\x62\x7a\x41\ -\x59\x59\x72\x71\x42\x4a\x4d\x76\x38\x38\x36\x74\x76\x6d\x4c\x31\ -\x36\x50\x58\x6b\x65\x4e\x34\x4e\x7a\x4d\x68\x6d\x63\x6e\x55\x6d\ -\x2f\x6a\x48\x52\x79\x33\x43\x6b\x34\x62\x66\x45\x7a\x62\x6b\x32\ -\x4e\x44\x57\x54\x6e\x35\x42\x47\x4a\x68\x4f\x4e\x32\x7a\x34\x72\ -\x36\x52\x6e\x34\x6f\x20\x4b\x79\x66\x50\x34\x79\x4c\x4c\x6e\x55\ -\x4b\x47\x30\x30\x47\x79\x31\x52\x4b\x33\x2b\x78\x38\x75\x4e\x53\ -\x31\x74\x31\x44\x53\x33\x6b\x75\x5a\x49\x4a\x74\x32\x5a\x6a\x4d\ -\x31\x73\x4f\x6d\x35\x61\x41\x46\x5a\x73\x72\x65\x43\x37\x7a\x56\ -\x76\x4a\x38\x37\x6a\x4a\x54\x2f\x65\x51\x6b\x65\x49\x6b\x7a\x5a\ -\x47\x4d\x20\x78\x52\x68\x62\x76\x39\x6d\x66\x6f\x39\x47\x32\x4b\ -\x37\x5a\x57\x38\x4e\x58\x61\x44\x65\x53\x6e\x65\x52\x69\x51\x6d\ -\x55\x47\x4b\x33\x55\x5a\x75\x71\x6f\x73\x6b\x69\x7a\x6c\x75\x7a\ -\x7a\x68\x63\x50\x63\x65\x69\x4c\x6e\x76\x4c\x6b\x6f\x31\x6c\x7a\ -\x46\x75\x2f\x69\x56\x79\x33\x6d\x33\x34\x5a\x71\x66\x52\x78\x20\ -\x70\x35\x44\x75\x53\x4d\x4b\x54\x6c\x49\x52\x4f\x70\x34\x33\x62\ -\x63\x33\x70\x71\x57\x33\x30\x73\x4e\x32\x31\x6f\x37\x2b\x44\x78\ -\x54\x32\x61\x69\x4e\x78\x69\x35\x61\x50\x53\x4a\x58\x44\x76\x2b\ -\x4e\x45\x71\x72\x61\x79\x69\x74\x72\x6d\x58\x42\x68\x69\x33\x73\ -\x61\x6d\x70\x42\x72\x39\x57\x53\x35\x58\x49\x77\x20\x73\x45\x38\ -\x6d\x52\x54\x6d\x5a\x46\x47\x61\x6b\x34\x55\x36\x32\x59\x7a\x63\ -\x66\x6e\x77\x36\x77\x42\x31\x6c\x52\x2b\x47\x4c\x31\x65\x6c\x36\ -\x66\x75\x34\x51\x42\x57\x52\x6e\x73\x62\x47\x36\x6a\x75\x71\x6d\ -\x46\x68\x76\x59\x4f\x6a\x46\x6f\x64\x47\x63\x35\x6b\x63\x6c\x50\ -\x64\x46\x47\x61\x6d\x4d\x69\x41\x7a\x20\x67\x33\x52\x6e\x4d\x6b\ -\x6b\x57\x4d\x31\x61\x54\x45\x59\x31\x47\x45\x33\x63\x39\x6b\x69\ -\x7a\x7a\x78\x55\x38\x6c\x50\x44\x5a\x6a\x4c\x71\x30\x36\x45\x79\ -\x5a\x46\x77\x6f\x61\x4d\x78\x32\x4b\x68\x77\x4a\x4e\x43\x51\x61\ -\x71\x62\x2f\x44\x51\x50\x2b\x52\x6d\x70\x35\x48\x6c\x63\x58\x56\ -\x70\x4d\x4d\x55\x34\x65\x20\x50\x52\x45\x57\x52\x4e\x35\x64\x2b\ -\x44\x31\x66\x72\x39\x76\x49\x4f\x53\x4f\x4b\x61\x51\x38\x4c\x7a\ -\x46\x68\x56\x51\x6c\x31\x72\x47\x38\x30\x64\x50\x6d\x77\x57\x45\ -\x2b\x6e\x4a\x79\x57\x53\x37\x6e\x66\x54\x50\x54\x4b\x4d\x67\x50\ -\x59\x32\x4d\x46\x41\x63\x4f\x71\x2b\x57\x34\x47\x38\x77\x39\x32\ -\x71\x66\x2f\x20\x2b\x42\x4e\x31\x51\x5a\x47\x2b\x41\x34\x70\x70\ -\x57\x37\x6d\x56\x6b\x4b\x38\x64\x67\x79\x70\x69\x30\x65\x6e\x49\ -\x64\x6a\x6b\x59\x6d\x70\x31\x4a\x75\x6a\x4f\x4a\x51\x64\x6c\x39\ -\x4b\x45\x68\x50\x78\x57\x59\x79\x34\x6b\x71\x79\x48\x7a\x55\x39\ -\x30\x35\x61\x76\x78\x6d\x34\x78\x38\x2b\x75\x54\x52\x78\x37\x58\ -\x20\x75\x76\x53\x48\x77\x72\x7a\x32\x78\x55\x4c\x65\x58\x4c\x79\ -\x55\x6b\x58\x6e\x5a\x6a\x4f\x78\x66\x79\x4a\x71\x71\x57\x6d\x61\ -\x76\x32\x55\x42\x64\x61\x7a\x74\x68\x51\x63\x52\x74\x74\x35\x48\ -\x68\x54\x43\x59\x2f\x33\x55\x4e\x42\x65\x69\x72\x35\x61\x61\x6d\ -\x34\x6b\x71\x79\x6b\x4f\x5a\x4c\x6a\x31\x76\x38\x31\x20\x33\x6f\ -\x37\x32\x49\x38\x72\x7a\x57\x56\x4f\x78\x6b\x38\x63\x2b\x2b\x5a\ -\x79\x37\x4c\x6a\x79\x58\x38\x30\x63\x4e\x5a\x2b\x58\x57\x37\x56\ -\x77\x77\x61\x73\x51\x2b\x33\x31\x45\x55\x68\x59\x5a\x32\x4c\x39\ -\x56\x4e\x4c\x57\x79\x70\x32\x63\x32\x6d\x71\x68\x6f\x32\x56\x64\ -\x65\x77\x73\x36\x47\x52\x6d\x58\x2b\x38\x20\x69\x32\x79\x33\x36\ -\x37\x43\x65\x47\x61\x2f\x5a\x4d\x52\x67\x52\x65\x47\x72\x71\x62\ -\x4e\x70\x43\x59\x5a\x36\x2b\x35\x6a\x4c\x4b\x61\x6e\x59\x7a\x38\ -\x64\x52\x52\x51\x4e\x51\x6f\x4e\x58\x74\x39\x31\x4c\x61\x30\x55\ -\x64\x58\x59\x7a\x4c\x62\x61\x4f\x72\x62\x57\x31\x72\x4f\x37\x74\ -\x51\x31\x76\x4d\x45\x69\x53\x20\x32\x63\x53\x37\x64\x30\x34\x69\ -\x78\x57\x36\x4c\x53\x63\x50\x65\x64\x41\x53\x43\x50\x50\x48\x70\ -\x4c\x4c\x37\x61\x55\x55\x39\x79\x30\x51\x68\x55\x67\x78\x46\x52\ -\x6c\x6f\x68\x49\x49\x75\x46\x51\x6b\x45\x67\x77\x67\x42\x41\x4b\ -\x51\x43\x67\x45\x34\x53\x41\x47\x55\x63\x42\x6a\x30\x4a\x4a\x6d\ -\x4d\x6e\x4a\x79\x20\x59\x56\x39\x65\x76\x50\x35\x79\x39\x44\x70\ -\x64\x33\x50\x54\x55\x74\x58\x62\x77\x38\x49\x66\x54\x36\x4e\x65\ -\x6e\x44\x35\x65\x65\x63\x69\x49\x66\x4c\x56\x37\x4b\x6c\x48\x74\ -\x76\x36\x37\x6f\x75\x53\x68\x49\x4e\x37\x56\x37\x71\x32\x74\x71\ -\x70\x62\x6d\x70\x68\x57\x32\x30\x64\x46\x58\x57\x4e\x56\x4e\x51\ -\x33\x20\x30\x4e\x6a\x65\x7a\x76\x38\x65\x2f\x6a\x33\x5a\x37\x70\ -\x54\x44\x65\x6d\x61\x38\x32\x6e\x5a\x76\x37\x62\x38\x39\x38\x33\ -\x52\x75\x66\x6d\x38\x6d\x76\x37\x72\x73\x52\x76\x78\x43\x47\x48\ -\x38\x6b\x54\x48\x76\x41\x52\x33\x4e\x62\x43\x32\x30\x64\x72\x62\ -\x53\x33\x74\x2b\x4a\x72\x62\x79\x58\x6b\x62\x55\x63\x4a\x20\x42\ -\x55\x6a\x58\x4b\x73\x7a\x37\x38\x77\x50\x30\x54\x66\x50\x45\x70\ -\x4b\x45\x6e\x50\x54\x65\x64\x4f\x35\x62\x5a\x4b\x39\x62\x77\x78\ -\x4e\x57\x2f\x37\x72\x72\x65\x55\x31\x33\x75\x61\x47\x69\x6b\x76\ -\x71\x33\x74\x69\x4f\x72\x79\x59\x47\x79\x74\x72\x65\x50\x75\x39\ -\x7a\x35\x6c\x68\x32\x4c\x45\x31\x69\x65\x58\x20\x6b\x31\x51\x66\ -\x55\x78\x2b\x2b\x71\x2b\x75\x36\x71\x71\x70\x34\x51\x32\x45\x61\ -\x32\x74\x71\x70\x61\x32\x32\x6e\x6f\x72\x36\x52\x37\x58\x55\x4e\ -\x6c\x4f\x32\x71\x5a\x58\x46\x4a\x4b\x51\x75\x66\x65\x6f\x6a\x42\ -\x4f\x5a\x6d\x48\x39\x63\x79\x34\x72\x58\x77\x6b\x57\x65\x59\x2f\ -\x53\x35\x59\x78\x61\x33\x55\x4a\x20\x37\x39\x33\x33\x4f\x77\x5a\ -\x6c\x5a\x37\x4b\x39\x72\x6f\x46\x2f\x66\x2f\x50\x39\x41\x63\x5a\ -\x48\x71\x39\x57\x53\x36\x58\x4b\x53\x36\x58\x4a\x79\x38\x73\x42\ -\x2b\x68\x45\x57\x52\x33\x37\x30\x2b\x68\x52\x56\x62\x79\x6d\x6e\ -\x32\x2b\x67\x2f\x62\x2b\x4d\x53\x44\x44\x56\x55\x31\x50\x50\x4c\ -\x52\x64\x4b\x34\x2f\x20\x63\x77\x79\x33\x54\x54\x69\x54\x6e\x59\ -\x33\x4e\x66\x4c\x78\x6b\x61\x5a\x66\x78\x30\x57\x6d\x31\x70\x44\ -\x73\x64\x70\x44\x73\x64\x6e\x4e\x69\x76\x4c\x78\x42\x74\x45\x45\ -\x56\x56\x2b\x64\x76\x6e\x58\x2f\x4f\x6e\x2f\x30\x7a\x46\x47\x77\ -\x7a\x46\x78\x66\x69\x6f\x71\x73\x71\x79\x73\x75\x33\x38\x34\x65\ -\x4f\x5a\x20\x6d\x50\x4f\x48\x4d\x50\x79\x73\x55\x55\x69\x4b\x67\ -\x69\x68\x4c\x68\x43\x57\x52\x6b\x43\x67\x51\x4e\x4a\x6f\x49\x57\ -\x6d\x7a\x34\x68\x54\x42\x68\x55\x55\x41\x46\x52\x46\x57\x6c\x54\ -\x6c\x57\x70\x4b\x79\x38\x6a\x73\x4b\x47\x4d\x73\x43\x42\x69\x74\ -\x38\x52\x75\x66\x46\x52\x56\x5a\x57\x46\x4a\x4b\x53\x2f\x4e\x20\ -\x6d\x73\x64\x54\x31\x31\x7a\x4f\x42\x61\x4f\x47\x30\x39\x54\x68\ -\x34\x36\x6f\x78\x70\x2b\x7a\x7a\x50\x59\x4e\x65\x54\x37\x62\x48\ -\x52\x62\x62\x48\x78\x65\x6a\x2b\x42\x51\x41\x45\x49\x78\x47\x75\ -\x65\x58\x6b\x79\x33\x35\x61\x56\x45\x34\x78\x45\x59\x74\x59\x53\ -\x44\x2b\x30\x37\x47\x35\x74\x52\x46\x42\x6b\x56\x20\x46\x55\x56\ -\x52\x6b\x42\x55\x46\x74\x46\x71\x4d\x4e\x6a\x73\x57\x76\x51\x37\ -\x4a\x5a\x6b\x64\x78\x70\x79\x4b\x48\x41\x67\x52\x4b\x53\x39\x6a\ -\x64\x32\x6b\x78\x45\x46\x49\x2b\x61\x6e\x76\x5a\x41\x73\x4b\x74\ -\x50\x37\x61\x47\x37\x75\x74\x77\x7a\x54\x6c\x61\x56\x56\x38\x61\ -\x74\x4c\x6b\x56\x4a\x34\x73\x4e\x76\x20\x66\x2b\x53\x76\x58\x79\ -\x79\x69\x33\x2b\x69\x78\x6a\x4d\x7a\x75\x53\x33\x74\x7a\x41\x30\ -\x70\x7a\x78\x7a\x37\x66\x30\x32\x67\x30\x4f\x4b\x77\x57\x48\x46\ -\x59\x4c\x41\x37\x49\x79\x47\x54\x64\x30\x4d\x43\x46\x42\x34\x4a\ -\x5a\x2f\x76\x49\x74\x4f\x70\x30\x4e\x52\x34\x35\x65\x54\x66\x46\ -\x6a\x47\x70\x38\x58\x6e\x20\x35\x36\x6c\x70\x73\x7a\x47\x62\x7a\ -\x4d\x78\x35\x34\x67\x45\x63\x6e\x66\x36\x63\x62\x4c\x65\x4c\x4a\ -\x36\x36\x2b\x39\x4b\x42\x6c\x4a\x56\x6e\x6d\x6d\x55\x38\x2f\x52\ -\x36\x50\x52\x4d\x50\x48\x55\x55\x53\x6a\x4b\x73\x55\x32\x73\x46\ -\x69\x57\x5a\x44\x37\x35\x62\x7a\x68\x65\x72\x53\x33\x6a\x39\x39\ -\x68\x73\x5a\x20\x55\x5a\x43\x48\x52\x71\x4f\x68\x6a\x38\x76\x4a\ -\x30\x39\x64\x64\x66\x73\x6a\x79\x55\x2b\x5a\x2f\x79\x2b\x77\x56\ -\x61\x7a\x68\x6a\x79\x45\x42\x30\x63\x56\x68\x6c\x42\x4d\x49\x52\ -\x58\x76\x74\x69\x49\x54\x4d\x32\x56\x54\x4c\x69\x72\x49\x6b\x6b\ -\x70\x62\x69\x52\x46\x49\x58\x49\x48\x71\x4d\x6a\x52\x4e\x42\x72\ -\x20\x74\x57\x6a\x51\x6f\x4b\x6f\x67\x4b\x54\x4b\x53\x4c\x43\x4d\ -\x71\x4d\x71\x67\x71\x6d\x71\x6f\x4b\x72\x69\x6b\x71\x59\x46\x76\ -\x4e\x37\x72\x6a\x73\x7a\x2f\x32\x68\x4d\x4b\x2f\x4d\x6d\x55\x39\ -\x46\x59\x77\x76\x2f\x65\x2f\x51\x2b\x63\x6a\x78\x75\x4e\x42\x6f\ -\x4e\x49\x55\x46\x67\x35\x64\x62\x74\x6e\x48\x66\x43\x20\x30\x42\ -\x37\x4c\x43\x70\x4c\x45\x2f\x56\x4d\x2b\x59\x56\x47\x44\x46\x36\ -\x50\x4c\x67\x2f\x6b\x6f\x62\x51\x56\x37\x6f\x69\x66\x74\x42\x70\ -\x30\x4f\x55\x52\x4a\x6f\x44\x77\x57\x6a\x64\x53\x70\x47\x43\x49\ -\x6b\x69\x59\x55\x6b\x6b\x49\x6b\x6c\x45\x4f\x6c\x65\x58\x6b\x63\ -\x70\x74\x59\x44\x53\x69\x53\x58\x62\x45\x20\x52\x58\x74\x50\x65\ -\x6c\x70\x38\x66\x6a\x35\x61\x73\x76\x53\x41\x53\x58\x70\x76\x39\ -\x68\x34\x6e\x34\x34\x63\x4f\x6a\x6f\x75\x65\x58\x63\x32\x74\x50\ -\x50\x72\x4a\x54\x4d\x70\x38\x43\x68\x4f\x75\x75\x67\x57\x72\x4c\ -\x51\x6c\x5a\x55\x64\x41\x47\x41\x38\x69\x48\x47\x49\x65\x69\x4a\ -\x50\x48\x59\x68\x35\x2b\x52\x20\x35\x6b\x78\x6d\x7a\x4a\x42\x42\ -\x63\x66\x56\x50\x39\x62\x72\x58\x62\x71\x6d\x70\x34\x39\x72\x58\ -\x33\x6d\x46\x4d\x63\x52\x47\x54\x37\x35\x6a\x55\x5a\x58\x67\x41\ -\x4f\x6f\x4a\x42\x6e\x70\x38\x2b\x35\x36\x44\x6c\x2f\x7a\x56\x33\ -\x45\x65\x73\x71\x64\x2f\x4c\x47\x48\x54\x64\x69\x4d\x75\x68\x52\ -\x56\x4f\x58\x49\x20\x56\x52\x38\x6d\x37\x59\x45\x67\x74\x2f\x2f\ -\x72\x41\x37\x62\x58\x4e\x7a\x50\x6a\x73\x54\x39\x77\x51\x72\x2b\ -\x2b\x58\x66\x76\x57\x56\x70\x2b\x66\x70\x7a\x2f\x39\x2f\x4b\x44\ -\x6c\x70\x79\x39\x64\x79\x5a\x51\x46\x53\x2f\x6a\x30\x6a\x33\x65\ -\x54\x5a\x44\x47\x6a\x6a\x58\x48\x50\x75\x37\x32\x75\x67\x63\x74\ -\x66\x20\x65\x59\x76\x76\x57\x68\x55\x75\x75\x50\x77\x6d\x42\x76\ -\x59\x74\x4a\x44\x50\x5a\x69\x64\x74\x71\x4a\x38\x6c\x6b\x78\x6d\ -\x6f\x77\x59\x74\x49\x62\x4d\x4f\x6a\x30\x36\x4c\x56\x61\x64\x46\ -\x6f\x4e\x57\x6f\x33\x6d\x35\x37\x31\x32\x54\x54\x55\x54\x30\x6c\ -\x4e\x34\x2b\x36\x36\x62\x55\x52\x57\x56\x57\x48\x66\x67\x20\x4f\ -\x78\x71\x61\x2b\x4d\x31\x72\x37\x2b\x42\x78\x4f\x70\x6e\x36\x38\ -\x4f\x2f\x4a\x54\x66\x56\x30\x50\x55\x74\x57\x46\x42\x72\x62\x76\ -\x51\x63\x74\x2f\x2b\x4c\x30\x4c\x2f\x69\x73\x64\x41\x63\x70\x51\ -\x34\x5a\x6a\x30\x47\x72\x52\x61\x75\x50\x6e\x72\x44\x77\x55\x42\ -\x39\x4e\x75\x30\x4f\x75\x51\x4a\x49\x6d\x32\x20\x6b\x4a\x2b\x4f\ -\x55\x41\x42\x76\x4f\x49\x78\x66\x43\x42\x4d\x51\x49\x70\x32\x47\ -\x53\x43\x43\x77\x63\x7a\x74\x53\x4f\x41\x78\x35\x42\x61\x41\x6f\ -\x4d\x57\x73\x2f\x6d\x4a\x35\x73\x74\x34\x74\x6e\x72\x72\x76\x69\ -\x6f\x4f\x58\x33\x48\x69\x63\x61\x4e\x44\x48\x72\x6d\x62\x64\x32\ -\x49\x78\x65\x2b\x4e\x42\x6d\x76\x20\x75\x34\x41\x4c\x4a\x31\x35\ -\x50\x51\x55\x59\x4f\x36\x55\x6b\x4f\x6e\x42\x59\x72\x46\x71\x50\ -\x70\x6b\x43\x75\x5a\x6c\x32\x5a\x38\x53\x58\x31\x62\x42\x79\x39\ -\x4d\x75\x68\x70\x4a\x6c\x6a\x45\x61\x34\x72\x65\x39\x37\x39\x58\ -\x4b\x35\x39\x4d\x66\x56\x76\x4c\x43\x7a\x4b\x2f\x35\x35\x4b\x48\ -\x66\x63\x2b\x71\x67\x20\x77\x67\x4d\x63\x54\x6c\x61\x54\x69\x5a\ -\x50\x36\x39\x2b\x75\x32\x72\x4b\x71\x71\x7a\x46\x69\x2b\x6d\x6b\ -\x2b\x2f\x57\x38\x36\x58\x54\x7a\x37\x55\x4f\x58\x69\x31\x30\x53\ -\x58\x77\x4d\x65\x43\x62\x6b\x6c\x49\x65\x2f\x76\x42\x2f\x50\x48\ -\x7a\x35\x52\x64\x78\x32\x33\x76\x67\x44\x47\x74\x4e\x6d\x4e\x6a\ -\x4e\x2b\x20\x36\x4f\x42\x75\x79\x36\x71\x71\x79\x74\x77\x31\x4a\ -\x54\x77\x37\x62\x52\x5a\x7a\x6e\x6e\x69\x41\x33\x46\x51\x33\x69\ -\x71\x4b\x69\x30\x78\x37\x35\x63\x48\x2f\x39\x71\x30\x57\x38\x4e\ -\x75\x38\x37\x52\x70\x30\x33\x6b\x62\x7a\x63\x41\x76\x52\x36\x41\ -\x37\x4b\x69\x49\x4d\x6b\x79\x67\x69\x77\x69\x79\x4e\x4c\x50\x20\ -\x50\x35\x4b\x30\x7a\x2b\x2b\x53\x4c\x45\x4e\x64\x44\x65\x4f\x53\ -\x6a\x45\x7a\x37\x34\x39\x33\x59\x7a\x4e\x48\x4f\x6f\x39\x55\x63\ -\x65\x51\x65\x64\x2b\x73\x4e\x4b\x6e\x70\x6f\x32\x68\x7a\x66\x75\ -\x6d\x4d\x54\x45\x55\x30\x63\x64\x30\x4c\x59\x5a\x4b\x51\x36\x75\ -\x48\x58\x39\x61\x74\x32\x56\x56\x56\x65\x58\x39\x20\x68\x64\x2f\ -\x78\x32\x70\x4b\x56\x35\x4a\x78\x32\x4a\x6c\x35\x52\x51\x4b\x38\ -\x42\x58\x51\x78\x36\x44\x6f\x65\x70\x50\x36\x7a\x6b\x72\x7a\x4f\ -\x2f\x5a\x73\x6f\x39\x74\x33\x48\x32\x38\x4b\x49\x44\x74\x42\x74\ -\x30\x4f\x6d\x52\x5a\x6f\x69\x58\x67\x52\x35\x42\x2b\x33\x73\x6f\ -\x47\x68\x41\x68\x42\x49\x59\x4a\x33\x20\x31\x77\x34\x69\x4c\x59\ -\x30\x77\x73\x42\x69\x30\x57\x72\x53\x6f\x78\x44\x4b\x76\x48\x45\ -\x70\x50\x55\x34\x65\x58\x68\x39\x37\x2f\x4c\x37\x4f\x66\x65\x4f\ -\x43\x41\x73\x74\x32\x4e\x45\x31\x6d\x52\x59\x36\x72\x4c\x76\x30\ -\x79\x64\x7a\x56\x76\x66\x72\x75\x44\x30\x38\x36\x38\x67\x4e\x79\ -\x63\x66\x57\x56\x55\x4a\x20\x43\x68\x46\x6b\x56\x53\x45\x6b\x43\ -\x6b\x52\x6b\x43\x58\x6f\x59\x68\x34\x71\x71\x38\x75\x36\x38\x78\ -\x58\x79\x2f\x61\x51\x73\x7a\x48\x2f\x38\x44\x46\x71\x4d\x52\x57\ -\x5a\x46\x69\x36\x6d\x76\x37\x30\x79\x76\x6a\x38\x2f\x37\x69\x70\ -\x65\x53\x6d\x65\x6e\x6a\x77\x76\x55\x39\x77\x32\x71\x30\x55\x35\ -\x57\x51\x78\x20\x75\x6e\x38\x42\x77\x77\x76\x79\x79\x48\x41\x36\ -\x4d\x42\x6b\x4d\x36\x48\x71\x77\x30\x45\x73\x32\x62\x4f\x62\x35\ -\x7a\x32\x59\x7a\x36\x34\x6e\x37\x75\x79\x49\x4a\x4f\x71\x33\x32\ -\x6b\x4d\x75\x39\x65\x50\x48\x43\x72\x50\x6e\x6f\x55\x6a\x4c\x34\ -\x35\x2f\x79\x6c\x76\x4c\x39\x6f\x47\x63\x50\x79\x2b\x6c\x43\x63\ -\x20\x6d\x38\x30\x70\x41\x77\x76\x4a\x54\x58\x56\x68\x4e\x42\x69\ -\x49\x69\x46\x4c\x33\x32\x6a\x65\x57\x38\x61\x63\x50\x70\x76\x48\ -\x5a\x49\x2f\x65\x53\x6e\x35\x45\x47\x52\x46\x63\x43\x50\x66\x32\ -\x74\x76\x65\x47\x2f\x50\x36\x79\x6b\x4b\x43\x75\x64\x48\x61\x73\ -\x57\x73\x32\x50\x44\x4b\x71\x77\x4f\x4e\x36\x36\x30\x20\x50\x74\ -\x68\x53\x58\x47\x41\x77\x49\x41\x42\x42\x49\x54\x70\x41\x39\x6a\ -\x68\x4a\x2f\x5a\x45\x49\x51\x55\x46\x41\x61\x61\x78\x6a\x75\x42\ -\x70\x68\x2b\x70\x38\x65\x49\x64\x6c\x71\x51\x5a\x51\x6b\x64\x44\ -\x6f\x74\x32\x68\x69\x4d\x34\x62\x2b\x58\x4c\x4f\x4f\x30\x77\x66\ -\x33\x35\x2b\x2b\x78\x35\x76\x44\x70\x72\x20\x4c\x6f\x56\x39\x30\ -\x68\x6d\x57\x6c\x38\x50\x4a\x41\x77\x76\x70\x6d\x35\x35\x4b\x57\ -\x42\x42\x34\x2f\x72\x4d\x35\x66\x50\x48\x6b\x67\x77\x65\x55\x6e\ -\x62\x31\x69\x44\x59\x2f\x2f\x62\x79\x35\x44\x78\x31\x2b\x41\x58\ -\x31\x56\x51\x68\x41\x68\x36\x51\x4b\x65\x4c\x66\x7a\x53\x77\x4f\ -\x39\x35\x62\x76\x49\x79\x38\x20\x56\x41\x39\x2f\x2f\x6e\x67\x36\ -\x66\x35\x74\x31\x59\x4c\x2f\x55\x36\x62\x51\x6f\x73\x6b\x52\x4c\ -\x77\x49\x65\x6f\x79\x46\x45\x48\x76\x74\x68\x70\x67\x42\x70\x32\ -\x45\x36\x36\x70\x67\x73\x48\x46\x30\x4c\x6d\x4e\x6a\x72\x62\x71\ -\x6b\x57\x73\x2f\x6c\x42\x36\x72\x32\x63\x52\x5a\x77\x34\x71\x36\ -\x4c\x64\x76\x64\x20\x4f\x4a\x46\x6b\x4a\x61\x61\x36\x2f\x47\x72\ -\x74\x52\x69\x77\x70\x48\x74\x59\x75\x2f\x59\x62\x31\x47\x67\x33\ -\x4a\x44\x69\x64\x4f\x54\x7a\x72\x4a\x37\x6a\x52\x4d\x53\x51\x36\ -\x38\x76\x67\x34\x63\x33\x52\x67\x66\x56\x56\x58\x35\x33\x39\x4b\ -\x56\x66\x4c\x68\x6b\x4b\x56\x2f\x38\x2b\x63\x47\x75\x79\x4c\x51\ -\x6b\x20\x78\x7a\x62\x78\x37\x6b\x2b\x76\x6a\x49\x38\x6e\x32\x63\ -\x37\x6b\x4f\x32\x38\x6d\x49\x38\x58\x42\x31\x74\x6f\x36\x64\x6a\ -\x59\x30\x38\x58\x33\x70\x56\x6a\x37\x35\x64\x6a\x6e\x56\x54\x53\ -\x32\x34\x6b\x32\x78\x73\x32\x31\x31\x50\x70\x73\x76\x4a\x36\x50\ -\x34\x46\x39\x45\x33\x7a\x6f\x4e\x56\x71\x32\x56\x53\x31\x20\x69\ -\x2f\x75\x6e\x66\x4d\x7a\x37\x39\x2f\x32\x4f\x33\x4e\x53\x66\x49\ -\x77\x68\x61\x72\x65\x61\x59\x2b\x58\x7a\x73\x56\x67\x74\x44\x7a\ -\x37\x69\x45\x56\x4a\x63\x48\x76\x39\x39\x4c\x59\x31\x4d\x39\x30\ -\x79\x71\x71\x2b\x4d\x63\x50\x4d\x78\x42\x38\x62\x61\x53\x5a\x64\ -\x54\x53\x30\x64\x57\x44\x55\x36\x78\x69\x61\x20\x6c\x38\x50\x6f\ -\x41\x66\x32\x77\x6d\x6f\x79\x73\x72\x64\x6a\x4a\x41\x31\x4d\x2b\ -\x35\x72\x31\x37\x62\x6d\x56\x51\x39\x73\x2f\x65\x66\x55\x57\x56\ -\x59\x39\x70\x32\x5a\x58\x74\x63\x76\x48\x33\x33\x4c\x58\x69\x53\ -\x6b\x39\x6a\x52\x30\x45\x54\x35\x37\x6e\x70\x57\x62\x61\x74\x67\ -\x30\x2b\x59\x79\x4e\x75\x78\x75\x20\x77\x71\x74\x6f\x4d\x44\x69\ -\x63\x61\x4f\x78\x4a\x53\x46\x59\x62\x49\x5a\x32\x57\x69\x43\x53\ -\x68\x74\x44\x5a\x54\x47\x47\x68\x6e\x78\x6c\x4d\x50\x6b\x75\x70\ -\x49\x41\x6b\x43\x51\x6f\x6a\x4e\x6a\x4c\x48\x70\x63\x53\x54\x5a\ -\x65\x76\x66\x56\x36\x73\x74\x77\x70\x31\x4c\x65\x31\x55\x31\x48\ -\x58\x79\x4c\x72\x4b\x20\x4b\x74\x36\x5a\x76\x35\x68\x74\x74\x58\ -\x57\x45\x52\x59\x6d\x77\x49\x50\x44\x50\x4c\x2b\x5a\x54\x6e\x4a\ -\x66\x44\x4b\x51\x50\x37\x59\x54\x57\x5a\x2b\x48\x46\x4c\x4f\x66\ -\x66\x2b\x5a\x7a\x6f\x6a\x7a\x72\x6f\x49\x32\x57\x7a\x47\x36\x2f\ -\x63\x68\x4b\x51\x70\x36\x72\x53\x59\x6d\x34\x33\x77\x34\x65\x4a\ -\x4a\x74\x20\x76\x48\x6e\x58\x4c\x61\x51\x37\x6b\x37\x76\x76\x6c\ -\x38\x6c\x32\x6d\x74\x76\x61\x43\x46\x5a\x75\x51\x35\x4f\x55\x6a\ -\x47\x51\x77\x45\x4a\x45\x6b\x77\x6d\x30\x74\x53\x4a\x58\x6c\x4d\ -\x4c\x41\x49\x39\x44\x2f\x37\x4d\x48\x51\x51\x30\x38\x72\x6e\x55\ -\x48\x70\x53\x48\x55\x6e\x6b\x70\x58\x6d\x59\x39\x73\x4f\x4b\x20\ -\x58\x6f\x30\x54\x4a\x63\x61\x4a\x7a\x6d\x77\x30\x34\x4f\x34\x2f\ -\x46\x49\x63\x6e\x44\x56\x55\x55\x69\x50\x68\x39\x74\x4c\x61\x31\ -\x55\x4c\x31\x70\x4c\x53\x46\x66\x4f\x33\x49\x34\x6a\x45\x73\x48\ -\x7a\x30\x32\x62\x78\x61\x6a\x43\x41\x6b\x37\x6f\x6c\x30\x65\x61\ -\x49\x35\x6b\x6c\x47\x38\x74\x34\x61\x63\x61\x58\x20\x66\x50\x62\ -\x49\x50\x66\x75\x6b\x48\x73\x51\x36\x38\x65\x35\x50\x72\x34\x79\ -\x50\x32\x57\x41\x6b\x4a\x41\x69\x59\x44\x41\x61\x47\x39\x63\x31\ -\x6c\x57\x4e\x39\x63\x4c\x6a\x6c\x35\x4a\x47\x72\x6e\x66\x72\x47\ -\x71\x71\x5a\x6c\x50\x76\x6c\x33\x4f\x75\x6f\x6f\x71\x70\x69\x7a\ -\x34\x6c\x6a\x61\x66\x48\x34\x38\x6a\x20\x6d\x5a\x72\x6d\x56\x74\ -\x36\x34\x34\x34\x59\x44\x50\x50\x77\x36\x72\x52\x62\x35\x47\x50\ -\x6c\x38\x7a\x41\x59\x6a\x76\x6c\x41\x41\x55\x38\x53\x4f\x78\x6d\ -\x44\x45\x6d\x5a\x47\x46\x79\x5a\x31\x4b\x35\x71\x42\x68\x42\x49\ -\x51\x77\x37\x58\x34\x76\x32\x6f\x71\x74\x2f\x47\x56\x35\x4b\x66\ -\x34\x76\x6c\x79\x44\x37\x20\x66\x65\x51\x37\x37\x49\x69\x52\x43\ -\x42\x2f\x38\x34\x58\x5a\x47\x39\x53\x2f\x59\x5a\x2f\x6b\x73\x53\ -\x72\x45\x31\x67\x4e\x31\x73\x78\x42\x73\x4d\x6b\x5a\x66\x6d\x6f\ -\x54\x67\x76\x6d\x2b\x4b\x38\x62\x48\x35\x39\x79\x73\x69\x75\x36\ -\x36\x75\x32\x56\x66\x44\x45\x52\x39\x4d\x5a\x30\x7a\x2b\x44\x46\ -\x56\x75\x33\x20\x55\x39\x48\x63\x79\x67\x35\x2f\x69\x41\x77\x64\ -\x7a\x48\x72\x71\x49\x66\x70\x31\x72\x73\x43\x69\x57\x69\x54\x30\ -\x75\x74\x68\x38\x4c\x43\x61\x39\x67\x62\x41\x67\x6f\x74\x4e\x71\ -\x79\x58\x4b\x37\x79\x48\x4b\x37\x47\x46\x73\x38\x71\x4b\x74\x74\ -\x61\x31\x76\x62\x75\x50\x72\x46\x31\x39\x46\x71\x4e\x48\x79\x34\ -\x20\x36\x41\x63\x65\x2f\x57\x42\x71\x39\x50\x4e\x32\x50\x36\x4d\ -\x6e\x58\x49\x48\x4a\x36\x61\x4c\x4a\x37\x30\x56\x53\x5a\x41\x52\ -\x5a\x77\x6f\x4a\x36\x7a\x49\x7a\x50\x48\x75\x30\x39\x39\x63\x75\ -\x64\x6a\x63\x32\x63\x39\x71\x66\x6e\x61\x47\x79\x6f\x52\x61\x6e\ -\x59\x41\x70\x49\x59\x4e\x54\x61\x69\x43\x50\x30\x48\x20\x67\x33\ -\x6e\x66\x5a\x46\x4b\x39\x52\x68\x50\x54\x4e\x75\x64\x51\x65\x6a\ -\x5a\x56\x31\x58\x44\x72\x36\x2b\x2b\x53\x37\x6e\x54\x30\x61\x70\ -\x7a\x49\x73\x68\x78\x54\x58\x56\x70\x4e\x42\x6e\x62\x35\x4f\x67\ -\x67\x61\x6a\x57\x69\x31\x57\x72\x51\x47\x41\x32\x70\x61\x42\x71\ -\x62\x55\x4e\x48\x53\x79\x51\x74\x6a\x58\x20\x67\x61\x74\x32\x4f\ -\x33\x31\x63\x4b\x55\x78\x66\x74\x70\x4b\x2f\x66\x6a\x59\x4c\x58\ -\x79\x68\x4d\x59\x34\x65\x58\x75\x58\x39\x35\x6d\x48\x36\x5a\x36\ -\x66\x76\x71\x55\x57\x4c\x54\x73\x7a\x2b\x39\x4d\x7a\x35\x36\x50\ -\x57\x48\x68\x77\x42\x44\x6b\x6e\x6b\x47\x5a\x6c\x2b\x70\x68\x79\ -\x59\x62\x4e\x66\x50\x37\x34\x20\x2f\x64\x6a\x4e\x4a\x6a\x6f\x43\ -\x51\x61\x71\x62\x57\x72\x6a\x37\x72\x51\x38\x59\x57\x7a\x7a\x34\ -\x67\x4c\x32\x76\x54\x71\x75\x4e\x61\x38\x6a\x75\x59\x46\x67\x4e\ -\x4f\x72\x7a\x42\x41\x49\x5a\x77\x45\x41\x30\x67\x4b\x51\x71\x43\ -\x4c\x42\x45\x53\x42\x55\x4b\x69\x69\x43\x44\x4c\x74\x4f\x34\x73\ -\x78\x33\x58\x79\x20\x57\x4b\x53\x4d\x50\x76\x6a\x44\x49\x63\x71\ -\x46\x43\x49\x57\x37\x4b\x37\x73\x69\x59\x6e\x75\x6a\x4b\x47\x70\ -\x4d\x30\x61\x55\x6b\x69\x78\x6c\x66\x4b\x4c\x54\x50\x5a\x33\x73\ -\x2f\x77\x35\x56\x6b\x70\x79\x41\x7a\x6e\x53\x65\x76\x6d\x59\x69\ -\x71\x71\x76\x6a\x44\x59\x54\x35\x59\x39\x41\x4d\x4e\x37\x56\x36\ -\x4b\x20\x63\x72\x4c\x32\x4b\x53\x66\x49\x4d\x76\x6f\x59\x4f\x34\ -\x4e\x4a\x72\x2b\x38\x32\x76\x4c\x78\x48\x6b\x39\x4e\x71\x35\x64\ -\x52\x42\x2f\x62\x6e\x37\x6f\x76\x4d\x41\x69\x49\x67\x69\x4e\x63\ -\x32\x74\x6a\x48\x74\x75\x4d\x70\x6c\x39\x63\x6d\x6e\x75\x33\x4e\ -\x49\x49\x55\x6a\x52\x79\x6c\x48\x51\x4d\x56\x7a\x36\x48\x20\x30\ -\x74\x34\x33\x7a\x59\x50\x4e\x5a\x6b\x58\x4a\x79\x67\x57\x74\x44\ -\x6d\x51\x5a\x77\x6b\x48\x59\x57\x51\x6e\x64\x76\x46\x5a\x6b\x30\ -\x47\x70\x69\x32\x73\x49\x65\x53\x73\x2f\x67\x6e\x44\x36\x38\x65\ -\x2f\x65\x74\x44\x4d\x76\x50\x52\x56\x58\x56\x51\x34\x34\x54\x4b\ -\x63\x61\x56\x52\x70\x4c\x5a\x54\x48\x76\x41\x20\x68\x38\x39\x6f\ -\x37\x46\x72\x52\x71\x59\x43\x71\x67\x71\x49\x71\x4b\x4f\x45\x67\ -\x51\x2b\x30\x32\x62\x6a\x35\x33\x48\x44\x65\x66\x4f\x77\x35\x4a\ -\x6c\x70\x6d\x2f\x64\x69\x4d\x7a\x6c\x71\x39\x69\x57\x4e\x2f\x63\ -\x41\x2b\x34\x6e\x79\x66\x46\x64\x2b\x66\x54\x71\x54\x6d\x61\x54\ -\x6f\x56\x76\x6a\x73\x77\x65\x4e\x20\x52\x73\x4e\x4e\x35\x34\x7a\ -\x46\x6f\x4e\x4f\x69\x30\x57\x68\x77\x32\x6d\x33\x30\x79\x30\x78\ -\x48\x52\x59\x33\x2b\x70\x66\x73\x2f\x56\x4b\x4e\x42\x4f\x55\x59\ -\x4f\x5a\x37\x4e\x42\x6a\x7a\x63\x55\x6f\x43\x4d\x55\x70\x44\x30\ -\x63\x78\x42\x73\x4f\x34\x51\x75\x48\x43\x45\x53\x69\x45\x59\x2b\ -\x49\x49\x6d\x50\x4e\x20\x4c\x53\x44\x53\x36\x64\x79\x56\x55\x63\ -\x46\x6f\x52\x4e\x56\x6f\x6f\x76\x72\x33\x51\x31\x61\x55\x6d\x4a\ -\x78\x75\x54\x70\x75\x56\x4e\x6e\x2b\x77\x78\x2b\x74\x39\x58\x43\ -\x6e\x63\x65\x50\x59\x59\x49\x46\x71\x76\x53\x52\x59\x4c\x47\x53\ -\x6b\x4f\x4e\x42\x6f\x4f\x36\x4a\x79\x69\x4a\x47\x48\x51\x78\x35\ -\x53\x6b\x20\x6a\x74\x47\x67\x49\x33\x79\x51\x33\x42\x61\x54\x77\ -\x63\x41\x4a\x2f\x66\x4b\x36\x5a\x6d\x2b\x54\x77\x55\x42\x47\x69\ -\x68\x4f\x4e\x47\x74\x30\x57\x43\x4c\x49\x55\x39\x61\x4e\x49\x41\ -\x68\x46\x52\x78\x4b\x69\x4e\x62\x52\x73\x59\x54\x2b\x30\x61\x6a\ -\x51\x61\x7a\x58\x67\x2b\x4b\x47\x74\x31\x50\x36\x66\x56\x67\x20\ -\x73\x6b\x53\x64\x72\x4e\x31\x6f\x4e\x4d\x52\x6f\x4f\x41\x2b\x6c\ -\x4a\x78\x51\x52\x75\x50\x75\x74\x44\x31\x42\x56\x74\x56\x66\x6a\ -\x52\x46\x62\x55\x6d\x4f\x72\x53\x61\x62\x4f\x69\x45\x53\x56\x6b\ -\x53\x55\x61\x55\x5a\x41\x52\x4a\x52\x70\x52\x6c\x4a\x45\x58\x75\ -\x6d\x76\x79\x6c\x76\x63\x61\x68\x58\x71\x66\x44\x20\x6e\x57\x78\ -\x48\x73\x33\x64\x6b\x64\x53\x2b\x69\x77\x5a\x5a\x6a\x76\x75\x30\ -\x79\x45\x42\x4b\x45\x48\x71\x2b\x72\x71\x73\x71\x47\x48\x64\x57\ -\x63\x55\x54\x53\x51\x76\x4d\x37\x73\x55\x4c\x31\x4f\x68\x36\x79\ -\x6f\x33\x64\x56\x70\x64\x4f\x56\x7a\x6a\x48\x77\x2b\x4e\x71\x4d\ -\x52\x58\x7a\x43\x41\x4e\x68\x7a\x73\x20\x30\x69\x72\x4b\x30\x53\ -\x31\x43\x52\x42\x4c\x78\x4e\x6a\x66\x67\x71\x36\x71\x45\x67\x41\ -\x38\x78\x79\x51\x47\x79\x42\x42\x5a\x72\x64\x4c\x42\x31\x49\x31\ -\x46\x52\x6c\x4a\x67\x36\x68\x4e\x74\x75\x6f\x39\x6e\x62\x63\x2b\ -\x6a\x36\x6d\x2f\x57\x62\x75\x4f\x66\x74\x44\x31\x6a\x34\x37\x4b\ -\x4e\x38\x75\x58\x6f\x64\x20\x5a\x77\x38\x66\x67\x71\x72\x53\x37\ -\x59\x77\x71\x53\x4c\x47\x48\x50\x73\x32\x47\x67\x30\x38\x73\x32\ -\x33\x62\x58\x38\x66\x78\x6e\x63\x78\x68\x56\x57\x4d\x43\x6d\x36\ -\x6c\x32\x4d\x4b\x52\x71\x49\x7a\x52\x79\x4e\x78\x41\x54\x46\x61\ -\x4e\x51\x6f\x2b\x71\x2b\x41\x70\x4d\x67\x59\x4e\x5a\x71\x34\x52\ -\x6b\x52\x69\x20\x30\x54\x35\x6a\x32\x53\x6f\x51\x42\x66\x72\x57\ -\x56\x46\x41\x64\x45\x56\x46\x73\x79\x64\x45\x56\x6a\x36\x70\x45\ -\x42\x2f\x74\x2b\x37\x57\x6a\x55\x61\x6d\x50\x7a\x73\x52\x78\x43\ -\x7a\x36\x49\x4e\x6d\x39\x6c\x63\x33\x30\x54\x52\x66\x55\x38\x79\ -\x49\x69\x65\x44\x6b\x77\x59\x55\x4d\x4b\x78\x76\x44\x70\x4b\x73\ -\x20\x52\x4b\x4f\x57\x2b\x33\x31\x66\x6c\x75\x58\x59\x4a\x6a\x71\ -\x72\x46\x57\x4e\x7a\x42\x49\x32\x71\x52\x55\x4a\x46\x30\x71\x68\ -\x30\x44\x54\x74\x56\x67\x64\x32\x37\x36\x4e\x41\x71\x6e\x50\x33\ -\x34\x38\x30\x79\x2b\x38\x30\x59\x32\x56\x64\x55\x67\x4b\x77\x71\ -\x69\x4a\x48\x63\x5a\x79\x48\x33\x30\x48\x49\x39\x6f\x20\x6c\x39\ -\x31\x6b\x77\x68\x2f\x75\x4f\x65\x33\x39\x72\x62\x6d\x4c\x57\x4c\ -\x53\x68\x6c\x4d\x74\x4f\x47\x38\x30\x7a\x55\x7a\x39\x6e\x66\x50\ -\x46\x67\x7a\x68\x6b\x78\x42\x46\x47\x57\x6b\x56\x55\x46\x33\x58\ -\x37\x56\x71\x74\x55\x65\x75\x31\x43\x37\x7a\x57\x54\x45\x31\x78\ -\x47\x41\x55\x4e\x54\x34\x4b\x4b\x71\x4b\x20\x72\x4d\x69\x49\x73\ -\x6f\x53\x2f\x75\x5a\x47\x77\x45\x49\x48\x63\x76\x67\x68\x61\x4c\ -\x57\x72\x41\x42\x36\x33\x4e\x6b\x4a\x46\x46\x59\x30\x73\x72\x50\ -\x32\x7a\x65\x69\x73\x74\x75\x49\x79\x50\x46\x53\x55\x36\x71\x47\ -\x36\x31\x47\x67\x78\x53\x6a\x38\x58\x48\x5a\x37\x54\x52\x37\x2f\ -\x51\x64\x38\x4c\x73\x6b\x79\x20\x58\x2f\x32\x30\x6e\x69\x78\x33\ -\x43\x67\x75\x65\x2f\x52\x4d\x35\x71\x53\x37\x53\x6e\x51\x37\x71\ -\x32\x74\x70\x5a\x56\x31\x6e\x46\x56\x36\x74\x4c\x6d\x48\x54\x57\ -\x57\x47\x61\x74\x2b\x49\x6e\x4c\x54\x78\x75\x4e\x78\x35\x46\x4d\ -\x52\x79\x43\x49\x51\x52\x75\x62\x38\x62\x45\x61\x6a\x64\x31\x6d\ -\x30\x53\x71\x71\x20\x69\x69\x38\x59\x34\x72\x30\x46\x33\x2f\x48\ -\x71\x72\x64\x64\x68\x4d\x35\x76\x59\x73\x47\x4d\x58\x36\x51\x34\ -\x48\x62\x38\x39\x62\x6a\x43\x68\x4c\x31\x4e\x62\x73\x70\x4b\x36\ -\x6c\x6b\x61\x44\x4e\x52\x6a\x41\x63\x52\x46\x58\x56\x61\x4b\x67\ -\x39\x6a\x68\x47\x52\x49\x39\x45\x75\x53\x6a\x4a\x62\x61\x33\x66\ -\x6a\x20\x44\x59\x57\x5a\x39\x2f\x51\x6a\x32\x43\x30\x6d\x61\x70\ -\x76\x62\x57\x4c\x32\x39\x6b\x68\x56\x62\x4b\x2f\x68\x33\x65\x52\ -\x6e\x32\x37\x5a\x74\x70\x31\x78\x70\x51\x37\x45\x6c\x67\x54\x77\ -\x4b\x54\x43\x5a\x4e\x4f\x47\x39\x4d\x32\x74\x6b\x63\x39\x73\x73\ -\x79\x55\x2b\x55\x74\x34\x5a\x63\x46\x79\x54\x72\x2f\x6b\x20\x4f\ -\x6b\x53\x4e\x68\x6f\x72\x57\x4a\x6e\x37\x63\x55\x49\x31\x76\x38\ -\x57\x72\x38\x4e\x64\x57\x63\x2f\x74\x6a\x7a\x6a\x4d\x37\x50\x35\ -\x64\x52\x42\x68\x5a\x7a\x59\x4c\x35\x39\x4d\x6c\x37\x4e\x7a\x32\ -\x33\x58\x6b\x64\x57\x6b\x31\x47\x54\x43\x71\x6f\x4e\x64\x71\x6b\ -\x56\x51\x31\x2b\x6f\x4f\x4b\x4a\x49\x6c\x51\x20\x56\x63\x36\x39\ -\x70\x77\x7a\x6e\x69\x61\x73\x75\x4a\x53\x79\x49\x57\x45\x78\x47\ -\x76\x6c\x71\x39\x6e\x71\x59\x4f\x48\x2f\x50\x58\x62\x75\x43\x36\ -\x56\x39\x37\x6b\x75\x64\x39\x65\x79\x62\x72\x4b\x4b\x73\x59\x55\ -\x44\x53\x44\x4a\x59\x6f\x6c\x47\x75\x2b\x49\x59\x79\x65\x79\x56\ -\x38\x62\x47\x5a\x54\x66\x68\x44\x20\x42\x78\x6f\x66\x58\x79\x6a\ -\x4d\x6b\x67\x32\x62\x79\x55\x39\x50\x35\x5a\x76\x6e\x48\x6f\x75\ -\x6d\x5a\x64\x75\x73\x68\x41\x57\x52\x65\x57\x73\x32\x73\x4b\x75\ -\x70\x68\x64\x4b\x71\x47\x75\x61\x73\x57\x73\x74\x31\x34\x30\x36\ -\x6a\x49\x43\x4d\x4e\x62\x57\x66\x53\x33\x4c\x46\x4b\x63\x4c\x61\ -\x61\x6a\x66\x6a\x71\x20\x57\x31\x48\x32\x57\x76\x6c\x49\x69\x6b\ -\x4b\x6f\x76\x68\x62\x2f\x72\x68\x33\x6f\x69\x34\x59\x68\x71\x47\ -\x70\x30\x70\x57\x4f\x78\x67\x6a\x73\x56\x56\x42\x57\x37\x33\x55\ -\x37\x2f\x7a\x41\x79\x2b\x33\x62\x69\x5a\x4f\x53\x76\x58\x4d\x6e\ -\x70\x41\x50\x2f\x37\x31\x39\x54\x66\x6f\x64\x62\x48\x4e\x6a\x75\ -\x34\x6b\x20\x47\x2b\x75\x72\x64\x78\x2f\x77\x2b\x61\x4b\x53\x55\ -\x6a\x37\x39\x37\x6b\x66\x65\x76\x2b\x38\x32\x72\x4b\x62\x6f\x79\ -\x34\x54\x58\x6e\x33\x6b\x36\x41\x42\x61\x6a\x67\x63\x62\x32\x44\ -\x6a\x4a\x64\x54\x67\x6f\x79\x30\x67\x68\x45\x42\x4e\x36\x65\x4e\ -\x6f\x75\x6c\x6d\x37\x63\x78\x49\x44\x50\x74\x67\x48\x73\x64\x20\ -\x44\x6c\x61\x7a\x6b\x55\x44\x34\x77\x41\x48\x7a\x31\x74\x66\x66\ -\x73\x4c\x61\x79\x69\x6e\x66\x75\x76\x71\x58\x4c\x32\x4f\x37\x4a\ -\x42\x42\x2f\x56\x50\x35\x38\x2b\x64\x7a\x36\x4f\x58\x34\x6a\x51\ -\x56\x46\x65\x44\x37\x45\x34\x6c\x55\x72\x6f\x65\x58\x42\x36\x4d\ -\x65\x6c\x31\x63\x33\x34\x67\x2b\x45\x75\x32\x76\x20\x7a\x5a\x35\ -\x4c\x56\x57\x4d\x7a\x62\x39\x77\x78\x36\x57\x66\x66\x6c\x63\x33\ -\x47\x6b\x4c\x78\x73\x4a\x70\x30\x31\x68\x70\x2f\x4b\x4b\x35\x6e\ -\x78\x36\x4c\x31\x55\x31\x6a\x65\x78\x61\x6c\x73\x46\x4b\x38\x73\ -\x72\x57\x62\x6d\x6a\x48\x4c\x74\x52\x6a\x30\x46\x2f\x35\x4d\x61\ -\x38\x4f\x7a\x30\x52\x55\x65\x54\x78\x20\x6a\x36\x59\x7a\x62\x33\ -\x73\x44\x5a\x31\x35\x38\x4c\x57\x46\x56\x78\x52\x63\x4a\x59\x55\ -\x76\x78\x34\x4c\x48\x61\x4d\x47\x62\x6c\x30\x4e\x48\x53\x79\x45\ -\x5a\x6e\x4a\x71\x75\x71\x6d\x35\x6c\x63\x57\x6f\x6b\x75\x34\x43\ -\x66\x48\x70\x43\x50\x4e\x59\x6f\x71\x70\x4c\x69\x31\x47\x49\x79\ -\x61\x4e\x42\x6f\x76\x4f\x20\x67\x4b\x67\x6f\x69\x4b\x70\x43\x4f\ -\x42\x4a\x45\x57\x31\x6e\x47\x43\x35\x64\x4e\x34\x4a\x36\x4c\x4a\ -\x2b\x77\x7a\x6b\x54\x34\x34\x38\x51\x49\x32\x56\x65\x32\x69\x66\ -\x48\x63\x39\x7a\x39\x39\x77\x46\x53\x61\x44\x6e\x6e\x55\x56\x4f\ -\x37\x47\x5a\x6a\x4d\x78\x59\x76\x68\x71\x62\x79\x59\x67\x2b\x78\ -\x73\x6c\x75\x20\x62\x33\x71\x33\x38\x72\x47\x59\x38\x4f\x31\x6e\ -\x66\x4d\x4b\x43\x79\x41\x76\x54\x35\x35\x43\x62\x36\x75\x62\x32\ -\x58\x35\x33\x56\x31\x63\x69\x44\x73\x76\x73\x41\x4d\x44\x77\x2f\ -\x6c\x38\x6c\x66\x4c\x79\x54\x4c\x34\x32\x4a\x51\x64\x68\x38\x43\ -\x45\x59\x46\x72\x58\x70\x35\x4d\x74\x73\x65\x46\x51\x61\x38\x2f\ -\x20\x5a\x69\x73\x66\x75\x38\x6c\x4d\x49\x42\x68\x45\x44\x41\x55\ -\x41\x55\x45\x57\x52\x53\x48\x6b\x5a\x35\x50\x52\x46\x47\x56\x68\ -\x4d\x70\x44\x73\x64\x47\x67\x30\x47\x76\x59\x35\x55\x52\x78\x4b\ -\x33\x6e\x33\x39\x32\x39\x4e\x30\x75\x4a\x5a\x70\x77\x57\x4a\x79\ -\x56\x45\x56\x4f\x48\x38\x43\x54\x62\x61\x66\x62\x36\x20\x75\x70\ -\x61\x31\x48\x59\x45\x67\x39\x37\x33\x7a\x45\x51\x39\x64\x64\x69\ -\x48\x2f\x66\x65\x69\x75\x62\x69\x4e\x58\x4a\x6f\x4d\x42\x52\x56\ -\x56\x4a\x73\x64\x76\x34\x7a\x64\x68\x54\x41\x63\x68\x4c\x64\x58\ -\x50\x78\x73\x33\x2f\x6a\x77\x55\x76\x4f\x4f\x32\x49\x74\x45\x4b\ -\x30\x66\x2f\x31\x34\x44\x70\x69\x4d\x51\x20\x5a\x50\x72\x53\x6c\ -\x5a\x77\x30\x6f\x4a\x41\x62\x7a\x78\x6e\x62\x62\x64\x61\x4c\x32\ -\x57\x68\x45\x56\x6d\x51\x55\x71\x77\x33\x62\x67\x43\x4c\x71\x66\ -\x52\x32\x6f\x51\x34\x5a\x44\x78\x56\x61\x75\x4f\x58\x2f\x73\x4d\ -\x58\x4d\x34\x37\x36\x2b\x39\x78\x65\x66\x6e\x62\x35\x39\x2f\x7a\ -\x65\x38\x76\x50\x43\x66\x71\x20\x6c\x2b\x70\x6d\x68\x52\x72\x39\ -\x54\x43\x55\x6a\x78\x55\x6c\x65\x57\x69\x70\x6e\x44\x69\x74\x43\ -\x56\x68\x54\x75\x6e\x2f\x49\x78\x42\x61\x6d\x75\x6d\x45\x34\x4a\ -\x36\x45\x37\x50\x54\x66\x39\x34\x6c\x79\x61\x54\x6d\x33\x45\x58\ -\x58\x45\x6c\x49\x46\x42\x43\x45\x4d\x49\x49\x73\x49\x53\x71\x64\ -\x2f\x68\x64\x5a\x20\x42\x6b\x41\x32\x47\x4d\x48\x70\x41\x71\x63\ -\x4c\x57\x56\x48\x59\x75\x62\x57\x55\x4f\x38\x61\x66\x47\x71\x4d\ -\x50\x53\x6f\x38\x5a\x63\x42\x67\x4d\x43\x49\x71\x43\x74\x37\x30\ -\x56\x77\x2b\x35\x79\x33\x72\x76\x6e\x4a\x69\x61\x63\x4f\x4c\x54\ -\x62\x2b\x74\x48\x72\x64\x47\x67\x30\x30\x44\x63\x39\x46\x59\x42\ -\x6e\x20\x72\x37\x2b\x43\x73\x43\x44\x79\x7a\x79\x38\x57\x38\x4d\ -\x68\x6c\x46\x38\x54\x6b\x6b\x44\x2f\x67\x57\x62\x33\x35\x6b\x74\ -\x31\x6b\x77\x72\x75\x58\x38\x56\x6c\x63\x55\x73\x72\x37\x33\x33\ -\x7a\x50\x35\x44\x73\x6d\x6b\x57\x79\x31\x39\x4e\x6a\x49\x69\x68\ -\x71\x4e\x37\x6c\x7a\x64\x2b\x57\x4c\x69\x66\x2b\x36\x2f\x20\x6e\ -\x5a\x72\x6d\x56\x6d\x35\x34\x39\x53\x30\x75\x48\x64\x6e\x7a\x75\ -\x30\x4c\x78\x78\x47\x6f\x32\x45\x68\x48\x43\x43\x4a\x45\x77\x68\ -\x45\x4f\x6f\x6f\x67\x68\x4a\x79\x57\x41\x77\x48\x44\x53\x66\x62\ -\x47\x39\x66\x6c\x55\x61\x6a\x59\x56\x48\x4a\x4a\x75\x70\x61\x32\ -\x6e\x6a\x35\x2b\x73\x74\x69\x30\x75\x4f\x79\x20\x32\x32\x6a\x78\ -\x52\x62\x64\x64\x74\x53\x32\x74\x4e\x48\x58\x34\x4f\x47\x74\x34\ -\x45\x59\x4f\x79\x4d\x33\x73\x4d\x6d\x5a\x76\x32\x53\x34\x53\x55\ -\x46\x59\x56\x6e\x70\x73\x33\x69\x38\x6c\x4e\x4f\x70\x48\x43\x2f\ -\x63\x4f\x6a\x68\x45\x70\x32\x74\x6f\x32\x33\x72\x44\x51\x5a\x35\ -\x66\x2b\x46\x33\x4a\x4e\x73\x73\x20\x6e\x4e\x41\x76\x37\x36\x41\ -\x64\x58\x31\x45\x55\x76\x4a\x30\x4f\x66\x45\x45\x53\x6f\x61\x4f\ -\x4e\x73\x39\x4e\x64\x54\x44\x71\x7a\x2b\x32\x7a\x6f\x6f\x38\x48\ -\x65\x32\x70\x73\x37\x66\x48\x79\x33\x71\x59\x7a\x69\x76\x47\x77\ -\x79\x55\x70\x77\x48\x31\x36\x36\x79\x54\x37\x52\x31\x30\x66\x70\ -\x53\x4b\x6e\x59\x33\x20\x38\x50\x53\x56\x46\x38\x56\x4e\x7a\x35\ -\x5a\x64\x75\x37\x6e\x70\x6a\x66\x63\x77\x35\x68\x55\x7a\x61\x50\ -\x41\x77\x66\x4a\x48\x77\x58\x75\x2b\x58\x43\x59\x52\x46\x67\x62\ -\x41\x6b\x45\x70\x59\x6b\x46\x46\x56\x46\x55\x65\x53\x66\x62\x39\ -\x54\x63\x79\x42\x6c\x70\x44\x6e\x35\x33\x33\x72\x69\x59\x39\x4a\ -\x6a\x31\x20\x42\x6b\x77\x61\x53\x44\x45\x5a\x71\x61\x76\x62\x68\ -\x61\x75\x39\x6a\x6b\x2b\x66\x75\x49\x38\x68\x75\x64\x6b\x39\x48\ -\x6f\x75\x68\x31\x2b\x6d\x51\x35\x48\x30\x6e\x35\x4c\x66\x6d\x4c\ -\x71\x4a\x76\x71\x6f\x76\x78\x51\x77\x62\x47\x70\x47\x64\x2f\x65\ -\x6d\x56\x57\x37\x57\x59\x7a\x2f\x6e\x41\x59\x53\x5a\x61\x5a\x20\ -\x76\x57\x49\x4e\x4b\x76\x44\x69\x70\x4b\x74\x78\x32\x4b\x77\x48\ -\x50\x64\x74\x44\x56\x64\x53\x75\x4b\x41\x6c\x45\x4f\x2b\x7a\x39\ -\x55\x7a\x37\x6d\x7a\x67\x6e\x6a\x4b\x4d\x37\x4e\x36\x72\x46\x63\ -\x50\x4c\x47\x62\x54\x43\x44\x4c\x71\x4d\x45\x41\x36\x72\x62\x4e\ -\x30\x59\x68\x48\x57\x73\x59\x68\x73\x38\x6d\x55\x20\x76\x62\x53\ -\x33\x65\x48\x30\x38\x4e\x32\x30\x57\x7a\x31\x31\x7a\x61\x63\x78\ -\x48\x56\x31\x68\x4e\x4a\x67\x4c\x68\x61\x43\x37\x46\x74\x61\x2b\ -\x38\x53\x55\x51\x55\x75\x65\x47\x73\x4d\x51\x65\x39\x72\x39\x6c\ -\x67\x32\x4d\x66\x68\x2f\x4f\x57\x71\x64\x56\x51\x33\x4e\x48\x4c\ -\x54\x6d\x57\x66\x45\x70\x41\x58\x32\x20\x2b\x50\x4d\x69\x4c\x43\ -\x34\x70\x35\x64\x71\x58\x33\x2b\x54\x57\x43\x65\x4f\x35\x2b\x5a\ -\x78\x78\x68\x35\x78\x78\x5a\x55\x57\x68\x49\x78\x54\x43\x48\x77\ -\x6d\x6a\x69\x69\x4b\x65\x70\x6a\x70\x65\x2f\x75\x31\x6c\x63\x54\ -\x33\x61\x34\x31\x44\x73\x30\x62\x36\x2b\x73\x6f\x6f\x72\x58\x76\ -\x77\x48\x70\x77\x37\x75\x20\x7a\x37\x58\x6a\x54\x6a\x75\x6b\x64\ -\x76\x55\x6f\x74\x65\x30\x65\x50\x64\x2b\x58\x62\x75\x47\x53\x6c\ -\x79\x61\x6a\x4c\x54\x77\x42\x64\x33\x35\x2f\x32\x6b\x50\x42\x36\ -\x50\x74\x6c\x34\x53\x44\x65\x63\x42\x68\x66\x4a\x49\x79\x2f\x36\ -\x2f\x32\x79\x43\x4b\x72\x4b\x7a\x2b\x4d\x6b\x45\x73\x62\x52\x57\ -\x4d\x76\x66\x20\x4a\x6c\x30\x64\x65\x31\x38\x7a\x47\x39\x47\x71\ -\x45\x72\x36\x36\x4b\x76\x49\x31\x41\x65\x59\x39\x2b\x51\x44\x46\ -\x65\x54\x6b\x48\x48\x62\x4e\x36\x72\x62\x5a\x72\x4e\x51\x5a\x51\ -\x73\x71\x4f\x61\x6d\x63\x74\x58\x38\x64\x68\x6c\x46\x38\x61\x6b\ -\x70\x54\x74\x36\x5a\x33\x79\x73\x5a\x6c\x70\x39\x66\x6a\x35\x65\ -\x20\x73\x6f\x78\x6c\x5a\x64\x73\x34\x6f\x32\x67\x41\x32\x5a\x35\ -\x44\x48\x34\x65\x68\x71\x45\x72\x58\x43\x69\x49\x69\x69\x74\x7a\ -\x37\x39\x6b\x65\x4d\x48\x56\x54\x49\x78\x4a\x4e\x50\x6a\x45\x6e\ -\x30\x34\x57\x41\x7a\x6d\x36\x47\x78\x48\x6f\x51\x49\x44\x42\x6b\ -\x65\x39\x65\x76\x30\x41\x6b\x56\x56\x4f\x33\x4d\x69\x20\x56\x42\ -\x37\x2f\x61\x44\x71\x2f\x4f\x58\x31\x30\x7a\x4b\x73\x4d\x41\x4a\ -\x4e\x42\x54\x32\x31\x4c\x57\x7a\x51\x76\x36\x72\x45\x2f\x63\x4e\ -\x4b\x41\x37\x74\x2b\x4a\x32\x37\x66\x4d\x7a\x79\x75\x66\x75\x74\ -\x5a\x32\x6e\x70\x33\x36\x4f\x53\x39\x63\x66\x30\x56\x4d\x2f\x6f\ -\x6b\x39\x32\x4d\x78\x6d\x46\x71\x7a\x62\x20\x69\x44\x76\x5a\x7a\ -\x6a\x76\x33\x33\x49\x4c\x64\x62\x4f\x37\x56\x59\x56\x47\x4b\x49\ -\x74\x4d\x52\x44\x69\x49\x71\x4d\x72\x72\x71\x53\x70\x36\x2b\x35\ -\x4e\x79\x34\x31\x4d\x2f\x68\x59\x44\x4f\x62\x6d\x62\x75\x6d\x42\ -\x46\x6c\x52\x2b\x4f\x69\x42\x4f\x38\x6c\x4d\x63\x66\x61\x71\x33\ -\x4a\x35\x2b\x47\x65\x2b\x32\x20\x74\x5a\x6e\x4e\x7a\x46\x72\x78\ -\x45\x78\x50\x2f\x2f\x6a\x37\x32\x45\x30\x35\x48\x6c\x2b\x4b\x6d\ -\x4a\x65\x43\x6e\x4a\x65\x69\x6e\x4a\x52\x69\x67\x4c\x52\x6a\x6f\ -\x66\x4d\x45\x31\x69\x43\x38\x63\x4e\x64\x79\x42\x53\x49\x53\x75\ -\x73\x4b\x71\x71\x6f\x71\x6e\x63\x78\x70\x4f\x58\x54\x6d\x42\x77\ -\x39\x75\x47\x64\x20\x6d\x64\x4d\x64\x79\x56\x59\x4c\x35\x64\x75\ -\x33\x63\x4b\x4c\x48\x7a\x4f\x65\x50\x33\x6b\x64\x57\x4c\x38\x34\ -\x46\x30\x75\x74\x30\x58\x65\x48\x33\x73\x43\x42\x77\x37\x7a\x73\ -\x66\x38\x76\x54\x56\x6c\x2b\x4b\x77\x78\x66\x39\x30\x7a\x31\x34\ -\x5a\x6e\x32\x53\x7a\x6d\x59\x2b\x58\x4c\x4b\x4e\x66\x5a\x68\x71\ -\x50\x20\x58\x6e\x6b\x4a\x78\x6c\x37\x6d\x6c\x69\x69\x64\x6a\x6c\ -\x78\x46\x55\x58\x6a\x36\x30\x38\x39\x4a\x74\x68\x68\x6a\x58\x6b\ -\x6f\x65\x4c\x72\x6d\x70\x4c\x72\x4c\x4e\x42\x6e\x54\x4e\x6a\x64\ -\x44\x52\x44\x6f\x4c\x51\x62\x55\x37\x46\x2f\x71\x69\x64\x32\x75\ -\x65\x75\x4b\x61\x47\x68\x72\x59\x32\x72\x7a\x78\x67\x64\x20\x46\ -\x7a\x31\x4a\x5a\x6a\x4e\x6e\x44\x4f\x72\x50\x79\x7a\x4f\x2f\x34\ -\x74\x6d\x70\x73\x35\x69\x33\x5a\x67\x50\x4e\x48\x62\x36\x44\x35\ -\x6a\x32\x5a\x6a\x64\x48\x6b\x74\x59\x67\x6f\x63\x76\x2b\x55\x6a\ -\x33\x6e\x67\x34\x6e\x50\x4a\x63\x76\x56\x75\x6f\x42\x32\x4b\x33\ -\x46\x51\x58\x32\x32\x76\x72\x65\x47\x76\x75\x20\x59\x74\x5a\x58\ -\x56\x74\x48\x6b\x39\x66\x55\x71\x41\x56\x52\x56\x56\x63\x4b\x69\ -\x41\x4b\x33\x4e\x58\x4a\x44\x6c\x69\x56\x76\x39\x48\x41\x35\x37\ -\x74\x4c\x2f\x2b\x35\x51\x49\x32\x56\x75\x33\x71\x74\x58\x62\x6c\ -\x4b\x4c\x56\x74\x54\x6d\x6f\x4b\x32\x32\x72\x72\x55\x45\x77\x57\ -\x57\x6c\x75\x61\x61\x47\x35\x76\x20\x6f\x54\x58\x6f\x70\x7a\x58\ -\x6f\x70\x79\x33\x6f\x70\x79\x30\x55\x6f\x4c\x30\x7a\x35\x38\x7a\ -\x62\x61\x58\x78\x45\x57\x61\x4a\x72\x2f\x39\x2f\x55\x77\x4e\x6c\ -\x5a\x71\x66\x78\x32\x33\x43\x6b\x48\x66\x55\x35\x76\x4f\x57\x31\ -\x67\x49\x56\x65\x63\x63\x69\x4b\x62\x71\x71\x71\x35\x39\x35\x30\ -\x50\x6d\x62\x35\x30\x20\x4a\x58\x57\x74\x37\x51\x64\x73\x71\x2f\ -\x5a\x47\x72\x34\x75\x75\x66\x42\x52\x46\x34\x66\x6e\x70\x63\x78\ -\x68\x58\x31\x4a\x39\x52\x68\x58\x33\x6a\x6f\x75\x65\x41\x5a\x2f\ -\x58\x6d\x53\x30\x55\x35\x66\x58\x6a\x32\x6d\x6f\x6e\x38\x66\x64\ -\x62\x58\x31\x4c\x56\x37\x79\x55\x39\x50\x34\x39\x77\x52\x78\x5a\ -\x77\x35\x20\x72\x49\x6a\x63\x56\x48\x65\x50\x4d\x2b\x57\x65\x51\ -\x37\x6a\x65\x58\x66\x41\x74\x32\x32\x76\x72\x6d\x48\x7a\x62\x74\ -\x63\x66\x4d\x47\x62\x6d\x48\x34\x74\x77\x73\x56\x72\x7a\x34\x4f\ -\x47\x73\x71\x64\x72\x4b\x67\x70\x4a\x51\x46\x6d\x37\x65\x7a\x50\ -\x52\x42\x42\x54\x58\x46\x42\x69\x67\x65\x4d\x78\x6d\x36\x33\x20\ -\x59\x49\x71\x71\x30\x74\x6a\x68\x35\x53\x2f\x2f\x6e\x63\x6d\x48\ -\x39\x39\x37\x53\x61\x34\x4e\x37\x4b\x49\x77\x47\x50\x53\x39\x50\ -\x75\x70\x4b\x4f\x59\x49\x69\x31\x46\x54\x75\x5a\x75\x33\x6f\x4e\ -\x4c\x30\x79\x66\x6a\x54\x73\x35\x69\x51\x6b\x6e\x44\x75\x4f\x69\ -\x30\x53\x65\x51\x35\x55\x37\x5a\x70\x30\x35\x4e\x20\x6e\x65\x38\ -\x6b\x66\x62\x42\x6f\x4b\x52\x61\x44\x6a\x6f\x74\x48\x39\x33\x77\ -\x65\x7a\x4f\x46\x53\x6e\x4a\x76\x46\x30\x75\x63\x66\x5a\x55\x33\ -\x46\x54\x72\x35\x65\x74\x59\x62\x6e\x50\x35\x74\x44\x75\x74\x50\ -\x42\x2b\x53\x4f\x48\x63\x66\x36\x6f\x45\x66\x52\x78\x64\x65\x2b\ -\x34\x52\x56\x56\x42\x69\x4a\x44\x53\x20\x55\x4d\x76\x2f\x50\x58\ -\x56\x2f\x33\x4f\x72\x6e\x63\x4c\x58\x2f\x32\x4e\x6d\x32\x68\x36\ -\x4e\x64\x56\x56\x55\x61\x32\x6a\x76\x69\x33\x72\x5a\x44\x63\x37\ -\x4e\x5a\x39\x74\x66\x48\x57\x4c\x6d\x39\x6b\x76\x6e\x72\x4e\x72\ -\x46\x77\x32\x54\x6f\x43\x52\x67\x74\x47\x54\x7a\x6f\x36\x64\x79\ -\x71\x4b\x30\x59\x41\x67\x20\x79\x55\x52\x6b\x45\x55\x6d\x57\x39\ -\x30\x30\x6a\x69\x34\x53\x78\x31\x65\x33\x69\x74\x57\x63\x65\x78\ -\x47\x77\x30\x78\x6b\x56\x50\x5a\x6f\x71\x44\x4b\x58\x66\x64\x69\ -\x43\x38\x55\x5a\x74\x32\x4f\x61\x68\x5a\x76\x4b\x4f\x4f\x31\x32\ -\x56\x2b\x54\x62\x4c\x56\x78\x7a\x6f\x68\x69\x4c\x6a\x6e\x70\x42\ -\x50\x72\x33\x20\x79\x64\x69\x6e\x6a\x6e\x52\x61\x48\x62\x4b\x69\ -\x73\x4c\x79\x73\x6e\x4f\x38\x32\x6c\x6a\x48\x7a\x6a\x33\x63\x64\ -\x6c\x57\x4f\x44\x34\x51\x69\x4f\x55\x5a\x56\x6c\x68\x55\x32\x37\ -\x61\x6c\x6d\x38\x73\x59\x79\x6c\x5a\x64\x73\x4a\x69\x53\x49\x6a\ -\x43\x76\x49\x59\x58\x7a\x79\x59\x6b\x59\x58\x35\x35\x4b\x58\x39\ -\x20\x66\x48\x35\x4a\x30\x56\x31\x2f\x35\x4d\x47\x4a\x46\x7a\x44\ -\x31\x32\x2b\x58\x38\x39\x2f\x37\x62\x59\x71\x37\x55\x65\x42\x32\ -\x31\x75\x57\x31\x33\x50\x66\x50\x58\x6c\x66\x4c\x4e\x68\x73\x32\ -\x73\x61\x57\x7a\x44\x61\x37\x5a\x43\x69\x68\x76\x73\x39\x6d\x67\ -\x61\x50\x75\x41\x71\x58\x63\x63\x5a\x2f\x66\x4f\x35\x20\x5a\x47\ -\x51\x78\x56\x35\x31\x2b\x55\x6b\x7a\x50\x36\x77\x30\x56\x39\x59\ -\x30\x73\x58\x46\x2f\x4b\x67\x67\x31\x6c\x4b\x4b\x72\x4b\x4b\x51\ -\x4d\x4c\x2b\x64\x58\x49\x34\x59\x77\x6f\x79\x45\x57\x44\x68\x67\ -\x47\x33\x50\x30\x52\x2b\x75\x70\x75\x70\x44\x39\x77\x52\x31\x30\ -\x50\x35\x75\x32\x4e\x50\x2f\x53\x7a\x61\x20\x57\x49\x5a\x47\x71\ -\x32\x58\x4d\x6b\x49\x47\x63\x64\x38\x4a\x51\x52\x68\x54\x6b\x59\ -\x65\x6c\x73\x51\x39\x4d\x31\x64\x36\x42\x61\x37\x66\x7a\x72\x69\ -\x67\x6c\x78\x71\x5a\x39\x34\x74\x2b\x33\x42\x74\x41\x2b\x38\x34\ -\x79\x47\x47\x35\x2b\x63\x78\x59\x64\x69\x67\x6f\x39\x36\x32\x4b\ -\x37\x5a\x57\x73\x4c\x42\x6b\x20\x4d\x30\x73\x32\x62\x57\x46\x6a\ -\x71\x35\x64\x49\x6b\x69\x4d\x61\x31\x62\x49\x6e\x52\x64\x2b\x6d\ -\x56\x32\x54\x59\x73\x42\x61\x64\x32\x63\x79\x72\x6c\x35\x7a\x4e\ -\x54\x57\x66\x46\x37\x73\x63\x37\x46\x4e\x56\x4e\x4c\x53\x77\x6f\ -\x4b\x57\x58\x2b\x2b\x6c\x4a\x38\x6f\x51\x69\x6a\x2b\x75\x64\x7a\ -\x77\x61\x67\x52\x20\x6a\x43\x72\x4d\x52\x36\x76\x56\x4d\x75\x61\ -\x52\x5a\x33\x48\x61\x72\x4c\x77\x36\x36\x61\x72\x44\x50\x6a\x4b\ -\x31\x4f\x33\x70\x71\x32\x79\x4d\x2b\x77\x78\x6d\x69\x44\x75\x51\ -\x32\x66\x35\x42\x4e\x75\x32\x72\x35\x66\x6e\x4d\x35\x4a\x54\x74\ -\x33\x67\x55\x62\x44\x71\x50\x37\x35\x6a\x42\x39\x61\x78\x42\x55\ -\x76\x20\x2f\x49\x4f\x69\x37\x45\x77\x2b\x75\x4f\x64\x57\x4d\x6c\ -\x32\x4f\x6f\x2f\x5a\x48\x48\x43\x6d\x79\x72\x46\x44\x66\x34\x65\ -\x58\x48\x4c\x65\x58\x4d\x4b\x79\x6c\x6a\x61\x57\x55\x56\x6a\x52\ -\x6f\x44\x6b\x69\x4d\x46\x54\x66\x6b\x57\x4c\x68\x38\x31\x6c\x48\ -\x66\x75\x6e\x48\x52\x4d\x6e\x61\x69\x4b\x6f\x74\x44\x6b\x20\x39\ -\x62\x47\x36\x66\x43\x63\x4c\x4e\x32\x36\x6d\x6f\x72\x36\x4a\x76\ -\x75\x6d\x70\x54\x50\x31\x2b\x42\x54\x4d\x66\x2b\x54\x31\x6a\x69\ -\x77\x59\x63\x4d\x79\x31\x37\x31\x38\x2b\x69\x54\x56\x75\x70\x62\ -\x6d\x35\x68\x61\x46\x34\x75\x45\x30\x34\x63\x78\x70\x55\x76\x76\ -\x63\x37\x46\x49\x34\x66\x78\x37\x6c\x33\x78\x20\x71\x5a\x2b\x6a\ -\x32\x62\x62\x37\x61\x2f\x2f\x4e\x2f\x37\x33\x42\x68\x53\x4f\x48\ -\x38\x63\x36\x64\x4e\x78\x79\x7a\x74\x68\x55\x6c\x6d\x5a\x71\x57\ -\x56\x72\x37\x5a\x73\x4a\x6e\x35\x4a\x57\x57\x73\x72\x61\x6d\x6e\ -\x56\x57\x64\x41\x63\x61\x54\x41\x39\x69\x33\x38\x61\x76\x67\x51\ -\x50\x72\x6e\x76\x6c\x70\x68\x66\x20\x6c\x7a\x6b\x63\x46\x45\x57\ -\x68\x78\x52\x64\x67\x62\x65\x56\x4f\x35\x71\x2f\x66\x54\x46\x6c\ -\x74\x48\x65\x6c\x4f\x4a\x37\x4e\x57\x2f\x4d\x52\x4c\x4e\x31\x7a\ -\x42\x37\x65\x65\x4e\x6a\x38\x74\x7a\x6a\x6f\x72\x78\x36\x59\x36\ -\x61\x35\x6c\x62\x57\x37\x61\x6a\x6d\x2b\x38\x33\x6c\x37\x47\x68\ -\x73\x34\x72\x6c\x72\x20\x4a\x75\x35\x7a\x4a\x45\x55\x73\x48\x49\ -\x33\x2f\x58\x6d\x56\x76\x66\x4b\x45\x77\x61\x79\x75\x72\x57\x4c\ -\x53\x78\x6a\x4b\x32\x31\x64\x62\x77\x79\x36\x57\x70\x79\x65\x75\ -\x46\x59\x50\x35\x71\x45\x49\x69\x4b\x6c\x75\x32\x72\x77\x68\x73\ -\x4b\x4d\x48\x7a\x4c\x77\x6d\x4a\x34\x53\x75\x44\x39\x48\x73\x33\ -\x35\x2b\x20\x61\x57\x33\x62\x31\x4f\x48\x6a\x70\x2b\x30\x37\x57\ -\x56\x43\x79\x69\x62\x4c\x61\x4f\x74\x36\x38\x37\x58\x6f\x4b\x4d\ -\x6d\x4a\x4c\x47\x49\x32\x56\x69\x43\x69\x79\x65\x64\x64\x75\x56\ -\x70\x58\x76\x59\x4e\x4b\x5a\x70\x32\x4f\x4f\x30\x35\x47\x70\x78\ -\x38\x7a\x34\x4a\x45\x69\x51\x49\x45\x46\x76\x4f\x48\x37\x54\x20\ -\x61\x49\x49\x45\x43\x58\x37\x52\x4a\x49\x78\x50\x67\x67\x51\x4a\ -\x6a\x67\x73\x4a\x34\x35\x4d\x67\x51\x59\x4c\x6a\x51\x73\x4c\x34\ -\x4a\x45\x69\x51\x34\x4c\x69\x51\x4d\x44\x34\x4a\x45\x69\x51\x34\ -\x4c\x69\x53\x4d\x54\x34\x49\x45\x43\x59\x34\x4c\x43\x65\x4f\x54\ -\x49\x45\x47\x43\x34\x30\x4c\x43\x2b\x43\x52\x49\x20\x6b\x4f\x43\ -\x34\x6b\x44\x41\x2b\x43\x52\x49\x6b\x4f\x43\x34\x6b\x6a\x45\x2b\ -\x43\x42\x41\x6d\x4f\x43\x2f\x38\x50\x32\x32\x63\x47\x79\x2b\x42\ -\x2f\x69\x58\x30\x41\x41\x41\x41\x41\x53\x55\x56\x4f\x52\x4b\x35\ -\x43\x59\x49\x49\x3d\x20\x22\x20\x68\x65\x69\x67\x68\x74\x3d\x22\ -\x34\x31\x22\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x38\x37\x22\x20\ -\x79\x3d\x22\x2d\x36\x35\x35\x2e\x33\x37\x22\x20\x78\x3d\x22\x31\ -\x32\x39\x39\x2e\x37\x22\x20\x70\x72\x65\x73\x65\x72\x76\x65\x41\ -\x73\x70\x65\x63\x74\x52\x61\x74\x69\x6f\x3d\x22\x6e\x6f\x6e\x65\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\ -\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x33\x33\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\ -\x2d\x35\x39\x31\x2e\x38\x33\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x34\x37\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x35\x36\x36\x2e\x35\x39\ -\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x20\x32\x35\ -\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x33\x34\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\ -\x32\x2d\x35\x39\x31\x2e\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\ -\x38\x2e\x34\x35\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x33\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x35\x38\x2e\ -\x31\x34\x76\x33\x32\x6c\x2d\x33\x31\x2e\x35\x34\x37\x2d\x38\x2e\ -\x34\x35\x33\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x32\ -\x36\x2e\x31\x34\x20\x32\x35\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\ -\x33\x38\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x37\ -\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x39\x31\ -\x2e\x38\x33\x76\x33\x32\x6c\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x39\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x35\x39\x2e\ -\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x36\x31\x22\x20\x64\x3d\x22\x6d\x31\ -\x32\x33\x36\x2e\x36\x2d\x36\x35\x36\x2e\x32\x38\x2d\x31\x32\x2e\ -\x36\x31\x39\x20\x31\x32\x2e\x36\x31\x39\x76\x31\x36\x6c\x31\x38\ -\x2e\x39\x32\x38\x20\x35\x2e\x30\x37\x31\x38\x76\x2d\x31\x36\x6c\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x36\x33\x22\x20\x64\x3d\x22\x6d\x31\x32\ -\x34\x33\x2d\x36\x32\x32\x2e\x35\x39\x20\x31\x32\x2e\x36\x31\x39\ -\x2d\x31\x32\x2e\x36\x31\x39\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x36\x33\x38\x2e\ -\x35\x39\x20\x31\x32\x2e\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\ -\x76\x31\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x37\x22\x20\x64\ -\x3d\x22\x6d\x31\x32\x35\x35\x2e\x36\x2d\x36\x35\x31\x2e\x32\x31\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x76\x31\ -\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x32\x32\x34\x2d\x36\x32\x37\x2e\x36\x36\x20\x31\x32\x2e\ -\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\x20\x31\x38\x2e\x39\x32\ -\x38\x20\x35\x2e\x30\x37\x31\x38\x22\x2f\x3e\x0a\x20\x20\x20\x3c\ -\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x31\ -\x22\x20\x64\x3d\x22\x6d\x31\x33\x33\x38\x2e\x31\x2d\x35\x35\x39\ -\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\ -\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\ -\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\ -\x37\x33\x22\x20\x64\x3d\x22\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\ -\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\ -\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\ -\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x37\x37\x22\x20\x64\x3d\x22\x6d\x31\ -\x33\x35\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\ -\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\ -\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x31\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x36\x36\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x20\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3d\x22\ -\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\x69\x6c\x6c\x2d\x6f\x70\ -\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\x37\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\ -\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x31\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x32\x30\x22\x20\x64\x3d\x22\x6d\x31\x33\x38\x36\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x36\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x32\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x32\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x20\x66\x69\x6c\x6c\x2d\ -\x72\x75\x6c\x65\x3d\x22\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\ -\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\ -\x36\x36\x37\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\ -\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\ -\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\ -\x6c\x3d\x22\x23\x30\x30\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\ -\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x34\x34\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x38\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x38\x30\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x30\x22\x20\ -\x64\x3d\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x35\x36\x2e\x34\ -\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\ -\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\ -\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x34\x34\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x30\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x30\x22\x20\x66\x69\x6c\ -\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\ -\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x39\x34\x2e\x32\x2d\x35\x35\x30\x2e\x34\x36\ -\x20\x30\x2e\x30\x30\x31\x2d\x35\x2e\x38\x36\x36\x36\x20\x32\x2e\ -\x36\x35\x32\x31\x2d\x32\x2e\x39\x37\x30\x35\x63\x31\x2e\x34\x35\ -\x38\x37\x2d\x31\x2e\x36\x33\x33\x38\x20\x32\x2e\x36\x37\x38\x37\ -\x2d\x32\x2e\x39\x39\x38\x31\x20\x32\x2e\x37\x31\x31\x32\x2d\x33\ -\x2e\x30\x33\x31\x39\x20\x30\x2e\x30\x33\x35\x2d\x30\x2e\x30\x33\ -\x36\x38\x20\x30\x2e\x30\x35\x39\x20\x32\x2e\x31\x37\x30\x39\x20\ -\x30\x2e\x30\x35\x39\x20\x35\x2e\x35\x38\x35\x39\x76\x35\x2e\x36\ -\x34\x37\x32\x6c\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\ -\x31\x34\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\x31\x34\ -\x76\x2d\x35\x2e\x38\x36\x36\x38\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\ -\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\ -\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\ -\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ -\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x34\x38\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x39\ -\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\ -\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\ -\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x34\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x34\x30\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\ -\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\ -\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\ -\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x31\x34\x2d\x35\x36\x33\x2e\x35\ -\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x39\x30\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x37\x2e\x37\x2d\x35\ -\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\ -\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x30\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x30\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\ -\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\ -\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x30\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x31\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\ -\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x32\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x35\x32\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x36\x35\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\ -\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\ -\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\ -\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x31\x36\x22\x20\x64\x3d\x22\x6d\x31\x34\x37\x32\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x31\x38\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\ -\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\ -\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\ -\x67\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x32\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x36\x2e\x39\x2d\x35\x36\x36\ -\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\ -\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x36\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x37\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\ -\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\x2e\x31\x2d\x35\x35\x39\x2e\ -\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\ -\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\ -\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x33\ -\x30\x22\x20\x64\x3d\x22\x6d\x31\x35\x32\x31\x2e\x37\x2d\x35\x35\ -\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\ -\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\ -\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x35\ -\x32\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x35\x33\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x35\x32\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\ -\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x3c\ -\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ -\x00\x00\x4e\x4c\ -\x3c\ -\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ -\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ -\x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ -\x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ -\x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ -\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ -\x3c\x73\x76\x67\x20\x69\x64\x3d\x22\x73\x76\x67\x32\x22\x20\x78\ -\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\ -\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\x39\ -\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\x2d\x73\x79\x6e\x74\x61\ -\x78\x2d\x6e\x73\x23\x22\x20\x78\x6d\x6c\x6e\x73\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x68\x65\x69\x67\x68\x74\ -\x3d\x22\x32\x33\x2e\x39\x39\x34\x22\x20\x77\x69\x64\x74\x68\x3d\ -\x22\x32\x30\x2e\x39\x36\x31\x22\x20\x76\x65\x72\x73\x69\x6f\x6e\ -\x3d\x22\x31\x2e\x31\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\x3d\ -\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\x65\ -\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\x22\ -\x20\x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x31\x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x76\x69\x65\x77\ -\x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x30\x2e\x39\x36\x30\x37\ -\x38\x34\x20\x32\x33\x2e\x39\x39\x33\x35\x39\x31\x22\x20\x78\x6d\ -\x6c\x6e\x73\x3a\x64\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\ -\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\ -\x6e\x74\x73\x2f\x31\x2e\x31\x2f\x22\x3e\x0a\x20\x3c\x6d\x65\x74\ -\x61\x64\x61\x74\x61\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ -\x74\x61\x37\x22\x3e\x0a\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\ -\x3e\x0a\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x20\x72\x64\ -\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\ -\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\ -\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\ -\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ -\x65\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\ -\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\ -\x6c\x49\x6d\x61\x67\x65\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x64\ -\x63\x3a\x74\x69\x74\x6c\x65\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x63\ -\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x3c\x2f\x72\x64\x66\x3a\ -\x52\x44\x46\x3e\x0a\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ -\x3e\x0a\x20\x3c\x67\x20\x69\x64\x3d\x22\x6c\x61\x79\x65\x72\x31\ -\x22\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x74\x72\x61\ -\x6e\x73\x6c\x61\x74\x65\x28\x2d\x31\x33\x33\x37\x2e\x36\x20\x35\ -\x36\x36\x2e\x38\x34\x29\x22\x3e\x0a\x20\x20\x3c\x67\x20\x66\x69\ -\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\ -\x36\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x3e\ -\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x33\x36\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\ -\x2e\x33\x2d\x35\x35\x33\x2e\x32\x39\x63\x30\x2d\x34\x2e\x33\x34\ -\x33\x31\x20\x30\x2e\x30\x31\x31\x2d\x35\x2e\x34\x32\x34\x33\x20\ -\x30\x2e\x30\x36\x2d\x35\x2e\x34\x32\x34\x33\x20\x30\x2e\x30\x36\ -\x31\x20\x30\x20\x38\x2e\x33\x34\x31\x39\x20\x31\x2e\x38\x31\x33\ -\x32\x20\x38\x2e\x33\x35\x35\x39\x20\x31\x2e\x38\x32\x39\x37\x20\ -\x30\x20\x30\x20\x30\x2e\x30\x32\x34\x20\x30\x2e\x36\x32\x30\x34\ -\x33\x20\x30\x2e\x30\x34\x32\x20\x31\x2e\x33\x36\x37\x33\x6c\x30\ -\x2e\x30\x33\x34\x20\x31\x2e\x33\x35\x37\x39\x2d\x34\x2e\x32\x34\ -\x35\x38\x20\x33\x2e\x31\x34\x36\x39\x2d\x34\x2e\x32\x34\x35\x39\ -\x20\x33\x2e\x31\x34\x36\x39\x76\x2d\x35\x2e\x34\x32\x34\x33\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x35\x33\x38\x22\x20\x64\x3d\x22\x6d\x31\ -\x35\x31\x32\x2e\x38\x2d\x35\x35\x38\x2e\x36\x34\x63\x2d\x32\x2e\ -\x31\x37\x39\x34\x2d\x30\x2e\x34\x36\x37\x31\x33\x2d\x33\x2e\x39\ -\x39\x35\x32\x2d\x30\x2e\x38\x35\x36\x31\x33\x2d\x34\x2e\x30\x33\ -\x35\x2d\x30\x2e\x38\x36\x34\x35\x35\x2d\x30\x2e\x30\x33\x39\x2d\ -\x30\x2e\x30\x31\x30\x37\x20\x31\x2e\x37\x32\x39\x34\x2d\x31\x2e\ -\x33\x38\x32\x39\x20\x33\x2e\x39\x33\x31\x34\x2d\x33\x2e\x30\x35\ -\x34\x36\x20\x32\x2e\x32\x30\x32\x32\x2d\x31\x2e\x36\x37\x31\x36\ -\x20\x34\x2e\x30\x31\x31\x39\x2d\x33\x2e\x30\x33\x31\x36\x20\x34\ -\x2e\x30\x32\x31\x36\x2d\x33\x2e\x30\x32\x32\x32\x20\x30\x2e\x30\ -\x32\x31\x20\x30\x2e\x30\x31\x39\x32\x20\x30\x2e\x31\x36\x39\x31\ -\x20\x36\x2e\x33\x37\x38\x37\x20\x30\x2e\x31\x36\x39\x34\x20\x37\ -\x2e\x32\x34\x31\x31\x20\x30\x2e\x30\x30\x30\x32\x20\x30\x2e\x34\ -\x31\x38\x38\x39\x2d\x30\x2e\x30\x31\x34\x20\x30\x2e\x35\x35\x38\ -\x34\x37\x2d\x30\x2e\x30\x36\x32\x20\x30\x2e\x35\x35\x34\x36\x34\ -\x2d\x30\x2e\x30\x33\x35\x20\x30\x2d\x31\x2e\x38\x34\x35\x36\x2d\ -\x30\x2e\x33\x38\x37\x33\x31\x2d\x34\x2e\x30\x32\x35\x33\x2d\x30\ -\x2e\x38\x35\x34\x34\x33\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x30\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x35\x39\x2e\x34\x2d\x35\x34\x35\ -\x2e\x34\x33\x63\x2d\x33\x2e\x33\x32\x36\x32\x2d\x30\x2e\x39\x32\ -\x33\x32\x33\x2d\x36\x2e\x31\x37\x37\x38\x2d\x31\x2e\x37\x31\x33\ -\x33\x2d\x36\x2e\x33\x33\x36\x38\x2d\x31\x2e\x37\x35\x35\x37\x2d\ -\x30\x2e\x32\x37\x38\x31\x2d\x30\x2e\x30\x37\x34\x34\x2d\x30\x2e\ -\x31\x32\x30\x39\x2d\x30\x2e\x32\x30\x32\x37\x39\x20\x34\x2e\x30\ -\x31\x35\x31\x2d\x33\x2e\x32\x38\x38\x37\x20\x32\x2e\x33\x36\x37\ -\x36\x2d\x31\x2e\x37\x36\x36\x35\x20\x34\x2e\x33\x37\x30\x31\x2d\ -\x33\x2e\x32\x30\x35\x39\x20\x34\x2e\x34\x35\x30\x32\x2d\x33\x2e\ -\x31\x39\x38\x35\x20\x30\x2e\x30\x38\x20\x30\x2e\x30\x31\x30\x38\ -\x20\x31\x2e\x30\x33\x33\x34\x20\x30\x2e\x32\x37\x35\x34\x32\x20\ -\x32\x2e\x31\x31\x38\x38\x20\x30\x2e\x35\x39\x35\x38\x37\x20\x31\ -\x2e\x30\x38\x35\x34\x20\x30\x2e\x33\x32\x30\x35\x37\x20\x31\x2e\ -\x39\x38\x38\x39\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x32\x2e\x30\ -\x30\x37\x38\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x30\x2e\x30\x31\ -\x39\x20\x30\x20\x30\x2e\x30\x33\x35\x20\x31\x2e\x39\x36\x39\x39\ -\x20\x30\x2e\x30\x33\x35\x20\x34\x2e\x33\x37\x37\x35\x20\x30\x20\ -\x33\x2e\x34\x34\x31\x31\x2d\x30\x2e\x30\x32\x36\x20\x34\x2e\x33\ -\x37\x36\x33\x2d\x30\x2e\x31\x32\x30\x39\x20\x34\x2e\x33\x37\x31\ -\x35\x2d\x30\x2e\x30\x36\x36\x20\x30\x2d\x32\x2e\x38\x34\x32\x34\ -\x2d\x30\x2e\x37\x36\x31\x32\x37\x2d\x36\x2e\x31\x36\x38\x35\x2d\ -\x31\x2e\x36\x38\x34\x36\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x32\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\x2e\x39\x2d\x35\x34\x38\ -\x2e\x30\x39\x63\x30\x2d\x32\x2e\x31\x37\x33\x35\x20\x30\x2e\x30\ -\x32\x2d\x33\x2e\x39\x35\x31\x38\x20\x30\x2e\x30\x34\x37\x2d\x33\ -\x2e\x39\x35\x31\x38\x20\x30\x2e\x31\x30\x36\x31\x20\x30\x20\x35\ -\x2e\x32\x33\x37\x20\x31\x2e\x35\x30\x34\x31\x20\x35\x2e\x32\x38\ -\x32\x36\x20\x31\x2e\x35\x34\x38\x37\x20\x30\x2e\x30\x33\x35\x20\ -\x30\x2e\x30\x33\x35\x2d\x34\x2e\x34\x39\x35\x20\x35\x2e\x34\x34\ -\x35\x32\x2d\x35\x2e\x32\x34\x32\x20\x36\x2e\x32\x35\x39\x33\x2d\ -\x30\x2e\x30\x34\x38\x20\x30\x2e\x30\x35\x33\x2d\x30\x2e\x30\x38\ -\x38\x2d\x31\x2e\x36\x36\x39\x35\x2d\x30\x2e\x30\x38\x38\x2d\x33\ -\x2e\x38\x35\x36\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\x35\x35\x33\x2e\ -\x38\x2d\x31\x2e\x37\x38\x30\x33\x2d\x30\x2e\x35\x33\x32\x39\x76\ -\x2d\x31\x2e\x31\x37\x38\x37\x63\x30\x2d\x31\x2e\x31\x36\x31\x37\ -\x20\x30\x2d\x31\x2e\x31\x37\x38\x20\x30\x2e\x32\x30\x35\x34\x2d\ -\x31\x2e\x31\x32\x35\x32\x20\x30\x2e\x31\x31\x32\x38\x20\x30\x2e\ -\x30\x32\x39\x39\x20\x30\x2e\x39\x34\x36\x20\x30\x2e\x32\x31\x35\ -\x38\x38\x20\x31\x2e\x38\x35\x31\x36\x20\x30\x2e\x34\x31\x33\x39\ -\x31\x6c\x31\x2e\x36\x34\x36\x31\x20\x30\x2e\x33\x36\x30\x32\x39\ -\x76\x31\x2e\x33\x30\x36\x33\x63\x30\x20\x30\x2e\x37\x31\x38\x34\ -\x36\x2d\x30\x2e\x30\x33\x32\x20\x31\x2e\x33\x30\x32\x34\x2d\x30\ -\x2e\x30\x37\x32\x20\x31\x2e\x32\x39\x37\x38\x2d\x30\x2e\x30\x33\ -\x39\x20\x30\x2d\x30\x2e\x38\x37\x32\x33\x2d\x30\x2e\x32\x34\x38\ -\x33\x32\x2d\x31\x2e\x38\x35\x31\x36\x2d\x30\x2e\x35\x34\x31\x35\ -\x32\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x31\x30\x2e\x38\x2d\x35\x35\x32\x2e\x31\x38\x2d\x32\ -\x2e\x36\x38\x31\x31\x2d\x30\x2e\x37\x38\x35\x33\x34\x76\x2d\x31\ -\x2e\x36\x35\x39\x33\x2d\x31\x2e\x36\x35\x39\x33\x6c\x32\x2e\x36\ -\x31\x37\x32\x2d\x32\x2e\x38\x38\x36\x33\x63\x31\x2e\x34\x33\x39\ -\x34\x2d\x31\x2e\x35\x38\x37\x35\x20\x32\x2e\x36\x37\x37\x34\x2d\ -\x32\x2e\x39\x34\x36\x38\x20\x32\x2e\x37\x35\x30\x39\x2d\x33\x2e\ -\x30\x32\x30\x36\x20\x30\x2e\x31\x31\x36\x32\x2d\x30\x2e\x31\x31\ -\x36\x36\x34\x20\x30\x2e\x31\x33\x33\x38\x20\x30\x2e\x35\x38\x33\ -\x37\x39\x20\x30\x2e\x31\x33\x33\x38\x20\x35\x2e\x33\x33\x39\x39\ -\x20\x30\x20\x33\x2e\x30\x31\x30\x38\x20\x30\x2e\x31\x30\x30\x33\ -\x20\x35\x2e\x35\x30\x32\x34\x20\x30\x2e\x30\x36\x31\x20\x35\x2e\ -\x34\x39\x37\x36\x2d\x30\x2e\x30\x33\x39\x20\x30\x2d\x31\x2e\x34\ -\x30\x38\x2d\x30\x2e\x33\x39\x34\x36\x34\x2d\x32\x2e\x38\x38\x32\ -\x34\x2d\x30\x2e\x38\x32\x36\x35\x39\x7a\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x39\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\ -\x35\x35\x37\x2e\x31\x34\x2d\x31\x2e\x37\x31\x34\x37\x2d\x30\x2e\ -\x33\x39\x33\x38\x33\x2d\x30\x2e\x30\x35\x38\x2d\x32\x2e\x32\x32\ -\x36\x34\x63\x2d\x30\x2e\x30\x39\x36\x2d\x33\x2e\x37\x34\x33\x32\ -\x2d\x30\x2e\x32\x31\x38\x33\x2d\x35\x2e\x39\x33\x31\x39\x2d\x30\ -\x2e\x31\x31\x34\x37\x2d\x35\x2e\x39\x33\x31\x39\x20\x30\x2e\x31\ -\x33\x35\x20\x30\x20\x39\x2e\x34\x39\x39\x35\x20\x32\x2e\x32\x35\ -\x31\x39\x20\x39\x2e\x37\x30\x33\x31\x20\x32\x2e\x33\x33\x36\x37\ -\x20\x30\x2e\x31\x34\x32\x35\x20\x30\x2e\x30\x35\x39\x34\x2d\x30\ -\x2e\x32\x39\x37\x33\x20\x30\x2e\x35\x39\x35\x36\x39\x2d\x32\x2e\ -\x37\x32\x35\x32\x20\x33\x2e\x33\x32\x35\x31\x2d\x32\x2e\x33\x31\ -\x31\x39\x20\x32\x2e\x35\x39\x39\x2d\x32\x2e\x39\x34\x33\x32\x20\ -\x33\x2e\x32\x35\x37\x34\x2d\x33\x2e\x31\x33\x35\x39\x20\x33\x2e\ -\x32\x36\x39\x32\x2d\x30\x2e\x31\x33\x32\x36\x20\x30\x2e\x30\x31\ -\x30\x34\x2d\x31\x2e\x30\x31\x32\x38\x2d\x30\x2e\x31\x36\x32\x32\ -\x35\x2d\x31\x2e\x39\x35\x36\x2d\x30\x2e\x33\x37\x38\x38\x32\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x67\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\ -\x35\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x36\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x32\ -\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\ -\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\ -\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x34\x39\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x33\ -\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\ -\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x39\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x30\x2e\x38\x35\x39\x20\x33\x2e\x30\x33\x30\ -\x34\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x32\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x38\x2e\x39\x2d\ -\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\ -\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\ -\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ -\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x32\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\ -\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\ -\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x33\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\ -\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x34\x31\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x34\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\ -\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\ -\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x35\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\ -\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x37\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x36\x2e\x39\x2d\x35\x36\x36\x2e\ -\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\ -\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x38\x31\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x37\x2e\x32\x2d\x35\x35\x33\x2e\ -\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x3e\x0a\ -\x20\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x30\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x35\ -\x36\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\ -\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\ -\x37\x33\x32\x2e\x31\x2d\x35\x30\x37\x2e\x36\x34\x20\x31\x33\x38\ -\x2e\x35\x36\x2d\x38\x30\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\ -\x2d\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x2d\x31\x33\x38\x2e\x35\ -\x36\x2d\x38\x30\x76\x31\x36\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x35\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x37\x33\x32\x2e\x31\x2d\x33\x34\x37\x2e\x36\x34\x20\ -\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x38\x37\x30\x2e\x36\x2d\x32\x36\x37\x2e\x36\x34\x20\x31\x33\ -\x38\x2e\x35\x36\x2d\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x32\x36\x32\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x35\x38\x37\ -\x2e\x36\x34\x76\x31\x36\x30\x6c\x2d\x31\x33\x38\x2e\x35\x36\x20\ -\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x34\x22\x20\ -\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x34\x32\x37\x2e\x36\ -\x34\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x36\x36\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x2d\x38\x30\x20\x38\x30\ -\x20\x38\x30\x20\x38\x30\x20\x38\x30\x2d\x38\x30\x7a\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x37\x30\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x37\x32\x37\x2e\x36\x34\x76\x38\x30\x6c\x38\x30\ -\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x32\x37\x32\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x36\x34\ -\x37\x2e\x36\x34\x2d\x38\x30\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x37\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x76\x38\x30\x6c\x2d\ -\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x37\ -\x36\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x38\x30\x37\x2e\ -\x36\x34\x20\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x30\x22\x20\x64\x3d\x22\x6d\x32\x32\x35\x32\x2e\x39\ -\x2d\x39\x36\x37\x2e\x36\x34\x2d\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x76\x31\x36\x30\x6c\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x38\x32\x22\x20\x64\x3d\ -\x22\x6d\x32\x30\x38\x38\x2e\x31\x2d\x39\x30\x37\x2e\x36\x34\x2d\ -\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\ -\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x39\x32\x33\x2e\x32\x2d\x39\x36\x37\x2e\x36\x34\x76\x31\x36\x30\ -\x6c\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x32\x38\x36\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\ -\x2e\x31\x2d\x31\x30\x32\x37\x2e\x36\x76\x31\x36\x30\x6c\x2d\x31\ -\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x38\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\x2e\x31\ -\x2d\x38\x36\x37\x2e\x36\x34\x20\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x3c\x67\x20\x73\ -\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\ -\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x33\x32\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x31\x38\x38\x2e\x31\x2d\x33\x34\x31\x2e\x36\x37\x20\x31\x35\ -\x33\x2e\x33\x31\x2d\x37\x31\x2e\x34\x38\x38\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x2d\x31\x35\x33\x2e\x33\x31\ -\x20\x37\x31\x2e\x34\x38\x38\x2d\x31\x35\x33\x2e\x33\x31\x2d\x38\ -\x38\x2e\x35\x31\x32\x76\x31\x36\x30\x6c\x31\x35\x33\x2e\x33\x31\ -\x20\x38\x38\x2e\x35\x31\x32\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x39\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\x33\x31\ -\x2d\x37\x31\x2e\x34\x38\x38\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x34\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x34\x31\x33\x2e\x31\x36\x76\x31\x36\x30\x6c\x2d\ -\x31\x35\x33\x2e\x33\x31\x20\x37\x31\x2e\x34\x38\x38\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x32\x36\x22\x20\x64\x3d\x22\x6d\x31\x33\ -\x34\x31\x2e\x34\x2d\x32\x35\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\ -\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x20\x69\x64\ -\x3d\x22\x69\x6d\x61\x67\x65\x34\x33\x33\x36\x22\x20\x73\x74\x79\ -\x6c\x65\x3d\x22\x69\x6d\x61\x67\x65\x2d\x72\x65\x6e\x64\x65\x72\ -\x69\x6e\x67\x3a\x6f\x70\x74\x69\x6d\x69\x7a\x65\x53\x70\x65\x65\ -\x64\x22\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\ -\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\ -\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\ -\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x52\x38\ -\x41\x41\x41\x41\x70\x43\x41\x59\x41\x41\x41\x41\x4d\x41\x79\x31\ -\x4a\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\ -\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x48\x69\x68\x4a\x52\x45\x46\ -\x55\x20\x65\x4a\x7a\x74\x6e\x58\x64\x34\x56\x46\x58\x36\x78\x7a\ -\x2f\x54\x61\x7a\x4b\x54\x6d\x55\x6b\x6a\x6a\x59\x54\x51\x51\x69\ -\x67\x4b\x32\x43\x6c\x57\x31\x72\x35\x59\x31\x37\x4a\x69\x58\x63\ -\x74\x61\x31\x72\x61\x75\x5a\x58\x55\x74\x61\x2f\x6e\x70\x36\x75\ -\x34\x71\x72\x67\x58\x64\x74\x61\x30\x67\x43\x77\x49\x57\x20\x6d\ -\x6f\x41\x46\x6b\x43\x49\x6c\x51\x41\x67\x51\x45\x6b\x68\x49\x53\ -\x47\x2f\x54\x35\x39\x62\x66\x48\x78\x4d\x69\x4a\x59\x48\x41\x44\ -\x50\x43\x48\x38\x33\x6d\x65\x50\x44\x79\x5a\x4f\x2b\x66\x65\x62\ -\x30\x35\x35\x7a\x7a\x6e\x76\x2b\x39\x36\x44\x35\x73\x55\x58\x58\ -\x6c\x42\x4a\x6b\x43\x42\x42\x67\x6d\x4f\x4d\x20\x50\x69\x4d\x7a\ -\x34\x33\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x66\x55\x46\x2b\ -\x2f\x76\x48\x57\x6b\x43\x42\x42\x67\x6c\x38\x67\x65\x72\x66\x62\ -\x66\x62\x77\x31\x4a\x45\x69\x51\x34\x42\x65\x49\x50\x6a\x6b\x35\ -\x2b\x58\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x76\x64\x56\x71\ -\x50\x64\x34\x61\x45\x69\x52\x49\x20\x38\x41\x74\x45\x62\x7a\x41\ -\x59\x59\x72\x71\x42\x4a\x4d\x76\x38\x38\x36\x74\x76\x6d\x4c\x31\ -\x36\x50\x58\x6b\x65\x4e\x34\x4e\x7a\x4d\x68\x6d\x63\x6e\x55\x6d\ -\x2f\x6a\x48\x52\x79\x33\x43\x6b\x34\x62\x66\x45\x7a\x62\x6b\x32\ -\x4e\x44\x57\x54\x6e\x35\x42\x47\x4a\x68\x4f\x4e\x32\x7a\x34\x72\ -\x36\x52\x6e\x34\x6f\x20\x4b\x79\x66\x50\x34\x79\x4c\x4c\x6e\x55\ -\x4b\x47\x30\x30\x47\x79\x31\x52\x4b\x33\x2b\x78\x38\x75\x4e\x53\ -\x31\x74\x31\x44\x53\x33\x6b\x75\x5a\x49\x4a\x74\x32\x5a\x6a\x4d\ -\x31\x73\x4f\x6d\x35\x61\x41\x46\x5a\x73\x72\x65\x43\x37\x7a\x56\ -\x76\x4a\x38\x37\x6a\x4a\x54\x2f\x65\x51\x6b\x65\x49\x6b\x7a\x5a\ -\x47\x4d\x20\x78\x52\x68\x62\x76\x39\x6d\x66\x6f\x39\x47\x32\x4b\ -\x37\x5a\x57\x38\x4e\x58\x61\x44\x65\x53\x6e\x65\x52\x69\x51\x6d\ -\x55\x47\x4b\x33\x55\x5a\x75\x71\x6f\x73\x6b\x69\x7a\x6c\x75\x7a\ -\x7a\x68\x63\x50\x63\x65\x69\x4c\x6e\x76\x4c\x6b\x6f\x31\x6c\x7a\ -\x46\x75\x2f\x69\x56\x79\x33\x6d\x33\x34\x5a\x71\x66\x52\x78\x20\ -\x70\x35\x44\x75\x53\x4d\x4b\x54\x6c\x49\x52\x4f\x70\x34\x33\x62\ -\x63\x33\x70\x71\x57\x33\x30\x73\x4e\x32\x31\x6f\x37\x2b\x44\x78\ -\x54\x32\x61\x69\x4e\x78\x69\x35\x61\x50\x53\x4a\x58\x44\x76\x2b\ -\x4e\x45\x71\x72\x61\x79\x69\x74\x72\x6d\x58\x42\x68\x69\x33\x73\ -\x61\x6d\x70\x42\x72\x39\x57\x53\x35\x58\x49\x77\x20\x73\x45\x38\ -\x6d\x52\x54\x6d\x5a\x46\x47\x61\x6b\x34\x55\x36\x32\x59\x7a\x63\ -\x66\x6e\x77\x36\x77\x42\x31\x6c\x52\x2b\x47\x4c\x31\x65\x6c\x36\ -\x66\x75\x34\x51\x42\x57\x52\x6e\x73\x62\x47\x36\x6a\x75\x71\x6d\ -\x46\x68\x76\x59\x4f\x6a\x46\x6f\x64\x47\x63\x35\x6b\x63\x6c\x50\ -\x64\x46\x47\x61\x6d\x4d\x69\x41\x7a\x20\x67\x33\x52\x6e\x4d\x6b\ -\x6b\x57\x4d\x31\x61\x54\x45\x59\x31\x47\x45\x33\x63\x39\x6b\x69\ -\x7a\x7a\x78\x55\x38\x6c\x50\x44\x5a\x6a\x4c\x71\x30\x36\x45\x79\ -\x5a\x46\x77\x6f\x61\x4d\x78\x32\x4b\x68\x77\x4a\x4e\x43\x51\x61\ -\x71\x62\x2f\x44\x51\x50\x2b\x52\x6d\x70\x35\x48\x6c\x63\x58\x56\ -\x70\x4d\x4d\x55\x34\x65\x20\x50\x52\x45\x57\x52\x4e\x35\x64\x2b\ -\x44\x31\x66\x72\x39\x76\x49\x4f\x53\x4f\x4b\x61\x51\x38\x4c\x7a\ -\x46\x68\x56\x51\x6c\x31\x72\x47\x38\x30\x64\x50\x6d\x77\x57\x45\ -\x2b\x6e\x4a\x79\x57\x53\x37\x6e\x66\x54\x50\x54\x4b\x4d\x67\x50\ -\x59\x32\x4d\x46\x41\x63\x4f\x71\x2b\x57\x34\x47\x38\x77\x39\x32\ -\x71\x66\x2f\x20\x2b\x42\x4e\x31\x51\x5a\x47\x2b\x41\x34\x70\x70\ -\x57\x37\x6d\x56\x6b\x4b\x38\x64\x67\x79\x70\x69\x30\x65\x6e\x49\ -\x64\x6a\x6b\x59\x6d\x70\x31\x4a\x75\x6a\x4f\x4a\x51\x64\x6c\x39\ -\x4b\x45\x68\x50\x78\x57\x59\x79\x34\x6b\x71\x79\x48\x7a\x55\x39\ -\x30\x35\x61\x76\x78\x6d\x34\x78\x38\x2b\x75\x54\x52\x78\x37\x58\ -\x20\x75\x76\x53\x48\x77\x72\x7a\x32\x78\x55\x4c\x65\x58\x4c\x79\ -\x55\x6b\x58\x6e\x5a\x6a\x4f\x78\x66\x79\x4a\x71\x71\x57\x6d\x61\ -\x76\x32\x55\x42\x64\x61\x7a\x74\x68\x51\x63\x52\x74\x74\x35\x48\ -\x68\x54\x43\x59\x2f\x33\x55\x4e\x42\x65\x69\x72\x35\x61\x61\x6d\ -\x34\x6b\x71\x79\x6b\x4f\x5a\x4c\x6a\x31\x76\x38\x31\x20\x33\x6f\ -\x37\x32\x49\x38\x72\x7a\x57\x56\x4f\x78\x6b\x38\x63\x2b\x2b\x5a\ -\x79\x37\x4c\x6a\x79\x58\x38\x30\x63\x4e\x5a\x2b\x58\x57\x37\x56\ -\x77\x77\x61\x73\x51\x2b\x33\x31\x45\x55\x68\x59\x5a\x32\x4c\x39\ -\x56\x4e\x4c\x57\x79\x70\x32\x63\x32\x6d\x71\x68\x6f\x32\x56\x64\ -\x65\x77\x73\x36\x47\x52\x6d\x58\x2b\x38\x20\x69\x32\x79\x33\x36\ -\x37\x43\x65\x47\x61\x2f\x5a\x4d\x52\x67\x52\x65\x47\x72\x71\x62\ -\x4e\x70\x43\x59\x5a\x36\x2b\x35\x6a\x4c\x4b\x61\x6e\x59\x7a\x38\ -\x64\x52\x52\x51\x4e\x51\x6f\x4e\x58\x74\x39\x31\x4c\x61\x30\x55\ -\x64\x58\x59\x7a\x4c\x62\x61\x4f\x72\x62\x57\x31\x72\x4f\x37\x74\ -\x51\x31\x76\x4d\x45\x69\x53\x20\x32\x63\x53\x37\x64\x30\x34\x69\ -\x78\x57\x36\x4c\x53\x63\x50\x65\x64\x41\x53\x43\x50\x50\x48\x70\ -\x4c\x4c\x37\x61\x55\x55\x39\x79\x30\x51\x68\x55\x67\x78\x46\x52\ -\x6c\x6f\x68\x49\x49\x75\x46\x51\x6b\x45\x67\x77\x67\x42\x41\x4b\ -\x51\x43\x67\x45\x34\x53\x41\x47\x55\x63\x42\x6a\x30\x4a\x4a\x6d\ -\x4d\x6e\x4a\x79\x20\x59\x56\x39\x65\x76\x50\x35\x79\x39\x44\x70\ -\x64\x33\x50\x54\x55\x74\x58\x62\x77\x38\x49\x66\x54\x36\x4e\x65\ -\x6e\x44\x35\x65\x65\x63\x69\x49\x66\x4c\x56\x37\x4b\x6c\x48\x74\ -\x76\x36\x37\x6f\x75\x53\x68\x49\x4e\x37\x56\x37\x71\x32\x74\x71\ -\x70\x62\x6d\x70\x68\x57\x32\x30\x64\x46\x58\x57\x4e\x56\x4e\x51\ -\x33\x20\x30\x4e\x6a\x65\x7a\x76\x38\x65\x2f\x6a\x33\x5a\x37\x70\ -\x54\x44\x65\x6d\x61\x38\x32\x6e\x5a\x76\x37\x62\x38\x39\x38\x33\ -\x52\x75\x66\x6d\x38\x6d\x76\x37\x72\x73\x52\x76\x78\x43\x47\x48\ -\x38\x6b\x54\x48\x76\x41\x52\x33\x4e\x62\x43\x32\x30\x64\x72\x62\ -\x53\x33\x74\x2b\x4a\x72\x62\x79\x58\x6b\x62\x55\x63\x4a\x20\x42\ -\x55\x6a\x58\x4b\x73\x7a\x37\x38\x77\x50\x30\x54\x66\x50\x45\x70\ -\x4b\x45\x6e\x50\x54\x65\x64\x4f\x35\x62\x5a\x4b\x39\x62\x77\x78\ -\x4e\x57\x2f\x37\x72\x72\x65\x55\x31\x33\x75\x61\x47\x69\x6b\x76\ -\x71\x33\x74\x69\x4f\x72\x79\x59\x47\x79\x74\x72\x65\x50\x75\x39\ -\x7a\x35\x6c\x68\x32\x4c\x45\x31\x69\x65\x58\x20\x6b\x31\x51\x66\ -\x55\x78\x2b\x2b\x71\x2b\x75\x36\x71\x71\x70\x34\x51\x32\x45\x61\ -\x32\x74\x71\x70\x61\x32\x32\x6e\x6f\x72\x36\x52\x37\x58\x55\x4e\ -\x6c\x4f\x32\x71\x5a\x58\x46\x4a\x4b\x51\x75\x66\x65\x6f\x6a\x42\ -\x4f\x5a\x6d\x48\x39\x63\x79\x34\x72\x58\x77\x6b\x57\x65\x59\x2f\ -\x53\x35\x59\x78\x61\x33\x55\x4a\x20\x37\x39\x33\x33\x4f\x77\x5a\ -\x6c\x5a\x37\x4b\x39\x72\x6f\x46\x2f\x66\x2f\x50\x39\x41\x63\x5a\ -\x48\x71\x39\x57\x53\x36\x58\x4b\x53\x36\x58\x4a\x79\x38\x73\x42\ -\x2b\x68\x45\x57\x52\x33\x37\x30\x2b\x68\x52\x56\x62\x79\x6d\x6e\ -\x32\x2b\x67\x2f\x62\x2b\x4d\x53\x44\x44\x56\x55\x31\x50\x50\x4c\ -\x52\x64\x4b\x34\x2f\x20\x63\x77\x79\x33\x54\x54\x69\x54\x6e\x59\ -\x33\x4e\x66\x4c\x78\x6b\x61\x5a\x66\x78\x30\x57\x6d\x31\x70\x44\ -\x73\x64\x70\x44\x73\x64\x6e\x4e\x69\x76\x4c\x78\x42\x74\x45\x45\ -\x56\x56\x2b\x64\x76\x6e\x58\x2f\x4f\x6e\x2f\x30\x7a\x46\x47\x77\ -\x7a\x46\x78\x66\x69\x6f\x71\x73\x71\x79\x73\x75\x33\x38\x34\x65\ -\x4f\x5a\x20\x6d\x50\x4f\x48\x4d\x50\x79\x73\x55\x55\x69\x4b\x67\ -\x69\x68\x4c\x68\x43\x57\x52\x6b\x43\x67\x51\x4e\x4a\x6f\x49\x57\ -\x6d\x7a\x34\x68\x54\x42\x68\x55\x55\x41\x46\x52\x46\x57\x6c\x54\ -\x6c\x57\x70\x4b\x79\x38\x6a\x73\x4b\x47\x4d\x73\x43\x42\x69\x74\ -\x38\x52\x75\x66\x46\x52\x56\x5a\x57\x46\x4a\x4b\x53\x2f\x4e\x20\ -\x6d\x73\x64\x54\x31\x31\x7a\x4f\x42\x61\x4f\x47\x30\x39\x54\x68\ -\x34\x36\x6f\x78\x70\x2b\x7a\x7a\x50\x59\x4e\x65\x54\x37\x62\x48\ -\x52\x62\x62\x48\x78\x65\x6a\x2b\x42\x51\x41\x45\x49\x78\x47\x75\ -\x65\x58\x6b\x79\x33\x35\x61\x56\x45\x34\x78\x45\x59\x74\x59\x53\ -\x44\x2b\x30\x37\x47\x35\x74\x52\x46\x42\x6b\x56\x20\x46\x55\x56\ -\x52\x6b\x42\x55\x46\x74\x46\x71\x4d\x4e\x6a\x73\x57\x76\x51\x37\ -\x4a\x5a\x6b\x64\x78\x70\x79\x4b\x48\x41\x67\x52\x4b\x53\x39\x6a\ -\x64\x32\x6b\x78\x45\x46\x49\x2b\x61\x6e\x76\x5a\x41\x73\x4b\x74\ -\x50\x37\x61\x47\x37\x75\x74\x77\x7a\x54\x6c\x61\x56\x56\x38\x61\ -\x74\x4c\x6b\x56\x4a\x34\x73\x4e\x76\x20\x66\x2b\x53\x76\x58\x79\ -\x79\x69\x33\x2b\x69\x78\x6a\x4d\x7a\x75\x53\x33\x74\x7a\x41\x30\ -\x70\x7a\x78\x7a\x37\x66\x30\x32\x67\x30\x4f\x4b\x77\x57\x48\x46\ -\x59\x4c\x41\x37\x49\x79\x47\x54\x64\x30\x4d\x43\x46\x42\x34\x4a\ -\x5a\x2f\x76\x49\x74\x4f\x70\x30\x4e\x52\x34\x35\x65\x54\x66\x46\ -\x6a\x47\x70\x38\x58\x6e\x20\x35\x36\x6c\x70\x73\x7a\x47\x62\x7a\ -\x4d\x78\x35\x34\x67\x45\x63\x6e\x66\x36\x63\x62\x4c\x65\x4c\x4a\ -\x36\x36\x2b\x39\x4b\x42\x6c\x4a\x56\x6e\x6d\x6d\x55\x38\x2f\x52\ -\x36\x50\x52\x4d\x50\x48\x55\x55\x53\x6a\x4b\x73\x55\x32\x73\x46\ -\x69\x57\x5a\x44\x37\x35\x62\x7a\x68\x65\x72\x53\x33\x6a\x39\x39\ -\x68\x73\x5a\x20\x55\x5a\x43\x48\x52\x71\x4f\x68\x6a\x38\x76\x4a\ -\x30\x39\x64\x64\x66\x73\x6a\x79\x55\x2b\x5a\x2f\x79\x2b\x77\x56\ -\x61\x7a\x68\x6a\x79\x45\x42\x30\x63\x56\x68\x6c\x42\x4d\x49\x52\ -\x58\x76\x74\x69\x49\x54\x4d\x32\x56\x54\x4c\x69\x72\x49\x6b\x6b\ -\x70\x62\x69\x52\x46\x49\x58\x49\x48\x71\x4d\x6a\x52\x4e\x42\x72\ -\x20\x74\x57\x6a\x51\x6f\x4b\x6f\x67\x4b\x54\x4b\x53\x4c\x43\x4d\ -\x71\x4d\x71\x67\x71\x6d\x71\x6f\x4b\x72\x69\x6b\x71\x59\x46\x76\ -\x4e\x37\x72\x6a\x73\x7a\x2f\x32\x68\x4d\x4b\x2f\x4d\x6d\x55\x39\ -\x46\x59\x77\x76\x2f\x65\x2f\x51\x2b\x63\x6a\x78\x75\x4e\x42\x6f\ -\x4e\x49\x55\x46\x67\x35\x64\x62\x74\x6e\x48\x66\x43\x20\x30\x42\ -\x37\x4c\x43\x70\x4c\x45\x2f\x56\x4d\x2b\x59\x56\x47\x44\x46\x36\ -\x50\x4c\x67\x2f\x6b\x6f\x62\x51\x56\x37\x6f\x69\x66\x74\x42\x70\ -\x30\x4f\x55\x52\x4a\x6f\x44\x77\x57\x6a\x64\x53\x70\x47\x43\x49\ -\x6b\x69\x59\x55\x6b\x6b\x49\x6b\x6c\x45\x4f\x6c\x65\x58\x6b\x63\ -\x70\x74\x59\x44\x53\x69\x53\x58\x62\x45\x20\x52\x58\x74\x50\x65\ -\x6c\x70\x38\x66\x6a\x35\x61\x73\x76\x53\x41\x53\x58\x70\x76\x39\ -\x68\x34\x6e\x34\x34\x63\x4f\x6a\x6f\x75\x65\x58\x63\x32\x74\x50\ -\x50\x72\x4a\x54\x4d\x70\x38\x43\x68\x4f\x75\x75\x67\x57\x72\x4c\ -\x51\x6c\x5a\x55\x64\x41\x47\x41\x38\x69\x48\x47\x49\x65\x69\x4a\ -\x50\x48\x59\x68\x35\x2b\x52\x20\x35\x6b\x78\x6d\x7a\x4a\x42\x42\ -\x63\x66\x56\x50\x39\x62\x72\x58\x62\x71\x6d\x70\x34\x39\x72\x58\ -\x33\x6d\x46\x4d\x63\x52\x47\x54\x37\x35\x6a\x55\x5a\x58\x67\x41\ -\x4f\x6f\x4a\x42\x6e\x70\x38\x2b\x35\x36\x44\x6c\x2f\x7a\x56\x33\ -\x45\x65\x73\x71\x64\x2f\x4c\x47\x48\x54\x64\x69\x4d\x75\x68\x52\ -\x56\x4f\x58\x49\x20\x56\x52\x38\x6d\x37\x59\x45\x67\x74\x2f\x2f\ -\x72\x41\x37\x62\x58\x4e\x7a\x50\x6a\x73\x54\x39\x77\x51\x72\x2b\ -\x2b\x58\x66\x76\x57\x56\x70\x2b\x66\x70\x7a\x2f\x39\x2f\x4b\x44\ -\x6c\x70\x79\x39\x64\x79\x5a\x51\x46\x53\x2f\x6a\x30\x6a\x33\x65\ -\x54\x5a\x44\x47\x6a\x6a\x58\x48\x50\x75\x37\x32\x75\x67\x63\x74\ -\x66\x20\x65\x59\x76\x76\x57\x68\x55\x75\x75\x50\x77\x6d\x42\x76\ -\x59\x74\x4a\x44\x50\x5a\x69\x64\x74\x71\x4a\x38\x6c\x6b\x78\x6d\ -\x6f\x77\x59\x74\x49\x62\x4d\x4f\x6a\x30\x36\x4c\x56\x61\x64\x46\ -\x6f\x4e\x57\x6f\x33\x6d\x35\x37\x31\x32\x54\x54\x55\x54\x30\x6c\ -\x4e\x34\x2b\x36\x36\x62\x55\x52\x57\x56\x57\x48\x66\x67\x20\x4f\ -\x78\x71\x61\x2b\x4d\x31\x72\x37\x2b\x42\x78\x4f\x70\x6e\x36\x38\ -\x4f\x2f\x4a\x54\x66\x56\x30\x50\x55\x74\x57\x46\x42\x72\x62\x76\ -\x51\x63\x74\x2f\x2b\x4c\x30\x4c\x2f\x69\x73\x64\x41\x63\x70\x51\ -\x34\x5a\x6a\x30\x47\x72\x52\x61\x75\x50\x6e\x72\x44\x77\x55\x42\ -\x39\x4e\x75\x30\x4f\x75\x51\x4a\x49\x6d\x32\x20\x6b\x4a\x2b\x4f\ -\x55\x41\x42\x76\x4f\x49\x78\x66\x43\x42\x4d\x51\x49\x70\x32\x47\ -\x53\x43\x43\x77\x63\x7a\x74\x53\x4f\x41\x78\x35\x42\x61\x41\x6f\ -\x4d\x57\x73\x2f\x6d\x4a\x35\x73\x74\x34\x74\x6e\x72\x72\x76\x69\ -\x6f\x4f\x58\x33\x48\x69\x63\x61\x4e\x44\x48\x72\x6d\x62\x64\x32\ -\x49\x78\x65\x2b\x4e\x42\x6d\x76\x20\x75\x34\x41\x4c\x4a\x31\x35\ -\x50\x51\x55\x59\x4f\x36\x55\x6b\x4f\x6e\x42\x59\x72\x46\x71\x50\ -\x70\x6b\x43\x75\x5a\x6c\x32\x5a\x38\x53\x58\x31\x62\x42\x79\x39\ -\x4d\x75\x68\x70\x4a\x6c\x6a\x45\x61\x34\x72\x65\x39\x37\x39\x58\ -\x4b\x35\x39\x4d\x66\x56\x76\x4c\x43\x7a\x4b\x2f\x35\x35\x4b\x48\ -\x66\x63\x2b\x71\x67\x20\x77\x67\x4d\x63\x54\x6c\x61\x54\x69\x5a\ -\x50\x36\x39\x2b\x75\x32\x72\x4b\x71\x71\x7a\x46\x69\x2b\x6d\x6b\ -\x2b\x2f\x57\x38\x36\x58\x54\x7a\x37\x55\x4f\x58\x69\x31\x30\x53\ -\x58\x77\x4d\x65\x43\x62\x6b\x6c\x49\x65\x2f\x76\x42\x2f\x50\x48\ -\x7a\x35\x52\x64\x78\x32\x33\x76\x67\x44\x47\x74\x4e\x6d\x4e\x6a\ -\x4e\x2b\x20\x36\x4f\x42\x75\x79\x36\x71\x71\x79\x74\x77\x31\x4a\ -\x54\x77\x37\x62\x52\x5a\x7a\x6e\x6e\x69\x41\x33\x46\x51\x33\x69\ -\x71\x4b\x69\x30\x78\x37\x35\x63\x48\x2f\x39\x71\x30\x57\x38\x4e\ -\x75\x38\x37\x52\x70\x30\x33\x6b\x62\x7a\x63\x41\x76\x52\x36\x41\ -\x37\x4b\x69\x49\x4d\x6b\x79\x67\x69\x77\x69\x79\x4e\x4c\x50\x20\ -\x50\x35\x4b\x30\x7a\x2b\x2b\x53\x4c\x45\x4e\x64\x44\x65\x4f\x53\ -\x6a\x45\x7a\x37\x34\x39\x33\x59\x7a\x4e\x48\x4f\x6f\x39\x55\x63\ -\x65\x51\x65\x64\x2b\x73\x4e\x4b\x6e\x70\x6f\x32\x68\x7a\x66\x75\ -\x6d\x4d\x54\x45\x55\x30\x63\x64\x30\x4c\x59\x5a\x4b\x51\x36\x75\ -\x48\x58\x39\x61\x74\x32\x56\x56\x56\x65\x58\x39\x20\x68\x64\x2f\ -\x78\x32\x70\x4b\x56\x35\x4a\x78\x32\x4a\x6c\x35\x52\x51\x4b\x38\ -\x42\x58\x51\x78\x36\x44\x6f\x65\x70\x50\x36\x7a\x6b\x72\x7a\x4f\ -\x2f\x5a\x73\x6f\x39\x74\x33\x48\x32\x38\x4b\x49\x44\x74\x42\x74\ -\x30\x4f\x6d\x52\x5a\x6f\x69\x58\x67\x52\x35\x42\x2b\x33\x73\x6f\ -\x47\x68\x41\x68\x42\x49\x59\x4a\x33\x20\x31\x77\x34\x69\x4c\x59\ -\x30\x77\x73\x42\x69\x30\x57\x72\x53\x6f\x78\x44\x4b\x76\x48\x45\ -\x70\x50\x55\x34\x65\x58\x68\x39\x37\x2f\x4c\x37\x4f\x66\x65\x4f\ -\x43\x41\x73\x74\x32\x4e\x45\x31\x6d\x52\x59\x36\x72\x4c\x76\x30\ -\x79\x64\x7a\x56\x76\x66\x72\x75\x44\x30\x38\x36\x38\x67\x4e\x79\ -\x63\x66\x57\x56\x55\x4a\x20\x43\x68\x46\x6b\x56\x53\x45\x6b\x43\ -\x6b\x52\x6b\x43\x58\x6f\x59\x68\x34\x71\x71\x38\x75\x36\x38\x78\ -\x58\x79\x2f\x61\x51\x73\x7a\x48\x2f\x38\x44\x46\x71\x4d\x52\x57\ -\x5a\x46\x69\x36\x6d\x76\x37\x30\x79\x76\x6a\x38\x2f\x37\x69\x70\ -\x65\x53\x6d\x65\x6e\x6a\x77\x76\x55\x39\x77\x32\x71\x30\x55\x35\ -\x57\x51\x78\x20\x75\x6e\x38\x42\x77\x77\x76\x79\x79\x48\x41\x36\ -\x4d\x42\x6b\x4d\x36\x48\x71\x77\x30\x45\x73\x32\x62\x4f\x62\x35\ -\x7a\x32\x59\x7a\x36\x34\x6e\x37\x75\x79\x49\x4a\x4f\x71\x33\x32\ -\x6b\x4d\x75\x39\x65\x50\x48\x43\x72\x50\x6e\x6f\x55\x6a\x4c\x34\ -\x35\x2f\x79\x6c\x76\x4c\x39\x6f\x47\x63\x50\x79\x2b\x6c\x43\x63\ -\x20\x6d\x38\x30\x70\x41\x77\x76\x4a\x54\x58\x56\x68\x4e\x42\x69\ -\x49\x69\x46\x4c\x33\x32\x6a\x65\x57\x38\x61\x63\x50\x70\x76\x48\ -\x5a\x49\x2f\x65\x53\x6e\x35\x45\x47\x52\x46\x63\x43\x50\x66\x32\ -\x74\x76\x65\x47\x2f\x50\x36\x79\x6b\x4b\x43\x75\x64\x48\x61\x73\ -\x57\x73\x32\x50\x44\x4b\x71\x77\x4f\x4e\x36\x36\x30\x20\x50\x74\ -\x68\x53\x58\x47\x41\x77\x49\x41\x42\x42\x49\x54\x70\x41\x39\x6a\ -\x68\x4a\x2f\x5a\x45\x49\x51\x55\x46\x41\x61\x61\x78\x6a\x75\x42\ -\x70\x68\x2b\x70\x38\x65\x49\x64\x6c\x71\x51\x5a\x51\x6b\x64\x44\ -\x6f\x74\x32\x68\x69\x4d\x34\x62\x2b\x58\x4c\x4f\x4f\x30\x77\x66\ -\x33\x35\x2b\x2b\x78\x35\x76\x44\x70\x72\x20\x4c\x6f\x56\x39\x30\ -\x68\x6d\x57\x6c\x38\x50\x4a\x41\x77\x76\x70\x6d\x35\x35\x4b\x57\ -\x42\x42\x34\x2f\x72\x4d\x35\x66\x50\x48\x6b\x67\x77\x65\x55\x6e\ -\x62\x31\x69\x44\x59\x2f\x2f\x62\x79\x35\x44\x78\x31\x2b\x41\x58\ -\x31\x56\x51\x68\x41\x68\x36\x51\x4b\x65\x4c\x66\x7a\x53\x77\x4f\ -\x39\x35\x62\x76\x49\x79\x38\x20\x56\x41\x39\x2f\x2f\x6e\x67\x36\ -\x66\x35\x74\x31\x59\x4c\x2f\x55\x36\x62\x51\x6f\x73\x6b\x52\x4c\ -\x77\x49\x65\x6f\x79\x46\x45\x48\x76\x74\x68\x70\x67\x42\x70\x32\ -\x45\x36\x36\x70\x67\x73\x48\x46\x30\x4c\x6d\x4e\x6a\x72\x62\x71\ -\x6b\x57\x73\x2f\x6c\x42\x36\x72\x32\x63\x52\x5a\x77\x34\x71\x36\ -\x4c\x64\x76\x64\x20\x4f\x4a\x46\x6b\x4a\x61\x61\x36\x2f\x47\x72\ -\x74\x52\x69\x77\x70\x48\x74\x59\x75\x2f\x59\x62\x31\x47\x67\x33\ -\x4a\x44\x69\x64\x4f\x54\x7a\x72\x4a\x37\x6a\x52\x4d\x53\x51\x36\ -\x38\x76\x67\x34\x63\x33\x52\x67\x66\x56\x56\x58\x35\x33\x39\x4b\ -\x56\x66\x4c\x68\x6b\x4b\x56\x2f\x38\x2b\x63\x47\x75\x79\x4c\x51\ -\x6b\x20\x78\x7a\x62\x78\x37\x6b\x2b\x76\x6a\x49\x38\x6e\x32\x63\ -\x37\x6b\x4f\x32\x38\x6d\x49\x38\x58\x42\x31\x74\x6f\x36\x64\x6a\ -\x59\x30\x38\x58\x33\x70\x56\x6a\x37\x35\x64\x6a\x6e\x56\x54\x53\ -\x32\x34\x6b\x32\x78\x73\x32\x31\x31\x50\x70\x73\x76\x4a\x36\x50\ -\x34\x46\x39\x45\x33\x7a\x6f\x4e\x56\x71\x32\x56\x53\x31\x20\x69\ -\x2f\x75\x6e\x66\x4d\x7a\x37\x39\x2f\x32\x4f\x33\x4e\x53\x66\x49\ -\x77\x68\x61\x72\x65\x61\x59\x2b\x58\x7a\x73\x56\x67\x74\x44\x7a\ -\x37\x69\x45\x56\x4a\x63\x48\x76\x39\x39\x4c\x59\x31\x4d\x39\x30\ -\x79\x71\x71\x2b\x4d\x63\x50\x4d\x78\x42\x38\x62\x61\x53\x5a\x64\ -\x54\x53\x30\x64\x57\x44\x55\x36\x78\x69\x61\x20\x6c\x38\x50\x6f\ -\x41\x66\x32\x77\x6d\x6f\x79\x73\x72\x64\x6a\x4a\x41\x31\x4d\x2b\ -\x35\x72\x31\x37\x62\x6d\x56\x51\x39\x73\x2f\x65\x66\x55\x57\x56\ -\x59\x39\x70\x32\x5a\x58\x74\x63\x76\x48\x33\x33\x4c\x58\x69\x53\ -\x6b\x39\x6a\x52\x30\x45\x54\x35\x37\x6e\x70\x57\x62\x61\x74\x67\ -\x30\x2b\x59\x79\x4e\x75\x78\x75\x20\x77\x71\x74\x6f\x4d\x44\x69\ -\x63\x61\x4f\x78\x4a\x53\x46\x59\x62\x49\x5a\x32\x57\x69\x43\x53\ -\x68\x74\x44\x5a\x54\x47\x47\x68\x6e\x78\x6c\x4d\x50\x6b\x75\x70\ -\x49\x41\x6b\x43\x51\x6f\x6a\x4e\x6a\x4c\x48\x70\x63\x53\x54\x5a\ -\x65\x76\x66\x56\x36\x73\x74\x77\x70\x31\x4c\x65\x31\x55\x31\x48\ -\x58\x79\x4c\x72\x4b\x20\x4b\x74\x36\x5a\x76\x35\x68\x74\x74\x58\ -\x57\x45\x52\x59\x6d\x77\x49\x50\x44\x50\x4c\x2b\x5a\x54\x6e\x4a\ -\x66\x44\x4b\x51\x50\x37\x59\x54\x57\x5a\x2b\x48\x46\x4c\x4f\x66\ -\x66\x2b\x5a\x7a\x6f\x6a\x7a\x72\x6f\x49\x32\x57\x7a\x47\x36\x2f\ -\x63\x68\x4b\x51\x70\x36\x72\x53\x59\x6d\x34\x33\x77\x34\x65\x4a\ -\x4a\x74\x20\x76\x48\x6e\x58\x4c\x61\x51\x37\x6b\x37\x76\x76\x6c\ -\x38\x6c\x32\x6d\x74\x76\x61\x43\x46\x5a\x75\x51\x35\x4f\x55\x6a\ -\x47\x51\x77\x45\x4a\x45\x6b\x77\x6d\x30\x74\x53\x4a\x58\x6c\x4d\ -\x4c\x41\x49\x39\x44\x2f\x37\x4d\x48\x51\x51\x30\x38\x72\x6e\x55\ -\x48\x70\x53\x48\x55\x6e\x6b\x70\x58\x6d\x59\x39\x73\x4f\x4b\x20\ -\x58\x6f\x30\x54\x4a\x63\x61\x4a\x7a\x6d\x77\x30\x34\x4f\x34\x2f\ -\x46\x49\x63\x6e\x44\x56\x55\x55\x69\x50\x68\x39\x74\x4c\x61\x31\ -\x55\x4c\x31\x70\x4c\x53\x46\x66\x4f\x33\x49\x34\x6a\x45\x73\x48\ -\x7a\x30\x32\x62\x78\x61\x6a\x43\x41\x6b\x37\x6f\x6c\x30\x65\x61\ -\x49\x35\x6b\x6c\x47\x38\x74\x34\x61\x63\x61\x58\x20\x66\x50\x62\ -\x49\x50\x66\x75\x6b\x48\x73\x51\x36\x38\x65\x35\x50\x72\x34\x79\ -\x50\x32\x57\x41\x6b\x4a\x41\x69\x59\x44\x41\x61\x47\x39\x63\x31\ -\x6c\x57\x4e\x39\x63\x4c\x6a\x6c\x35\x4a\x47\x72\x6e\x66\x72\x47\ -\x71\x71\x5a\x6c\x50\x76\x6c\x33\x4f\x75\x6f\x6f\x71\x70\x69\x7a\ -\x34\x6c\x6a\x61\x66\x48\x34\x38\x6a\x20\x6d\x5a\x72\x6d\x56\x74\ -\x36\x34\x34\x34\x59\x44\x50\x50\x77\x36\x72\x52\x62\x35\x47\x50\ -\x6c\x38\x7a\x41\x59\x6a\x76\x6c\x41\x41\x55\x38\x53\x4f\x78\x6d\ -\x44\x45\x6d\x5a\x47\x46\x79\x5a\x31\x4b\x35\x71\x42\x68\x42\x49\ -\x51\x77\x37\x58\x34\x76\x32\x6f\x71\x74\x2f\x47\x56\x35\x4b\x66\ -\x34\x76\x6c\x79\x44\x37\x20\x66\x65\x51\x37\x37\x49\x69\x52\x43\ -\x42\x2f\x38\x34\x58\x5a\x47\x39\x53\x2f\x59\x5a\x2f\x6b\x73\x53\ -\x72\x45\x31\x67\x4e\x31\x73\x78\x42\x73\x4d\x6b\x5a\x66\x6d\x6f\ -\x54\x67\x76\x6d\x2b\x4b\x38\x62\x48\x35\x39\x79\x73\x69\x75\x36\ -\x36\x75\x32\x56\x66\x44\x45\x52\x39\x4d\x5a\x30\x7a\x2b\x44\x46\ -\x56\x75\x33\x20\x55\x39\x48\x63\x79\x67\x35\x2f\x69\x41\x77\x64\ -\x7a\x48\x72\x71\x49\x66\x70\x31\x72\x73\x43\x69\x57\x69\x54\x30\ -\x75\x74\x68\x38\x4c\x43\x61\x39\x67\x62\x41\x67\x6f\x74\x4e\x71\ -\x79\x58\x4b\x37\x79\x48\x4b\x37\x47\x46\x73\x38\x71\x4b\x74\x74\ -\x61\x31\x76\x62\x75\x50\x72\x46\x31\x39\x46\x71\x4e\x48\x79\x34\ -\x20\x36\x41\x63\x65\x2f\x57\x42\x71\x39\x50\x4e\x32\x50\x36\x4d\ -\x6e\x58\x49\x48\x4a\x36\x61\x4c\x4a\x37\x30\x56\x53\x5a\x41\x52\ -\x5a\x77\x6f\x4a\x36\x7a\x49\x7a\x50\x48\x75\x30\x39\x39\x63\x75\ -\x64\x6a\x63\x32\x63\x39\x71\x66\x6e\x61\x47\x79\x6f\x52\x61\x6e\ -\x59\x41\x70\x49\x59\x4e\x54\x61\x69\x43\x50\x30\x48\x20\x67\x33\ -\x6e\x66\x5a\x46\x4b\x39\x52\x68\x50\x54\x4e\x75\x64\x51\x65\x6a\ -\x5a\x56\x31\x58\x44\x72\x36\x2b\x2b\x53\x37\x6e\x54\x30\x61\x70\ -\x7a\x49\x73\x68\x78\x54\x58\x56\x70\x4e\x42\x6e\x62\x35\x4f\x67\ -\x67\x61\x6a\x57\x69\x31\x57\x72\x51\x47\x41\x32\x70\x61\x42\x71\ -\x62\x55\x4e\x48\x53\x79\x51\x74\x6a\x58\x20\x67\x61\x74\x32\x4f\ -\x33\x31\x63\x4b\x55\x78\x66\x74\x70\x4b\x2f\x66\x6a\x59\x4c\x58\ -\x79\x68\x4d\x59\x34\x65\x58\x75\x58\x39\x35\x6d\x48\x36\x5a\x36\ -\x66\x76\x71\x55\x57\x4c\x54\x73\x7a\x2b\x39\x4d\x7a\x35\x36\x50\ -\x57\x48\x68\x77\x42\x44\x6b\x6e\x6b\x47\x5a\x6c\x2b\x70\x68\x79\ -\x59\x62\x4e\x66\x50\x37\x34\x20\x2f\x64\x6a\x4e\x4a\x6a\x6f\x43\ -\x51\x61\x71\x62\x57\x72\x6a\x37\x72\x51\x38\x59\x57\x7a\x7a\x34\ -\x67\x4c\x32\x76\x54\x71\x75\x4e\x61\x38\x6a\x75\x59\x46\x67\x4e\ -\x4f\x72\x7a\x42\x41\x49\x5a\x77\x45\x41\x30\x67\x4b\x51\x71\x43\ -\x4c\x42\x45\x53\x42\x55\x4b\x69\x69\x43\x44\x4c\x74\x4f\x34\x73\ -\x78\x33\x58\x79\x20\x57\x4b\x53\x4d\x50\x76\x6a\x44\x49\x63\x71\ -\x46\x43\x49\x57\x37\x4b\x37\x73\x69\x59\x6e\x75\x6a\x4b\x47\x70\ -\x4d\x30\x61\x55\x6b\x69\x78\x6c\x66\x4b\x4c\x54\x50\x5a\x33\x73\ -\x2f\x77\x35\x56\x6b\x70\x79\x41\x7a\x6e\x53\x65\x76\x6d\x59\x69\ -\x71\x71\x76\x6a\x44\x59\x54\x35\x59\x39\x41\x4d\x4e\x37\x56\x36\ -\x4b\x20\x63\x72\x4c\x32\x4b\x53\x66\x49\x4d\x76\x6f\x59\x4f\x34\ -\x4e\x4a\x72\x2b\x38\x32\x76\x4c\x78\x48\x6b\x39\x4e\x71\x35\x64\ -\x52\x42\x2f\x62\x6e\x37\x6f\x76\x4d\x41\x69\x49\x67\x69\x4e\x63\ -\x32\x74\x6a\x48\x74\x75\x4d\x70\x6c\x39\x63\x6d\x6e\x75\x33\x4e\ -\x49\x49\x55\x6a\x52\x79\x6c\x48\x51\x4d\x56\x7a\x36\x48\x20\x30\ -\x74\x34\x33\x7a\x59\x50\x4e\x5a\x6b\x58\x4a\x79\x67\x57\x74\x44\ -\x6d\x51\x5a\x77\x6b\x48\x59\x57\x51\x6e\x64\x76\x46\x5a\x6b\x30\ -\x47\x70\x69\x32\x73\x49\x65\x53\x73\x2f\x67\x6e\x44\x36\x38\x65\ -\x2f\x65\x74\x44\x4d\x76\x50\x52\x56\x58\x56\x51\x34\x34\x54\x4b\ -\x63\x61\x56\x52\x70\x4c\x5a\x54\x48\x76\x41\x20\x68\x38\x39\x6f\ -\x37\x46\x72\x52\x71\x59\x43\x71\x67\x71\x49\x71\x4b\x4f\x45\x67\ -\x51\x2b\x30\x32\x62\x6a\x35\x33\x48\x44\x65\x66\x4f\x77\x35\x4a\ -\x6c\x70\x6d\x2f\x64\x69\x4d\x7a\x6c\x71\x39\x69\x57\x4e\x2f\x63\ -\x41\x2b\x34\x6e\x79\x66\x46\x64\x2b\x66\x54\x71\x54\x6d\x61\x54\ -\x6f\x56\x76\x6a\x73\x77\x65\x4e\x20\x52\x73\x4e\x4e\x35\x34\x7a\ -\x46\x6f\x4e\x4f\x69\x30\x57\x68\x77\x32\x6d\x33\x30\x79\x30\x78\ -\x48\x52\x59\x33\x2b\x70\x66\x73\x2f\x56\x4b\x4e\x42\x4f\x55\x59\ -\x4f\x5a\x37\x4e\x42\x6a\x7a\x63\x55\x6f\x43\x4d\x55\x70\x44\x30\ -\x63\x78\x42\x73\x4f\x34\x51\x75\x48\x43\x45\x53\x69\x45\x59\x2b\ -\x49\x49\x6d\x50\x4e\x20\x4c\x53\x44\x53\x36\x64\x79\x56\x55\x63\ -\x46\x6f\x52\x4e\x56\x6f\x6f\x76\x72\x33\x51\x31\x61\x55\x6d\x4a\ -\x78\x75\x54\x70\x75\x56\x4e\x6e\x2b\x77\x78\x2b\x74\x39\x58\x43\ -\x6e\x63\x65\x50\x59\x59\x49\x46\x71\x76\x53\x52\x59\x4c\x47\x53\ -\x6b\x4f\x4e\x42\x6f\x4f\x36\x4a\x79\x69\x4a\x47\x48\x51\x78\x35\ -\x53\x6b\x20\x6a\x74\x47\x67\x49\x33\x79\x51\x33\x42\x61\x54\x77\ -\x63\x41\x4a\x2f\x66\x4b\x36\x5a\x6d\x2b\x54\x77\x55\x42\x47\x69\ -\x68\x4f\x4e\x47\x74\x30\x57\x43\x4c\x49\x55\x39\x61\x4e\x49\x41\ -\x68\x46\x52\x78\x4b\x69\x4e\x62\x52\x73\x59\x54\x2b\x30\x61\x6a\ -\x51\x61\x7a\x58\x67\x2b\x4b\x47\x74\x31\x50\x36\x66\x56\x67\x20\ -\x73\x6b\x53\x64\x72\x4e\x31\x6f\x4e\x4d\x52\x6f\x4f\x41\x2b\x6c\ -\x4a\x78\x51\x52\x75\x50\x75\x74\x44\x31\x42\x56\x74\x56\x66\x6a\ -\x52\x46\x62\x55\x6d\x4f\x72\x53\x61\x62\x4f\x69\x45\x53\x56\x6b\ -\x53\x55\x61\x55\x5a\x41\x52\x4a\x52\x70\x52\x6c\x4a\x45\x58\x75\ -\x6d\x76\x79\x6c\x76\x63\x61\x68\x58\x71\x66\x44\x20\x6e\x57\x78\ -\x48\x73\x33\x64\x6b\x64\x53\x2b\x69\x77\x5a\x5a\x6a\x76\x75\x30\ -\x79\x45\x42\x4b\x45\x48\x71\x2b\x72\x71\x73\x71\x47\x48\x64\x57\ -\x63\x55\x54\x53\x51\x76\x4d\x37\x73\x55\x4c\x31\x4f\x68\x36\x79\ -\x6f\x33\x64\x56\x70\x64\x4f\x56\x7a\x6a\x48\x77\x2b\x4e\x71\x4d\ -\x52\x58\x7a\x43\x41\x4e\x68\x7a\x73\x20\x30\x69\x72\x4b\x30\x53\ -\x31\x43\x52\x42\x4c\x78\x4e\x6a\x66\x67\x71\x36\x71\x45\x67\x41\ -\x38\x78\x79\x51\x47\x79\x42\x42\x5a\x72\x64\x4c\x42\x31\x49\x31\ -\x46\x52\x6c\x4a\x67\x36\x68\x4e\x74\x75\x6f\x39\x6e\x62\x63\x2b\ -\x6a\x36\x6d\x2f\x57\x62\x75\x4f\x66\x74\x44\x31\x6a\x34\x37\x4b\ -\x4e\x38\x75\x58\x6f\x64\x20\x5a\x77\x38\x66\x67\x71\x72\x53\x37\ -\x59\x77\x71\x53\x4c\x47\x48\x50\x73\x32\x47\x67\x30\x38\x73\x32\ -\x33\x62\x58\x38\x66\x78\x6e\x63\x78\x68\x56\x57\x4d\x43\x6d\x36\ -\x6c\x32\x4d\x4b\x52\x71\x49\x7a\x52\x79\x4e\x78\x41\x54\x46\x61\ -\x4e\x51\x6f\x2b\x71\x2b\x41\x70\x4d\x67\x59\x4e\x5a\x71\x34\x52\ -\x6b\x52\x69\x20\x30\x54\x35\x6a\x32\x53\x6f\x51\x42\x66\x72\x57\ -\x56\x46\x41\x64\x45\x56\x46\x73\x79\x64\x45\x56\x6a\x36\x70\x45\ -\x42\x2f\x74\x2b\x37\x57\x6a\x55\x61\x6d\x50\x7a\x73\x52\x78\x43\ -\x7a\x36\x49\x4e\x6d\x39\x6c\x63\x33\x30\x54\x52\x66\x55\x38\x79\ -\x49\x69\x65\x44\x6b\x77\x59\x55\x4d\x4b\x78\x76\x44\x70\x4b\x73\ -\x20\x52\x4b\x4f\x57\x2b\x33\x31\x66\x6c\x75\x58\x59\x4a\x6a\x71\ -\x72\x46\x57\x4e\x7a\x42\x49\x32\x71\x52\x55\x4a\x46\x30\x71\x68\ -\x30\x44\x54\x74\x56\x67\x64\x32\x37\x36\x4e\x41\x71\x6e\x50\x33\ -\x34\x38\x30\x79\x2b\x38\x30\x59\x32\x56\x64\x55\x67\x4b\x77\x71\ -\x69\x4a\x48\x63\x5a\x79\x48\x33\x30\x48\x49\x39\x6f\x20\x6c\x39\ -\x31\x6b\x77\x68\x2f\x75\x4f\x65\x33\x39\x72\x62\x6d\x4c\x57\x4c\ -\x53\x68\x6c\x4d\x74\x4f\x47\x38\x30\x7a\x55\x7a\x39\x6e\x66\x50\ -\x46\x67\x7a\x68\x6b\x78\x42\x46\x47\x57\x6b\x56\x55\x46\x33\x58\ -\x37\x56\x71\x74\x55\x65\x75\x31\x43\x37\x7a\x57\x54\x45\x31\x78\ -\x47\x41\x55\x4e\x54\x34\x4b\x4b\x71\x4b\x20\x72\x4d\x69\x49\x73\ -\x6f\x53\x2f\x75\x5a\x47\x77\x45\x49\x48\x63\x76\x67\x68\x61\x4c\ -\x57\x72\x41\x42\x36\x33\x4e\x6b\x4a\x46\x46\x59\x30\x73\x72\x50\ -\x32\x7a\x65\x69\x73\x74\x75\x49\x79\x50\x46\x53\x55\x36\x71\x47\ -\x36\x31\x47\x67\x78\x53\x6a\x38\x58\x48\x5a\x37\x54\x52\x37\x2f\ -\x51\x64\x38\x4c\x73\x6b\x79\x20\x58\x2f\x32\x30\x6e\x69\x78\x33\ -\x43\x67\x75\x65\x2f\x52\x4d\x35\x71\x53\x37\x53\x6e\x51\x37\x71\ -\x32\x74\x70\x5a\x56\x31\x6e\x46\x56\x36\x74\x4c\x6d\x48\x54\x57\ -\x57\x47\x61\x74\x2b\x49\x6e\x4c\x54\x78\x75\x4e\x78\x35\x46\x4d\ -\x52\x79\x43\x49\x51\x52\x75\x62\x38\x62\x45\x61\x6a\x64\x31\x6d\ -\x30\x53\x71\x71\x20\x69\x69\x38\x59\x34\x72\x30\x46\x33\x2f\x48\ -\x71\x72\x64\x64\x68\x4d\x35\x76\x59\x73\x47\x4d\x58\x36\x51\x34\ -\x48\x62\x38\x39\x62\x6a\x43\x68\x4c\x31\x4e\x62\x73\x70\x4b\x36\ -\x6c\x6b\x61\x44\x4e\x52\x6a\x41\x63\x52\x46\x58\x56\x61\x4b\x67\ -\x39\x6a\x68\x47\x52\x49\x39\x45\x75\x53\x6a\x4a\x62\x61\x33\x66\ -\x6a\x20\x44\x59\x57\x5a\x39\x2f\x51\x6a\x32\x43\x30\x6d\x61\x70\ -\x76\x62\x57\x4c\x32\x39\x6b\x68\x56\x62\x4b\x2f\x68\x33\x65\x52\ -\x6e\x32\x37\x5a\x74\x70\x31\x78\x70\x51\x37\x45\x6c\x67\x54\x77\ -\x4b\x54\x43\x5a\x4e\x4f\x47\x39\x4d\x32\x74\x6b\x63\x39\x73\x73\ -\x79\x55\x2b\x55\x74\x34\x5a\x63\x46\x79\x54\x72\x2f\x6b\x20\x4f\ -\x6b\x53\x4e\x68\x6f\x72\x57\x4a\x6e\x37\x63\x55\x49\x31\x76\x38\ -\x57\x72\x38\x4e\x64\x57\x63\x2f\x74\x6a\x7a\x6a\x4d\x37\x50\x35\ -\x64\x52\x42\x68\x5a\x7a\x59\x4c\x35\x39\x4d\x6c\x37\x4e\x7a\x32\ -\x33\x58\x6b\x64\x57\x6b\x31\x47\x54\x43\x71\x6f\x4e\x64\x71\x6b\ -\x56\x51\x31\x2b\x6f\x4f\x4b\x4a\x49\x6c\x51\x20\x56\x63\x36\x39\ -\x70\x77\x7a\x6e\x69\x61\x73\x75\x4a\x53\x79\x49\x57\x45\x78\x47\ -\x76\x6c\x71\x39\x6e\x71\x59\x4f\x48\x2f\x50\x58\x62\x75\x43\x36\ -\x56\x39\x37\x6b\x75\x64\x39\x65\x79\x62\x72\x4b\x4b\x73\x59\x55\ -\x44\x53\x44\x4a\x59\x6f\x6c\x47\x75\x2b\x49\x59\x79\x65\x79\x56\ -\x38\x62\x47\x5a\x54\x66\x68\x44\x20\x42\x78\x6f\x66\x58\x79\x6a\ -\x4d\x6b\x67\x32\x62\x79\x55\x39\x50\x35\x5a\x76\x6e\x48\x6f\x75\ -\x6d\x5a\x64\x75\x73\x68\x41\x57\x52\x65\x57\x73\x32\x73\x4b\x75\ -\x70\x68\x64\x4b\x71\x47\x75\x61\x73\x57\x73\x74\x31\x34\x30\x36\ -\x6a\x49\x43\x4d\x4e\x62\x57\x66\x53\x33\x4c\x46\x4b\x63\x4c\x61\ -\x61\x6a\x66\x6a\x71\x20\x57\x31\x48\x32\x57\x76\x6c\x49\x69\x6b\ -\x4b\x6f\x76\x68\x62\x2f\x72\x68\x33\x6f\x69\x34\x59\x68\x71\x47\ -\x70\x30\x70\x57\x4f\x78\x67\x6a\x73\x56\x56\x42\x57\x37\x33\x55\ -\x37\x2f\x7a\x41\x79\x2b\x33\x62\x69\x5a\x4f\x53\x76\x58\x4d\x6e\ -\x70\x41\x50\x2f\x37\x31\x39\x54\x66\x6f\x64\x62\x48\x4e\x6a\x75\ -\x34\x6b\x20\x47\x2b\x75\x72\x64\x78\x2f\x77\x2b\x61\x4b\x53\x55\ -\x6a\x37\x39\x37\x6b\x66\x65\x76\x2b\x38\x32\x72\x4b\x62\x6f\x79\ -\x34\x54\x58\x6e\x33\x6b\x36\x41\x42\x61\x6a\x67\x63\x62\x32\x44\ -\x6a\x4a\x64\x54\x67\x6f\x79\x30\x67\x68\x45\x42\x4e\x36\x65\x4e\ -\x6f\x75\x6c\x6d\x37\x63\x78\x49\x44\x50\x74\x67\x48\x73\x64\x20\ -\x44\x6c\x61\x7a\x6b\x55\x44\x34\x77\x41\x48\x7a\x31\x74\x66\x66\ -\x73\x4c\x61\x79\x69\x6e\x66\x75\x76\x71\x58\x4c\x32\x4f\x37\x4a\ -\x42\x42\x2f\x56\x50\x35\x38\x2b\x64\x7a\x36\x4f\x58\x34\x6a\x51\ -\x56\x46\x65\x44\x37\x45\x34\x6c\x55\x72\x6f\x65\x58\x42\x36\x4d\ -\x65\x6c\x31\x63\x33\x34\x67\x2b\x45\x75\x32\x76\x20\x7a\x5a\x35\ -\x4c\x56\x57\x4d\x7a\x62\x39\x77\x78\x36\x57\x66\x66\x6c\x63\x33\ -\x47\x6b\x4c\x78\x73\x4a\x70\x30\x31\x68\x70\x2f\x4b\x4b\x35\x6e\ -\x78\x36\x4c\x31\x55\x31\x6a\x65\x78\x61\x6c\x73\x46\x4b\x38\x73\ -\x72\x57\x62\x6d\x6a\x48\x4c\x74\x52\x6a\x30\x46\x2f\x35\x4d\x61\ -\x38\x4f\x7a\x30\x52\x55\x65\x54\x78\x20\x6a\x36\x59\x7a\x62\x33\ -\x73\x44\x5a\x31\x35\x38\x4c\x57\x46\x56\x78\x52\x63\x4a\x59\x55\ -\x76\x78\x34\x4c\x48\x61\x4d\x47\x62\x6c\x30\x4e\x48\x53\x79\x45\ -\x5a\x6e\x4a\x71\x75\x71\x6d\x35\x6c\x63\x57\x6f\x6b\x75\x34\x43\ -\x66\x48\x70\x43\x50\x4e\x59\x6f\x71\x70\x4c\x69\x31\x47\x49\x79\ -\x61\x4e\x42\x6f\x76\x4f\x20\x67\x4b\x67\x6f\x69\x4b\x70\x43\x4f\ -\x42\x4a\x45\x57\x31\x6e\x47\x43\x35\x64\x4e\x34\x4a\x36\x4c\x4a\ -\x2b\x77\x7a\x6b\x54\x34\x34\x38\x51\x49\x32\x56\x65\x32\x69\x66\ -\x48\x63\x39\x7a\x39\x39\x77\x46\x53\x61\x44\x6e\x6e\x55\x56\x4f\ -\x37\x47\x5a\x6a\x4d\x78\x59\x76\x68\x71\x62\x79\x59\x67\x2b\x78\ -\x73\x6c\x75\x20\x62\x33\x71\x33\x38\x72\x47\x59\x38\x4f\x31\x6e\ -\x66\x4d\x4b\x43\x79\x41\x76\x54\x35\x35\x43\x62\x36\x75\x62\x32\ -\x58\x35\x33\x56\x31\x63\x69\x44\x73\x76\x73\x41\x4d\x44\x77\x2f\ -\x6c\x38\x6c\x66\x4c\x79\x54\x4c\x34\x32\x4a\x51\x64\x68\x38\x43\ -\x45\x59\x46\x72\x58\x70\x35\x4d\x74\x73\x65\x46\x51\x61\x38\x2f\ -\x20\x5a\x69\x73\x66\x75\x38\x6c\x4d\x49\x42\x68\x45\x44\x41\x55\ -\x41\x55\x45\x57\x52\x53\x48\x6b\x5a\x35\x50\x52\x46\x47\x56\x68\ -\x4d\x70\x44\x73\x64\x47\x67\x30\x47\x76\x59\x35\x55\x52\x78\x4b\ -\x33\x6e\x33\x39\x32\x39\x4e\x30\x75\x4a\x5a\x70\x77\x57\x4a\x79\ -\x56\x45\x56\x4f\x48\x38\x43\x54\x62\x61\x66\x62\x36\x20\x75\x70\ -\x61\x31\x48\x59\x45\x67\x39\x37\x33\x7a\x45\x51\x39\x64\x64\x69\ -\x48\x2f\x66\x65\x69\x75\x62\x69\x4e\x58\x4a\x6f\x4d\x42\x52\x56\ -\x56\x4a\x73\x64\x76\x34\x7a\x64\x68\x54\x41\x63\x68\x4c\x64\x58\ -\x50\x78\x73\x33\x2f\x6a\x77\x55\x76\x4f\x4f\x32\x49\x74\x45\x4b\ -\x30\x66\x2f\x31\x34\x44\x70\x69\x4d\x51\x20\x5a\x50\x72\x53\x6c\ -\x5a\x77\x30\x6f\x4a\x41\x62\x7a\x78\x6e\x62\x62\x64\x61\x4c\x32\ -\x57\x68\x45\x56\x6d\x51\x55\x71\x77\x33\x62\x67\x43\x4c\x71\x66\ -\x52\x32\x6f\x51\x34\x5a\x44\x78\x56\x61\x75\x4f\x58\x2f\x73\x4d\ -\x58\x4d\x34\x37\x36\x2b\x39\x78\x65\x66\x6e\x62\x35\x39\x2f\x7a\ -\x65\x38\x76\x50\x43\x66\x71\x20\x6c\x2b\x70\x6d\x68\x52\x72\x39\ -\x54\x43\x55\x6a\x78\x55\x6c\x65\x57\x69\x70\x6e\x44\x69\x74\x43\ -\x56\x68\x54\x75\x6e\x2f\x49\x78\x42\x61\x6d\x75\x6d\x45\x34\x4a\ -\x36\x45\x37\x50\x54\x66\x39\x34\x6c\x79\x61\x54\x6d\x33\x45\x58\ -\x58\x45\x6c\x49\x46\x42\x43\x45\x4d\x49\x49\x73\x49\x53\x71\x64\ -\x2f\x68\x64\x5a\x20\x42\x6b\x41\x32\x47\x4d\x48\x70\x41\x71\x63\ -\x4c\x57\x56\x48\x59\x75\x62\x57\x55\x4f\x38\x61\x66\x47\x71\x4d\ -\x50\x53\x6f\x38\x5a\x63\x42\x67\x4d\x43\x49\x71\x43\x74\x37\x30\ -\x56\x77\x2b\x35\x79\x33\x72\x76\x6e\x4a\x69\x61\x63\x4f\x4c\x54\ -\x62\x2b\x74\x48\x72\x64\x47\x67\x30\x30\x44\x63\x39\x46\x59\x42\ -\x6e\x20\x72\x37\x2b\x43\x73\x43\x44\x79\x7a\x79\x38\x57\x38\x4d\ -\x68\x6c\x46\x38\x54\x6b\x6b\x44\x2f\x67\x57\x62\x33\x35\x6b\x74\ -\x31\x6b\x77\x72\x75\x58\x38\x56\x6c\x63\x55\x73\x72\x37\x33\x33\ -\x7a\x50\x35\x44\x73\x6d\x6b\x57\x79\x31\x39\x4e\x6a\x49\x69\x68\ -\x71\x4e\x37\x6c\x7a\x64\x2b\x57\x4c\x69\x66\x2b\x36\x2f\x20\x6e\ -\x5a\x72\x6d\x56\x6d\x35\x34\x39\x53\x30\x75\x48\x64\x6e\x7a\x75\ -\x30\x4c\x78\x78\x47\x6f\x32\x45\x68\x48\x43\x43\x4a\x45\x77\x68\ -\x45\x4f\x6f\x6f\x67\x68\x4a\x79\x57\x41\x77\x48\x44\x53\x66\x62\ -\x47\x39\x66\x6c\x55\x61\x6a\x59\x56\x48\x4a\x4a\x75\x70\x61\x32\ -\x6e\x6a\x35\x2b\x73\x74\x69\x30\x75\x4f\x79\x20\x32\x32\x6a\x78\ -\x52\x62\x64\x64\x74\x53\x32\x74\x4e\x48\x58\x34\x4f\x47\x74\x34\ -\x45\x59\x4f\x79\x4d\x33\x73\x4d\x6d\x5a\x76\x32\x53\x34\x53\x55\ -\x46\x59\x56\x6e\x70\x73\x33\x69\x38\x6c\x4e\x4f\x70\x48\x43\x2f\ -\x63\x4f\x6a\x68\x45\x70\x32\x74\x6f\x32\x33\x72\x44\x51\x5a\x35\ -\x66\x2b\x46\x33\x4a\x4e\x73\x73\x20\x6e\x4e\x41\x76\x37\x36\x41\ -\x64\x58\x31\x45\x55\x76\x4a\x30\x4f\x66\x45\x45\x53\x6f\x61\x4f\ -\x4e\x73\x39\x4e\x64\x54\x44\x71\x7a\x2b\x32\x7a\x6f\x6f\x38\x48\ -\x65\x32\x70\x73\x37\x66\x48\x79\x33\x71\x59\x7a\x69\x76\x47\x77\ -\x79\x55\x70\x77\x48\x31\x36\x36\x79\x54\x37\x52\x31\x30\x66\x70\ -\x53\x4b\x6e\x59\x33\x20\x38\x50\x53\x56\x46\x38\x56\x4e\x7a\x35\ -\x5a\x64\x75\x37\x6e\x70\x6a\x66\x63\x77\x35\x68\x55\x7a\x61\x50\ -\x41\x77\x66\x4a\x48\x77\x58\x75\x2b\x58\x43\x59\x52\x46\x67\x62\ -\x41\x6b\x45\x70\x59\x6b\x46\x46\x56\x46\x55\x65\x53\x66\x62\x39\ -\x54\x63\x79\x42\x6c\x70\x44\x6e\x35\x33\x33\x72\x69\x59\x39\x4a\ -\x6a\x31\x20\x42\x6b\x77\x61\x53\x44\x45\x5a\x71\x61\x76\x62\x68\ -\x61\x75\x39\x6a\x6b\x2b\x66\x75\x49\x38\x68\x75\x64\x6b\x39\x48\ -\x6f\x75\x68\x31\x2b\x6d\x51\x35\x48\x30\x6e\x35\x4c\x66\x6d\x4c\ -\x71\x4a\x76\x71\x6f\x76\x78\x51\x77\x62\x47\x70\x47\x64\x2f\x65\ -\x6d\x56\x57\x37\x57\x59\x7a\x2f\x6e\x41\x59\x53\x5a\x61\x5a\x20\ -\x76\x57\x49\x4e\x4b\x76\x44\x69\x70\x4b\x74\x78\x32\x4b\x77\x48\ -\x50\x64\x74\x44\x56\x64\x53\x75\x4b\x41\x6c\x45\x4f\x2b\x7a\x39\ -\x55\x7a\x37\x6d\x7a\x67\x6e\x6a\x4b\x4d\x37\x4e\x36\x72\x46\x63\ -\x50\x4c\x47\x62\x54\x43\x44\x4c\x71\x4d\x45\x41\x36\x72\x62\x4e\ -\x30\x59\x68\x48\x57\x73\x59\x68\x73\x38\x6d\x55\x20\x76\x62\x53\ -\x33\x65\x48\x30\x38\x4e\x32\x30\x57\x7a\x31\x31\x7a\x61\x63\x78\ -\x48\x56\x31\x68\x4e\x4a\x67\x4c\x68\x61\x43\x37\x46\x74\x61\x2b\ -\x38\x53\x55\x51\x55\x75\x65\x47\x73\x4d\x51\x65\x39\x72\x39\x6c\ -\x67\x32\x4d\x66\x68\x2f\x4f\x57\x71\x64\x56\x51\x33\x4e\x48\x4c\ -\x54\x6d\x57\x66\x45\x70\x41\x58\x32\x20\x2b\x50\x4d\x69\x4c\x43\ -\x34\x70\x35\x64\x71\x58\x33\x2b\x54\x57\x43\x65\x4f\x35\x2b\x5a\ -\x78\x78\x68\x35\x78\x78\x5a\x55\x57\x68\x49\x78\x54\x43\x48\x77\ -\x6d\x6a\x69\x69\x4b\x65\x70\x6a\x70\x65\x2f\x75\x31\x6c\x63\x54\ -\x33\x61\x34\x31\x44\x73\x30\x62\x36\x2b\x73\x6f\x6f\x72\x58\x76\ -\x77\x48\x70\x77\x37\x75\x20\x7a\x37\x58\x6a\x54\x6a\x75\x6b\x64\ -\x76\x55\x6f\x74\x65\x30\x65\x50\x64\x2b\x58\x62\x75\x47\x53\x6c\ -\x79\x61\x6a\x4c\x54\x77\x42\x64\x33\x35\x2f\x32\x6b\x50\x42\x36\ -\x50\x74\x6c\x34\x53\x44\x65\x63\x42\x68\x66\x4a\x49\x79\x2f\x36\ -\x2f\x32\x79\x43\x4b\x72\x4b\x7a\x2b\x4d\x6b\x45\x73\x62\x52\x57\ -\x4d\x76\x66\x20\x4a\x6c\x30\x64\x65\x31\x38\x7a\x47\x39\x47\x71\ -\x45\x72\x36\x36\x4b\x76\x49\x31\x41\x65\x59\x39\x2b\x51\x44\x46\ -\x65\x54\x6b\x48\x48\x62\x4e\x36\x72\x62\x5a\x72\x4e\x51\x5a\x51\ -\x73\x71\x4f\x61\x6d\x63\x74\x58\x38\x64\x68\x6c\x46\x38\x61\x6b\ -\x70\x54\x74\x36\x5a\x33\x79\x73\x5a\x6c\x70\x39\x66\x6a\x35\x65\ -\x20\x73\x6f\x78\x6c\x5a\x64\x73\x34\x6f\x32\x67\x41\x32\x5a\x35\ -\x44\x48\x34\x65\x68\x71\x45\x72\x58\x43\x69\x49\x69\x69\x74\x7a\ -\x37\x39\x6b\x65\x4d\x48\x56\x54\x49\x78\x4a\x4e\x50\x6a\x45\x6e\ -\x30\x34\x57\x41\x7a\x6d\x36\x47\x78\x48\x6f\x51\x49\x44\x42\x6b\ -\x65\x39\x65\x76\x30\x41\x6b\x56\x56\x4f\x33\x4d\x69\x20\x56\x42\ -\x37\x2f\x61\x44\x71\x2f\x4f\x58\x31\x30\x7a\x4b\x73\x4d\x41\x4a\ -\x4e\x42\x54\x32\x31\x4c\x57\x7a\x51\x76\x36\x72\x45\x2f\x63\x4e\ -\x4b\x41\x37\x74\x2b\x4a\x32\x37\x66\x4d\x7a\x79\x75\x66\x75\x74\ -\x5a\x32\x6e\x70\x33\x36\x4f\x53\x39\x63\x66\x30\x56\x4d\x2f\x6f\ -\x6b\x39\x32\x4d\x78\x6d\x46\x71\x7a\x62\x20\x69\x44\x76\x5a\x7a\ -\x6a\x76\x33\x33\x49\x4c\x64\x62\x4f\x37\x56\x59\x56\x47\x4b\x49\ -\x74\x4d\x52\x44\x69\x49\x71\x4d\x72\x72\x71\x53\x70\x36\x2b\x35\ -\x4e\x79\x34\x31\x4d\x2f\x68\x59\x44\x4f\x62\x6d\x62\x75\x6d\x42\ -\x46\x6c\x52\x2b\x4f\x69\x42\x4f\x38\x6c\x4d\x63\x66\x61\x71\x33\ -\x4a\x35\x2b\x47\x65\x2b\x32\x20\x74\x5a\x6e\x4e\x7a\x46\x72\x78\ -\x45\x78\x50\x2f\x2f\x6a\x37\x32\x45\x30\x35\x48\x6c\x2b\x4b\x6d\ -\x4a\x65\x43\x6e\x4a\x65\x69\x6e\x4a\x52\x69\x67\x4c\x52\x6a\x6f\ -\x66\x4d\x45\x31\x69\x43\x38\x63\x4e\x64\x79\x42\x53\x49\x53\x75\ -\x73\x4b\x71\x71\x6f\x71\x6e\x63\x78\x70\x4f\x58\x54\x6d\x42\x77\ -\x39\x75\x47\x64\x20\x6d\x64\x4d\x64\x79\x56\x59\x4c\x35\x64\x75\ -\x33\x63\x4b\x4c\x48\x7a\x4f\x65\x50\x33\x6b\x64\x57\x4c\x38\x34\ -\x46\x30\x75\x74\x30\x58\x65\x48\x33\x73\x43\x42\x77\x37\x7a\x73\ -\x66\x38\x76\x54\x56\x6c\x2b\x4b\x77\x78\x66\x39\x30\x7a\x31\x34\ -\x5a\x6e\x32\x53\x7a\x6d\x59\x2b\x58\x4c\x4b\x4e\x66\x5a\x68\x71\ -\x50\x20\x58\x6e\x6b\x4a\x78\x6c\x37\x6d\x6c\x69\x69\x64\x6a\x6c\ -\x78\x46\x55\x58\x6a\x36\x30\x38\x39\x4a\x74\x68\x68\x6a\x58\x6b\ -\x6f\x65\x4c\x72\x6d\x70\x4c\x72\x4c\x4e\x42\x6e\x54\x4e\x6a\x64\ -\x44\x52\x44\x6f\x4c\x51\x62\x55\x37\x46\x2f\x71\x69\x64\x32\x75\ -\x65\x75\x4b\x61\x47\x68\x72\x59\x32\x72\x7a\x78\x67\x64\x20\x46\ -\x7a\x31\x4a\x5a\x6a\x4e\x6e\x44\x4f\x72\x50\x79\x7a\x4f\x2f\x34\ -\x74\x6d\x70\x73\x35\x69\x33\x5a\x67\x50\x4e\x48\x62\x36\x44\x35\ -\x6a\x32\x5a\x6a\x64\x48\x6b\x74\x59\x67\x6f\x63\x76\x2b\x55\x6a\ -\x33\x6e\x67\x34\x6e\x50\x4a\x63\x76\x56\x75\x6f\x42\x32\x4b\x33\ -\x46\x51\x58\x32\x32\x76\x72\x65\x47\x76\x75\x20\x59\x74\x5a\x58\ -\x56\x74\x48\x6b\x39\x66\x55\x71\x41\x56\x52\x56\x56\x63\x4b\x69\ -\x41\x4b\x33\x4e\x58\x4a\x44\x6c\x69\x56\x76\x39\x48\x41\x35\x37\ -\x74\x4c\x2f\x2b\x35\x51\x49\x32\x56\x75\x33\x71\x74\x58\x62\x6c\ -\x4b\x4c\x56\x74\x54\x6d\x6f\x4b\x32\x32\x72\x72\x55\x45\x77\x57\ -\x57\x6c\x75\x61\x61\x47\x35\x76\x20\x6f\x54\x58\x6f\x70\x7a\x58\ -\x6f\x70\x79\x33\x6f\x70\x79\x30\x55\x6f\x4c\x30\x7a\x35\x38\x7a\ -\x62\x61\x58\x78\x45\x57\x61\x4a\x72\x2f\x39\x2f\x55\x77\x4e\x6c\ -\x5a\x71\x66\x78\x32\x33\x43\x6b\x48\x66\x55\x35\x76\x4f\x57\x31\ -\x67\x49\x56\x65\x63\x63\x69\x4b\x62\x71\x71\x71\x35\x39\x35\x30\ -\x50\x6d\x62\x35\x30\x20\x4a\x58\x57\x74\x37\x51\x64\x73\x71\x2f\ -\x5a\x47\x72\x34\x75\x75\x66\x42\x52\x46\x34\x66\x6e\x70\x63\x78\ -\x68\x58\x31\x4a\x39\x52\x68\x58\x33\x6a\x6f\x75\x65\x41\x5a\x2f\ -\x58\x6d\x53\x30\x55\x35\x66\x58\x6a\x32\x6d\x6f\x6e\x38\x66\x64\ -\x62\x58\x31\x4c\x56\x37\x79\x55\x39\x50\x34\x39\x77\x52\x78\x5a\ -\x77\x35\x20\x72\x49\x6a\x63\x56\x48\x65\x50\x4d\x2b\x57\x65\x51\ -\x37\x6a\x65\x58\x66\x41\x74\x32\x32\x76\x72\x6d\x48\x7a\x62\x74\ -\x63\x66\x4d\x47\x62\x6d\x48\x34\x74\x77\x73\x56\x72\x7a\x34\x4f\ -\x47\x73\x71\x64\x72\x4b\x67\x70\x4a\x51\x46\x6d\x37\x65\x7a\x50\ -\x52\x42\x42\x54\x58\x46\x42\x69\x67\x65\x4d\x78\x6d\x36\x33\x20\ -\x59\x49\x71\x71\x30\x74\x6a\x68\x35\x53\x2f\x2f\x6e\x63\x6d\x48\ -\x39\x39\x37\x53\x61\x34\x4e\x37\x4b\x49\x77\x47\x50\x53\x39\x50\ -\x75\x70\x4b\x4f\x59\x49\x69\x31\x46\x54\x75\x5a\x75\x33\x6f\x4e\ -\x4c\x30\x79\x66\x6a\x54\x73\x35\x69\x51\x6b\x6e\x44\x75\x4f\x69\ -\x30\x53\x65\x51\x35\x55\x37\x5a\x70\x30\x35\x4e\x20\x6e\x65\x38\ -\x6b\x66\x62\x42\x6f\x4b\x52\x61\x44\x6a\x6f\x74\x48\x39\x33\x77\ -\x65\x7a\x4f\x46\x53\x6e\x4a\x76\x46\x30\x75\x63\x66\x5a\x55\x33\ -\x46\x54\x72\x35\x65\x74\x59\x62\x6e\x50\x35\x74\x44\x75\x74\x50\ -\x42\x2b\x53\x4f\x48\x63\x66\x36\x6f\x45\x66\x52\x78\x64\x65\x2b\ -\x34\x52\x56\x56\x42\x69\x4a\x44\x53\x20\x55\x4d\x76\x2f\x50\x58\ -\x56\x2f\x33\x4f\x72\x6e\x63\x4c\x58\x2f\x32\x4e\x6d\x32\x68\x36\ -\x4e\x64\x56\x56\x55\x61\x32\x6a\x76\x69\x33\x72\x5a\x44\x63\x37\ -\x4e\x5a\x39\x74\x66\x48\x57\x4c\x6d\x39\x6b\x76\x6e\x72\x4e\x72\ -\x46\x77\x32\x54\x6f\x43\x52\x67\x74\x47\x54\x7a\x6f\x36\x64\x79\ -\x71\x4b\x30\x59\x41\x67\x20\x79\x55\x52\x6b\x45\x55\x6d\x57\x39\ -\x30\x30\x6a\x69\x34\x53\x78\x31\x65\x33\x69\x74\x57\x63\x65\x78\ -\x47\x77\x30\x78\x6b\x56\x50\x5a\x6f\x71\x44\x4b\x58\x66\x64\x69\ -\x43\x38\x55\x5a\x74\x32\x4f\x61\x68\x5a\x76\x4b\x4f\x4f\x31\x32\ -\x56\x2b\x54\x62\x4c\x56\x78\x7a\x6f\x68\x69\x4c\x6a\x6e\x70\x42\ -\x50\x72\x33\x20\x79\x64\x69\x6e\x6a\x6e\x52\x61\x48\x62\x4b\x69\ -\x73\x4c\x79\x73\x6e\x4f\x38\x32\x6c\x6a\x48\x7a\x6a\x33\x63\x64\ -\x6c\x57\x4f\x44\x34\x51\x69\x4f\x55\x5a\x56\x6c\x68\x55\x32\x37\ -\x61\x6c\x6d\x38\x73\x59\x79\x6c\x5a\x64\x73\x4a\x69\x53\x49\x6a\ -\x43\x76\x49\x59\x58\x7a\x79\x59\x6b\x59\x58\x35\x35\x4b\x58\x39\ -\x20\x66\x48\x35\x4a\x30\x56\x31\x2f\x35\x4d\x47\x4a\x46\x7a\x44\ -\x31\x32\x2b\x58\x38\x39\x2f\x37\x62\x59\x71\x37\x55\x65\x42\x32\ -\x31\x75\x57\x31\x33\x50\x66\x50\x58\x6c\x66\x4c\x4e\x68\x73\x32\ -\x73\x61\x57\x7a\x44\x61\x37\x5a\x43\x69\x68\x76\x73\x39\x6d\x67\ -\x61\x50\x75\x41\x71\x58\x63\x63\x5a\x2f\x66\x4f\x35\x20\x5a\x47\ -\x51\x78\x56\x35\x31\x2b\x55\x6b\x7a\x50\x36\x77\x30\x56\x39\x59\ -\x30\x73\x58\x46\x2f\x4b\x67\x67\x31\x6c\x4b\x4b\x72\x4b\x4b\x51\ -\x4d\x4c\x2b\x64\x58\x49\x34\x59\x77\x6f\x79\x45\x57\x44\x68\x67\ -\x47\x33\x50\x30\x52\x2b\x75\x70\x75\x70\x44\x39\x77\x52\x31\x30\ -\x50\x35\x75\x32\x4e\x50\x2f\x53\x7a\x61\x20\x57\x49\x5a\x47\x71\ -\x32\x58\x4d\x6b\x49\x47\x63\x64\x38\x4a\x51\x52\x68\x54\x6b\x59\ -\x65\x6c\x73\x51\x39\x4d\x31\x64\x36\x42\x61\x37\x66\x7a\x72\x69\ -\x67\x6c\x78\x71\x5a\x39\x34\x74\x2b\x33\x42\x74\x41\x2b\x38\x34\ -\x79\x47\x47\x35\x2b\x63\x78\x59\x64\x69\x67\x6f\x39\x36\x32\x4b\ -\x37\x5a\x57\x73\x4c\x42\x6b\x20\x4d\x30\x73\x32\x62\x57\x46\x6a\ -\x71\x35\x64\x49\x6b\x69\x4d\x61\x31\x62\x49\x6e\x52\x64\x2b\x6d\ -\x56\x32\x54\x59\x73\x42\x61\x64\x32\x63\x79\x72\x6c\x35\x7a\x4e\ -\x54\x57\x66\x46\x37\x73\x63\x37\x46\x4e\x56\x4e\x4c\x53\x77\x6f\ -\x4b\x57\x58\x2b\x2b\x6c\x4a\x38\x6f\x51\x69\x6a\x2b\x75\x64\x7a\ -\x77\x61\x67\x52\x20\x6a\x43\x72\x4d\x52\x36\x76\x56\x4d\x75\x61\ -\x52\x5a\x33\x48\x61\x72\x4c\x77\x36\x36\x61\x72\x44\x50\x6a\x4b\ -\x31\x4f\x33\x70\x71\x32\x79\x4d\x2b\x77\x78\x6d\x69\x44\x75\x51\ -\x32\x66\x35\x42\x4e\x75\x32\x72\x35\x66\x6e\x4d\x35\x4a\x54\x74\ -\x33\x67\x55\x62\x44\x71\x50\x37\x35\x6a\x42\x39\x61\x78\x42\x55\ -\x76\x20\x2f\x49\x4f\x69\x37\x45\x77\x2b\x75\x4f\x64\x57\x4d\x6c\ -\x32\x4f\x6f\x2f\x5a\x48\x48\x43\x6d\x79\x72\x46\x44\x66\x34\x65\ -\x58\x48\x4c\x65\x58\x4d\x4b\x79\x6c\x6a\x61\x57\x55\x56\x6a\x52\ -\x6f\x44\x6b\x69\x4d\x46\x54\x66\x6b\x57\x4c\x68\x38\x31\x6c\x48\ -\x66\x75\x6e\x48\x52\x4d\x6e\x61\x69\x4b\x6f\x74\x44\x6b\x20\x39\ -\x62\x47\x36\x66\x43\x63\x4c\x4e\x32\x36\x6d\x6f\x72\x36\x4a\x76\ -\x75\x6d\x70\x54\x50\x31\x2b\x42\x54\x4d\x66\x2b\x54\x31\x6a\x69\ -\x77\x59\x63\x4d\x79\x31\x37\x31\x38\x2b\x69\x54\x56\x75\x70\x62\ -\x6d\x35\x68\x61\x46\x34\x75\x45\x30\x34\x63\x78\x70\x55\x76\x76\ -\x63\x37\x46\x49\x34\x66\x78\x37\x6c\x33\x78\x20\x71\x5a\x2b\x6a\ -\x32\x62\x62\x37\x61\x2f\x2f\x4e\x2f\x37\x33\x42\x68\x53\x4f\x48\ -\x38\x63\x36\x64\x4e\x78\x79\x7a\x74\x68\x55\x6c\x6d\x5a\x71\x57\ -\x56\x72\x37\x5a\x73\x4a\x6e\x35\x4a\x57\x57\x73\x72\x61\x6d\x6e\ -\x56\x57\x64\x41\x63\x61\x54\x41\x39\x69\x33\x38\x61\x76\x67\x51\ -\x50\x72\x6e\x76\x6c\x70\x68\x66\x20\x6c\x7a\x6b\x63\x46\x45\x57\ -\x68\x78\x52\x64\x67\x62\x65\x56\x4f\x35\x71\x2f\x66\x54\x46\x6c\ -\x74\x48\x65\x6c\x4f\x4a\x37\x4e\x57\x2f\x4d\x52\x4c\x4e\x31\x7a\ -\x42\x37\x65\x65\x4e\x6a\x38\x74\x7a\x6a\x6f\x72\x78\x36\x59\x36\ -\x61\x35\x6c\x62\x57\x37\x61\x6a\x6d\x2b\x38\x33\x6c\x37\x47\x68\ -\x73\x34\x72\x6c\x72\x20\x4a\x75\x35\x7a\x4a\x45\x55\x73\x48\x49\ -\x33\x2f\x58\x6d\x56\x76\x66\x4b\x45\x77\x61\x79\x75\x72\x57\x4c\ -\x53\x78\x6a\x4b\x32\x31\x64\x62\x77\x79\x36\x57\x70\x79\x65\x75\ -\x46\x59\x50\x35\x71\x45\x49\x69\x4b\x6c\x75\x32\x72\x77\x68\x73\ -\x4b\x4d\x48\x7a\x4c\x77\x6d\x4a\x34\x53\x75\x44\x39\x48\x73\x33\ -\x35\x2b\x20\x61\x57\x33\x62\x31\x4f\x48\x6a\x70\x2b\x30\x37\x57\ -\x56\x43\x79\x69\x62\x4c\x61\x4f\x74\x36\x38\x37\x58\x6f\x4b\x4d\ -\x6d\x4a\x4c\x47\x49\x32\x56\x69\x43\x69\x79\x65\x64\x64\x75\x56\ -\x70\x58\x76\x59\x4e\x4b\x5a\x70\x32\x4f\x4f\x30\x35\x47\x70\x78\ -\x38\x7a\x34\x4a\x45\x69\x51\x49\x45\x46\x76\x4f\x48\x37\x54\x20\ -\x61\x49\x49\x45\x43\x58\x37\x52\x4a\x49\x78\x50\x67\x67\x51\x4a\ -\x6a\x67\x73\x4a\x34\x35\x4d\x67\x51\x59\x4c\x6a\x51\x73\x4c\x34\ -\x4a\x45\x69\x51\x34\x4c\x69\x51\x4d\x44\x34\x4a\x45\x69\x51\x34\ -\x4c\x69\x53\x4d\x54\x34\x49\x45\x43\x59\x34\x4c\x43\x65\x4f\x54\ -\x49\x45\x47\x43\x34\x30\x4c\x43\x2b\x43\x52\x49\x20\x6b\x4f\x43\ -\x34\x6b\x44\x41\x2b\x43\x52\x49\x6b\x4f\x43\x34\x6b\x6a\x45\x2b\ -\x43\x42\x41\x6d\x4f\x43\x2f\x38\x50\x32\x32\x63\x47\x79\x2b\x42\ -\x2f\x69\x58\x30\x41\x41\x41\x41\x41\x53\x55\x56\x4f\x52\x4b\x35\ -\x43\x59\x49\x49\x3d\x20\x22\x20\x68\x65\x69\x67\x68\x74\x3d\x22\ -\x34\x31\x22\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x38\x37\x22\x20\ -\x79\x3d\x22\x2d\x36\x35\x35\x2e\x33\x37\x22\x20\x78\x3d\x22\x31\ -\x32\x39\x39\x2e\x37\x22\x20\x70\x72\x65\x73\x65\x72\x76\x65\x41\ -\x73\x70\x65\x63\x74\x52\x61\x74\x69\x6f\x3d\x22\x6e\x6f\x6e\x65\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\ -\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x33\x33\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\ -\x2d\x35\x39\x31\x2e\x38\x33\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x34\x37\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x35\x36\x36\x2e\x35\x39\ -\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x20\x32\x35\ -\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x33\x34\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\ -\x32\x2d\x35\x39\x31\x2e\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\ -\x38\x2e\x34\x35\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x33\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x35\x38\x2e\ -\x31\x34\x76\x33\x32\x6c\x2d\x33\x31\x2e\x35\x34\x37\x2d\x38\x2e\ -\x34\x35\x33\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x32\ -\x36\x2e\x31\x34\x20\x32\x35\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\ -\x33\x38\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x37\ -\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x39\x31\ -\x2e\x38\x33\x76\x33\x32\x6c\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x39\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x35\x39\x2e\ -\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x36\x31\x22\x20\x64\x3d\x22\x6d\x31\ -\x32\x33\x36\x2e\x36\x2d\x36\x35\x36\x2e\x32\x38\x2d\x31\x32\x2e\ -\x36\x31\x39\x20\x31\x32\x2e\x36\x31\x39\x76\x31\x36\x6c\x31\x38\ -\x2e\x39\x32\x38\x20\x35\x2e\x30\x37\x31\x38\x76\x2d\x31\x36\x6c\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x36\x33\x22\x20\x64\x3d\x22\x6d\x31\x32\ -\x34\x33\x2d\x36\x32\x32\x2e\x35\x39\x20\x31\x32\x2e\x36\x31\x39\ -\x2d\x31\x32\x2e\x36\x31\x39\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x36\x33\x38\x2e\ -\x35\x39\x20\x31\x32\x2e\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\ -\x76\x31\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x37\x22\x20\x64\ -\x3d\x22\x6d\x31\x32\x35\x35\x2e\x36\x2d\x36\x35\x31\x2e\x32\x31\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x76\x31\ -\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x32\x32\x34\x2d\x36\x32\x37\x2e\x36\x36\x20\x31\x32\x2e\ -\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\x20\x31\x38\x2e\x39\x32\ -\x38\x20\x35\x2e\x30\x37\x31\x38\x22\x2f\x3e\x0a\x20\x20\x20\x3c\ -\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x31\ -\x22\x20\x64\x3d\x22\x6d\x31\x33\x33\x38\x2e\x31\x2d\x35\x35\x39\ -\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\ -\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\ -\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\ -\x37\x33\x22\x20\x64\x3d\x22\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\ -\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\ -\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\ -\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x37\x37\x22\x20\x64\x3d\x22\x6d\x31\ -\x33\x35\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\ -\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\ -\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x31\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x36\x36\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x20\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3d\x22\ -\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\x69\x6c\x6c\x2d\x6f\x70\ -\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\x37\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\ -\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x31\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x32\x30\x22\x20\x64\x3d\x22\x6d\x31\x33\x38\x36\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x36\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x32\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x32\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x20\x66\x69\x6c\x6c\x2d\ -\x72\x75\x6c\x65\x3d\x22\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\ -\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\ -\x36\x36\x37\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\ -\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\ -\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\ -\x6c\x3d\x22\x23\x30\x30\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\ -\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x34\x34\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x38\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x38\x30\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x30\x22\x20\ -\x64\x3d\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x35\x36\x2e\x34\ -\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\ -\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\ -\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x34\x34\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x30\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x30\x22\x20\x66\x69\x6c\ -\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\ -\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x39\x34\x2e\x32\x2d\x35\x35\x30\x2e\x34\x36\ -\x20\x30\x2e\x30\x30\x31\x2d\x35\x2e\x38\x36\x36\x36\x20\x32\x2e\ -\x36\x35\x32\x31\x2d\x32\x2e\x39\x37\x30\x35\x63\x31\x2e\x34\x35\ -\x38\x37\x2d\x31\x2e\x36\x33\x33\x38\x20\x32\x2e\x36\x37\x38\x37\ -\x2d\x32\x2e\x39\x39\x38\x31\x20\x32\x2e\x37\x31\x31\x32\x2d\x33\ -\x2e\x30\x33\x31\x39\x20\x30\x2e\x30\x33\x35\x2d\x30\x2e\x30\x33\ -\x36\x38\x20\x30\x2e\x30\x35\x39\x20\x32\x2e\x31\x37\x30\x39\x20\ -\x30\x2e\x30\x35\x39\x20\x35\x2e\x35\x38\x35\x39\x76\x35\x2e\x36\ -\x34\x37\x32\x6c\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\ -\x31\x34\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\x31\x34\ -\x76\x2d\x35\x2e\x38\x36\x36\x38\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\ -\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\ -\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\ -\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ -\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x34\x38\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x39\ -\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\ -\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\ -\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x34\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x34\x30\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\ -\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\ -\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\ -\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x31\x34\x2d\x35\x36\x33\x2e\x35\ -\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x39\x30\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x37\x2e\x37\x2d\x35\ -\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\ -\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x30\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x30\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\ -\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\ -\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x30\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x31\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\ -\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x32\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x35\x32\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x36\x35\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\ -\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\ -\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\ -\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x31\x36\x22\x20\x64\x3d\x22\x6d\x31\x34\x37\x32\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x31\x38\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\ -\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\ -\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\ -\x67\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x32\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x36\x2e\x39\x2d\x35\x36\x36\ -\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\ -\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x36\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x37\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\ -\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\x2e\x31\x2d\x35\x35\x39\x2e\ -\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\ -\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\ -\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x33\ -\x30\x22\x20\x64\x3d\x22\x6d\x31\x35\x32\x31\x2e\x37\x2d\x35\x35\ -\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\ -\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\ -\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x35\ -\x32\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x35\x33\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x35\x32\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\ -\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x3c\ -\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ -\x00\x00\x4e\x4c\ -\x3c\ -\x3f\x78\x6d\x6c\x20\x76\x65\x72\x73\x69\x6f\x6e\x3d\x22\x31\x2e\ -\x30\x22\x20\x65\x6e\x63\x6f\x64\x69\x6e\x67\x3d\x22\x55\x54\x46\ -\x2d\x38\x22\x20\x73\x74\x61\x6e\x64\x61\x6c\x6f\x6e\x65\x3d\x22\ -\x6e\x6f\x22\x3f\x3e\x0a\x3c\x21\x2d\x2d\x20\x43\x72\x65\x61\x74\ -\x65\x64\x20\x77\x69\x74\x68\x20\x49\x6e\x6b\x73\x63\x61\x70\x65\ -\x20\x28\x68\x74\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x69\x6e\x6b\ -\x73\x63\x61\x70\x65\x2e\x6f\x72\x67\x2f\x29\x20\x2d\x2d\x3e\x0a\ -\x3c\x73\x76\x67\x20\x69\x64\x3d\x22\x73\x76\x67\x32\x22\x20\x78\ -\x6d\x6c\x6e\x73\x3a\x72\x64\x66\x3d\x22\x68\x74\x74\x70\x3a\x2f\ -\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\x31\x39\x39\x39\ -\x2f\x30\x32\x2f\x32\x32\x2d\x72\x64\x66\x2d\x73\x79\x6e\x74\x61\ -\x78\x2d\x6e\x73\x23\x22\x20\x78\x6d\x6c\x6e\x73\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x32\x30\x30\x30\x2f\x73\x76\x67\x22\x20\x68\x65\x69\x67\x68\x74\ -\x3d\x22\x32\x33\x2e\x39\x39\x34\x22\x20\x77\x69\x64\x74\x68\x3d\ -\x22\x32\x30\x2e\x39\x36\x31\x22\x20\x76\x65\x72\x73\x69\x6f\x6e\ -\x3d\x22\x31\x2e\x31\x22\x20\x78\x6d\x6c\x6e\x73\x3a\x63\x63\x3d\ -\x22\x68\x74\x74\x70\x3a\x2f\x2f\x63\x72\x65\x61\x74\x69\x76\x65\ -\x63\x6f\x6d\x6d\x6f\x6e\x73\x2e\x6f\x72\x67\x2f\x6e\x73\x23\x22\ -\x20\x78\x6d\x6c\x6e\x73\x3a\x78\x6c\x69\x6e\x6b\x3d\x22\x68\x74\ -\x74\x70\x3a\x2f\x2f\x77\x77\x77\x2e\x77\x33\x2e\x6f\x72\x67\x2f\ -\x31\x39\x39\x39\x2f\x78\x6c\x69\x6e\x6b\x22\x20\x76\x69\x65\x77\ -\x42\x6f\x78\x3d\x22\x30\x20\x30\x20\x32\x30\x2e\x39\x36\x30\x37\ -\x38\x32\x20\x32\x33\x2e\x39\x39\x33\x35\x39\x31\x22\x20\x78\x6d\ -\x6c\x6e\x73\x3a\x64\x63\x3d\x22\x68\x74\x74\x70\x3a\x2f\x2f\x70\ -\x75\x72\x6c\x2e\x6f\x72\x67\x2f\x64\x63\x2f\x65\x6c\x65\x6d\x65\ -\x6e\x74\x73\x2f\x31\x2e\x31\x2f\x22\x3e\x0a\x20\x3c\x6d\x65\x74\ -\x61\x64\x61\x74\x61\x20\x69\x64\x3d\x22\x6d\x65\x74\x61\x64\x61\ -\x74\x61\x37\x22\x3e\x0a\x20\x20\x3c\x72\x64\x66\x3a\x52\x44\x46\ -\x3e\x0a\x20\x20\x20\x3c\x63\x63\x3a\x57\x6f\x72\x6b\x20\x72\x64\ -\x66\x3a\x61\x62\x6f\x75\x74\x3d\x22\x22\x3e\x0a\x20\x20\x20\x20\ -\x3c\x64\x63\x3a\x66\x6f\x72\x6d\x61\x74\x3e\x69\x6d\x61\x67\x65\ -\x2f\x73\x76\x67\x2b\x78\x6d\x6c\x3c\x2f\x64\x63\x3a\x66\x6f\x72\ -\x6d\x61\x74\x3e\x0a\x20\x20\x20\x20\x3c\x64\x63\x3a\x74\x79\x70\ -\x65\x20\x72\x64\x66\x3a\x72\x65\x73\x6f\x75\x72\x63\x65\x3d\x22\ -\x68\x74\x74\x70\x3a\x2f\x2f\x70\x75\x72\x6c\x2e\x6f\x72\x67\x2f\ -\x64\x63\x2f\x64\x63\x6d\x69\x74\x79\x70\x65\x2f\x53\x74\x69\x6c\ -\x6c\x49\x6d\x61\x67\x65\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x64\ -\x63\x3a\x74\x69\x74\x6c\x65\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x63\ -\x63\x3a\x57\x6f\x72\x6b\x3e\x0a\x20\x20\x3c\x2f\x72\x64\x66\x3a\ -\x52\x44\x46\x3e\x0a\x20\x3c\x2f\x6d\x65\x74\x61\x64\x61\x74\x61\ -\x3e\x0a\x20\x3c\x67\x20\x69\x64\x3d\x22\x6c\x61\x79\x65\x72\x31\ -\x22\x20\x74\x72\x61\x6e\x73\x66\x6f\x72\x6d\x3d\x22\x74\x72\x61\ -\x6e\x73\x6c\x61\x74\x65\x28\x2d\x31\x34\x32\x33\x2e\x36\x20\x35\ -\x36\x36\x2e\x38\x34\x29\x22\x3e\x0a\x20\x20\x3c\x67\x20\x66\x69\ -\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\ -\x36\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x3e\ -\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x33\x36\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\ -\x2e\x33\x2d\x35\x35\x33\x2e\x32\x39\x63\x30\x2d\x34\x2e\x33\x34\ -\x33\x31\x20\x30\x2e\x30\x31\x31\x2d\x35\x2e\x34\x32\x34\x33\x20\ -\x30\x2e\x30\x36\x2d\x35\x2e\x34\x32\x34\x33\x20\x30\x2e\x30\x36\ -\x31\x20\x30\x20\x38\x2e\x33\x34\x31\x39\x20\x31\x2e\x38\x31\x33\ -\x32\x20\x38\x2e\x33\x35\x35\x39\x20\x31\x2e\x38\x32\x39\x37\x20\ -\x30\x20\x30\x20\x30\x2e\x30\x32\x34\x20\x30\x2e\x36\x32\x30\x34\ -\x33\x20\x30\x2e\x30\x34\x32\x20\x31\x2e\x33\x36\x37\x33\x6c\x30\ -\x2e\x30\x33\x34\x20\x31\x2e\x33\x35\x37\x39\x2d\x34\x2e\x32\x34\ -\x35\x38\x20\x33\x2e\x31\x34\x36\x39\x2d\x34\x2e\x32\x34\x35\x39\ -\x20\x33\x2e\x31\x34\x36\x39\x76\x2d\x35\x2e\x34\x32\x34\x33\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x35\x33\x38\x22\x20\x64\x3d\x22\x6d\x31\ -\x35\x31\x32\x2e\x38\x2d\x35\x35\x38\x2e\x36\x34\x63\x2d\x32\x2e\ -\x31\x37\x39\x34\x2d\x30\x2e\x34\x36\x37\x31\x33\x2d\x33\x2e\x39\ -\x39\x35\x32\x2d\x30\x2e\x38\x35\x36\x31\x33\x2d\x34\x2e\x30\x33\ -\x35\x2d\x30\x2e\x38\x36\x34\x35\x35\x2d\x30\x2e\x30\x33\x39\x2d\ -\x30\x2e\x30\x31\x30\x37\x20\x31\x2e\x37\x32\x39\x34\x2d\x31\x2e\ -\x33\x38\x32\x39\x20\x33\x2e\x39\x33\x31\x34\x2d\x33\x2e\x30\x35\ -\x34\x36\x20\x32\x2e\x32\x30\x32\x32\x2d\x31\x2e\x36\x37\x31\x36\ -\x20\x34\x2e\x30\x31\x31\x39\x2d\x33\x2e\x30\x33\x31\x36\x20\x34\ -\x2e\x30\x32\x31\x36\x2d\x33\x2e\x30\x32\x32\x32\x20\x30\x2e\x30\ -\x32\x31\x20\x30\x2e\x30\x31\x39\x32\x20\x30\x2e\x31\x36\x39\x31\ -\x20\x36\x2e\x33\x37\x38\x37\x20\x30\x2e\x31\x36\x39\x34\x20\x37\ -\x2e\x32\x34\x31\x31\x20\x30\x2e\x30\x30\x30\x32\x20\x30\x2e\x34\ -\x31\x38\x38\x39\x2d\x30\x2e\x30\x31\x34\x20\x30\x2e\x35\x35\x38\ -\x34\x37\x2d\x30\x2e\x30\x36\x32\x20\x30\x2e\x35\x35\x34\x36\x34\ -\x2d\x30\x2e\x30\x33\x35\x20\x30\x2d\x31\x2e\x38\x34\x35\x36\x2d\ -\x30\x2e\x33\x38\x37\x33\x31\x2d\x34\x2e\x30\x32\x35\x33\x2d\x30\ -\x2e\x38\x35\x34\x34\x33\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x30\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x35\x39\x2e\x34\x2d\x35\x34\x35\ -\x2e\x34\x33\x63\x2d\x33\x2e\x33\x32\x36\x32\x2d\x30\x2e\x39\x32\ -\x33\x32\x33\x2d\x36\x2e\x31\x37\x37\x38\x2d\x31\x2e\x37\x31\x33\ -\x33\x2d\x36\x2e\x33\x33\x36\x38\x2d\x31\x2e\x37\x35\x35\x37\x2d\ -\x30\x2e\x32\x37\x38\x31\x2d\x30\x2e\x30\x37\x34\x34\x2d\x30\x2e\ -\x31\x32\x30\x39\x2d\x30\x2e\x32\x30\x32\x37\x39\x20\x34\x2e\x30\ -\x31\x35\x31\x2d\x33\x2e\x32\x38\x38\x37\x20\x32\x2e\x33\x36\x37\ -\x36\x2d\x31\x2e\x37\x36\x36\x35\x20\x34\x2e\x33\x37\x30\x31\x2d\ -\x33\x2e\x32\x30\x35\x39\x20\x34\x2e\x34\x35\x30\x32\x2d\x33\x2e\ -\x31\x39\x38\x35\x20\x30\x2e\x30\x38\x20\x30\x2e\x30\x31\x30\x38\ -\x20\x31\x2e\x30\x33\x33\x34\x20\x30\x2e\x32\x37\x35\x34\x32\x20\ -\x32\x2e\x31\x31\x38\x38\x20\x30\x2e\x35\x39\x35\x38\x37\x20\x31\ -\x2e\x30\x38\x35\x34\x20\x30\x2e\x33\x32\x30\x35\x37\x20\x31\x2e\ -\x39\x38\x38\x39\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x32\x2e\x30\ -\x30\x37\x38\x20\x30\x2e\x35\x38\x32\x37\x33\x20\x30\x2e\x30\x31\ -\x39\x20\x30\x20\x30\x2e\x30\x33\x35\x20\x31\x2e\x39\x36\x39\x39\ -\x20\x30\x2e\x30\x33\x35\x20\x34\x2e\x33\x37\x37\x35\x20\x30\x20\ -\x33\x2e\x34\x34\x31\x31\x2d\x30\x2e\x30\x32\x36\x20\x34\x2e\x33\ -\x37\x36\x33\x2d\x30\x2e\x31\x32\x30\x39\x20\x34\x2e\x33\x37\x31\ -\x35\x2d\x30\x2e\x30\x36\x36\x20\x30\x2d\x32\x2e\x38\x34\x32\x34\ -\x2d\x30\x2e\x37\x36\x31\x32\x37\x2d\x36\x2e\x31\x36\x38\x35\x2d\ -\x31\x2e\x36\x38\x34\x36\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x32\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\x2e\x39\x2d\x35\x34\x38\ -\x2e\x30\x39\x63\x30\x2d\x32\x2e\x31\x37\x33\x35\x20\x30\x2e\x30\ -\x32\x2d\x33\x2e\x39\x35\x31\x38\x20\x30\x2e\x30\x34\x37\x2d\x33\ -\x2e\x39\x35\x31\x38\x20\x30\x2e\x31\x30\x36\x31\x20\x30\x20\x35\ -\x2e\x32\x33\x37\x20\x31\x2e\x35\x30\x34\x31\x20\x35\x2e\x32\x38\ -\x32\x36\x20\x31\x2e\x35\x34\x38\x37\x20\x30\x2e\x30\x33\x35\x20\ -\x30\x2e\x30\x33\x35\x2d\x34\x2e\x34\x39\x35\x20\x35\x2e\x34\x34\ -\x35\x32\x2d\x35\x2e\x32\x34\x32\x20\x36\x2e\x32\x35\x39\x33\x2d\ -\x30\x2e\x30\x34\x38\x20\x30\x2e\x30\x35\x33\x2d\x30\x2e\x30\x38\ -\x38\x2d\x31\x2e\x36\x36\x39\x35\x2d\x30\x2e\x30\x38\x38\x2d\x33\ -\x2e\x38\x35\x36\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\x35\x35\x33\x2e\ -\x38\x2d\x31\x2e\x37\x38\x30\x33\x2d\x30\x2e\x35\x33\x32\x39\x76\ -\x2d\x31\x2e\x31\x37\x38\x37\x63\x30\x2d\x31\x2e\x31\x36\x31\x37\ -\x20\x30\x2d\x31\x2e\x31\x37\x38\x20\x30\x2e\x32\x30\x35\x34\x2d\ -\x31\x2e\x31\x32\x35\x32\x20\x30\x2e\x31\x31\x32\x38\x20\x30\x2e\ -\x30\x32\x39\x39\x20\x30\x2e\x39\x34\x36\x20\x30\x2e\x32\x31\x35\ -\x38\x38\x20\x31\x2e\x38\x35\x31\x36\x20\x30\x2e\x34\x31\x33\x39\ -\x31\x6c\x31\x2e\x36\x34\x36\x31\x20\x30\x2e\x33\x36\x30\x32\x39\ -\x76\x31\x2e\x33\x30\x36\x33\x63\x30\x20\x30\x2e\x37\x31\x38\x34\ -\x36\x2d\x30\x2e\x30\x33\x32\x20\x31\x2e\x33\x30\x32\x34\x2d\x30\ -\x2e\x30\x37\x32\x20\x31\x2e\x32\x39\x37\x38\x2d\x30\x2e\x30\x33\ -\x39\x20\x30\x2d\x30\x2e\x38\x37\x32\x33\x2d\x30\x2e\x32\x34\x38\ -\x33\x32\x2d\x31\x2e\x38\x35\x31\x36\x2d\x30\x2e\x35\x34\x31\x35\ -\x32\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x39\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x31\x30\x2e\x38\x2d\x35\x35\x32\x2e\x31\x38\x2d\x32\ -\x2e\x36\x38\x31\x31\x2d\x30\x2e\x37\x38\x35\x33\x34\x76\x2d\x31\ -\x2e\x36\x35\x39\x33\x2d\x31\x2e\x36\x35\x39\x33\x6c\x32\x2e\x36\ -\x31\x37\x32\x2d\x32\x2e\x38\x38\x36\x33\x63\x31\x2e\x34\x33\x39\ -\x34\x2d\x31\x2e\x35\x38\x37\x35\x20\x32\x2e\x36\x37\x37\x34\x2d\ -\x32\x2e\x39\x34\x36\x38\x20\x32\x2e\x37\x35\x30\x39\x2d\x33\x2e\ -\x30\x32\x30\x36\x20\x30\x2e\x31\x31\x36\x32\x2d\x30\x2e\x31\x31\ -\x36\x36\x34\x20\x30\x2e\x31\x33\x33\x38\x20\x30\x2e\x35\x38\x33\ -\x37\x39\x20\x30\x2e\x31\x33\x33\x38\x20\x35\x2e\x33\x33\x39\x39\ -\x20\x30\x20\x33\x2e\x30\x31\x30\x38\x20\x30\x2e\x31\x30\x30\x33\ -\x20\x35\x2e\x35\x30\x32\x34\x20\x30\x2e\x30\x36\x31\x20\x35\x2e\ -\x34\x39\x37\x36\x2d\x30\x2e\x30\x33\x39\x20\x30\x2d\x31\x2e\x34\ -\x30\x38\x2d\x30\x2e\x33\x39\x34\x36\x34\x2d\x32\x2e\x38\x38\x32\ -\x34\x2d\x30\x2e\x38\x32\x36\x35\x39\x7a\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x39\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x35\x2e\x33\x2d\ -\x35\x35\x37\x2e\x31\x34\x2d\x31\x2e\x37\x31\x34\x37\x2d\x30\x2e\ -\x33\x39\x33\x38\x33\x2d\x30\x2e\x30\x35\x38\x2d\x32\x2e\x32\x32\ -\x36\x34\x63\x2d\x30\x2e\x30\x39\x36\x2d\x33\x2e\x37\x34\x33\x32\ -\x2d\x30\x2e\x32\x31\x38\x33\x2d\x35\x2e\x39\x33\x31\x39\x2d\x30\ -\x2e\x31\x31\x34\x37\x2d\x35\x2e\x39\x33\x31\x39\x20\x30\x2e\x31\ -\x33\x35\x20\x30\x20\x39\x2e\x34\x39\x39\x35\x20\x32\x2e\x32\x35\ -\x31\x39\x20\x39\x2e\x37\x30\x33\x31\x20\x32\x2e\x33\x33\x36\x37\ -\x20\x30\x2e\x31\x34\x32\x35\x20\x30\x2e\x30\x35\x39\x34\x2d\x30\ -\x2e\x32\x39\x37\x33\x20\x30\x2e\x35\x39\x35\x36\x39\x2d\x32\x2e\ -\x37\x32\x35\x32\x20\x33\x2e\x33\x32\x35\x31\x2d\x32\x2e\x33\x31\ -\x31\x39\x20\x32\x2e\x35\x39\x39\x2d\x32\x2e\x39\x34\x33\x32\x20\ -\x33\x2e\x32\x35\x37\x34\x2d\x33\x2e\x31\x33\x35\x39\x20\x33\x2e\ -\x32\x36\x39\x32\x2d\x30\x2e\x31\x33\x32\x36\x20\x30\x2e\x30\x31\ -\x30\x34\x2d\x31\x2e\x30\x31\x32\x38\x2d\x30\x2e\x31\x36\x32\x32\ -\x35\x2d\x31\x2e\x39\x35\x36\x2d\x30\x2e\x33\x37\x38\x38\x32\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x67\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\ -\x35\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x36\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x32\ -\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\ -\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\ -\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x34\x39\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x33\ -\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\ -\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x39\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x30\x2e\x38\x35\x39\x20\x33\x2e\x30\x33\x30\ -\x34\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x32\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\x34\x38\x38\x2e\x39\x2d\ -\x35\x36\x36\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\ -\x2e\x33\x37\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\ -\x38\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\ -\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x32\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\x30\ -\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\x30\ -\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\x6f\ -\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x36\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x33\x33\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\x31\ -\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x34\x31\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x34\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\ -\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\ -\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x33\x37\x35\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\ -\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x37\x35\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x36\x2e\x39\x2d\x35\x36\x36\x2e\ -\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\ -\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x38\x31\x22\ -\x20\x64\x3d\x22\x6d\x31\x33\x34\x37\x2e\x32\x2d\x35\x35\x33\x2e\ -\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x3e\x0a\ -\x20\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x30\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x35\ -\x36\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\ -\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\x6d\x31\ -\x37\x33\x32\x2e\x31\x2d\x35\x30\x37\x2e\x36\x34\x20\x31\x33\x38\ -\x2e\x35\x36\x2d\x38\x30\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\ -\x2d\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x2d\x31\x33\x38\x2e\x35\ -\x36\x2d\x38\x30\x76\x31\x36\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x35\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x37\x33\x32\x2e\x31\x2d\x33\x34\x37\x2e\x36\x34\x20\ -\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x38\x37\x30\x2e\x36\x2d\x32\x36\x37\x2e\x36\x34\x20\x31\x33\ -\x38\x2e\x35\x36\x2d\x38\x30\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x32\x36\x32\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x35\x38\x37\ -\x2e\x36\x34\x76\x31\x36\x30\x6c\x2d\x31\x33\x38\x2e\x35\x36\x20\ -\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x36\x34\x22\x20\ -\x64\x3d\x22\x6d\x31\x38\x37\x30\x2e\x36\x2d\x34\x32\x37\x2e\x36\ -\x34\x20\x31\x33\x38\x2e\x35\x36\x20\x38\x30\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x20\x3c\x67\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\ -\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x36\x36\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x2d\x38\x30\x20\x38\x30\ -\x20\x38\x30\x20\x38\x30\x20\x38\x30\x2d\x38\x30\x7a\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x37\x30\x22\x20\x64\x3d\x22\x6d\x31\ -\x36\x32\x30\x2d\x37\x32\x37\x2e\x36\x34\x76\x38\x30\x6c\x38\x30\ -\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x32\x37\x32\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x36\x34\ -\x37\x2e\x36\x34\x2d\x38\x30\x2d\x38\x30\x76\x2d\x38\x30\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x32\x37\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x36\x32\x30\x2d\x38\x38\x37\x2e\x36\x34\x76\x38\x30\x6c\x2d\ -\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x37\ -\x36\x22\x20\x64\x3d\x22\x6d\x31\x36\x32\x30\x2d\x38\x30\x37\x2e\ -\x36\x34\x20\x38\x30\x20\x38\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x30\x22\x20\x64\x3d\x22\x6d\x32\x32\x35\x32\x2e\x39\ -\x2d\x39\x36\x37\x2e\x36\x34\x2d\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x76\x31\x36\x30\x6c\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x7a\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x32\x38\x32\x22\x20\x64\x3d\ -\x22\x6d\x32\x30\x38\x38\x2e\x31\x2d\x39\x30\x37\x2e\x36\x34\x2d\ -\x31\x36\x34\x2e\x38\x35\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\ -\x2d\x36\x30\x20\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x32\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x39\x32\x33\x2e\x32\x2d\x39\x36\x37\x2e\x36\x34\x76\x31\x36\x30\ -\x6c\x31\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x32\x38\x36\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\ -\x2e\x31\x2d\x31\x30\x32\x37\x2e\x36\x76\x31\x36\x30\x6c\x2d\x31\ -\x36\x34\x2e\x38\x35\x20\x36\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x32\x38\x38\x22\x20\x64\x3d\x22\x6d\x32\x30\x38\x38\x2e\x31\ -\x2d\x38\x36\x37\x2e\x36\x34\x20\x31\x36\x34\x2e\x38\x35\x20\x36\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x20\x3c\x67\x20\x73\ -\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\ -\x22\x3e\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x33\x32\x30\x22\x20\x64\x3d\x22\x6d\ -\x31\x31\x38\x38\x2e\x31\x2d\x33\x34\x31\x2e\x36\x37\x20\x31\x35\ -\x33\x2e\x33\x31\x2d\x37\x31\x2e\x34\x38\x38\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x2d\x31\x35\x33\x2e\x33\x31\ -\x20\x37\x31\x2e\x34\x38\x38\x2d\x31\x35\x33\x2e\x33\x31\x2d\x38\ -\x38\x2e\x35\x31\x32\x76\x31\x36\x30\x6c\x31\x35\x33\x2e\x33\x31\ -\x20\x38\x38\x2e\x35\x31\x32\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x39\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\x33\x31\ -\x2d\x37\x31\x2e\x34\x38\x38\x76\x2d\x31\x36\x30\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x33\x32\x34\x22\x20\x64\x3d\x22\x6d\x31\x33\x34\ -\x31\x2e\x34\x2d\x34\x31\x33\x2e\x31\x36\x76\x31\x36\x30\x6c\x2d\ -\x31\x35\x33\x2e\x33\x31\x20\x37\x31\x2e\x34\x38\x38\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x32\x36\x22\x20\x64\x3d\x22\x6d\x31\x33\ -\x34\x31\x2e\x34\x2d\x32\x35\x33\x2e\x31\x36\x20\x31\x35\x33\x2e\ -\x33\x31\x20\x38\x38\x2e\x35\x31\x32\x22\x2f\x3e\x0a\x20\x20\x20\ -\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\ -\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x69\x6d\x61\x67\x65\x20\x69\x64\ -\x3d\x22\x69\x6d\x61\x67\x65\x34\x33\x33\x36\x22\x20\x73\x74\x79\ -\x6c\x65\x3d\x22\x69\x6d\x61\x67\x65\x2d\x72\x65\x6e\x64\x65\x72\ -\x69\x6e\x67\x3a\x6f\x70\x74\x69\x6d\x69\x7a\x65\x53\x70\x65\x65\ -\x64\x22\x20\x78\x6c\x69\x6e\x6b\x3a\x68\x72\x65\x66\x3d\x22\x64\ -\x61\x74\x61\x3a\x69\x6d\x61\x67\x65\x2f\x70\x6e\x67\x3b\x62\x61\ -\x73\x65\x36\x34\x2c\x69\x56\x42\x4f\x52\x77\x30\x4b\x47\x67\x6f\ -\x41\x41\x41\x41\x4e\x53\x55\x68\x45\x55\x67\x41\x41\x41\x52\x38\ -\x41\x41\x41\x41\x70\x43\x41\x59\x41\x41\x41\x41\x4d\x41\x79\x31\ -\x4a\x41\x41\x41\x41\x42\x48\x4e\x43\x53\x56\x51\x49\x43\x41\x67\ -\x49\x66\x41\x68\x6b\x69\x41\x41\x41\x48\x69\x68\x4a\x52\x45\x46\ -\x55\x20\x65\x4a\x7a\x74\x6e\x58\x64\x34\x56\x46\x58\x36\x78\x7a\ -\x2f\x54\x61\x7a\x4b\x54\x6d\x55\x6b\x6a\x6a\x59\x54\x51\x51\x69\ -\x67\x4b\x32\x43\x6c\x57\x31\x72\x35\x59\x31\x37\x4a\x69\x58\x63\ -\x74\x61\x31\x72\x61\x75\x5a\x58\x55\x74\x61\x2f\x6e\x70\x36\x75\ -\x34\x71\x72\x67\x58\x64\x74\x61\x30\x67\x43\x77\x49\x57\x20\x6d\ -\x6f\x41\x46\x6b\x43\x49\x6c\x51\x41\x67\x51\x45\x6b\x68\x49\x53\ -\x47\x2f\x54\x35\x39\x62\x66\x48\x78\x4d\x69\x4a\x59\x48\x41\x44\ -\x50\x43\x48\x38\x33\x6d\x65\x50\x44\x79\x5a\x4f\x2b\x66\x65\x62\ -\x30\x35\x35\x7a\x7a\x6e\x76\x2b\x39\x36\x44\x35\x73\x55\x58\x58\ -\x6c\x42\x4a\x6b\x43\x42\x42\x67\x6d\x4f\x4d\x20\x50\x69\x4d\x7a\ -\x34\x33\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x66\x55\x46\x2b\ -\x2f\x76\x48\x57\x6b\x43\x42\x42\x67\x6c\x38\x67\x65\x72\x66\x62\ -\x66\x62\x77\x31\x4a\x45\x69\x51\x34\x42\x65\x49\x50\x6a\x6b\x35\ -\x2b\x58\x68\x72\x53\x4a\x41\x67\x77\x53\x38\x51\x76\x64\x56\x71\ -\x50\x64\x34\x61\x45\x69\x52\x49\x20\x38\x41\x74\x45\x62\x7a\x41\ -\x59\x59\x72\x71\x42\x4a\x4d\x76\x38\x38\x36\x74\x76\x6d\x4c\x31\ -\x36\x50\x58\x6b\x65\x4e\x34\x4e\x7a\x4d\x68\x6d\x63\x6e\x55\x6d\ -\x2f\x6a\x48\x52\x79\x33\x43\x6b\x34\x62\x66\x45\x7a\x62\x6b\x32\ -\x4e\x44\x57\x54\x6e\x35\x42\x47\x4a\x68\x4f\x4e\x32\x7a\x34\x72\ -\x36\x52\x6e\x34\x6f\x20\x4b\x79\x66\x50\x34\x79\x4c\x4c\x6e\x55\ -\x4b\x47\x30\x30\x47\x79\x31\x52\x4b\x33\x2b\x78\x38\x75\x4e\x53\ -\x31\x74\x31\x44\x53\x33\x6b\x75\x5a\x49\x4a\x74\x32\x5a\x6a\x4d\ -\x31\x73\x4f\x6d\x35\x61\x41\x46\x5a\x73\x72\x65\x43\x37\x7a\x56\ -\x76\x4a\x38\x37\x6a\x4a\x54\x2f\x65\x51\x6b\x65\x49\x6b\x7a\x5a\ -\x47\x4d\x20\x78\x52\x68\x62\x76\x39\x6d\x66\x6f\x39\x47\x32\x4b\ -\x37\x5a\x57\x38\x4e\x58\x61\x44\x65\x53\x6e\x65\x52\x69\x51\x6d\ -\x55\x47\x4b\x33\x55\x5a\x75\x71\x6f\x73\x6b\x69\x7a\x6c\x75\x7a\ -\x7a\x68\x63\x50\x63\x65\x69\x4c\x6e\x76\x4c\x6b\x6f\x31\x6c\x7a\ -\x46\x75\x2f\x69\x56\x79\x33\x6d\x33\x34\x5a\x71\x66\x52\x78\x20\ -\x70\x35\x44\x75\x53\x4d\x4b\x54\x6c\x49\x52\x4f\x70\x34\x33\x62\ -\x63\x33\x70\x71\x57\x33\x30\x73\x4e\x32\x31\x6f\x37\x2b\x44\x78\ -\x54\x32\x61\x69\x4e\x78\x69\x35\x61\x50\x53\x4a\x58\x44\x76\x2b\ -\x4e\x45\x71\x72\x61\x79\x69\x74\x72\x6d\x58\x42\x68\x69\x33\x73\ -\x61\x6d\x70\x42\x72\x39\x57\x53\x35\x58\x49\x77\x20\x73\x45\x38\ -\x6d\x52\x54\x6d\x5a\x46\x47\x61\x6b\x34\x55\x36\x32\x59\x7a\x63\ -\x66\x6e\x77\x36\x77\x42\x31\x6c\x52\x2b\x47\x4c\x31\x65\x6c\x36\ -\x66\x75\x34\x51\x42\x57\x52\x6e\x73\x62\x47\x36\x6a\x75\x71\x6d\ -\x46\x68\x76\x59\x4f\x6a\x46\x6f\x64\x47\x63\x35\x6b\x63\x6c\x50\ -\x64\x46\x47\x61\x6d\x4d\x69\x41\x7a\x20\x67\x33\x52\x6e\x4d\x6b\ -\x6b\x57\x4d\x31\x61\x54\x45\x59\x31\x47\x45\x33\x63\x39\x6b\x69\ -\x7a\x7a\x78\x55\x38\x6c\x50\x44\x5a\x6a\x4c\x71\x30\x36\x45\x79\ -\x5a\x46\x77\x6f\x61\x4d\x78\x32\x4b\x68\x77\x4a\x4e\x43\x51\x61\ -\x71\x62\x2f\x44\x51\x50\x2b\x52\x6d\x70\x35\x48\x6c\x63\x58\x56\ -\x70\x4d\x4d\x55\x34\x65\x20\x50\x52\x45\x57\x52\x4e\x35\x64\x2b\ -\x44\x31\x66\x72\x39\x76\x49\x4f\x53\x4f\x4b\x61\x51\x38\x4c\x7a\ -\x46\x68\x56\x51\x6c\x31\x72\x47\x38\x30\x64\x50\x6d\x77\x57\x45\ -\x2b\x6e\x4a\x79\x57\x53\x37\x6e\x66\x54\x50\x54\x4b\x4d\x67\x50\ -\x59\x32\x4d\x46\x41\x63\x4f\x71\x2b\x57\x34\x47\x38\x77\x39\x32\ -\x71\x66\x2f\x20\x2b\x42\x4e\x31\x51\x5a\x47\x2b\x41\x34\x70\x70\ -\x57\x37\x6d\x56\x6b\x4b\x38\x64\x67\x79\x70\x69\x30\x65\x6e\x49\ -\x64\x6a\x6b\x59\x6d\x70\x31\x4a\x75\x6a\x4f\x4a\x51\x64\x6c\x39\ -\x4b\x45\x68\x50\x78\x57\x59\x79\x34\x6b\x71\x79\x48\x7a\x55\x39\ -\x30\x35\x61\x76\x78\x6d\x34\x78\x38\x2b\x75\x54\x52\x78\x37\x58\ -\x20\x75\x76\x53\x48\x77\x72\x7a\x32\x78\x55\x4c\x65\x58\x4c\x79\ -\x55\x6b\x58\x6e\x5a\x6a\x4f\x78\x66\x79\x4a\x71\x71\x57\x6d\x61\ -\x76\x32\x55\x42\x64\x61\x7a\x74\x68\x51\x63\x52\x74\x74\x35\x48\ -\x68\x54\x43\x59\x2f\x33\x55\x4e\x42\x65\x69\x72\x35\x61\x61\x6d\ -\x34\x6b\x71\x79\x6b\x4f\x5a\x4c\x6a\x31\x76\x38\x31\x20\x33\x6f\ -\x37\x32\x49\x38\x72\x7a\x57\x56\x4f\x78\x6b\x38\x63\x2b\x2b\x5a\ -\x79\x37\x4c\x6a\x79\x58\x38\x30\x63\x4e\x5a\x2b\x58\x57\x37\x56\ -\x77\x77\x61\x73\x51\x2b\x33\x31\x45\x55\x68\x59\x5a\x32\x4c\x39\ -\x56\x4e\x4c\x57\x79\x70\x32\x63\x32\x6d\x71\x68\x6f\x32\x56\x64\ -\x65\x77\x73\x36\x47\x52\x6d\x58\x2b\x38\x20\x69\x32\x79\x33\x36\ -\x37\x43\x65\x47\x61\x2f\x5a\x4d\x52\x67\x52\x65\x47\x72\x71\x62\ -\x4e\x70\x43\x59\x5a\x36\x2b\x35\x6a\x4c\x4b\x61\x6e\x59\x7a\x38\ -\x64\x52\x52\x51\x4e\x51\x6f\x4e\x58\x74\x39\x31\x4c\x61\x30\x55\ -\x64\x58\x59\x7a\x4c\x62\x61\x4f\x72\x62\x57\x31\x72\x4f\x37\x74\ -\x51\x31\x76\x4d\x45\x69\x53\x20\x32\x63\x53\x37\x64\x30\x34\x69\ -\x78\x57\x36\x4c\x53\x63\x50\x65\x64\x41\x53\x43\x50\x50\x48\x70\ -\x4c\x4c\x37\x61\x55\x55\x39\x79\x30\x51\x68\x55\x67\x78\x46\x52\ -\x6c\x6f\x68\x49\x49\x75\x46\x51\x6b\x45\x67\x77\x67\x42\x41\x4b\ -\x51\x43\x67\x45\x34\x53\x41\x47\x55\x63\x42\x6a\x30\x4a\x4a\x6d\ -\x4d\x6e\x4a\x79\x20\x59\x56\x39\x65\x76\x50\x35\x79\x39\x44\x70\ -\x64\x33\x50\x54\x55\x74\x58\x62\x77\x38\x49\x66\x54\x36\x4e\x65\ -\x6e\x44\x35\x65\x65\x63\x69\x49\x66\x4c\x56\x37\x4b\x6c\x48\x74\ -\x76\x36\x37\x6f\x75\x53\x68\x49\x4e\x37\x56\x37\x71\x32\x74\x71\ -\x70\x62\x6d\x70\x68\x57\x32\x30\x64\x46\x58\x57\x4e\x56\x4e\x51\ -\x33\x20\x30\x4e\x6a\x65\x7a\x76\x38\x65\x2f\x6a\x33\x5a\x37\x70\ -\x54\x44\x65\x6d\x61\x38\x32\x6e\x5a\x76\x37\x62\x38\x39\x38\x33\ -\x52\x75\x66\x6d\x38\x6d\x76\x37\x72\x73\x52\x76\x78\x43\x47\x48\ -\x38\x6b\x54\x48\x76\x41\x52\x33\x4e\x62\x43\x32\x30\x64\x72\x62\ -\x53\x33\x74\x2b\x4a\x72\x62\x79\x58\x6b\x62\x55\x63\x4a\x20\x42\ -\x55\x6a\x58\x4b\x73\x7a\x37\x38\x77\x50\x30\x54\x66\x50\x45\x70\ -\x4b\x45\x6e\x50\x54\x65\x64\x4f\x35\x62\x5a\x4b\x39\x62\x77\x78\ -\x4e\x57\x2f\x37\x72\x72\x65\x55\x31\x33\x75\x61\x47\x69\x6b\x76\ -\x71\x33\x74\x69\x4f\x72\x79\x59\x47\x79\x74\x72\x65\x50\x75\x39\ -\x7a\x35\x6c\x68\x32\x4c\x45\x31\x69\x65\x58\x20\x6b\x31\x51\x66\ -\x55\x78\x2b\x2b\x71\x2b\x75\x36\x71\x71\x70\x34\x51\x32\x45\x61\ -\x32\x74\x71\x70\x61\x32\x32\x6e\x6f\x72\x36\x52\x37\x58\x55\x4e\ -\x6c\x4f\x32\x71\x5a\x58\x46\x4a\x4b\x51\x75\x66\x65\x6f\x6a\x42\ -\x4f\x5a\x6d\x48\x39\x63\x79\x34\x72\x58\x77\x6b\x57\x65\x59\x2f\ -\x53\x35\x59\x78\x61\x33\x55\x4a\x20\x37\x39\x33\x33\x4f\x77\x5a\ -\x6c\x5a\x37\x4b\x39\x72\x6f\x46\x2f\x66\x2f\x50\x39\x41\x63\x5a\ -\x48\x71\x39\x57\x53\x36\x58\x4b\x53\x36\x58\x4a\x79\x38\x73\x42\ -\x2b\x68\x45\x57\x52\x33\x37\x30\x2b\x68\x52\x56\x62\x79\x6d\x6e\ -\x32\x2b\x67\x2f\x62\x2b\x4d\x53\x44\x44\x56\x55\x31\x50\x50\x4c\ -\x52\x64\x4b\x34\x2f\x20\x63\x77\x79\x33\x54\x54\x69\x54\x6e\x59\ -\x33\x4e\x66\x4c\x78\x6b\x61\x5a\x66\x78\x30\x57\x6d\x31\x70\x44\ -\x73\x64\x70\x44\x73\x64\x6e\x4e\x69\x76\x4c\x78\x42\x74\x45\x45\ -\x56\x56\x2b\x64\x76\x6e\x58\x2f\x4f\x6e\x2f\x30\x7a\x46\x47\x77\ -\x7a\x46\x78\x66\x69\x6f\x71\x73\x71\x79\x73\x75\x33\x38\x34\x65\ -\x4f\x5a\x20\x6d\x50\x4f\x48\x4d\x50\x79\x73\x55\x55\x69\x4b\x67\ -\x69\x68\x4c\x68\x43\x57\x52\x6b\x43\x67\x51\x4e\x4a\x6f\x49\x57\ -\x6d\x7a\x34\x68\x54\x42\x68\x55\x55\x41\x46\x52\x46\x57\x6c\x54\ -\x6c\x57\x70\x4b\x79\x38\x6a\x73\x4b\x47\x4d\x73\x43\x42\x69\x74\ -\x38\x52\x75\x66\x46\x52\x56\x5a\x57\x46\x4a\x4b\x53\x2f\x4e\x20\ -\x6d\x73\x64\x54\x31\x31\x7a\x4f\x42\x61\x4f\x47\x30\x39\x54\x68\ -\x34\x36\x6f\x78\x70\x2b\x7a\x7a\x50\x59\x4e\x65\x54\x37\x62\x48\ -\x52\x62\x62\x48\x78\x65\x6a\x2b\x42\x51\x41\x45\x49\x78\x47\x75\ -\x65\x58\x6b\x79\x33\x35\x61\x56\x45\x34\x78\x45\x59\x74\x59\x53\ -\x44\x2b\x30\x37\x47\x35\x74\x52\x46\x42\x6b\x56\x20\x46\x55\x56\ -\x52\x6b\x42\x55\x46\x74\x46\x71\x4d\x4e\x6a\x73\x57\x76\x51\x37\ -\x4a\x5a\x6b\x64\x78\x70\x79\x4b\x48\x41\x67\x52\x4b\x53\x39\x6a\ -\x64\x32\x6b\x78\x45\x46\x49\x2b\x61\x6e\x76\x5a\x41\x73\x4b\x74\ -\x50\x37\x61\x47\x37\x75\x74\x77\x7a\x54\x6c\x61\x56\x56\x38\x61\ -\x74\x4c\x6b\x56\x4a\x34\x73\x4e\x76\x20\x66\x2b\x53\x76\x58\x79\ -\x79\x69\x33\x2b\x69\x78\x6a\x4d\x7a\x75\x53\x33\x74\x7a\x41\x30\ -\x70\x7a\x78\x7a\x37\x66\x30\x32\x67\x30\x4f\x4b\x77\x57\x48\x46\ -\x59\x4c\x41\x37\x49\x79\x47\x54\x64\x30\x4d\x43\x46\x42\x34\x4a\ -\x5a\x2f\x76\x49\x74\x4f\x70\x30\x4e\x52\x34\x35\x65\x54\x66\x46\ -\x6a\x47\x70\x38\x58\x6e\x20\x35\x36\x6c\x70\x73\x7a\x47\x62\x7a\ -\x4d\x78\x35\x34\x67\x45\x63\x6e\x66\x36\x63\x62\x4c\x65\x4c\x4a\ -\x36\x36\x2b\x39\x4b\x42\x6c\x4a\x56\x6e\x6d\x6d\x55\x38\x2f\x52\ -\x36\x50\x52\x4d\x50\x48\x55\x55\x53\x6a\x4b\x73\x55\x32\x73\x46\ -\x69\x57\x5a\x44\x37\x35\x62\x7a\x68\x65\x72\x53\x33\x6a\x39\x39\ -\x68\x73\x5a\x20\x55\x5a\x43\x48\x52\x71\x4f\x68\x6a\x38\x76\x4a\ -\x30\x39\x64\x64\x66\x73\x6a\x79\x55\x2b\x5a\x2f\x79\x2b\x77\x56\ -\x61\x7a\x68\x6a\x79\x45\x42\x30\x63\x56\x68\x6c\x42\x4d\x49\x52\ -\x58\x76\x74\x69\x49\x54\x4d\x32\x56\x54\x4c\x69\x72\x49\x6b\x6b\ -\x70\x62\x69\x52\x46\x49\x58\x49\x48\x71\x4d\x6a\x52\x4e\x42\x72\ -\x20\x74\x57\x6a\x51\x6f\x4b\x6f\x67\x4b\x54\x4b\x53\x4c\x43\x4d\ -\x71\x4d\x71\x67\x71\x6d\x71\x6f\x4b\x72\x69\x6b\x71\x59\x46\x76\ -\x4e\x37\x72\x6a\x73\x7a\x2f\x32\x68\x4d\x4b\x2f\x4d\x6d\x55\x39\ -\x46\x59\x77\x76\x2f\x65\x2f\x51\x2b\x63\x6a\x78\x75\x4e\x42\x6f\ -\x4e\x49\x55\x46\x67\x35\x64\x62\x74\x6e\x48\x66\x43\x20\x30\x42\ -\x37\x4c\x43\x70\x4c\x45\x2f\x56\x4d\x2b\x59\x56\x47\x44\x46\x36\ -\x50\x4c\x67\x2f\x6b\x6f\x62\x51\x56\x37\x6f\x69\x66\x74\x42\x70\ -\x30\x4f\x55\x52\x4a\x6f\x44\x77\x57\x6a\x64\x53\x70\x47\x43\x49\ -\x6b\x69\x59\x55\x6b\x6b\x49\x6b\x6c\x45\x4f\x6c\x65\x58\x6b\x63\ -\x70\x74\x59\x44\x53\x69\x53\x58\x62\x45\x20\x52\x58\x74\x50\x65\ -\x6c\x70\x38\x66\x6a\x35\x61\x73\x76\x53\x41\x53\x58\x70\x76\x39\ -\x68\x34\x6e\x34\x34\x63\x4f\x6a\x6f\x75\x65\x58\x63\x32\x74\x50\ -\x50\x72\x4a\x54\x4d\x70\x38\x43\x68\x4f\x75\x75\x67\x57\x72\x4c\ -\x51\x6c\x5a\x55\x64\x41\x47\x41\x38\x69\x48\x47\x49\x65\x69\x4a\ -\x50\x48\x59\x68\x35\x2b\x52\x20\x35\x6b\x78\x6d\x7a\x4a\x42\x42\ -\x63\x66\x56\x50\x39\x62\x72\x58\x62\x71\x6d\x70\x34\x39\x72\x58\ -\x33\x6d\x46\x4d\x63\x52\x47\x54\x37\x35\x6a\x55\x5a\x58\x67\x41\ -\x4f\x6f\x4a\x42\x6e\x70\x38\x2b\x35\x36\x44\x6c\x2f\x7a\x56\x33\ -\x45\x65\x73\x71\x64\x2f\x4c\x47\x48\x54\x64\x69\x4d\x75\x68\x52\ -\x56\x4f\x58\x49\x20\x56\x52\x38\x6d\x37\x59\x45\x67\x74\x2f\x2f\ -\x72\x41\x37\x62\x58\x4e\x7a\x50\x6a\x73\x54\x39\x77\x51\x72\x2b\ -\x2b\x58\x66\x76\x57\x56\x70\x2b\x66\x70\x7a\x2f\x39\x2f\x4b\x44\ -\x6c\x70\x79\x39\x64\x79\x5a\x51\x46\x53\x2f\x6a\x30\x6a\x33\x65\ -\x54\x5a\x44\x47\x6a\x6a\x58\x48\x50\x75\x37\x32\x75\x67\x63\x74\ -\x66\x20\x65\x59\x76\x76\x57\x68\x55\x75\x75\x50\x77\x6d\x42\x76\ -\x59\x74\x4a\x44\x50\x5a\x69\x64\x74\x71\x4a\x38\x6c\x6b\x78\x6d\ -\x6f\x77\x59\x74\x49\x62\x4d\x4f\x6a\x30\x36\x4c\x56\x61\x64\x46\ -\x6f\x4e\x57\x6f\x33\x6d\x35\x37\x31\x32\x54\x54\x55\x54\x30\x6c\ -\x4e\x34\x2b\x36\x36\x62\x55\x52\x57\x56\x57\x48\x66\x67\x20\x4f\ -\x78\x71\x61\x2b\x4d\x31\x72\x37\x2b\x42\x78\x4f\x70\x6e\x36\x38\ -\x4f\x2f\x4a\x54\x66\x56\x30\x50\x55\x74\x57\x46\x42\x72\x62\x76\ -\x51\x63\x74\x2f\x2b\x4c\x30\x4c\x2f\x69\x73\x64\x41\x63\x70\x51\ -\x34\x5a\x6a\x30\x47\x72\x52\x61\x75\x50\x6e\x72\x44\x77\x55\x42\ -\x39\x4e\x75\x30\x4f\x75\x51\x4a\x49\x6d\x32\x20\x6b\x4a\x2b\x4f\ -\x55\x41\x42\x76\x4f\x49\x78\x66\x43\x42\x4d\x51\x49\x70\x32\x47\ -\x53\x43\x43\x77\x63\x7a\x74\x53\x4f\x41\x78\x35\x42\x61\x41\x6f\ -\x4d\x57\x73\x2f\x6d\x4a\x35\x73\x74\x34\x74\x6e\x72\x72\x76\x69\ -\x6f\x4f\x58\x33\x48\x69\x63\x61\x4e\x44\x48\x72\x6d\x62\x64\x32\ -\x49\x78\x65\x2b\x4e\x42\x6d\x76\x20\x75\x34\x41\x4c\x4a\x31\x35\ -\x50\x51\x55\x59\x4f\x36\x55\x6b\x4f\x6e\x42\x59\x72\x46\x71\x50\ -\x70\x6b\x43\x75\x5a\x6c\x32\x5a\x38\x53\x58\x31\x62\x42\x79\x39\ -\x4d\x75\x68\x70\x4a\x6c\x6a\x45\x61\x34\x72\x65\x39\x37\x39\x58\ -\x4b\x35\x39\x4d\x66\x56\x76\x4c\x43\x7a\x4b\x2f\x35\x35\x4b\x48\ -\x66\x63\x2b\x71\x67\x20\x77\x67\x4d\x63\x54\x6c\x61\x54\x69\x5a\ -\x50\x36\x39\x2b\x75\x32\x72\x4b\x71\x71\x7a\x46\x69\x2b\x6d\x6b\ -\x2b\x2f\x57\x38\x36\x58\x54\x7a\x37\x55\x4f\x58\x69\x31\x30\x53\ -\x58\x77\x4d\x65\x43\x62\x6b\x6c\x49\x65\x2f\x76\x42\x2f\x50\x48\ -\x7a\x35\x52\x64\x78\x32\x33\x76\x67\x44\x47\x74\x4e\x6d\x4e\x6a\ -\x4e\x2b\x20\x36\x4f\x42\x75\x79\x36\x71\x71\x79\x74\x77\x31\x4a\ -\x54\x77\x37\x62\x52\x5a\x7a\x6e\x6e\x69\x41\x33\x46\x51\x33\x69\ -\x71\x4b\x69\x30\x78\x37\x35\x63\x48\x2f\x39\x71\x30\x57\x38\x4e\ -\x75\x38\x37\x52\x70\x30\x33\x6b\x62\x7a\x63\x41\x76\x52\x36\x41\ -\x37\x4b\x69\x49\x4d\x6b\x79\x67\x69\x77\x69\x79\x4e\x4c\x50\x20\ -\x50\x35\x4b\x30\x7a\x2b\x2b\x53\x4c\x45\x4e\x64\x44\x65\x4f\x53\ -\x6a\x45\x7a\x37\x34\x39\x33\x59\x7a\x4e\x48\x4f\x6f\x39\x55\x63\ -\x65\x51\x65\x64\x2b\x73\x4e\x4b\x6e\x70\x6f\x32\x68\x7a\x66\x75\ -\x6d\x4d\x54\x45\x55\x30\x63\x64\x30\x4c\x59\x5a\x4b\x51\x36\x75\ -\x48\x58\x39\x61\x74\x32\x56\x56\x56\x65\x58\x39\x20\x68\x64\x2f\ -\x78\x32\x70\x4b\x56\x35\x4a\x78\x32\x4a\x6c\x35\x52\x51\x4b\x38\ -\x42\x58\x51\x78\x36\x44\x6f\x65\x70\x50\x36\x7a\x6b\x72\x7a\x4f\ -\x2f\x5a\x73\x6f\x39\x74\x33\x48\x32\x38\x4b\x49\x44\x74\x42\x74\ -\x30\x4f\x6d\x52\x5a\x6f\x69\x58\x67\x52\x35\x42\x2b\x33\x73\x6f\ -\x47\x68\x41\x68\x42\x49\x59\x4a\x33\x20\x31\x77\x34\x69\x4c\x59\ -\x30\x77\x73\x42\x69\x30\x57\x72\x53\x6f\x78\x44\x4b\x76\x48\x45\ -\x70\x50\x55\x34\x65\x58\x68\x39\x37\x2f\x4c\x37\x4f\x66\x65\x4f\ -\x43\x41\x73\x74\x32\x4e\x45\x31\x6d\x52\x59\x36\x72\x4c\x76\x30\ -\x79\x64\x7a\x56\x76\x66\x72\x75\x44\x30\x38\x36\x38\x67\x4e\x79\ -\x63\x66\x57\x56\x55\x4a\x20\x43\x68\x46\x6b\x56\x53\x45\x6b\x43\ -\x6b\x52\x6b\x43\x58\x6f\x59\x68\x34\x71\x71\x38\x75\x36\x38\x78\ -\x58\x79\x2f\x61\x51\x73\x7a\x48\x2f\x38\x44\x46\x71\x4d\x52\x57\ -\x5a\x46\x69\x36\x6d\x76\x37\x30\x79\x76\x6a\x38\x2f\x37\x69\x70\ -\x65\x53\x6d\x65\x6e\x6a\x77\x76\x55\x39\x77\x32\x71\x30\x55\x35\ -\x57\x51\x78\x20\x75\x6e\x38\x42\x77\x77\x76\x79\x79\x48\x41\x36\ -\x4d\x42\x6b\x4d\x36\x48\x71\x77\x30\x45\x73\x32\x62\x4f\x62\x35\ -\x7a\x32\x59\x7a\x36\x34\x6e\x37\x75\x79\x49\x4a\x4f\x71\x33\x32\ -\x6b\x4d\x75\x39\x65\x50\x48\x43\x72\x50\x6e\x6f\x55\x6a\x4c\x34\ -\x35\x2f\x79\x6c\x76\x4c\x39\x6f\x47\x63\x50\x79\x2b\x6c\x43\x63\ -\x20\x6d\x38\x30\x70\x41\x77\x76\x4a\x54\x58\x56\x68\x4e\x42\x69\ -\x49\x69\x46\x4c\x33\x32\x6a\x65\x57\x38\x61\x63\x50\x70\x76\x48\ -\x5a\x49\x2f\x65\x53\x6e\x35\x45\x47\x52\x46\x63\x43\x50\x66\x32\ -\x74\x76\x65\x47\x2f\x50\x36\x79\x6b\x4b\x43\x75\x64\x48\x61\x73\ -\x57\x73\x32\x50\x44\x4b\x71\x77\x4f\x4e\x36\x36\x30\x20\x50\x74\ -\x68\x53\x58\x47\x41\x77\x49\x41\x42\x42\x49\x54\x70\x41\x39\x6a\ -\x68\x4a\x2f\x5a\x45\x49\x51\x55\x46\x41\x61\x61\x78\x6a\x75\x42\ -\x70\x68\x2b\x70\x38\x65\x49\x64\x6c\x71\x51\x5a\x51\x6b\x64\x44\ -\x6f\x74\x32\x68\x69\x4d\x34\x62\x2b\x58\x4c\x4f\x4f\x30\x77\x66\ -\x33\x35\x2b\x2b\x78\x35\x76\x44\x70\x72\x20\x4c\x6f\x56\x39\x30\ -\x68\x6d\x57\x6c\x38\x50\x4a\x41\x77\x76\x70\x6d\x35\x35\x4b\x57\ -\x42\x42\x34\x2f\x72\x4d\x35\x66\x50\x48\x6b\x67\x77\x65\x55\x6e\ -\x62\x31\x69\x44\x59\x2f\x2f\x62\x79\x35\x44\x78\x31\x2b\x41\x58\ -\x31\x56\x51\x68\x41\x68\x36\x51\x4b\x65\x4c\x66\x7a\x53\x77\x4f\ -\x39\x35\x62\x76\x49\x79\x38\x20\x56\x41\x39\x2f\x2f\x6e\x67\x36\ -\x66\x35\x74\x31\x59\x4c\x2f\x55\x36\x62\x51\x6f\x73\x6b\x52\x4c\ -\x77\x49\x65\x6f\x79\x46\x45\x48\x76\x74\x68\x70\x67\x42\x70\x32\ -\x45\x36\x36\x70\x67\x73\x48\x46\x30\x4c\x6d\x4e\x6a\x72\x62\x71\ -\x6b\x57\x73\x2f\x6c\x42\x36\x72\x32\x63\x52\x5a\x77\x34\x71\x36\ -\x4c\x64\x76\x64\x20\x4f\x4a\x46\x6b\x4a\x61\x61\x36\x2f\x47\x72\ -\x74\x52\x69\x77\x70\x48\x74\x59\x75\x2f\x59\x62\x31\x47\x67\x33\ -\x4a\x44\x69\x64\x4f\x54\x7a\x72\x4a\x37\x6a\x52\x4d\x53\x51\x36\ -\x38\x76\x67\x34\x63\x33\x52\x67\x66\x56\x56\x58\x35\x33\x39\x4b\ -\x56\x66\x4c\x68\x6b\x4b\x56\x2f\x38\x2b\x63\x47\x75\x79\x4c\x51\ -\x6b\x20\x78\x7a\x62\x78\x37\x6b\x2b\x76\x6a\x49\x38\x6e\x32\x63\ -\x37\x6b\x4f\x32\x38\x6d\x49\x38\x58\x42\x31\x74\x6f\x36\x64\x6a\ -\x59\x30\x38\x58\x33\x70\x56\x6a\x37\x35\x64\x6a\x6e\x56\x54\x53\ -\x32\x34\x6b\x32\x78\x73\x32\x31\x31\x50\x70\x73\x76\x4a\x36\x50\ -\x34\x46\x39\x45\x33\x7a\x6f\x4e\x56\x71\x32\x56\x53\x31\x20\x69\ -\x2f\x75\x6e\x66\x4d\x7a\x37\x39\x2f\x32\x4f\x33\x4e\x53\x66\x49\ -\x77\x68\x61\x72\x65\x61\x59\x2b\x58\x7a\x73\x56\x67\x74\x44\x7a\ -\x37\x69\x45\x56\x4a\x63\x48\x76\x39\x39\x4c\x59\x31\x4d\x39\x30\ -\x79\x71\x71\x2b\x4d\x63\x50\x4d\x78\x42\x38\x62\x61\x53\x5a\x64\ -\x54\x53\x30\x64\x57\x44\x55\x36\x78\x69\x61\x20\x6c\x38\x50\x6f\ -\x41\x66\x32\x77\x6d\x6f\x79\x73\x72\x64\x6a\x4a\x41\x31\x4d\x2b\ -\x35\x72\x31\x37\x62\x6d\x56\x51\x39\x73\x2f\x65\x66\x55\x57\x56\ -\x59\x39\x70\x32\x5a\x58\x74\x63\x76\x48\x33\x33\x4c\x58\x69\x53\ -\x6b\x39\x6a\x52\x30\x45\x54\x35\x37\x6e\x70\x57\x62\x61\x74\x67\ -\x30\x2b\x59\x79\x4e\x75\x78\x75\x20\x77\x71\x74\x6f\x4d\x44\x69\ -\x63\x61\x4f\x78\x4a\x53\x46\x59\x62\x49\x5a\x32\x57\x69\x43\x53\ -\x68\x74\x44\x5a\x54\x47\x47\x68\x6e\x78\x6c\x4d\x50\x6b\x75\x70\ -\x49\x41\x6b\x43\x51\x6f\x6a\x4e\x6a\x4c\x48\x70\x63\x53\x54\x5a\ -\x65\x76\x66\x56\x36\x73\x74\x77\x70\x31\x4c\x65\x31\x55\x31\x48\ -\x58\x79\x4c\x72\x4b\x20\x4b\x74\x36\x5a\x76\x35\x68\x74\x74\x58\ -\x57\x45\x52\x59\x6d\x77\x49\x50\x44\x50\x4c\x2b\x5a\x54\x6e\x4a\ -\x66\x44\x4b\x51\x50\x37\x59\x54\x57\x5a\x2b\x48\x46\x4c\x4f\x66\ -\x66\x2b\x5a\x7a\x6f\x6a\x7a\x72\x6f\x49\x32\x57\x7a\x47\x36\x2f\ -\x63\x68\x4b\x51\x70\x36\x72\x53\x59\x6d\x34\x33\x77\x34\x65\x4a\ -\x4a\x74\x20\x76\x48\x6e\x58\x4c\x61\x51\x37\x6b\x37\x76\x76\x6c\ -\x38\x6c\x32\x6d\x74\x76\x61\x43\x46\x5a\x75\x51\x35\x4f\x55\x6a\ -\x47\x51\x77\x45\x4a\x45\x6b\x77\x6d\x30\x74\x53\x4a\x58\x6c\x4d\ -\x4c\x41\x49\x39\x44\x2f\x37\x4d\x48\x51\x51\x30\x38\x72\x6e\x55\ -\x48\x70\x53\x48\x55\x6e\x6b\x70\x58\x6d\x59\x39\x73\x4f\x4b\x20\ -\x58\x6f\x30\x54\x4a\x63\x61\x4a\x7a\x6d\x77\x30\x34\x4f\x34\x2f\ -\x46\x49\x63\x6e\x44\x56\x55\x55\x69\x50\x68\x39\x74\x4c\x61\x31\ -\x55\x4c\x31\x70\x4c\x53\x46\x66\x4f\x33\x49\x34\x6a\x45\x73\x48\ -\x7a\x30\x32\x62\x78\x61\x6a\x43\x41\x6b\x37\x6f\x6c\x30\x65\x61\ -\x49\x35\x6b\x6c\x47\x38\x74\x34\x61\x63\x61\x58\x20\x66\x50\x62\ -\x49\x50\x66\x75\x6b\x48\x73\x51\x36\x38\x65\x35\x50\x72\x34\x79\ -\x50\x32\x57\x41\x6b\x4a\x41\x69\x59\x44\x41\x61\x47\x39\x63\x31\ -\x6c\x57\x4e\x39\x63\x4c\x6a\x6c\x35\x4a\x47\x72\x6e\x66\x72\x47\ -\x71\x71\x5a\x6c\x50\x76\x6c\x33\x4f\x75\x6f\x6f\x71\x70\x69\x7a\ -\x34\x6c\x6a\x61\x66\x48\x34\x38\x6a\x20\x6d\x5a\x72\x6d\x56\x74\ -\x36\x34\x34\x34\x59\x44\x50\x50\x77\x36\x72\x52\x62\x35\x47\x50\ -\x6c\x38\x7a\x41\x59\x6a\x76\x6c\x41\x41\x55\x38\x53\x4f\x78\x6d\ -\x44\x45\x6d\x5a\x47\x46\x79\x5a\x31\x4b\x35\x71\x42\x68\x42\x49\ -\x51\x77\x37\x58\x34\x76\x32\x6f\x71\x74\x2f\x47\x56\x35\x4b\x66\ -\x34\x76\x6c\x79\x44\x37\x20\x66\x65\x51\x37\x37\x49\x69\x52\x43\ -\x42\x2f\x38\x34\x58\x5a\x47\x39\x53\x2f\x59\x5a\x2f\x6b\x73\x53\ -\x72\x45\x31\x67\x4e\x31\x73\x78\x42\x73\x4d\x6b\x5a\x66\x6d\x6f\ -\x54\x67\x76\x6d\x2b\x4b\x38\x62\x48\x35\x39\x79\x73\x69\x75\x36\ -\x36\x75\x32\x56\x66\x44\x45\x52\x39\x4d\x5a\x30\x7a\x2b\x44\x46\ -\x56\x75\x33\x20\x55\x39\x48\x63\x79\x67\x35\x2f\x69\x41\x77\x64\ -\x7a\x48\x72\x71\x49\x66\x70\x31\x72\x73\x43\x69\x57\x69\x54\x30\ -\x75\x74\x68\x38\x4c\x43\x61\x39\x67\x62\x41\x67\x6f\x74\x4e\x71\ -\x79\x58\x4b\x37\x79\x48\x4b\x37\x47\x46\x73\x38\x71\x4b\x74\x74\ -\x61\x31\x76\x62\x75\x50\x72\x46\x31\x39\x46\x71\x4e\x48\x79\x34\ -\x20\x36\x41\x63\x65\x2f\x57\x42\x71\x39\x50\x4e\x32\x50\x36\x4d\ -\x6e\x58\x49\x48\x4a\x36\x61\x4c\x4a\x37\x30\x56\x53\x5a\x41\x52\ -\x5a\x77\x6f\x4a\x36\x7a\x49\x7a\x50\x48\x75\x30\x39\x39\x63\x75\ -\x64\x6a\x63\x32\x63\x39\x71\x66\x6e\x61\x47\x79\x6f\x52\x61\x6e\ -\x59\x41\x70\x49\x59\x4e\x54\x61\x69\x43\x50\x30\x48\x20\x67\x33\ -\x6e\x66\x5a\x46\x4b\x39\x52\x68\x50\x54\x4e\x75\x64\x51\x65\x6a\ -\x5a\x56\x31\x58\x44\x72\x36\x2b\x2b\x53\x37\x6e\x54\x30\x61\x70\ -\x7a\x49\x73\x68\x78\x54\x58\x56\x70\x4e\x42\x6e\x62\x35\x4f\x67\ -\x67\x61\x6a\x57\x69\x31\x57\x72\x51\x47\x41\x32\x70\x61\x42\x71\ -\x62\x55\x4e\x48\x53\x79\x51\x74\x6a\x58\x20\x67\x61\x74\x32\x4f\ -\x33\x31\x63\x4b\x55\x78\x66\x74\x70\x4b\x2f\x66\x6a\x59\x4c\x58\ -\x79\x68\x4d\x59\x34\x65\x58\x75\x58\x39\x35\x6d\x48\x36\x5a\x36\ -\x66\x76\x71\x55\x57\x4c\x54\x73\x7a\x2b\x39\x4d\x7a\x35\x36\x50\ -\x57\x48\x68\x77\x42\x44\x6b\x6e\x6b\x47\x5a\x6c\x2b\x70\x68\x79\ -\x59\x62\x4e\x66\x50\x37\x34\x20\x2f\x64\x6a\x4e\x4a\x6a\x6f\x43\ -\x51\x61\x71\x62\x57\x72\x6a\x37\x72\x51\x38\x59\x57\x7a\x7a\x34\ -\x67\x4c\x32\x76\x54\x71\x75\x4e\x61\x38\x6a\x75\x59\x46\x67\x4e\ -\x4f\x72\x7a\x42\x41\x49\x5a\x77\x45\x41\x30\x67\x4b\x51\x71\x43\ -\x4c\x42\x45\x53\x42\x55\x4b\x69\x69\x43\x44\x4c\x74\x4f\x34\x73\ -\x78\x33\x58\x79\x20\x57\x4b\x53\x4d\x50\x76\x6a\x44\x49\x63\x71\ -\x46\x43\x49\x57\x37\x4b\x37\x73\x69\x59\x6e\x75\x6a\x4b\x47\x70\ -\x4d\x30\x61\x55\x6b\x69\x78\x6c\x66\x4b\x4c\x54\x50\x5a\x33\x73\ -\x2f\x77\x35\x56\x6b\x70\x79\x41\x7a\x6e\x53\x65\x76\x6d\x59\x69\ -\x71\x71\x76\x6a\x44\x59\x54\x35\x59\x39\x41\x4d\x4e\x37\x56\x36\ -\x4b\x20\x63\x72\x4c\x32\x4b\x53\x66\x49\x4d\x76\x6f\x59\x4f\x34\ -\x4e\x4a\x72\x2b\x38\x32\x76\x4c\x78\x48\x6b\x39\x4e\x71\x35\x64\ -\x52\x42\x2f\x62\x6e\x37\x6f\x76\x4d\x41\x69\x49\x67\x69\x4e\x63\ -\x32\x74\x6a\x48\x74\x75\x4d\x70\x6c\x39\x63\x6d\x6e\x75\x33\x4e\ -\x49\x49\x55\x6a\x52\x79\x6c\x48\x51\x4d\x56\x7a\x36\x48\x20\x30\ -\x74\x34\x33\x7a\x59\x50\x4e\x5a\x6b\x58\x4a\x79\x67\x57\x74\x44\ -\x6d\x51\x5a\x77\x6b\x48\x59\x57\x51\x6e\x64\x76\x46\x5a\x6b\x30\ -\x47\x70\x69\x32\x73\x49\x65\x53\x73\x2f\x67\x6e\x44\x36\x38\x65\ -\x2f\x65\x74\x44\x4d\x76\x50\x52\x56\x58\x56\x51\x34\x34\x54\x4b\ -\x63\x61\x56\x52\x70\x4c\x5a\x54\x48\x76\x41\x20\x68\x38\x39\x6f\ -\x37\x46\x72\x52\x71\x59\x43\x71\x67\x71\x49\x71\x4b\x4f\x45\x67\ -\x51\x2b\x30\x32\x62\x6a\x35\x33\x48\x44\x65\x66\x4f\x77\x35\x4a\ -\x6c\x70\x6d\x2f\x64\x69\x4d\x7a\x6c\x71\x39\x69\x57\x4e\x2f\x63\ -\x41\x2b\x34\x6e\x79\x66\x46\x64\x2b\x66\x54\x71\x54\x6d\x61\x54\ -\x6f\x56\x76\x6a\x73\x77\x65\x4e\x20\x52\x73\x4e\x4e\x35\x34\x7a\ -\x46\x6f\x4e\x4f\x69\x30\x57\x68\x77\x32\x6d\x33\x30\x79\x30\x78\ -\x48\x52\x59\x33\x2b\x70\x66\x73\x2f\x56\x4b\x4e\x42\x4f\x55\x59\ -\x4f\x5a\x37\x4e\x42\x6a\x7a\x63\x55\x6f\x43\x4d\x55\x70\x44\x30\ -\x63\x78\x42\x73\x4f\x34\x51\x75\x48\x43\x45\x53\x69\x45\x59\x2b\ -\x49\x49\x6d\x50\x4e\x20\x4c\x53\x44\x53\x36\x64\x79\x56\x55\x63\ -\x46\x6f\x52\x4e\x56\x6f\x6f\x76\x72\x33\x51\x31\x61\x55\x6d\x4a\ -\x78\x75\x54\x70\x75\x56\x4e\x6e\x2b\x77\x78\x2b\x74\x39\x58\x43\ -\x6e\x63\x65\x50\x59\x59\x49\x46\x71\x76\x53\x52\x59\x4c\x47\x53\ -\x6b\x4f\x4e\x42\x6f\x4f\x36\x4a\x79\x69\x4a\x47\x48\x51\x78\x35\ -\x53\x6b\x20\x6a\x74\x47\x67\x49\x33\x79\x51\x33\x42\x61\x54\x77\ -\x63\x41\x4a\x2f\x66\x4b\x36\x5a\x6d\x2b\x54\x77\x55\x42\x47\x69\ -\x68\x4f\x4e\x47\x74\x30\x57\x43\x4c\x49\x55\x39\x61\x4e\x49\x41\ -\x68\x46\x52\x78\x4b\x69\x4e\x62\x52\x73\x59\x54\x2b\x30\x61\x6a\ -\x51\x61\x7a\x58\x67\x2b\x4b\x47\x74\x31\x50\x36\x66\x56\x67\x20\ -\x73\x6b\x53\x64\x72\x4e\x31\x6f\x4e\x4d\x52\x6f\x4f\x41\x2b\x6c\ -\x4a\x78\x51\x52\x75\x50\x75\x74\x44\x31\x42\x56\x74\x56\x66\x6a\ -\x52\x46\x62\x55\x6d\x4f\x72\x53\x61\x62\x4f\x69\x45\x53\x56\x6b\ -\x53\x55\x61\x55\x5a\x41\x52\x4a\x52\x70\x52\x6c\x4a\x45\x58\x75\ -\x6d\x76\x79\x6c\x76\x63\x61\x68\x58\x71\x66\x44\x20\x6e\x57\x78\ -\x48\x73\x33\x64\x6b\x64\x53\x2b\x69\x77\x5a\x5a\x6a\x76\x75\x30\ -\x79\x45\x42\x4b\x45\x48\x71\x2b\x72\x71\x73\x71\x47\x48\x64\x57\ -\x63\x55\x54\x53\x51\x76\x4d\x37\x73\x55\x4c\x31\x4f\x68\x36\x79\ -\x6f\x33\x64\x56\x70\x64\x4f\x56\x7a\x6a\x48\x77\x2b\x4e\x71\x4d\ -\x52\x58\x7a\x43\x41\x4e\x68\x7a\x73\x20\x30\x69\x72\x4b\x30\x53\ -\x31\x43\x52\x42\x4c\x78\x4e\x6a\x66\x67\x71\x36\x71\x45\x67\x41\ -\x38\x78\x79\x51\x47\x79\x42\x42\x5a\x72\x64\x4c\x42\x31\x49\x31\ -\x46\x52\x6c\x4a\x67\x36\x68\x4e\x74\x75\x6f\x39\x6e\x62\x63\x2b\ -\x6a\x36\x6d\x2f\x57\x62\x75\x4f\x66\x74\x44\x31\x6a\x34\x37\x4b\ -\x4e\x38\x75\x58\x6f\x64\x20\x5a\x77\x38\x66\x67\x71\x72\x53\x37\ -\x59\x77\x71\x53\x4c\x47\x48\x50\x73\x32\x47\x67\x30\x38\x73\x32\ -\x33\x62\x58\x38\x66\x78\x6e\x63\x78\x68\x56\x57\x4d\x43\x6d\x36\ -\x6c\x32\x4d\x4b\x52\x71\x49\x7a\x52\x79\x4e\x78\x41\x54\x46\x61\ -\x4e\x51\x6f\x2b\x71\x2b\x41\x70\x4d\x67\x59\x4e\x5a\x71\x34\x52\ -\x6b\x52\x69\x20\x30\x54\x35\x6a\x32\x53\x6f\x51\x42\x66\x72\x57\ -\x56\x46\x41\x64\x45\x56\x46\x73\x79\x64\x45\x56\x6a\x36\x70\x45\ -\x42\x2f\x74\x2b\x37\x57\x6a\x55\x61\x6d\x50\x7a\x73\x52\x78\x43\ -\x7a\x36\x49\x4e\x6d\x39\x6c\x63\x33\x30\x54\x52\x66\x55\x38\x79\ -\x49\x69\x65\x44\x6b\x77\x59\x55\x4d\x4b\x78\x76\x44\x70\x4b\x73\ -\x20\x52\x4b\x4f\x57\x2b\x33\x31\x66\x6c\x75\x58\x59\x4a\x6a\x71\ -\x72\x46\x57\x4e\x7a\x42\x49\x32\x71\x52\x55\x4a\x46\x30\x71\x68\ -\x30\x44\x54\x74\x56\x67\x64\x32\x37\x36\x4e\x41\x71\x6e\x50\x33\ -\x34\x38\x30\x79\x2b\x38\x30\x59\x32\x56\x64\x55\x67\x4b\x77\x71\ -\x69\x4a\x48\x63\x5a\x79\x48\x33\x30\x48\x49\x39\x6f\x20\x6c\x39\ -\x31\x6b\x77\x68\x2f\x75\x4f\x65\x33\x39\x72\x62\x6d\x4c\x57\x4c\ -\x53\x68\x6c\x4d\x74\x4f\x47\x38\x30\x7a\x55\x7a\x39\x6e\x66\x50\ -\x46\x67\x7a\x68\x6b\x78\x42\x46\x47\x57\x6b\x56\x55\x46\x33\x58\ -\x37\x56\x71\x74\x55\x65\x75\x31\x43\x37\x7a\x57\x54\x45\x31\x78\ -\x47\x41\x55\x4e\x54\x34\x4b\x4b\x71\x4b\x20\x72\x4d\x69\x49\x73\ -\x6f\x53\x2f\x75\x5a\x47\x77\x45\x49\x48\x63\x76\x67\x68\x61\x4c\ -\x57\x72\x41\x42\x36\x33\x4e\x6b\x4a\x46\x46\x59\x30\x73\x72\x50\ -\x32\x7a\x65\x69\x73\x74\x75\x49\x79\x50\x46\x53\x55\x36\x71\x47\ -\x36\x31\x47\x67\x78\x53\x6a\x38\x58\x48\x5a\x37\x54\x52\x37\x2f\ -\x51\x64\x38\x4c\x73\x6b\x79\x20\x58\x2f\x32\x30\x6e\x69\x78\x33\ -\x43\x67\x75\x65\x2f\x52\x4d\x35\x71\x53\x37\x53\x6e\x51\x37\x71\ -\x32\x74\x70\x5a\x56\x31\x6e\x46\x56\x36\x74\x4c\x6d\x48\x54\x57\ -\x57\x47\x61\x74\x2b\x49\x6e\x4c\x54\x78\x75\x4e\x78\x35\x46\x4d\ -\x52\x79\x43\x49\x51\x52\x75\x62\x38\x62\x45\x61\x6a\x64\x31\x6d\ -\x30\x53\x71\x71\x20\x69\x69\x38\x59\x34\x72\x30\x46\x33\x2f\x48\ -\x71\x72\x64\x64\x68\x4d\x35\x76\x59\x73\x47\x4d\x58\x36\x51\x34\ -\x48\x62\x38\x39\x62\x6a\x43\x68\x4c\x31\x4e\x62\x73\x70\x4b\x36\ -\x6c\x6b\x61\x44\x4e\x52\x6a\x41\x63\x52\x46\x58\x56\x61\x4b\x67\ -\x39\x6a\x68\x47\x52\x49\x39\x45\x75\x53\x6a\x4a\x62\x61\x33\x66\ -\x6a\x20\x44\x59\x57\x5a\x39\x2f\x51\x6a\x32\x43\x30\x6d\x61\x70\ -\x76\x62\x57\x4c\x32\x39\x6b\x68\x56\x62\x4b\x2f\x68\x33\x65\x52\ -\x6e\x32\x37\x5a\x74\x70\x31\x78\x70\x51\x37\x45\x6c\x67\x54\x77\ -\x4b\x54\x43\x5a\x4e\x4f\x47\x39\x4d\x32\x74\x6b\x63\x39\x73\x73\ -\x79\x55\x2b\x55\x74\x34\x5a\x63\x46\x79\x54\x72\x2f\x6b\x20\x4f\ -\x6b\x53\x4e\x68\x6f\x72\x57\x4a\x6e\x37\x63\x55\x49\x31\x76\x38\ -\x57\x72\x38\x4e\x64\x57\x63\x2f\x74\x6a\x7a\x6a\x4d\x37\x50\x35\ -\x64\x52\x42\x68\x5a\x7a\x59\x4c\x35\x39\x4d\x6c\x37\x4e\x7a\x32\ -\x33\x58\x6b\x64\x57\x6b\x31\x47\x54\x43\x71\x6f\x4e\x64\x71\x6b\ -\x56\x51\x31\x2b\x6f\x4f\x4b\x4a\x49\x6c\x51\x20\x56\x63\x36\x39\ -\x70\x77\x7a\x6e\x69\x61\x73\x75\x4a\x53\x79\x49\x57\x45\x78\x47\ -\x76\x6c\x71\x39\x6e\x71\x59\x4f\x48\x2f\x50\x58\x62\x75\x43\x36\ -\x56\x39\x37\x6b\x75\x64\x39\x65\x79\x62\x72\x4b\x4b\x73\x59\x55\ -\x44\x53\x44\x4a\x59\x6f\x6c\x47\x75\x2b\x49\x59\x79\x65\x79\x56\ -\x38\x62\x47\x5a\x54\x66\x68\x44\x20\x42\x78\x6f\x66\x58\x79\x6a\ -\x4d\x6b\x67\x32\x62\x79\x55\x39\x50\x35\x5a\x76\x6e\x48\x6f\x75\ -\x6d\x5a\x64\x75\x73\x68\x41\x57\x52\x65\x57\x73\x32\x73\x4b\x75\ -\x70\x68\x64\x4b\x71\x47\x75\x61\x73\x57\x73\x74\x31\x34\x30\x36\ -\x6a\x49\x43\x4d\x4e\x62\x57\x66\x53\x33\x4c\x46\x4b\x63\x4c\x61\ -\x61\x6a\x66\x6a\x71\x20\x57\x31\x48\x32\x57\x76\x6c\x49\x69\x6b\ -\x4b\x6f\x76\x68\x62\x2f\x72\x68\x33\x6f\x69\x34\x59\x68\x71\x47\ -\x70\x30\x70\x57\x4f\x78\x67\x6a\x73\x56\x56\x42\x57\x37\x33\x55\ -\x37\x2f\x7a\x41\x79\x2b\x33\x62\x69\x5a\x4f\x53\x76\x58\x4d\x6e\ -\x70\x41\x50\x2f\x37\x31\x39\x54\x66\x6f\x64\x62\x48\x4e\x6a\x75\ -\x34\x6b\x20\x47\x2b\x75\x72\x64\x78\x2f\x77\x2b\x61\x4b\x53\x55\ -\x6a\x37\x39\x37\x6b\x66\x65\x76\x2b\x38\x32\x72\x4b\x62\x6f\x79\ -\x34\x54\x58\x6e\x33\x6b\x36\x41\x42\x61\x6a\x67\x63\x62\x32\x44\ -\x6a\x4a\x64\x54\x67\x6f\x79\x30\x67\x68\x45\x42\x4e\x36\x65\x4e\ -\x6f\x75\x6c\x6d\x37\x63\x78\x49\x44\x50\x74\x67\x48\x73\x64\x20\ -\x44\x6c\x61\x7a\x6b\x55\x44\x34\x77\x41\x48\x7a\x31\x74\x66\x66\ -\x73\x4c\x61\x79\x69\x6e\x66\x75\x76\x71\x58\x4c\x32\x4f\x37\x4a\ -\x42\x42\x2f\x56\x50\x35\x38\x2b\x64\x7a\x36\x4f\x58\x34\x6a\x51\ -\x56\x46\x65\x44\x37\x45\x34\x6c\x55\x72\x6f\x65\x58\x42\x36\x4d\ -\x65\x6c\x31\x63\x33\x34\x67\x2b\x45\x75\x32\x76\x20\x7a\x5a\x35\ -\x4c\x56\x57\x4d\x7a\x62\x39\x77\x78\x36\x57\x66\x66\x6c\x63\x33\ -\x47\x6b\x4c\x78\x73\x4a\x70\x30\x31\x68\x70\x2f\x4b\x4b\x35\x6e\ -\x78\x36\x4c\x31\x55\x31\x6a\x65\x78\x61\x6c\x73\x46\x4b\x38\x73\ -\x72\x57\x62\x6d\x6a\x48\x4c\x74\x52\x6a\x30\x46\x2f\x35\x4d\x61\ -\x38\x4f\x7a\x30\x52\x55\x65\x54\x78\x20\x6a\x36\x59\x7a\x62\x33\ -\x73\x44\x5a\x31\x35\x38\x4c\x57\x46\x56\x78\x52\x63\x4a\x59\x55\ -\x76\x78\x34\x4c\x48\x61\x4d\x47\x62\x6c\x30\x4e\x48\x53\x79\x45\ -\x5a\x6e\x4a\x71\x75\x71\x6d\x35\x6c\x63\x57\x6f\x6b\x75\x34\x43\ -\x66\x48\x70\x43\x50\x4e\x59\x6f\x71\x70\x4c\x69\x31\x47\x49\x79\ -\x61\x4e\x42\x6f\x76\x4f\x20\x67\x4b\x67\x6f\x69\x4b\x70\x43\x4f\ -\x42\x4a\x45\x57\x31\x6e\x47\x43\x35\x64\x4e\x34\x4a\x36\x4c\x4a\ -\x2b\x77\x7a\x6b\x54\x34\x34\x38\x51\x49\x32\x56\x65\x32\x69\x66\ -\x48\x63\x39\x7a\x39\x39\x77\x46\x53\x61\x44\x6e\x6e\x55\x56\x4f\ -\x37\x47\x5a\x6a\x4d\x78\x59\x76\x68\x71\x62\x79\x59\x67\x2b\x78\ -\x73\x6c\x75\x20\x62\x33\x71\x33\x38\x72\x47\x59\x38\x4f\x31\x6e\ -\x66\x4d\x4b\x43\x79\x41\x76\x54\x35\x35\x43\x62\x36\x75\x62\x32\ -\x58\x35\x33\x56\x31\x63\x69\x44\x73\x76\x73\x41\x4d\x44\x77\x2f\ -\x6c\x38\x6c\x66\x4c\x79\x54\x4c\x34\x32\x4a\x51\x64\x68\x38\x43\ -\x45\x59\x46\x72\x58\x70\x35\x4d\x74\x73\x65\x46\x51\x61\x38\x2f\ -\x20\x5a\x69\x73\x66\x75\x38\x6c\x4d\x49\x42\x68\x45\x44\x41\x55\ -\x41\x55\x45\x57\x52\x53\x48\x6b\x5a\x35\x50\x52\x46\x47\x56\x68\ -\x4d\x70\x44\x73\x64\x47\x67\x30\x47\x76\x59\x35\x55\x52\x78\x4b\ -\x33\x6e\x33\x39\x32\x39\x4e\x30\x75\x4a\x5a\x70\x77\x57\x4a\x79\ -\x56\x45\x56\x4f\x48\x38\x43\x54\x62\x61\x66\x62\x36\x20\x75\x70\ -\x61\x31\x48\x59\x45\x67\x39\x37\x33\x7a\x45\x51\x39\x64\x64\x69\ -\x48\x2f\x66\x65\x69\x75\x62\x69\x4e\x58\x4a\x6f\x4d\x42\x52\x56\ -\x56\x4a\x73\x64\x76\x34\x7a\x64\x68\x54\x41\x63\x68\x4c\x64\x58\ -\x50\x78\x73\x33\x2f\x6a\x77\x55\x76\x4f\x4f\x32\x49\x74\x45\x4b\ -\x30\x66\x2f\x31\x34\x44\x70\x69\x4d\x51\x20\x5a\x50\x72\x53\x6c\ -\x5a\x77\x30\x6f\x4a\x41\x62\x7a\x78\x6e\x62\x62\x64\x61\x4c\x32\ -\x57\x68\x45\x56\x6d\x51\x55\x71\x77\x33\x62\x67\x43\x4c\x71\x66\ -\x52\x32\x6f\x51\x34\x5a\x44\x78\x56\x61\x75\x4f\x58\x2f\x73\x4d\ -\x58\x4d\x34\x37\x36\x2b\x39\x78\x65\x66\x6e\x62\x35\x39\x2f\x7a\ -\x65\x38\x76\x50\x43\x66\x71\x20\x6c\x2b\x70\x6d\x68\x52\x72\x39\ -\x54\x43\x55\x6a\x78\x55\x6c\x65\x57\x69\x70\x6e\x44\x69\x74\x43\ -\x56\x68\x54\x75\x6e\x2f\x49\x78\x42\x61\x6d\x75\x6d\x45\x34\x4a\ -\x36\x45\x37\x50\x54\x66\x39\x34\x6c\x79\x61\x54\x6d\x33\x45\x58\ -\x58\x45\x6c\x49\x46\x42\x43\x45\x4d\x49\x49\x73\x49\x53\x71\x64\ -\x2f\x68\x64\x5a\x20\x42\x6b\x41\x32\x47\x4d\x48\x70\x41\x71\x63\ -\x4c\x57\x56\x48\x59\x75\x62\x57\x55\x4f\x38\x61\x66\x47\x71\x4d\ -\x50\x53\x6f\x38\x5a\x63\x42\x67\x4d\x43\x49\x71\x43\x74\x37\x30\ -\x56\x77\x2b\x35\x79\x33\x72\x76\x6e\x4a\x69\x61\x63\x4f\x4c\x54\ -\x62\x2b\x74\x48\x72\x64\x47\x67\x30\x30\x44\x63\x39\x46\x59\x42\ -\x6e\x20\x72\x37\x2b\x43\x73\x43\x44\x79\x7a\x79\x38\x57\x38\x4d\ -\x68\x6c\x46\x38\x54\x6b\x6b\x44\x2f\x67\x57\x62\x33\x35\x6b\x74\ -\x31\x6b\x77\x72\x75\x58\x38\x56\x6c\x63\x55\x73\x72\x37\x33\x33\ -\x7a\x50\x35\x44\x73\x6d\x6b\x57\x79\x31\x39\x4e\x6a\x49\x69\x68\ -\x71\x4e\x37\x6c\x7a\x64\x2b\x57\x4c\x69\x66\x2b\x36\x2f\x20\x6e\ -\x5a\x72\x6d\x56\x6d\x35\x34\x39\x53\x30\x75\x48\x64\x6e\x7a\x75\ -\x30\x4c\x78\x78\x47\x6f\x32\x45\x68\x48\x43\x43\x4a\x45\x77\x68\ -\x45\x4f\x6f\x6f\x67\x68\x4a\x79\x57\x41\x77\x48\x44\x53\x66\x62\ -\x47\x39\x66\x6c\x55\x61\x6a\x59\x56\x48\x4a\x4a\x75\x70\x61\x32\ -\x6e\x6a\x35\x2b\x73\x74\x69\x30\x75\x4f\x79\x20\x32\x32\x6a\x78\ -\x52\x62\x64\x64\x74\x53\x32\x74\x4e\x48\x58\x34\x4f\x47\x74\x34\ -\x45\x59\x4f\x79\x4d\x33\x73\x4d\x6d\x5a\x76\x32\x53\x34\x53\x55\ -\x46\x59\x56\x6e\x70\x73\x33\x69\x38\x6c\x4e\x4f\x70\x48\x43\x2f\ -\x63\x4f\x6a\x68\x45\x70\x32\x74\x6f\x32\x33\x72\x44\x51\x5a\x35\ -\x66\x2b\x46\x33\x4a\x4e\x73\x73\x20\x6e\x4e\x41\x76\x37\x36\x41\ -\x64\x58\x31\x45\x55\x76\x4a\x30\x4f\x66\x45\x45\x53\x6f\x61\x4f\ -\x4e\x73\x39\x4e\x64\x54\x44\x71\x7a\x2b\x32\x7a\x6f\x6f\x38\x48\ -\x65\x32\x70\x73\x37\x66\x48\x79\x33\x71\x59\x7a\x69\x76\x47\x77\ -\x79\x55\x70\x77\x48\x31\x36\x36\x79\x54\x37\x52\x31\x30\x66\x70\ -\x53\x4b\x6e\x59\x33\x20\x38\x50\x53\x56\x46\x38\x56\x4e\x7a\x35\ -\x5a\x64\x75\x37\x6e\x70\x6a\x66\x63\x77\x35\x68\x55\x7a\x61\x50\ -\x41\x77\x66\x4a\x48\x77\x58\x75\x2b\x58\x43\x59\x52\x46\x67\x62\ -\x41\x6b\x45\x70\x59\x6b\x46\x46\x56\x46\x55\x65\x53\x66\x62\x39\ -\x54\x63\x79\x42\x6c\x70\x44\x6e\x35\x33\x33\x72\x69\x59\x39\x4a\ -\x6a\x31\x20\x42\x6b\x77\x61\x53\x44\x45\x5a\x71\x61\x76\x62\x68\ -\x61\x75\x39\x6a\x6b\x2b\x66\x75\x49\x38\x68\x75\x64\x6b\x39\x48\ -\x6f\x75\x68\x31\x2b\x6d\x51\x35\x48\x30\x6e\x35\x4c\x66\x6d\x4c\ -\x71\x4a\x76\x71\x6f\x76\x78\x51\x77\x62\x47\x70\x47\x64\x2f\x65\ -\x6d\x56\x57\x37\x57\x59\x7a\x2f\x6e\x41\x59\x53\x5a\x61\x5a\x20\ -\x76\x57\x49\x4e\x4b\x76\x44\x69\x70\x4b\x74\x78\x32\x4b\x77\x48\ -\x50\x64\x74\x44\x56\x64\x53\x75\x4b\x41\x6c\x45\x4f\x2b\x7a\x39\ -\x55\x7a\x37\x6d\x7a\x67\x6e\x6a\x4b\x4d\x37\x4e\x36\x72\x46\x63\ -\x50\x4c\x47\x62\x54\x43\x44\x4c\x71\x4d\x45\x41\x36\x72\x62\x4e\ -\x30\x59\x68\x48\x57\x73\x59\x68\x73\x38\x6d\x55\x20\x76\x62\x53\ -\x33\x65\x48\x30\x38\x4e\x32\x30\x57\x7a\x31\x31\x7a\x61\x63\x78\ -\x48\x56\x31\x68\x4e\x4a\x67\x4c\x68\x61\x43\x37\x46\x74\x61\x2b\ -\x38\x53\x55\x51\x55\x75\x65\x47\x73\x4d\x51\x65\x39\x72\x39\x6c\ -\x67\x32\x4d\x66\x68\x2f\x4f\x57\x71\x64\x56\x51\x33\x4e\x48\x4c\ -\x54\x6d\x57\x66\x45\x70\x41\x58\x32\x20\x2b\x50\x4d\x69\x4c\x43\ -\x34\x70\x35\x64\x71\x58\x33\x2b\x54\x57\x43\x65\x4f\x35\x2b\x5a\ -\x78\x78\x68\x35\x78\x78\x5a\x55\x57\x68\x49\x78\x54\x43\x48\x77\ -\x6d\x6a\x69\x69\x4b\x65\x70\x6a\x70\x65\x2f\x75\x31\x6c\x63\x54\ -\x33\x61\x34\x31\x44\x73\x30\x62\x36\x2b\x73\x6f\x6f\x72\x58\x76\ -\x77\x48\x70\x77\x37\x75\x20\x7a\x37\x58\x6a\x54\x6a\x75\x6b\x64\ -\x76\x55\x6f\x74\x65\x30\x65\x50\x64\x2b\x58\x62\x75\x47\x53\x6c\ -\x79\x61\x6a\x4c\x54\x77\x42\x64\x33\x35\x2f\x32\x6b\x50\x42\x36\ -\x50\x74\x6c\x34\x53\x44\x65\x63\x42\x68\x66\x4a\x49\x79\x2f\x36\ -\x2f\x32\x79\x43\x4b\x72\x4b\x7a\x2b\x4d\x6b\x45\x73\x62\x52\x57\ -\x4d\x76\x66\x20\x4a\x6c\x30\x64\x65\x31\x38\x7a\x47\x39\x47\x71\ -\x45\x72\x36\x36\x4b\x76\x49\x31\x41\x65\x59\x39\x2b\x51\x44\x46\ -\x65\x54\x6b\x48\x48\x62\x4e\x36\x72\x62\x5a\x72\x4e\x51\x5a\x51\ -\x73\x71\x4f\x61\x6d\x63\x74\x58\x38\x64\x68\x6c\x46\x38\x61\x6b\ -\x70\x54\x74\x36\x5a\x33\x79\x73\x5a\x6c\x70\x39\x66\x6a\x35\x65\ -\x20\x73\x6f\x78\x6c\x5a\x64\x73\x34\x6f\x32\x67\x41\x32\x5a\x35\ -\x44\x48\x34\x65\x68\x71\x45\x72\x58\x43\x69\x49\x69\x69\x74\x7a\ -\x37\x39\x6b\x65\x4d\x48\x56\x54\x49\x78\x4a\x4e\x50\x6a\x45\x6e\ -\x30\x34\x57\x41\x7a\x6d\x36\x47\x78\x48\x6f\x51\x49\x44\x42\x6b\ -\x65\x39\x65\x76\x30\x41\x6b\x56\x56\x4f\x33\x4d\x69\x20\x56\x42\ -\x37\x2f\x61\x44\x71\x2f\x4f\x58\x31\x30\x7a\x4b\x73\x4d\x41\x4a\ -\x4e\x42\x54\x32\x31\x4c\x57\x7a\x51\x76\x36\x72\x45\x2f\x63\x4e\ -\x4b\x41\x37\x74\x2b\x4a\x32\x37\x66\x4d\x7a\x79\x75\x66\x75\x74\ -\x5a\x32\x6e\x70\x33\x36\x4f\x53\x39\x63\x66\x30\x56\x4d\x2f\x6f\ -\x6b\x39\x32\x4d\x78\x6d\x46\x71\x7a\x62\x20\x69\x44\x76\x5a\x7a\ -\x6a\x76\x33\x33\x49\x4c\x64\x62\x4f\x37\x56\x59\x56\x47\x4b\x49\ -\x74\x4d\x52\x44\x69\x49\x71\x4d\x72\x72\x71\x53\x70\x36\x2b\x35\ -\x4e\x79\x34\x31\x4d\x2f\x68\x59\x44\x4f\x62\x6d\x62\x75\x6d\x42\ -\x46\x6c\x52\x2b\x4f\x69\x42\x4f\x38\x6c\x4d\x63\x66\x61\x71\x33\ -\x4a\x35\x2b\x47\x65\x2b\x32\x20\x74\x5a\x6e\x4e\x7a\x46\x72\x78\ -\x45\x78\x50\x2f\x2f\x6a\x37\x32\x45\x30\x35\x48\x6c\x2b\x4b\x6d\ -\x4a\x65\x43\x6e\x4a\x65\x69\x6e\x4a\x52\x69\x67\x4c\x52\x6a\x6f\ -\x66\x4d\x45\x31\x69\x43\x38\x63\x4e\x64\x79\x42\x53\x49\x53\x75\ -\x73\x4b\x71\x71\x6f\x71\x6e\x63\x78\x70\x4f\x58\x54\x6d\x42\x77\ -\x39\x75\x47\x64\x20\x6d\x64\x4d\x64\x79\x56\x59\x4c\x35\x64\x75\ -\x33\x63\x4b\x4c\x48\x7a\x4f\x65\x50\x33\x6b\x64\x57\x4c\x38\x34\ -\x46\x30\x75\x74\x30\x58\x65\x48\x33\x73\x43\x42\x77\x37\x7a\x73\ -\x66\x38\x76\x54\x56\x6c\x2b\x4b\x77\x78\x66\x39\x30\x7a\x31\x34\ -\x5a\x6e\x32\x53\x7a\x6d\x59\x2b\x58\x4c\x4b\x4e\x66\x5a\x68\x71\ -\x50\x20\x58\x6e\x6b\x4a\x78\x6c\x37\x6d\x6c\x69\x69\x64\x6a\x6c\ -\x78\x46\x55\x58\x6a\x36\x30\x38\x39\x4a\x74\x68\x68\x6a\x58\x6b\ -\x6f\x65\x4c\x72\x6d\x70\x4c\x72\x4c\x4e\x42\x6e\x54\x4e\x6a\x64\ -\x44\x52\x44\x6f\x4c\x51\x62\x55\x37\x46\x2f\x71\x69\x64\x32\x75\ -\x65\x75\x4b\x61\x47\x68\x72\x59\x32\x72\x7a\x78\x67\x64\x20\x46\ -\x7a\x31\x4a\x5a\x6a\x4e\x6e\x44\x4f\x72\x50\x79\x7a\x4f\x2f\x34\ -\x74\x6d\x70\x73\x35\x69\x33\x5a\x67\x50\x4e\x48\x62\x36\x44\x35\ -\x6a\x32\x5a\x6a\x64\x48\x6b\x74\x59\x67\x6f\x63\x76\x2b\x55\x6a\ -\x33\x6e\x67\x34\x6e\x50\x4a\x63\x76\x56\x75\x6f\x42\x32\x4b\x33\ -\x46\x51\x58\x32\x32\x76\x72\x65\x47\x76\x75\x20\x59\x74\x5a\x58\ -\x56\x74\x48\x6b\x39\x66\x55\x71\x41\x56\x52\x56\x56\x63\x4b\x69\ -\x41\x4b\x33\x4e\x58\x4a\x44\x6c\x69\x56\x76\x39\x48\x41\x35\x37\ -\x74\x4c\x2f\x2b\x35\x51\x49\x32\x56\x75\x33\x71\x74\x58\x62\x6c\ -\x4b\x4c\x56\x74\x54\x6d\x6f\x4b\x32\x32\x72\x72\x55\x45\x77\x57\ -\x57\x6c\x75\x61\x61\x47\x35\x76\x20\x6f\x54\x58\x6f\x70\x7a\x58\ -\x6f\x70\x79\x33\x6f\x70\x79\x30\x55\x6f\x4c\x30\x7a\x35\x38\x7a\ -\x62\x61\x58\x78\x45\x57\x61\x4a\x72\x2f\x39\x2f\x55\x77\x4e\x6c\ -\x5a\x71\x66\x78\x32\x33\x43\x6b\x48\x66\x55\x35\x76\x4f\x57\x31\ -\x67\x49\x56\x65\x63\x63\x69\x4b\x62\x71\x71\x71\x35\x39\x35\x30\ -\x50\x6d\x62\x35\x30\x20\x4a\x58\x57\x74\x37\x51\x64\x73\x71\x2f\ -\x5a\x47\x72\x34\x75\x75\x66\x42\x52\x46\x34\x66\x6e\x70\x63\x78\ -\x68\x58\x31\x4a\x39\x52\x68\x58\x33\x6a\x6f\x75\x65\x41\x5a\x2f\ -\x58\x6d\x53\x30\x55\x35\x66\x58\x6a\x32\x6d\x6f\x6e\x38\x66\x64\ -\x62\x58\x31\x4c\x56\x37\x79\x55\x39\x50\x34\x39\x77\x52\x78\x5a\ -\x77\x35\x20\x72\x49\x6a\x63\x56\x48\x65\x50\x4d\x2b\x57\x65\x51\ -\x37\x6a\x65\x58\x66\x41\x74\x32\x32\x76\x72\x6d\x48\x7a\x62\x74\ -\x63\x66\x4d\x47\x62\x6d\x48\x34\x74\x77\x73\x56\x72\x7a\x34\x4f\ -\x47\x73\x71\x64\x72\x4b\x67\x70\x4a\x51\x46\x6d\x37\x65\x7a\x50\ -\x52\x42\x42\x54\x58\x46\x42\x69\x67\x65\x4d\x78\x6d\x36\x33\x20\ -\x59\x49\x71\x71\x30\x74\x6a\x68\x35\x53\x2f\x2f\x6e\x63\x6d\x48\ -\x39\x39\x37\x53\x61\x34\x4e\x37\x4b\x49\x77\x47\x50\x53\x39\x50\ -\x75\x70\x4b\x4f\x59\x49\x69\x31\x46\x54\x75\x5a\x75\x33\x6f\x4e\ -\x4c\x30\x79\x66\x6a\x54\x73\x35\x69\x51\x6b\x6e\x44\x75\x4f\x69\ -\x30\x53\x65\x51\x35\x55\x37\x5a\x70\x30\x35\x4e\x20\x6e\x65\x38\ -\x6b\x66\x62\x42\x6f\x4b\x52\x61\x44\x6a\x6f\x74\x48\x39\x33\x77\ -\x65\x7a\x4f\x46\x53\x6e\x4a\x76\x46\x30\x75\x63\x66\x5a\x55\x33\ -\x46\x54\x72\x35\x65\x74\x59\x62\x6e\x50\x35\x74\x44\x75\x74\x50\ -\x42\x2b\x53\x4f\x48\x63\x66\x36\x6f\x45\x66\x52\x78\x64\x65\x2b\ -\x34\x52\x56\x56\x42\x69\x4a\x44\x53\x20\x55\x4d\x76\x2f\x50\x58\ -\x56\x2f\x33\x4f\x72\x6e\x63\x4c\x58\x2f\x32\x4e\x6d\x32\x68\x36\ -\x4e\x64\x56\x56\x55\x61\x32\x6a\x76\x69\x33\x72\x5a\x44\x63\x37\ -\x4e\x5a\x39\x74\x66\x48\x57\x4c\x6d\x39\x6b\x76\x6e\x72\x4e\x72\ -\x46\x77\x32\x54\x6f\x43\x52\x67\x74\x47\x54\x7a\x6f\x36\x64\x79\ -\x71\x4b\x30\x59\x41\x67\x20\x79\x55\x52\x6b\x45\x55\x6d\x57\x39\ -\x30\x30\x6a\x69\x34\x53\x78\x31\x65\x33\x69\x74\x57\x63\x65\x78\ -\x47\x77\x30\x78\x6b\x56\x50\x5a\x6f\x71\x44\x4b\x58\x66\x64\x69\ -\x43\x38\x55\x5a\x74\x32\x4f\x61\x68\x5a\x76\x4b\x4f\x4f\x31\x32\ -\x56\x2b\x54\x62\x4c\x56\x78\x7a\x6f\x68\x69\x4c\x6a\x6e\x70\x42\ -\x50\x72\x33\x20\x79\x64\x69\x6e\x6a\x6e\x52\x61\x48\x62\x4b\x69\ -\x73\x4c\x79\x73\x6e\x4f\x38\x32\x6c\x6a\x48\x7a\x6a\x33\x63\x64\ -\x6c\x57\x4f\x44\x34\x51\x69\x4f\x55\x5a\x56\x6c\x68\x55\x32\x37\ -\x61\x6c\x6d\x38\x73\x59\x79\x6c\x5a\x64\x73\x4a\x69\x53\x49\x6a\ -\x43\x76\x49\x59\x58\x7a\x79\x59\x6b\x59\x58\x35\x35\x4b\x58\x39\ -\x20\x66\x48\x35\x4a\x30\x56\x31\x2f\x35\x4d\x47\x4a\x46\x7a\x44\ -\x31\x32\x2b\x58\x38\x39\x2f\x37\x62\x59\x71\x37\x55\x65\x42\x32\ -\x31\x75\x57\x31\x33\x50\x66\x50\x58\x6c\x66\x4c\x4e\x68\x73\x32\ -\x73\x61\x57\x7a\x44\x61\x37\x5a\x43\x69\x68\x76\x73\x39\x6d\x67\ -\x61\x50\x75\x41\x71\x58\x63\x63\x5a\x2f\x66\x4f\x35\x20\x5a\x47\ -\x51\x78\x56\x35\x31\x2b\x55\x6b\x7a\x50\x36\x77\x30\x56\x39\x59\ -\x30\x73\x58\x46\x2f\x4b\x67\x67\x31\x6c\x4b\x4b\x72\x4b\x4b\x51\ -\x4d\x4c\x2b\x64\x58\x49\x34\x59\x77\x6f\x79\x45\x57\x44\x68\x67\ -\x47\x33\x50\x30\x52\x2b\x75\x70\x75\x70\x44\x39\x77\x52\x31\x30\ -\x50\x35\x75\x32\x4e\x50\x2f\x53\x7a\x61\x20\x57\x49\x5a\x47\x71\ -\x32\x58\x4d\x6b\x49\x47\x63\x64\x38\x4a\x51\x52\x68\x54\x6b\x59\ -\x65\x6c\x73\x51\x39\x4d\x31\x64\x36\x42\x61\x37\x66\x7a\x72\x69\ -\x67\x6c\x78\x71\x5a\x39\x34\x74\x2b\x33\x42\x74\x41\x2b\x38\x34\ -\x79\x47\x47\x35\x2b\x63\x78\x59\x64\x69\x67\x6f\x39\x36\x32\x4b\ -\x37\x5a\x57\x73\x4c\x42\x6b\x20\x4d\x30\x73\x32\x62\x57\x46\x6a\ -\x71\x35\x64\x49\x6b\x69\x4d\x61\x31\x62\x49\x6e\x52\x64\x2b\x6d\ -\x56\x32\x54\x59\x73\x42\x61\x64\x32\x63\x79\x72\x6c\x35\x7a\x4e\ -\x54\x57\x66\x46\x37\x73\x63\x37\x46\x4e\x56\x4e\x4c\x53\x77\x6f\ -\x4b\x57\x58\x2b\x2b\x6c\x4a\x38\x6f\x51\x69\x6a\x2b\x75\x64\x7a\ -\x77\x61\x67\x52\x20\x6a\x43\x72\x4d\x52\x36\x76\x56\x4d\x75\x61\ -\x52\x5a\x33\x48\x61\x72\x4c\x77\x36\x36\x61\x72\x44\x50\x6a\x4b\ -\x31\x4f\x33\x70\x71\x32\x79\x4d\x2b\x77\x78\x6d\x69\x44\x75\x51\ -\x32\x66\x35\x42\x4e\x75\x32\x72\x35\x66\x6e\x4d\x35\x4a\x54\x74\ -\x33\x67\x55\x62\x44\x71\x50\x37\x35\x6a\x42\x39\x61\x78\x42\x55\ -\x76\x20\x2f\x49\x4f\x69\x37\x45\x77\x2b\x75\x4f\x64\x57\x4d\x6c\ -\x32\x4f\x6f\x2f\x5a\x48\x48\x43\x6d\x79\x72\x46\x44\x66\x34\x65\ -\x58\x48\x4c\x65\x58\x4d\x4b\x79\x6c\x6a\x61\x57\x55\x56\x6a\x52\ -\x6f\x44\x6b\x69\x4d\x46\x54\x66\x6b\x57\x4c\x68\x38\x31\x6c\x48\ -\x66\x75\x6e\x48\x52\x4d\x6e\x61\x69\x4b\x6f\x74\x44\x6b\x20\x39\ -\x62\x47\x36\x66\x43\x63\x4c\x4e\x32\x36\x6d\x6f\x72\x36\x4a\x76\ -\x75\x6d\x70\x54\x50\x31\x2b\x42\x54\x4d\x66\x2b\x54\x31\x6a\x69\ -\x77\x59\x63\x4d\x79\x31\x37\x31\x38\x2b\x69\x54\x56\x75\x70\x62\ -\x6d\x35\x68\x61\x46\x34\x75\x45\x30\x34\x63\x78\x70\x55\x76\x76\ -\x63\x37\x46\x49\x34\x66\x78\x37\x6c\x33\x78\x20\x71\x5a\x2b\x6a\ -\x32\x62\x62\x37\x61\x2f\x2f\x4e\x2f\x37\x33\x42\x68\x53\x4f\x48\ -\x38\x63\x36\x64\x4e\x78\x79\x7a\x74\x68\x55\x6c\x6d\x5a\x71\x57\ -\x56\x72\x37\x5a\x73\x4a\x6e\x35\x4a\x57\x57\x73\x72\x61\x6d\x6e\ -\x56\x57\x64\x41\x63\x61\x54\x41\x39\x69\x33\x38\x61\x76\x67\x51\ -\x50\x72\x6e\x76\x6c\x70\x68\x66\x20\x6c\x7a\x6b\x63\x46\x45\x57\ -\x68\x78\x52\x64\x67\x62\x65\x56\x4f\x35\x71\x2f\x66\x54\x46\x6c\ -\x74\x48\x65\x6c\x4f\x4a\x37\x4e\x57\x2f\x4d\x52\x4c\x4e\x31\x7a\ -\x42\x37\x65\x65\x4e\x6a\x38\x74\x7a\x6a\x6f\x72\x78\x36\x59\x36\ -\x61\x35\x6c\x62\x57\x37\x61\x6a\x6d\x2b\x38\x33\x6c\x37\x47\x68\ -\x73\x34\x72\x6c\x72\x20\x4a\x75\x35\x7a\x4a\x45\x55\x73\x48\x49\ -\x33\x2f\x58\x6d\x56\x76\x66\x4b\x45\x77\x61\x79\x75\x72\x57\x4c\ -\x53\x78\x6a\x4b\x32\x31\x64\x62\x77\x79\x36\x57\x70\x79\x65\x75\ -\x46\x59\x50\x35\x71\x45\x49\x69\x4b\x6c\x75\x32\x72\x77\x68\x73\ -\x4b\x4d\x48\x7a\x4c\x77\x6d\x4a\x34\x53\x75\x44\x39\x48\x73\x33\ -\x35\x2b\x20\x61\x57\x33\x62\x31\x4f\x48\x6a\x70\x2b\x30\x37\x57\ -\x56\x43\x79\x69\x62\x4c\x61\x4f\x74\x36\x38\x37\x58\x6f\x4b\x4d\ -\x6d\x4a\x4c\x47\x49\x32\x56\x69\x43\x69\x79\x65\x64\x64\x75\x56\ -\x70\x58\x76\x59\x4e\x4b\x5a\x70\x32\x4f\x4f\x30\x35\x47\x70\x78\ -\x38\x7a\x34\x4a\x45\x69\x51\x49\x45\x46\x76\x4f\x48\x37\x54\x20\ -\x61\x49\x49\x45\x43\x58\x37\x52\x4a\x49\x78\x50\x67\x67\x51\x4a\ -\x6a\x67\x73\x4a\x34\x35\x4d\x67\x51\x59\x4c\x6a\x51\x73\x4c\x34\ -\x4a\x45\x69\x51\x34\x4c\x69\x51\x4d\x44\x34\x4a\x45\x69\x51\x34\ -\x4c\x69\x53\x4d\x54\x34\x49\x45\x43\x59\x34\x4c\x43\x65\x4f\x54\ -\x49\x45\x47\x43\x34\x30\x4c\x43\x2b\x43\x52\x49\x20\x6b\x4f\x43\ -\x34\x6b\x44\x41\x2b\x43\x52\x49\x6b\x4f\x43\x34\x6b\x6a\x45\x2b\ -\x43\x42\x41\x6d\x4f\x43\x2f\x38\x50\x32\x32\x63\x47\x79\x2b\x42\ -\x2f\x69\x58\x30\x41\x41\x41\x41\x41\x53\x55\x56\x4f\x52\x4b\x35\ -\x43\x59\x49\x49\x3d\x20\x22\x20\x68\x65\x69\x67\x68\x74\x3d\x22\ -\x34\x31\x22\x20\x77\x69\x64\x74\x68\x3d\x22\x32\x38\x37\x22\x20\ -\x79\x3d\x22\x2d\x36\x35\x35\x2e\x33\x37\x22\x20\x78\x3d\x22\x31\ -\x32\x39\x39\x2e\x37\x22\x20\x70\x72\x65\x73\x65\x72\x76\x65\x41\ -\x73\x70\x65\x63\x74\x52\x61\x74\x69\x6f\x3d\x22\x6e\x6f\x6e\x65\ -\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x3d\ -\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x67\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x33\x33\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\ -\x2d\x35\x39\x31\x2e\x38\x33\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x34\x37\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x35\x36\x36\x2e\x35\x39\ -\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x20\x32\x35\ -\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\ -\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\ -\x68\x34\x33\x34\x39\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\ -\x32\x2d\x35\x39\x31\x2e\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\ -\x38\x2e\x34\x35\x33\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x33\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x35\x38\x2e\ -\x31\x34\x76\x33\x32\x6c\x2d\x33\x31\x2e\x35\x34\x37\x2d\x38\x2e\ -\x34\x35\x33\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x37\x34\x2e\x35\x2d\x35\x32\ -\x36\x2e\x31\x34\x20\x32\x35\x2e\x32\x33\x38\x2d\x32\x35\x2e\x32\ -\x33\x38\x76\x2d\x33\x32\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x37\ -\x22\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x39\x31\ -\x2e\x38\x33\x76\x33\x32\x6c\x2d\x32\x35\x2e\x32\x33\x38\x20\x32\ -\x35\x2e\x32\x33\x38\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x35\x39\x22\ -\x20\x64\x3d\x22\x6d\x31\x32\x36\x38\x2e\x32\x2d\x35\x35\x39\x2e\ -\x38\x33\x20\x33\x31\x2e\x35\x34\x37\x20\x38\x2e\x34\x35\x33\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x36\x31\x22\x20\x64\x3d\x22\x6d\x31\ -\x32\x33\x36\x2e\x36\x2d\x36\x35\x36\x2e\x32\x38\x2d\x31\x32\x2e\ -\x36\x31\x39\x20\x31\x32\x2e\x36\x31\x39\x76\x31\x36\x6c\x31\x38\ -\x2e\x39\x32\x38\x20\x35\x2e\x30\x37\x31\x38\x76\x2d\x31\x36\x6c\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x33\x36\x33\x22\x20\x64\x3d\x22\x6d\x31\x32\ -\x34\x33\x2d\x36\x32\x32\x2e\x35\x39\x20\x31\x32\x2e\x36\x31\x39\ -\x2d\x31\x32\x2e\x36\x31\x39\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\ -\x35\x22\x20\x64\x3d\x22\x6d\x31\x32\x34\x33\x2d\x36\x33\x38\x2e\ -\x35\x39\x20\x31\x32\x2e\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\ -\x76\x31\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x37\x22\x20\x64\ -\x3d\x22\x6d\x31\x32\x35\x35\x2e\x36\x2d\x36\x35\x31\x2e\x32\x31\ -\x2d\x31\x38\x2e\x39\x32\x38\x2d\x35\x2e\x30\x37\x31\x38\x76\x31\ -\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x36\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x32\x32\x34\x2d\x36\x32\x37\x2e\x36\x36\x20\x31\x32\x2e\ -\x36\x31\x39\x2d\x31\x32\x2e\x36\x31\x39\x20\x31\x38\x2e\x39\x32\ -\x38\x20\x35\x2e\x30\x37\x31\x38\x22\x2f\x3e\x0a\x20\x20\x20\x3c\ -\x2f\x67\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x31\ -\x22\x20\x64\x3d\x22\x6d\x31\x33\x33\x38\x2e\x31\x2d\x35\x35\x39\ -\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\ -\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\ -\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x33\ -\x37\x33\x22\x20\x64\x3d\x22\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\ -\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\ -\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\ -\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x33\x37\x37\x22\x20\x64\x3d\x22\x6d\x31\ -\x33\x35\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\ -\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x33\x37\x39\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x35\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\ -\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\ -\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x31\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\ -\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\x22\ -\x6d\x31\x33\x36\x36\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x20\x66\x69\x6c\x6c\x2d\x72\x75\x6c\x65\x3d\x22\ -\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\x69\x6c\x6c\x2d\x6f\x70\ -\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\x37\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\ -\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\ -\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\ -\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\ -\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\ -\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x31\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x32\x30\x22\x20\x64\x3d\x22\x6d\x31\x33\x38\x36\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x32\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x37\x39\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x32\x36\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x32\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x32\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\ -\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\ -\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x20\x66\x69\x6c\x6c\x2d\ -\x72\x75\x6c\x65\x3d\x22\x65\x76\x65\x6e\x6f\x64\x64\x22\x20\x66\ -\x69\x6c\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\ -\x36\x36\x37\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\ -\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\ -\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\x66\x69\x6c\ -\x6c\x3d\x22\x23\x30\x30\x66\x22\x2f\x3e\x0a\x20\x20\x3c\x67\x20\ -\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\ -\x23\x30\x30\x30\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\x31\x70\x78\x22\x20\ -\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\x3e\x0a\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x34\x34\x34\x2d\x35\x36\x33\ -\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\ -\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\ -\x34\x33\x34\x22\x20\x64\x3d\x22\x6d\x31\x34\x33\x37\x2e\x37\x2d\ -\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\ -\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x33\x38\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x38\x30\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\ -\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\ -\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\ -\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\ -\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x30\x22\x20\ -\x64\x3d\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x35\x36\x2e\x34\ -\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\ -\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\ -\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x34\x34\x34\x22\x20\x64\x3d\x22\x6d\x31\x35\x30\x30\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x30\x22\x20\x66\x69\x6c\ -\x6c\x2d\x6f\x70\x61\x63\x69\x74\x79\x3d\x22\x2e\x36\x36\x36\x36\ -\x37\x22\x20\x66\x69\x6c\x6c\x3d\x22\x23\x30\x30\x66\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x39\x34\x2e\x32\x2d\x35\x35\x30\x2e\x34\x36\ -\x20\x30\x2e\x30\x30\x31\x2d\x35\x2e\x38\x36\x36\x36\x20\x32\x2e\ -\x36\x35\x32\x31\x2d\x32\x2e\x39\x37\x30\x35\x63\x31\x2e\x34\x35\ -\x38\x37\x2d\x31\x2e\x36\x33\x33\x38\x20\x32\x2e\x36\x37\x38\x37\ -\x2d\x32\x2e\x39\x39\x38\x31\x20\x32\x2e\x37\x31\x31\x32\x2d\x33\ -\x2e\x30\x33\x31\x39\x20\x30\x2e\x30\x33\x35\x2d\x30\x2e\x30\x33\ -\x36\x38\x20\x30\x2e\x30\x35\x39\x20\x32\x2e\x31\x37\x30\x39\x20\ -\x30\x2e\x30\x35\x39\x20\x35\x2e\x35\x38\x35\x39\x76\x35\x2e\x36\ -\x34\x37\x32\x6c\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\ -\x31\x34\x2d\x32\x2e\x37\x31\x31\x31\x20\x33\x2e\x32\x35\x31\x34\ -\x76\x2d\x35\x2e\x38\x36\x36\x38\x7a\x22\x2f\x3e\x0a\x20\x20\x3c\ -\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x77\x69\x64\x74\x68\x3d\x22\ -\x31\x70\x78\x22\x20\x66\x69\x6c\x6c\x3d\x22\x6e\x6f\x6e\x65\x22\ -\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\ -\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\ -\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x34\x36\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x39\x33\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\ -\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\ -\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\ -\x61\x74\x68\x34\x34\x38\x32\x22\x20\x64\x3d\x22\x6d\x31\x33\x39\ -\x34\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\x33\x2e\x36\x33\ -\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\x38\x37\x39\x6c\ -\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\x38\x31\x7a\x22\ -\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\ -\x22\x70\x61\x74\x68\x34\x34\x38\x34\x22\x20\x64\x3d\x22\x6d\x31\ -\x34\x30\x37\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\x20\x36\x2e\x33\ -\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\x31\x2e\x31\x31\ -\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\x38\x36\x33\x20\ -\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\x38\x38\ -\x22\x20\x64\x3d\x22\x6d\x31\x34\x31\x34\x2d\x35\x36\x33\x2e\x35\ -\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\x20\x20\x20\x20\ -\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x34\ -\x39\x30\x22\x20\x64\x3d\x22\x6d\x31\x34\x30\x37\x2e\x37\x2d\x35\ -\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x35\ -\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\x67\x3e\x0a\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x30\x38\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\ -\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x30\x2e\x39\x2d\x35\x36\x36\x2e\x33\x33\x20\ -\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\x34\x2d\x39\x2e\ -\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\ -\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\ -\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x30\x22\x20\x64\x3d\ -\x22\x6d\x31\x34\x36\x31\x2e\x32\x2d\x35\x35\x33\x2e\x39\x35\x20\ -\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\x22\x20\x73\x74\ -\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\x22\x2f\x3e\ -\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\ -\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\x22\x20\x73\ -\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\x20\x73\x74\x72\ -\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\x22\x72\x6f\x75\ -\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\ -\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x32\x22\x20\x64\x3d\x22\ -\x6d\x31\x34\x35\x32\x2e\x31\x2d\x35\x35\x39\x2e\x32\x36\x20\x31\ -\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\x76\x31\x32\x2e\ -\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\x33\x2e\x37\x38\ -\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\ -\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x31\x34\x22\x20\x64\ -\x3d\x22\x6d\x31\x34\x36\x35\x2e\x37\x2d\x35\x35\x36\x2e\x34\x38\ -\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\x31\x31\x2d\x31\ -\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\x2d\x38\x2e\x35\ -\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\x3e\x0a\x20\x20\ -\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\ -\x34\x35\x31\x36\x22\x20\x64\x3d\x22\x6d\x31\x34\x37\x32\x2d\x35\ -\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\x22\x2f\x3e\x0a\ -\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\ -\x74\x68\x34\x35\x31\x38\x22\x20\x64\x3d\x22\x6d\x31\x34\x36\x35\ -\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\x33\x31\x33\x34\ -\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x2f\ -\x67\x3e\x0a\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x32\x34\x22\x20\x73\x74\x72\x6f\x6b\x65\ -\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\x64\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x36\x2e\x39\x2d\x35\x36\x36\ -\x2e\x33\x33\x20\x30\x2e\x32\x35\x32\x35\x20\x31\x32\x2e\x33\x37\ -\x34\x2d\x39\x2e\x30\x39\x31\x34\x20\x36\x2e\x38\x31\x38\x35\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\x30\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\ -\x3d\x22\x72\x6f\x75\x6e\x64\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x70\ -\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x36\ -\x22\x20\x64\x3d\x22\x6d\x31\x35\x31\x37\x2e\x32\x2d\x35\x35\x33\ -\x2e\x39\x35\x20\x31\x31\x2e\x31\x31\x32\x20\x33\x2e\x32\x38\x33\ -\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x35\x30\x35\x30\x35\ -\x30\x22\x2f\x3e\x0a\x20\x20\x20\x3c\x67\x20\x73\x74\x72\x6f\x6b\ -\x65\x2d\x6c\x69\x6e\x65\x6a\x6f\x69\x6e\x3d\x22\x72\x6f\x75\x6e\ -\x64\x22\x20\x73\x74\x72\x6f\x6b\x65\x3d\x22\x23\x30\x30\x30\x22\ -\x20\x73\x74\x72\x6f\x6b\x65\x2d\x6c\x69\x6e\x65\x63\x61\x70\x3d\ -\x22\x72\x6f\x75\x6e\x64\x22\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\ -\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x32\x38\x22\ -\x20\x64\x3d\x22\x6d\x31\x35\x30\x38\x2e\x31\x2d\x35\x35\x39\x2e\ -\x32\x36\x20\x31\x33\x2e\x36\x33\x37\x20\x33\x2e\x30\x33\x30\x34\ -\x76\x31\x32\x2e\x38\x37\x39\x6c\x2d\x31\x33\x2e\x36\x33\x37\x2d\ -\x33\x2e\x37\x38\x38\x31\x7a\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\ -\x70\x61\x74\x68\x20\x69\x64\x3d\x22\x70\x61\x74\x68\x34\x35\x33\ -\x30\x22\x20\x64\x3d\x22\x6d\x31\x35\x32\x31\x2e\x37\x2d\x35\x35\ -\x36\x2e\x34\x38\x20\x36\x2e\x33\x31\x33\x34\x2d\x37\x2e\x30\x37\ -\x31\x31\x2d\x31\x31\x2e\x31\x31\x32\x2d\x32\x2e\x37\x37\x37\x39\ -\x2d\x38\x2e\x35\x38\x36\x33\x20\x36\x2e\x38\x31\x38\x36\x22\x2f\ -\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\x3d\x22\ -\x70\x61\x74\x68\x34\x35\x33\x32\x22\x20\x64\x3d\x22\x6d\x31\x35\ -\x32\x38\x2d\x35\x36\x33\x2e\x35\x35\x76\x31\x32\x2e\x36\x32\x37\ -\x22\x2f\x3e\x0a\x20\x20\x20\x20\x3c\x70\x61\x74\x68\x20\x69\x64\ -\x3d\x22\x70\x61\x74\x68\x34\x35\x33\x34\x22\x20\x64\x3d\x22\x6d\ -\x31\x35\x32\x31\x2e\x37\x2d\x35\x34\x33\x2e\x33\x35\x20\x36\x2e\ -\x33\x31\x33\x34\x2d\x37\x2e\x35\x37\x36\x32\x22\x2f\x3e\x0a\x20\ -\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x20\x3c\x2f\x67\x3e\x0a\x20\x3c\ -\x2f\x67\x3e\x0a\x3c\x2f\x73\x76\x67\x3e\x0a\ -" - -qt_resource_name = b"\ -\x00\x06\ -\x07\x03\x7d\xc3\ -\x00\x69\ -\x00\x6d\x00\x61\x00\x67\x00\x65\x00\x73\ -\x00\x05\ -\x00\x6f\xa6\x53\ -\x00\x69\ -\x00\x63\x00\x6f\x00\x6e\x00\x73\ -\x00\x12\ -\x00\x94\x5e\xc7\ -\x00\x6c\ -\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x73\x00\x69\x00\x64\x00\x65\x00\x5f\x00\x76\x00\x69\x00\x65\x00\x77\x00\x2e\x00\x73\x00\x76\ -\x00\x67\ -\x00\x0e\ -\x0d\x05\x0c\x27\ -\x00\x66\ -\x00\x72\x00\x6f\x00\x6e\x00\x74\x00\x5f\x00\x76\x00\x69\x00\x65\x00\x77\x00\x2e\x00\x73\x00\x76\x00\x67\ -\x00\x0d\ -\x0f\x3e\x76\xe7\ -\x00\x62\ -\x00\x61\x00\x63\x00\x6b\x00\x5f\x00\x76\x00\x69\x00\x65\x00\x77\x00\x2e\x00\x73\x00\x76\x00\x67\ -\x00\x0f\ -\x08\xa7\x92\xe7\ -\x00\x62\ -\x00\x6f\x00\x74\x00\x74\x00\x6f\x00\x6d\x00\x5f\x00\x76\x00\x69\x00\x65\x00\x77\x00\x2e\x00\x73\x00\x76\x00\x67\ -\x00\x16\ -\x0c\x10\x30\xc7\ -\x00\x63\ -\x00\x61\x00\x64\x00\x71\x00\x75\x00\x65\x00\x72\x00\x79\x00\x5f\x00\x6c\x00\x6f\x00\x67\x00\x6f\x00\x5f\x00\x64\x00\x61\x00\x72\ -\x00\x6b\x00\x2e\x00\x73\x00\x76\x00\x67\ -\x00\x13\ -\x0f\xcc\xdd\x27\ -\x00\x72\ -\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x73\x00\x69\x00\x64\x00\x65\x00\x5f\x00\x76\x00\x69\x00\x65\x00\x77\x00\x2e\x00\x73\ -\x00\x76\x00\x67\ -\x00\x12\ -\x05\x00\xf8\x47\ -\x00\x69\ -\x00\x73\x00\x6f\x00\x6d\x00\x65\x00\x74\x00\x72\x00\x69\x00\x63\x00\x5f\x00\x76\x00\x69\x00\x65\x00\x77\x00\x2e\x00\x73\x00\x76\ -\x00\x67\ -\x00\x0c\ -\x00\xa6\x97\x47\ -\x00\x74\ -\x00\x6f\x00\x70\x00\x5f\x00\x76\x00\x69\x00\x65\x00\x77\x00\x2e\x00\x73\x00\x76\x00\x67\ -" - -qt_resource_struct = b"\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\ -\x00\x00\x00\x12\x00\x02\x00\x00\x00\x08\x00\x00\x00\x03\ -\x00\x00\x00\x22\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\ -\x00\x00\x01\x3a\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x61\ -\x00\x00\x01\x10\x00\x00\x00\x00\x00\x01\x00\x01\x97\x11\ -\x00\x00\x00\x8e\x00\x00\x00\x00\x00\x01\x00\x00\xea\xf0\ -\x00\x00\x00\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x39\x40\ -\x00\x00\x00\x4c\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x50\ -\x00\x00\x00\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x9c\xa0\ -\x00\x00\x00\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x48\xc1\ -" - - -def qInitResources(): - QtCore.qRegisterResourceData( - 0x01, qt_resource_struct, qt_resource_name, qt_resource_data - ) - - -def qCleanupResources(): - QtCore.qUnregisterResourceData( - 0x01, qt_resource_struct, qt_resource_name, qt_resource_data - ) - - -qInitResources() diff --git a/cq_editor/main_window.py b/cq_editor/main_window.py deleted file mode 100644 index d976556c7..000000000 --- a/cq_editor/main_window.py +++ /dev/null @@ -1,693 +0,0 @@ -import sys -from pathlib import Path - -from PyQt5.QtCore import QObject, pyqtSignal -from PyQt5.QtGui import QPalette, QColor -from PyQt5.QtWidgets import ( - QLabel, - QMainWindow, - QMessageBox, - QToolBar, - QDockWidget, - QAction, - QApplication, - QMenu, - QProxyStyle, - QStyle, -) -from logbook import Logger -import cadquery as cq - -from .widgets.editor import Editor -from .widgets.viewer import OCCViewer -from .widgets.console import ConsoleWidget -from .widgets.object_tree import ObjectTree -from .widgets.traceback_viewer import TracebackPane -from .widgets.debugger import Debugger, LocalsView -from .widgets.cq_object_inspector import CQObjectInspector -from .widgets.log import LogViewer -from .widgets.upload_dialog import UploadDialog - -from . import __version__ -from .utils import ( - dock, - add_actions, - open_url, - about_dialog, - check_gtihub_for_updates, - confirm, -) -from .mixins import MainMixin -from .icons import icon -from pyqtgraph.parametertree import Parameter -from .preferences import PreferencesWidget - - -class _PrintRedirectorSingleton(QObject): - """This class monkey-patches `sys.stdout.write` to emit a signal. - It is instanciated as `.main_window.PRINT_REDIRECTOR` and should not be instanciated again. - """ - - sigStdoutWrite = pyqtSignal(str) - - def __init__(self): - super().__init__() - - original_stdout_write = sys.stdout.write - - def new_stdout_write(text: str): - self.sigStdoutWrite.emit(text) - return original_stdout_write(text) - - sys.stdout.write = new_stdout_write - - -PRINT_REDIRECTOR = _PrintRedirectorSingleton() - - -class DockSeparatorStyle(QProxyStyle): - """Widens the dock separators so that they are easier to grab (#277). - - A style proxy is used instead of a stylesheet because setting a stylesheet - on the main window moves its whole widget subtree to QStyleSheetStyle, - which discards palette based theming (e.g. editor syntax highlighting). - """ - - def pixelMetric(self, metric, option=None, widget=None): - - extent = super().pixelMetric(metric, option, widget) - if metric == QStyle.PM_DockWidgetSeparatorExtent: - return max(extent, 6) - - return extent - - -class MainWindow(QMainWindow, MainMixin): - - name = "CQ-Editor" - org = "CadQuery" - - preferences = Parameter.create( - name="Preferences", - children=[ - { - "name": "Light/Dark Theme", - "type": "list", - "value": "Light", - "values": [ - "Light", - "Dark", - ], - }, - ], - ) - - def __init__(self, parent=None, filename=None): - - super(MainWindow, self).__init__(parent) - MainMixin.__init__(self) - - self.setWindowIcon(icon("app")) - - # Windows workaround - makes the correct task bar icon show up. - if sys.platform == "win32": - import ctypes - - myappid = "cq-editor" # arbitrary string - ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid) - - self.viewer = OCCViewer(self) - self.setCentralWidget(self.viewer.canvas) - - # Make sure the dock separators are wide enough to grab on high-DPI displays. - # setStyle does not take ownership, so keep a reference on self. - self._separator_style = DockSeparatorStyle() - self.setStyle(self._separator_style) - - self.prepare_panes() - self.registerComponent("viewer", self.viewer) - self.prepare_toolbar() - self.prepare_menubar() - - self.prepare_statusbar() - self.prepare_actions() - - self.components["object_tree"].addLines() - - self.prepare_console() - - self.fill_dummy() - - self.setup_logging() - - # Allows us to react to the top-level settings for this window being changed - self.preferences.sigTreeStateChanged.connect(self.preferencesChanged) - - self.restorePreferences() - self.restoreWindow() - - # Handle the event of the editor being hidden or shown - self.editor_dock = self.docks["editor"] - self.editor_dock.visibilityChanged.connect(self.handleEditorVisiblityChange) - self.handleEditorVisiblityChange(not self.editor_dock.isHidden()) - - # Let the user know when the file has been modified - self.components["editor"].document().modificationChanged.connect( - self.update_window_title - ) - - if filename: - self.components["editor"].load_from_file(filename) - - self.restoreComponentState() - - try: - import pyi_splash - - pyi_splash.close() - except ImportError: - pass - - def handleEditorVisiblityChange(self, visible): - """ - Does the work required to enable/disable menu items when the Editor visibility is changed. - """ - self.toggle_comment_action.setEnabled(visible) - self.autocomplete_action.setEnabled(visible) - - def preferencesChanged(self, param, changes): - """ - Triggered when the preferences for this window are changed. - """ - - # Use the default light theme/palette - if self.preferences["Light/Dark Theme"] == "Light": - QApplication.instance().setStyleSheet("") - QApplication.instance().setPalette(QApplication.style().standardPalette()) - - # The console theme needs to be changed separately - self.components["console"].app_theme_changed("Light") - # Use the dark theme/palette - elif self.preferences["Light/Dark Theme"] == "Dark": - QApplication.instance().setStyle("Fusion") - - # Now use a palette to switch to dark colors: - white_color = QColor(255, 255, 255) - black_color = QColor(0, 0, 0) - red_color = QColor(255, 0, 0) - palette = QPalette() - palette.setColor(QPalette.Window, QColor(53, 53, 53)) - palette.setColor(QPalette.WindowText, white_color) - palette.setColor(QPalette.Base, QColor(25, 25, 25)) - palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) - palette.setColor(QPalette.ToolTipBase, black_color) - palette.setColor(QPalette.ToolTipText, white_color) - palette.setColor(QPalette.Text, white_color) - palette.setColor(QPalette.Button, QColor(53, 53, 53)) - palette.setColor(QPalette.ButtonText, white_color) - palette.setColor(QPalette.BrightText, red_color) - palette.setColor(QPalette.Link, QColor(42, 130, 218)) - palette.setColor(QPalette.Highlight, QColor(42, 130, 218)) - palette.setColor(QPalette.HighlightedText, black_color) - QApplication.instance().setPalette(palette) - - # The console theme needs to be changed separately - self.components["console"].app_theme_changed("Dark") - - # We alter the color of the toolbar separately to avoid having separate dark theme icons - p = self.toolbar.palette() - if self.preferences["Light/Dark Theme"] == "Dark": - p.setColor(QPalette.Background, QColor(120, 120, 120)) - - # TWeak the QMenu items palette for dark theme - menu_palette = self.menuBar().palette() - menu_palette.setColor(QPalette.Base, QColor(80, 80, 80)) - for menu in self.menuBar().findChildren(QMenu): - menu.setPalette(menu_palette) - else: - p.setColor(QPalette.Background, QColor(240, 240, 240)) - - # Revert the QMenu items palette for dark theme - menu_palette = self.menuBar().palette() - menu_palette.setColor(QPalette.Base, QColor(240, 240, 240)) - for menu in self.menuBar().findChildren(QMenu): - menu.setPalette(menu_palette) - - self.toolbar.setPalette(p) - - def closeEvent(self, event): - - self.saveWindow() - self.savePreferences() - self.saveComponentState() - - if self.components["editor"].document().isModified(): - - rv = QMessageBox.warning( - self, - "Unsaved changes", - "Save changes before closing?", - QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, - QMessageBox.Save, - ) - - if rv == QMessageBox.Save: - self.components["editor"].save() - if self.components["editor"].document().isModified(): - # Save As was cancelled - abort the close. - event.ignore() - return - event.accept() - super(MainWindow, self).closeEvent(event) - elif rv == QMessageBox.Discard: - event.accept() - super(MainWindow, self).closeEvent(event) - else: - event.ignore() - else: - super(MainWindow, self).closeEvent(event) - - def prepare_panes(self): - - self.registerComponent( - "editor", - Editor(self), - lambda c: dock(c, "Editor", self, defaultArea="left"), - ) - - self.registerComponent( - "object_tree", - ObjectTree(self), - lambda c: dock(c, "Objects", self, defaultArea="right"), - ) - - self.registerComponent( - "traceback_viewer", - TracebackPane(self), - lambda c: dock(c, "Current traceback", self, defaultArea="bottom"), - ) - - self.registerComponent("debugger", Debugger(self)) - - self.registerComponent( - "console", - ConsoleWidget(self), - lambda c: dock(c, "Console", self, defaultArea="bottom"), - ) - - self.registerComponent( - "variables_viewer", - LocalsView(self), - lambda c: dock(c, "Variables", self, defaultArea="right"), - ) - - self.registerComponent( - "cq_object_inspector", - CQObjectInspector(self), - lambda c: dock(c, "CQ object inspector", self, defaultArea="right"), - ) - self.registerComponent( - "log", - LogViewer(self), - lambda c: dock(c, "Log viewer", self, defaultArea="bottom"), - ) - - for d in self.docks.values(): - d.show() - - # Connect the bound method rather than a lambda: PRINT_REDIRECTOR is a - # module-level singleton, and PyQt drops a connection to a QObject's - # bound method when that QObject is destroyed. A lambda would outlive - # the LogViewer and call into a deleted C++ object. - PRINT_REDIRECTOR.sigStdoutWrite.connect(self.components["log"].append) - - def prepare_menubar(self): - - menu = self.menuBar() - - menu_file = menu.addMenu("&File") - menu_edit = menu.addMenu("&Edit") - menu_tools = menu.addMenu("&Tools") - menu_run = menu.addMenu("&Run") - menu_view = menu.addMenu("&View") - menu_help = menu.addMenu("&Help") - - # per component menu elements - menus = { - "File": menu_file, - "Edit": menu_edit, - "Run": menu_run, - "Tools": menu_tools, - "View": menu_view, - "Help": menu_help, - } - - for comp in self.components.values(): - self.prepare_menubar_component(menus, comp.menuActions()) - - # Examples submenu - menu_file.addSeparator() - examples_menu = menu_file.addMenu("Examples") - self._populate_examples_menu(examples_menu) - - menu_file.addSeparator() - menu_file.addAction( - QAction("Quit", self, shortcut="ctrl+Q", triggered=self.close) - ) - - # global menu elements - menu_view.addSeparator() - for d in self.findChildren(QDockWidget): - menu_view.addAction(d.toggleViewAction()) - - menu_view.addSeparator() - for t in self.findChildren(QToolBar): - menu_view.addAction(t.toggleViewAction()) - - self.toggle_comment_action = QAction( - icon("toggle-comment"), - "Toggle Comment", - self, - shortcut="ctrl+/", - triggered=self.components["editor"].toggle_comment, - ) - menu_edit.addAction(self.toggle_comment_action) - - # Add the menu action to toggle auto-completion - self.autocomplete_action = QAction( - icon("search"), - "Auto-Complete", - self, - shortcut="alt+/", - triggered=self.components["editor"]._trigger_autocomplete, - ) - menu_edit.addAction(self.autocomplete_action) - - # Add the menu action to open the code search controls - self.search_action = QAction( - icon("search"), - "Search", - self, - shortcut="ctrl+F", - triggered=self.components["editor"].search_widget.show_search, - ) - menu_edit.addAction(self.search_action) - - menu_edit.addAction( - QAction( - icon("preferences"), - "Preferences", - self, - triggered=self.edit_preferences, - ) - ) - - menu_help.addAction( - QAction(icon("help"), "Documentation", self, triggered=self.documentation) - ) - - menu_help.addAction( - QAction("CQ documentation", self, triggered=self.cq_documentation) - ) - - menu_help.addAction(QAction(icon("about"), "About", self, triggered=self.about)) - - menu_help.addAction( - QAction( - "Check for CadQuery updates", self, triggered=self.check_for_cq_updates - ) - ) - - # Add the Upload dialog action - menu_tools.addAction( - QAction( - "Upload Model...", - self, - triggered=self._upload_model, - ) - ) - - def prepare_menubar_component(self, menus, comp_menu_dict): - - for name, action in comp_menu_dict.items(): - menus[name].addActions(action) - - def prepare_toolbar(self): - - self.toolbar = QToolBar("Main toolbar", self, objectName="Main toolbar") - - for c in self.components.values(): - add_actions(self.toolbar, c.toolbarActions()) - - self.addToolBar(self.toolbar) - - def prepare_statusbar(self): - - self.status_label = QLabel("", parent=self) - self.statusBar().insertPermanentWidget(0, self.status_label) - - def prepare_actions(self): - - self.components["debugger"].sigRendered.connect( - self.components["object_tree"].addObjects - ) - self.components["debugger"].sigTraceback.connect( - self.components["traceback_viewer"].addTraceback - ) - self.components["debugger"].sigLocals.connect( - self.components["variables_viewer"].update_frame - ) - self.components["debugger"].sigLocals.connect( - self.components["console"].push_vars - ) - - self.components["object_tree"].sigObjectsAdded[list].connect( - self.components["viewer"].display_many - ) - self.components["object_tree"].sigObjectsAdded[list, bool].connect( - self.components["viewer"].display_many - ) - self.components["object_tree"].sigItemChanged.connect( - self.components["viewer"].update_item - ) - self.components["object_tree"].sigObjectsRemoved.connect( - self.components["viewer"].remove_items - ) - self.components["object_tree"].sigCQObjectSelected.connect( - self.components["cq_object_inspector"].setObject - ) - self.components["object_tree"].sigObjectPropertiesChanged.connect( - self.components["viewer"].redraw - ) - self.components["object_tree"].sigAISObjectsSelected.connect( - self.components["viewer"].set_selected - ) - self.components["object_tree"].sigHelpersResized.connect( - self.components["viewer"].redisplay - ) - - self.components["viewer"].sigObjectSelected.connect( - self.components["object_tree"].handleGraphicalSelection - ) - - self.components["traceback_viewer"].sigHighlightLine.connect( - self.components["editor"].go_to_line - ) - - self.components["cq_object_inspector"].sigDisplayObjects.connect( - self.components["viewer"].display_many - ) - self.components["cq_object_inspector"].sigRemoveObjects.connect( - self.components["viewer"].remove_items - ) - self.components["cq_object_inspector"].sigShowPlane.connect( - self.components["viewer"].toggle_grid - ) - self.components["cq_object_inspector"].sigShowPlane[bool, float].connect( - self.components["viewer"].toggle_grid - ) - self.components["cq_object_inspector"].sigChangePlane.connect( - self.components["viewer"].set_grid_orientation - ) - - self.components["debugger"].sigLocalsChanged.connect( - self.components["variables_viewer"].update_frame - ) - self.components["debugger"].sigLineChanged.connect( - self.components["editor"].set_debug_line - ) - self.components["debugger"].sigDebugging.connect( - self.components["object_tree"].stashObjects - ) - self.components["debugger"].sigDebugging.connect( - lambda active: ( - self.components["editor"].clear_debug_line() if not active else None - ) - ) - self.components["debugger"].sigCQChanged.connect( - self.components["object_tree"].addObjects - ) - self.components["debugger"].sigTraceback.connect( - self.components["traceback_viewer"].addTraceback - ) - - # trigger re-render when file is modified externally or saved - self.components["editor"].triggerRerender.connect( - self.components["debugger"].render - ) - self.components["editor"].sigFilenameChanged.connect( - self.handle_filename_change - ) - # Allows updating of the status bar from the Editor - self.components["editor"].statusChanged.connect(self.update_statusbar) - - def prepare_console(self): - - console = self.components["console"] - obj_tree = self.components["object_tree"] - - # application related items - console.push_vars({"self": self}) - - # CQ related items - console.push_vars( - { - "show": obj_tree.addObject, - "show_object": obj_tree.addObject, - "rand_color": self.components["debugger"]._rand_color, - "cq": cq, - "log": Logger(self.name).info, - } - ) - - def _examples_dir(self): - # In a PyInstaller bundle examples are extracted alongside the package. - # In development they live next to the cq_editor package directory. - if getattr(sys, "frozen", False): - return Path(sys._MEIPASS) / "examples" - return Path(__file__).parent.parent / "examples" - - def _populate_examples_menu(self, menu): - examples_dir = self._examples_dir() - if not examples_dir.is_dir(): - menu.setEnabled(False) - return - - for path in sorted(examples_dir.glob("*.py")): - # Strip the leading "NN_" numbering prefix for the menu label. - label = path.stem - if len(label) > 3 and label[2] == "_" and label[:2].isdigit(): - label = label[3:] - label = label.replace("_", " ").title() - - menu.addAction( - QAction( - label, - self, - triggered=lambda checked, p=path: self.components[ - "editor" - ].load_example(str(p)), - ) - ) - - def fill_dummy(self): - - self.components["editor"].set_text( - 'import cadquery as cq\nresult = cq.Workplane("XY" ).box(3, 3, 0.5).edges("|Z").fillet(0.125)\nshow_object(result)' - ) - - def setup_logging(self): - - from logbook.compat import redirect_logging - from logbook import INFO, Logger - - redirect_logging() - self.components["log"].handler.level = INFO - self.components["log"].handler.push_application() - - self._logger = Logger(self.name) - - def handle_exception(exc_type, exc_value, exc_traceback): - - if issubclass(exc_type, KeyboardInterrupt): - sys.__excepthook__(exc_type, exc_value, exc_traceback) - return - - self._logger.error( - "Uncaught exception occurred", - exc_info=(exc_type, exc_value, exc_traceback), - ) - - sys.excepthook = handle_exception - - def edit_preferences(self): - - prefs = PreferencesWidget(self, self.components) - prefs.exec_() - - def about(self): - - about_dialog( - self, - f"About CQ-editor", - f"PyQt GUI for CadQuery.\nVersion: {__version__}.\nSource Code: https://github.com/CadQuery/CQ-editor", - ) - - def check_for_cq_updates(self): - - check_gtihub_for_updates(self, cq) - - def documentation(self): - - open_url("https://github.com/CadQuery") - - def cq_documentation(self): - - open_url("https://cadquery.readthedocs.io/en/latest/") - - def handle_filename_change(self, fname): - - new_title = fname if fname else "*" - self.setWindowTitle(f"{self.name}: {new_title}") - - def update_window_title(self, modified): - """ - Allows updating the window title to show that the document has been modified. - """ - title = self.windowTitle().rstrip("*") - if modified: - title += "*" - self.setWindowTitle(title) - - def update_statusbar(self, status_text): - """ - Allow updating the status bar with information. - """ - - # Update the statusbar text - self.status_label.setText(status_text) - - def _upload_model(self): - """ - Allows the userr to easily upload models to an online service for manufacturing, - analysis, simulation, display, etc. - """ - - obj_tree = self.components["object_tree"] - selected = [ - item - for item in obj_tree.tree.selectedItems() - if item.parent() is obj_tree.CQ - ] - dlg = UploadDialog( - self, - self.components["object_tree"], - self.components["editor"], - selected_shapes=[item.shape for item in selected], - ) - dlg.exec_() - - -if __name__ == "__main__": - - pass diff --git a/cq_editor/mixins.py b/cq_editor/mixins.py deleted file mode 100644 index f614ffe66..000000000 --- a/cq_editor/mixins.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -Created on Wed May 23 22:02:30 2018 - -@author: adam -""" - -from functools import reduce -from operator import add -from logbook import Logger - -from PyQt5.QtCore import pyqtSlot, QSettings - - -class MainMixin(object): - - name = "Main" - org = "Unknown" - - components = {} - docks = {} - preferences = None - - def __init__(self): - - self.settings = QSettings(self.org, self.name) - - def registerComponent(self, name, component, dock=None): - - self.components[name] = component - - if dock: - self.docks[name] = dock(component) - - def saveWindow(self): - - self.settings.setValue("geometry", self.saveGeometry()) - self.settings.setValue("windowState", self.saveState()) - - def restoreWindow(self): - - if self.settings.value("geometry"): - self.restoreGeometry(self.settings.value("geometry")) - if self.settings.value("windowState"): - self.restoreState(self.settings.value("windowState")) - - def savePreferences(self): - - settings = self.settings - - if self.preferences: - settings.setValue("General", self.preferences.saveState()) - - for comp in (c for c in self.components.values() if c.preferences): - settings.setValue(comp.name, comp.preferences.saveState()) - - def restorePreferences(self): - - settings = self.settings - - if self.preferences and settings.value("General"): - self.preferences.restoreState( - settings.value("General"), removeChildren=False - ) - - for comp in (c for c in self.components.values() if c.preferences): - if settings.value(comp.name): - comp.preferences.restoreState( - settings.value(comp.name), removeChildren=False - ) - - def saveComponentState(self): - - settings = self.settings - - for comp in self.components.values(): - comp.saveComponentState(settings) - - def restoreComponentState(self): - - settings = self.settings - - for comp in self.components.values(): - comp.restoreComponentState(settings) - - -class ComponentMixin(object): - - name = "Component" - preferences = None - - _actions = {} - - def __init__(self): - - if self.preferences: - self.preferences.sigTreeStateChanged.connect(self.updatePreferences) - - self._logger = Logger(self.name) - - def menuActions(self): - - return self._actions - - def toolbarActions(self): - - if len(self._actions) > 0: - return reduce(add, [a for a in self._actions.values()]) - else: - return [] - - @pyqtSlot(object, object) - def updatePreferences(self, *args): - - pass - - def saveComponentState(self, store): - - pass - - def restoreComponentState(self, store): - - pass diff --git a/cq_editor/preferences.py b/cq_editor/preferences.py deleted file mode 100644 index 2badd7408..000000000 --- a/cq_editor/preferences.py +++ /dev/null @@ -1,107 +0,0 @@ -from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QStackedWidget, QDialog -from PyQt5.QtCore import pyqtSlot, Qt - -from pyqtgraph.parametertree import ParameterTree - -from .utils import splitter, layout - - -class PreferencesTreeItem(QTreeWidgetItem): - - def __init__( - self, - name, - widget, - ): - - super(PreferencesTreeItem, self).__init__(name) - self.widget = widget - - -class PreferencesWidget(QDialog): - - def __init__(self, parent, components): - - super(PreferencesWidget, self).__init__( - parent, - Qt.Window | Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint, - windowTitle="Preferences", - ) - - self.stacked = QStackedWidget(self) - self.preferences_tree = QTreeWidget( - self, - headerHidden=True, - itemsExpandable=False, - rootIsDecorated=False, - columnCount=1, - ) - - self.root = self.preferences_tree.invisibleRootItem() - - self.add("General", parent) - - for v in parent.components.values(): - self.add(v.name, v) - - self.splitter = splitter((self.preferences_tree, self.stacked), (2, 5)) - layout(self, (self.splitter,), self) - - self.preferences_tree.currentItemChanged.connect(self.handleSelection) - - def add(self, name, component): - - if component.preferences: - widget = ParameterTree() - widget.setHeaderHidden(True) - widget.setParameters(component.preferences, showTop=False) - self.root.addChild(PreferencesTreeItem((name,), widget)) - - self.stacked.addWidget(widget) - - # PyQtGraph is not setting items in drop down lists properly, so we do it manually - for child in component.preferences.children(): - # Fill the editor color scheme drop down list - if child.name() == "Color scheme": - child.setLimits(["Light", "Dark"]) - # Fill the camera projection type - elif child.name() == "Projection Type": - child.setLimits( - [ - "Orthographic", - "Perspective", - "Stereo", - "MonoLeftEye", - "MonoRightEye", - ] - ) - # Fill the stereo mode, or lack thereof - elif child.name() == "Stereo Mode": - child.setLimits( - [ - "QuadBuffer", - "Anaglyph", - "RowInterlaced", - "ColumnInterlaced", - "ChessBoard", - "SideBySide", - "OverUnder", - ] - ) - # Fill the light/dark theme in the general settings - elif child.name() == "Light/Dark Theme": - child.setLimits(["Light", "Dark"]) - # Fill the orbit method - elif child.name() == "Orbit Method": - child.setLimits( - [ - "Turntable", - "Trackball", - ] - ) - - @pyqtSlot(QTreeWidgetItem, QTreeWidgetItem) - def handleSelection(self, item, *args): - - if item: - self.stacked.setCurrentWidget(item.widget) diff --git a/cq_editor/utils.py b/cq_editor/utils.py deleted file mode 100644 index 1f8ad935c..000000000 --- a/cq_editor/utils.py +++ /dev/null @@ -1,163 +0,0 @@ -import requests - -from packaging.version import parse as parse_version - -from PyQt5 import QtCore, QtWidgets -from PyQt5.QtGui import QDesktopServices -from PyQt5.QtCore import QUrl -from PyQt5.QtWidgets import QFileDialog, QMessageBox - -DOCK_POSITIONS = { - "right": QtCore.Qt.RightDockWidgetArea, - "left": QtCore.Qt.LeftDockWidgetArea, - "top": QtCore.Qt.TopDockWidgetArea, - "bottom": QtCore.Qt.BottomDockWidgetArea, -} - - -def layout( - parent, - items, - top_widget=None, - layout_type=QtWidgets.QVBoxLayout, - margin=2, - spacing=0, -): - - if not top_widget: - top_widget = QtWidgets.QWidget(parent) - top_widget_was_none = True - else: - top_widget_was_none = False - layout = layout_type(top_widget) - top_widget.setLayout(layout) - - for item in items: - layout.addWidget(item) - - layout.setSpacing(spacing) - layout.setContentsMargins(margin, margin, margin, margin) - - if top_widget_was_none: - return top_widget - else: - return layout - - -def splitter(items, stretch_factors=None, orientation=QtCore.Qt.Horizontal): - - sp = QtWidgets.QSplitter(orientation) - - for item in items: - sp.addWidget(item) - - if stretch_factors: - for i, s in enumerate(stretch_factors): - sp.setStretchFactor(i, s) - - return sp - - -def dock( - widget, - title, - parent, - allowedAreas=QtCore.Qt.AllDockWidgetAreas, - defaultArea="right", - name=None, - icon=None, -): - - dock = QtWidgets.QDockWidget(title, parent, objectName=title) - - if name: - dock.setObjectName(name) - if icon: - dock.toggleViewAction().setIcon(icon) - - dock.setAllowedAreas(allowedAreas) - dock.setWidget(widget) - action = dock.toggleViewAction() - action.setText(title) - - dock.setFeatures( - QtWidgets.QDockWidget.DockWidgetFeatures( - QtWidgets.QDockWidget.AllDockWidgetFeatures - ) - ) - - parent.addDockWidget(DOCK_POSITIONS[defaultArea], dock) - - return dock - - -def add_actions(menu, actions): - - if len(actions) > 0: - menu.addActions(actions) - menu.addSeparator() - - -def open_url(url): - - QDesktopServices.openUrl(QUrl(url)) - - -def about_dialog(parent, title, text): - - QtWidgets.QMessageBox.about(parent, title, text) - - -def get_save_filename(suffix): - - rv, _ = QFileDialog.getSaveFileName(filter="*.{}".format(suffix)) - if rv != "" and not rv.endswith(suffix): - rv += "." + suffix - - return rv - - -def get_open_filename(suffix, curr_dir): - - rv, _ = QFileDialog.getOpenFileName( - directory=curr_dir, filter="*.{}".format(suffix) - ) - if rv != "" and not rv.endswith(suffix): - rv += "." + suffix - - return rv - - -def check_gtihub_for_updates( - parent, mod, github_org="cadquery", github_proj="cadquery" -): - - url = f"https://api.github.com/repos/{github_org}/{github_proj}/releases" - resp = requests.get(url).json() - - newer = [ - el["tag_name"] - for el in resp - if not el["draft"] - and parse_version(el["tag_name"]) > parse_version(mod.__version__) - ] - - if newer: - title = "Updates available" - text = ( - f"There are newer versions of {github_proj} " - f"available on github:\n" + "\n".join(newer) - ) - - else: - title = "No updates available" - text = f"You are already using the latest version of {github_proj}" - - QtWidgets.QMessageBox.about(parent, title, text) - - -def confirm(parent, title, msg): - - rv = QMessageBox.question(parent, title, msg, QMessageBox.Yes, QMessageBox.No) - - return True if rv == QMessageBox.Yes else False diff --git a/cq_editor/widgets/__init__.py b/cq_editor/widgets/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/cq_editor/widgets/code_editor.py b/cq_editor/widgets/code_editor.py deleted file mode 100644 index 52ffc7bce..000000000 --- a/cq_editor/widgets/code_editor.py +++ /dev/null @@ -1,910 +0,0 @@ -# Much of this code was adapted from https://github.com/leixingyu/codeEditor which is under -# an MIT license -import os -from PyQt5 import QtCore, QtGui, QtWidgets -from PyQt5.QtGui import QPalette, QColor - -DARK_BLUE = QtGui.QColor(118, 150, 185) - - -class SearchWidget(QtWidgets.QWidget): - def __init__(self, editor): - super(SearchWidget, self).__init__(editor) - self.editor = editor - self.current_match = 0 - self.total_matches = 0 - - self.setup_ui() - - # This widget should initially be hidden - self.hide() - - def setup_ui(self): - # Horizontal layout - layout = QtWidgets.QHBoxLayout() - layout.setContentsMargins(5, 5, 5, 5) - - # Search input box - self.search_input = QtWidgets.QLineEdit() - self.search_input.setPlaceholderText("Search...") - self.search_input.setMinimumWidth(100) - self.search_input.textChanged.connect(self.on_search_text_changed) - self.search_input.returnPressed.connect(self.find_next) - - # Previous button - self.prev_button = QtWidgets.QPushButton("Prev") - self.prev_button.clicked.connect(self.find_previous) - self.prev_button.setEnabled(False) - - # Next button - self.next_button = QtWidgets.QPushButton("Next") - self.next_button.clicked.connect(self.find_next) - self.next_button.setEnabled(False) - - # Match count label - self.match_label = QtWidgets.QLabel("0 matches") - - # Close button - self.close_button = QtWidgets.QPushButton("×") - self.close_button.setMaximumSize(20, 20) - self.close_button.clicked.connect(self.hide_search) - - # Add widgets to layout - layout.addWidget(self.search_input) - layout.addWidget(self.prev_button) - layout.addWidget(self.next_button) - layout.addWidget(self.match_label) - layout.addWidget(self.close_button) - self.setLayout(layout) - - def on_search_text_changed(self, text): - """ - Called as the user types text into the search field. - """ - if not text: - self.clear_highlights() - self.update_match_count(0, 0) - self.prev_button.setEnabled(False) - self.next_button.setEnabled(False) - return - - self.find_all_matches(text) - - def find_all_matches(self, search_text): - """ - Finds all the matches within the search text. - """ - if not search_text: - return - - # Clear any previous highlights - self.clear_highlights() - - # Find all matches - document = self.editor.document() - cursor = QtGui.QTextCursor(document) - self.matches = [] - - # Find all occurrences - while True: - # Look for a match - cursor = document.find(search_text, cursor) - if cursor.isNull(): - break - self.matches.append(cursor) - - self.total_matches = len(self.matches) - - # If there are matches make them visible to the user - if self.total_matches > 0: - self.current_match = 0 - self.highlight_matches() - self.highlight_current_match() - self.prev_button.setEnabled(True) - self.next_button.setEnabled(True) - else: - self.prev_button.setEnabled(False) - self.next_button.setEnabled(False) - - self.update_match_count( - self.current_match + 1 if self.total_matches > 0 else 0, self.total_matches - ) - - def highlight_matches(self): - """ - Highlights all matches to make them visible. - """ - extra_selections = [] - - for cursor in self.matches: - selection = QtWidgets.QTextEdit.ExtraSelection() - selection.format.setBackground(QtGui.QColor(255, 255, 0, 100)) - selection.cursor = cursor - extra_selections.append(selection) - - self.editor.setExtraSelections(extra_selections) - - def highlight_current_match(self): - """ - Makes the current match stand out from the others. - """ - - # If there are no matches to highlight, then skip this step - if not self.matches or self.current_match >= len(self.matches): - return - - # Highlight current match more than others and scroll to it - extra_selections = [] - - for i, cursor in enumerate(self.matches): - selection = QtWidgets.QTextEdit.ExtraSelection() - # The current match should stand out - if i == self.current_match: - selection.format.setBackground(QtGui.QColor(255, 165, 0)) - else: - selection.format.setBackground(QtGui.QColor(255, 255, 0, 100)) - selection.cursor = cursor - extra_selections.append(selection) - - self.editor.setExtraSelections(extra_selections) - - # Scroll to the current match - self.editor.setTextCursor(self.matches[self.current_match]) - self.editor.ensureCursorVisible() - - def find_next(self): - """ - Finds the next match. - """ - - # If there are no matches, skip this step - if not self.matches: - return - - self.current_match = (self.current_match + 1) % len(self.matches) - self.highlight_current_match() - self.update_match_count(self.current_match + 1, self.total_matches) - - def find_previous(self): - """ - Finds the previous match. - """ - - # If there are no matches, skip this step - if not self.matches: - return - - self.current_match = (self.current_match - 1) % len(self.matches) - self.highlight_current_match() - self.update_match_count(self.current_match + 1, self.total_matches) - - def update_match_count(self, current, total): - """ - Updates the match count for the user. - """ - if total == 0: - self.match_label.setText("0 matches") - else: - self.match_label.setText(f"{current} of {total}") - - def clear_highlights(self): - """ - Clears all of the find highlights. - """ - self.editor.setExtraSelections([]) - self.matches = [] - - def show_search(self): - """ - Makes the search dialog visible. - """ - self.show() - - # Make sure the user can start typing search text right away - self.search_input.setFocus() - self.search_input.selectAll() - - self.position_widget() - - # If there is already text in the search box, trigger the search - if self.search_input.text(): - self.find_all_matches(self.search_input.text()) - - def hide_search(self): - """ - Hides the search dialog again. - """ - self.hide() - self.clear_highlights() - self.editor.setFocus() - - def position_widget(self): - """ - Makes sure that the search widget gets placed in the right location - in the window. - """ - - # Top-right corner of the editor - editor_rect = self.editor.geometry() - widget_width = 400 - widget_height = 40 - x = editor_rect.width() - widget_width - 20 - y = 10 - - # Set the size of the widget and bring it to the front - self.setGeometry(x, y, widget_width, widget_height) - self.raise_() - - -class LineNumberArea(QtWidgets.QWidget): - def __init__(self, editor): - super(LineNumberArea, self).__init__(editor) - self._code_editor = editor - - def sizeHint(self): - return QtCore.QSize(self._code_editor.line_number_area_width(), 0) - - def mousePressEvent(self, event): - """ - Handles mouse clicks to add/remove breakpoints. - """ - if event.button() == QtCore.Qt.LeftButton: - # Calculate which line was clicked - line_number = self.get_line_number_from_position(event.pos()) - if line_number is not None: - self._code_editor.toggle_breakpoint(line_number) - - def get_line_number_from_position(self, pos): - """ - Convert mouse position to line number. - """ - - # Get the first visible block - block = self._code_editor.firstVisibleBlock() - block_number = block.blockNumber() - offset = self._code_editor.contentOffset() - top = self._code_editor.blockBoundingGeometry(block).translated(offset).top() - - # Find which block the click position corresponds to - while block.isValid(): - bottom = top + self._code_editor.blockBoundingRect(block).height() - - if top <= pos.y() <= bottom: - return ( - block_number + 1 - ) # Line numbers start at 0 internally and 1 for the user - - block = block.next() - top = bottom - block_number += 1 - - return None - - def paintEvent(self, event): - self._code_editor.lineNumberAreaPaintEvent(event) - - -class EdgeLine(QtWidgets.QWidget): - edge_line = None - columns = 80 - - def __init__(self): - super(QtWidgets.QWidget, self).__init__() - - def set_enabled(self, enabled_state): - self.setEnabled = enabled_state - - def set_columns(self, number_of_columns): - self.columns = number_of_columns - - -class CodeTextEdit(QtWidgets.QPlainTextEdit): - is_first = False - pressed_keys = list() - - indented = QtCore.pyqtSignal(object) - unindented = QtCore.pyqtSignal(object) - - def __init__(self): - super(CodeTextEdit, self).__init__() - - self._eol = os.linesep - - self.indented.connect(self.do_indent) - self.unindented.connect(self.undo_indent) - - def clear_selection(self): - """ - Clear text selection on cursor - """ - cursor = self.textCursor() - pos = cursor.selectionEnd() - cursor.movePosition(pos) - self.setTextCursor(cursor) - - def get_selection_range(self): - """ - Get text selection line range from cursor - Note: currently only support continuous selection - - :return: (int, int). start line number and end line number - """ - cursor = self.textCursor() - if not cursor.hasSelection(): - return 0, 0 - - start_pos = cursor.selectionStart() - end_pos = cursor.selectionEnd() - - cursor.setPosition(start_pos) - start_line = cursor.blockNumber() - cursor.setPosition(end_pos) - end_line = cursor.blockNumber() - - return start_line, end_line - - def remove_line_start(self, string, line_number): - """ - Remove certain string occurrence on line start - - :param string: str. string pattern to remove - :param line_number: int. line number - """ - cursor = QtGui.QTextCursor(self.document().findBlockByLineNumber(line_number)) - cursor.select(QtGui.QTextCursor.LineUnderCursor) - text = cursor.selectedText() - if text.startswith(string): - cursor.removeSelectedText() - cursor.insertText(text.split(string, 1)[-1]) - - def insert_line_start(self, string, line_number): - """ - Insert certain string pattern on line start - - :param string: str. string pattern to insert - :param line_number: int. line number - """ - cursor = QtGui.QTextCursor(self.document().findBlockByLineNumber(line_number)) - self.setTextCursor(cursor) - self.textCursor().insertText(string) - - def keyPressEvent(self, event): - """ - Extend the key press event to create key shortcuts - """ - self.is_first = True - self.pressed_keys.append(event.key()) - start_line, end_line = self.get_selection_range() - - # indent event - if event.key() == QtCore.Qt.Key_Tab: - lines = range(start_line, end_line + 1) - self.indented.emit(lines) - return - elif event.key() == QtCore.Qt.Key_Tab and (end_line - start_line): - lines = range(start_line, end_line + 1) - self.indented.emit(lines) - return - # un-indent event - elif event.key() == QtCore.Qt.Key_Backtab: - lines = range(start_line, end_line + 1) - self.unindented.emit(lines) - return - - super(CodeTextEdit, self).keyPressEvent(event) - - def do_indent(self, lines): - """ - Indent lines - - :param lines: [int]. line numbers - """ - - # Get the selection range of lines - start_line, end_line = self.get_selection_range() - - # If a single line is selected, make sure it is the only line in the range - if start_line == 0 and end_line == 0: - # Insert a tab at the current cursor location - cursor = self.textCursor() - cursor.insertText(" ") - - # Make sure that no lines are changed - lines = [] - # Multiple lines have been selected - else: - lines = range(start_line, end_line + 1) - - # Walk through the selected lines and tab them (with 4 spaces) - for line in lines: - self.insert_line_start(" ", line) - - def undo_indent(self, lines): - """ - Un-indent lines - - :param lines: [int]. line numbers - """ - for line in lines: - self.remove_line_start(" ", line) - - # Set the cursor to the beginning of the last line - cursor = self.textCursor() - cursor.setPosition(cursor.selectionEnd()) # Move to end of selection - cursor.movePosition(QtGui.QTextCursor.StartOfLine) # Jump to start of line - self.setTextCursor(cursor) - - -class CodeEditor(CodeTextEdit): - def __init__(self, parent=None): - super(CodeEditor, self).__init__() - self.line_number_area = LineNumberArea(self) - - self.font = QtGui.QFont() - self.font.setFamily("Courier New") - self.font.setStyleHint(QtGui.QFont.Monospace) - self.font.setPointSize(10) - self.setFont(self.font) - - self.tab_size = 4 - self.setTabStopWidth(self.tab_size * self.fontMetrics().width(" ")) - - self.blockCountChanged.connect(self.update_line_number_area_width) - self.updateRequest.connect(self.update_line_number_area) - # self.cursorPositionChanged.connect(self.highlight_current_line) - - self.update_line_number_area_width(0) - # self.highlight_current_line() - - self.menu = QtWidgets.QMenu() - - self.edge_line = EdgeLine() - - self.search_widget = SearchWidget(self) - - self._filename = "" - - def keyPressEvent(self, event): - # Handle Ctrl+F for search - if ( - event.modifiers() == QtCore.Qt.ControlModifier - and event.key() == QtCore.Qt.Key_F - ): - self.search_widget.show_search() - return - - # Handle F3 for find next (when search widget is visible) - if event.key() == QtCore.Qt.Key_F3 and self.search_widget.isVisible(): - if event.modifiers() == QtCore.Qt.AltModifier: - self.search_widget.find_previous() # Alt+F3 for previous - else: - self.search_widget.find_next() # F3 for next - return - - # Handle Escape to close search - if event.key() == QtCore.Qt.Key_Escape and self.search_widget.isVisible(): - self.search_widget.hide_search() - return - - # Call parent for other keys - super(CodeEditor, self).keyPressEvent(event) - - def setup_editor( - self, - line_numbers=True, - markers=True, - edge_line=100, - tab_mode=False, - show_blanks=True, - font=QtGui.QFontDatabase.systemFont(QtGui.QFontDatabase.FixedFont), - language="Python", - filename="", - ): - print("setup_editor called") - - def set_color_scheme(self, color_scheme): - """ - Sets the color theme of the editor widget. - :param str color_scheme: Name of the color theme to be set - """ - - if color_scheme == "Light": - self.setStyleSheet("") - self.setPalette(QtWidgets.QApplication.style().standardPalette()) - else: - # Now use a palette to switch to dark colors: - white_color = QColor(255, 255, 255) - black_color = QColor(0, 0, 0) - red_color = QColor(255, 0, 0) - palette = QPalette() - palette.setColor(QPalette.Window, QColor(53, 53, 53)) - palette.setColor(QPalette.WindowText, white_color) - palette.setColor(QPalette.Base, QColor(25, 25, 25)) - palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53)) - palette.setColor(QPalette.ToolTipBase, black_color) - palette.setColor(QPalette.ToolTipText, white_color) - palette.setColor(QPalette.Text, white_color) - palette.setColor(QPalette.Button, QColor(53, 53, 53)) - palette.setColor(QPalette.ButtonText, white_color) - palette.setColor(QPalette.BrightText, red_color) - palette.setColor(QPalette.Link, QColor(42, 130, 218)) - palette.setColor(QPalette.Highlight, QColor(42, 130, 218)) - palette.setColor(QPalette.HighlightedText, black_color) - self.setPalette(palette) - - def set_font(self, new_font): - self.font = new_font - self.setFont(new_font) - - def toggle_wrap_mode(self, wrap_mode): - self.setLineWrapMode(wrap_mode) - - def set_cursor_position(self, position): - """ - Allows the caller to set the position of the cursor within - the editor text. - """ - - cursor = self.textCursor() - cursor.setPosition(position) - self.setTextCursor(cursor) - - def go_to_line(self, line_number): - """ - Set the text cursor at a specific line number. - """ - - cursor = self.textCursor() - - # Line numbers start at 0 - block = self.document().findBlockByNumber(line_number - 1) - - cursor.setPosition(block.position()) - self.setTextCursor(cursor) - - def set_debug_line(self, line_number): - """ - Sets which line is currently being debugged. - """ - self.debugger.current_debug_line = line_number - self.line_number_area.update() - self.go_to_line(line_number) - - def clear_debug_line(self): - """ - Clears the line being debugged. - """ - self.debugger.current_debug_line = None - self.line_number_area.update() - - def toggle_comment(self): - """ - High level method to comment or uncomment a single line, - or block of lines. - """ - - # See if there is a selection range - sel_range = self.get_selection_range() - if sel_range[0] == 0 and sel_range[1] == 0: - # Get the text of the line - cursor = self.textCursor() - cursor.movePosition(QtGui.QTextCursor.StartOfLine) - line_text = cursor.block().text() - - # Skip blank lines - if line_text == "": - return - - # Find the first non-whitespace character position - pos = 0 - while pos < len(line_text) and line_text[pos].isspace(): - pos += 1 - - # Move right by pos characters to the position before text starts - cursor.movePosition( - QtGui.QTextCursor.Right, QtGui.QTextCursor.MoveAnchor, pos - ) - cursor.movePosition( - QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, 1 - ) - - # If we have a single line comment, remove it - if cursor.selectedText() == "#": - cursor.removeSelectedText() - - # Remove any whitespace after the comment character - cursor.movePosition( - QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, 1 - ) - if cursor.selectedText() == " ": - cursor.removeSelectedText() - else: - # Insert the comment characters - cursor.movePosition( - QtGui.QTextCursor.Left, QtGui.QTextCursor.MoveAnchor, 1 - ) - cursor.insertText("# ") - else: - # Make the selected line numbers 1-based - sel_start = sel_range[0] - sel_end = sel_range[1] - cursor = self.textCursor() - - # Select the text block - block = self.document().findBlockByNumber(sel_start) - cursor.setPosition(block.position()) - last_block = self.document().findBlockByNumber(sel_end) - end_pos = last_block.position() + last_block.length() - 1 - cursor.setPosition(end_pos, QtGui.QTextCursor.KeepAnchor) - - # Find the left-most position to put the comment at - leftmost_pos = 99999 - comment_line_found = False - non_comment_line_found = False - blank_lines = [] - # Step through all of the selected lines and toggle their comments - for i in range(sel_start, sel_end + 1): - # Set the cursor to the current line number - block = self.document().findBlockByNumber(i) - cursor.setPosition(block.position()) - cursor.movePosition(cursor.EndOfBlock, cursor.KeepAnchor) - line_text = cursor.selectedText() - - # Make sure the line is not blank - if line_text == "": - blank_lines.append(i) - continue - - if line_text.strip()[0] == "#": - comment_line_found = True - else: - non_comment_line_found = True - - # Find the first non-whitespace character position - pos = 0 - while pos < len(line_text) and line_text[pos].isspace(): - pos += 1 - - # Save the left-most position - if pos < leftmost_pos: - leftmost_pos = pos - - # Step through all of the selected lines and toggle their comments - cursor.beginEditBlock() - for i in range(sel_start, sel_end + 1): - # If this is a blank line, do not process it - if i in blank_lines: - continue - - # Set the cursor to the current line number - block = self.document().findBlockByNumber(i) - cursor.setPosition(block.position()) - - # See if we need to comment the whole block - if comment_line_found and non_comment_line_found: - # Insert the comment characters - cursor.insertText("# ") - else: - # Move right by pos characters to the position before text starts - cursor.movePosition( - QtGui.QTextCursor.Right, - QtGui.QTextCursor.MoveAnchor, - leftmost_pos, - ) - cursor.movePosition( - QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, 1 - ) - - # If the line starts with a hash, uncomment it. Otherwise comment it - if cursor.selectedText() == "#": - cursor.removeSelectedText() - - # Remove any whitespace after the comment character - cursor.movePosition( - QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor, 1 - ) - if cursor.selectedText() == " ": - cursor.removeSelectedText() - else: - # Insert the comment characters - cursor.movePosition( - QtGui.QTextCursor.Left, QtGui.QTextCursor.MoveAnchor, 1 - ) - cursor.insertText("# ") - cursor.endEditBlock() - - def set_text(self, new_text): - """ - Sets the text content of the editor. - :param str new_text: Text to be set in the editor. - """ - # Set the text in the document - self.setPlainText(new_text) - - # Set the cursor at the end of the text - cursor = self.textCursor() - cursor.movePosition(cursor.End) - self.setTextCursor(cursor) - - # Set the document to be modified - self.document().setModified(True) - - def set_text_from_file(self, file_name): - """ - Allows the editor text to be set from a file. - :param str file_name: Full path of the file to be loaded into the editor. - """ - - self._filename = file_name - - # Detect the EOL style used in the file so we can preserve it on save - with open(file_name, "rb") as f: - raw = f.read() - if b"\r\n" in raw: - self._eol = "\r\n" - elif b"\r" in raw: - self._eol = "\r" - else: - self._eol = "\n" - - # Load the text into the text field - with open(file_name, "r", encoding="utf-8") as file: - file_content = file.read() - - self.setPlainText(file_content) - - def get_text_with_eol(self): - """ - Returns a string representing the full text in the editor. - """ - return self.toPlainText() - - def line_number_area_width(self): - digits = 1 - max_num = max(1, self.blockCount()) - while max_num >= 10: - max_num *= 0.1 - digits += 1 - - space = 30 + self.fontMetrics().width("9") * digits - return space - - def resizeEvent(self, e): - super(CodeEditor, self).resizeEvent(e) - cr = self.contentsRect() - width = self.line_number_area_width() - rect = QtCore.QRect(cr.left(), cr.top(), width, cr.height()) - self.line_number_area.setGeometry(rect) - - def lineNumberAreaPaintEvent(self, event): - painter = QtGui.QPainter(self.line_number_area) - try: - # painter.fillRect(event.rect(), QtCore.Qt.lightGray) - block = self.firstVisibleBlock() - block_number = block.blockNumber() - offset = self.contentOffset() - top = self.blockBoundingGeometry(block).translated(offset).top() - bottom = top + self.blockBoundingRect(block).height() - - while block.isValid() and top <= event.rect().bottom(): - if block.isVisible() and bottom >= event.rect().top(): - line_number = block_number + 1 - - # Draw the breakpoint dot, if there is a breakpoint on this line - if self.line_has_breakpoint(line_number): - painter.setBrush( - QtGui.QBrush(QtGui.QColor(255, 0, 0)) - ) # Red circle - painter.setPen(QtGui.QPen(QtGui.QColor(150, 0, 0))) - circle_size = 10 - circle_x = 5 - circle_y = ( - int(top) - + (self.fontMetrics().height() - circle_size - 2) // 2 - ) - painter.drawEllipse( - circle_x, circle_y, circle_size, circle_size - ) - - # Draw the debug position arrow - if self.debugger.current_debug_line == line_number: - painter.setBrush(QtGui.QBrush(QtGui.QColor(255, 200, 0))) - painter.setPen(QtGui.QPen(QtGui.QColor(200, 150, 0))) - mid_y = int(top) + self.fontMetrics().height() // 2 - arrow = QtGui.QPolygon( - [ - QtCore.QPoint(7, mid_y - 5), - QtCore.QPoint(15, mid_y), - QtCore.QPoint(7, mid_y + 5), - ] - ) - painter.drawPolygon(arrow) - - # Draw the line number - number = str(line_number) - painter.setPen(DARK_BLUE) - width = self.line_number_area.width() - 10 - height = self.fontMetrics().height() - painter.drawText( - 0, int(top), width, height, QtCore.Qt.AlignRight, number - ) - - block = block.next() - top = bottom - bottom = top + self.blockBoundingRect(block).height() - block_number += 1 - finally: - painter.end() - - def update_line_number_area_width(self, newBlockCount): - self.setViewportMargins(self.line_number_area_width(), 0, 0, 0) - - def update_line_number_area(self, rect, dy): - if dy: - self.line_number_area.scroll(0, dy) - else: - width = self.line_number_area.width() - self.line_number_area.update(0, rect.y(), width, rect.height()) - - if rect.contains(self.viewport().rect()): - self.update_line_number_area_width(0) - - def highlight_current_line(self): - extra_selections = list() - if not self.isReadOnly(): - selection = QtWidgets.QTextEdit.ExtraSelection() - line_color = DARK_BLUE.lighter(160) - selection.format.setBackground(line_color) - selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True) - - selection.cursor = self.textCursor() - selection.cursor.clearSelection() - extra_selections.append(selection) - self.setExtraSelections(extra_selections) - - def toggle_breakpoint(self, line_number): - """ - Toggle breakpoint on/off for a given line number. - """ - if line_number in self.debugger.breakpoints: - self.debugger.breakpoints.remove(line_number) - else: - self.debugger.breakpoints.append(line_number) - - # Repaint the line number area - self.line_number_area.update() - - def line_has_breakpoint(self, line_number): - """ - Checks if a line has a breakpoint. - """ - return line_number in self.debugger.breakpoints - - def paintEvent(self, event): - """ - Overrides the default paint event so that we can draw the line length indicator. - """ - - # Call the parent's paintEvent first to render the text - super(CodeEditor, self).paintEvent(event) - - painter = QtGui.QPainter(self.viewport()) - try: - # Calculate the x position for the line - font_metrics = self.fontMetrics() - char_width = font_metrics.width("M") # Use 'M' for average character width - x_position = self.edge_line.columns * char_width + self.contentOffset().x() - - # Only draw if the line is within the visible area - if 0 <= x_position <= self.viewport().width(): - # Set the pen color (light gray is common) - painter.setPen( - QtGui.QPen(QtGui.QColor(200, 200, 200), 1, QtCore.Qt.SolidLine) - ) - - # Draw the vertical line from top to bottom of the viewport - painter.drawLine( - int(x_position), 0, int(x_position), self.viewport().height() - ) - finally: - painter.end() diff --git a/cq_editor/widgets/console.py b/cq_editor/widgets/console.py deleted file mode 100644 index 75cda2a7b..000000000 --- a/cq_editor/widgets/console.py +++ /dev/null @@ -1,137 +0,0 @@ -from PyQt5.QtWidgets import QApplication, QAction -from PyQt5.QtCore import pyqtSlot - -from qtconsole.rich_jupyter_widget import RichJupyterWidget -from qtconsole.inprocess import QtInProcessKernelManager - -from ..mixins import ComponentMixin - -from ..icons import icon - - -class ConsoleWidget(RichJupyterWidget, ComponentMixin): - - name = "Console" - - def __init__(self, customBanner=None, namespace=dict(), *args, **kwargs): - super(ConsoleWidget, self).__init__(*args, **kwargs) - - # if not customBanner is None: - # self.banner = customBanner - - self._actions = { - "Run": [ - QAction( - icon("clear-2"), "Clear Console", self, triggered=self.reset_console - ), - ] - } - self.font_size = 6 - self.style_sheet = """ - """ - self.syntax_style = "zenburn" - - self.kernel_manager = kernel_manager = QtInProcessKernelManager() - kernel_manager.start_kernel(show_banner=False) - kernel_manager.kernel.shell.display_banner = False - kernel_manager.kernel.shell.banner1 = "" - kernel_manager.kernel.gui = "qt" - - self.kernel_client = kernel_client = self._kernel_manager.client() - kernel_client.start_channels() - - def stop(): - kernel_client.stop_channels() - kernel_manager.shutdown_kernel() - QApplication.instance().exit() - - self.exit_requested.connect(stop) - - self.clear() - - self.push_vars(namespace) - - def _append_plain_text(self, text, *args, **kwargs): - """ - Overrides the super's method to filter out IPython tips. - """ - # Drop IPython startup tips (including the unicode completion tip) - # Done because turning the banner off does not work - if isinstance(text, str) and text.lstrip().startswith("Tip:"): - return - - return super(ConsoleWidget, self)._append_plain_text(text, *args, **kwargs) - - @pyqtSlot(dict) - def push_vars(self, variableDict): - """ - Given a dictionary containing name / value pairs, push those variables - to the Jupyter console widget - """ - self.kernel_manager.kernel.shell.push(variableDict) - - def clear(self): - """ - Clears the terminal - """ - self._control.clear() - - def reset_console(self): - """ - Resets the terminal, which clears it back to a single prompt. - """ - self.reset(clear=True) - - def print_text(self, text): - """ - Prints some plain text to the console - """ - self._append_plain_text(text) - - def execute_command(self, command): - """ - Execute a command in the frame of the console widget - """ - self._execute(command, False) - - def _banner_default(self): - - return "" - - def app_theme_changed(self, theme): - """ - Allows this console to be changed to match the light or dark theme of the rest of the app. - """ - - if theme == "Dark": - self.set_default_style("linux") - else: - self.set_default_style("lightbg") - - -if __name__ == "__main__": - - import sys - - app = QApplication(sys.argv) - - console = ConsoleWidget(customBanner="IPython console test") - console.show() - - sys.exit(app.exec_()) diff --git a/cq_editor/widgets/cq_object_inspector.py b/cq_editor/widgets/cq_object_inspector.py deleted file mode 100644 index b9faac01d..000000000 --- a/cq_editor/widgets/cq_object_inspector.py +++ /dev/null @@ -1,134 +0,0 @@ -from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QAction -from PyQt5.QtCore import Qt, pyqtSlot, pyqtSignal - -from OCP.AIS import AIS_ColoredShape -from OCP.gp import gp_Ax3 - -from cadquery import Vector - -from ..mixins import ComponentMixin -from ..icons import icon - - -class CQChildItem(QTreeWidgetItem): - - def __init__(self, cq_item, **kwargs): - - super(CQChildItem, self).__init__( - [type(cq_item).__name__, str(cq_item)], **kwargs - ) - - self.cq_item = cq_item - - -class CQStackItem(QTreeWidgetItem): - - def __init__(self, name, workplane=None, **kwargs): - - super(CQStackItem, self).__init__([name, ""], **kwargs) - - self.workplane = workplane - - -class CQObjectInspector(QTreeWidget, ComponentMixin): - - name = "CQ Object Inspector" - - sigRemoveObjects = pyqtSignal(list) - sigDisplayObjects = pyqtSignal(list, bool) - sigShowPlane = pyqtSignal([bool], [bool, float]) - sigChangePlane = pyqtSignal(gp_Ax3) - - def __init__(self, parent): - - super(CQObjectInspector, self).__init__(parent) - self.setHeaderHidden(False) - self.setRootIsDecorated(True) - self.setContextMenuPolicy(Qt.ActionsContextMenu) - self.setColumnCount(2) - self.setHeaderLabels(["Type", "Value"]) - - self.root = self.invisibleRootItem() - self.inspected_items = [] - - self._toolbar_actions = [ - QAction( - icon("inspect"), - "Inspect CQ object", - self, - toggled=self.inspect, - checkable=True, - ) - ] - - self.addActions(self._toolbar_actions) - - def menuActions(self): - - return {"Tools": self._toolbar_actions} - - def toolbarActions(self): - - return self._toolbar_actions - - @pyqtSlot(bool) - def inspect(self, value): - - if value: - self.itemSelectionChanged.connect(self.handleSelection) - self.itemSelectionChanged.emit() - else: - self.itemSelectionChanged.disconnect(self.handleSelection) - self.sigRemoveObjects.emit(self.inspected_items) - self.sigShowPlane.emit(False) - - @pyqtSlot() - def handleSelection(self): - - inspected_items = self.inspected_items - self.sigRemoveObjects.emit(inspected_items) - inspected_items.clear() - - items = self.selectedItems() - if len(items) == 0: - return - - item = items[-1] - if type(item) is CQStackItem: - cq_plane = item.workplane.plane - dim = item.workplane.largestDimension() - plane = gp_Ax3( - cq_plane.origin.toPnt(), cq_plane.zDir.toDir(), cq_plane.xDir.toDir() - ) - self.sigChangePlane.emit(plane) - self.sigShowPlane[bool, float].emit(True, dim) - - for child in (item.child(i) for i in range(item.childCount())): - obj = child.cq_item - if hasattr(obj, "wrapped") and type(obj) != Vector: - ais = AIS_ColoredShape(obj.wrapped) - inspected_items.append(ais) - - else: - self.sigShowPlane.emit(False) - obj = item.cq_item - if hasattr(obj, "wrapped") and type(obj) != Vector: - ais = AIS_ColoredShape(obj.wrapped) - inspected_items.append(ais) - - self.sigDisplayObjects.emit(inspected_items, False) - - @pyqtSlot(object) - def setObject(self, cq_obj): - - self.root.takeChildren() - - # iterate through parent objects if they exist - while getattr(cq_obj, "parent", None): - current_frame = CQStackItem(str(cq_obj.plane.origin), workplane=cq_obj) - self.root.addChild(current_frame) - - for obj in cq_obj.objects: - current_frame.addChild(CQChildItem(obj)) - - cq_obj = cq_obj.parent diff --git a/cq_editor/widgets/debugger.py b/cq_editor/widgets/debugger.py deleted file mode 100644 index c98bbc780..000000000 --- a/cq_editor/widgets/debugger.py +++ /dev/null @@ -1,446 +0,0 @@ -import sys -from contextlib import ExitStack, contextmanager -from enum import Enum, auto -from types import SimpleNamespace, FrameType, ModuleType -from typing import List -from bdb import BdbQuit -from inspect import currentframe - -import cadquery as cq -from PyQt5 import QtCore -from PyQt5.QtCore import ( - Qt, - QObject, - pyqtSlot, - pyqtSignal, - QEventLoop, - QAbstractTableModel, -) -from PyQt5.QtWidgets import QAction, QTableView - -from logbook import info -from path import Path -from pyqtgraph.parametertree import Parameter -from ..icons import icon -from random import randrange as rrr, seed - -from ..cq_utils import find_cq_objects, reload_cq -from ..mixins import ComponentMixin - -DUMMY_FILE = "" - - -class DbgState(Enum): - - STEP = auto() - CONT = auto() - STEP_IN = auto() - RETURN = auto() - - -class DbgEevent(object): - - LINE = "line" - CALL = "call" - RETURN = "return" - - -class LocalsModel(QAbstractTableModel): - - HEADER = ("Name", "Type", "Value") - - def __init__(self, parent): - - super(LocalsModel, self).__init__(parent) - self.frame = None - - def update_frame(self, frame): - - self.frame = [ - (k, type(v).__name__, str(v)) - for k, v in frame.items() - if not k.startswith("_") - ] - - def rowCount(self, parent=QtCore.QModelIndex()): - - if self.frame: - return len(self.frame) - else: - return 0 - - def columnCount(self, parent=QtCore.QModelIndex()): - - return 3 - - def headerData(self, section, orientation, role=Qt.DisplayRole): - if role == Qt.DisplayRole and orientation == Qt.Horizontal: - return self.HEADER[section] - return QAbstractTableModel.headerData(self, section, orientation, role) - - def data(self, index, role): - if role == QtCore.Qt.DisplayRole: - i = index.row() - j = index.column() - return self.frame[i][j] - else: - return QtCore.QVariant() - - -class LocalsView(QTableView, ComponentMixin): - - name = "Variables" - - def __init__(self, parent): - - super(LocalsView, self).__init__(parent) - ComponentMixin.__init__(self) - - header = self.horizontalHeader() - header.setStretchLastSection(True) - - vheader = self.verticalHeader() - vheader.setVisible(False) - - @pyqtSlot(dict) - def update_frame(self, frame): - - model = LocalsModel(self) - model.update_frame(frame) - - self.setModel(model) - - -class Debugger(QObject, ComponentMixin): - - name = "Debugger" - - preferences = Parameter.create( - name="Preferences", - children=[ - {"name": "Reload CQ", "type": "bool", "value": False}, - {"name": "Add script dir to path", "type": "bool", "value": True}, - {"name": "Change working dir to script dir", "type": "bool", "value": True}, - {"name": "Reload imported modules", "type": "bool", "value": True}, - ], - ) - - sigRendered = pyqtSignal(dict) - sigLocals = pyqtSignal(dict) - sigTraceback = pyqtSignal(object, str) - - sigFrameChanged = pyqtSignal(object) - sigLineChanged = pyqtSignal(int) - sigLocalsChanged = pyqtSignal(dict) - sigCQChanged = pyqtSignal(dict, bool) - sigDebugging = pyqtSignal(bool) - - _frames: List[FrameType] - _stop_debugging: bool - - def __init__(self, parent): - - super(Debugger, self).__init__(parent) - ComponentMixin.__init__(self) - - self.inner_event_loop = QEventLoop(self) - - self._actions = { - "Run": [ - QAction( - icon("run"), "Render", self, shortcut="F5", triggered=self.render - ), - QAction( - icon("debug"), - "Debug", - self, - checkable=True, - shortcut="ctrl+F5", - triggered=self.debug, - ), - QAction( - icon("arrow-step-over"), - "Step", - self, - shortcut="ctrl+F10", - triggered=lambda: self.debug_cmd(DbgState.STEP), - ), - QAction( - icon("arrow-step-in"), - "Step in", - self, - shortcut="ctrl+F11", - triggered=lambda: self.debug_cmd(DbgState.STEP_IN), - ), - QAction( - icon("arrow-continue"), - "Continue", - self, - shortcut="ctrl+F12", - triggered=lambda: self.debug_cmd(DbgState.CONT), - ), - ] - } - - self._frames = [] - self._stop_debugging = False - - def get_current_script(self): - - return self.parent().components["editor"].get_text_with_eol() - - def get_current_script_path(self): - - filename = self.parent().components["editor"].filename - if filename: - return Path(filename).absolute() - - def get_breakpoints(self): - - return self.parent().components["editor"].debugger.get_breakpoints() - - def set_breakpoints(self, breakpoints): - return self.parent().components["editor"].debugger.set_breakpoints(breakpoints) - - def compile_code(self, cq_script, cq_script_path=None): - - try: - module = ModuleType("__cq_main__") - if cq_script_path: - module.__dict__["__file__"] = cq_script_path - cq_code = compile(cq_script, DUMMY_FILE, "exec") - return cq_code, module - except Exception: - self.sigTraceback.emit(sys.exc_info(), cq_script) - return None, None - - def _exec(self, code, locals_dict, globals_dict): - - with ExitStack() as stack: - p = (self.get_current_script_path() or Path("")).absolute().dirname() - - if self.preferences["Add script dir to path"] and p.exists(): - sys.path.insert(0, p) - stack.callback(sys.path.remove, p) - if self.preferences["Change working dir to script dir"] and p.exists(): - stack.enter_context(p) - if self.preferences["Reload imported modules"]: - stack.enter_context(module_manager()) - - exec(code, locals_dict, globals_dict) - - @staticmethod - def _rand_color(alpha=0.0, cfloat=False): - # helper function to generate a random color dict - # for CQ-editor's show_object function - lower = 10 - upper = 100 # not too high to keep color brightness in check - if cfloat: # for two output types depending on need - return ( - (rrr(lower, upper) / 255), - (rrr(lower, upper) / 255), - (rrr(lower, upper) / 255), - alpha, - ) - return { - "alpha": alpha, - "color": ( - rrr(lower, upper), - rrr(lower, upper), - rrr(lower, upper), - ), - } - - def _inject_locals(self, module): - - cq_objects = {} - - def _show_object(obj, name=None, options={}): - - if name: - cq_objects.update({name: SimpleNamespace(shape=obj, options=options)}) - else: - # get locals of the enclosing scope - d = currentframe().f_back.f_locals - - # try to find the name - try: - name = list(d.keys())[list(d.values()).index(obj)] - except ValueError: - # use id if not found - name = str(id(obj)) - - cq_objects.update({name: SimpleNamespace(shape=obj, options=options)}) - - def _debug(obj, name=None): - - _show_object(obj, name, options=dict(color="red", alpha=0.2)) - - module.__dict__["show_object"] = _show_object - module.__dict__["debug"] = _debug - module.__dict__["rand_color"] = self._rand_color - module.__dict__["log"] = lambda x: info(str(x)) - module.__dict__["cq"] = cq - - return cq_objects, set(module.__dict__) - {"cq"} - - def _cleanup_locals(self, module, injected_names): - - for name in injected_names: - module.__dict__.pop(name) - - @pyqtSlot(bool) - def render(self): - - seed(59798267586177) - if self.preferences["Reload CQ"]: - reload_cq() - - cq_script = self.get_current_script() - cq_script_path = self.get_current_script_path() - cq_code, module = self.compile_code(cq_script, cq_script_path) - - if cq_code is None: - return - - cq_objects, injected_names = self._inject_locals(module) - - try: - self._exec(cq_code, module.__dict__, module.__dict__) - - # remove the special methods - self._cleanup_locals(module, injected_names) - - # collect all CQ objects if no explicit show_object was called - if len(cq_objects) == 0: - cq_objects = find_cq_objects(module.__dict__) - self.sigRendered.emit(cq_objects) - self.sigTraceback.emit(None, cq_script) - self.sigLocals.emit(module.__dict__) - except Exception: - exc_info = sys.exc_info() - sys.last_traceback = exc_info[-1] - self.sigTraceback.emit(exc_info, cq_script) - - @property - def breakpoints(self): - return [el[0] for el in self.get_breakpoints()] - - @pyqtSlot(bool) - def debug(self, value): - - # used to stop the debugging session early - self._stop_debugging = False - - if value: - self.previous_trace = previous_trace = sys.gettrace() - - self.sigDebugging.emit(True) - self.state = DbgState.CONT - - self.script = self.get_current_script() - cq_script_path = self.get_current_script_path() - code, module = self.compile_code(self.script, cq_script_path) - - if code is None: - self.sigDebugging.emit(False) - self._actions["Run"][1].setChecked(False) - return - - cq_objects, injected_names = self._inject_locals(module) - - # clear possible traceback - self.sigTraceback.emit(None, self.script) - - try: - sys.settrace(self.trace_callback) - exec(code, module.__dict__, module.__dict__) - except BdbQuit: - pass - except Exception: - exc_info = sys.exc_info() - sys.last_traceback = exc_info[-1] - self.sigTraceback.emit(exc_info, self.script) - finally: - sys.settrace(previous_trace) - self.sigDebugging.emit(False) - self._actions["Run"][1].setChecked(False) - - if len(cq_objects) == 0: - cq_objects = find_cq_objects(module.__dict__) - self.sigRendered.emit(cq_objects) - - self._cleanup_locals(module, injected_names) - self.sigLocals.emit(module.__dict__) - - self._frames = [] - self.inner_event_loop.exit(0) - else: - self._stop_debugging = True - self.inner_event_loop.exit(0) - - def debug_cmd(self, state=DbgState.STEP): - - self.state = state - self.inner_event_loop.exit(0) - - def trace_callback(self, frame, event, arg): - - filename = frame.f_code.co_filename - - if filename == DUMMY_FILE: - if not self._frames: - self._frames.append(frame) - self.trace_local(frame, event, arg) - return self.trace_callback - - else: - return None - - def trace_local(self, frame, event, arg): - - lineno = frame.f_lineno - - if event in (DbgEevent.LINE,): - if ( - self.state in (DbgState.STEP, DbgState.STEP_IN) - and frame is self._frames[-1] - ) or (lineno in self.get_breakpoints()): - - if lineno in self.get_breakpoints(): - self._frames.append(frame) - - self.sigLineChanged.emit(lineno) - self.sigFrameChanged.emit(frame) - self.sigLocalsChanged.emit(frame.f_locals) - self.sigCQChanged.emit(find_cq_objects(frame.f_locals), True) - - self.inner_event_loop.exec_() - - elif event in (DbgEevent.RETURN): - self.sigLocalsChanged.emit(frame.f_locals) - self._frames.pop() - - elif event == DbgEevent.CALL: - func_filename = frame.f_code.co_filename - if self.state == DbgState.STEP_IN and func_filename == DUMMY_FILE: - self.sigLineChanged.emit(lineno) - self.sigFrameChanged.emit(frame) - self.state = DbgState.STEP - self._frames.append(frame) - - if self._stop_debugging: - raise BdbQuit # stop debugging if requested - - -@contextmanager -def module_manager(): - """unloads any modules loaded while the context manager is active""" - loaded_modules = set(sys.modules.keys()) - - try: - yield - finally: - new_modules = set(sys.modules.keys()) - loaded_modules - for module_name in new_modules: - del sys.modules[module_name] diff --git a/cq_editor/widgets/editor.py b/cq_editor/widgets/editor.py deleted file mode 100644 index 0f45c7480..000000000 --- a/cq_editor/widgets/editor.py +++ /dev/null @@ -1,611 +0,0 @@ -import os - -# import spyder.utils.encoding -from modulefinder import ModuleFinder - -from .code_editor import CodeEditor - -from PyQt5.QtCore import pyqtSignal, QFileSystemWatcher, QTimer, Qt, QEvent -from PyQt5.QtWidgets import ( - QAction, - QFileDialog, - QApplication, - QListWidget, - QListWidgetItem, - QShortcut, -) -from PyQt5.QtGui import ( - QFontDatabase, - QTextCursor, - QKeyEvent, -) -from path import Path - -import sys - -import jedi - -from pyqtgraph.parametertree import Parameter - -from ..mixins import ComponentMixin -from ..utils import get_save_filename, get_open_filename, confirm -from .pyhighlight import PythonHighlighter - -from ..icons import icon - - -class EditorDebugger: - def __init__(self): - self.breakpoints = [] - self.current_debug_line = None - - def get_breakpoints(self): - return self.breakpoints - - def set_breakpoints(self, breakpoints): - self.breakpoints = breakpoints - return True - - -class Editor(CodeEditor, ComponentMixin): - - name = "Code Editor" - - # This signal is emitted whenever the currently-open file changes and - # autoreload is enabled. - triggerRerender = pyqtSignal(bool) - sigFilenameChanged = pyqtSignal(str) - statusChanged = pyqtSignal(str) - - preferences = Parameter.create( - name="Preferences", - children=[ - {"name": "Font size", "type": "int", "value": 12}, - {"name": "Autoreload", "type": "bool", "value": False}, - {"name": "Autoreload delay", "type": "int", "value": 50}, - { - "name": "Autoreload: watch imported modules", - "type": "bool", - "value": False, - }, - {"name": "Line wrap", "type": "bool", "value": False}, - { - "name": "Color scheme", - "type": "list", - "values": ["Light", "Dark"], - "value": "Light", - }, - {"name": "Maximum line length", "type": "int", "value": 79}, - ], - ) - - EXTENSIONS = "py" - - # Tracks whether or not the document was saved from the internal editor vs an external editor - was_modified_by_self = False - - # Set to True when a file was loaded from the examples directory; causes - # Save to redirect to Save As so the originals are never overwritten. - _is_example = False - - # Helps display the completion list for the editor - completion_list = None - - def __init__(self, parent=None): - - self._watched_file = None - - self.debugger = EditorDebugger() - - super(Editor, self).__init__(parent) - ComponentMixin.__init__(self) - - self.setup_editor( - line_numbers=True, - markers=True, - edge_line=self.preferences["Maximum line length"], - tab_mode=False, - show_blanks=True, - font=QFontDatabase.systemFont(QFontDatabase.FixedFont), - language="Python", - filename="", - ) - - self._actions = { - "File": [ - QAction( - icon("new"), "New", self, shortcut="ctrl+N", triggered=self.new - ), - QAction( - icon("open"), "Open", self, shortcut="ctrl+O", triggered=self.open - ), - QAction( - icon("save"), "Save", self, shortcut="ctrl+S", triggered=self.save - ), - QAction( - icon("save_as"), - "Save as", - self, - shortcut="ctrl+shift+S", - triggered=self.save_as, - ), - QAction( - icon("autoreload"), - "Automatic reload and preview", - self, - triggered=self.autoreload, - checkable=True, - checked=False, - objectName="autoreload", - ), - ] - } - - for a in self._actions.values(): - self.addActions(a) - - self._fixContextMenu() - - # autoreload support - self._file_watcher = QFileSystemWatcher(self) - # we wait for 50ms after a file change for the file to be written completely - self._file_watch_timer = QTimer(self) - self._file_watch_timer.setInterval(self.preferences["Autoreload delay"]) - self._file_watch_timer.setSingleShot(True) - self._file_watcher.fileChanged.connect( - lambda val: self._file_watch_timer.start() - ) - self._file_watch_timer.timeout.connect(self._file_changed) - - self.updatePreferences() - - # Create a floating list widget for completions - self.completion_list = QListWidget(self) - self.completion_list.setWindowFlags(Qt.Popup) - self.completion_list.setFocusPolicy(Qt.NoFocus) - self.completion_list.hide() - - # Connect the completion list to the editor - self.completion_list.itemClicked.connect(self.insert_completion) - - # Ensure that when the escape key is pressed with the completion_list in focus, it will be hidden - self.completion_list.installEventFilter(self) - - self.highlighter = PythonHighlighter(self.document()) - - def eventFilter(self, watched, event): - """ - Allows us to do things like escape and tab key press for the completion list. - """ - - if watched == self.completion_list and event.type() == QEvent.KeyPress: - key_event = QKeyEvent(event) - # Handle the escape key press - if key_event.key() == Qt.Key_Escape: - if self.completion_list and self.completion_list.isVisible(): - self.completion_list.hide() - return True # Event handled - # Handle the tab key press - elif key_event.key() == Qt.Key_Tab: - if self.completion_list and self.completion_list.isVisible(): - self.insert_completion(self.completion_list.currentItem()) - return True # Event handled - elif key_event.key() == Qt.Key_Return: - if self.completion_list and self.completion_list.isVisible(): - self.insert_completion(self.completion_list.currentItem()) - return True # Event handled - - # Let the event propagate to the editor - return False - - # Let the event propagate to the editor - return False - - def _fixContextMenu(self): - - menu = self.menu - - # menu.removeAction(self.run_cell_action) - # menu.removeAction(self.run_cell_and_advance_action) - # menu.removeAction(self.run_selection_action) - # menu.removeAction(self.re_run_last_cell_action) - - def updatePreferences(self, *args): - - self.set_color_scheme(self.preferences["Color scheme"]) - - font = self.font - font.setPointSize(self.preferences["Font size"]) - self.set_font(font) - - self.findChild(QAction, "autoreload").setChecked(self.preferences["Autoreload"]) - - self._file_watch_timer.setInterval(self.preferences["Autoreload delay"]) - - self.toggle_wrap_mode(self.preferences["Line wrap"]) - - # Update the edge line (maximum line length) - self.edge_line.set_enabled(True) - self.edge_line.set_columns(self.preferences["Maximum line length"]) - - self._clear_watched_paths() - self._watch_paths() - - def confirm_discard(self): - - if self.modified: - rv = confirm( - self, - "Please confirm", - "Current document is not saved - do you want to continue?", - ) - else: - rv = True - - return rv - - def new(self): - - if not self.confirm_discard(): - return - - self.set_text("") - self.filename = "" - self.reset_modified() - - def open(self): - - if not self.confirm_discard(): - return - - curr_dir = Path(self.filename).absolute().dirname() - fname = get_open_filename(self.EXTENSIONS, curr_dir) - if fname != "": - self.load_from_file(fname) - - def load_from_file(self, fname): - - self.set_text_from_file(fname) - self.filename = fname - self._is_example = False - self.reset_modified() - - def load_example(self, fname): - """Load a file from the examples directory. - - Identical to load_from_file except it marks the buffer as an example - so that Save redirects to Save As, keeping the originals intact. - """ - self.load_from_file(fname) - self._is_example = True - - def save(self): - """ - Saves the current document to the current filename if it exists, otherwise it triggers a - save-as dialog. - """ - - if self._filename != "": - if self._is_example: - self.statusChanged.emit( - "Examples are read-only — choose a new location to save your changes" - ) - self.save_as() - return - - with open(self._filename, "w", encoding="utf-8", newline="") as f: - f.write(self.toPlainText().replace("\n", self._eol)) - - # Let the editor and the rest of the app know that the file is no longer dirty - self.reset_modified() - - self.was_modified_by_self = True - - else: - self.save_as() - - def save_as(self): - - fname = get_save_filename(self.EXTENSIONS) - if fname != "": - with open(fname, "w", encoding="utf-8", newline="") as f: - f.write(self.toPlainText().replace("\n", self._eol)) - self.filename = fname - self._is_example = False - - self.reset_modified() - - def toggle_comment(self): - """ - Allows us to mark the document as modified when the user toggles a comment. - """ - super(Editor, self).toggle_comment() - self.document().setModified(True) - - def _update_filewatcher(self): - if self._watched_file and ( - self._watched_file != self.filename or not self.preferences["Autoreload"] - ): - self._clear_watched_paths() - self._watched_file = None - if ( - self.preferences["Autoreload"] - and self.filename - and self.filename != self._watched_file - ): - self._watched_file = self._filename - self._watch_paths() - - @property - def filename(self): - return self._filename - - @filename.setter - def filename(self, fname): - self._filename = fname - self._update_filewatcher() - self.sigFilenameChanged.emit(fname) - - def _clear_watched_paths(self): - paths = self._file_watcher.files() - if paths: - self._file_watcher.removePaths(paths) - - def _watch_paths(self): - if Path(self._filename).exists(): - self._file_watcher.addPath(self._filename) - if self.preferences["Autoreload: watch imported modules"]: - module_paths = self.get_imported_module_paths(self._filename) - if module_paths: - self._file_watcher.addPaths(module_paths) - - def _trigger_autocomplete(self): - """ - Allows the user to ask for autocomplete suggestions. - """ - - # Clear the status bar - self.statusChanged.emit("") - - # Track whether or not there are any completions to show - completions_present = False - - script = jedi.Script(self.toPlainText(), path=self.filename) - - # Clear the completion list - self.completion_list.clear() - - # Check to see if the character before the cursor is an open parenthesis - cursor_pos = self.textCursor().position() - text_before_cursor = self.toPlainText()[:cursor_pos] - text_after_cursor = self.toPlainText()[cursor_pos:] - if text_before_cursor.endswith("("): - # If there is a trailing close parentheis after the cursor, remove it - if text_after_cursor.startswith(")"): - self.textCursor().deleteChar() - - # Update the script with the modified text - script = jedi.Script(self.toPlainText(), path=self.filename) - - # Check if there are any function signatures - signatures = script.get_signatures() - if signatures: - # Let the rest of the code know that there was a completion - completions_present = True - - # Load the signatures into the completion list - for signature in signatures: - # Build a human-readable signature - i = 0 - cur_signature = f"{signature.name}(" - for param in signature.params: - # Prevent trailing comma in parameter list - param_ending = "," - if i == len(signature.params) - 1: - param_ending = "" - - # If the parameter is optional, do not overload the user with it - if "Optional" in param.description: - i += 1 - continue - - if "=" in param.description: - cur_signature += f"{param.name}={param.description.split('=')[1].strip()}{param_ending}" - else: - cur_signature += f"{param.name}{param_ending}" - i += 1 - cur_signature += ")" - - # Add the current signature to the list - item = QListWidgetItem(cur_signature) - self.completion_list.addItem(item) - else: - completions = script.complete() - if completions: - # Let the rest of the code know that there was a completion - completions_present = True - - # Add completions to the list - for completion in completions: - item = QListWidgetItem(completion.name) - self.completion_list.addItem(item) - - # Only show the completions list if there were any - if completions_present: - # Position the list near the cursor - cursor_rect = self.cursorRect() - global_pos = self.mapToGlobal(cursor_rect.bottomLeft()) - self.completion_list.move(global_pos) - - # Show the completion list - self.completion_list.show() - - # Select the first item in the list - self.completion_list.setCurrentRow(0) - else: - # Let the user know that no completions are available - self.statusChanged.emit("No completions available") - - def insert_completion(self, item): - """ - Inserts the selected completion into the editor. - """ - - # If there is an open parenthesis before the cursor, replace it with the completion - if ( - self.textCursor().position() > 0 - and self.toPlainText()[self.textCursor().position() - 1] == "(" - ): - cursor = self.textCursor() - cursor.setPosition(cursor.position() - 1) - cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) - cursor.removeSelectedText() - - # Find the last period in the text - text_before_cursor = self.toPlainText()[: self.textCursor().position()] - last_period_index = text_before_cursor.rfind(".") - - # Move the cursor to just after the last period position - cursor = self.textCursor() - cursor.setPosition(last_period_index + 1) - - # Remove text after last period - cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) - cursor.removeSelectedText() - - # Insert the completion text - cursor.insertText(item.text()) - self.setTextCursor(cursor) - - # Hide the completion list - self.completion_list.hide() - - # callback triggered by QFileSystemWatcher - def _file_changed(self): - # neovim writes a file by removing it first so must re-add each time - self._watch_paths() - - # QFileSystemWater reports deletions as changes - if not Path(self._filename).exists(): - return - - # Save the current cursor position and selection - cursor = self.textCursor() - cursor_position = cursor.position() - anchor_position = cursor.anchor() - - # Save the current scroll position - vertical_scroll_pos = self.verticalScrollBar().value() - horizontal_scroll_pos = self.horizontalScrollBar().value() - - # Block signals to avoid reset issues - self.blockSignals(True) - - # Read the contents of the file into a string - with open(self._filename, "r", encoding="utf-8") as f: - file_contents = f.read() - - # Insert new text while preserving history - cursor = self.textCursor() - cursor.select(QTextCursor.Document) - cursor.insertText(file_contents) - - # The editor will not always update after a text insertion, so we force it - QApplication.processEvents() - - # Stop blocking signals - self.blockSignals(False) - - self.document().setModified(True) - - # Undo has to be backed up one step to compensate for the text insertion - if self.was_modified_by_self: - self.document().undo() - self.was_modified_by_self = False - - # Restore the cursor position and selection - cursor.setPosition(anchor_position) - cursor.setPosition(cursor_position, QTextCursor.KeepAnchor) - self.setTextCursor(cursor) - - # Restore the scroll position - self.verticalScrollBar().setValue(vertical_scroll_pos) - self.horizontalScrollBar().setValue(horizontal_scroll_pos) - - # Reset the dirty state and trigger a 3D render - self.reset_modified() - self.triggerRerender.emit(True) - - # Turn autoreload on/off. - def autoreload(self, enabled): - self.preferences["Autoreload"] = enabled - self._update_filewatcher() - - def reset_modified(self): - - self.document().setModified(False) - - @property - def modified(self): - - return self.document().isModified() - - def saveComponentState(self, store): - - if self.filename != "": - store.setValue(self.name + "/state", self.filename) - - def restoreComponentState(self, store): - - filename = store.value(self.name + "/state") - - if filename and self.filename == "": - try: - self.load_from_file(filename) - except IOError: - self._logger.warning(f"could not open {filename}") - - def get_imported_module_paths(self, module_path): - - finder = ModuleFinder([os.path.dirname(module_path)]) - imported_modules = [] - - try: - finder.run_script(module_path) - except SyntaxError as err: - self._logger.warning(f"Syntax error in {module_path}: {err}") - except Exception as err: - # Suppress PyInstaller-specific module finder error - if ( - getattr(sys, "frozen", False) - and isinstance(err, AttributeError) - and "is_package" in str(err) - ): - pass - # The module finder has trouble when CadQuery is imported in the top level script and in - # imported modules. The warning about it can be ignored. - elif "cadquery" not in finder.badmodules or ( - "cadquery" in finder.badmodules and len(finder.badmodules) > 1 - ): - self._logger.warning( - f"Cannot determine imported modules in {module_path}: {type(err).__name__} {err}" - ) - else: - for module_name, module in finder.modules.items(): - if module_name != "__main__": - path = getattr(module, "__file__", None) - if path is not None and os.path.isfile(path): - imported_modules.append(path) - - return imported_modules - - -if __name__ == "__main__": - - from PyQt5.QtWidgets import QApplication - - app = QApplication(sys.argv) - editor = Editor() - editor.show() - - sys.exit(app.exec_()) diff --git a/cq_editor/widgets/log.py b/cq_editor/widgets/log.py deleted file mode 100644 index 1e9dd911f..000000000 --- a/cq_editor/widgets/log.py +++ /dev/null @@ -1,102 +0,0 @@ -import logbook as logging -import re - -from PyQt5 import QtGui -from PyQt5.QtCore import QObject, pyqtSignal -from PyQt5.QtWidgets import QPlainTextEdit, QAction - -from ..mixins import ComponentMixin - -from ..icons import icon - - -def strip_escape_sequences(input_string): - # Regular expression pattern to match ANSI escape codes - escape_pattern = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]") - - # Use re.sub to replace escape codes with an empty string - clean_string = re.sub(escape_pattern, "", input_string) - - return clean_string - - -class _QtLogHandlerQObject(QObject): - sigRecordEmit = pyqtSignal(str) - - -class QtLogHandler(logging.Handler, logging.StringFormatterHandlerMixin): - - def __init__(self, log_widget, *args, **kwargs): - - super(QtLogHandler, self).__init__(*args, **kwargs) - - log_format_string = ( - "[{record.time:%H:%M:%S%z}] {record.level_name}: {record.message}" - ) - - logging.StringFormatterHandlerMixin.__init__(self, log_format_string) - - self._qobject = _QtLogHandlerQObject() - self._qobject.sigRecordEmit.connect(log_widget.append) - self._is_closed = False - - def emit(self, record): - # Skip emit if handler has been closed - if self._is_closed or self._qobject is None: - # No-op when Qt side is no longer valid - return - - # Protect signal emission against Qt object lifetime race at shutdown - try: - self._qobject.sigRecordEmit.emit(self.format(record) + "\n") - # Catch wrapped C/C++ deletion error during teardown - except RuntimeError: - # Mark handler closed so future emits are ignored - self._is_closed = True - # Drop QObject reference to avoid further access - self._qobject = None - - # Explicit close hook to safely disable handler at teardown - def close(self): - # Mark handler as closed - self._is_closed = True - # Release QObject reference - self._qobject = None - # Preserve base class close behavior - super(QtLogHandler, self).close() - - -class LogViewer(QPlainTextEdit, ComponentMixin): - - name = "Log viewer" - - def __init__(self, *args, **kwargs): - - super(LogViewer, self).__init__(*args, **kwargs) - self._MAX_ROWS = 500 - - self._actions = { - "Run": [ - QAction(icon("clear"), "Clear Log", self, triggered=self.clear), - ] - } - - self.setReadOnly(True) - self.setMaximumBlockCount(self._MAX_ROWS) - self.setLineWrapMode(QPlainTextEdit.NoWrap) - - self.handler = QtLogHandler(self) - - # Ensure handler is closed when widget is destroyed - self.destroyed.connect(lambda *_: self.handler.close()) - - def append(self, msg): - """Append text to the panel with ANSI escape sequences stipped.""" - self.moveCursor(QtGui.QTextCursor.End) - self.insertPlainText(strip_escape_sequences(msg)) - - def clear_log(self): - """ - Clear the log content. - """ - self.clear() diff --git a/cq_editor/widgets/navigation_cube.py b/cq_editor/widgets/navigation_cube.py deleted file mode 100644 index 41445340e..000000000 --- a/cq_editor/widgets/navigation_cube.py +++ /dev/null @@ -1,148 +0,0 @@ -from math import cos, radians, sin - -from PyQt5.QtCore import QRect - -from OCP.AIS import AIS_Shape, AIS_ViewCube -from OCP.Aspect import Aspect_TOTP_RIGHT_UPPER -from OCP.BRepBuilderAPI import BRepBuilderAPI_MakeFace, BRepBuilderAPI_MakePolygon -from OCP.gp import gp_Pnt -from OCP.Graphic3d import ( - Graphic3d_TransformPers, - Graphic3d_TMF_2d, - Graphic3d_TMF_TriedronPers, - Graphic3d_TypeOfShadingModel, - Graphic3d_Vec2i, - Graphic3d_ZLayerId_Topmost, -) -from OCP.Font import Font_FontAspect -from OCP.Quantity import Quantity_Color, Quantity_TOC_RGB - -CORNER_OFFSET = 85 -SIZE = 55 -FACET_EXTENSION = 13 -EDGE_MIN_SIZE = 6 -CORNER_MIN_SIZE = 6 -FONT_HEIGHT = 14 -ANIMATION_DURATION = 0.25 - -ARROW_COLOR = Quantity_Color(0.72, 0.72, 0.75, Quantity_TOC_RGB) -ARROW_HILIGHT_COLOR = Quantity_Color(0.0, 1.0, 1.0, Quantity_TOC_RGB) -ARROW_INNER_RADIUS = 58 -ARROW_OUTER_RADIUS = 69 -ARROW_TAIL_ANGLE = 74 # degrees from screen-x, where the arc starts -ARROW_HEAD_ANGLE = 50 # degrees, where the head base sits -ARROW_TIP_SWEEP = 13 # degrees swept by the head triangle -ARROW_HEAD_OVERHANG = 6 # px the head base juts beyond the band -ARC_SEGMENTS = 12 - - -class NavigationCube(AIS_ViewCube): - """FreeCAD-style navigation cube. - - Transform-persistent overlay in the upper-right corner of the view: it - is rendered by the main camera, so it always reflects the current - orientation, keeps a constant screen size and is unaffected by zoom. - Faces, edges and corners are pickable; a click starts the built-in - eased camera animation (projection preserved; the owning widget - restores zoom and center, and drives frames via UpdateAnimation()). - """ - - def __init__(self): - - super().__init__() - - self.SetTransformPersistence( - Graphic3d_TransformPers( - Graphic3d_TMF_TriedronPers, - Aspect_TOTP_RIGHT_UPPER, - Graphic3d_Vec2i(CORNER_OFFSET, CORNER_OFFSET), - ) - ) - # SetSize(..., True) auto-derives facet/font metrics, so the - # explicit overrides must come after it - self.SetSize(SIZE, True) - self.SetBoxFacetExtension(FACET_EXTENSION) - self.SetBoxEdgeMinSize(EDGE_MIN_SIZE) - self.SetBoxCornerMinSize(CORNER_MIN_SIZE) - self.SetFontHeight(FONT_HEIGHT) - self.Attributes().TextAspect().Aspect().SetTextFontAspect( - Font_FontAspect.Font_FontAspect_Bold - ) - self.SetBoxColor(Quantity_Color(0.72, 0.72, 0.75, Quantity_TOC_RGB)) - self.SetTextColor(Quantity_Color(0.0, 0.0, 0.0, Quantity_TOC_RGB)) - self.SetDrawAxes(False) - - self.SetDuration(ANIMATION_DURATION) - self.SetAutoStartAnimation(True) - self.SetFixedAnimationLoop(False) - - def hit_region(self, widget_width): - """Screen-space rectangle (widget coordinates) covering the cube.""" - - extent = 2 * CORNER_OFFSET - return QRect(widget_width - extent, 0, extent, extent) - - -class RotationArrow(AIS_Shape): - """Curved roll-arrow button drawn above the navigation cube. - - Screen-fixed 2D overlay (it does not rotate with the camera) anchored - at the cube's corner offset. Clicking it rolls the view by 45 degrees - around the screen-normal axis; `sense` (+1 left arrow, -1 right arrow) - selects the roll direction and mirrors the geometry. - """ - - def __init__(self, sense): - - self.sense = sense - super().__init__(self._make_face(sense)) - - self.SetTransformPersistence( - Graphic3d_TransformPers( - Graphic3d_TMF_2d, - Aspect_TOTP_RIGHT_UPPER, - Graphic3d_Vec2i(CORNER_OFFSET, CORNER_OFFSET), - ) - ) - self.SetColor(ARROW_COLOR) - self.SetZLayer(Graphic3d_ZLayerId_Topmost) - # unlit: a flat overlay button facing the camera head-on saturates - # to white under the headlight's specular otherwise - self.Attributes().ShadingAspect().Aspect().SetShadingModel( - Graphic3d_TypeOfShadingModel.Graphic3d_TypeOfShadingModel_Unlit - ) - - def set_hovered(self, hovered): - """Fill with the highlight color, like the cube's face hover. - - OCCT's dynamic-highlight presentation is coplanar with the arrow - face and loses the depth test (only its boundary shows), so the - hover feedback swaps the fill color instead. - """ - - self.SetColor(ARROW_HILIGHT_COLOR if hovered else ARROW_COLOR) - - @staticmethod - def _make_face(sense): - """Flat curved-arrow face in pixel units around the local origin.""" - - def polar(radius, angle): - # sense +1 mirrors the right-side arrow across the vertical - a = radians(180 - angle if sense > 0 else angle) - return gp_Pnt(radius * cos(a), radius * sin(a), 0) - - mid = (ARROW_INNER_RADIUS + ARROW_OUTER_RADIUS) / 2 - polygon = BRepBuilderAPI_MakePolygon() - - for i in range(ARC_SEGMENTS + 1): - step = (ARROW_HEAD_ANGLE - ARROW_TAIL_ANGLE) * i / ARC_SEGMENTS - polygon.Add(polar(ARROW_OUTER_RADIUS, ARROW_TAIL_ANGLE + step)) - polygon.Add(polar(ARROW_OUTER_RADIUS + ARROW_HEAD_OVERHANG, ARROW_HEAD_ANGLE)) - polygon.Add(polar(mid, ARROW_HEAD_ANGLE - ARROW_TIP_SWEEP)) - polygon.Add(polar(ARROW_INNER_RADIUS - ARROW_HEAD_OVERHANG, ARROW_HEAD_ANGLE)) - for i in range(ARC_SEGMENTS + 1): - step = (ARROW_TAIL_ANGLE - ARROW_HEAD_ANGLE) * i / ARC_SEGMENTS - polygon.Add(polar(ARROW_INNER_RADIUS, ARROW_HEAD_ANGLE + step)) - polygon.Close() - - return BRepBuilderAPI_MakeFace(polygon.Wire()).Face() diff --git a/cq_editor/widgets/object_tree.py b/cq_editor/widgets/object_tree.py deleted file mode 100644 index 1e216e73a..000000000 --- a/cq_editor/widgets/object_tree.py +++ /dev/null @@ -1,583 +0,0 @@ -from cadquery import Location, Assembly -from PyQt5.QtWidgets import ( - QTreeWidget, - QTreeWidgetItem, - QAction, - QMenu, - QWidget, - QAbstractItemView, -) -from PyQt5.QtCore import Qt, pyqtSlot, pyqtSignal - -from pyqtgraph.parametertree import Parameter, ParameterTree - -from OCP.AIS import AIS_Line -from OCP.Geom import Geom_CartesianPoint -from OCP.gp import gp_Pnt -from OCP.Bnd import Bnd_Box - -from ..mixins import ComponentMixin -from ..icons import icon -from ..cq_utils import ( - make_AIS, - export, - to_occ_color, - is_obj_empty, - get_occ_color, - set_color, - set_transparency, - to_compound, -) -from .viewer import DEFAULT_FACE_COLOR -from ..utils import splitter, layout, get_save_filename - -# Default size of the axis helper lines half-length -DEFAULT_AXIS_HALF_LEN = 100.0 - - -class TopTreeItem(QTreeWidgetItem): - - def __init__(self, *args, **kwargs): - - super(TopTreeItem, self).__init__(*args, **kwargs) - - -class ObjectTreeItem(QTreeWidgetItem): - - props = [ - {"name": "Name", "type": "str", "value": "", "readonly": True}, - # {"name": "Color", "type": "color", "value": "#f4a824"}, - # {"name": "Alpha", "type": "float", "value": 0, "limits": (0, 1), "step": 1e-1}, - {"name": "Visible", "type": "bool", "value": True}, - ] - - def __init__( - self, - name, - ais=None, - shape=None, - shape_display=None, - sig=None, - alpha=0.0, - color="#f4a824", - **kwargs, - ): - - super(ObjectTreeItem, self).__init__([name], **kwargs) - self.setFlags(self.flags() | Qt.ItemIsUserCheckable) - self.setCheckState(0, Qt.Checked) - - self.ais = ais - self.shape = shape - self.shape_display = shape_display - self.sig = sig - - self.properties = Parameter.create(name="Properties", children=self.props) - - self.properties["Name"] = name - # Alpha and Color from this panel fight with the options in show_object and so they are - # disabled for now until a better solution is found - # self.properties["Alpha"] = ais.Transparency() - # self.properties["Color"] = ( - # get_occ_color(ais) - # if ais and ais.HasColor() - # else get_occ_color(DEFAULT_FACE_COLOR) - # ) - self.properties.sigTreeStateChanged.connect(self.propertiesChanged) - - def propertiesChanged(self, properties, changed): - - changed_prop = changed[0][0] - - self.setData(0, 0, self.properties["Name"]) - - # if changed_prop.name() == "Alpha": - # self.ais.SetTransparency(self.properties["Alpha"]) - - # if changed_prop.name() == "Color": - # set_color(self.ais, to_occ_color(self.properties["Color"])) - - # self.ais.Redisplay() - - if self.properties["Visible"]: - self.setCheckState(0, Qt.Checked) - else: - self.setCheckState(0, Qt.Unchecked) - - if self.sig: - self.sig.emit() - - -class CQRootItem(TopTreeItem): - - def __init__(self, *args, **kwargs): - - super(CQRootItem, self).__init__(["CQ models"], *args, **kwargs) - - -class HelpersRootItem(TopTreeItem): - - def __init__(self, *args, **kwargs): - - super(HelpersRootItem, self).__init__(["Helpers"], *args, **kwargs) - - -class ObjectTree(QWidget, ComponentMixin): - - name = "Object Tree" - _stash = [] - - preferences = Parameter.create( - name="Preferences", - children=[ - {"name": "Preserve properties on reload", "type": "bool", "value": False}, - {"name": "Clear all before each run", "type": "bool", "value": True}, - {"name": "Merge Assemblies", "type": "bool", "value": False}, - {"name": "STL precision", "type": "float", "value": 0.1}, - ], - ) - - sigObjectsAdded = pyqtSignal([list], [list, bool]) - sigObjectsRemoved = pyqtSignal(list) - sigCQObjectSelected = pyqtSignal(object) - sigAISObjectsSelected = pyqtSignal(list) - sigItemChanged = pyqtSignal(QTreeWidgetItem, int) - sigObjectPropertiesChanged = pyqtSignal() - sigHelpersResized = pyqtSignal(list) - - def __init__(self, parent): - - super(ObjectTree, self).__init__(parent) - - self.tree = tree = QTreeWidget( - self, selectionMode=QAbstractItemView.ExtendedSelection - ) - self.properties_editor = ParameterTree(self) - - tree.setHeaderHidden(True) - tree.setItemsExpandable(True) - tree.setRootIsDecorated(False) - tree.setContextMenuPolicy(Qt.ActionsContextMenu) - - # forward itemChanged singal - tree.itemChanged.connect(lambda item, col: self.sigItemChanged.emit(item, col)) - # handle visibility changes form tree - tree.itemChanged.connect(self.handleChecked) - - self.CQ = CQRootItem() - self.Helpers = HelpersRootItem() - - root = tree.invisibleRootItem() - root.addChild(self.CQ) - root.addChild(self.Helpers) - - tree.expandToDepth(1) - - self._export_STL_action = QAction( - "Export as STL", - self, - enabled=False, - triggered=lambda: self.export("stl", self.preferences["STL precision"]), - ) - - self._export_STEP_action = QAction( - "Export as STEP", self, enabled=False, triggered=lambda: self.export("step") - ) - - self._clear_current_action = QAction( - icon("delete"), - "Clear current", - self, - enabled=False, - triggered=self.removeSelected, - ) - - self._toolbar_actions = [ - QAction( - icon("delete-many"), "Clear all", self, triggered=self.removeObjects - ), - self._clear_current_action, - ] - - self.prepareMenu() - - tree.itemSelectionChanged.connect(self.handleSelection) - tree.customContextMenuRequested.connect(self.showMenu) - - self.prepareLayout() - - def _axis_points(self, direction, halfLen): - """Calculates the points needed to draw the axis helper lines""" - p1 = Geom_CartesianPoint(gp_Pnt(*(-halfLen * d for d in direction))) - p2 = Geom_CartesianPoint(gp_Pnt(*(halfLen * d for d in direction))) - - return p1, p2 - - def _rescale_helpers(self): - """Called to resize the axis helper lines to the model's bounding box.""" - - # Bounding box over all currently displayed CQ shapes - bbox = Bnd_Box() - for i in range(self.CQ.childCount()): - ais = self.CQ.child(i).ais - if ais is not None: - bbox.Add(ais.BoundingBox()) - - if bbox.IsVoid(): - halfLen = DEFAULT_AXIS_HALF_LEN - else: - halfLen = 2.0 * bbox.CornerMin().Distance(bbox.CornerMax()) - - resized = [] - for item, direction in self._helper_dirs: - p1, p2 = self._axis_points(direction, halfLen) - item.ais.SetPoints(p1, p2) # update geometry in place - resized.append(item.ais) - - if resized: - self.sigHelpersResized.emit(resized) - - def prepareMenu(self): - - self.tree.setContextMenuPolicy(Qt.CustomContextMenu) - - self._context_menu = QMenu(self) - self._context_menu.addActions(self._toolbar_actions) - self._context_menu.addActions( - (self._export_STL_action, self._export_STEP_action) - ) - - def prepareLayout(self): - - self._splitter = splitter( - (self.tree, self.properties_editor), - stretch_factors=(2, 1), - orientation=Qt.Vertical, - ) - layout(self, (self._splitter,), top_widget=self) - - self._splitter.show() - - def showMenu(self, position): - - self._context_menu.exec_(self.tree.viewport().mapToGlobal(position)) - - def menuActions(self): - - return {"Tools": [self._export_STL_action, self._export_STEP_action]} - - def toolbarActions(self): - - return self._toolbar_actions - - def addLines(self): - ais_list = [] - self._helper_dirs = [] # (item, direction) pairs, for later rescaling - - for name, color, direction in zip( - ("X", "Y", "Z"), - ("red", "lawngreen", "blue"), - ((1, 0, 0), (0, 1, 0), (0, 0, 1)), - ): - p1, p2 = self._axis_points(direction, DEFAULT_AXIS_HALF_LEN) - line = AIS_Line(p1, p2) - line.SetColor(to_occ_color(color)) - - item = ObjectTreeItem(name, ais=line) - self.Helpers.addChild(item) - self._helper_dirs.append((item, direction)) - - ais_list.append(line) - - self.sigObjectsAdded.emit(ais_list) - - def _item_path(self, item): - """Stable identity of an item across runs: names from the CQ root down.""" - parts = [] - node = item - while node is not None and node is not self.CQ: - parts.append(node.properties["Name"]) - node = node.parent() - return "/".join(reversed(parts)) - - def _current_properties(self): - """ - Snapshot every CQ item's properties before a reload, keyed by tree - path so nested parts that share a name do not collide. - """ - current_params = {} - for i in range(self.CQ.childCount()): - for it in self._iter_subtree(self.CQ.child(i)): - current_params[self._item_path(it)] = it.properties - - return current_params - - def _restore_properties(self, obj, properties): - """ - Re-apply a snapshot from _current_properties to obj and all its - descendants, matching items by tree path. - """ - for it in self._iter_subtree(obj): - key = self._item_path(it) - if key in properties: - for p in properties[key]: - it.properties[p.name()] = p.value() - - def _build_assembly_item( - self, node, label, options, parent_loc, inherited_color, ais_list - ): - """ - Recursively build the tree item for one assembly node, mirroring - the hierarchy. Accumulates world location and nearest-ancestor color. - """ - world = parent_loc * node.loc - color = node.color if node.color is not None else inherited_color - - ais = None - shape = None - if node.obj is not None: - # A node can have both a shape and children - shape = to_compound(node.obj).moved(world) - ais, _ = make_AIS(shape, options) - if color is not None: - r, g, b, a = color.toTuple() - set_color(ais, to_occ_color((r, g, b))) - set_transparency(ais, a) - ais_list.append(ais) - - item = ObjectTreeItem( - label, shape=shape, ais=ais, sig=self.sigObjectPropertiesChanged - ) - - for child in node.children: - item.addChild( - self._build_assembly_item( - child, child.name, options, world, color, ais_list - ) - ) - - if node.children: - item.setFlags(item.flags() | Qt.ItemIsAutoTristate) - - return item - - def _build_items(self, name, shape, options): - """ - Build the ObjectTreeItem(s) for one shown object. Assemblies explode - into one item per part. Everything else is one item. - """ - # Explode assemblies into per-part items - if isinstance(shape, Assembly) and not self.preferences["Merge Assemblies"]: - ais_list = [] - item = self._build_assembly_item( - shape, name, options, Location(), None, ais_list - ) - return [item], ais_list - - ais, shape_display = make_AIS(shape, options) - item = ObjectTreeItem( - name, - shape=shape, - shape_display=shape_display, - ais=ais, - sig=self.sigObjectPropertiesChanged, - ) - return [item], [ais] - - def _iter_subtree(self, item): - """Yield item and every descendant.""" - yield item - for i in range(item.childCount()): - yield from self._iter_subtree(item.child(i)) - - def _under_cq(self, item): - """True if item is anywhere beneath the CQ root (exluding Helpers).""" - p = item.parent() - while p is not None: - if p is self.CQ: - return True - p = p.parent() - return False - - def _subtree_ais(self, tops): - return [ - it.ais - for top in tops - for it in self._iter_subtree(top) - if it.ais is not None - ] - - @pyqtSlot(dict, bool) - @pyqtSlot(dict) - def addObjects(self, objects, clean=False, root=None): - - if root is None: - root = self.CQ - - request_fit_view = True if root.childCount() == 0 else False - preserve_props = self.preferences["Preserve properties on reload"] - - if preserve_props: - current_props = self._current_properties() - - if clean or self.preferences["Clear all before each run"]: - self.removeObjects() - - ais_list = [] - - # remove empty objects - objects_f = {k: v for k, v in objects.items() if not is_obj_empty(v.shape)} - - for name, obj in objects_f.items(): - top_items, obj_ais = self._build_items(name, obj.shape, obj.options) - for item in top_items: - if preserve_props and name in current_props: - self._restore_properties(item, current_props) - self.CQ.addChild(item) - self.tree.expandItem(item) - - ais_list.extend(obj_ais) - - if request_fit_view: - self.sigObjectsAdded[list, bool].emit(ais_list, True) - else: - self.sigObjectsAdded[list].emit(ais_list) - - self._rescale_helpers() - - @pyqtSlot(object, str, object) - def addObject(self, obj, name="", options=None): - - if options is None: - options = {} - - root = self.CQ - - top_items, ais_list = self._build_items(name, obj, options) - for item in top_items: - self.CQ.addChild(item) - self.sigObjectsAdded.emit(ais_list) - - @pyqtSlot(list) - @pyqtSlot() - def removeObjects(self, objects=None): - - taken = ( - [self.CQ.takeChild(i) for i in objects] - if objects - else self.CQ.takeChildren() - ) - removed_items_ais = [ - it.ais - for top in taken - for it in self._iter_subtree(top) - if it.ais is not None - ] - - self.sigObjectsRemoved.emit(removed_items_ais) - - @pyqtSlot(bool) - def stashObjects(self, action: bool): - - if action: - self._stash = self.CQ.takeChildren() - # removed_items_ais = [ch.ais for ch in self._stash] - removed_items_ais = self._subtree_ais(self._stash) - self.sigObjectsRemoved.emit(removed_items_ais) - else: - self.removeObjects() - self.CQ.addChildren(self._stash) - ais_list = self._subtree_ais(self._stash) - self.sigObjectsAdded.emit(ais_list) - - @pyqtSlot() - def removeSelected(self): - tops = [it for it in self.tree.selectedItems() if it.parent() is self.CQ] - removed_items_ais = self._subtree_ais(tops) - for it in tops: - self.CQ.removeChild(it) - self.sigObjectsRemoved.emit(removed_items_ais) - - def export(self, export_type, precision=None): - - items = self.tree.selectedItems() - - # If the CQ root is selected, take all top-level objects - if any(it is self.CQ for it in items): - roots = [self.CQ.child(i) for i in range(self.CQ.childCount())] - # Otherwise take every selected item anywhere under CQ - else: - roots = [it for it in items if self._under_cq(it)] - - seen = set() - shapes = [] - for r in roots: - for it in self._iter_subtree(r): - if it.shape is not None and id(it) not in seen: - seen.add(id(it)) - shapes.append(it.shape) - - fname = get_save_filename(export_type) - if fname != "": - export(shapes, export_type, fname, precision) - - @pyqtSlot() - def handleSelection(self): - - items = self.tree.selectedItems() - if len(items) == 0: - self._export_STL_action.setEnabled(False) - self._export_STEP_action.setEnabled(False) - return - - # emit list of all selected ais objects (might be empty) - # ais_objects = [item.ais for item in items if item.parent() is self.CQ] - ais_objects = [ - it.ais - for sel in items - if self._under_cq(sel) - for it in self._iter_subtree(sel) - if it.ais is not None - ] - self.sigAISObjectsSelected.emit(ais_objects) - - # Context menu + last-selected object - item = items[-1] - if self._under_cq(item): - self._export_STL_action.setEnabled(True) - self._export_STEP_action.setEnabled(True) - self._clear_current_action.setEnabled(True) - if item.shape is not None: - self.sigCQObjectSelected.emit(item.shape) - self.properties_editor.setParameters(item.properties, showTop=False) - self.properties_editor.setEnabled(True) - elif item is self.CQ and item.childCount() > 0: - self._export_STL_action.setEnabled(True) - self._export_STEP_action.setEnabled(True) - else: - self._export_STL_action.setEnabled(False) - self._export_STEP_action.setEnabled(False) - self._clear_current_action.setEnabled(False) - self.properties_editor.setEnabled(False) - self.properties_editor.clear() - - @pyqtSlot(list) - def handleGraphicalSelection(self, shapes): - - self.tree.clearSelection() - - for item in self._iter_subtree(self.CQ): - ais = getattr(item, "ais", None) - if ais is None: - continue - if any(ais.Shape().IsEqual(shape) for shape in shapes): - item.setSelected(True) - - @pyqtSlot(QTreeWidgetItem, int) - def handleChecked(self, item, col): - - if type(item) is ObjectTreeItem: - if item.checkState(0): - item.properties["Visible"] = True - else: - item.properties["Visible"] = False diff --git a/cq_editor/widgets/occt_widget.py b/cq_editor/widgets/occt_widget.py deleted file mode 100755 index 7f5917b6f..000000000 --- a/cq_editor/widgets/occt_widget.py +++ /dev/null @@ -1,434 +0,0 @@ -from math import pi -from sys import platform - - -from PyQt5.QtWidgets import QWidget, QApplication -from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QPoint, QTimer - -import OCP - -from OCP.Aspect import Aspect_DisplayConnection, Aspect_TypeOfTriedronPosition -from OCP.OpenGl import OpenGl_GraphicDriver -from OCP.V3d import V3d_Viewer -from OCP.gp import gp_Trsf, gp_Ax1, gp_Dir, gp_Pnt -from OCP.AIS import ( - AIS_AnimationCamera, - AIS_InteractiveContext, - AIS_DisplayMode, - AIS_ViewCubeOwner, -) -from OCP.Graphic3d import Graphic3d_Camera -from OCP.Quantity import Quantity_Color -from OCP.TCollection import TCollection_AsciiString - -from .navigation_cube import ANIMATION_DURATION, NavigationCube, RotationArrow - -ZOOM_STEP = 0.9 - - -class OCCTWidget(QWidget): - - sigObjectSelected = pyqtSignal(list) - - def __init__(self, parent=None): - - super(OCCTWidget, self).__init__(parent) - - self.setAttribute(Qt.WA_NativeWindow) - self.setAttribute(Qt.WA_PaintOnScreen) - self.setAttribute(Qt.WA_NoSystemBackground) - - self._initialized = False - self._needs_update = False - self._previous_pos = QPoint( - 0, 0 # Keeps track of where the previous mouse position - ) - self._rotate_step = ( - 0.008 # Controls the speed of rotation with the turntable orbit method - ) - - # Orbit method settings - self._orbit_method = "Turntable" - - # Drives the view cube and roll camera animations; runs only while - # animating - self._cube_timer = QTimer(self) - self._cube_timer.setInterval(16) - self._cube_timer.timeout.connect(self._animate_view_cube) - self._roll_animation = None - - self._cube_hover = False - self._hovered_arrow = None - self.setMouseTracking(True) - - # OCCT secific things - self.display_connection = Aspect_DisplayConnection() - self.graphics_driver = OpenGl_GraphicDriver(self.display_connection) - - self.viewer = V3d_Viewer(self.graphics_driver) - self.view = self.viewer.CreateView() - self.context = AIS_InteractiveContext(self.viewer) - - # Trihedorn, lights, etc - self.prepare_display() - - def prepare_display(self): - - view = self.view - - params = view.ChangeRenderingParams() - params.NbMsaaSamples = 8 - params.IsAntialiasingEnabled = True - - view.TriedronDisplay( - Aspect_TypeOfTriedronPosition.Aspect_TOTP_RIGHT_LOWER, Quantity_Color(), 0.1 - ) - - viewer = self.viewer - - viewer.SetDefaultLights() - viewer.SetLightOn() - - ctx = self.context - - ctx.SetDisplayMode(AIS_DisplayMode.AIS_Shaded, True) - ctx.DefaultDrawer().SetFaceBoundaryDraw(True) - - self.view_cube = NavigationCube() - self.view_cube.ViewAnimation().SetView(view) - ctx.Display(self.view_cube, False) - - self.rotate_arrows = (RotationArrow(1), RotationArrow(-1)) - for arrow in self.rotate_arrows: - ctx.Display(arrow, AIS_DisplayMode.AIS_Shaded, 0, False) - - def set_orbit_method(self, method): - """ - Set the orbit method for the OCCT view. - """ - - # Keep track of which orbit method is used - if method == "Turntable": - self._orbit_method = "Turntable" - self.view.SetUp(0, 0, 1) - elif method == "Trackball": - self._orbit_method = "Trackball" - else: - raise ValueError(f"Unknown orbit method: {method}") - - def wheelEvent(self, event): - - delta = event.angleDelta().y() - factor = ZOOM_STEP if delta < 0 else 1 / ZOOM_STEP - - self.view.SetZoom(factor) - - def mousePressEvent(self, event): - - pos = event.pos() - - if event.button() == Qt.LeftButton: - # Used to prevent drag selection of objects - self.pending_select = True - self.left_press = pos - - # We only start the rotation if the orbit method is set to Trackball - if self._orbit_method == "Trackball": - self.view.StartRotation(pos.x(), pos.y()) - elif event.button() == Qt.RightButton: - self.view.StartZoomAtPoint(pos.x(), pos.y()) - - self._previous_pos = pos - - def mouseMoveEvent(self, event): - - pos = event.pos() - x, y = pos.x(), pos.y() - - # Hover highlight is confined to the cube's corner region so the - # rest of the viewport keeps its existing no-hover behavior - if not event.buttons(): - if self.view_cube.hit_region(self.width()).contains(pos): - self.context.MoveTo(x, y, self.view, True) - owner = ( - self.context.DetectedOwner() if self.context.HasDetected() else None - ) - detected = self._detected_interactive() - if not isinstance(owner, AIS_ViewCubeOwner) and not isinstance( - detected, RotationArrow - ): - self.context.ClearDetected(True) - self._set_hovered_arrow( - detected if isinstance(detected, RotationArrow) else None - ) - self._cube_hover = True - elif self._cube_hover: - self.context.ClearDetected(True) - self._set_hovered_arrow(None) - self._cube_hover = False - self._previous_pos = pos - return - - # Check for mouse drag rotation - if event.buttons() == Qt.LeftButton and event.modifiers() not in ( - Qt.ShiftModifier, - Qt.ControlModifier, - ): - # Set the rotation differently based on the orbit method - if self._orbit_method == "Trackball": - self.view.Rotation(x, y) - elif self._orbit_method == "Turntable": - # Control the turntable rotation manually - delta_x, delta_y = ( - x - self._previous_pos.x(), - y - self._previous_pos.y(), - ) - cam = self.view.Camera() - z_rotation = gp_Trsf() - z_rotation.SetRotation( - gp_Ax1(cam.Center(), gp_Dir(0, 0, 1)), -delta_x * self._rotate_step - ) - cam.Transform(z_rotation) - self.view.Rotate(0, -delta_y * self._rotate_step, 0) - - # If the user moves the mouse at all, the selection will not happen - if event.buttons() == Qt.LeftButton: - if abs(x - self.left_press.x()) > 2 or abs(y - self.left_press.y()) > 2: - self.pending_select = False - - if event.buttons() == Qt.MiddleButton or ( - event.buttons() == Qt.LeftButton and event.modifiers() == Qt.ControlModifier - ): - self.view.Pan( - x - self._previous_pos.x(), self._previous_pos.y() - y, theToStart=True - ) - - elif event.buttons() == Qt.RightButton or ( - event.buttons() == Qt.LeftButton and event.modifiers() == Qt.ShiftModifier - ): - self.view.ZoomAtPoint(self._previous_pos.x(), y, x, self._previous_pos.y()) - - self._previous_pos = pos - - def mouseReleaseEvent(self, event): - - if event.button() == Qt.LeftButton: - pos = event.pos() - x, y = pos.x(), pos.y() - - # Only make the selection if the user has not moved the mouse - if self.pending_select: - self.context.MoveTo(x, y, self.view, True) - - owner = ( - self.context.DetectedOwner() if self.context.HasDetected() else None - ) - detected = self._detected_interactive() - if isinstance(owner, AIS_ViewCubeOwner): - self._handle_cube_click(owner) - elif isinstance(detected, RotationArrow): - self._handle_rotate_click(detected.sense) - else: - self._handle_selection() - - def _detected_interactive(self): - - if not self.context.HasDetected(): - return None - return self.context.DetectedInteractive() - - def _set_hovered_arrow(self, arrow): - - if arrow is self._hovered_arrow: - return - - if self._hovered_arrow is not None: - self._hovered_arrow.set_hovered(False) - self.context.Redisplay(self._hovered_arrow, False) - self._hovered_arrow = arrow - if arrow is not None: - arrow.set_hovered(True) - self.context.Redisplay(arrow, False) - - self.context.UpdateCurrentViewer() - - def _handle_selection(self): - - self.context.Select(True) - self.context.InitSelected() - - selected = [] - if self.context.HasSelectedShape(): - selected.append(self.context.SelectedShape()) - - self.sigObjectSelected.emit(selected) - - def _settle_animations(self): - """Snap any running camera animation to its end state. - - A click during a running animation must start from the settled end: - OCCT treats a repeated click on the current orientation specially - (snaps up to the canonical value), and that detection compares - against a partially-rotated camera otherwise. - """ - - self._cube_timer.stop() - - cube_animation = self.view_cube.ViewAnimation() - if not cube_animation.IsStopped(): - cube_animation.Stop() - self.view.Camera().Copy(cube_animation.CameraEnd()) - - if self._roll_animation is not None: - if not self._roll_animation.IsStopped(): - self._roll_animation.Stop() - self.view.Camera().Copy(self._roll_animation.CameraEnd()) - self._roll_animation = None - - def _handle_rotate_click(self, sense): - """Roll the view by 45 degrees around the screen-normal axis.""" - - self._settle_animations() - - camera = self.view.Camera() - end_camera = Graphic3d_Camera(camera) - roll = gp_Trsf() - roll.SetRotation( - gp_Ax1(end_camera.Center(), end_camera.Direction()), sense * pi / 4 - ) - end_camera.SetUp(end_camera.Up().Transformed(roll)) - - animation = AIS_AnimationCamera( - TCollection_AsciiString("navigation_roll"), self.view - ) - animation.SetCameraStart(Graphic3d_Camera(camera)) - animation.SetCameraEnd(end_camera) - animation.SetOwnDuration(ANIMATION_DURATION) - animation.StartTimer(0.0, 1.0, True) - - self._roll_animation = animation - self._cube_timer.start() - - def _handle_cube_click(self, owner): - """Start the animated camera reorientation for a picked cube part.""" - - self._settle_animations() - - camera = self.view.Camera() - center, distance, scale = camera.Center(), camera.Distance(), camera.Scale() - - self.view_cube.HandleClick(owner) - - # HandleClick fits the scene into the animation's target camera; - # restore the current framing so the click is a pure rotation that - # preserves zoom, center and distance. The eye is placed explicitly - # together with the old center: SetCenter alone would tilt the - # target direction after a pan, and MoveEyeTo alone would keep the - # fitted distance and drag the center along the view axis (visible - # as a zoom in perspective projection). - animation = self.view_cube.ViewAnimation() - self._restore_framing(animation.CameraEnd(), center, distance, scale) - - # with a zero duration the animation completes inside HandleClick, - # so the fitted end camera is already applied; restore the view - # camera directly in that case - if animation.IsStopped(): - self._restore_framing(self.view.Camera(), center, distance, scale) - self.view.Redraw() - - self._cube_timer.start() - - @staticmethod - def _restore_framing(camera, center, distance, scale): - """Re-frame a camera on center/distance/scale, keeping its direction.""" - - direction = camera.Direction() - camera.SetEyeAndCenter( - gp_Pnt( - center.X() - direction.X() * distance, - center.Y() - direction.Y() * distance, - center.Z() - direction.Z() * distance, - ), - center, - ) - camera.SetScale(scale) - - def _animate_view_cube(self): - - active = self.view_cube.UpdateAnimation(True) - - if self._roll_animation is not None: - self._roll_animation.UpdateTimer() - if self._roll_animation.ElapsedTime() >= ANIMATION_DURATION: - self._roll_animation.Stop() - self.view.Camera().Copy(self._roll_animation.CameraEnd()) - self._roll_animation = None - else: - active = True - self.view.Redraw() - - if not active: - self._cube_timer.stop() - # the finishing UpdateAnimation applies the end camera but only - # invalidates the view; without an explicit redraw the screen - # keeps the previous frame until an unrelated repaint - self.view.Redraw() - - def paintEngine(self): - - return None - - def paintEvent(self, event): - - if not self._initialized: - self._initialize() - else: - self.view.Redraw() - - def showEvent(self, event): - - super(OCCTWidget, self).showEvent(event) - - def resizeEvent(self, event): - - super(OCCTWidget, self).resizeEvent(event) - - self.view.MustBeResized() - - def leaveEvent(self, event): - - if self._cube_hover: - self.context.ClearDetected(True) - self._set_hovered_arrow(None) - self._cube_hover = False - - def _initialize(self): - - wins = { - "darwin": self._get_window_osx, - "linux": self._get_window_linux, - "win32": self._get_window_win, - } - - self.view.SetWindow(wins.get(platform, self._get_window_linux)(self.winId())) - - self._initialized = True - - def _get_window_win(self, wid): - - from OCP.WNT import WNT_Window - - return WNT_Window(wid.ascapsule()) - - def _get_window_linux(self, wid): - - # X11 only as OCCT currently doesn't have wayland support - from OCP.Xw import Xw_Window - - return Xw_Window(self.display_connection, int(wid)) - - def _get_window_osx(self, wid): - - from OCP.Cocoa import Cocoa_Window - - return Cocoa_Window(wid.ascapsule()) diff --git a/cq_editor/widgets/pyhighlight.py b/cq_editor/widgets/pyhighlight.py deleted file mode 100644 index 78a402615..000000000 --- a/cq_editor/widgets/pyhighlight.py +++ /dev/null @@ -1,247 +0,0 @@ -from PyQt5.QtCore import QRegExp -from PyQt5.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter - - -def format(color, style=""): - """ - Return a QTextCharFormat with the given attributes. - """ - _color = QColor() - _color.setNamedColor(color) - - _format = QTextCharFormat() - _format.setForeground(_color) - if "bold" in style: - _format.setFontWeight(QFont.Bold) - if "italic" in style: - _format.setFontItalic(True) - - return _format - - -# Syntax styles that can be shared by all languages -STYLES = { - "keyword": format("blue"), - "operator": format("gray"), - "brace": format("darkGray"), - "defclass": format("gray", "bold"), - "string": format("orange"), - "string2": format("darkMagenta"), - "comment": format("darkGreen", "italic"), - "self": format("blue", "italic"), - "numbers": format("magenta"), -} - - -class PythonHighlighter(QSyntaxHighlighter): - """ - Syntax highlighter for the Python language. - """ - - # Python keywords - keywords = [ - "and", - "assert", - "break", - "class", - "continue", - "def", - "del", - "elif", - "else", - "except", - "exec", - "finally", - "for", - "from", - "global", - "if", - "import", - "in", - "is", - "lambda", - "not", - "or", - "pass", - "print", - "raise", - "return", - "try", - "while", - "yield", - "None", - "True", - "False", - ] - - # Python operators - operators = [ - "=", - # Comparison - "==", - "!=", - "<", - "<=", - ">", - ">=", - # Arithmetic - r"\+", - "-", - r"\*", - "/", - "//", - r"\%", - r"\*\*", - # In-place - r"\+=", - "-=", - r"\*=", - "/=", - r"\%=", - # Bitwise - r"\^", - r"\|", - r"\&", - r"\~", - ">>", - "<<", - ] - - # Python braces - braces = [ - r"\{", - r"\}", - r"\(", - r"\)", - r"\[", - r"\]", - ] - - def __init__(self, parent=None): - super(PythonHighlighter, self).__init__(parent) - - # Multi-line strings (expression, flag, style) - self.tri_single = (QRegExp("'''"), 1, STYLES["string2"]) - self.tri_double = (QRegExp('"""'), 2, STYLES["string2"]) - - rules = [] - - # Keyword, operator, and brace rules - rules += [ - (r"\b%s\b" % w, 0, STYLES["keyword"]) for w in PythonHighlighter.keywords - ] - rules += [ - (r"%s" % o, 0, STYLES["operator"]) for o in PythonHighlighter.operators - ] - rules += [(r"%s" % b, 0, STYLES["brace"]) for b in PythonHighlighter.braces] - - # All other rules - rules += [ - # 'self' - (r"\bself\b", 0, STYLES["self"]), - # 'def' followed by an identifier - (r"\bdef\b\s*(\w+)", 1, STYLES["defclass"]), - # 'class' followed by an identifier - (r"\bclass\b\s*(\w+)", 1, STYLES["defclass"]), - # Numeric literals - (r"\b[+-]?[0-9]+[lL]?\b", 0, STYLES["numbers"]), - (r"\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b", 0, STYLES["numbers"]), - (r"\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b", 0, STYLES["numbers"]), - # Double-quoted string, possibly containing escape sequences - (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES["string"]), - # Single-quoted string, possibly containing escape sequences - (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES["string"]), - # From '#' until a newline - (r"#[^\n]*", 0, STYLES["comment"]), - ] - - # Build a QRegExp for each pattern - self.rules = [(QRegExp(pat), index, fmt) for (pat, index, fmt) in rules] - - def highlightBlock(self, text): - """ - Apply syntax highlighting to the given block of text. - """ - self.tripleQuoutesWithinStrings = [] - # Do other syntax formatting - for expression, nth, format in self.rules: - index = expression.indexIn(text, 0) - if index >= 0: - # if there is a string we check - # if there are some triple quotes within the string - # they will be ignored if they are matched again - if expression.pattern() in [ - r'"[^"\\]*(\\.[^"\\]*)*"', - r"'[^'\\]*(\\.[^'\\]*)*'", - ]: - innerIndex = self.tri_single[0].indexIn(text, index + 1) - if innerIndex == -1: - innerIndex = self.tri_double[0].indexIn(text, index + 1) - - if innerIndex != -1: - tripleQuoteIndexes = range(innerIndex, innerIndex + 3) - self.tripleQuoutesWithinStrings.extend(tripleQuoteIndexes) - - while index >= 0: - # skipping triple quotes within strings - if index in self.tripleQuoutesWithinStrings: - index += 1 - expression.indexIn(text, index) - continue - - # We actually want the index of the nth match - index = expression.pos(nth) - length = len(expression.cap(nth)) - self.setFormat(index, length, format) - index = expression.indexIn(text, index + length) - - self.setCurrentBlockState(0) - - # Do multi-line strings - in_multiline = self.match_multiline(text, *self.tri_single) - if not in_multiline: - in_multiline = self.match_multiline(text, *self.tri_double) - - def match_multiline(self, text, delimiter, in_state, style): - """ - Do highlighting of multi-line strings. ``delimiter`` should be a - ``QRegExp`` for triple-single-quotes or triple-double-quotes, and - ``in_state`` should be a unique integer to represent the corresponding - state changes when inside those strings. Returns True if we're still - inside a multi-line string when this function is finished. - """ - # If inside triple-single quotes, start at 0 - if self.previousBlockState() == in_state: - start = 0 - add = 0 - # Otherwise, look for the delimiter on this line - else: - start = delimiter.indexIn(text) - # skipping triple quotes within strings - if start in self.tripleQuoutesWithinStrings: - return False - # Move past this match - add = delimiter.matchedLength() - - # As long as there's a delimiter match on this line... - while start >= 0: - # Look for the ending delimiter - end = delimiter.indexIn(text, start + add) - # Ending delimiter on this line? - if end >= add: - length = end - start + add + delimiter.matchedLength() - self.setCurrentBlockState(0) - # No; multi-line string - else: - self.setCurrentBlockState(in_state) - length = len(text) - start + add - # Apply formatting - self.setFormat(start, length, style) - # Look for the next match - start = delimiter.indexIn(text, start + length) - - # Return True if still inside a multi-line string, False otherwise - if self.currentBlockState() == in_state: - return True - else: - return False diff --git a/cq_editor/widgets/traceback_viewer.py b/cq_editor/widgets/traceback_viewer.py deleted file mode 100644 index b02f378f2..000000000 --- a/cq_editor/widgets/traceback_viewer.py +++ /dev/null @@ -1,111 +0,0 @@ -from traceback import extract_tb, format_exception_only -from itertools import dropwhile - -from PyQt5.QtWidgets import QWidget, QTreeWidget, QTreeWidgetItem, QAction, QLabel -from PyQt5.QtCore import Qt, pyqtSlot, pyqtSignal -from PyQt5.QtGui import QFontMetrics - -from ..mixins import ComponentMixin -from ..utils import layout - - -class TracebackTree(QTreeWidget): - - name = "Traceback Viewer" - - def __init__(self, parent): - - super(TracebackTree, self).__init__(parent) - self.setHeaderHidden(False) - self.setItemsExpandable(False) - self.setRootIsDecorated(False) - self.setContextMenuPolicy(Qt.ActionsContextMenu) - - self.setColumnCount(3) - self.setHeaderLabels(["File", "Line", "Code"]) - - self.root = self.invisibleRootItem() - - -class TracebackPane(QWidget, ComponentMixin): - - sigHighlightLine = pyqtSignal(int) - - def __init__(self, parent): - - super(TracebackPane, self).__init__(parent) - - self.tree = TracebackTree(self) - self.current_exception = QLabel(self) - self.current_exception.setStyleSheet("QLabel {color : red; }") - - layout(self, (self.current_exception, self.tree), self) - - self.tree.currentItemChanged.connect(self.handleSelection) - - def truncate_text(self, text, max_length=100): - """ - Used to prevent the label from expanding the window width off the screen. - """ - metrics = QFontMetrics(self.current_exception.font()) - elided_text = metrics.elidedText( - text, Qt.ElideRight, self.current_exception.width() - 75 - ) - - return elided_text - - @pyqtSlot(object, str) - def addTraceback(self, exc_info, code): - - self.tree.clear() - - if exc_info: - t, exc, tb = exc_info - - root = self.tree.root - code = code.splitlines() - - for el in dropwhile( - lambda el: "string>" not in el.filename, extract_tb(tb) - ): - # workaround of the traceback module - if el.line == "": - line = code[el.lineno - 1].strip() - else: - line = el.line - - root.addChild(QTreeWidgetItem([el.filename, str(el.lineno), line])) - - exc_name = t.__name__ - exc_msg = str(exc) - exc_msg = exc_msg.replace("<", "<").replace(">", ">") # replace <> - - truncated_msg = self.truncate_text(exc_msg) - self.current_exception.setText( - "{}: {}".format(exc_name, truncated_msg) - ) - self.current_exception.setToolTip(exc_msg) - - # handle the special case of a SyntaxError - if t is SyntaxError: - root.addChild( - QTreeWidgetItem( - [ - exc.filename, - str(exc.lineno), - exc.text.strip() if exc.text else "", - ] - ) - ) - else: - self.current_exception.setText("") - self.current_exception.setToolTip("") - - @pyqtSlot(QTreeWidgetItem, QTreeWidgetItem) - def handleSelection(self, item, *args): - - if item: - f, line = item.data(0, 0), int(item.data(1, 0)) - - if "" in f: - self.sigHighlightLine.emit(line) diff --git a/cq_editor/widgets/upload_dialog.py b/cq_editor/widgets/upload_dialog.py deleted file mode 100644 index badfa1477..000000000 --- a/cq_editor/widgets/upload_dialog.py +++ /dev/null @@ -1,176 +0,0 @@ -import json -import os -import tempfile - -import requests -from PyQt5.QtGui import QDesktopServices -from PyQt5.QtCore import QRunnable, QThreadPool, pyqtSignal, QObject -from PyQt5.QtWidgets import ( - QComboBox, - QDialog, - QHBoxLayout, - QLabel, - QLineEdit, - QPushButton, - QTextBrowser, - QVBoxLayout, -) -from ..cq_utils import export - -PRESETS = [ - { - "name": "PCBWay", - "url": "https://www.pcbway.com/common/CadQueryUpFile", - "file_type": "step", - "result_key": "redirect", - }, -] - - -class UploadSignals(QObject): - finished = pyqtSignal(str) # Emits formatted JSON or error message - error = pyqtSignal(str) - - -class _UploadRunnable(QRunnable): - def __init__(self, url, file_path, file_type): - super().__init__() - self.url = url - self.file_path = file_path - self.file_type = file_type - self.signals = UploadSignals() - - def run(self): - try: - with open(self.file_path, "rb") as f: - resp = requests.post( - self.url, - files={"file": (f"model.{self.file_type}", f)}, - ) - resp.raise_for_status() - self.signals.finished.emit(json.dumps(resp.json(), indent=2)) - except Exception as e: - self.signals.error.emit(str(e)) - - -class UploadDialog(QDialog): - def __init__(self, parent, object_tree, editor, selected_shapes=None): - super().__init__(parent, windowTitle="Upload Model") - self._object_tree = object_tree - self._editor = editor - self._active_preset = None - self._selected_shapes = selected_shapes or [] - - # URL row - url_layout = QHBoxLayout() - url_layout.addWidget(QLabel("URL:")) - self._url_input = QLineEdit() - url_layout.addWidget(self._url_input) - - # Preset buttons - preset_layout = QHBoxLayout() - preset_layout.addWidget(QLabel("Presets:")) - for preset in PRESETS: - btn = QPushButton(preset["name"]) - btn.clicked.connect(lambda checked, p=preset: self._apply_preset(p)) - preset_layout.addWidget(btn) - preset_layout.addStretch() - - # File type selector - type_layout = QHBoxLayout() - type_layout.addWidget(QLabel("File type:")) - self._type_combo = QComboBox() - self._type_combo.addItems(["STEP", "STL", "CadQuery"]) - type_layout.addWidget(self._type_combo) - type_layout.addStretch() - - # Upload button - self._upload_btn = QPushButton("Upload") - self._upload_btn.clicked.connect(self._do_upload) - - # Response area - self._response = QTextBrowser(placeholderText="Response will appear here...") - self._response.setOpenLinks(False) - self._response.anchorClicked.connect(lambda url: QDesktopServices.openUrl(url)) - - layout = QVBoxLayout() - layout.addLayout(url_layout) - layout.addLayout(preset_layout) - layout.addLayout(type_layout) - layout.addWidget(self._upload_btn) - layout.addWidget(self._response) - self.setLayout(layout) - self.resize(500, 400) - - def _apply_preset(self, preset): - self._url_input.setText(preset["url"]) - self._type_combo.setCurrentText(preset["file_type"].upper()) - self._active_preset = preset - - def _do_upload(self): - url = self._url_input.text().strip() - if not url: - self._response.setPlainText("Error: no URL entered.") - return - - file_type = self._type_combo.currentText() - self._upload_btn.setEnabled(False) - self._response.setPlainText("Uploading...") - - if file_type == "CadQuery": - tmp = tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode="w") - tmp.write(self._editor.toPlainText()) - tmp.close() - self._run_upload(url, tmp.name, "py") - return - else: - # Prefer selected item, fall back to add top-level CQ objects - shapes = ( - self._selected_shapes - if self._selected_shapes - else [ - self._object_tree.CQ.child(i).shape - for i in range(self._object_tree.CQ.childCount()) - ] - ) - - # If the user did not select an object, let them know - if not shapes: - self._response.setPlainText("ERROR: Please select a model to upload.") - self._upload_btn.setEnabled(True) - return - - # Assume that only one object is selected and upload it - cur_type = file_type.lower() - tmp = tempfile.NamedTemporaryFile(suffix=f".{cur_type}", delete=False) - tmp.close() - export(shapes, cur_type, tmp.name) - self._run_upload(url, tmp.name, cur_type) - - def _run_upload(self, url, file_path, file_type): - runnable = _UploadRunnable(url, file_path, file_type) - runnable.signals.finished.connect(lambda msg: self._on_done(file_path, msg)) - runnable.signals.error.connect( - lambda msg: self._on_done(file_path, f"Error: {msg}") - ) - QThreadPool.globalInstance().start(runnable) - - def _on_done(self, file_path, message): - os.unlink(file_path) - try: - data = json.loads(message) - result_key = ( - self._active_preset.get("result_key") if self._active_preset else None - ) - if result_key and result_key in data: - link = data[result_key] - name = self._active_preset.get("name", "unknown service") - self._response.setHtml( - f"

Click the link below to view your model on {name}'s website.

" - f'{link}' - ) - else: - self._response.setPlainText(message) - except json.JSONDecodeError: - self._response.setPlainText(message) - self._upload_btn.setEnabled(True) diff --git a/cq_editor/widgets/viewer.py b/cq_editor/widgets/viewer.py deleted file mode 100644 index 2c093e95b..000000000 --- a/cq_editor/widgets/viewer.py +++ /dev/null @@ -1,535 +0,0 @@ -from PyQt5.QtWidgets import QWidget, QDialog, QTreeWidgetItem, QApplication, QAction - -from PyQt5.QtCore import pyqtSlot, pyqtSignal -from PyQt5.QtGui import QIcon - -from OCP.Graphic3d import ( - Graphic3d_Camera, - Graphic3d_StereoMode, - Graphic3d_NOM_JADE, - Graphic3d_MaterialAspect, -) -from OCP.AIS import ( - AIS_Shaded, - AIS_WireFrame, - AIS_ColoredShape, - AIS_Axis, - AIS_Line, - AIS_ListOfInteractive, - AIS_ViewCube, -) -from OCP.Aspect import Aspect_GDM_Lines, Aspect_GT_Rectangular -from OCP.Quantity import ( - Quantity_NOC_BLACK as BLACK, - Quantity_TOC_RGB as TOC_RGB, - Quantity_Color, -) -from OCP.Geom import Geom_Axis1Placement -from OCP.gp import gp_Ax3, gp_Dir, gp_Pnt, gp_Ax1 -from OCP.Bnd import Bnd_Box - -from ..utils import layout, get_save_filename -from ..mixins import ComponentMixin -from ..icons import icon -from ..cq_utils import to_occ_color, make_AIS, DEFAULT_FACE_COLOR - -from .navigation_cube import RotationArrow -from .occt_widget import OCCTWidget - -from pyqtgraph.parametertree import Parameter -import qtawesome as qta - -DEFAULT_EDGE_COLOR = Quantity_Color(BLACK) -DEFAULT_EDGE_WIDTH = 2 - - -class OCCViewer(QWidget, ComponentMixin): - - name = "3D Viewer" - - preferences = Parameter.create( - name="Pref", - children=[ - {"name": "Fit automatically", "type": "bool", "value": True}, - {"name": "Show navigation cube", "type": "bool", "value": True}, - {"name": "Use gradient", "type": "bool", "value": False}, - {"name": "Background color", "type": "color", "value": (95, 95, 95)}, - {"name": "Background color (aux)", "type": "color", "value": (30, 30, 30)}, - { - "name": "Deviation", - "type": "float", - "value": 1e-5, - "dec": True, - "step": 1, - }, - { - "name": "Angular deviation", - "type": "float", - "value": 0.1, - "dec": True, - "step": 1, - }, - { - "name": "Projection Type", - "type": "list", - "value": "Orthographic", - "values": [ - "Orthographic", - "Perspective", - "Stereo", - "MonoLeftEye", - "MonoRightEye", - ], - }, - { - "name": "Stereo Mode", - "type": "list", - "value": "QuadBuffer", - "values": [ - "QuadBuffer", - "Anaglyph", - "RowInterlaced", - "ColumnInterlaced", - "ChessBoard", - "SideBySide", - "OverUnder", - ], - }, - { - "name": "Orbit Method", - "type": "list", - "value": "Turntable", - "values": [ - "Turntable", - "Trackball", - ], - }, - ], - ) - IMAGE_EXTENSIONS = "png" - - sigObjectSelected = pyqtSignal(list) - - def __init__(self, parent=None): - - super(OCCViewer, self).__init__(parent) - ComponentMixin.__init__(self) - - self.canvas = OCCTWidget() - self.canvas.sigObjectSelected.connect(self.handle_selection) - - self.create_actions(self) - - self.layout_ = layout( - self, - [ - self.canvas, - ], - top_widget=self, - margin=0, - ) - - self.setup_default_drawer() - self.updatePreferences() - - def setup_default_drawer(self): - - # set the default color and material - material = Graphic3d_MaterialAspect(Graphic3d_NOM_JADE) - - shading_aspect = self.canvas.context.DefaultDrawer().ShadingAspect() - shading_aspect.SetMaterial(material) - shading_aspect.SetColor(DEFAULT_FACE_COLOR) - - # face edge lw - line_aspect = self.canvas.context.DefaultDrawer().FaceBoundaryAspect() - line_aspect.SetWidth(DEFAULT_EDGE_WIDTH) - line_aspect.SetColor(DEFAULT_EDGE_COLOR) - - def updatePreferences(self, *args): - - color1 = to_occ_color(self.preferences["Background color"]) - color2 = to_occ_color(self.preferences["Background color (aux)"]) - - if not self.preferences["Use gradient"]: - color2 = color1 - self.canvas.view.SetBgGradientColors(color1, color2, theToUpdate=True) - - # Set the orbit method - orbit_method = self.preferences["Orbit Method"] - if not orbit_method: - orbit_method = "Trackball" - self.canvas.set_orbit_method(orbit_method) - - ctx = self.canvas.context - cube = self.canvas.view_cube - if self.preferences["Show navigation cube"]: - if not ctx.IsDisplayed(cube): - ctx.Display(cube, False) - for arrow in self.canvas.rotate_arrows: - ctx.Display(arrow, AIS_Shaded, 0, False) - ctx.UpdateCurrentViewer() - elif ctx.IsDisplayed(cube): - ctx.Erase(cube, False) - for arrow in self.canvas.rotate_arrows: - ctx.Erase(arrow, False) - ctx.UpdateCurrentViewer() - - self.canvas.update() - - ctx.SetDeviationCoefficient(self.preferences["Deviation"]) - ctx.SetDeviationAngle(self.preferences["Angular deviation"]) - - v = self._get_view() - camera = v.Camera() - projection_type = self.preferences["Projection Type"] - camera.SetProjectionType( - getattr( - Graphic3d_Camera, - f"Projection_{projection_type}", - Graphic3d_Camera.Projection_Orthographic, - ) - ) - - # onle relevant for stereo projection - stereo_mode = self.preferences["Stereo Mode"] - params = v.ChangeRenderingParams() - params.StereoMode = getattr( - Graphic3d_StereoMode, - f"Graphic3d_StereoMode_{stereo_mode}", - Graphic3d_StereoMode.Graphic3d_StereoMode_QuadBuffer, - ) - - def create_actions(self, parent): - - self._actions = { - "View": [ - QAction( - qta.icon("fa6s.maximize"), - "Fit (Shift+F1)", - parent, - shortcut="shift+F1", - triggered=self.fit, - ), - QAction( - QIcon(":/images/icons/isometric_view.svg"), - "Iso (Shift+F2)", - parent, - shortcut="shift+F2", - triggered=self.iso_view, - ), - QAction( - QIcon(":/images/icons/top_view.svg"), - "Top (Shift+F3)", - parent, - shortcut="shift+F3", - triggered=self.top_view, - ), - QAction( - QIcon(":/images/icons/bottom_view.svg"), - "Bottom (Shift+F4)", - parent, - shortcut="shift+F4", - triggered=self.bottom_view, - ), - QAction( - QIcon(":/images/icons/front_view.svg"), - "Front (Shift+F5)", - parent, - shortcut="shift+F5", - triggered=self.front_view, - ), - QAction( - QIcon(":/images/icons/back_view.svg"), - "Back (Shift+F6)", - parent, - shortcut="shift+F6", - triggered=self.back_view, - ), - QAction( - QIcon(":/images/icons/left_side_view.svg"), - "Left (Shift+F7)", - parent, - shortcut="shift+F7", - triggered=self.left_view, - ), - QAction( - QIcon(":/images/icons/right_side_view.svg"), - "Right (Shift+F8)", - parent, - shortcut="shift+F8", - triggered=self.right_view, - ), - QAction( - qta.icon("fa5.stop-circle"), - "Wireframe (Shift+F9)", - parent, - shortcut="shift+F9", - triggered=self.wireframe_view, - ), - QAction( - qta.icon("fa5.square"), - "Shaded (Shift+F10)", - parent, - shortcut="shift+F10", - triggered=self.shaded_view, - ), - ], - "Tools": [ - QAction( - qta.icon("fa5s.camera"), - "Screenshot", - parent, - triggered=self.save_screenshot, - ) - ], - } - - def toolbarActions(self): - - return self._actions["View"] - - def clear(self): - - self.displayed_shapes = [] - self.displayed_ais = [] - self.canvas.context.EraseAll(True) - context = self._get_context() - context.PurgeDisplay() - context.RemoveAll(True) - - def _display(self, shape): - - ais = make_AIS(shape) - self.canvas.context.Display(shape, True) - - self.displayed_shapes.append(shape) - self.displayed_ais.append(ais) - - # self.canvas._display.Repaint() - - @pyqtSlot(object) - def display(self, ais): - - context = self._get_context() - context.Display(ais, True) - - if self.preferences["Fit automatically"]: - self.fit() - - @pyqtSlot(list) - @pyqtSlot(list, bool) - def display_many(self, ais_list, fit=None): - context = self._get_context() - for ais in ais_list: - context.Display(ais, False) - - if self.preferences["Fit automatically"] and fit is None: - self.fit() - elif fit: - self.fit() - elif ais_list: - context.UpdateCurrentViewer() - - @pyqtSlot(QTreeWidgetItem, int) - def update_item(self, item, col): - - if getattr(item, "ais", None) is None: - return - - ctx = self._get_context() - if item.checkState(0): - ctx.Display(item.ais, True) - else: - ctx.Erase(item.ais, True) - - @pyqtSlot(list) - def redisplay(self, ais_list): - ctx = self._get_context() - for ais in ais_list: - if ctx.IsDisplayed(ais): - ctx.Redisplay(ais, True) - - @pyqtSlot(list) - def remove_items(self, ais_items): - - ctx = self._get_context() - for ais in ais_items: - ctx.Erase(ais, False) - if ais_items: - ctx.UpdateCurrentViewer() - - @pyqtSlot() - def redraw(self): - - self._get_viewer().Redraw() - - def fit(self): - ctx = self._get_context() - view = self.canvas.view - - displayed = AIS_ListOfInteractive() - ctx.DisplayedObjects(displayed) - - # Accumulate the bounding box for displayed objects - bbox = Bnd_Box() - for ais in displayed: - if not isinstance(ais, (AIS_Line, AIS_ViewCube, RotationArrow)): - bbox.Add(ais.BoundingBox()) - - # If nothing but the axis helpers are visible, fit to default - if bbox.IsVoid(): - view.FitAll() - else: - view.FitAll(bbox, 0.01, True) - - def iso_view(self): - - v = self._get_view() - v.SetProj(1, -1, 1) - v.SetTwist(0) - - def bottom_view(self): - - v = self._get_view() - v.SetProj(0, 0, -1) - v.SetTwist(0) - - def top_view(self): - - v = self._get_view() - v.SetProj(0, 0, 1) - v.SetTwist(0) - - def front_view(self): - - v = self._get_view() - v.SetProj(0, -1, 0) - v.SetTwist(0) - - def back_view(self): - - v = self._get_view() - v.SetProj(0, 1, 0) - v.SetTwist(0) - - def left_view(self): - - v = self._get_view() - v.SetProj(-1, 0, 0) - v.SetTwist(0) - - def right_view(self): - - v = self._get_view() - v.SetProj(1, 0, 0) - v.SetTwist(0) - - def shaded_view(self): - - c = self._get_context() - c.SetDisplayMode(AIS_Shaded, True) - - def wireframe_view(self): - - c = self._get_context() - c.SetDisplayMode(AIS_WireFrame, True) - - def show_grid( - self, step=1.0, size=10.0 + 1e-6, color1=(0.7, 0.7, 0.7), color2=(0, 0, 0) - ): - - viewer = self._get_viewer() - viewer.ActivateGrid(Aspect_GT_Rectangular, Aspect_GDM_Lines) - viewer.SetRectangularGridGraphicValues(size, size, 0) - viewer.SetRectangularGridValues(0, 0, step, step, 0) - grid = viewer.Grid() - grid.SetColors( - Quantity_Color(*color1, TOC_RGB), Quantity_Color(*color2, TOC_RGB) - ) - - def hide_grid(self): - - viewer = self._get_viewer() - viewer.DeactivateGrid() - - @pyqtSlot(bool, float) - @pyqtSlot(bool) - def toggle_grid(self, value: bool, dim: float = 10.0): - - if value: - self.show_grid(step=dim / 20, size=dim + 1e-9) - else: - self.hide_grid() - - @pyqtSlot(gp_Ax3) - def set_grid_orientation(self, orientation: gp_Ax3): - - viewer = self._get_viewer() - viewer.SetPrivilegedPlane(orientation) - - def show_axis(self, origin=(0, 0, 0), direction=(0, 0, 1)): - - ax_placement = Geom_Axis1Placement(gp_Ax1(gp_Pnt(*origin), gp_Dir(*direction))) - ax = AIS_Axis(ax_placement) - self._display_ais(ax) - - def save_screenshot(self): - - fname = get_save_filename(self.IMAGE_EXTENSIONS) - if fname != "": - self._get_view().Dump(fname) - - def _display_ais(self, ais): - - self._get_context().Display(ais) - - def _get_view(self): - - return self.canvas.view - - def _get_viewer(self): - - return self.canvas.viewer - - def _get_context(self): - - return self.canvas.context - - @pyqtSlot(list) - def handle_selection(self, obj): - - self.sigObjectSelected.emit(obj) - - @pyqtSlot(list) - def set_selected(self, ais): - - ctx = self._get_context() - ctx.ClearSelected(False) - - for obj in ais: - ctx.AddOrRemoveSelected(obj, False) - - self.redraw() - - -if __name__ == "__main__": - - import sys - from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox - - app = QApplication(sys.argv) - viewer = OCCViewer() - - dlg = QDialog() - dlg.setFixedHeight(400) - dlg.setFixedWidth(600) - - layout(dlg, (viewer,), dlg) - dlg.show() - - box = BRepPrimAPI_MakeBox(20, 20, 30) - box_ais = AIS_ColoredShape(box.Shape()) - viewer.display(box_ais) - - sys.exit(app.exec_()) diff --git a/cqgui_env.yml b/cqgui_env.yml deleted file mode 100644 index cb19f4db0..000000000 --- a/cqgui_env.yml +++ /dev/null @@ -1,14 +0,0 @@ -name: cq-occ-conda-test-py3 -channels: - - CadQuery - - conda-forge -dependencies: - - pyqt=5 - - pyqtgraph - - python=3.10 - - qtawesome=1.4.0 - - path - - logbook - - requests - - cadquery - - qtconsole >=5.5.1,<5.7.0 diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 000000000..3caa90981 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,53 @@ +# CQ-editor documentation + +CQ-editor is a code editor and 3D viewer for [CadQuery](https://github.com/CadQuery/cadquery). +You write ordinary Python, press **F5**, and the model appears. The editor +adds the tools you need around that loop: a debugger, a stack inspector, an +interactive console and exporters. + +![CQ-editor main window](images/main-window-light.png) + +## Getting started + +| Page | What you will learn | +| --- | --- | +| [Installation](getting-started/installation.md) | Install a self-contained release, verify its checksum, or configure a custom Python | +| [Your first model](getting-started/first-model.md) | A 10-minute tour: model a bracket, change parameters, select faces, debug and export | + +## User guide + +| Page | Topics | +| --- | --- | +| [The interface](user-guide/interface.md) | Window layout, panels, menus, toolbar, status bar, themes | +| [Writing scripts](user-guide/scripting.md) | `show_object`, colors, assemblies, `debug`, `log`, the script environment | +| [3D view](user-guide/viewer.md) | Mouse controls, navigation cube, standard views, selecting faces, edges and vertices | +| [Code editor](user-guide/editor.md) | Editing, completion, search, files, automatic reload, crash recovery, local history | +| [Projects and multiple files](user-guide/projects.md) | Tabs, the Project panel, the main script, errors across files | +| [Debugging and inspection](user-guide/debugging.md) | Breakpoints, stepping, the CQ Inspector | +| [Console, variables and logs](user-guide/console.md) | Interactive Python, Variables, Traceback and Log panels | +| [Exporting and sharing](user-guide/exporting.md) | STEP, STL, BREP, screenshots, model upload | +| [Headless build and check](user-guide/headless.md) | Export and validate models from a terminal or CI | +| [Preferences](user-guide/preferences.md) | Every option with its default value | +| [Keyboard and mouse reference](user-guide/shortcuts.md) | All shortcuts on one page | +| [Troubleshooting](user-guide/troubleshooting.md) | Python not found, slow models, display problems, where files are stored | + +## Development + +| Page | Topics | +| --- | --- | +| [Architecture](development/architecture.md) | Rust interface, Python worker, frame loop, renderer, geometry cache | +| [Worker protocol](development/protocol.md) | The JSON-lines protocol (version 12) between the two processes | +| [Building](development/building.md) | Toolchains, platform notes, release builds | +| [Testing](development/testing.md) | Test layout, running the suites, continuous integration | +| [CadQuery/OCP compatibility](development/dependency-compatibility.md) | Supported Python and CAD-kernel versions, CI lanes and environment reporting | +| [Original compatibility](development/compatibility.md) | Verified legacy behavior, exact shortcuts and mouse controls, deliberate differences and open gaps | +| [Contributing](development/contributing.md) | Workflow, code style, where to make common changes | + +## Project + +* [Roadmap](roadmap.md): known bugs, planned features and the direction of the project +* [Changelog](changelog.md): what changed in each release + +> These pages describe the current source tree (version `0.9.0`). If +> something here does not match what the program does, please +> [open an issue](https://github.com/igors93/CQ-editor/issues/new). diff --git a/docs/changelog.md b/docs/changelog.md new file mode 100644 index 000000000..2862eb754 --- /dev/null +++ b/docs/changelog.md @@ -0,0 +1,395 @@ +# Changelog + +## Unreleased + +* Changed: the ground grid is a floor on the XY plane at the model's + lowest point, so the model stands on it. It stays flat in every view + instead of turning into a wall in the Front and Right views, reaches the + edge of the view and fades into the distance, and its spacing follows the + size of the model (5 mm for a 60 mm screw) instead of the zoom; lines too + close together on screen fade out +* Changed: the X, Y and Z axes in the view are dashed where the model hides + them, so a part built around the origin no longer makes them disappear, + and a white dot marks the origin +* Changed: an orbit started on the model turns around the point under the + pointer, which stays in place on screen, even in a panned view; started + on empty space it turns around the middle of the view as before +* Changed: right drag orbits like left drag instead of zooming; the wheel, + pinch and Shift + left drag still zoom +* Changed: the installers leave out the Boost, Eigen and TBB headers, CMake + files and import libraries that the VTK package brings for compiling + against it, which nothing uses at run time: each installer is about 19 MB + smaller, and an installation about 230 MB and 17,000 files smaller +* Changed: the editor is built with whole-program optimization (fat LTO, + one codegen unit), and its icon stores the 64 to 192 px images as PNG + (the same pixels) and is embedded once: the Windows executable is 3.6 MB + (17%) smaller + +## 0.9.0 (2026-10-27) + +* New: a Presentation display mode (View menu, toolbar ✦, command palette) + for showing a model: no edges, Studio lights, matte plastic for objects + without a material, a light grey gradient and no axes, grid or scale bar + by default, all set apart from the modeling view in *Preferences > + Presentation* +* New: a soft shadow on the ground under the model in the Presentation + mode, darkest where the model touches the ground, with its strength and + softness in *Preferences > Presentation*. It is the same from every side + and in large or transparent screenshots +* New: materials. `show_object(part, material="matte plastic")` shades an + object as matte or glossy plastic, brushed steel, aluminum or wood, by + metalness and roughness, with metals reflecting a soft studio around the + model; the Objects panel's **Material** list changes it per object. + Metals and wood have their own color for objects without one; Default + keeps the plain shading +* New: *Preferences > Rendering > Edges* chooses which edges are drawn: + all of them, **Sharp edges** (without the edges between faces that + continue smoothly, such as fillet borders and cylinder seams, below a + *Sharp edge angle*), or **Outline** (sharp edges plus the outline of + curved surfaces seen from the camera, also in Hidden Line mode). The + worker measures the angle at every edge (mesh format 2) +* New: *Preferences > Rendering* sets the lighting of the 3D view: key, + fill, ambient and rim lights, highlights and shininess, the direction of + the key light, exposure and contrast, with Default, Studio, Bright and + Dramatic presets. Default keeps the earlier look +* Fixed: one NaN in a `show_object` option or in an object's placement lost + the whole run, every valid object included, with *ValueError: Out of range + float values are not JSON compliant*. A non-finite option is now ignored + with a warning (the object's other options still apply), and an object + that cannot be sent is left out and named in the log (BUG-40) +* Fixed: a model too large to transfer from Python (over 512 MiB of mesh, + about ten million triangles) was reported as *CadQuery is not + available*, and the run never finished. It is now explained, with how to + coarsen the mesh, and Python is restarted with the previous model kept + on screen (BUG-39) +* Fixed: closing the tab of a script paused in the debugger left the + session paused on a document that was gone; it now stops it (BUG-38) +* Fixed: a part or sub-assembly selected inside an assembly and exported to + STEP lost the placement of its parents (STL and BREP were right), and + parts lost the color inherited from their parents, which the view shows + but CadQuery's STEP writer leaves out (BUG-37) +* Fixed: with the Editor panel closed, opening a file or going to a + traceback line showed it in an editor nobody could see, and the closed + panel was restored that way at every start. The Editor now comes back, + left of the 3D view, whenever a file or a line is shown and at start-up, + and the empty view says when it is closed (BUG-36) +* Fixed: in a folder where case matters (Linux, case-sensitive macOS + volumes or Windows folders), renaming `part.py` to `Part.py` in the + Project panel replaced an existing `Part.py`; it is now refused, while + changing only the case of a name still works (BUG-35) +* Fixed: keyboard shortcuts ran behind modal dialogs. Ctrl+Tab under the + File changed on disk dialog made it describe another file, and its answer + was then dropped, leaving the conflict unresolved. Shortcuts now wait + until a dialog is answered, and a conflict is always resolved on the + file it concerns (BUG-34) +* Fixed: on Windows, the local history of a file depended on whether its + path was written with `/` or `\`, so some versions could be missing from + File > Local History (BUG-41) +* Fixed: saving replaced a version of the file that another program had + written since it was opened or saved: with automatic reload off (the + default), a Ctrl+S could undo a `git pull`. Saving now asks first, with + the File changed on disk dialog, and keeps the replaced version in the + local history (BUG-33) +* New: View > Command Palette (Ctrl+Shift+P) finds any command, tab, + recent file, example, panel or named view by a few letters of its name, + and shows its shortcut +* New: a panel can fill the window: double-click its tab, use View > + Maximize Panel (Ctrl+Shift+M) or its tab's menu; the same brings the + layout back, and the saved layout stays the whole one +* New: a panel tab's right-click menu has Maximize and Reset Layout, and + names its other items Float in a Window and Close Panel +* Fixed: in a narrow window the toolbar's last groups were cut off; they now + move to a » menu at its end +* Changed: the Render button is green, and with several files open the + editor panel's tab reads "Editor" (their names are on the tab strip) +* New: multiple files in tabs (FEAT-D1). Each tab keeps its caret, + scrolling, undo history and breakpoints; Ctrl+Tab / Ctrl+Shift+Tab switch, + Ctrl+W closes, and File > Save All saves them all. Opening a file no + longer replaces the one shown, so it no longer asks to save it first +* New: File > Open Folder (Ctrl+Shift+O) shows the folder in a Project panel + that opens, creates, renames and deletes files and folders; renames keep + open tabs, breakpoints and named views in step +* New: a project's main script, guessed when clear and chosen from the + panel, a tab or the Run menu: while a file of the project is shown, F5, + Profile and Debug run the main script, whose errors, debug line and + parameters stay in its tab. The status bar names it, and a render warns + about unsaved modules that Python will not see +* New: the Traceback panel opens the imported module of a frame at its line +* New: the open tabs and the project folder are restored at the next start; + closing or quitting asks about every unsaved tab at once, and crash + recovery and automatic reload cover every tab +* Fixed: text and partially visible rows in docked panels are clipped to their + own tab body instead of painting over split separators or neighbouring tabs +* Fixed: rich console results are tied to the command that produced them; + retained or background `display()` calls can no longer appear as output of + a later command +* Fixed: upload and release-check responses have explicit limits, preventing + an oversized HTTP response from consuming unbounded worker memory or + exceeding the GUI protocol limit +* Security: updated Tokio to 1.54.1 to address RUSTSEC-2026-0384, and made CI + reject dependency-lock drift and Rust compiler warnings +* Quality: the worker CI now rejects Python syntax/import errors with Ruff + and enforces at least 85% branch-aware test coverage + +## 0.8.0 (2026-10-22) + +The interface was rebuilt in Rust (egui + wgpu); CadQuery now runs in a +separate Python worker process (`worker/cq_worker`). The core script contract, +legacy shortcuts and mouse bindings are preserved. Full GUI equivalence is +tracked in the compatibility matrix instead of being assumed. + +* New: a running or crashing script no longer freezes or closes the editor; + Run > Stop (Ctrl+Shift+F5) aborts it and a crashed worker restarts itself +* New: self-contained installers for Windows, Linux, macOS Apple Silicon and + macOS Intel bundle the tested Python 3.12, CadQuery 2.8, OCP 7.9 and Jedi + runtime; every installer is smoke-tested after installation and published + with SHA-256 checksums and its resolved dependency lockfile +* New: installed applications add a native launcher; Windows and Linux also + register CQ-editor as an option for opening Python files without replacing + the user's chosen editor inside CQ-editor +* New: GPU renderer with MSAA, smooth camera animations, zoom at the mouse + pointer, hover highlighting and double-click to zoom to an object +* New: section view (View > Section View); a plane across X, Y or Z, with a + position slider and a flip, cuts the model and fills the cut faces of + solids; picking goes through what the plane removes +* New: CQ-editor looks for a newer release of itself once a day (Preferences + > General) and offers it in the Help menu; Help > Check for Updates now + covers CQ-editor and CadQuery +* New: environments from the preferences: pick a Python found on the + computer, create a virtual environment with CadQuery and jedi, or install + packages into the Python in use, with pip's output shown and Cancel +* New: the console shows pictures, as Jupyter does: a matplotlib figure or + an object with `_repr_png_` / `_repr_jpeg_` is drawn in the console, and + `display()` shows several values; images are checked and limited before + they reach the editor, and HTML is shown as plain text +* New: Run > Profile (Alt+F5) shows in the gutter the time each line took, + with what it called, and in a tooltip its CadQuery operations by time +* New: Stop interrupts the script or console command first, keeping Python, + the console's variables and the mesh cache, and reports the line it + stopped at; Python is restarted only if the script does not stop within + 3 seconds or Stop is pressed again +* New: the original editor's stereo projections (Stereo, Mono Left Eye, + Mono Right Eye) and stereo modes (anaglyph, row/column interlaced, chess + board, side by side, over-under); Quad Buffer shows the anaglyph with a + note, since no current renderer backend can present it +* New: ground grid on the XY plane (View > Ground Grid) whose spacing follows + the zoom, and a scale bar (View > Scale Bar) in the units chosen in the + preferences +* New: large models; parts outside the view are not drawn, parts small on + screen use a simplified mesh (Preferences > 3D View > Large models), and + meshing shows its progress in the view and can be cancelled while the + previous model stays +* New: screenshots at the view's size ×1/×2/×4 or any size up to 8192 + pixels, with a transparent background if wanted, and turntable animations + as an animated PNG or numbered PNG files (Tools > Screenshot…) +* New: named views; save the camera under a name from the toolbar or View > + Named Views and come back to it later; views are remembered per file +* New: X-Ray (Shift+F11) and Hidden Line (Shift+F12) display modes; hidden + edges are dashed and sections hatched in Hidden Line, and each object can + show or hide its own edges in the Objects panel +* New: exploded view (View > Exploded View) with a 0–200% slider, and + Isolate Selection / End Isolation / Show All in the View menu and the + Objects panel; picking and framing follow the exploded parts, isolation + follows objects by name across runs +* New: the Measurements panel reports exact bounding boxes, measures the + selected objects (volume, area, center of mass) when no entity is picked, + and copies a measurement as Python using the script's variables and + selectors, checked by running it +* New: Go to Source (Ctrl+Shift+G) from an object, its property sheet or a + CQ Inspector step to the script line that created it, following the + edits made since the run +* New: Parameters panel; the script's top-level numbers as spin boxes and + sliders that rewrite their literal and render again, with ranges from + `# [min, max, step]` comments and one Undo step per drag +* New: `selected()` in the console returns the picked faces, edges and + vertices (or the selected objects' shapes) as live CadQuery shapes, for + measurements and experiments +* New: selection to code; picked faces, edges or vertices get a CadQuery + selector (`.faces(">Z")`, `.edges("|Z and >Y")`, `.edges("|Z")` for + several), verified with CadQuery, to copy or insert at the cursor + (Ctrl+Shift+I), with alternatives and a flagged index fallback; Ctrl+click + now gathers up to 64 entities +* New: precise OCCT face, edge and vertex selection with subshape highlighting + and live-scene topology identifiers retained by the Python worker +* New: Auto/Object/Face/Edge/Vertex selection modes and an exact Measurements + panel for OCCT distance, closest points, angle, length, area, surface/curve + type, radius and diameter; topology ids are explicitly scoped to one render +* New: navigation cube redrawn natively, with hover feedback and the 45° roll + arrows; view icons follow the theme +* New: debugger "Step out" (Ctrl+Shift+F11) and a cleaner stepping model +* New: editor auto-indentation, current-line highlight, match-case search, + completion popup filtered while typing and call signature tips +* New: object colors and opacity can be changed in the Objects panel, which + also shows sizes and triangle counts +* New: Open Recent, Reset Layout, Restart Python, BREP export; single + assemblies export to STEP with their names and colors +* New: Log panel with level filters; console with history +* New: atomic saves that preserve line endings, the UTF-8 BOM, permissions + and file metadata; files that are not valid UTF-8 are never rewritten + without asking +* New: crash recovery (checkpoints every 5 seconds while a buffer is + modified, restore on the next start) and File > Local History with the + newest 20 versions per document +* New: automatic reload never discards unsaved edits; a dialog offers to + keep them, reload, save a copy or compare +* New: Edit > Undo and Redo (Ctrl+Z, Ctrl+Y or Ctrl+Shift+Z) with an + editor history of its own: typing is undone a burst at a time, and an + indent, a comment, an accepted completion, a Replace all or a reload is + one step; undo no longer brings back the text of a previous document +* New: Replace (Ctrl+H), whole-word search and Go to Line (Ctrl+G) +* New: completions are offered after the first characters of a name + (three by default, configurable), and resting the pointer on a name + shows its signature and docstring, or the type of a variable +* New: breakpoints are remembered per file across sessions and follow + the text of their lines when the file changed meanwhile +* New: the Objects property sheet shows the type, area or length, radius + and center of a selected face, edge or vertex +* New: when Python or CadQuery is missing, the dialog lists the + interpreters found on the computer, and offers to choose one or to open + the installation guide (also in the Help menu) +* New: content-addressed mesh cache and assembly instancing; unchanged + meshes are not sent or uploaded again +* New: hover and click selection stay fast on large assemblies; a retained + spatial index of scene parts and per-mesh edge and vertex indexes replace + the linear scan (about 0.1 ms instead of 150 ms per pointer move with + 16,384 parts) +* New: documentation in `docs/` (user guide, development guide, roadmap) +* New: a ninth example, a welded 20 x 20 mm square-tube workbench built as + an assembly, with its cutting plan and a tube summary in the Log panel +* New: a tested compatibility matrix inventories original features, guards + legacy shortcuts and mouse gestures, and runs every pre-rewrite example +* New: CI tests the worker against the supported Python/CadQuery/OCP release + matrix and the current CadQuery development branch; test, benchmark and + application logs now identify the exact runtime versions +* Changed: theme follows the system by default; the separate editor color + scheme preference was merged into the application theme +* Changed: the Quad Buffer stereo mode cannot be presented by the new + renderer and shows the red-cyan anaglyph, with a note saying so +* Fixed: the 3D view failed on systems where wgpu falls back to OpenGL + (no Vulkan, or software rendering), which cannot view the scene's sRGB + texture in another format; it now gets a plain copy encoded by a small pass +* Fixed: with OCP 8, bounding boxes in the Measurements panel and in the + code copied from it failed (`Bnd_Box.Get()` returns a type OCP 8 cannot + convert); the box corners are read instead +* Fixed: `rand_color()` defaulted to a fully transparent color +* Fixed: after Stop, Restart Python or a worker crash, the first run could + free its own objects, so the CQ Inspector, export and upload failed; scene + keys are now unique per worker process +* Fixed: the CI format check (`black`) failed on three worker files +* Fixed: after switching Python environments or upgrading OCP, a render + could reuse meshes made by the previous mesher; mesh ids now include + the mesh format and the OCP build, and conda installs report their OCP + version instead of `unknown` +* Fixed: the CQ inspector could draw the geometry of a previously + selected step or workplane when its reply arrived late +* Fixed: the first Enter or F3 after typing a search skipped the first + match +* Fixed: OCP 8 moved generated collection types and removed the `_s` suffix + from `TopoDS` downcasts, preventing the worker from importing with current + CadQuery `master`; one compatibility shim now supports both OCP 7 and 8 +* Fixed: equal per-face triangle counts could conceal a changed glTF face + order and assign the wrong OCCT face id; every proposed face group is now + checked geometrically before display triangles are accepted for picking +* Fixed: script output without a newline and JSON protocol lines could grow + without a bound; output is now chunked and truncated per request, while + control, mesh and native-stderr messages have separate reader limits +* Fixed: in a short Objects pane, the property sheet grew over the object + tree; it now scrolls and leaves the tree its room +* Fixed: breakpoints and the error line stayed on their line numbers when + lines were added or removed above them; they now follow their statements +* Fixed: while debugging, a paused view that no longer showed an object made + the next pauses and the final result fail with "Cannot update the 3D + scene" once the object reappeared; meshes now stay available for the + whole session +* New: after each run the Log panel reports the time spent in the script, + meshing, encoding, transfer and decoding, and how many meshes were reused; + GPU uploads are logged at the debug level +* New: faster meshing for selection; the display triangles carry their OCCT + face ids instead of a second set of pick triangles, so detailed parts mesh + up to 3x faster and their messages are about a third smaller +* New: recently used meshes and their GPU buffers are kept (up to 128 MB), + so rendering after Clear, debugging and repeated runs transfer and upload + only geometry that changed +* Fixed: the Previous match tooltip now shows its actual Alt+F3 shortcut + instead of conflicting with the Shift+F3 Top view shortcut +* Fixed: Ctrl+left-drag explicitly selects Pan even when a platform event does + not also set egui's synthesized Command modifier +* Fixed: worker replies, automatic reload and recovery checkpoints are + handled while the window is minimized, instead of waiting for a repaint +* Fixed: icons in dialog titles (Preferences, Upload Model) showed as empty + boxes +* Fixed: Help > Documentation opens these docs instead of the old PyQt wiki +* Fixed: with *Autoreload: watch imported modules*, modules imported after + watching started were never watched; the list is refreshed after each save + and successful run, without duplicates or modules no longer imported +* Fixed: the Variables panel showed every value as "…"; the value column now + gets the room the other columns leave, and clicking a row shows the whole + value (up to 2000 characters), ready to copy +* Fixed: after a failed run, the empty view and Objects panel point to the + Traceback instead of asking to press F5 again; empty-panel texts are no + longer justified with uneven word spacing +* Fixed: opening another file cleared nothing, so the previous file's model + looked like the result of the new script; a run or debugging session still + going for the previous file is discarded +* Fixed: `debug()` in the console named objects *Workplane 1* instead of + after their variable +* Fixed: `--help` and command-line errors printed nothing from the Windows + release executable +* Fixed: every release left its extracted worker folder behind; a new one + removes the others +* Fixed: each recovery checkpoint read every history file of every document; + history now lives in one folder per document and is pruned by age (90 + days) and total size (64 MB), which also clears the history of deleted + files +* Fixed: files that are not UTF-8 could not be opened; they can now be read + as Windows-1252 and are converted to UTF-8 on save +* Fixed: the Windows executable had no icon or version information in + Explorer +* Fixed: building with the Windows GNU toolchain needed a hand-made + `libshlwapi.a`; links are opened with the `open` crate +* Fixed: GUI panics and the messages before them were lost; the log is also + written to `logs/cq-editor.log` in the data folder +* Fixed: a worker stopped while meshing left `cq-editor-*.glb` files in the + temporary folder; meshing uses one scratch folder per worker and the next + worker removes leftovers +* Fixed: quitting with *Don't save* offered the discarded edits as unsaved + work at the next start +* Fixed: *Stop debugging* could be swallowed by an `except Exception` in the + script +* Fixed: the editor could crash when an edit moved the completion popup's + anchor inside a multi-byte character +* Fixed: a link in an upload service's reply could open a local file or + program; only http and https links are opened +* Fixed: a long status message pushed the Python state, cursor position and + encoding out of the status bar +* Fixed: the Log filter matched message sources case-sensitively +* Fixed: a scene that could not be decoded also dropped the run's variables + and a queued render; a failed run request left the debugger arrow and + dropped a queued render +* Fixed: clicking the text of a Traceback row did not jump to its line, only + the empty part of a cell did +* Removed: the PyQt GUI, PyInstaller and conda constructor packaging + +## Release 0.5.0 + +* Implemented a dark theme and tweaked it to work better with icons (#490) +* Fixed bug causing the cursor to jump when autoreload was enabled (#496) +* Added a max line length indicator (#495) +* Mentioned work-around for Linux-Wayland users in the readme (#497) +* Fixed bug where dragging over an object while rotating would select the object (#498) +* Changed alpha setting in `show_object` to be consistent with other CadQuery alpha settings (#499) +* Added ability to clear the Log View and Console (#500) +* Started preserving undo history across saves (#501) +* Updated run.sh script to find the real path to the executable (#505) + +## Release 0.4.0 + +* Updated version pins in order to fix some issues, including segfaults on Python 3.12 +* Changed to forcing UTF-8 when saving (#480) +* Added `Toggle Comment` Edit menu item with a `Ctrl+/` hotkey (#481) +* Fixed the case where long exceptions would force the window to expand (#481) +* Add stdout redirect so that print statements could be used and passed to log viewer (#481) +* Improvements in stdout redirect method (#483 and #485) +* Fixed preferences drop downs not populating (#484) +* Fixed double-render calls on saves in some cases (#486) +* Added a lint check to CI and linted codebase (#487) diff --git a/docs/development/architecture.md b/docs/development/architecture.md new file mode 100644 index 000000000..35428d9f3 --- /dev/null +++ b/docs/development/architecture.md @@ -0,0 +1,372 @@ +# Architecture + +CQ-editor is two programs that talk over a pipe: + +``` +┌─────────────────────────────────────┐ requests (JSON lines, stdin) ┌──────────────────────────────────┐ +│ cq-editor (Rust) │ ───────────────────────────────► │ python -m cq_worker │ +│ │ │ │ +│ egui + egui_dock window, panels │ messages (JSON lines, stdout) │ runs scripts with CadQuery │ +│ wgpu 3D renderer │ ◄─────────────────────────────── │ tessellates shapes (OCCT) │ +│ scene, picking, camera, documents │ │ debugger, inspector, console │ +│ recovery, file watching, settings │ stderr → Log panel │ export, upload, completion (jedi)│ +└─────────────────────────────────────┘ ◄─────────────────────────────── └──────────────────────────────────┘ +``` + +**Why two processes?** CadQuery and OpenCascade are Python and C++ code that +can block for a long time or crash on bad geometry. Running them in a child +process means: + +* the interface never freezes, even during a long boolean operation; +* *Stop* is reliable: the GUI kills the process and starts a fresh one; +* a segmentation fault inside OpenCascade costs a restart, not your + unsaved work; +* the GUI does not depend on Python at build time. Any environment with + CadQuery can be used at run time. + +The worker package (`worker/cq_worker`) and the example scripts are compiled +into the executable by `build.rs`. At run time `embedded::worker_dir` +extracts the package into the data folder (`worker-/`) and puts +it on `PYTHONPATH`. Debug builds use `worker/` from the source tree directly, +and `CQ_EDITOR_WORKER_DIR` overrides both. + +## Rust side (`src/`) + +| Module | Responsibility | +| --- | --- | +| `main.rs` | Command line, window options, start-up | +| `app/` | Application state (`AppState`), the frame loop and action dispatch (`mod.rs`); `CqEditorApp` wraps it with the dock layout and implements `eframe::App`. One `impl AppState` module per concern: `documents.rs` (open, save, reload, recovery, history), `tabs.rs` (the open documents, the session, the script F5 runs), `projects.rs` (the project folder, its main script, file operations), `runs.rs` (render, debug, stop), `worker_events.rs` (worker lifecycle, message routing), `watching.rs` (automatic reload), `services.rs` (selection, measurement, inspector, export, console, upload). `execution.rs` is the pure state machine of runs and pending requests | +| `commands.rs` | `Action`, everything the user can ask for, and the keyboard shortcut table | +| `document.rs` | An open script: UTF-8 decoding (Windows-1252 on request, saved back as UTF-8), BOM and line-ending preservation, atomic saves, external change classification | +| `recovery.rs` | Crash-recovery session (every tab with unsaved changes) and bounded local history | +| `project.rs` | The project folder: cached listings of its tree, the main-script guess, checked names, create/rename/delete | +| `file_watcher.rs` | Polling watcher behind *Automatic reload* | +| `settings.rs` | Preferences, persisted by eframe | +| `scene.rs` | What the view shows: nodes, parts, meshes, visibility, colors, selection, topology selection, inspector overlay | +| `spatial.rs` | Bounding-volume hierarchies for picking: triangles, and generic boxes for scene parts, edge segments and vertices | +| `viewer/` | 3D view: `camera.rs` (orbit camera, fixed-point orbit, standard views, animation), `renderer.rs` (wgpu pipelines), `shaders.wgsl`, `picking.rs`, `overlays.rs` (navigation cube, axes indicator), `section.rs` (section plane), `views.rs` (named views), `capture.rs` (screenshots, turntables), `culling.rs` (frustum culling, level of detail), `ground.rs` (floor grid under the model with fading edges, scale bar), `shadow.rs` and `shadow.wgsl` (the Presentation mode's ground shadow), `stereo.rs` and `stereo.wgsl` (stereo composition) | +| `editor/` | Code editor: `highlight.rs` (Python tokenizer), `text_ops.rs` (pure text edits: indent, comment, auto-indent, replace, names, *Go to line*, breakpoint relocation), `history.rs` (the undo history: typing grouped into steps, one step per command or reload) | +| `panels/` | Objects, Measurements, Variables, CQ Inspector, Console, Traceback, Log, Project, and the default dock layout | +| `dialogs/` | Preferences, Upload, About, Screenshot, Python environments, unsaved changes, external change, recovery, local history, messages | +| `ui/` | Menu bar, toolbar, status bar, the editor's tab strip | +| `worker/` | Child process management and the reason a start failed (`mod.rs`), interpreter discovery and the interpreters offered when it fails (`launch.rs`), protocol types (`protocol.rs`) | +| `environments.rs` | Creating virtual environments and running `pip install` from the preferences: the commands, package checks, and a cancellable background job that collects their output | +| `embedded.rs` | Access to the files embedded by `build.rs` | +| `logging.rs` | The bounded, application-wide log behind the Log panel | +| `theme.rs` | Light/dark visuals, fonts, editor and viewer colors | + +### The frame loop and actions + +egui is an immediate-mode toolkit: the whole interface is rebuilt every +frame. To keep that manageable, widgets **never change application state +directly**. They push an `Action` (see `commands.rs`), and `app/` runs the +queued actions after the UI of the frame has been built: + +``` +logic process worker events · poll file watcher · recovery checkpoint +begin_frame apply theme/scale · collect shortcuts +build UI menu bar · toolbar · dock (editor, view, panels) · status bar · dialogs → push Actions +execute for each Action: open/save/run/select/export/… → may send worker Requests +end_frame handle window close requests (unsaved changes guard) +``` + +`logic` is eframe's `App::logic`: it runs before every frame and also while +the window is minimized or hidden, whenever a repaint was requested. Worker +replies, automatic reload and recovery checkpoints therefore never wait for +the window to be drawn. + +Menus, toolbar buttons, shortcuts and context menus therefore share one code +path per command, and the shortcut shown in a menu comes from the same table +that handles the key press. + +### Documents and tabs + +`AppState::document` and `AppState::editor` are always the **shown** tab's, +so the code that works on "the document" (editing, completion, search, +saving, the window title) needs no notion of tabs. The other open documents +are *parked* in `EditorTabs` (`app/tabs.rs`) with their own `CodeEditor`; +showing a tab swaps it with the shown one. Each editor has its own egui id, +so egui keeps the caret and scrolling of every tab, and the editor itself +keeps its undo history, breakpoints and markers. + +Every document has a *generation*, its identity for as long as it is open. +A run records the generation of the script it executes (`RunScript`), which +is not always the shown one: in a project, F5 runs the main script +(`AppState::run_target`). Error and debug lines, profiles, the Parameters +panel and *Go to Source* use that generation to reach the right editor, +shown or parked, and completions answered for a tab that is no longer shown +are dropped. + +### Talking to the worker + +`worker::Worker` owns the child process and three helper threads: + +* a **writer** thread that serializes requests to stdin; +* a **reader** thread that parses stdout lines into `Message`s and decodes + the base64 mesh arrays, so the UI thread never parses large payloads; +* a **stderr** thread that forwards lines to the Log panel. + +Events reach the UI through a channel and wake egui up with +`request_repaint`, which runs `App::logic` even when nothing is drawn. Each process gets a *generation* number, so late events +of a killed process are ignored. Requests that expect an answer get an id, +which `Execution` (`app/execution.rs`) maps to what the answer is for (run, +completion, inspection, export, …). The same state machine decides whether a +render starts, waits for Python, is queued behind the running one or belongs +to a document that was replaced since; `tests/rust/app/test_execution.rs` +covers its transitions without a window or a process. + +### Rendering + +`viewer/renderer.rs` draws the scene off screen into an sRGB texture with 4× +MSAA when available. egui then shows it like an image, through a non-sRGB +view of the same texture so colors are not encoded twice. Devices that +cannot view a texture in another format (wgpu's OpenGL backend, used where +Vulkan is missing and by Mesa's software llvmpipe) get a plain copy instead, +which a small pass (`present.wgsl`) fills after each frame by encoding the +colors by hand; offscreen targets (captures, stereo eyes) need neither. +Multisampling is used only when both the color and the depth-stencil format +support it. Draw order: +background (flat or gradient), opaque faces, edges and points, transparent +faces back to front, then the inspector overlay on top. The same code renders +into textures of its own for screenshots (`render_pixels`), which also lets +the tests draw on any adapter without a window. A capture larger than +2048 pixels on a side is drawn in tiles: each pass scales and shifts clip +space after the projection (`Tile::projection`), so both projections work +and screen-space widths stay in image pixels, and the camera uniform's +`frame` places the tile in the whole image for the background gradient. A +transparent capture draws over transparent black; blending then leaves +premultiplied colors, which `viewer/capture.rs` turns into the straight +alpha of PNG (in linear space, since the colors are sRGB). Turntable frames +are written one per frame of the view, with the `png` crate's animated PNG +encoder. + +A **section plane** (`viewer/section.rs`) is a uniform: the fragment shaders +discard what lies on the removed side of it for objects marked `clipped`. The +cut is filled per object with the stencil buffer: every remaining surface of +the object inverts the stencil, without depth test, so the count is odd +exactly where the plane passes through material; a quad on the plane is then +drawn where the stencil is set, and resets it (pass and depth-fail) for the +next object. Picking applies the same plane to the ray (`ClipPlane::kept_range`) +and ignores edges and vertices it removes. + +`shaders.wgsl` lights faces with a camera-attached three-point setup (key, +fill, rim) and lights both sides of a face, so open shells look right. The +strengths, the key light's direction, the highlights, exposure and contrast +come from `settings::Lighting` (*Preferences > Rendering*) through the +camera uniform; `lighting_uniform` bounds them, so a damaged settings file +cannot produce negative light or NaN. + +Materials (`settings::Finish`) reach the shader as the item's `surface`: +the plain model of `lit`, or `lit_material`, a microfacet model (GGX, +Smith, Schlick) driven by metalness and roughness under the same lights, +which also reflects `studio`, an analytic photo studio attached to the +camera, so metals look like metals without an environment map. Wood adds +value noise in the part's own coordinates (`MeshOut::local`), so the grain +moves with the part. + +The Presentation mode's **ground shadow** (`viewer/shadow.rs`, +`shadow.wgsl`) does not depend on the camera, so it is drawn only when the +shadowed items or the settings change (`shadow_key`), and is the same in +every tile of a capture and for both stereo eyes. The opaque faces are drawn +from straight above, with the scene's own object uniforms, into a 256² +two-channel texture that keeps, by max blending, how close to the ground the +lowest face over each texel is. Two separable Gaussian passes, read texel by +texel, blur it a little in the red channel (the contact shadow) and much in +the green one (the ambient shadow); both spreads are fractions of the +model's width, so the square of ground under the model is as many times as +wide as the model. In the scene pass, after the opaque faces, a quad on the +ground darkens the background by both, the ambient one through a curve with +a long tail; the depth test keeps it behind the model and back-face culling +hides it from below. + +Which edges are drawn is decided on the GPU, so changing the edge style +uploads nothing. Every segment carries the angle at which the faces of its +B-rep edge meet, measured by the worker (`edge_angles` in +`tessellation.py`), and `vs_edge` collapses the segments below the item's +`edge_filter`. The outline of curved surfaces comes from the triangles: +`Mesh::silhouette_edges` lists, once, the interior mesh edges between two +triangles that do not lie in one plane, with both triangles' normals +(corners at the same place are welded, since the worker meshes each face +apart). `vs_silhouette` draws one where one triangle faces the camera and +the other does not; the buffer is made the first time an item needs it. +Edges and points are camera-facing quads expanded in screen space, which +gives constant pixel widths at any zoom. Faces get a depth bias so edges +stay visible on top of them. + +`viewer/culling.rs` decides what is drawn of a large model. Every pass skips +items whose bounds are outside its view frustum (per tile in a tiled +capture), widened by the widest edge or point, which are expanded on +screen. In large-model mode `Viewer::draw_items` swaps the mesh of a part +that is small on screen for `Mesh::simplified`, a vertex-clustered copy made +once per mesh, and drops the edges of specks; picking keeps the full mesh. + +Stereo projections (`viewer/stereo.rs`) draw the scene once per eye +(`Camera::eye_view_projection`: the eye moved sideways, its clip space +shifted so both eyes agree on the target's plane) into textures of their +own, then `stereo.wgsl` composes them into the view's texture, reading +texels without filtering. Captures draw each eye with `render_pixels` and +compose on the CPU with the same rules; a test compares the two. + +Display modes are styles, not separate renderers (`DisplayMode::style`): +X-ray lowers the face opacity, so faces take the transparent path and +write no depth; hidden-line fills faces with the background color +computed per pixel (gradient included), and draws edges a second time +where the depth test fails (`Greater`), dashed by their screen-space +length. + +Assembly parts are **instances**: one mesh plus a transform per part. +Identical geometry is uploaded to the GPU once. + +The exploded view and isolation belong to the `Scene`, not to the viewer: +`Scene::part_transform` adds the explosion offset to a part's placement and +`Scene::visible_nodes` leaves out what an isolation hides, so drawing, +picking, framing and the section plane all see the same parts in the same +places. Both changes bump the pick revision, which rebuilds the picking +index. Placements themselves never change, so measurements and exports, +which the worker computes from the real shapes, are unaffected. + +### Profiling + +`worker/cq_worker/profiling.py` times a run with `sys.settrace`, which also +works on supported Python versions: the global trace function follows the +frames of the editor buffer line by line, adding the time between two events +of a frame to the line that was running, so a line's time includes its callees. +Calls from the script straight into CadQuery's files are timed per function; their own +lines are not traced (`f_trace_lines = False`), and other code is not traced +at all, which keeps the overhead to one Python call per function call. The +GUI maps the profile from the text that ran onto the edited document, and +`CodeEditor::sync_markers` moves it with later edits like the breakpoints. + +### Picking + +`viewer/picking.rs` hit-tests faces exactly with a ray, accelerated by the +BVH in `spatial.rs`. Edges and vertices are matched in screen space within 6 +pixels, and a face in front of them occludes them. The worker sends, with +every mesh, which triangle belongs to which OCCT face and which segment to +which edge (`MeshTopology`). A click can therefore name *Face 6* rather than +"triangle 1234". + +Picking never scans the whole scene. It runs in two phases: + +* **Broad phase:** the viewer keeps a `SceneIndex`, a BVH over the + world-space bounds of every visible part. A part is kept when the pointer + ray hits its box or, when edges or vertices may be picked, when its + projected box lies within the pixel tolerance of the pointer. The index is + rebuilt only when `Scene::pick_revision` changes (parts added, removed or + shown/hidden), never on camera moves or selection changes. +* **Narrow phase:** each remaining mesh tests its triangles, edge segments + and vertices through its own lazily built BVHs, shared by every instance + of the mesh. Edge and vertex boxes are pruned in screen space. + +Both phases return candidates in scene and index order, so ties between +coincident entities resolve exactly as a linear scan would. The camera +matrices are computed once per pick (`camera::project_with`). +`pick_latency_on_growing_assemblies` measures hover latency as the part +count grows (see [Testing](testing.md#benchmarks)). + +GPU picking (rendering entity ids and reading a pixel back) was considered +and not adopted for now: the readback adds at least a frame of latency and +a GPU-to-CPU synchronization, while the CPU path above stays near 0.1 ms per +hover in the benchmark's assembly of 16,384 parts. Revisit it only if a +measured scene makes the CPU path the bottleneck again. + +## Python side (`worker/cq_worker/`) + +| Module | Responsibility | +| --- | --- | +| `__main__.py` | Entry point: takes over stdout, imports CadQuery, reports `ready` or `fatal` | +| `protocol.py` | JSON-lines transport. Captures `print` output and native writes to descriptor 1 | +| `environment.py` | Reproducible Python, CadQuery, OCP, platform and interpreter version report | +| `server.py` | Request dispatch, the run loop, debug pause loop, session state | +| `execution.py` | Running the editor buffer as `__cq_main__`: injected API, environment, module reloading, tracebacks | +| `debugger.py` | Line stepping with `sys.settrace`, tracing only the script's own frames | +| `scene.py` | Shown objects → scene nodes: colors, assemblies, the `Registry` of live objects by key | +| `tessellation.py` | Meshing, the content-addressed `GeometryCache`, `TopologyIndex` | +| `inspector.py` | Workplane stack description and per-step geometry | +| `measurement_code.py` | *Copy as code*: Python that repeats a measurement with the script's variables and selectors, run on a copy of the console namespace to verify it | +| `provenance.py` | While a script runs, records on each new Workplane, Shape, Assembly and Sketch the script line that created it, for *Go to Source* | +| `selection.py` | Selectors for picked entities: simple selectors evaluated with CadQuery's rules on cached entity features, combined as bit masks, then verified with CadQuery itself | +| `console.py` | The persistent interactive console | +| `completion.py` | jedi completions, call signatures and the documentation shown on hover | +| `exporting.py` | STEP / STL / BREP export | +| `network.py` | Model upload and CadQuery release checks, standard library only | + +The worker is **single threaded**: it handles one request at a time. While a +debugging session is paused, `Server.wait_for_debug_action` keeps serving +read-only requests (completion, inspection, export, …), so the GUI stays +useful at a breakpoint. + +### The registry + +The GUI never holds CadQuery objects. It holds **keys** (`s1-n1`, `s1-n2`, +…). The worker's `Registry` maps each key to the live object, its +world-space shape and its topology index. Export, inspection, measurement and upload +refer to objects by key. When the GUI drops objects it sends `release`, so +the worker can free them. + +Keys carry the worker's session number (`CQ_EDITOR_SESSION`, the GUI's +worker generation). Objects stay on screen when Python is restarted, and the +next run releases their keys. With per-session keys, that release can never +free the new worker's objects. + +### Tessellation and the geometry cache + +1. BRepMesh triangulates the faces in parallel. +2. OCCT's glTF writer (`RWGltf_CafWriter`) emits positions, exact normals and + indices from C++ in one pass. numpy reads the binary back, which is much + faster than walking `Poly_Triangulation` from Python. +3. The writer emits each face's triangles in explorer order. Per-face counts + propose the OCCT face id of each display triangle (`triangle_faces`), then + each group is checked against the independent OCCT triangulation bounds + and sampled centroids. Picking and face highlights use the display + triangles only after that validation; a count or geometry mismatch + extracts separate pick triangles instead. +4. Edges are discretized with `GCPnts_TangentialDeflection`. Free vertices + are sent as points. +5. Each mesh gets a **content id**: a BLAKE2b hash of the shape's binary BREP, + the tolerances and the mesh generator (`mesh_generator()`: the + `MESH_FORMAT` of `tessellation.py`, the OCP version and the installed OCP + binary). The GUI keeps meshes across Python restarts, so after a switch to + another environment or an OCP upgrade the ids change and no mesh of the + previous mesher is reused. + +`GeometryCache` is an LRU of 256 MB keyed by that id. On top of it, the GUI +sends the ids of meshes it already has (`known_geometry`), and the worker +answers with a bare reference instead of the arrays. Re-running an unchanged +model, or showing the same part many times in an assembly, sends each mesh +only once: after editing one part of an assembly, only that part is meshed, +sent and uploaded again. + +On the GUI side, `MeshLibrary` (`scene.rs`) holds the meshes by content id. +It pins the meshes a running request may reference and retains up to +128 MB of recently used ones beyond the shown scene. A reference, or a full +mesh for geometry it still holds, resolves to the same `Arc`, and the +renderer keeps GPU buffers per mesh for as long as it lives, so a render +after Clear, a debugging session and repeated runs reuse both the CPU mesh +and its GPU buffers. + +## Persistence + +| Data | Where | How | +| --- | --- | --- | +| Preferences, layout, window, open tabs, project folders | `app.ron` | eframe persistence (`App::save`) | +| Scripts | wherever you save them | `document.rs`: temp file + atomic replace (`ReplaceFileW`/`MoveFileExW` on Windows, `rename` elsewhere), synchronized to disk | +| Recovery session | `recovery/active-session.json` | Every tab with unsaved changes, in tab order; written every 5 s while one is modified. The single snapshot of earlier releases is still read | +| Local history | `recovery/history//version--.json` | One folder per document (FNV-1a hash of its path, `untitled` for buffers without a file); file names carry the timestamps, so a checkpoint lists one small folder and reads no JSON. 20 newest versions per document; once per session, versions older than 90 days and the oldest beyond 64 MB in total are removed | +| Log | `logs/cq-editor.log`, `logs/cq-editor.1.log` | `logging.rs` appends every Log panel line and GUI panics; rotated at 2 MB | + +## Design principles + +* **The script is the source of truth.** The GUI shows and explains what + the code produced. Changes made in the GUI (colors, visibility) never + rewrite the script. +* **Compatibility.** Scripts written for the original PyQt CQ-editor run + unchanged: same `show_object` options, same namespace, same execution + settings. User-interface equivalence and intentional differences are + recorded separately in the [compatibility matrix](compatibility.md). +* **The UI thread never blocks** on Python, on the disk for long, or on the + network. +* **No silent data loss.** Atomic saves, recovery checkpoints, conflict + dialogs. +* **One code path per command** (`Action`), shared by menus, toolbar and + shortcuts. diff --git a/docs/development/building.md b/docs/development/building.md new file mode 100644 index 000000000..dd9fcc030 --- /dev/null +++ b/docs/development/building.md @@ -0,0 +1,162 @@ +# Building + +## Requirements + +* **Rust 1.88 or newer** (edition 2024), installed with + [rustup](https://rustup.rs). +* Python 3.11–3.14 with a matching supported CadQuery/OCP environment, to *run* the editor and the worker + tests (see [Installation](../getting-started/installation.md)). Python is + not needed to compile. + +```sh +cargo build # debug build: target/debug/cq-editor +cargo build --release # release build: target/release/cq-editor +cargo run -- examples/01_hello_box.py +``` + +### Debug and release builds + +| | Debug | Release | +| --- | --- | --- | +| Worker sources | Loaded from `worker/` in the source tree. Python edits apply on the next worker restart (Run > Restart Python) | Embedded in the executable and extracted to the data folder on first use | +| Console window on Windows | Yes (logs are visible) | No (`windows_subsystem = "windows"`). `--help` and command-line errors are written to the console of the shell that started it, or shown in a message box | +| Optimization | Dependencies are optimized (`opt-level = 2`), the crate itself is not, and only line tables are kept for debugging | Fat LTO with one codegen unit, stripped | +| `.venv` discovery | Also looks in the source tree | Next to the executable and in the working directory | + +`CQ_EDITOR_WORKER_DIR=/path/to/dir` makes any build load the `cq_worker` +package from `dir` instead. + +`build.rs` embeds every `.py` file of `worker/cq_worker/` and `examples/`. +Adding a worker module or an example therefore needs no code change: it is +picked up on the next build. + +## Linux + +Install the development packages for keyboard handling and the GTK file +dialogs (the same ones CI uses on Ubuntu 22.04): + +```sh +sudo apt-get install -y libxkbcommon-dev libgtk-3-dev +``` + +## macOS + +Install the Xcode command line tools (`xcode-select --install`). No other +dependency is needed. + +## Windows + +Two Rust toolchains work. + +### MSVC (recommended for most people) + +Install the *Desktop development with C++* workload of Visual Studio (or the +Build Tools), then: + +```powershell +rustup default stable-x86_64-pc-windows-msvc +cargo build --release +``` + +Nothing else is needed. + +### GNU (no Visual Studio) + +The `x86_64-pc-windows-gnu` toolchain avoids Visual Studio, but its minimal +self-contained MinGW environment lacks **`as` and `dlltool`** from MinGW-w64 +binutils, used by the `windows` crates to build import libraries. Install +binutils, for example from [WinLibs](https://winlibs.com) or MSYS2 (`pacman +-S mingw-w64-x86_64-binutils`), and put its `bin` folder on `PATH`. +Otherwise the build fails with *dlltool could not create import library*. + +Then build from a shell where binutils is on `PATH`: + +```sh +export PATH="$HOME/.cargo/bin:/path/to/mingw/bin:$PATH" +cargo build --release +``` + +The `.exe` gets its icon and version information (shown by Explorer) from a +resource compiled by `build.rs` with `windres`, which also needs `gcc` as its +preprocessor: both come with a full MinGW-w64 installation (MSYS2: `pacman +-S mingw-w64-x86_64-gcc`). Without them the build still succeeds, with a +warning and an executable without that information. The MSVC toolchain uses +`rc.exe` from the Windows SDK instead. Release builds in CI set +`CQ_EDITOR_REQUIRE_RESOURCES=1`, which makes a missing resource compiler an +error. + +Links are opened with the `open` crate rather than eframe's `links` feature, +so the GNU toolchain no longer needs a hand-made `libshlwapi.a`. + +Setting `CARGO_INCREMENTAL=0` reduces the size of `target/` considerably, +which helps on small disks. + +## Release builds in CI + +`.github/workflows/release.yml` runs for a version tag (or manually without +publishing). It builds the native Rust executable and then uses constructor +3.17.3 to create four self-contained distributions: + +* Windows x86_64 `.exe`; +* Linux x86_64 self-extracting `.sh`; +* macOS Apple Silicon `.pkg`; +* macOS Intel `.pkg`. + +`packaging/constructor/construct.yaml` pins Python, CadQuery, OCP, Jedi and +menuinst. The Rust executable is copied into the same private prefix and +`src/worker/launch.rs` discovers that bundled Python before global or active +environments. Explicit user choices still win. + +That runtime is most of an installer: Qt 6 (which VTK links), VTK, OCCT, +LLVM (for Numba) and Python, against about 20 MB for the editor. Its +`exclude` list leaves out the Boost, Eigen and TBB development files that +the `vtk` metapackage brings for compiling against VTK, about 17,000 files +and 230 MB once installed, which nothing loads at run time. Constructor +fails if a listed package is no longer in the solved environment, so check +the list when a pin changes. + +The Windows job signs the native executable and the finished installer with +Authenticode and an RFC 3161 timestamp. The macOS jobs sign the native editor +with Developer ID Application; constructor signs the embedded bootstrap and +package with the Application and Installer identities. Apple notarization must +accept each package, and the ticket is stapled and verified before upload. +Missing credentials or a failed signature stops the release. Linux continues +to publish its checksum without platform code signing. + +Configure these GitHub Actions repository secrets before pushing a release tag: + +| Platform | Secret | Value | +| --- | --- | --- | +| Windows | `WINDOWS_SIGNING_PFX_BASE64` | Base64 of the Authenticode `.pfx` including its private key | +| Windows | `WINDOWS_SIGNING_PFX_PASSWORD` | Password for that `.pfx` | +| macOS | `MACOS_APPLICATION_P12_BASE64`, `MACOS_APPLICATION_P12_PASSWORD` | Base64 of the Developer ID Application `.p12` and its password | +| macOS | `MACOS_INSTALLER_P12_BASE64`, `MACOS_INSTALLER_P12_PASSWORD` | Base64 of the Developer ID Installer `.p12` and its password | +| macOS | `MACOS_APPLICATION_IDENTITY`, `MACOS_INSTALLER_IDENTITY` | Full identity names, including team ID, matching the certificates | +| macOS | `MACOS_NOTARY_KEY_P8_BASE64`, `MACOS_NOTARY_KEY_ID`, `MACOS_NOTARY_ISSUER_ID` | Base64 App Store Connect API private key, key ID and issuer ID for `notarytool` | + +The signing certificates are written only to the hosted runner's temporary +directory. The Windows PFX is deleted after each signature, and the macOS +temporary keychain is deleted at the end of the job. The workflow never puts +certificates in the repository or release artifacts. Constructor's +[signing options](https://conda.github.io/constructor/howto/#signing-and-notarization) +are enabled only when the macOS identities are supplied; local builds without +credentials are still possible but must not be published as release artifacts. + +Each matrix job installs its finished artifact, imports the bundled CAD +runtime and starts the installed executable with `--help`. Publication waits +for all four smoke tests, generates `SHA256SUMS.txt`, creates the GitHub +release and attaches the installers plus constructor's dependency lockfiles. +The tag must exactly equal the Cargo package version, for example `0.9.0`. + +To build on one platform manually, first create `target/release/cq-editor` +(or `.exe`), install constructor 3.17.3 from conda-forge and run: + +```sh +mkdir dist +cd dist +constructor ../packaging/constructor +``` + +macOS additionally needs the `.icns` prepared as shown in the release +workflow. Constructor builds only for the host platform; it does not +cross-compile native installers. diff --git a/docs/development/compatibility.md b/docs/development/compatibility.md new file mode 100644 index 000000000..308693581 --- /dev/null +++ b/docs/development/compatibility.md @@ -0,0 +1,245 @@ +# Compatibility with the original CQ-editor + +This document is the compatibility contract for the Rust rewrite. It prevents +"implemented" from being used as a synonym for "equivalent" and makes every +known removal or changed behavior explicit. + +## Baseline and rules + +The baseline is commit [`71903d5`](https://github.com/igors93/CQ-editor/tree/71903d5), +the last PyQt/OCCT revision immediately before the Rust rewrite. The primary +legacy surfaces are +[`viewer.py`](https://github.com/igors93/CQ-editor/blob/71903d5/cq_editor/widgets/viewer.py), +[`occt_widget.py`](https://github.com/igors93/CQ-editor/blob/71903d5/cq_editor/widgets/occt_widget.py), +[`editor.py`](https://github.com/igors93/CQ-editor/blob/71903d5/cq_editor/widgets/editor.py) +and +[`main_window.py`](https://github.com/igors93/CQ-editor/blob/71903d5/cq_editor/main_window.py). +The eight scripts `01` to `08` in `examples/` are byte-for-byte unchanged from +that commit and are executable compatibility fixtures; later examples are +additions. + +Compatibility means the same user-visible result or script contract. It does +not require the same toolkit, process model or rendering implementation. A +legacy defect is not preserved merely for fidelity; a corrected behavior is +marked **Enhanced** and protected by a regression test. + +The states below have precise meanings: + +* **Verified**: an automated test exercises the compatible result. +* **Enhanced**: the original result remains available and a tested superset or + deliberate defect correction is provided. +* **Changed**: a deliberate, documented product decision replaces the old + behavior. +* **Gap**: the original capability is not currently delivered. +* **Unverified**: it is implemented, but no automated test proves the complete + user interaction yet. It must not be described as equivalent. + +## Compatibility matrix + +The first column is a stable contract id. `compatibility_matrix_is_complete_and_evidenced` +checks that no row disappears, every Verified/Enhanced row points to a real +test, and every Changed/Gap/Unverified row points to an explicit decision or +follow-up. A passing matrix test therefore proves the inventory is maintained; +it does not turn the open gap into a supported feature. + +| Contract id | Original capability and current result | State | Evidence or decision | +| --- | --- | --- | --- | +| `file.lifecycle` | New, Open, Save and Save As preserve the editable Python file workflow. Saves are now atomic, and files open in tabs, so opening one no longer replaces the current file. | Enhanced | `tests/rust/editor/test_document.rs::preserves_line_endings_and_tracks_modification` | +| `file.autoreload` | Automatic reload and imported-file watching remain; local edits now require an explicit conflict decision. | Enhanced | `tests/rust/editor/test_document.rs::reload_refuses_to_discard_unsaved_changes` | +| `file.recovery` | Unsaved buffers gain crash recovery and local history, for every open tab. | Enhanced | `tests/rust/editor/test_recovery.rs::checkpoint_restores_unsaved_work_after_a_simulated_crash` | +| `editor.syntax` | Python syntax highlighting and the injected CQ-editor names remain recognized. | Verified | `tests/rust/editor/test_highlight.rs::recognizes_python_constructs` | +| `editor.editing` | Line numbers, breakpoints, indentation and Toggle Comment remain; markers now follow edits. | Enhanced | `tests/rust/editor/test_text_ops.rs::comments_blocks_at_the_common_indentation` | +| `editor.search` | Find and repeated match navigation remain available. | Verified | `tests/rust/editor/test_editor.rs::finds_matches_with_and_without_case` | +| `editor.completion` | Jedi completion and call signatures remain optional and use the live namespace. | Verified | `tests/worker/execution/test_completion.py::test_completion_uses_live_namespace_values` | +| `script.examples` | All eight projects shipped before the rewrite still execute and produce a visible model. | Verified | `tests/worker/execution/test_examples.py::test_legacy_example_executes_and_produces_a_model` | +| `script.show-object` | `show_object(obj, name, options, **options)` and variable-derived names remain supported. | Verified | `tests/worker/execution/test_execution.py::test_show_object_names_from_variables` | +| `script.discovery` | CadQuery values are still displayed when a script omits `show_object`. | Verified | `tests/worker/geometry/test_scene.py::test_find_cq_objects_ignores_private_and_plain_values` | +| `script.logging` | `print` output and `log()` messages still reach their panels. | Verified | `tests/worker/protocol/test_server.py::test_script_log_reaches_the_gui` | +| `script.execution-settings` | Reload CadQuery, script directory on `sys.path`, script working directory and imported-module reload remain configurable. | Verified | `tests/worker/execution/test_environment.py::test_script_environment_respects_disabled_path_and_cwd_changes` | +| `debugger.controls` | Debug, Step, Step in and Continue remain; Step out and Stop were added. | Enhanced | `tests/worker/execution/test_debugger.py::test_step_in_and_out` | +| `debugger.breakpoints` | Gutter breakpoints remain and now follow inserted or deleted lines. | Enhanced | `tests/rust/editor/test_editor.rs::breakpoints_and_the_error_line_follow_inserted_and_deleted_lines` | +| `debugger.errors` | Tracebacks retain script lines and nested call frames; variables remain described separately. | Verified | `tests/worker/execution/test_execution.py::test_errors_inside_script_functions_keep_the_call_chain` | +| `console.state` | The Python console remains interactive, multiline and persistent across commands. | Verified | `tests/worker/execution/test_console.py::test_console_keeps_variables_between_commands` | +| `console.rich-output` | Expression results and `display()` show images (matplotlib figures, `_repr_png_`, `_repr_jpeg_`) and plain text, checked and bounded; HTML, SVG and LaTeX show their plain text. | Changed | Decision: [Rich console](#rich-console); tested by `tests/worker/execution/test_display.py::test_the_console_sends_results_and_images_after_what_was_printed` | +| `inspector.workplane` | The CQ Inspector still traverses Workplane parents and can display a stack item, plane and grid. | Verified | `tests/worker/protocol/test_server.py::test_inspection` | +| `objects.tree` | Objects and assembly children retain visibility, selection, removal and clearing semantics. | Verified | `tests/rust/scene/test_scene.rs::hiding_a_parent_hides_the_subtree` | +| `objects.properties` | Visibility and colors can be preserved by name; color and opacity editing are a tested superset. | Enhanced | `tests/rust/scene/test_scene.rs::properties_survive_a_reload_by_name` | +| `objects.assemblies` | Assemblies can remain hierarchical or be merged, retaining per-part transforms and colors. | Verified | `tests/worker/geometry/test_scene.py::test_builder_explodes_assemblies` | +| `export.step-stl` | Selected objects still export to STEP and STL; BREP was added. | Enhanced | `tests/worker/protocol/test_server.py::test_export` | +| `tools.upload` | Python or exported model bytes can still be uploaded to the configured service. | Verified | `tests/worker/protocol/test_server_commands.py::test_step_upload_sends_actual_model_bytes` | +| `tools.update` | CadQuery release checks remain available; CQ-editor's own releases are checked too, by hand and once a day. | Enhanced | `tests/worker/protocol/test_server_commands.py::test_update_checks_can_cover_cq_editor_and_skip_cadquery` | +| `viewer.standard-views` | Fit, isometric, top, bottom, front, back, left and right camera results remain. | Verified | `tests/rust/viewer/test_camera.rs::standard_views_look_where_expected` | +| `viewer.display-modes` | Shaded and wireframe keep their commands and shortcuts; X-ray and hidden-line modes and per-object edge visibility were added. Each mode is rendered offscreen and its pixels are checked. | Enhanced | `tests/rust/viewer/test_renderer.rs::display_modes_render_faces_edges_and_fills_as_documented` | +| `viewer.projection` | Orthographic and perspective cameras remain and produce consistent pick rays. | Verified | `tests/rust/viewer/test_camera.rs::projection_round_trips_through_rays` | +| `viewer.mouse` | Left orbit/select, middle or Ctrl+left pan, Shift+left zoom and wheel zoom retain their bindings; right drag now orbits instead of zooming, and an orbit begun on the model turns around the point under the pointer. | Changed | Decision: [Mouse navigation](#mouse-navigation); tested by `tests/rust/viewer/test_navigation.rs::mouse_gestures_choose_their_navigation_modes` | +| `viewer.navigation-cube` | Face/edge/corner views and 45-degree roll remain, with native hover feedback and animation. | Enhanced | `tests/rust/viewer/test_overlays.rs::arrows_are_hit_on_both_sides` | +| `viewer.selection` | Object selection remains and now resolves stable OCCT face, edge and vertex identities. | Enhanced | `tests/rust/viewer/test_picking.rs::prioritizes_vertices_then_edges_then_faces` | +| `viewer.screenshot` | Tools > Screenshot still saves the view as PNG; larger sizes (drawn in tiles), a transparent background and turntable animations were added. Capture, tiling, transparency and PNG writing are tested; only the native save dialog is not. | Enhanced | `tests/rust/viewer/test_renderer.rs::captures_leave_out_a_transparent_background_and_scale_edges` | +| `viewer.stereo` | The Stereo, MonoLeftEye and MonoRightEye projections and the Anaglyph, RowInterlaced, ColumnInterlaced, ChessBoard, SideBySide and OverUnder modes are rendered and tested; QuadBuffer cannot be presented by wgpu and visibly falls back to the anaglyph. | Changed | Decision: [Stereo projection](#stereo-projection) | +| `panels.docking` | All legacy panels are dockable and resizable, but full drag/detach/layout equivalence has no automated UI test. | Unverified | Follow-up: [GUI-only validation](#gui-only-validation) | +| `preferences.persistence` | Supported preferences and the dock layout persist across sessions. | Verified | `tests/rust/app/test_settings.rs::preferences_round_trip_through_json` | +| `preferences.defaults` | Configurable font and tessellation settings remain, but three numeric defaults differ from the PyQt values. | Changed | Decision: [Preference defaults](#preference-defaults) | +| `shortcuts.legacy` | Every legacy file, editor, debugger and view shortcut is retained; additions do not replace them. | Verified | `tests/rust/app/test_commands.rs::legacy_shortcuts_are_preserved` | +| `behavior.rand-color` | `rand_color()` now defaults to visible opacity instead of reproducing the original invisible-color defect. | Enhanced | `tests/worker/execution/test_execution.py::test_rand_color_is_reproducible` | +| `ui.theme` | Separate application/editor schemes became one System/Light/Dark application theme. | Changed | Decision: [Theme settings](#theme-settings) | +| `packaging.distribution` | Native installers again bundle Python and CadQuery; they add platform launchers, install without a pre-existing environment and are smoke-tested after installation. | Enhanced | `tests/packaging/test_release.py::test_installer_contains_a_pinned_cadquery_runtime` | +| `worker.isolation` | Script execution moved out of process; crashes no longer take down the editor and stale scene ids cannot collide after restart. | Enhanced | `tests/worker/protocol/test_worker_process.py::test_worker_can_be_restarted_after_a_native_process_exit` | + +## Exact interaction inventory + +### Legacy shortcuts + +The compatibility test asserts the complete set below. Ctrl means the +platform command modifier where appropriate. + +| Area | Action | Original | Current | +| --- | --- | --- | --- | +| File | New / Open / Save / Save As / Quit | Ctrl+N / Ctrl+O / Ctrl+S / Ctrl+Shift+S / Ctrl+Q | Preserved | +| Edit | Toggle Comment / Auto-Complete / Search | Ctrl+/ / Alt+/ / Ctrl+F | Preserved; Ctrl+Space also completes | +| Run | Render / Debug / Step / Step in / Continue | F5 / Ctrl+F5 / Ctrl+F10 / Ctrl+F11 / Ctrl+F12 | Preserved; Step out and Stop added | +| View | Fit / Iso / Top / Bottom / Front / Back / Left / Right | Shift+F1 through Shift+F8 | Preserved | +| View | Wireframe / Shaded | Shift+F9 / Shift+F10 | Preserved; X-Ray and Hidden Line added on Shift+F11 / Shift+F12 | + +### Legacy mouse behavior + +| Gesture | Original result | Current result | +| --- | --- | --- | +| Left drag | Orbit using Turntable or Trackball | Preserved; a drag begun on the model now holds its picked point on screen | +| Left click without a drag | Select | Preserved; exact topology is also returned | +| Middle drag or Ctrl+left drag | Pan | Preserved | +| Right drag or Shift+left drag | Zoom | Right drag now orbits around the point under the pointer; Shift+left still zooms | +| Wheel | Zoom | Preserved; anchored at the pointer | +| Navigation cube or roll arrow click | Reorient or roll by 45 degrees | Preserved | + +### Legacy preferences + +| Original group | Original setting | Current mapping | +| --- | --- | --- | +| General | Light/Dark Theme | System/Light/Dark application theme; see the decision below | +| Viewer | Fit automatically, navigation cube, gradient and two background colors | Preserved | +| Viewer | Deviation and angular deviation | Preserved as tessellation tolerances; the defaults changed as documented below | +| Viewer | Projection Type | Orthographic, Perspective, Stereo, MonoLeftEye and MonoRightEye preserved, under the same setting names | +| Viewer | Stereo Mode | Anaglyph, RowInterlaced, ColumnInterlaced, ChessBoard, SideBySide and OverUnder preserved; QuadBuffer falls back to the anaglyph, see the decision below | +| Viewer | Orbit Method | Turntable and Trackball preserved | +| Editor | Font size, autoreload, reload delay, imported-file watch, line wrap and maximum line length | Preserved; the font-size default changed as documented below | +| Editor | Color scheme | Merged into the application theme | +| Debugger | Reload CQ, add script directory, change working directory and reload imported modules | Preserved as Execution settings | +| Objects | Preserve properties, clear before run, merge assemblies and STL precision | Preserved | + +Default shape/edge colors, edge visibility/width, axes, animation and STL +angular tolerance are additions rather than legacy settings. + +## Known differences and decisions + +### Stereo projection + +The legacy modes were thin bindings to OCCT's `Graphic3d_Camera` and +`Graphic3d_StereoMode`. The wgpu renderer now draws them itself (`FEAT-C8`): +the two eyes are perspective cameras 5% of the target distance apart (OCCT's +default relative interocular distance), with off-axis frustums that converge +on the target's plane, and a composition pass combines them. + +* **Stereo**, **MonoLeftEye** and **MonoRightEye** keep their meaning; mono + eyes also pick from their eye. + `tests/rust/viewer/test_camera.rs::the_eyes_of_the_stereo_pair_agree_on_the_target_plane` + and `mono_eye_projections_draw_and_pick_from_one_eye` check zero parallax + at the target, crossed disparity in front of it and consistent pick rays. +* **Anaglyph** (OCCT's default optimized red-cyan filter), **RowInterlaced**, + **ColumnInterlaced**, **ChessBoard**, **SideBySide** and **OverUnder** are + composed on the GPU for the view and on the CPU for screenshots; + `tests/rust/viewer/test_stereo.rs` checks each mode's layout, and + `tests/rust/viewer/test_renderer.rs::stereo_modes_compose_on_the_gpu_as_the_reference_does` + checks that the GPU composition gives the same pixels as the CPU one + (exactly, or within one level for the anaglyph's mixing), on the software + adapter in CI. +* **QuadBuffer** needs a stereo swap chain (one back buffer per eye) and + stereo glasses synchronized by the driver. wgpu exposes no such surface on + any backend, and most current drivers dropped it, so this mode is + **Changed**: it is still offered, under its name, and the view shows the + red-cyan anaglyph with a note saying so, instead of silently showing + something else. + +Side-by-side and over-under draw each eye at half the width or height +without stretching it (for free viewing and for displays that take that +layout), where OCCT could also stretch them for 3D televisions. + +### Mouse navigation + +The original editor zoomed with a right drag. Right drag now orbits like a +left drag. Both turn around the model point under the pointer when the drag +begins on the model, and that point stays in place on screen, also in a +panned view; begun on empty space, they turn around the middle of the view +as before. Zoom keeps the wheel, the touchpad pinch, Shift + left drag and +the zoom controls, so only the right drag changed. The pointer point is +picked after any camera transition has ended, in the view the drag turns +(`tests/rust/viewer/test_navigation.rs::an_orbit_turns_around_the_model_point_under_the_pointer`). + +### Rich console + +The old console embedded an in-process Jupyter kernel and could render rich +IPython output. The isolated worker keeps user code out of the GUI process, +so rich results travel as serialized MIME bundles (`FEAT-E6`): expression +results and `display()` show their image (matplotlib figures, anything with +`_repr_png_` or `_repr_jpeg_`) and their plain text. The worker only sends +PNG or JPEG images it has checked, within size and count limits, and the +GUI decodes them away from the drawing thread, within its own limits. HTML, +Markdown, SVG and LaTeX are deliberately not rendered: they would need a web +view and would let user code put markup or scripts in the GUI; their plain +text is shown instead. Plain Python evaluation, multiline input, completion, +history, `show_object`, `debug`, stdout and errors remain covered. + +### Theme settings + +The editor and application no longer have independent Light/Dark choices. +One System/Light/Dark theme prevents unreadable mixed combinations and follows +the operating system by default. This is an intentional settings migration, +not a missing editor feature. + +### Preference defaults + +The PyQt baseline used font size `12`, deviation `1e-5` and angular deviation +`0.1`. The current defaults are `13`, `1e-3` and `0.2`. Font units and raster +metrics differ between Qt and egui, so equal numbers do not imply equal visual +size. Tessellation now occurs in a separate process and its mesh crosses the +worker protocol; the looser defaults bound routine render cost. The legacy +values remain configurable, and worker tests verify that a finer tolerance +produces a finer mesh and that large structural dimensions retain small +cross-sections. These defaults must not be described as identical. + +### Distribution + +The old PyInstaller and conda-constructor paths bundled the Python runtime and +dependencies. The new constructor installers retain that property while the +Rust executable keeps its worker source embedded: Windows receives an `.exe`, +Linux a self-extracting `.sh`, and macOS a `.pkg` for each supported CPU +architecture. The application prefers the bundled runtime unless the user +explicitly chooses another interpreter. Release CI installs every artifact, +imports CadQuery/OCP/Jedi, starts the installed executable with `--help`, and +publishes checksums plus the resolved package lockfile. Signing still depends +on platform certificates and is not claimed when release credentials are not +configured. + +### GUI-only validation + +Free-form dock dragging crosses native window boundaries. It remains +**Unverified**, not presumed equivalent. `ENG-03` tracks a headless UI +harness. The display modes and screenshots are no longer in this group: +`tests/rust/viewer/test_renderer.rs` renders them offscreen on any wgpu +adapter and checks pixels that each must produce (tiled captures included), +and `tests/rust/viewer/test_capture.rs` checks the PNG and animated PNG +files; CI requires the software adapter (WARP) on Windows, so the pixel +checks always run there. The native save dialog is the only untested part +of a screenshot. + +## Change policy + +Any change to a legacy capability must do one of the following in the same +commit: + +1. preserve or enhance it and add/update automated evidence; +2. mark it Changed with the product decision and migration behavior; or +3. mark it as a Gap with a tracked roadmap item. + +A feature may move to Verified only when its named test exercises the stated +result. Passing unrelated unit tests or merely retaining a menu label is not +equivalence evidence. diff --git a/docs/development/contributing.md b/docs/development/contributing.md new file mode 100644 index 000000000..c39f35ed5 --- /dev/null +++ b/docs/development/contributing.md @@ -0,0 +1,72 @@ +# Contributing + +Contributions of all sizes are welcome: bug reports, documentation fixes, +examples, features. For larger changes, open an issue or a +[discussion](https://github.com/igors93/CQ-editor/discussions) first, so +the direction can be agreed on before you invest time. The +[roadmap](../roadmap.md) lists known bugs and planned work. + +## Workflow + +1. Fork the repository and create a branch from `master`. +2. Build and run the editor ([Building](building.md)). +3. Make your change, with tests ([Testing](testing.md)). +4. Run the CI checks locally: + + ```sh + cargo fmt --all -- --check + cargo clippy --locked --all-targets --all-features -- -D warnings + cargo test --locked + black --check worker tests/worker tests/packaging packaging/constructor/prepare_macos_icon.py + ruff check --isolated --select E4,E7,E9,F worker tests/worker tests/packaging packaging/constructor/prepare_macos_icon.py + python -m unittest discover -s tests/packaging -p "test_*.py" + PYTHONPATH=worker python -m coverage run --branch --source worker/cq_worker -m pytest tests/worker + python -m coverage report --show-missing --fail-under=85 + ``` + +5. Update the documentation in `docs/` if behavior changed, and add a line + to [the changelog](../changelog.md) under *Unreleased*. +6. Open a pull request describing what changed and why. + +## Code style + +* **Rust:** `cargo fmt`, no clippy warnings, edition 2024. +* **Python:** `black`, type hints, `from __future__ import annotations`, and + compatibility with the supported Python/CadQuery/OCP matrix (the worker + runs in the user's environment). +* **Comments and docs in English.** Comments explain *why*, not what the + code already says. Every module starts with a short doc comment saying + what it is for. +* **Keep the worker dependency-free** beyond CadQuery, numpy and the + standard library (`jedi` is optional). It runs inside environments we do + not control. + +## Where to make common changes + +| Change | Where | +| --- | --- | +| A new command (menu item, toolbar button, shortcut) | Add a variant to `Action` in `src/commands.rs` (and a shortcut in `shortcuts()`), handle it in `AppState::execute` in `src/app/mod.rs` (dock layout actions go to `CqEditorApp::execute`) and put the work in the `src/app/` module of its concern, then add the menu item in `src/ui/menu_bar.rs` and/or the button in `src/ui/toolbar.rs` | +| A new preference | A field with a default in `src/settings.rs` (keep `#[serde(default)]` so old `app.ron` files still load), a row in `src/dialogs/preferences.rs`, a line in [Preferences](../user-guide/preferences.md) | +| A new worker request | A `Request` and a `Message` variant in `src/worker/protocol.rs`, a handler in `Server._handlers` (`worker/cq_worker/server.py`), and a row in [Worker protocol](protocol.md). Bump `PROTOCOL_VERSION` on both sides if old workers would misbehave | +| A new `show_object` option | `DisplayOptions` in `worker/cq_worker/scene.py`, `SceneNode` in `protocol.rs`, the renderer, and [Writing scripts](../user-guide/scripting.md) | +| A new panel | A `Tab` in `src/panels/mod.rs` with its default position, a module in `src/panels/` | +| A new example | A commented `NN_name.py` in `examples/`. It appears in *File > Examples* automatically | +| How runs, queued renders, stale results or pending requests behave | `Execution` in `src/app/execution.rs`, a pure state machine; add the transition to `tests/rust/app/test_execution.rs` | +| A change to how meshes are produced | `worker/cq_worker/tessellation.py`; bump `MESH_FORMAT` when the same shape and tolerances would mesh differently, so the GUI never reuses a mesh of the previous format | +| A new export format | `ExportFormat` in `protocol.rs` and `FORMATS` / `export()` in `worker/cq_worker/exporting.py` | + +## Principles to keep + +These are what make CQ-editor CQ-editor (see [Architecture](architecture.md#design-principles) +and [Roadmap](../roadmap.md#guiding-principles)): + +* the **script stays the source of truth**. A GUI feature may generate or + insert code, but it must never hide the model in a GUI-only state; +* scripts written for the original CQ-editor must **keep working**; +* the interface must **never block** on Python; +* the editor must **never lose user work**. + +## Reporting bugs + +See [Reporting a bug](../../README.md#reporting-a-bug) in the README. Please +include the lines from the Log panel and the versions from *Help > About*. diff --git a/docs/development/dependency-compatibility.md b/docs/development/dependency-compatibility.md new file mode 100644 index 000000000..052ecf284 --- /dev/null +++ b/docs/development/dependency-compatibility.md @@ -0,0 +1,79 @@ +# CadQuery and OCP compatibility + +The worker calls OCP directly for tessellation, topology and exact +measurements, so a successful `import cadquery` is not enough to establish +compatibility. Generated OCP names can change even when the corresponding +OCCT operation still exists. + +## Supported matrix + +These are the reproducible CI environments. The exact OCP patch is pinned in +CI; the package metadata uses the wider supported families so normal installs +can receive compatible fixes. + +| Lane | Python | CadQuery | cadquery-ocp | Policy | +| --- | --- | --- | --- | --- | +| Previous CadQuery minor | 3.11 | 2.7.0 | 7.8.1.1.post1 | Required | +| Current stable, minimum Python | 3.11 | 2.8.0 | 7.9.3.1.1 | Required | +| Current stable | 3.12 | 2.8.0 | 7.9.3.1.1 | Required | +| Current stable | 3.13 | 2.8.0 | 7.9.3.1.1 | Required | +| Current stable, maximum Python | 3.14 | 2.8.0 | 7.9.3.1.1 | Required | +| Upstream development | 3.12 | `CadQuery/master` (currently 2.9.0dev) | 8.0.1.1.0 | Early warning | + +The supported package ranges are Python 3.11–3.14, CadQuery 2.7.x–2.8.x and +OCP 7.8.1–7.9.x. The Python window includes security-supported versions with +matching released OCP wheels. Python 3.10 reached end of life in October 2026; +Python 3.15 is still outside this window because OCP 7.9 has no 3.15 wheels. +The CadQuery window contains its last two released minor versions and their +matching OCP families. +The 2.9/OCP 8 lane is an early warning probe until that release is published +and passes the complete suite. + +The released combinations are blocking CI jobs. The development lane +runs the same complete worker suite but is allowed to fail because it follows +a moving external branch. A failure there is still a compatibility issue to +investigate before that CadQuery/OCP family becomes stable. + +The versions were selected from CadQuery's official metadata: + +* [Python version status](https://devguide.python.org/versions/) identifies + the branches still receiving security fixes; +* [CadQuery releases](https://github.com/CadQuery/cadquery/releases) lists + 2.8 and 2.7 as the two latest released minor versions; +* [CadQuery 2.7.0](https://github.com/CadQuery/cadquery/blob/v2.7.0/setup.py) + uses OCP 7.8.x; +* [CadQuery 2.8.0](https://github.com/CadQuery/cadquery/blob/v2.8.0/setup.py) + requires Python 3.11+ and OCP 7.9.x; +* [OCP 7.9 release files](https://pypi.org/project/cadquery-ocp/7.9.3.1.1/) + include wheels through Python 3.14; +* [CadQuery `master`](https://github.com/CadQuery/cadquery/blob/master/setup.py) + currently declares 2.9.0dev, Python 3.11+ and OCP 8.0.1.1; +* [OCP's build matrix](https://github.com/CadQuery/ocp-build-system/blob/main/.github/workflows/build-ocp.yml) + provides the platform-specific Python wheels. + +## What the gate exercises + +`test_compatibility.py` checks that the selected versions match the intended +lane and performs a real box tessellation with topology identifiers. The +complete worker suite then covers execution, assemblies, inspection, GLB +conversion, exact measurements and exports. + +The tessellation suite also compares the display mesh with a separate +face-by-face OCCT extraction across ten shape families. An injected glTF face +reordering preserves every triangle count and verifies that geometric +validation activates the independent pick-mesh fallback. + +OCP 8 moved generated collection types to `OCP.collections` and removed the +`_s` suffix from the `TopoDS` downcasts. `tessellation.py` selects those two +spellings at import time. Geometry behavior is shared; there is no forked +tessellation implementation. + +Every pytest run prints Python, implementation, CadQuery, OCP, platform and +the interpreter path in its header. The worker sends CadQuery and OCP versions +in `ready`, so application logs and timing reports can be tied to the same +environment. The ignored Rust picking benchmark prints its own application +version, OS, architecture, build profile and logical CPU count. + +When a stable CadQuery or Python release changes, add its exact combination +to `.github/workflows/ci.yml`, run the entire worker suite, and only then move +the documented range or remove an older lane. diff --git a/docs/development/protocol.md b/docs/development/protocol.md new file mode 100644 index 000000000..b309f5e0b --- /dev/null +++ b/docs/development/protocol.md @@ -0,0 +1,327 @@ +# Worker protocol (version 12) + +The GUI and the Python worker exchange **one JSON object per line**, encoded +as UTF-8: + +* **requests** go from the GUI to the worker's **stdin** and carry a `cmd` + field; +* **messages** go from the worker to the GUI on a private duplicate of the + original **stdout** and carry a `type` field; +* the worker's **stderr** is free text, shown in the Log panel line by line. + +Definitions: `src/worker/protocol.rs` (Rust, authoritative for the GUI) and +`worker/cq_worker/server.py` (Python). + +## Process start-up + +The GUI runs: + +``` + -u -m cq_worker with PYTHONPATH=[:] + PYTHONIOENCODING=utf-8 + CQ_EDITOR_SESSION= +``` + +`CQ_EDITOR_SESSION` numbers the GUI's successive worker processes. The worker +uses it to namespace its scene keys (see [Scene nodes](#scene-nodes)). + +The worker then: + +1. duplicates descriptor 1 for the protocol, and points descriptor 1 at + stderr. C++ code printing to stdout (OpenCascade) can then never corrupt + the message stream; +2. replaces `sys.stdout`/`sys.stderr` with streams that send `output` + messages, and `sys.stdin` with an empty stream (scripts must not consume + requests); +3. removes a stale `CASROOT` variable and imports CadQuery; +4. sends **`ready`**, or **`fatal`** if the import failed. + +```json +{"type":"ready","protocol":12,"python":"3.12.10","cadquery":"2.8.0","ocp":"7.9.3.1.1","executable":"C:\\…\\python.exe","completion":true,"pid":1234} +{"type":"fatal","message":"Cannot load CadQuery: ModuleNotFoundError: …","detail":"Traceback …","executable":"…"} +``` + +The GUI refuses a worker whose `protocol` differs from its own +`PROTOCOL_VERSION`. **Bump the version on both sides** whenever a change is +not backward compatible. + +## Ids and replies + +Most requests carry an `id` chosen by the GUI. The reply carries the same +`id`. `output` and `log` messages produced while a request is handled are +tagged with that request's id. This is how console output ends up in the +console and script output in the Log panel. + +A failing request is answered with: + +```json +{"type":"error","id":7,"message":"KeyError: \"Unknown object 's1-n3'; it may have been cleared or come from a previous Python session (render again)\""} +``` + +The worker handles one request at a time, in arrival order. + +## Requests + +| `cmd` | Fields | Reply | +| --- | --- | --- | +| `run` | `id`, `script`, `path` (or null), `debug`, `breakpoints` (main script lines), `project_root`, `module_breakpoints` (path to line numbers), `settings` (RunSettings), `scene` (SceneSettings), `known_geometry` (mesh ids), `profile` (time each line; ignored with `debug`) | `run_finished`, preceded by `debug_paused` messages when debugging | +| `debug` | `action` (`continue`, `step`, `step_in`, `step_out`, `stop`), `breakpoints`, `module_breakpoints` | Only while paused. Refreshes breakpoints and resumes the session | +| `release` | `keys` | None. Frees registry entries | +| `complete` | `id`, `source`, `line` (1-based), `column` (0-based, characters), `path`, `target` (`editor` or `console`) | `completions` | +| `describe` | `id`, `source`, `line` (1-based), `column` (0-based, characters), `path` | `description` | +| `inspect` | `id`, `key` | `inspection` | +| `inspect_geometry` | `id`, `key`, `frame`, `item` (or null for the whole frame), `scene` | `inspection_geometry` | +| `measure` | `id`, up to 64 `selections` (`key`, zero-based `part`, `kind`, one-based `identifier`), and `objects` (keys) measured when `selections` is empty | `measurement` | +| `measurement_code` | `id`, `selections`, `objects` as for `measure` | `measurement_code` | +| `selector` | `id`, `selections` of one object, part and kind | `selector` | +| `selector_preview` | `id`, `run_id`, 1-based `line` and character `column`, optional `preferred_key` | `selector_preview` | +| `console` | `id`, `source`, `scene`, `known_geometry`, `selection` (`entities`: picked topology references, `objects`: selected keys) for `selected()` | `display` for each result, `scene_add` (if objects were shown), then `console_result` | +| `console_reset` | `id` | `console_result` | +| `export` | `id`, `keys`, `format` (see Export dialog), `path`, tolerances, STEP mode/schema, STL ASCII, `flat_parts`, `unit`, `on_invalid` (`check`, `fix`, `ignore`), `on_interference` (`check`, `ignore`) | `export_finished` or `geometry_invalid` | +| `check` | `id`, `keys`, `flat_parts`, optional `interference_tolerance`, `clearance` (model units) | `geometry_checked` | +| `interference_geometry` | `id`, `first`, `second` (live pair references from a geometry report), `scene` | `interference_geometry` with exact shared-volume mesh | +| `upload` | `id`, `url`, `file_type` (`step`, `stl`, `py`), `keys`, `source` | `upload_finished` | +| `check_updates` | `id`, `editor` (the GUI's version: list CQ-editor's newer releases), `cadquery` (also list CadQuery's; true when missing) | `updates` | +| `imports` | `id`, `path` | `imports` (local module files imported by the script) | +| `cancel` | `target` (the id of a `run`) | None. Read even while the worker is busy; meshing stops at the next part and the run finishes with `cancelled` | +| `interrupt` | `target` (the id of a `run` or `console` request) | None. Read even while the worker is busy; raises `KeyboardInterrupt` in that request, which then finishes as usual (`interrupted` for a run, a traceback in the console's output) | +| `shutdown` | | The worker exits | + +**RunSettings:** `reload_cq`, `add_script_dir_to_path`, `change_working_dir`, +`reload_imported_modules` (booleans, see [Preferences](../user-guide/preferences.md#execution)). + +**SceneSettings:** `linear_tolerance`, `angular_tolerance` (display mesh), +`merge_assemblies`, `units`. + +## Messages + +| `type` | Fields | Meaning | +| --- | --- | --- | +| `ready` | `protocol`, `python`, `cadquery`, `ocp`, `executable`, `completion`, `pid` | Worker is ready; the version fields identify the exact CAD runtime | +| `fatal` | `message`, `detail`, `executable` | Worker cannot start | +| `output` | `id`, `stream` (`stdout`/`stderr`), `text` | Captured `print` / `sys.stderr` text | +| `log` | `id`, `level`, `source`, `message` | A Python logging record (including the script's `log()`) | +| `run_part` | `id`, `name`, `part` | A complete mesh part, sent before the final scene. The GUI draws received parts progressively and retains their meshes for this request. A single part exceeding the wire limit fails with an error naming the object. | +| `run_finished` | `id`, `ok`, `debug`, `stopped`, `cancelled`, `interrupted`, `objects`, `variables`, `error`, `checks`, `duration`, `timings`, `profile` | End of a run. Meshes in `objects` refer by id to preceding `run_part` messages. `objects` is null when a failed, cancelled or interrupted run should keep the current scene; an interrupted run's `error` is the `KeyboardInterrupt` and its line. `checks` contains script requirements. `timings` is described below. `profile`, for a run asked to profile (null otherwise): `lines` (`file` null for main, `line`, `seconds` with everything the line called, `hits`), `operations` (`file`, `line`, `name`, `seconds`, `calls`), at most 8 per line, and `sources` for project modules | +| `progress` | `id`, `stage` (`meshing`), `done`, `total` | How many of the run's parts (one per shape of an assembly) are meshed: first `0`, at most every 0.1 s, and `total` at the end | +| `debug_paused` | `id`, `line`, `path` (null for the main buffer), `variables`, `objects` | The debugger stopped in this document at `line`. `objects` are the CadQuery locals | +| `completions` | `id`, `available`, `items` (`name`, `insert`, `kind`), `signatures` | | +| `description` | `id`, `available`, `signatures` (call signatures, or `name: type` for a variable), `text` (the docstring, cut to 14 lines / 1200 characters); both empty when there is nothing to show | | +| `inspection` | `id`, `key`, `frames` (`type`, `value`, `line`, `items` (`type`, `value`, `displayable`, `line`)) | Workplane stack, newest first; `line` is the script line that made each step and object | +| `inspection_geometry` | `id`, `meshes`, `plane` (`origin`, `x_dir`, `z_dir`, `size`) | Overlay geometry | +| `measurement` | `id`, `identity`, `entities`, `pair`, `objects`, `bounding_box` | Exact properties of each entity, each with its `bounding_box` (`min`, `max`, `size`, `center`); `pair` (the relationship) only for exactly two. Without entities, `objects` describes the selected objects (`shape_type`, `volume`, `area`, `length`, center of mass, `bounding_box`, topology counts). `bounding_box` surrounds everything measured; boxes come from the exact geometry, not the mesh | +| `measurement_code` | `id`, `code`, `verified`, `problem` | Python repeating the measurement with the script's variables; `verified` when running it on a copy of the console namespace reproduced every value | +| `selector` | `id`, `method` (`faces`, `edges` or `vertices`), `candidates` | CadQuery selectors for the entities, best first. Each candidate has `expression` (to append to the object, e.g. `.faces(">Z")`), `selector` (`">Z"`, null for an index), `description` and `index_based`. Every candidate was verified with CadQuery on the object the script holds | +| `selector_preview` | `id`, `active`, `count`, `matches`, `message` | Exact topology references for a literal selector on a displayed variable from `run_id`; at most 64 highlights. Dynamic expressions are never evaluated for a preview | +| `scene_add` | `id`, `objects` | Objects shown from the console | +| `display` | `id`, `text`, `image` (null, or `format`: `png` or `jpeg`, `data`: base64) | A console result: the value of an expression, or each argument of `display()`. See [Rich console results](#rich-console-results) | +| `console_result` | `id`, `more` | `more` is true when the statement is incomplete | +| `export_finished` | `id`, `path` | | +| `geometry_checked` | `id`, `reports`, `interferences`, `assessment` | Topology per object and exact solid-pair results (`interference`, `contact`, `clearance`, `inconclusive`); declared pairs include `allowance_reason`, and assessment includes the accepted count and status (`clear`, `interference`, or `inconclusive`) | +| `interference_geometry` | `id`, `mesh` | Mesh of the exact positive shared volume for the selected pair | +| `geometry_invalid` | `id`, `reports`, `interferences` | Export wrote nothing and awaits the user's decision about topology or part interference | +| `upload_finished` | `id`, `status`, `body` | HTTP status and response body | +| `updates` | `id`, `current`, `newer`, `editor` | CadQuery release tags newer than `current` (empty when not asked); with `editor`, CQ-editor's newer releases (`current`, `newer`: `tag`, `name`, `url`, newest first, drafts and pre-releases left out) | +| `imports` | `id`, `paths` | | +| `error` | `id`, `message` | A request failed | + +`error` (in `run_finished`) is a ScriptError: `type_name`, `message`, +`frames` (`file`, `line`, `function`, `code`), `line` (the last line of the +script involved), `text` (Python's formatted traceback), and `diagnostic` +(null or `operation`, `receiver`, `line`, `hints`). The editor +buffer appears as the file ``. + +## Scene nodes + +```json +{ + "key": "s1-n4", "name": "bracket", "kind": "Workplane", "inspectable": true, "line": 12, + "color": [0.27, 0.51, 0.71], "alpha": null, "edge_color": null, "finish": "matte_plastic", + "parts": [{ "mesh": { … }, "transform": [16 floats, column-major], "color": null, "alpha": null }], + "children": [] +} +``` + +* `key` identifies the object in the worker's registry. It is used for + `export`, `inspect`, `upload` and `release`. Keys are opaque to the GUI. + They have the form `s-n`, or `n` when + `CQ_EDITOR_SESSION` is not set. A restarted worker therefore never reuses + the keys of objects that are still on screen, and releasing such a stale + key is a no-op. +* An assembly is a node whose `children` mirror the assembly tree. Each + child carries its own parts and placement. +* A part may carry `face_attributes` (`id`, `name`, `layer`, `color`, `alpha`) + indexed by its live OCCT face ids. These belong to the part instance, not + the content-addressed mesh. `material` carries CadQuery's name, density and + density unit; measurements report mass in grams when the density unit is + supported. +* Colors are sRGB floats in 0–1. `null` means "use the default". +* `finish` is the `material` option of `show_object`: `matte_plastic`, + `glossy_plastic`, `brushed_steel`, `aluminum`, `wood`, `default`, or + `null` for the plain shading. The worker refuses unknown names with a + warning; the GUI treats a name it does not know as `null`. +* `line` is the 1-based script line that created the object (for an + assembly child, the line of its `add` call), or the line of the + `show_object` call when the object was not created by this run; `null` + for objects shown from the console. While a script runs, the worker + records the innermost script frame of every new `Workplane`, `Shape`, + `Assembly` and `Sketch` (`provenance.py`). Lines refer to the script text + of the `run` request; the GUI maps them onto the edited text. + +### Meshes + +A full mesh: + +| Field | Encoding | +| --- | --- | +| `id` | Content id: BLAKE2b of the shape's binary BREP, the tolerances and the mesh generator (`MESH_FORMAT`, the OCP version and its installed binary), so an id never names a mesh made by another environment's mesher | +| `positions`, `normals` | base64 of little-endian `f32` triples | +| `indices` | base64 of little-endian `u32`, three per triangle | +| `edges` | base64 `f32` triples, two points per segment | +| `segment_angles` | base64 `f32`, one per segment: degrees between the faces that meet at its edge, at the edge's middle (0 smooth, 90 a box corner, 180 an edge of one face or a wire). The GUI's Sharp edges and Outline styles leave out the edges below an angle. Absent in older meshes, which then count as all 180 | +| `points` | base64 `f32` triples (free vertices) | +| `bbox` | `[[min x, y, z], [max x, y, z]]` | +| `topology` | `triangle_faces` (OCCT face id per pick triangle), `segment_edges` (OCCT edge id per segment), `vertices`, and `face_positions` / `face_indices`: separate pick triangles, normally empty so that `triangle_faces` follows the display `indices` | + +A **reference** is just `{"id": "…"}`. The worker sends it instead of the +arrays when the id is in the request's `known_geometry` or was already sent +earlier for the same request, which includes the previous `debug_paused` +messages of a debugging session. The GUI resolves it from its mesh library +and therefore pins every advertised and received mesh until the request +ends (`run_finished`, `console_result` or a worker restart), even when a +paused view no longer shows it. `scene_add` carries its request `id` for the +same reason. + +`known_geometry` lists every mesh the GUI still holds: the shown ones and +up to 128 MB of recently used ones, so a render after Clear or a debugging +session can also receive references. + +The line transport has explicit memory ceilings. Ordinary control messages +are limited to 2 MiB; the four replies that may carry mesh arrays +(`run_finished`, `debug_paused`, `inspection_geometry` and `scene_add`) have +a separate 512 MiB limit. The reader drains an oversized line without +retaining more than its limit and reports it as `Event::ProtocolError`, +which is not a failed start: nothing later from that process is read, so +the GUI ends the waiting run, says what happened (for a mesh reply, that the +model is too large and how to coarsen it) and starts a new worker. Native +stderr lines retain at most 256 KiB and are marked when truncated. + +Captured `stdout` and `stderr` are flushed in chunks of 64 Ki characters, +even without a newline, and keep at most 1 MiB per stream and request. A +single Python logging record keeps at most 256 Ki characters. Both paths add +an explicit truncation marker rather than silently consuming unbounded +memory; repeated logging records share a 1 MiB per-request ceiling. + +Binary arrays are decoded on the GUI's reader thread, so large models never +stall the interface. Base64 inside JSON is kept on purpose: for a message +with 5 MB of mesh arrays, encoding and serializing take about 35 ms in the +worker and parsing about 6 ms in the GUI, against more than a second of +meshing. Unchanged geometry is not sent at all (see references above). + +`timings` in `run_finished` reports where the time went, in seconds for the +whole request (a debugging session included): `script` (equal to +`duration`), `identify` (content ids), `tessellate` (meshing of geometry not +sent as a reference), `encode` (base64), the mesh counts `meshed`, `cached` +(served from the worker's cache) and `referenced`, `mesh_bytes` (raw arrays +sent in full) and `sent_at` (worker wall clock, seconds since the Unix +epoch). The GUI adds the transfer time, its own parsing and scene decoding, +and writes one *Run timings* line to the Log panel; GPU uploads are logged +at the debug level. + +### Topology identity and measurements + +The topology arrays associate display primitives with the 1-based OCCT face, +edge and vertex order of one live registry entry. A `measure` request resolves +those references with `RegistryEntry.subshape`; it never measures the display +mesh. Registry shapes are already placed in world coordinates, including +assembly locations. + +`measurement.identity` is always +`{"scope":"scene_entry","persistent":false}`. This is an explicit contract: +an id remains usable only while its scene key is alive. OCCT subshape order is +not a persistent naming scheme across rebuilds or remodeling. + +Each entity returns `geometry_type`, `center` and applicable `position`, +`length`, `area`, `radius` and `diameter` values as JSON doubles. A two-entity +response adds exact minimum `distance`, the two closest points and, when the +relationship is well-defined, `angle_degrees`/`angle_kind`. Angles currently +cover straight edge/edge, planar face/face and straight edge/planar face. + +## Debugging sessions + +``` +GUI worker + │ run {debug: true, breakpoints} │ + │ ───────────────────────────────────► │ runs under sys.settrace + │ debug_paused {line: 9} │ pauses, waits for a command + │ ◄─────────────────────────────────── │ + │ complete / inspect / measure / export │ served while paused + │ ───────────────────────────────────► │ + │ debug {action: "step"} │ + │ ───────────────────────────────────► │ resumes + │ debug_paused {line: 10} │ + │ ◄─────────────────────────────────── │ + │ debug {action: "continue"} │ + │ ───────────────────────────────────► │ + │ run_finished │ + │ ◄─────────────────────────────────── │ +``` + +While paused, only `complete`, `inspect`, `inspect_geometry`, `measure`, `selector`, `export`, `check`, +`imports`, `release` and `check_updates` are served. Anything else is +answered with an `error` (*Not available while debugging; continue or stop +first*). + +## Rich console results + +While a `console` request runs, `sys.displayhook` and the console's +`display()` gather each value's representations as Jupyter does +(`_repr_mimebundle_`, `_repr_png_`, `_repr_jpeg_`, and matplotlib figures +through `savefig`), in `worker/cq_worker/display.py`. A representation that +raises is skipped; the value still gets its `repr`. + +Only what the console shows leaves the worker: the plain text and one image. +HTML, Markdown, SVG, LaTeX and JSON are never sent, so no markup or script +from user code reaches the GUI. The worker bounds each message: the text to +64K characters, the image to 4 MB, recognized by its PNG or JPEG signature, +at most 20 images and 100 rich results per command; what is left out is +described in the text. Oversized base64 is rejected before decoding. Standard +output and error are flushed before each `display`, so the console keeps the +order in which things happened. A dedicated 8 MB wire ceiling accepts a +maximum-size rich result without granting it the 512 MB mesh-message limit. + +The GUI does not trust the image either. The reader thread decodes it, never +the thread that draws: only `png` and `jpeg`, at most 4096 pixels on either +side and 128 MB of memory; an image that fails is replaced by *[image not +shown: …]* in the text. The console keeps its newest 50 images; older ones +leave an *[image]* note, and decoded pixels also share a 128 MB retention +budget. Results are accepted only while their console request is still +pending. A slow `_repr_*_` only takes the worker's time, and Stop interrupts +it like any other code. + +## Stopping + +**Cancelling** only stops meshing: before each part the worker reads, without +waiting, whatever the GUI has sent (`PeekNamedPipe` on Windows, `select` +elsewhere), records `cancel` requests and keeps the other requests, in order, +for later. A thread blocked reading stdin is not used: on Windows, loading a +DLL (an `import` of a native module) would wait for that read. The parts +meshed so far are dropped and their registry entries released. + +**Stop** interrupts first. While a `run` or `console` request is handled, a +watcher thread polls the same way every 50 ms; on an `interrupt` for that +request it sends SIGINT to the main thread (`signal.raise_signal` on +Windows, `pthread_kill` elsewhere), so Python raises `KeyboardInterrupt` +there and waits such as `time.sleep` wake up. `_thread.interrupt_main` is +not enough on Windows: it does not wake those waits. The run reports +`interrupted`, the console prints the traceback, and the process keeps its +console namespace and caches. An interrupt that lands after its request +ended is absorbed, so it never reaches the next one, and the worker sets +the default SIGINT handler at start-up, since an inherited "ignore" would +disable all this. + +Python cannot interrupt C++ code: an interrupt is only raised when it +returns to Python. If the request has not answered 3 seconds after the +interrupt, or Stop is pressed again, the GUI kills the worker process and +starts a new one. Events from the old process are discarded by their +generation number. diff --git a/docs/development/testing.md b/docs/development/testing.md new file mode 100644 index 000000000..0e65f4742 --- /dev/null +++ b/docs/development/testing.md @@ -0,0 +1,142 @@ +# Testing + +## Running the tests + +From the repository root, with supported Python 3.11–3.14, CadQuery, pytest (and optionally jedi) +installed in the active Python environment: + +```sh +cargo test --locked # Rust tests +PYTHONPATH=worker python -m pytest tests/worker # worker tests +``` + +In PowerShell, set the path first: + +```powershell +$env:PYTHONPATH = 'worker' +python -m pytest tests/worker +``` + +The network tests use local fakes. The process tests start a real worker but +never contact external services. + +## Layout + +The test folders follow the parts of the application they protect: + +| Folder | Coverage | +| --- | --- | +| `tests/packaging/` | Version synchronization, bundled dependency pins, native shortcuts and the release workflow contract | +| `tests/rust/app/` | Commands, the run and request state machine, editor tabs and projects, preferences, file watching, logging, embedded files and the command line | +| `tests/rust/editor/` | Document persistence, recovery, text editing and highlighting | +| `tests/rust/panels/` | Console behavior and the Objects panel layout | +| `tests/rust/protocol/` | JSON messages, binary mesh decoding and interpreter discovery | +| `tests/fixtures/protocol/` | Golden worker messages read by both Rust and Python, including references, non-finite data and oversized output | +| `tests/rust/scene/` | Scene tree, visibility, selection, colors and bounds | +| `tests/rust/viewer/` | Camera, navigation overlays, picking, section planes, WGSL validation and GPU rendering | +| `tests/worker/execution/` | Script environment, debugger, console and completion | +| `tests/worker/geometry/` | Scene building, display options, colors, registry, glTF reading, tessellation and inspection | +| `tests/worker/protocol/` | Request handling, transport, uploads, releases and real worker processes | + +The shaders are parsed and validated with naga, wgpu's WGSL front end, and +their uniform layouts are compared with the Rust structs, so these tests need +no GPU. The rendering tests in `test_renderer.rs` draw offscreen on whatever +adapter wgpu finds, software adapters included, one test at a time on a +shared device, and pass without checking anything (with a message on +stderr) on a machine that has none. Set `CQ_EDITOR_REQUIRE_GPU=1` to make a +missing adapter fail instead (CI does on Windows), and +`WGPU_ADAPTER_NAME` (part of a name) or `WGPU_BACKEND` to choose one, for +example `WGPU_ADAPTER_NAME="Microsoft Basic Render Driver"` for the +software adapter CI uses on Windows. On Linux, CI renders with Mesa's +llvmpipe through wgpu's OpenGL backend; `WGPU_BACKEND=gl` reproduces that +backend's limits on any machine. + +Rust tests live in `tests/rust/` but are **included from the source module +they test** with `#[cfg(test)] #[path = "…"] mod tests;`. They can therefore +exercise private items without making them public. Python tests share the +protocol fixtures of `tests/worker/conftest.py`. Both suites also read +`tests/fixtures/protocol/messages.json`: the Python writer must emit strict +JSON, and the Rust reader must accept the same mesh parts and references +within its message limits. `tests/rust/app/` draws a modal and a restored +dock with egui's headless `Context::run_ui`, then checks keyboard actions and +visible panels without opening a native window. + +## Continuous integration + +`.github/workflows/ci.yml` runs on every push to `master` and on pull +requests: + +| Job | Steps | +| --- | --- | +| `packaging` (Ubuntu 22.04) | Installer metadata, version and release-workflow contract tests | +| `rust` (Ubuntu 22.04, Windows, macOS) | `cargo fmt --all -- --check` · `cargo clippy --locked --all-targets --all-features -- -D warnings` · `cargo test --locked` | +| `worker` released matrix (Ubuntu 22.04) | Python 3.11/CadQuery 2.7/OCP 7.8 and Python 3.11–3.14/CadQuery 2.8/OCP 7.9 · package check · Black · Ruff · mypy across all worker modules · full pytest suite with branch coverage at least 85% | +| `worker` development probe (Ubuntu 22.04) | Python 3.12 · current `CadQuery/master` · OCP 8.0 · package check · Black · Ruff · mypy · full pytest suite with branch coverage; early-warning lane, allowed to fail while upstream moves | + +Run the same checks locally before opening a pull request: + +```sh +cargo fmt --all -- --check +cargo clippy --locked --all-targets --all-features -- -D warnings +cargo test --locked +black --check worker tests/worker tests/packaging packaging/constructor/prepare_macos_icon.py +ruff check --isolated --select E4,E7,E9,F worker tests/worker tests/packaging packaging/constructor/prepare_macos_icon.py +mypy --config-file worker/pyproject.toml worker/cq_worker +python -m unittest discover -s tests/packaging -p "test_*.py" +PYTHONPATH=worker python -m coverage run --branch --source worker/cq_worker -m pytest tests/worker +python -m coverage report --show-missing --fail-under=85 +``` + +The CI run is the authoritative status. Do not hand-maintain test totals here: +parameterized compatibility cases make the number change often. CI installs +the latest `black`; use the version reported by the failing job if local and +CI formatting differ. + +See [CadQuery and OCP compatibility](dependency-compatibility.md) for the +support policy and exact dependency pins. Pytest's header records Python, +CadQuery, OCP, platform and interpreter for every saved result. + +## Original compatibility gate + +The [compatibility matrix](compatibility.md) is part of the test suite, not +just a checklist. `compatibility_matrix_is_complete_and_evidenced` contains +the stable legacy contract ids and fails when: + +* an inventoried capability silently disappears from the matrix; +* a Verified or Enhanced row does not name an existing test function; +* a Changed or Gap row has no explicit decision; or +* an Unverified GUI interaction has no follow-up. + +`legacy_shortcuts_are_preserved` checks every original shortcut, +`legacy_mouse_gestures_keep_their_navigation_modes` checks the original mouse +bindings, and `test_examples.py` executes every example project, including +the eight (`01` to `08`) that are unchanged from the pre-rewrite revision. This gate checks inventory and +evidence; it deliberately does not claim that documented gaps are complete. + +## Benchmarks + +Benchmarks are `#[ignore]`d tests, so `cargo test` skips them. Run them in +release mode, where the timings are meaningful: + +```sh +cargo test --release pick_latency -- --ignored --nocapture +``` + +`pick_latency_on_growing_assemblies` sweeps the pointer across assemblies +of 64 to 16,384 instanced parts and prints the median, 95th percentile and +maximum pick latency without and with the scene index, plus the index +build time. Its first line records CQ-editor version, operating system, +architecture, build profile and logical CPU count so results are comparable. + +## Writing tests + +* **Rust:** put the test next to its siblings in `tests/rust//` and + include it from the module, as the existing files do. Keep tests free of + a GPU or a window: test the camera math, picking, scene and text + operations directly. +* **Worker:** prefer calling `Server.dispatch` or the module functions with + small CadQuery shapes. Use the fixtures in `conftest.py` for protocol + round trips. Tests that start a real `python -m cq_worker` process belong + in `tests/worker/protocol/`. +* **Regression tests first:** a bug fix should come with a test that fails + without it. diff --git a/docs/getting-started/first-model.md b/docs/getting-started/first-model.md new file mode 100644 index 000000000..72b9c4464 --- /dev/null +++ b/docs/getting-started/first-model.md @@ -0,0 +1,141 @@ +# Your first model + +This tour takes about ten minutes. You will model a small bracket, change its +dimensions, select faces in the 3D view, find a bug with the debugger and +export the result. It assumes CQ-editor starts and the status bar shows the +Python and CadQuery versions (see [Installation](installation.md)). + +## 1. Write the script + +Choose **File > New** (Ctrl+N) and type, or paste, this script: + +```python +import cadquery as cq + +# Parameters +width, depth, height = 40, 30, 12 +pocket_depth = 6 +hole = 3 + +base = cq.Workplane("XY").box(width, depth, height).edges("|Z").fillet(3) +pocket = base.faces(">Z").workplane().rect(width - 12, depth - 12).cutBlind(-pocket_depth) +bracket = ( + pocket.faces(" Save** (Ctrl+S). An untitled buffer asks where to save +it; call it `bracket.py`. Saving matters for two reasons: the script's folder +becomes its working directory, and automatic reload needs a file to watch. + +## 2. Render + +Press **F5** (or the ▷ button). The model appears in the 3D view, the +**Objects** panel lists `bracket`, and the status bar reports something like +*Rendered 1 object in 0.09 s*. + +![The bracket rendered](../images/first-model-render.png) + +`show_object` is how a script tells the editor what to draw. It also accepts +a color: + +```python +show_object(bracket, name="bracket", options={"color": "steelblue", "alpha": 0.8}) +``` + +[Writing scripts](../user-guide/scripting.md) covers all the options. + +## 3. Change a parameter + +CadQuery models are parametric: dimensions are plain Python variables. Change +`hole = 3` to `hole = 5` and press **F5** again. The view frames the new +model (turn off *Preferences > 3D View > Fit automatically* to keep the +camera where it is). + +To work in another editor (VS Code, vim, …) instead, turn on **File > +Automatic Reload and Preview**. CQ-editor then re-runs the script every time +the file changes on disk. If you also have unsaved edits in CQ-editor, it +asks before replacing them (see [Code editor](../user-guide/editor.md#automatic-reload-and-preview)). + +## 4. Look around + +| Do this | To | +| --- | --- | +| Left drag | Orbit | +| Middle drag, or Ctrl + left drag | Pan | +| Mouse wheel | Zoom at the pointer | +| Click a face, edge or corner of the navigation cube | Look from that direction | +| Click the curved arrows above the cube | Roll the view by 45° | +| Shift+F1 / Shift+F2 | Fit the model / isometric view | +| Double-click the model | Zoom to it | + +## 5. Select a face + +Click a face of the bracket. The face is highlighted, the status bar reads +*Selected Face 6 of bracket*, and the Objects panel shows the entity under +the object's name. Edges and vertices can be picked the same way; the pointer +only needs to be within a few pixels of them. + +![A selected face](../images/first-model-selection.png) + +The numbers are stable topological ids: the same face keeps its number as +long as the geometry does not change. + +## 6. Make a mistake on purpose + +Change `.edges("|Z")` to `.edgs("|Z")` and press **F5**. The run fails: + +* the offending line is highlighted in red in the editor; +* the status bar shows the error and its line; +* the **Traceback** panel lists the stack. Click a row to jump to that line. + +![An error in the Traceback panel](../images/error-traceback.png) + +The previous model stays on screen until the next successful run. Fix the +typo before going on. + +## 7. Step through the script + +Click the line number of line 9 (`pocket = …`). A red dot marks a breakpoint. +Now choose **Run > Debug** (Ctrl+F5): + +* the script runs until it reaches line 9, which is highlighted; +* the 3D view shows the CadQuery objects that exist at that point (`base`); +* the **Variables** panel lists the local variables. + +![Paused at a breakpoint](../images/first-model-debugger.png) + +Press **Step** (Ctrl+F10) to run one line and watch `pocket` appear, or +**Continue** (Ctrl+F12) to run to the next breakpoint or to the end. **Run > +Stop Debugging** (Ctrl+F5 again) ends the session. More in [Debugging and +inspection](../user-guide/debugging.md). + +## 8. Inspect how the model was built + +Select `bracket` in the Objects panel and open the **CQ Inspector** tab. It +lists the chain of CadQuery operations that produced the object, newest +first. Turn on **Show in view** and click a step: its objects and its +workplane grid are drawn over the model. + +## 9. Export + +Choose **Tools > Export as STEP…** (or STL, or BREP). The selected objects +are exported, or all of them when nothing is selected. The **Export** button +in the Objects panel does the same. + +## Where next + +* **File > Examples** has nine commented scripts, from a simple box to + assemblies such as a welded square-tube workbench. Examples open + read-only; saving asks for a new location. +* The **Console** panel runs Python with the variables of the last run. Try + `show_object(bracket.faces(">Z"))`. +* [The interface](../user-guide/interface.md) walks through every panel and + menu. +* The [CadQuery documentation](https://cadquery.readthedocs.io/en/latest/) + is the reference for modeling itself. diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md new file mode 100644 index 000000000..fa4738ee1 --- /dev/null +++ b/docs/getting-started/installation.md @@ -0,0 +1,212 @@ +# Installation + +The release installers are self-contained. They include the native CQ-editor, +Python 3.12.15, CadQuery 2.8, OCP 7.9 and Jedi, so a new user does not need to +install Python, conda or CadQuery first. + +## Download an installer + +Open the [CQ-editor releases](https://github.com/igors93/CQ-editor/releases) +page and choose the file for your computer: + +| System | Installer | +| --- | --- | +| Windows 10/11, 64-bit | `Windows-x86_64.exe` | +| macOS on Apple Silicon (M1 or newer) | `MacOSX-arm64.pkg` | +| macOS on Intel | `MacOSX-x86_64.pkg` | +| Linux, 64-bit x86 | `Linux-x86_64.sh` | + +The release also contains `SHA256SUMS.txt`. Verify the download before running +it when possible: + +```sh +# Linux or macOS, from the download folder +sha256sum -c SHA256SUMS.txt --ignore-missing +``` + +On Windows, compare this command's result with the matching line in +`SHA256SUMS.txt`: + +```powershell +Get-FileHash .\CQ-editor-*.exe -Algorithm SHA256 +``` + +### Windows + +Run the `.exe`, choose **Just Me** for a normal per-user installation, and +finish the wizard. CQ-editor appears in the Start menu and in **Open with** for +Python files. It does not replace the system Python or add its private runtime +to `PATH`. + +### macOS + +Run the `.pkg` matching the Mac's processor. The runtime is installed under +the user's Library and **CQ-editor.app** is added to Applications. Intel and +Apple Silicon packages are built and tested separately rather than relying on +emulation. + +### Linux + +Make the downloaded installer executable and start its interactive wizard: + +```sh +chmod +x CQ-editor-*-Linux-x86_64.sh +./CQ-editor-*-Linux-x86_64.sh +``` + +The default is `~/.local/share/CQ-editor`. The installer creates an application +menu entry and registers CQ-editor as an option for opening Python files. A +typical desktop Linux installation already has the GTK/X11 or Wayland system +libraries used by the native window. + +Published Windows installers are Authenticode signed and timestamped. The +macOS packages are Developer ID signed, notarized by Apple and stapled. +Release CI refuses to upload or publish those artifacts if signing or +notarization fails. Windows SmartScreen can still warn until a new signing +certificate has built up reputation. + +## What is verified before publication + +Release CI builds four native artifacts: Linux x86_64, Windows x86_64, macOS +Apple Silicon and macOS Intel. On the matching operating system it then: + +1. runs the finished installer in unattended mode; +2. imports CadQuery, OCP and Jedi with the installed Python; +3. verifies the expected CadQuery version; and +4. starts the installed CQ-editor executable with `--help`. + +Only when all four jobs pass, including signature and notarization checks, are +the installers and their checksums attached to the GitHub release. Each build +also records a dependency lockfile and the +third-party license inventory generated by constructor. + +## First start + +Launch CQ-editor from the application menu. The status bar briefly shows +**Starting Python…** while the bundled CadQuery runtime is imported, then +shows the versions in use, for example **Python 3.12 · CadQuery 2.8.0**. Hover +the status to see the OCP version, and press **F5** to render. + +![First launch](../images/first-launch.png) + +The installer keeps the runtime private so it cannot change another Python +installation. Advanced users can still install extra Python packages with the +bundled `pip`, or select a completely different compatible environment in +**Edit > Preferences > General > Python interpreter**. + +## Use another Python environment + +This section is optional for installed releases and useful for add-ons, +development or source builds. + +| | Supported | +| --- | --- | +| Python | 3.11–3.14 with a matching supported CadQuery version | +| Recommended external environment | Python 3.11–3.14 with CadQuery 2.8 | +| Previous CadQuery release | Python 3.11 with CadQuery 2.7 | + +The exact tested combinations are in the +[CadQuery/OCP compatibility matrix](../development/dependency-compatibility.md). + +**From CQ-editor.** *Preferences > General > Python interpreter* manages +environments without a terminal: + +* **Detected** lists the Pythons found on this computer (the active and + conda/mamba environments, `.venv` folders, python.org installs and `PATH`); + pick one, then **Restart Python with this interpreter**. +* **Create Environment…** makes a virtual environment (`python -m venv`) in a + folder of your choice, by default `environments/cadquery` in the folder + below, with a supported Python (3.11 or newer, the one in use by + default), and installs CadQuery and jedi into it. Add other packages to the + list as for `pip install`. Downloading CadQuery takes a few minutes; the + window shows pip's output and can cancel it. **Use this environment** + switches to it and restarts Python. +* **Install Packages…** runs `pip install` for the packages you name in the + Python in use (or another one), for example `trimesh numpy-stl`; then + restart Python to import them. + +Package names are passed to pip as they are, with versions or extras +(`ocp-vscode>=2`, `trimesh[easy]`) or a local `.whl` file, but pip options +are refused. No command goes through a shell. + +**pip and a virtual environment** + +```sh +python -m venv .venv +# Windows: .venv\Scripts\pip install cadquery jedi +# Linux/macOS: .venv/bin/pip install cadquery jedi +``` + +**conda / mamba** + +```sh +mamba create -n cadquery -c conda-forge cadquery=2.8 jedi +mamba activate cadquery +``` + +Start CQ-editor with a one-session override: + +```sh +cq-editor --python /path/to/environment/bin/python my_part.py +``` + +| Option | Meaning | +| --- | --- | +| `FILE` | CadQuery script to open | +| `--python PATH` | Python interpreter to use for this session | +| `-h`, `--help` | Print the usage text | + +## How CQ-editor finds Python + +The first match wins (`src/worker/launch.rs`): + +1. `--python PATH`, or the interpreter selected in Preferences; +2. the `CQ_EDITOR_PYTHON` environment variable; +3. the runtime bundled beside an installed CQ-editor executable; +4. an active virtual or conda environment (`VIRTUAL_ENV` or `CONDA_PREFIX`); +5. a `.venv` beside the executable or in the working directory (debug builds + also look in the source tree); +6. `python` on Windows or `python3` on Linux and macOS from `PATH`. + +The two explicit choices remain ahead of the bundled runtime, so installing a +self-contained release does not remove control from users who need a custom +CadQuery environment. + +## Build from source + +Source builds need Rust 1.88 or newer and a compatible Python/CadQuery +environment: + +```sh +git clone https://github.com/igors93/CQ-editor.git +cd CQ-editor +cargo build --release +``` + +The executable is written to `target/release/cq-editor` (`cq-editor.exe` on +Windows). Linux needs a few system packages first, and Windows has two +toolchain options. [Building](../development/building.md) covers both. + +## Where CQ-editor keeps its files + +Settings and recovery data live in one per-user folder: + +| System | Folder | +| --- | --- | +| Windows | `%APPDATA%\cq-editor\data\` | +| Linux | `~/.local/share/cq-editor/` | +| macOS | `~/Library/Application Support/cq-editor/` | + +| Entry | Content | +| --- | --- | +| `app.ron` | Preferences, recent files, panel layout and window position | +| `recovery/` | Crash-recovery session and local history | +| `logs/` | Current and previous application logs | +| `worker-/` | Extracted embedded worker; obsolete versions are removed automatically | +| `environments/` | Default place of the environments created from the preferences | + +Deleting `app.ron` while the editor is closed restores all defaults. + +## Next step + +Follow [Your first model](first-model.md). diff --git a/docs/images/debugger.png b/docs/images/debugger.png new file mode 100644 index 000000000..aedcbad77 Binary files /dev/null and b/docs/images/debugger.png differ diff --git a/docs/images/error-traceback.png b/docs/images/error-traceback.png new file mode 100644 index 000000000..360a54473 Binary files /dev/null and b/docs/images/error-traceback.png differ diff --git a/docs/images/exploded-view.png b/docs/images/exploded-view.png new file mode 100644 index 000000000..7788ab3b4 Binary files /dev/null and b/docs/images/exploded-view.png differ diff --git a/docs/images/first-launch.png b/docs/images/first-launch.png new file mode 100644 index 000000000..7c0ad6d5d Binary files /dev/null and b/docs/images/first-launch.png differ diff --git a/docs/images/first-model-debugger.png b/docs/images/first-model-debugger.png new file mode 100644 index 000000000..12501ab59 Binary files /dev/null and b/docs/images/first-model-debugger.png differ diff --git a/docs/images/first-model-render.png b/docs/images/first-model-render.png new file mode 100644 index 000000000..e1fbf47d7 Binary files /dev/null and b/docs/images/first-model-render.png differ diff --git a/docs/images/first-model-selection.png b/docs/images/first-model-selection.png new file mode 100644 index 000000000..3507727ab Binary files /dev/null and b/docs/images/first-model-selection.png differ diff --git a/docs/images/inspector.png b/docs/images/inspector.png new file mode 100644 index 000000000..1ae7414c2 Binary files /dev/null and b/docs/images/inspector.png differ diff --git a/docs/images/main-window-dark.png b/docs/images/main-window-dark.png new file mode 100644 index 000000000..43d3e907e Binary files /dev/null and b/docs/images/main-window-dark.png differ diff --git a/docs/images/main-window-light.png b/docs/images/main-window-light.png new file mode 100644 index 000000000..7372f981b Binary files /dev/null and b/docs/images/main-window-light.png differ diff --git a/docs/images/navigation-cube.png b/docs/images/navigation-cube.png new file mode 100644 index 000000000..a05216916 Binary files /dev/null and b/docs/images/navigation-cube.png differ diff --git a/docs/images/parameters.png b/docs/images/parameters.png new file mode 100644 index 000000000..d827485b8 Binary files /dev/null and b/docs/images/parameters.png differ diff --git a/docs/images/preferences.png b/docs/images/preferences.png new file mode 100644 index 000000000..5c75a405b Binary files /dev/null and b/docs/images/preferences.png differ diff --git a/docs/images/section-view.png b/docs/images/section-view.png new file mode 100644 index 000000000..9244fbfdb Binary files /dev/null and b/docs/images/section-view.png differ diff --git a/docs/images/topology-selection.png b/docs/images/topology-selection.png new file mode 100644 index 000000000..2a673ee2f Binary files /dev/null and b/docs/images/topology-selection.png differ diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 000000000..d99b03d29 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,899 @@ +# Roadmap + +This is the plan for CQ-editor after `0.8.0`. It comes from a review of the +whole source tree (commit `74c1535`, October 2026) and of the libraries it +builds on, checked with CadQuery 2.7 / OCP 7.8 (the development +environment; the installers ship CadQuery 2.8 / OCP 7.9). It has four +parts: + +1. **[Bugs](#1-bugs-and-problems)**: defects that were reproduced, not + suspected. Each one was confirmed by running code against the current + tree. A suspicion that did not reproduce is not listed. +2. **[Required improvements](#2-required-improvements)**: work that follows + from what CQ-editor is, an IDE whose product is CAD data made by code, or + from a maintenance duty. These are not optional. +3. **[Suggested improvements](#3-suggested-improvements)**: work that fits the + code and would make it better, but that the program can live without. +4. **[Direction](#4-direction)**: where CQ-editor can go to become the + reference tool for building 3D objects with code, based on what CadQuery + and OpenCascade already offer. + +The items of the previous roadmap (BUG-01…BUG-32, PERF-01…PERF-04 and the +finished FEAT items) are all resolved. They are summarized under +[Completed](#completed), and described in the [changelog](changelog.md). Items +that were still open have moved into the sections below. + +**Evidence** says how each bug was confirmed: + +* **test**: a throwaway Rust test, run against the tree. It asserted the + faulty behaviour and passed. Each bug says what the test did, so it can + become the regression test of the fix, with its assertion turned around. +* **script**: a Python script run against the worker package, with + CadQuery 2.7 / OCP 7.8. +* **seen**: observed in the running application. + +**Priorities:** **P1** fix before the next release · **P2** should fix soon · +**P3** fix when the code is touched. + +Want to help? Pick an item, open an issue that mentions its id (for example +`REQ-04`), and see [Contributing](development/contributing.md). + +## Guiding principles + +CQ-editor is, first of all, **an IDE for running Python CadQuery code that +builds 3D models**. Everything on this roadmap has to respect that: + +1. **The code is the model.** The script stays the single source of truth. + GUI features may *read* the model (measure, inspect, select) and may + *write code* (insert a selector, change a parameter), but they never keep + design intent in a hidden GUI-only state. +2. **One tool for beginners and experts.** Beginners need a guided path, + clear errors and things they can click. Experts need speed, keyboard + control, multi-file projects and automation. Advanced features are + available but stay out of the way until needed (progressive disclosure). +3. **Compatibility.** Scripts written for the original CQ-editor, and the + `show_object` conventions shared with other CadQuery tools, keep working. + The [compatibility matrix](development/compatibility.md) distinguishes + tested equivalence, intentional changes and open gaps. +4. **Never block, never lose work.** Python runs in its own process. Saves + are atomic. Unsaved work is recoverable, and no file is replaced with + contents the user has not seen. +5. **What leaves the editor is right.** An exported file carries the shapes, + placements, names, colors and units the code produced, or the editor says + what it could not keep. + +## Where we are + +The modeling workflow is complete and well tested. Scripts run in an +isolated worker. The view picks faces, edges and vertices exactly, and the +GUI writes selectors, parameters and measurements back as code. Projects +with several files, crash recovery and local history are in place. The +weak points found by this review are at the seams: the file system shared +with other programs, keyboard focus under dialogs, the pipe between the two +processes, and the export of what the view shows. + +The libraries offer much more than the editor uses. This table was checked +against the installed packages (CadQuery 2.7.0, OCP 7.8.1): + +| Capability of CadQuery / OCP | In CQ-editor today | +| --- | --- | +| `Workplane`, `Shape`, `Sketch`, `Assembly` display, nested assemblies, instancing | ✅ Shown, picked, measured | +| Free-function API (`cadquery.func`: `box`, `extrude`, `loft`, `sweep`, `fillet`, `offset`, `text`, `imprint`, `split`, `fill`, `cap`, `check`, `closest`…) | Usable in scripts; no snippets or help of its own | +| Per-face names, colors and layers (`Assembly.addSubshape`) | ✅ Drawn and shown when picking ([REQ-07](#req-07--show-everything-the-cadquery-api-can-specify)) | +| Materials (`cq.Material`: name, density, visual material) | ✅ Name, density, supported visual base color and measured mass | +| Assembly constraints (`constrain`, `solve`, casadi) and sketch constraints (nlopt) | Only the solved result is shown | +| Assembly export: STEP (default or fused), OCAF XBF/XML, glTF/GLB, VRML, VTK.js, STL | STEP, only when one assembly is exported alone | +| Shape export: STEP, STL, BREP, 3MF, AMF, SVG and DXF (2D), VRML, VTP, TJS, BIN | STEP, STL, BREP | +| Import: STEP (also as an assembly with names and colors), BREP, BIN, DXF | Through code only | +| `cqgi` script interface (`describe_parameter`, typed parameters) used by `cq-cli` and servers | ❌ `describe_parameter` is not defined in scripts | +| OCP: `BRepExtrema` (distances) | ✅ Measurements | +| OCP: `BRepGProp` (mass properties), `BRepCheck` / `ShapeFix` (validity, healing), `HLRBRep` (hidden-line projection), `XCAFDimTolObjects` (PMI in STEP AP242), `TNaming` (topological naming), `BRepFeat`, `GeomPlate` | Not used | + +--- + +## 1. Bugs and problems + +| Status | Id | Problem | Priority | +| :---: | --- | --- | --- | +| ✅ | [BUG-33](#bug-33--saving-replaces-a-newer-version-on-disk-without-a-word) | Saving replaces a newer version on disk without a word | P1 | +| ✅ | [BUG-34](#bug-34--shortcuts-act-behind-modal-dialogs-and-a-conflict-can-vanish) | Shortcuts act behind modal dialogs, and a conflict can vanish | P1 | +| ✅ | [BUG-35](#bug-35--renaming-a-file-only-by-case-replaces-another-file) | Renaming a file only by case replaces another file | P1 | +| ✅ | [BUG-36](#bug-36--a-closed-editor-panel-never-comes-back) | A closed Editor panel never comes back | P2 | +| ✅ | [BUG-37](#bug-37--step-export-of-a-sub-assembly-loses-its-placement) | STEP export of a sub-assembly loses its placement | P2 | +| ✅ | [BUG-38](#bug-38--closing-the-tab-of-a-paused-script-leaves-the-debugger-paused) | Closing the tab of a paused script leaves the debugger paused | P2 | +| ✅ | [BUG-39](#bug-39--a-model-too-large-to-transfer-is-reported-as-missing-cadquery) | A model too large to transfer is reported as missing CadQuery | P3 | +| ✅ | [BUG-40](#bug-40--one-invalid-display-option-loses-the-whole-run) | One invalid display option loses the whole run | P3 | +| ✅ | [BUG-41](#bug-41--the-local-history-depends-on-how-a-path-is-written) | The local history depends on how a path is written | P3 | + +### BUG-33 · Saving replaces a newer version on disk without a word + +✅ **Resolved.** `Document::unseen_disk_version` reads the file before a +save and returns it when it is neither the saved baseline nor the buffer's +text; a deleted file is simply written again. `AppState::save` then writes +nothing and opens the **File changed on disk** dialog (`on_save`), with +**Save my version**, **Reload from disk**, **Save a copy…** and **Cancel**; +Escape cancels. Keeping one's version, from a save or from the watcher, +archives the disk version in the local history and adopts it as the +baseline (`adopt_disk_baseline`), so the next save goes ahead. Tests: +`a_save_finds_the_version_another_program_wrote`, +`saving_never_replaces_a_version_another_program_wrote_unseen`. + +*Evidence: test.* **Where:** `src/document.rs` (`Document::save`, `write`), +`src/app/documents.rs` (`AppState::save`). + +Automatic reload is off by default (`Editor::autoreload`). In that state +nothing compares the file on disk with what the editor loaded. When another +program changes the file (a `git pull` or `checkout`, VS Code, a formatter), +**File > Save** writes the editor's older text over it. It does so even when +the buffer was never edited, so a habitual Ctrl+S is enough. The overwritten +version is not archived in the local history. This contradicts the user +guide ("CQ-editor never silently throws away your edits"). + +**Reproduce:** open `part.py`, change it with another program, press Ctrl+S +in CQ-editor. The other program's change is gone. The test also checked +that `RecoveryStore::history` holds no copy of it. + +**Fix:** the document remembers a fingerprint of the file it loaded or +saved: length, modification time and the hash it already keeps. `save` +reads the disk version first. If it differs from the saved baseline, save +does not write. It opens the **File changed on disk** dialog (Keep mine and +overwrite, Reload, Save a copy, Compare) and archives the disk version with +`RecoveryStore::archive_path` before any overwrite. A file deleted since it +was opened gets the same question. See [REQ-01](#req-01--saving-checks-the-disk-first). + +### BUG-34 · Shortcuts act behind modal dialogs, and a conflict can vanish + +✅ **Resolved.** `begin_frame` collects global shortcuts only while +`Dialogs::modal_open()` is false (about, unsaved changes, file changed on +disk, recovery, Project prompts, command palette, local history, legacy +encoding and messages). `ExternalChange` carries the generation of its +document: the dialog shows that document's name and text, and +`resolve_external_change` shows its tab and acts on it, or drops the +conflict when the tab was closed. Tests: +`shortcuts_wait_while_a_modal_dialog_is_open`, +`a_conflict_is_resolved_on_its_own_document_whichever_tab_is_shown`. + +*Evidence: test.* **Where:** `src/commands.rs` (`collect_shortcuts`, called +from `begin_frame` before the dialogs), `src/dialogs/mod.rs` (`show`, +`external_change`), `src/app/documents.rs` (`resolve_external_change`). + +An egui `Modal` keeps the pointer away from the rest of the window, but +global shortcuts are read from the input before any dialog is drawn. So +every shortcut still runs while a modal dialog is open: Ctrl+Tab, Ctrl+W, +Ctrl+N, F5, Ctrl+Q. A test drew a `Modal` and pressed Ctrl+Tab, and +`NextTab` was queued. + +The **File changed on disk** dialog then breaks. It describes +`state.document`, the tab that is shown now, not the file in conflict. After +Ctrl+Tab it names the other file and compares its text with the conflicting +file's disk version. **Reload from disk** and **Keep my version** reach +`resolve_external_change`, which returns early because the shown path +differs. The dialog closes, nothing is reloaded, and the conflict is +forgotten. The test confirmed this: the buffer kept its edits, and no dialog +or queued conflict was left. A later save then overwrites the other +program's change (BUG-33). + +**Fix:** ignore global shortcuts while a modal dialog is open (a +`Dialogs::modal_open()` check in `collect_shortcuts`; Escape stays with the +dialog). `ExternalChange` carries the document's generation, and the dialog +and its resolution act on that document, whichever tab is shown. See +[REQ-02](#req-02--dialogs-own-the-keyboard-and-their-document). + +### BUG-35 · Renaming a file only by case replaces another file + +✅ **Resolved.** `rename` skips the "already exists" check only when the new +name differs by case alone *and* names the same file +(`same_file::is_same_file`: volume and file index on Windows, device and +inode elsewhere). Test: `changing_only_the_case_never_replaces_another_file`, +which takes the refusing branch where the temporary folder is case-sensitive +(checked with `TMP` in a folder made case-sensitive by `fsutil`) and the +case-changing branch elsewhere. + +*Evidence: test, in a folder made case-sensitive with +`fsutil file setCaseSensitiveInfo`.* **Where:** `src/project.rs` (`rename`). + +To allow `part.py` → `Part.py` on Windows and macOS, `rename` skips the +"already exists" check whenever the old and new names differ only by case. +It assumes the file system ignores case. On Linux, on case-sensitive macOS +volumes and in case-sensitive Windows folders, both files can exist. The +Project panel's **Rename…** then calls `std::fs::rename`, which replaces the +existing `Part.py`. The test created `part.py` ("lower") and `Part.py` +("UPPER, another file") and renamed the first. One file was left, holding +"lower". + +**Fix:** skip the check only when the target is the same file as the +source: compare file identities (volume and file index on Windows, device +and inode elsewhere), for example with the `same-file` crate. Otherwise +refuse, as for any existing name. + +### BUG-36 · A closed Editor panel never comes back + +✅ **Resolved.** `ensure_editor` adds the Editor left of the 3D view when the +layout has none. `show_editor_panel` uses it, and `CqEditorApp::execute` +calls it after every action that changes the shown document (New, Open, +examples, recent files, tabs, recovered work). The saved layout goes +through `restored_layout`, which keeps the user's arrangement and adds the +Editor back. While the panel is closed, the empty view's hint ends with +*the editor is closed: View > Editor*. Tests: +`a_closed_editor_comes_back_whenever_a_file_or_a_line_is_shown`, +`a_layout_saved_without_the_editor_gets_it_back`, +`the_empty_view_says_when_the_editor_is_closed`. + +*Evidence: test; seen (a session restored without the Editor panel).* +**Where:** `src/app/mod.rs` (`CqEditorApp::show_editor_panel`, +`CqEditorApp::new`), `src/panels/mod.rs` (`is_closeable`). + +The Editor panel can be closed like any other, and the layout without it is +saved and restored at the next start. Opening a file, a traceback line, +*Go to Source* and *Go to Line* call `show_editor_panel`, which only brings +an **existing** Editor tab to the front. With the panel closed, the file is +opened into an editor nobody can see. The test closed the panel, opened +`a.py` and went to a line: `a.py` became the shown document and the dock +still had no Editor. The only way back is **View > Editor** or +**View > Reset Layout**, and nothing on screen hints at it. The view keeps +saying *Press F5 to render the script* about a script the user cannot see. + +**Fix:** when the Editor is missing, `show_editor_panel` adds it back where +the default layout has it (left of the 3D view). **File > Open**, **New** +and the examples do the same. The saved layout is accepted only when it +has both the Editor and the 3D View; today only the 3D View is required. +See [REQ-03](#req-03--the-editor-can-never-be-lost). + +### BUG-37 · STEP export of a sub-assembly loses its placement + +✅ **Resolved.** The registry keeps, for each node below the top of an +assembly, its parents' world location and the color it inherits +(`RegistryEntry.parent_location`, `inherited_color`). `placed_assembly` +exports a copy placed with that location. Fixing it also showed that +CadQuery's STEP writer colors only nodes that have their own color, while +the view draws children in their parents' color: the copy gives every node +its inherited color, for whole assemblies too. The script's assembly is not +changed. Tests in `tests/worker/geometry/test_exporting.py` compare STEP +with BREP at every level and read the colors back. + +*Evidence: script.* **Where:** `worker/cq_worker/exporting.py` (`export`). + +When exactly one key is exported to STEP and it holds a `cq.Assembly`, +`export` calls `obj.export(path, "STEP")` on it. A key below the top of an +assembly holds the child `Assembly`, whose `loc` is relative to its parent. +The STEP file therefore places it without its parents' locations and +without the color it inherits. STL and BREP use the registry's world-space +shapes and are right. With a sub-assembly at `y = 500` inside its parent, +STEP gave `y = −5…5` and BREP `y = 495…505`. The same selection exported to +two formats ends up in two places. + +**Fix:** export a wrapper assembly whose only child is the sub-assembly, +with the accumulated location and inherited color. Better, build every +STEP export as an assembly with world placements (see +[REQ-04](#req-04--exports-keep-what-the-code-built)). + +### BUG-38 · Closing the tab of a paused script leaves the debugger paused + +✅ **Resolved.** `Phase::run_id()` names the run whether it is running or +paused, and `running_document` uses it. Closing the paused script's tab now +reaches `Execution::abandon`, which sends *Stop* to the debugger and marks +the run stale, so what it still sends is discarded. Tests: +`closing_the_script_paused_in_the_debugger_ends_its_session`, +`a_paused_session_resumes_as_a_running_debug_session`. + +*Evidence: test.* **Where:** `src/app/tabs.rs` (`forget_document`, +`running_document`), `src/app/execution.rs` (`Phase::running_id`). + +`forget_document` should end a debugging session of the document being +closed. It asks `running_document()`, which uses `Phase::running_id()`, and +that is `None` while the session is **paused**. A paused session is the +usual state while debugging. Closing that tab therefore leaves the session +paused on a document that no longer exists. The test confirmed the phase +stayed `Paused` after the tab closed. The debug toolbar stays active. +**Continue** sends no breakpoints, because the editor is gone, and the run +finishes into the scene with its error line lost. + +**Fix:** give `Phase` a `run_id()` that includes the paused state and use +it in `running_document`. `Execution::abandon` already handles the paused +case. + +### BUG-39 · A model too large to transfer is reported as missing CadQuery + +✅ **Resolved.** The reader thread reports an oversized message as +`Event::ProtocolError`, which `Worker::poll` does not treat as a failed +start. `AppState::worker_protocol_failed` explains it in a dialog (for a mesh +reply: *the model is too large to transfer: raise Deviation in +Preferences > 3D View, or show fewer objects*) and restarts the worker, +which also ends the waiting run; the model shown before stays. Tests: +`an_unreadable_message_is_not_a_failed_start`, +`a_result_too_large_to_transfer_ends_the_run_and_restarts_python`. Sending +meshes per part, so that no limit is reached at all, stays in +[REQ-09](#req-09--large-and-unusual-results-travel-safely). + +*Evidence: test.* **Where:** `src/worker/mod.rs` (reader thread, +`oversized_message`, `Worker::poll`). + +A reply above the transport limit (512 MiB for mesh replies, about ten +million triangles) is turned into `Message::Fatal`. `Worker::poll` treats +every `Fatal` as a failed start and sets `Problem::NoCadQuery`. The test +made the worker ready, then fed it the oversized message. The status became +`Failed` and the first-run popup says **CadQuery is not available. Install +CadQuery in that environment**, which is false. The reader then ignores +every later message while the process lives. The run never finishes, and +the view shows *Running script…* until Stop restarts Python. + +**Fix:** report oversized and unreadable messages as their own event. Say +that the model is too large to transfer and suggest a coarser tolerance or +the large-model mode. Restart the worker cleanly. See +[REQ-09](#req-09--large-and-unusual-results-travel-safely). + +### BUG-40 · One invalid display option loses the whole run + +✅ **Resolved.** `DisplayOptions.parse` reads each option on its own, so an +invalid one no longer drops the others, and refuses NaN and infinities +(`finite`) with the usual warning. Fixing it showed that a NaN placement +(`moved(cq.Location((math.nan, 0, 0)))`) broke the reply the same way: +`SceneBuilder` now checks every node with `non_finite`, and leaves out an +object that holds a NaN, releasing its keys and naming it in the log +(*Cannot display lost: parts[0].mesh.bbox[0][0] is not a finite number*). +Tests: `test_non_finite_opacity_is_ignored`, +`test_one_invalid_option_keeps_the_others`, +`test_a_non_finite_number_never_loses_the_whole_run`. + +*Evidence: script.* **Where:** `worker/cq_worker/scene.py` +(`DisplayOptions.parse`), `worker/cq_worker/protocol.py` (`Channel.send`, +`allow_nan=False`). + +`show_object(part, options={"alpha": math.nan})` passes through +`DisplayOptions.parse`, because `min(max(nan, 0), 1)` is `nan`. The +`run_finished` reply then cannot be encoded. The whole run, every valid +object included, is replaced by the error *ValueError: Out of range float +values are not JSON compliant*, which does not name the object or the +option. The same holds for a NaN alpha given in `rgba`. + +**Fix:** `DisplayOptions.parse` rejects non-finite numbers with the existing +"Ignoring invalid display option" warning. A node that cannot be encoded is +dropped and named in the log instead of failing the reply. + +### BUG-41 · The local history depends on how a path is written + +✅ **Resolved.** *Evidence: test (found while fixing BUG-33: +`renaming_or_deleting_files_keeps_the_tabs_in_step` failed on Windows on the +unchanged tree).* **Where:** `src/recovery.rs` (`document_folder`). + +A document's history folder was named after a hash of its path's raw +bytes. On Windows `C:/x/part.py` and `C:\x\part.py` are the same file but +got two folders, so versions saved under one spelling were missing from +**File > Local History…** under the other. A path that went through a +rename (`project::relocated` joins with `\`) and a path typed with `/` on +the command line could thus lose sight of each other's history. + +**Resolution:** the path is rebuilt from its components before it is +hashed, so `/` and `\` (and `.` components) give one folder. Paths written +with `\`, which the system's file dialogs return, keep the folders of +earlier releases. Tests: `a_file_has_one_history_however_its_path_is_written`, +`folder_names_are_stable_across_releases`. + +--- + +## 2. Required improvements + +These follow from what CQ-editor is. A code-CAD IDE must not lose files, it +must hand over correct CAD data, and it must work on supported platforms. +Each item says **why it is required**, **what changes** and **how it helps +the code**. + +| Status | Id | Improvement | Fixes | Priority | +| :---: | --- | --- | --- | --- | +| ✅ | [REQ-01](#req-01--saving-checks-the-disk-first) | Saving checks the disk first | BUG-33 | P1 | +| ✅ | [REQ-02](#req-02--dialogs-own-the-keyboard-and-their-document) | Dialogs own the keyboard and their document | BUG-34 | P1 | +| ✅ | [REQ-03](#req-03--the-editor-can-never-be-lost) | The editor can never be lost | BUG-36 | P2 | +| ✅ | [REQ-04](#req-04--exports-keep-what-the-code-built) | Exports keep what the code built | BUG-37 | P1 | +| ✅ | [REQ-05](#req-05--units-reach-the-exported-files) | Units reach the exported files | | P2 | +| ✅ | [REQ-06](#req-06--geometry-is-validated-before-it-leaves) | Geometry is validated before it leaves | | P2 | +| ✅ | [REQ-07](#req-07--show-everything-the-cadquery-api-can-specify) | Show everything the CadQuery API can specify | | P2 | +| ✅ | [REQ-08](#req-08--debugging-and-profiling-cover-the-whole-project) | Debugging and profiling cover the whole project | BUG-38 | P2 | +| ✅ | [REQ-09](#req-09--large-and-unusual-results-travel-safely) | Large and unusual results travel safely | BUG-39, BUG-40 | P2 | +| ✅ | [REQ-10](#req-10--headless-build-and-check) | Headless build and check | | P2 | +| ✅ | [REQ-11](#req-11--a-supported-python-window) | A supported Python window | | P1 | +| ✅ | [REQ-12](#req-12--signed-installers) | Signed installers | | P2 | +| ✅ | [REQ-13](#req-13--tests-at-the-seams) | Tests at the seams | all | P2 | + +### REQ-01 · Saving checks the disk first + +**Why it is required.** Scripts live in folders shared with other tools: +git, other editors, formatters, sync clients. An editor that writes without +looking destroys their work (BUG-33). Principle 4 promises it never happens. + +**What changes.** `Document` keeps a disk fingerprint (length, modification +time, content hash) from load and save. `save` compares it with the disk. +On a difference, save does not write. It shows the conflict dialog the +watcher already uses, and archives the disk version before any overwrite. +The same check runs when the window gets focus back, even with automatic +reload off. That is how other editors notice changes. A tab whose file was +deleted or moved says so in its title. + +**How it helps the code.** One conflict path (`ExternalChange`) for the +watcher, save and focus, instead of a protection that exists only while +autoreload is on. `Document::save` gets a precondition the tests can state. + +**Progress.** Done. Save compares the disk with the saved baseline. Regaining +focus checks every open tab even with automatic reload off: clean files are +reloaded, conflicts use the same dialog as the watcher, and a missing file +is labeled in its tab and title while its buffer is preserved. The baseline +also records length, modification time and a hash of the original bytes. + +### REQ-02 · Dialogs own the keyboard and their document + +**Why it is required.** A confirmation is only worth something if nothing +else happens while it is asked. Today keys act behind every modal (BUG-34). + +**What changes.** `Dialogs::modal_open()` gates `collect_shortcuts`. Each +dialog that concerns a document stores its generation and acts on that +document: external change, unsaved changes, local history. The dialog +shows the name of that document, not of the shown tab. + +**How it helps the code.** Dialog outcomes stop depending on the shown tab. +That removes a class of "the user switched tabs meanwhile" bugs that tabs +(FEAT-D1) made possible. + +**Progress.** Done. Modal dialogs gate global shortcuts. External-change, +unsaved-changes and local-history actions carry document generations; history +restores the tab that opened it, and refuses a version of another path. + +### REQ-03 · The editor can never be lost + +**Why it is required.** In a code-CAD IDE the code is the model, and the +editor is where it is written. A layout without it is not a valid state of +the program (BUG-36). + +**What changes.** The saved layout is validated to contain the Editor and +the 3D View. Everything that shows a file or a line re-adds the Editor when +it is missing. Closing the Editor panel can stay possible, to work with an +external editor and autoreload. The view's empty state then says +*The editor is hidden — View > Editor*. + +**How it helps the code.** One `ensure_panel(Tab)` replaces the ad-hoc +`show_editor_panel` and `show_project_panel`, and covers the Traceback and +Console panels the same way when an action needs them. + +**Progress.** Done. `ensure_panel` restores the Editor, Project, Console, +Traceback or another panel when an action needs it. Restored layouts always +have an Editor and a 3D View. Opening a document shows the Editor, console +actions show the Console, and a new run error shows Traceback. + +### REQ-04 · Exports keep what the code built + +**Why it is required.** For a CAD tool, the exported file is the product. +Today, exporting several shown objects to STEP fuses them into one +anonymous compound. Checked by script: objects shown as `base` (steelblue) +and `pin` (red) come back from the STEP file as `1` and `2` without colors. +A sub-assembly loses its placement (BUG-37). Downstream tools (CAM, PDM, +other CAD) need the parts, names, colors and hierarchy. + +**What changes.** + +* STEP is written as an assembly made of what is exported: one child per + shown object or assembly node, with its name, color and world placement. + `merge_assemblies` and STEP's `fused` mode are offered as options, not + imposed. +* An **Export dialog** replaces the bare file picker: format, STEP mode and + schema (AP214 or AP242), STL ASCII or binary and tolerances, and what to + export (selection, visible objects or everything). +* The formats CadQuery 2.7 already writes, without new dependencies: + **3MF** (units and colors, the printing format), **glTF/GLB** (web, + rendering), **AMF**, **VRML**, **VTK.js**, OCAF **XBF** (lossless, + reopens with names and colors), **SVG** (a hidden-line projection) and + **DXF** (a section or planar faces). This closes the former FEAT-D3. + +**How it helps the code.** `exporting.py` gets one path built on +`cq.Assembly` instead of two (fused compound, or a single assembly). The +registry's world placements, already used by STL and BREP, become the +single source of placement for every format. + +**Progress.** Done. STEP exports multiple shown objects as named, colored +assembly children with world placements. The Export dialog chooses scope, +format, STEP mode and schema, STL encoding and mesh tolerances. The worker +also exports 3MF (with per-part names and display colors), glTF/GLB, AMF, +VRML, VTK.js, XBF, SVG and DXF. A VTK.js exporter that returns an empty +archive is reported as a failure instead of a false success. + +### REQ-05 · Units reach the exported files + +**Why it is required.** *Preferences > 3D View > Units* labels the grid and +the scale bar (for example in inches). Every STEP file is still written in +millimeters, because neither CadQuery nor the editor sets +`write.step.unit`. A part modeled and checked in inches is imported 25.4 +times too small. The documentation says Units "only names them". In a CAD +program that is a trap, not a feature. + +**What changes.** Exports write the chosen unit where the format has one: +STEP (`write.step.unit`), 3MF (`unit`) and glTF (a scale to meters). STL +and DXF have no unit, so the export dialog states it. With *Units: none*, +the dialog asks. + +**How it helps the code.** Units become a setting the worker receives with +every export (`SceneSettings`), not a label known only to the view. + +**Progress.** Done. The Export dialog requires a model unit, defaulting to +the 3D View preference. STEP sets the OCCT output unit and restores its +previous setting afterward; 3MF records the unit in the model XML; glTF/GLB +scale coordinates to meters. STL and DXF show that their formats carry no +unit metadata. Tests read the resulting STEP, 3MF and glTF files back. + +### REQ-06 · Geometry is validated before it leaves + +**Why it is required.** OpenCascade operations can produce invalid solids +(self-intersections, open shells, bad tolerances) that still display. +Exported to STL or STEP, they break slicers and CAM silently. The user only +learns about it far away from the code that caused it. + +**What changes.** Exports run `BRepCheck_Analyzer` (`Shape.isValid()`) on +what they write. They warn with the object's name, and offer to export +anyway or to try `ShapeFix` (`Shape.fix()`). The Objects panel gets an +on-demand **Check geometry**, which also reports open shells, non-manifold +edges and solids that are not closed. A badge marks invalid objects. + +**How it helps the code.** The worker gains a `check` request that +measurement, export and CI ([REQ-10](#req-10--headless-build-and-check)) +share. + +**Progress.** Done. The worker checks each exported shape for OCCT validity, +open shells and non-manifold edges before opening an output file. The user +can cancel, export anyway, or try ShapeFix; an unsuccessful repair is +refused. **Check Geometry** in Objects and Tools uses the same request and +marks invalid nodes until their scene is replaced. The protocol is version 8. + +### REQ-07 · Show everything the CadQuery API can specify + +**Why it is required.** Principle 1: the view shows what the code says. +CadQuery 2.7 lets scripts name and color individual faces +(`Assembly.addSubshape(face, name=, color=, layer=)`) and attach materials +(`cq.Material`, with a density and a visual material). Checked by script: +a red face named "top face" is drawn in the part's gray, and its name +exists nowhere in the scene. Yet a STEP export of the same assembly keeps +both. The view and the file disagree. + +**What changes.** Scene parts carry per-face colors, as a color per +triangle group, which the face ids already provide, and per-face names. +Picking reports *top face* instead of *Face 6*, and selectors and *Copy as +code* can use the name. Materials give the part its visual color and their +density to measurements (see [SUG-10](#3-suggested-improvements)). + +**How it helps the code.** `MeshTopology` gains attributes per face rather +than one color per part. The same structure later carries PMI and +inspection highlights. + +**Progress.** Done. Assembly face names, layers and colors travel with each +part instance, independent of the shared mesh. The viewer shades named faces +with their own color, and picking and measurements show the name and layer. +Copy as code uses a unique assembly face name when available. Assembly +materials carry their physical density to exact mass measurements, and their +visual base color to the part when specified. The protocol is version 9. + +### REQ-08 · Debugging and profiling cover the whole project + +**Why it is required.** Projects with several files are first-class +(FEAT-D1), but the debugger traces only the editor buffer. Breakpoints in +an imported module can be set in its tab's gutter and are silently +ignored. The user guide admits it ("breakpoints in modules are ignored"). +Closing a paused script's tab does not end the session (BUG-38). + +**What changes.** The debugger traces files of the project folder too, with +the breakpoints of their open tabs (`Request::Debug` carries breakpoints +per path). Pausing in a module shows its tab at the line. The profiler +reports module lines in their tabs' gutters. A paused session ends when its +script closes. + +**How it helps the code.** Breakpoints become per document instead of "the +run target's", which removes the special case that BUG-38 slipped through. + +**Progress.** Done. Run and resume requests carry open-tab breakpoints by +path. The worker traces project modules, reports the paused file, and the +editor opens that module at its paused line. Profiling records file paths +and source snapshots so module tabs receive line timings. Closing the run +script or paused module ends debugging. The protocol is version 12. + +### REQ-09 · Large and unusual results travel safely + +**Why it is required.** Large assemblies are where a CAD viewer is judged. +Today a reply above 512 MiB is fatal and misreported (BUG-39). One bad +number loses a whole run (BUG-40). + +**What changes.** Mesh replies are sent per part, as `run_part` messages +followed by `run_finished`, so no single line grows with the model. The GUI +decodes parts as they arrive and can draw them progressively. The size +limit then applies per part and can be explained. Protocol encoding errors +name the object they belong to. Worker results are checked for finite +numbers at the source. + +**How it helps the code.** Bounded memory on both sides of the pipe, and an +error model in which "the transport failed" and "CadQuery is missing" are +different things. + +### REQ-10 · Headless build and check + +**Why it is required.** The main promise of code-CAD over GUI CAD is +reproducibility: the same script gives the same part, on any machine, in +CI. That needs a way to build without a window. This is the former +FEAT-D2. + +**What changes.** +`cq-editor build part.py --export out.step --set width=40` runs the worker +without the GUI, with the same settings and `show_object` semantics, and +writes any format of REQ-04. `cq-editor check part.py` exits non-zero on an +error or invalid geometry ([REQ-06](#req-06--geometry-is-validated-before-it-leaves)) +and prints the traceback as text or JSON. Parameter names follow `cq-cli` +and `cqgi`, so scripts can move between tools. + +**How it helps the code.** It separates the run logic from egui (the +`Execution` state machine and the worker client already are), which also +makes [REQ-13](#req-13--tests-at-the-seams) easier. + +### REQ-11 · A supported Python window + +**Why it is required.** Python 3.10 reached its end of life in October 2026 +(PEP 619). At the time of the review, the worker declared +`requires-python = ">=3.10"`, a CI lane ran 3.10, and the development +environment of this repository was 3.10. +Libraries following the scientific Python support schedule (SPEC 0) have +already dropped it. + +**What changes.** A written support policy: the Python versions still +receiving security fixes, and the last two CadQuery minor releases with +their OCP. `requires-python` moves to `>=3.11`, and the CadQuery 2.7 lane +moves to 3.11. The development setup described in the docs moves too. The +installer already bundles Python 3.12. + +**How it helps the code.** Newer syntax (`except*`, `tomllib`, +`contextlib.chdir`) and +fewer compatibility shims. + +### REQ-12 · Signed installers + +**Why it is required.** At the time of the review, the release workflow built +the Windows `.exe` and macOS `.pkg` without signing them. Windows SmartScreen +and macOS Gatekeeper +warn about, or block, unsigned installers. A tool that runs code on the +user's machine has to be verifiable. Releases already publish +`SHA256SUMS.txt` and each installer's resolved lockfile; a checksum proves a +download intact, not who made it. + +**What changes.** Authenticode signing on Windows, and Developer ID signing +and notarization on macOS, in `release.yml`, with the certificates kept as +repository secrets. + +**How it helps the code.** Releases get a known origin that the operating +systems check by themselves, and the update check +([FEAT-E5](#completed)) leads to downloads that install without warnings. + +### REQ-13 · Tests at the seams + +**Why it is required.** The bugs above sit at seams that needed direct +coverage: keyboard focus under dialogs, the dock layout, the file +system shared with other programs, the pipe between the processes, tabs +combined with the debugger, and exported files read back by another +program. These flows can be tested without a native window. + +**Implemented.** Each resolved bug above names its regression test. The +headless egui harness draws a modal and a restored dock, then checks keyboard +actions and visible panels. Rust and Python read the same golden protocol +messages for binary parts, geometry references, non-finite values and an +oversized control reply. CI runs mypy over every worker module, Ruff and the +worker suite with branch coverage; an in-process CLI test keeps terminal +dispatch inside the coverage measurement. + +**What changes.** + +* A regression test per bug of section 1, starting from the probe + described in each. +* Headless UI tests of dialogs, the dock and keyboard flows, for example + with `egui_kittest` (former ENG-03). +* Golden protocol messages read by both the Rust and the Python suites + (former ENG-02), including oversized and non-finite cases. +* `ruff`, a type checker and coverage for the worker (former ENG-01). + +**How it helps the code.** Each seam gets a harness, so the next change +there is checked by a test instead of found by a review. + +--- + +## 3. Suggested improvements + +Worth doing, not required. Labels: 🟢 mostly for beginners · 🔵 mostly for +advanced users · ⚪ both. + +### Learning and writing code + +| Status | Id | Suggestion | Why it fits | +| :---: | --- | --- | --- | +| ✅ | SUG-01 🟢 | **Friendly kernel errors** (former FEAT-A3): identify the CAD operation and script line behind common kernel and selector errors, then offer possible causes | The traceback remains intact; hints are qualified rather than presented as proven geometric facts | +| ✅ | SUG-02 🟢 | **Selector preview** (former FEAT-A4): with the caret on a literal call such as `part.faces(">Z")`, matching entities light up in the view | Uses the last run's displayed variable and exact topology; moving the caret never evaluates dynamic Python expressions | +| | SUG-03 🟢 | **Start page** (former FEAT-A1) with templates, recent files and projects, and an examples gallery with thumbnails | Every template is code; thumbnails come from the screenshot code (FEAT-C5) | +| | SUG-04 🟢 | **Snippets** (former FEAT-A5) for frequent patterns, including the free-function API (`cadquery.func`) and `cq.Sketch` | Inserts ordinary code | +| | SUG-05 🟢 | **Guided lessons** (former FEAT-A2): steps that each explain one concept and check the result, such as the expected volume | Learning by editing and running real code | +| | SUG-06 ⚪ | **Translations** (former FEAT-A6), starting with Portuguese and Spanish | Lowers the entry barrier; the API stays English | +| ✅ | SUG-07 🔵 | **Outline and go to definition**: script symbols in a panel, F12 for definitions and Ctrl+Shift+F12 for project references through Jedi | Static navigation in multi-file projects; outline works without Jedi | +| | SUG-08 🟢 | **Warn when `show_object` reuses a name**: in a loop such as `for i in …: part = …; show_object(part)`, each object replaces the previous one, as documented and as in the original editor. A log line could suggest `name=f"part{i}"` | Explains a frequent surprise without breaking compatibility | + +### Code and model + +| Status | Id | Suggestion | Why it fits | +| :---: | --- | --- | --- | +| | SUG-09 ⚪ | **Typed parameters**: booleans as checkboxes, strings and choices as drop-downs, and `describe_parameter()` descriptions, compatible with CadQuery's `cqgi` | `describe_parameter` raises `NameError` today; `cq-cli` and model servers use it | +| | SUG-10 ⚪ | **Mass properties** in Measurements: volume, mass from the material density, center of mass and inertia (`BRepGProp`) | Engineering answers from the code's own data | +| | SUG-11 🔵 | **Clearance and interference** between parts of an assembly (`BRepExtrema`, `BRepAlgoAPI_Common`), listed and highlighted | The most common assembly question | +| | SUG-12 ⚪ | **Inspector completeness**: show the root workplane's objects (`Workplane(obj=…)`) and the steps of a `Sketch` | Today the chain starts at the first operation | + +### View, projects and running + +| Status | Id | Suggestion | Why it fits | +| :---: | --- | --- | --- | +| | SUG-13 ⚪ | Section plane aligned to a picked face, and more than one plane | Extends FEAT-C1 | +| | SUG-14 ⚪ | Dimensions kept in the view: measurements pinned as annotations, included in screenshots | Extends FEAT-B5 and FEAT-C5 | +| | SUG-15 ⚪ | **Import by drag and drop** (former FEAT-D4): a STEP, STL or DXF file dropped on the editor inserts the matching `cq.importers…` or `cq.Assembly.importStep` line | Writes code | +| | SUG-16 🔵 | **Git awareness** (former FEAT-D5): changed-lines markers and a diff against the last commit | The conflict dialog's comparison view is a start | +| | SUG-17 🔵 | **Run selection and cells** (former FEAT-D6): run the selected lines, or a `# %%` cell, in the console | Fast experiments on the last run's variables | +| | SUG-18 ⚪ | Local history follows renames (today the versions stay in the folder of the old path) | Completes FEAT-D1's rename handling | +| | SUG-19 🔵 | Project panel for large folders: build rows only when a listing changes, not every frame, and honor `.gitignore` | Keeps the panel cheap in big repositories | + +### Extensibility and engineering + +| Status | Id | Suggestion | +| :---: | --- | --- | +| | SUG-20 🔵 | **Plugin API** (former FEAT-F2): Python plugins loaded by the worker that register exporters, `show_object` handlers or commands | +| | SUG-21 🔵 | **User themes** (former FEAT-F3): custom syntax and viewer colors | +| | SUG-22 | Benchmarks of tessellation, decoding and picking tracked over time (former ENG-04) | +| | SUG-23 | Accessibility review (former ENG-05): keyboard-only use, AccessKit screen readers, contrast of both themes | + +--- + +## 4. Direction + +Code-CAD has one decisive advantage over GUI CAD: a design is a program. It +can be versioned, parameterized, tested, generated and reused. CQ-editor +already turns the view into a way to *write* code (selectors, parameters, +measurements as code). The directions below follow that line. Each one +lists what it builds on, in this code and in the libraries, and a first +step small enough to start with. + +### NORTH-01 · Direct manipulation that writes code + +Drag a face or a dimension handle in the view, and the editor changes the +parameter that drives it, then renders. The code stays the only source of +truth (principle 1), and the view becomes an input device for it. + +* **Builds on:** parameters (FEAT-B3), provenance of each object's line + (FEAT-B4), selectors (FEAT-B1), exact picking. +* **How:** for a picked face, re-run with each parameter nudged by a small + amount and see which parameters move that face and how. That gives the + handle's direction and scale without any symbolic analysis. +* **First step:** a *Which parameters move this?* command on a picked face. + +### NORTH-02 · Incremental execution + +Re-run only what an edit changed. A `Workplane` chain is a graph of +immutable steps, and the worker already hashes geometry by content. Caching +operation results by their inputs (the source line, the parameters, the +input shapes' ids) would let a late edit skip early booleans. Live preview +could then follow typing, even on heavy models. + +* **Builds on:** `GeometryCache` and content ids, provenance recording of + `Workplane.newObject`, the profiler's timing per line and operation. +* **First step:** profile-guided memoization of the slowest operations + (FEAT-E2 already knows which ones they are), behind a preference. + +### NORTH-03 · Geometric diff and history + +Compare two versions of a model: two runs, two local-history versions or +two git commits. Show added and removed material +(`BRepAlgoAPI_Cut` in both directions), changed faces, and how volume, mass +and bounding box changed. + +* **Builds on:** local history, the conflict dialog's comparison view, + measurements, SUG-16. +* **First step:** *Compare with the last run* in the Objects panel. + +### NORTH-04 · Test-driven CAD + +Design rules as code: `expect(part).volume_between(…)`, +`.clearance(a, b) >= 0.2`, `.min_wall(1.2)`, `.no_overhang_beyond(45)`. +They are shown as a *Checks* panel after every run and run headless in CI +([REQ-10](#req-10--headless-build-and-check)). A failing check points to the +code line and highlights the geometry. + +* **Library support:** `BRepExtrema` (distances, wall thickness by + sampling), `BRepGProp` (mass properties), `BRepCheck` (validity), face + normals for overhang and draft analysis. +* **First step:** a small `cq_editor.checks` module injected like + `show_object`, with three checks and a panel. + +### NORTH-05 · Drawings and model-based definition from code + +Technical drawings made by code: views made with `HLRBRep` (hidden-line +projection, already used by CadQuery's SVG exporter), dimensions from +measurements, sheets exported to SVG, DXF and PDF. Then the same dimensions +and tolerances written into STEP AP242 as PMI (`XCAFDimTolObjects` is in +OCP), so the 3D file carries the manufacturing information. + +* **First step:** a *Drawing* tab with front, top and side views of the + selection, exported to SVG. + +### NORTH-06 · Assemblies as mechanisms + +Show the constraints of `Assembly.constrain` (which faces and points, the +kind) and the solver's residuals. Animate joints by driving a parameter +over time, detect interference along the motion (SUG-11), and produce a +bill of materials with mass from materials. + +* **Library support:** CadQuery's assembly solver (casadi), `cq.Material`, + `BRepExtrema`. +* **First step:** list constraints under each assembly in the Objects + panel and highlight their entities on hover. + +### NORTH-07 · Design-space exploration and optimization + +Sweep parameters over a grid and show the variants side by side, with +their measured properties. Then optimize: minimize mass under a clearance +or stiffness constraint, with nlopt, already installed as a CadQuery +dependency. Variants are saved as named parameter sets of the script. + +* **Builds on:** parameters, headless runs (REQ-10), checks (NORTH-04). +* **First step:** *Sweep parameter…* producing a table and thumbnails. + +### NORTH-08 · A sketch workbench that writes `cq.Sketch` + +Draw 2D profiles with constraints in the view. The workbench writes them as +`cq.Sketch` code with `.constrain()` calls and solves them with CadQuery's +sketch solver. Editing the code updates the drawing. + +* **First step:** show a `Sketch`'s constraints and their status (solved, + over- or under-constrained) when it is selected. + +### NORTH-09 · An AI design partner that works through code + +An assistant that turns intent into CadQuery code, reads tracebacks and +measurements, proposes selectors and fixes, and checks its own proposals by +running them in the worker. The loop is code → model → checks → code, so +the result is always ordinary, reviewable code (principle 1). It can use the +same tools the GUI uses: run, measure, selectors and checks (NORTH-04). It +is optional, with explicit consent before any code or model leaves the +machine. + +* **First step:** *Explain this error* and *Write a selector for this face*, + each answered as a code edit the user accepts or rejects. + +### NORTH-10 · The OCP ecosystem + +Show any object that wraps a `TopoDS_Shape` (`.wrapped`), so build123d, +`cq_warehouse` parts and OCP-based libraries work with `show_object` +(former FEAT-F1). Offer part libraries through the environment manager +(FEAT-E3), and a plugin API (SUG-20) for exporters and commands. + +* **First step:** accept `.wrapped` in `to_compound` and test with build123d. + +--- + +## 5. Milestones + +| Milestone | Goal | Contents | +| --- | --- | --- | +| **0.8.x: safe files** | Nothing is lost or mislabeled | BUG-33…BUG-40, REQ-01, REQ-02, REQ-03, REQ-11, regression tests of REQ-13 | +| **0.9: correct output** | What leaves the editor is right | REQ-04, REQ-05, REQ-06, REQ-07, REQ-09, REQ-12 | +| **1.0: projects and automation** | Comfortable for large designs and CI | REQ-08, REQ-10, the rest of REQ-13, SUG-01, SUG-02, SUG-09, NORTH-10 | +| **Later** | Leading code-CAD | The other suggestions, NORTH-01…NORTH-09 | + +Bugs come before features. The order inside a milestone is flexible. + +--- + +## Completed + +What the previous roadmap marked as resolved; its open items moved into +the sections above. The ids are kept because code comments and the +changelog refer to them. + +| Ids | What | +| --- | --- | +| BUG-01…BUG-32 | Bugs of the rewrite and of the October 2026 reviews (object keys across restarts, breakpoints following edits, worker events while minimized, recovery after *Don't save*, the debugger's `DebugStop`, bounded output, mesh ids per mesher…); see the [changelog](changelog.md) | +| PERF-01…PERF-04 | Validated face mapping for picking, glTF scratch reuse, two-phase BVH picking, exact measurements from live geometry | +| FEAT-B1…B5 | Selection to code, `selected()` in the console, Parameters panel, *Go to Source*, measurements and *Copy as code* | +| FEAT-C1…C8 | Section view, exploded view and isolation, X-ray and hidden-line modes, named views, high-resolution screenshots and turntables, large-model mode, ground grid and scale bar, stereo modes | +| FEAT-D1 | Tabs and the Project panel | +| FEAT-E1…E6 | Gentle stop, per-line profiling, environment manager, self-contained installers, update check, rich console output | +| ENG-06 | `src/app/` split by concern around the `Execution` state machine | diff --git a/docs/user-guide/console.md b/docs/user-guide/console.md new file mode 100644 index 000000000..14e6b30fb --- /dev/null +++ b/docs/user-guide/console.md @@ -0,0 +1,133 @@ +# Console, variables and logs + +## Console + +The **Console** panel is an interactive Python prompt running in the same +Python process as your scripts. + +* After each run it contains the script's **variables**, so you can query + the model without editing the script: + + ```python + >>> bracket.val().Volume() + 10944.0… + >>> bracket.faces(">Z").val().Center() + ``` + +* It offers the script API: `show_object` (or its alias `show`), `debug`, + `log`, `rand_color` and `cq`. Objects shown from the console are **added** + to the view, next to the script's objects: + + ```python + >>> show_object(cq.Workplane().sphere(5), name="ball", color="tomato") + ``` + +* `selected()` returns what is picked in the 3D view, for measurements and + experiments: the picked faces, edges and vertices as `cq.Face`, + `cq.Edge` and `cq.Vertex`, in the order they were picked and placed as + shown (an assembly part in the assembly's coordinates). When no entity is + picked, it returns the shapes of the selected objects (a shown workplane + holding one solid gives that `cq.Solid`), and an empty list when nothing + is selected: + + ```python + >>> top, hole = selected() # a face and an edge, Ctrl+clicked + >>> top.Area(), hole.radius() + >>> top.distance(hole) + >>> selected()[0].Volume() # with an object selected instead + ``` + + The selection is read when `selected()` runs. Picks from before a Python + restart, or of a model that changed since, raise a `LookupError` that + says so. + +* `print` output and errors appear in the console itself. + +* **Rich results**: a value with a picture shows it, as in Jupyter. A + matplotlib figure, or any object with `_repr_png_` or `_repr_jpeg_` + (PIL images, for example), is drawn in the console, scaled to fit, above + its text. `display(a, b, …)` shows each value the same way, also from + inside a loop or a function: + + ```python + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.plot(sizes, volumes) + >>> fig # the plot appears in the console + >>> display(fig, "done") + ``` + + Only PNG and JPEG images are shown; HTML, Markdown, SVG and LaTeX show + their plain text. An image over 4 MB or 4096 pixels, or beyond the 20th + of one command, is replaced by a note. Each command may produce up to 100 + rich results. The console keeps its newest 50 images within a shared memory + budget, replacing older images with a note when necessary. + +| Key | Action | +| --- | --- | +| Enter | Run the input | +| Shift+Enter | New line (for multi-line statements such as `for` loops) | +| ↑ / ↓ | Browse the input history (single-line input) | +| Tab | Complete the name before the cursor (needs `jedi`) | + +An incomplete statement (an open `for:` block, for example) waits for more +input, as in the standard Python prompt. + +The buttons next to the input clear the console (**Run > Clear Console** +does the same) and restart it with a fresh namespace. While a command runs, +a Stop button appears there too: like **Run > Stop**, it interrupts the +command (`KeyboardInterrupt`) and keeps the namespace, unless the command does +not stop within 3 seconds and Python has to be restarted. **Run > Restart +Python** always resets the console, since it starts a new Python process. + +## Variables + +The **Variables** panel lists name, type and value of every public variable +after a run, or of the local variables of the paused frame while debugging. + +* Type in the filter box to search by name or type. +* The **Value** column takes the width that **Name** and **Type** leave; drag + the column borders to resize them. +* **Click a row** to show its whole value below the table, where it wraps and + can be selected or copied; × closes it. Right-click a row to copy its value + or name. +* Values are cut at 2000 characters. +* The names CQ-editor injects (`show_object`, `debug`, …) are hidden. + +## Traceback + +When a run fails, the **Traceback** panel shows: + +* the exception type and message, in red; +* one row per frame (**File**, **Line**, **Function**, **Code**), starting + at your script. Frames inside CQ-editor are hidden, frames inside CadQuery + are kept; +* a copy button for the full Python traceback. + +Click a row that belongs to your script to jump to that line, in the tab of +the script that ran. A row in another Python file that exists, such as a +module of your project, opens that file at the line. When the last run +succeeded, the panel shows *No errors*. + +## Log + +The **Log** panel collects everything that is not a direct result: + +| Source | Examples | +| --- | --- | +| `print` | `print()` calls in scripts (stdout) | +| `stderr` | Text written to `sys.stderr` and native library messages (OpenCascade) | +| `script` | `log(value)` calls | +| Python loggers | `logging.info(...)`, warnings such as *Ignoring invalid display option* | +| CQ-editor | Worker start-up, recovery events, file reload messages | + +* Toggle **Errors**, **Warnings**, **Info** and **Debug** to filter by level + (Debug is hidden by default), or type in the filter box, which matches the + text and the source and ignores case. +* The copy button copies the lines currently shown. **Clear** (or **Run > + Clear Log**) empties the panel. +* Every line is also written to the log file `logs/cq-editor.log` in the + [application data + folder](../getting-started/installation.md#where-cq-editor-keeps-its-files), + which survives a crash of CQ-editor and is not affected by **Clear**. +* The log keeps the newest 10,000 lines. diff --git a/docs/user-guide/debugging.md b/docs/user-guide/debugging.md new file mode 100644 index 000000000..082133c04 --- /dev/null +++ b/docs/user-guide/debugging.md @@ -0,0 +1,118 @@ +# Debugging and inspection + +Two tools help you see *how* a model is built, not only the result: + +* the **debugger** runs the script line by line and shows the model as it + grows; +* the **CQ Inspector** replays the chain of CadQuery operations behind any + workplane. + +## The debugger + +![Paused at a breakpoint](../images/debugger.png) + +### Starting a session + +1. Click line numbers to set breakpoints (red dots). +2. Choose **Run > Debug** (Ctrl+F5, toolbar bug icon). + +As in the original CQ-editor, the script **runs until the first +breakpoint**. Without breakpoints it runs to the end, so set at least one. +The 3D view is cleared when the session starts. + +### While paused + +* The paused line is highlighted and the status bar reads *Paused at line N*. +* The **3D view** shows every CadQuery object among the local variables of + the paused frame, so you see the model at that exact point. +* The **Variables** panel lists those locals. +* Completion, the CQ Inspector and export still work. Requests that would + change the session (another run, the console) are refused with *Not + available while debugging; continue or stop first*. +* You can add or remove breakpoints. They take effect with the next step. + +### Stepping + +| Command | Shortcut | What it does | +| --- | --- | --- | +| Step | Ctrl+F10 | Run the current line, stepping over function calls | +| Step In | Ctrl+F11 | Stop at the next line, entering functions defined in the script | +| Step Out | Ctrl+Shift+F11 | Run until the current function returns | +| Continue | Ctrl+F12 | Run to the next breakpoint, or to the end | +| Stop Debugging | Ctrl+F5 | End the session | + +The debugger traces the main script and Python modules inside the project +folder. Set breakpoints in their tabs; the paused module opens at its line. +CadQuery and OpenCascade libraries run at full speed. Closing the tab of the +script being debugged, or the module currently paused, ends the session. + +When the session ends, normally or with *Stop Debugging*, the view shows +what the script displayed, or the CadQuery objects that existed when it +stopped. + +### Stopping a runaway script + +**Run > Stop** (Ctrl+Shift+F5) first asks the script to stop, as Ctrl+C +would in a terminal: Python raises `KeyboardInterrupt` where the script is, +so a loop or a `time.sleep` stops at once, and the status bar says at which +line. Python keeps running, with the console's variables and the meshes it +has cached. Native code (a long OpenCascade operation) only notices when it +returns to Python; if the script has not stopped after 3 seconds, or if you +press Stop again, Python is restarted instead. A paused debugging session is ended +by the debugger, as with *Stop Debugging*. + +After a restart the console's variables are lost. The objects on screen +stay; render again before exporting or inspecting them. + +## CQ Inspector + +![The CQ Inspector with the overlay on](../images/inspector.png) + +A CadQuery `Workplane` remembers the chain of workplanes that produced it. +The inspector shows that chain for the selected object: + +1. Select a workplane object in the Objects panel (or in the view). +2. Open the **CQ Inspector** tab. + +Each row is one step of the chain, **newest first**, with the workplane's +origin and the number of objects on its stack. Expand a step to see its +objects with a short description, for example *Compound 1 solid(s), volume +1.09e+04*, *face plane, area 120*, *edge line, length 30* or a vertex +position. + +Turn on **Show in view** to overlay the selection on the model. **Tools > +Inspect CQ Object** and the layers button in the toolbar toggle the same +option. + +* click a **step** to draw all of its objects together with a grid on its + **workplane**; +* click a single **object** to draw only that object. + +The **line N** button of a step or an object goes to the script line that +made it, so the chain can be followed in the code. + +This is the quickest way to understand selectors such as +`.faces(">Z").workplane()` or `.vertices()`: you see which plane the next +operation is relative to, and which entities it acts on. + +Only workplanes have a construction chain. Shapes, sketches and assemblies +show *Select a workplane in Objects to inspect it*. + +## Debugging tips + +When a recognized CadQuery operation fails with a related kernel or selector +error, the **Traceback** panel shows possible CAD causes above the original +Python traceback. The operation and script line are linked; click its line +button to return to the code. These hints are troubleshooting suggestions, +not a geometric diagnosis proven by OpenCascade. The full traceback remains +available for copying, and ordinary Python errors receive no CAD advice. + +* **Check a selection without changing the model:** `debug(part.edges("|Z"))` + draws the edges in translucent red. +* **Measure from the console:** after a run, `bracket.val().Volume()` or + `bracket.faces(">Z").val().Center()`. +* **Find which line breaks:** when a CadQuery operation fails with an + OpenCascade error such as `StdFail_NotDone`, set a breakpoint just before + it. Inspect the inputs in the view and the inspector, then step over it. +* **Selected face ids** (*Selected Face 6 of bracket*) tell you which entity + you clicked. Compare them with what your selector returns. diff --git a/docs/user-guide/editor.md b/docs/user-guide/editor.md new file mode 100644 index 000000000..2d2cda83d --- /dev/null +++ b/docs/user-guide/editor.md @@ -0,0 +1,261 @@ +# Code editor + +The editor is built for short CadQuery scripts: Python highlighting, smart +indentation, completion, documentation on hover, search and replace, and +breakpoints. It also takes care that your work is never lost. + +## Editing + +| Feature | How | +| --- | --- | +| Syntax highlighting | Automatic. Colors follow the light or dark theme | +| Line numbers, current line | Always shown. The current-line highlight can be turned off | +| Vertical ruler | At column 79 by default (*Maximum line length*, 0 hides it) | +| Indent / unindent | Tab / Shift+Tab. With several lines selected, Tab indents them all. Indentation is 4 spaces | +| Auto-indent | Enter keeps the indentation, indents after a line ending with `:` and dedents after `return`, `pass`, `break`, `continue` or `raise` | +| Toggle comment | Ctrl+/ comments or uncomments the selected lines | +| Undo / redo | Ctrl+Z / Ctrl+Y (or Ctrl+Shift+Z), also in the **Edit** menu. Typing is undone a burst at a time: a pause, a new line or a click elsewhere starts the next step. An indent, a comment, an accepted completion, a *Replace all* and a reload from disk are each one step. Each tab has its own history | +| Go to line | Ctrl+G opens a bar above the editor: type a line, or `line:column`, and press Enter | +| Line wrap | Off by default (*Preferences > Editor*) | +| Font size | 13 by default (8–28) | + +## Completion and call signatures + +Completion opens by itself after you type `.` (for example `cq.` or +`result.`), and once you have typed the first three characters of a name +(*Preferences > Editor > Complete names after*; 0 turns that off). Press +**Ctrl+Space** (or **Alt+/**) to complete the name under the cursor at any +other time: + +* a popup lists matching names (up to 200) and filters as you keep typing; +* **↑/↓** choose, **Enter** or **Tab** accept, **Esc** closes; +* right after `(` or `,`, the call signature of the function is shown + instead, for example the parameters of `Workplane.box`. + +Completion runs in the Python worker with [jedi](https://github.com/davidhalter/jedi). +It knows the script API (`show_object`, `cq`, …) and anything importable from +the selected environment. Install `jedi` in that environment to enable it. +Without jedi, the command does nothing. + +## Documentation on hover + +Rest the mouse pointer on a name for a moment to see its documentation in a +tooltip: the call signature and docstring of a function or class (for +example `Workplane.box`), the docstring of a module, or the type a variable +holds (`box: Workplane`). It also comes from jedi, and appears only while +no script is running. + +## Code navigation + +**Alt+O** opens the Navigation panel. Its outline lists top-level +variables, functions, classes and methods from the current script, including +unsaved edits. Filter by name and click a symbol to jump to its line. The +outline uses Python's parser and works without Jedi; it is empty while the +script has a syntax error. + +Place the caret on a name and press **F12** to go to its definition, or +**Ctrl+Shift+F12** to list its references. Both commands are in the **Edit** +menu and command palette. These queries use Jedi's static analysis, so they +do not run the script. Open a project folder to include its other Python +files in the reference search. Results are capped at 200 and the panel says +when there are more. Install `jedi` in the selected Python environment to +enable definitions and references. + +## Selector preview + +After rendering, place the caret inside a literal selector call such as +`part.faces(">Z")`, `part.edges("|Z")` or `part.vertices(">X")`. Matching +entities light up in the 3D view, and **Measurements** shows the match count +or why a preview is unavailable. The highlight is temporary and does not +change the user's selection. It updates after a short pause while moving the +caret and disappears when the caret leaves the call or the script changes. + +The receiver must be a variable from the last successful run that is shown +in the view. The selector must be a literal string. Expressions that compute +the receiver or selector are not run merely to provide a preview. Render the +script again after editing it; old topology IDs cannot be reused safely. + +## Search + +**Ctrl+F** opens the search bar above the editor: + +* matches are highlighted as you type, and the bar shows *N of M* (or *No + matches*); +* **Enter** / **Shift+Enter** go to the next / previous match after the + cursor. From the editor, use **F3** / **Alt+F3**; +* **Aa** toggles *Match case*, and **ab** *Whole word*, which skips the + term inside longer names (`box` but not `boxes`); +* **Esc** closes the bar. + +**Ctrl+H** (or the ⇄ button of the bar) shows the replace row. **Replace** +(or Enter in its field) replaces the selected match and selects the next +one; when no match is selected it first selects the next one, so nothing is +replaced unseen. **Replace all** replaces every match at once, as a single +step to undo. + +## Breakpoints and markers + +Click a line number to toggle a **breakpoint** (red dot). Breakpoints stay +on their statements while you edit: adding or removing lines above one moves +it along, and deleting its line removes it. + +Breakpoints are **remembered per file** across sessions (for the last 100 +files). Each is saved with the text of its line, so if the file changed in +another editor meanwhile, it returns to the line with that text, or is +dropped when no line has it any more. The gutter and line backgrounds also +show: + +* the **current debug line** (yellow) while a debugging session is paused; +* the **error line** (red) after a failed run; +* the **time of each line** after a profiled run (below). + +See [Debugging and inspection](debugging.md). + +## Profiling + +**Run > Profile** (Alt+F5, toolbar stopwatch) renders the script and measures +where the time goes. The gutter then shows, next to the line numbers, the +time each line took **with everything it called**: a line calling a slow +function of the script shows that function's time too, and the function's +own lines show theirs. The slowest lines are the most orange; lines that took +less than a millisecond stay blank. The status bar names the slowest line. + +Hover a time for details: how many times the line ran (in a loop) and its +calls into CadQuery by operation, slowest first, for example +`Workplane.fillet: 1.2 s (3 calls)`. + +The times follow your edits, like breakpoints, until the next run, which +clears them; **Run > Clear Profile** removes them at once. A script that +fails is profiled up to its error. Profiling slows Python-heavy code +somewhat (CadQuery's geometry work happens in OpenCascade and is not +slowed), and a debugging session is never profiled. + +## Files + +| Command | Shortcut | Notes | +| --- | --- | --- | +| New | Ctrl+N | Empty untitled script, in a new tab | +| Open… | Ctrl+O | Python files (`*.py`), several at once, each in a tab | +| Open Folder… | Ctrl+Shift+O | Shows the folder in the Project panel | +| Open Recent | | The last 10 files, then recent folders | +| Save | Ctrl+S | Untitled scripts and examples ask for a location | +| Save As… | Ctrl+Shift+S | | +| Save All | | Every tab with unsaved changes | +| Close Tab | Ctrl+W | Asks first when the tab has unsaved changes | +| Quit | Ctrl+Q | | + +* Every open file has a **tab**; see [Projects and multiple + files](projects.md) for tabs, the Project panel and the main script. +* CQ-editor reopens the tabs of the last session when it starts, and shows + the file that was shown. A file given on the command line is opened too, + and shown. +* Closing a tab, closing the window or quitting with unsaved changes asks + **Save**, **Don't save** or **Cancel**, once for all the files concerned. +* **Examples** (File > Examples) open as read-only buffers. You can edit and + run them; saving asks for a new location. + +### Encoding and line endings + +Files are read and written as **UTF-8**. When a file is not valid UTF-8, +CQ-editor asks before doing anything: **Open as Windows-1252** reads it with +the Western European encoding of older Windows editors, without changing the +file. Saving it then writes UTF-8, the encoding Python expects; until then +the status bar shows *Windows-1252 → UTF-8*. **Cancel** leaves the file +alone. A UTF-8 byte order mark and the file's line endings (LF, CRLF or CR) +are preserved on save. The status bar shows the encoding and the line +endings. + +### Safe saving + +Saves are **atomic**: the new contents are written to a temporary file next +to the script and then swapped in. A crash or power loss in the middle of a +save leaves either the old or the new file, never a truncated one. + +## Parameters panel + +The **Parameters** panel lists the script's top-level numbers, such as +`width = 40` or `wall: float = 2.5`, each with a spin box and a slider. +Changing a value rewrites its literal in the script and renders again once +the value stops changing for a moment, so the script stays the source of +truth: the change is an ordinary edit (a whole drag is one Undo step), and +saving keeps it. Click a name to go to its line. + +![The Parameters panel next to a twisted vase](../images/parameters.png) + +Integers stay integers, and floats keep the decimals they are written with +(`2.50` moves by 0.01). A comment after the value sets the slider's range, +optionally with a step, and bounds the value: + +```python +width = 40 # [10, 100] +hole = 2.5 # diameter [0.5, 5, 0.25] +count = 3 # 1..12 +``` + +Without a range, the slider spans from zero to twice the first value. +Only plain assignments at the start of a top-level line count: numbers +inside functions or blocks, bracketed or continued lines, strings, and +expressions such as `a = 1 + 2` are left alone. Values cannot be changed +while debugging. + +## Automatic reload and preview + +Turn on **File > Automatic Reload and Preview** (toolbar ⟳) to edit the +script in your favorite editor while CQ-editor shows the result: + +* the file is checked every 250 ms, and the script re-runs after it changes. + Editors that save by deleting and recreating the file (vim, neovim) are + supported; +* *Autoreload delay* (default 50 ms) waits for the other editor to finish + writing; +* *Autoreload: watch imported modules* also re-runs when local modules + imported by the script change; +* a save that only touches the timestamp, without changing the contents, + does not re-run anything; +* the other open tabs are watched too, and reloaded when another program + changes their file (see [Projects and multiple + files](projects.md#automatic-reload)). + +### When the file changes while you have unsaved edits + +CQ-editor never silently throws away your edits. If the file on disk changes +while the buffer has unsaved changes that differ from it, the **File changed +on disk** dialog appears: + +| Choice | Result | +| --- | --- | +| **Keep my version** | The buffer is unchanged. Saving later overwrites the disk version, which is first kept in the local history | +| **Reload from disk** | The disk version replaces the buffer. Your edits are first saved as a recovery backup, whose path is shown in the status bar and the log | +| **Save a copy…** | Saves your edits under another name (`.local-copy.py` by default), then reloads the disk version | +| **Compare changes** | Shows both versions side by side before you decide | + +If the disk version matches your buffer, nothing is lost and the reload +happens without a question. + +Saving checks the file too, with or without automatic reload. If another +program (git, another editor, a formatter) changed it since you opened or +last saved it, nothing is written: the same dialog asks first, with +**Save my version** (the other version is kept in the local history before +it is replaced) and **Cancel** in place of *Keep my version*. + +## Crash recovery and local history + +While a buffer has unsaved changes, CQ-editor writes a **recovery +checkpoint** every 5 seconds (and before risky operations such as reloading +or saving). + +* **After a crash** or a forced shutdown, the next start shows **Unsaved work + can be recovered**, with the time of the checkpoint and every file that + had unsaved changes. Choose **Restore session**, which puts each back in + its tab, or **Discard recovery**. +* **File > Local History…** lists earlier versions of the current document: + checkpoints, saved versions and the contents a *Save As* replaced. Select + one to preview it, then **Restore this version**. The newest **20 + versions per document** are kept. Versions older than 90 days are removed, + which also clears the history of files you deleted or renamed, and the + oldest versions go first when the whole history exceeds 64 MB. + +Recovery data stays on your computer, in the `recovery/` folder of the +[application data folder](../getting-started/installation.md#where-cq-editor-keeps-its-files). +Saving a file, or a deliberate *Don't save*, takes it out of the recovery +session; the session ends once no tab has unsaved changes. diff --git a/docs/user-guide/exporting.md b/docs/user-guide/exporting.md new file mode 100644 index 000000000..cf7b10b4a --- /dev/null +++ b/docs/user-guide/exporting.md @@ -0,0 +1,111 @@ +# Exporting and sharing + +## Export formats + +| Format | Menu | Best for | +| --- | --- | --- | +| **STEP** (`.step`) | Tools > Export as STEP… | Exact CAD geometry with names, hierarchy and colors, including multiple objects | +| **STL** (`.stl`) | Tools > Export as STL… | 3D printing, mesh tools | +| **BREP** (`.brep`) | Tools > Export as BREP… | OpenCascade's native format: lossless, for other OCCT-based tools | +| **3MF** (`.3mf`) | Tools > Export as 3MF… | 3D printing with part names and colors | +| **glTF / GLB** (`.gltf`, `.glb`) | Tools > Export as glTF / GLB… | Web viewers and rendering | +| **XBF** (`.xbf`) | Tools > Export as XBF… | OpenCascade assemblies with names and colors | +| **AMF, VRML, VTK.js, SVG, DXF** | Tools > Export as… | Mesh or drawing interchange | + +The same commands are in the **Export** button of the Objects panel and in +the right-click menu of an object. + +**What gets exported.** The Export dialog offers the selection (including +its children), visible parts, or everything. STEP exports named assembly +children by default, with world placement and colors even when several +objects were shown separately. You may choose fused STEP output and AP214 +or AP242. Other formats preserve the properties their file format supports; +the dialog calls out limitations before export. A broken or empty VTK.js +archive is reported as an error. + +**Model units.** Choose what one number in the script means. The dialog uses +the 3D View preference and asks you to choose when it is *None*. STEP records +that unit, 3MF records it in the model, and glTF/GLB convert coordinates to +meters. STL and DXF cannot store a unit; tell the recipient what you chose. + +**Geometry check.** Before writing, CQ-editor checks each exported shape for +invalid topology, open shells and non-manifold edges. If it finds a problem, +you can cancel, export anyway, or try OpenCascade ShapeFix on an export copy. +The script and displayed model are unchanged by that repair. **Tools > Check +Geometry** also compares the exact solids of the assembled model. Its report +distinguishes interferences, contacts, clearances and inconclusive calculations; +**Select pair** highlights both pieces and draws their exact shared volume in +red when they interfere. The Objects panel marks checked objects +with topology problems. + +An export with interfering pieces pauses for review. **Export anyway** keeps +the geometry exactly as scripted; ShapeFix is offered only for topology defects +and does not resolve an overlap between distinct parts. +For a known press fit or weld, declare the specific pair and reason with +`allow_interference(...)` in the script. Other overlaps remain blocked. + +The file dialog proposes the script's name (`bracket.step`) and adds the +extension if you leave it out. The status bar shows *Exporting …* while the +file is written. + +**Mesh precision.** The dialog starts with the two values from +*Preferences > Objects* and lets you adjust them for each export. They are +separate from the display mesh. STL can be binary or ASCII. + +| Setting | Default | Meaning | +| --- | --- | --- | +| STL precision | 0.1 (model units) | Maximum distance between the mesh and the true surface | +| STL angular precision | 0.1 rad | Maximum angle between neighboring facets | + +Lower values give smoother prints and bigger files. + +### Exporting from the script + +For repeatable output, export from the script with CadQuery: + +```python +cq.exporters.export(bracket, "bracket.step") +cq.exporters.export(bracket.section(), "bracket.dxf") +assy.export("assembly.step") +``` + +With *Change working dir to script dir* on (the default), relative paths are +written next to the script. + +## Screenshots + +**Tools > Screenshot…** (camera icon in the toolbar) saves the 3D view, at +its current size, as a PNG image. + +## Upload Model + +**Tools > Upload Model…** sends the model to a web service, for example to +order a part from a manufacturing service. + +* **URL**: the endpoint that receives the file. **Presets** fills it in for + known services. **PCBWay** is built in. +* **File type**: **STEP**, **STL** or **CadQuery script** (the editor's + source code). +* The selected objects are uploaded, or all objects when nothing is + selected. + +The file is sent as a multipart form field named `file`. If the service +answers with a link (as the PCBWay preset expects), the dialog shows it so +you can continue on the service's website. Otherwise the raw HTTP response +is shown. + +> **Privacy.** Uploading sends your model, or your script, to the URL in the +> dialog. Nothing is sent unless you press **Upload**. + +## Network access + +CQ-editor works offline. It contacts the network only when you ask it to, +and once a day to look for a newer CQ-editor, which you can turn off: + +| Action | Contacts | +| --- | --- | +| Tools > Upload Model… | The URL you enter | +| Help > Check for Updates | `api.github.com`, to list CQ-editor and CadQuery releases newer than the ones you have | +| The daily check (*Preferences > General > Check for updates*, on by default) | `api.github.com`, once a day when Python starts, to list CQ-editor's releases; nothing about you or your files is sent, and a failure (offline) is only logged | +| Preferences > General > Create Environment… / Install Packages… | The Python package index, through pip, for the packages you name | +| Help > Documentation / CadQuery Documentation | Opens your web browser | diff --git a/docs/user-guide/headless.md b/docs/user-guide/headless.md new file mode 100644 index 000000000..32a46b86e --- /dev/null +++ b/docs/user-guide/headless.md @@ -0,0 +1,41 @@ +# Build and check without a window + +CQ-editor can run the same CadQuery script and export handlers from a terminal: + +```sh +cq-editor build part.py --export out.step --set width=40 +cq-editor check part.py --json +``` + +`build` writes the format named by the output extension: STEP, STL, BREP, +3MF, glTF, GLB, AMF, VRML, VTKJS, XBF, SVG or DXF. It checks geometry before +writing and returns a nonzero exit status if the script, topology, interference +check or export fails. `--allow-interference` explicitly permits export despite +an interfering or inconclusive pair, while invalid topology remains blocked. +For a specific intentional overlap, `allow_interference("first", "second", +reason="press fit")` in the script accepts only that pair. `check` reports each displayed object's exact geometry and checks pairs of +solids for interference. It exits nonzero for invalid topology, open shells, +non-manifold edges, interference or an inconclusive exact comparison. +`--clearance DISTANCE` also lists nearby parts below that distance in model +units. Both commands use the +same `show_object` calls, assembly hierarchy and script directory as the GUI. +Requirements declared with `expect(...)` also appear in `check --json` under +`checks`, with their script line and result. A failed requirement makes +`check` exit nonzero and stops `build` before creating an output file. The GUI +shows the same results in its **Checks** panel. + +Use `--set name=value` more than once to override top-level literal assignments +without editing the file. Values are Python scalar literals, such as `40`, +`2.5`, `True` or `'small'`; an unknown parameter is an error. `--unit` sets +the interpretation of model units for export (`millimeter` by default). +`--json` prints one machine-readable result to stdout; script output goes to +stderr. Script failures include their traceback. `--python PATH` selects the +same CadQuery Python environment as the GUI and can appear before or after +the command. + +```sh +cq-editor --python /path/to/python check part.py --set width=40 --json +``` + +The command exits with status 0 on success, 1 for a model or environment +failure, and 2 for invalid command-line syntax. diff --git a/docs/user-guide/interface.md b/docs/user-guide/interface.md new file mode 100644 index 000000000..c7e691d92 --- /dev/null +++ b/docs/user-guide/interface.md @@ -0,0 +1,189 @@ +# The interface + +![Main window, light theme](../images/main-window-light.png) + +The window has one idea: **the script is the model**. The code editor sits on +the left and the 3D view in the center. The panels around them help you +understand what the code produced. Each open file has a tab in the editor, +and an open folder is shown in the Project panel, left of the editor (see +[Projects and multiple files](projects.md)). + +``` +┌───────────────────────────── menu bar · toolbar ─────────────────────────────┐ +│ Editor │ 3D View │ Objects │ +│ (your script) │ (navigation cube, axes) ├───────────────────────┤ +│ │ │ Variables · Inspector │ +├────────────────────┴───────────────┬─────────────────┴───────────────────────┤ +│ Console │ Traceback · Log │ +├────────────────────────────────────┴─────────────────────────────────────────┤ +│ status messages Ln, Col · line ending · UTF-8 · Python/CadQuery │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +## Panels + +Every panel is a dockable tab. Drag a tab to move it, drop it on another +panel to stack it, or close it. **View** lists all panels as toggles, and +**View > Reset Layout** restores the arrangement above. The layout is saved +between sessions. + +The Editor panel can be closed too, for example to write the script in +another editor with automatic reload. It comes back, left of the 3D view, +as soon as a file or a line is shown: opening or creating a file, switching +tabs, a traceback line, *Go to Source*. A layout saved without it gets it +back at the next start, and while it is closed the empty 3D view says so. + +* **Double-click a panel's tab** (or **View > Maximize Panel**, Ctrl+Shift+M, + for the panel you last clicked in) to let it fill the window, for example + the editor while you write or the 3D view while you inspect a model. + Double-click the tab again, or press Ctrl+Shift+M, to bring the layout + back. Going to a line, showing a panel or resetting the layout also brings + it back, and the layout saved between sessions is always the whole one. +* **Right-click a panel's tab** for **Maximize** / **Restore Layout**, + **Reset Layout**, **Float in a Window** (the panel moves to a window of its + own inside CQ-editor; drag its tab back to dock it again) and **Close + Panel**. + +| Panel | Purpose | Details | +| --- | --- | --- | +| **Editor** | The script, with highlighting, breakpoints and completion; a tab per open file | [Code editor](editor.md), [tabs](projects.md#tabs) | +| **Project** | The open folder's files: open, create, rename and delete them, choose the main script | [Projects and multiple files](projects.md#the-project-panel) | +| **3D View** | The rendered model, navigation cube, axes indicator | [3D view](viewer.md) | +| **Objects** | Tree of shown objects and helpers (X/Y/Z axes), with visibility toggles and a property sheet (type, visibility, color, opacity, size, triangle count) | [below](#objects-panel) | +| **Measurements** | Exact OCCT properties for one selected face, edge or vertex, and distance/angle for two | [3D view](viewer.md#exact-measurements) | +| **Parameters** | The script's top-level numbers as spin boxes and sliders; a change rewrites the line and renders again | [Code editor](editor.md#parameters-panel) | +| **Variables** | Name, type and value of the script's variables after a run, or of the locals while debugging | [Console, variables and logs](console.md#variables) | +| **CQ Inspector** | The construction stack of the selected workplane | [Debugging and inspection](debugging.md#cq-inspector) | +| **Console** | Interactive Python sharing the last run's variables | [Console, variables and logs](console.md) | +| **Traceback** | The last error, frame by frame; click a row to jump to the line, in the script or in an imported module | [Console, variables and logs](console.md#traceback) | +| **Log** | `print` output, `log()` messages, warnings from Python and OpenCascade | [Console, variables and logs](console.md#log) | + +### Objects panel + +* **CQ models** lists what the script showed. Assemblies appear as a tree + with one node per part (or as a single object with *Merge assemblies*). +* **Helpers** holds the X, Y and Z axes. +* The checkbox toggles visibility. The color square is the object's color. +* Click to select, Ctrl+click to add to the selection, double-click to zoom + to the object. +* Right-click opens a menu with **Zoom to**, **Go to Source**, + **Show/Hide**, **Isolate** / **End Isolation**, **Show All**, export and + removal (see [Exploded view and + isolation](viewer.md#exploded-view-and-isolation)). Objects hidden by an + isolation are grayed. **Go to Source** (also *Edit > Go to + Source*, Ctrl+Shift+G, and the **Source** row of the property sheet) + shows the script line that created the object: the line of the last + operation of a chain, the line inside a function of the script that made + it, or the line of the `add` call for an assembly part. Lines follow the + edits made since the run; when the line itself was edited, the status + bar says so. +* The toolbar at the top has **Clear all**, **Remove selected** (×) and + **Export** (the selection, or everything when nothing is selected). +* The property sheet below the tree edits the selected object: visibility, + **Color** (with **Reset** to go back to the script's colors), **Opacity**, + **Edges** (this object's edges in the Shaded, X-Ray and Presentation + modes, with **Reset** to follow the preference), **Material** (see + [Materials](viewer.md#materials), with **Reset** to go back to the + script's), and shows its **Size** and + **Triangles**. When a face, edge or vertex is + selected, its id is shown too (for example *Face 6 · part 1*) with its + exact measurements: the surface or curve type, the **Area** of a face, + the **Length** of an edge, a **Radius** when there is one, and the + **Center** (the **Position** of a vertex). Its **Selector** row has + buttons to copy the CadQuery selector of the picked entities or insert it + at the editor's cursor (see [Selection to code](viewer.md#selection-to-code)). + +Colors and visibility changed here last until the next run. Turn on +*Preferences > Objects > Preserve properties on reload* to keep them across +runs (objects are matched by name). + +## Toolbar + +From left to right: + +| Group | Buttons | +| --- | --- | +| File | New, Open, Save, Save as, Automatic reload and preview | +| Objects | Clear all objects, Clear current object | +| Run | Render, Profile, Debug, Step, Step in, Step out, Continue, Stop | +| Inspect | Inspect CQ object | +| View | Fit, then Iso, Top, Bottom, Front, Back, Left, Right, Named views | +| Display | Wireframe, Shaded, X-ray, Hidden line, Presentation, Section view, Exploded view, Screenshot | +| Selection | Auto, Object, Face, Edge or Vertex drop-down | + +Buttons that cannot be used right now (for example *Step* when no debugging +session is paused) are disabled. Hover a button to see its shortcut. The +green ▷ **Render** button is the one to start with. + +When the window is too narrow for every group, the last groups move to the +**»** button at the end of the toolbar, which shows them in a menu. + +## Command palette + +**View > Command Palette…** (Ctrl+Shift+P) searches every command: type a +few letters of its name, in order, such as `exp stl` for +*Export as STL…* or `max` for *Maximize Panel*. Use ↑/↓ and Enter, or click; +Esc closes it. Each command shows its menu and its shortcut, so the palette +also teaches the shortcuts. Besides the menus' commands, it finds the open +tabs, named views, recent files and folders, examples and panels. Commands +that cannot be used right now, such as *Step* when no debugging session is +paused, are not offered. + +## Menus + +| Menu | Items | +| --- | --- | +| **File** | New · Open… · Open Folder… · Open Recent · Save · Save As… · Save All · Local History… · Close Tab · Close Folder · Automatic Reload and Preview · Examples · Quit | +| **Edit** | Undo · Redo · Toggle Comment · Auto-Complete · Search · Replace · Go to Line… · Copy Selector · Insert Selector · Go to Source · Preferences… | +| **Tools** | Export as STEP… · Export as STL… · Export as BREP… · Inspect CQ Object · Screenshot… · Upload Model… | +| **Run** | Render · Set as Main Script / Clear Main Script · Profile · Clear Profile · Debug / Stop Debugging · Step · Step In · Step Out · Continue · Stop · Clear Console · Clear Log · Restart Python | +| **View** | Command Palette… · Fit · Zoom to Selection · Iso · Top · Bottom · Front · Back · Left · Right · Named Views · Wireframe · Shaded · X-Ray · Hidden Line · Presentation · Perspective Projection · Section View · Exploded View · Ground Grid · Scale Bar · Isolate Selection / End Isolation · Show All · panel toggles · Maximize Panel · Reset Layout | +| **Help** | Documentation · CadQuery Documentation · Download CQ-editor *x.y.z*… (when a newer release is out) · Check for Updates · About | + +All shortcuts are listed in the [keyboard and mouse reference](shortcuts.md). + +## Status bar + +* **Left:** the latest status message with an icon: success (*Rendered 1 + object in 0.09 s*), information, warning or error (*AttributeError: … + (line 4)*). +* **Right:** the project's main script (▶ *main.py*) while another file of + the project is shown, since F5 renders it; an *Autoreload* indicator when + automatic reload is on, the cursor position (*Ln, Col*), the file's line ending (*LF*, *CRLF* or + *CR*), the encoding (*UTF-8*) and the state of Python: *Starting Python…*, + *Python 3.x · CadQuery 2.x*, *Python not started* or *Python unavailable*. + Hover the Python state to see the CadQuery and OCP versions and which + interpreter is used. + +The window title shows the file name and folder, for example +*bracket.py — demo — CQ-editor*. An asterisk after the name in the title, +and a dot on the editor's tabs, mark unsaved changes. A dot on the Traceback +tab means the last run failed. + +## Themes and scale + +*Preferences > General > Theme* chooses **System** (default), **Light** or +**Dark**. The editor's syntax colors follow the theme. + +![Main window, dark theme](../images/main-window-dark.png) + +*Interface scale* (0.75–2.0) zooms the whole interface on top of the system +scale. Ctrl + plus and Ctrl + minus do the same while you work. + +## Python status and long runs + +Scripts run in a separate Python process, so the window always stays +responsive: + +* **Run > Stop** (Ctrl+Shift+F5) interrupts a script or console command that + takes too long, keeping Python, its console and its caches; Python is + restarted only if the script does not stop within 3 seconds, or when Stop + is pressed again (see [Debugging](debugging.md#stopping-a-runaway-script)). +* If Python crashes (for example inside OpenCascade), the status bar says so + and a fresh Python process starts on its own. +* **Run > Restart Python** starts a fresh process on demand, for example + after installing a package. + +A restart forgets the console's variables. The objects stay on screen, but +the new Python process does not know them: render again before exporting +or inspecting them. diff --git a/docs/user-guide/preferences.md b/docs/user-guide/preferences.md new file mode 100644 index 000000000..4e89e94cb --- /dev/null +++ b/docs/user-guide/preferences.md @@ -0,0 +1,123 @@ +# Preferences + +**Edit > Preferences…** (Ctrl+,) opens the preferences window. Changes apply +immediately and are saved with the rest of the application state in +`app.ron` (see [where files are stored](../getting-started/installation.md#where-cq-editor-keeps-its-files)). +**Restore defaults**, at the bottom of each page, resets the options of that +page. + +![Preferences window](../images/preferences.png) + +Defaults follow the original CQ-editor wherever the option existed there. + +## General + +| Option | Default | Description | +| --- | --- | --- | +| Theme | System | `System` follows the operating system, or force `Light` / `Dark` | +| Interface scale | 1.00 | 0.75–2.0, on top of the system scale. Ctrl + plus / Ctrl + minus also work | +| Check for updates | on | Look for a newer CQ-editor on GitHub once a day, when Python starts. A release found is announced in the status bar and offered in the Help menu (*Download CQ-editor x.y.z…*, which opens its page) | +| Python interpreter | *(empty: auto-detect)* | Path to the `python` executable with CadQuery. The folder button browses. **Restart Python with this interpreter** applies it. **Detected** lists the Pythons found on this computer; **Create Environment…** makes a new environment with CadQuery and jedi, and **Install Packages…** runs `pip install` in the Python in use (see [Use another Python environment](../getting-started/installation.md#use-another-python-environment)). See [how Python is found](../getting-started/installation.md#how-cq-editor-finds-python) | + +## 3D View + +| Option | Default | Description | +| --- | --- | --- | +| Fit automatically | on | Frame the model after every run | +| Show navigation cube | on | | +| Show axes indicator | on | | +| Animate view changes | on | Standard views, navigation cube and fit | +| Projection | Orthographic | Or Perspective, Stereo, Mono Left Eye, Mono Right Eye (see [Stereo](viewer.md#stereo)). Also toggled from the View menu | +| Stereo mode | Anaglyph | How the Stereo projection combines the eyes: Anaglyph, Row/Column Interlaced, Chess Board, Side by Side, Over Under, or Quad Buffer (shown as the anaglyph) | +| Orbit method | Turntable | Turntable keeps Z up; Trackball rotates freely | +| Background color | (95, 95, 95) | | +| Use gradient | off | Blend to the second color at the bottom | +| Background color (aux) | (30, 30, 30) | Bottom color of the gradient | +| Default object color | (255, 215, 0) gold | For objects without a color | +| Show edges | on | Each object can override it (Objects panel, **Edges**) | +| Hidden edges | on | Faint dashed edges behind faces in the Hidden Line display mode | +| Ground grid | on | A floor grid on the XY plane under the model, also in View > Ground Grid | +| Scale bar | on | A round length at the bottom right of the view, also in View > Scale Bar | +| Units | Millimeters | What one model unit means in the scale bar and export dialog: millimeters, centimeters, meters, inches or none | +| Large models | Automatic | Draw parts that are small on screen with a simplified mesh: from 2 million triangles shown, always, or never (see [Large models](viewer.md#large-models)) | +| Edge color | black | | +| Edge width | 1.5 px | 0.5–5 | +| Deviation | 0.001 | Display mesh chordal deviation, relative to the object size (1e-5 to 0.05). Smaller is finer. Applies on the next run | +| Angular deviation | 0.2 rad | 0.02–1.0. Applies on the next run | + +## Rendering + +How the 3D view lights the model. The lights are attached to the camera, +so the model is lit the same way from every side; changes show at once, +in screenshots too. + +| Option | Default | Description | +| --- | --- | --- | +| Lighting | Default | A preset: **Default** (the crisp look of earlier releases, for modeling), **Studio** (soft and even), **Bright** (for dark colors) or **Dramatic** (one strong side light). Changing a value below shows *Custom* | +| Key light | 0.62 | The main light | +| Fill light | 0.24 | A softer light from the lower right that keeps shadows readable | +| Ambient light | 0.24 | Light from everywhere: the darkest a face can be | +| Rim light | 0.10 | Light grazing the outline of curved surfaces | +| Highlights | 0.22 | Strength of the reflections of the key light | +| Shininess | 48 | Higher gives smaller, sharper highlights | +| Light direction | −24.7° | Where the key light comes from, around the line of sight: negative is left | +| Light height | 33.3° | How far above the line of sight the key light is | +| Exposure | 0 | Overall brightness in photographic stops: +1 doubles the light | +| Contrast | 1.00 | Above 1 darkens shadows and brightens lights around middle grey | +| Edges | All edges | Which edges Shaded, X-Ray and Hidden Line draw, when *3D View > Show edges* is on: **All edges**; **Sharp edges**, without the edges between faces that continue smoothly (a fillet's borders, the seams of cylinders and spheres, faces split in one plane); or **Outline**, the sharp edges plus the outline of curved surfaces as seen from the camera. Wireframe always draws every edge | +| Sharp edge angle | 30° | Faces meeting at less than this angle continue smoothly: Sharp edges and Outline leave their edge out | + +## Presentation + +The look of the Presentation display mode (*View > Presentation*), apart +from the modeling view. + +| Option | Default | Description | +| --- | --- | --- | +| Material | Matte plastic | The material of objects whose script and Objects panel choose none | +| Show edges | off | Each object can still override it in the Objects panel | +| Edges | Outline | Which edges, when shown: All edges, Sharp edges or Outline (see *Rendering*) | +| Background, top / bottom | (236, 237, 240) / (188, 191, 198) | A vertical gradient | +| Axes and grid | off | Also draws the axes, the ground grid and the scale bar | +| Shadow | on | A soft shadow on the ground under the model, as in a product photograph | +| Shadow strength | 0.60 | 0–1. How dark the shadow is where the model touches the ground | +| Shadow softness | 0.50 | 0–1. How far the shadow spreads around the model: 0 is crisp, 1 very soft | +| Lighting … Contrast | Studio | The same controls as in *Rendering*, for this mode | + +## Editor + +| Option | Default | Description | +| --- | --- | --- | +| Font size | 13 | 8–28 | +| Line wrap | off | | +| Maximum line length | 79 | Column of the vertical ruler. 0 hides it | +| Highlight current line | on | | +| Auto-indent | on | Keep and extend indentation on Enter | +| Complete names after | 3 characters | 0–10. Offer completions once this many characters of a name are typed; 0 offers them only after `.` and on Ctrl+Space | +| Autoreload | off | Re-run the script whenever its file changes on disk (same as *File > Automatic Reload and Preview*) | +| Autoreload delay | 50 ms | 0–5000. Wait after a change before reloading | +| Autoreload: watch imported modules | off | Also re-run when local modules imported by the script change | + +## Objects + +| Option | Default | Description | +| --- | --- | --- | +| Preserve properties on reload | off | Keep visibility and colors changed in the Objects panel across runs (matched by object name) | +| Clear all before each run | on | When off, each run adds its objects to the ones already shown | +| Merge assemblies | off | Show an assembly as one object instead of one per part | +| STL precision | 0.1 | Chordal tolerance of STL exports, in model units | +| STL angular precision | 0.1 rad | Angular tolerance of STL exports | + +## Execution + +| Option | Default | Description | +| --- | --- | --- | +| Reload CQ | off | Re-import CadQuery before each run (for CadQuery development) | +| Add script dir to path | on | Scripts can import modules next to them | +| Change working dir to script dir | on | Relative file paths resolve next to the script | +| Reload imported modules | on | Pick up changes to local modules on every run | + +## Other remembered state + +Besides the options above, `app.ron` stores the last 10 recent files, the +file reopened at start-up, the panel layout and the window size and position. diff --git a/docs/user-guide/projects.md b/docs/user-guide/projects.md new file mode 100644 index 000000000..f41f68fc2 --- /dev/null +++ b/docs/user-guide/projects.md @@ -0,0 +1,153 @@ +# Projects and multiple files + +A CadQuery model often grows into several files: a script that assembles the +model and modules for its parts. CQ-editor keeps every file you open in a +**tab** of the editor, and shows a folder's files in the **Project** panel. +The code stays the source of truth: tabs and the panel only help you move +between the files and run the right one. + +``` +gearbox/ +├── main.py ▶ the main script: F5 renders it +├── parts/ +│ ├── __init__.py +│ ├── axle.py +│ └── plate.py +└── README.md +``` + +## Tabs + +Every file you open (**File > Open…**, **Open Recent**, the Project panel, a +traceback row) gets a tab; opening a file that is already open shows its +tab. **New** (Ctrl+N), the examples and recovered work open in tabs too. The +untitled script shown when CQ-editor starts gives way to the first file you +open, as long as you did not edit it. + +The tab strip appears above the editor once two or more files are open: + +* click a tab to show it; **Ctrl+Tab** / **Ctrl+Shift+Tab** (or + **Ctrl+PageDown** / **Ctrl+PageUp**) go to the next or previous tab; +* a dot after the name marks unsaved changes, and ▶ the project's main + script; +* **×**, the middle mouse button or **Ctrl+W** closes a tab. Closing the + last one leaves an empty untitled script; +* right-click a tab for **Close**, **Close Others**, **Close All**, **Set + as Main Script** and **Copy Path**; +* two files with the same name show their folder, for example + *part.py — left* and *part.py — right*. + +Each tab keeps its own state while another one is shown: the caret and the +scroll position, the undo history, breakpoints, the error line, the times of +a profiled run and the search bar. + +### Saving and closing + +**Save** and **Save As…** work on the shown tab; **File > Save All** saves +every tab with unsaved changes (an untitled one asks for a location). +Closing a tab with unsaved changes asks **Save**, **Don't save** or +**Cancel**. Closing the window or **Quit** asks once for all of them, with +the list of files, and **Save all** saves each in turn: if you cancel the +location of an untitled one, nothing is closed. + +### The next session + +CQ-editor reopens the tabs of the last session in their order and shows the +file that was shown. Files deleted meanwhile are skipped. A file given on +the command line is opened as well, and shown. The project folder is opened +again too. + +## The Project panel + +**File > Open Folder…** (Ctrl+Shift+O) shows a folder in the **Project** +panel, docked to the left of the editor. **Open Recent** lists recent +folders below recent files, and **File > Close Folder** (or the × of the +panel) closes it. The panel can be moved like any other (see +[the interface](interface.md#panels)) and shown again from the **View** +menu. + +* Folders come first, then files, sorted by name. Hidden files and folders + (`.git`, `.venv`), `__pycache__`, compiled files and `*.egg-info` are not + listed. +* Click a folder to open or close it, and a script or text file (`.py`, + `.md`, `.txt`, `.json`, `.toml`, `.yaml`, …) to open it in a tab. Other + files are grayed out. +* The file shown in the editor is highlighted, and open files with unsaved + changes have a dot. +* Files created, renamed or deleted by other programs show up by + themselves as you work in the window; the ⟳ button reads the folder + again at once. +* The open folders are remembered per project. + +Right-click a file or folder, or the empty space below the tree, for: + +| Command | What it does | +| --- | --- | +| **New File…** | Creates an empty file in the folder and opens it. Without an extension, the name gets `.py` | +| **New Folder…** | Creates a folder | +| **Rename…** | Renames in place. Open tabs follow the new name and keep unsaved edits; breakpoints, named views, recent files and the main script follow too. An existing name is refused, also when it differs only by case in a folder where case matters; changing just the case of a name works everywhere | +| **Delete…** | Deletes the file, or the folder and everything in it, after a confirmation that names open files with unsaved changes. Their tabs close; their last contents and a deleted file stay in the [local history](editor.md#crash-recovery-and-local-history) | +| **Set as Main Script** | Makes the script the one F5 renders (below) | +| **Copy Path** | Copies the full path | +| **Show in File Manager** | Opens the folder in the system's file manager | + +Names are checked before anything is created: an existing file is never +replaced, and names that some systems refuse (`a:b`, `con.py`, a trailing +dot) are refused everywhere, so the project can move between computers. + +## The main script + +A project's **main script** is the one that builds the model. While a file +of the project is shown, **F5** (and Profile and Debug) runs the main +script, not the file shown, so you can edit a part module and press F5 to +see the whole model. A file outside the project, an untitled script or an +example still renders itself. + +* When a folder is opened for the first time, CQ-editor picks `main.py`, + `__main__.py` or a script named after the folder, else the only script at + the top of the folder that calls `show_object`. When that is not clear, + there is no main script and F5 renders the file shown. +* **Set as Main Script** in the Project panel, on a tab or in the **Run** + menu chooses another one; **Clear Main Script** goes back to rendering + the file shown. The choice is remembered per folder. +* The main script has ▶ in the tree and on its tab. While another file is + shown, the status bar shows ▶ and its name, and so does the tooltip of + the **Render** button. +* The main script opens in a tab, without being shown, the first time F5 + runs it. Its error line, the debugger's current line and profile times go + to its tab; the Parameters panel shows its parameters. + +Python imports the **saved** version of a module. When an open module next +to the script has unsaved changes, the status bar says so after the render: +save it (or **Save All**) and render again. With *Reload imported modules* +on (the default), saved edits to modules apply on the next run. + +## Errors and debugging across files + +* The **Traceback** panel names the script that ran. A frame in the script + goes to its line, in its tab. A frame in another Python file, such as a + module of the project, opens that file at the line. +* A debugging session pauses in the main script and shows its tab. Only + the script itself is stepped through: breakpoints in modules are ignored + (see [Debugging](debugging.md)). +* **Go to Source** on an object shows the line of the script that created + it, in its tab. + +## Automatic reload + +With **File > Automatic Reload and Preview** on, CQ-editor watches the +script F5 runs (the main script in a project), its imported modules +(*Autoreload: watch imported modules*) and every file open in a tab: + +* a file changed by another program is reloaded in its tab, unless the tab + has unsaved edits that differ: then the **File changed on disk** dialog + shows that tab and asks (see [the editor](editor.md#when-the-file-changes-while-you-have-unsaved-edits)); + several conflicts are asked about one after the other; +* a change to the script or to one of its modules renders it again. + +## Crash recovery + +Every tab with unsaved changes is part of the recovery checkpoint. After a +crash, **Unsaved work can be recovered** lists the files; **Restore +session** puts each back in the tab of its file, or in a new tab for an +untitled script. diff --git a/docs/user-guide/scripting.md b/docs/user-guide/scripting.md new file mode 100644 index 000000000..725cd791c --- /dev/null +++ b/docs/user-guide/scripting.md @@ -0,0 +1,336 @@ +# Writing scripts + +A CQ-editor script is a normal CadQuery Python file. It needs no special +imports and no special structure. The same file runs with plain `python`, in +CQ-editor, or in other CadQuery tools that support `show_object`. CQ-editor +adds a few names to the script's namespace so you can display results. + +## The script API + +| Name | Purpose | +| --- | --- | +| `show_object(obj, name=None, options=None, **options)` | Display `obj` in the 3D view and the Objects panel | +| `debug(obj, name=None)` | Display `obj` as a translucent red overlay, handy for checking a selection or a construction shape | +| `expect(obj, name=None)` | Record CAD requirements for the Checks panel and headless CI | +| `log(value)` | Write `str(value)` to the Log panel | +| `rand_color(alpha=1.0, cfloat=False)` | A random, not-too-bright color for `show_object` options | +| `cq` | The `cadquery` module, even if the script did not import it | + +The interactive console offers the same names, plus `show` as a short alias +of `show_object`. + +## `show_object` + +```python +show_object(result) # name taken from the variable: "result" +show_object(result, name="housing") # explicit name +show_object(result, options={"color": "steelblue"}) # options as a dict… +show_object(result, color="steelblue", alpha=0.5) # …or as keyword arguments +``` + +**Naming.** When `name` is omitted, the editor uses the variable that holds +the object in the calling code. If there is none (for example +`show_object(box.faces(">Z"))`), it uses the type and a counter, such as +*Workplane 1*. Showing a second object with the same name replaces the first +one. + +**What can be shown:** + +* `cq.Workplane`: every shape on its stack (sketches included); +* any `cq.Shape` (`Solid`, `Compound`, `Face`, `Wire`, `Edge`, `Vertex`, …); +* `cq.Sketch`, with its placement applied; +* `cq.Assembly`, with its hierarchy, locations and colors; +* a raw OCP `TopoDS_Shape`; +* a list of any of the above, fused into one object. + +Non-shape stack entries (vectors, locations) are skipped. If an object +cannot be displayed, the reason goes to the Log panel and the other objects +are still shown. + +### Display options + +| Option | Value | Effect | +| --- | --- | --- | +| `color` | a color (see below) | Face color. A color with an alpha below 1 also sets the opacity | +| `alpha` | float, 0–1 | Opacity: `1` is opaque, `0` invisible. Values are clamped to 0–1 | +| `rgba` | `(r, g, b, a)` | Color and opacity in one tuple | +| `edgecolor` | a color | Color of the edges | +| `material` | `"matte plastic"`, `"glossy plastic"`, `"brushed steel"`, `"aluminum"`, `"wood"` or `"default"` | How the faces are shaded (see [Materials](viewer.md#materials)). Case, spaces, hyphens and underscores do not matter; `"aluminium"` works too. Metals and wood have a color of their own for objects without a `color` | + +```python +show_object(organizer, color="green", material="matte plastic") +show_object(shaft, material="brushed steel") # steel grey +``` + +Accepted color forms: + +```python +"red", "steelblue", "lightgray" # names known to OpenCascade +"#4682b4", "#48b", "#4682b480" # hex: #rgb, #rgba, #rrggbb, #rrggbbaa +(70, 130, 180) # 0–255 integers +(0.27, 0.51, 0.71, 0.8) # 0–1 floats, optional alpha +cq.Color("steelblue") # CadQuery colors +``` + +An invalid option, such as a NaN alpha, is ignored with a warning in the +Log panel, and the other options of the object still apply. It never stops +the script. An object that cannot be drawn, such as one placed at a NaN +coordinate, is left out with an error in the Log panel; the other objects +are shown. Objects without a color use *Preferences > 3D View > Default +object color* (gold by default). + +### Scripts without `show_object` + +If a script never calls `show_object`, CQ-editor shows **every CadQuery +object bound to a public variable** (a name not starting with `_`). This +keeps quick experiments short: + +```python +import cadquery as cq +plate = cq.Workplane().box(30, 20, 4) +boss = plate.faces(">Z").workplane().circle(5).extrude(6) +# plate and boss are both displayed +``` + +## Assemblies + +```python +assy = ( + cq.Assembly() + .add(plate, name="plate", color=cq.Color("lightgray")) + .add(bolt, name="bolt", color=cq.Color("steelblue"), + loc=cq.Location(cq.Vector(0, 0, 14))) +) +show_object(assy) +``` + +* The Objects panel mirrors the assembly tree. Each part can be hidden, + recolored or exported on its own. +* Parts inherit the color of their parent when they have none. +* Repeated parts share one mesh, so large assemblies stay light. +* *Preferences > Objects > Merge assemblies* shows the whole assembly as one + object instead. +* Exporting a single assembly to STEP keeps its names, structure and colors. + +Example *08 Assembly* (**File > Examples**) is a complete bolted joint. + +### Dimensional fit checks + +Call `require_fit` in the script to make rendering, headless checking and +building fail when the stated worst-case cylindrical fit cannot meet its +requirements: + +```python +require_fit( + hole_diameter=6.5, + pin_diameter=6.0, + hole_lower=-0.1, + hole_upper=0.1, + pin_lower=-0.05, + pin_upper=0.05, + center_offset=0.1, + required_clearance=0.1, +) +``` + +All numbers use the same model unit. Lower and upper deviations are signed; +`center_offset` is the maximum radial misalignment and consumes twice that +value of diametral clearance. Optional pairs `insertion_depth`/`hole_depth`, +`head_diameter`/`counterbore_diameter` and +`head_height`/`counterbore_depth` check blind-hole and head seating dimensions. +`cylindrical_fit(...)` returns the report without raising. This dimensional +calculation is conservative and does not identify an actual hole in a shape; +**Check Geometry** separately verifies the solids as modeled. + +### Intentional interference + +An intentional press fit or welded overlap can be declared in the model script: + +```python +allow_interference("plate", "pin", reason="specified press fit") +``` + +The two names must each identify one solid in the checked scene. Give parts +unique names; merged assemblies also accept the full path shown in +**Check Geometry** if a basename is ambiguous. The +check still reports the exact overlap and its reason. Only that pair is +accepted for export; other collisions and inconclusive Boolean calculations +still block it. A new script run replaces the declarations, so an old +allowance cannot silently apply to a new model. + +### Assembly motion paths + +For insertion or moving mechanisms, declare a path in the script. Each pose is +`(x, y, z, rx, ry, rz)`: translation in model units and XYZ Euler rotation in +degrees. The moving shape is defined around its local origin; obstacles remain +fixed in world coordinates. + +```python +require_clear_path( + pin, + [plate, bracket], + [(0, 0, -20, 0, 0, 0), (0, 0, 0, 0, 0, 0)], + required_clearance=0.1, +) +``` + +`trace_path(...)` returns `clear`, `blocked` or `inconclusive` without raising. +`require_clear_path(...)` stops the run unless the *whole* path is certified +clear. A pose budget and subdivision limit prevent an indefinite check; contact +or numerical uncertainty can therefore remain inconclusive. Paths are +explicit because the final assembly cannot reveal how a part was inserted. + +### Assembly constraint diagnostics + +After calling CadQuery's `assy.solve()`, use `assembly_diagnostics(assy)` for +the constraint list, unconstrained components, solver status and residual, +a conservative lower bound on remaining degrees of freedom, and exact +interference results. `require_constrained_assembly(assy)` fails the script +unless the report is clear. A positive degree-of-freedom lower bound proves +underconstraint; zero does not prove full constraint because redundant or +dependent constraints can hide further freedom. Nested assemblies return an +inconclusive degree-of-freedom result instead of a false assurance. + +### Material, beam and tool-access checks + +For prismatic parts, declare engineering material properties and a section in +the script. The following check includes self-weight, an end load, yielding, +deflection and a minimum wall thickness: + +```python +steel = EngineeringMaterial("Steel", density_g_cm3=7.85, + youngs_modulus_mpa=210000, yield_strength_mpa=250) +tube = BeamSection.hollow_rectangle(20, 20, wall_mm=1.5) +require_beam(section=tube, material=steel, length_mm=700, + transverse_load_n=100, required_safety_factor=2, + maximum_deflection_mm=10, required_wall_mm=1.2) +``` + +Dimensions are millimeters, forces newtons and stresses megapascals. Supported +sections are `rectangle`, `hollow_rectangle` and `round_tube`; support cases are +`cantilever` (end point load) and `simply_supported_center_load` (center point +load). `beam_check` returns the calculation without raising. Compression is +checked against Euler buckling; free thermal expansion or restrained thermal +stress can be included explicitly. The model is a one-dimensional linear +elastic beam with ideal supports. It does not evaluate local buckling, welds, +joint stiffness or a general three-dimensional stress field. + +For tool access, `tool_access(diameter, length, obstacles, poses)` checks a +cylindrical tool envelope along the declared approach path; +`require_tool_access(...)` stops the script if blocked or inconclusive. Model +the actual wrench, drill or driver envelope and its approach when a cylinder +is insufficient. + +### CAD requirements + +Use `expect` to keep measurable requirements next to the model. Every call +records a result; a failure does not stop subsequent checks. The **Checks** +panel lists passes and failures, and clicking a row opens its script line. + +```python +part = cq.Workplane().box(20, 10, 4) +pin = cq.Workplane().circle(2).extrude(4).translate((30, 0, 0)) +expect(part, "housing").is_valid().volume_between(790, 810) +expect(part, "envelope").dimensions_within(x=(19.99, 20.01), z=(3.99, 4.01)) +expect(part, "pin gap").clearance_at_least(pin, 5) +show_object(part) +show_object(pin) +``` + +Ranges are inclusive and use the script's model units (volume uses cubed +model units). `is_valid()` checks topology, open shells and non-manifold +edges; `volume_between()` requires a solid. `dimensions_within()` accepts +any combination of `x`, `y` and `z` ranges. `clearance_at_least()` measures +the minimum exact distance between two shapes; touching or overlapping +shapes have zero clearance. Leave room for geometric tolerance in exact +dimension ranges. Invalid arguments such as a reversed range raise a script +error. A general minimum-wall-thickness test is not provided: the beam +section check above applies only to the declared beam geometry. + +`expect` is a CQ-editor script helper. Scripts intended to run in other +CadQuery tools can guard these optional requirements or provide their own +compatible helper. + +## `debug` + +`debug(obj)` displays `obj` in translucent red (`color="red"`, `alpha=0.2`) +on top of the model: + +```python +edges = part.edges("|Z") +debug(edges) # are these the edges I meant? +part = edges.fillet(1) +``` + +## Output: `print` and `log` + +* `print(...)` output from a script goes to the **Log** panel (source + `print`). Text written to `stderr` appears there as a warning. +* `log(value)` writes an *INFO* entry (source `script`). +* Python `logging` records at level INFO and above are forwarded too. +* Messages printed by native libraries (OpenCascade warnings) are captured + and shown as well. + +In the **Console**, output appears in the console itself instead. + +## The script environment + +Each run starts from a fresh module called `__cq_main__`, so no variable +leaks from one run into the next. Some behavior is configurable in +*Preferences > Execution*: + +| Behavior | Default | Notes | +| --- | --- | --- | +| The script's folder is added to `sys.path` | on | `import my_helpers` works for a file next to the script | +| The working directory is the script's folder | on | Relative paths such as `cq.importers.importStep("part.step")` resolve next to the script | +| Local modules are re-imported on every run | on | Edits to helper modules are picked up. Installed packages (standard library, site-packages) are never reloaded | +| CadQuery itself is re-imported before each run | off | Only useful when developing CadQuery | + +More details: + +* `__file__` is set to the script's path once the script has been saved. +* `rand_color()` is seeded the same way before every run, so "random" + colors are stable from run to run. +* `input()` raises `EOFError`: scripts cannot read from the terminal. +* `sys.exit()` ends the script early without an error. +* Folder and environment settings apply only while the script runs. + +## Errors + +When a script raises an exception: + +* the line is highlighted in the editor, and the status bar shows the + exception and the line number; +* the **Traceback** panel lists the frames from your script onwards (frames + inside CQ-editor are hidden). Click a row in your script to jump to it; +* the full traceback is also written to the Log panel; +* the model of the previous successful run stays on screen. + +Syntax errors are reported the same way, with the line of the error. + +## Patterns that work well + +**Keep parameters at the top.** Dimensions as variables make the model easy +to tweak, and they show up in the Variables panel: + +```python +length, width, thickness = 80, 60, 10 +hole_d = 8.5 +``` + +**Split big models into modules.** Put shared parts in `parts.py` next to the +script and `import parts`. With *Reload imported modules* on, edits to +`parts.py` apply on the next run. With *Autoreload: watch imported modules*, +saving `parts.py` even triggers the run. Open the folder (**File > Open +Folder…**) to edit the modules in tabs while F5 keeps rendering the main +script: see [Projects and multiple files](projects.md). + +**Show intermediate steps while you work** and remove them later: + +```python +show_object(sketch_profile, name="profile", alpha=0.3) +show_object(result) +``` + +**Use the console to experiment** on the last run's objects without editing +the script: `result.faces(">Z").val().Area()`. diff --git a/docs/user-guide/shortcuts.md b/docs/user-guide/shortcuts.md new file mode 100644 index 000000000..b64d7124b --- /dev/null +++ b/docs/user-guide/shortcuts.md @@ -0,0 +1,116 @@ +# Keyboard and mouse reference + +On macOS, **Ctrl** means **Cmd**. + +## Global shortcuts + +Global shortcuts wait while a dialog asks a question (unsaved changes, a +file changed on disk, a message, the command palette…): answer or close +it first, so nothing changes behind it. + +### File and edit + +| Command | Shortcut | +| --- | --- | +| New | Ctrl+N | +| Open… | Ctrl+O | +| Save | Ctrl+S | +| Save As… | Ctrl+Shift+S | +| Open Folder… | Ctrl+Shift+O | +| Close Tab | Ctrl+W | +| Next / previous tab | Ctrl+Tab / Ctrl+Shift+Tab, or Ctrl+PageDown / Ctrl+PageUp | +| Quit | Ctrl+Q | +| Undo (in the editor) | Ctrl+Z | +| Redo (in the editor) | Ctrl+Y or Ctrl+Shift+Z | +| Toggle Comment | Ctrl+/ | +| Auto-Complete | Ctrl+Space or Alt+/ | +| Search | Ctrl+F | +| Replace | Ctrl+H | +| Go to Line… | Ctrl+G | +| Insert Selector (of the picked entities) | Ctrl+Shift+I | +| Go to Source (of the selected object) | Ctrl+Shift+G | +| Next / previous match | F3 / Alt+F3 | +| Preferences… | Ctrl+, | +| Command Palette… (search every command) | Ctrl+Shift+P | +| Maximize the focused panel / restore the layout | Ctrl+Shift+M, or double-click a panel's tab | +| Zoom the interface | Ctrl + plus / Ctrl + minus | + +### Run and debug + +| Command | Shortcut | +| --- | --- | +| Render | F5 | +| Profile (render and time each line) | Alt+F5 | +| Debug / Stop Debugging | Ctrl+F5 | +| Stop (interrupt the script or console command; again to restart Python) | Ctrl+Shift+F5 | +| Step | Ctrl+F10 | +| Step In | Ctrl+F11 | +| Step Out | Ctrl+Shift+F11 | +| Continue | Ctrl+F12 | + +Pressing F5 while a script is already rendering queues one more run, which +starts as soon as the current one ends. + +### View + +| Command | Shortcut | +| --- | --- | +| Fit | Shift+F1 | +| Iso | Shift+F2 | +| Top | Shift+F3 | +| Bottom | Shift+F4 | +| Front | Shift+F5 | +| Back | Shift+F6 | +| Left | Shift+F7 | +| Right | Shift+F8 | +| Wireframe | Shift+F9 | +| Shaded | Shift+F10 | +| X-Ray | Shift+F11 | +| Hidden Line | Shift+F12 | + +## Editor + +| Key | Action | +| --- | --- | +| Tab / Shift+Tab | Indent / unindent the line or the selected lines | +| Enter | New line with automatic indentation | +| Click on a line number | Toggle a breakpoint | +| In the completion popup: ↑ ↓, Enter or Tab, Esc | Choose, accept, close | +| In the search bar: Enter / Shift+Enter, Esc | Next / previous match, close | +| In the replace field: Enter | Replace the selected match and select the next one | +| In the *Go to line* bar: Enter, Esc | Go, close | + +Undo and redo act on the editor only while it has the keyboard focus; the +console input and the search fields keep their own undo. + +## Console + +| Key | Action | +| --- | --- | +| Enter | Run | +| Shift+Enter | New line | +| ↑ / ↓ | Input history | +| Tab | Complete | + +## 3D view + +| Action | Mouse | +| --- | --- | +| Orbit | Left or right drag (around the point under the pointer) | +| Pan | Middle drag, or Ctrl + left drag | +| Zoom | Wheel or pinch (toward the pointer), or Shift + left drag | +| Select according to the toolbar mode (Auto, Object, Face, Edge or Vertex) | Click | +| Add/remove a second measured entity, or add/remove an object in Object mode | Ctrl + click | +| Clear the selection | Click on empty space | +| Zoom to an object | Double-click | +| Look from a side, edge or corner | Click the navigation cube | +| Roll 45° | Click a curved arrow above the cube | + +## Objects panel + +| Action | Mouse | +| --- | --- | +| Select / add to selection | Click / Ctrl + click | +| Zoom to object | Double-click | +| Zoom to, Show/Hide, Export, Remove | Right-click | +| Show / hide | Checkbox | diff --git a/docs/user-guide/troubleshooting.md b/docs/user-guide/troubleshooting.md new file mode 100644 index 000000000..63a69ceb1 --- /dev/null +++ b/docs/user-guide/troubleshooting.md @@ -0,0 +1,135 @@ +# Troubleshooting + +Start with the **Log** panel and the status bar: most problems are explained +there. Hover the Python state at the right of the status bar to see which +interpreter is in use. + +## Python and CadQuery + +**The status bar says *Python unavailable* or *Python not started*.** +CQ-editor could not start the interpreter. Hover the status to read the +reason. Check the path in *Preferences > General > Python interpreter*, or +leave it empty to auto-detect. [How CQ-editor finds +Python](../getting-started/installation.md#how-cq-editor-finds-python) lists +the search order. + +**A *Python was not found* or *CadQuery is not available* dialog appears.** +Either no interpreter could be started (on Windows, `python` may only be +the Microsoft Store placeholder), or it starts but cannot import CadQuery. +The dialog shows the interpreter it tried and lists the other interpreters +found on this computer (virtual and conda environments, python.org installs +and `python` on `PATH`): click one to restart Python with it. **Choose +interpreter…** picks any other one, and **Installation guide** opens +[Installation](../getting-started/installation.md). The interpreter you +choose is kept in *Preferences > General*. Alternatively, install CadQuery +into the environment it tried (`python -m pip install cadquery`) and click +**Retry**. + +**The wrong environment is used.** Start CQ-editor from a terminal in which +the right environment is activated, set `CQ_EDITOR_PYTHON`, or pass +`--python PATH` on the command line. + +**F5 does nothing for a few seconds after start-up.** CadQuery takes a few +seconds to import. The status bar shows *Starting Python…*. A run requested +meanwhile starts automatically when Python is ready. + +**Completion does nothing.** Install `jedi` in the environment that runs +CadQuery (*Preferences > General > Install Packages…*, or +`python -m pip install jedi`) and use **Run > Restart Python**. + +**CadQuery is not installed in any Python I have.** *Preferences > General > +Create Environment…* makes one with CadQuery and jedi, and switches to it. + +**A package I just installed is not found.** Use **Run > Restart Python**: +modules already imported stay loaded in the running process. + +## Scripts + +**The script runs forever.** Press **Run > Stop** (Ctrl+Shift+F5). The script +is interrupted where it is, and the status bar says at which line. If it is +stuck inside OpenCascade and does not stop within 3 seconds, Python is +restarted; the editor stays responsive either way. + +**The status bar says *Python crashed while running the script; it was +restarted*.** A native error (usually inside OpenCascade) killed the Python +process. CQ-editor restarted it. The Log panel shows what the process printed +before it died. Isolate the operation with the debugger (set a breakpoint +just before it). + +**My model does not appear.** +* Did the run succeed? Check the status bar and the Traceback panel. A + failed run keeps the previous model on screen. +* Is the object hidden? Check its box in the Objects panel. +* Was it shown? Without any `show_object` call, only CadQuery objects bound + to public variables are displayed. With a call, only what you pass to + `show_object`. +* Is it off-screen? Press **Shift+F1** (Fit). + +**Relative paths in my script do not work.** Save the script first: an +untitled script has no folder to use as working directory. Also check that +*Preferences > Execution > Change working dir to script dir* is on. + +**Edits to my helper module are ignored.** Keep *Reload imported modules* +on, and keep helpers next to the script (or on `sys.path`) rather than in +site-packages: installed packages are never reloaded. + +**`input()` raises `EOFError`.** Scripts cannot read from a terminal. Use +parameters at the top of the script instead. + +## Files + +**"Not a UTF-8 file".** The script was saved in another encoding, typically +by an older Windows editor. Choose **Open as Windows-1252** to read it; the +file is not changed until you save, and saving converts it to UTF-8 (the +status bar shows *Windows-1252 → UTF-8* until then). If the text looks wrong, +the file uses yet another encoding: cancel, convert it with your editor's +*Save with encoding* command, then open it again. + +**Automatic reload does not trigger.** The script must be saved to a file. +Check that the *Autoreload* indicator is shown in the status bar. If your +editor saves through a temporary file, raise *Autoreload delay*. + +**I lost unsaved work after a crash.** Restart CQ-editor and choose **Restore +session**. If you already discarded it, look in **File > Local History…**. + +## Display + +**The view is slow or uses a lot of memory.** Large or highly curved models +produce many triangles (the Objects panel shows the count). Raise +*Deviation* and *Angular deviation* in *Preferences > 3D View*, or hide +objects you do not need. Turn off *Show edges* for very large assemblies. + +**Rendering takes long.** After each run the Log panel shows a *Run +timings* line: how long the script itself took, the meshing, encoding and +transfer of the geometry, and how many meshes were meshed, taken from the +cache or reused unchanged. If *script* dominates, the time is spent in +CadQuery; if *meshing* does, raise the deviations as above. Parts that did +not change since the last run are reused, not meshed or sent again. + +**Curved surfaces look faceted.** Lower *Deviation* (for example to 0.0005) +and *Angular deviation*, then render again. + +**The window opens off-screen or larger than the screen.** Close CQ-editor +and delete `app.ron` from the [application data +folder](../getting-started/installation.md#where-cq-editor-keeps-its-files). +This also resets the preferences. + +**Panels are lost or squeezed.** Use **View > Reset Layout**. + +**The window does not open, or the 3D view stays black.** The graphics +driver must support Vulkan, Metal or Direct3D 12 (through wgpu). Update the +GPU driver. On Linux, check that Vulkan works (`vulkaninfo`). + +## Reporting a problem + +Please include the information listed in [Reporting a +bug](../../README.md#reporting-a-bug), and copy the relevant lines of the Log +panel (copy button in its toolbar). The **Help > About** dialog shows the +CQ-editor, Python and CadQuery versions. + +Everything the Log panel shows is also written to `logs/cq-editor.log` in +the [application data +folder](../getting-started/installation.md#where-cq-editor-keeps-its-files), +with the date of each line. If CQ-editor itself crashed, the file keeps the +messages that led to it and the panic report. It is rotated at 2 MB; the +previous part is `cq-editor.1.log`. diff --git a/docs/user-guide/viewer.md b/docs/user-guide/viewer.md new file mode 100644 index 000000000..0b1ec7774 --- /dev/null +++ b/docs/user-guide/viewer.md @@ -0,0 +1,488 @@ +# 3D view + +The 3D view draws every visible object with GPU shading, 4× anti-aliasing and +constant-width edges. The camera is controlled with the mouse, the +navigation cube and the View menu. + +## Mouse + +| Action | Control | +| --- | --- | +| Orbit | Left or right drag; a drag started on the model keeps that point fixed on screen | +| Pan | Middle drag, or Ctrl + left drag | +| Zoom | Mouse wheel or touchpad pinch (zooms toward the pointer), or Shift + left drag | +| Select | Left click on a face, edge or vertex | +| Add to / remove from the selection | Ctrl + click | +| Clear the selection | Click on empty space | +| Zoom to an object | Double-click it | + +While the view is being orbited or panned, the pointer becomes a closed hand +to make it clear that the camera is being held and moved. A click without a +drag still selects the object under the pointer. + +The orbit point is chosen when the drag starts. If the pointer is over a +surface, that point stays in place while the view turns, including after a +pan. A drag started on empty space turns around the current view centre. + +The floating zoom controls in the top-left corner offer precise adjustments +without a mouse wheel. Use the magnifying-glass buttons for small steps or drag +the logarithmic slider to a specific percentage. **100%** is the framing set by +the most recent **Fit** or **Zoom to Selection** command. + +**Orbit method** (*Preferences > 3D View*): + +* **Turntable** (default) rotates around the world Z axis and the screen's + horizontal axis, so Z always stays up. This is the most comfortable mode + for mechanical parts. +* **Trackball** rotates freely, like rolling a ball under the pointer. + +Faces annotated with `Assembly.addSubshape` use their specified color in the +view. Picking a named face shows its name and layer in Objects and +Measurements. The assembly material's name and density appear in Objects; +Measurements reports mass when the density is in g/cm³, kg/m³ or g/mm³. + +## Navigation cube + +![Navigation cube](../images/navigation-cube.png) + +The cube in the top-right corner always shows the current orientation. + +* Click one of its **6 faces** to look straight at that side (TOP, FRONT, + RIGHT, …). +* Click one of its **12 edges** or **8 corners** to look from that diagonal. +* Click the **two curved arrows** above it to roll the view by 45°. +* Hovering highlights the part that will be clicked. + +The axes indicator in the bottom-right corner shows the X (red), Y (green) +and Z (blue) directions. Both can be hidden in *Preferences > 3D View*. +In the view itself, short X, Y and Z guides start at the world origin, which +is marked with a white dot. Where the model hides them they are drawn dashed, +so a part built around the origin never makes them disappear. + +## Standard views and framing + +| Command | Shortcut | Toolbar | +| --- | --- | --- | +| Fit (frame all visible objects) | Shift+F1 | ⛶ | +| Iso · Top · Bottom · Front · Back · Left · Right | Shift+F2 … Shift+F8 | cube icons | +| Zoom to Selection | View menu, or double-click | | + +View changes are animated. Turn this off with *Animate view changes*. With +*Fit automatically* (on by default), the view frames the model after every +run. The first model shown is always framed. + +### Named views + +A named view is a camera saved under a name: the point it looks at, its +direction, its zoom and its projection. The toolbar's bookmarks button, +after the standard views, opens the list: + +* click a name to go back to that view (animated like the standard views); +* ⟳ replaces a view with the current camera, 🗑 deletes it; +* type a name and press **Save** (or Enter) to save the current camera; + without a name it becomes *View 1*, *View 2*…, and an existing name is + replaced. + +**View > Named Views** lists the same views and has **Save Current View**. + +Named views belong to the file: they are remembered with the preferences +for the 100 most recently used files and come back when the file is opened +again. A new, unsaved script keeps its views in memory and takes them along +when it is first saved. The display mode, section and exploded view are not +part of a named view. + +## Display modes and projection + +| Command | Shortcut | +| --- | --- | +| Wireframe (edges only) | Shift+F9 | +| Shaded | Shift+F10 | +| X-Ray (see-through faces) | Shift+F11 | +| Hidden Line (visible edges, hidden ones dashed) | Shift+F12 | +| Presentation (the model for showing) | View menu, toolbar ✦, command palette | +| Perspective Projection (toggle) | View menu | + +**X-Ray** draws faces at 30% opacity (less if the object is already more +transparent), so every edge shows through and inner features stay visible. +**Hidden Line** fills faces with the background color: they hide what is +behind them, which leaves a line drawing of the visible edges. Hidden +edges are drawn as faint dashes; turn *Hidden edges* off in *Preferences > +3D View* for visible edges only. In this mode a [section](#section-view) +is hatched in the edge color. + +**Presentation** is for showing a model rather than working on it: in +screenshots, turntables, reviews. It has settings of its own, in +*Preferences > Presentation*, so switching back to Shaded restores the +modeling view untouched. By default it draws no edges, lights the model +with the Studio lights, shades objects without a material of their own +as matte plastic, puts the model on a light grey gradient with a soft +shadow on the ground under it, and leaves out the axes, the ground grid and +the scale bar. Every one of these can be changed there: edges (with the +Outline style, the contour of curved surfaces and the sharp edges), the +lights, the default material, the two background colors, the shadow's +strength and softness, and the helpers. Objects keep their own colors and +materials, and the Objects panel's Edges and Material choices still apply. + +The shadow lies at the bottom of the model (lowest Z), darkest where the +model touches the ground and fading around it, and is seen from above +only. It belongs to the model, not to the view: it is the same from every +side, in screenshots of any size and in turntables, and a screenshot with a +transparent background keeps it as a translucent shade, ready to lay the +picture on any page. Transparent objects (opacity below 30%) and the +helpers cast none. + +In Shaded and X-Ray modes each object can show or hide its own edges: the +**Edges** checkbox in the Objects panel's property sheet overrides *Show +edges* for that object (**Reset** follows the preference again). Wireframe +and Hidden Line always draw edges, and wires and points are always drawn. + +*Preferences > Rendering > Edges* chooses which edges are drawn. **All +edges** draws every edge of every face. **Sharp edges** leaves out the +edges between faces that continue smoothly: the borders of fillets, the +seams of cylinders and spheres, faces split in one plane. On curved, +filleted or fluted models, which have many such edges, the shape reads +much more clearly. *Sharp edge angle* (30° by default) sets how far faces +must turn for their edge to count as sharp. **Outline** adds the outline +of curved surfaces as seen from the camera, the line along which a +cylinder or a sphere turns away, so a model keeps its contour without the +clutter; in Hidden Line mode it makes a proper drawing of round parts. +Wireframe always draws every edge. + +The default projection is **orthographic**, the usual choice for CAD because +parallel lines stay parallel. The menu toggle and *Preferences > 3D View > +Projection* change the same setting, which is remembered. + +### Stereo + +*Preferences > 3D View > Projection* also offers the original editor's +stereo projections: + +| Projection | What it shows | +| --- | --- | +| Stereo | Two perspective views, one per eye, combined as *Stereo mode* says | +| Mono Left Eye · Mono Right Eye | The perspective view of one eye only; clicks pick from that eye | + +The eyes are 5% of the distance to the target apart. Both see the target's +plane in the same place, so what is nearer stands out of the screen and what +is farther sinks behind it. *Stereo mode* chooses how the two views are +combined: + +| Stereo mode | For | +| --- | --- | +| Anaglyph (red-cyan), the default | Red-cyan glasses; red is taken from the left eye's green and blue, which avoids flicker on red objects | +| Row Interlaced · Column Interlaced · Chess Board | Passive 3D displays: even rows, columns or squares for the left eye | +| Side by Side · Over Under | Each eye in its half of the view (left or top for the left eye), for free viewing or displays that take that layout | +| Quad Buffer | Hardware stereo, which this renderer cannot drive: the view shows the anaglyph and says so | + +Screenshots and turntable animations are composed the same way. Picking in +the Stereo projection uses the point between the eyes. The View menu's +*Perspective Projection* toggle goes back to orthographic from any of them. + +## Section view + +![A ball valve cut along Y, with the cut faces filled](../images/section-view.png) + +**View > Section View** (toolbar scissors icon) cuts the model with a plane +to show its inside. The plane starts in the middle of the visible objects, +and a bar at the bottom left of the view controls it: + +| Control | Effect | +| --- | --- | +| X · Y · Z | The axis the plane is perpendicular to; changing it recenters the plane | +| ⇅ | Keep the other side (by default the side towards +X, +Y or +Z is removed) | +| Slider | Position of the plane along the axis, in model units; the range covers the visible objects and any value can be typed | +| Fill | Fill the cut faces of solids with a darker shade of their color | +| ✕ | Remove the section | + +What the plane removes cannot be selected: clicks go through to what is +behind the plane, so faces and edges inside the model can be picked. The +axes, the ground grid and the CQ Inspector overlay (with its plane grid) are +not cut. + +The cut faces are filled wherever the cut goes through material, which +assumes closed solids. An open shell or a face shows no fill, and so do +places where several solids overlap each other an even number of times. +The section is a view setting: it is not saved, and exports always contain +the whole model. + +## Exploded view and isolation + +**View > Exploded View** (toolbar arrows icon) moves the parts of the +shown objects away from their common center, so the parts of an assembly +can be seen and picked one by one. Each part moves along the line from the +center to its own center. The bar at the bottom left of the view sets how +far, from 0% (assembled) to 200% (three times as far from the center as +assembled); the view opens at 50%, and ✕ assembles the parts again. + +![A quadcopter assembly in the exploded view](../images/exploded-view.png) + +Parts are what an assembly is made of: each `add`ed shape (with *Merge +assemblies* too) or each object shown with `show_object`. The solids of a +single shape stay together. + +**View > Isolate Selection** (also in the Objects panel's right-click menu) +shows only the selected objects, with their parts and children, until +**End Isolation**; a bar at the bottom left of the view says what is +isolated and has both buttons. The checkboxes of the Objects panel are left +as they are: isolated objects that were hidden stay hidden, and the objects +hidden by the isolation are grayed in the tree. **Show All** ends the +isolation and makes every object visible again. + +Fit, Zoom to Selection, the section plane and picking all work on what is +shown, where it is shown. The exploded view spreads what is shown: isolate a +sub-assembly to explode it around its own center. Measurements, selectors +and exports always use the real, assembled placement. Isolation follows the +objects by name when the script runs again, and ends by itself when none of +the isolated objects is left. + +## Selection + +Selection works at two levels. + +**Objects.** Clicking an object selects it in the view and in the Objects +panel. The selected object is tinted and the property sheet shows its +details. Export, upload, *Zoom to Selection* and *Remove selected* act on the +selected objects. + +**Topological entities.** The selection control at the right of the toolbar +chooses **Auto**, **Object**, **Face**, **Edge** or **Vertex**. Auto preserves +the usual nearest vertex-before-edge-before-face behavior. The explicit modes +make dense models easier to pick without accidentally selecting another kind. +When a topological mode is active, a click identifies the exact entity: + +* the entity is highlighted on its own; +* the status bar reports it, for example *Selected Face 6 of bracket*; +* the property sheet in the Objects panel shows the id and part, for example + *Face 6 · part 1*, with the area, length, radius and center of the entity; +* the Measurements panel reports exact geometric properties from OCCT. + +![A selected face](../images/topology-selection.png) + +Faces are hit-tested exactly. Edges and vertices only need the pointer within +6 pixels, and a face in front of them hides them. Ids are 1-based and follow +OpenCascade's topology order for the current shape. They are valid only for +that displayed scene entry: rebuilding or remodeling can assign the same id +to a different subshape. They are therefore selection handles, not persistent +topological names. + +### Exact measurements + +Select one face, edge or vertex to see its geometry type, center and the +properties that apply: vertex position, edge length, face area, radius and +diameter, and its **bounding box** (size, minimum and maximum). With no +entity picked, the panel measures the **selected objects** instead: volume, +area, center of mass, the number of solids, faces, edges and vertices, and +their bounding boxes. Several entities or objects also get one bounding +box around all of them. + +Bounding boxes come from the exact geometry. CadQuery's own +`BoundingBox()` uses the triangulation of a shape once it has one, and +every shape on screen has been meshed: for a sphere of radius 5 it reports +about 5.04. Ctrl+click a second entity to add exact minimum distance and closest +points. Two straight edges or two planar faces also report their smaller +angle; a straight edge and planar face report the edge-to-plane angle. + +The viewer's triangles and `f32` coordinates are used only to find what was +clicked. The Measurements panel asks the Python worker to calculate every +displayed value from the corresponding world-space OCCT geometry in double +precision. Curved-edge length and distances are consequently independent of +the display tessellation. Ctrl+click keeps adding entities (up to 64; the +oldest makes room for the newest), and Ctrl+clicking a selected entity +removes it. The relationship is shown when exactly two are selected. + +### Selection to code + +A picked face, edge or vertex also gets a **CadQuery selector**: the +expression that selects exactly the picked entities in the script, such as +`.faces(">Z")`, `.edges("|Z and >Y")` or, for several picked edges, +`.edges("|Z")`. The Measurements panel and the Objects property sheet show +it with **Copy** and **Insert**; *Edit > Copy Selector* and *Edit > Insert +Selector* (Ctrl+Shift+I) do the same, and the *Alternatives* list offers +other selectors for the same entities. + +Selectors are found among direction selectors (`>Z`, `Z[-2]` is the +second highest among those parallel to Z, `>>X[-3]` the third largest X of +all), inclined directions (`+(1,0,1)`) and their combinations with `and`, +`or` and `exc`. Simpler and more meaningful selectors come first. Each one +shown was applied by CadQuery to the object as the script holds it and +selected exactly the picked entities; for an assembly part, that is the +part's own object in its own coordinates. + +When no such selector exists, an index is offered instead, such as +`.faces()[5]`, with a warning: it follows CadQuery's entity order and can +select another entity once the model changes. Selectors are generated for +workplanes and shapes; a picked sketch has none. + +**Copy as code** puts Python on the clipboard that measures the same +entities or objects again, from the script's variables: a selector for +each picked entity (see below), placed as shown for assembly parts, then +one line per value with the measured value as a comment: + +```python +face_1 = plate.faces(">Z").val() +area_1 = face_1.Area() # 40 +bounds_1 = exact_bounds(face_1) # (10, -5, -2, 10, 5, 2) +distance = face_1.distance(edge_2) # 20 +``` + +Before copying, the worker runs that code on a copy of the console's +namespace and compares every value with the measurement; the status bar +says whether it checked out. When an object is not a variable of the +script, the code says `obj` and the status bar explains it. The code needs +the variables of the last run, so it is not available while debugging. + +Hovering an object highlights it before you click. + +## Ground grid and scale bar + +**View > Ground Grid** (on by default) draws a floor under the model: a grid +on the XY plane at the model's lowest point, so the model stands on it. It +stays flat in every view, Front and Right included, and its lines do not +move or change spacing while the view turns or zooms; they change only when +the shown model does. Its spacing follows the size of the model in 1, 2 or +5 steps (5 mm for a 60 mm screw), with a stronger line every five, and its +lines are on round coordinates. The floor reaches the edge of the view, +however far it is zoomed out or panned, and fades away into the distance; +when the view is zoomed out, lines too close together on screen fade out +rather than blur. With nothing shown, it lies on z = 0 around the origin. + +The **scale bar** at the bottom right of the view (**View > Scale Bar**, on +by default) shows a round length (1, 2 or 5 × a power of ten) at the depth +of the point the camera looks at; in perspective, nearer things look larger +than the bar says. With the grid shown it also gives the grid's spacing, +for example *50 mm · grid 10 mm*. + +CadQuery has no units. *Units* in *Preferences > 3D View* says what one model +unit means (millimeters by default, centimeters, meters, inches, or plain +numbers). The Export dialog uses this choice for files that support units; +STL and DXF have no unit metadata. The grid and the scale bar appear in +screenshots and animations too. + +## Appearance + +These options live in *Preferences > 3D View*: + +| Setting | Default | +| --- | --- | +| Background color | dark gray (95, 95, 95) | +| Use gradient, Background color (aux) | off; (30, 30, 30) at the bottom | +| Default object color | gold (255, 215, 0) | +| Show edges, Edge color, Edge width | on; black; 1.5 px | + +Individual objects can be recolored from the script (`show_object` options) +or in the Objects panel. + +### Materials + +Each object can be shaded as a material instead of the plain shading of a +CAD view. The script chooses it with `show_object(..., material="matte +plastic")` (see [Display options](scripting.md#display-options)), and the +**Material** list of the Objects panel's property sheet changes it for one +object (**Reset** returns to the script's). + +| Material | Look | +| --- | --- | +| **Default** | The plain shading of earlier releases, crisp for modeling | +| **Matte plastic** | Soft, without sharp highlights, in the object's color | +| **Glossy plastic** | Sharp highlights of the lights, in the object's color | +| **Brushed steel** | A metal: steel grey (unless the object has a color), blurred reflections | +| **Aluminum** | A brighter, smoother metal | +| **Wood** | Wood-colored, with growth rings around the part's Z axis about 2.5 model units apart and a fine grain along it | + +Materials are shaded by their metalness and roughness. Metals have no +color of their own in the diffuse light: they reflect a soft photo studio +around the model, attached to the camera like the lights, so they keep +their sheen from every side. The lighting settings below apply to +materials too; *Highlights* scales their highlights, and *Ambient light* +the studio they reflect. + +### Lighting + +*Preferences > Rendering* sets the lights: a key light, a softer fill +light, ambient and rim light, the strength and sharpness of highlights, +where the key light comes from, and the exposure and contrast of the lit +faces. The lights move with the camera, as a photographer's lights stay +with the camera around a subject, so every side of the model is lit alike. +Presets give a starting point: **Default** keeps the crisp look of earlier +releases, **Studio** is soft and even, **Bright** helps dark colors, and +**Dramatic** sets one strong light from the side. Edges, points and the +background are not affected. + +## Large models + +Parts outside the view are never drawn, so zooming in on a detail of a big +assembly is fast. The *Large models* preference (*Preferences > 3D View*) +also lets the view draw parts that are small on screen with fewer triangles: + +| Setting | Effect | +| --- | --- | +| Automatic (default) | From 2 million triangles shown | +| Always | At any size of model | +| Off | Every part in full | + +While it is on, a part less than 80 pixels across is drawn from a coarser +copy of its mesh (vertices merged on a grid of 40 cells along its longest +side), and a part less than 6 pixels across also without its edges and +vertices. Selected and hovered parts are always drawn in full, and so are +screenshots and animations. Picking and measurements always use the full +mesh. *Large model: small parts simplified* at the bottom right of the view +says when this is happening. + +When meshing the objects of a render takes more than a moment, a bar at the +bottom left of the view counts the parts meshed (one per shape of an +assembly); ✕ cancels the meshing. The model shown before stays, and the +script's variables are still updated. To stop a script that runs too long, +or the meshing of one huge shape, use **Run > Stop** (Ctrl+Shift+F5), which +interrupts it and, if that is not enough, restarts Python. + +## Mesh quality + +The view displays a triangle mesh of the exact CAD geometry. Two settings +control how fine it is (*Preferences > 3D View*). They apply from the next +run. + +| Setting | Default | Meaning | +| --- | --- | --- | +| Deviation | 0.001 | Maximum distance between mesh and surface, relative to the object size | +| Angular deviation | 0.2 rad | Maximum angle between neighboring mesh facets | + +Smaller values give smoother curves but take more time and memory. Meshes +are cached by content: re-running a script whose parts did not change reuses +the previous meshes, and identical parts in an assembly are meshed only once. + +Export precision is set separately (see [Exporting](exporting.md)). + +## Screenshots + +**Tools > Screenshot…** (toolbar camera icon) opens the screenshot options; +**Save Image…** then asks where to save the PNG. + +| Option | Effect | +| --- | --- | +| View ×1 · ×2 · ×4 | The view's size in pixels, times 1, 2 or 4 | +| Custom | Any width and height; what is shown keeps the view's height, so a wider image shows more on the sides | +| Transparent | Leaves the background out: only the model, with antialiased edges, in a PNG with alpha | + +The image looks like the view at any size: edges and points get wider in +proportion, and so do the dashes and section hatching of the Hidden Line +mode. Images up to 8192 pixels on a side can be saved; when that is more +than the graphics card can draw at once, the image is drawn in tiles. + +### Turntable animations + +The second part of the screenshot window exports one turn of the camera +around the model, starting from the current view, at the size and with the +background chosen above: + +| Option | Default | Meaning | +| --- | --- | --- | +| Frames | 72 | Images per turn (4 to 720) | +| fps | 24 | Frames per second when played, up to 60; 72 frames at 24 fps is a 3-second turn | +| Direction | Counterclockwise | How the model turns, seen from above (about the vertical Z axis through the point the camera looks at) | +| Format | Animated PNG | One looping animated PNG, which browsers and most image viewers play; or one PNG file per frame, `name_0001.png` and on, for video tools such as `ffmpeg -framerate 24 -i name_%04d.png name.mp4` | + +**Export Turntable…** asks for the file name and writes one frame per +frame of the view, so the editor stays responsive. A bar at the bottom left +of the view shows the progress; ✕ (or **Cancel** in the window) stops the +export and deletes what was written. diff --git a/examples/09_square_tube_workbench.py b/examples/09_square_tube_workbench.py new file mode 100644 index 000000000..27ae849ba --- /dev/null +++ b/examples/09_square_tube_workbench.py @@ -0,0 +1,130 @@ +# Example 9: Square Tube Workbench +# +# A simple welded workbench made of 20 x 20 mm square steel tube, with a +# wooden top. Every tube is cut square (90 degrees), which makes it a good +# first welding project. +# +# Frame outside dimensions: 880 x 420 x 720 mm +# Suggested top: 950 x 500 x 25 mm (final height 745 mm) +# +# Each tube is a hollow box: a solid box minus a slightly longer inner box, +# so both ends are open. A helper function places every tube in a +# cq.Assembly with a cq.Location and records its length, so the script can +# print a summary of the tube it uses (see the Log panel). +# +# Cutting plan (five 2000 mm bars): +# Bar 1: 880 + 700 + 380 = 1960 mm +# Bar 2: 880 + 700 + 380 = 1960 mm +# Bar 3: 840 + 700 + 380 = 1920 mm +# Bar 4: 700 + 380 + 380 = 1460 mm +# Bar 5: uncut (2000 mm spare) +# +# Weld beads and the fasteners of the top are not modelled. Do not use this +# design for heavy loads without a proper structural check. +# +# For more examples and the full API reference, see https://cadquery.readthedocs.io/en/latest/ + +import cadquery as cq + +# --- Dimensions (mm) -------------------------------------------------------- +TUBE = 20.0 # outside size of the square tube +WALL = 1.5 # for display only; check your tube +LENGTH = 880.0 # outside length of the top frame +DEPTH = 420.0 # outside depth of the top frame +LEG = 700.0 # from the floor to the underside of the top frame +LOWER_RAIL_HEIGHT = 180.0 # axis of the lower rails above the floor + +TOP_WIDTH = 950.0 +TOP_DEPTH = 500.0 +TOP_THICKNESS = 25.0 + +METAL_COLOR = cq.Color(0.14, 0.16, 0.18) +WOOD_COLOR = cq.Color(0.77, 0.58, 0.39) + +bench = cq.Assembly(name="Workbench - 20x20 square tube") +parts = [] # (name, length) of every tube + + +def add_tube(name, axis, length, center): + """Add a hollow square tube along X, Y or Z, with square-cut ends.""" + outer = [TUBE, TUBE, TUBE] + inner = [TUBE - 2 * WALL] * 3 + index = {"x": 0, "y": 1, "z": 2}[axis] + outer[index] = length + inner[index] = length + 2.0 # opens both ends + tube = cq.Workplane("XY").box(*outer).cut( + cq.Workplane("XY").box(*inner) + ) + bench.add( + tube, + name=name, + color=METAL_COLOR, + loc=cq.Location(cq.Vector(*center)), + ) + parts.append((name, length)) + + +# --- Top frame: 880 x 420 mm ------------------------------------------------ +# Two long rails, with the short side rails welded between them. +# Every frame tube is centred at z = 710. +frame_z = LEG + TUBE / 2 +corner_x = LENGTH / 2 - TUBE / 2 # 430 +corner_y = DEPTH / 2 - TUBE / 2 # 200 + +for side, sy in (("front", 1), ("back", -1)): + add_tube( + "top_frame_" + side, "x", LENGTH, + (0, sy * corner_y, frame_z), + ) + +for side, sx in (("left", -1), ("right", 1)): + add_tube( + "top_frame_" + side, "y", DEPTH - 2 * TUBE, + (sx * corner_x, 0, frame_z), + ) + +# An extra cross member supports the middle of the top. +add_tube( + "center_top_support", "y", DEPTH - 2 * TUBE, + (0, 0, frame_z), +) + +# --- Legs: four 700 mm tubes, welded under the frame corners ---------------- +for sx, side in ((-1, "left"), (1, "right")): + for sy, end in ((-1, "back"), (1, "front")): + add_tube( + "leg_" + side + "_" + end, + "z", LEG, (sx * corner_x, sy * corner_y, LEG / 2), + ) + +# --- Lower bracing: a U, open at the front so knees do not hit a rail ------- +# 180 mm is the height of the rails' CENTRE, not of their top face. +add_tube( + "lower_rail_back", "x", LENGTH - 2 * TUBE, + (0, -corner_y, LOWER_RAIL_HEIGHT), +) +for sx, side in ((-1, "left"), (1, "right")): + add_tube( + "lower_rail_" + side, "y", DEPTH - 2 * TUBE, + (sx * corner_x, 0, LOWER_RAIL_HEIGHT), + ) + +# --- Wooden top, resting on the frame (fasteners not modelled) -------------- +top = cq.Workplane("XY").box(TOP_WIDTH, TOP_DEPTH, TOP_THICKNESS) +bench.add( + top, + name="wooden_top_950x500x25", + color=WOOD_COLOR, + loc=cq.Location(cq.Vector(0, 0, LEG + TUBE + TOP_THICKNESS / 2)), +) + +show_object(bench, name="Compact 20x20 square tube workbench") + +# Optional: export from the script itself (may need extra packages): +# bench.save("square_tube_workbench.step") + +# This summary appears in the Log panel. +total_length = sum(length for _, length in parts) +print("Square tube pieces:", len(parts)) +print("Tube length used:", total_length, "mm") +print("Final height:", LEG + TUBE + TOP_THICKNESS, "mm") diff --git a/icons/back_view.svg b/icons/back_view.svg deleted file mode 100644 index a9425df02..000000000 --- a/icons/back_view.svg +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icons/bottom_view.svg b/icons/bottom_view.svg deleted file mode 100644 index a33c01b36..000000000 --- a/icons/bottom_view.svg +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icons/cadquery_logo_dark.ico b/icons/cadquery_logo_dark.ico deleted file mode 100644 index fc38a6bd4..000000000 Binary files a/icons/cadquery_logo_dark.ico and /dev/null differ diff --git a/icons/front_view.svg b/icons/front_view.svg deleted file mode 100644 index 813b0d739..000000000 --- a/icons/front_view.svg +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icons/isometric_view.svg b/icons/isometric_view.svg deleted file mode 100644 index 135be2226..000000000 --- a/icons/isometric_view.svg +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icons/left_side_view.svg b/icons/left_side_view.svg deleted file mode 100644 index 24615a510..000000000 --- a/icons/left_side_view.svg +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icons/right_side_view.svg b/icons/right_side_view.svg deleted file mode 100644 index 98b61110e..000000000 --- a/icons/right_side_view.svg +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/icons/top_view.svg b/icons/top_view.svg deleted file mode 100644 index d7eb0c301..000000000 --- a/icons/top_view.svg +++ /dev/null @@ -1,131 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/packaging/constructor/construct.yaml b/packaging/constructor/construct.yaml new file mode 100644 index 000000000..7e1fda33c --- /dev/null +++ b/packaging/constructor/construct.yaml @@ -0,0 +1,93 @@ +name: CQ-editor +company: CQ-editor contributors +version: 0.9.0 + +# Constructor produces the native installer for the host platform. +installer_type: sh # [linux] +installer_type: exe # [win] +installer_type: pkg # [osx] + +# Constructor signs the package and its embedded conda bootstrap when CI has +# installed both Developer ID identities. Local builds can omit the identities. +{% if environ.get("CQ_MAC_INSTALLER_IDENTITY") and environ.get("CQ_MAC_APPLICATION_IDENTITY") %} +signing_identity_name: {{ environ["CQ_MAC_INSTALLER_IDENTITY"] | tojson }} # [osx] +notarization_identity_name: {{ environ["CQ_MAC_APPLICATION_IDENTITY"] | tojson }} # [osx] +{% endif %} + +icon_image: ../../assets/icons/cadquery_logo_dark.ico +license_file: ../../LICENSE +register_python: false +initialize_conda: false +keep_pkgs: false +write_condarc: false +menu_packages: [] + +# A private, relocatable runtime: no pre-existing Python, conda or CadQuery is +# required on the user's computer. The generated lockfile records every +# resolved transitive package for each released installer. +channels: + - https://conda.anaconda.org/conda-forge + +specs: + - python=3.12.15 + - cadquery=2.8.0 + - ocp=7.9.3.1 + - jedi=0.19.2 + - menuinst=2.5.2 + - pip + - nomkl + +# OCP and OCCT require the `vtk` metapackage, which also brings what compiling +# C++ against VTK needs: Boost, Eigen and TBB headers, CMake files and import +# libraries. Nothing installed links Boost's DLLs and the rest is not code that +# runs, yet Boost's headers alone are about 16,000 files and 195 MB. The +# runtime libraries (tbb, liblzma, libexpat) stay. Constructor stops when a +# name is missing from the solved environment, so a changed solution fails the +# build instead of shipping something else. +exclude: + - libboost-devel + - libboost-headers + - libboost + - eigen + - tbb-devel + - liblzma-devel + +default_prefix: ${HOME}/.local/share/CQ-editor # [linux] +default_prefix: '%LOCALAPPDATA%\Programs\CQ-editor' # [win] +default_prefix_domain_user: '%LOCALAPPDATA%\Programs\CQ-editor' # [win] +default_prefix_all_users: '%PROGRAMFILES%\CQ-editor' # [win] +# Constructor's PKG bootstrap cannot relocate its embedded conda packages when +# the installation prefix contains spaces. Keep the private runtime in the +# user's Library while the application launcher remains in ~/Applications. +default_location_pkg: Library # [osx] +pkg_name: CQ-editor # [osx] +progress_notifications: true # [osx] +welcome_image: "" # [osx] + +welcome_text: >- + CQ-editor is a CadQuery code editor and 3D viewer. This installer includes + its own tested Python and CadQuery runtime, so no separate setup is needed. +conclusion_text: |- + CQ-editor 0.9.0 is ready + Launch CQ-editor from the application menu. Python files can also be opened + with CQ-editor on Windows and Linux. + +post_install: post_install.sh # [unix] +post_install: post_install.bat # [win] +pre_uninstall: pre_uninstall.bat # [win] +uninstall_name: CQ-editor 0.9.0 # [win] +uninstall_with_conda_exe: true # [win] + +extra_files: + - ../../target/release/cq-editor: bin/cq-editor # [unix] + - ../../target/release/cq-editor.exe: cq-editor.exe # [win] + - menu/cq-editor_menu.json: Menu/cq-editor_menu.json + - ../../assets/icons/cadquery_logo_dark.svg: share/icons/cq-editor.svg # [linux] + - ../../assets/icons/cadquery_logo_dark.ico: share/icons/cq-editor.ico # [win] + - generated/cq-editor.icns: share/icons/cq-editor.icns # [osx] + +build_outputs: + - info.json + - licenses + - lockfile + - pkgs_list diff --git a/packaging/constructor/menu/cq-editor_menu.json b/packaging/constructor/menu/cq-editor_menu.json new file mode 100644 index 000000000..0b2db2b96 --- /dev/null +++ b/packaging/constructor/menu/cq-editor_menu.json @@ -0,0 +1,66 @@ +{ + "$schema": "https://schemas.conda.org/menuinst-1-1-1.schema.json", + "menu_name": "CQ-editor", + "menu_items": [ + { + "name": "CQ-editor", + "description": "Edit and render parametric CadQuery models", + "activate": false, + "terminal": false, + "command": [ + "{{ PREFIX }}/bin/cq-editor" + ], + "platforms": { + "linux": { + "command": [ + "{{ PREFIX }}/bin/cq-editor", + "%F" + ], + "icon": "{{ PREFIX }}/share/icons/cq-editor.svg", + "Categories": [ + "Development", + "Graphics", + "Engineering" + ], + "GenericName": "CadQuery editor", + "Keywords": [ + "CAD", + "CadQuery", + "Python", + "3D" + ], + "MimeType": [ + "text/x-python" + ], + "StartupNotify": true, + "StartupWMClass": "cq-editor", + "TryExec": "{{ PREFIX }}/bin/cq-editor" + }, + "osx": { + "command": [ + "{{ PREFIX }}/bin/cq-editor" + ], + "icon": "{{ PREFIX }}/share/icons/cq-editor.icns", + "CFBundleDisplayName": "CQ-editor", + "CFBundleIdentifier": "io.github.igors93.cq-editor", + "CFBundleName": "CQ-editor", + "CFBundleVersion": "0.9.0", + "LSApplicationCategoryType": "public.app-category.developer-tools", + "LSMinimumSystemVersion": "12.0", + "NSSupportsAutomaticGraphicsSwitching": true + }, + "win": { + "command": [ + "{{ PREFIX }}/cq-editor.exe" + ], + "icon": "{{ PREFIX }}/share/icons/cq-editor.ico", + "desktop": false, + "file_extensions": [ + ".py" + ], + "app_user_model_id": "CQEditor.CQEditor" + } + } + } + ] +} diff --git a/packaging/constructor/post_install.bat b/packaging/constructor/post_install.bat new file mode 100644 index 000000000..df01f6060 --- /dev/null +++ b/packaging/constructor/post_install.bat @@ -0,0 +1,9 @@ +@echo off +setlocal + +if not exist "%PREFIX%\Scripts\menuinst.exe" exit /b 1 + +rem Refresh the Start menu entry and the optional Python file association. +"%PREFIX%\Scripts\menuinst.exe" --prefix "%PREFIX%" --remove cq-editor_menu.json >nul 2>&1 +"%PREFIX%\Scripts\menuinst.exe" --prefix "%PREFIX%" --install cq-editor_menu.json +exit /b %ERRORLEVEL% diff --git a/packaging/constructor/post_install.sh b/packaging/constructor/post_install.sh new file mode 100644 index 000000000..e8f3d3258 --- /dev/null +++ b/packaging/constructor/post_install.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu + +chmod 755 "$PREFIX/bin/cq-editor" + +# Reinstalling the shortcut is idempotent and also refreshes stale launchers +# from an older CQ-editor installation. +"$PREFIX/bin/menuinst" --prefix "$PREFIX" --remove cq-editor_menu.json >/dev/null 2>&1 || true +"$PREFIX/bin/menuinst" --prefix "$PREFIX" --install cq-editor_menu.json diff --git a/packaging/constructor/pre_uninstall.bat b/packaging/constructor/pre_uninstall.bat new file mode 100644 index 000000000..346750453 --- /dev/null +++ b/packaging/constructor/pre_uninstall.bat @@ -0,0 +1,7 @@ +@echo off +setlocal + +if exist "%PREFIX%\Scripts\menuinst.exe" ( + "%PREFIX%\Scripts\menuinst.exe" --prefix "%PREFIX%" --remove cq-editor_menu.json +) +exit /b 0 diff --git a/packaging/constructor/prepare_macos_icon.py b/packaging/constructor/prepare_macos_icon.py new file mode 100644 index 000000000..b49e6bd57 --- /dev/null +++ b/packaging/constructor/prepare_macos_icon.py @@ -0,0 +1,23 @@ +"""Create the iconset consumed by macOS' native ``iconutil`` command.""" + +from pathlib import Path +import sys + +from PIL import Image + + +def main() -> None: + if len(sys.argv) != 3: + raise SystemExit("usage: prepare_macos_icon.py SOURCE.ico OUTPUT.iconset") + source, output = map(Path, sys.argv[1:]) + output.mkdir(parents=True, exist_ok=True) + image = Image.open(source).convert("RGBA") + for points in (16, 32, 128, 256, 512): + for scale in (1, 2): + pixels = points * scale + name = f"icon_{points}x{points}{'@2x' if scale == 2 else ''}.png" + image.resize((pixels, pixels), Image.Resampling.LANCZOS).save(output / name) + + +if __name__ == "__main__": + main() diff --git a/packaging/notarize_macos.sh b/packaging/notarize_macos.sh new file mode 100644 index 000000000..45294796c --- /dev/null +++ b/packaging/notarize_macos.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail + +for name in CQ_MAC_NOTARY_KEY_BASE64 CQ_MAC_NOTARY_KEY_ID CQ_MAC_NOTARY_ISSUER_ID; do + if [[ -z "${!name:-}" ]]; then + printf 'Missing notarization credential: %s\n' "$name" >&2 + exit 1 + fi +done + +shopt -s nullglob +packages=(dist/*.pkg) +if (( ${#packages[@]} != 1 )); then + echo 'Expected exactly one macOS installer package.' >&2 + exit 1 +fi +package="${packages[0]}" +key="$RUNNER_TEMP/cq-editor-notary-key.p8" +result="$RUNNER_TEMP/cq-editor-notarization.json" +trap 'rm -f "$key" "$result"' EXIT +printf '%s' "$CQ_MAC_NOTARY_KEY_BASE64" | base64 -D > "$key" +chmod 600 "$key" + +pkgutil --check-signature "$package" +xcrun notarytool submit "$package" --key "$key" --key-id "$CQ_MAC_NOTARY_KEY_ID" --issuer "$CQ_MAC_NOTARY_ISSUER_ID" --wait --timeout 45m --output-format json > "$result" +status="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["status"])' "$result")" +if [[ "$status" != Accepted ]]; then + submission="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["id"])' "$result")" + xcrun notarytool log "$submission" --key "$key" --key-id "$CQ_MAC_NOTARY_KEY_ID" --issuer "$CQ_MAC_NOTARY_ISSUER_ID" || true + printf 'Apple notarization failed with status: %s\n' "$status" >&2 + exit 1 +fi +xcrun stapler staple "$package" +xcrun stapler validate "$package" +pkgutil --check-signature "$package" +spctl --assess --type install --verbose=2 "$package" diff --git a/packaging/prepare_macos_signing.sh b/packaging/prepare_macos_signing.sh new file mode 100644 index 000000000..aeb4c8d48 --- /dev/null +++ b/packaging/prepare_macos_signing.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +set -euo pipefail + +for name in CQ_MAC_APP_CERT_BASE64 CQ_MAC_APP_CERT_PASSWORD CQ_MAC_INSTALLER_CERT_BASE64 CQ_MAC_INSTALLER_CERT_PASSWORD CQ_MAC_APPLICATION_IDENTITY CQ_MAC_INSTALLER_IDENTITY; do + if [[ -z "${!name:-}" ]]; then + printf 'Missing macOS signing credential: %s\n' "$name" >&2 + exit 1 + fi +done + +keychain="$RUNNER_TEMP/cq-editor-signing.keychain-db" +app_cert="$RUNNER_TEMP/cq-editor-application.p12" +installer_cert="$RUNNER_TEMP/cq-editor-installer.p12" +password="$(openssl rand -hex 24)" +trap 'rm -f "$app_cert" "$installer_cert"' EXIT + +printf '%s' "$CQ_MAC_APP_CERT_BASE64" | base64 -D > "$app_cert" +printf '%s' "$CQ_MAC_INSTALLER_CERT_BASE64" | base64 -D > "$installer_cert" +security create-keychain -p "$password" "$keychain" +security set-keychain-settings -lut 21600 "$keychain" +security unlock-keychain -p "$password" "$keychain" +security import "$app_cert" -k "$keychain" -P "$CQ_MAC_APP_CERT_PASSWORD" -T /usr/bin/codesign +security import "$installer_cert" -k "$keychain" -P "$CQ_MAC_INSTALLER_CERT_PASSWORD" -T /usr/bin/productsign +security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$password" "$keychain" +security list-keychains -d user -s "$keychain" "$HOME/Library/Keychains/login.keychain-db" + +security find-identity -v -p codesigning "$keychain" | grep -F -- "$CQ_MAC_APPLICATION_IDENTITY" >/dev/null +security find-identity -v "$keychain" | grep -F -- "$CQ_MAC_INSTALLER_IDENTITY" >/dev/null +printf 'CQ_MAC_KEYCHAIN=%s\n' "$keychain" >> "$GITHUB_ENV" diff --git a/packaging/sign_windows.ps1 b/packaging/sign_windows.ps1 new file mode 100644 index 000000000..173926136 --- /dev/null +++ b/packaging/sign_windows.ps1 @@ -0,0 +1,33 @@ +param( + [Parameter(Mandatory = $true)] + [ValidateScript({ Test-Path -LiteralPath $_ -PathType Leaf })] + [string]$Path +) + +$ErrorActionPreference = 'Stop' +if (-not $env:CQ_WINDOWS_PFX_BASE64 -or -not $env:CQ_WINDOWS_PFX_PASSWORD) { + throw 'Windows signing requires CQ_WINDOWS_PFX_BASE64 and CQ_WINDOWS_PFX_PASSWORD.' +} + +$sdk = Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\bin' +$signTool = Get-ChildItem -LiteralPath $sdk -Filter signtool.exe -Recurse -File | + Where-Object { $_.DirectoryName -match '[\\/]x64$' } | + Sort-Object FullName -Descending | + Select-Object -First 1 +if (-not $signTool) { throw 'The Windows SDK x64 signtool.exe was not found.' } + +$certificate = Join-Path $env:RUNNER_TEMP ([guid]::NewGuid().ToString() + '.pfx') +try { + [IO.File]::WriteAllBytes($certificate, [Convert]::FromBase64String($env:CQ_WINDOWS_PFX_BASE64)) + & $signTool.FullName sign /f $certificate /p $env:CQ_WINDOWS_PFX_PASSWORD /fd SHA256 /tr https://timestamp.digicert.com /td SHA256 $Path + if ($LASTEXITCODE -ne 0) { throw "Authenticode signing failed for $Path." } + & $signTool.FullName verify /pa /all /v /tw $Path + if ($LASTEXITCODE -ne 0) { throw "Authenticode verification failed for $Path." } + $signature = Get-AuthenticodeSignature -LiteralPath $Path + if ($signature.Status -ne 'Valid' -or -not $signature.TimeStamperCertificate) { + throw "The signature or RFC 3161 timestamp is invalid for $Path." + } +} +finally { + Remove-Item -LiteralPath $certificate -Force -ErrorAction SilentlyContinue +} diff --git a/pyinstaller.spec b/pyinstaller.spec deleted file mode 100644 index 6e013939f..000000000 --- a/pyinstaller.spec +++ /dev/null @@ -1,103 +0,0 @@ -# -*- mode: python -*- - -import sys -from pathlib import Path -import parso -from PyInstaller.utils.hooks import collect_data_files, collect_dynamic_libs, collect_all - -block_cipher = None - -parso_grammar = (Path(parso.__file__).parent / 'python').glob('grammar*') -casadi_datas, casadi_binaries, casadi_hiddenimports = collect_all('casadi') - -a = Analysis( - ['run.py'], - pathex=['.'], - binaries=[ - *casadi_binaries, - ], - datas=[ - ('cq_editor/icons_res.py', 'cq_editor'), - ('examples', 'examples'), - *[(str(p), 'parso/python') for p in parso_grammar], - *collect_data_files('debugpy'), - *casadi_datas, - ], - hiddenimports=[ - 'ipykernel.datapub', - 'pygments.styles.default', - 'qtconsole.client', - 'OCP', - 'cadquery.func', - 'cadquery.units', - *casadi_hiddenimports, - ], - hookspath=[], - runtime_hooks=[ - 'pyinstaller/pyi_rth_fontconfig.py', - 'pyinstaller/pyi_rth_qt_xcb.py', - 'pyinstaller/pyi_rth_casadi.py', - ], - excludes=['_tkinter', 'spyder'], - win_no_prefer_redirects=False, - win_private_assemblies=False, - cipher=block_cipher, - noarchive=False, -) - -# Exclude unmangled system X11/GL libraries that would shadow the system stack -# via PyInstaller's LD_LIBRARY_PATH. Manylinux-vendored copies with a hash in -# their name (e.g. libXcursor-1a09904e.so.1.0.2) are safe to keep because -# their SONAME is also mangled and won't conflict with system libraries. -if sys.platform == 'linux': - import os, re - _HASH_RE = re.compile(r'-[0-9a-f]{8}\.') - _SYSTEM_PREFIXES = ( - # OpenGL / EGL - 'libGL', 'libEGL', 'libGLX', 'libGLdispatch', 'libGLES', - 'libdrm', 'libgbm', - # X11 / XCB - 'libX11', 'libXau', 'libxcb', 'libXcursor', 'libXext', - 'libXfixes', 'libXi', 'libXrender', 'libXss', 'libXtst', - # C++ / GCC runtime — must come from the user's system - 'libstdc++', 'libgcc_s', - # GLib / D-Bus — tightly coupled to the rest of the system - 'libglib-2.0', 'libgobject-2.0', 'libgio-2.0', 'libgmodule-2.0', - 'libdbus-1', - # Misc system libs - 'libbsd', - ) - def _is_conflicting(name): - bn = os.path.basename(name) - return bn.startswith(_SYSTEM_PREFIXES) and not _HASH_RE.search(bn) - a.binaries = TOC([x for x in a.binaries if not _is_conflicting(x[0])]) - -pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) - -if sys.platform != 'darwin': - splash = Splash( - 'pyinstaller/splash_screen.png', - binaries=a.binaries, - datas=a.datas, - ) - splash_scripts = [splash, splash.binaries] -else: - splash_scripts = [] - -exe = EXE( - pyz, - a.scripts, - *splash_scripts, - a.binaries, - a.zipfiles, - a.datas, - name='CQ-editor', - debug=False, - bootloader_ignore_signals=False, - strip=False, - upx=True, - upx_exclude=[], - console=False, - icon='icons/cadquery_logo_dark.ico', -) - diff --git a/pyinstaller/pyi_rth_casadi.py b/pyinstaller/pyi_rth_casadi.py deleted file mode 100644 index a87c03ea7..000000000 --- a/pyinstaller/pyi_rth_casadi.py +++ /dev/null @@ -1,10 +0,0 @@ -import os -import sys - -# Python 3.8+ uses a restricted DLL search path on Windows. PyInstaller adds -# _MEIPASS to the search path but not subdirectories. casadi's companion DLLs -# live in _MEIPASS/casadi/, so register that directory explicitly. -if sys.platform == "win32": - casadi_dir = os.path.join(sys._MEIPASS, "casadi") - if os.path.isdir(casadi_dir): - os.add_dll_directory(casadi_dir) diff --git a/pyinstaller/pyi_rth_fontconfig.py b/pyinstaller/pyi_rth_fontconfig.py deleted file mode 100644 index 93326e22c..000000000 --- a/pyinstaller/pyi_rth_fontconfig.py +++ /dev/null @@ -1,6 +0,0 @@ -import os -import sys - -if sys.platform.startswith("linux"): - os.environ["FONTCONFIG_FILE"] = "/etc/fonts/fonts.conf" - os.environ["FONTCONFIG_PATH"] = "/etc/fonts/" diff --git a/pyinstaller/pyi_rth_occ.py b/pyinstaller/pyi_rth_occ.py deleted file mode 100644 index 9dc0932c7..000000000 --- a/pyinstaller/pyi_rth_occ.py +++ /dev/null @@ -1,7 +0,0 @@ -from os import environ as env - -env["CASROOT"] = "opencascade" - -env["CSF_ShadersDirectory"] = "opencascade/src/Shaders" -env["CSF_UnitsLexicon"] = "opencascade/src/UnitsAPI/Lexi_Expr.dat" -env["CSF_UnitsDefinition"] = "opencascade/src/UnitsAPI/Units.dat" diff --git a/pyinstaller/pyi_rth_qt_xcb.py b/pyinstaller/pyi_rth_qt_xcb.py deleted file mode 100644 index 0d557c21c..000000000 --- a/pyinstaller/pyi_rth_qt_xcb.py +++ /dev/null @@ -1,10 +0,0 @@ -import os -import sys - -# Prevent Qt's XCB plugin from initializing GLX before OCCT does. -# When Qt's bundled libqxcb.so fails to find a matching GLX FBConfig, -# it can leave the display connection in a state that breaks OCCT's own -# GLX initialization. OCCT creates its own GL context via Xw_Window -# directly, so Qt does not need GLX integration. -if sys.platform.startswith("linux"): - os.environ["QT_XCB_GL_INTEGRATION"] = "none" diff --git a/pyinstaller/splash_screen.png b/pyinstaller/splash_screen.png deleted file mode 100644 index 9bc8cd3a8..000000000 Binary files a/pyinstaller/splash_screen.png and /dev/null differ diff --git a/pyinstaller/splash_screen.svg b/pyinstaller/splash_screen.svg deleted file mode 100644 index d584205dc..000000000 --- a/pyinstaller/splash_screen.svg +++ /dev/null @@ -1,77 +0,0 @@ - - - -CQ-editorCadQuery IDE diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index dbf3f5c9a..000000000 --- a/pyproject.toml +++ /dev/null @@ -1,54 +0,0 @@ -[build-system] -requires = ["setuptools"] -build-backend = "setuptools.build_meta" - -[project] -name = "CQ-editor" -version = "0.8.dev0" -dependencies = [ - "cadquery", - "PyQt5", - "pyqtgraph", - "qtawesome==1.4.0", - "path", - "logbook", - "requests", - "qtconsole>=5.5.1,<5.7.0", - "packaging" -] -requires-python = ">=3.10,<=3.14" -authors = [ - { name="CadQuery Developers" } -] -maintainers = [ - { name="CadQuery Developers" } -] -description = "Cross-platform CadQuery 3D viewer and optional editor built on PyQt" -readme = "README.md" -license = {file = "LICENSE"} -keywords = ["cadquery", "CAD", "engineering", "design"] -classifiers = [ - "Development Status :: 4 - Beta", - "Programming Language :: Python" -] - -[project.scripts] -CQ-editor = "cq_editor.cqe_run:main" -cq-editor = "cq_editor.cqe_run:main" - -[project.optional-dependencies] -test = [ - "pytest", - "pluggy", - "pytest-qt", - "pytest-mock", - "pytest-repeat", - "pyvirtualdisplay" -] -dev = [ - "black", -] - -[project.urls] -Repository = "https://github.com/CadQuery/CQ-editor.git" -"Bug Tracker" = "https://github.com/CadQuery/CQ-editor/issues" diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index 5720d3725..000000000 --- a/pytest.ini +++ /dev/null @@ -1,3 +0,0 @@ -[pytest] -xvfb_args=-ac +extension GLX +render -log_level=DEBUG \ No newline at end of file diff --git a/run.py b/run.py deleted file mode 100644 index a8bd2bafc..000000000 --- a/run.py +++ /dev/null @@ -1,15 +0,0 @@ -import sys -import faulthandler - -# PyInstaller with console=False sets sys.stdout/stderr to None on Windows -if sys.stdout is None: - sys.stdout = open("nul", "w") -if sys.stderr is None: - sys.stderr = open("nul", "w") - -faulthandler.enable() - -from cq_editor.cqe_run import main - -if __name__ == "__main__": - main() diff --git a/runtests_locally.sh b/runtests_locally.sh deleted file mode 100644 index 9364cb2f0..000000000 --- a/runtests_locally.sh +++ /dev/null @@ -1 +0,0 @@ -python -m pytest --no-xvfb -s diff --git a/screenshots/navigation_cube.png b/screenshots/navigation_cube.png deleted file mode 100644 index 6795f397b..000000000 Binary files a/screenshots/navigation_cube.png and /dev/null differ diff --git a/screenshots/screenshot1.png b/screenshots/screenshot1.png deleted file mode 100644 index 413d5d49e..000000000 Binary files a/screenshots/screenshot1.png and /dev/null differ diff --git a/screenshots/screenshot2.png b/screenshots/screenshot2.png deleted file mode 100644 index 21b0091e1..000000000 Binary files a/screenshots/screenshot2.png and /dev/null differ diff --git a/screenshots/screenshot3.png b/screenshots/screenshot3.png deleted file mode 100644 index ea8a15b15..000000000 Binary files a/screenshots/screenshot3.png and /dev/null differ diff --git a/screenshots/screenshot4.png b/screenshots/screenshot4.png deleted file mode 100644 index ff933686e..000000000 Binary files a/screenshots/screenshot4.png and /dev/null differ diff --git a/setup.py b/setup.py deleted file mode 100644 index 1141c444c..000000000 --- a/setup.py +++ /dev/null @@ -1,32 +0,0 @@ -import codecs -import os.path - -from setuptools import setup, find_packages - - -def read(rel_path): - here = os.path.abspath(os.path.dirname(__file__)) - with codecs.open(os.path.join(here, rel_path), "r") as fp: - return fp.read() - - -def get_version(rel_path): - for line in read(rel_path).splitlines(): - if line.startswith("__version__"): - delim = '"' if '"' in line else "'" - return line.split(delim)[1] - else: - raise RuntimeError("Unable to find version string.") - - -setup( - name="CQ-editor", - version=get_version("cq_editor/_version.py"), - packages=find_packages(), - entry_points={ - "gui_scripts": [ - "cq-editor = cq_editor.__main__:main", - "CQ-editor = cq_editor.__main__:main", - ] - }, -) diff --git a/src/app/documents.rs b/src/app/documents.rs new file mode 100644 index 000000000..138d6b3b4 --- /dev/null +++ b/src/app/documents.rs @@ -0,0 +1,602 @@ +//! The documents: opening, saving, reloading after external changes, +//! crash-recovery checkpoints and local history. + +use std::path::Path; +use std::time::Instant; + +use egui::ViewportCommand; + +use super::{AppState, StatusKind}; +use crate::dialogs::{ + ExternalChange, ExternalChangeChoice, HistoryDialog, Intent, RecoverySession, UnsavedChoice, +}; +use crate::document::{DiskVersion, Document, Encoding, is_not_utf8}; +use crate::logging::{self, Level}; +use crate::recovery::{CHECKPOINT_INTERVAL, RecoverySnapshot}; + +impl AppState { + /// Performs `intent`, or asks first when it would close documents with + /// unsaved changes. + pub(super) fn guard_unsaved(&mut self, intent: Intent) { + let unsaved = self.unsaved_of(&intent); + match unsaved.first() { + None => self.perform(intent), + Some(&first) => { + // A single file is shown while it is asked about. + if unsaved.len() == 1 { + self.activate(first); + } + self.dialogs.unsaved = Some(intent); + } + } + } + + pub fn resolve_unsaved(&mut self, intent: Intent, choice: UnsavedChoice) { + match choice { + UnsavedChoice::Save => { + let unsaved = self.unsaved_of(&intent); + if self.save_documents(&unsaved) { + self.perform(intent); + } + } + UnsavedChoice::Discard => self.perform(intent), + UnsavedChoice::Cancel => {} + } + } + + pub fn resolve_recovery_session(&mut self, session: RecoverySession, restore: bool) { + if let Err(error) = self.recovery.clear_session() { + self.dialogs.error( + "Cannot update recovery state", + format!("Your recovery was kept on disk.\n\n{error}"), + ); + self.dialogs.recovery_session = Some(session); + return; + } + if restore { + let names: Vec = session + .documents + .iter() + .map(RecoverySnapshot::display_name) + .collect(); + for snapshot in session.documents { + self.restore_recovered(snapshot.into_document()); + } + self.checkpoint_recovery(); + self.set_status( + StatusKind::Success, + format!("Recovered unsaved work for {}", names.join(", ")), + ); + } else { + self.set_status( + StatusKind::Info, + "Discarded the interrupted recovery session", + ); + } + } + + /// Puts a recovered buffer back in the tab of its file, or in a new + /// tab. + fn restore_recovered(&mut self, document: Document) { + match document.path().and_then(|path| self.find_open(path)) { + Some(open) => { + self.activate(open); + self.replace_document(document); + } + None => self.add_tab(document), + } + } + + pub fn restore_history(&mut self, generation: u64, snapshot: RecoverySnapshot) { + if !self.activate(generation) { + return; + } + if self.document.path() != snapshot.path.as_deref() { + self.dialogs.error( + "Cannot restore local history", + "This history belongs to another document.", + ); + return; + } + self.checkpoint_recovery(); + let name = snapshot.display_name(); + // Another version of the same file, like a reload: the model stays. + self.replace_document(snapshot.into_document()); + self.checkpoint_recovery(); + self.set_status( + StatusKind::Success, + format!("Restored a local history version of {name}"), + ); + } + + /// Carries out the choice about a conflict on the document it concerns, + /// which is shown for that, whichever tab was shown meanwhile. A + /// document closed or moved since is left alone. + pub fn resolve_external_change( + &mut self, + change: ExternalChange, + choice: ExternalChangeChoice, + ) { + if !self.activate(change.document) || self.document.path() != Some(change.path.as_path()) { + self.rerun_after_external_change(change.rerun_after_resolution); + return; + } + match choice { + ExternalChangeChoice::KeepLocal => { + self.keep_local_version(&change); + if change.on_save { + self.save(); + } else { + self.set_status( + StatusKind::Info, + format!("Kept unsaved changes to {}", self.document.display_name()), + ); + } + self.rerun_after_external_change(change.rerun_after_resolution); + } + ExternalChangeChoice::Cancel => { + self.set_status( + StatusKind::Info, + format!("{} was not saved", self.document.display_name()), + ); + self.rerun_after_external_change(change.rerun_after_resolution); + } + ExternalChangeChoice::Reload => self.reload_external_change(change), + ExternalChangeChoice::SaveCopy => self.save_copy_then_reload(change), + } + } + + /// The user keeps the buffer over the version another program wrote: + /// that version goes to the local history, since the next save replaces + /// it, and becomes the baseline the save no longer asks about. + fn keep_local_version(&mut self, change: &ExternalChange) { + if let Err(error) = self.recovery.archive_path(&change.path) { + log::warn!( + "Cannot keep the disk version of {} in local history: {error}", + change.path.display() + ); + } + self.document.adopt_disk_baseline(&change.disk); + } + + /// Saving would replace a version of the file the editor has not seen: + /// the user is asked first, with the dialog of the file watcher. + fn ask_before_overwriting(&mut self, disk: DiskVersion) { + let Some(path) = self.document.path().map(Path::to_path_buf) else { + return; + }; + let change = ExternalChange { + document: self.document_generation, + path, + disk, + show_comparison: false, + rerun_after_resolution: false, + on_save: true, + }; + if self.dialogs.external_change.is_none() { + self.dialogs.external_change = Some(change); + } else { + self.dialogs.external_queue.insert(0, change); + } + self.set_status( + StatusKind::Warning, + format!( + "{} was changed by another program; nothing was saved yet", + self.document.display_name() + ), + ); + } + + fn perform(&mut self, intent: Intent) { + match intent { + Intent::Close(documents) => { + for generation in documents { + self.close_now(generation); + } + } + Intent::Quit => { + self.clear_recovery_session(); + self.allow_close = true; + self.ctx.send_viewport_cmd(ViewportCommand::Close); + } + } + } + + pub(super) fn new_file(&mut self) { + self.add_tab(Document::untitled("")); + } + + /// Asks for scripts and opens each in a tab. + pub(super) fn choose_files(&mut self) { + let mut dialog = rfd::FileDialog::new().add_filter("Python script", &["py"]); + let folder = self + .document + .path() + .and_then(Path::parent) + .map(Path::to_path_buf) + .or_else(|| self.project.as_ref().map(|p| p.root().to_path_buf())); + if let Some(folder) = folder { + dialog = dialog.set_directory(folder); + } + for path in dialog.pick_files().unwrap_or_default() { + self.open_path(&path); + } + } + + pub(super) fn open_example(&mut self, index: usize) { + if let Some(example) = self.examples.get(index) { + let document = Document::example(&example.title, example.source); + self.add_tab(document); + self.set_status( + StatusKind::Info, + "Examples are read-only; saving asks for a new location", + ); + } + } + + /// Shows the file at `path`: its tab when it is open, else a new one. + pub(super) fn open_path(&mut self, path: &Path) { + match self.find_open(path) { + Some(open) => { + self.activate(open); + } + None => self.open_path_with(path, Encoding::Utf8), + } + } + + /// Shows the file at `path` with the caret on `line`, from the + /// traceback of a module the script imported. + pub(super) fn open_path_at(&mut self, path: &Path, line: usize) { + self.open_path(path); + if self.find_open(path) == Some(self.document_generation) { + self.editor.go_to_line(&self.document.text, line); + } + } + + /// Opens a file in a new tab; one that is not UTF-8 is opened after + /// the user agreed to read it as `encoding` (and to convert it on save). + pub fn open_path_with(&mut self, path: &Path, encoding: Encoding) { + match Document::open_with(path, encoding) { + Ok(document) => { + self.add_tab(document); + self.settings.add_recent_file(path); + self.settings.last_file = Some(path.to_path_buf()); + if let Some(project) = &mut self.project { + project.reveal(path); + } + let status = match encoding { + Encoding::Utf8 => format!("Opened {}", path.display()), + _ => format!( + "Opened {} as {}; saving converts it to UTF-8", + path.display(), + encoding.label() + ), + }; + self.set_status(StatusKind::Info, status); + } + Err(err) if is_not_utf8(&err) => { + self.dialogs.legacy_encoding = Some(path.to_path_buf()); + } + Err(err) => self + .dialogs + .error("Cannot open file", format!("{}\n\n{err}", path.display())), + } + } + + /// Replaces the shown document with another version of the same file + /// (recovered, or from the local history), like a reload: the model + /// stays, and the editor starts afresh. + fn replace_document(&mut self, document: Document) { + self.remember_breakpoints(); + self.remember_views(); + self.document = document; + self.dialogs.external_change = None; + self.dialogs.history = None; + self.next_recovery = Instant::now() + CHECKPOINT_INTERVAL; + self.editor.reset(); + self.restore_breakpoints(); + self.restore_views(); + if self.traceback_document == Some(self.document_generation) { + self.traceback = None; + } + } + + /// Returns whether the document ended up saved. A file that another + /// program changed since it was loaded or saved is not replaced without + /// asking. + pub(super) fn save(&mut self) -> bool { + self.checkpoint_recovery(); + match self.document.unseen_disk_version() { + Ok(None) => {} + Ok(Some(disk)) => { + self.ask_before_overwriting(disk); + return false; + } + Err(error) => { + let path = self + .document + .path() + .map_or_else(String::new, |path| path.display().to_string()); + self.dialogs.error( + "Cannot save", + format!( + "{path} could not be read to check it before saving:\n{error}\n\n\ + Nothing was saved. Use Save As to save your edits elsewhere." + ), + ); + return false; + } + } + match self.document.save() { + Ok(true) => { + self.after_save(); + true + } + Ok(false) => { + if self.document.example_title().is_some() { + self.set_status( + StatusKind::Info, + "Examples are read-only — choose a new location to save your changes", + ); + } + self.save_as() + } + Err(err) => { + self.dialogs.error("Cannot save", err.to_string()); + false + } + } + } + + pub(super) fn save_as(&mut self) -> bool { + self.checkpoint_recovery(); + let mut dialog = rfd::FileDialog::new() + .add_filter("Python script", &["py"]) + .set_file_name(self.document.path().and_then(Path::file_name).map_or_else( + || "script.py".to_owned(), + |name| name.to_string_lossy().into_owned(), + )); + if let Some(dir) = self.document.path().and_then(Path::parent) { + dialog = dialog.set_directory(dir); + } + let Some(mut path) = dialog.save_file() else { + return false; + }; + if path.extension().is_none() { + path.set_extension("py"); + } + if let Err(error) = self.recovery.archive_path(&path) { + log::warn!("Cannot archive the previous Save As target: {error}"); + } + match self.document.save_as(&path) { + Ok(()) => { + self.after_save(); + true + } + Err(err) => { + self.dialogs + .error("Cannot save", format!("{}\n\n{err}", path.display())); + false + } + } + } + + fn save_copy_then_reload(&mut self, change: ExternalChange) { + let stem = change + .path + .file_stem() + .map_or_else(|| "script".into(), |name| name.to_string_lossy()); + let mut dialog = rfd::FileDialog::new() + .add_filter("Python script", &["py"]) + .set_file_name(format!("{stem}.local-copy.py")); + if let Some(directory) = change.path.parent() { + dialog = dialog.set_directory(directory); + } + let Some(mut path) = dialog.save_file() else { + self.dialogs.external_change = Some(change); + return; + }; + if path.extension().is_none() { + path.set_extension("py"); + } + match self.document.save_copy(&path) { + Ok(()) => self.reload_external_change(change), + Err(error) => { + self.dialogs.error( + "Cannot save a copy", + format!("{}\n\n{error}", path.display()), + ); + self.dialogs.external_change = Some(change); + } + } + } + + fn reload_external_change(&mut self, change: ExternalChange) { + self.checkpoint_recovery(); + let backup = if self.document.is_modified() { + match self + .document + .create_recovery_backup(&self.cache_dir.join("recovery")) + { + Ok(path) => Some(path), + Err(error) => { + self.dialogs.error( + "Cannot create recovery backup", + format!( + "The file was not reloaded and your edits are unchanged.\n\n{error}" + ), + ); + self.dialogs.external_change = Some(change); + return; + } + } + } else { + None + }; + + match self.document.apply_disk_version(change.disk) { + Ok(_) => { + if let Some(path) = &backup { + logging::push( + Level::Info, + "recovery", + &format!("Saved unsaved edits to {}", path.display()), + ); + } + let message = backup.map_or_else( + || format!("Reloaded {}", self.document.display_name()), + |path| { + format!( + "Reloaded {}; recovery backup: {}", + self.document.display_name(), + path.display() + ) + }, + ); + self.set_status(StatusKind::Info, message); + self.checkpoint_recovery(); + self.rerun_after_external_change(change.rerun_after_resolution); + } + Err(error) => self + .dialogs + .error("Cannot reload the script", error.to_string()), + } + } + + /// After a conflict was resolved: the next waiting one is asked about, + /// with its file shown, or the script renders if a change asked for it. + fn rerun_after_external_change(&mut self, rerun: bool) { + while !self.dialogs.external_queue.is_empty() { + let mut next = self.dialogs.external_queue.remove(0); + if !self.activate(next.document) { + continue; + } + next.rerun_after_resolution |= rerun; + self.dialogs.external_change = Some(next); + return; + } + if rerun { + self.start_run(false); + } + } + + /// Shows the breakpoints the document had when it was last open. + pub(super) fn restore_breakpoints(&mut self) { + if let Some(path) = self.document.path() { + let saved = self.settings.breakpoints_of(path).to_vec(); + self.editor.restore_breakpoints(&self.document.text, &saved); + } + } + + /// Keeps the breakpoints of the document for the next time it opens. + pub(super) fn remember_breakpoints(&mut self) { + if let Some(path) = self.document.path().map(Path::to_path_buf) { + let saved = self.editor.saved_breakpoints(&self.document.text); + self.settings.remember_breakpoints(&path, saved); + } + } + + /// Shows the named views the document had when it was last open. + pub(super) fn restore_views(&mut self) { + self.viewer.named_views = self + .document + .path() + .map(|path| self.settings.views_of(path).to_vec()) + .unwrap_or_default(); + } + + /// Keeps the named views of the document for the next time it opens. + pub(super) fn remember_views(&mut self) { + if let Some(path) = self.document.path().map(Path::to_path_buf) { + let views = self.viewer.named_views.clone(); + self.settings.remember_views(&path, views); + } + } + + fn after_save(&mut self) { + // Under the new name after a Save As. + self.remember_breakpoints(); + self.remember_views(); + if let Err(error) = self.recovery.archive(&self.document) { + log::warn!("Cannot add the saved document to local history: {error}"); + } + // Other tabs may still have unsaved edits. + self.checkpoint_recovery(); + if let Some(path) = self.document.path().map(Path::to_path_buf) { + self.settings.add_recent_file(&path); + self.settings.last_file = Some(path.clone()); + self.set_status(StatusKind::Success, format!("Saved {}", path.display())); + } + // The saved script may import other modules now. + self.request_imports(); + } + + pub(super) fn show_local_history(&mut self) { + self.checkpoint_recovery(); + match self.recovery.history(self.document.path()) { + Ok(versions) if versions.is_empty() => self.dialogs.info( + "Local history", + "No recovery versions are available for this document yet.", + ), + Ok(versions) => { + self.dialogs.history = Some(HistoryDialog { + document: self.document_generation, + versions, + selected: 0, + }); + } + Err(error) => self + .dialogs + .error("Cannot read local history", error.to_string()), + } + } + + pub(super) fn checkpoint_recovery(&mut self) { + // The startup documents are separate clean buffers while the + // recovered session awaits a decision. They must never clear that + // pending session. + // When quitting was confirmed, the edits were saved or deliberately + // discarded ("Don't save"); eframe's final `save` must not bring + // them back as an interrupted session on the next start. + if self.dialogs.recovery_session.is_some() || self.allow_close { + return; + } + match self.checkpoint_documents() { + Ok(_) => self.recovery_error_reported = false, + Err(error) => { + log::warn!("Cannot create recovery checkpoint: {error}"); + if !self.recovery_error_reported { + self.set_status( + StatusKind::Warning, + "Automatic recovery is unavailable; see the Log panel", + ); + self.recovery_error_reported = true; + } + } + } + } + + pub(super) fn clear_recovery_session(&mut self) { + if let Err(error) = self.recovery.clear_session() { + log::warn!("Cannot clear recovery session: {error}"); + } + } + + pub(super) fn poll_recovery(&mut self, ctx: &egui::Context) { + if self.dialogs.recovery_session.is_some() { + return; + } + if !self.any_modified() { + self.clear_recovery_session(); + self.next_recovery = Instant::now() + CHECKPOINT_INTERVAL; + return; + } + + let now = Instant::now(); + if now >= self.next_recovery { + self.checkpoint_recovery(); + self.next_recovery = now + CHECKPOINT_INTERVAL; + } + ctx.request_repaint_after(self.next_recovery.saturating_duration_since(now)); + } +} diff --git a/src/app/execution.rs b/src/app/execution.rs new file mode 100644 index 000000000..ed52f543d --- /dev/null +++ b/src/app/execution.rs @@ -0,0 +1,375 @@ +//! Script runs and the requests that still wait for an answer. +//! +//! A pure state machine, without egui or a process, so every transition is +//! tested directly (`tests/rust/app/test_execution.rs`). `AppState` asks it +//! what a user request or a worker message leads to and carries out the side +//! effects: sending requests, updating the scene, the status bar and the log. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use crate::scene::NodeKey; +use crate::worker::{ + self, + protocol::{InterferencePart, RequestId}, +}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Phase { + #[default] + Idle, + Running { + id: RequestId, + debug: bool, + }, + Paused { + id: RequestId, + }, +} + +/// What an outstanding request was for, so replies and errors can be routed. +impl Phase { + /// The run going on, unless it is paused in the debugger. + pub fn running_id(self) -> Option { + match self { + Phase::Running { id, .. } => Some(id), + Phase::Idle | Phase::Paused { .. } => None, + } + } + + /// The run going on, paused in the debugger or not. + pub fn run_id(self) -> Option { + match self { + Phase::Running { id, .. } | Phase::Paused { id } => Some(id), + Phase::Idle => None, + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Pending { + Run, + /// Completions for the editor of the document (generation) + /// `document`; `automatic` ones were offered while typing a name, not + /// asked for. + Completion { + automatic: bool, + document: u64, + }, + ConsoleCompletion, + /// Documentation of the name under the pointer in `document`. + Describe { + document: u64, + }, + Outline { + document: u64, + }, + Navigate { + document: u64, + }, + Inspect, + /// The construction geometry of one inspector entry: the workplane and + /// its selected (frame, item). + InspectGeometry { + key: NodeKey, + entry: (usize, Option), + }, + InterferenceGeometry { + first: InterferencePart, + second: InterferencePart, + }, + Console, + Export, + Check, + Upload, + /// `automatic` checks, once a day, stay silent unless a newer + /// CQ-editor is out. + Updates { + automatic: bool, + }, + /// The local modules imported by the script at this path. + Imports(PathBuf), + Measure, + /// Selector expressions for the topology selection. + Selector, + SelectorPreview, + /// Code repeating the current measurement, for the clipboard. + MeasurementCode, +} + +/// Whether the worker can take a run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WorkerAvailability { + Ready, + Starting, + Unavailable, +} + +impl From<&worker::Status> for WorkerAvailability { + fn from(status: &worker::Status) -> Self { + match status { + worker::Status::Ready(_) => Self::Ready, + worker::Status::Starting => Self::Starting, + worker::Status::NotStarted | worker::Status::Failed(_) => Self::Unavailable, + } + } +} + +/// What a request to run the script leads to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RunRequest { + /// Send the run now and report it with [`Execution::started`]. + Start, + /// Python is still starting; [`Execution::worker_ready`] returns the run. + WhenReady, + /// There is no Python to run it. + Unavailable, + /// A render is running; one more render follows it. + Queued, + /// A debugging session runs, or a render runs and debugging was asked. + Busy, +} + +/// What follows the end of a run. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RunEnd { + /// The run belongs to a document that was replaced since: its results + /// would look like the output of the new script and are discarded. + pub stale: bool, + /// A render was requested while it ran and starts now. + pub rerun: bool, +} + +#[derive(Debug, Default)] +pub struct Execution { + phase: Phase, + /// A render was requested while one was running. + rerun: bool, + /// The run of a document that was replaced since. + stale_run: Option, + /// Render as soon as the worker is ready (`Some(debug)`). + run_when_ready: Option, + pending: HashMap, + meshing: Option, + /// Stop interrupted this request and waits for it to answer. + stopping: Option<(RequestId, Instant)>, +} + +/// How long Stop waits for an interrupted script before restarting Python. +pub const STOP_GRACE: Duration = Duration::from_secs(3); + +/// What Stop does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StopPlan { + /// Nothing is running. + Nothing, + /// Interrupt the request (`KeyboardInterrupt`) and wait for it. + Interrupt(RequestId), + /// Restart Python: Stop was pressed again while waiting. + Restart, +} + +/// How far the worker is in meshing the running run's objects. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Meshing { + pub done: u32, + pub total: u32, + /// When the first progress report arrived. + pub since: Instant, +} + +impl Execution { + pub fn phase(&self) -> Phase { + self.phase + } + + pub fn is_busy(&self) -> bool { + self.phase != Phase::Idle + } + + pub fn is_paused(&self) -> bool { + matches!(self.phase, Phase::Paused { .. }) + } + + pub fn is_debugging(&self) -> bool { + matches!( + self.phase, + Phase::Paused { .. } | Phase::Running { debug: true, .. } + ) + } + + // -- requests --------------------------------------------------------------- + + pub fn track(&mut self, id: RequestId, kind: Pending) { + self.pending.insert(id, kind); + } + + /// What the request `id` was for, without answering it. + pub fn pending(&self, id: RequestId) -> Option<&Pending> { + self.pending.get(&id) + } + + pub fn is_pending(&self, id: RequestId) -> bool { + self.pending.contains_key(&id) + } + + /// The request `id` was answered: what it was for, once. + pub fn answer(&mut self, id: RequestId) -> Option { + self.forget_stop(id); + self.pending.remove(&id) + } + + // -- stopping ----------------------------------------------------------------- + + /// What Stop does now: interrupt the running script, else a console + /// command, and restart Python if Stop is pressed again before it + /// answers. A paused debugging session is stopped by the debugger. + pub fn stop(&mut self, now: Instant) -> StopPlan { + if let Some((target, _)) = self.stopping.take() + && self.pending.contains_key(&target) + { + return StopPlan::Restart; + } + let console = || { + self.pending + .iter() + .filter(|(_, kind)| **kind == Pending::Console) + .map(|(id, _)| *id) + .min() + }; + match self.phase.running_id().or_else(console) { + Some(target) => { + self.stopping = Some((target, now)); + StopPlan::Interrupt(target) + } + None => StopPlan::Nothing, + } + } + + /// When Python is restarted if the interrupted request has not + /// answered. + pub fn stop_deadline(&self) -> Option { + self.stopping.map(|(_, since)| since + STOP_GRACE) + } + + pub fn is_stopping(&self) -> bool { + self.stopping.is_some() + } + + fn forget_stop(&mut self, id: RequestId) { + if self.stopping.is_some_and(|(target, _)| target == id) { + self.stopping = None; + } + } + + // -- runs --------------------------------------------------------------------- + + /// A render (`debug` false) or a debugging session was asked for. + pub fn request_run(&mut self, debug: bool, worker: WorkerAvailability) -> RunRequest { + match worker { + WorkerAvailability::Ready => {} + WorkerAvailability::Starting => { + self.run_when_ready = Some(debug); + return RunRequest::WhenReady; + } + WorkerAvailability::Unavailable => return RunRequest::Unavailable, + } + match self.phase { + Phase::Idle => RunRequest::Start, + Phase::Running { debug: false, .. } if !debug => { + self.rerun = true; + RunRequest::Queued + } + _ => RunRequest::Busy, + } + } + + /// The run `id` was sent. + pub fn started(&mut self, id: RequestId, debug: bool) { + self.pending.insert(id, Pending::Run); + self.phase = Phase::Running { id, debug }; + self.meshing = None; + } + + /// The worker meshed `done` of the `total` parts of run `id`. Reports + /// for anything but the running run are ignored. + pub fn meshing_progress(&mut self, id: RequestId, done: u32, total: u32, now: Instant) { + if self.phase.running_id() == Some(id) { + let since = self.meshing.map_or(now, |meshing| meshing.since); + self.meshing = Some(Meshing { done, total, since }); + } + } + + /// The meshing of the running run, while it goes on. + pub fn meshing(&self) -> Option { + self.meshing.filter(|meshing| meshing.done < meshing.total) + } + + /// The debugger stopped the run `id`. Returns whether the run is stale, + /// and should be stopped instead of shown. + pub fn paused(&mut self, id: RequestId) -> bool { + self.phase = Phase::Paused { id }; + self.stale_run == Some(id) + } + + /// A debugger command continues the paused run, whose id is returned. + pub fn resume(&mut self) -> Option { + let Phase::Paused { id } = self.phase else { + return None; + }; + self.phase = Phase::Running { id, debug: true }; + Some(id) + } + + /// The run `id` finished or failed. + pub fn ended(&mut self, id: RequestId) -> RunEnd { + self.forget_stop(id); + self.pending.remove(&id); + self.phase = Phase::Idle; + self.meshing = None; + RunEnd { + stale: self.stale_run.take() == Some(id), + rerun: std::mem::take(&mut self.rerun), + } + } + + /// The worker became ready: the run asked for while it started, if any. + pub fn worker_ready(&mut self) -> Option { + self.run_when_ready.take() + } + + /// The document was replaced. Queued runs are dropped and a run still + /// going becomes stale. Returns whether that run is paused and must be + /// stopped. + pub fn abandon(&mut self) -> bool { + self.rerun = false; + self.run_when_ready = None; + match self.phase { + Phase::Idle => false, + Phase::Running { id, .. } => { + self.stale_run = Some(id); + false + } + Phase::Paused { id } => { + self.stale_run = Some(id); + true + } + } + } + + /// The worker restarted: nothing it was doing will answer. A render + /// asked for while Python starts still follows. + pub fn reset(&mut self) { + self.phase = Phase::Idle; + self.rerun = false; + self.stale_run = None; + self.pending.clear(); + self.meshing = None; + self.stopping = None; + } +} + +#[cfg(test)] +#[path = "../../tests/rust/app/test_execution.rs"] +mod tests; diff --git a/src/app/mod.rs b/src/app/mod.rs new file mode 100644 index 000000000..786faa514 --- /dev/null +++ b/src/app/mod.rs @@ -0,0 +1,1162 @@ +//! Application state and the frame loop. +//! +//! Worker events, the file watcher and recovery checkpoints are handled in +//! [`eframe::App::logic`], which also runs while the window is minimized or +//! hidden, so runs never stall waiting for a repaint. Each frame then applies +//! settings and collects keyboard shortcuts, builds the UI (menu, toolbar, +//! dock area, status bar, dialogs), which only *queues* [`Action`]s, and +//! finally executes the queued actions. Keeping mutations out of the widget +//! code makes the data flow easy to follow. +//! +//! [`AppState::execute`] dispatches each action. The work behind it lives in +//! one submodule per concern, each an `impl AppState` block: +//! +//! * `documents`: open, save, reload, external changes, recovery, history; +//! * `tabs`: the open documents, switching and closing tabs, the session +//! they are restored from and the script F5 runs; +//! * `projects`: the project folder, its main script and file operations; +//! * `runs`: rendering, debugging and stopping scripts; +//! * `worker_events`: the worker's lifecycle and the routing of its messages; +//! * `watching`: automatic reload of the script and its imported modules; +//! * `services`: selection, measurement, inspection, export, console, upload. +//! +//! The run and request state is the pure state machine in `execution`. + +mod documents; +mod execution; +mod projects; +mod runs; +mod services; +mod tabs; +mod watching; +mod worker_events; + +pub use tabs::TabInfo; + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; + +use egui::ViewportCommand; +use egui_dock::{DockArea, DockState}; + +use crate::commands::{self, Action}; +use crate::dialogs::{self, Dialogs, FilePrompt, Intent, RecoverySession}; +use crate::document::{DEFAULT_SCRIPT, Document}; +use crate::editor::{CodeEditor, EditorOptions}; +use crate::embedded::{self, Example}; +use crate::file_watcher::FileWatcher; +use crate::logging; +use crate::panels::{ + self, ConsoleState, EntryKind, InspectorState, LogView, MeasurementState, NavigationState, + ParametersState, SelectorPreviewState, SelectorState, SelectorUse, Tab, TabContext, +}; +use crate::project::Project; +use crate::recovery::{CHECKPOINT_INTERVAL, RecoveryStore}; +use crate::scene::{Overlay, Rgb, RunScript, Scene}; +use crate::settings::{self, Projection, Settings}; +use crate::theme::{self, Palette}; +use crate::updates; +use crate::viewer::{ViewInput, Viewer, ViewerEvent}; +use crate::worker::protocol::{CadCheck, NavigationMode, Request, RequestId, Variable}; +use crate::worker::{self, Worker}; + +use execution::{Execution, Pending, Phase}; +use services::ExportJob; +use tabs::EditorTabs; +use watching::WatchKey; + +const SETTINGS_KEY: &str = "settings"; +/// Meshing shows its progress bar only once it has taken this long. +const MESHING_BAR_DELAY: std::time::Duration = std::time::Duration::from_millis(300); +const LAYOUT_KEY: &str = "dock_layout"; +/// The CadQuery logo for the window icon and the About dialog: a static, so +/// the binary holds the bytes once. +pub static LOGO_ICO: &[u8] = include_bytes!("../../assets/icons/cadquery_logo_dark.ico"); +/// The documentation of this editor, not the wiki of the PyQt one. +pub const DOCUMENTATION_URL: &str = + concat!(env!("CARGO_PKG_REPOSITORY"), "/blob/master/docs/README.md"); +/// How to set up Python with CadQuery for the editor. +pub const INSTALLATION_URL: &str = concat!( + env!("CARGO_PKG_REPOSITORY"), + "/blob/master/docs/getting-started/installation.md" +); + +/// Command-line options. +#[derive(Debug, Default)] +pub struct StartupOptions { + pub file: Option, + pub python: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StatusKind { + Info, + Success, + Warning, + Error, +} + +pub struct Status { + pub kind: StatusKind, + pub text: String, +} + +pub struct AppState { + pub settings: Settings, + /// The document of the shown tab. + pub document: Document, + /// The editor of the shown tab. + pub editor: CodeEditor, + /// The other open tabs. + tabs: EditorTabs, + /// The folder of the Project panel. + pub project: Option, + pub scene: Scene, + pub viewer: Viewer, + pub worker: Worker, + pub variables: Vec, + pub traceback: Option, + /// The document whose run raised the traceback. + pub traceback_document: Option, + pub inspector: InspectorState, + pub measurements: MeasurementState, + /// The CadQuery selector of the topology selection. + pub selector: SelectorState, + pub selector_preview: SelectorPreviewState, + pub navigation: NavigationState, + pub parameters: ParametersState, + /// When to render after a parameter changed (`ctx` time, seconds). + parameter_render_at: Option, + /// Identifies the shown document among those opened or created; a + /// reload of the same file keeps it, so the lines of its objects still + /// apply. + pub(crate) document_generation: u64, + /// The script the current run executes, for its objects' lines. + run_script: Option<(RequestId, Arc)>, + pub console: ConsoleState, + pub log_view: LogView, + pub status: Option, + pub dialogs: Dialogs, + pub geometry_checks: HashMap, + pub cad_checks: Vec, + pub cad_checks_document: Option, + export_job: Option, + ctx: egui::Context, + execution: Execution, + actions: Vec, + watcher: FileWatcher, + watch_key: Option, + focused_last_frame: bool, + /// The local modules the script F5 runs imports, while they are watched. + imports: Vec, + examples: Vec, + palette: Palette, + cache_dir: PathBuf, + recovery: RecoveryStore, + next_recovery: Instant, + recovery_error_reported: bool, + python_override: Option, + worker_was_ready: bool, + allow_close: bool, + title: String, + applied_theme: Option, + applied_scale: f32, + logo: Option, + /// Whether the layout has the Editor panel, for the empty view's hint. + editor_panel_open: bool, +} + +impl AppState { + pub fn queue(&mut self, actions: impl IntoIterator) { + self.actions.extend(actions); + } + + pub fn palette(&self) -> &Palette { + &self.palette + } + + pub fn examples(&self) -> &[Example] { + &self.examples + } + + pub fn default_color(&self) -> Rgb { + self.settings + .viewer + .default_color + .map(|c| f32::from(c) / 255.0) + } + + pub fn is_paused(&self) -> bool { + self.execution.is_paused() + } + + pub fn is_debugging(&self) -> bool { + self.execution.is_debugging() + } + + pub fn is_busy(&self) -> bool { + self.execution.is_busy() + } + + /// Something Stop can stop: a script, or a console command. + pub fn can_stop(&self) -> bool { + self.execution.is_busy() || self.console.busy + } + + /// The CadQuery logo, loaded on first use. + pub fn logo(&mut self, ctx: &egui::Context) -> Option { + if self.logo.is_none() { + let image = + image::load_from_memory_with_format(LOGO_ICO, image::ImageFormat::Ico).ok()?; + let rgba = image.to_rgba8(); + let size = [rgba.width() as usize, rgba.height() as usize]; + let color_image = egui::ColorImage::from_rgba_unmultiplied(size, rgba.as_raw()); + self.logo = + Some(ctx.load_texture("cadquery-logo", color_image, egui::TextureOptions::LINEAR)); + } + self.logo.clone() + } + + fn set_status(&mut self, kind: StatusKind, text: impl Into) { + self.status = Some(Status { + kind, + text: text.into(), + }); + } + + fn now(&self) -> f64 { + self.ctx.input(|i| i.time) + } + + // -- per-frame bookkeeping ------------------------------------------------ + + /// Work that must go on without painting: eframe calls this before + /// every frame and also while the window is minimized or hidden, + /// whenever a repaint was requested (the worker threads request one per + /// message; the watcher and recovery timers schedule theirs). + fn logic(&mut self, ctx: &egui::Context) { + self.process_worker_events(); + self.poll_stop(ctx); + self.poll_parameter_render(ctx); + self.poll_selector_preview(ctx); + let focused = ctx.input(|input| input.focused); + if focused && !self.focused_last_frame { + self.check_disk_on_focus(); + } + self.focused_last_frame = focused; + self.sync_watcher(); + self.poll_watcher(ctx); + self.poll_recovery(ctx); + } + + fn begin_frame(&mut self, ctx: &egui::Context) { + if self.applied_theme != Some(self.settings.general.theme) { + theme::apply(ctx, self.settings.general.theme); + self.applied_theme = Some(self.settings.general.theme); + } + // egui's own Ctrl +/- zoom and the preference stay in sync. + if self.settings.general.ui_scale != self.applied_scale { + ctx.set_zoom_factor(self.settings.general.ui_scale); + self.applied_scale = self.settings.general.ui_scale; + } else if (ctx.zoom_factor() - self.applied_scale).abs() > 1e-3 { + self.applied_scale = ctx.zoom_factor(); + self.settings.general.ui_scale = self.applied_scale; + } + self.palette = Palette::of(ctx.theme()); + // A modal dialog keeps the pointer from the window, but not the + // keyboard: shortcuts wait until its question is answered, so no + // tab switches or file opens behind it. + if !self.dialogs.modal_open() { + commands::collect_shortcuts(ctx, &mut self.actions); + commands::collect_selection_shortcuts( + ctx, + &self.settings.viewer.selection_shortcuts, + &mut self.actions, + ); + } + } + + fn end_frame(&mut self, ctx: &egui::Context) { + if ctx.input(|i| i.viewport().close_requested()) && !self.allow_close && self.any_modified() + { + ctx.send_viewport_cmd(ViewportCommand::CancelClose); + self.guard_unsaved(Intent::Quit); + } + + let marker = if self.document.is_modified() { "*" } else { "" }; + let folder = self + .document + .path() + .and_then(Path::parent) + .and_then(Path::file_name) + .map(|name| format!(" — {}", name.to_string_lossy())) + .unwrap_or_default(); + let title = format!( + "{}{marker}{folder} — CQ-editor", + self.document.display_name() + ); + if title != self.title { + ctx.send_viewport_cmd(ViewportCommand::Title(title.clone())); + self.title = title; + } + } + + // -- panels --------------------------------------------------------------- + + pub fn editor_ui(&mut self, ui: &mut egui::Ui) { + let colors = self.palette.editor(); + let options = EditorOptions { + font_size: self.settings.editor.font_size, + line_wrap: self.settings.editor.line_wrap, + ruler: self.settings.editor.max_line_length, + highlight_current_line: self.settings.editor.highlight_current_line, + auto_indent: self.settings.editor.auto_indent, + completion_min_chars: self.settings.editor.completion_min_chars, + colors: &colors, + }; + let tabs = self.tabs(); + if tabs.len() > 1 { + crate::ui::editor_tabs::ui(ui, &tabs, &mut self.actions); + } + let output = self.editor.ui(ui, &mut self.document, &options); + if let Some(request) = output.completion_request { + self.request_completion(request); + } + if let Some(request) = output.hover_request { + self.request_description(request); + } + self.update_selector_preview_cursor(); + } + + pub fn viewer_ui(&mut self, ui: &mut egui::Ui, frame: &eframe::Frame) { + let colors = self.palette.viewer(); + let busy = match (self.execution.phase(), self.worker.status()) { + (Phase::Running { debug: false, .. }, _) => Some("Running script…"), + (Phase::Running { debug: true, .. }, _) => Some("Debugging…"), + (Phase::Idle, worker::Status::Starting) => Some("Starting Python…"), + _ => None, + }; + let busy = if self.execution.is_stopping() { + Some("Stopping…") + } else { + busy + }; + let hint = self.worker.is_ready().then(|| self.empty_view_hint()); + let events = self.viewer.ui( + ui, + frame, + ViewInput { + scene: &self.scene, + settings: &self.settings.viewer, + rendering: &self.settings.rendering, + colors: &colors, + busy, + empty_hint: hint.as_deref(), + meshing: self + .execution + .meshing() + .filter(|meshing| meshing.since.elapsed() >= MESHING_BAR_DELAY) + .map(|meshing| (meshing.done, meshing.total)), + }, + ); + for event in events { + match event { + ViewerEvent::Picked { + key, + topology, + extend, + } => self.actions.push(Action::Select { + key, + topology, + extend, + }), + ViewerEvent::FocusRequested => self.actions.push(Action::FitSelection), + ViewerEvent::Command(action) => self.actions.push(action), + ViewerEvent::Captured(Ok(message)) => self.set_status(StatusKind::Success, message), + ViewerEvent::Captured(Err(err)) => self.dialogs.error("Capture failed", err), + } + } + } + + /// What an empty view and Objects panel suggest: after a failed run, + /// pressing F5 again is not the answer, and a closed editor is named. + pub fn empty_view_hint(&self) -> String { + let hint = match &self.traceback { + Some(error) => { + let location = error + .line + .map_or_else(String::new, |l| format!(" at line {l}")); + format!("The last run failed{location}; see the Traceback panel") + } + None => "Press F5 to render the script".to_owned(), + }; + if self.editor_panel_open { + hint + } else { + format!("{hint} · the editor is closed: View > Editor") + } + } + + // -- actions ---------------------------------------------------------------- + + fn execute(&mut self, action: Action) { + let animate = self.settings.viewer.animate; + let now = self.now(); + match action { + Action::NewFile => self.new_file(), + Action::OpenFile => self.choose_files(), + Action::OpenPath(path) => self.open_path(&path), + Action::OpenExample(index) => self.open_example(index), + Action::Save => { + self.save(); + } + Action::SaveAs => { + self.save_as(); + } + Action::SaveAll => self.save_all(), + Action::CloseTab => self.close_tabs(vec![self.document_generation]), + Action::CloseDocument(generation) => self.close_tabs(vec![generation]), + Action::CloseOtherTabs(kept) => { + let others = self + .tabs() + .into_iter() + .map(|tab| tab.generation) + .filter(|&generation| generation != kept) + .collect(); + self.activate(kept); + self.close_tabs(others); + } + Action::CloseAllTabs => { + let all = self.tabs().into_iter().map(|tab| tab.generation).collect(); + self.close_tabs(all); + } + Action::ActivateTab(generation) => { + self.activate(generation); + } + Action::NextTab => self.cycle_tab(true), + Action::PreviousTab => self.cycle_tab(false), + Action::OpenFolder => self.choose_project_folder(), + Action::OpenFolderPath(path) => self.open_project_folder(&path), + Action::CloseFolder => self.close_project(), + Action::RefreshProject => { + if let Some(project) = &mut self.project { + project.refresh(); + } + } + Action::NewFileIn(folder) => { + self.dialogs.file_prompt = Some(FilePrompt::NewFile { + folder, + name: String::new(), + error: None, + }); + } + Action::NewFolderIn(folder) => { + self.dialogs.file_prompt = Some(FilePrompt::NewFolder { + folder, + name: String::new(), + error: None, + }); + } + Action::RenamePath(path) => { + self.dialogs.file_prompt = Some(FilePrompt::rename(&path)); + } + Action::DeletePath(path) => { + let unsaved = self.unsaved_below(&path); + self.dialogs.file_prompt = Some(FilePrompt::Delete { + path, + unsaved, + error: None, + }); + } + Action::SetMainScript(path) => self.set_main_script(path), + Action::RevealPath(path) => self.reveal_in_file_manager(&path), + Action::LocalHistory => self.show_local_history(), + Action::ToggleAutoreload => { + self.settings.editor.autoreload = !self.settings.editor.autoreload + } + Action::Quit => self.guard_unsaved(Intent::Quit), + + Action::Undo => self.editor.undo(&mut self.document), + Action::Redo => self.editor.redo(&mut self.document), + Action::ToggleComment => self.editor.toggle_comment(&mut self.document), + Action::DuplicateLine => self.editor.duplicate_line(&mut self.document), + Action::MoveLineUp => self.editor.move_lines(&mut self.document, true), + Action::MoveLineDown => self.editor.move_lines(&mut self.document, false), + Action::InsertSnippet(index) => { + if let Some(snippet) = crate::editor::snippets::SNIPPETS.get(index) { + self.editor.insert_snippet(&mut self.document, snippet); + } + } + Action::Autocomplete => self.editor.request_completion(), + Action::Find => self.editor.open_search(&self.document), + Action::Replace => self.editor.open_replace(&self.document), + Action::GoToLinePrompt => self.editor.open_go_to_line(), + Action::ShowOutline => self.request_outline(), + Action::GoToDefinition => self.request_navigation(NavigationMode::Definition), + Action::FindReferences => self.request_navigation(NavigationMode::References), + Action::CopySelector => self.use_selector(SelectorUse::Copy), + Action::InsertSelector => self.use_selector(SelectorUse::Insert), + Action::CopyMeasurementCode => self.request_measurement_code(), + Action::CopyMeasurement(format) => self.copy_measurement(format), + Action::FindNext | Action::FindPrevious => { + if self.editor.search_is_open() { + self.editor + .find_next(&self.document, action == Action::FindNext); + } else { + self.editor.open_search(&self.document); + } + } + Action::Preferences => self.dialogs.preferences = true, + + Action::Render => self.start_run(false), + Action::Profile => self.start_profile(), + Action::ClearProfile => self.clear_line_profiles(), + Action::ToggleDebug => { + if self.is_debugging() { + self.stop_debugging(); + } else { + self.start_run(true); + } + } + Action::Debug(action) => self.debug_command(action), + Action::CancelMeshing => { + if let Some(id) = self.execution.phase().running_id() + && self.execution.meshing().is_some() + && self.worker.send(&Request::Cancel { target: id }) + { + self.set_status(StatusKind::Info, "Cancelling the meshing…"); + } + } + Action::Stop => self.stop(), + Action::ClearConsole => self.console.clear(), + Action::ClearLog => logging::clear(), + Action::RestartPython => self.start_worker(), + Action::CreateEnvironment => { + let folder = unused_folder(&self.cache_dir.join("environments").join("cadquery")); + let base = self.python_in_use(); + self.dialogs.environment = Some(dialogs::environment::EnvironmentDialog::create( + folder, + base, + worker::launch::candidates(), + )); + } + Action::InstallPackages => { + let python = self.python_in_use(); + self.dialogs.environment = Some(dialogs::environment::EnvironmentDialog::install( + python, + worker::launch::candidates(), + )); + } + Action::UsePython(path) => { + self.settings.general.python = path.display().to_string(); + // A --python from the command line would win otherwise. + self.python_override = None; + self.start_worker(); + } + + Action::Fit => self.viewer.fit(&self.scene, animate, now), + Action::FitSelection => self.viewer.fit_selection(&self.scene, animate, now), + Action::View(view) => self.viewer.set_standard_view(view, animate, now), + Action::Display(mode) => self.viewer.display_mode = mode, + Action::SelectionMode(mode) => self.viewer.selection_mode = mode, + Action::ToggleSection => self.viewer.toggle_section(&self.scene), + Action::ToggleGroundGrid => { + self.settings.viewer.ground_grid = !self.settings.viewer.ground_grid; + } + Action::ToggleScaleBar => { + self.settings.viewer.scale_bar = !self.settings.viewer.scale_bar; + } + Action::ToggleExplode => self.viewer.toggle_explode(&mut self.scene), + Action::SetExplode(factor) => self.scene.set_explode(factor), + Action::ToggleIsolate => { + if self.scene.is_isolating() { + self.scene.end_isolation(); + } else if self.scene.selection.is_empty() { + self.set_status(StatusKind::Info, "Select the objects to isolate"); + } else { + let keys = self.scene.selection.clone(); + self.scene.isolate(&keys); + } + } + Action::ShowAll => self.scene.show_all(), + Action::SaveView(name) => { + let projection = self.settings.viewer.projection; + let name = self.viewer.save_view(name.as_deref(), projection); + self.set_status(StatusKind::Success, format!("Saved the view \"{name}\"")); + } + Action::GoToView(index) => { + if let Some(projection) = self.viewer.go_to_view(index, animate, now) { + self.settings.viewer.projection = projection; + } else if index < self.viewer.named_views.len() { + self.set_status(StatusKind::Error, "This saved view is damaged"); + } + } + Action::UpdateView(index) => { + let projection = self.settings.viewer.projection; + if let Some(name) = self.viewer.update_view(index, projection) { + let text = format!("Updated the view \"{name}\""); + self.set_status(StatusKind::Success, text); + } + } + Action::DeleteView(index) => { + self.viewer.delete_view(index); + } + Action::ToggleProjection => { + self.settings.viewer.projection = match self.settings.viewer.projection { + Projection::Orthographic => Projection::Perspective, + _ => Projection::Orthographic, + }; + } + // Layout changes are handled by the app, which owns the dock. + Action::TogglePanel(_) | Action::ResetLayout | Action::ToggleMaximize(_) => {} + Action::CommandPalette => self.dialogs.palette = Some(Default::default()), + + Action::Export(format) => self.export(format), + Action::CheckGeometry => self.check_geometry(), + Action::ToggleInspect => self.toggle_inspect(), + Action::Screenshot => self.dialogs.capture.open = true, + Action::SaveImage => self.save_image(), + Action::CopyImage => self.copy_image(), + Action::ExportTurntable => self.export_turntable(), + Action::CancelTurntable => { + if self.viewer.turntable_progress().is_some() { + self.viewer.cancel_turntable(); + self.set_status(StatusKind::Info, "Turntable export cancelled"); + } + } + Action::Upload => { + self.dialogs.upload.get_or_insert_with(Default::default); + } + + Action::Documentation => open_url(DOCUMENTATION_URL), + Action::InstallationGuide => open_url(INSTALLATION_URL), + Action::CadQueryDocumentation => open_url("https://cadquery.readthedocs.io/en/latest/"), + Action::About => self.dialogs.about = true, + Action::DownloadUpdate => { + if let Some(release) = updates::available(&self.settings.general) { + open_url(&release.url); + } + } + Action::CheckUpdates => { + if self.send_tracked(Pending::Updates { automatic: false }, |id| { + Request::CheckUpdates { + id, + editor: updates::VERSION.to_owned(), + cadquery: true, + } + }) { + self.set_status(StatusKind::Info, "Checking for CadQuery updates…"); + } + } + + Action::GoToLine(line) => { + // A line of the script F5 runs, wherever its tab is. + self.activate(self.run_target()); + self.editor.go_to_line(&self.document.text, line); + } + Action::GoToScriptLine { document, line } => { + if self.activate(document) { + self.editor.go_to_line(&self.document.text, line); + } else { + self.set_status( + StatusKind::Info, + "The script of this traceback is no longer open", + ); + } + } + Action::OpenFileAt { path, line } => self.open_path_at(&path, line), + Action::Select { + key, + topology, + extend, + } => self.select(key, topology, extend), + Action::SetVisible { key, visible } => self.scene.set_visible(&key, visible), + Action::SetParameter { name, line, value } => self.set_parameter(&name, line, value), + Action::ResetParameters => self.reset_parameters(), + Action::GoToSource { key, step } => self.go_to_source(&key, step), + Action::GoToSelectionSource => { + if let Some(key) = self.scene.current().map(|node| node.key.clone()) { + self.go_to_source(&key, None); + } else { + self.set_status(StatusKind::Info, "Select an object to go to its source"); + } + } + Action::RemoveSelected => { + let keys = self.scene.selected_top_level(); + let removed = self.scene.remove_top_level(&keys); + self.geometry_checks.clear(); + self.release(removed); + self.request_topology_results(); + self.refresh_inspector(); + } + Action::ClearObjects => { + let removed = self.scene.clear(); + self.geometry_checks.clear(); + self.release(removed); + self.measurements.clear(); + self.selector.clear(); + self.scene.overlay = Overlay::default(); + self.refresh_inspector(); + } + Action::InspectEntry { frame, item } => { + self.inspector.selected = Some((frame, item)); + if self.inspector.show_in_view { + self.request_inspection_geometry(); + } + } + Action::ConsoleSubmit(source) => self.console_submit(source), + Action::ConsoleComplete => self.console_complete(), + Action::ResetConsole => { + if self.send_tracked(Pending::Console, |id| Request::ConsoleReset { id }) { + self.console.more = false; + self.console.push(EntryKind::Info, "Console restarted\n"); + } + } + Action::StartUpload { url, file_type } => self.start_upload(url, file_type), + } + } +} + +/// Opens a web page in the browser: the menu's links and the links of egui +/// widgets (eframe's own link handling is disabled, see `Cargo.toml`). +/// +/// Only http(s) URLs are opened. An upload service's reply supplies links +/// too, and handed to the system, a path or another scheme would open local +/// documents or start programs. +pub fn open_url(url: &str) { + if !is_web_url(url) { + log::warn!("Not opening {url}: only http and https links are opened"); + return; + } + if let Err(err) = open::that(url) { + log::warn!("Cannot open {url}: {err}"); + } +} + +fn is_web_url(url: &str) -> bool { + url.split_once("://").is_some_and(|(scheme, rest)| { + (scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")) + && !rest.is_empty() + && !url.chars().any(char::is_control) + }) +} + +/// Takes the links egui widgets asked to open this frame. +fn take_requested_urls(ctx: &egui::Context) -> Vec { + ctx.output_mut(|output| { + let mut urls = Vec::new(); + output.commands.retain(|command| match command { + egui::OutputCommand::OpenUrl(open) => { + urls.push(open.url.clone()); + false + } + _ => true, + }); + urls + }) +} + +pub struct CqEditorApp { + dock: DockState, + /// The whole layout while one panel is maximized in `dock`. + maximized: Option>, + state: AppState, +} + +/// Recreates a panel where it belongs in the default workspace. Actions +/// can rely on this even after the user closed the panel or maximized one. +fn ensure_panel(dock: &mut DockState, tab: Tab) { + if dock.find_tab(&tab).is_some() { + return; + } + let tree = dock.main_surface_mut(); + match tab { + Tab::Editor => match tree.find_tab(&Tab::Viewer) { + Some((node, _)) => { + tree.split_left(node, 0.45, vec![tab]); + } + None => tree.push_to_focused_leaf(tab), + }, + Tab::Project => match tree.find_tab(&Tab::Editor) { + Some((node, _)) => { + tree.split_left(node, 0.25, vec![tab]); + } + None => tree.push_to_focused_leaf(tab), + }, + Tab::Console | Tab::Traceback | Tab::Log => { + let sibling = [Tab::Console, Tab::Traceback, Tab::Log] + .into_iter() + .find_map(|other| tree.find_tab(&other).map(|(node, _)| node)); + if let Some(node) = sibling { + tree.set_focused_node(node); + tree.push_to_focused_leaf(tab); + } else if let Some((node, _)) = tree.find_tab(&Tab::Viewer) { + tree.split_below(node, 0.74, vec![tab]); + } else { + tree.push_to_focused_leaf(tab); + } + } + _ => tree.push_to_focused_leaf(tab), + } +} + +/// The layout of the last session, when it has the 3D view, with its +/// Editor back if it was closed; else the default layout. +fn restored_layout(saved: Option>) -> DockState { + let mut dock = saved + .filter(|dock| dock.find_tab(&Tab::Viewer).is_some()) + .unwrap_or_else(panels::default_layout); + ensure_panel(&mut dock, Tab::Editor); + dock +} + +/// Names of the panel tabs' own menu that a newcomer understands. +fn label_tab_menus(dock: &mut DockState) { + let menu = &mut dock.translations.tab_context_menu; + menu.eject_button = "Float in a Window".to_owned(); + menu.close_button = "Close Panel".to_owned(); +} + +impl CqEditorApp { + pub fn new(cc: &eframe::CreationContext<'_>, options: StartupOptions) -> Self { + let ctx = cc.egui_ctx.clone(); + ctx.set_fonts(theme::fonts()); + + let settings: Settings = cc + .storage + .and_then(|storage| eframe::get_value(storage, SETTINGS_KEY)) + .unwrap_or_default(); + let dock = restored_layout( + cc.storage + .and_then(|storage| eframe::get_value::>(storage, LAYOUT_KEY)), + ); + + let cache_dir = eframe::storage_dir(crate::APP_ID).unwrap_or_else(std::env::temp_dir); + let recovery = RecoveryStore::new(cache_dir.join("recovery")); + let mut startup_errors = Vec::new(); + let recovery_session = match recovery.load_session() { + Ok(documents) if documents.is_empty() => None, + Ok(documents) => Some(RecoverySession { + documents, + selected: 0, + }), + Err(error) => { + log::warn!("Cannot load the recovery session: {error}"); + startup_errors.push(format!("Cannot load the recovery session:\n{error}")); + None + } + }; + let dialogs = Dialogs { + recovery_session, + ..Dialogs::default() + }; + + let mut state = AppState { + worker: Worker::new(ctx.clone()), + ctx, + settings, + document: Document::untitled(DEFAULT_SCRIPT), + editor: CodeEditor::default(), + tabs: EditorTabs::new(0), + project: None, + scene: Scene::default(), + viewer: Viewer::default(), + variables: Vec::new(), + traceback: None, + traceback_document: None, + inspector: InspectorState::default(), + measurements: MeasurementState::default(), + selector: SelectorState::default(), + selector_preview: SelectorPreviewState::default(), + navigation: NavigationState::default(), + parameters: ParametersState::default(), + parameter_render_at: None, + document_generation: 0, + run_script: None, + console: ConsoleState::default(), + log_view: LogView::default(), + status: None, + dialogs, + geometry_checks: HashMap::new(), + cad_checks: Vec::new(), + cad_checks_document: None, + export_job: None, + execution: Execution::default(), + actions: Vec::new(), + watcher: FileWatcher::default(), + watch_key: None, + focused_last_frame: false, + imports: Vec::new(), + examples: embedded::examples(), + palette: Palette::DARK, + cache_dir, + recovery, + next_recovery: Instant::now() + CHECKPOINT_INTERVAL, + recovery_error_reported: false, + python_override: options.python, + worker_was_ready: false, + allow_close: false, + title: String::new(), + applied_theme: None, + applied_scale: 1.0, + logo: None, + editor_panel_open: true, + }; + startup_errors.extend(state.restore_session(options.file)); + if !startup_errors.is_empty() { + state + .dialogs + .error("Startup problem", startup_errors.join("\n\n")); + } + if let Some(path) = state.document.path().map(Path::to_path_buf) { + state.settings.add_recent_file(&path); + state.settings.last_file = Some(path); + } + state.restore_views(); + state.start_worker(); + let mut dock = dock; + label_tab_menus(&mut dock); + let mut app = Self { + dock, + maximized: None, + state, + }; + if app.state.project.is_some() { + app.show_panel(Tab::Project); + } + app + } + + /// Shows `tab` alone in the window (the focused panel when `None`), or + /// brings the whole layout back. + fn toggle_maximize(&mut self, tab: Option) { + if self.maximized.is_some() { + self.restore_layout(); + return; + } + let tab = tab.or_else(|| self.dock.find_active_focused().map(|(_, tab)| *tab)); + let Some(tab) = tab else { + self.state.set_status( + StatusKind::Info, + "Click in a panel first, or double-click its tab, to maximize it", + ); + return; + }; + let mut alone = DockState::new(vec![tab]); + label_tab_menus(&mut alone); + self.maximized = Some(std::mem::replace(&mut self.dock, alone)); + self.state.set_status( + StatusKind::Info, + format!( + "{} is maximized; double-click its tab to bring the layout back", + tab.title() + ), + ); + } + + /// Ends a maximized panel, bringing the whole layout back. + fn restore_layout(&mut self) { + if let Some(layout) = self.maximized.take() { + self.dock = layout; + } + } + + /// Shows a panel required by an action, recreating it if closed. + fn show_panel(&mut self, tab: Tab) { + if self.dock.find_tab(&tab).is_none() { + self.restore_layout(); + } + ensure_panel(&mut self.dock, tab); + if let Some(path) = self.dock.find_tab(&tab) { + let _ = self.dock.set_active_tab(path); + } + } + + fn execute(&mut self, action: Action) { + let shown = self.state.document_generation; + self.execute_action(action); + // New, Open, examples, tabs, recovered work…: another document is + // shown, so its editor must be on screen. + if self.state.document_generation != shown { + self.show_panel(Tab::Editor); + } + } + + fn execute_action(&mut self, action: Action) { + match action { + Action::TogglePanel(tab) => { + self.restore_layout(); + match self.dock.find_tab(&tab) { + Some(path) => { + self.dock.remove_tab(path); + } + None => self.dock.push_to_focused_leaf(tab), + } + } + Action::ToggleMaximize(tab) => self.toggle_maximize(tab), + Action::ResetLayout => { + self.maximized = None; + self.dock = panels::default_layout(); + label_tab_menus(&mut self.dock); + if self.state.project.is_some() { + self.show_panel(Tab::Project); + } + } + Action::GoToSource { .. } + | Action::GoToSelectionSource + | Action::OpenPath(_) + | Action::ActivateTab(_) + | Action::GoToLine(_) + | Action::GoToScriptLine { .. } + | Action::OpenFileAt { .. } => { + // The file or line is shown in the editor, wherever its + // panel is. + self.show_panel(Tab::Editor); + self.state.execute(action); + } + Action::ShowOutline | Action::GoToDefinition | Action::FindReferences => { + self.show_panel(Tab::Navigation); + self.state.execute(action); + } + Action::OpenFolder | Action::OpenFolderPath(_) => { + self.state.execute(action); + if self.state.project.is_some() { + self.show_panel(Tab::Project); + } + } + Action::ConsoleSubmit(source) => { + self.show_panel(Tab::Console); + self.state.execute(Action::ConsoleSubmit(source)); + } + Action::ResetConsole => { + self.show_panel(Tab::Console); + self.state.execute(Action::ResetConsole); + } + other => self.state.execute(other), + } + } +} + +impl eframe::App for CqEditorApp { + fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { + let had_traceback = self.state.traceback.is_some(); + self.state.logic(ctx); + if !had_traceback && self.state.traceback.is_some() { + self.show_panel(Tab::Traceback); + } + } + + fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + let ctx = ui.ctx().clone(); + self.state.begin_frame(&ctx); + let palette = self.state.palette; + + let layout = self.maximized.as_ref().unwrap_or(&self.dock); + let open_panels: Vec = layout.iter_all_tabs().map(|(_, tab)| *tab).collect(); + self.state.editor_panel_open = open_panels.contains(&Tab::Editor); + let bar = |margin_y: i8| { + egui::Frame::NONE + .fill(palette.window) + .inner_margin(egui::Margin::symmetric(8, margin_y)) + }; + egui::Panel::top("menu_bar").frame(bar(2)).show(ui, |ui| { + crate::ui::menu_bar::ui(ui, &mut self.state, &open_panels, self.maximized.is_some()) + }); + egui::Panel::top("toolbar") + .frame(bar(3)) + .show(ui, |ui| crate::ui::toolbar::ui(ui, &mut self.state)); + egui::Panel::bottom("status_bar") + .frame(bar(3)) + .show(ui, |ui| crate::ui::status_bar::ui(ui, &self.state)); + egui::CentralPanel::default() + .frame( + egui::Frame::NONE + .fill(palette.window) + .inner_margin(egui::Margin::symmetric(4, 0)), + ) + .show(ui, |ui| { + let style = theme::dock_style(ui.style(), &palette); + DockArea::new(&mut self.dock) + .style(style) + .show_leaf_collapse_buttons(false) + .show_leaf_close_all_buttons(false) + .show_inside( + ui, + &mut TabContext { + state: &mut self.state, + frame, + maximized: self.maximized.is_some(), + }, + ); + }); + + // Closing the one panel shown maximized brings the layout back. + if self.maximized.is_some() && self.dock.iter_all_tabs().next().is_none() { + self.restore_layout(); + } + + dialogs::show(&ctx, &mut self.state); + if let worker::Status::Failed(reason) = self.state.worker.status() { + let problem = dialogs::PythonProblem { + problem: self.state.worker.problem(), + reason: reason.clone(), + python: self.state.worker.config().map(|c| c.python.clone()), + }; + // Looked for once, not on every frame. + let candidates = self + .state + .dialogs + .python_candidates + .get_or_insert_with(worker::launch::candidates); + let mut actions = Vec::new(); + dialogs::python_problem(&ctx, &problem, candidates, &mut actions); + self.state.queue(actions); + } + + for action in std::mem::take(&mut self.state.actions) { + log::debug!("action {action:?}"); + self.execute(action); + } + for url in take_requested_urls(&ctx) { + open_url(&url); + } + self.state.end_frame(&ctx); + } + + fn save(&mut self, storage: &mut dyn eframe::Storage) { + self.state.checkpoint_recovery(); + self.state.remember_all_breakpoints(); + self.state.remember_views(); + self.state.remember_session(); + eframe::set_value(storage, SETTINGS_KEY, &self.state.settings); + // The whole layout, not the one panel maximized. + let layout = self.maximized.as_ref().unwrap_or(&self.dock); + eframe::set_value(storage, LAYOUT_KEY, layout); + } + + fn on_exit(&mut self) { + logging::flush(); + } +} + +#[cfg(test)] +#[path = "../../tests/rust/app/test_app.rs"] +pub(crate) mod tests; + +/// `preferred`, or `preferred-2`, `-3`… when it exists and is not empty. +fn unused_folder(preferred: &Path) -> PathBuf { + let free = + |path: &Path| std::fs::read_dir(path).map_or(true, |mut entries| entries.next().is_none()); + if free(preferred) { + return preferred.to_path_buf(); + } + let name = preferred + .file_name() + .map_or_else(|| "environment".into(), |name| name.to_string_lossy()); + (2..) + .map(|n| preferred.with_file_name(format!("{name}-{n}"))) + .find(|path| free(path)) + .expect("a free folder") +} diff --git a/src/app/projects.rs b/src/app/projects.rs new file mode 100644 index 000000000..6d99395a8 --- /dev/null +++ b/src/app/projects.rs @@ -0,0 +1,271 @@ +//! The project folder: opening and closing it, its main script, and the +//! file operations of the Project panel, which keep the open tabs and what +//! is remembered of each file in step with the disk. + +use std::io; +use std::path::{Path, PathBuf}; + +use super::{AppState, StatusKind}; +use crate::dialogs::FilePrompt; +use crate::document::Document; +use crate::project::{self, Project}; +use crate::settings::ProjectState; + +impl AppState { + /// Asks for a folder and opens it as the project. + pub(super) fn choose_project_folder(&mut self) { + let mut dialog = rfd::FileDialog::new().set_title("Open Folder"); + let start = self + .project + .as_ref() + .map(|project| project.root().to_path_buf()) + .or_else(|| { + self.document + .path() + .and_then(Path::parent) + .map(Path::to_path_buf) + }); + if let Some(start) = start { + dialog = dialog.set_directory(start); + } + if let Some(folder) = dialog.pick_folder() { + self.open_project_folder(&folder); + } + } + + /// Opens `folder` as the project, reporting the outcome. + pub(super) fn open_project_folder(&mut self, folder: &Path) { + match self.open_project(folder) { + Ok(()) => { + let project = self.project.as_ref().expect("just opened"); + let main = project.main.as_deref().map_or_else(String::new, |main| { + format!("; F5 renders {}", project.relative(main).display()) + }); + let text = format!("Opened the folder {}{main}", project.name()); + self.set_status(StatusKind::Info, text); + } + Err(error) => self.dialogs.error( + "Cannot open folder", + format!("{}\n\n{error}", folder.display()), + ), + } + } + + /// Makes `folder` the project, with the main script and expanded + /// folders it had last time. A folder opened for the first time gets + /// the main script [`project::guess_main`] finds. + pub(super) fn open_project(&mut self, folder: &Path) -> io::Result<()> { + let mut project = Project::open(folder)?; + self.remember_project(); + match self.settings.project_state(project.root()) { + Some(state) => { + project.main = state.main.clone().filter(|main| main.is_file()); + project.restore_expanded(&state.expanded.clone()); + } + None => project.main = project::guess_main(project.root()), + } + if let Some(path) = self.document.path() { + project.reveal(path); + } + self.settings.project = Some(project.root().to_path_buf()); + self.project = Some(project); + self.remember_project(); + Ok(()) + } + + pub(super) fn close_project(&mut self) { + self.remember_project(); + self.project = None; + self.settings.project = None; + } + + /// Keeps the project's main script and expanded folders. + pub(super) fn remember_project(&mut self) { + if let Some(project) = &self.project { + self.settings.remember_project(ProjectState { + root: project.root().to_path_buf(), + main: project.main.clone(), + expanded: project.expanded(), + }); + } + } + + /// Makes `path` the script F5 runs while a project file is shown, or + /// lets F5 run the shown file again. + pub(super) fn set_main_script(&mut self, path: Option) { + let Some(project) = &mut self.project else { + return; + }; + let text = match &path { + Some(path) if !project.contains(path) => { + self.set_status( + StatusKind::Warning, + "The main script must be a file of the project folder", + ); + return; + } + Some(path) => format!( + "F5 now renders {} while a file of the project is shown", + project.relative(path).display() + ), + None => "F5 now renders the file shown".to_owned(), + }; + project.main = path; + self.remember_project(); + self.set_status(StatusKind::Info, text); + } + + /// Carries out a confirmed prompt of the Project panel. Returns the + /// error to show in the prompt, which then stays open. + pub fn confirm_file_prompt(&mut self, prompt: &FilePrompt) -> Option { + let result = match prompt { + FilePrompt::NewFile { folder, name, .. } => self.create_project_file(folder, name), + FilePrompt::NewFolder { folder, name, .. } => self.create_project_folder(folder, name), + FilePrompt::Rename { path, name, .. } => self.rename_project_path(path, name), + FilePrompt::Delete { path, .. } => self.delete_project_path(path), + }; + result.err() + } + + /// Creates a file in `folder` and opens it. Errors are for the prompt. + pub fn create_project_file(&mut self, folder: &Path, name: &str) -> Result<(), String> { + let path = project::create_file(folder, name).map_err(|error| error.to_string())?; + if let Some(project) = &mut self.project { + project.reveal(&path); + project.refresh(); + } + match Document::open(&path) { + Ok(document) => { + self.add_tab(document); + self.settings.add_recent_file(&path); + self.set_status(StatusKind::Success, format!("Created {}", path.display())); + } + Err(error) => self.set_status( + StatusKind::Warning, + format!( + "Created {}, which cannot be opened: {error}", + path.display() + ), + ), + } + Ok(()) + } + + pub fn create_project_folder(&mut self, folder: &Path, name: &str) -> Result<(), String> { + let path = project::create_folder(folder, name).map_err(|error| error.to_string())?; + if let Some(project) = &mut self.project { + project.reveal(&path); + if !project.is_expanded(&path) { + project.toggle(&path); + } + project.refresh(); + } + self.set_status(StatusKind::Success, format!("Created {}", path.display())); + Ok(()) + } + + /// Renames a file or folder. Open tabs, the main script, breakpoints, + /// named views and recent files follow it; unsaved edits stay unsaved. + pub fn rename_project_path(&mut self, path: &Path, name: &str) -> Result<(), String> { + let target = project::rename(path, name).map_err(|error| error.to_string())?; + // The views of the shown file are in the viewer, not yet remembered. + self.remember_views(); + self.remember_all_breakpoints(); + for generation in self + .documents_in_order() + .into_iter() + .map(|(g, _)| g) + .collect::>() + { + if let Some((document, _)) = self.open_mut(generation) + && let Some(moved) = document + .path() + .and_then(|open| project::relocated(open, path, &target)) + { + document.set_path(moved); + } + } + self.settings.relocate(path, &target); + if let Some(project) = &mut self.project { + project.relocate(path, &target); + } + self.remember_project(); + self.set_status( + StatusKind::Success, + format!("Renamed {} to {}", path.display(), target.display()), + ); + Ok(()) + } + + /// Open documents in or at `path` with unsaved changes. + pub fn unsaved_below(&self, path: &Path) -> Vec { + self.documents_in_order() + .into_iter() + .filter(|(_, document)| { + document.is_modified() && document.path().is_some_and(|open| open.starts_with(path)) + }) + .map(|(_, document)| document.display_name()) + .collect() + } + + /// Deletes a file, or a folder and everything in it, after the prompt + /// confirmed it. The open tabs of what was deleted close; their last + /// contents, and a deleted script, stay in the local history. + pub fn delete_project_path(&mut self, path: &Path) -> Result<(), String> { + if self + .project + .as_ref() + .is_some_and(|project| project.root() == path) + { + return Err("The project folder itself cannot be deleted here".to_owned()); + } + let below: Vec = self + .documents_in_order() + .into_iter() + .filter(|(_, document)| document.path().is_some_and(|open| open.starts_with(path))) + .map(|(generation, _)| generation) + .collect(); + let copies: Vec = below + .iter() + .filter_map(|&generation| self.document_of(generation).cloned()) + .collect(); + for document in &copies { + if let Err(error) = self.recovery.archive(document) { + log::warn!( + "Cannot keep {} in local history: {error}", + document.display_name() + ); + } + } + if path.is_file() + && let Err(error) = self.recovery.archive_path(path) + { + log::warn!("Cannot keep {} in local history: {error}", path.display()); + } + project::delete(path).map_err(|error| error.to_string())?; + for generation in below { + self.close_now(generation); + } + if let Some(project) = &mut self.project { + project.forget(path); + } + self.remember_project(); + self.set_status(StatusKind::Info, format!("Deleted {}", path.display())); + Ok(()) + } + + /// Opens the system's file manager on `path`'s folder. + pub(super) fn reveal_in_file_manager(&mut self, path: &Path) { + let folder = if path.is_dir() { + path + } else { + path.parent().unwrap_or(path) + }; + if let Err(error) = open::that(folder) { + self.set_status( + StatusKind::Error, + format!("Cannot open the file manager: {error}"), + ); + } + } +} diff --git a/src/app/runs.rs b/src/app/runs.rs new file mode 100644 index 000000000..ad27a5e02 --- /dev/null +++ b/src/app/runs.rs @@ -0,0 +1,618 @@ +//! Rendering and debugging the script. [`Execution`](super::execution) +//! decides; these methods send the requests and apply the results. +//! +//! A run executes the script F5 runs ([`AppState::run_target`]): the shown +//! document, or the project's main script. Its error line, debug line and +//! profile go to that document's editor, shown or not. + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Instant; + +use super::execution::{RunEnd, RunRequest, StopPlan}; +use super::{AppState, StatusKind}; +use crate::editor::text_ops::{self, Located}; +use crate::editor::{LineTiming, format_seconds}; +use crate::logging::{self, Level}; +use crate::parameters; +use crate::scene::{Overlay, RunScript, SceneNode}; +use crate::worker::protocol::{ + DebugAction, Request, RequestId, RunFinished, RunProfile, SceneNode as NodeMessage, +}; + +/// How long after the last parameter change the script renders again, in +/// seconds: a drag renders once it pauses, not on every pixel. +pub(super) const PARAMETER_RENDER_DELAY: f64 = 0.3; + +impl AppState { + /// Writes a parameter's new value into the script, as an undoable + /// edit, and renders again shortly after. + pub(super) fn set_parameter(&mut self, name: &str, line: usize, value: f64) { + if self.is_debugging() { + self.set_status( + StatusKind::Warning, + "Parameters can be changed once debugging ends", + ); + return; + } + let now = self.now(); + let target = self.run_target(); + let Some((document, editor)) = self.open_mut(target) else { + return; + }; + let Some(parameter) = parameters::parameters(&document.text) + .into_iter() + .find(|parameter| parameter.line == line && parameter.name == name) + else { + return; + }; + let literal = parameter.literal_for(value); + editor.adjust_text(document, parameter.literal, &literal, now); + self.parameter_render_at = Some(now + PARAMETER_RENDER_DELAY); + } + + /// Restores all modified parameters in the run target script to their + /// reference values in a single undo step and schedules a render. + pub(super) fn reset_parameters(&mut self) { + if self.is_debugging() { + self.set_status( + StatusKind::Warning, + "Parameters can be changed once debugging ends", + ); + return; + } + let now = self.now(); + let target = self.run_target(); + let Some((text, saved_text)) = self + .document_of(target) + .map(|document| (document.text.clone(), document.saved_text().to_owned())) + else { + return; + }; + let current = parameters::parameters(&text); + self.parameters.update_references(&saved_text, ¤t); + let mut replacements = Vec::new(); + for parameter in ¤t { + if self.parameters.is_modified(parameter) + && let Some(reference) = self.parameters.reference_value(¶meter.name) + { + let literal = parameter.literal_for(reference); + if text.get(parameter.literal.clone()) != Some(literal.as_str()) { + replacements.push((parameter.literal.clone(), literal)); + } + } + } + if replacements.is_empty() { + return; + } + if let Some((document, editor)) = self.open_mut(target) { + editor.replace_literals(document, &replacements, now); + self.parameter_render_at = Some(now + PARAMETER_RENDER_DELAY); + } + } + + /// Renders once the parameters stopped changing for a moment. + pub(super) fn poll_parameter_render(&mut self, ctx: &egui::Context) { + let Some(at) = self.parameter_render_at else { + return; + }; + let now = ctx.input(|input| input.time); + if now < at { + if let Ok(wait) = std::time::Duration::try_from_secs_f64(at - now) { + ctx.request_repaint_after(wait); + } + return; + } + self.parameter_render_at = None; + if !self.is_debugging() { + self.start_run(false); + } + } + + pub(super) fn start_run(&mut self, debug: bool) { + self.start_run_with(debug, false); + } + + /// Renders with the time of each line measured, shown in the gutter. + pub(super) fn start_profile(&mut self) { + if self.is_busy() { + self.set_status(StatusKind::Warning, "Already running; stop it first"); + return; + } + self.start_run_with(false, true); + } + + fn start_run_with(&mut self, debug: bool, profile: bool) { + let availability = self.worker.status().into(); + match self.execution.request_run(debug, availability) { + RunRequest::Start => {} + RunRequest::WhenReady => { + self.set_status(StatusKind::Info, "Waiting for Python to start…"); + return; + } + RunRequest::Unavailable => { + self.set_status( + StatusKind::Error, + "Python is not available — check Preferences > General", + ); + return; + } + RunRequest::Queued => return, + RunRequest::Busy => { + self.set_status(StatusKind::Warning, "Already running; stop it first"); + return; + } + } + + let target = self.prepare_run_target(); + let Some((document, editor)) = self.open_mut(target) else { + return; + }; + // A reload may have changed the text since the editor last drew. + editor.sync_markers(&document.text); + let script = document.text.clone(); + let path = document.path().map(|p| p.display().to_string()); + let (breakpoints, module_breakpoints) = self.open_breakpoints(target); + let project_root = self + .project + .as_ref() + .map(|project| project.root().display().to_string()); + let id = self.worker.next_id(); + // Pinned, so a debugging session may reference them even after it + // clears the view below. + let known_geometry = self.scene.known_geometry(); + self.scene.pin_geometry(id, &known_geometry); + self.run_script = Some(( + id, + Arc::new(RunScript { + document: target, + text: script.clone(), + }), + )); + let request = Request::Run { + id, + script, + path, + debug, + breakpoints, + project_root, + module_breakpoints, + settings: self.settings.run_settings(), + scene: self.settings.scene_settings(), + known_geometry, + profile, + }; + if !self.worker.send(&request) { + self.set_status(StatusKind::Error, "Cannot reach Python"); + return; + } + self.execution.started(id, debug); + self.selector_preview.clear(); + self.scene.clear_selector_preview(); + self.cad_checks.clear(); + self.cad_checks_document = Some(target); + self.scene.clear_preview(); + // The times of an earlier profile no longer describe the script. + self.clear_line_profiles(); + if profile { + self.set_status(StatusKind::Info, "Profiling…"); + } + if debug { + // Like the original: the view starts empty and follows the + // locals of each paused frame. + let removed = self.scene.clear(); + self.geometry_checks.clear(); + self.release(removed); + self.measurements.clear(); + self.selector.clear(); + self.set_status( + StatusKind::Info, + "Debugging — running to the first breakpoint", + ); + } + } + + /// The document the run `id` executes: the one it started with, or the + /// shown one. + pub(super) fn run_document(&self, id: RequestId) -> u64 { + self.run_script + .as_ref() + .filter(|(run, _)| *run == id) + .map_or(self.document_generation, |(_, script)| script.document) + } + + fn set_error_line(&mut self, document: u64, line: Option) { + if let Some((_, editor)) = self.open_mut(document) { + editor.error_line = line; + } + } + + pub(super) fn finish_run(&mut self, result: RunFinished) { + let RunEnd { stale, rerun } = self.execution.ended(result.id); + let target = self.run_document(result.id); + self.clear_debug_lines(); + + if stale { + self.scene.clear_preview(); + let keys = result.objects.into_iter().flatten().map(|node| node.key); + self.release(keys.collect()); + log::info!("Discarded the result of a run of the previous document"); + if rerun { + self.start_run(false); + } + return; + } + + self.cad_checks = result.checks; + self.cad_checks_document = Some(target); + let failed_checks = self.cad_checks.iter().filter(|check| !check.ok).count(); + + match &result.error { + Some(error) if result.interrupted => { + // Not an error: the user asked for it. + self.set_error_line(target, None); + let location = error + .line + .map(|line| format!(" at line {line}")) + .unwrap_or_default(); + self.set_status(StatusKind::Info, format!("Stopped{location}")); + logging::push(Level::Info, "script", &error.text); + } + Some(error) => { + self.set_error_line(target, error.line); + let location = error + .line + .map(|l| format!(" (line {l})")) + .unwrap_or_default(); + // Named when it is not the file shown. + let file = match self.document_of(target) { + Some(document) if target != self.document_generation => { + format!("{}: ", document.display_name()) + } + _ => String::new(), + }; + self.set_status( + StatusKind::Error, + format!("{file}{}: {}{location}", error.type_name, error.message), + ); + logging::push(Level::Error, "script", &error.text); + } + None => self.set_error_line(target, None), + } + let ok = result.ok; + self.traceback = result.error.filter(|_| !result.interrupted); + self.traceback_document = Some(target); + + if let Some(objects) = result.objects { + let preserved = self + .settings + .objects + .preserve_properties + .then(|| self.scene.snapshot_properties()); + let was_empty = self.scene.is_empty(); + let decoding = Instant::now(); + // A scene that cannot be decoded is reported, and the rest of + // the result (variables, a queued render) still applies. + if let Some(mut nodes) = self.decode_scene_nodes(Some(result.id), objects) { + self.scene.clear_preview(); + self.attach_run_script(result.id, &mut nodes); + if let Some(timings) = &result.timings { + log::info!("{}", timings.report(&result.receipt, decoding.elapsed())); + } + let count = nodes.len(); + if self.settings.objects.clear_before_run || result.debug { + let removed = self.scene.replace(nodes, preserved.as_ref()); + self.geometry_checks.clear(); + self.release(removed); + self.measurements.clear(); + self.selector.clear(); + } else { + self.scene.append(nodes, preserved.as_ref()); + } + self.scene.overlay = Overlay::default(); + self.refresh_inspector(); + if self.settings.viewer.fit_automatically || was_empty { + let animate = self.settings.viewer.animate && !was_empty; + self.viewer.fit(&self.scene, animate, self.now()); + } + if ok { + let plural = if count == 1 { "" } else { "s" }; + let rendered = format!( + "Rendered {count} object{plural} in {:.2} s", + result.duration + ); + match self.unsaved_modules(target).as_slice() { + [] => self.set_status(StatusKind::Success, rendered), + unsaved => self.set_status( + StatusKind::Warning, + format!( + "{rendered}; unsaved changes to {} were not used, save them first", + unsaved.join(", ") + ), + ), + } + } + } + } + self.scene.clear_preview(); + if let Some(variables) = result.variables { + self.variables = variables; + } + if result.stopped { + self.set_status(StatusKind::Info, "Debugging stopped"); + } + if result.cancelled { + self.set_status( + StatusKind::Info, + "Meshing cancelled; the model shown before stays", + ); + } + if ok && !result.cancelled && failed_checks > 0 { + self.set_status( + StatusKind::Warning, + format!("{failed_checks} CAD requirement(s) failed — see Checks"), + ); + } + if let Some(profile) = result.profile { + self.show_profile(result.id, profile); + } + if ok { + // The script may have started importing other modules. + self.request_imports(); + } + if rerun { + self.start_run(false); + } + } + + /// A run of the worker failed before it could finish. + pub(super) fn run_failed(&mut self, id: RequestId, message: String) { + let RunEnd { stale, rerun } = self.execution.ended(id); + self.scene.clear_preview(); + self.clear_debug_lines(); + if stale { + log::warn!("A run of the previous document failed: {message}"); + } else { + self.set_status(StatusKind::Error, message); + } + if rerun { + self.start_run(false); + } + } + + pub(super) fn debug_command(&mut self, action: DebugAction) { + let Some(id) = self.execution.resume() else { + return; + }; + let target = self.run_document(id); + let (breakpoints, module_breakpoints) = self.open_breakpoints(target); + let sent = self.worker.send(&Request::Debug { + action, + breakpoints, + module_breakpoints, + }); + self.clear_debug_lines(); + if !sent { + self.execution.ended(id); + self.set_status( + StatusKind::Warning, + "The debugging session ended when Python disconnected", + ); + } + } + + pub(super) fn stop_debugging(&mut self) { + if self.is_paused() { + self.debug_command(DebugAction::Stop); + } else { + self.stop(); + } + } + + /// Aborts a running script by restarting the worker. + /// Stops the running script or console command gently: Python raises + /// `KeyboardInterrupt` in it, so the console and the caches survive. + /// Python is restarted when Stop is pressed again, or when the script + /// does not stop within `STOP_GRACE` (native code that never returns + /// to Python). A paused debugging session ends through the debugger. + pub(super) fn stop(&mut self) { + if self.is_paused() { + self.debug_command(DebugAction::Stop); + return; + } + match self.execution.stop(Instant::now()) { + StopPlan::Nothing => {} + StopPlan::Interrupt(target) => { + if self.worker.send(&Request::Interrupt { target }) { + self.set_status(StatusKind::Info, "Stopping… (Stop again to restart Python)"); + } else { + self.restart_to_stop("Execution stopped; Python was restarted"); + } + } + StopPlan::Restart => self.restart_to_stop("Execution stopped; Python was restarted"), + } + } + + /// Restarts Python once an interrupted script has had `STOP_GRACE` to + /// stop, and wakes the UI for that moment. + pub(super) fn poll_stop(&mut self, ctx: &egui::Context) { + let Some(deadline) = self.execution.stop_deadline() else { + return; + }; + let now = Instant::now(); + if now >= deadline { + self.restart_to_stop("The script did not stop; Python was restarted"); + } else { + ctx.request_repaint_after(deadline - now); + } + } + + fn restart_to_stop(&mut self, message: &str) { + self.start_worker(); + self.set_status(StatusKind::Warning, message); + } + + /// Puts a profiled run's times in the gutter, on the lines of the + /// document as it is now. + fn show_profile(&mut self, id: RequestId, profile: RunProfile) { + let Some((target, run_text)) = self + .run_script + .as_ref() + .filter(|(run, _)| *run == id) + .map(|(_, script)| (script.document, script.text.clone())) + else { + return; + }; + let mut by_file: BTreeMap, BTreeMap> = BTreeMap::new(); + for line in profile.lines { + by_file.entry(line.file).or_default().insert( + line.line, + LineTiming { + seconds: line.seconds, + hits: line.hits, + operations: Vec::new(), + }, + ); + } + for operation in profile.operations { + if let Some(timing) = by_file + .get_mut(&operation.file) + .and_then(|lines| lines.get_mut(&operation.line)) + { + timing + .operations + .push((operation.name, operation.seconds, operation.calls)); + } + } + let mut slowest: Option<(String, usize, f64)> = None; + for (file, lines) in by_file { + let generation = match file.as_deref() { + Some(path) => self.find_open(std::path::Path::new(path)), + None => Some(target), + }; + let Some(generation) = generation else { + continue; + }; + let source = match file.as_deref() { + Some(path) => profile + .sources + .get(path) + .cloned() + .or_else(|| std::fs::read_to_string(path).ok()), + None => Some(run_text.clone()), + }; + let Some((document, editor)) = self.open_mut(generation) else { + continue; + }; + let source = source.unwrap_or_else(|| document.text.clone()); + editor.set_line_profile(lines, &source, &document.text); + if let Some((line, timing)) = editor + .line_profile + .iter() + .max_by(|a, b| a.1.seconds.total_cmp(&b.1.seconds)) + && slowest + .as_ref() + .is_none_or(|(_, _, seconds)| timing.seconds > *seconds) + { + let label = file + .as_deref() + .and_then(|path| std::path::Path::new(path).file_name()) + .map_or_else( + || document.display_name(), + |name| name.to_string_lossy().into_owned(), + ); + slowest = Some((label, *line, timing.seconds)); + } + } + if let Some((file, line, seconds)) = slowest { + let text = format!( + "Profiled: the slowest line is {file}:{line} ({}); times are in the gutters", + format_seconds(seconds) + ); + self.set_status(StatusKind::Success, text); + } + } + + /// Gives the nodes of a run the script text their lines refer to. + pub(super) fn attach_run_script(&self, id: RequestId, nodes: &mut [SceneNode]) { + if let Some((run, script)) = &self.run_script + && *run == id + { + for node in nodes { + node.attach_script(script); + } + } + } + + /// Moves the editor to the script line that created an object, or one + /// step of its construction stack in the CQ Inspector, following the + /// edits made since the run. + pub(super) fn go_to_source(&mut self, key: &str, step: Option<(usize, Option)>) { + let Some(node) = self.scene.find(key) else { + return; + }; + let line = match step { + None => node.line, + Some(_) if self.inspector.key.as_deref() != Some(key) => None, + Some((frame, item)) => { + let frame = self.inspector.frames.get(frame); + match item { + None => frame.and_then(|frame| frame.line), + Some(item) => frame + .and_then(|frame| frame.items.get(item)) + .and_then(|item| item.line), + } + } + }; + let (Some(line), Some(script)) = (line, node.script.clone()) else { + self.set_status( + StatusKind::Info, + "No script line is known for this object (objects shown from the console have none)", + ); + return; + }; + // Its script is shown, in whichever tab it is. + if !self.activate(script.document) { + self.set_status( + StatusKind::Warning, + "This object comes from another script, which is no longer open; render again \ + to go to its source", + ); + return; + } + let Some(located) = text_ops::locate_line(&script.text, line, &self.document.text) else { + self.set_status( + StatusKind::Warning, + format!("Line {line} was deleted since the last run"), + ); + return; + }; + self.editor.go_to_line(&self.document.text, located.line()); + match located { + Located::Unchanged(at) => self.set_status(StatusKind::Info, format!("Line {at}")), + Located::Moved(at) => self.set_status( + StatusKind::Info, + format!("Line {at} (line {line} when the script ran)"), + ), + Located::Changed(at) => self.set_status( + StatusKind::Warning, + format!("Line {at}: edited since the last run"), + ), + } + } + + pub(super) fn decode_scene_nodes( + &mut self, + request: Option, + objects: Vec, + ) -> Option> { + match self.scene.decode_nodes(request, objects) { + Ok(nodes) => Some(nodes), + Err(error) => { + log::error!("Cannot decode worker scene: {error}"); + self.set_status(StatusKind::Error, "Cannot update the 3D scene"); + None + } + } + } +} diff --git a/src/app/services.rs b/src/app/services.rs new file mode 100644 index 000000000..6f83bb002 --- /dev/null +++ b/src/app/services.rs @@ -0,0 +1,798 @@ +//! Requests on behalf of the editor and the panels: completion, selection, +//! measurement, the CQ inspector, export, screenshots, console and upload. + +use std::path::{Path, PathBuf}; + +use super::execution::Pending; +use super::{AppState, StatusKind}; +use crate::editor::{CompletionRequest, HoverRequest}; +use crate::panels::{EntryKind, SelectorUse}; +use crate::scene::{NodeKey, Overlay, TopologySelection}; +use crate::worker::protocol::{ + CompletionTarget, ConsoleSelection, ExportFormat, InterferenceReport, NavigationMode, Request, + SelectorCandidate, TopologyReference, +}; + +#[derive(Clone)] +pub(super) struct ExportJob { + pub keys: Vec, + pub format: ExportFormat, + pub path: String, + pub tolerance: f64, + pub angular_tolerance: f64, + pub step_mode: String, + pub step_schema: String, + pub stl_ascii: bool, + pub flat_parts: bool, + pub unit: String, +} + +impl AppState { + pub(crate) fn request_outline(&mut self) { + if !self.worker.is_ready() || self.is_busy() { + return; + } + let source = self.document.text.clone(); + let id = self.worker.next_id(); + if self.worker.send(&Request::Outline { + id, + source: source.clone(), + }) { + self.execution.track( + id, + Pending::Outline { + document: self.document_generation, + }, + ); + self.navigation.document = self.document_generation; + self.navigation.source = source; + self.navigation.outline_request = Some(id); + self.navigation.symbols.clear(); + self.navigation.locations.clear(); + self.navigation.mode = None; + } + } + + pub(super) fn request_navigation(&mut self, mode: NavigationMode) { + if !self.worker.is_ready() || self.is_busy() { + self.set_status( + StatusKind::Info, + "Code navigation is available when Python is ready", + ); + return; + } + let (line, column) = self.editor.cursor_position(&self.document.text); + let source = self.document.text.clone(); + let path = self.document.path().map(|p| p.display().to_string()); + let project_root = self + .project + .as_ref() + .map(|p| p.root().display().to_string()); + let id = self.worker.next_id(); + if self.worker.send(&Request::Navigate { + id, + source, + line, + column, + path, + project_root, + mode, + }) { + self.execution.track( + id, + Pending::Navigate { + document: self.document_generation, + }, + ); + self.navigation.document = self.document_generation; + self.navigation.mode = Some(mode); + self.navigation.navigation_request = Some(id); + self.navigation.navigation_source = self.document.text.clone(); + self.navigation.navigation_document = self.document_generation; + self.navigation.locations.clear(); + self.navigation.truncated = false; + } + } + + /// Schedule a preview only for the unchanged script that produced the scene. + pub(super) fn update_selector_preview_cursor(&mut self) { + let run = self.run_script.as_ref().and_then(|(id, script)| { + (script.document == self.document_generation && script.text == self.document.text) + .then_some(*id) + }); + if !self.worker.is_ready() + || self.scene.is_empty() + || self.execution.phase() != super::execution::Phase::Idle + { + self.selector_preview.clear(); + self.scene.clear_selector_preview(); + return; + } + let Some(run_id) = run else { + self.selector_preview.clear(); + self.scene.clear_selector_preview(); + return; + }; + let (line, column) = self.editor.cursor_position(&self.document.text); + let cursor = (run_id, line, column); + if self.selector_preview.cursor == Some(cursor) { + return; + } + self.selector_preview.clear(); + self.scene.clear_selector_preview(); + self.selector_preview.cursor = Some(cursor); + self.selector_preview.due_at = Some(self.now() + 0.15); + self.ctx + .request_repaint_after(std::time::Duration::from_millis(160)); + } + + /// Debounce caret motion so a rapid series of arrows sends one worker request. + pub(super) fn poll_selector_preview(&mut self, ctx: &egui::Context) { + let Some(due) = self.selector_preview.due_at else { + return; + }; + if self.now() < due { + ctx.request_repaint_after(std::time::Duration::from_millis(20)); + return; + } + if self.execution.phase() != super::execution::Phase::Idle || !self.worker.is_ready() { + self.selector_preview.due_at = Some(self.now() + 0.15); + ctx.request_repaint_after(std::time::Duration::from_millis(160)); + return; + } + self.selector_preview.due_at = None; + let Some((run_id, line, column)) = self.selector_preview.cursor else { + return; + }; + let id = self.worker.next_id(); + let preferred_key = self.scene.current().map(|node| node.key.clone()); + if self.worker.send(&Request::SelectorPreview { + id, + run_id, + line, + column, + preferred_key, + }) { + self.execution.track(id, Pending::SelectorPreview); + self.selector_preview.request_id = Some(id); + } + } + // -- editor services ---------------------------------------------------------- + + pub(super) fn request_completion(&mut self, request: CompletionRequest) { + if !self.worker.is_ready() { + return; + } + let source = self.document.text.clone(); + let path = self.document.path().map(|p| p.display().to_string()); + let automatic = request.automatic; + let document = self.document_generation; + self.send_tracked( + Pending::Completion { + automatic, + document, + }, + |id| Request::Complete { + id, + source, + line: request.line, + column: request.column, + path, + target: CompletionTarget::Editor, + }, + ); + } + + /// Asks for the documentation of the name under the editor's pointer. + pub(super) fn request_description(&mut self, request: HoverRequest) { + if !self.worker.is_ready() || self.is_busy() { + return; + } + let source = self.document.text.clone(); + let path = self.document.path().map(|p| p.display().to_string()); + let document = self.document_generation; + self.send_tracked(Pending::Describe { document }, |id| Request::Describe { + id, + source, + line: request.line, + column: request.column, + path, + }); + } + + // -- objects and inspection ------------------------------------------------- + + pub(super) fn select( + &mut self, + key: Option, + topology: Option, + extend: bool, + ) { + match (key, topology) { + (Some(key), Some(selection)) => { + if extend { + self.scene.ensure_selected(&key); + } else { + self.scene.select_only(&key); + } + let entity = selection.entity; + let node = selection.node.clone(); + let part_index = selection.part; + if self.scene.select_topology(selection, extend) { + let count = self.scene.topology_selections.len(); + if count == 0 { + self.set_status(StatusKind::Info, "Entity selection cleared"); + } else { + let name = self + .scene + .find(&node) + .map_or(node.as_str(), |node| node.name.as_str()); + let entity_label = self + .scene + .find(&node) + .and_then(|scene_node| scene_node.parts.get(part_index)) + .and_then(|part| { + part.face_attributes.iter().find(|face| { + entity.kind() == "Face" && face.id == entity.identifier() + }) + }) + .and_then(|face| face.name.clone()) + .unwrap_or_else(|| { + format!("{} {}", entity.kind(), entity.identifier()) + }); + let plural = if count == 1 { "entity" } else { "entities" }; + self.set_status( + StatusKind::Info, + format!( + "Selected {entity_label} of {name} · {count} {plural} selected" + ), + ); + } + } + } + (Some(key), None) if extend => self.scene.toggle_selected(&key), + (Some(key), None) => self.scene.select_only(&key), + (None, _) if !extend => self.scene.clear_selection(), + (None, _) => {} + } + self.request_topology_results(); + self.refresh_inspector(); + } + + /// What the console's `selected()` returns: the picked entities, or + /// the selected objects. + pub(super) fn console_selection(&self) -> ConsoleSelection { + ConsoleSelection { + entities: self.topology_references(), + objects: self.scene.selected_roots(), + } + } + + /// The selected entities as the worker names them. + fn topology_references(&self) -> Vec { + self.scene + .topology_selections + .iter() + .map(|selection| TopologyReference { + key: selection.node.clone(), + part: selection.part, + kind: selection.entity.topology_kind(), + identifier: selection.entity.identifier(), + }) + .collect() + } + + /// Measures the topology selection and finds its selector, or clears + /// both when nothing is selected. + pub(super) fn request_topology_results(&mut self) { + self.request_measurement(); + self.request_selector(); + } + + /// What the Measurements panel measures: the picked entities, else the + /// selected objects. + pub(super) fn measured(&self) -> (Vec, Vec) { + let selections = self.topology_references(); + let objects = if selections.is_empty() { + self.scene.selected_roots() + } else { + Vec::new() + }; + (selections, objects) + } + + fn request_measurement(&mut self) { + let (selections, objects) = self.measured(); + if (selections.is_empty() && objects.is_empty()) || !self.worker.is_ready() { + self.measurements.clear(); + return; + } + let id = self.worker.next_id(); + if self.worker.send(&Request::Measure { + id, + selections, + objects, + }) { + self.execution.track(id, Pending::Measure); + self.measurements.loading = true; + self.measurements.error = None; + self.measurements.request_id = Some(id); + } else { + self.measurements.loading = false; + self.measurements.error = Some("Cannot reach Python".to_owned()); + self.measurements.request_id = None; + } + } + + /// Copies the current measurement values to the clipboard as structured + /// text, JSON or CSV. + pub(super) fn copy_measurement(&mut self, format: crate::commands::MeasurementFormat) { + let Some(result) = &self.measurements.result else { + self.set_status( + StatusKind::Warning, + "Select objects, or pick faces, edges or vertices, to measure", + ); + return; + }; + let formatted = crate::panels::format_measurement( + result, + &self.scene, + self.settings.viewer.units, + format, + ); + self.ctx.copy_text(formatted); + self.set_status( + StatusKind::Success, + format!("Copied the measurement as {}", format.label()), + ); + } + + /// Asks for code repeating the current measurement; it goes to the + /// clipboard when it arrives. + pub(super) fn request_measurement_code(&mut self) { + let (selections, objects) = self.measured(); + if selections.is_empty() && objects.is_empty() { + self.set_status( + StatusKind::Warning, + "Select objects, or pick faces, edges or vertices, to measure", + ); + return; + } + if self.send_tracked(Pending::MeasurementCode, |id| Request::MeasurementCode { + id, + selections, + objects, + }) { + self.set_status( + StatusKind::Info, + "Writing and checking the measurement code…", + ); + } + } + + /// The code of a measurement arrived: to the clipboard, with a warning + /// unless the worker reproduced every value with it. + pub(super) fn measurement_code_arrived( + &mut self, + code: String, + verified: bool, + problem: Option, + ) { + self.ctx.copy_text(code); + if verified { + self.set_status( + StatusKind::Success, + "Copied the measurement as code (checked: it reproduces every value)", + ); + } else { + let why = problem.unwrap_or_else(|| "it could not be checked".to_owned()); + self.set_status( + StatusKind::Warning, + format!("Copied the measurement as code, but {why}"), + ); + } + } + + fn request_selector(&mut self) { + // A Copy or Insert asked for the previous selection does not apply + // to this one. + self.selector.clear(); + if self.scene.topology_selections.is_empty() || !self.worker.is_ready() { + return; + } + let selections = self.topology_references(); + let id = self.worker.next_id(); + if self.worker.send(&Request::Selector { id, selections }) { + self.execution.track(id, Pending::Selector); + self.selector.loading = true; + self.selector.request_id = Some(id); + } else { + self.selector.error = Some("Cannot reach Python".to_owned()); + } + } + + /// Copies or inserts the selector of the topology selection, once it is + /// known. + pub(super) fn use_selector(&mut self, usage: SelectorUse) { + if self.scene.topology_selections.is_empty() { + self.set_status( + StatusKind::Warning, + "Pick faces, edges or vertices first (Face, Edge or Vertex selection mode)", + ); + return; + } + if let Some(candidate) = self.selector.candidate().cloned() { + self.apply_selector(usage, &candidate); + } else if self.selector.loading { + self.selector.then = Some(usage); + self.set_status(StatusKind::Info, "Finding a selector…"); + } else if let Some(error) = self.selector.error.clone() { + self.set_status(StatusKind::Warning, error); + } else { + self.request_selector(); + if self.selector.loading { + self.selector.then = Some(usage); + } + } + } + + pub(super) fn apply_selector(&mut self, usage: SelectorUse, candidate: &SelectorCandidate) { + let expression = &candidate.expression; + let caution = if candidate.index_based { + " (by index: it may select another entity once the model changes)" + } else { + "" + }; + match usage { + SelectorUse::Copy => { + self.ctx.copy_text(expression.clone()); + self.set_status(StatusKind::Success, format!("Copied {expression}{caution}")); + } + SelectorUse::Insert => { + self.editor.insert_text(&mut self.document, expression); + self.set_status( + StatusKind::Success, + format!("Inserted {expression}{caution}"), + ); + } + } + } + + /// Inspects the current object when it is a workplane. + pub(super) fn refresh_inspector(&mut self) { + let target = self + .scene + .current() + .filter(|node| node.inspectable) + .map(|node| (node.key.clone(), node.name.clone())); + match target { + Some((key, name)) => { + if self.inspector.key.as_deref() == Some(key.as_str()) { + return; + } + self.inspector.clear(); + self.scene.overlay = Overlay::default(); + self.inspector.key = Some(key.clone()); + self.inspector.name = name; + self.inspector.loading = + self.send_tracked(Pending::Inspect, |id| Request::Inspect { id, key }); + } + None => { + let gone = self + .inspector + .key + .as_ref() + .is_some_and(|key| self.scene.find(key).is_none()); + if gone { + self.inspector.clear(); + self.scene.overlay = Overlay::default(); + } + } + } + } + + pub(super) fn toggle_inspect(&mut self) { + self.inspector.show_in_view = !self.inspector.show_in_view; + if self.inspector.show_in_view { + self.request_inspection_geometry(); + } else { + self.scene.overlay = Overlay::default(); + } + } + + pub(super) fn request_inspection_geometry(&mut self) { + let (Some(key), Some(entry)) = (self.inspector.key.clone(), self.inspector.selected) else { + return; + }; + let scene = self.settings.scene_settings(); + let (frame, item) = entry; + let request_key = key.clone(); + self.send_tracked(Pending::InspectGeometry { key, entry }, |id| { + Request::InspectGeometry { + id, + key: request_key, + frame, + item, + scene, + } + }); + } + + /// The selection, or everything when nothing is selected. + fn objects_to_process(&self) -> Vec { + let selected = self.scene.selected_roots(); + if selected.is_empty() { + self.scene.top_level_keys() + } else { + selected + } + } + + pub(super) fn export(&mut self, format: ExportFormat) { + if self.scene.top_level_keys().is_empty() { + self.set_status(StatusKind::Warning, "Nothing to export"); + return; + } + let mut options = crate::dialogs::ExportDialog::new( + format, + self.settings.objects.stl_tolerance, + self.settings.objects.stl_angular_tolerance, + self.settings.viewer.units, + ); + if !self.scene.selected_roots().is_empty() { + options.scope = crate::dialogs::ExportScope::Selection; + } + self.dialogs.export = Some(options); + } + + pub(crate) fn export_confirmed(&mut self, options: crate::dialogs::ExportDialog) { + use crate::dialogs::ExportScope; + let keys = match options.scope { + ExportScope::Selection => self.scene.selected_roots(), + ExportScope::Visible => self + .scene + .visible_nodes() + .into_iter() + .filter(|node| !node.parts.is_empty()) + .map(|node| node.key.clone()) + .collect(), + ExportScope::Everything => self.scene.top_level_keys(), + }; + if keys.is_empty() { + self.set_status(StatusKind::Warning, "Nothing to export in the chosen scope"); + return; + } + let format = options.format; + // Named after the script that made the model. + let stem = self + .run_target_path() + .as_deref() + .and_then(Path::file_stem) + .map_or_else(|| "model".to_owned(), |s| s.to_string_lossy().into_owned()); + let Some(mut path) = rfd::FileDialog::new() + .add_filter(format.label(), &[format.extension()]) + .set_file_name(format!("{stem}.{}", format.extension())) + .save_file() + else { + return; + }; + if path.extension().is_none() { + path.set_extension(format.extension()); + } + let (tolerance, angular_tolerance) = (options.tolerance, options.angular_tolerance); + if !tolerance.is_finite() + || tolerance <= 0.0 + || !angular_tolerance.is_finite() + || angular_tolerance <= 0.0 + { + self.dialogs.error( + "Cannot export", + "Tolerances must be finite positive numbers.", + ); + return; + } + self.export_job = Some(ExportJob { + keys, + format, + path: path.display().to_string(), + tolerance, + angular_tolerance, + step_mode: if options.step_fused { + "fused" + } else { + "default" + } + .into(), + step_schema: if options.step_ap242 { "ap242" } else { "ap214" }.into(), + stl_ascii: options.stl_ascii, + flat_parts: options.scope == ExportScope::Visible, + unit: options.unit.export_code().to_owned(), + }); + if self.send_export("check") { + self.set_status(StatusKind::Info, format!("Exporting {}…", path.display())); + } + } + + fn send_export(&mut self, on_invalid: &str) -> bool { + let Some(job) = self.export_job.clone() else { + return false; + }; + let on_invalid = on_invalid.to_owned(); + self.send_tracked(Pending::Export, |id| Request::Export { + id, + keys: job.keys, + format: job.format, + path: job.path, + tolerance: job.tolerance, + angular_tolerance: job.angular_tolerance, + step_mode: job.step_mode, + step_schema: job.step_schema, + stl_ascii: job.stl_ascii, + flat_parts: job.flat_parts, + unit: job.unit, + on_interference: if on_invalid == "ignore" { + "ignore" + } else { + "check" + } + .to_owned(), + on_invalid, + }) + } + + pub(crate) fn resolve_geometry_export(&mut self, choice: crate::dialogs::GeometryChoice) { + match choice { + crate::dialogs::GeometryChoice::Cancel => self.export_job = None, + crate::dialogs::GeometryChoice::ExportAnyway => { + self.send_export("ignore"); + } + crate::dialogs::GeometryChoice::TryFix => { + self.send_export("fix"); + } + crate::dialogs::GeometryChoice::SelectPair(_) => {} + } + } + + pub(crate) fn show_interference(&mut self, pair: &InterferenceReport) { + self.scene.overlay = Overlay::default(); + if pair.kind != "interference" { + return; + } + let first = pair.first.clone(); + let second = pair.second.clone(); + let scene = self.settings.scene_settings(); + self.send_tracked( + Pending::InterferenceGeometry { + first: first.clone(), + second: second.clone(), + }, + |id| Request::InterferenceGeometry { + id, + first, + second, + scene, + }, + ); + } + + pub(super) fn check_geometry(&mut self) { + let keys = self.objects_to_process(); + if keys.is_empty() { + self.set_status(StatusKind::Warning, "Nothing to check"); + return; + } + if self.send_tracked(Pending::Check, |id| Request::Check { + id, + keys, + flat_parts: false, + }) { + self.set_status(StatusKind::Info, "Checking geometry…"); + } + } + + pub(super) fn save_image(&mut self) { + if self.viewer.turntable_progress().is_some() { + self.set_status(StatusKind::Info, "Wait for the turntable export to finish"); + return; + } + if let Some(path) = ask_png_path("screenshot.png") { + self.viewer + .request_image(path, self.dialogs.capture.options); + } + } + + pub(super) fn copy_image(&mut self) { + if self.viewer.turntable_progress().is_some() { + self.set_status(StatusKind::Info, "Wait for the turntable export to finish"); + return; + } + self.viewer + .request_clipboard_image(self.dialogs.capture.options); + } + + pub(super) fn export_turntable(&mut self) { + let Some(path) = ask_png_path("turntable.png") else { + return; + }; + let (options, turntable) = (self.dialogs.capture.options, self.dialogs.capture.turntable); + match self.viewer.start_turntable(path, options, turntable) { + Ok(()) => self.set_status(StatusKind::Info, "Exporting the turntable…"), + Err(error) => self.dialogs.error("Capture failed", error), + } + } + + pub(super) fn console_submit(&mut self, source: String) { + if !self.worker.is_ready() { + self.console + .push(EntryKind::Error, "Python is not running\n"); + return; + } + self.console.record_input(&source); + let scene = self.settings.scene_settings(); + let known_geometry = self.scene.known_geometry(); + let selection = self.console_selection(); + let mut sent = None; + if self.send_tracked(Pending::Console, |id| { + sent = Some(id); + Request::Console { + id, + source, + scene, + known_geometry: known_geometry.clone(), + selection, + } + }) { + if let Some(id) = sent { + self.scene.pin_geometry(id, &known_geometry); + } + } else { + self.console.busy = false; + } + } + + pub(super) fn console_complete(&mut self) { + let source = self.console.input.clone(); + let line = source.split('\n').count(); + let column = source + .rsplit('\n') + .next() + .map_or(0, |last| last.chars().count()); + self.send_tracked(Pending::ConsoleCompletion, |id| Request::Complete { + id, + source, + line, + column, + path: None, + target: CompletionTarget::Console, + }); + } + + pub(super) fn start_upload(&mut self, url: String, file_type: String) { + let keys = self.objects_to_process(); + let source = self + .document_of(self.run_target()) + .map_or_else(String::new, |document| document.text.clone()); + if !self.send_tracked(Pending::Upload, |id| Request::Upload { + id, + url, + file_type, + keys, + source, + }) && let Some(upload) = &mut self.dialogs.upload + { + upload.failed("Python is not ready"); + } + } +} + +/// Where to save a PNG, from the save dialog (`.png` added when missing). +fn ask_png_path(file_name: &str) -> Option { + let mut path = rfd::FileDialog::new() + .add_filter("PNG image", &["png"]) + .set_file_name(file_name) + .save_file()?; + if path.extension().is_none() { + path.set_extension("png"); + } + Some(path) +} diff --git a/src/app/tabs.rs b/src/app/tabs.rs new file mode 100644 index 000000000..6898aadd5 --- /dev/null +++ b/src/app/tabs.rs @@ -0,0 +1,661 @@ +//! The editor tabs: the documents open besides the one shown, switching +//! between them, closing them, the session they are restored from, and the +//! script F5 runs. +//! +//! The shown tab's document and editor are `AppState::document` and +//! `AppState::editor`, so everything that works on "the document" works on +//! the one the user sees. The other tabs wait in [`EditorTabs`], each with +//! its own editor (caret, scrolling, undo history, breakpoints), until they +//! are shown again. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use super::{AppState, StatusKind}; +use crate::dialogs::Intent; +use crate::document::{Document, is_not_utf8}; +use crate::editor::CodeEditor; +use crate::project; +use crate::worker::protocol::DebugAction; + +/// A document open in a tab that is not shown, with its editor. +struct Parked { + document: Document, + editor: CodeEditor, + generation: u64, +} + +/// The open tabs other than the shown one, and the order of all of them. +pub struct EditorTabs { + /// The generation of every open document, in tab order. + order: Vec, + parked: Vec, + next_generation: u64, +} + +impl EditorTabs { + /// The tabs of a session that starts with the document `generation`. + pub fn new(generation: u64) -> Self { + Self { + order: vec![generation], + parked: Vec::new(), + next_generation: generation + 1, + } + } +} + +/// A tab, as the tab strip and the menus show it. +#[derive(Clone, Debug, PartialEq)] +pub struct TabInfo { + pub generation: u64, + /// The file name, with its folder when another tab has the same name. + pub name: String, + pub path: Option, + pub modified: bool, + pub active: bool, + /// The project's main script, which F5 runs. + pub main: bool, +} + +/// The egui id of the editor of the document `generation`. +fn editor_id(generation: u64) -> egui::Id { + egui::Id::new(("code_editor_text", generation)) +} + +impl AppState { + /// The open tabs, in order. + pub fn tabs(&self) -> Vec { + let main = self.project.as_ref().and_then(|p| p.main.as_deref()); + let mut tabs: Vec = self + .documents_in_order() + .into_iter() + .map(|(generation, document)| TabInfo { + generation, + name: document.display_name(), + path: document.path().map(Path::to_path_buf), + modified: document.is_modified(), + active: generation == self.document_generation, + main: main.is_some() && document.path() == main, + }) + .collect(); + let names: Vec = tabs.iter().map(|tab| tab.name.clone()).collect(); + for tab in &mut tabs { + let twins = names.iter().filter(|name| **name == tab.name).count(); + if twins > 1 + && let Some(folder) = tab.path.as_deref().and_then(Path::parent) + && let Some(folder) = folder.file_name() + { + tab.name = format!("{} — {}", tab.name, folder.to_string_lossy()); + } + } + tabs + } + + /// Every open document, the shown one first. + fn open_documents(&self) -> impl Iterator { + std::iter::once((self.document_generation, &self.document)).chain( + self.tabs + .parked + .iter() + .map(|parked| (parked.generation, &parked.document)), + ) + } + + /// Every open document, in tab order. + pub(super) fn documents_in_order(&self) -> Vec<(u64, &Document)> { + let mut documents: Vec<_> = self.open_documents().collect(); + let position = |generation: u64| { + self.tabs + .order + .iter() + .position(|&g| g == generation) + .unwrap_or(usize::MAX) + }; + documents.sort_by_key(|(generation, _)| position(*generation)); + documents + } + + pub fn document_of(&self, generation: u64) -> Option<&Document> { + self.open_documents() + .find(|(g, _)| *g == generation) + .map(|(_, document)| document) + } + + /// The document `generation` and its editor, shown or not. + pub(super) fn open_mut(&mut self, generation: u64) -> Option<(&mut Document, &mut CodeEditor)> { + if generation == self.document_generation { + return Some((&mut self.document, &mut self.editor)); + } + self.tabs + .parked + .iter_mut() + .find(|parked| parked.generation == generation) + .map(|parked| (&mut parked.document, &mut parked.editor)) + } + + fn editors_mut(&mut self) -> impl Iterator { + std::iter::once(&mut self.editor) + .chain(self.tabs.parked.iter_mut().map(|parked| &mut parked.editor)) + } + + /// Current breakpoints of the run target and every open project module. + /// Each editor syncs markers before reporting line numbers. + pub(super) fn open_breakpoints( + &mut self, + target: u64, + ) -> (Vec, BTreeMap>) { + let Some((document, editor)) = self.open_mut(target) else { + return (Vec::new(), BTreeMap::new()); + }; + editor.sync_markers(&document.text); + let main_path = document.path().map(Path::to_path_buf); + let main = editor.breakpoints.iter().copied().collect(); + let mut modules = BTreeMap::new(); + let mut add = |document: &Document, editor: &mut CodeEditor| { + let Some(path) = document.path() else { return }; + if main_path.as_deref() == Some(path) { + return; + } + editor.sync_markers(&document.text); + modules.insert( + path.display().to_string(), + editor.breakpoints.iter().copied().collect(), + ); + }; + if target != self.document_generation { + add(&self.document, &mut self.editor); + } + for parked in &mut self.tabs.parked { + if parked.generation != target { + add(&parked.document, &mut parked.editor); + } + } + (main, modules) + } + + pub(super) fn clear_line_profiles(&mut self) { + for editor in self.editors_mut() { + editor.line_profile.clear(); + } + } + + pub fn any_modified(&self) -> bool { + self.open_documents() + .any(|(_, document)| document.is_modified()) + } + + /// The tab of the file at `path`, written exactly so. + fn find_open_exactly(&self, path: &Path) -> Option { + self.open_documents() + .find(|(_, document)| document.path() == Some(path)) + .map(|(generation, _)| generation) + } + + /// The tab of the file at `path`, however the path is written. + pub(super) fn find_open(&self, path: &Path) -> Option { + self.find_open_exactly(path).or_else(|| { + let wanted = path.canonicalize().ok()?; + self.open_documents() + .find(|(_, document)| { + document + .path() + .and_then(|open| open.canonicalize().ok()) + .is_some_and(|open| open == wanted) + }) + .map(|(generation, _)| generation) + }) + } + + /// Shows the tab of the document `generation`. Returns whether it is + /// open. + pub(super) fn activate(&mut self, generation: u64) -> bool { + if generation == self.document_generation { + return true; + } + let Some(index) = self + .tabs + .parked + .iter() + .position(|parked| parked.generation == generation) + else { + return false; + }; + self.remember_views(); + let shown = self.tabs.parked.swap_remove(index); + self.editor.close_popups(); + let hidden = Parked { + document: std::mem::replace(&mut self.document, shown.document), + editor: std::mem::replace(&mut self.editor, shown.editor), + generation: std::mem::replace(&mut self.document_generation, shown.generation), + }; + self.tabs.parked.push(hidden); + self.after_tab_change(); + true + } + + /// What follows a change of the shown document. + fn after_tab_change(&mut self) { + self.restore_views(); + // Local history is about the document that was shown. + self.dialogs.history = None; + self.editor.focus(); + } + + /// Shows the next tab, or the previous one, wrapping around. + pub(super) fn cycle_tab(&mut self, forward: bool) { + let order = &self.tabs.order; + let Some(position) = order.iter().position(|&g| g == self.document_generation) else { + return; + }; + let count = order.len(); + let next = if forward { + (position + 1) % count + } else { + (position + count - 1) % count + }; + self.activate(order[next]); + } + + /// A new generation and an editor showing the breakpoints `document` + /// had when it was last open. + fn editor_for(&mut self, document: &Document) -> (u64, CodeEditor) { + let generation = self.tabs.next_generation; + self.tabs.next_generation += 1; + let mut editor = CodeEditor::with_id(editor_id(generation)); + if let Some(path) = document.path() { + editor.restore_breakpoints(&document.text, self.settings.breakpoints_of(path)); + } + (generation, editor) + } + + /// An untitled buffer that was never edited: opening a file replaces + /// it rather than adding a tab next to it. + fn shows_pristine_buffer(&self) -> bool { + self.document.path().is_none() + && self.document.example_title().is_none() + && !self.document.is_modified() + } + + /// Opens `document` in a new tab after the shown one and shows it. A + /// shown untitled buffer that was never edited is replaced instead, as + /// the startup script is by the first file opened. + pub(super) fn add_tab(&mut self, document: Document) { + let replace = self.shows_pristine_buffer(); + let previous = self.document_generation; + if replace { + self.forget_document(previous); + } + let (generation, editor) = self.editor_for(&document); + self.remember_views(); + self.editor.close_popups(); + let hidden = Parked { + document: std::mem::replace(&mut self.document, document), + editor: std::mem::replace(&mut self.editor, editor), + generation: std::mem::replace(&mut self.document_generation, generation), + }; + let position = self.tabs.order.iter().position(|&g| g == previous); + match (replace, position) { + (true, Some(position)) => self.tabs.order[position] = generation, + (false, Some(position)) => { + self.tabs.order.insert(position + 1, generation); + self.tabs.parked.push(hidden); + } + (true, None) => self.tabs.order.push(generation), + (false, None) => { + self.tabs.order.push(generation); + self.tabs.parked.push(hidden); + } + } + self.after_tab_change(); + } + + /// Opens `document` in a tab after the shown one, without showing it. + fn add_background_tab(&mut self, document: Document) -> u64 { + let (generation, editor) = self.editor_for(&document); + let position = self + .tabs + .order + .iter() + .position(|&g| g == self.document_generation) + .map_or(self.tabs.order.len(), |position| position + 1); + self.tabs.order.insert(position, generation); + self.tabs.parked.push(Parked { + document, + editor, + generation, + }); + generation + } + + /// Closes the tabs of `documents`, asking about unsaved changes first. + pub(super) fn close_tabs(&mut self, documents: Vec) { + self.guard_unsaved(Intent::Close(documents)); + } + + /// Closes a tab without asking. Closing the last one leaves an empty + /// untitled buffer: there is always a document. + pub(super) fn close_now(&mut self, generation: u64) { + if self.document_of(generation).is_none() { + return; + } + self.forget_document(generation); + if generation == self.document_generation { + let order = &self.tabs.order; + let neighbor = order + .iter() + .position(|&g| g == generation) + .and_then(|position| { + order + .get(position + 1) + .or_else(|| position.checked_sub(1).and_then(|left| order.get(left))) + }) + .copied(); + match neighbor { + Some(neighbor) => { + self.activate(neighbor); + } + None => self.add_tab(Document::untitled("")), + } + } + self.tabs + .parked + .retain(|parked| parked.generation != generation); + self.tabs.order.retain(|&g| g != generation); + // Its edits were saved or discarded. + self.checkpoint_recovery(); + } + + /// Before a document goes away: its breakpoints are remembered for the + /// next time it opens, and a debugging session of it ends. + fn forget_document(&mut self, generation: u64) { + if let Some((document, editor)) = self.open_mut(generation) + && let Some(path) = document.path().map(Path::to_path_buf) + { + let saved = editor.saved_breakpoints(&document.text); + self.settings.remember_breakpoints(&path, saved); + } + let paused_here = self + .open_mut(generation) + .is_some_and(|(_, editor)| editor.debug_line.is_some()); + if self.is_debugging() + && (self.running_document() == Some(generation) || paused_here) + && self.execution.abandon() + { + self.debug_command(DebugAction::Stop); + } + } + + /// The document of the run going on, if any, also while it is paused + /// in the debugger: closing that document ends the session. + pub(super) fn running_document(&self) -> Option { + let running = self.execution.phase().run_id()?; + self.run_script + .as_ref() + .filter(|(id, _)| *id == running) + .map(|(_, script)| script.document) + } + + /// Checkpoints every open document, in tab order, for crash recovery. + pub(super) fn checkpoint_documents(&mut self) -> std::io::Result { + let order = &self.tabs.order; + let mut documents: Vec<(u64, &Document)> = + std::iter::once((self.document_generation, &self.document)) + .chain(self.tabs.parked.iter().map(|p| (p.generation, &p.document))) + .collect(); + documents.sort_by_key(|(generation, _)| { + order + .iter() + .position(|g| g == generation) + .unwrap_or(usize::MAX) + }); + let documents: Vec<&Document> = documents.into_iter().map(|(_, d)| d).collect(); + self.recovery.checkpoint_all(&documents) + } + + /// Keeps the breakpoints of every open file for the next time it opens. + pub(super) fn remember_all_breakpoints(&mut self) { + let shown = std::iter::once((&self.document, &mut self.editor)); + let parked = self + .tabs + .parked + .iter_mut() + .map(|parked| (&parked.document, &mut parked.editor)); + let saved: Vec<_> = shown + .chain(parked) + .filter_map(|(document, editor)| { + let path = document.path()?.to_path_buf(); + Some((path, editor.saved_breakpoints(&document.text))) + }) + .collect(); + for (path, lines) in saved { + self.settings.remember_breakpoints(&path, lines); + } + } + + /// The modified documents among those `intent` would close. + pub fn unsaved_of(&self, intent: &Intent) -> Vec { + let modified = |generation: &u64| { + self.document_of(*generation) + .is_some_and(Document::is_modified) + }; + match intent { + Intent::Close(documents) => documents.iter().copied().filter(modified).collect(), + Intent::Quit => self + .documents_in_order() + .into_iter() + .map(|(generation, _)| generation) + .filter(modified) + .collect(), + } + } + + /// The names of `documents`, for messages. + pub fn names_of(&self, documents: &[u64]) -> Vec { + documents + .iter() + .filter_map(|&generation| self.document_of(generation)) + .map(Document::display_name) + .collect() + } + + /// Saves each of `documents` that is modified, showing the ones that + /// need a name first. Returns whether all of them ended up saved. + pub(super) fn save_documents(&mut self, documents: &[u64]) -> bool { + let shown = self.document_generation; + for &generation in documents { + if !self + .document_of(generation) + .is_some_and(Document::is_modified) + { + continue; + } + self.activate(generation); + if !self.save() { + return false; + } + } + self.activate(shown); + true + } + + /// Saves every modified document. + pub(super) fn save_all(&mut self) { + let modified = self.unsaved_of(&Intent::Quit); + if modified.is_empty() { + self.set_status(StatusKind::Info, "Every file is saved"); + } else if self.save_documents(&modified) && modified.len() > 1 { + self.set_status( + StatusKind::Success, + format!("Saved {} files", modified.len()), + ); + } + } + + pub(super) fn clear_debug_lines(&mut self) { + for editor in self.editors_mut() { + editor.set_debug_line(None); + } + } + + // -- the script F5 runs ----------------------------------------------------- + + /// The project's main script, while a file of the project is shown. + pub fn main_script(&self) -> Option<&Path> { + let project = self.project.as_ref()?; + let main = project.main.as_deref()?; + let shown = self.document.path()?; + project.contains(shown).then_some(main) + } + + /// The path of the script F5 runs, if it has one. + pub(super) fn run_target_path(&self) -> Option { + self.main_script() + .or(self.document.path()) + .map(Path::to_path_buf) + } + + /// The open document F5 runs: the project's main script while a file + /// of the project is shown and the script is open, else the shown one. + pub fn run_target(&self) -> u64 { + self.main_script() + .and_then(|main| self.find_open_exactly(main)) + .unwrap_or(self.document_generation) + } + + /// The document to run now, opening the main script in a tab (without + /// showing it) when it is not open yet. + pub(super) fn prepare_run_target(&mut self) -> u64 { + let Some(main) = self.main_script().map(Path::to_path_buf) else { + return self.document_generation; + }; + if let Some(open) = self.find_open(&main) { + return open; + } + match Document::open(&main) { + Ok(document) => self.add_background_tab(document), + Err(error) => { + let message = format!( + "Cannot open the main script {}: {error}; rendering {} instead", + main.display(), + self.document.display_name() + ); + log::warn!("{message}"); + self.set_status(StatusKind::Warning, message); + self.document_generation + } + } + } + + /// Open scripts next to the one `target` runs that have unsaved + /// changes: Python imports their saved version. + pub(super) fn unsaved_modules(&self, target: u64) -> Vec { + let Some(folder) = self + .document_of(target) + .and_then(Document::path) + .and_then(Path::parent) + else { + return Vec::new(); + }; + self.documents_in_order() + .into_iter() + .filter(|(generation, document)| { + *generation != target + && document.is_modified() + && document + .path() + .is_some_and(|path| path.starts_with(folder) && project::is_script(path)) + }) + .map(|(_, document)| document.display_name()) + .collect() + } + + // -- sessions ----------------------------------------------------------- + + /// Remembers the open tabs and the project for the next session. + pub(super) fn remember_session(&mut self) { + self.settings.open_files = self + .documents_in_order() + .into_iter() + .filter_map(|(_, document)| document.path().map(Path::to_path_buf)) + .collect(); + if let Some(path) = self.document.path() { + self.settings.last_file = Some(path.to_path_buf()); + } + self.settings.project = self.project.as_ref().map(|p| p.root().to_path_buf()); + self.remember_project(); + } + + /// Opens the project and the tabs of the last session, then the file + /// given on the command line, which is shown. Returns the problems to + /// report; a file that is not UTF-8 is asked about like a file opened + /// later. + pub(super) fn restore_session(&mut self, startup: Option) -> Vec { + let mut problems = Vec::new(); + if let Some(root) = self.settings.project.clone() + && root.is_dir() + && let Err(error) = self.open_project(&root) + { + log::warn!("Cannot open the project {}: {error}", root.display()); + } + + let mut files = self.settings.open_files.clone(); + if files.is_empty() { + // Settings of a release without tabs. + files.extend(self.settings.last_file.clone()); + } + for path in files.into_iter().filter(|path| path.is_file()) { + if self.find_open_exactly(&path).is_some() { + continue; + } + match Document::open(&path) { + Ok(document) => self.add_tab(document), + Err(error) if is_not_utf8(&error) => { + log::info!("Not reopening {}: {error}", path.display()); + } + Err(error) => { + log::warn!("Cannot open {}: {error}", path.display()); + problems.push(format!("Cannot reopen {}:\n{error}", path.display())); + } + } + } + + // Kept in the session, where a relative path would not survive a + // start from another folder. + let startup = startup.map(|path| std::path::absolute(&path).unwrap_or(path)); + match startup { + Some(path) => match self.find_open(&path) { + Some(open) => { + self.activate(open); + } + None => match Document::open(&path) { + Ok(document) => self.add_tab(document), + Err(error) if is_not_utf8(&error) => { + self.dialogs.legacy_encoding = Some(path); + } + Err(error) => { + log::warn!("Cannot open {}: {error}", path.display()); + problems.push(format!( + "Cannot open the startup file {}:\n{error}", + path.display() + )); + } + }, + }, + None => { + if let Some(open) = self + .settings + .last_file + .clone() + .and_then(|last| self.find_open_exactly(&last)) + { + self.activate(open); + } + } + } + problems + } +} + +#[cfg(test)] +#[path = "../../tests/rust/app/test_tabs.rs"] +mod tests; diff --git a/src/app/watching.rs b/src/app/watching.rs new file mode 100644 index 000000000..c13db98e3 --- /dev/null +++ b/src/app/watching.rs @@ -0,0 +1,290 @@ +//! Automatic reload: the script F5 runs, the local modules it imports and +//! the files open in tabs are watched. A changed tab is reloaded (or, with +//! unsaved edits, asked about), and a change to the script or its modules +//! renders it again. + +use std::io; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use super::execution::Pending; +use super::{AppState, StatusKind}; +use crate::dialogs::ExternalChange; +use crate::document::ExternalUpdate; +use crate::worker::protocol::Request; + +/// What the watcher follows; it is told again when this changes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct WatchKey { + autoreload: bool, + watch_imports: bool, + /// The script F5 runs, whose imports are asked for. + script: Option, + files: Vec, +} + +impl AppState { + /// Inspect all open files when the window regains focus. This runs even + /// when automatic preview is disabled: external edits must not remain + /// invisible until the next save. + pub(super) fn check_disk_on_focus(&mut self) { + let documents: Vec<_> = self + .documents_in_order() + .into_iter() + .filter_map(|(generation, document)| { + document.path().map(|path| (generation, path.to_path_buf())) + }) + .collect(); + let mut conflicts = Vec::new(); + for (generation, path) in documents { + let snapshot = self + .document_of(generation) + .and_then(|document| document.disk_version().transpose()) + .transpose(); + match snapshot { + Err(error) if error.kind() == io::ErrorKind::NotFound => { + if let Some((document, _)) = self.open_mut(generation) { + document.set_missing_on_disk(true); + } + self.set_status( + StatusKind::Warning, + format!( + "{} was deleted or moved on disk; the editor buffer is preserved", + path.display() + ), + ); + } + Err(error) => { + self.dialogs.error( + "Cannot check a file on disk", + format!("{}\n\n{error}", path.display()), + ); + } + Ok(Some(version)) => { + if let Some((document, _)) = self.open_mut(generation) { + document.set_missing_on_disk(false); + } + let update = self + .document_of(generation) + .map(|document| document.classify_external_update(&version)); + match update { + Some(ExternalUpdate::Conflict) => { + let already_queued = self + .dialogs + .external_change + .as_ref() + .is_some_and(|change| change.document == generation) + || self + .dialogs + .external_queue + .iter() + .any(|change| change.document == generation); + if !already_queued { + conflicts.push(ExternalChange { + document: generation, + path, + disk: version, + show_comparison: false, + rerun_after_resolution: false, + on_save: false, + }); + } + } + Some(ExternalUpdate::Reload | ExternalUpdate::MatchesBuffer) => { + self.reload_tab(generation); + } + _ => {} + } + } + Ok(None) => {} + } + } + if !conflicts.is_empty() { + self.dialogs.external_queue.extend(conflicts); + if self.dialogs.external_change.is_none() { + let next = self.dialogs.external_queue.remove(0); + self.activate(next.document); + self.dialogs.external_change = Some(next); + } + } + } + + pub(super) fn sync_watcher(&mut self) { + let editor = &self.settings.editor; + let (autoreload, watch_imports) = (editor.autoreload, editor.watch_imported_modules); + let script = self.run_target_path(); + let mut files = Vec::new(); + if autoreload { + files.extend(script.clone()); + if watch_imports { + files.extend(self.imports.iter().cloned()); + } + files.extend( + self.documents_in_order() + .into_iter() + .filter_map(|(_, document)| document.path().map(Path::to_path_buf)), + ); + files.sort(); + files.dedup(); + } + let key = WatchKey { + autoreload, + watch_imports, + script, + files, + }; + if self.watch_key.as_ref() == Some(&key) { + return; + } + let ask = self.watch_key.as_ref().is_none_or(|previous| { + ( + previous.autoreload, + previous.watch_imports, + &previous.script, + ) != (key.autoreload, key.watch_imports, &key.script) + }); + self.start_watching(&key, ask); + self.watch_key = Some(key); + } + + fn start_watching(&mut self, key: &WatchKey, ask_imports: bool) { + if key.files.is_empty() { + self.watcher.clear(); + } else { + self.watcher.set_files(key.files.clone()); + } + if ask_imports { + // Imports of another script, or of none, are of no use now. + self.imports.clear(); + self.request_imports(); + } + } + + /// The script whose local imports are watched, if any. + pub(super) fn watched_imports_of(&self) -> Option { + let editor = &self.settings.editor; + (editor.autoreload && editor.watch_imported_modules) + .then(|| self.run_target_path()) + .flatten() + } + + /// Asks which local modules the script imports, so the watcher follows + /// them. Called whenever watching starts and again after each save and + /// successful run, as the imports change with the script. + pub(super) fn request_imports(&mut self) { + let Some(script) = self.watched_imports_of() else { + return; + }; + if !self.worker.is_ready() { + return; // asked again after the first run + } + let path = script.display().to_string(); + self.send_tracked(Pending::Imports(script), |id| Request::Imports { id, path }); + } + + pub(super) fn poll_watcher(&mut self, ctx: &egui::Context) { + if !self.watcher.is_watching() { + return; + } + ctx.request_repaint_after(self.watcher.next_poll_in()); + let delay = Duration::from_millis(self.settings.editor.autoreload_delay_ms); + let changed = self.watcher.poll(delay); + if changed.is_empty() { + return; + } + + let script = self.run_target_path(); + let imported_changed = changed.iter().any(|path| self.imports.contains(path)); + // A script that is not open always counts; an open one only when + // its contents changed. + let mut script_changed = script + .as_ref() + .is_some_and(|script| changed.contains(script) && self.find_open(script).is_none()); + let mut conflicts = Vec::new(); + for path in &changed { + let Some(generation) = self.find_open(path) else { + continue; + }; + let is_script = script.as_ref() == Some(path); + match self.reload_tab(generation) { + Some(ExternalUpdate::Unchanged) | None => {} + Some(ExternalUpdate::Conflict) => { + let Some(disk) = self + .document_of(generation) + .and_then(|document| document.disk_version().ok().flatten()) + else { + continue; + }; + conflicts.push(ExternalChange { + document: generation, + path: path.clone(), + disk, + show_comparison: false, + rerun_after_resolution: is_script, + on_save: false, + }); + } + Some(ExternalUpdate::MatchesBuffer | ExternalUpdate::Reload) => { + script_changed |= is_script; + } + } + } + + if !conflicts.is_empty() { + self.dialogs.external_queue.extend(conflicts); + if self.dialogs.external_change.is_none() { + let next = self.dialogs.external_queue.remove(0); + self.activate(next.document); + self.dialogs.external_change = Some(next); + } + self.set_status( + StatusKind::Warning, + "File changed on disk; waiting for your decision", + ); + } + if script_changed || imported_changed { + match &mut self.dialogs.external_change { + Some(conflict) => conflict.rerun_after_resolution = true, + None => self.start_run(false), + } + } + } + + /// Reloads the open document `generation` from disk when that loses + /// nothing. Returns how the disk version relates to the buffer; + /// a conflict is left for the user to decide. + pub(super) fn reload_tab(&mut self, generation: u64) -> Option { + let (document, _) = self.open_mut(generation)?; + let version = match document.disk_version() { + Ok(version) => version?, + Err(error) => { + log::warn!("Cannot read the changed file: {error}"); + self.dialogs + .error("Cannot read the changed file", error.to_string()); + return None; + } + }; + let update = document.classify_external_update(&version); + let applied = match update { + // A timestamp-only rewrite must neither erase local edits nor + // trigger a needless rebuild. + ExternalUpdate::Unchanged | ExternalUpdate::Conflict => return Some(update), + ExternalUpdate::MatchesBuffer => document.apply_disk_version(version), + ExternalUpdate::Reload => document.reload(version), + }; + match applied { + Ok(_) => { + let name = document.display_name(); + self.set_status(StatusKind::Info, format!("Reloaded {name}")); + if update == ExternalUpdate::MatchesBuffer { + self.checkpoint_recovery(); + } + Some(update) + } + Err(error) => { + log::warn!("Cannot reload the file: {error}"); + None + } + } + } +} diff --git a/src/app/worker_events.rs b/src/app/worker_events.rs new file mode 100644 index 000000000..01eb5fa61 --- /dev/null +++ b/src/app/worker_events.rs @@ -0,0 +1,709 @@ +//! The worker process: starting it, recovering from its crashes, sending +//! requests and routing its messages to whatever asked for them. + +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::Arc; + +use super::execution::Pending; +use super::{AppState, StatusKind}; +use crate::embedded; +use crate::logging::{self, Level}; +use crate::panels::EntryKind; +use crate::scene::{Grid, Mesh, NodeKey, Overlay}; +use crate::updates; +use crate::worker::protocol::{DebugAction, Message, OutputStream, Request, RequestId}; +use crate::worker::{self, Event, LaunchConfig, launch}; + +impl AppState { + /// Asks for CQ-editor's newer releases once a day, without a word + /// unless one is out (Preferences > General turns it off). + fn check_updates_daily(&mut self) { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.as_secs()); + if !updates::check_due(&self.settings.general, now) || !self.worker.is_ready() { + return; + } + let sent = self.send_tracked(Pending::Updates { automatic: true }, |id| { + Request::CheckUpdates { + id, + editor: updates::VERSION.to_owned(), + cadquery: false, + } + }); + if sent { + self.settings.general.last_update_check = now; + } + } + + /// The interpreter Python is (or will be) started with: the command + /// line's, else the preferences', else the one detected. + pub(super) fn python_in_use(&self) -> std::path::PathBuf { + let explicit = self + .python_override + .clone() + .unwrap_or_else(|| self.settings.general.python.clone()); + launch::find_python(Some(&explicit)) + } + + pub(super) fn start_worker(&mut self) { + let python = self.python_in_use(); + let worker_dir = match embedded::worker_dir(&self.cache_dir) { + Ok(dir) => dir, + Err(err) => { + self.set_status( + StatusKind::Error, + format!("Cannot prepare the Python worker: {err}"), + ); + return; + } + }; + self.worker.start(LaunchConfig { python, worker_dir }); + self.worker_was_ready = false; + // Look for interpreters again if this one fails too: one may have + // been installed meanwhile. + self.dialogs.python_candidates = None; + self.reset_execution_state(); + // The new process knows nothing about the old one's inspections. + self.inspector.clear(); + self.scene.clear_topology_selection(); + self.measurements.clear(); + self.selector.clear(); + self.selector_preview.clear(); + self.scene.clear_selector_preview(); + self.scene.overlay = Overlay::default(); + } + + /// Forgets everything that was in flight in the worker. + fn reset_execution_state(&mut self) { + self.execution.reset(); + self.scene.clear_preview(); + self.console.busy = false; + self.clear_debug_lines(); + self.inspector.loading = false; + if let Some(upload) = &mut self.dialogs.upload { + upload.busy = false; + } + } + + /// Sends a request with a fresh id, remembering what it was for. + pub(super) fn send_tracked( + &mut self, + kind: Pending, + build: impl FnOnce(RequestId) -> Request, + ) -> bool { + if !self.worker.is_ready() { + self.set_status(StatusKind::Warning, "Python is not ready yet"); + return false; + } + let id = self.worker.next_id(); + if self.worker.send(&build(id)) { + self.execution.track(id, kind); + true + } else { + false + } + } + + pub(super) fn release(&mut self, keys: Vec) { + if !keys.is_empty() { + self.worker.send(&Request::Release { keys }); + } + } + + pub(super) fn process_worker_events(&mut self) { + for event in self.worker.poll() { + match event { + Event::Message(message) => self.handle_message(message), + Event::Stderr(line) => logging::push(Level::Warn, "python", &line), + Event::ProtocolError(message) => { + // The rest of these events are the old process's. + self.worker_protocol_failed(message); + break; + } + Event::Exited => { + let reason = match self.worker.status() { + worker::Status::Failed(reason) => reason.clone(), + _ => "The Python worker stopped".to_owned(), + }; + log::error!("{reason}"); + let was_busy = self.is_busy(); + self.reset_execution_state(); + if self.worker_was_ready { + // A crash inside OpenCascade must not leave the + // editor without Python: start a fresh worker. + self.set_status( + StatusKind::Error, + if was_busy { + "Python crashed while running the script; it was restarted" + } else { + "Python stopped unexpectedly; it was restarted" + }, + ); + self.start_worker(); + } else { + self.set_status(StatusKind::Error, reason); + } + } + } + } + // References in a response are only valid while its request runs. + let execution = &self.execution; + self.scene.release_geometry(|id| execution.is_pending(id)); + } + + /// The worker sent what cannot be read, such as a model too large to + /// transfer. Nothing more can be read from that process: a new one + /// takes over, the run that was waiting ends, and the model shown + /// before stays. Python and CadQuery are fine, and the user is told why. + pub(super) fn worker_protocol_failed(&mut self, message: String) { + log::error!("{message}"); + self.dialogs.error("Cannot show the result", message); + self.start_worker(); + } + + pub(super) fn handle_message(&mut self, message: Message) { + match message { + Message::Ready(info) => { + log::info!( + "Python {} with CadQuery {} / OCP {} is ready ({})", + info.python, + info.cadquery, + info.ocp, + info.executable + ); + if !info.completion { + log::info!("Install jedi in the Python environment for code completion"); + } + self.worker_was_ready = true; + self.check_updates_daily(); + self.set_status( + StatusKind::Success, + format!("CadQuery {} ready", info.cadquery), + ); + if let Some(debug) = self.execution.worker_ready() { + self.start_run(debug); + } + } + Message::Fatal { message, detail } => { + log::error!("{message}"); + if let Some(detail) = detail { + logging::push(Level::Error, "python", &detail); + } + self.set_status(StatusKind::Error, message); + } + Message::Output { id, stream, text } => { + let to_console = id + .is_some_and(|id| matches!(self.execution.pending(id), Some(Pending::Console))); + match (to_console, stream) { + (true, OutputStream::Stdout) => self.console.push(EntryKind::Output, &text), + (true, OutputStream::Stderr) => self.console.push(EntryKind::Error, &text), + (false, OutputStream::Stdout) => logging::push(Level::Info, "print", &text), + (false, OutputStream::Stderr) => logging::push(Level::Warn, "stderr", &text), + } + } + Message::Log { + level, + source, + message, + } => { + logging::push(Level::from_python(&level), &source, &message); + } + Message::RunFinished(result) => self.finish_run(*result), + Message::RunPart { id, name, part } => { + if matches!(self.execution.pending(id), Some(Pending::Run)) { + match self.scene.add_preview_part(id, *part) { + Ok(()) => self.set_status(StatusKind::Info, format!("Rendering {name}…")), + Err(error) => self.worker_protocol_failed(error), + } + } + } + Message::Progress { + id, + stage, + done, + total, + } => { + if stage == "meshing" { + self.execution + .meshing_progress(id, done, total, std::time::Instant::now()); + } + } + Message::DebugPaused { + id, + line, + path, + variables, + objects, + } => { + if self.execution.paused(id) { + // A session of the previous document reached a breakpoint. + self.release(objects.into_iter().map(|node| node.key).collect()); + self.debug_command(DebugAction::Stop); + return; + } + // Show the frame's document, including an imported module. + self.clear_debug_lines(); + if let Some(path) = path.as_deref() { + self.open_path_at(std::path::Path::new(path), line); + } else { + let target = self.run_document(id); + self.activate(target); + } + self.editor.set_debug_line(Some(line)); + self.variables = variables; + self.scene.clear_preview(); + let Some(mut nodes) = self.decode_scene_nodes(Some(id), objects) else { + return; + }; + self.attach_run_script(id, &mut nodes); + let removed = self.scene.replace(nodes, None); + self.geometry_checks.clear(); + self.release(removed); + self.measurements.clear(); + self.selector.clear(); + self.refresh_inspector(); + let file = path + .as_deref() + .and_then(|p| std::path::Path::new(p).file_name()) + .map_or(String::new(), |name| { + format!("{}: ", name.to_string_lossy()) + }); + self.set_status(StatusKind::Info, format!("Paused at {file}line {line}")); + } + Message::Completions { + id, + available, + items, + signatures, + } => { + match self.execution.answer(id) { + Some(Pending::ConsoleCompletion) => { + let inserts: Vec<(String, String)> = + items.into_iter().map(|i| (i.name, i.insert)).collect(); + self.console.complete(&inserts, &signatures); + } + // Offered while typing a name: names only, and silence + // when there are none. + // Asked for in a tab that is no longer shown. + Some(Pending::Completion { document, .. }) + if document != self.document_generation => {} + Some(Pending::Completion { + automatic: true, .. + }) => { + if !items.is_empty() { + self.editor.show_completions(items, Vec::new()); + } + } + _ if !available => self.set_status( + StatusKind::Info, + "Code completion needs jedi: pip install jedi", + ), + _ => { + if !self.editor.show_completions(items, signatures) { + self.set_status(StatusKind::Info, "No completions available"); + } + } + } + } + Message::Description { id, documentation } => { + if self.execution.answer(id) + == Some(Pending::Describe { + document: self.document_generation, + }) + { + self.editor.show_documentation(documentation); + } + } + Message::Outline { id, symbols } => { + if self.execution.answer(id) + == Some(Pending::Outline { + document: self.document_generation, + }) + && self.navigation.outline_request == Some(id) + && self.navigation.source == self.document.text + { + self.navigation.symbols = symbols; + self.navigation.outline_request = None; + } + } + Message::Navigation { + id, + available, + mode, + locations, + truncated, + } => { + if self.execution.answer(id) + == Some(Pending::Navigate { + document: self.document_generation, + }) + && self.navigation.navigation_request == Some(id) + && self.navigation.navigation_source == self.document.text + { + self.navigation.navigation_request = None; + self.navigation.available = available; + self.navigation.mode = Some(mode); + self.navigation.truncated = truncated; + self.navigation.locations = locations; + if !available { + self.set_status( + StatusKind::Info, + "Code navigation needs jedi: pip install jedi", + ); + } else if mode == crate::worker::protocol::NavigationMode::Definition + && self.navigation.locations.len() == 1 + { + let location = &self.navigation.locations[0]; + let action = if let Some(path) = &location.path { + crate::commands::Action::OpenFileAt { + path: path.into(), + line: location.line, + } + } else { + crate::commands::Action::GoToScriptLine { + document: self.document_generation, + line: location.line, + } + }; + self.queue([action]); + } + } + } + Message::Inspection { id, key, frames } => { + self.execution.answer(id); + if self.inspector.key.as_deref() == Some(key.as_str()) { + self.inspector.frames = frames; + self.inspector.loading = false; + } + } + Message::InspectionGeometry { id, meshes, plane } => { + // Only for the entry still selected: the inspector may show + // another workplane, or another step, by now. + let current = match self.execution.answer(id) { + Some(Pending::InspectGeometry { key, entry }) => { + self.inspector.key.as_ref() == Some(&key) + && self.inspector.selected == Some(entry) + } + _ => false, + }; + if current && self.inspector.show_in_view { + self.scene.overlay = Overlay { + meshes: meshes + .into_iter() + .map(|m| Arc::new(Mesh::from(m))) + .collect(), + grid: plane.map(|p| Grid { + origin: p.origin.into(), + x_dir: p.x_dir.into(), + z_dir: p.z_dir.into(), + size: p.size, + }), + }; + } + } + Message::InterferenceGeometry { id, mesh } => { + if let Some(Pending::InterferenceGeometry { first, second }) = + self.execution.answer(id) + && self.dialogs.geometry.as_ref().is_some_and(|dialog| { + dialog + .selected_pair + .and_then(|index| dialog.interferences.get(index)) + .is_some_and(|pair| pair.first == first && pair.second == second) + }) + { + self.scene.overlay = Overlay { + meshes: vec![Arc::new(Mesh::from(*mesh))], + grid: None, + }; + } + } + Message::Measurement(result) => { + let id = result.id; + let tracked = matches!(self.execution.answer(id), Some(Pending::Measure)); + if tracked && self.measurements.request_id == Some(id) { + self.measurements.loading = false; + self.measurements.error = None; + self.measurements.request_id = None; + self.measurements.result = Some(*result); + } + } + Message::MeasurementCode { + id, + code, + verified, + problem, + } => { + if matches!(self.execution.answer(id), Some(Pending::MeasurementCode)) { + self.measurement_code_arrived(code, verified, problem); + } + } + Message::Selector(reply) => { + let id = reply.id; + let tracked = matches!(self.execution.answer(id), Some(Pending::Selector)); + // Only the reply for the current selection. + if tracked && self.selector.request_id == Some(id) { + self.selector.loading = false; + self.selector.request_id = None; + self.selector.chosen = 0; + self.selector.reply = Some(reply); + if let Some(usage) = self.selector.then.take() + && let Some(candidate) = self.selector.candidate().cloned() + { + self.apply_selector(usage, &candidate); + } + } + } + Message::SelectorPreview { + id, + active, + count, + matches, + message, + } => { + if matches!(self.execution.answer(id), Some(Pending::SelectorPreview)) + && self.selector_preview.request_id == Some(id) + { + self.selector_preview.request_id = None; + self.selector_preview.active = active; + self.selector_preview.count = count; + self.selector_preview.message = message; + self.scene.set_selector_preview(&matches); + self.selector_preview.shown = self.scene.selector_preview_count(); + } + } + Message::SceneAdd { id, objects } => { + self.selector_preview.clear(); + let was_empty = self.scene.is_empty(); + let Some(nodes) = self.decode_scene_nodes(id, objects) else { + return; + }; + self.scene.append(nodes, None); + if was_empty { + self.viewer.fit(&self.scene, false, self.now()); + } + } + Message::Display(output) => { + if matches!(self.execution.pending(output.id), Some(Pending::Console)) { + self.console.push_display(output); + } + } + Message::ConsoleResult { id, more } => { + self.execution.answer(id); + self.console.more = more; + self.console.busy = false; + } + Message::ExportFinished { id, path } => { + self.execution.answer(id); + self.export_job = None; + self.set_status(StatusKind::Success, format!("Exported {path}")); + } + Message::GeometryChecked { + id, + reports, + interferences, + } => { + if matches!(self.execution.answer(id), Some(Pending::Check)) { + for report in &reports { + self.geometry_checks + .insert(report.key.clone(), report.clone()); + } + self.dialogs.geometry = Some(crate::dialogs::GeometryDialog { + reports, + interferences, + for_export: false, + selected_pair: None, + }); + } + } + Message::GeometryInvalid { + id, + reports, + interferences, + } => { + if matches!(self.execution.answer(id), Some(Pending::Export)) { + for report in &reports { + self.geometry_checks + .insert(report.key.clone(), report.clone()); + } + self.dialogs.geometry = Some(crate::dialogs::GeometryDialog { + reports, + interferences, + for_export: true, + selected_pair: None, + }); + self.set_status(StatusKind::Warning, "Export waits for a geometry decision"); + } + } + Message::UploadFinished { id, status, body } => { + self.execution.answer(id); + if let Some(upload) = &mut self.dialogs.upload { + upload.finished(status, &body); + } + } + Message::Updates { + id, + current, + newer, + editor, + } => { + let automatic = matches!( + self.execution.answer(id), + Some(Pending::Updates { automatic: true }) + ); + if let Some(editor) = &editor { + self.settings.general.newer_release = editor.newer.first().cloned(); + } + let available = updates::available(&self.settings.general).cloned(); + if automatic { + if let Some(release) = available { + self.set_status( + StatusKind::Info, + format!( + "CQ-editor {} is available: Help > Download CQ-editor {}", + release.tag, release.tag + ), + ); + } + return; + } + self.status = None; + let editor_text = match &available { + Some(release) => format!( + "CQ-editor {} is available (you have {}): Help > Download \ + CQ-editor {} opens its page.", + release.tag, + updates::VERSION, + release.tag + ), + None => format!("CQ-editor {} is the latest version.", updates::VERSION), + }; + let cadquery_text = if newer.is_empty() { + format!("CadQuery {current} is the latest version.") + } else { + format!( + "Newer CadQuery releases ({current} installed):\n{}", + newer.join("\n") + ) + }; + let title = if available.is_some() || !newer.is_empty() { + "Updates available" + } else { + "No updates available" + }; + self.dialogs + .info(title, format!("{editor_text}\n\n{cadquery_text}")); + } + Message::Imports { id, paths } => { + let Some(Pending::Imports(script)) = self.execution.answer(id) else { + return; + }; + // Answers for another file, or after watching changed, are + // outdated. + if self.watched_imports_of().as_deref() != Some(script.as_path()) { + return; + } + // Its current imports: modules no longer imported stop + // being watched (see `sync_watcher`). + let imports: BTreeSet = paths + .into_iter() + .map(PathBuf::from) + .filter(|path| *path != script) + .collect(); + self.imports = imports.into_iter().collect(); + } + Message::Error { id, message } => self.request_failed(id, message), + } + } + + pub(super) fn request_failed(&mut self, id: Option, message: String) { + let kind = id.and_then(|id| self.execution.answer(id).map(|kind| (id, kind))); + match kind { + Some((_, Pending::Console)) => { + self.console.push(EntryKind::Error, &format!("{message}\n")); + self.console.busy = false; + } + Some((_, Pending::Export)) => { + self.export_job = None; + self.dialogs.error("Export failed", message); + } + Some((_, Pending::Check)) => self.dialogs.error("Geometry check failed", message), + Some((_, Pending::InterferenceGeometry { .. })) => { + self.set_status( + StatusKind::Warning, + format!("Cannot draw overlap: {message}"), + ); + } + Some((_, Pending::Upload)) => { + if let Some(upload) = &mut self.dialogs.upload { + upload.failed(&message); + } + } + Some((_, Pending::Updates { automatic: true })) => { + // Offline, rate-limited…: tried again tomorrow, silently. + log::info!("Cannot check for CQ-editor updates: {message}"); + } + Some((_, Pending::Updates { automatic: false })) => { + self.status = None; + self.dialogs.error("Cannot check for updates", message); + } + Some((_, Pending::Inspect | Pending::InspectGeometry { .. })) => { + self.inspector.loading = false; + self.set_status(StatusKind::Warning, message); + } + Some((id, Pending::Run)) => self.run_failed(id, message), + Some((id, Pending::Measure)) if self.measurements.request_id == Some(id) => { + self.measurements.loading = false; + self.measurements.error = Some(message); + self.measurements.request_id = None; + } + Some((_, Pending::Measure)) => {} + Some((id, Pending::Selector)) if self.selector.request_id == Some(id) => { + self.selector.loading = false; + self.selector.request_id = None; + if self.selector.then.take().is_some() { + self.set_status(StatusKind::Warning, message.clone()); + } + self.selector.error = Some(message); + } + Some((_, Pending::Selector)) => {} + Some((id, Pending::SelectorPreview)) + if self.selector_preview.request_id == Some(id) => + { + self.selector_preview.request_id = None; + self.selector_preview.message = Some(message); + self.selector_preview.active = true; + } + Some((_, Pending::SelectorPreview)) => {} + Some((_, Pending::MeasurementCode)) => { + self.set_status( + StatusKind::Warning, + format!("Cannot write the measurement as code: {message}"), + ); + } + // Hovering over a name the worker cannot describe is not news. + Some(( + _, + Pending::Describe { .. } + | Pending::Completion { + automatic: true, .. + }, + )) => { + log::debug!("{message}"); + } + Some(( + _, + Pending::Completion { .. } + | Pending::ConsoleCompletion + | Pending::Imports(_) + | Pending::Outline { .. } + | Pending::Navigate { .. }, + )) + | None => { + log::warn!("{message}"); + self.set_status(StatusKind::Warning, message); + } + } + } +} diff --git a/src/commands.rs b/src/commands.rs new file mode 100644 index 000000000..52630dbdf --- /dev/null +++ b/src/commands.rs @@ -0,0 +1,478 @@ +//! Everything the user can ask for, from menus, the toolbar, panels and +//! keyboard shortcuts. Widgets only queue actions; the `app` module +//! executes them after the frame's UI has been built. + +use std::path::PathBuf; + +use egui::{Key, KeyboardShortcut, Modifiers}; + +use crate::panels::Tab; +use crate::scene::{NodeKey, TopologySelection}; +use crate::settings::SelectionShortcuts; +use crate::viewer::camera::StandardView; +use crate::viewer::{DisplayMode, SelectionMode}; +use crate::worker::protocol::{DebugAction, ExportFormat}; + +/// Structured formats for copying exact measurements to the clipboard. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MeasurementFormat { + Text, + Json, + Csv, +} + +impl MeasurementFormat { + pub const ALL: [Self; 3] = [Self::Text, Self::Json, Self::Csv]; + + pub fn label(self) -> &'static str { + match self { + Self::Text => "Text", + Self::Json => "JSON", + Self::Csv => "CSV", + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum Action { + // File + NewFile, + OpenFile, + OpenPath(PathBuf), + OpenExample(usize), + Save, + SaveAs, + /// Saves every tab with unsaved changes. + SaveAll, + LocalHistory, + ToggleAutoreload, + Quit, + // Tabs + /// Closes the shown tab. + CloseTab, + /// Closes the tab of this document (by generation). + CloseDocument(u64), + CloseOtherTabs(u64), + CloseAllTabs, + ActivateTab(u64), + NextTab, + PreviousTab, + // Project + /// Asks for a folder and shows it in the Project panel. + OpenFolder, + OpenFolderPath(PathBuf), + CloseFolder, + /// Reads the project's folders again. + RefreshProject, + /// Asks for the name of a new file in this folder. + NewFileIn(PathBuf), + NewFolderIn(PathBuf), + /// Asks for a new name of this file or folder. + RenamePath(PathBuf), + /// Asks to confirm deleting this file or folder. + DeletePath(PathBuf), + /// The script F5 runs while a file of the project is shown; `None` + /// runs the shown file. + SetMainScript(Option), + /// Opens the system's file manager on this file's folder. + RevealPath(PathBuf), + // Edit + Undo, + Redo, + ToggleComment, + DuplicateLine, + MoveLineUp, + MoveLineDown, + InsertSnippet(usize), + Autocomplete, + Find, + FindNext, + FindPrevious, + Replace, + /// Opens the *Go to line* bar. + GoToLinePrompt, + ShowOutline, + GoToDefinition, + FindReferences, + /// The CadQuery selector of the picked entities, to the clipboard. + CopySelector, + /// The CadQuery selector of the picked entities, at the editor's cursor. + InsertSelector, + /// Python repeating the current measurement, to the clipboard. + CopyMeasurementCode, + /// Copies the current measurement as structured data (Text, JSON, CSV). + CopyMeasurement(MeasurementFormat), + Preferences, + // Run + Render, + /// Renders with the time of each line measured, shown in the gutter. + Profile, + /// Removes the profile's times from the gutter. + ClearProfile, + /// Starts a debugging session, or ends the running one. + ToggleDebug, + Debug(DebugAction), + /// Aborts whatever the worker is doing (by restarting it). + Stop, + /// Stops meshing the running render's objects; the model shown stays. + CancelMeshing, + ClearConsole, + ClearLog, + RestartPython, + /// Restarts Python with this interpreter and keeps it in the + /// preferences. + UsePython(PathBuf), + /// Opens the dialog creating a Python environment with CadQuery. + CreateEnvironment, + /// Opens the dialog installing packages into the Python in use. + InstallPackages, + // View + Fit, + FitSelection, + View(StandardView), + Display(DisplayMode), + SelectionMode(SelectionMode), + ToggleProjection, + /// Turns the section plane on or off. + ToggleSection, + ToggleGroundGrid, + ToggleScaleBar, + /// Spreads the parts of the model apart and shows the controls of the + /// exploded view, or assembles the parts again. + ToggleExplode, + /// How far the exploded view spreads the parts (`Scene::set_explode`). + SetExplode(f32), + /// Shows only the selected objects, or ends the isolation. + ToggleIsolate, + /// Ends the isolation and makes every object visible. + ShowAll, + /// Saves the camera as a named view of the document: under this name + /// (replacing a view of the same name), or the next "View N". + SaveView(Option), + /// Moves the camera to the named view at this index. + GoToView(usize), + /// Stores the current camera in the named view at this index. + UpdateView(usize), + DeleteView(usize), + TogglePanel(Tab), + /// Shows this panel (`None`: the focused one) alone in the window, or + /// brings the whole layout back. + ToggleMaximize(Option), + ResetLayout, + /// Opens the search over every command. + CommandPalette, + // Tools + Export(ExportFormat), + CheckGeometry, + ToggleInspect, + /// Opens the screenshot and animation options. + Screenshot, + /// Asks where to save a screenshot with the chosen options. + SaveImage, + /// Renders a screenshot with the chosen options directly to the clipboard. + CopyImage, + /// Asks where to save a turntable animation and starts it. + ExportTurntable, + CancelTurntable, + Upload, + // Help + Documentation, + InstallationGuide, + CadQueryDocumentation, + About, + CheckUpdates, + /// Opens the page of the newer CQ-editor release found. + DownloadUpdate, + // From panels and the view + /// A line of the script F5 runs. + GoToLine(usize), + /// A line of the open document `document` (by generation), the script + /// of a traceback. + GoToScriptLine { + document: u64, + line: usize, + }, + /// A line of a file, such as a module in a traceback, opened if needed. + OpenFileAt { + path: PathBuf, + line: usize, + }, + Select { + key: Option, + topology: Option, + extend: bool, + }, + SetVisible { + key: NodeKey, + visible: bool, + }, + /// The script line that created an object, or one step of its + /// construction stack as (frame, item) in the CQ Inspector. + GoToSource { + key: NodeKey, + step: Option<(usize, Option)>, + }, + /// The script line that created the current object. + GoToSelectionSource, + /// A new value for the parameter `name` assigned on `line` (1-based). + SetParameter { + name: String, + line: usize, + value: f64, + }, + /// Restores all modified parameters in the active script to their reference values. + ResetParameters, + RemoveSelected, + ClearObjects, + InspectEntry { + frame: usize, + item: Option, + }, + ConsoleSubmit(String), + /// Tab in the console input. + ConsoleComplete, + /// Fresh console namespace. + ResetConsole, + StartUpload { + url: String, + file_type: String, + }, +} + +const fn key(key: Key) -> KeyboardShortcut { + KeyboardShortcut::new(Modifiers::NONE, key) +} + +const fn ctrl(key: Key) -> KeyboardShortcut { + KeyboardShortcut::new(Modifiers::COMMAND, key) +} + +const fn shift(key: Key) -> KeyboardShortcut { + KeyboardShortcut::new(Modifiers::SHIFT, key) +} + +const fn alt(key: Key) -> KeyboardShortcut { + KeyboardShortcut::new(Modifiers::ALT, key) +} + +const fn shift_alt(key: Key) -> KeyboardShortcut { + KeyboardShortcut::new(Modifiers::SHIFT.plus(Modifiers::ALT), key) +} + +const fn ctrl_shift(key: Key) -> KeyboardShortcut { + KeyboardShortcut::new(Modifiers::COMMAND.plus(Modifiers::SHIFT), key) +} + +/// The shortcut shown next to an action in menus and tooltips. +pub fn shortcut(action: &Action) -> Option { + shortcuts() + .into_iter() + .chain(editor_shortcuts()) + .find(|(a, _)| a == action) + .map(|(_, shortcut)| shortcut) +} + +/// Shortcuts the code editor handles itself, only while it has the +/// keyboard focus: the console and the search fields keep their own undo. +/// Ctrl+Shift+Z also redoes. +pub fn editor_shortcuts() -> Vec<(Action, KeyboardShortcut)> { + vec![(Action::Undo, ctrl(Key::Z)), (Action::Redo, ctrl(Key::Y))] +} + +/// All global shortcuts, most specific first: egui ignores extra Shift/Alt +/// when matching, so Shift+F5 must be checked before F5. +pub fn shortcuts() -> Vec<(Action, KeyboardShortcut)> { + let mut all = vec![ + (Action::NewFile, ctrl(Key::N)), + (Action::OpenFile, ctrl(Key::O)), + (Action::SaveAs, ctrl_shift(Key::S)), + (Action::Save, ctrl(Key::S)), + (Action::OpenFolder, ctrl_shift(Key::O)), + (Action::CloseTab, ctrl(Key::W)), + (Action::PreviousTab, ctrl_shift(Key::Tab)), + (Action::NextTab, ctrl(Key::Tab)), + (Action::PreviousTab, ctrl(Key::PageUp)), + (Action::NextTab, ctrl(Key::PageDown)), + (Action::Quit, ctrl(Key::Q)), + (Action::ToggleComment, ctrl(Key::Slash)), + (Action::DuplicateLine, ctrl_shift(Key::D)), + (Action::DuplicateLine, shift_alt(Key::ArrowDown)), + (Action::MoveLineUp, alt(Key::ArrowUp)), + (Action::MoveLineDown, alt(Key::ArrowDown)), + (Action::Autocomplete, ctrl(Key::Space)), + (Action::Autocomplete, alt(Key::Slash)), + (Action::Find, ctrl(Key::F)), + (Action::Replace, ctrl(Key::H)), + (Action::GoToLinePrompt, ctrl(Key::G)), + (Action::ShowOutline, alt(Key::O)), + (Action::GoToDefinition, key(Key::F12)), + (Action::FindReferences, ctrl_shift(Key::F12)), + (Action::InsertSelector, ctrl_shift(Key::I)), + (Action::GoToSelectionSource, ctrl_shift(Key::G)), + (Action::FindPrevious, alt(Key::F3)), + (Action::FindNext, key(Key::F3)), + (Action::Preferences, ctrl(Key::Comma)), + (Action::CommandPalette, ctrl_shift(Key::P)), + (Action::ToggleMaximize(None), ctrl_shift(Key::M)), + (Action::Stop, ctrl_shift(Key::F5)), + (Action::ToggleDebug, ctrl(Key::F5)), + (Action::Render, key(Key::F5)), + (Action::Profile, alt(Key::F5)), + (Action::Debug(DebugAction::Step), ctrl(Key::F10)), + (Action::Debug(DebugAction::StepOut), ctrl_shift(Key::F11)), + (Action::Debug(DebugAction::StepIn), ctrl(Key::F11)), + (Action::Debug(DebugAction::Continue), ctrl(Key::F12)), + (Action::Fit, shift(Key::F1)), + (Action::View(StandardView::Iso), shift(Key::F2)), + (Action::View(StandardView::Top), shift(Key::F3)), + (Action::View(StandardView::Bottom), shift(Key::F4)), + (Action::View(StandardView::Front), shift(Key::F5)), + (Action::View(StandardView::Back), shift(Key::F6)), + (Action::View(StandardView::Left), shift(Key::F7)), + (Action::View(StandardView::Right), shift(Key::F8)), + (Action::Display(DisplayMode::Wireframe), shift(Key::F9)), + (Action::Display(DisplayMode::Shaded), shift(Key::F10)), + (Action::Display(DisplayMode::XRay), shift(Key::F11)), + (Action::Display(DisplayMode::HiddenLine), shift(Key::F12)), + (Action::SelectionMode(SelectionMode::Auto), alt(Key::Num1)), + (Action::SelectionMode(SelectionMode::Object), alt(Key::Num2)), + (Action::SelectionMode(SelectionMode::Face), alt(Key::Num3)), + (Action::SelectionMode(SelectionMode::Edge), alt(Key::Num4)), + (Action::SelectionMode(SelectionMode::Vertex), alt(Key::Num5)), + ]; + let specificity = |s: &KeyboardShortcut| { + let m = s.modifiers; + u8::from(m.command || m.ctrl) + u8::from(m.shift) + u8::from(m.alt) + }; + // Stable, so equally specific shortcuts keep their listed order. + all.sort_by_key(|(_, s)| std::cmp::Reverse(specificity(s))); + all +} + +/// Queues the actions whose shortcuts were pressed this frame. +pub fn collect_shortcuts(ctx: &egui::Context, actions: &mut Vec) { + ctx.input_mut(|input| { + for (action, shortcut) in shortcuts() { + if input.consume_shortcut(&shortcut) { + actions.push(action); + } + } + }); +} + +/// Parses a user-configurable shortcut string such as `"1"`, `"F"`, `"Alt+1"`, +/// or `"Ctrl+Shift+F"`. +pub fn parse_shortcut(spec: &str) -> Option { + let parts: Vec<&str> = spec + .split('+') + .map(str::trim) + .filter(|part| !part.is_empty()) + .collect(); + let (&key_part, mod_parts) = parts.split_last()?; + let mut modifiers = Modifiers::NONE; + for part in mod_parts { + match part.to_ascii_lowercase().as_str() { + "ctrl" | "control" | "cmd" | "command" => { + modifiers = modifiers.plus(Modifiers::COMMAND) + } + "shift" => modifiers = modifiers.plus(Modifiers::SHIFT), + "alt" | "opt" | "option" => modifiers = modifiers.plus(Modifiers::ALT), + _ => return None, + } + } + let key = parse_key(key_part)?; + Some(KeyboardShortcut::new(modifiers, key)) +} + +fn parse_key(token: &str) -> Option { + match token.to_ascii_uppercase().as_str() { + "0" => Some(Key::Num0), + "1" => Some(Key::Num1), + "2" => Some(Key::Num2), + "3" => Some(Key::Num3), + "4" => Some(Key::Num4), + "5" => Some(Key::Num5), + "6" => Some(Key::Num6), + "7" => Some(Key::Num7), + "8" => Some(Key::Num8), + "9" => Some(Key::Num9), + "A" => Some(Key::A), + "B" => Some(Key::B), + "C" => Some(Key::C), + "D" => Some(Key::D), + "E" => Some(Key::E), + "F" => Some(Key::F), + "G" => Some(Key::G), + "H" => Some(Key::H), + "I" => Some(Key::I), + "J" => Some(Key::J), + "K" => Some(Key::K), + "L" => Some(Key::L), + "M" => Some(Key::M), + "N" => Some(Key::N), + "O" => Some(Key::O), + "P" => Some(Key::P), + "Q" => Some(Key::Q), + "R" => Some(Key::R), + "S" => Some(Key::S), + "T" => Some(Key::T), + "U" => Some(Key::U), + "V" => Some(Key::V), + "W" => Some(Key::W), + "X" => Some(Key::X), + "Y" => Some(Key::Y), + "Z" => Some(Key::Z), + "F1" => Some(Key::F1), + "F2" => Some(Key::F2), + "F3" => Some(Key::F3), + "F4" => Some(Key::F4), + "F5" => Some(Key::F5), + "F6" => Some(Key::F6), + "F7" => Some(Key::F7), + "F8" => Some(Key::F8), + "F9" => Some(Key::F9), + "F10" => Some(Key::F10), + "F11" => Some(Key::F11), + "F12" => Some(Key::F12), + _ => None, + } +} + +/// Checks configurable 3D selection mode shortcuts. Plain keys (without Ctrl/Alt) +/// are only consumed when no text editor or input field has keyboard focus. +pub fn collect_selection_shortcuts( + ctx: &egui::Context, + config: &SelectionShortcuts, + actions: &mut Vec, +) { + let text_focused = ctx.egui_wants_keyboard_input(); + let mut bindings: Vec<(SelectionMode, KeyboardShortcut)> = SelectionMode::ALL + .into_iter() + .filter_map(|mode| { + let shortcut = parse_shortcut(config.get(mode))?; + let has_modifier = + shortcut.modifiers.command || shortcut.modifiers.ctrl || shortcut.modifiers.alt; + if text_focused && !has_modifier { + return None; + } + Some((mode, shortcut)) + }) + .collect(); + let specificity = |s: &KeyboardShortcut| { + let m = s.modifiers; + u8::from(m.command || m.ctrl) + u8::from(m.shift) + u8::from(m.alt) + }; + bindings.sort_by_key(|(_, s)| std::cmp::Reverse(specificity(s))); + + ctx.input_mut(|input| { + for (mode, shortcut) in bindings { + if input.consume_shortcut(&shortcut) { + actions.push(Action::SelectionMode(mode)); + } + } + }); +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_commands.rs"] +mod tests; diff --git a/src/dialogs/capture.rs b/src/dialogs/capture.rs new file mode 100644 index 000000000..47e2bc6d9 --- /dev/null +++ b/src/dialogs/capture.rs @@ -0,0 +1,210 @@ +//! Screenshot and turntable animation options (Tools > Screenshot…). + +use egui_phosphor::regular as icon; + +use crate::commands::Action; +use crate::viewer::capture::{ + AnimationFormat, CaptureOptions, MAX_FRAMES_PER_SECOND, MAX_IMAGE_SIDE, MAX_TURNTABLE_FRAMES, + ResolutionPreset, TurntableOptions, aspect_ratio_label, +}; + +pub struct CaptureDialog { + pub open: bool, + pub options: CaptureOptions, + pub turntable: TurntableOptions, + /// The size typed for a custom size, kept while another is chosen. + custom: [u32; 2], +} + +impl Default for CaptureDialog { + fn default() -> Self { + Self { + open: false, + options: CaptureOptions::default(), + turntable: TurntableOptions::default(), + custom: [1920, 1080], + } + } +} + +/// `view` is the size of the 3D view in pixels; `progress` the frames of a +/// turntable being exported. +pub fn window( + ctx: &egui::Context, + dialog: &mut CaptureDialog, + view: [u32; 2], + progress: Option<(u32, u32)>, + actions: &mut Vec, +) { + let mut open = dialog.open; + egui::Window::new(format!("{} Screenshot", icon::CAMERA)) + .open(&mut open) + .collapsible(false) + .resizable(false) + .show(ctx, |ui| { + egui::Grid::new("capture_grid") + .num_columns(2) + .spacing([12.0, 8.0]) + .show(ui, |ui| { + image_rows(ui, dialog, view); + ui.label(""); + ui.horizontal(|ui| { + if ui + .button(format!("{} Save Image…", icon::CAMERA)) + .on_hover_text("Save the view as a PNG image") + .clicked() + { + actions.push(Action::SaveImage); + } + if ui + .button(format!("{} Copy to Clipboard", icon::COPY)) + .on_hover_text("Copy the rendered image directly to the clipboard") + .clicked() + { + actions.push(Action::CopyImage); + } + }); + ui.end_row(); + }); + ui.separator(); + ui.strong("Turntable animation"); + egui::Grid::new("turntable_grid") + .num_columns(2) + .spacing([12.0, 8.0]) + .show(ui, |ui| { + turntable_rows(ui, &mut dialog.turntable); + ui.label(""); + match progress { + Some((written, frames)) => { + ui.horizontal(|ui| { + ui.add( + egui::ProgressBar::new(written as f32 / frames.max(1) as f32) + .desired_width(160.0) + .text(format!("{written}/{frames}")), + ); + if ui.button("Cancel").clicked() { + actions.push(Action::CancelTurntable); + } + }); + } + None => { + if ui + .button(format!("{} Export Turntable…", icon::FILM_STRIP)) + .on_hover_text( + "One turn of the camera around the model, \ + from the current view, with the size above", + ) + .clicked() + { + actions.push(Action::ExportTurntable); + } + } + } + ui.end_row(); + }); + }); + dialog.open = open; +} + +fn image_rows(ui: &mut egui::Ui, dialog: &mut CaptureDialog, view: [u32; 2]) { + let options = &mut dialog.options; + ui.label("Size"); + ui.vertical(|ui| { + ui.horizontal(|ui| { + for scale in [1, 2, 4] { + let selected = options.size.is_none() && options.scale == scale; + if ui + .selectable_label(selected, format!("View ×{scale}")) + .on_hover_text("The view's size in pixels, times this") + .clicked() + { + options.size = None; + options.scale = scale; + } + } + if ui + .selectable_label(options.size.is_some(), "Custom / Preset") + .clicked() + { + options.size = Some(dialog.custom); + } + }); + ui.horizontal_wrapped(|ui| { + ui.weak("Presets:"); + for preset in ResolutionPreset::ALL { + let selected = options.size == Some(preset.size()); + if ui + .selectable_label(selected, preset.short_label()) + .on_hover_text(preset.label()) + .clicked() + { + options.size = Some(preset.size()); + dialog.custom = preset.size(); + } + } + }); + if let Some(size) = &mut options.size { + ui.horizontal(|ui| { + for (index, side) in size.iter_mut().enumerate() { + if index == 1 { + ui.label("×"); + } + ui.add(egui::DragValue::new(side).range(16..=MAX_IMAGE_SIDE)); + } + ui.label("px"); + }); + dialog.custom = *size; + } + let [width, height] = options.image_size(view); + let ratio = aspect_ratio_label([width, height]); + ui.weak(format!("{width} × {height} pixels ({ratio})")); + }); + ui.end_row(); + + ui.label("Background"); + ui.checkbox(&mut options.transparent, "Transparent") + .on_hover_text("Only the model; the background is left out of the PNG"); + ui.end_row(); +} + +fn turntable_rows(ui: &mut egui::Ui, turntable: &mut TurntableOptions) { + ui.label("Frames"); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut turntable.frames).range(4..=MAX_TURNTABLE_FRAMES)); + ui.label("at"); + ui.add( + egui::DragValue::new(&mut turntable.frames_per_second) + .range(1..=MAX_FRAMES_PER_SECOND) + .suffix(" fps"), + ); + ui.weak(format!( + "{:.1} s per turn", + turntable.frames as f32 / turntable.frames_per_second.max(1) as f32 + )); + }); + ui.end_row(); + + ui.label("Direction"); + ui.horizontal(|ui| { + ui.radio_value(&mut turntable.clockwise, false, "Counterclockwise"); + ui.radio_value(&mut turntable.clockwise, true, "Clockwise"); + }) + .response + .on_hover_text("How the model turns, seen from above"); + ui.end_row(); + + ui.label("Format"); + ui.vertical(|ui| { + ui.radio_value( + &mut turntable.format, + AnimationFormat::AnimatedPng, + "Animated PNG (one file, plays in browsers)", + ); + ui.radio_value( + &mut turntable.format, + AnimationFormat::PngFiles, + "PNG files (name_0001.png …, for video tools)", + ); + }); + ui.end_row(); +} diff --git a/src/dialogs/environment.rs b/src/dialogs/environment.rs new file mode 100644 index 000000000..b52444358 --- /dev/null +++ b/src/dialogs/environment.rs @@ -0,0 +1,258 @@ +//! Creating a Python environment with CadQuery, or installing packages into +//! the interpreter in use, from Preferences > General (FEAT-E3). + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use egui_phosphor::regular as icon; + +use crate::commands::Action; +use crate::environments::{ + DEFAULT_PACKAGES, Job, JobState, create_steps, install_steps, parse_packages, +}; +use crate::worker::launch::venv_python; + +/// What the dialog does. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + /// A new virtual environment with CadQuery and jedi. + Create, + /// Packages into an existing interpreter. + Install, +} + +pub struct EnvironmentDialog { + mode: Mode, + /// Create: the environment's folder and the Python that makes it. + folder: String, + base: String, + /// Install: the interpreter that gets the packages. + target: String, + packages: String, + /// Interpreters found on this computer, to pick from. + candidates: Vec, + job: Option, + problem: Option, +} + +impl EnvironmentDialog { + /// Creating an environment in `folder` with the interpreter `base`. + pub fn create(folder: PathBuf, base: PathBuf, candidates: Vec) -> Self { + Self { + mode: Mode::Create, + folder: folder.display().to_string(), + base: base.display().to_string(), + target: String::new(), + packages: DEFAULT_PACKAGES.to_owned(), + candidates, + job: None, + problem: None, + } + } + + /// Installing packages into the interpreter `python`. + pub fn install(python: PathBuf, candidates: Vec) -> Self { + Self { + mode: Mode::Install, + folder: String::new(), + base: String::new(), + target: python.display().to_string(), + packages: String::new(), + candidates, + job: None, + problem: None, + } + } + + fn running(&self) -> bool { + self.job + .as_ref() + .is_some_and(|job| *job.state() == JobState::Running) + } + + /// Checks the fields and starts the commands. + fn start(&mut self) { + self.problem = None; + let packages = match parse_packages(&self.packages) { + Ok(packages) => packages, + Err(problem) => { + self.problem = Some(problem); + return; + } + }; + let steps = match self.mode { + Mode::Create => { + let folder = PathBuf::from(self.folder.trim()); + if self.folder.trim().is_empty() { + self.problem = Some("Choose a folder for the environment".to_owned()); + return; + } + if std::fs::read_dir(&folder).is_ok_and(|mut entries| entries.next().is_some()) { + self.problem = Some(format!( + "{} is not empty; choose a new or empty folder", + folder.display() + )); + return; + } + create_steps(Path::new(self.base.trim()), &folder, &packages) + } + Mode::Install => install_steps(Path::new(self.target.trim()), &packages), + }; + self.job = Some(Job::start(steps)); + } + + /// Returns `false` once the window was closed (which stops a running + /// job). + pub fn window(&mut self, ctx: &egui::Context, actions: &mut Vec) -> bool { + if let Some(job) = &mut self.job + && *job.poll() == JobState::Running + { + ctx.request_repaint_after(Duration::from_millis(100)); + } + let title = match self.mode { + Mode::Create => format!("{} Create Python Environment", icon::PLUS_CIRCLE), + Mode::Install => format!("{} Install Packages", icon::PACKAGE), + }; + let mut open = true; + egui::Window::new(title) + .open(&mut open) + .collapsible(false) + .default_size([620.0, 420.0]) + .show(ctx, |ui| { + ui.add_enabled_ui(!self.running(), |ui| self.fields(ui)); + ui.separator(); + self.progress(ui, actions); + }); + open + } + + fn fields(&mut self, ui: &mut egui::Ui) { + egui::Grid::new("environment_grid") + .num_columns(2) + .spacing([12.0, 8.0]) + .show(ui, |ui| { + match self.mode { + Mode::Create => { + ui.label("Folder"); + ui.horizontal(|ui| { + ui.add( + egui::TextEdit::singleline(&mut self.folder).desired_width(380.0), + ); + if ui + .button(icon::FOLDER_OPEN) + .on_hover_text("Browse…") + .clicked() + && let Some(folder) = rfd::FileDialog::new().pick_folder() + { + self.folder = folder.display().to_string(); + } + }); + ui.end_row(); + ui.label("Made with") + .on_hover_text("The Python that creates it (3.10 or newer)"); + interpreter_field(ui, &mut self.base, &self.candidates); + ui.end_row(); + } + Mode::Install => { + ui.label("Into"); + interpreter_field(ui, &mut self.target, &self.candidates); + ui.end_row(); + } + } + ui.label("Packages").on_hover_text( + "Names as for pip install, separated by spaces: cadquery, \ + ocp-vscode>=2, trimesh[easy]…", + ); + ui.add( + egui::TextEdit::singleline(&mut self.packages) + .desired_width(380.0) + .hint_text("for example: trimesh numpy-stl"), + ); + ui.end_row(); + }); + } + + fn progress(&mut self, ui: &mut egui::Ui, actions: &mut Vec) { + ui.horizontal(|ui| { + if self.running() { + ui.spinner(); + ui.label("Working… (downloading CadQuery takes a few minutes)"); + if ui.button("Cancel").clicked() + && let Some(job) = &self.job + { + job.cancel(); + } + return; + } + let start = match self.mode { + Mode::Create => "Create", + Mode::Install => "Install", + }; + if ui.button(start).clicked() { + self.start(); + } + match self.job.as_ref().map(Job::state) { + Some(JobState::Succeeded) => match self.mode { + Mode::Create => { + ui.colored_label(ui.visuals().text_color(), "Done."); + let python = venv_python(Path::new(self.folder.trim())); + if ui + .button(format!("{} Use this environment", icon::CHECK)) + .on_hover_text(python.display().to_string()) + .clicked() + { + actions.push(Action::UsePython(python)); + } + } + Mode::Install => { + ui.label("Installed; restart Python to import them."); + if ui.button("Restart Python").clicked() { + actions.push(Action::RestartPython); + } + } + }, + Some(JobState::Failed(problem)) => { + ui.colored_label(ui.visuals().error_fg_color, problem); + } + Some(JobState::Cancelled) => { + ui.weak("Cancelled."); + } + Some(JobState::Running) | None => {} + } + }); + if let Some(problem) = &self.problem { + ui.colored_label(ui.visuals().error_fg_color, problem); + } + if let Some(job) = &self.job { + egui::ScrollArea::vertical() + .stick_to_bottom(true) + .auto_shrink([false, false]) + .show(ui, |ui| { + for line in job.output() { + ui.monospace(line); + } + }); + } + } +} + +/// A path typed or picked among the interpreters found. +fn interpreter_field(ui: &mut egui::Ui, path: &mut String, candidates: &[PathBuf]) { + ui.horizontal(|ui| { + ui.add(egui::TextEdit::singleline(path).desired_width(350.0)); + ui.menu_button(icon::LIST_BULLETS, |ui| { + if candidates.is_empty() { + ui.weak("No other Python found"); + } + for candidate in candidates { + let text = candidate.display().to_string(); + if ui.button(&text).clicked() { + *path = text; + ui.close(); + } + } + }) + .response + .on_hover_text("Pythons found on this computer"); + }); +} diff --git a/src/dialogs/mod.rs b/src/dialogs/mod.rs new file mode 100644 index 000000000..7f85f8e81 --- /dev/null +++ b/src/dialogs/mod.rs @@ -0,0 +1,1409 @@ +//! Modal and floating windows: preferences, upload, about, unsaved changes, +//! the Project panel's prompts and messages. + +pub mod capture; +pub mod environment; +pub mod preferences; +pub mod upload; + +use std::path::{Path, PathBuf}; + +use egui::{Align2, RichText}; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::document::{DiskVersion, Encoding}; +use crate::recovery::RecoverySnapshot; +use crate::settings::Units; +use crate::worker::Problem; +use crate::worker::protocol::{ExportFormat, GeometryReport, InterferenceReport}; + +/// Something that would discard unsaved changes, waiting for confirmation. +#[derive(Clone, Debug, PartialEq)] +pub enum Intent { + /// Close the tabs of these documents (by generation). + Close(Vec), + Quit, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnsavedChoice { + Save, + Discard, + Cancel, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExternalChangeChoice { + Reload, + /// Keep the buffer; a save that asked goes ahead over the disk version. + KeepLocal, + SaveCopy, + /// A save that asked is given up; nothing changes. + Cancel, +} + +/// An on-disk edit that conflicts with the editor contents. +pub struct ExternalChange { + /// The open document (generation) in conflict, whichever tab is shown. + pub document: u64, + pub path: PathBuf, + pub disk: DiskVersion, + pub show_comparison: bool, + pub rerun_after_resolution: bool, + /// Found by a save, which waits for the answer, rather than by the + /// file watcher. + pub on_save: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RecoverySessionChoice { + Restore, + Discard, +} + +/// The unsaved documents of an interrupted session, waiting for a decision. +pub struct RecoverySession { + pub documents: Vec, + /// The one previewed. + pub selected: usize, +} + +/// A question of the Project panel: a name for a new or renamed file or +/// folder, or the confirmation of a deletion. +pub enum FilePrompt { + NewFile { + folder: PathBuf, + name: String, + error: Option, + }, + NewFolder { + folder: PathBuf, + name: String, + error: Option, + }, + Rename { + path: PathBuf, + name: String, + error: Option, + }, + Delete { + path: PathBuf, + /// Open files below it with unsaved changes, which would be lost. + unsaved: Vec, + error: Option, + }, +} + +impl FilePrompt { + pub fn rename(path: &Path) -> Self { + FilePrompt::Rename { + path: path.to_path_buf(), + name: path + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(), + error: None, + } + } +} + +pub struct HistoryDialog { + /// The tab whose history was opened, independent of the shown tab. + pub document: u64, + pub versions: Vec, + pub selected: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExportScope { + Selection, + Visible, + Everything, +} + +#[derive(Clone, Debug)] +pub struct ExportDialog { + pub format: ExportFormat, + pub scope: ExportScope, + pub step_fused: bool, + pub step_ap242: bool, + pub stl_ascii: bool, + pub tolerance: f64, + pub angular_tolerance: f64, + pub unit: Units, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GeometryChoice { + Cancel, + ExportAnyway, + TryFix, + SelectPair(usize), +} + +pub struct GeometryDialog { + pub reports: Vec, + pub interferences: Vec, + pub for_export: bool, + pub selected_pair: Option, +} + +impl ExportDialog { + pub fn new(format: ExportFormat, tolerance: f64, angular_tolerance: f64, unit: Units) -> Self { + Self { + format, + scope: ExportScope::Everything, + step_fused: false, + step_ap242: true, + stl_ascii: false, + tolerance, + angular_tolerance, + unit, + } + } +} + +enum HistoryChoice { + Restore(RecoverySnapshot), + Close, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MessageKind { + Info, + Error, +} + +pub struct Message { + pub title: String, + pub text: String, + pub kind: MessageKind, +} + +#[derive(Default)] +pub struct Dialogs { + pub preferences: bool, + pub preferences_page: preferences::Page, + pub about: bool, + pub upload: Option, + pub capture: capture::CaptureDialog, + pub environment: Option, + pub unsaved: Option, + pub external_change: Option, + /// Conflicts in other tabs, asked about once the shown one is resolved. + pub external_queue: Vec, + pub recovery_session: Option, + pub file_prompt: Option, + /// The command palette, while it is open. + pub palette: Option, + pub history: Option, + pub export: Option, + pub geometry: Option, + /// A file that is not UTF-8, waiting for permission to read it as + /// Windows-1252. + pub legacy_encoding: Option, + pub message: Option, + /// Interpreters found on this computer, looked for once Python failed. + pub python_candidates: Option>, +} + +impl Dialogs { + /// Whether a modal dialog is shown. Global shortcuts wait until it is + /// answered, so nothing changes behind the question it asks. + pub fn modal_open(&self) -> bool { + self.about + || self.unsaved.is_some() + || self.external_change.is_some() + || self.recovery_session.is_some() + || self.file_prompt.is_some() + || self.palette.is_some() + || self.history.is_some() + || self.export.is_some() + || self.geometry.is_some() + || self.legacy_encoding.is_some() + || self.message.is_some() + } + + pub fn info(&mut self, title: &str, text: impl Into) { + self.message = Some(Message { + title: title.to_owned(), + text: text.into(), + kind: MessageKind::Info, + }); + } + + pub fn error(&mut self, title: &str, text: impl Into) { + self.message = Some(Message { + title: title.to_owned(), + text: text.into(), + kind: MessageKind::Error, + }); + } +} + +pub fn show(ctx: &egui::Context, state: &mut AppState) { + let mut actions = Vec::new(); + + if state.dialogs.preferences { + let dialogs = &mut state.dialogs; + preferences::window( + ctx, + &mut dialogs.preferences, + &mut dialogs.preferences_page, + &mut state.settings, + &mut actions, + ); + } + + if let Some(upload) = &mut state.dialogs.upload + && !upload.window(ctx, &mut actions) + { + state.dialogs.upload = None; + } + + if let Some(dialog) = &mut state.dialogs.environment + && !dialog.window(ctx, &mut actions) + { + state.dialogs.environment = None; + } + + if state.dialogs.capture.open { + capture::window( + ctx, + &mut state.dialogs.capture, + state.viewer.view_px(), + state.viewer.turntable_progress(), + &mut actions, + ); + } + + if state.dialogs.about { + about(ctx, state); + } + + let recovery_was_open = state.dialogs.recovery_session.is_some(); + let recovery_choice = state + .dialogs + .recovery_session + .as_mut() + .and_then(|session| recovery_session(ctx, session)); + if let Some(choice) = recovery_choice + && let Some(session) = state.dialogs.recovery_session.take() + { + state.resolve_recovery_session(session, choice == RecoverySessionChoice::Restore); + } + if recovery_was_open { + state.queue(actions); + return; + } + + if state.dialogs.palette.is_some() { + let commands = crate::ui::command_palette::commands(state); + let palette = state.dialogs.palette.as_mut().expect("open"); + if let Some(chosen) = + crate::ui::command_palette::window(ctx, palette, commands, &mut state.settings) + { + state.dialogs.palette = None; + actions.extend(chosen); + } + } + + if let Some(intent) = state.dialogs.unsaved.clone() { + let names = state.names_of(&state.unsaved_of(&intent)); + // Saved meanwhile: nothing is left to ask about. + let choice = if names.is_empty() { + Some(UnsavedChoice::Discard) + } else { + unsaved_changes(ctx, &names, intent == Intent::Quit) + }; + if let Some(choice) = choice { + state.dialogs.unsaved = None; + state.resolve_unsaved(intent, choice); + } + } + + if let Some(prompt) = &mut state.dialogs.file_prompt + && let Some(confirmed) = file_prompt(ctx, prompt) + { + if confirmed { + let prompt = state.dialogs.file_prompt.take().expect("shown"); + if let Some(error) = state.confirm_file_prompt(&prompt) { + state.dialogs.file_prompt = Some(prompt.with_error(error)); + } + } else { + state.dialogs.file_prompt = None; + } + } + + if let Some(path) = state.dialogs.legacy_encoding.clone() + && let Some(open) = legacy_encoding(ctx, &path) + { + state.dialogs.legacy_encoding = None; + if open { + state.open_path_with(&path, Encoding::Windows1252); + } + } + + // About the document in conflict, not the tab shown. + let conflicted = state + .dialogs + .external_change + .as_ref() + .map(|change| state.document_of(change.document)) + .map(|document| document.map(|d| (d.display_name(), d.text.clone()))); + let external_choice = match (conflicted, state.dialogs.external_change.as_mut()) { + (Some(Some((name, text))), Some(change)) => external_change(ctx, &name, &text, change), + // Its tab was closed meanwhile: nothing is left to decide. + (Some(None), Some(_)) => Some(ExternalChangeChoice::KeepLocal), + _ => None, + }; + if let Some(choice) = external_choice + && let Some(change) = state.dialogs.external_change.take() + { + state.resolve_external_change(change, choice); + } + + let history_choice = state + .dialogs + .history + .as_mut() + .and_then(|history| local_history(ctx, history)); + match history_choice { + Some(HistoryChoice::Restore(snapshot)) => { + if let Some(history) = state.dialogs.history.take() { + state.restore_history(history.document, snapshot); + } + } + Some(HistoryChoice::Close) => state.dialogs.history = None, + None => {} + } + + let selected = state.scene.selected_roots().len(); + let visible = state + .scene + .visible_nodes() + .iter() + .filter(|node| !node.parts.is_empty()) + .count(); + let everything = state.scene.top_level_keys().len(); + let export_choice = state + .dialogs + .export + .as_mut() + .and_then(|dialog| export_options(ctx, dialog, selected, visible, everything)); + if let Some(confirmed) = export_choice + && let Some(options) = state.dialogs.export.take() + && confirmed + { + state.export_confirmed(options); + } + let geometry_choice = state + .dialogs + .geometry + .as_ref() + .and_then(|dialog| geometry_review(ctx, dialog)); + if let Some(choice) = geometry_choice { + if let GeometryChoice::SelectPair(index) = choice { + if let Some(pair) = state.dialogs.geometry.as_mut().and_then(|dialog| { + dialog.selected_pair = Some(index); + dialog.interferences.get(index).cloned() + }) { + let first = pair.first.key.clone(); + let second = pair.second.key.clone(); + state.scene.select_only(&first); + if first != second { + state.scene.toggle_selected(&second); + } + state + .viewer + .fit_selection(&state.scene, true, ctx.input(|input| input.time)); + state.show_interference(&pair); + } + } else if let Some(dialog) = state.dialogs.geometry.take() + && dialog.for_export + { + state.resolve_geometry_export(choice); + } + } + + if let Some(message) = &state.dialogs.message + && message_box(ctx, message) + { + state.dialogs.message = None; + } + + state.queue(actions); +} + +fn modal_frame(ctx: &egui::Context) -> egui::Frame { + egui::Frame::popup(&ctx.style_of(ctx.theme())).inner_margin(egui::Margin::same(18)) +} + +fn export_options( + ctx: &egui::Context, + options: &mut ExportDialog, + selected: usize, + visible: usize, + everything: usize, +) -> Option { + let mut choice = None; + let response = egui::Modal::new(egui::Id::new("export_options")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(390.0); + ui.heading("Export model"); + egui::ComboBox::from_label("Format") + .selected_text(options.format.label()) + .show_ui(ui, |ui| { + for format in ExportFormat::ALL { + ui.selectable_value(&mut options.format, format, format.label()); + } + }); + ui.separator(); + egui::ComboBox::from_label("Model unit") + .selected_text(options.unit.label()) + .show_ui(ui, |ui| { + for unit in Units::ALL.into_iter().filter(|unit| *unit != Units::None) { + ui.selectable_value(&mut options.unit, unit, unit.label()); + } + }); + if options.unit == Units::None { + ui.colored_label( + ui.visuals().warn_fg_color, + "Choose the unit represented by one model unit.", + ); + } + if matches!(options.format, ExportFormat::Stl | ExportFormat::Dxf) { + ui.weak( + "This file format has no unit metadata. Tell the recipient the model unit.", + ); + } + ui.separator(); + ui.label("Objects"); + ui.add_enabled_ui(selected > 0, |ui| { + ui.radio_value( + &mut options.scope, + ExportScope::Selection, + format!("Selection ({selected})"), + ); + }); + ui.add_enabled_ui(visible > 0, |ui| { + ui.radio_value( + &mut options.scope, + ExportScope::Visible, + format!("Visible parts ({visible})"), + ); + }); + ui.radio_value( + &mut options.scope, + ExportScope::Everything, + format!("Everything ({everything})"), + ); + if options.format == ExportFormat::Step { + ui.separator(); + ui.checkbox(&mut options.step_fused, "Fuse STEP assembly"); + ui.checkbox(&mut options.step_ap242, "STEP AP242 (uncheck for AP214)"); + } + if options.format == ExportFormat::Stl { + ui.separator(); + ui.checkbox(&mut options.stl_ascii, "ASCII STL (larger file)"); + } + if matches!( + options.format, + ExportFormat::Stl + | ExportFormat::ThreeMf + | ExportFormat::Gltf + | ExportFormat::Glb + | ExportFormat::Amf + | ExportFormat::Vrml + | ExportFormat::Vtkjs + ) { + ui.horizontal(|ui| { + ui.label("Linear tolerance"); + ui.add( + egui::DragValue::new(&mut options.tolerance) + .speed(0.01) + .range(0.0001..=100.0), + ); + }); + ui.horizontal(|ui| { + ui.label("Angular tolerance (rad)"); + ui.add( + egui::DragValue::new(&mut options.angular_tolerance) + .speed(0.01) + .range(0.0001..=std::f64::consts::PI), + ); + }); + } + let note = match options.format { + ExportFormat::Step | ExportFormat::Gltf | ExportFormat::Glb | ExportFormat::Xbf => { + "Keeps object hierarchy, names and colors." + } + ExportFormat::ThreeMf => "Keeps part names and colors for 3D printing.", + ExportFormat::Stl + | ExportFormat::Brep + | ExportFormat::Amf + | ExportFormat::Vrml + | ExportFormat::Vtkjs => "This format may not keep hierarchy or display colors.", + ExportFormat::Svg => "Exports a projected hidden-line drawing.", + ExportFormat::Dxf => "Requires planar faces or a 2D section.", + }; + ui.weak(note); + ui.add_space(10.0); + ui.horizontal(|ui| { + if ui.button("Cancel").clicked() { + choice = Some(false); + } + if ui + .add_enabled( + options.unit != Units::None, + egui::Button::new("Choose file…"), + ) + .clicked() + { + choice = Some(true); + } + }); + }); + if response.should_close() { + choice = Some(false); + } + choice +} + +fn geometry_review(ctx: &egui::Context, dialog: &GeometryDialog) -> Option { + let mut choice = None; + let response = egui::Modal::new(egui::Id::new("geometry_review")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(470.0); + ui.heading(if dialog.for_export { + "Geometry needs review" + } else { + "Geometry check" + }); + let invalid: Vec<_> = dialog + .reports + .iter() + .filter(|report| !report.valid) + .collect(); + let collisions = dialog + .interferences + .iter() + .filter(|pair| pair.kind == "interference" && pair.allowance_reason.is_none()) + .count(); + let accepted = dialog + .interferences + .iter() + .filter(|pair| pair.allowance_reason.is_some()) + .count(); + let uncertain = dialog + .interferences + .iter() + .filter(|pair| pair.kind == "inconclusive") + .count(); + if invalid.is_empty() { + ui.label(format!( + "{} object(s) have valid topology.", + dialog.reports.len() + )); + } else { + ui.label(format!( + "{} object(s) have geometry problems:", + invalid.len() + )); + egui::ScrollArea::vertical() + .max_height(250.0) + .show(ui, |ui| { + for report in &invalid { + ui.label(RichText::new(&report.name).strong()); + ui.weak(report.issues.join(" · ")); + ui.small(format!( + "{} solid(s) · {} open shell(s) · {} non-manifold edge(s)", + report.solids, report.open_shells, report.non_manifold_edges + )); + } + }); + } + if !dialog.interferences.is_empty() { + ui.label(format!( + "{collisions} interfering pair(s); {accepted} accepted pair(s); {uncertain} inconclusive pair(s)." + )); + egui::ScrollArea::vertical() + .max_height(250.0) + .show(ui, |ui| { + for (index, pair) in dialog.interferences.iter().enumerate() { + ui.horizontal(|ui| { + if ui.button("Select pair").clicked() { + choice = Some(GeometryChoice::SelectPair(index)); + } + ui.label(format!( + "{} [part {}, solid {}] / {} [part {}, solid {}]: {}", + pair.first.name, + pair.first.part + 1, + pair.first.solid + 1, + pair.second.name, + pair.second.part + 1, + pair.second.solid + 1, + pair.kind + )); + }); + if let Some(volume) = pair.overlap_volume + && pair.kind == "interference" + { + ui.small(format!("Shared volume: {volume:.6} model units³")); + } + if let Some(distance) = pair.distance + && pair.kind == "clearance" + { + ui.small(format!("Clearance: {distance:.6} model units")); + } + if let Some(reason) = &pair.reason { + ui.weak(reason); + } + if let Some(reason) = &pair.allowance_reason { + ui.small(format!("Accepted in script: {reason}")); + } + if let Some([x, y, z]) = pair.point { + ui.small(format!("Overlap center: ({x:.3}, {y:.3}, {z:.3})")); + } + } + }); + } + ui.add_space(10.0); + ui.horizontal(|ui| { + if ui + .button(if dialog.for_export { + "Cancel export" + } else { + "Close" + }) + .clicked() + { + choice = Some(GeometryChoice::Cancel); + } + if dialog.for_export { + if !invalid.is_empty() && ui.button("Try ShapeFix").clicked() { + choice = Some(GeometryChoice::TryFix); + } + if ui.button("Export anyway").clicked() { + choice = Some(GeometryChoice::ExportAnyway); + } + } + }); + }); + if response.should_close() { + choice = Some(GeometryChoice::Cancel); + } + choice +} + +fn about(ctx: &egui::Context, state: &mut AppState) { + let response = egui::Modal::new(egui::Id::new("about")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(380.0); + ui.vertical_centered(|ui| { + if let Some(logo) = state.logo(ctx) { + ui.add(egui::Image::new(&logo).fit_to_exact_size(egui::Vec2::splat(72.0))); + } + ui.add_space(6.0); + ui.label(RichText::new("CQ-editor").size(22.0).strong()); + ui.weak(format!("Version {}", env!("CARGO_PKG_VERSION"))); + ui.add_space(8.0); + ui.label("CadQuery script editor and 3D viewer."); + ui.weak("Rust interface (egui + wgpu) with a Python worker running CadQuery."); + ui.add_space(8.0); + if let Some(info) = state.worker.info() { + ui.weak(format!( + "Python {} · CadQuery {} · OCP {}", + info.python, info.cadquery, info.ocp + )); + } + ui.hyperlink_to( + format!("{} Source code", icon::GITHUB_LOGO), + "https://github.com/igors93/CQ-editor", + ); + ui.add_space(10.0); + if ui.button("Close").clicked() { + ui.close(); + } + }); + }); + if response.should_close() { + state.dialogs.about = false; + } +} + +/// Returns the user's choice once made about the unsaved changes to the +/// files `names`. +fn unsaved_changes(ctx: &egui::Context, names: &[String], quitting: bool) -> Option { + let mut choice = None; + let response = egui::Modal::new(egui::Id::new("unsaved_changes")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(380.0); + ui.horizontal(|ui| { + ui.label( + RichText::new(icon::WARNING) + .size(28.0) + .color(ui.visuals().warn_fg_color), + ); + ui.vertical(|ui| { + ui.label(RichText::new("Unsaved changes").strong().size(16.0)); + match names { + [name] => { + ui.label(format!("Save the changes to {name} first?")); + } + _ => { + ui.label(format!("Save the changes to {} files first?", names.len())); + egui::ScrollArea::vertical() + .max_height(140.0) + .show(ui, |ui| { + for name in names { + ui.label(format!("{} {name}", icon::FILE_PY)); + } + }); + } + } + if quitting { + ui.weak("Unsaved changes are lost when CQ-editor closes without saving."); + } + }); + }); + ui.add_space(12.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Cancel").clicked() { + choice = Some(UnsavedChoice::Cancel); + } + if ui.button("Don't save").clicked() { + choice = Some(UnsavedChoice::Discard); + } + let save = if names.len() > 1 { "Save all" } else { "Save" }; + if ui + .add( + egui::Button::new(RichText::new(save).strong()) + .fill(ui.visuals().selection.bg_fill), + ) + .clicked() + { + choice = Some(UnsavedChoice::Save); + } + }); + }); + if response.should_close() && choice.is_none() { + choice = Some(UnsavedChoice::Cancel); + } + choice +} + +impl FilePrompt { + fn with_error(mut self, message: String) -> Self { + match &mut self { + FilePrompt::NewFile { error, .. } + | FilePrompt::NewFolder { error, .. } + | FilePrompt::Rename { error, .. } + | FilePrompt::Delete { error, .. } => *error = Some(message), + } + self + } +} + +/// Asks for a name, or to confirm a deletion. Returns `Some(true)` once +/// confirmed and `Some(false)` once cancelled. +fn file_prompt(ctx: &egui::Context, prompt: &mut FilePrompt) -> Option { + let mut choice = None; + let display = |path: &Path| { + path.file_name().map_or_else( + || path.display().to_string(), + |n| n.to_string_lossy().into_owned(), + ) + }; + let (title, text, confirm) = match prompt { + FilePrompt::NewFile { folder, .. } => ( + "New file", + format!( + "A new file in {}. Without an extension, it is a Python script.", + display(folder) + ), + "Create", + ), + FilePrompt::NewFolder { folder, .. } => ( + "New folder", + format!("A new folder in {}.", display(folder)), + "Create", + ), + FilePrompt::Rename { path, .. } => ( + "Rename", + format!("A new name for {}.", display(path)), + "Rename", + ), + FilePrompt::Delete { path, .. } => { + let what = if path.is_dir() { + format!("Delete the folder {} and everything in it?", display(path)) + } else { + format!("Delete {}?", display(path)) + }; + ("Delete", what, "Delete") + } + }; + let response = egui::Modal::new(egui::Id::new("file_prompt")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(400.0); + ui.label(RichText::new(title).strong().size(16.0)); + ui.label(text); + ui.add_space(6.0); + let (name, error) = match prompt { + FilePrompt::NewFile { name, error, .. } + | FilePrompt::NewFolder { name, error, .. } + | FilePrompt::Rename { name, error, .. } => (Some(name), error), + FilePrompt::Delete { + unsaved, + error, + path, + } => { + if !unsaved.is_empty() { + ui.colored_label( + ui.visuals().warn_fg_color, + format!( + "{} {} unsaved changes, which will be lost.", + unsaved.join(", "), + if unsaved.len() == 1 { "has" } else { "have" } + ), + ); + } + if path.is_file() { + ui.weak("Its last version stays in the local history."); + } else { + ui.weak("This cannot be undone."); + } + (None, error) + } + }; + if let Some(name) = name { + let field = ui.add(egui::TextEdit::singleline(name).desired_width(f32::INFINITY)); + // The only text field: it keeps the keyboard, even from the + // code editor below the prompt. + if !field.has_focus() { + field.request_focus(); + } + if field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + choice = Some(true); + } + if field.changed() { + *error = None; + } + } + if let Some(error) = error { + ui.colored_label(ui.visuals().error_fg_color, error.as_str()); + } + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Cancel").clicked() { + choice = Some(false); + } + let destructive = matches!(prompt, FilePrompt::Delete { .. }); + let fill = if destructive { + ui.visuals().error_fg_color.gamma_multiply(0.35) + } else { + ui.visuals().selection.bg_fill + }; + if ui + .add(egui::Button::new(RichText::new(confirm).strong()).fill(fill)) + .clicked() + { + choice = Some(true); + } + }); + }); + if response.should_close() && choice.is_none() { + choice = Some(false); + } + choice +} + +/// Offers to read a file that is not UTF-8 as Windows-1252. Returns whether +/// to open it once the user decided. +fn legacy_encoding(ctx: &egui::Context, path: &Path) -> Option { + let mut choice = None; + let name = path.file_name().map_or_else( + || path.display().to_string(), + |n| n.to_string_lossy().into_owned(), + ); + let response = egui::Modal::new(egui::Id::new("legacy_encoding")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(440.0); + ui.horizontal(|ui| { + ui.label( + RichText::new(icon::WARNING) + .size(28.0) + .color(ui.visuals().warn_fg_color), + ); + ui.vertical(|ui| { + ui.label(RichText::new("Not a UTF-8 file").strong().size(16.0)); + ui.label(format!("{name} is not valid UTF-8 text.")) + .on_hover_text(path.display().to_string()); + ui.label( + "It can be opened as Windows-1252 (Western European), the usual \ + encoding of older Windows editors. Saving then converts it to \ + UTF-8, the encoding Python expects.", + ); + ui.weak("Opening does not change the file."); + }); + }); + ui.add_space(12.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Cancel").clicked() { + choice = Some(false); + } + if ui + .add( + egui::Button::new(RichText::new("Open as Windows-1252").strong()) + .fill(ui.visuals().selection.bg_fill), + ) + .clicked() + { + choice = Some(true); + } + }); + }); + if response.should_close() && choice.is_none() { + choice = Some(false); + } + choice +} + +/// Returns a resolution only after an explicit choice. Comparing keeps the +/// dialog open, and Escape takes the lossless path: keeping the buffer, or +/// giving up the save that asked. +fn external_change( + ctx: &egui::Context, + name: &str, + local_text: &str, + change: &mut ExternalChange, +) -> Option { + let mut choice = None; + let response = egui::Modal::new(egui::Id::new("external_change")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(if change.show_comparison { 760.0 } else { 500.0 }); + ui.horizontal(|ui| { + ui.label( + RichText::new(icon::WARNING) + .size(28.0) + .color(ui.visuals().warn_fg_color), + ); + ui.vertical(|ui| { + ui.label(RichText::new("File changed on disk").strong().size(16.0)); + if change.on_save { + ui.label(format!( + "{name} was changed by another program since you opened or \ + saved it. Saving would replace that version." + )); + ui.weak("Nothing was saved yet."); + } else { + ui.label(format!( + "{name} was changed by another program while you have unsaved \ + edits." + )); + ui.weak("Your editor contents have not been replaced."); + } + }); + }); + + if change.show_comparison { + ui.add_space(10.0); + ui.columns(2, |columns| { + let show_version = + |column: &mut egui::Ui, title: &str, text: &str, id: &str| { + column.label(RichText::new(title).strong()); + egui::Frame::group(column.style()).show(column, |ui| { + egui::ScrollArea::both().id_salt(id).max_height(300.0).show( + ui, + |ui| { + ui.add( + egui::Label::new(RichText::new(text).monospace()) + .selectable(true), + ); + }, + ); + }); + }; + show_version(&mut columns[0], "Your version", local_text, "local_change"); + show_version( + &mut columns[1], + "Version on disk", + &change.disk.text, + "disk_change", + ); + }); + } + + ui.add_space(12.0); + ui.weak( + "Reload creates a recovery backup before replacing the editor contents. \ + Saving a copy preserves your version separately, then reloads the disk version. \ + The disk version is kept in the local history before it is overwritten.", + ); + ui.add_space(8.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let keep = if change.on_save { + "Save my version" + } else { + "Keep my version" + }; + if ui + .add( + egui::Button::new(RichText::new(keep).strong()) + .fill(ui.visuals().selection.bg_fill), + ) + .clicked() + { + choice = Some(ExternalChangeChoice::KeepLocal); + } + if change.on_save && ui.button("Cancel").clicked() { + choice = Some(ExternalChangeChoice::Cancel); + } + if ui.button("Reload from disk").clicked() { + choice = Some(ExternalChangeChoice::Reload); + } + if ui.button("Save a copy…").clicked() { + choice = Some(ExternalChangeChoice::SaveCopy); + } + let compare = if change.show_comparison { + "Hide comparison" + } else { + "Compare changes" + }; + if ui.button(compare).clicked() { + change.show_comparison = !change.show_comparison; + } + }); + }); + if response.should_close() && choice.is_none() { + choice = Some(if change.on_save { + ExternalChangeChoice::Cancel + } else { + ExternalChangeChoice::KeepLocal + }); + } + choice +} + +fn recovery_session( + ctx: &egui::Context, + session: &mut RecoverySession, +) -> Option { + let mut choice = None; + egui::Modal::new(egui::Id::new("recovery_session")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(560.0); + ui.horizontal(|ui| { + ui.label( + RichText::new(icon::LIFEBUOY) + .size(28.0) + .color(ui.visuals().warn_fg_color), + ); + ui.vertical(|ui| { + ui.label( + RichText::new("Unsaved work can be recovered") + .strong() + .size(16.0), + ); + match session.documents.as_slice() { + [snapshot] => { + ui.label(format!( + "CQ-editor found an interrupted session for {}.", + snapshot.display_name() + )); + } + documents => { + ui.label(format!( + "CQ-editor found an interrupted session with unsaved changes \ + to {} files.", + documents.len() + )); + } + } + if let Some(snapshot) = session.documents.first() { + ui.weak(format!("Recovery checkpoint: {}", snapshot_time(snapshot))); + } + }); + }); + if session.documents.len() > 1 { + ui.add_space(6.0); + ui.horizontal_wrapped(|ui| { + for (index, snapshot) in session.documents.iter().enumerate() { + if ui + .selectable_label(session.selected == index, snapshot.display_name()) + .on_hover_text(snapshot.path.as_ref().map_or_else( + || "Untitled".to_owned(), + |path| path.display().to_string(), + )) + .clicked() + { + session.selected = index; + } + } + }); + } + ui.add_space(10.0); + if let Some(snapshot) = session.documents.get(session.selected) { + egui::Frame::group(ui.style()).show(ui, |ui| { + egui::ScrollArea::both() + .id_salt("recovery_preview") + .max_height(180.0) + .show(ui, |ui| { + ui.add( + egui::Label::new(RichText::new(&snapshot.text).monospace()) + .selectable(true), + ); + }); + }); + } + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .add( + egui::Button::new(RichText::new("Restore session").strong()) + .fill(ui.visuals().selection.bg_fill), + ) + .clicked() + { + choice = Some(RecoverySessionChoice::Restore); + } + if ui.button("Discard recovery").clicked() { + choice = Some(RecoverySessionChoice::Discard); + } + }); + }); + choice +} + +fn local_history(ctx: &egui::Context, history: &mut HistoryDialog) -> Option { + let mut choice = None; + let response = egui::Modal::new(egui::Id::new("local_history")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_width(760.0); + ui.label(RichText::new("Local history").strong().size(16.0)); + ui.weak("Recovery checkpoints are retained locally; the newest 20 versions are kept per document."); + ui.add_space(10.0); + ui.columns(2, |columns| { + columns[0].set_width(220.0); + egui::ScrollArea::vertical() + .id_salt("history_versions") + .max_height(360.0) + .show(&mut columns[0], |ui| { + for (index, snapshot) in history.versions.iter().enumerate() { + if ui + .selectable_label( + history.selected == index, + snapshot_time(snapshot), + ) + .clicked() + { + history.selected = index; + } + } + }); + if let Some(snapshot) = history.versions.get(history.selected) { + columns[1].label(RichText::new(snapshot.display_name()).strong()); + egui::Frame::group(columns[1].style()).show(&mut columns[1], |ui| { + egui::ScrollArea::both() + .id_salt("history_preview") + .max_height(330.0) + .show(ui, |ui| { + ui.add( + egui::Label::new(RichText::new(&snapshot.text).monospace()) + .selectable(true), + ); + }); + }); + } + }); + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .add_enabled( + !history.versions.is_empty(), + egui::Button::new(RichText::new("Restore this version").strong()) + .fill(ui.visuals().selection.bg_fill), + ) + .clicked() + && let Some(snapshot) = history.versions.get(history.selected) + { + choice = Some(HistoryChoice::Restore(snapshot.clone())); + } + if ui.button("Close").clicked() { + choice = Some(HistoryChoice::Close); + } + }); + }); + if response.should_close() && choice.is_none() { + choice = Some(HistoryChoice::Close); + } + choice +} + +fn snapshot_time(snapshot: &RecoverySnapshot) -> String { + let time = std::time::UNIX_EPOCH + .checked_add(std::time::Duration::from_millis(snapshot.timestamp_ms)) + .unwrap_or(std::time::UNIX_EPOCH); + let local: chrono::DateTime = time.into(); + local.format("%Y-%m-%d %H:%M:%S").to_string() +} + +/// Returns `true` once dismissed. +fn message_box(ctx: &egui::Context, message: &Message) -> bool { + let mut dismissed = false; + let response = egui::Modal::new(egui::Id::new("message_box")) + .frame(modal_frame(ctx)) + .show(ctx, |ui| { + ui.set_max_width(460.0); + let (glyph, color) = match message.kind { + MessageKind::Info => (icon::INFO, ui.visuals().hyperlink_color), + MessageKind::Error => (icon::X_CIRCLE, ui.visuals().error_fg_color), + }; + ui.horizontal(|ui| { + ui.label(RichText::new(glyph).size(26.0).color(color)); + ui.label(RichText::new(&message.title).strong().size(16.0)); + }); + ui.add_space(6.0); + egui::ScrollArea::vertical() + .max_height(260.0) + .show(ui, |ui| { + ui.add(egui::Label::new(&message.text).selectable(true)); + }); + ui.add_space(10.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("OK").clicked() { + dismissed = true; + } + }); + }); + dismissed || response.should_close() +} + +/// Why Python is not available, for [`python_problem`]. +pub struct PythonProblem { + pub problem: Option, + pub reason: String, + /// The interpreter that failed. + pub python: Option, +} + +impl PythonProblem { + /// Title and advice. + pub fn explanation(&self) -> (&'static str, &'static str) { + match self.problem { + Some(Problem::NoPython) => ( + "Python was not found", + "CQ-editor runs your scripts with a Python that has CadQuery. Install one \ + (see the installation guide), or choose an interpreter.", + ), + Some(Problem::NoCadQuery) => ( + "CadQuery is not available", + "Install CadQuery in that environment (python -m pip install cadquery), \ + or choose another interpreter.", + ), + Some(Problem::Exited) | None => ( + "Python stopped before it was ready", + "The Log panel shows what it printed. Choose another interpreter, or retry.", + ), + } + } +} + +/// Most detected interpreters listed at once. +const MAX_LISTED_INTERPRETERS: usize = 8; + +/// Floating hint shown while the worker could not start, with ways out: +/// interpreters found on this computer, picking one, the installation +/// guide, the preferences and a retry. +pub fn python_problem( + ctx: &egui::Context, + problem: &PythonProblem, + candidates: &[PathBuf], + actions: &mut Vec, +) { + let (title, advice) = problem.explanation(); + let others: Vec<&PathBuf> = candidates + .iter() + .filter(|path| Some(*path) != problem.python.as_ref()) + .take(MAX_LISTED_INTERPRETERS) + .collect(); + egui::Area::new(egui::Id::new("python_problem")) + .anchor(Align2::CENTER_BOTTOM, [0.0, -40.0]) + .order(egui::Order::Foreground) + .show(ctx, |ui| { + egui::Frame::popup(ui.style()) + .inner_margin(egui::Margin::same(12)) + .show(ui, |ui| { + ui.set_max_width(560.0); + ui.horizontal(|ui| { + ui.label( + RichText::new(icon::WARNING_OCTAGON) + .size(22.0) + .color(ui.visuals().error_fg_color), + ); + ui.vertical(|ui| { + ui.label(RichText::new(title).strong()); + ui.label(&problem.reason); + if let Some(python) = &problem.python { + ui.weak(format!("Interpreter: {}", python.display())); + } + ui.weak(advice); + }); + }); + if !others.is_empty() { + ui.add_space(4.0); + ui.label("Interpreters found on this computer:"); + for path in others { + if ui + .link(format!("{} {}", icon::FILE_PY, path.display())) + .on_hover_text("Restart Python with this interpreter") + .clicked() + { + actions.push(Action::UsePython(path.clone())); + } + } + } + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + if ui + .button(format!("{} Choose interpreter…", icon::FOLDER_OPEN)) + .clicked() + && let Some(path) = rfd::FileDialog::new() + .set_title("Python interpreter with CadQuery") + .pick_file() + { + actions.push(Action::UsePython(path)); + } + if ui + .button(format!("{} Installation guide", icon::BOOK_OPEN_TEXT)) + .clicked() + { + actions.push(Action::InstallationGuide); + } + if ui + .button(format!("{} Preferences…", icon::GEAR_SIX)) + .clicked() + { + actions.push(Action::Preferences); + } + if ui + .button(format!("{} Retry", icon::ARROW_CLOCKWISE)) + .clicked() + { + actions.push(Action::RestartPython); + } + }); + }); + }); +} diff --git a/src/dialogs/preferences.rs b/src/dialogs/preferences.rs new file mode 100644 index 000000000..668858f55 --- /dev/null +++ b/src/dialogs/preferences.rs @@ -0,0 +1,816 @@ +//! The preferences window. Changes apply immediately. + +use egui_phosphor::regular as icon; + +use crate::commands::Action; +use crate::settings::{ + EdgeStyle, Finish, Lighting, LightingPreset, OrbitMethod, Projection, Rendering, Settings, + Theme, +}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub enum Page { + #[default] + General, + Viewer, + Rendering, + Presentation, + Editor, + Objects, + Execution, +} + +impl Page { + const ALL: [Page; 7] = [ + Page::General, + Page::Viewer, + Page::Rendering, + Page::Presentation, + Page::Editor, + Page::Objects, + Page::Execution, + ]; + + fn label(self) -> &'static str { + match self { + Page::General => "General", + Page::Viewer => "3D View", + Page::Rendering => "Rendering", + Page::Presentation => "Presentation", + Page::Editor => "Editor", + Page::Objects => "Objects", + Page::Execution => "Execution", + } + } + + fn icon(self) -> &'static str { + match self { + Page::General => icon::SLIDERS_HORIZONTAL, + Page::Viewer => icon::CUBE, + Page::Rendering => icon::SUN, + Page::Presentation => icon::SPARKLE, + Page::Editor => icon::CODE, + Page::Objects => icon::TREE_STRUCTURE, + Page::Execution => icon::PLAY, + } + } +} + +pub fn window( + ctx: &egui::Context, + open: &mut bool, + page: &mut Page, + settings: &mut Settings, + actions: &mut Vec, +) { + egui::Window::new(format!("{} Preferences", icon::GEAR_SIX)) + .open(open) + .collapsible(false) + .resizable(true) + .default_size([620.0, 420.0]) + .show(ctx, |ui| { + egui::Panel::left("preferences_pages") + .resizable(false) + .exact_size(150.0) + .frame(egui::Frame::NONE) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 4.0; + for candidate in Page::ALL { + let text = format!("{} {}", candidate.icon(), candidate.label()); + if ui.selectable_label(*page == candidate, text).clicked() { + *page = candidate; + } + } + }); + egui::CentralPanel::default() + .frame(egui::Frame::NONE.inner_margin(egui::Margin { + left: 16, + ..Default::default() + })) + .show(ui, |ui| { + egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.heading(page.label()); + ui.add_space(6.0); + egui::Grid::new(("preferences", *page)) + .num_columns(2) + .spacing([18.0, 10.0]) + .striped(false) + .show(ui, |ui| match page { + Page::General => general(ui, settings, actions), + Page::Viewer => viewer(ui, settings), + Page::Rendering => rendering(ui, settings), + Page::Presentation => presentation(ui, settings), + Page::Editor => editor(ui, settings), + Page::Objects => objects(ui, settings), + Page::Execution => execution(ui, settings), + }); + ui.add_space(12.0); + if ui + .button(format!( + "{} Restore defaults", + icon::ARROW_COUNTER_CLOCKWISE + )) + .clicked() + { + restore_defaults(*page, settings); + } + }); + }); + }); +} + +fn restore_defaults(page: Page, settings: &mut Settings) { + let defaults = Settings::default(); + match page { + Page::General => settings.general = defaults.general, + Page::Viewer => settings.viewer = defaults.viewer, + // Presentation has a page of its own. + Page::Rendering => { + settings.rendering = Rendering { + presentation: settings.rendering.presentation.clone(), + ..defaults.rendering + } + } + Page::Presentation => settings.rendering.presentation = defaults.rendering.presentation, + Page::Editor => settings.editor = defaults.editor, + Page::Objects => settings.objects = defaults.objects, + Page::Execution => settings.execution = defaults.execution, + } +} + +fn row(ui: &mut egui::Ui, label: &str, hint: &str, add: impl FnOnce(&mut egui::Ui)) { + let response = ui.label(label); + if !hint.is_empty() { + response.on_hover_text(hint); + } + add(ui); + ui.end_row(); +} + +fn general(ui: &mut egui::Ui, settings: &mut Settings, actions: &mut Vec) { + let general = &mut settings.general; + row(ui, "Theme", "", |ui| { + egui::ComboBox::from_id_salt("theme") + .selected_text(general.theme.label()) + .show_ui(ui, |ui| { + for theme in Theme::ALL { + ui.selectable_value(&mut general.theme, theme, theme.label()); + } + }); + }); + row( + ui, + "Check for updates", + "Look for a newer CQ-editor on GitHub once a day, when Python starts; \ + only the releases list is fetched, nothing is sent about you", + |ui| { + ui.checkbox(&mut general.check_updates, ""); + }, + ); + row( + ui, + "Interface scale", + "Zoom of the whole interface (Ctrl + / Ctrl - also work)", + |ui| { + ui.add(egui::Slider::new(&mut general.ui_scale, 0.75..=2.0).step_by(0.05)); + }, + ); + row( + ui, + "Python interpreter", + "A Python with CadQuery installed. Leave empty to detect it: CQ_EDITOR_PYTHON, \ + the active virtual/conda environment, a .venv folder, then python on PATH.", + |ui| { + ui.vertical(|ui| { + ui.horizontal(|ui| { + ui.add( + egui::TextEdit::singleline(&mut general.python) + .hint_text("auto-detect") + .desired_width(260.0), + ); + if ui + .button(icon::FOLDER_OPEN) + .on_hover_text("Browse…") + .clicked() + && let Some(path) = rfd::FileDialog::new() + .set_title("Python interpreter") + .pick_file() + { + general.python = path.display().to_string(); + } + }); + ui.horizontal(|ui| { + if ui + .button(format!( + "{} Restart Python with this interpreter", + icon::ARROW_CLOCKWISE + )) + .clicked() + { + actions.push(Action::RestartPython); + } + ui.menu_button(format!("{} Detected", icon::LIST_BULLETS), |ui| { + let candidates = crate::worker::launch::candidates(); + if candidates.is_empty() { + ui.weak("No Python found"); + } + for candidate in candidates { + let text = candidate.display().to_string(); + if ui.button(&text).clicked() { + general.python = text; + ui.close(); + } + } + }) + .response + .on_hover_text("Pythons found on this computer"); + }); + ui.horizontal(|ui| { + if ui + .button(format!("{} Create Environment…", icon::PLUS_CIRCLE)) + .on_hover_text( + "A new virtual environment with CadQuery and jedi, \ + to use with CQ-editor", + ) + .clicked() + { + actions.push(Action::CreateEnvironment); + } + if ui + .button(format!("{} Install Packages…", icon::PACKAGE)) + .on_hover_text("pip install into the Python in use") + .clicked() + { + actions.push(Action::InstallPackages); + } + }); + }); + }, + ); +} + +fn color_row(ui: &mut egui::Ui, label: &str, color: &mut [u8; 3]) { + row(ui, label, "", |ui| { + ui.color_edit_button_srgb(color); + }); +} + +fn viewer(ui: &mut egui::Ui, settings: &mut Settings) { + let viewer = &mut settings.viewer; + row( + ui, + "Fit automatically", + "Frame the model after every run", + |ui| { + ui.checkbox(&mut viewer.fit_automatically, ""); + }, + ); + row(ui, "Show navigation cube", "", |ui| { + ui.checkbox(&mut viewer.show_navigation_cube, ""); + }); + row(ui, "Show axes indicator", "", |ui| { + ui.checkbox(&mut viewer.show_axes_indicator, ""); + }); + row(ui, "Animate view changes", "", |ui| { + ui.checkbox(&mut viewer.animate, ""); + }); + row( + ui, + "Projection", + "Stereo shows two eyes as the stereo mode says; the mono eyes show one of them", + |ui| { + egui::ComboBox::from_id_salt("projection") + .selected_text(viewer.projection.label()) + .show_ui(ui, |ui| { + for projection in Projection::ALL { + ui.selectable_value(&mut viewer.projection, projection, projection.label()); + } + }); + }, + ); + row( + ui, + "Stereo mode", + "How the Stereo projection shows its two images. Quad Buffer needs a stereo \ + display this renderer cannot drive, so it shows the red-cyan anaglyph", + |ui| { + ui.add_enabled_ui(viewer.projection == Projection::Stereo, |ui| { + egui::ComboBox::from_id_salt("stereo_mode") + .selected_text(viewer.stereo_mode.label()) + .show_ui(ui, |ui| { + for mode in crate::settings::StereoMode::ALL { + ui.selectable_value(&mut viewer.stereo_mode, mode, mode.label()); + } + }); + }); + }, + ); + row( + ui, + "Orbit method", + "Turntable keeps Z up; Trackball rotates freely", + |ui| { + egui::ComboBox::from_id_salt("orbit") + .selected_text(viewer.orbit_method.label()) + .show_ui(ui, |ui| { + for method in OrbitMethod::ALL { + ui.selectable_value(&mut viewer.orbit_method, method, method.label()); + } + }); + }, + ); + color_row(ui, "Background color", &mut viewer.background); + row( + ui, + "Use gradient", + "Blend to the second color at the bottom", + |ui| { + ui.checkbox(&mut viewer.use_gradient, ""); + }, + ); + color_row(ui, "Background color (aux)", &mut viewer.background_aux); + color_row(ui, "Default object color", &mut viewer.default_color); + row(ui, "Show edges", "", |ui| { + ui.checkbox(&mut viewer.show_edges, ""); + }); + row( + ui, + "Hidden edges", + "Show the edges behind faces as faint dashes in the Hidden Line display mode", + |ui| { + ui.checkbox(&mut viewer.hidden_edges, ""); + }, + ); + color_row(ui, "Edge color", &mut viewer.edge_color); + row( + ui, + "Ground grid", + "A grid on the XY plane (View > Ground Grid)", + |ui| { + ui.checkbox(&mut viewer.ground_grid, ""); + }, + ); + row( + ui, + "Scale bar", + "A round length at the bottom right of the view", + |ui| { + ui.checkbox(&mut viewer.scale_bar, ""); + }, + ); + row( + ui, + "Units", + "What one model unit means in the scale bar and exported files; CadQuery itself has no units", + |ui| { + egui::ComboBox::from_id_salt("units") + .selected_text(viewer.units.label()) + .show_ui(ui, |ui| { + for units in crate::settings::Units::ALL { + ui.selectable_value(&mut viewer.units, units, units.label()); + } + }); + }, + ); + row( + ui, + "Large models", + "Draw parts that are small on screen with a simplified mesh: automatically from 2 million triangles shown, always, or never", + |ui| { + egui::ComboBox::from_id_salt("large_models") + .selected_text(viewer.large_models.label()) + .show_ui(ui, |ui| { + for mode in crate::settings::LargeModels::ALL { + ui.selectable_value(&mut viewer.large_models, mode, mode.label()); + } + }); + }, + ); + row(ui, "Edge width", "In pixels", |ui| { + ui.add(egui::Slider::new(&mut viewer.edge_width, 0.5..=5.0).step_by(0.25)); + }); + row( + ui, + "Deviation", + "Mesh chordal deviation relative to the object size; smaller is finer (applies on the next run)", + |ui| { + ui.add( + egui::DragValue::new(&mut viewer.linear_tolerance) + .range(1e-5..=0.05) + .speed(1e-5) + .max_decimals(5), + ); + }, + ); + row( + ui, + "Angular deviation", + "Mesh angular deviation in radians; smaller is finer (applies on the next run)", + |ui| { + ui.add( + egui::DragValue::new(&mut viewer.angular_tolerance) + .range(0.02..=1.0) + .speed(0.005) + .max_decimals(3), + ); + }, + ); + row( + ui, + "Selection mode shortcuts", + "Keys that switch between Auto, Object, Face, Edge and Vertex selection modes \ + when no text field has keyboard focus (Alt+1..Alt+5 also work anywhere)", + |ui| { + ui.horizontal_wrapped(|ui| { + for mode in crate::viewer::SelectionMode::ALL { + ui.label(format!("{}:", mode.label())); + ui.add( + egui::TextEdit::singleline(viewer.selection_shortcuts.get_mut(mode)) + .desired_width(48.0), + ); + } + }); + }, + ); +} + +fn rendering(ui: &mut egui::Ui, settings: &mut Settings) { + let rendering = &mut settings.rendering; + lighting_rows(ui, "lighting", &mut rendering.lighting); + row( + ui, + "Edges", + "Which edges the Shaded, X-Ray and Hidden Line modes draw (when shown at all, see \ + 3D View > Show edges). Sharp edges leaves out the edges between faces that continue \ + smoothly, such as a fillet's borders and the seams of cylinders; Outline adds the \ + outline of curved surfaces, as a drawing has it. Wireframe always draws every edge", + |ui| { + egui::ComboBox::from_id_salt("edge_style") + .selected_text(rendering.edges.label()) + .show_ui(ui, |ui| { + for style in EdgeStyle::ALL { + ui.selectable_value(&mut rendering.edges, style, style.label()); + } + }); + }, + ); + row( + ui, + "Sharp edge angle", + "Faces meeting at less than this many degrees continue smoothly: Sharp edges and \ + Outline leave the edge between them out", + |ui| { + ui.add_enabled( + rendering.edges != EdgeStyle::All, + egui::Slider::new(&mut rendering.sharp_angle, 1.0..=90.0) + .step_by(1.0) + .suffix("°"), + ); + }, + ); +} + +/// The Presentation display mode's own look. +fn presentation(ui: &mut egui::Ui, settings: &mut Settings) { + let presentation = &mut settings.rendering.presentation; + row( + ui, + "Material", + "The material of objects whose script and Objects panel choose none", + |ui| { + egui::ComboBox::from_id_salt("presentation_material") + .selected_text(presentation.material.label()) + .show_ui(ui, |ui| { + for finish in Finish::ALL { + ui.selectable_value(&mut presentation.material, finish, finish.label()); + } + }); + }, + ); + row( + ui, + "Show edges", + "Off, the shapes speak alone; each object can still override it in the Objects panel", + |ui| { + ui.checkbox(&mut presentation.show_edges, ""); + }, + ); + row( + ui, + "Edges", + "Which edges, when they are shown: Outline gives the contour of curved surfaces \ + and the sharp edges, as an illustration has them", + |ui| { + ui.add_enabled_ui(presentation.show_edges, |ui| { + egui::ComboBox::from_id_salt("presentation_edges") + .selected_text(presentation.edges.label()) + .show_ui(ui, |ui| { + for style in EdgeStyle::ALL { + ui.selectable_value(&mut presentation.edges, style, style.label()); + } + }); + }); + }, + ); + color_row(ui, "Background, top", &mut presentation.background_top); + color_row( + ui, + "Background, bottom", + &mut presentation.background_bottom, + ); + row( + ui, + "Axes and grid", + "Draw the axes, the ground grid and the scale bar in this mode too", + |ui| { + ui.checkbox(&mut presentation.helpers, ""); + }, + ); + row( + ui, + "Shadow", + "A soft shadow on the ground under the model, as in a product photograph", + |ui| { + ui.checkbox(&mut presentation.shadow, ""); + }, + ); + let shadow = presentation.shadow; + row( + ui, + "Shadow strength", + "How dark the shadow is where the model touches the ground", + |ui| { + ui.add_enabled( + shadow, + egui::Slider::new(&mut presentation.shadow_strength, 0.0..=1.0).step_by(0.01), + ); + }, + ); + row( + ui, + "Shadow softness", + "How far the shadow spreads around the model: 0 is crisp, 1 very soft", + |ui| { + ui.add_enabled( + shadow, + egui::Slider::new(&mut presentation.shadow_softness, 0.0..=1.0).step_by(0.01), + ); + }, + ); + lighting_rows(ui, "presentation_lighting", &mut presentation.lighting); +} + +/// The rows of one set of lights, starting with a preset. +fn lighting_rows(ui: &mut egui::Ui, id: &str, lighting: &mut Lighting) { + row( + ui, + "Lighting", + "A starting point; the values below fine-tune it", + |ui| { + let current = lighting.preset().map_or("Custom", LightingPreset::label); + egui::ComboBox::from_id_salt((id, "preset")) + .selected_text(current) + .show_ui(ui, |ui| { + for preset in LightingPreset::ALL { + if ui + .selectable_label(lighting.preset() == Some(preset), preset.label()) + .clicked() + { + *lighting = preset.lighting(); + } + } + }); + }, + ); + let mut slider = |label: &str, hint: &str, value: &mut f32, range, step: f64| { + row(ui, label, hint, |ui| { + ui.add(egui::Slider::new(value, range).step_by(step)); + }); + }; + slider( + "Key light", + "The main light", + &mut lighting.key, + 0.0..=1.5, + 0.01, + ); + slider( + "Fill light", + "A softer light from the lower right, which keeps shadows readable", + &mut lighting.fill, + 0.0..=1.0, + 0.01, + ); + slider( + "Ambient light", + "Light from everywhere: the darkest a face can be", + &mut lighting.ambient, + 0.0..=1.0, + 0.01, + ); + slider( + "Rim light", + "Light grazing the outline of curved surfaces", + &mut lighting.rim, + 0.0..=1.0, + 0.01, + ); + slider( + "Highlights", + "Strength of the reflections of the key light", + &mut lighting.specular, + 0.0..=1.0, + 0.01, + ); + slider( + "Shininess", + "Higher gives smaller, sharper highlights, as on a glossy surface", + &mut lighting.shininess, + 2.0..=256.0, + 1.0, + ); + slider( + "Light direction", + "Where the key light comes from, in degrees around the line of sight: negative is left", + &mut lighting.azimuth, + -180.0..=180.0, + 1.0, + ); + slider( + "Light height", + "How far above the line of sight the key light is, in degrees", + &mut lighting.elevation, + -90.0..=90.0, + 1.0, + ); + slider( + "Exposure", + "Overall brightness in photographic stops: +1 doubles the light", + &mut lighting.exposure, + -3.0..=3.0, + 0.05, + ); + slider( + "Contrast", + "Above 1 darkens the shadows and brightens the lights; below 1 flattens them", + &mut lighting.contrast, + 0.5..=2.0, + 0.01, + ); +} + +fn editor(ui: &mut egui::Ui, settings: &mut Settings) { + let editor = &mut settings.editor; + row(ui, "Font size", "", |ui| { + ui.add(egui::Slider::new(&mut editor.font_size, 8.0..=28.0).step_by(1.0)); + }); + row(ui, "Line wrap", "", |ui| { + ui.checkbox(&mut editor.line_wrap, ""); + }); + row( + ui, + "Maximum line length", + "Column of the vertical ruler (0 hides it)", + |ui| { + ui.add(egui::DragValue::new(&mut editor.max_line_length).range(0..=300)); + }, + ); + row(ui, "Highlight current line", "", |ui| { + ui.checkbox(&mut editor.highlight_current_line, ""); + }); + row( + ui, + "Auto-indent", + "Keep and extend indentation on Enter", + |ui| { + ui.checkbox(&mut editor.auto_indent, ""); + }, + ); + row( + ui, + "Complete names after", + "Offer completions once this many characters of a name are typed (0: only after . and on Ctrl+Space)", + |ui| { + ui.add( + egui::DragValue::new(&mut editor.completion_min_chars) + .range(0..=10) + .suffix(" characters"), + ); + }, + ); + row( + ui, + "Autoreload", + "Re-run the script whenever its file changes on disk", + |ui| { + ui.checkbox(&mut editor.autoreload, ""); + }, + ); + row( + ui, + "Autoreload delay", + "Wait after a change before reloading, in milliseconds", + |ui| { + ui.add( + egui::DragValue::new(&mut editor.autoreload_delay_ms) + .range(0..=5000) + .suffix(" ms"), + ); + }, + ); + row( + ui, + "Autoreload: watch imported modules", + "Also re-run when local modules the script imports change", + |ui| { + ui.checkbox(&mut editor.watch_imported_modules, ""); + }, + ); +} + +fn objects(ui: &mut egui::Ui, settings: &mut Settings) { + let objects = &mut settings.objects; + row( + ui, + "Preserve properties on reload", + "Keep visibility and colors of objects (matched by name)", + |ui| { + ui.checkbox(&mut objects.preserve_properties, ""); + }, + ); + row(ui, "Clear all before each run", "", |ui| { + ui.checkbox(&mut objects.clear_before_run, ""); + }); + row( + ui, + "Merge assemblies", + "Show an assembly as one object instead of one per part", + |ui| { + ui.checkbox(&mut objects.merge_assemblies, ""); + }, + ); + row( + ui, + "STL precision", + "Chordal tolerance of STL exports, in model units", + |ui| { + ui.add( + egui::DragValue::new(&mut objects.stl_tolerance) + .range(1e-4..=10.0) + .speed(0.001) + .max_decimals(4), + ); + }, + ); + row( + ui, + "STL angular precision", + "Angular tolerance of STL exports, in radians", + |ui| { + ui.add( + egui::DragValue::new(&mut objects.stl_angular_tolerance) + .range(0.01..=1.0) + .speed(0.005) + .max_decimals(3), + ); + }, + ); +} + +fn execution(ui: &mut egui::Ui, settings: &mut Settings) { + let execution = &mut settings.execution; + row( + ui, + "Reload CQ", + "Re-import CadQuery before each run (for CadQuery development)", + |ui| { + ui.checkbox(&mut execution.reload_cq, ""); + }, + ); + row( + ui, + "Add script dir to path", + "So scripts can import modules next to them", + |ui| { + ui.checkbox(&mut execution.add_script_dir_to_path, ""); + }, + ); + row( + ui, + "Change working dir to script dir", + "So relative file paths resolve next to the script", + |ui| { + ui.checkbox(&mut execution.change_working_dir, ""); + }, + ); + row( + ui, + "Reload imported modules", + "Pick up changes to local modules on every run", + |ui| { + ui.checkbox(&mut execution.reload_imported_modules, ""); + }, + ); +} diff --git a/src/dialogs/upload.rs b/src/dialogs/upload.rs new file mode 100644 index 000000000..b07d54eaa --- /dev/null +++ b/src/dialogs/upload.rs @@ -0,0 +1,210 @@ +//! Uploading models to online services (manufacturing, analysis, ...). + +use egui_phosphor::regular as icon; + +use crate::commands::Action; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FileType { + Step, + Stl, + /// The script itself. + CadQuery, +} + +impl FileType { + const ALL: [FileType; 3] = [FileType::Step, FileType::Stl, FileType::CadQuery]; + + fn label(self) -> &'static str { + match self { + FileType::Step => "STEP", + FileType::Stl => "STL", + FileType::CadQuery => "CadQuery script", + } + } + + /// The worker's name for it. + fn wire_name(self) -> &'static str { + match self { + FileType::Step => "step", + FileType::Stl => "stl", + FileType::CadQuery => "py", + } + } +} + +pub struct Preset { + pub name: &'static str, + pub url: &'static str, + pub file_type: FileType, + /// JSON field of the response holding a link for the user. + pub result_key: &'static str, +} + +pub const PRESETS: &[Preset] = &[Preset { + name: "PCBWay", + url: "https://www.pcbway.com/common/CadQueryUpFile", + file_type: FileType::Step, + result_key: "redirect", +}]; + +enum Outcome { + Link { service: &'static str, url: String }, + Text(String), + Error(String), +} + +pub struct UploadDialog { + url: String, + file_type: FileType, + preset: Option<&'static Preset>, + pub busy: bool, + outcome: Option, +} + +impl Default for UploadDialog { + fn default() -> Self { + Self { + url: String::new(), + file_type: FileType::Step, + preset: None, + busy: false, + outcome: None, + } + } +} + +impl UploadDialog { + pub fn finished(&mut self, status: u16, body: &str) { + self.busy = false; + let json: Option = serde_json::from_str(body).ok(); + let link = self.preset.and_then(|preset| { + json.as_ref()? + .get(preset.result_key)? + .as_str() + .map(|url| Outcome::Link { + service: preset.name, + url: url.to_owned(), + }) + }); + self.outcome = Some(link.unwrap_or_else(|| { + let text = json + .and_then(|v| serde_json::to_string_pretty(&v).ok()) + .unwrap_or_else(|| body.to_owned()); + Outcome::Text(format!("HTTP {status}\n{text}")) + })); + } + + pub fn failed(&mut self, message: &str) { + self.busy = false; + self.outcome = Some(Outcome::Error(message.to_owned())); + } + + /// Returns `false` once the window was closed. + pub fn window(&mut self, ctx: &egui::Context, actions: &mut Vec) -> bool { + let mut open = true; + egui::Window::new(format!("{} Upload Model", icon::UPLOAD_SIMPLE)) + .open(&mut open) + .collapsible(false) + .default_size([480.0, 320.0]) + .show(ctx, |ui| { + egui::Grid::new("upload_grid") + .num_columns(2) + .spacing([12.0, 8.0]) + .show(ui, |ui| { + ui.label("URL"); + if ui + .add( + egui::TextEdit::singleline(&mut self.url) + .desired_width(320.0) + .hint_text("https://…"), + ) + .changed() + { + self.preset = None; + } + ui.end_row(); + + ui.label("Presets"); + ui.horizontal(|ui| { + for preset in PRESETS { + if ui.button(preset.name).clicked() { + self.url = preset.url.to_owned(); + self.file_type = preset.file_type; + self.preset = Some(preset); + } + } + }); + ui.end_row(); + + ui.label("File type"); + egui::ComboBox::from_id_salt("upload_type") + .selected_text(self.file_type.label()) + .show_ui(ui, |ui| { + for file_type in FileType::ALL { + ui.selectable_value( + &mut self.file_type, + file_type, + file_type.label(), + ); + } + }); + ui.end_row(); + }); + + ui.add_space(6.0); + ui.horizontal(|ui| { + let ready = !self.url.trim().is_empty() && !self.busy; + if ui + .add_enabled( + ready, + egui::Button::new(format!("{} Upload", icon::UPLOAD_SIMPLE)), + ) + .clicked() + { + self.busy = true; + self.outcome = None; + actions.push(Action::StartUpload { + url: self.url.trim().to_owned(), + file_type: self.file_type.wire_name().to_owned(), + }); + } + if self.busy { + ui.spinner(); + ui.weak("Uploading…"); + } + }); + ui.weak( + "The selected objects are uploaded, or all objects when nothing is selected.", + ); + ui.separator(); + + egui::ScrollArea::vertical() + .max_height(180.0) + .show(ui, |ui| match &self.outcome { + None => { + ui.weak("The response will appear here"); + } + Some(Outcome::Link { service, url }) => { + ui.label(format!( + "Click the link below to view your model on {service}'s website." + )); + ui.hyperlink(url); + } + Some(Outcome::Text(text)) => { + ui.add( + egui::Label::new(egui::RichText::new(text).monospace()) + .selectable(true), + ); + } + Some(Outcome::Error(message)) => { + ui.colored_label( + ui.visuals().error_fg_color, + format!("Error: {message}"), + ); + } + }); + }); + open + } +} diff --git a/src/document.rs b/src/document.rs new file mode 100644 index 000000000..dc607ce9e --- /dev/null +++ b/src/document.rs @@ -0,0 +1,701 @@ +//! The script being edited. +//! +//! Text is kept with `\n` line endings internally; the file's original +//! convention is remembered and restored on save. Files are written as +//! UTF-8. A file in another encoding is only opened when the user asks for +//! Windows-1252 explicitly, and saving it converts it to UTF-8. + +use std::fs::File; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::io::{self, Read as _, Write as _}; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +/// Script shown when no file is open. +pub const DEFAULT_SCRIPT: &str = "import cadquery as cq\n\nresult = cq.Workplane(\"XY\").box(3, 3, 0.5).edges(\"|Z\").fillet(0.125)\nshow_object(result)\n"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum LineEnding { + Lf, + CrLf, + Cr, +} + +/// How the bytes of a file on disk map to text. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Encoding { + #[default] + Utf8, + /// Western European legacy encoding (a superset of printable Latin-1), + /// common for scripts written with older Windows editors. + Windows1252, +} + +impl Encoding { + pub fn label(self) -> &'static str { + match self { + Encoding::Utf8 => "UTF-8", + Encoding::Windows1252 => "Windows-1252", + } + } +} + +/// The error of reading a file that is not valid UTF-8; see [`is_not_utf8`]. +#[derive(Debug)] +struct NotUtf8 { + path: PathBuf, + offset: usize, +} + +impl std::fmt::Display for NotUtf8 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{} is not valid UTF-8 (invalid data near byte {}); the file was not opened or modified", + self.path.display(), + self.offset + ) + } +} + +impl std::error::Error for NotUtf8 {} + +/// Whether opening a file failed only because it is not UTF-8, so it can be +/// offered again as [`Encoding::Windows1252`]. +pub fn is_not_utf8(error: &io::Error) -> bool { + error.get_ref().is_some_and(|inner| inner.is::()) +} + +/// A normalized snapshot read from the document's current path without +/// modifying the editor buffer. +#[derive(Clone, Debug)] +pub struct DiskVersion { + pub text: String, + path: PathBuf, + fingerprint: DiskFingerprint, + line_ending: LineEnding, + utf8_bom: bool, + encoding: Encoding, +} + +/// Identity of the bytes last read or written at a document path. The hash +/// catches rewrites that keep both the length and modification timestamp. +#[derive(Clone, Copy, Debug)] +struct DiskFingerprint { + len: u64, + _modified: Option, + content_hash: u64, +} + +impl DiskFingerprint { + fn of(bytes: &[u8], modified: Option) -> Self { + let mut hasher = DefaultHasher::new(); + bytes.hash(&mut hasher); + Self { + len: bytes.len() as u64, + _modified: modified, + content_hash: hasher.finish(), + } + } + + fn same_content(self, other: Self) -> bool { + self.len == other.len && self.content_hash == other.content_hash + } +} + +/// Relationship between an on-disk snapshot and the editor's local state. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExternalUpdate { + /// Only metadata changed; disk contents still match the saved baseline. + Unchanged, + /// Disk and buffer now agree, so accepting the snapshot loses nothing. + MatchesBuffer, + /// The buffer is clean and can be reloaded automatically. + Reload, + /// Disk and buffer diverged from the same saved baseline. + Conflict, +} + +impl LineEnding { + #[cfg(windows)] + pub const NATIVE: LineEnding = LineEnding::CrLf; + #[cfg(not(windows))] + pub const NATIVE: LineEnding = LineEnding::Lf; + + /// The convention used by `text`, or the platform's for text without + /// line breaks. + pub fn detect(text: &str) -> Self { + if text.contains("\r\n") { + LineEnding::CrLf + } else if text.contains('\r') { + LineEnding::Cr + } else if text.contains('\n') { + LineEnding::Lf + } else { + LineEnding::NATIVE + } + } + + pub fn as_str(self) -> &'static str { + match self { + LineEnding::Lf => "\n", + LineEnding::CrLf => "\r\n", + LineEnding::Cr => "\r", + } + } + + pub fn label(self) -> &'static str { + match self { + LineEnding::Lf => "LF", + LineEnding::CrLf => "CRLF", + LineEnding::Cr => "CR", + } + } +} + +#[derive(Clone, Debug)] +pub struct Document { + pub text: String, + saved_text: String, + path: Option, + line_ending: LineEnding, + utf8_bom: bool, + /// Encoding of the file when it was opened; saving writes UTF-8. + encoding: Encoding, + saved_hash: u64, + saved_fingerprint: Option, + /// The original path disappeared while the document remained open. + missing_on_disk: bool, + /// Title of the bundled example this buffer was loaded from. Examples + /// are read-only: saving one asks for a new location. + example: Option, +} + +impl Document { + pub fn untitled(text: &str) -> Self { + let text = normalize(text); + let saved_text = text.clone(); + Self { + saved_hash: hash(&text), + saved_fingerprint: None, + saved_text, + text, + path: None, + line_ending: LineEnding::NATIVE, + utf8_bom: false, + encoding: Encoding::Utf8, + missing_on_disk: false, + example: None, + } + } + + pub fn example(title: &str, source: &str) -> Self { + Self { + example: Some(title.to_owned()), + ..Self::untitled(source) + } + } + + pub fn open(path: &Path) -> io::Result { + Self::open_with(path, Encoding::Utf8) + } + + /// Opens `path` decoded as `encoding`. Saving writes UTF-8 whatever the + /// encoding was. + pub fn open_with(path: &Path, encoding: Encoding) -> io::Result { + let (text, line_ending, utf8_bom, fingerprint) = read(path, encoding)?; + let saved_text = text.clone(); + Ok(Self { + saved_hash: hash(&text), + saved_fingerprint: Some(fingerprint), + saved_text, + text, + path: Some(path.to_path_buf()), + line_ending, + utf8_bom, + encoding, + missing_on_disk: false, + example: None, + }) + } + + /// Opens `path` as UTF-8 or, when it is not, as Windows-1252. For + /// archiving existing contents, where asking the user is not possible. + pub fn open_any(path: &Path) -> io::Result { + match Self::open(path) { + Err(error) if is_not_utf8(&error) => Self::open_with(path, Encoding::Windows1252), + result => result, + } + } + + /// Reconstructs a recovered buffer while using the current disk contents, + /// when readable, as its saved baseline. + pub fn recovered( + text: String, + path: Option, + line_ending: LineEnding, + utf8_bom: bool, + ) -> Self { + let text = normalize(&text); + let disk = path.as_deref().and_then(|path| Self::open_any(path).ok()); + let saved_hash = disk + .as_ref() + .map_or_else(|| hash(&text) ^ u64::MAX, |disk| disk.saved_hash); + let saved_fingerprint = disk.as_ref().and_then(|disk| disk.saved_fingerprint); + let saved_text = disk + .as_ref() + .map_or_else(|| text.clone(), |disk| disk.text.clone()); + Self { + saved_hash, + saved_fingerprint, + saved_text, + text, + path, + line_ending, + utf8_bom, + // Keeps reading the file the way it is encoded on disk, so the + // file watcher can compare it. + encoding: disk.map_or(Encoding::Utf8, |disk| disk.encoding), + missing_on_disk: false, + example: None, + } + } + + /// The baseline text when the document was last opened, created or saved. + pub fn saved_text(&self) -> &str { + &self.saved_text + } + + pub fn path(&self) -> Option<&Path> { + self.path.as_deref() + } + + /// The file was renamed or moved: the buffer stays as it is, modified + /// or not, and saves go to `path` from now on. + pub fn set_path(&mut self, path: PathBuf) { + self.path = Some(path); + self.missing_on_disk = false; + } + + /// The interface shows it through [`Document::display_name`]. + #[cfg(test)] + pub fn is_missing_on_disk(&self) -> bool { + self.missing_on_disk + } + + pub fn set_missing_on_disk(&mut self, missing: bool) { + self.missing_on_disk = missing && self.path.is_some(); + } + + pub fn line_ending(&self) -> LineEnding { + self.line_ending + } + + pub fn has_utf8_bom(&self) -> bool { + self.utf8_bom + } + + /// The encoding the file was opened with; the next save writes UTF-8. + pub fn encoding(&self) -> Encoding { + self.encoding + } + + pub fn example_title(&self) -> Option<&str> { + self.example.as_deref() + } + + /// True when the buffer differs from what was last loaded or saved. + pub fn is_modified(&self) -> bool { + hash(&self.text) != self.saved_hash + } + + /// Name for the window title and tabs. + pub fn display_name(&self) -> String { + if let Some(title) = &self.example { + return format!("{title} (example)"); + } + let name = self.path.as_ref().and_then(|p| p.file_name()).map_or_else( + || "untitled".to_owned(), + |n| n.to_string_lossy().into_owned(), + ); + if self.missing_on_disk { + format!("{name} (deleted on disk)") + } else { + name + } + } + + /// Saves to the current path; `false` when a "save as" is needed first + /// (untitled buffers and examples). + pub fn save(&mut self) -> io::Result { + match (&self.path, &self.example) { + (Some(path), None) => { + let path = path.clone(); + self.write(&path)?; + Ok(true) + } + _ => Ok(false), + } + } + + pub fn save_as(&mut self, path: &Path) -> io::Result<()> { + self.write(path)?; + self.path = Some(path.to_path_buf()); + self.example = None; + Ok(()) + } + + /// Applies an inspected disk version when the editor buffer is clean. + /// Unsaved changes are never discarded by this convenience method; + /// callers need an explicit conflict flow to replace a modified buffer. + pub fn reload(&mut self, version: DiskVersion) -> io::Result { + if self.is_modified() { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "refusing to reload a document with unsaved changes", + )); + } + self.apply_disk_version(version) + } + + /// Reads the current file without changing the buffer or saved state. + pub fn disk_version(&self) -> io::Result> { + let Some(path) = &self.path else { + return Ok(None); + }; + let (text, line_ending, utf8_bom, fingerprint) = read(path, self.encoding)?; + Ok(Some(DiskVersion { + text, + path: path.clone(), + fingerprint, + line_ending, + utf8_bom, + encoding: self.encoding, + })) + } + + /// The file's contents when another program changed them since they + /// were last loaded or saved, which a save would replace unseen. `None` + /// for untitled buffers, for a file that still holds that version or + /// the buffer's own text, and for a deleted file, which saving recreates. + pub fn unseen_disk_version(&self) -> io::Result> { + match self.disk_version() { + Ok(Some(version)) + if !self.disk_matches_saved(&version) && version.text != self.text => + { + Ok(Some(version)) + } + Ok(_) => Ok(None), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } + } + + /// The user saw `version` and keeps the buffer: it becomes the saved + /// baseline, so the buffer counts as modified until it is saved over it. + pub fn adopt_disk_baseline(&mut self, version: &DiskVersion) { + self.saved_hash = hash(&version.text); + self.saved_fingerprint = Some(version.fingerprint); + self.saved_text = version.text.clone(); + } + + /// Whether a disk snapshot still has the contents last loaded or saved. + pub fn disk_matches_saved(&self, version: &DiskVersion) -> bool { + self.path.as_ref() == Some(&version.path) + && self + .saved_fingerprint + .is_some_and(|saved| saved.same_content(version.fingerprint)) + } + + pub fn classify_external_update(&self, version: &DiskVersion) -> ExternalUpdate { + if self.disk_matches_saved(version) { + ExternalUpdate::Unchanged + } else if version.text == self.text { + ExternalUpdate::MatchesBuffer + } else if self.is_modified() { + ExternalUpdate::Conflict + } else { + ExternalUpdate::Reload + } + } + + /// Explicitly replaces the buffer with a previously inspected snapshot. + pub fn apply_disk_version(&mut self, version: DiskVersion) -> io::Result { + if self.path.as_ref() != Some(&version.path) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "disk snapshot belongs to another document", + )); + } + let changed = version.text != self.text; + self.saved_hash = hash(&version.text); + self.saved_fingerprint = Some(version.fingerprint); + self.saved_text = version.text.clone(); + self.text = version.text; + self.line_ending = version.line_ending; + self.utf8_bom = version.utf8_bom; + self.encoding = version.encoding; + self.missing_on_disk = false; + Ok(changed) + } + + /// Writes the current buffer elsewhere without changing this document's + /// path or marking its edits as saved. + pub fn save_copy(&self, path: &Path) -> io::Result<()> { + if self.path.as_deref() == Some(path) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "the copy must use a different path", + )); + } + atomic_write(path, &self.encoded_bytes()) + } + + /// Creates a uniquely named recovery copy of the current editor buffer. + /// The document remains modified and keeps its original path. + pub fn create_recovery_backup(&self, directory: &Path) -> io::Result { + std::fs::create_dir_all(directory)?; + let stem = self + .path + .as_deref() + .and_then(Path::file_stem) + .and_then(|name| name.to_str()) + .filter(|name| !name.is_empty()) + .unwrap_or("script"); + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis(); + for suffix in 0..1000 { + let path = directory.join(format!("{stem}-{timestamp}-{suffix}.recovery.py")); + match atomic_create(&path, &self.encoded_bytes()) { + Ok(()) => return Ok(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "could not allocate a unique recovery file name", + )) + } + + fn write(&mut self, path: &Path) -> io::Result<()> { + let bytes = self.encoded_bytes(); + atomic_write(path, &bytes)?; + self.saved_hash = hash(&self.text); + self.saved_text = self.text.clone(); + self.saved_fingerprint = Some(DiskFingerprint::of( + &bytes, + std::fs::metadata(path) + .ok() + .and_then(|metadata| metadata.modified().ok()), + )); + self.encoding = Encoding::Utf8; + self.missing_on_disk = false; + Ok(()) + } + + fn encoded_bytes(&self) -> Vec { + let text = if self.line_ending == LineEnding::Lf { + self.text.clone() + } else { + self.text.replace('\n', self.line_ending.as_str()) + }; + let mut encoded = Vec::with_capacity(text.len() + usize::from(self.utf8_bom) * 3); + if self.utf8_bom { + encoded.extend_from_slice(&[0xef, 0xbb, 0xbf]); + } + encoded.extend_from_slice(text.as_bytes()); + encoded + } +} + +fn read( + path: &Path, + encoding: Encoding, +) -> io::Result<(String, LineEnding, bool, DiskFingerprint)> { + let mut file = File::open(path)?; + let modified = file.metadata()?.modified().ok(); + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes)?; + let fingerprint = DiskFingerprint::of(&bytes, modified); + let utf8_bom = bytes.starts_with(&[0xef, 0xbb, 0xbf]); + if utf8_bom { + bytes.drain(..3); + } + let raw = match encoding { + Encoding::Utf8 => String::from_utf8(bytes).map_err(|error| { + let offset = error.utf8_error().valid_up_to() + usize::from(utf8_bom) * 3; + io::Error::new( + io::ErrorKind::InvalidData, + NotUtf8 { + path: path.to_path_buf(), + offset, + }, + ) + })?, + Encoding::Windows1252 => decode_windows_1252(&bytes), + }; + let line_ending = LineEnding::detect(&raw); + Ok((normalize(&raw), line_ending, utf8_bom, fingerprint)) +} + +/// Decodes Windows-1252 as the WHATWG Encoding Standard does: every byte is +/// a character, so decoding never fails. Bytes 0x80..=0x9F map to +/// typographic characters; the five unassigned ones to C1 controls. +pub fn decode_windows_1252(bytes: &[u8]) -> String { + const HIGH: [char; 32] = [ + '\u{20AC}', '\u{0081}', '\u{201A}', '\u{0192}', '\u{201E}', '\u{2026}', '\u{2020}', + '\u{2021}', '\u{02C6}', '\u{2030}', '\u{0160}', '\u{2039}', '\u{0152}', '\u{008D}', + '\u{017D}', '\u{008F}', '\u{0090}', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', + '\u{2022}', '\u{2013}', '\u{2014}', '\u{02DC}', '\u{2122}', '\u{0161}', '\u{203A}', + '\u{0153}', '\u{009D}', '\u{017E}', '\u{0178}', + ]; + bytes + .iter() + .map(|&byte| match byte { + 0x80..=0x9f => HIGH[usize::from(byte - 0x80)], + _ => char::from(byte), + }) + .collect() +} + +/// Writes and synchronizes a temporary file in the destination directory, +/// then atomically replaces the destination. Existing permissions are kept. +pub(crate) fn atomic_write(path: &Path, contents: &[u8]) -> io::Result<()> { + atomic_write_with(path, true, |file| file.write_all(contents)) +} + +/// Atomic creation variant used for uniquely named recovery versions. +pub(crate) fn atomic_create(path: &Path, contents: &[u8]) -> io::Result<()> { + atomic_write_with(path, false, |file| file.write_all(contents)) +} + +fn atomic_write_with( + path: &Path, + overwrite: bool, + write: impl FnOnce(&mut File) -> io::Result<()>, +) -> io::Result<()> { + let target = match std::fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_symlink() => std::fs::canonicalize(path)?, + _ => path.to_path_buf(), + }; + let parent = target + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")); + #[cfg(not(windows))] + let permissions = std::fs::metadata(&target) + .ok() + .map(|metadata| metadata.permissions()); + let mut temporary = tempfile::Builder::new() + .prefix(".cq-editor-") + .tempfile_in(parent)?; + write(temporary.as_file_mut())?; + temporary.as_file_mut().flush()?; + temporary.as_file().sync_all()?; + + #[cfg(not(windows))] + if let Some(permissions) = permissions.clone() { + temporary.as_file().set_permissions(permissions)?; + } + + let persisted = persist_temporary(temporary, &target, overwrite)?; + persisted.sync_all()?; + sync_parent(parent) +} + +#[cfg(not(windows))] +fn persist_temporary( + temporary: tempfile::NamedTempFile, + target: &Path, + overwrite: bool, +) -> io::Result { + if overwrite { + temporary.persist(target) + } else { + temporary.persist_noclobber(target) + } + .map_err(|error| error.error) +} + +#[cfg(windows)] +fn persist_temporary( + temporary: tempfile::NamedTempFile, + target: &Path, + overwrite: bool, +) -> io::Result { + use std::os::windows::ffi::OsStrExt as _; + + use windows_sys::Win32::Storage::FileSystem::{ + MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH, MoveFileExW, REPLACEFILE_WRITE_THROUGH, + ReplaceFileW, + }; + + // Windows replacement calls require the temporary file to be closed. + // TempPath remains alive so a failed operation still removes the temp. + let target_exists = target.exists(); + let temporary = temporary.into_temp_path(); + let destination: Vec = target.as_os_str().encode_wide().chain(Some(0)).collect(); + let replacement: Vec = temporary.as_os_str().encode_wide().chain(Some(0)).collect(); + + if overwrite && target_exists { + // ReplaceFileW performs a single filesystem replacement while keeping + // the destination's ACLs, creation time, compression and encryption. + let replaced_ok = unsafe { + ReplaceFileW( + destination.as_ptr(), + replacement.as_ptr(), + std::ptr::null(), + REPLACEFILE_WRITE_THROUGH, + std::ptr::null(), + std::ptr::null(), + ) + }; + if replaced_ok == 0 { + return Err(io::Error::last_os_error()); + } + } else { + let flags = MOVEFILE_WRITE_THROUGH + | if overwrite { + MOVEFILE_REPLACE_EXISTING + } else { + 0 + }; + let moved_ok = unsafe { MoveFileExW(replacement.as_ptr(), destination.as_ptr(), flags) }; + if moved_ok == 0 { + return Err(io::Error::last_os_error()); + } + } + std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(target) +} + +#[cfg(unix)] +fn sync_parent(parent: &Path) -> io::Result<()> { + File::open(parent)?.sync_all() +} + +#[cfg(not(unix))] +fn sync_parent(_parent: &Path) -> io::Result<()> { + Ok(()) +} + +fn normalize(text: &str) -> String { + text.replace("\r\n", "\n").replace('\r', "\n") +} + +fn hash(text: &str) -> u64 { + let mut hasher = DefaultHasher::new(); + text.hash(&mut hasher); + hasher.finish() +} + +#[cfg(test)] +#[path = "../tests/rust/editor/test_document.rs"] +mod tests; diff --git a/src/editor/highlight.rs b/src/editor/highlight.rs new file mode 100644 index 000000000..9580af6d5 --- /dev/null +++ b/src/editor/highlight.rs @@ -0,0 +1,332 @@ +//! Python syntax highlighting for the code editor. +//! +//! A small hand-written lexer: it understands strings (prefixes, triple +//! quotes, escapes), comments, numbers, decorators and the names following +//! `def` and `class`, which is all highlighting needs. + +use std::ops::Range; + +use egui::text::{LayoutJob, TextFormat}; +use egui::{Color32, FontId}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TokenKind { + Keyword, + /// `True`, `False`, `None`. + Constant, + Builtin, + /// The names CQ-editor injects into scripts (`show_object`, `cq`, ...). + EditorApi, + SelfParam, + String, + Number, + Comment, + Decorator, + FunctionName, + ClassName, + Operator, + Bracket, + Identifier, + Whitespace, +} + +const KEYWORDS: &[&str] = &[ + "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", + "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", + "match", "case", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", + "yield", +]; + +const CONSTANTS: &[&str] = &["True", "False", "None"]; + +const BUILTINS: &[&str] = &[ + "abs", + "all", + "any", + "bool", + "dict", + "dir", + "enumerate", + "filter", + "float", + "format", + "getattr", + "hasattr", + "int", + "isinstance", + "iter", + "len", + "list", + "map", + "max", + "min", + "next", + "object", + "open", + "print", + "range", + "repr", + "reversed", + "round", + "set", + "setattr", + "sorted", + "str", + "sum", + "super", + "tuple", + "type", + "zip", + "Exception", + "ValueError", + "TypeError", + "RuntimeError", + "KeyError", + "IndexError", +]; + +const EDITOR_API: &[&str] = &["show_object", "debug", "log", "rand_color", "cq"]; + +/// Colors for each token kind. +#[derive(Clone, Debug, PartialEq)] +pub struct SyntaxColors { + pub text: Color32, + pub keyword: Color32, + pub constant: Color32, + pub builtin: Color32, + pub editor_api: Color32, + pub self_param: Color32, + pub string: Color32, + pub number: Color32, + pub comment: Color32, + pub decorator: Color32, + pub function: Color32, + pub class: Color32, + pub operator: Color32, +} + +impl SyntaxColors { + fn color(&self, kind: TokenKind) -> Color32 { + match kind { + TokenKind::Keyword => self.keyword, + TokenKind::Constant => self.constant, + TokenKind::Builtin => self.builtin, + TokenKind::EditorApi => self.editor_api, + TokenKind::SelfParam => self.self_param, + TokenKind::String => self.string, + TokenKind::Number => self.number, + TokenKind::Comment => self.comment, + TokenKind::Decorator => self.decorator, + TokenKind::FunctionName => self.function, + TokenKind::ClassName => self.class, + TokenKind::Operator | TokenKind::Bracket => self.operator, + TokenKind::Identifier | TokenKind::Whitespace => self.text, + } + } +} + +/// Splits `text` into tokens covering it completely. +pub fn tokenize(text: &str) -> Vec<(Range, TokenKind)> { + let bytes = text.as_bytes(); + let mut tokens: Vec<(Range, TokenKind)> = Vec::new(); + let mut i = 0; + // What the previous identifier-like token makes of the next name. + let mut expect_name: Option = None; + let mut line_start = true; + + while i < bytes.len() { + let start = i; + let c = bytes[i]; + + if matches!(c, b' ' | b'\t' | b'\r' | b'\n') { + while i < bytes.len() && matches!(bytes[i], b' ' | b'\t' | b'\r' | b'\n') { + line_start |= bytes[i] == b'\n'; + i += 1; + } + tokens.push((start..i, TokenKind::Whitespace)); + continue; + } + + // A name right after `def`/`class`; any other token cancels it. + let pending_name = expect_name.take(); + let kind = if c == b'#' { + i = line_end(bytes, i); + TokenKind::Comment + } else if let Some(end) = string_end(bytes, i) { + i = end; + TokenKind::String + } else if c.is_ascii_digit() + || (c == b'.' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit)) + { + i = number_end(bytes, i); + TokenKind::Number + } else if c == b'@' && line_start { + i += 1; + while i < bytes.len() && (is_ident_byte(bytes[i]) || bytes[i] == b'.') { + i += 1; + } + TokenKind::Decorator + } else if is_ident_start(text, i) { + i = ident_end(text, i); + let word = &text[start..i]; + let kind = if let Some(kind) = pending_name { + kind + } else if KEYWORDS.contains(&word) { + TokenKind::Keyword + } else if CONSTANTS.contains(&word) { + TokenKind::Constant + } else if word == "self" || word == "cls" { + TokenKind::SelfParam + } else if EDITOR_API.contains(&word) { + TokenKind::EditorApi + } else if BUILTINS.contains(&word) && !follows_dot(bytes, start) { + TokenKind::Builtin + } else { + TokenKind::Identifier + }; + match word { + "def" => expect_name = Some(TokenKind::FunctionName), + "class" => expect_name = Some(TokenKind::ClassName), + _ => {} + } + kind + } else if matches!(c, b'(' | b')' | b'[' | b']' | b'{' | b'}') { + i += 1; + TokenKind::Bracket + } else { + // Any other character, taking care of multi-byte UTF-8. + i += text[i..].chars().next().map_or(1, char::len_utf8); + TokenKind::Operator + }; + + line_start = false; + tokens.push((start..i, kind)); + } + tokens +} + +/// Whether the text just before `cursor` is code, not a comment or a +/// string (closed or still being typed). +pub fn in_code(text: &str, cursor: usize) -> bool { + let before = text.get(..cursor).unwrap_or(text); + !tokenize(before).last().is_some_and(|(range, kind)| { + range.end == before.len() && matches!(kind, TokenKind::Comment | TokenKind::String) + }) +} + +/// Builds the layout job for the editor: highlighted, monospace, wrapping +/// at `wrap_width` (infinite to disable wrapping). +pub fn layout_job(text: &str, font: FontId, colors: &SyntaxColors, wrap_width: f32) -> LayoutJob { + let mut job = LayoutJob { + text: text.to_owned(), + ..Default::default() + }; + job.wrap.max_width = wrap_width; + for (range, kind) in tokenize(text) { + let format = TextFormat { + font_id: font.clone(), + color: colors.color(kind), + italics: kind == TokenKind::Comment, + ..Default::default() + }; + job.sections.push(egui::text::LayoutSection { + leading_space: 0.0, + byte_range: egui::text::ByteIndex(range.start)..egui::text::ByteIndex(range.end), + format, + }); + } + job +} + +fn line_end(bytes: &[u8], mut i: usize) -> usize { + while i < bytes.len() && bytes[i] != b'\n' { + i += 1; + } + i +} + +fn follows_dot(bytes: &[u8], start: usize) -> bool { + bytes[..start] + .iter() + .rev() + .find(|b| !b.is_ascii_whitespace()) + == Some(&b'.') +} + +/// If a string literal (with optional prefix) starts at `i`, returns the +/// index just past it. Unterminated single-quoted strings stop at the end of +/// the line, unterminated triple-quoted ones at the end of the text. +fn string_end(bytes: &[u8], i: usize) -> Option { + let mut j = i; + while j < bytes.len() + && j - i < 2 + && matches!(bytes[j].to_ascii_lowercase(), b'r' | b'b' | b'f' | b'u') + { + j += 1; + } + let quote = *bytes.get(j)?; + if quote != b'"' && quote != b'\'' { + return None; + } + // A prefix must not be the tail of a longer identifier. + if j > i && i > 0 && is_ident_byte(bytes[i - 1]) { + return None; + } + let triple = bytes.get(j + 1) == Some("e) && bytes.get(j + 2) == Some("e); + let mut k = j + if triple { 3 } else { 1 }; + while k < bytes.len() { + match bytes[k] { + // Even in raw strings a backslash keeps the next quote inside. + b'\\' => k += 2, + b'\n' if !triple => return Some(k), + c if c == quote => { + if !triple { + return Some(k + 1); + } + if bytes.get(k + 1) == Some("e) && bytes.get(k + 2) == Some("e) { + return Some(k + 3); + } + k += 1; + } + _ => k += 1, + } + } + Some(bytes.len()) +} + +fn number_end(bytes: &[u8], mut i: usize) -> usize { + let mut previous = 0u8; + while i < bytes.len() { + let c = bytes[i]; + let sign_in_exponent = (c == b'+' || c == b'-') && matches!(previous, b'e' | b'E'); + if c.is_ascii_alphanumeric() || c == b'_' || c == b'.' || sign_in_exponent { + previous = c; + i += 1; + } else { + break; + } + } + i +} + +fn is_ident_byte(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b >= 0x80 +} + +fn is_ident_start(text: &str, i: usize) -> bool { + text[i..] + .chars() + .next() + .is_some_and(|c| c == '_' || c.is_alphabetic()) +} + +fn ident_end(text: &str, i: usize) -> usize { + text[i..] + .char_indices() + .find(|(_, c)| !(*c == '_' || c.is_alphanumeric())) + .map_or(text.len(), |(offset, _)| i + offset) +} + +#[cfg(test)] +#[path = "../../tests/rust/editor/test_highlight.rs"] +mod tests; diff --git a/src/editor/history.rs b/src/editor/history.rs new file mode 100644 index 000000000..09cac7df2 --- /dev/null +++ b/src/editor/history.rs @@ -0,0 +1,250 @@ +//! The editor's undo history. +//! +//! egui's `TextEdit` keeps a history of its own: it takes a snapshot once +//! the text and the caret have been still for a second, so an indent or a +//! completion may be undone together with the typing around it, a caret +//! move counts as a step, and the history lives in egui's memory, where it +//! outlives the document (undo after opening another file brought back the +//! previous file's text). The editor records explicit steps instead and +//! never lets `TextEdit` see the undo keys: +//! +//! * typing is one step while it continues at the caret: characters typed +//! one after another, or deleted one after another, without a pause, a +//! caret move or a new line; +//! * every editor command (indent, comment, completion, replace) and every +//! change made outside the editor (a reload from disk) is one step; +//! * adjusting one value, such as dragging a parameter, is one step while +//! it continues without a pause. + +use std::collections::VecDeque; + +use super::text_ops::Selection; + +/// Steps kept for undo. +const MAX_STEPS: usize = 1000; +/// Text kept by the undo and redo steps together. +const MAX_BYTES: usize = 32 * 1024 * 1024; +/// A pause this long, in seconds, ends a typing step. +const TYPING_PAUSE: f64 = 1.5; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EditKind { + /// Typing in the text field; keystrokes at the caret are grouped. + Typing, + /// An editor command or a change from outside the editor. + Command, + /// A new value for the literal starting at this byte; successive + /// values of the same literal are grouped. + Adjust(usize), +} + +/// `removed`, at byte `start`, was replaced by `inserted`. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Change { + start: usize, + removed: String, + inserted: String, +} + +impl Change { + fn bytes(&self) -> usize { + self.removed.len() + self.inserted.len() + } +} + +/// The changes a step groups: typing, or the values of one literal. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Keystrokes { + Insert, + Delete, + Adjust(usize), +} + +#[derive(Clone, Debug)] +struct Step { + /// Applied in order. + changes: Vec, + before: Selection, + after: Selection, + /// Set while typing may still extend the step. + keystrokes: Option, + time: f64, +} + +impl Step { + fn bytes(&self) -> usize { + self.changes.iter().map(Change::bytes).sum() + } +} + +#[derive(Default)] +pub struct History { + undo: VecDeque, + redo: Vec, + /// The text the history last saw; `None` until the first record. + text: Option, + bytes: usize, +} + +impl History { + /// Forgets everything, for another document. + pub fn clear(&mut self) { + *self = Self::default(); + } + + pub fn can_undo(&self) -> bool { + !self.undo.is_empty() + } + + pub fn can_redo(&self) -> bool { + !self.redo.is_empty() + } + + /// Records how the text changed since the last record, if it did. The + /// selection was `before` just before the change and is `after` now. + pub fn record( + &mut self, + text: &str, + before: &Selection, + after: &Selection, + kind: EditKind, + now: f64, + ) { + let Some(previous) = &self.text else { + self.text = Some(text.to_owned()); + return; + }; + if previous == text { + return; + } + let change = diff(previous, text); + self.text = Some(text.to_owned()); + self.bytes -= self.redo.drain(..).map(|step| step.bytes()).sum::(); + self.bytes += change.bytes(); + + let keystrokes = match kind { + EditKind::Typing => keystrokes(&change), + EditKind::Command => None, + EditKind::Adjust(literal) => Some(Keystrokes::Adjust(literal)), + }; + if let Some(keystrokes) = keystrokes + && let Some(last) = self.undo.back_mut() + && last.keystrokes == Some(keystrokes) + && last.after == *before + && now - last.time < TYPING_PAUSE + { + last.changes.push(change); + last.after = after.clone(); + last.time = now; + return; + } + self.undo.push_back(Step { + changes: vec![change], + before: before.clone(), + after: after.clone(), + keystrokes, + time: now, + }); + self.trim(); + } + + /// Reverts the last step of `text`, which must be the recorded text. + /// Returns the text and the selection from before that step. + pub fn undo(&mut self, text: &str) -> Option<(String, Selection)> { + if self.text.as_deref() != Some(text) { + return None; + } + let step = self.undo.pop_back()?; + let mut text = text.to_owned(); + for change in step.changes.iter().rev() { + text.replace_range( + change.start..change.start + change.inserted.len(), + &change.removed, + ); + } + let selection = step.before.clone(); + self.redo.push(step); + self.close_typing(); + self.text = Some(text.clone()); + Some((text, selection)) + } + + /// Applies the last undone step again. Returns the text and the + /// selection after that step. + pub fn redo(&mut self, text: &str) -> Option<(String, Selection)> { + if self.text.as_deref() != Some(text) { + return None; + } + let step = self.redo.pop()?; + let mut text = text.to_owned(); + for change in &step.changes { + text.replace_range( + change.start..change.start + change.removed.len(), + &change.inserted, + ); + } + let selection = step.after.clone(); + self.undo.push_back(step); + self.close_typing(); + self.text = Some(text.clone()); + Some((text, selection)) + } + + /// Typing after an undo or a redo starts a step of its own. + fn close_typing(&mut self) { + if let Some(last) = self.undo.back_mut() { + last.keystrokes = None; + } + } + + fn trim(&mut self) { + while self.undo.len() > MAX_STEPS || (self.bytes > MAX_BYTES && self.undo.len() > 1) { + if let Some(step) = self.undo.pop_front() { + self.bytes -= step.bytes(); + } + } + } +} + +/// The keystrokes a change could be part of: one character typed (over a +/// selection or not), or one character deleted. A new line ends the +/// typing: it is a step of its own. +fn keystrokes(change: &Change) -> Option { + let single = |text: &str| text.chars().nth(1).is_none() && !text.is_empty(); + if single(&change.inserted) && change.inserted != "\n" { + Some(Keystrokes::Insert) + } else if change.inserted.is_empty() && single(&change.removed) { + Some(Keystrokes::Delete) + } else { + None + } +} + +/// The smallest change that turns `old` into `new`. +fn diff(old: &str, new: &str) -> Change { + let (a, b) = (old.as_bytes(), new.as_bytes()); + let mut prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count(); + while !old.is_char_boundary(prefix) { + prefix -= 1; + } + let limit = a.len().min(b.len()) - prefix; + let mut suffix = a + .iter() + .rev() + .zip(b.iter().rev()) + .take(limit) + .take_while(|(x, y)| x == y) + .count(); + while !old.is_char_boundary(old.len() - suffix) { + suffix -= 1; + } + Change { + start: prefix, + removed: old[prefix..old.len() - suffix].to_owned(), + inserted: new[prefix..new.len() - suffix].to_owned(), + } +} + +#[cfg(test)] +#[path = "../../tests/rust/editor/test_history.rs"] +mod tests; diff --git a/src/editor/mod.rs b/src/editor/mod.rs new file mode 100644 index 000000000..39c302873 --- /dev/null +++ b/src/editor/mod.rs @@ -0,0 +1,1898 @@ +//! The code editor panel. +//! +//! Built on egui's `TextEdit` with a custom layouter for syntax highlighting. +//! Around it the editor adds a gutter (line numbers, breakpoints, the debug +//! position), current/error/debug line backgrounds, a line-length ruler, a +//! search and replace bar, a *Go to line* bar, the completion popup, hover +//! documentation and its own undo history. + +pub mod highlight; +pub mod history; +pub mod snippets; +pub mod text_ops; + +use std::collections::{BTreeMap, BTreeSet}; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::ops::Range; +use std::sync::Arc; + +use egui::text::{CCursor, CCursorRange}; +use egui::{ + Align, Align2, Color32, FontId, Galley, Key, Modifiers, Pos2, Rect, Sense, Shape, Stroke, + TextBuffer, TextEdit, Vec2, +}; + +use crate::commands::{self, Action}; +use crate::document::Document; +use crate::settings::SavedBreakpoint; +use crate::worker::protocol::{CompletionItem, Documentation}; +use highlight::SyntaxColors; +use history::{EditKind, History}; +use text_ops::Selection; + +/// Most search matches highlighted at once. +const MAX_HIGHLIGHTED_MATCHES: usize = 2000; +const COMPLETION_ROWS: usize = 10; +/// Seconds the pointer rests on a name before its documentation is asked for. +const HOVER_DELAY: f64 = 0.6; +/// Width of the documentation tooltip, in points. +const HOVER_WIDTH: f32 = 520.0; + +#[derive(Clone, Debug, PartialEq)] +pub struct EditorColors { + pub syntax: SyntaxColors, + pub gutter_text: Color32, + pub gutter_text_current: Color32, + pub current_line: Color32, + pub ruler: Color32, + pub breakpoint: Color32, + pub debug_line: Color32, + pub debug_marker: Color32, + pub error_line: Color32, + pub error_text: Color32, + pub search_match: Color32, + pub search_current: Color32, +} + +pub struct EditorOptions<'a> { + pub font_size: f32, + pub line_wrap: bool, + /// Ruler column; 0 hides it. + pub ruler: usize, + pub highlight_current_line: bool, + pub auto_indent: bool, + /// Offer completions after this many characters of a name; 0 only + /// after `.` and on request. + pub completion_min_chars: usize, + pub colors: &'a EditorColors, +} + +/// Where the editor wants completions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CompletionRequest { + /// 1-based. + pub line: usize, + /// 0-based, in characters. + pub column: usize, + /// Offered while typing a name, not asked for: an empty answer is + /// not worth a message. + pub automatic: bool, +} + +/// Where the editor wants the documentation of the name under the pointer. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct HoverRequest { + /// 1-based. + pub line: usize, + /// 0-based, in characters. + pub column: usize, +} + +#[derive(Default)] +pub struct EditorOutput { + pub changed: bool, + pub completion_request: Option, + pub hover_request: Option, +} + +#[derive(Default)] +struct Search { + open: bool, + query: String, + match_case: bool, + whole_word: bool, + matches: Vec>, + current: usize, + focus_query: bool, + computed_for: u64, + /// The match the bar selected last, while the text and the query are + /// those of `computed_for`. An unfocused `TextEdit` collapses its + /// selection to the caret, so while the replace field has the keyboard + /// the editor's selection cannot tell which match is selected. + visited: Option<(Range, u64)>, + /// The replace row is shown. + replacing: bool, + replacement: String, + focus_replacement: bool, +} + +/// What the replace row was asked to do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Replace { + Current, + All, +} + +/// The *Go to line* bar. +#[derive(Default)] +struct GoToLine { + input: String, + focus: bool, +} + +/// Documentation of the name under the pointer. +#[derive(Default)] +struct Hover { + /// The name under the pointer and when the pointer arrived on it. + target: Option<(Range, f64)>, + /// The name whose documentation was asked for. + requested: Option>, + /// Documentation of the `requested` name, once it arrived. + text: Option, +} + +#[derive(Default)] +struct Completion { + items: Vec, + selected: usize, + /// Cursor position (byte) when the completion was requested. + anchor: usize, + open: bool, + scroll_to_selected: bool, +} + +/// The highlighted layout job of the last text. Galleys themselves are not +/// kept: egui rebuilds its font atlas now and then, which invalidates old +/// galleys, while its own galley cache handles that. +#[derive(Default)] +struct LayoutCache { + key: u64, + job: Option, + /// Width of the last laid out text, for horizontal scrolling. + width: f32, +} + +/// What a profiled run spent on one line (FEAT-E2). +#[derive(Clone, Debug, PartialEq)] +pub struct LineTiming { + /// With everything the line called. + pub seconds: f64, + pub hits: u64, + /// Its slowest calls into CadQuery: name, seconds and calls. + pub operations: Vec<(String, f64, u64)>, +} + +/// Lines faster than this get no time in the gutter. +const PROFILE_FLOOR_SECONDS: f64 = 0.001; +/// Characters of the gutter's time column ("999 ms", "12.3 s"). +const PROFILE_CHARS: f32 = 6.0; + +/// A duration as the gutter shows it: `850 ms`, `1.2 s`, `14 s`. +pub fn format_seconds(seconds: f64) -> String { + if seconds >= 10.0 { + format!("{seconds:.0} s") + } else if seconds >= 0.9995 { + format!("{seconds:.1} s") + } else if seconds >= PROFILE_FLOOR_SECONDS { + format!("{:.0} ms", seconds * 1000.0) + } else { + "<1 ms".to_owned() + } +} + +pub struct CodeEditor { + /// 1-based line numbers. + pub breakpoints: BTreeSet, + /// The last profiled run's time per 1-based line; it follows edits like + /// the breakpoints do. + pub line_profile: BTreeMap, + pub debug_line: Option, + pub error_line: Option, + /// The text the line markers above refer to; see [`Self::sync_markers`]. + marked_text: Option, + text_id: egui::Id, + /// Last known selection, in bytes. + selection: Selection, + pending_selection: Option, + pending_scroll_line: Option, + pending_focus: bool, + completion_wanted: bool, + /// Cursor position (byte) of the last completion request; the worker's + /// answer completes the text from there. + completion_anchor: usize, + completion: Completion, + calltip: Option, + search: Search, + go_to: Option, + hover: Hover, + history: History, + /// Time of the current frame, in seconds; groups typing into steps. + now: f64, + layout: LayoutCache, +} + +impl Default for CodeEditor { + fn default() -> Self { + Self::with_id(egui::Id::new("code_editor_text")) + } +} + +impl CodeEditor { + /// An editor whose widgets keep their state (caret, scrolling) in egui + /// under `id`: each tab has its own, so switching tabs keeps them. + pub fn with_id(id: egui::Id) -> Self { + Self { + breakpoints: BTreeSet::new(), + line_profile: BTreeMap::new(), + debug_line: None, + error_line: None, + marked_text: None, + text_id: id, + selection: Selection::caret(0), + pending_selection: None, + pending_scroll_line: None, + pending_focus: false, + completion_wanted: false, + completion_anchor: 0, + completion: Completion::default(), + calltip: None, + search: Search::default(), + go_to: None, + hover: Hover::default(), + history: History::default(), + now: 0.0, + layout: LayoutCache::default(), + } + } + + /// 1-based line and column of the cursor, for the status bar. + pub fn cursor_position(&self, text: &str) -> (usize, usize) { + let (line, column) = text_ops::line_column(text, self.selection.cursor.min(text.len())); + (line + 1, column + 1) + } + + /// Forgets per-document state when another file is loaded. + pub fn reset(&mut self) { + self.breakpoints.clear(); + self.line_profile.clear(); + self.debug_line = None; + self.error_line = None; + self.marked_text = None; + self.close_popups(); + self.hover = Hover::default(); + self.history.clear(); + self.pending_selection = Some(Selection::caret(0)); + self.pending_scroll_line = Some(1); + } + + pub fn can_undo(&self) -> bool { + self.history.can_undo() + } + + pub fn can_redo(&self) -> bool { + self.history.can_redo() + } + + /// Reverts the last edit step (typing, a command or a reload). + pub fn undo(&mut self, document: &mut Document) { + self.record_outside_edits(document); + if let Some((text, selection)) = self.history.undo(&document.text) { + self.restore(document, text, selection); + } + } + + pub fn redo(&mut self, document: &mut Document) { + self.record_outside_edits(document); + if let Some((text, selection)) = self.history.redo(&document.text) { + self.restore(document, text, selection); + } + } + + fn restore(&mut self, document: &mut Document, text: String, selection: Selection) { + document.text = text; + if self.marked_text.is_some() { + self.sync_markers(&document.text); + } + self.close_popups(); + self.selection = selection.clone(); + self.pending_scroll_line = Some(text_ops::line_of(&document.text, selection.cursor) + 1); + self.pending_selection = Some(selection); + self.pending_focus = true; + } + + /// Makes a change made outside the editor, such as a reload from disk, + /// a step of its own. + fn record_outside_edits(&mut self, document: &Document) { + let selection = self.clamped_selection(&document.text); + self.history.record( + &document.text, + &selection, + &selection, + EditKind::Command, + self.now, + ); + } + + /// The breakpoints with the text of their lines, to find them again + /// in a later session even if lines were added above them meanwhile. + pub fn saved_breakpoints(&mut self, text: &str) -> Vec { + self.sync_markers(text); + self.breakpoints + .iter() + .map(|&line| SavedBreakpoint { + line, + text: text[text_ops::line_range(text, line - 1)].trim().to_owned(), + }) + .collect() + } + + /// Restores breakpoints of an earlier session; see [`text_ops::relocate_lines`]. + pub fn restore_breakpoints(&mut self, text: &str, saved: &[SavedBreakpoint]) { + let saved: Vec<(usize, String)> = saved + .iter() + .map(|breakpoint| (breakpoint.line, breakpoint.text.clone())) + .collect(); + self.breakpoints = text_ops::relocate_lines(text, &saved); + self.marked_text = Some(text.to_owned()); + } + + /// Gives the keyboard to the text on the next frame. + pub fn focus(&mut self) { + self.pending_focus = true; + } + + pub fn go_to_line(&mut self, text: &str, line: usize) { + let start = text_ops::line_start(text, line.saturating_sub(1)); + self.pending_selection = Some(Selection::caret(start)); + self.pending_scroll_line = Some(line); + self.pending_focus = true; + } + + pub fn set_debug_line(&mut self, line: Option) { + self.debug_line = line; + if line.is_some() { + self.pending_scroll_line = line; + } + } + + /// Moves breakpoints and the error and debug lines along with the edits + /// made since the last call, so they stay on their statements when lines + /// are added or removed above them. Edits come from typing, the editor + /// commands and reloads alike, so this compares texts instead of hooking + /// each of them. + pub fn sync_markers(&mut self, text: &str) { + if let Some(marked) = &self.marked_text { + if marked == text { + return; + } + let map = text_ops::LineMap::new(marked, text); + self.breakpoints = self + .breakpoints + .iter() + .filter_map(|&line| map.map(line)) + .collect(); + self.error_line = self.error_line.and_then(|line| map.map(line)); + self.debug_line = self.debug_line.and_then(|line| map.map(line)); + self.line_profile = std::mem::take(&mut self.line_profile) + .into_iter() + .filter_map(|(line, timing)| Some((map.map(line)?, timing))) + .collect(); + } + self.marked_text = Some(text.to_owned()); + } + + /// Shows the times of a profiled run of `run_text` in the gutter of + /// `text`, the document as it is now (edited, perhaps, while it ran). + pub fn set_line_profile( + &mut self, + profile: BTreeMap, + run_text: &str, + text: &str, + ) { + self.sync_markers(text); + let map = text_ops::LineMap::new(run_text, text); + self.line_profile = profile + .into_iter() + .filter_map(|(line, timing)| Some((map.map(line)?, timing))) + .collect(); + } + + pub fn toggle_breakpoint(&mut self, line: usize) { + if !self.breakpoints.remove(&line) { + self.breakpoints.insert(line); + } + } + + pub fn toggle_comment(&mut self, document: &mut Document) { + let edited = + text_ops::toggle_comment(&document.text, &self.clamped_selection(&document.text)); + self.apply(document, edited); + } + + pub fn duplicate_line(&mut self, document: &mut Document) { + let edited = + text_ops::duplicate_lines(&document.text, &self.clamped_selection(&document.text)); + self.pending_scroll_line = + Some(text_ops::line_of(&edited.text, edited.selection.cursor) + 1); + self.apply(document, edited); + } + + pub fn move_lines(&mut self, document: &mut Document, up: bool) { + self.sync_markers(&document.text); + let selection = self.clamped_selection(&document.text); + let lines = text_ops::selected_lines(&document.text, &selection); + let total_lines = document.text.matches('\n').count() + 1; + let edited = if up { + if lines.start == 0 { + return; + } + text_ops::move_lines_up(&document.text, &selection) + } else { + if lines.end >= total_lines { + return; + } + text_ops::move_lines_down(&document.text, &selection) + }; + let first_1 = lines.start + 1; + let last_1 = lines.end; + let remap = |line: usize| -> usize { + if up { + if line == first_1 - 1 { + last_1 + } else if (first_1..=last_1).contains(&line) { + line - 1 + } else { + line + } + } else if line == last_1 + 1 { + first_1 + } else if (first_1..=last_1).contains(&line) { + line + 1 + } else { + line + } + }; + self.breakpoints = self.breakpoints.iter().map(|&l| remap(l)).collect(); + self.error_line = self.error_line.map(remap); + self.debug_line = self.debug_line.map(remap); + self.line_profile = std::mem::take(&mut self.line_profile) + .into_iter() + .map(|(line, timing)| (remap(line), timing)) + .collect(); + self.marked_text = Some(edited.text.clone()); + self.pending_scroll_line = + Some(text_ops::line_of(&edited.text, edited.selection.cursor) + 1); + self.apply(document, edited); + } + + pub fn insert_snippet(&mut self, document: &mut Document, snippet: &snippets::Snippet) { + let selection = self.clamped_selection(&document.text); + let edited = text_ops::insert_snippet( + &document.text, + &selection, + snippet.code, + snippet.needs_import, + ); + self.pending_scroll_line = + Some(text_ops::line_of(&edited.text, edited.selection.cursor) + 1); + self.apply(document, edited); + } + + /// Replaces `range` with `replacement` as a new value of the literal + /// there: successive values, such as those of a drag in the Parameters + /// panel, are one undo step. The caret stays on the text it was on and + /// the keyboard focus stays where it is. `now` is in seconds. + pub fn adjust_text( + &mut self, + document: &mut Document, + range: Range, + replacement: &str, + now: f64, + ) { + if document.text.get(range.clone()) == Some(replacement) { + return; + } + self.record_outside_edits(document); + let before = self.clamped_selection(&document.text); + let shift = |at: usize| { + if at >= range.end { + at - range.end + range.start + replacement.len() + } else { + at.min(range.start + replacement.len()) + } + }; + let after = Selection { + anchor: shift(before.anchor), + cursor: shift(before.cursor), + }; + document.text.replace_range(range.clone(), replacement); + self.history.record( + &document.text, + &before, + &after, + EditKind::Adjust(range.start), + now, + ); + self.close_popups(); + self.selection = after.clone(); + self.pending_selection = Some(after); + } + + /// Replaces multiple non-overlapping ranges (sorted by start byte) with + /// their replacements in a single undoable command step. + pub fn replace_literals( + &mut self, + document: &mut Document, + replacements: &[(Range, String)], + now: f64, + ) { + if replacements.is_empty() { + return; + } + self.record_outside_edits(document); + let before = self.clamped_selection(&document.text); + let mut after = before.clone(); + for (range, replacement) in replacements.iter().rev() { + if document.text.get(range.clone()) == Some(replacement.as_str()) { + continue; + } + let shift = |at: usize| { + if at >= range.end { + at - range.end + range.start + replacement.len() + } else { + at.min(range.start + replacement.len()) + } + }; + after.anchor = shift(after.anchor); + after.cursor = shift(after.cursor); + document.text.replace_range(range.clone(), replacement); + } + self.history + .record(&document.text, &before, &after, EditKind::Command, now); + self.close_popups(); + self.selection = after.clone(); + self.pending_selection = Some(after); + } + + /// Replaces the selection with `text` as one undo step and leaves the + /// caret after it, e.g. to insert a selector picked in the 3D view. + pub fn insert_text(&mut self, document: &mut Document, text: &str) { + let range = self.clamped_selection(&document.text).range(); + let mut edited = document.text.clone(); + edited.replace_range(range.clone(), text); + let caret = range.start + text.len(); + self.pending_scroll_line = Some(text_ops::line_of(&edited, caret) + 1); + self.apply( + document, + text_ops::Edited { + text: edited, + selection: Selection::caret(caret), + }, + ); + } + + pub fn open_search(&mut self, document: &Document) { + let range = self.clamped_selection(&document.text).range(); + let selected = &document.text[range]; + if !selected.is_empty() && !selected.contains('\n') { + self.search.query = selected.to_owned(); + } + self.search.open = true; + self.search.focus_query = true; + self.search.computed_for = 0; + self.go_to = None; + } + + /// Opens the search bar with its replace row. + pub fn open_replace(&mut self, document: &Document) { + let had_query = !self.search.query.is_empty(); + self.open_search(document); + self.search.replacing = true; + // With the query already filled in, the replacement is next. + if had_query || !self.search.query.is_empty() { + self.search.focus_query = false; + self.search.focus_replacement = true; + } + } + + pub fn open_go_to_line(&mut self) { + self.go_to = Some(GoToLine { + input: String::new(), + focus: true, + }); + self.search.open = false; + } + + /// Documentation for the name the editor asked about; empty when there + /// is none. + pub fn show_documentation(&mut self, documentation: Documentation) { + let current = self.hover.target.as_ref().map(|(range, _)| range); + if current.is_some() && current == self.hover.requested.as_ref() { + self.hover.text = Some(documentation); + } + } + + pub fn search_is_open(&self) -> bool { + self.search.open + } + + /// Selects the match after the selection (or before it), wrapping + /// around: from where the caret is, not from the last match visited. + pub fn find_next(&mut self, document: &Document, forward: bool) { + self.update_matches(&document.text); + let selection = self.clamped_selection(&document.text).range(); + if let Some(index) = next_match(&self.search.matches, &selection, forward) { + self.search.current = index; + self.select_current_match(&document.text); + } + } + + /// Asks for completions at the cursor on the next frame. + pub fn request_completion(&mut self) { + self.completion_wanted = true; + } + + /// Completion results from the worker. Returns `false` when there is + /// nothing to show. + pub fn show_completions( + &mut self, + items: Vec, + signatures: Vec, + ) -> bool { + self.calltip = None; + self.completion.open = false; + if !items.is_empty() { + self.completion = Completion { + items, + selected: 0, + anchor: self.completion_anchor, + open: true, + scroll_to_selected: true, + }; + true + } else if !signatures.is_empty() { + self.calltip = Some(signatures.join("\n")); + true + } else { + false + } + } + + pub fn close_popups(&mut self) { + self.completion.open = false; + self.calltip = None; + } + + fn clamped_selection(&self, text: &str) -> Selection { + let clamp = |i: usize| floor_char_boundary(text, i.min(text.len())); + Selection { + anchor: clamp(self.selection.anchor), + cursor: clamp(self.selection.cursor), + } + } + + /// Applies an editor command as one undo step. + fn apply(&mut self, document: &mut Document, edited: text_ops::Edited) { + if edited.text != document.text { + self.record_outside_edits(document); + if self.marked_text.is_some() { + self.sync_markers(&document.text); + } + let before = self.clamped_selection(&document.text); + document.text = edited.text; + if self.marked_text.is_some() { + self.sync_markers(&document.text); + } + self.history.record( + &document.text, + &before, + &edited.selection, + EditKind::Command, + self.now, + ); + } + self.selection = edited.selection.clone(); + self.pending_selection = Some(edited.selection); + self.pending_focus = true; + } + + pub fn ui( + &mut self, + ui: &mut egui::Ui, + document: &mut Document, + options: &EditorOptions<'_>, + ) -> EditorOutput { + let mut output = EditorOutput::default(); + self.now = ui.input(|i| i.time); + self.selection = self.read_selection(ui.ctx(), &document.text); + // A reload since the last frame is an undo step of its own. + self.record_outside_edits(document); + if self.search.open { + self.search_bar(ui, document); + } + if self.go_to.is_some() { + self.go_to_bar(ui, document); + } + + let font = FontId::monospace(options.font_size); + let (row_height, char_width) = + ui.fonts_mut(|f| (f.row_height(&font), f.glyph_width(&font, 'M'))); + + // Keys the editor handles itself must be taken before TextEdit sees + // them; that includes undo and redo, so `TextEdit`'s own history, + // which does not know the editor commands, is never used. + if ui.memory(|m| m.has_focus(self.text_id)) { + output.changed |= self.handle_keys(ui, document, options); + } + if let Some(selection) = self.pending_selection.take() { + self.write_selection(ui.ctx(), &document.text, &selection); + self.selection = selection; + } + let before_typing = self.clamped_selection(&document.text); + if std::mem::take(&mut self.pending_focus) { + ui.memory_mut(|m| m.request_focus(self.text_id)); + } + + let line_count = document.text.matches('\n').count() + 1; + let digits = line_count.to_string().len().max(2); + let number_width = digits as f32 * char_width; + let profile_width = if self.line_profile.is_empty() { + 0.0 + } else { + PROFILE_CHARS * char_width + 8.0 + }; + let gutter_width = number_width + 28.0 + profile_width; + + let dark = ui.visuals().dark_mode; + let colors = options.colors; + let area = ui.available_rect_before_wrap(); + let gutter_rect = Rect::from_min_size(area.min, Vec2::new(gutter_width, area.height())); + let text_rect = Rect::from_min_max(Pos2::new(gutter_rect.right(), area.top()), area.max); + ui.allocate_rect(area, Sense::hover()); + + // The text scrolls both ways; the gutter only follows it vertically, + // so the line numbers stay in view. + let mut text_ui = ui.new_child(egui::UiBuilder::new().max_rect(text_rect)); + let geometry = egui::ScrollArea::both() + .id_salt(self.text_id.with("scroll")) + .auto_shrink([false, false]) + .show(&mut text_ui, |ui| { + ui.spacing_mut().item_spacing = Vec2::ZERO; + // Placeholder for backgrounds that must sit under the text. + let background = ui.painter().add(Shape::Noop); + + let wrap = options.line_wrap; + let previous_width = self.layout.width; + let cache = &mut self.layout; + let mut layouter = |ui: &egui::Ui, buffer: &dyn TextBuffer, wrap_width: f32| { + let text = buffer.as_str(); + let wrap_width = if wrap { wrap_width } else { f32::INFINITY }; + let key = layout_key(text, wrap_width, font.size, dark); + if cache.key != key || cache.job.is_none() { + cache.key = key; + cache.job = Some(highlight::layout_job( + text, + font.clone(), + &colors.syntax, + wrap_width, + )); + } + let job = cache.job.clone().unwrap_or_default(); + let galley = ui.fonts_mut(|f| f.layout_job(job)); + cache.width = galley.size().x; + galley + }; + + let available = ui.available_size(); + // Without wrapping the text edit must be as wide as its + // longest line, so the scroll area can scroll sideways + // (last frame's layout is a good enough measure). + let text_width = if wrap { + available.x + } else { + (previous_width + 24.0).max(available.x) + }; + let edit = TextEdit::multiline(&mut document.text) + .id(self.text_id) + .font(font.clone()) + .lock_focus(true) + .frame(egui::Frame::NONE) + .margin(egui::Margin::symmetric(6, 2)) + .desired_width(if wrap { available.x } else { f32::INFINITY }) + .min_size(Vec2::new(text_width, available.y.max(row_height))) + .layouter(&mut layouter) + .show(ui); + let text_changed = edit.response.response.changed(); + output.changed |= text_changed; + if let Some(range) = edit.cursor_range { + self.selection = Selection { + anchor: text_ops::char_to_byte(&document.text, range.secondary.index.0), + cursor: text_ops::char_to_byte(&document.text, range.primary.index.0), + }; + } + if text_changed { + self.history.record( + &document.text, + &before_typing, + &self.selection, + EditKind::Typing, + self.now, + ); + self.close_popups_if_left(&document.text); + self.hover = Hover::default(); + } + // Before the line backgrounds and the gutter are drawn. + self.sync_markers(&document.text); + + // Typing "." asks for member completions, and typing the + // first characters of a name for names. + let typed = |test: fn(&str) -> bool| { + text_changed + && ui.input(|i| { + i.events.iter().any( + |e| matches!(e, egui::Event::Text(t) if !t.is_empty() && test(t)), + ) + }) + }; + let typed_dot = typed(|t| t == "."); + let typed_name = !self.completion.open + && typed(|t| t.chars().all(text_ops::is_word_char)) + && completes_name( + &document.text, + self.selection.cursor, + options.completion_min_chars, + ); + let wanted = std::mem::take(&mut self.completion_wanted); + if typed_dot || typed_name || wanted { + let cursor = self.selection.cursor.min(document.text.len()); + let (line, column) = text_ops::line_column(&document.text, cursor); + self.completion_anchor = cursor; + output.completion_request = Some(CompletionRequest { + line: line + 1, + column, + automatic: typed_name && !typed_dot && !wanted, + }); + } + + output.hover_request = self.hover(ui, &edit, &document.text); + + let geometry = Geometry::new(&edit.galley, edit.galley_pos); + let text_left = edit.response.response.rect.left(); + let shapes = self.backgrounds( + &geometry, + &document.text, + options, + text_left, + ui.clip_rect(), + char_width, + ); + ui.painter().set(background, Shape::Vec(shapes)); + + if let Some(line) = self.pending_scroll_line.take() + && let Some(rect) = geometry.line_rect(line.saturating_sub(1)) + { + // Aim at the start of the line: vertical scrolling only. + let target = Rect::from_min_size( + Pos2::new(text_left, rect.top()), + Vec2::new(1.0, rect.height()), + ); + ui.scroll_to_rect(target, Some(Align::Center)); + } + + let caret = geometry.caret_rect(&document.text, self.selection.cursor); + self.popups(ui, document, caret, row_height); + geometry + }) + .inner; + + self.paint_gutter(ui, &geometry, gutter_rect, colors, number_width); + let gutter = ui.interact(gutter_rect, self.text_id.with("gutter"), Sense::click()); + if gutter.clicked() + && let Some(line) = gutter + .interact_pointer_pos() + .and_then(|p| geometry.line_at(p.y)) + { + self.toggle_breakpoint(line + 1); + } + gutter.on_hover_cursor(egui::CursorIcon::PointingHand); + output + } + + fn read_selection(&self, ctx: &egui::Context, text: &str) -> Selection { + TextEdit::load_state(ctx, self.text_id) + .and_then(|state| state.cursor.char_range()) + .map_or(self.selection.clone(), |range| Selection { + anchor: text_ops::char_to_byte(text, range.secondary.index.0), + cursor: text_ops::char_to_byte(text, range.primary.index.0), + }) + } + + fn write_selection(&self, ctx: &egui::Context, text: &str, selection: &Selection) { + let mut state = TextEdit::load_state(ctx, self.text_id).unwrap_or_default(); + state.cursor.set_char_range(Some(CCursorRange { + primary: CCursor::new(text_ops::byte_to_char(text, selection.cursor)), + secondary: CCursor::new(text_ops::byte_to_char(text, selection.anchor)), + h_pos: None, + })); + TextEdit::store_state(ctx, self.text_id, state); + } + + /// Handles Tab, Shift+Tab, Enter and the completion popup's keys. + fn handle_keys( + &mut self, + ui: &egui::Ui, + document: &mut Document, + options: &EditorOptions<'_>, + ) -> bool { + let consume = |modifiers, key| ui.input_mut(|i| i.consume_key(modifiers, key)); + // egui ignores an extra Shift when matching, so Ctrl+Shift+Z first. + if consume(Modifiers::COMMAND.plus(Modifiers::SHIFT), Key::Z) + || consume(Modifiers::COMMAND, Key::Y) + { + self.redo(document); + return true; + } + if consume(Modifiers::COMMAND, Key::Z) { + self.undo(document); + return true; + } + let selection = self.clamped_selection(&document.text); + + if self.completion.open { + let visible = self.visible_completions(&document.text); + if consume(Modifiers::NONE, Key::Escape) { + self.completion.open = false; + } else if consume(Modifiers::NONE, Key::ArrowDown) { + self.completion.selected = + (self.completion.selected + 1).min(visible.len().saturating_sub(1)); + self.completion.scroll_to_selected = true; + } else if consume(Modifiers::NONE, Key::ArrowUp) { + self.completion.selected = self.completion.selected.saturating_sub(1); + self.completion.scroll_to_selected = true; + } else if !visible.is_empty() + && (consume(Modifiers::NONE, Key::Enter) || consume(Modifiers::NONE, Key::Tab)) + { + let index = visible[self.completion.selected.min(visible.len() - 1)]; + self.accept_completion(document, index); + return true; + } + } + if self.calltip.is_some() && consume(Modifiers::NONE, Key::Escape) { + self.calltip = None; + } + + let edited = if consume(Modifiers::SHIFT, Key::Tab) { + Some(text_ops::unindent(&document.text, &selection)) + } else if consume(Modifiers::NONE, Key::Tab) { + Some(text_ops::indent(&document.text, &selection)) + } else if options.auto_indent && consume(Modifiers::NONE, Key::Enter) { + let range = selection.range(); + let insert = text_ops::newline_with_indent(&document.text, range.start); + let mut text = document.text.clone(); + text.replace_range(range.clone(), &insert); + Some(text_ops::Edited { + text, + selection: Selection::caret(range.start + insert.len()), + }) + } else { + None + }; + match edited { + Some(edited) => { + self.apply(document, edited); + true + } + None => false, + } + } + + /// Indices of the completion items matching what was typed since the + /// completion was requested. + fn visible_completions(&self, text: &str) -> Vec { + let typed = typed_since(text, self.completion.anchor, self.selection.cursor); + self.completion + .items + .iter() + .enumerate() + .filter(|(_, item)| item.insert.starts_with(typed)) + .map(|(i, _)| i) + .collect() + } + + fn accept_completion(&mut self, document: &mut Document, index: usize) { + let Some(item) = self.completion.items.get(index) else { + return; + }; + let cursor = self.selection.cursor.min(document.text.len()); + let typed = typed_since(&document.text, self.completion.anchor, cursor).len(); + let insert = item.insert.get(typed..).unwrap_or_default().to_owned(); + let mut text = document.text.clone(); + text.insert_str(cursor, &insert); + self.completion.open = false; + self.apply( + document, + text_ops::Edited { + text, + selection: Selection::caret(cursor + insert.len()), + }, + ); + } + + /// Typing outside the identifier being completed closes the popups. + fn close_popups_if_left(&mut self, text: &str) { + if !self.completion.open { + return; + } + let typed = typed_text(text, self.completion.anchor, self.selection.cursor); + if typed.is_none_or(|t| !t.chars().all(text_ops::is_word_char)) { + self.completion.open = false; + } + } + + /// Follows the name under the pointer. Once the pointer has rested on + /// it, asks for its documentation; once that arrived, shows it. + fn hover( + &mut self, + ui: &egui::Ui, + edit: &egui::text_edit::TextEditOutput, + text: &str, + ) -> Option { + let pointer = edit + .response + .response + .hover_pos() + .filter(|_| !self.completion.open && self.calltip.is_none()); + let name = pointer.and_then(|pos| name_at(&edit.galley, edit.galley_pos, text, pos)); + if self.hover.target.as_ref().map(|(range, _)| range) != name.as_ref() { + self.hover = Hover { + target: name.map(|range| (range, self.now)), + ..Hover::default() + }; + } + let (range, since) = self.hover.target.clone()?; + + if self.hover.requested.as_ref() != Some(&range) { + let waited = self.now - since; + if waited < HOVER_DELAY { + ui.ctx() + .request_repaint_after(std::time::Duration::from_secs_f64( + HOVER_DELAY - waited, + )); + return None; + } + self.hover.requested = Some(range.clone()); + let (line, column) = text_ops::line_column(text, range.start); + return Some(HoverRequest { + line: line + 1, + column, + }); + } + + if let (Some(pos), Some(documentation)) = (pointer, &self.hover.text) + && !(documentation.signatures.is_empty() && documentation.text.is_empty()) + { + // Below the pointer, or above it in the lower half of the + // screen, so it never covers the name it describes. + let below = pos.y < ui.ctx().content_rect().center().y; + let (pivot, offset) = if below { + (Align2::LEFT_TOP, Vec2::new(12.0, 18.0)) + } else { + (Align2::LEFT_BOTTOM, Vec2::new(12.0, -12.0)) + }; + egui::Area::new(self.text_id.with("documentation")) + .order(egui::Order::Tooltip) + .pivot(pivot) + .fixed_pos(pos + offset) + .interactable(false) + .constrain(true) + .show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_max_width(HOVER_WIDTH); + for signature in &documentation.signatures { + ui.label(egui::RichText::new(signature).monospace().strong()); + } + if !documentation.text.is_empty() { + if !documentation.signatures.is_empty() { + ui.separator(); + } + ui.label(&documentation.text); + } + }); + }); + } + None + } + + fn search_bar(&mut self, ui: &mut egui::Ui, document: &mut Document) { + use egui_phosphor::regular as icon; + + self.update_matches(&document.text); + let mut navigate: Option = None; + let mut close = false; + let mut replace: Option = None; + let shortcut_hint = |label: &str, action: Action| { + commands::shortcut(&action).map_or_else( + || label.to_owned(), + |shortcut| format!("{label} ({})", ui.ctx().format_shortcut(&shortcut)), + ) + }; + let previous_hint = shortcut_hint("Previous match", Action::FindPrevious); + let next_hint = shortcut_hint("Next match", Action::FindNext); + let replace_hint = shortcut_hint("Replace", Action::Replace); + let field_width = bar_field_width(ui); + ui.horizontal(|ui| { + ui.label(egui_phosphor::regular::MAGNIFYING_GLASS); + let response = ui.add( + TextEdit::singleline(&mut self.search.query) + .hint_text("Search") + .desired_width(field_width), + ); + if std::mem::take(&mut self.search.focus_query) { + response.request_focus(); + } + if response.changed() { + self.search.computed_for = 0; + self.search.current = 0; + } + if response.has_focus() || response.lost_focus() { + let (enter, shift, escape) = take_bar_keys(ui); + if enter { + navigate = Some(!shift); + response.request_focus(); + } + close |= escape; + } + if ui + .add_enabled( + !self.search.matches.is_empty(), + egui::Button::new(egui_phosphor::regular::ARROW_UP), + ) + .on_hover_text(previous_hint) + .clicked() + { + navigate = Some(false); + } + if ui + .add_enabled( + !self.search.matches.is_empty(), + egui::Button::new(egui_phosphor::regular::ARROW_DOWN), + ) + .on_hover_text(next_hint) + .clicked() + { + navigate = Some(true); + } + if ui + .selectable_label(self.search.match_case, "Aa") + .on_hover_text("Match case") + .clicked() + { + self.search.match_case = !self.search.match_case; + self.search.computed_for = 0; + } + if ui + .selectable_label( + self.search.whole_word, + egui::RichText::new("ab").underline(), + ) + .on_hover_text("Whole word") + .clicked() + { + self.search.whole_word = !self.search.whole_word; + self.search.computed_for = 0; + } + let count = self.search.matches.len(); + ui.weak(match count { + 0 if self.search.query.is_empty() => String::new(), + 0 => "No matches".to_owned(), + _ => format!("{} of {count}", self.search.current.min(count - 1) + 1), + }); + ui.with_layout(egui::Layout::right_to_left(Align::Center), |ui| { + if ui.button(icon::X).on_hover_text("Close (Esc)").clicked() { + close = true; + } + if ui + .selectable_label(self.search.replacing, icon::SWAP) + .on_hover_text(replace_hint) + .clicked() + { + self.search.replacing = !self.search.replacing; + self.search.focus_replacement = self.search.replacing; + } + }); + }); + if self.search.replacing { + ui.horizontal(|ui| { + ui.label(icon::SWAP); + let response = ui.add( + TextEdit::singleline(&mut self.search.replacement) + .hint_text("Replace with") + .desired_width(field_width), + ); + if std::mem::take(&mut self.search.focus_replacement) { + response.request_focus(); + } + if response.has_focus() || response.lost_focus() { + let (enter, _, escape) = take_bar_keys(ui); + if enter { + replace = Some(Replace::Current); + response.request_focus(); + } + close |= escape; + } + let found = !self.search.matches.is_empty(); + if ui + .add_enabled(found, egui::Button::new("Replace")) + .on_hover_text("Replace this match and go to the next one (Enter)") + .clicked() + { + replace = Some(Replace::Current); + } + if ui + .add_enabled(found, egui::Button::new("Replace all")) + .on_hover_text("Replace every match, as one step to undo") + .clicked() + { + replace = Some(Replace::All); + } + }); + } + ui.separator(); + + match replace { + Some(Replace::Current) => self.replace_current(document), + Some(Replace::All) => self.replace_all(document), + None => {} + } + if let Some(forward) = navigate { + self.find_next(document, forward); + } + if close { + self.search.open = false; + self.pending_focus = true; + } + } + + /// Replaces the selected match and moves on to the next one. Without a + /// selected match, selects the next one first, so nothing is replaced + /// unseen. + fn replace_current(&mut self, document: &mut Document) { + self.update_matches(&document.text); + let selected = self.clamped_selection(&document.text).range(); + let visited = self + .search + .visited + .clone() + .filter(|(_, key)| *key == self.search.computed_for) + .map(|(range, _)| range); + let index = self + .search + .matches + .iter() + .position(|m| *m == selected || Some(m) == visited.as_ref()); + let Some(index) = index else { + self.find_next(document, true); + return; + }; + let range = self.search.matches[index].clone(); + let replacement = self.search.replacement.clone(); + let edited = text_ops::replace_ranges( + &document.text, + &Selection::caret(range.start), + std::slice::from_ref(&range), + &replacement, + ); + self.apply(document, edited); + // The replace field keeps the keyboard for the next Enter. + self.pending_focus = false; + self.update_matches(&document.text); + let after = range.start + replacement.len(); + let next = self.search.matches.iter().position(|m| m.start >= after); + if let Some(next) = next.or((!self.search.matches.is_empty()).then_some(0)) { + self.search.current = next; + self.select_current_match(&document.text); + } + } + + fn replace_all(&mut self, document: &mut Document) { + self.update_matches(&document.text); + if self.search.matches.is_empty() { + return; + } + let selection = self.clamped_selection(&document.text); + let edited = text_ops::replace_ranges( + &document.text, + &selection, + &self.search.matches, + &self.search.replacement, + ); + self.apply(document, edited); + self.pending_focus = false; + } + + fn go_to_bar(&mut self, ui: &mut egui::Ui, document: &Document) { + use egui_phosphor::regular as icon; + + let Some(go_to) = &mut self.go_to else { + return; + }; + let lines = document.text.matches('\n').count() + 1; + let target = text_ops::go_to_target(&document.text, &go_to.input); + let mut jump = false; + let mut close = false; + let field_width = bar_field_width(ui); + ui.horizontal(|ui| { + ui.label(icon::LIST_NUMBERS); + let response = ui.add( + TextEdit::singleline(&mut go_to.input) + .hint_text(format!("Line (1–{lines}), or line:column")) + .desired_width(field_width), + ); + if std::mem::take(&mut go_to.focus) { + response.request_focus(); + } + if response.has_focus() || response.lost_focus() { + let (enter, _, escape) = take_bar_keys(ui); + jump |= enter; + close |= escape; + } + if ui + .add_enabled(target.is_some(), egui::Button::new("Go")) + .clicked() + { + jump = true; + } + if !go_to.input.trim().is_empty() && target.is_none() { + ui.weak("Not a line number"); + } + ui.with_layout(egui::Layout::right_to_left(Align::Center), |ui| { + close |= ui.button(icon::X).on_hover_text("Close (Esc)").clicked(); + }); + }); + ui.separator(); + + if jump && let Some((line, offset)) = target { + self.pending_selection = Some(Selection::caret(offset)); + self.pending_scroll_line = Some(line + 1); + close = true; + } + if close { + self.go_to = None; + self.pending_focus = true; + } + } + + fn update_matches(&mut self, text: &str) { + let mut hasher = DefaultHasher::new(); + let search = &self.search; + (text, &search.query, search.match_case, search.whole_word).hash(&mut hasher); + let key = hasher.finish() | 1; + if self.search.computed_for == key { + return; + } + self.search.computed_for = key; + self.search.matches = find_all( + text, + &self.search.query, + self.search.match_case, + self.search.whole_word, + ); + if self.search.current >= self.search.matches.len() { + self.search.current = 0; + } + } + + fn select_current_match(&mut self, text: &str) { + if let Some(range) = self.search.matches.get(self.search.current).cloned() { + self.search.visited = Some((range.clone(), self.search.computed_for)); + self.pending_selection = Some(Selection { + anchor: range.start, + cursor: range.end, + }); + self.pending_scroll_line = Some(text_ops::line_of(text, range.start) + 1); + } + } + + fn backgrounds( + &self, + geometry: &Geometry, + text: &str, + options: &EditorOptions<'_>, + text_left: f32, + clip: Rect, + char_width: f32, + ) -> Vec { + let colors = options.colors; + let mut shapes = Vec::new(); + let full_width = |rect: Rect| { + Rect::from_x_y_ranges(text_left..=clip.right().max(rect.right()), rect.y_range()) + }; + + let mut line_background = |line: Option, color: Color32| { + if let Some(rect) = line.and_then(|l| geometry.line_rect(l.saturating_sub(1))) + && rect.intersects(clip) + { + shapes.push(Shape::rect_filled(full_width(rect), 0.0, color)); + } + }; + if options.highlight_current_line && self.selection.range().is_empty() { + line_background( + Some(text_ops::line_of(text, self.selection.cursor) + 1), + colors.current_line, + ); + } + line_background(self.error_line, colors.error_line); + line_background(self.debug_line, colors.debug_line); + + if self.search.open { + for (i, range) in self + .search + .matches + .iter() + .enumerate() + .take(MAX_HIGHLIGHTED_MATCHES) + { + let start = geometry.caret_rect(text, range.start); + let end = geometry.caret_rect(text, range.end); + if !start.intersects(clip) { + continue; + } + let rect = if (start.top() - end.top()).abs() < 1.0 { + Rect::from_min_max(start.left_top(), Pos2::new(end.left(), start.bottom())) + } else { + Rect::from_min_max( + start.left_top(), + Pos2::new(start.left() + char_width, start.bottom()), + ) + }; + let color = if i == self.search.current { + colors.search_current + } else { + colors.search_match + }; + shapes.push(Shape::rect_filled( + rect.expand2(Vec2::new(1.0, 0.0)), + 2.0, + color, + )); + } + } + + if options.ruler > 0 { + let x = geometry.origin.x + options.ruler as f32 * char_width; + if (clip.left()..=clip.right()).contains(&x) { + shapes.push(Shape::line_segment( + [Pos2::new(x, clip.top()), Pos2::new(x, clip.bottom())], + Stroke::new(1.0, colors.ruler), + )); + } + } + shapes + } + + fn paint_gutter( + &self, + ui: &egui::Ui, + geometry: &Geometry, + gutter: Rect, + colors: &EditorColors, + number_width: f32, + ) { + let painter = ui.painter_at(gutter); + let clip = gutter; + let font = FontId::monospace(geometry.row_height.max(8.0) * 0.8); + let cursor_line = geometry.line_of_byte(self.selection.cursor); + let slowest = self + .line_profile + .values() + .map(|timing| timing.seconds) + .fold(0.0, f64::max); + let time_right = gutter.right() - 10.0 - number_width - 8.0; + for (line, rect) in geometry.lines() { + if rect.bottom() < clip.top() || rect.top() > clip.bottom() { + continue; + } + let number = line + 1; + let y_center = rect.top() + geometry.row_height / 2.0; + let color = if self.error_line == Some(number) { + colors.error_text + } else if Some(line) == cursor_line { + colors.gutter_text_current + } else { + colors.gutter_text + }; + painter.text( + Pos2::new(gutter.right() - 10.0, rect.top()), + Align2::RIGHT_TOP, + number.to_string(), + font.clone(), + color, + ); + if let Some(timing) = self.line_profile.get(&number) + && timing.seconds >= PROFILE_FLOOR_SECONDS + { + // Hotter for a larger share of the slowest line's time. + let share = (timing.seconds / slowest.max(f64::EPSILON)).sqrt() as f32; + let color = lerp_color(colors.gutter_text, PROFILE_HOT, share); + let galley = painter.layout_no_wrap( + format_seconds(timing.seconds), + FontId::monospace(font.size * 0.9), + color, + ); + let at = Pos2::new( + time_right - galley.size().x, + y_center - galley.size().y / 2.0, + ); + let area = Rect::from_min_size(at, galley.size()); + painter.galley(at, galley, color); + ui.interact(area, self.text_id.with(("profile", number)), Sense::hover()) + .on_hover_text(profile_tooltip(number, timing)); + } + let marker = Pos2::new(gutter.left() + 10.0, y_center); + if self.breakpoints.contains(&number) { + painter.circle( + marker, + 4.5, + colors.breakpoint, + Stroke::new(1.0, colors.breakpoint.gamma_multiply(0.6)), + ); + } + if self.debug_line == Some(number) { + let arrow = vec![ + marker + Vec2::new(-4.0, -5.0), + marker + Vec2::new(5.0, 0.0), + marker + Vec2::new(-4.0, 5.0), + ]; + painter.add(Shape::convex_polygon( + arrow, + colors.debug_marker, + Stroke::NONE, + )); + } + } + } + + fn popups(&mut self, ui: &egui::Ui, document: &mut Document, caret: Rect, row_height: f32) { + let anchor = caret.left_bottom() + Vec2::new(0.0, 2.0); + if self.completion.open { + let visible = self.visible_completions(&document.text); + if visible.is_empty() { + self.completion.open = false; + } else { + self.completion.selected = self.completion.selected.min(visible.len() - 1); + let mut clicked = None; + let scroll = std::mem::take(&mut self.completion.scroll_to_selected); + egui::Area::new(self.text_id.with("completion")) + .order(egui::Order::Foreground) + .fixed_pos(anchor) + .show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.set_min_width(220.0); + egui::ScrollArea::vertical() + .max_height(row_height * COMPLETION_ROWS as f32 * 1.6) + .show(ui, |ui| { + for (position, &index) in visible.iter().enumerate() { + let item = &self.completion.items[index]; + let selected = position == self.completion.selected; + let label = + format!("{} {}", kind_icon(&item.kind), item.name); + let response = ui.selectable_label(selected, label); + if selected && scroll { + response.scroll_to_me(None); + } + if response.clicked() { + clicked = Some(index); + } + } + }); + }); + }); + if let Some(index) = clicked { + self.accept_completion(document, index); + } + } + } + if let Some(calltip) = &self.calltip { + egui::Area::new(self.text_id.with("calltip")) + .order(egui::Order::Foreground) + .fixed_pos(anchor) + .interactable(false) + .show(ui.ctx(), |ui| { + egui::Frame::popup(ui.style()).show(ui, |ui| { + ui.monospace(calltip); + }); + }); + } + } +} + +/// Width of the text field of the search, replace and *Go to line* bars: +/// as wide as the buttons next to it leave room for in a narrow editor. +fn bar_field_width(ui: &egui::Ui) -> f32 { + (ui.available_width() - 320.0).clamp(100.0, 220.0) +} + +/// Takes Enter and Escape from this frame's input: a bar's text field acts +/// on them, and the editor, which may get the keyboard back in this frame, +/// must not see them too (Enter would replace its selection with a new +/// line). Returns whether Enter was pressed, with Shift held, and Escape. +fn take_bar_keys(ui: &egui::Ui) -> (bool, bool, bool) { + ui.input_mut(|i| { + let shift = i.modifiers.shift; + let enter = i.consume_key(Modifiers::NONE, Key::Enter); + let escape = i.consume_key(Modifiers::NONE, Key::Escape); + (enter, shift, escape) + }) +} + +/// Whether typing has just reached `min_chars` characters of a name at +/// `cursor`, the moment to offer completions. Names never start with a +/// digit, and words in comments and strings are not names; 0 turns this +/// off. +fn completes_name(text: &str, cursor: usize, min_chars: usize) -> bool { + let name = text_ops::name_before(text, cursor); + min_chars > 0 + && name.chars().count() == min_chars + && !name.starts_with(|c: char| c.is_ascii_digit()) + && highlight::in_code(text, cursor) +} + +/// The name whose characters are under the pointer at `pos`. +fn name_at(galley: &Galley, origin: Pos2, text: &str, pos: Pos2) -> Option> { + let caret = galley.cursor_from_pos(pos - origin); + let byte = text_ops::char_to_byte(text, caret.index.0); + // The caret is between two characters: the pointer is on the one after + // it when it is to the right of the caret. + let caret_x = galley.pos_from_cursor(caret).left() + origin.x; + let on = if pos.x >= caret_x { + byte + } else { + text[..byte].char_indices().next_back()?.0 + }; + let name = text_ops::word_at(text, on)?; + let rect = |byte: usize| { + galley + .pos_from_cursor(CCursor::new(text_ops::byte_to_char(text, byte))) + .translate(origin.to_vec2()) + }; + let (start, end) = (rect(name.start), rect(name.end)); + let inside = (start.top() - end.top()).abs() < 1.0 + && (start.left()..=end.left()).contains(&pos.x) + && start.y_range().contains(pos.y); + inside.then_some(name) +} + +/// Text typed between `anchor` and `cursor` (empty if the cursor moved back). +fn typed_since(text: &str, anchor: usize, cursor: usize) -> &str { + typed_text(text, anchor, cursor).unwrap_or_default() +} + +/// Text between `anchor` and `cursor`, or `None` when the cursor moved back +/// or an edit elsewhere left the anchor outside the text or inside a +/// character, where slicing would panic. +fn typed_text(text: &str, anchor: usize, cursor: usize) -> Option<&str> { + (anchor <= cursor && text.is_char_boundary(anchor) && text.is_char_boundary(cursor)) + .then(|| &text[anchor..cursor]) +} + +fn kind_icon(kind: &str) -> &'static str { + use egui_phosphor::regular as icon; + match kind { + "function" => icon::FUNCTION, + "class" => icon::CUBE, + "module" => icon::PACKAGE, + "keyword" => icon::TEXT_AA, + "param" => icon::AT, + "property" | "statement" | "instance" => icon::DOT_OUTLINE, + _ => icon::DOT, + } +} + +fn layout_key(text: &str, wrap_width: f32, font_size: f32, dark: bool) -> u64 { + let mut hasher = DefaultHasher::new(); + (text, wrap_width.to_bits(), font_size.to_bits(), dark).hash(&mut hasher); + hasher.finish() +} + +fn floor_char_boundary(text: &str, mut index: usize) -> usize { + while index > 0 && !text.is_char_boundary(index) { + index -= 1; + } + index +} + +/// The match to go to from `selection`: the first one after it going +/// forward, the last one before it going back, wrapping around. +fn next_match(matches: &[Range], selection: &Range, forward: bool) -> Option { + if matches.is_empty() { + return None; + } + Some(if forward { + matches + .iter() + .position(|m| m.start >= selection.end && m != selection) + .unwrap_or(0) + } else { + matches + .iter() + .rposition(|m| m.end <= selection.start && m != selection) + .unwrap_or(matches.len() - 1) + }) +} + +/// Whether `range` is a whole word: no name character touches either end. +fn is_whole_word(text: &str, range: &Range) -> bool { + let before = text[..range.start].chars().next_back(); + let after = text[range.end..].chars().next(); + !before.is_some_and(text_ops::is_word_char) && !after.is_some_and(text_ops::is_word_char) +} + +/// Byte ranges of every occurrence of `query`, optionally only where it is +/// a whole word. +fn find_all(text: &str, query: &str, match_case: bool, whole_word: bool) -> Vec> { + let mut matches = find_occurrences(text, query, match_case); + if whole_word { + matches.retain(|range| is_whole_word(text, range)); + } + matches +} + +fn find_occurrences(text: &str, query: &str, match_case: bool) -> Vec> { + if query.is_empty() { + return Vec::new(); + } + if match_case { + return text + .match_indices(query) + .map(|(i, m)| i..i + m.len()) + .collect(); + } + // Lowercasing can change byte lengths for some scripts, so compare + // character by character. + let needle: Vec = query.chars().flat_map(char::to_lowercase).collect(); + let haystack: Vec<(usize, char)> = text + .char_indices() + .flat_map(|(i, c)| c.to_lowercase().map(move |l| (i, l))) + .collect(); + let mut matches = Vec::new(); + let mut i = 0; + while i + needle.len() <= haystack.len() { + if haystack[i..i + needle.len()] + .iter() + .map(|(_, c)| *c) + .eq(needle.iter().copied()) + { + let start = haystack[i].0; + let last = haystack[i + needle.len() - 1].0; + let end = last + text[last..].chars().next().map_or(0, char::len_utf8); + matches.push(start..end); + i += needle.len(); + } else { + i += 1; + } + } + matches +} + +/// Where lines and characters ended up on screen. +struct Geometry { + galley: Arc, + origin: Pos2, + row_height: f32, + /// First row index of each logical line. + line_rows: Vec, +} + +impl Geometry { + fn new(galley: &Arc, origin: Pos2) -> Self { + let mut line_rows = vec![0]; + for (index, row) in galley.rows.iter().enumerate() { + if row.ends_with_newline { + line_rows.push(index + 1); + } + } + let row_height = galley.rows.first().map_or(14.0, |row| row.rect().height()); + Self { + galley: galley.clone(), + origin, + row_height, + line_rows, + } + } + + /// Screen rectangle of a (0-based) logical line, across its wrapped rows. + fn line_rect(&self, line: usize) -> Option { + let first = *self.line_rows.get(line)?; + let last = self + .line_rows + .get(line + 1) + .map_or(self.galley.rows.len(), |&next| next) + .max(first + 1); + let top = self + .galley + .rows + .get(first) + .map_or_else(|| self.galley.rect.bottom(), |row| row.rect().top()); + let bottom = self + .galley + .rows + .get(last - 1) + .map_or(top + self.row_height, |row| row.rect().bottom()); + Some(Rect::from_min_max( + Pos2::new(self.origin.x, self.origin.y + top), + Pos2::new( + self.origin.x + self.galley.rect.width(), + self.origin.y + bottom, + ), + )) + } + + fn lines(&self) -> impl Iterator + '_ { + (0..self.line_rows.len()).filter_map(|line| self.line_rect(line).map(|rect| (line, rect))) + } + + fn line_at(&self, y: f32) -> Option { + self.lines() + .find(|(_, rect)| rect.y_range().contains(y)) + .map(|(line, _)| line) + } + + fn line_of_byte(&self, byte: usize) -> Option { + let text = self.galley.text(); + Some(text_ops::line_of(text, byte.min(text.len()))) + } + + /// Screen rectangle of the caret at `byte`. + fn caret_rect(&self, text: &str, byte: usize) -> Rect { + let index = text_ops::byte_to_char(text, byte.min(text.len())); + self.galley + .pos_from_cursor(CCursor::new(index)) + .translate(self.origin.to_vec2()) + } +} + +#[cfg(test)] +#[path = "../../tests/rust/editor/test_editor.rs"] +mod tests; + +/// The gutter's color for the slowest lines. +const PROFILE_HOT: Color32 = Color32::from_rgb(235, 110, 45); + +fn lerp_color(from: Color32, to: Color32, amount: f32) -> Color32 { + let mix = |a: u8, b: u8| { + (f32::from(a) + (f32::from(b) - f32::from(a)) * amount.clamp(0.0, 1.0)).round() as u8 + }; + Color32::from_rgb( + mix(from.r(), to.r()), + mix(from.g(), to.g()), + mix(from.b(), to.b()), + ) +} + +fn profile_tooltip(line: usize, timing: &LineTiming) -> String { + let times = if timing.hits == 1 { + String::new() + } else { + format!(" over {} runs of the line", timing.hits) + }; + let mut text = format!("Line {line}: {}{times}", format_seconds(timing.seconds)); + for (name, seconds, calls) in &timing.operations { + let calls = if *calls == 1 { + String::new() + } else { + format!(" ({calls} calls)") + }; + text += &format!("\n{name}: {}{calls}", format_seconds(*seconds)); + } + text +} diff --git a/src/editor/snippets.rs b/src/editor/snippets.rs new file mode 100644 index 000000000..5adee3a88 --- /dev/null +++ b/src/editor/snippets.rs @@ -0,0 +1,97 @@ +//! Built-in CadQuery code snippets for common modeling operations. + +/// A reusable CadQuery code template that can be inserted into the editor. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Snippet { + pub title: &'static str, + pub description: &'static str, + pub code: &'static str, + pub needs_import: bool, +} + +pub const SNIPPETS: &[Snippet] = &[ + Snippet { + title: "Workplane", + description: "Create a CadQuery Workplane on the XY plane", + code: "result = cq.Workplane(\"XY\")\n", + needs_import: true, + }, + Snippet { + title: "Box", + description: "Create a centered rectangular box on the XY plane", + code: "result = (\n cq.Workplane(\"XY\")\n .box(40, 30, 10)\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Cylinder", + description: "Create a cylinder defined by height and radius", + code: "result = (\n cq.Workplane(\"XY\")\n .cylinder(30, 10)\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Sphere", + description: "Create a sphere centered at the workplane origin", + code: "result = (\n cq.Workplane(\"XY\")\n .sphere(15)\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Fillet & Chamfer", + description: "Round vertical edges with a fillet and bevel the top edges with a chamfer", + code: "result = (\n cq.Workplane(\"XY\")\n .box(40, 30, 15)\n .edges(\"|Z\")\n .fillet(3)\n .faces(\">Z\")\n .edges()\n .chamfer(1)\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Extrude Profile", + description: "Sketch a 2D rectangular profile and extrude it into a 3D solid", + code: "result = (\n cq.Workplane(\"XY\")\n .rect(40, 25)\n .extrude(12)\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Revolve Profile", + description: "Revolve a 2D profile around an axis", + code: "result = (\n cq.Workplane(\"XZ\")\n .moveTo(10, 0)\n .lineTo(20, 0)\n .lineTo(20, 15)\n .lineTo(10, 15)\n .close()\n .revolve(360, (0, 0, 0), (0, 1, 0))\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Loft Sections", + description: "Loft smoothly between two cross-section profiles", + code: "result = (\n cq.Workplane(\"XY\")\n .rect(40, 30)\n .workplane(offset=25)\n .circle(10)\n .loft()\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Sweep Along Path", + description: "Sweep a circular cross-section along a spline path", + code: "path = cq.Workplane(\"XZ\").spline([(0, 0), (15, 20), (40, 25)])\nresult = (\n cq.Workplane(\"XY\")\n .circle(4)\n .sweep(path)\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Select Faces & Edges", + description: "Select a face to cut a pocket and round parallel edges", + code: "result = (\n cq.Workplane(\"XY\")\n .box(40, 30, 10)\n .faces(\">Z\")\n .workplane()\n .rect(20, 15)\n .cutBlind(-4)\n .edges(\"|Z\")\n .fillet(2)\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Holes (Through & Counterbore)", + description: "Create a center through-hole and corner counterbored mounting holes", + code: "result = (\n cq.Workplane(\"XY\")\n .box(50, 40, 10)\n .faces(\">Z\")\n .workplane()\n .hole(12)\n .faces(\">Z\")\n .workplane()\n .rect(36, 26, forConstruction=True)\n .vertices()\n .cboreHole(4.5, 8.0, 3.0)\n)\n\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "Assembly", + description: "Combine multiple parts with locations and colors into a CadQuery Assembly", + code: "base = cq.Workplane(\"XY\").box(40, 40, 8)\npeg = cq.Workplane(\"XY\").cylinder(20, 6)\n\nassembly = cq.Assembly()\nassembly.add(base, name=\"base\", color=cq.Color(\"steelblue\"))\nassembly.add(\n peg,\n name=\"peg\",\n loc=cq.Location((0, 0, 14)),\n color=cq.Color(\"orange\"),\n)\n\nshow_object(assembly, name=\"assembly\")\n", + needs_import: true, + }, + Snippet { + title: "Sketch (2D)", + description: "Construct a 2D Sketch with filleted vertices and a subtracted circle", + code: "sketch = (\n cq.Sketch()\n .rect(40, 25)\n .vertices()\n .fillet(4)\n .circle(6, mode=\"s\")\n)\n\nresult = cq.Workplane(\"XY\").placeSketch(sketch).extrude(8)\nshow_object(result)\n", + needs_import: true, + }, + Snippet { + title: "show_object()", + description: "Display a CadQuery object in the 3D view with custom name and color options", + code: "show_object(result, name=\"result\", options={\"color\": (65, 130, 200), \"alpha\": 1.0})\n", + needs_import: false, + }, +]; diff --git a/src/editor/text_ops.rs b/src/editor/text_ops.rs new file mode 100644 index 000000000..6c10c413f --- /dev/null +++ b/src/editor/text_ops.rs @@ -0,0 +1,676 @@ +//! Pure text operations behind the editor commands. +//! +//! Positions are byte offsets into the text. A selection is an +//! `(anchor, cursor)` pair; both are remapped through every edit so the +//! selection keeps covering the same text afterwards. + +use std::ops::Range; + +pub const INDENT: &str = " "; +const INDENT_WIDTH: usize = 4; + +/// Statements after which the next line is usually dedented. +const DEDENT_KEYWORDS: &[&str] = &["return", "pass", "break", "continue", "raise"]; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Selection { + pub anchor: usize, + pub cursor: usize, +} + +impl Selection { + pub fn caret(at: usize) -> Self { + Self { + anchor: at, + cursor: at, + } + } + + pub fn range(&self) -> Range { + self.anchor.min(self.cursor)..self.anchor.max(self.cursor) + } +} + +/// The result of an edit: the new text and the remapped selection. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Edited { + pub text: String, + pub selection: Selection, +} + +pub fn char_to_byte(text: &str, char_index: usize) -> usize { + text.char_indices() + .nth(char_index) + .map_or(text.len(), |(i, _)| i) +} + +pub fn byte_to_char(text: &str, byte_index: usize) -> usize { + text[..byte_index.min(text.len())].chars().count() +} + +/// 0-based line containing `byte`. +pub fn line_of(text: &str, byte: usize) -> usize { + text.as_bytes()[..byte.min(text.len())] + .iter() + .filter(|&&b| b == b'\n') + .count() +} + +/// Byte offset where 0-based `line` starts (the end of the text past the last line). +pub fn line_start(text: &str, line: usize) -> usize { + if line == 0 { + return 0; + } + text.match_indices('\n') + .nth(line - 1) + .map_or(text.len(), |(i, _)| i + 1) +} + +/// Byte range of 0-based `line`, without its line break. +pub fn line_range(text: &str, line: usize) -> Range { + let start = line_start(text, line); + let end = text[start..].find('\n').map_or(text.len(), |i| start + i); + start..end +} + +/// 0-based line and character column of `byte`. +pub fn line_column(text: &str, byte: usize) -> (usize, usize) { + let line = line_of(text, byte); + let start = line_start(text, line); + (line, text[start..byte.min(text.len())].chars().count()) +} + +/// Follows 1-based line numbers (breakpoints, the error line) through an +/// edit, so they stay on their statements when lines are added or removed. +/// +/// The edit is taken as one block of replaced lines between the lines both +/// texts share at the start and at the end, which is what typing, pasting, +/// the editor commands and reloads produce. Lines before the block keep +/// their number, lines after it shift, and lines inside it map by position +/// within the block; a block deleted entirely takes its lines with it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum BlockMove { + None, + /// The first line of the replaced block moved to its end (the other lines moved up by 1). + FirstToLast, + /// The last line of the replaced block moved to its start (the other lines moved down by 1). + LastToFirst, +} + +pub struct LineMap { + /// Unchanged leading lines. + prefix: usize, + /// Length of the replaced block in the old text, in lines. + old_count: usize, + /// Length of the block that replaced it, in lines. + new_count: usize, + /// Whether the replaced block is a one-line rotation (Move Line Up / Down). + moved: BlockMove, +} + +impl LineMap { + pub fn new(old: &str, new: &str) -> Self { + let old_lines: Vec<&str> = old.split('\n').collect(); + let new_lines: Vec<&str> = new.split('\n').collect(); + let prefix = old_lines + .iter() + .zip(&new_lines) + .take_while(|(a, b)| a == b) + .count(); + let room = old_lines.len().min(new_lines.len()) - prefix; + let suffix = old_lines + .iter() + .rev() + .zip(new_lines.iter().rev()) + .take(room) + .take_while(|(a, b)| a == b) + .count(); + let old_count = old_lines.len() - prefix - suffix; + let new_count = new_lines.len() - prefix - suffix; + let old_block = &old_lines[prefix..prefix + old_count]; + let new_block = &new_lines[prefix..prefix + new_count]; + let moved = if old_count == new_count && old_count >= 2 { + if old_block[1..] == new_block[..old_count - 1] + && old_block[0] == new_block[old_count - 1] + { + BlockMove::FirstToLast + } else if old_block[..old_count - 1] == new_block[1..] + && old_block[old_count - 1] == new_block[0] + { + BlockMove::LastToFirst + } else { + BlockMove::None + } + } else { + BlockMove::None + }; + Self { + prefix, + old_count, + new_count, + moved, + } + } + + /// Where 1-based `line` of the old text is now; `None` if it was deleted. + pub fn map(&self, line: usize) -> Option { + let index = line.checked_sub(1)?; + if index < self.prefix { + return Some(line); + } + let offset = index - self.prefix; + if offset >= self.old_count { + return Some(line - self.old_count + self.new_count); + } + if self.new_count == 0 { + return None; + } + match self.moved { + BlockMove::FirstToLast => { + let new_offset = if offset == 0 { + self.old_count - 1 + } else { + offset - 1 + }; + return Some(self.prefix + new_offset + 1); + } + BlockMove::LastToFirst => { + let new_offset = if offset + 1 == self.old_count { + 0 + } else { + offset + 1 + }; + return Some(self.prefix + new_offset + 1); + } + BlockMove::None => {} + } + // Merged lines end up on the last line of the new block. + Some(self.prefix + offset.min(self.new_count - 1) + 1) + } +} + +/// Lines touched by a selection. A selection ending at the very start of a +/// line does not include that line. +pub fn selected_lines(text: &str, selection: &Selection) -> Range { + let range = selection.range(); + let first = line_of(text, range.start); + let mut last = line_of(text, range.end); + if last > first && range.end == line_start(text, last) { + last -= 1; + } + first..last + 1 +} + +/// Applies non-overlapping replacements, sorted by position. +fn apply(text: &str, selection: &Selection, edits: &[(Range, String)]) -> Edited { + let mut out = String::with_capacity(text.len() + edits.len() * INDENT_WIDTH); + let mut last = 0; + for (range, replacement) in edits { + out.push_str(&text[last..range.start]); + out.push_str(replacement); + last = range.end; + } + out.push_str(&text[last..]); + + let map = |offset: usize| { + let mut shift: isize = 0; + for (range, replacement) in edits { + if offset >= range.end { + shift += replacement.len() as isize - range.len() as isize; + } else if offset > range.start { + // Inside a removed span: snap to its start. + shift -= (offset - range.start) as isize; + } + } + (offset as isize + shift).max(0) as usize + }; + Edited { + text: out, + selection: Selection { + anchor: map(selection.anchor), + cursor: map(selection.cursor), + }, + } +} + +fn leading_whitespace(line: &str) -> &str { + &line[..line.len() - line.trim_start().len()] +} + +/// Comments the selected lines with `# `, or uncomments them when every +/// non-blank line is already a comment. +pub fn toggle_comment(text: &str, selection: &Selection) -> Edited { + let lines: Vec> = selected_lines(text, selection) + .map(|line| line_range(text, line)) + .filter(|range| !text[range.clone()].trim().is_empty()) + .collect(); + if lines.is_empty() { + return Edited { + text: text.to_owned(), + selection: selection.clone(), + }; + } + + let all_commented = lines + .iter() + .all(|range| text[range.clone()].trim_start().starts_with('#')); + let edits: Vec<(Range, String)> = if all_commented { + lines + .iter() + .map(|range| { + let line = &text[range.clone()]; + let hash = range.start + leading_whitespace(line).len(); + let end = if text[hash + 1..].starts_with(' ') { + hash + 2 + } else { + hash + 1 + }; + (hash..end, String::new()) + }) + .collect() + } else { + let column = lines + .iter() + .map(|range| leading_whitespace(&text[range.clone()]).len()) + .min() + .unwrap_or(0); + lines + .iter() + .map(|range| (range.start + column..range.start + column, "# ".to_owned())) + .collect() + }; + apply(text, selection, &edits) +} + +/// Tab: indents every selected line when the selection spans several lines, +/// otherwise replaces the selection with spaces up to the next tab stop. +pub fn indent(text: &str, selection: &Selection) -> Edited { + let lines = selected_lines(text, selection); + if lines.len() > 1 { + let edits: Vec<_> = lines + .map(|line| line_range(text, line)) + .filter(|range| !range.is_empty()) + .map(|range| (range.start..range.start, INDENT.to_owned())) + .collect(); + return apply(text, selection, &edits); + } + + let range = selection.range(); + let (_, column) = line_column(text, range.start); + let spaces = INDENT_WIDTH - column % INDENT_WIDTH; + let mut edited = apply(text, selection, &[(range.clone(), " ".repeat(spaces))]); + edited.selection = Selection::caret(range.start + spaces); + edited +} + +/// Shift+Tab: removes one level of indentation from the selected lines. +pub fn unindent(text: &str, selection: &Selection) -> Edited { + let edits: Vec<_> = selected_lines(text, selection) + .map(|line| line_range(text, line)) + .filter_map(|range| { + let line = &text[range.clone()]; + let remove = if line.starts_with('\t') { + 1 + } else { + let spaces = line.len() - line.trim_start_matches(' ').len(); + match spaces { + 0 => return None, + n if n % INDENT_WIDTH == 0 => INDENT_WIDTH, + n => n % INDENT_WIDTH, + } + }; + Some((range.start..range.start + remove, String::new())) + }) + .collect(); + apply(text, selection, &edits) +} + +/// Line break plus indentation for Enter at `cursor`: keeps the current +/// indentation, adds a level after a trailing `:` and removes one after +/// `return`, `pass` and similar. +pub fn newline_with_indent(text: &str, cursor: usize) -> String { + let line = line_of(text, cursor); + let before_cursor = &text[line_start(text, line)..cursor]; + let indent = leading_whitespace(before_cursor); + let code = strip_comment(before_cursor).trim_end(); + + let mut new_indent = indent.to_owned(); + if code.ends_with(':') { + new_indent.push_str(INDENT); + } else { + let first_word = code + .trim_start() + .split(|c: char| !c.is_alphanumeric() && c != '_') + .next(); + if first_word.is_some_and(|w| DEDENT_KEYWORDS.contains(&w)) { + let keep = new_indent.len().saturating_sub(INDENT_WIDTH); + new_indent.truncate(keep); + } + } + format!("\n{new_indent}") +} + +/// Replaces every one of the non-overlapping, sorted `ranges` with +/// `replacement` in one edit. +pub fn replace_ranges( + text: &str, + selection: &Selection, + ranges: &[Range], + replacement: &str, +) -> Edited { + let edits: Vec<(Range, String)> = ranges + .iter() + .map(|range| (range.clone(), replacement.to_owned())) + .collect(); + apply(text, selection, &edits) +} + +/// Duplicates the current line or the selected block of lines immediately +/// below, moving the caret or selection onto the duplicated copy. +pub fn duplicate_lines(text: &str, selection: &Selection) -> Edited { + let lines = selected_lines(text, selection); + let block_start = line_start(text, lines.start); + let block_end = line_range(text, lines.end - 1).end; + let block = &text[block_start..block_end]; + let shift = block.len() + 1; + + let mut out = String::with_capacity(text.len() + shift); + out.push_str(&text[..block_end]); + out.push('\n'); + out.push_str(block); + out.push_str(&text[block_end..]); + + Edited { + selection: Selection { + anchor: (selection.anchor + shift).min(out.len()), + cursor: (selection.cursor + shift).min(out.len()), + }, + text: out, + } +} + +/// Moves the current line or selected block of lines one line up, preserving +/// the selection within the moved block. +pub fn move_lines_up(text: &str, selection: &Selection) -> Edited { + let lines = selected_lines(text, selection); + if lines.start == 0 { + return Edited { + text: text.to_owned(), + selection: selection.clone(), + }; + } + let above_range = line_range(text, lines.start - 1); + let block_start = line_start(text, lines.start); + let block_end = line_range(text, lines.end - 1).end; + let delta = above_range.len() + 1; + + let mut out = String::with_capacity(text.len()); + out.push_str(&text[..above_range.start]); + out.push_str(&text[block_start..block_end]); + out.push('\n'); + out.push_str(&text[above_range]); + out.push_str(&text[block_end..]); + + Edited { + selection: Selection { + anchor: selection.anchor.saturating_sub(delta), + cursor: selection.cursor.saturating_sub(delta), + }, + text: out, + } +} + +/// Moves the current line or selected block of lines one line down, preserving +/// the selection within the moved block. +pub fn move_lines_down(text: &str, selection: &Selection) -> Edited { + let lines = selected_lines(text, selection); + let total_lines = text.matches('\n').count() + 1; + if lines.end >= total_lines { + return Edited { + text: text.to_owned(), + selection: selection.clone(), + }; + } + let block_start = line_start(text, lines.start); + let block_end = line_range(text, lines.end - 1).end; + let below_range = line_range(text, lines.end); + let delta = below_range.len() + 1; + + let mut out = String::with_capacity(text.len()); + out.push_str(&text[..block_start]); + out.push_str(&text[below_range.clone()]); + out.push('\n'); + out.push_str(&text[block_start..block_end]); + out.push_str(&text[below_range.end..]); + + Edited { + selection: Selection { + anchor: (selection.anchor + delta).min(out.len()), + cursor: (selection.cursor + delta).min(out.len()), + }, + text: out, + } +} + +/// Inserts a code snippet at `selection`, adapting indentation to the target +/// line and adding `import cadquery as cq` when needed in a fresh script. +pub fn insert_snippet(text: &str, selection: &Selection, code: &str, needs_import: bool) -> Edited { + let range = selection.range(); + let line = line_of(text, range.start); + let line_span = line_range(text, line); + let indent = leading_whitespace(&text[line_span.clone()]); + let prepend_import = needs_import && !text.contains("import cadquery") && indent.is_empty(); + + let body = if prepend_import { + format!("import cadquery as cq\n\n{}", code.trim_end_matches('\n')) + } else { + code.trim_end_matches('\n').to_owned() + }; + + let indent_lines = |first_indented: bool| -> String { + body.split('\n') + .enumerate() + .map(|(index, row)| { + if row.is_empty() || (index == 0 && !first_indented) { + row.to_owned() + } else { + format!("{indent}{row}") + } + }) + .collect::>() + .join("\n") + }; + + let (replace_range, inserted) = + if range.is_empty() && !text[line_span.start..range.start].trim().is_empty() { + ( + line_span.end..line_span.end, + format!("\n{}", indent_lines(true)), + ) + } else { + (range, indent_lines(false)) + }; + + let cursor = replace_range.start + inserted.len(); + let mut out = String::with_capacity(text.len() + inserted.len()); + out.push_str(&text[..replace_range.start]); + out.push_str(&inserted); + out.push_str(&text[replace_range.end..]); + + Edited { + text: out, + selection: Selection::caret(cursor), + } +} + +/// Characters of a Python name. +pub fn is_word_char(c: char) -> bool { + c == '_' || c.is_alphanumeric() +} + +/// Byte range of the name containing the character at `byte`, if that +/// character is part of a name. +pub fn word_at(text: &str, byte: usize) -> Option> { + let c = text.get(byte..)?.chars().next()?; + if !is_word_char(c) { + return None; + } + let start = text[..byte] + .char_indices() + .rev() + .take_while(|(_, c)| is_word_char(*c)) + .last() + .map_or(byte, |(i, _)| i); + let end = text[byte..] + .char_indices() + .find(|(_, c)| !is_word_char(*c)) + .map_or(text.len(), |(i, _)| byte + i); + Some(start..end) +} + +/// The part of a name typed just before `cursor`, when the cursor is at +/// the end of that name. +pub fn name_before(text: &str, cursor: usize) -> &str { + let Some(before) = text.get(..cursor) else { + return ""; + }; + if text[cursor..].chars().next().is_some_and(is_word_char) { + return ""; + } + let start = before + .char_indices() + .rev() + .take_while(|(_, c)| is_word_char(*c)) + .last() + .map_or(cursor, |(i, _)| i); + &text[start..cursor] +} + +/// Parses *Go to line* input: `line` or `line:column`, both 1-based. +/// Returns the 0-based line and the byte offset to jump to, clamped to the +/// text. +pub fn go_to_target(text: &str, input: &str) -> Option<(usize, usize)> { + let (line, column) = match input.trim().split_once(':') { + Some((line, column)) => (line.trim(), Some(column.trim())), + None => (input.trim(), None), + }; + let line: usize = line.parse().ok().filter(|&l| l > 0)?; + let column: usize = match column { + Some(column) => column.parse().ok().filter(|&c| c > 0)?, + None => 1, + }; + let last_line = text.matches('\n').count(); + let line = (line - 1).min(last_line); + let range = line_range(text, line); + let offset = text[range.clone()] + .char_indices() + .nth(column - 1) + .map_or(range.end, |(i, _)| range.start + i); + Some((line, offset)) +} + +/// Where a line of an earlier version of the text is now. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Located { + /// The same line, with the same text. + Unchanged(usize), + /// The same text, on another line. + Moved(usize), + /// Its text was edited; this is where the edits put the line. + Changed(usize), +} + +impl Located { + pub fn line(self) -> usize { + match self { + Self::Unchanged(line) | Self::Moved(line) | Self::Changed(line) => line, + } + } +} + +/// Where 1-based `line` of `old` is in `new`: on the line the edits moved +/// it to if its text is there, else on the nearest line with its text, else +/// where the edits put it. `None` if the line no longer exists. +pub fn locate_line(old: &str, line: usize, new: &str) -> Option { + let content = old.split('\n').nth(line.checked_sub(1)?)?.trim(); + let lines: Vec<&str> = new.split('\n').map(str::trim).collect(); + let mapped = LineMap::new(old, new).map(line); + if let Some(at) = mapped + && lines.get(at - 1) == Some(&content) + { + return Some(if at == line { + Located::Unchanged(at) + } else { + Located::Moved(at) + }); + } + if !content.is_empty() { + let near = mapped.unwrap_or(line) - 1; + let same = lines + .iter() + .enumerate() + .filter(|(_, candidate)| **candidate == content) + .min_by_key(|(index, _)| index.abs_diff(near)); + if let Some((index, _)) = same { + return Some(if index + 1 == line { + Located::Unchanged(line) + } else { + Located::Moved(index + 1) + }); + } + } + mapped.map(Located::Changed) +} + +/// Places breakpoints saved with the text of their lines (1-based line, +/// line text) in `text`: on the same line when its text is unchanged, +/// otherwise on the nearest line with that text, otherwise nowhere. +pub fn relocate_lines(text: &str, saved: &[(usize, String)]) -> std::collections::BTreeSet { + let lines: Vec<&str> = text.split('\n').map(str::trim).collect(); + saved + .iter() + .filter_map(|(line, content)| { + let content = content.trim(); + if content.is_empty() { + return None; + } + let index = line.checked_sub(1)?; + if lines.get(index) == Some(&content) { + return Some(*line); + } + lines + .iter() + .enumerate() + .filter(|(_, candidate)| **candidate == content) + .min_by_key(|(candidate, _)| candidate.abs_diff(index)) + .map(|(candidate, _)| candidate + 1) + }) + .collect() +} + +/// The line without a trailing `#` comment (ignoring `#` inside strings). +fn strip_comment(line: &str) -> &str { + let mut quote: Option = None; + let mut escaped = false; + for (i, c) in line.char_indices() { + match quote { + Some(q) => { + if escaped { + escaped = false; + } else if c == '\\' { + escaped = true; + } else if c == q { + quote = None; + } + } + None if c == '#' => return &line[..i], + None if c == '"' || c == '\'' => quote = Some(c), + None => {} + } + } + line +} + +#[cfg(test)] +#[path = "../../tests/rust/editor/test_text_ops.rs"] +mod tests; diff --git a/src/embedded.rs b/src/embedded.rs new file mode 100644 index 000000000..bdc057525 --- /dev/null +++ b/src/embedded.rs @@ -0,0 +1,113 @@ +//! Files compiled into the binary by `build.rs`: the Python worker package +//! and the example scripts. + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::io; +use std::path::{Path, PathBuf}; + +include!(concat!(env!("OUT_DIR"), "/embedded.rs")); + +/// An example script shown in the File > Examples menu. +pub struct Example { + pub title: String, + pub source: &'static str, +} + +/// The bundled examples, titled after their file names: +/// `03_extruded_profile.py` becomes "Extruded Profile". +pub fn examples() -> Vec { + EXAMPLES + .iter() + .map(|(file_name, source)| Example { + title: example_title(file_name), + source, + }) + .collect() +} + +fn example_title(file_name: &str) -> String { + let stem = file_name.strip_suffix(".py").unwrap_or(file_name); + // Drop the "NN_" ordering prefix. + let stem = match stem.split_once('_') { + Some((number, rest)) if number.chars().all(|c| c.is_ascii_digit()) => rest, + _ => stem, + }; + stem.split('_') + .filter(|word| !word.is_empty()) + .map(|word| { + let mut chars = word.chars(); + chars.next().map_or_else(String::new, |first| { + first.to_uppercase().chain(chars).collect() + }) + }) + .collect::>() + .join(" ") +} + +/// Directory that contains the `cq_worker` package, ready to be put on +/// `PYTHONPATH`. +/// +/// `CQ_EDITOR_WORKER_DIR` overrides it, and debug builds use the source tree +/// directly so worker edits apply without rebuilding. Otherwise the embedded +/// copy is extracted into `cache_dir`, in a folder named after its content +/// hash so that different versions never mix. +pub fn worker_dir(cache_dir: &Path) -> io::Result { + if let Some(dir) = std::env::var_os("CQ_EDITOR_WORKER_DIR") { + return Ok(PathBuf::from(dir)); + } + + let source_tree = Path::new(env!("CARGO_MANIFEST_DIR")).join("worker"); + if cfg!(debug_assertions) && source_tree.join("cq_worker").is_dir() { + return Ok(source_tree); + } + extract(cache_dir, WORKER_FILES) +} + +/// Writes `files` into a `worker-` folder of `cache_dir`, unless an +/// earlier start already did, and then removes the folders of other worker +/// versions. +fn extract(cache_dir: &Path, files: &[(&str, &str)]) -> io::Result { + let mut hasher = DefaultHasher::new(); + files.hash(&mut hasher); + let dir = cache_dir.join(format!("worker-{:016x}", hasher.finish())); + let marker = dir.join(".complete"); + if !marker.exists() { + for (relative, contents) in files { + let path = dir.join(relative); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(path, contents)?; + } + std::fs::write(marker, b"")?; + remove_other_versions(cache_dir, &dir); + } + Ok(dir) +} + +/// Every version used to leave its folder behind. A still running instance +/// of another version loses nothing: its worker has imported all its +/// modules, and a restart extracts them again. +fn remove_other_versions(cache_dir: &Path, keep: &Path) { + let Ok(entries) = std::fs::read_dir(cache_dir) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + let is_worker = entry + .file_name() + .to_str() + .is_some_and(|name| name.starts_with("worker-")); + if is_worker + && path != keep + && entry.file_type().is_ok_and(|kind| kind.is_dir()) + && let Err(error) = std::fs::remove_dir_all(&path) + { + log::warn!("Cannot remove the old worker {}: {error}", path.display()); + } + } +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_embedded.rs"] +mod tests; diff --git a/src/environments.rs b/src/environments.rs new file mode 100644 index 000000000..9985d544c --- /dev/null +++ b/src/environments.rs @@ -0,0 +1,252 @@ +//! Creating Python environments and installing packages into them, from the +//! preferences (FEAT-E3). +//! +//! A [`Job`] runs a few commands (`python -m venv`, `python -m pip install`) +//! one after the other on a thread of its own, collecting their output line +//! by line for the dialog, and can be cancelled. Commands are started +//! directly, never through a shell, and package names are checked first. + +use std::ffi::OsString; +use std::io::{BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; +use std::thread; + +use crate::worker::launch::venv_python; + +/// What a new environment gets: CadQuery, and jedi for completion. +pub const DEFAULT_PACKAGES: &str = "cadquery jedi"; +/// Output kept for the dialog; older lines are dropped. +const MAX_OUTPUT_LINES: usize = 5_000; + +/// One command of a job. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Step { + /// Shown in the output before the command's own lines. + pub title: String, + pub program: PathBuf, + pub args: Vec, +} + +/// The packages typed by the user, as `pip install` arguments: names with +/// optional extras, versions or markers (`cadquery`, `ocp-vscode>=2`, +/// `trimesh[easy]`), or local wheels. Options are refused, so a typed +/// `--index-url` cannot point pip elsewhere. +pub fn parse_packages(text: &str) -> Result, String> { + let packages: Vec = text + .split(|c: char| c.is_whitespace() || c == ',') + .filter(|word| !word.is_empty()) + .map(str::to_owned) + .collect(); + if packages.is_empty() { + return Err("Name at least one package".to_owned()); + } + for package in &packages { + if package.starts_with('-') { + return Err(format!( + "\"{package}\" is an option; only package names are accepted" + )); + } + let allowed = |c: char| c.is_alphanumeric() || "-_.[]<>=!~*:/\\+@".contains(c); + if let Some(bad) = package.chars().find(|&c| !allowed(c)) { + return Err(format!("\"{package}\" contains \"{bad}\"")); + } + } + Ok(packages) +} + +/// Creates a virtual environment in `folder` with `base`, then installs +/// `packages` into it. +pub fn create_steps(base: &Path, folder: &Path, packages: &[String]) -> Vec { + let mut steps = vec![Step { + title: format!("Creating the environment in {}", folder.display()), + program: base.to_path_buf(), + args: vec!["-m".into(), "venv".into(), folder.into()], + }]; + steps.extend(install_steps(&venv_python(folder), packages)); + steps +} + +/// Installs `packages` into the environment of `python`. +pub fn install_steps(python: &Path, packages: &[String]) -> Vec { + let mut args: Vec = ["-m", "pip", "install"].map(OsString::from).to_vec(); + args.extend(packages.iter().map(OsString::from)); + vec![Step { + title: format!("Installing {}", packages.join(" ")), + program: python.to_path_buf(), + args, + }] +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum JobState { + Running, + Succeeded, + Failed(String), + Cancelled, +} + +enum Event { + Line(String), + Finished(JobState), +} + +/// Commands running one after the other in the background. +pub struct Job { + output: Vec, + state: JobState, + events: mpsc::Receiver, + cancelled: Arc, + child: Arc>>, +} + +impl Job { + pub fn start(steps: Vec) -> Self { + let (sender, events) = mpsc::channel(); + let cancelled = Arc::new(AtomicBool::new(false)); + let child = Arc::new(Mutex::new(None)); + let (flag, slot) = (cancelled.clone(), child.clone()); + thread::Builder::new() + .name("environment-job".into()) + .spawn(move || { + let state = run_steps(&steps, &sender, &flag, &slot); + let _ = sender.send(Event::Finished(state)); + }) + .expect("a thread for the job"); + Self { + output: Vec::new(), + state: JobState::Running, + events, + cancelled, + child, + } + } + + /// Takes in what the commands printed since the last call. + pub fn poll(&mut self) -> &JobState { + while let Ok(event) = self.events.try_recv() { + match event { + Event::Line(line) => { + self.output.push(line); + if self.output.len() > MAX_OUTPUT_LINES { + self.output.drain(..self.output.len() - MAX_OUTPUT_LINES); + } + } + Event::Finished(state) => self.state = state, + } + } + &self.state + } + + pub fn state(&self) -> &JobState { + &self.state + } + + pub fn output(&self) -> &[String] { + &self.output + } + + /// Stops the command running now and skips the others. + pub fn cancel(&self) { + self.cancelled.store(true, Ordering::SeqCst); + if let Some(child) = self.child.lock().expect("child slot").as_mut() { + let _ = child.kill(); + } + } +} + +impl Drop for Job { + fn drop(&mut self) { + if self.state == JobState::Running { + self.cancel(); + } + } +} + +fn run_steps( + steps: &[Step], + sender: &mpsc::Sender, + cancelled: &AtomicBool, + slot: &Mutex>, +) -> JobState { + for step in steps { + if cancelled.load(Ordering::SeqCst) { + return JobState::Cancelled; + } + let _ = sender.send(Event::Line(format!("▶ {}", step.title))); + let mut command = Command::new(&step.program); + command + .args(&step.args) + .env("PIP_DISABLE_PIP_VERSION_CHECK", "1") + .env("PYTHONIOENCODING", "utf-8") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt as _; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + let mut child = match command.spawn() { + Ok(child) => child, + Err(error) => { + return JobState::Failed(format!( + "Cannot start {}: {error}", + step.program.display() + )); + } + }; + let stdout = child.stdout.take().expect("piped stdout"); + let stderr = child.stderr.take().expect("piped stderr"); + *slot.lock().expect("child slot") = Some(child); + // A cancel between the check above and storing the child. + if cancelled.load(Ordering::SeqCst) + && let Some(child) = slot.lock().expect("child slot").as_mut() + { + let _ = child.kill(); + } + let errors = { + let sender = sender.clone(); + thread::spawn(move || forward_lines(stderr, &sender)) + }; + forward_lines(stdout, sender); + let _ = errors.join(); + let status = slot + .lock() + .expect("child slot") + .take() + .map(|mut child| child.wait()); + if cancelled.load(Ordering::SeqCst) { + return JobState::Cancelled; + } + match status { + Some(Ok(status)) if status.success() => {} + Some(Ok(status)) => { + let code = status + .code() + .map_or_else(|| "a signal".to_owned(), |code| format!("code {code}")); + return JobState::Failed(format!("{} failed (exit {code})", step.title)); + } + Some(Err(error)) => return JobState::Failed(error.to_string()), + None => return JobState::Cancelled, + } + } + JobState::Succeeded +} + +fn forward_lines(stream: impl Read, sender: &mpsc::Sender) { + let mut reader = BufReader::new(stream); + let mut line = Vec::new(); + while matches!(reader.read_until(b'\n', &mut line), Ok(read) if read > 0) { + let text = String::from_utf8_lossy(&line); + let _ = sender.send(Event::Line(text.trim_end().to_owned())); + line.clear(); + } +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_environments.rs"] +mod tests; diff --git a/src/file_watcher.rs b/src/file_watcher.rs new file mode 100644 index 000000000..857df81e6 --- /dev/null +++ b/src/file_watcher.rs @@ -0,0 +1,115 @@ +//! Detects changes to the open script (and optionally its local imports) +//! for "Automatic reload and preview". +//! +//! Polling modification times is simple, dependency free and copes with +//! editors that save by deleting and recreating the file (vim, neovim): +//! a missing file is simply waited for. + +use std::path::PathBuf; +use std::time::{Duration, Instant, SystemTime}; + +const POLL_INTERVAL: Duration = Duration::from_millis(250); + +#[derive(Clone, Copy, PartialEq, Eq)] +struct Stamp { + modified: Option, + len: u64, +} + +fn stamp(path: &PathBuf) -> Option { + let metadata = std::fs::metadata(path).ok()?; + Some(Stamp { + modified: metadata.modified().ok(), + len: metadata.len(), + }) +} + +#[derive(Default)] +pub struct FileWatcher { + files: Vec<(PathBuf, Option)>, + last_poll: Option, + /// When a change was first seen; reported once the settle delay passed. + changed_at: Option, + pending: Vec, +} + +impl FileWatcher { + pub fn is_watching(&self) -> bool { + !self.files.is_empty() + } + + #[cfg(test)] + pub fn watched(&self) -> impl Iterator { + self.files.iter().map(|(path, _)| path) + } + + /// Replaces the watched files, keeping known stamps. + pub fn set_files(&mut self, paths: Vec) { + let previous = std::mem::take(&mut self.files); + self.files = paths + .into_iter() + .map(|path| { + let known = previous + .iter() + .find(|(p, _)| *p == path) + .and_then(|(_, s)| *s); + let current = known.or_else(|| stamp(&path)); + (path, current) + }) + .collect(); + self.pending + .retain(|changed| self.files.iter().any(|(path, _)| path == changed)); + if self.pending.is_empty() { + self.changed_at = None; + } + } + + pub fn clear(&mut self) { + self.files.clear(); + self.changed_at = None; + self.pending.clear(); + } + + /// Returns the paths whose changes have settled for `delay` (so the + /// writer has finished). Call every frame; ask for a repaint after + /// [`FileWatcher::next_poll_in`] to keep polling while idle. + pub fn poll(&mut self, delay: Duration) -> Vec { + let now = Instant::now(); + if self.files.is_empty() { + return Vec::new(); + } + if self + .last_poll + .is_none_or(|last| now - last >= POLL_INTERVAL) + { + self.last_poll = Some(now); + for (path, known) in &mut self.files { + // A file that vanished is probably being replaced. + if let Some(current) = stamp(path) + && *known != Some(current) + { + *known = Some(current); + if !self.pending.contains(path) { + self.pending.push(path.clone()); + } + self.changed_at.get_or_insert(now); + } + } + } + match self.changed_at { + Some(at) if now - at >= delay => { + self.changed_at = None; + std::mem::take(&mut self.pending) + } + _ => Vec::new(), + } + } + + pub fn next_poll_in(&self) -> Duration { + POLL_INTERVAL + } +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_file_watcher.rs"] +mod tests; diff --git a/src/headless.rs b/src/headless.rs new file mode 100644 index 000000000..f7ee86410 --- /dev/null +++ b/src/headless.rs @@ -0,0 +1,95 @@ +//! Terminal commands executed by the bundled Python worker without egui. + +use std::process::Command; + +use crate::{APP_ID, embedded, worker}; + +struct Invocation { + python: Option, + arguments: Vec, +} + +/// Run a headless command if present; leave ordinary file/open arguments to +/// the GUI parser. +pub fn run(args: &[String]) -> Option { + let Invocation { python, arguments } = match invocation(args) { + Ok(Some(invocation)) => invocation, + Ok(None) => return None, + Err(message) => { + eprintln!("{message}"); + return Some(2); + } + }; + + let python = worker::launch::find_python(python.as_deref()); + let cache = eframe::storage_dir(APP_ID).unwrap_or_else(|| std::env::temp_dir().join(APP_ID)); + let worker_dir = match embedded::worker_dir(&cache) { + Ok(path) => path, + Err(error) => { + eprintln!("Cannot prepare Python worker: {error}"); + return Some(1); + } + }; + let mut python_paths = vec![worker_dir]; + if let Some(existing) = std::env::var_os("PYTHONPATH") { + python_paths.extend(std::env::split_paths(&existing)); + } + let python_path = match std::env::join_paths(python_paths) { + Ok(path) => path, + Err(error) => { + eprintln!("Cannot set PYTHONPATH: {error}"); + return Some(1); + } + }; + // Release builds use the Windows GUI subsystem. Attach the shell before + // launching Python so its inherited stdout/stderr reach the terminal. + #[cfg(all(windows, not(debug_assertions)))] + unsafe { + use windows_sys::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole}; + AttachConsole(ATTACH_PARENT_PROCESS); + } + let status = Command::new(&python) + .arg("-m") + .arg("cq_worker.cli") + .args(arguments) + .env("PYTHONPATH", python_path) + .env("PYTHONIOENCODING", "utf-8") + .status(); + Some(match status { + Ok(status) => status.code().unwrap_or(1), + Err(error) => { + eprintln!("Cannot start {}: {error}", python.display()); + 1 + } + }) +} + +fn invocation(args: &[String]) -> Result, String> { + let mut python = None; + let mut forwarded = Vec::new(); + let mut index = 0; + while index < args.len() { + if args[index] == "--python" { + python = Some(args.get(index + 1).ok_or("--python needs a path")?.clone()); + index += 2; + } else { + forwarded.push(args[index].clone()); + index += 1; + } + } + if matches!( + forwarded.first().map(String::as_str), + Some("build" | "check") + ) { + Ok(Some(Invocation { + python, + arguments: forwarded, + })) + } else { + Ok(None) + } +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_headless.rs"] +mod tests; diff --git a/src/logging.rs b/src/logging.rs new file mode 100644 index 000000000..6dd1fa820 --- /dev/null +++ b/src/logging.rs @@ -0,0 +1,308 @@ +//! Application-wide log shown by the Log panel. +//! +//! Records from the `log` crate, the worker's stderr, Python logging and +//! script `print`/`log()` output all land in one bounded buffer. Multi-line +//! messages are split into one entry per line so the panel can use fixed-height +//! rows. +//! +//! Every entry is also appended to a log file in the data folder (see +//! [`init_file`]), together with GUI panics, so the messages explaining a +//! crash survive it. The file is rotated at [`MAX_FILE_BYTES`]. + +use std::collections::VecDeque; +use std::fs::File; +use std::io::{BufWriter, Write as _}; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, MutexGuard, OnceLock, TryLockError}; +use std::time::{Duration, Instant}; + +/// Oldest entries are dropped beyond this many lines. +const MAX_ENTRIES: usize = 10_000; +/// The log file is renamed to [`PREVIOUS_LOG_FILE`] beyond this size. +pub const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024; +pub const LOG_FILE: &str = "cq-editor.log"; +pub const PREVIOUS_LOG_FILE: &str = "cq-editor.1.log"; +/// Buffered informational lines reach the file at least this often; +/// warnings and errors are written at once. +const FLUSH_INTERVAL: Duration = Duration::from_secs(1); + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Level { + Error, + Warn, + Info, + Debug, +} + +impl Level { + pub fn label(self) -> &'static str { + match self { + Level::Error => "ERROR", + Level::Warn => "WARN", + Level::Info => "INFO", + Level::Debug => "DEBUG", + } + } + + /// Maps Python logging level names. + pub fn from_python(name: &str) -> Self { + match name { + "critical" | "error" => Level::Error, + "warning" => Level::Warn, + "debug" => Level::Debug, + _ => Level::Info, + } + } +} + +#[derive(Clone, Debug)] +pub struct Entry { + pub time: String, + pub level: Level, + pub source: String, + pub text: String, +} + +#[derive(Default)] +struct Store { + entries: VecDeque, + /// Increments on every change so views can cheaply detect updates. + revision: u64, + file: Option, +} + +/// The rotating log file. +struct LogFile { + directory: PathBuf, + writer: BufWriter, + /// Bytes in the current file. + size: u64, + flushed_at: Instant, +} + +impl LogFile { + fn open(directory: &Path) -> std::io::Result { + std::fs::create_dir_all(directory)?; + let file = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(directory.join(LOG_FILE))?; + let size = file.metadata()?.len(); + Ok(Self { + directory: directory.to_path_buf(), + writer: BufWriter::new(file), + size, + flushed_at: Instant::now(), + }) + } + + fn write_line(&mut self, line: &str, urgent: bool) { + if self.size >= MAX_FILE_BYTES + && let Err(error) = self.rotate() + { + eprintln!("Cannot rotate the log file: {error}"); + } + if self.writer.write_all(line.as_bytes()).is_ok() { + self.size += line.len() as u64; + } + if urgent || self.flushed_at.elapsed() >= FLUSH_INTERVAL { + self.flush(); + } + } + + fn flush(&mut self) { + let _ = self.writer.flush(); + self.flushed_at = Instant::now(); + } + + /// Keeps one previous file, which the current one replaces. + fn rotate(&mut self) -> std::io::Result<()> { + self.flush(); + let directory = self.directory.clone(); + // Windows cannot rename a file that is open, so close it first. + let placeholder = BufWriter::new(tempfile::tempfile()?); + drop(std::mem::replace(&mut self.writer, placeholder)); + let renamed = std::fs::rename(directory.join(LOG_FILE), directory.join(PREVIOUS_LOG_FILE)); + *self = Self::open(&directory)?; + renamed + } +} + +fn store() -> &'static Mutex { + static STORE: OnceLock> = OnceLock::new(); + STORE.get_or_init(Mutex::default) +} + +fn lock() -> MutexGuard<'static, Store> { + store().lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Starts writing the log to [`LOG_FILE`] in `directory` and records GUI +/// panics there. Returns the file's path. +pub fn init_file(directory: &Path) -> std::io::Result { + let mut file = LogFile::open(directory)?; + let started = chrono::Local::now().format("%Y-%m-%d %H:%M:%S"); + file.write_line( + &format!( + "--- CQ-editor {} started {started} ---\n", + env!("CARGO_PKG_VERSION") + ), + true, + ); + lock().file = Some(file); + // Buffered lines reach the file within FLUSH_INTERVAL even when nothing + // else is logged after them. + let flusher = std::thread::Builder::new() + .name("log-flush".into()) + .spawn(|| { + loop { + std::thread::sleep(FLUSH_INTERVAL); + flush(); + } + }); + if let Err(error) = flusher { + eprintln!("Cannot start flushing the log file: {error}"); + } + + let previous_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + record_panic(&format!( + "{info}\n{}", + std::backtrace::Backtrace::force_capture() + )); + previous_hook(info); + })); + Ok(directory.join(LOG_FILE)) +} + +/// Writes buffered lines to the log file. +pub fn flush() { + if let Some(file) = &mut lock().file { + file.flush(); + } +} + +/// Writes a panic report without waiting for the lock: the panic may have +/// happened while this thread held it. +fn record_panic(report: &str) { + let mut store = match store().try_lock() { + Ok(store) => store, + Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), + Err(TryLockError::WouldBlock) => return, + }; + if let Some(file) = &mut store.file { + let time = chrono::Local::now().format("%Y-%m-%d %H:%M:%S"); + for line in report.lines() { + file.write_line(&format!("{time} ERROR panic: {line}\n"), false); + } + file.flush(); + } +} + +/// Appends a message, stripping terminal escape sequences. +pub fn push(level: Level, source: &str, message: &str) { + let now = chrono::Local::now(); + let time = now.format("%H:%M:%S").to_string(); + let message = strip_ansi(message); + let mut store = lock(); + for line in message.trim_end_matches('\n').split('\n') { + let text = line.trim_end_matches('\r'); + if let Some(file) = &mut store.file { + let line = format!( + "{} {} {source}: {text}\n", + now.format("%Y-%m-%d %H:%M:%S"), + level.label() + ); + file.write_line(&line, level <= Level::Warn); + } + store.entries.push_back(Entry { + time: time.clone(), + level, + source: source.to_owned(), + text: text.to_owned(), + }); + } + while store.entries.len() > MAX_ENTRIES { + store.entries.pop_front(); + } + store.revision += 1; +} + +/// Clears the Log panel; the log file keeps everything. +pub fn clear() { + let mut store = lock(); + store.entries.clear(); + store.revision += 1; +} + +pub fn revision() -> u64 { + lock().revision +} + +/// Calls `f` with the current entries, oldest first. +pub fn with_entries(f: impl FnOnce(&VecDeque) -> R) -> R { + f(&lock().entries) +} + +/// Removes ANSI escape sequences such as color codes (`ESC [ ... letter`). +pub fn strip_ansi(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\x1b' && chars.peek() == Some(&'[') { + chars.next(); + // Parameter and intermediate bytes, then one final byte in @..~. + for c in chars.by_ref() { + if ('@'..='~').contains(&c) { + break; + } + } + } else { + out.push(c); + } + } + out +} + +struct Logger; + +impl log::Log for Logger { + fn enabled(&self, metadata: &log::Metadata) -> bool { + // Our own records down to debug; libraries (wgpu, winit) only when + // something is wrong. + metadata.target().starts_with("cq_editor") || metadata.level() <= log::Level::Warn + } + + fn log(&self, record: &log::Record) { + if !self.enabled(record.metadata()) { + return; + } + let level = match record.level() { + log::Level::Error => Level::Error, + log::Level::Warn => Level::Warn, + log::Level::Info => Level::Info, + log::Level::Debug | log::Level::Trace => Level::Debug, + }; + let message = record.args().to_string(); + eprintln!("[{}] {}: {message}", level.label(), record.target()); + // The Vulkan loader reports every stale layer registered on the + // system (e.g. of uninstalled overlays); that is noise for users. + let loader_noise = record.target().starts_with("wgpu_hal::vulkan::instance"); + if level != Level::Debug && !loader_noise { + push(level, "app", &message); + } + } + + fn flush(&self) {} +} + +pub fn init() { + static LOGGER: Logger = Logger; + if log::set_logger(&LOGGER).is_ok() { + log::set_max_level(log::LevelFilter::Debug); + } +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_logging.rs"] +mod tests; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 000000000..5d3316f77 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,196 @@ +//! CQ-editor: a CadQuery script editor and 3D viewer. +//! +//! The interface is written in Rust (egui + wgpu); CadQuery itself runs in a +//! Python worker process (`worker/cq_worker`). + +// No console window for release builds on Windows. +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] + +mod app; +mod commands; +mod dialogs; +mod document; +mod editor; +mod embedded; +mod environments; +mod file_watcher; +mod headless; +mod logging; +mod panels; +mod parameters; +mod project; +mod recovery; +mod scene; +mod settings; +mod spatial; +mod theme; +mod ui; +mod updates; +mod viewer; +mod worker; + +use std::path::PathBuf; + +use app::{CqEditorApp, StartupOptions}; + +const USAGE: &str = "Usage: cq-editor [--python PATH] [FILE] + cq-editor [--python PATH] build FILE --export OUTPUT [--set NAME=VALUE]... [--unit UNIT] [--json] + cq-editor [--python PATH] check FILE [--set NAME=VALUE]... [--json] + + FILE CadQuery script to open + --python PATH Python interpreter with CadQuery (overrides the preferences)"; + +/// Name of the data folder (settings, recovery, logs) and of the app. +pub const APP_ID: &str = "cq-editor"; + +fn main() -> eframe::Result { + logging::init(); + + let args: Vec<_> = std::env::args().skip(1).collect(); + if let Some(status) = headless::run(&args) { + std::process::exit(status); + } + + let options = match parse_args(args.into_iter()) { + Ok(options) => options, + Err(message) => { + show_cli_message(&format!("{message}\n\n{USAGE}"), true); + std::process::exit(2); + } + }; + + if let Some(data) = eframe::storage_dir(APP_ID) { + match logging::init_file(&data.join("logs")) { + Ok(path) => log::debug!("Writing the log to {}", path.display()), + Err(error) => log::warn!("Cannot write a log file: {error}"), + } + } + + let native_options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_title("CQ-editor") + .with_app_id("cq-editor") + .with_inner_size([1280.0, 780.0]) + .with_min_inner_size([760.0, 480.0]) + .with_icon(window_icon()), + persist_window: true, + centered: true, + ..Default::default() + }; + + let result = eframe::run_native( + APP_ID, + native_options, + Box::new(move |cc| Ok(Box::new(CqEditorApp::new(cc, options)))), + ); + logging::flush(); + result +} + +/// Shows command-line output: usage and argument errors. +fn show_cli_message(message: &str, is_error: bool) { + #[cfg(all(windows, not(debug_assertions)))] + if windows_console::show(message, is_error) { + return; + } + if is_error { + eprintln!("{message}"); + } else { + println!("{message}"); + } +} + +/// Release builds on Windows are GUI programs without a console of their +/// own, so standard output goes nowhere unless a shell redirected it. +#[cfg(all(windows, not(debug_assertions)))] +mod windows_console { + use std::io::Write as _; + + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::System::Console::{ + ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_ERROR_HANDLE, STD_OUTPUT_HANDLE, + }; + + /// Writes `message` to the console of the shell that started the + /// program, or shows it in a message box when there is none (for + /// example when started from Explorer). Returns `false` when standard + /// output is redirected, so plain printing works. + pub fn show(message: &str, is_error: bool) -> bool { + let stream = if is_error { + STD_ERROR_HANDLE + } else { + STD_OUTPUT_HANDLE + }; + // SAFETY: plain Win32 calls without pointer arguments. + let handle = unsafe { GetStdHandle(stream) }; + if !handle.is_null() && handle != INVALID_HANDLE_VALUE { + return false; + } + // SAFETY: as above. + if unsafe { AttachConsole(ATTACH_PARENT_PROCESS) } != 0 + && let Ok(mut console) = std::fs::OpenOptions::new().write(true).open("CONOUT$") + { + // The shell has already printed its next prompt. + let text = message.replace('\n', "\r\n"); + let _ = write!(console, "\r\n{text}\r\n"); + return true; + } + rfd::MessageDialog::new() + .set_title("CQ-editor") + .set_description(message) + .set_level(if is_error { + rfd::MessageLevel::Error + } else { + rfd::MessageLevel::Info + }) + .show(); + true + } +} + +fn parse_args(args: impl Iterator) -> Result { + let mut options = StartupOptions::default(); + let mut args = args.peekable(); + while let Some(arg) = args.next() { + match arg.as_str() { + "-h" | "--help" => { + show_cli_message(USAGE, false); + std::process::exit(0); + } + "--python" => { + options.python = Some(args.next().ok_or("--python needs a path")?); + } + flag if flag.starts_with('-') => return Err(format!("Unknown option {flag}")), + file if options.file.is_none() => options.file = Some(PathBuf::from(file)), + extra => return Err(format!("Unexpected argument {extra}")), + } + } + Ok(options) +} + +fn window_icon() -> egui::IconData { + match image::load_from_memory_with_format(app::LOGO_ICO, image::ImageFormat::Ico) { + Ok(image) => { + let image = image + .resize(128, 128, image::imageops::FilterType::Lanczos3) + .to_rgba8(); + egui::IconData { + width: image.width(), + height: image.height(), + rgba: image.into_raw(), + } + } + Err(err) => { + log::warn!("Cannot decode the application icon: {err}"); + egui::IconData::default() + } + } +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_cli.rs"] +mod tests; + +#[cfg(test)] +#[path = "../tests/rust/app/test_compatibility.rs"] +mod compatibility_tests; diff --git a/src/panels/checks.rs b/src/panels/checks.rs new file mode 100644 index 000000000..a21b31408 --- /dev/null +++ b/src/panels/checks.rs @@ -0,0 +1,59 @@ +//! Requirements declared by expect() in the last script run. + +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + if state.cad_checks.is_empty() { + super::empty_state( + ui, + icon::CHECK_CIRCLE, + "No CAD requirements in the last run", + ); + return; + } + let failed = state.cad_checks.iter().filter(|check| !check.ok).count(); + let total = state.cad_checks.len(); + ui.strong(format!("{} passed · {} failed", total - failed, failed)); + ui.separator(); + let mut actions = Vec::new(); + egui::ScrollArea::vertical().show(ui, |ui| { + for check in &state.cad_checks { + let color = if check.ok { + ui.visuals().strong_text_color() + } else { + ui.visuals().error_fg_color + }; + let symbol = if check.ok { + icon::CHECK_CIRCLE + } else { + icon::X_CIRCLE + }; + let location = check + .line + .map(|line| format!(" · line {line}")) + .unwrap_or_default(); + let label = format!("{symbol} {} · {}{location}", check.name, check.kind); + let response = ui.add( + egui::Label::new(egui::RichText::new(label).color(color)) + .sense(egui::Sense::click()), + ); + ui.indent(response.id, |ui| { + ui.label(&check.detail); + }); + if response.clicked() + && let Some(line) = check.line + { + if let Some(document) = state.cad_checks_document { + actions.push(Action::GoToScriptLine { document, line }); + } else { + actions.push(Action::GoToLine(line)); + } + } + ui.separator(); + } + }); + state.queue(actions); +} diff --git a/src/panels/console.rs b/src/panels/console.rs new file mode 100644 index 000000000..662d5ef45 --- /dev/null +++ b/src/panels/console.rs @@ -0,0 +1,594 @@ +//! Interactive Python console running in the worker. +//! +//! Its namespace has the script API (`show_object` adds to the view) and the +//! variables of the last run. Enter runs the input, Shift+Enter adds a line, +//! Up/Down browse the history. Results with an image (a matplotlib figure, +//! anything with `_repr_png_`) show it, decoded before it gets here. + +use egui::{Color32, Key, Modifiers, RichText}; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::worker::protocol::{DisplayImage, DisplayOutput}; + +const MAX_ENTRIES: usize = 2000; +/// Images kept; older ones are replaced by a note, to bound memory. +const MAX_IMAGES: usize = 50; +/// Decoded pixels retained on the CPU. Textures use additional GPU memory. +const MAX_IMAGE_MEMORY: usize = 128 * 1024 * 1024; +/// Images are drawn at most this tall, in points. +const MAX_IMAGE_HEIGHT: f32 = 360.0; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum EntryKind { + Input, + Output, + Error, + Info, +} + +pub struct Entry { + pub kind: EntryKind, + pub text: String, + /// A rich result's picture, shown above its text. + pub image: Option, +} + +/// An image in the console; its texture is made when it is first drawn. +pub struct ConsoleImage { + pixels: DisplayImage, + texture: Option, +} + +#[derive(Default)] +pub struct ConsoleState { + pub entries: Vec, + pub input: String, + /// The last statement is incomplete (a block is open). + pub more: bool, + pub busy: bool, + history: Vec, + history_index: Option, + /// In-progress input saved before browsing or searching history. + draft_input: Option, + /// Whether the interactive history search bar (`Ctrl+R`) is open. + pub search_open: bool, + pub search_query: String, + pub search_match_index: usize, + focus_search: bool, + focus_input: bool, +} + +impl ConsoleState { + #[cfg(test)] + pub fn history(&self) -> &[String] { + &self.history + } + + /// Indices into `self.history` (most recent first) matching `query` + /// case-insensitively. + pub fn history_matches(&self, query: &str) -> Vec { + let needle = query.trim().to_lowercase(); + (0..self.history.len()) + .rev() + .filter(|&i| needle.is_empty() || self.history[i].to_lowercase().contains(&needle)) + .collect() + } + + /// Opens the reverse history search bar (`Ctrl+R`), saving the current + /// input so `Esc` can restore it. + pub fn open_history_search(&mut self) { + if !self.search_open { + self.draft_input = Some(self.input.clone()); + } + self.search_open = true; + self.focus_search = true; + self.search_match_index = 0; + if !self.search_query.trim().is_empty() { + self.apply_search_match(); + } + } + + /// Updates the history search query and loads the newest matching command. + pub fn set_history_search_query(&mut self, query: &str) { + if !self.search_open { + self.draft_input = Some(self.input.clone()); + self.search_open = true; + } + self.search_query = query.to_owned(); + self.search_match_index = 0; + if self.search_query.trim().is_empty() { + if let Some(draft) = &self.draft_input { + self.input = draft.clone(); + } + self.history_index = None; + } else { + self.apply_search_match(); + } + } + + /// Cycles to the next older (`true`) or newer (`false`) matching command. + pub fn step_history_search(&mut self, next_older: bool) { + let matches = self.history_matches(&self.search_query); + if matches.is_empty() { + return; + } + if next_older { + self.search_match_index = (self.search_match_index + 1) % matches.len(); + } else { + self.search_match_index = (self.search_match_index + matches.len() - 1) % matches.len(); + } + let hist_idx = matches[self.search_match_index]; + self.history_index = Some(hist_idx); + self.input = self.history[hist_idx].clone(); + } + + /// Accepts the currently matched history command into the input field + /// without executing it. + pub fn accept_history_search(&mut self) { + self.search_open = false; + self.focus_search = false; + self.draft_input = None; + self.focus_input = true; + } + + /// Cancels history search and restores the input that was present before + /// the search started. + pub fn cancel_history_search(&mut self) { + self.search_open = false; + self.focus_search = false; + if let Some(draft) = self.draft_input.take() { + self.input = draft; + } + self.history_index = None; + self.focus_input = true; + } + + fn apply_search_match(&mut self) { + let matches = self.history_matches(&self.search_query); + if let Some(&hist_idx) = matches.get(self.search_match_index) { + self.history_index = Some(hist_idx); + self.input = self.history[hist_idx].clone(); + } + } + /// Applies completion results for the input: a unique match or the + /// common prefix is inserted, otherwise the candidates are listed. + pub fn complete(&mut self, inserts: &[(String, String)], signatures: &[String]) { + if inserts.is_empty() { + if !signatures.is_empty() { + self.push(EntryKind::Info, &(signatures.join("\n") + "\n")); + } + return; + } + let prefix = common_prefix(inserts.iter().map(|(_, insert)| insert.as_str())); + if !prefix.is_empty() { + self.input.push_str(prefix); + } else if inserts.len() > 1 { + let names: Vec<&str> = inserts.iter().map(|(name, _)| name.as_str()).collect(); + self.push(EntryKind::Info, &(names.join(" ") + "\n")); + } + self.focus_input = true; + } + + pub fn push(&mut self, kind: EntryKind, text: &str) { + // Consecutive output chunks are merged into one entry. + if let Some(last) = self.entries.last_mut() + && last.kind == kind + && kind != EntryKind::Input + && last.image.is_none() + && !last.text.ends_with('\n') + { + last.text.push_str(text); + return; + } + self.add(Entry { + kind, + text: text.to_owned(), + image: None, + }); + } + + /// A rich result of a command: its image, if any, then its text. + pub fn push_display(&mut self, output: DisplayOutput) { + let text = if output.text.is_empty() { + String::new() + } else { + output.text + "\n" + }; + match output.image { + Some(pixels) => { + self.add(Entry { + kind: EntryKind::Output, + text, + image: Some(ConsoleImage { + pixels, + texture: None, + }), + }); + self.trim_images(MAX_IMAGES, MAX_IMAGE_MEMORY); + } + None if !text.is_empty() => self.push(EntryKind::Output, &text), + None => {} + } + } + + fn add(&mut self, entry: Entry) { + self.entries.push(entry); + if self.entries.len() > MAX_ENTRIES { + self.entries.drain(..self.entries.len() - MAX_ENTRIES); + } + } + + fn trim_images(&mut self, max_images: usize, max_bytes: usize) { + let mut images = self + .entries + .iter() + .filter(|entry| entry.image.is_some()) + .count(); + let mut bytes: usize = self + .entries + .iter() + .filter_map(|entry| entry.image.as_ref()) + .map(|image| image.pixels.rgba.len()) + .sum(); + for entry in &mut self.entries { + if images <= max_images && bytes <= max_bytes { + break; + } + if let Some(image) = entry.image.take() { + entry.text.insert_str(0, "[image]\n"); + images -= 1; + bytes = bytes.saturating_sub(image.pixels.rgba.len()); + } + } + } + + pub fn clear(&mut self) { + self.entries.clear(); + } + + pub fn record_input(&mut self, source: &str) { + let prompt = if self.more { "... " } else { ">>> " }; + let shown: Vec = source + .lines() + .enumerate() + .map(|(i, line)| format!("{}{line}", if i == 0 { prompt } else { "... " })) + .collect(); + self.push(EntryKind::Input, &(shown.join("\n") + "\n")); + if !source.trim().is_empty() && self.history.last().map(String::as_str) != Some(source) { + self.history.push(source.to_owned()); + } + self.history_index = None; + self.draft_input = None; + self.search_open = false; + self.busy = true; + } + + /// Moves one step through the command history (`older = true` for `Up`, + /// `false` for `Down`), preserving any in-progress draft input. + pub fn step_history(&mut self, older: bool) -> bool { + if self.history.is_empty() || (self.input.contains('\n') && self.history_index.is_none()) { + return false; + } + if older { + if self.history_index.is_none() { + self.draft_input = Some(self.input.clone()); + } + let index = self + .history_index + .map_or(self.history.len() - 1, |i| i.saturating_sub(1)); + self.history_index = Some(index); + self.input = self.history[index].clone(); + true + } else { + match self.history_index { + Some(i) if i + 1 < self.history.len() => { + self.history_index = Some(i + 1); + self.input = self.history[i + 1].clone(); + true + } + Some(_) => { + self.history_index = None; + self.input = self.draft_input.take().unwrap_or_default(); + true + } + None => false, + } + } + } +} + +fn common_prefix<'a>(mut words: impl Iterator) -> &'a str { + let Some(first) = words.next() else { return "" }; + let mut length = first.len(); + for word in words { + length = first + .char_indices() + .zip(word.chars()) + .take_while(|((_, a), b)| a == b) + .last() + .map_or(0, |((i, c), _)| i + c.len_utf8()) + .min(length); + } + &first[..length] +} + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let mut actions = Vec::new(); + let colors = Colors::new(ui.visuals()); + let worker_ready = state.worker.is_ready(); + let console = &mut state.console; + + egui::Panel::bottom("console_input") + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(6, 4))) + .show(ui, |ui| { + if console.search_open { + history_search_bar(ui, console); + ui.add_space(4.0); + } + ui.horizontal(|ui| { + ui.label( + RichText::new(if console.more { "..." } else { ">>>" }) + .monospace() + .color(colors.prompt), + ); + let input_id = ui.id().with("console_input_text"); + let focused = ui.memory(|m| m.has_focus(input_id)); + if focused { + handle_keys(ui, console, &mut actions); + } + let response = ui.add_enabled( + worker_ready, + egui::TextEdit::multiline(&mut console.input) + .id(input_id) + .font(egui::TextStyle::Monospace) + .desired_rows(1) + // Room for the buttons, Stop included while busy. + .desired_width( + ui.available_width() - if console.busy { 120.0 } else { 90.0 }, + ) + .hint_text(if worker_ready { + "Python — Enter to run · Ctrl+R to search history" + } else { + "Waiting for Python…" + }), + ); + if std::mem::take(&mut console.focus_input) { + response.request_focus(); + } + if console.busy + && ui + .button(icon::STOP) + .on_hover_text( + "Stop the running command (Ctrl+Shift+F5); its variables stay", + ) + .clicked() + { + actions.push(Action::Stop); + } + if ui + .add_enabled( + !console.history.is_empty(), + egui::Button::new(icon::MAGNIFYING_GLASS).selected(console.search_open), + ) + .on_hover_text("Search command history (Ctrl+R)") + .clicked() + { + if console.search_open { + console.cancel_history_search(); + } else { + console.open_history_search(); + } + } + if ui + .button(icon::BROOM) + .on_hover_text("Clear the console") + .clicked() + { + actions.push(Action::ClearConsole); + } + if ui + .button(icon::ARROW_COUNTER_CLOCKWISE) + .on_hover_text("Restart the console (forgets its variables)") + .clicked() + { + actions.push(Action::ResetConsole); + } + }); + }); + + egui::CentralPanel::default() + .frame(egui::Frame::NONE) + .show(ui, |ui| { + output(ui, console, &colors); + }); + + state.queue(actions); +} + +fn output(ui: &mut egui::Ui, console: &mut ConsoleState, colors: &Colors) { + egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .stick_to_bottom(true) + .show(ui, |ui| { + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(8, 4)) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + if console.entries.is_empty() { + ui.weak( + "Python console. Try: show_object(cq.Workplane().sphere(5)) · \ + selected() returns what is picked in the 3D view", + ); + } + for entry in &mut console.entries { + if let Some(image) = &mut entry.image { + let texture = image.texture.get_or_insert_with(|| { + ui.ctx().load_texture( + "console image", + egui::ColorImage::from_rgba_unmultiplied( + image.pixels.size, + &image.pixels.rgba, + ), + egui::TextureOptions::LINEAR, + ) + }); + let size = texture.size_vec2(); + let scale = (ui.available_width() / size.x) + .min(MAX_IMAGE_HEIGHT / size.y) + .min(1.0); + ui.add_space(4.0); + ui.image((texture.id(), size * scale)); + ui.add_space(4.0); + } + if entry.text.is_empty() { + continue; + } + let color = match entry.kind { + EntryKind::Input => colors.input, + EntryKind::Output => colors.output, + EntryKind::Error => colors.error, + EntryKind::Info => colors.info, + }; + let text = entry.text.strip_suffix('\n').unwrap_or(&entry.text); + ui.add( + egui::Label::new(RichText::new(text).monospace().color(color)) + .selectable(true), + ); + } + if console.busy { + ui.spinner(); + } + }); + }); +} + +fn history_search_bar(ui: &mut egui::Ui, console: &mut ConsoleState) { + ui.horizontal(|ui| { + ui.label(icon::MAGNIFYING_GLASS); + let search_id = ui.id().with("console_history_search"); + let focused = ui.memory(|m| m.has_focus(search_id)); + if focused { + if ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { + console.cancel_history_search(); + return; + } + if ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) { + console.accept_history_search(); + return; + } + if ui.input_mut(|i| { + i.consume_key(Modifiers::COMMAND, Key::R) + || i.consume_key(Modifiers::NONE, Key::ArrowUp) + }) { + console.step_history_search(true); + } else if ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::ArrowDown)) { + console.step_history_search(false); + } + } + let mut query = console.search_query.clone(); + let response = ui.add( + egui::TextEdit::singleline(&mut query) + .id(search_id) + .desired_width((ui.available_width() - 150.0).max(80.0)) + .hint_text("Search history… (Enter to use, Esc to cancel)"), + ); + if std::mem::take(&mut console.focus_search) { + response.request_focus(); + } + if response.changed() { + console.set_history_search_query(&query); + } + let matches = console.history_matches(&console.search_query); + if matches.is_empty() { + ui.weak("No match"); + } else { + let current = console.search_match_index.min(matches.len() - 1) + 1; + ui.weak(format!("{current}/{}", matches.len())); + } + if ui + .add_enabled(!matches.is_empty(), egui::Button::new(icon::CARET_UP)) + .on_hover_text("Older match (Ctrl+R / Up)") + .clicked() + { + console.step_history_search(true); + } + if ui + .add_enabled(!matches.is_empty(), egui::Button::new(icon::CARET_DOWN)) + .on_hover_text("Newer match (Down)") + .clicked() + { + console.step_history_search(false); + } + if ui + .button(icon::CHECK) + .on_hover_text("Use command in input (Enter)") + .clicked() + { + console.accept_history_search(); + } + if ui + .button(icon::X) + .on_hover_text("Cancel search and restore previous input (Esc)") + .clicked() + { + console.cancel_history_search(); + } + }); +} + +fn handle_keys(ui: &egui::Ui, console: &mut ConsoleState, actions: &mut Vec) { + if ui.input_mut(|i| i.consume_key(Modifiers::COMMAND, Key::R)) { + if console.search_open { + console.step_history_search(true); + } else { + console.open_history_search(); + } + return; + } + let submit = ui.input_mut(|i| { + // Shift+Enter falls through to the text edit and inserts a newline. + !i.modifiers.shift && i.consume_key(Modifiers::NONE, Key::Enter) + }); + if submit { + let source = std::mem::take(&mut console.input); + actions.push(Action::ConsoleSubmit(source)); + console.focus_input = true; + return; + } + if !console.input.is_empty() && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)) { + actions.push(Action::ConsoleComplete); + return; + } + if ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::ArrowUp)) { + console.step_history(true); + } else if ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::ArrowDown)) { + console.step_history(false); + } +} + +struct Colors { + prompt: Color32, + input: Color32, + output: Color32, + error: Color32, + info: Color32, +} + +impl Colors { + fn new(visuals: &egui::Visuals) -> Self { + let text = visuals.text_color(); + Self { + prompt: visuals.hyperlink_color, + input: visuals.hyperlink_color.lerp_to_gamma(text, 0.35), + output: text, + error: visuals.error_fg_color, + info: visuals.weak_text_color(), + } + } +} + +#[cfg(test)] +#[path = "../../tests/rust/panels/test_console.rs"] +mod tests; diff --git a/src/panels/inspector.rs b/src/panels/inspector.rs new file mode 100644 index 000000000..ca308bb47 --- /dev/null +++ b/src/panels/inspector.rs @@ -0,0 +1,147 @@ +//! The CadQuery object inspector: the construction stack of the selected +//! workplane, newest step first. Selecting a step shows its objects and its +//! workplane grid in the 3D view (when "Show in view" is on). + +use egui::RichText; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::scene::NodeKey; +use crate::worker::protocol::StackFrame; + +#[derive(Default)] +pub struct InspectorState { + /// Overlay the selected step in the 3D view. + pub show_in_view: bool, + /// The inspected object and its name. + pub key: Option, + pub name: String, + pub frames: Vec, + /// Selected (frame, item); `None` item selects the whole frame. + pub selected: Option<(usize, Option)>, + pub loading: bool, +} + +impl InspectorState { + pub fn clear(&mut self) { + self.key = None; + self.name.clear(); + self.frames.clear(); + self.selected = None; + self.loading = false; + } +} + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let mut actions = Vec::new(); + let inspector = &mut state.inspector; + let source = |actions: &mut Vec, ui: &mut egui::Ui, key: &NodeKey, line, step| { + if ui + .small_button(format!("line {line}")) + .on_hover_text("Go to the script line that made it") + .clicked() + { + actions.push(Action::GoToSource { + key: key.clone(), + step: Some(step), + }); + } + }; + + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(6, 4)) + .show(ui, |ui| { + ui.horizontal(|ui| { + if ui + .selectable_label( + inspector.show_in_view, + format!("{} Show in view", icon::EYE), + ) + .on_hover_text("Overlay the selected step on the model, with its workplane") + .clicked() + { + actions.push(Action::ToggleInspect); + } + if !inspector.name.is_empty() { + ui.weak(&inspector.name); + } + }); + }); + ui.separator(); + + if inspector.key.is_none() { + super::empty_state( + ui, + icon::STACK, + "Select a workplane in Objects to inspect it", + ); + state.queue(actions); + return; + } + if inspector.loading { + ui.centered_and_justified(|ui| ui.spinner()); + state.queue(actions); + return; + } + + let key = inspector.key.clone().unwrap_or_default(); + egui::ScrollArea::both() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + for (frame_index, frame) in inspector.frames.iter().enumerate() { + let id = ui.make_persistent_id(("inspector_frame", frame_index)); + egui::collapsing_header::CollapsingState::load_with_default_open( + ui.ctx(), + id, + frame_index == 0, + ) + .show_header(ui, |ui| { + let selected = inspector.selected == Some((frame_index, None)); + let text = RichText::new(format!("{} {}", frame.type_name, frame.value)); + if ui + .add(egui::Button::selectable(selected, text).truncate()) + .clicked() + { + actions.push(Action::InspectEntry { + frame: frame_index, + item: None, + }); + } + ui.weak(format!("{} objects", frame.items.len())); + if let Some(line) = frame.line { + source(&mut actions, ui, &key, line, (frame_index, None)); + } + }) + .body(|ui| { + for (item_index, item) in frame.items.iter().enumerate() { + let selected = inspector.selected == Some((frame_index, Some(item_index))); + let text = RichText::new(format!("{} {}", item.type_name, item.value)); + let label = if item.displayable { text } else { text.weak() }; + ui.horizontal(|ui| { + if let Some(line) = item.line { + source( + &mut actions, + ui, + &key, + line, + (frame_index, Some(item_index)), + ); + } + if ui + .add(egui::Button::selectable(selected, label).truncate()) + .clicked() + { + actions.push(Action::InspectEntry { + frame: frame_index, + item: Some(item_index), + }); + } + }); + } + }); + } + }); + state.queue(actions); +} diff --git a/src/panels/log.rs b/src/panels/log.rs new file mode 100644 index 000000000..14056bdd9 --- /dev/null +++ b/src/panels/log.rs @@ -0,0 +1,190 @@ +//! The application log: script output, Python logging, worker diagnostics +//! and the editor's own messages. + +use egui::{Color32, RichText}; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::logging::{self, Level}; + +pub struct LogView { + filter: String, + show_debug: bool, + show_info: bool, + show_warnings: bool, + show_errors: bool, + /// Indices of the entries passing the filter, and what they were + /// computed for. + visible: Vec, + computed_for: Option<(u64, String, [bool; 4])>, +} + +impl Default for LogView { + fn default() -> Self { + Self { + filter: String::new(), + show_debug: false, + show_info: true, + show_warnings: true, + show_errors: true, + visible: Vec::new(), + computed_for: None, + } + } +} + +impl LogView { + fn shows(&self, level: Level) -> bool { + match level { + Level::Error => self.show_errors, + Level::Warn => self.show_warnings, + Level::Info => self.show_info, + Level::Debug => self.show_debug, + } + } + + fn refresh(&mut self) { + let key = ( + logging::revision(), + self.filter.clone(), + [ + self.show_debug, + self.show_info, + self.show_warnings, + self.show_errors, + ], + ); + if self.computed_for.as_ref() == Some(&key) { + return; + } + let needle = self.filter.to_lowercase(); + self.visible = logging::with_entries(|entries| { + entries + .iter() + .enumerate() + .filter(|(_, e)| self.shows(e.level)) + .filter(|(_, e)| needle.is_empty() || matches_filter(e, &needle)) + .map(|(i, _)| i) + .collect() + }); + self.computed_for = Some(key); + } +} + +/// Whether the text or the source of `entry` contains `needle`, which is +/// lowercase: the filter ignores case in both. +fn matches_filter(entry: &logging::Entry, needle: &str) -> bool { + entry.text.to_lowercase().contains(needle) || entry.source.to_lowercase().contains(needle) +} + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let mut actions = Vec::new(); + let view = &mut state.log_view; + + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(6, 4)) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.label(icon::FUNNEL_SIMPLE); + ui.add( + egui::TextEdit::singleline(&mut view.filter) + .hint_text("Filter") + .desired_width(160.0), + ); + ui.toggle_value(&mut view.show_errors, "Errors"); + ui.toggle_value(&mut view.show_warnings, "Warnings"); + ui.toggle_value(&mut view.show_info, "Info"); + ui.toggle_value(&mut view.show_debug, "Debug"); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .button(icon::ERASER) + .on_hover_text("Clear the log") + .clicked() + { + actions.push(Action::ClearLog); + } + if ui + .button(icon::COPY) + .on_hover_text("Copy the shown lines") + .clicked() + { + let text = logging::with_entries(|entries| { + view.visible + .iter() + .filter_map(|&i| entries.get(i)) + .map(|e| { + format!( + "[{}] {} {}: {}", + e.time, + e.level.label(), + e.source, + e.text + ) + }) + .collect::>() + .join("\n") + }); + ui.ctx().copy_text(text); + } + }); + }); + }); + ui.separator(); + + view.refresh(); + let colors = [ + ui.visuals().error_fg_color, + ui.visuals().warn_fg_color, + ui.visuals().text_color(), + ui.visuals().weak_text_color(), + ]; + let row_height = ui.text_style_height(&egui::TextStyle::Monospace) + 2.0; + let visible = &view.visible; + egui::ScrollArea::both() + .auto_shrink([false, false]) + .stick_to_bottom(true) + .show_rows(ui, row_height, visible.len(), |ui, rows| { + logging::with_entries(|entries| { + for &index in &visible[rows] { + let Some(entry) = entries.get(index) else { + continue; + }; + let color: Color32 = match entry.level { + Level::Error => colors[0], + Level::Warn => colors[1], + Level::Info => colors[2], + Level::Debug => colors[3], + }; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + ui.label(RichText::new(&entry.time).monospace().weak()); + ui.label(RichText::new(&entry.source).monospace().weak()); + ui.add( + egui::Label::new(RichText::new(&entry.text).monospace().color(color)) + .extend(), + ); + }); + } + }); + }); + state.queue(actions); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_filter_ignores_case_in_sources_too() { + let entry = logging::Entry { + time: "12:00:00".to_owned(), + level: Level::Warn, + source: "OCP.BRepMesh".to_owned(), + text: "Mesh warning".to_owned(), + }; + assert!(matches_filter(&entry, "brepmesh")); + assert!(matches_filter(&entry, "warning")); + assert!(!matches_filter(&entry, "python")); + } +} diff --git a/src/panels/measurements.rs b/src/panels/measurements.rs new file mode 100644 index 000000000..2c1df25d8 --- /dev/null +++ b/src/panels/measurements.rs @@ -0,0 +1,1015 @@ +use egui_phosphor::regular as icon; +use serde_json::json; + +use crate::app::AppState; +use crate::commands::{Action, MeasurementFormat}; +use crate::scene::{Scene, TopologySelection}; +use crate::settings::Units; +use crate::worker::protocol::{ + BoundingBox, EntityMeasurement, Measurement, ObjectMeasurement, PairMeasurement, RequestId, + SelectorCandidate, SelectorReply, TopologyKind, +}; + +#[derive(Default)] +pub struct MeasurementState { + pub result: Option, + pub loading: bool, + pub error: Option, + pub request_id: Option, +} + +impl MeasurementState { + pub fn clear(&mut self) { + self.result = None; + self.loading = false; + self.error = None; + self.request_id = None; + } +} + +/// What to do with a selector once the worker found it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SelectorUse { + Copy, + Insert, +} + +/// The CadQuery selector of the current topology selection. +#[derive(Default)] +pub struct SelectorState { + pub reply: Option, + /// The candidate in use, an index into `reply.candidates`. + pub chosen: usize, + pub loading: bool, + pub error: Option, + pub request_id: Option, + /// Asked for before the reply arrived; carried out on arrival. + pub then: Option, +} + +/// A read-only selector preview tied to the caret of the last successful run. +#[derive(Default)] +pub struct SelectorPreviewState { + pub cursor: Option<(RequestId, usize, usize)>, + pub due_at: Option, + pub request_id: Option, + pub active: bool, + pub count: usize, + pub shown: usize, + pub message: Option, +} + +impl SelectorPreviewState { + pub fn clear(&mut self) { + *self = Self::default(); + } +} + +impl SelectorState { + pub fn clear(&mut self) { + *self = Self::default(); + } + + pub fn candidate(&self) -> Option<&SelectorCandidate> { + let candidates = &self.reply.as_ref()?.candidates; + candidates.get(self.chosen).or_else(|| candidates.first()) + } +} + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let mut actions = Vec::new(); + egui::ScrollArea::vertical().show(ui, |ui| { + ui.horizontal(|ui| { + ui.strong("Exact CAD measurements"); + if state.measurements.loading { + ui.spinner(); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let has_result = state.measurements.result.is_some(); + if ui + .add_enabled( + has_result, + egui::Button::new(format!("{} Copy as code", icon::CLIPBOARD_TEXT)), + ) + .on_hover_text( + "Python measuring the same entities from the script's variables, \ + checked against these values", + ) + .clicked() + { + actions.push(Action::CopyMeasurementCode); + } + ui.add_enabled_ui(has_result, |ui| { + ui.menu_button(format!("{} Copy data", icon::COPY), |ui| { + for format in MeasurementFormat::ALL { + if ui + .button(format!("Copy as {}", format.label())) + .clicked() + { + actions.push(Action::CopyMeasurement(format)); + ui.close(); + } + } + }) + .response + .on_hover_text("Copy measurement values as structured Text, JSON or CSV"); + }); + }); + }); + ui.small(format!( + "Selection mode: {} · Ctrl+click adds entities", + state.viewer.selection_mode.label() + )); + ui.add_space(6.0); + + if state.selector_preview.active { + ui.separator(); + let preview = &state.selector_preview; + ui.strong(format!("Selector preview: {} matching entities", preview.count)); + if preview.shown < preview.count { + ui.weak(format!("Showing {} highlights", preview.shown)); + } + if let Some(message) = &preview.message { + ui.colored_label(ui.visuals().warn_fg_color, message); + } + ui.separator(); + } + + if !state.scene.topology_selections.is_empty() { + selector_ui(ui, &mut state.selector, &mut actions); + ui.separator(); + } + + if let Some(error) = &state.measurements.error { + ui.colored_label(ui.visuals().error_fg_color, error); + return; + } + let Some(result) = &state.measurements.result else { + super::empty_state( + ui, + icon::RULER, + "Select an object, or a face, edge or vertex, in the 3D view", + ); + return; + }; + + for (index, entity) in result.entities.iter().enumerate() { + if index > 0 { + ui.separator(); + } + entity_ui(ui, state, entity, index + 1); + } + for (index, object) in result.objects.iter().enumerate() { + if index > 0 { + ui.separator(); + } + object_ui(ui, state, object, index + 1); + } + if let Some(pair) = &result.pair { + ui.separator(); + pair_ui(ui, pair); + } + if result.entities.len() + result.objects.len() > 1 + && let Some(bounds) = &result.bounding_box + { + ui.separator(); + ui.strong("Selection bounds"); + egui::Grid::new("measurement_selection_bounds") + .num_columns(2) + .spacing([12.0, 4.0]) + .show(ui, |ui| bounds_rows(ui, bounds)); + } + + ui.separator(); + ui.weak( + "Topology IDs belong to this render only. Rebuilding or remodeling the object may change them.", + ); + }); + state.queue(actions); +} + +/// The selector of the picked entities, with Copy and Insert. +pub fn selector_ui(ui: &mut egui::Ui, selector: &mut SelectorState, actions: &mut Vec) { + ui.horizontal(|ui| { + ui.label(format!("{} Selector", icon::SELECTION)); + if selector.loading { + ui.spinner(); + } + }); + if let Some(error) = &selector.error { + ui.colored_label(ui.visuals().warn_fg_color, error); + return; + } + let Some(reply) = &selector.reply else { + return; + }; + let Some(candidate) = selector.candidate().cloned() else { + return; + }; + ui.add(egui::Label::new(egui::RichText::new(&candidate.expression).monospace()).wrap()); + if !candidate.description.is_empty() { + ui.weak(&candidate.description); + } + if candidate.index_based { + ui.colored_label( + ui.visuals().warn_fg_color, + format!( + "{} No geometric selector matches exactly; this index may select another entity once the model changes", + icon::WARNING + ), + ); + } + ui.horizontal(|ui| { + if ui + .button(format!("{} Copy", icon::COPY)) + .on_hover_text("Copy the selector to the clipboard") + .clicked() + { + actions.push(Action::CopySelector); + } + let insert = ui + .button(format!("{} Insert", icon::CURSOR_TEXT)) + .on_hover_text("Insert the selector at the editor's cursor"); + if insert.clicked() { + actions.push(Action::InsertSelector); + } + if reply.candidates.len() > 1 { + let mut chosen = selector.chosen.min(reply.candidates.len() - 1); + egui::ComboBox::from_id_salt("selector_alternatives") + .selected_text("Alternatives") + .show_ui(ui, |ui| { + for (index, alternative) in reply.candidates.iter().enumerate() { + ui.selectable_value(&mut chosen, index, &alternative.expression) + .on_hover_text(&alternative.description); + } + }); + selector.chosen = chosen; + } + }); +} + +/// The measurement of `selection` in `result`. +pub fn measurement_of<'a>( + result: &'a Measurement, + selection: &TopologySelection, +) -> Option<&'a EntityMeasurement> { + result.entities.iter().find(|entity| { + entity.key == selection.node + && entity.part == selection.part + && entity.kind == selection.entity.topology_kind() + && entity.identifier == selection.entity.identifier() + }) +} + +fn entity_ui(ui: &mut egui::Ui, state: &AppState, entity: &EntityMeasurement, number: usize) { + let name = state + .scene + .find(&entity.key) + .map_or(entity.key.as_str(), |node| node.name.as_str()); + let attribute = state.scene.find(&entity.key).and_then(|node| { + (entity.kind == TopologyKind::Face) + .then(|| node.parts.get(entity.part)) + .flatten() + .and_then(|part| { + part.face_attributes + .iter() + .find(|face| face.id == entity.identifier) + }) + }); + let face_label = attribute.and_then(|face| face.name.as_deref()).map_or_else( + || format!("{} {}", kind_label(entity.kind), entity.identifier), + str::to_owned, + ); + ui.strong(format!("{number}. {face_label} · {name}")); + egui::Grid::new(("measurement_entity", number)) + .num_columns(2) + .spacing([12.0, 4.0]) + .show(ui, |ui| { + row(ui, "Geometry", &title_case(&entity.geometry_type)); + if let Some(face) = attribute + && let Some(layer) = &face.layer + { + row(ui, "Layer", layer); + } + row(ui, "Part", &(entity.part + 1).to_string()); + row(ui, "Center", &format_point(entity.center)); + if let Some(position) = entity.position { + row(ui, "Position", &format_point(position)); + } + if let Some(value) = entity.length { + row(ui, "Length", &format_number(value)); + } + if let Some(value) = entity.area { + row(ui, "Area", &format_number(value)); + } + if let Some(value) = entity.radius { + row(ui, "Radius", &format_number(value)); + } + if let Some(value) = entity.diameter { + row(ui, "Diameter", &format_number(value)); + } + if let Some(bounds) = &entity.bounding_box { + bounds_rows(ui, bounds); + } + }); +} + +fn object_ui(ui: &mut egui::Ui, state: &AppState, object: &ObjectMeasurement, number: usize) { + let name = state + .scene + .find(&object.key) + .map_or(object.key.as_str(), |node| node.name.as_str()); + ui.strong(format!("{number}. {name}")); + egui::Grid::new(("measurement_object", number)) + .num_columns(2) + .spacing([12.0, 4.0]) + .show(ui, |ui| { + row(ui, "Shape", &title_case(&object.shape_type)); + if let Some(value) = object.volume { + row(ui, "Volume", &format_number(value)); + } + if let Some(value) = object.mass_g { + row(ui, "Mass (g)", &format_number(value)); + } + if !object.materials.is_empty() { + row(ui, "Materials", &object.materials.join(", ")); + } + if let Some(value) = object.area { + row(ui, "Area", &format_number(value)); + } + if let Some(value) = object.length { + row(ui, "Length", &format_number(value)); + } + row(ui, "Center of mass", &format_point(object.center)); + row( + ui, + "Topology", + &format!( + "{} solids · {} faces · {} edges · {} vertices", + object.solids, object.faces, object.edges, object.vertices + ), + ); + if let Some(bounds) = &object.bounding_box { + bounds_rows(ui, bounds); + } + }); +} + +/// Size, minimum and maximum of an exact bounding box. +fn bounds_rows(ui: &mut egui::Ui, bounds: &BoundingBox) { + let [x, y, z] = bounds.size; + row( + ui, + "Bounding box", + &format!( + "{} × {} × {}", + format_number(x), + format_number(y), + format_number(z) + ), + ); + row(ui, "Min", &format_point(bounds.min)); + row(ui, "Max", &format_point(bounds.max)); +} + +fn pair_ui(ui: &mut egui::Ui, pair: &PairMeasurement) { + ui.strong("Relationship"); + egui::Grid::new("measurement_pair") + .num_columns(2) + .spacing([12.0, 4.0]) + .show(ui, |ui| { + row(ui, "Distance", &format_number(pair.distance)); + row(ui, "Closest point 1", &format_point(pair.first_point)); + row(ui, "Closest point 2", &format_point(pair.second_point)); + if let Some(angle) = pair.angle_degrees { + let label = match pair.angle_kind.as_deref() { + Some("edge_edge") => "Edge angle", + Some("face_face") => "Face angle", + Some("edge_face") => "Edge/plane angle", + _ => "Angle", + }; + row(ui, label, &format!("{}°", format_number(angle))); + } + }); +} + +fn row(ui: &mut egui::Ui, label: &str, value: &str) { + ui.label(label); + ui.monospace(value); + ui.end_row(); +} + +fn kind_label(kind: TopologyKind) -> &'static str { + match kind { + TopologyKind::Face => "Face", + TopologyKind::Edge => "Edge", + TopologyKind::Vertex => "Vertex", + } +} + +pub fn title_case(value: &str) -> String { + let mut chars = value.chars(); + chars + .next() + .map(|first| first.to_uppercase().collect::() + chars.as_str()) + .unwrap_or_default() +} + +pub fn format_point(point: [f64; 3]) -> String { + format!( + "({}, {}, {})", + format_number(point[0]), + format_number(point[1]), + format_number(point[2]) + ) +} + +pub fn format_number(value: f64) -> String { + let absolute = value.abs(); + if absolute != 0.0 && !(1e-5..1e9).contains(&absolute) { + return format!("{value:.8e}"); + } + let text = format!("{value:.9}"); + text.trim_end_matches('0').trim_end_matches('.').to_owned() +} + +/// Formats `result` as structured text, JSON, or CSV with units. +pub fn format_measurement( + result: &Measurement, + scene: &Scene, + units: Units, + format: MeasurementFormat, +) -> String { + match format { + MeasurementFormat::Text => format_measurement_text(result, scene, units), + MeasurementFormat::Json => format_measurement_json(result, scene, units), + MeasurementFormat::Csv => format_measurement_csv(result, scene, units), + } +} + +fn unit_strings(units: Units) -> (&'static str, String, String) { + let linear = units.suffix(); + if linear.is_empty() { + ("", String::new(), String::new()) + } else { + (linear, format!("{linear}²"), format!("{linear}³")) + } +} + +fn with_unit(value: &str, unit: &str) -> String { + if unit.is_empty() { + value.to_owned() + } else { + format!("{value} {unit}") + } +} + +fn entity_label_for(entity: &EntityMeasurement, scene: &Scene) -> (String, String) { + let object_name = scene + .find(&entity.key) + .map_or(entity.key.as_str(), |node| node.name.as_str()) + .to_owned(); + let attribute = scene.find(&entity.key).and_then(|node| { + (entity.kind == TopologyKind::Face) + .then(|| node.parts.get(entity.part)) + .flatten() + .and_then(|part| { + part.face_attributes + .iter() + .find(|face| face.id == entity.identifier) + }) + }); + let label = attribute.and_then(|face| face.name.as_deref()).map_or_else( + || format!("{} {}", kind_label(entity.kind), entity.identifier), + str::to_owned, + ); + (object_name, label) +} + +fn format_measurement_text(result: &Measurement, scene: &Scene, units: Units) -> String { + let (u_lin, u_area, u_vol) = unit_strings(units); + let mut lines = Vec::new(); + + if let Some(pair) = &result.pair { + let delta = [ + pair.second_point[0] - pair.first_point[0], + pair.second_point[1] - pair.first_point[1], + pair.second_point[2] - pair.first_point[2], + ]; + lines.push(format!( + "Distance: {}", + with_unit(&format_number(pair.distance), u_lin) + )); + lines.push(format!("Delta: {}", with_unit(&format_point(delta), u_lin))); + lines.push(format!( + "Closest point 1: {}", + with_unit(&format_point(pair.first_point), u_lin) + )); + lines.push(format!( + "Closest point 2: {}", + with_unit(&format_point(pair.second_point), u_lin) + )); + if let Some(angle) = pair.angle_degrees { + lines.push(format!("Angle: {}°", format_number(angle))); + } + } + + for entity in &result.entities { + if !lines.is_empty() { + lines.push(String::new()); + } + let (object_name, label) = entity_label_for(entity, scene); + lines.push(format!( + "{label} · {object_name} ({})", + title_case(&entity.geometry_type) + )); + lines.push(format!( + "Center: {}", + with_unit(&format_point(entity.center), u_lin) + )); + if let Some(position) = entity.position { + lines.push(format!( + "Position: {}", + with_unit(&format_point(position), u_lin) + )); + } + if let Some(length) = entity.length { + lines.push(format!( + "Length: {}", + with_unit(&format_number(length), u_lin) + )); + } + if let Some(area) = entity.area { + lines.push(format!( + "Area: {}", + with_unit(&format_number(area), &u_area) + )); + } + if let Some(radius) = entity.radius { + lines.push(format!( + "Radius: {}", + with_unit(&format_number(radius), u_lin) + )); + } + if let Some(diameter) = entity.diameter { + lines.push(format!( + "Diameter: {}", + with_unit(&format_number(diameter), u_lin) + )); + } + if let Some(bounds) = &entity.bounding_box { + let [x, y, z] = bounds.size; + lines.push(format!( + "Bounding box: {}", + with_unit( + &format!( + "{} × {} × {}", + format_number(x), + format_number(y), + format_number(z) + ), + u_lin + ) + )); + } + } + + for object in &result.objects { + if !lines.is_empty() { + lines.push(String::new()); + } + let name = scene + .find(&object.key) + .map_or(object.key.as_str(), |node| node.name.as_str()); + lines.push(format!("{name} ({})", title_case(&object.shape_type))); + if let Some(volume) = object.volume { + lines.push(format!( + "Volume: {}", + with_unit(&format_number(volume), &u_vol) + )); + } + if let Some(mass) = object.mass_g { + lines.push(format!("Mass: {} g", format_number(mass))); + } + if let Some(area) = object.area { + lines.push(format!( + "Area: {}", + with_unit(&format_number(area), &u_area) + )); + } + if let Some(length) = object.length { + lines.push(format!( + "Length: {}", + with_unit(&format_number(length), u_lin) + )); + } + lines.push(format!( + "Center of mass: {}", + with_unit(&format_point(object.center), u_lin) + )); + if let Some(bounds) = &object.bounding_box { + let [x, y, z] = bounds.size; + lines.push(format!( + "Bounding box: {}", + with_unit( + &format!( + "{} × {} × {}", + format_number(x), + format_number(y), + format_number(z) + ), + u_lin + ) + )); + lines.push(format!( + "Min: {}", + with_unit(&format_point(bounds.min), u_lin) + )); + lines.push(format!( + "Max: {}", + with_unit(&format_point(bounds.max), u_lin) + )); + } + } + + if result.entities.len() + result.objects.len() > 1 + && let Some(bounds) = &result.bounding_box + { + if !lines.is_empty() { + lines.push(String::new()); + } + let [x, y, z] = bounds.size; + lines.push("Selection bounds".to_owned()); + lines.push(format!( + "Bounding box: {}", + with_unit( + &format!( + "{} × {} × {}", + format_number(x), + format_number(y), + format_number(z) + ), + u_lin + ) + )); + lines.push(format!( + "Min: {}", + with_unit(&format_point(bounds.min), u_lin) + )); + lines.push(format!( + "Max: {}", + with_unit(&format_point(bounds.max), u_lin) + )); + } + + lines.join("\n") +} + +fn format_measurement_json(result: &Measurement, scene: &Scene, units: Units) -> String { + let (u_lin, u_area, u_vol) = unit_strings(units); + let entities: Vec<_> = result + .entities + .iter() + .map(|entity| { + let (object_name, label) = entity_label_for(entity, scene); + json!({ + "object": object_name, + "label": label, + "kind": kind_label(entity.kind).to_ascii_lowercase(), + "id": entity.identifier, + "part": entity.part + 1, + "geometry_type": entity.geometry_type, + "center": entity.center, + "position": entity.position, + "length": entity.length, + "area": entity.area, + "radius": entity.radius, + "diameter": entity.diameter, + "bounding_box": entity.bounding_box.as_ref().map(|b| json!({ + "size": b.size, + "min": b.min, + "max": b.max, + })), + }) + }) + .collect(); + + let objects: Vec<_> = result + .objects + .iter() + .map(|object| { + let name = scene + .find(&object.key) + .map_or(object.key.as_str(), |node| node.name.as_str()); + json!({ + "name": name, + "shape_type": object.shape_type, + "volume": object.volume, + "mass_g": object.mass_g, + "materials": object.materials, + "area": object.area, + "length": object.length, + "center": object.center, + "topology": { + "solids": object.solids, + "faces": object.faces, + "edges": object.edges, + "vertices": object.vertices, + }, + "bounding_box": object.bounding_box.as_ref().map(|b| json!({ + "size": b.size, + "min": b.min, + "max": b.max, + })), + }) + }) + .collect(); + + let pair = result.pair.as_ref().map(|pair| { + let delta = [ + pair.second_point[0] - pair.first_point[0], + pair.second_point[1] - pair.first_point[1], + pair.second_point[2] - pair.first_point[2], + ]; + json!({ + "distance": pair.distance, + "delta": delta, + "first_point": pair.first_point, + "second_point": pair.second_point, + "angle_degrees": pair.angle_degrees, + "angle_kind": pair.angle_kind, + }) + }); + + let payload = json!({ + "unit": u_lin, + "area_unit": u_area, + "volume_unit": u_vol, + "pair": pair, + "entities": entities, + "objects": objects, + "bounding_box": result.bounding_box.as_ref().map(|b| json!({ + "size": b.size, + "min": b.min, + "max": b.max, + })), + }); + + serde_json::to_string_pretty(&payload).unwrap_or_default() +} + +fn csv_cell(text: &str) -> String { + if text.contains([',', '"', '\n', '\r']) { + format!("\"{}\"", text.replace('"', "\"\"")) + } else { + text.to_owned() + } +} + +fn push_csv_row(rows: &mut Vec, target: &str, property: &str, value: &str, unit: &str) { + rows.push(format!( + "{},{},{},{}", + csv_cell(target), + csv_cell(property), + csv_cell(value), + csv_cell(unit) + )); +} + +fn format_measurement_csv(result: &Measurement, scene: &Scene, units: Units) -> String { + let (u_lin, u_area, u_vol) = unit_strings(units); + let mut rows = vec!["target,property,value,unit".to_owned()]; + + if let Some(pair) = &result.pair { + let delta = [ + pair.second_point[0] - pair.first_point[0], + pair.second_point[1] - pair.first_point[1], + pair.second_point[2] - pair.first_point[2], + ]; + push_csv_row( + &mut rows, + "pair", + "distance", + &format_number(pair.distance), + u_lin, + ); + push_csv_row(&mut rows, "pair", "dx", &format_number(delta[0]), u_lin); + push_csv_row(&mut rows, "pair", "dy", &format_number(delta[1]), u_lin); + push_csv_row(&mut rows, "pair", "dz", &format_number(delta[2]), u_lin); + if let Some(angle) = pair.angle_degrees { + push_csv_row(&mut rows, "pair", "angle", &format_number(angle), "deg"); + } + } + + for entity in &result.entities { + let (object_name, label) = entity_label_for(entity, scene); + let target = format!("{object_name}:{label}"); + push_csv_row(&mut rows, &target, "geometry", &entity.geometry_type, ""); + push_csv_row( + &mut rows, + &target, + "center", + &format_point(entity.center), + u_lin, + ); + if let Some(position) = entity.position { + push_csv_row( + &mut rows, + &target, + "position", + &format_point(position), + u_lin, + ); + } + if let Some(length) = entity.length { + push_csv_row(&mut rows, &target, "length", &format_number(length), u_lin); + } + if let Some(area) = entity.area { + push_csv_row(&mut rows, &target, "area", &format_number(area), &u_area); + } + if let Some(radius) = entity.radius { + push_csv_row(&mut rows, &target, "radius", &format_number(radius), u_lin); + } + if let Some(diameter) = entity.diameter { + push_csv_row( + &mut rows, + &target, + "diameter", + &format_number(diameter), + u_lin, + ); + } + if let Some(bounds) = &entity.bounding_box { + push_csv_row( + &mut rows, + &target, + "bbox_size", + &format_point(bounds.size), + u_lin, + ); + } + } + + for object in &result.objects { + let name = scene + .find(&object.key) + .map_or(object.key.as_str(), |node| node.name.as_str()); + push_csv_row(&mut rows, name, "shape_type", &object.shape_type, ""); + if let Some(volume) = object.volume { + push_csv_row(&mut rows, name, "volume", &format_number(volume), &u_vol); + } + if let Some(mass) = object.mass_g { + push_csv_row(&mut rows, name, "mass", &format_number(mass), "g"); + } + if let Some(area) = object.area { + push_csv_row(&mut rows, name, "area", &format_number(area), &u_area); + } + if let Some(length) = object.length { + push_csv_row(&mut rows, name, "length", &format_number(length), u_lin); + } + push_csv_row( + &mut rows, + name, + "center_of_mass", + &format_point(object.center), + u_lin, + ); + if let Some(bounds) = &object.bounding_box { + push_csv_row( + &mut rows, + name, + "bbox_size", + &format_point(bounds.size), + u_lin, + ); + push_csv_row( + &mut rows, + name, + "bbox_min", + &format_point(bounds.min), + u_lin, + ); + push_csv_row( + &mut rows, + name, + "bbox_max", + &format_point(bounds.max), + u_lin, + ); + } + } + + rows.join("\n") +} + +#[cfg(test)] +mod tests { + use super::{format_number, measurement_of}; + use crate::scene::{TopologyEntity, TopologySelection}; + use crate::worker::protocol::{EntityMeasurement, Measurement, TopologyIdentity, TopologyKind}; + + #[test] + fn the_property_sheet_finds_the_measurement_of_its_selection() { + let entity = |kind, identifier| EntityMeasurement { + key: "s1-n1".into(), + part: 0, + kind, + identifier, + geometry_type: "plane".into(), + center: [0.0; 3], + position: None, + length: None, + area: Some(4.0), + radius: None, + diameter: None, + bounding_box: None, + }; + let result = Measurement { + id: 1, + identity: TopologyIdentity { + scope: "render".into(), + persistent: false, + }, + entities: vec![entity(TopologyKind::Face, 6), entity(TopologyKind::Edge, 6)], + pair: None, + objects: Vec::new(), + bounding_box: None, + }; + let selection = |entity| TopologySelection { + node: "s1-n1".into(), + part: 0, + entity, + position: Default::default(), + }; + + let edge = measurement_of(&result, &selection(TopologyEntity::Edge(6))); + assert_eq!(edge.map(|e| e.kind), Some(TopologyKind::Edge)); + assert!(measurement_of(&result, &selection(TopologyEntity::Face(7))).is_none()); + } + + #[test] + fn numeric_display_keeps_precision_without_noise() { + assert_eq!(format_number(5.0), "5"); + assert_eq!(format_number(1.2345678912), "1.234567891"); + assert_eq!(format_number(0.000_001), "1.00000000e-6"); + } + + #[test] + fn measurements_format_as_structured_text_json_and_csv() { + use super::{MeasurementFormat, format_measurement}; + use crate::scene::Scene; + use crate::settings::Units; + use crate::worker::protocol::PairMeasurement; + + let result = Measurement { + id: 1, + identity: TopologyIdentity { + scope: "render".into(), + persistent: false, + }, + entities: vec![EntityMeasurement { + key: "s1-n1".into(), + part: 0, + kind: TopologyKind::Face, + identifier: 2, + geometry_type: "plane".into(), + center: [0.0, 0.0, 5.0], + position: None, + length: None, + area: Some(120.5), + radius: None, + diameter: None, + bounding_box: None, + }], + pair: Some(PairMeasurement { + distance: 25.4, + first_point: [0.0, 0.0, 0.0], + second_point: [0.0, 0.0, 25.4], + angle_degrees: Some(90.0), + angle_kind: Some("face_face".into()), + }), + objects: Vec::new(), + bounding_box: None, + }; + let scene = Scene::default(); + + let text = format_measurement(&result, &scene, Units::Millimeters, MeasurementFormat::Text); + assert!(text.contains("Distance: 25.4 mm")); + assert!(text.contains("Delta: (0, 0, 25.4) mm")); + assert!(text.contains("Angle: 90°")); + assert!(text.contains("Area: 120.5 mm²")); + + let json_str = + format_measurement(&result, &scene, Units::Millimeters, MeasurementFormat::Json); + let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap(); + assert_eq!(parsed["unit"], "mm"); + assert_eq!(parsed["area_unit"], "mm²"); + assert_eq!(parsed["pair"]["distance"], 25.4); + assert_eq!(parsed["entities"][0]["area"], 120.5); + + let csv = format_measurement(&result, &scene, Units::Millimeters, MeasurementFormat::Csv); + assert!(csv.starts_with("target,property,value,unit\n")); + assert!(csv.contains("pair,distance,25.4,mm")); + assert!(csv.contains("s1-n1:Face 2,area,120.5,mm²")); + } +} diff --git a/src/panels/mod.rs b/src/panels/mod.rs new file mode 100644 index 000000000..29fddb3e6 --- /dev/null +++ b/src/panels/mod.rs @@ -0,0 +1,275 @@ +//! The dockable panels and their default arrangement. + +mod checks; +mod console; +mod inspector; +mod log; +mod measurements; +mod navigation; +mod objects; +mod parameters; +mod project; +mod traceback; +mod variables; + +pub use console::{ConsoleState, EntryKind}; +pub use inspector::InspectorState; +pub use log::LogView; +pub use measurements::{ + MeasurementState, SelectorPreviewState, SelectorState, SelectorUse, format_measurement, +}; +pub use navigation::NavigationState; +pub use parameters::ParametersState; + +use egui_dock::{DockState, NodeIndex, NodePath, TabViewer}; +use egui_phosphor::regular as icon; +use serde::{Deserialize, Serialize}; + +use crate::app::AppState; +use crate::commands::Action; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum Tab { + Editor, + Viewer, + Objects, + Measurements, + Checks, + Navigation, + Parameters, + Variables, + Inspector, + Console, + Traceback, + Log, + Project, +} + +impl Tab { + pub const ALL: [Tab; 13] = [ + Tab::Editor, + Tab::Viewer, + Tab::Objects, + Tab::Measurements, + Tab::Checks, + Tab::Navigation, + Tab::Parameters, + Tab::Variables, + Tab::Inspector, + Tab::Console, + Tab::Traceback, + Tab::Log, + Tab::Project, + ]; + + pub fn title(self) -> &'static str { + match self { + Tab::Editor => "Editor", + Tab::Viewer => "3D View", + Tab::Objects => "Objects", + Tab::Measurements => "Measurements", + Tab::Checks => "Checks", + Tab::Navigation => "Navigation", + Tab::Parameters => "Parameters", + Tab::Variables => "Variables", + Tab::Inspector => "CQ Inspector", + Tab::Console => "Console", + Tab::Traceback => "Traceback", + Tab::Log => "Log", + Tab::Project => "Project", + } + } + + pub fn icon(self) -> &'static str { + match self { + Tab::Editor => icon::CODE, + Tab::Viewer => icon::CUBE, + Tab::Objects => icon::TREE_STRUCTURE, + Tab::Measurements => icon::RULER, + Tab::Checks => icon::CHECKS, + Tab::Navigation => icon::TREE_STRUCTURE, + Tab::Parameters => icon::SLIDERS_HORIZONTAL, + Tab::Variables => icon::BRACKETS_CURLY, + Tab::Inspector => icon::STACK, + Tab::Console => icon::TERMINAL_WINDOW, + Tab::Traceback => icon::WARNING_CIRCLE, + Tab::Log => icon::LIST_BULLETS, + Tab::Project => icon::FOLDER_SIMPLE, + } + } +} + +/// Editor on the left, 3D view in the middle, objects and variables on the +/// right and console, traceback and log at the bottom, like the original. +/// The Project panel joins it, left of the editor, once a folder is open. +pub fn default_layout() -> DockState { + let mut dock = DockState::new(vec![Tab::Viewer]); + let tree = dock.main_surface_mut(); + // Fractions give the share of the left (or top) child of each split. + let [top, bottom] = tree.split_below(NodeIndex::root(), 0.74, vec![Tab::Console]); + tree.split_right(bottom, 0.45, vec![Tab::Checks, Tab::Traceback, Tab::Log]); + let [viewer, _editor] = tree.split_left(top, 0.36, vec![Tab::Editor]); + let [_viewer, objects] = tree.split_right(viewer, 0.72, vec![Tab::Objects]); + tree.split_below( + objects, + 0.6, + vec![ + Tab::Variables, + Tab::Parameters, + Tab::Inspector, + Tab::Measurements, + ], + ); + dock +} + +/// Shows the panels; holds what they need from the application. +pub struct TabContext<'a> { + pub state: &'a mut AppState, + pub frame: &'a eframe::Frame, + /// One panel fills the window (see `Action::ToggleMaximize`). + pub maximized: bool, +} + +impl TabViewer for TabContext<'_> { + type Tab = Tab; + + fn id(&mut self, tab: &mut Tab) -> egui::Id { + egui::Id::new(*tab) + } + + fn title(&mut self, tab: &mut Tab) -> egui::WidgetText { + let mut title = format!("{} {}", tab.icon(), tab.title()); + match tab { + // With several files open their names are on the tab strip. + Tab::Editor if self.state.tabs().len() > 1 => { + if self.state.any_modified() { + title.push_str(" •"); + } + } + Tab::Editor => { + title = format!("{} {}", tab.icon(), self.state.document.display_name()); + if self.state.document.is_modified() { + title.push_str(" •"); + } + } + Tab::Traceback if self.state.traceback.is_some() => title.push_str(" •"), + Tab::Checks if self.state.cad_checks.iter().any(|check| !check.ok) => { + title.push_str(" •"); + } + Tab::Project => { + if let Some(project) = &self.state.project { + title = format!("{} {}", tab.icon(), project.name()); + } + } + _ => {} + } + title.into() + } + + fn ui(&mut self, ui: &mut egui::Ui, tab: &mut Tab) { + constrain_to_tab(ui); + match tab { + Tab::Editor => self.state.editor_ui(ui), + Tab::Viewer => self.state.viewer_ui(ui, self.frame), + Tab::Objects => objects::ui(ui, self.state), + Tab::Measurements => measurements::ui(ui, self.state), + Tab::Checks => checks::ui(ui, self.state), + Tab::Navigation => navigation::ui(ui, self.state), + Tab::Parameters => parameters::ui(ui, self.state), + Tab::Variables => variables::ui(ui, self.state), + Tab::Inspector => inspector::ui(ui, self.state), + Tab::Console => console::ui(ui, self.state), + Tab::Traceback => traceback::ui(ui, self.state), + Tab::Log => log::ui(ui, self.state), + Tab::Project => project::ui(ui, self.state), + } + } + + fn on_tab_button(&mut self, tab: &mut Tab, response: &egui::Response) { + if response.double_clicked() { + self.state.queue([Action::ToggleMaximize(Some(*tab))]); + } + } + + /// Added above the dock's own Float and Close items. + fn context_menu(&mut self, ui: &mut egui::Ui, tab: &mut Tab, _path: NodePath) { + let (label, glyph) = if self.maximized { + ("Restore Layout", icon::ARROWS_IN) + } else { + ("Maximize", icon::ARROWS_OUT) + }; + let mut button = egui::Button::new(format!("{glyph} {label}")); + if let Some(shortcut) = crate::commands::shortcut(&Action::ToggleMaximize(None)) { + button = button.shortcut_text(ui.ctx().format_shortcut(&shortcut)); + } + if ui + .add(button) + .on_hover_text("Double-clicking the tab does the same") + .clicked() + { + self.state.queue([Action::ToggleMaximize(Some(*tab))]); + ui.close(); + } + if ui + .button(format!("{} Reset Layout", icon::LAYOUT)) + .clicked() + { + self.state.queue([Action::ResetLayout]); + ui.close(); + } + ui.separator(); + } + + fn is_closeable(&self, tab: &Tab) -> bool { + *tab != Tab::Viewer + } + + fn scroll_bars(&self, _tab: &Tab) -> [bool; 2] { + // Every panel scrolls its own content. + [false, false] + } +} + +/// Keep every panel's paint inside the body assigned by `egui_dock`. +/// +/// The dock creates tab bodies as fresh [`egui::Ui`]s. Their maximum rectangle +/// is the tab body, but their inherited clip rectangle can be as large as the +/// whole dock area. Most containers narrow it again; widgets that do not can +/// otherwise paint text over a split separator or a neighbouring tab bar. +fn constrain_to_tab(ui: &mut egui::Ui) { + ui.set_clip_rect(ui.clip_rect().intersect(ui.max_rect())); +} + +/// Centered, dimmed text for empty panels. +/// +/// Laid out with centered rows rather than a justified layout, which +/// stretched the spaces of wrapped lines unevenly. +pub(crate) fn empty_state(ui: &mut egui::Ui, icon: &str, text: &str) { + let rect = ui.available_rect_before_wrap(); + ui.allocate_rect(rect, egui::Sense::hover()); + let color = ui.visuals().weak_text_color(); + let job = empty_state_job(ui.style(), &format!("{icon} {text}"), color, rect.width()); + let galley = ui.painter().layout_job(job); + // Centered rows are laid out around x = 0. + let top = (rect.center().y - galley.size().y / 2.0).max(rect.top()); + ui.painter() + .galley(egui::pos2(rect.center().x, top), galley, color); +} + +fn empty_state_job( + style: &egui::Style, + text: &str, + color: egui::Color32, + width: f32, +) -> egui::text::LayoutJob { + let font = egui::TextStyle::Body.resolve(style); + let mut job = + egui::text::LayoutJob::simple(text.to_owned(), font, color, (width - 24.0).max(40.0)); + job.halign = egui::Align::Center; + job +} + +#[cfg(test)] +#[path = "../../tests/rust/panels/test_empty_state.rs"] +mod tests; diff --git a/src/panels/navigation.rs b/src/panels/navigation.rs new file mode 100644 index 000000000..3867d395e --- /dev/null +++ b/src/panels/navigation.rs @@ -0,0 +1,117 @@ +//! Source symbols and static references across the open project. + +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::worker::protocol::{NavigationLocation, NavigationMode, OutlineSymbol, RequestId}; + +#[derive(Default)] +pub struct NavigationState { + pub symbols: Vec, + pub locations: Vec, + pub mode: Option, + pub document: u64, + pub source: String, + pub outline_request: Option, + pub navigation_request: Option, + pub navigation_source: String, + pub navigation_document: u64, + pub truncated: bool, + pub available: bool, + pub filter: String, +} + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + if state.navigation.document != state.document_generation + || state.navigation.source != state.document.text + { + state.request_outline(); + } + ui.horizontal(|ui| { + ui.label("Symbols"); + if ui + .small_button(icon::ARROW_CLOCKWISE) + .on_hover_text("Refresh symbols") + .clicked() + { + state.request_outline(); + } + }); + ui.add(egui::TextEdit::singleline(&mut state.navigation.filter).hint_text("Filter symbols")); + ui.separator(); + let filter = state.navigation.filter.to_lowercase(); + let mut actions = Vec::new(); + egui::ScrollArea::vertical().show(ui, |ui| { + for symbol in &state.navigation.symbols { + if !symbol.name.to_lowercase().contains(&filter) { + continue; + } + let glyph = match symbol.kind.as_str() { + "class" => icon::CUBE, + "function" => icon::FUNCTION, + _ => icon::BRACKETS_CURLY, + }; + ui.horizontal(|ui| { + ui.add_space(symbol.depth.min(8) as f32 * 12.0); + if ui + .link(format!("{glyph} {} :{}", symbol.name, symbol.line)) + .clicked() + { + actions.push(Action::GoToScriptLine { + document: state.navigation.document, + line: symbol.line, + }); + } + }); + } + if let Some(mode) = state.navigation.mode { + ui.separator(); + let label = if mode == NavigationMode::Definition { + "Definitions" + } else { + "References" + }; + ui.strong(format!("{label} ({})", state.navigation.locations.len())); + if !state.navigation.available { + ui.label("Install jedi in the selected Python environment to navigate code."); + } else if state.navigation.locations.is_empty() { + ui.label("No locations found."); + } + for location in &state.navigation.locations { + let path = location.path.as_deref().unwrap_or("Current document"); + let file = std::path::Path::new(path) + .file_name() + .map_or(path.into(), |name| name.to_string_lossy()); + if ui + .link(format!( + "{} · {}:{} · {} ({})", + file, + location.line, + location.column + 1, + location.name, + location.kind + )) + .on_hover_text(path) + .clicked() + { + if let Some(path) = &location.path { + actions.push(Action::OpenFileAt { + path: path.into(), + line: location.line, + }); + } else { + actions.push(Action::GoToScriptLine { + document: state.navigation.navigation_document, + line: location.line, + }); + } + } + } + if state.navigation.truncated { + ui.label("Showing the first 200 locations."); + } + } + }); + state.queue(actions); +} diff --git a/src/panels/objects.rs b/src/panels/objects.rs new file mode 100644 index 000000000..cb4b56556 --- /dev/null +++ b/src/panels/objects.rs @@ -0,0 +1,699 @@ +//! The object tree: shown CadQuery objects, the axis helpers and the +//! properties of the current object. + +use std::collections::HashSet; + +use egui::{Color32, RichText, Sense, Vec2}; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::panels::measurements; +use crate::scene::{Rgb, SceneNode}; +use crate::settings::Finish; +use crate::worker::protocol::{EntityMeasurement, ExportFormat, SelectorCandidate}; + +/// Height the object tree keeps while the property sheet is open. +const TREE_MIN_HEIGHT: f32 = 80.0; +/// Smallest useful property sheet. +const SHEET_MIN_HEIGHT: f32 = 70.0; + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let mut actions = Vec::new(); + + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(6, 4)) + .show(ui, |ui| { + ui.horizontal(|ui| { + if ui + .add_enabled( + !state.scene.is_empty(), + egui::Button::new(format!("{} Clear all", icon::TRASH)), + ) + .on_hover_text("Remove all objects") + .clicked() + { + actions.push(Action::ClearObjects); + } + if ui + .add_enabled( + !state.scene.selection.is_empty(), + egui::Button::new(icon::X), + ) + .on_hover_text("Remove the selected objects") + .clicked() + { + actions.push(Action::RemoveSelected); + } + ui.add_enabled_ui(!state.scene.is_empty(), |ui| { + ui.menu_button(format!("{} Export", icon::EXPORT), |ui| { + export_menu(ui, &mut actions); + }) + .response + .on_hover_text("Export the selection, or everything when nothing is selected"); + }); + if ui + .add_enabled( + !state.scene.is_empty(), + egui::Button::new(format!("{} Check", icon::CHECK_CIRCLE)), + ) + .on_hover_text( + "Check selected geometry, or everything when nothing is selected", + ) + .clicked() + { + actions.push(Action::CheckGeometry); + } + }); + ui.add_space(2.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let has_filter = !state.scene.filter.is_empty(); + let width = (ui.available_width() - if has_filter { 22.0 } else { 0.0 }).max(40.0); + ui.add( + egui::TextEdit::singleline(&mut state.scene.filter) + .hint_text(format!( + "{} Filter objects by name…", + icon::MAGNIFYING_GLASS + )) + .desired_width(width), + ); + if has_filter + && ui + .add(egui::Button::new(icon::X).frame(false)) + .on_hover_text("Clear object filter") + .clicked() + { + state.scene.filter.clear(); + } + }); + }); + ui.separator(); + + if !state.scene.selection.is_empty() { + property_sheet(ui, |ui| properties(ui, state, &mut actions)); + } + + // The tree takes what the properties panel leaves (panels must be + // followed by a central panel to keep out of their space). + egui::CentralPanel::default() + .frame(egui::Frame::NONE) + .show(ui, |ui| { + tree(ui, state, &mut actions); + }); + + state.queue(actions); +} + +/// Shows the property sheet at the bottom of `ui` and returns its rect. +/// +/// A panel grows to fit its contents, so on a short pane the sheet used to +/// take the whole height and the tree was drawn over it. The sheet now +/// scrolls instead, and its height is capped so the tree keeps +/// [`TREE_MIN_HEIGHT`] (or most of a very short pane). +fn property_sheet(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui)) -> egui::Rect { + let available = ui.available_height(); + let max_height = (available - TREE_MIN_HEIGHT).max(available * 0.4); + egui::Panel::bottom("object_properties") + .resizable(true) + .default_size(130.0) + .size_range(SHEET_MIN_HEIGHT.min(max_height)..=max_height) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(8, 6))) + .show(ui, |ui| { + egui::ScrollArea::vertical() + .id_salt("object_properties_scroll") + .auto_shrink([false, false]) + .min_scrolled_height(0.0) + .show(ui, add_contents); + }) + .response + .rect +} + +fn tree(ui: &mut egui::Ui, state: &mut AppState, actions: &mut Vec) { + egui::ScrollArea::both() + .auto_shrink([false, false]) + // The default minimum (64 px) would overflow a squeezed pane. + .min_scrolled_height(0.0) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + let default = state.default_color(); + let filter = state.scene.filter.trim().to_owned(); + egui::CollapsingHeader::new(RichText::new("CQ models").strong()) + .default_open(true) + .show(ui, |ui| { + if state.scene.is_empty() { + ui.weak(state.empty_view_hint()); + } else { + let isolated = state.scene.isolation_members(); + let mut any_shown = false; + for node in &state.scene.nodes { + if node_matches_filter(node, &filter) { + any_shown = true; + node_row( + ui, + state, + node, + default, + isolated.as_ref(), + &filter, + actions, + ); + } + } + if !any_shown { + ui.weak("No matching objects"); + } + } + }); + egui::CollapsingHeader::new(RichText::new("Helpers").strong()) + .default_open(true) + .show(ui, |ui| { + for axis in &mut state.scene.axes { + ui.horizontal(|ui| { + ui.checkbox(&mut axis.visible, ""); + swatch(ui, axis.color, 1.0); + ui.label(format!("{} axis", axis.name)); + }); + } + }); + }); +} + +/// Returns `true` when `node` or any of its descendants matches `query` +/// (case-insensitive substring match on the object/component name). +pub fn node_matches_filter(node: &SceneNode, query: &str) -> bool { + let trimmed = query.trim(); + if trimmed.is_empty() { + return true; + } + let needle = trimmed.to_lowercase(); + node.name.to_lowercase().contains(&needle) + || node + .children + .iter() + .any(|child| node_matches_filter(child, trimmed)) +} + +fn export_menu(ui: &mut egui::Ui, actions: &mut Vec) { + for format in ExportFormat::ALL { + if ui + .button(format!("Export as {}…", format.label())) + .clicked() + { + actions.push(Action::Export(format)); + } + } +} + +fn node_row( + ui: &mut egui::Ui, + state: &AppState, + node: &SceneNode, + default: Rgb, + isolated: Option<&HashSet<&str>>, + filter: &str, + actions: &mut Vec, +) { + let isolated_out = isolated.is_some_and(|members| !members.contains(node.key.as_str())); + let id = ui.make_persistent_id(("scene_node", &node.key)); + let mut header = |ui: &mut egui::Ui| { + let mut visible = node.visible; + if ui + .checkbox(&mut visible, "") + .on_hover_text("Show / hide") + .changed() + { + actions.push(Action::SetVisible { + key: node.key.clone(), + visible, + }); + } + if let Some((color, alpha)) = node.display_color(default) { + swatch(ui, color, alpha); + } + let selected = state.scene.is_selected(&node.key); + let invalid = state + .geometry_checks + .get(&node.key) + .is_some_and(|report| !report.valid); + let mut text = RichText::new(if invalid { + format!("{} {}", icon::WARNING_CIRCLE, node.name) + } else { + node.name.clone() + }); + if invalid { + text = text.color(ui.visuals().warn_fg_color); + } + if !node.visible || isolated_out { + text = text.weak(); + } + let response = ui + .selectable_label(selected, text) + .on_hover_text(if isolated_out { + format!("{} · hidden by the isolation", node.kind) + } else { + node.kind.clone() + }); + if response.clicked() { + actions.push(Action::Select { + key: Some(node.key.clone()), + topology: None, + extend: ui.input(|i| i.modifiers.command), + }); + } + if response.double_clicked() { + actions.push(Action::FitSelection); + } + response.context_menu(|ui| { + if !selected { + actions.push(Action::Select { + key: Some(node.key.clone()), + topology: None, + extend: false, + }); + } + if ui + .button(format!("{} Zoom to", icon::MAGNIFYING_GLASS_PLUS)) + .clicked() + { + actions.push(Action::FitSelection); + ui.close(); + } + if ui + .add_enabled( + node.line.is_some(), + egui::Button::new(format!("{} Go to Source", icon::ARROW_SQUARE_OUT)), + ) + .on_hover_text("The script line that created it") + .on_disabled_hover_text("No script line is known (shown from the console?)") + .clicked() + { + actions.push(Action::GoToSource { + key: node.key.clone(), + step: None, + }); + ui.close(); + } + let (label, visible) = if node.visible { + ("Hide", false) + } else { + ("Show", true) + }; + if ui + .button(format!( + "{} {label}", + if visible { icon::EYE } else { icon::EYE_SLASH } + )) + .clicked() + { + actions.push(Action::SetVisible { + key: node.key.clone(), + visible, + }); + ui.close(); + } + let isolating = isolated.is_some(); + if ui + .button(format!( + "{} {}", + icon::SELECTION_FOREGROUND, + if isolating { + "End Isolation" + } else { + "Isolate" + } + )) + .on_hover_text(if isolating { + "Show the other objects again" + } else { + "Show only the selected objects" + }) + .clicked() + { + actions.push(Action::ToggleIsolate); + ui.close(); + } + if ui.button(format!("{} Show All", icon::EYE)).clicked() { + actions.push(Action::ShowAll); + ui.close(); + } + ui.separator(); + if ui + .button(format!("{} Check Geometry", icon::CHECK_CIRCLE)) + .clicked() + { + actions.push(Action::CheckGeometry); + ui.close(); + } + export_menu(ui, actions); + ui.separator(); + if ui.button(format!("{} Remove", icon::TRASH)).clicked() { + actions.push(Action::RemoveSelected); + ui.close(); + } + }); + }; + + if node.children.is_empty() { + ui.horizontal(|ui| { + // Line up with rows that have an expand arrow. + ui.add_space(ui.spacing().icon_width + ui.spacing().item_spacing.x); + header(ui); + }); + } else { + let has_matching_child = !filter.is_empty() + && node + .children + .iter() + .any(|child| node_matches_filter(child, filter)); + let mut collapsing = + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true); + if has_matching_child { + collapsing.set_open(true); + } + collapsing.show_header(ui, header).body(|ui| { + for child in &node.children { + if !has_matching_child || node_matches_filter(child, filter) { + node_row(ui, state, child, default, isolated, filter, actions); + } + } + }); + } +} + +/// A small rounded square showing a color. +fn swatch(ui: &mut egui::Ui, color: Rgb, alpha: f32) { + let (rect, _) = ui.allocate_exact_size(Vec2::splat(12.0), Sense::hover()); + let [r, g, b] = color.map(|c| (c * 255.0).round() as u8); + let fill = Color32::from_rgba_unmultiplied(r, g, b, (alpha.max(0.25) * 255.0) as u8); + ui.painter().rect_filled(rect, 3.0, fill); + ui.painter().rect_stroke( + rect, + 3.0, + ui.visuals().widgets.noninteractive.bg_stroke, + egui::StrokeKind::Inside, + ); +} + +fn properties(ui: &mut egui::Ui, state: &mut AppState, actions: &mut Vec) { + let default = state.default_color(); + let show_edges = state.settings.viewer.show_edges; + let Some(key) = state.scene.selection.last().cloned() else { + return; + }; + let topology = state + .scene + .current_topology() + .filter(|selection| selection.node == key) + .cloned(); + let measured = topology.as_ref().and_then(|selection| { + state + .measurements + .result + .as_ref() + .and_then(|result| measurements::measurement_of(result, selection)) + .cloned() + }); + let measuring = state.measurements.loading; + let selector = topology + .as_ref() + .and_then(|_| state.selector.candidate().cloned()); + let Some(node) = state.scene.find_mut(&key) else { + return; + }; + + ui.strong(&node.name); + if let Some(selection) = &topology { + let label = node + .parts + .get(selection.part) + .and_then(|part| { + part.face_attributes.iter().find(|face| { + selection.entity.kind() == "Face" && face.id == selection.entity.identifier() + }) + }) + .and_then(|face| face.name.as_deref()) + .map_or_else( + || { + format!( + "{} {}", + selection.entity.kind(), + selection.entity.identifier() + ) + }, + str::to_owned, + ); + ui.label(format!("{label} · part {}", selection.part + 1)); + } + egui::Grid::new("object_properties_grid") + .num_columns(2) + .spacing([12.0, 6.0]) + .show(ui, |ui| { + if let Some(entity) = &measured { + measured_rows(ui, entity); + } else if topology.is_some() && measuring { + ui.label("Geometry"); + ui.horizontal(|ui| { + ui.spinner(); + ui.weak("Measuring…"); + }); + ui.end_row(); + } + if let Some(candidate) = &selector { + selector_row(ui, candidate, actions); + } + + ui.label("Type"); + ui.weak(&node.kind); + ui.end_row(); + if let Some(material) = node.parts.first().and_then(|part| part.material.as_ref()) { + ui.label("Material"); + ui.weak(format!( + "{} · {} {}", + material.name, material.density, material.density_unit + )); + ui.end_row(); + } + + if let Some(line) = node.line { + ui.label("Source"); + if ui + .link(format!("line {line} {}", icon::ARROW_SQUARE_OUT)) + .on_hover_text("Go to the script line that created it (Ctrl+Shift+G)") + .clicked() + { + actions.push(Action::GoToSource { + key: key.clone(), + step: None, + }); + } + ui.end_row(); + } + + ui.label("Visible"); + let mut visible = node.visible; + if ui.checkbox(&mut visible, "").changed() { + actions.push(Action::SetVisible { + key: key.clone(), + visible, + }); + } + ui.end_row(); + + if !node.parts.is_empty() { + let (color, alpha) = node + .parts + .first() + .map(|part| node.part_color(part, default)) + .unwrap_or((default, 1.0)); + let mut srgb = color.map(|c| (c * 255.0).round() as u8); + ui.label("Color"); + ui.horizontal(|ui| { + if ui.color_edit_button_srgb(&mut srgb).changed() { + node.overrides.color = Some(srgb.map(|c| f32::from(c) / 255.0)); + } + let overrides = &mut node.overrides; + if (overrides.color.is_some() || overrides.alpha.is_some()) + && ui + .small_button("Reset") + .on_hover_text("Use the script's colors") + .clicked() + { + overrides.color = None; + overrides.alpha = None; + } + }); + ui.end_row(); + + ui.label("Opacity"); + let mut opacity = alpha; + if ui + .add(egui::Slider::new(&mut opacity, 0.05..=1.0).fixed_decimals(2)) + .changed() + { + node.overrides.alpha = Some(opacity); + } + ui.end_row(); + + ui.label("Edges"); + ui.horizontal(|ui| { + let mut edges = node.overrides.edges.unwrap_or(show_edges); + if ui + .checkbox(&mut edges, "") + .on_hover_text( + "Show this object's edges in the Shaded and X-Ray modes \ + (Wireframe and Hidden Line always show them)", + ) + .changed() + { + node.overrides.edges = Some(edges); + } + if node.overrides.edges.is_some() + && ui + .small_button("Reset") + .on_hover_text("Follow Preferences > 3D View > Show edges") + .clicked() + { + node.overrides.edges = None; + } + }); + ui.end_row(); + + ui.label("Material"); + ui.horizontal(|ui| { + let current = node.finish(); + egui::ComboBox::from_id_salt(("finish", key.as_str())) + .selected_text(current.label()) + .show_ui(ui, |ui| { + for finish in Finish::ALL { + if ui + .selectable_label(finish == current, finish.label()) + .clicked() + { + node.overrides.finish = Some(finish); + } + } + }) + .response + .on_hover_text( + "How the faces are shaded: Default is the plain shading of a CAD \ + view; the materials have their own gloss, and metals reflect a \ + studio around the model. Scripts choose one with \ + show_object(..., material=\"matte plastic\")", + ); + if node.overrides.finish.is_some() + && ui + .small_button("Reset") + .on_hover_text("Use the script's material") + .clicked() + { + node.overrides.finish = None; + } + }); + ui.end_row(); + } + + let bounds = node.subtree_bounds(); + if !bounds.is_empty() { + let size = bounds.size(); + ui.label("Size"); + ui.weak(format!( + "{} × {} × {}", + number(size.x), + number(size.y), + number(size.z) + )); + ui.end_row(); + } + let triangles = node.triangle_count(); + if triangles > 0 { + ui.label("Triangles"); + ui.weak(triangles.to_string()); + ui.end_row(); + } + }); + if node.inspectable { + ui.add_space(4.0); + ui.weak(format!( + "{} Its construction stack is in CQ Inspector", + icon::STACK + )); + } +} + +/// The selector of the picked entities, with Copy and Insert buttons. +fn selector_row(ui: &mut egui::Ui, candidate: &SelectorCandidate, actions: &mut Vec) { + ui.label("Selector"); + ui.horizontal(|ui| { + let text = RichText::new(&candidate.expression).monospace(); + let label = ui.add(egui::Label::new(text).truncate()); + let tip = if candidate.index_based { + format!( + "{} (by index: may change with the model)", + candidate.description + ) + } else { + candidate.description.clone() + }; + label.on_hover_text(tip); + if ui + .small_button(icon::COPY) + .on_hover_text("Copy the selector") + .clicked() + { + actions.push(Action::CopySelector); + } + if ui + .small_button(icon::CURSOR_TEXT) + .on_hover_text("Insert the selector at the editor's cursor") + .clicked() + { + actions.push(Action::InsertSelector); + } + }); + ui.end_row(); +} + +/// The exact size and position of the selected face, edge or vertex. +fn measured_rows(ui: &mut egui::Ui, entity: &EntityMeasurement) { + let mut row = |label: &str, value: String| { + ui.label(label); + ui.monospace(value); + ui.end_row(); + }; + row("Geometry", measurements::title_case(&entity.geometry_type)); + if let Some(area) = entity.area { + row("Area", compact(area)); + } + if let Some(length) = entity.length { + row("Length", compact(length)); + } + if let Some(radius) = entity.radius { + row("Radius", compact(radius)); + } + let point = |[x, y, z]: [f64; 3]| format!("({}, {}, {})", compact(x), compact(y), compact(z)); + match entity.position { + Some(position) => row("Position", point(position)), + None => row("Center", point(entity.center)), + } +} + +/// A short number for the narrow property sheet: four decimals, without +/// the rounding noise of exact geometry (`-6.9e-18` is 0). The +/// Measurements panel keeps the full precision. +fn compact(value: f64) -> String { + let text = format!("{value:.4}"); + let text = text.trim_end_matches('0').trim_end_matches('.'); + if text == "-0" { "0" } else { text }.to_owned() +} + +/// Compact number formatting for sizes. +fn number(value: f32) -> String { + let text = format!("{value:.3}"); + text.trim_end_matches('0').trim_end_matches('.').to_owned() +} + +#[cfg(test)] +#[path = "../../tests/rust/panels/test_objects.rs"] +mod tests; diff --git a/src/panels/parameters.rs b/src/panels/parameters.rs new file mode 100644 index 000000000..6e6fd7ecc --- /dev/null +++ b/src/panels/parameters.rs @@ -0,0 +1,256 @@ +//! The script's top-level numbers as spin boxes and sliders. A change +//! rewrites the literal in the script and renders again: the script stays +//! the source of truth, and undo works as for any edit. + +use std::collections::HashMap; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::ops::RangeInclusive; + +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::parameters::{self, Parameter}; + +#[derive(Default)] +pub struct ParametersState { + /// The parameters of the text with this hash. + parsed: Option<(u64, Vec)>, + /// Reference values parsed from the document's saved/opened baseline. + reference_parsed: Option<(u64, HashMap)>, + /// Initial values of parameters added during the current editing session. + session_initial: HashMap, + /// Slider ranges of parameters without a commented range, chosen from + /// their first value so that the slider does not move under a drag. + ranges: HashMap>, +} + +impl ParametersState { + /// The parameters of `text`, parsed once per version of the text. + pub fn of(&mut self, text: &str) -> &[Parameter] { + let hash = text_hash(text); + if self + .parsed + .as_ref() + .is_none_or(|(parsed, _)| *parsed != hash) + { + self.parsed = Some((hash, parameters::parameters(text))); + } + &self.parsed.as_ref().expect("parsed above").1 + } + + /// Updates reference values from `baseline_text` (the opened or last-saved + /// script) and records first-seen values for newly added parameters. + pub fn update_references(&mut self, baseline_text: &str, current: &[Parameter]) { + let hash = text_hash(baseline_text); + if self + .reference_parsed + .as_ref() + .is_none_or(|(parsed, _)| *parsed != hash) + { + let map: HashMap = parameters::parameters(baseline_text) + .into_iter() + .map(|parameter| (parameter.name, parameter.value)) + .collect(); + for (name, value) in &map { + self.session_initial.insert(name.clone(), *value); + } + self.reference_parsed = Some((hash, map)); + } + for parameter in current { + self.session_initial + .entry(parameter.name.clone()) + .or_insert(parameter.value); + } + } + + /// Reference value for `name` (from the saved baseline, or its first seen value). + pub fn reference_value(&self, name: &str) -> Option { + self.reference_parsed + .as_ref() + .and_then(|(_, map)| map.get(name).copied()) + .or_else(|| self.session_initial.get(name).copied()) + } + + /// True when `parameter` differs from its reference value. + pub fn is_modified(&self, parameter: &Parameter) -> bool { + self.reference_value(¶meter.name) + .is_some_and(|reference| (reference - parameter.value).abs() > 1e-12) + } + + /// True when any parameter in `current` differs from its reference value. + pub fn any_modified(&self, current: &[Parameter]) -> bool { + current.iter().any(|parameter| self.is_modified(parameter)) + } + + /// The slider range of `parameter`: its commented range, or one around + /// its first value, widened to keep the current value inside. + pub fn slider_range(&mut self, parameter: &Parameter) -> RangeInclusive { + if let Some(range) = ¶meter.range { + return range.clone(); + } + let value = parameter.value; + let range = self + .ranges + .entry(parameter.name.clone()) + .or_insert_with(|| automatic_range(value, parameter.integer)); + if !range.contains(&value) { + *range = range.start().min(value)..=range.end().max(value); + } + range.clone() + } +} + +fn text_hash(text: &str) -> u64 { + let mut hasher = DefaultHasher::new(); + text.hash(&mut hasher); + hasher.finish() +} + +/// Zero to twice the value (or twice the value to zero), at least 10 wide. +fn automatic_range(value: f64, integer: bool) -> RangeInclusive { + let span = (2.0 * value.abs()).max(10.0); + let span = if integer { span.ceil() } else { span }; + if value < 0.0 { + -span..=0.0 + } else if value == 0.0 { + -span / 2.0..=span / 2.0 + } else { + 0.0..=span + } +} + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let mut actions = Vec::new(); + let editable = !state.is_debugging(); + // Those of the script F5 runs, which may be another tab's. + let target = state.run_target(); + let (text, saved_text) = state.document_of(target).map_or_else( + || (String::new(), String::new()), + |document| (document.text.clone(), document.saved_text().to_owned()), + ); + let found = state.parameters.of(&text).to_vec(); + state.parameters.update_references(&saved_text, &found); + + if found.is_empty() { + super::empty_state( + ui, + icon::SLIDERS_HORIZONTAL, + "Top-level numbers of the script, such as width = 40, appear here", + ); + return; + } + + let any_modified = state.parameters.any_modified(&found); + + egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.add_enabled_ui(editable, |ui| { + if any_modified { + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .button(format!("{} Restore all", icon::ARROW_COUNTER_CLOCKWISE)) + .on_hover_text( + "Restore all modified parameters to their initial values", + ) + .clicked() + { + actions.push(Action::ResetParameters); + } + }); + }); + ui.add_space(4.0); + } + egui::Grid::new("parameters_grid") + .num_columns(4) + .spacing([10.0, 6.0]) + .striped(true) + .show(ui, |ui| { + for parameter in &found { + row(ui, state, parameter, &mut actions); + } + }); + }); + ui.add_space(6.0); + if editable { + ui.weak( + "A change rewrites the number in the script and renders again. \ + A comment such as # [10, 100] or # [0, 5, 0.5] sets the slider's \ + range and step.", + ); + } else { + ui.weak("Parameters can be changed once debugging ends."); + } + }); + state.queue(actions); +} + +fn row(ui: &mut egui::Ui, state: &mut AppState, parameter: &Parameter, actions: &mut Vec) { + let modified = state.parameters.is_modified(parameter); + let label = if modified { + format!("{}*", parameter.name) + } else { + parameter.name.clone() + }; + let name = ui + .link(label) + .on_hover_text(format!("Line {}: go to it", parameter.line)); + if name.clicked() { + actions.push(Action::GoToLine(parameter.line)); + } + + let precision = parameter.precision(); + let mut value = parameter.value; + let mut drag = egui::DragValue::new(&mut value) + .speed(parameter.drag_speed()) + .min_decimals(precision) + .max_decimals(precision); + if let Some(range) = ¶meter.range { + drag = drag.range(range.clone()); + } + let mut changed = ui.add(drag).changed(); + + let range = state.parameters.slider_range(parameter); + let mut slider = egui::Slider::new(&mut value, range).show_value(false); + if parameter.integer { + slider = slider.integer(); + } else if let Some(step) = parameter.step { + slider = slider.step_by(step); + } + changed |= ui.add(slider).changed(); + + if let Some(reference) = state + .parameters + .reference_value(¶meter.name) + .filter(|_| modified) + { + if ui + .small_button(icon::ARROW_COUNTER_CLOCKWISE) + .on_hover_text(format!("Restore to {}", parameter.literal_for(reference))) + .clicked() + { + actions.push(Action::SetParameter { + name: parameter.name.clone(), + line: parameter.line, + value: reference, + }); + } + } else { + ui.label(""); + } + ui.end_row(); + + if changed && value != parameter.value { + actions.push(Action::SetParameter { + name: parameter.name.clone(), + line: parameter.line, + value, + }); + } +} + +#[cfg(test)] +#[path = "../../tests/rust/panels/test_parameters.rs"] +mod tests; diff --git a/src/panels/project.rs b/src/panels/project.rs new file mode 100644 index 000000000..406fde789 --- /dev/null +++ b/src/panels/project.rs @@ -0,0 +1,352 @@ +//! The Project panel: the project folder's file tree. A click opens a +//! script in a tab or folds a folder; the context menus create, rename and +//! delete files and folders and choose the main script, which F5 runs. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use egui::{Align2, FontId, RichText, Sense, Vec2}; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::project::{self, Row}; + +/// Indentation of each level of the tree, in points. +const INDENT: f32 = 14.0; + +/// How an open file shows in the tree. +#[derive(Clone, Copy)] +struct OpenFile { + active: bool, + modified: bool, +} + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let mut actions = Vec::new(); + let open: HashMap = state + .tabs() + .into_iter() + .filter_map(|tab| { + let file = OpenFile { + active: tab.active, + modified: tab.modified, + }; + Some((tab.path?, file)) + }) + .collect(); + let Some(project) = &mut state.project else { + no_folder(ui, &mut actions); + state.queue(actions); + return; + }; + let root = project.root().to_path_buf(); + let main = project.main.clone(); + + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(6, 4)) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + let tool = |ui: &mut egui::Ui, glyph: &str, tip: &str| { + ui.add(egui::Button::new(glyph).frame(false)) + .on_hover_text(tip) + .clicked() + }; + if tool(ui, icon::FILE_PLUS, "New file") { + actions.push(Action::NewFileIn(root.clone())); + } + if tool(ui, icon::FOLDER_PLUS, "New folder") { + actions.push(Action::NewFolderIn(root.clone())); + } + if tool(ui, icon::ARROWS_CLOCKWISE, "Refresh") { + actions.push(Action::RefreshProject); + } + if tool(ui, icon::ARROWS_IN_LINE_VERTICAL, "Collapse all folders") { + project.collapse_all(); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if tool(ui, icon::X, "Close the folder") { + actions.push(Action::CloseFolder); + } + }); + }); + let main_text = match &main { + Some(main) => format!( + "{} F5 renders {}", + icon::PLAY, + project.relative(main).display() + ), + None => format!("{} No main script: F5 renders the file shown", icon::PLAY), + }; + ui.add(egui::Label::new(RichText::new(main_text).small().weak()).truncate()) + .on_hover_text( + "While a file of this folder is shown, F5 renders the main script. \ + Right-click a script to choose it.", + ); + ui.add_space(2.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let has_filter = !project.filter.is_empty(); + let width = (ui.available_width() - if has_filter { 22.0 } else { 0.0 }).max(40.0); + ui.add( + egui::TextEdit::singleline(&mut project.filter) + .hint_text(format!("{} Filter files…", icon::MAGNIFYING_GLASS)) + .desired_width(width), + ); + if has_filter + && ui + .add(egui::Button::new(icon::X).frame(false)) + .on_hover_text("Clear file search") + .clicked() + { + project.filter.clear(); + } + }); + }); + ui.separator(); + + let searching = !project.filter.trim().is_empty(); + let rows = if searching { + project.search_rows(&project.filter.clone()) + } else { + project.rows() + }; + if searching && rows.is_empty() { + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(8, 6)) + .show(ui, |ui| { + ui.weak("No matching files"); + }); + } + let row_height = ui.text_style_height(&egui::TextStyle::Body) + 6.0; + let mut toggled = None; + egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show_rows(ui, row_height, rows.len(), |ui, range| { + ui.spacing_mut().item_spacing.y = 0.0; + for row in &rows[range] { + let file = open.get(&row.entry.path).copied(); + let is_main = main.as_deref() == Some(row.entry.path.as_path()); + let display_name = if searching { + project + .relative(&row.entry.path) + .to_string_lossy() + .replace('\\', "/") + } else { + row.entry.name.clone() + }; + let response = row_ui(ui, row, &display_name, row_height, file, is_main); + if response.clicked() { + if row.entry.is_dir { + toggled = Some(row.entry.path.clone()); + } else if project::is_editable(&row.entry.path) { + actions.push(Action::OpenPath(row.entry.path.clone())); + } + } + response.context_menu(|ui| { + context_menu(ui, row, &root, is_main, &mut actions); + }); + } + }); + if let Some(folder) = toggled { + project.toggle(&folder); + } + + // The empty space below the tree has the folder's own menu. + let rest = ui.available_rect_before_wrap(); + if rest.height() > 0.0 { + ui.allocate_rect(rest, Sense::click()) + .context_menu(|ui| folder_items(ui, &root, &mut actions)); + } + state.queue(actions); +} + +fn no_folder(ui: &mut egui::Ui, actions: &mut Vec) { + ui.vertical_centered(|ui| { + ui.add_space(ui.available_height() / 3.0); + ui.label( + RichText::new("Open a folder to see its scripts here") + .color(ui.visuals().weak_text_color()), + ); + ui.add_space(6.0); + if ui + .button(format!("{} Open Folder…", icon::FOLDER_OPEN)) + .clicked() + { + actions.push(Action::OpenFolder); + } + }); +} + +/// One line of the tree, painted by hand so the whole width is a target. +fn row_ui( + ui: &mut egui::Ui, + row: &Row, + display_name: &str, + height: f32, + file: Option, + is_main: bool, +) -> egui::Response { + let (rect, response) = + ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::click()); + let visuals = ui.visuals(); + let active = file.is_some_and(|file| file.active); + if active { + ui.painter() + .rect_filled(rect, 2.0, visuals.selection.bg_fill.gamma_multiply(0.6)); + } else if response.hovered() { + ui.painter() + .rect_filled(rect, 2.0, visuals.widgets.hovered.weak_bg_fill); + } + + let entry = &row.entry; + let caret = match (entry.is_dir, row.expanded) { + (true, true) => icon::CARET_DOWN, + (true, false) => icon::CARET_RIGHT, + (false, _) => " ", + }; + let glyph = if entry.is_dir { + if row.expanded { + icon::FOLDER_OPEN + } else { + icon::FOLDER + } + } else if is_main { + icon::PLAY_CIRCLE + } else if project::is_script(&entry.path) { + icon::FILE_PY + } else if project::is_editable(&entry.path) { + icon::FILE_TEXT + } else { + icon::FILE + }; + let editable = entry.is_dir || project::is_editable(&entry.path); + let color = if is_main { + visuals.strong_text_color() + } else if editable { + visuals.text_color() + } else { + visuals.weak_text_color() + }; + let modified = if file.is_some_and(|file| file.modified) { + " •" + } else { + "" + }; + let font = FontId::proportional(ui.text_style_height(&egui::TextStyle::Body) * 0.95); + let left = rect.left() + 4.0 + row.depth as f32 * INDENT; + let painter = ui.painter_at(rect); + painter.text( + egui::pos2(left, rect.center().y), + Align2::LEFT_CENTER, + format!("{caret} {glyph} {display_name}{modified}"), + font, + color, + ); + + let hint = if entry.is_dir { + entry.path.display().to_string() + } else if is_main { + format!("{}\nThe main script: F5 renders it", entry.path.display()) + } else if editable { + entry.path.display().to_string() + } else { + format!("{}\nNot a script or text file", entry.path.display()) + }; + response.on_hover_text_at_pointer(hint) +} + +fn context_menu( + ui: &mut egui::Ui, + row: &Row, + root: &Path, + is_main: bool, + actions: &mut Vec, +) { + let path = &row.entry.path; + let mut item = |ui: &mut egui::Ui, glyph: &str, label: &str, action: Action| { + if ui.button(format!("{glyph} {label}")).clicked() { + actions.push(action); + ui.close(); + } + }; + if row.entry.is_dir { + folder_items(ui, path, actions); + } else { + if project::is_editable(path) { + item( + ui, + icon::FILE_ARROW_UP, + "Open", + Action::OpenPath(path.clone()), + ); + } + if project::is_script(path) { + if is_main { + item( + ui, + icon::PLAY_CIRCLE, + "Clear Main Script", + Action::SetMainScript(None), + ); + } else { + item( + ui, + icon::PLAY_CIRCLE, + "Set as Main Script", + Action::SetMainScript(Some(path.clone())), + ); + } + } + ui.separator(); + let folder = path.parent().unwrap_or(root).to_path_buf(); + item(ui, icon::FILE_PLUS, "New File…", Action::NewFileIn(folder)); + } + if path != root { + ui.separator(); + let mut item = |ui: &mut egui::Ui, glyph: &str, label: &str, action: Action| { + if ui.button(format!("{glyph} {label}")).clicked() { + actions.push(action); + ui.close(); + } + }; + item( + ui, + icon::PENCIL_SIMPLE, + "Rename…", + Action::RenamePath(path.clone()), + ); + item(ui, icon::TRASH, "Delete…", Action::DeletePath(path.clone())); + } + ui.separator(); + if ui.button(format!("{} Copy Path", icon::COPY)).clicked() { + ui.ctx().copy_text(path.display().to_string()); + ui.close(); + } + if ui + .button(format!("{} Show in File Manager", icon::FOLDER_OPEN)) + .clicked() + { + actions.push(Action::RevealPath(path.clone())); + ui.close(); + } +} + +/// What can be done in a folder. +fn folder_items(ui: &mut egui::Ui, folder: &Path, actions: &mut Vec) { + if ui + .button(format!("{} New File…", icon::FILE_PLUS)) + .clicked() + { + actions.push(Action::NewFileIn(folder.to_path_buf())); + ui.close(); + } + if ui + .button(format!("{} New Folder…", icon::FOLDER_PLUS)) + .clicked() + { + actions.push(Action::NewFolderIn(folder.to_path_buf())); + ui.close(); + } +} diff --git a/src/panels/traceback.rs b/src/panels/traceback.rs new file mode 100644 index 000000000..3b4c39624 --- /dev/null +++ b/src/panels/traceback.rs @@ -0,0 +1,152 @@ +//! The error of the last run. Clicking a frame jumps to its line: in the +//! script that ran, or in the imported module, which opens in a tab. + +use std::path::Path; + +use egui::RichText; +use egui_extras::{Column, TableBuilder}; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; +use crate::worker::protocol::SCRIPT_FILENAME; + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let Some(error) = &state.traceback else { + super::empty_state(ui, icon::CHECK_CIRCLE, "No errors"); + return; + }; + let mut actions = Vec::new(); + let script = state.traceback_document; + let script_name = script + .and_then(|document| state.document_of(document)) + .map_or_else(|| "script".to_owned(), |document| document.display_name()); + + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(8, 6)) + .show(ui, |ui| { + ui.horizontal(|ui| { + let error_color = ui.visuals().error_fg_color; + ui.label(RichText::new(icon::WARNING_CIRCLE).color(error_color)); + let summary = format!("{}: {}", error.type_name, error.message); + ui.add( + egui::Label::new(RichText::new(&summary).color(error_color).strong()) + .truncate(), + ) + .on_hover_text(&summary); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .button(icon::COPY) + .on_hover_text("Copy the full traceback") + .clicked() + { + ui.ctx().copy_text(error.text.clone()); + } + }); + }); + }); + + if let Some(diagnostic) = &error.diagnostic { + ui.group(|ui| { + ui.horizontal(|ui| { + let operation = diagnostic.receiver.as_ref().map_or_else( + || diagnostic.operation.clone(), + |receiver| format!("{receiver}.{}", diagnostic.operation), + ); + ui.strong(format!("Possible CAD causes · {operation}")); + if ui.button(format!("Line {}", diagnostic.line)).clicked() { + if let Some(document) = script { + actions.push(Action::GoToScriptLine { + document, + line: diagnostic.line, + }); + } else { + actions.push(Action::GoToLine(diagnostic.line)); + } + } + }); + for hint in &diagnostic.hints { + ui.label(format!("• {hint}")); + } + ui.weak("These are suggestions; the original traceback below is unchanged."); + }); + ui.add_space(4.0); + } + + let row_height = ui.text_style_height(&egui::TextStyle::Body) + 6.0; + TableBuilder::new(ui) + .striped(true) + .resizable(true) + .auto_shrink([false, false]) + .sense(egui::Sense::click()) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::initial(140.0).at_least(60.0).clip(true)) + .column(Column::initial(50.0).at_least(40.0)) + .column(Column::initial(110.0).at_least(50.0).clip(true)) + .column(Column::remainder().clip(true)) + .header(row_height, |mut header| { + for title in ["File", "Line", "Function", "Code"] { + header.col(|ui| { + ui.strong(title); + }); + } + }) + .body(|body| { + body.rows(row_height, error.frames.len(), |mut row| { + let frame = &error.frames[row.index()]; + let in_script = frame.file == SCRIPT_FILENAME; + // A module of the project, or any Python file that exists. + let module = (!in_script) + .then(|| Path::new(&frame.file)) + .filter(|path| path.is_absolute() && path.is_file()); + let file = if in_script { + script_name.as_str() + } else { + frame.file.as_str() + }; + // Not selectable: a selectable label takes the clicks on + // its text away from the row, which jumps to the line. + let cell = |text: RichText| egui::Label::new(text).selectable(false); + row.col(|ui| { + if in_script { + ui.add(cell(RichText::new(file).strong())); + } else if module.is_some() { + let name = Path::new(file) + .file_name() + .map_or_else(|| file.to_owned(), |n| n.to_string_lossy().into_owned()); + ui.add(cell(RichText::new(name))).on_hover_text(format!( + "{file}\nClick to open it at line {}", + frame.line + )); + } else { + ui.add(cell(RichText::new(file).weak())) + .on_hover_text(&frame.file); + } + }); + row.col(|ui| { + ui.add(cell(RichText::new(frame.line.to_string()))); + }); + row.col(|ui| { + ui.add(cell(RichText::new(&frame.function).weak())); + }); + row.col(|ui| { + ui.add(cell(RichText::new(&frame.code).monospace()).truncate()); + }); + if row.response().clicked() { + match (in_script, script, module) { + (true, Some(document), _) => actions.push(Action::GoToScriptLine { + document, + line: frame.line, + }), + (true, None, _) => actions.push(Action::GoToLine(frame.line)), + (false, _, Some(path)) => actions.push(Action::OpenFileAt { + path: path.to_path_buf(), + line: frame.line, + }), + (false, _, None) => {} + } + } + }); + }); + state.queue(actions); +} diff --git a/src/panels/variables.rs b/src/panels/variables.rs new file mode 100644 index 000000000..2b3c1073c --- /dev/null +++ b/src/panels/variables.rs @@ -0,0 +1,213 @@ +//! Variables of the last run, or of the paused frame while debugging. +//! +//! The value column takes the width the name and type columns leave, and +//! clicking a row shows its whole value below the table, where it can be +//! read, selected and copied. + +use egui::RichText; +use egui_extras::{Column, TableBuilder}; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::worker::protocol::Variable; + +/// The value column never gets narrower than this. +const MIN_VALUE_WIDTH: f32 = 80.0; +const DETAIL_DEFAULT_HEIGHT: f32 = 90.0; +const DETAIL_MIN_HEIGHT: f32 = 48.0; + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let filter_id = ui.id().with("variables_filter"); + let selected_id = ui.id().with("variables_selected"); + let mut filter: String = ui.data_mut(|d| d.get_temp(filter_id).unwrap_or_default()); + let mut selected: Option = ui.data_mut(|d| d.get_temp(selected_id)).flatten(); + + egui::Frame::NONE + .inner_margin(egui::Margin::symmetric(6, 4)) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.label(icon::FUNNEL_SIMPLE); + ui.add( + egui::TextEdit::singleline(&mut filter) + .hint_text("Filter by name or type") + .desired_width(f32::INFINITY), + ); + }); + }); + ui.data_mut(|d| d.insert_temp(filter_id, filter.clone())); + + if state.variables.is_empty() { + super::empty_state(ui, icon::BRACKETS_CURLY, "Variables appear after a run"); + return; + } + + let needle = filter.to_lowercase(); + let rows: Vec<&Variable> = state + .variables + .iter() + .filter(|v| { + needle.is_empty() + || v.name.to_lowercase().contains(&needle) + || v.type_name.to_lowercase().contains(&needle) + }) + .collect(); + + table_and_detail(ui, &rows, &mut selected); + ui.data_mut(|d| d.insert_temp(selected_id, selected)); +} + +/// The table and, for the selected row, its detail view below. Returns +/// where the table's rows and the detail view ended up. +fn table_and_detail( + ui: &mut egui::Ui, + rows: &[&Variable], + selected: &mut Option, +) -> (egui::Rect, Option) { + // A selection that is no longer listed (another run, the filter) closes + // the detail view. + let detail = selected + .as_deref() + .and_then(|name| rows.iter().copied().find(|v| v.name == name)); + if detail.is_none() { + *selected = None; + } + let detail_rect = detail.map(|variable| { + let max_height = (ui.available_height() * 0.6).max(DETAIL_MIN_HEIGHT); + egui::Panel::bottom("variable_detail") + .resizable(true) + .default_size(DETAIL_DEFAULT_HEIGHT) + .size_range(DETAIL_MIN_HEIGHT..=max_height) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(8, 6))) + .show(ui, |ui| { + if !detail_view(ui, variable) { + *selected = None; + } + }) + .response + .rect + }); + + let table_rect = egui::CentralPanel::default() + .frame(egui::Frame::NONE) + .show(ui, |ui| table(ui, rows, selected)) + .inner; + (table_rect, detail_rect) +} + +/// Column widths for a panel `width` wide: name and type get a share of it, +/// so the value column keeps room even in a narrow pane. +pub(crate) fn column_widths(width: f32) -> (f32, f32) { + let name = (width * 0.3).clamp(50.0, 160.0); + let type_name = (width * 0.22).clamp(40.0, 110.0); + (name, type_name) +} + +/// Returns the rectangle the rows are shown in. +fn table(ui: &mut egui::Ui, rows: &[&Variable], selected: &mut Option) -> egui::Rect { + let row_height = ui.text_style_height(&egui::TextStyle::Body) + 4.0; + let (name_width, type_width) = column_widths(ui.available_width()); + TableBuilder::new(ui) + // Not the id of the earlier fixed-width layout, whose remembered + // widths left no room for values. + .id_salt("variables_table") + .striped(true) + .resizable(true) + .auto_shrink([false, false]) + // The default minimum (200 points) made the table grow over the + // detail view in a short pane; it scrolls instead. + .min_scrolled_height(0.0) + .sense(egui::Sense::click()) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::initial(name_width).at_least(40.0).clip(true)) + .column(Column::initial(type_width).at_least(36.0).clip(true)) + .column(Column::remainder().at_least(MIN_VALUE_WIDTH).clip(true)) + .header(row_height + 2.0, |mut header| { + for title in ["Name", "Type", "Value"] { + header.col(|ui| { + ui.strong(title); + }); + } + }) + .body(|body| { + body.rows(row_height, rows.len(), |mut row| { + let variable = rows[row.index()]; + let is_selected = selected.as_deref() == Some(variable.name.as_str()); + row.set_selected(is_selected); + // Not selectable: a selectable label takes the clicks on + // its text away from the row. + row.col(|ui| { + ui.add(egui::Label::new(&variable.name).selectable(false)); + }); + row.col(|ui| { + ui.add( + egui::Label::new(RichText::new(&variable.type_name).weak()) + .selectable(false), + ); + }); + row.col(|ui| { + ui.add( + egui::Label::new(RichText::new(&variable.value).monospace()) + .truncate() + .selectable(false), + ); + }); + let response = row.response(); + // Selects; the detail view's × closes it. + if response.clicked() { + *selected = Some(variable.name.clone()); + } + response + .on_hover_text("Click to see the whole value") + .context_menu(|ui| { + if ui.button(format!("{} Copy value", icon::COPY)).clicked() { + ui.ctx().copy_text(variable.value.clone()); + ui.close(); + } + if ui.button(format!("{} Copy name", icon::COPY)).clicked() { + ui.ctx().copy_text(variable.name.clone()); + ui.close(); + } + }); + }); + }) + .inner_rect +} + +/// The whole value of `variable`. Returns `false` once closed. +fn detail_view(ui: &mut egui::Ui, variable: &Variable) -> bool { + let mut open = true; + ui.horizontal(|ui| { + ui.strong(&variable.name); + ui.weak(&variable.type_name); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(icon::X).on_hover_text("Close").clicked() { + open = false; + } + if ui + .button(icon::COPY) + .on_hover_text("Copy the value") + .clicked() + { + ui.ctx().copy_text(variable.value.clone()); + } + }); + }); + egui::ScrollArea::vertical() + .id_salt("variable_detail_scroll") + .auto_shrink([false, false]) + // The default minimum (64 points) would grow the panel over the + // table in a short pane. + .min_scrolled_height(0.0) + .show(ui, |ui| { + ui.add( + egui::Label::new(RichText::new(&variable.value).monospace()) + .wrap() + .selectable(true), + ); + }); + open +} + +#[cfg(test)] +#[path = "../../tests/rust/panels/test_variables.rs"] +mod tests; diff --git a/src/parameters.rs b/src/parameters.rs new file mode 100644 index 000000000..e12b58b78 --- /dev/null +++ b/src/parameters.rs @@ -0,0 +1,346 @@ +//! The script's parameters: top-level assignments of a number literal, such +//! as `width = 40`. The Parameters panel shows them as spin boxes and +//! sliders and changes the literal in the script, which stays the only +//! source of truth. +//! +//! Only statements that start a top-level line are recognized: lines inside +//! a function, a block, a bracketed expression, a triple-quoted string or a +//! backslash continuation are skipped, as are expressions, chained or +//! multiple assignments and other kinds of literals. A trailing comment may +//! give the slider's range: `# [10, 100]`, `# [0, 5, 0.5]` (with a step) or +//! `# 10..100`. + +use std::ops::{Range, RangeInclusive}; + +#[derive(Clone, Debug, PartialEq)] +pub struct Parameter { + pub name: String, + /// 1-based line of the assignment. + pub line: usize, + /// Byte range of the literal in the text, including its sign. + pub literal: Range, + pub value: f64, + /// Written as an integer; it stays one. + pub integer: bool, + /// Digits after the point in the literal (0 for integers). + pub decimals: usize, + /// Written with an exponent, such as `1e-3`. + pub exponent: bool, + /// From the trailing comment. + pub range: Option>, + pub step: Option, +} + +impl Parameter { + /// The literal to write for `value`, in the style of the current one. + pub fn literal_for(&self, value: f64) -> String { + let value = match &self.range { + Some(range) => value.clamp(*range.start(), *range.end()), + None => value, + }; + if self.integer { + return format!("{}", value.round() as i64); + } + if self.exponent { + return format!("{value:e}"); + } + let decimals = self.precision(); + let text = format!("{value:.decimals$}"); + if text.starts_with('-') && text[1..].bytes().all(|b| b == b'0' || b == b'.') { + text[1..].to_owned() + } else { + text + } + } + + /// Decimals a float keeps: those of the literal and of the step. + pub fn precision(&self) -> usize { + if self.integer { + return 0; + } + let step = self.step.map_or(0, decimals_of); + self.decimals.max(step).max(1) + } + + /// Change per pixel of a drag: a whole number of the smallest unit + /// written, about a 200th of the value. + pub fn drag_speed(&self) -> f64 { + if let Some(step) = self.step { + return step; + } + let unit = if self.integer { + 1.0 + } else { + 10f64.powi(-(self.precision() as i32)) + }; + unit * (self.value.abs() / 200.0 / unit).round().max(1.0) + } +} + +/// The parameters of `text`, in line order. +pub fn parameters(text: &str) -> Vec { + let mut found = Vec::new(); + let mut scanner = Scanner::default(); + let mut offset = 0; + for (index, line) in text.split('\n').enumerate() { + if scanner.at_statement_start() + && let Some(parameter) = parse_line(line, offset, index + 1) + { + found.push(parameter); + } + scanner.scan(line); + offset += line.len() + 1; + } + found +} + +/// Where each line starts: inside a string, brackets or a continuation. +#[derive(Default)] +struct Scanner { + /// The quote character of an open triple-quoted string. + triple: Option, + depth: usize, + continued: bool, +} + +impl Scanner { + fn at_statement_start(&self) -> bool { + self.triple.is_none() && self.depth == 0 && !self.continued + } + + fn scan(&mut self, line: &str) { + let bytes = line.as_bytes(); + let mut i = 0; + let mut quote: Option = None; + self.continued = false; + while i < bytes.len() { + let byte = bytes[i]; + if let Some(q) = self.triple { + if byte == b'\\' { + i += 2; + continue; + } + if bytes[i..].starts_with(&[q, q, q]) { + self.triple = None; + i += 3; + continue; + } + i += 1; + continue; + } + if let Some(q) = quote { + if byte == b'\\' { + i += 2; + continue; + } + if byte == q { + quote = None; + } + i += 1; + continue; + } + match byte { + b'#' => break, + b'"' | b'\'' => { + if bytes[i..].starts_with(&[byte, byte, byte]) { + self.triple = Some(byte); + i += 3; + continue; + } + quote = Some(byte); + } + b'(' | b'[' | b'{' => self.depth += 1, + b')' | b']' | b'}' => self.depth = self.depth.saturating_sub(1), + b'\\' if i + 1 == bytes.len() => self.continued = true, + _ => {} + } + i += 1; + } + } +} + +/// `name = number`, `name: int = number` or `name: float = number`, with +/// an optional comment, starting at column 0. +fn parse_line(line: &str, offset: usize, number: usize) -> Option { + let line = line.strip_suffix('\r').unwrap_or(line); + let mut cursor = Cursor { text: line, at: 0 }; + let name = cursor.identifier()?; + if name.starts_with("__") { + return None; + } + cursor.spaces(); + if cursor.eat(":") { + cursor.spaces(); + let annotation = cursor.identifier()?; + if annotation != "int" && annotation != "float" { + return None; + } + cursor.spaces(); + } + if !cursor.eat("=") || cursor.peek() == Some(b'=') { + return None; + } + cursor.spaces(); + let start = cursor.at; + let literal = cursor.number()?; + let end = cursor.at; + cursor.spaces(); + let comment = match cursor.rest() { + "" => "", + rest => rest.strip_prefix('#')?, + }; + let (range, step) = range_hint(comment).unzip(); + Some(Parameter { + name: name.to_owned(), + line: number, + literal: offset + start..offset + end, + value: literal.value, + integer: literal.integer, + decimals: literal.decimals, + exponent: literal.exponent, + range, + step: step.flatten(), + }) +} + +struct Literal { + value: f64, + integer: bool, + decimals: usize, + exponent: bool, +} + +struct Cursor<'a> { + text: &'a str, + at: usize, +} + +impl<'a> Cursor<'a> { + fn peek(&self) -> Option { + self.text.as_bytes().get(self.at).copied() + } + + fn rest(&self) -> &'a str { + &self.text[self.at..] + } + + fn eat(&mut self, token: &str) -> bool { + if self.rest().starts_with(token) { + self.at += token.len(); + true + } else { + false + } + } + + fn spaces(&mut self) { + while matches!(self.peek(), Some(b' ' | b'\t')) { + self.at += 1; + } + } + + fn take_while(&mut self, accept: impl Fn(u8) -> bool) -> &'a str { + let start = self.at; + while self.peek().is_some_and(&accept) { + self.at += 1; + } + &self.text[start..self.at] + } + + fn identifier(&mut self) -> Option<&'a str> { + if !self + .peek() + .is_some_and(|b| b.is_ascii_alphabetic() || b == b'_') + { + return None; + } + Some(self.take_while(|b| b.is_ascii_alphanumeric() || b == b'_')) + } + + /// A decimal int or float literal with an optional sign: `-12`, + /// `1_000`, `2.5`, `.5`, `5.`, `1e-3`. + fn number(&mut self) -> Option { + let start = self.at; + if matches!(self.peek(), Some(b'-' | b'+')) { + self.at += 1; + self.spaces(); + } + let digits = |b: u8| b.is_ascii_digit() || b == b'_'; + let whole = self.take_while(digits); + let mut fraction = None; + if self.eat(".") { + fraction = Some(self.take_while(digits)); + } + if whole.is_empty() && fraction.is_none_or(str::is_empty) { + return None; + } + // Not 0x10, 0o7, 1j or the start of a name: those are not plain. + if whole.len() > 1 && whole.starts_with('0') && fraction.is_none() { + return None; + } + let mut exponent = false; + if matches!(self.peek(), Some(b'e' | b'E')) { + self.at += 1; + if matches!(self.peek(), Some(b'-' | b'+')) { + self.at += 1; + } + if self.take_while(|b| b.is_ascii_digit()).is_empty() { + return None; + } + exponent = true; + } + if self + .peek() + .is_some_and(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'.') + { + return None; + } + // "- 5" is valid Python too; underscores only group digits. + let plain: String = self.text[start..self.at] + .chars() + .filter(|c| !matches!(c, '_' | ' ' | '\t')) + .collect(); + let value: f64 = plain.parse().ok()?; + value.is_finite().then(|| Literal { + value, + integer: fraction.is_none() && !exponent, + decimals: fraction.map_or(0, |f| f.chars().filter(|c| *c != '_').count()), + exponent, + }) + } +} + +/// `[min, max]`, `[min, max, step]` or `min..max` anywhere in a comment. +fn range_hint(comment: &str) -> Option<(RangeInclusive, Option)> { + if let Some(open) = comment.find('[') + && let Some(close) = comment[open..].find(']') + { + let numbers: Option> = comment[open + 1..open + close] + .split(',') + .map(|part| part.trim().parse::().ok()) + .collect(); + if let Some(numbers) = numbers { + match numbers.as_slice() { + [min, max] if min < max => return Some((*min..=*max, None)), + [min, max, step] if min < max && *step > 0.0 => { + return Some((*min..=*max, Some(*step))); + } + _ => {} + } + } + } + let (left, right) = comment.split_once("..")?; + let min = left.split_whitespace().last()?.parse::().ok()?; + let max = right.split_whitespace().next()?.parse::().ok()?; + (min < max).then_some((min..=max, None)) +} + +fn decimals_of(value: f64) -> usize { + let text = format!("{value}"); + text.split_once('.') + .map_or(0, |(_, fraction)| fraction.len()) +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_parameters.rs"] +mod tests; diff --git a/src/project.rs b/src/project.rs new file mode 100644 index 000000000..0d406b6e4 --- /dev/null +++ b/src/project.rs @@ -0,0 +1,505 @@ +//! The project folder of the Project panel: its file tree, its main script +//! and the file operations the panel offers. +//! +//! Folder listings are cached and read again when the folder's +//! modification time changes, checked at most once a second per shown +//! folder, so drawing the tree every frame touches the disk very little and +//! files added by other programs still appear. + +use std::collections::{BTreeSet, HashMap}; +use std::io::{self, Read as _}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant, SystemTime}; + +/// How often a shown folder is checked for changes made by other programs. +const RECHECK_INTERVAL: Duration = Duration::from_secs(1); +/// Root scripts read when looking for the main script, and how much of each. +const MAX_MAIN_CANDIDATES: usize = 64; +const MAX_MAIN_BYTES: u64 = 256 * 1024; + +/// Extensions of the files the editor opens from the tree; other files are +/// listed but left to other programs. +const TEXT_EXTENSIONS: &[&str] = &[ + "py", "pyw", "pyi", "txt", "md", "rst", "json", "toml", "cfg", "ini", "yaml", "yml", "csv", +]; + +/// A file or folder of the tree. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Entry { + pub path: PathBuf, + pub name: String, + pub is_dir: bool, +} + +/// One line of the tree as shown: an entry, how deep it is and, for a +/// folder, whether its contents are shown below it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Row { + pub entry: Entry, + pub depth: usize, + pub expanded: bool, +} + +struct Listing { + entries: Vec, + modified: Option, + checked: Instant, +} + +pub struct Project { + root: PathBuf, + /// The script F5 runs while a file of the project is shown. + pub main: Option, + /// Current file search query in the Project panel. + pub filter: String, + /// Folders whose contents are shown; the root's always are. + expanded: BTreeSet, + listings: HashMap, +} + +impl Project { + /// The project in the folder `root`, with nothing below it expanded. + pub fn open(root: &Path) -> io::Result { + let root = std::path::absolute(root)?; + if !root.is_dir() { + return Err(io::Error::new( + io::ErrorKind::NotADirectory, + format!("{} is not a folder", root.display()), + )); + } + Ok(Self { + root, + main: None, + filter: String::new(), + expanded: BTreeSet::new(), + listings: HashMap::new(), + }) + } + + pub fn root(&self) -> &Path { + &self.root + } + + /// The folder's name, for the panel and the menus. + pub fn name(&self) -> String { + self.root.file_name().map_or_else( + || self.root.display().to_string(), + |name| name.to_string_lossy().into_owned(), + ) + } + + /// Whether `path` is inside the project folder. + pub fn contains(&self, path: &Path) -> bool { + path.starts_with(&self.root) + } + + /// Path of `path` relative to the project folder, for display. + pub fn relative<'a>(&self, path: &'a Path) -> &'a Path { + path.strip_prefix(&self.root).unwrap_or(path) + } + + pub fn is_expanded(&self, folder: &Path) -> bool { + folder == self.root || self.expanded.contains(folder) + } + + pub fn toggle(&mut self, folder: &Path) { + if !self.expanded.remove(folder) { + self.expanded.insert(folder.to_path_buf()); + } + } + + pub fn collapse_all(&mut self) { + self.expanded.clear(); + } + + /// Expands the folders down to `path`, so its row is shown. + pub fn reveal(&mut self, path: &Path) { + let Ok(relative) = path.strip_prefix(&self.root) else { + return; + }; + let mut folder = self.root.clone(); + let parents = relative + .parent() + .map(Path::components) + .into_iter() + .flatten(); + for component in parents { + folder.push(component); + self.expanded.insert(folder.clone()); + } + } + + /// The expanded folders, for the next session. + pub fn expanded(&self) -> Vec { + self.expanded.iter().cloned().collect() + } + + /// Expands folders of an earlier session that still exist. + pub fn restore_expanded(&mut self, folders: &[PathBuf]) { + self.expanded = folders + .iter() + .filter(|folder| self.contains(folder) && folder.is_dir()) + .cloned() + .collect(); + } + + /// Reads every listing again on the next [`Project::rows`]. + pub fn refresh(&mut self) { + self.listings.clear(); + } + + /// Follows a rename or move from `from` to `to` (a file, or a folder and + /// everything in it). + pub fn relocate(&mut self, from: &Path, to: &Path) { + if let Some(main) = self + .main + .as_deref() + .and_then(|main| relocated(main, from, to)) + { + self.main = Some(main); + } + self.expanded = std::mem::take(&mut self.expanded) + .into_iter() + .map(|folder| relocated(&folder, from, to).unwrap_or(folder)) + .collect(); + self.refresh(); + } + + /// Forgets `path`, which was deleted, and what was below it. + pub fn forget(&mut self, path: &Path) { + if self + .main + .as_deref() + .is_some_and(|main| main.starts_with(path)) + { + self.main = None; + } + self.expanded.retain(|folder| !folder.starts_with(path)); + self.refresh(); + } + + /// The rows of the tree as shown: the contents of the root, and of + /// every expanded folder below its row. Unreadable folders show empty. + pub fn rows(&mut self) -> Vec { + let mut rows = Vec::new(); + let root = self.root.clone(); + self.push_rows(&root, 0, &mut rows); + rows + } + + /// Searches all files in the project (including inside collapsed folders) + /// whose file name or relative path matches `query` (case-insensitive), + /// without altering the expanded folder state. + pub fn search_rows(&mut self, query: &str) -> Vec { + let trimmed = query.trim(); + if trimmed.is_empty() { + return self.rows(); + } + let needle = trimmed.to_lowercase(); + let mut rows = Vec::new(); + let root = self.root.clone(); + let mut visited_dirs = 0usize; + self.push_search_rows(&root, 0, &needle, &mut visited_dirs, &mut rows); + rows + } + + fn push_search_rows( + &mut self, + folder: &Path, + depth: usize, + needle: &str, + visited_dirs: &mut usize, + rows: &mut Vec, + ) { + const MAX_SEARCH_DEPTH: usize = 16; + const MAX_SEARCH_DIRS: usize = 512; + if depth > MAX_SEARCH_DEPTH || *visited_dirs >= MAX_SEARCH_DIRS { + return; + } + *visited_dirs += 1; + for entry in self.entries(folder) { + if entry.is_dir { + let path = entry.path.clone(); + self.push_search_rows(&path, depth + 1, needle, visited_dirs, rows); + } else { + let rel = self + .relative(&entry.path) + .to_string_lossy() + .replace('\\', "/"); + if entry.name.to_lowercase().contains(needle) || rel.to_lowercase().contains(needle) + { + rows.push(Row { + entry, + depth: 0, + expanded: false, + }); + } + } + } + } + + fn push_rows(&mut self, folder: &Path, depth: usize, rows: &mut Vec) { + for entry in self.entries(folder) { + let expanded = entry.is_dir && self.expanded.contains(&entry.path); + let path = entry.path.clone(); + rows.push(Row { + entry, + depth, + expanded, + }); + if expanded { + self.push_rows(&path, depth + 1, rows); + } + } + } + + /// The cached entries of `folder`, read again when it changed. + fn entries(&mut self, folder: &Path) -> Vec { + let now = Instant::now(); + if let Some(listing) = self.listings.get_mut(folder) { + if now.duration_since(listing.checked) < RECHECK_INTERVAL { + return listing.entries.clone(); + } + listing.checked = now; + let modified = modified(folder); + if modified.is_some() && modified == listing.modified { + return listing.entries.clone(); + } + } + let entries = list(folder).unwrap_or_else(|error| { + log::warn!("Cannot list {}: {error}", folder.display()); + Vec::new() + }); + self.listings.insert( + folder.to_path_buf(), + Listing { + entries: entries.clone(), + modified: modified(folder), + checked: now, + }, + ); + entries + } +} + +fn modified(path: &Path) -> Option { + std::fs::metadata(path).and_then(|m| m.modified()).ok() +} + +/// The visible entries of `folder`: folders first, then files, each sorted +/// by name regardless of case. Hidden files, caches and compiled files are +/// left out. +pub fn list(folder: &Path) -> io::Result> { + let mut entries = Vec::new(); + for item in std::fs::read_dir(folder)? { + let item = item?; + let name = item.file_name().to_string_lossy().into_owned(); + if is_hidden(&name) { + continue; + } + // Follows links, so a linked folder is shown as a folder. + let is_dir = item.path().is_dir(); + entries.push(Entry { + path: item.path(), + name, + is_dir, + }); + } + entries.sort_by(|a, b| { + b.is_dir + .cmp(&a.is_dir) + .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) + .then_with(|| a.name.cmp(&b.name)) + }); + Ok(entries) +} + +/// Names the tree does not show: hidden files and folders (`.git`, +/// `.venv`), Python's caches and compiled files, and packaging metadata. +pub fn is_hidden(name: &str) -> bool { + name.starts_with('.') + || name == "__pycache__" + || name.ends_with(".pyc") + || name.ends_with(".pyo") + || name.ends_with(".egg-info") +} + +/// Whether the editor opens `path` from the tree: Python scripts and plain +/// text files. +pub fn is_editable(path: &Path) -> bool { + path.extension() + .and_then(|extension| extension.to_str()) + .is_some_and(|extension| { + TEXT_EXTENSIONS + .iter() + .any(|known| known.eq_ignore_ascii_case(extension)) + }) +} + +/// Whether `path` is a Python script, which the project can run. +pub fn is_script(path: &Path) -> bool { + path.extension() + .is_some_and(|extension| extension.eq_ignore_ascii_case("py")) +} + +/// The script that most probably renders the project in `root`: `main.py`, +/// `__main__.py` or a script named after the folder, else the only script +/// at the top of the folder that calls `show_object`. `None` when it is not +/// clear, rather than a guess that runs the wrong file. +pub fn guess_main(root: &Path) -> Option { + let folder_script = root + .file_name() + .map(|name| format!("{}.py", name.to_string_lossy())); + let named = ["main.py", "__main__.py"] + .into_iter() + .map(str::to_owned) + .chain(folder_script); + for name in named { + let path = root.join(name); + if path.is_file() { + return Some(path); + } + } + let mut showing = list(root) + .ok()? + .into_iter() + .filter(|entry| !entry.is_dir && is_script(&entry.path)) + .take(MAX_MAIN_CANDIDATES) + .filter(|entry| calls_show_object(&entry.path)); + let only = showing.next()?; + showing.next().is_none().then_some(only.path) +} + +fn calls_show_object(path: &Path) -> bool { + let mut text = String::new(); + std::fs::File::open(path) + .and_then(|file| file.take(MAX_MAIN_BYTES).read_to_string(&mut text)) + .is_ok() + && text.contains("show_object(") +} + +/// Checks a file or folder name typed by the user. Names that some systems +/// refuse are refused everywhere, so a project can move between them. +pub fn check_name(name: &str) -> Result<&str, String> { + const RESERVED: &[&str] = &[ + "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", + "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + ]; + let name = name.trim(); + if name.is_empty() { + return Err("Enter a name".to_owned()); + } + if name == "." || name == ".." { + return Err(format!("\"{name}\" is not a valid name")); + } + if let Some(invalid) = name.chars().find(|c| { + matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() + }) { + return Err(format!("A name cannot contain \"{invalid}\"")); + } + if name.ends_with('.') { + return Err("A name cannot end with a dot".to_owned()); + } + let stem = name.split('.').next().unwrap_or(name); + if RESERVED + .iter() + .any(|reserved| reserved.eq_ignore_ascii_case(stem)) + { + return Err(format!("\"{stem}\" is a reserved name on Windows")); + } + Ok(name) +} + +fn invalid_name(message: String) -> io::Error { + io::Error::new(io::ErrorKind::InvalidInput, message) +} + +/// Creates an empty file named `name` in `folder`; a name without an +/// extension becomes a Python script. An existing file is never replaced. +pub fn create_file(folder: &Path, name: &str) -> io::Result { + let name = check_name(name).map_err(invalid_name)?; + let mut path = folder.join(name); + if path.extension().is_none() { + path.set_extension("py"); + } + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(|error| describe_existing(error, &path))?; + Ok(path) +} + +/// Creates the folder `name` in `folder`. +pub fn create_folder(folder: &Path, name: &str) -> io::Result { + let name = check_name(name).map_err(invalid_name)?; + let path = folder.join(name); + std::fs::create_dir(&path).map_err(|error| describe_existing(error, &path))?; + Ok(path) +} + +/// Renames the file or folder at `path` to `name`, in the same folder. +/// Nothing is replaced: renaming onto an existing name fails, except to +/// change the case of the name where the system ignores case, which finds +/// the file itself under the new name. Where case matters, another file +/// may hold that name, and it is kept. +pub fn rename(path: &Path, name: &str) -> io::Result { + let name = check_name(name).map_err(invalid_name)?; + let parent = path + .parent() + .ok_or_else(|| invalid_name("The project folder itself cannot be renamed".to_owned()))?; + let target = parent.join(name); + if target == path { + return Ok(target); + } + let same_but_case = path + .file_name() + .is_some_and(|old| old.to_string_lossy().to_lowercase() == name.to_lowercase()); + let itself = same_but_case && same_file::is_same_file(path, &target).unwrap_or(false); + if !itself && std::fs::symlink_metadata(&target).is_ok() { + return Err(describe_existing( + io::Error::from(io::ErrorKind::AlreadyExists), + &target, + )); + } + std::fs::rename(path, &target)?; + Ok(target) +} + +/// Deletes the file, or the folder and everything in it, at `path`. +/// Links are removed, never followed. +pub fn delete(path: &Path) -> io::Result<()> { + let metadata = std::fs::symlink_metadata(path)?; + if metadata.is_dir() { + std::fs::remove_dir_all(path) + } else { + std::fs::remove_file(path) + } +} + +fn describe_existing(error: io::Error, path: &Path) -> io::Error { + if error.kind() == io::ErrorKind::AlreadyExists { + let name = path.file_name().map_or_else( + || path.display().to_string(), + |n| n.to_string_lossy().into_owned(), + ); + io::Error::new(error.kind(), format!("{name} already exists")) + } else { + error + } +} + +/// Where `path` is after `from` moved to `to`: `to` itself, or the same +/// place below it. `None` when `path` was not moved. +pub fn relocated(path: &Path, from: &Path, to: &Path) -> Option { + let rest = path.strip_prefix(from).ok()?; + Some(if rest.as_os_str().is_empty() { + to.to_path_buf() + } else { + to.join(rest) + }) +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_project.rs"] +mod tests; diff --git a/src/recovery.rs b/src/recovery.rs new file mode 100644 index 000000000..d1c681c98 --- /dev/null +++ b/src/recovery.rs @@ -0,0 +1,552 @@ +//! Crash recovery and bounded local document history. +//! +//! The unsaved buffers of the open tabs are stored as the active session, +//! separately from history, so startup can distinguish a recoverable +//! interrupted session. Every file is written with the same atomic, +//! synchronized primitive used by normal document saves. +//! +//! History lives in one folder per document, named after a hash of its path +//! (untitled buffers share one), and every version's file name carries its +//! timestamp. A checkpoint therefore lists one small folder and reads no +//! other version. Once per session, versions older than [`MAX_HISTORY_AGE`] +//! (which also removes the history of deleted or renamed files) and the +//! oldest versions beyond [`MAX_HISTORY_BYTES`] are pruned. + +use std::collections::HashSet; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::io; +use std::path::{Path, PathBuf}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +use crate::document::{Document, LineEnding, atomic_create, atomic_write}; + +const SCHEMA_VERSION: u32 = 1; +/// The session file holds every unsaved document since multiple tabs; the +/// single snapshot of earlier releases (schema 1) is still read. +const SESSION_SCHEMA_VERSION: u32 = 2; +pub const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(5); +pub const MAX_HISTORY_PER_DOCUMENT: usize = 20; +/// Versions older than this are removed, whatever document they belong to. +pub const MAX_HISTORY_AGE: Duration = Duration::from_secs(90 * 24 * 60 * 60); +/// Size budget of the whole history; the oldest versions go first beyond it. +pub const MAX_HISTORY_BYTES: u64 = 64 * 1024 * 1024; + +const UNTITLED_FOLDER: &str = "untitled"; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct RecoverySnapshot { + schema: u32, + pub timestamp_ms: u64, + pub path: Option, + pub text: String, + pub line_ending: LineEnding, + pub utf8_bom: bool, +} + +impl RecoverySnapshot { + fn capture(document: &Document, timestamp_ms: u64) -> Self { + Self { + schema: SCHEMA_VERSION, + timestamp_ms, + path: document.path().map(Path::to_path_buf), + text: document.text.clone(), + line_ending: document.line_ending(), + utf8_bom: document.has_utf8_bom(), + } + } + + pub fn display_name(&self) -> String { + self.path + .as_ref() + .and_then(|path| path.file_name()) + .map_or_else( + || "untitled".to_owned(), + |name| name.to_string_lossy().into_owned(), + ) + } + + pub fn into_document(self) -> Document { + Document::recovered(self.text, self.path, self.line_ending, self.utf8_bom) + } + + fn validate(self) -> io::Result { + if self.schema != SCHEMA_VERSION { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("unsupported recovery format version {}", self.schema), + )); + } + Ok(self) + } +} + +/// The active session: the unsaved documents, in tab order. +#[derive(Serialize, Deserialize)] +struct SessionFile { + schema: u32, + documents: Vec, +} + +/// A history version on disk, known from its file name alone. +struct VersionFile { + path: PathBuf, + timestamp_ms: u64, +} + +pub struct RecoveryStore { + root: PathBuf, + /// Content of the session last written, to skip identical ones. + last_session: Option, + /// Content of each document of that session, so only the documents + /// that changed since get a history version. + last_contents: HashSet, + /// Documents whose saved baseline was archived since the session began. + baselines: HashSet>, + last_timestamp_ms: u64, + session_active: bool, + /// Whether this session already migrated and pruned the whole history. + maintained: bool, + max_history_bytes: u64, +} + +impl RecoveryStore { + pub fn new(root: PathBuf) -> Self { + let session_active = root.join("active-session.json").is_file(); + Self { + root, + last_session: None, + last_contents: HashSet::new(), + baselines: HashSet::new(), + last_timestamp_ms: 0, + session_active, + maintained: false, + max_history_bytes: MAX_HISTORY_BYTES, + } + } + + fn session_path(&self) -> PathBuf { + self.root.join("active-session.json") + } + + fn history_dir(&self) -> PathBuf { + self.root.join("history") + } + + /// The folder holding the history of the document at `path`. + fn document_dir(&self, path: Option<&Path>) -> PathBuf { + self.history_dir().join(document_folder(path)) + } + + /// The unsaved documents of an interrupted session; empty when there + /// is none. + pub fn load_session(&self) -> io::Result> { + let path = self.session_path(); + match std::fs::read(&path) { + Ok(bytes) => decode_session(&bytes), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()), + Err(error) => Err(error), + } + } + + /// Persists a modified buffer as the active session and as a history + /// version; see [`RecoveryStore::checkpoint_all`]. + #[cfg(test)] + pub fn checkpoint(&mut self, document: &Document) -> io::Result { + self.checkpoint_all(&[document]) + } + + /// Persists the modified documents among `documents` as the active + /// session, and each one that changed since the last checkpoint as a + /// history version. Repeated identical contents write nothing, and + /// without modified documents the session is cleared. Returns whether + /// a session was written. + pub fn checkpoint_all(&mut self, documents: &[&Document]) -> io::Result { + let modified: Vec<&Document> = documents + .iter() + .copied() + .filter(|document| document.is_modified()) + .collect(); + if modified.is_empty() { + self.clear_session()?; + return Ok(false); + } + self.maintain(); + + // The saved version of each file first, so it is older than its + // edits in the history. + for document in &modified { + let path = document.path().map(Path::to_path_buf); + if self.baselines.insert(path.clone()) + && let Some(path) = path + && let Err(error) = self.archive_path(&path) + { + log::warn!( + "Cannot archive the saved baseline {}: {error}", + path.display() + ); + } + } + + let timestamp = self.next_timestamp(); + let snapshots: Vec = modified + .iter() + .map(|document| RecoverySnapshot::capture(document, timestamp)) + .collect(); + let contents: Vec = snapshots.iter().map(content_key).collect(); + let session = { + let mut hasher = DefaultHasher::new(); + contents.hash(&mut hasher); + hasher.finish() + }; + if self.last_session == Some(session) { + return Ok(false); + } + + for (snapshot, content) in snapshots.iter().zip(&contents) { + if self.last_contents.contains(content) { + continue; + } + let encoded = serde_json::to_vec(snapshot).map_err(io::Error::other)?; + self.append_history(snapshot, &encoded)?; + } + + let encoded = serde_json::to_vec(&SessionFile { + schema: SESSION_SCHEMA_VERSION, + documents: snapshots, + }) + .map_err(io::Error::other)?; + std::fs::create_dir_all(&self.root)?; + atomic_write(&self.session_path(), &encoded)?; + self.session_active = true; + self.last_session = Some(session); + self.last_contents = contents.into_iter().collect(); + self.last_timestamp_ms = timestamp; + Ok(true) + } + + /// Adds the current document state to history without marking it as an + /// interrupted session. Used to retain saved baselines and Save As targets. + pub fn archive(&mut self, document: &Document) -> io::Result { + self.maintain(); + let mut snapshot = RecoverySnapshot::capture(document, 0); + if self + .latest(snapshot.path.as_deref())? + .is_some_and(|latest| content_key(&latest) == content_key(&snapshot)) + { + return Ok(false); + } + snapshot.timestamp_ms = self.next_timestamp(); + let encoded = serde_json::to_vec(&snapshot).map_err(io::Error::other)?; + self.append_history(&snapshot, &encoded)?; + self.last_timestamp_ms = snapshot.timestamp_ms; + Ok(true) + } + + pub fn archive_path(&mut self, path: &Path) -> io::Result { + match Document::open_any(path) { + Ok(document) => self.archive(&document), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } + } + + pub fn clear_session(&mut self) -> io::Result<()> { + if self.session_active { + match std::fs::remove_file(self.session_path()) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + self.session_active = false; + } + self.last_session = None; + self.last_contents.clear(); + self.baselines.clear(); + Ok(()) + } + + /// The versions of the document at `path`, newest first. + pub fn history(&mut self, path: Option<&Path>) -> io::Result> { + self.maintain(); + let mut versions = Vec::new(); + for file in version_files(&self.document_dir(path))? { + if let Some(snapshot) = read_version(&file.path) + && snapshot.path.as_deref() == path + { + versions.push(snapshot); + } + } + versions.sort_by_key(|snapshot| std::cmp::Reverse(snapshot.timestamp_ms)); + Ok(versions) + } + + /// The newest version of the document at `path`. + fn latest(&self, path: Option<&Path>) -> io::Result> { + let mut files = version_files(&self.document_dir(path))?; + files.sort_by_key(|file| std::cmp::Reverse(file.timestamp_ms)); + // Two paths could share a folder; skip the other one's versions. + Ok(files + .iter() + .filter_map(|file| read_version(&file.path)) + .find(|snapshot| snapshot.path.as_deref() == path)) + } + + fn append_history(&self, snapshot: &RecoverySnapshot, encoded: &[u8]) -> io::Result<()> { + let directory = self.document_dir(snapshot.path.as_deref()); + std::fs::create_dir_all(&directory)?; + for suffix in 0..1000 { + let path = directory.join(version_name(snapshot.timestamp_ms, suffix)); + match atomic_create(&path, encoded) { + Ok(()) => return prune_document(&directory), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + Err(io::Error::new( + io::ErrorKind::AlreadyExists, + "could not allocate a unique history version name", + )) + } + + /// Migrates the flat history of earlier releases into document folders, + /// then prunes by age and size. Problems are logged, never fatal: the + /// history is a convenience and must not block checkpoints. + fn maintain(&mut self) { + if std::mem::replace(&mut self.maintained, true) { + return; + } + if let Err(error) = self.migrate_flat_history() { + log::warn!("Cannot migrate the local history: {error}"); + } + if let Err(error) = self.prune_all(timestamp_ms()) { + log::warn!("Cannot prune the local history: {error}"); + } + } + + fn migrate_flat_history(&self) -> io::Result<()> { + for file in version_files(&self.history_dir())? { + match std::fs::read(&file.path).and_then(|bytes| decode(&bytes)) { + Ok(snapshot) => { + let directory = self.document_dir(snapshot.path.as_deref()); + std::fs::create_dir_all(&directory)?; + let name = file.path.file_name().expect("a version file has a name"); + std::fs::rename(&file.path, directory.join(name))?; + } + Err(error) => { + log::warn!( + "Cannot read recovery history {}: {error}", + file.path.display() + ); + } + } + } + Ok(()) + } + + /// Removes versions older than [`MAX_HISTORY_AGE`], then the oldest + /// versions until the history fits [`MAX_HISTORY_BYTES`], then empty + /// folders. Recovery backups made before reloads expire by age too. + fn prune_all(&self, now_ms: u64) -> io::Result<()> { + let cutoff = now_ms.saturating_sub(MAX_HISTORY_AGE.as_millis() as u64); + let mut kept = Vec::new(); + for directory in subdirectories(&self.history_dir())? { + for file in version_files(&directory)? { + if file.timestamp_ms < cutoff { + remove_file(&file.path)?; + } else { + let size = std::fs::metadata(&file.path).map_or(0, |m| m.len()); + kept.push((file, size)); + } + } + } + + let mut total: u64 = kept.iter().map(|(_, size)| size).sum(); + kept.sort_by_key(|(file, _)| file.timestamp_ms); + for (file, size) in kept { + if total <= self.max_history_bytes { + break; + } + remove_file(&file.path)?; + total -= size; + } + + for directory in subdirectories(&self.history_dir())? { + // Fails harmlessly while the folder still has versions. + let _ = std::fs::remove_dir(directory); + } + self.prune_recovery_backups(cutoff) + } + + fn prune_recovery_backups(&self, cutoff_ms: u64) -> io::Result<()> { + let entries = match std::fs::read_dir(&self.root) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + }; + let cutoff = UNIX_EPOCH + Duration::from_millis(cutoff_ms); + for entry in entries { + let entry = entry?; + let is_backup = entry + .file_name() + .to_string_lossy() + .ends_with(".recovery.py"); + let expired = entry + .metadata() + .and_then(|metadata| metadata.modified()) + .is_ok_and(|modified| modified < cutoff); + if is_backup && expired { + remove_file(&entry.path())?; + } + } + Ok(()) + } + + fn next_timestamp(&self) -> u64 { + timestamp_ms().max(self.last_timestamp_ms.saturating_add(1)) + } +} + +/// Keeps the newest [`MAX_HISTORY_PER_DOCUMENT`] versions of one folder. +fn prune_document(directory: &Path) -> io::Result<()> { + let mut files = version_files(directory)?; + files.sort_by_key(|file| std::cmp::Reverse(file.timestamp_ms)); + for file in files.into_iter().skip(MAX_HISTORY_PER_DOCUMENT) { + remove_file(&file.path)?; + } + Ok(()) +} + +/// Folder name of a document's history: a hash of its path that does not +/// change between releases (unlike `DefaultHasher`, whose algorithm may). +/// +/// The path is rebuilt from its components first, so the same file gets +/// one folder however its path is written: on Windows `/` and `\` both +/// separate, and are hashed as `\`, which the paths of the system's file +/// dialogs, and so the folders of earlier releases, already use. +fn document_folder(path: Option<&Path>) -> String { + let Some(path) = path else { + return UNTITLED_FOLDER.to_owned(); + }; + let path: PathBuf = path.components().collect(); + // FNV-1a, 64 bits. + let hash = path + .as_os_str() + .as_encoded_bytes() + .iter() + .fold(0xcbf2_9ce4_8422_2325_u64, |hash, &byte| { + (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3) + }); + format!("doc-{hash:016x}") +} + +fn version_name(timestamp_ms: u64, suffix: usize) -> String { + format!("version-{timestamp_ms}-{suffix}.json") +} + +/// Parses the timestamp of a [`version_name`]. +fn version_timestamp(name: &str) -> Option { + let rest = name.strip_prefix("version-")?.strip_suffix(".json")?; + rest.split_once('-')?.0.parse().ok() +} + +/// The version files directly inside `directory`. +fn version_files(directory: &Path) -> io::Result> { + let entries = match std::fs::read_dir(directory) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error), + }; + let mut files = Vec::new(); + for entry in entries { + let entry = entry?; + if let Some(timestamp_ms) = version_timestamp(&entry.file_name().to_string_lossy()) + && entry.file_type()?.is_file() + { + files.push(VersionFile { + path: entry.path(), + timestamp_ms, + }); + } + } + Ok(files) +} + +fn subdirectories(directory: &Path) -> io::Result> { + let entries = match std::fs::read_dir(directory) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(error) => return Err(error), + }; + let mut directories = Vec::new(); + for entry in entries { + let entry = entry?; + if entry.file_type()?.is_dir() { + directories.push(entry.path()); + } + } + Ok(directories) +} + +fn read_version(path: &Path) -> Option { + match std::fs::read(path).and_then(|bytes| decode(&bytes)) { + Ok(snapshot) => Some(snapshot), + Err(error) => { + log::warn!("Cannot read recovery history {}: {error}", path.display()); + None + } + } +} + +fn remove_file(path: &Path) -> io::Result<()> { + match std::fs::remove_file(path) { + Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error), + _ => Ok(()), + } +} + +/// The documents of a session file, of this release or a single snapshot +/// of an earlier one. +fn decode_session(bytes: &[u8]) -> io::Result> { + match serde_json::from_slice::(bytes) { + Ok(session) if session.schema == SESSION_SCHEMA_VERSION => session + .documents + .into_iter() + .map(RecoverySnapshot::validate) + .collect(), + Ok(session) => Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("unsupported recovery session version {}", session.schema), + )), + Err(_) => decode(bytes).map(|snapshot| vec![snapshot]), + } +} + +fn decode(bytes: &[u8]) -> io::Result { + serde_json::from_slice::(bytes) + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))? + .validate() +} + +fn content_key(snapshot: &RecoverySnapshot) -> u64 { + let mut hasher = DefaultHasher::new(); + snapshot.path.hash(&mut hasher); + snapshot.text.hash(&mut hasher); + snapshot.line_ending.as_str().hash(&mut hasher); + snapshot.utf8_bom.hash(&mut hasher); + hasher.finish() +} + +fn timestamp_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + .try_into() + .unwrap_or(u64::MAX) +} + +#[cfg(test)] +#[path = "../tests/rust/editor/test_recovery.rs"] +mod tests; diff --git a/src/scene.rs b/src/scene.rs new file mode 100644 index 000000000..3c7c67cea --- /dev/null +++ b/src/scene.rs @@ -0,0 +1,1752 @@ +//! What the viewer shows: the objects of the last run, the axis helpers and +//! the inspector overlay. +//! +//! Nodes mirror the worker's scene nodes (one per shown object, assemblies as +//! subtrees). Display state that belongs to the GUI (visibility, color +//! overrides, selection) lives here too. + +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock, Weak}; + +use glam::{Mat4, Vec3}; + +use crate::settings::Finish; +use crate::spatial::{BoundsBvh, TriangleBvh}; +use crate::worker::protocol::{self, RequestId}; + +pub type NodeKey = String; + +/// sRGB color with components in 0..1. +pub type Rgb = [f32; 3]; + +/// A 1-based OCCT subshape identifier supplied by the worker. +/// +/// It is valid only for the current live scene entry. Rebuilding/remodeling +/// the object may assign the number to a different subshape. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum TopologyEntity { + Face(u32), + Edge(u32), + Vertex(u32), +} + +impl TopologyEntity { + pub fn kind(self) -> &'static str { + match self { + Self::Face(_) => "Face", + Self::Edge(_) => "Edge", + Self::Vertex(_) => "Vertex", + } + } + + pub fn identifier(self) -> u32 { + match self { + Self::Face(id) | Self::Edge(id) | Self::Vertex(id) => id, + } + } + + pub fn topology_kind(self) -> protocol::TopologyKind { + match self { + Self::Face(_) => protocol::TopologyKind::Face, + Self::Edge(_) => protocol::TopologyKind::Edge, + Self::Vertex(_) => protocol::TopologyKind::Vertex, + } + } +} + +/// The exact CAD entity selected in one displayed part of a scene node. +#[derive(Clone, Debug, PartialEq)] +pub struct TopologySelection { + pub node: NodeKey, + pub part: usize, + pub entity: TopologyEntity, + pub position: Vec3, +} + +/// Axis-aligned bounding box. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Aabb { + pub min: Vec3, + pub max: Vec3, +} + +impl Default for Aabb { + fn default() -> Self { + Aabb::EMPTY + } +} + +impl Aabb { + pub const EMPTY: Aabb = Aabb { + min: Vec3::splat(f32::INFINITY), + max: Vec3::splat(f32::NEG_INFINITY), + }; + + pub fn is_empty(&self) -> bool { + self.min.x > self.max.x + } + + pub fn union(self, other: Aabb) -> Aabb { + Aabb { + min: self.min.min(other.min), + max: self.max.max(other.max), + } + } + + pub fn center(&self) -> Vec3 { + (self.min + self.max) * 0.5 + } + + pub fn size(&self) -> Vec3 { + self.max - self.min + } + + pub fn diagonal(&self) -> f32 { + self.size().length() + } + + pub fn from_points(points: impl IntoIterator) -> Aabb { + points.into_iter().fold(Aabb::EMPTY, |b, p| Aabb { + min: b.min.min(p), + max: b.max.max(p), + }) + } + + pub fn transformed(self, transform: Mat4) -> Aabb { + if self.is_empty() { + return self; + } + Aabb::from_points((0..8).map(|corner| { + transform.transform_point3(Vec3::new( + if corner & 1 == 0 { + self.min.x + } else { + self.max.x + }, + if corner & 2 == 0 { + self.min.y + } else { + self.max.y + }, + if corner & 4 == 0 { + self.min.z + } else { + self.max.z + }, + )) + })) + } +} + +/// Triangulated geometry on the CPU side. The renderer caches GPU buffers by +/// [`Mesh::id`]. +#[derive(Debug, Default)] +pub struct Mesh { + pub id: u64, + pub positions: Vec<[f32; 3]>, + pub normals: Vec<[f32; 3]>, + pub indices: Vec, + /// Packed sRGB colors on render-only, face-styled meshes. Zero uses the + /// part color; other values hold RGBA with the top byte set to 255. + pub vertex_colors: Vec, + /// Line segments, two points each. + pub edges: Vec<[f32; 3]>, + /// Degrees between the faces that meet at each segment's edge: 0 where + /// they meet smoothly, [`OUTLINE_ANGLE`] for an edge of one face or + /// none. Empty when unknown, and then every segment counts as an + /// outline. + pub segment_angles: Vec, + pub points: Vec<[f32; 3]>, + pub topology: MeshTopology, + pub bounds: Aabb, + triangle_bvh: OnceLock, + edge_bvh: OnceLock, + vertex_bvh: OnceLock, + simplified: OnceLock>>, + silhouette_edges: OnceLock>, +} + +/// The angle of an edge with a face on one side only, or none: an outline, +/// drawn whatever edges are shown. +pub const OUTLINE_ANGLE: f32 = 180.0; + +/// Meshes larger than this have no silhouette edges: finding them takes +/// memory in proportion. +const MAX_SILHOUETTE_TRIANGLES: usize = 3_000_000; + +/// A mesh edge where the surface can turn away from the viewer: its two +/// ends, then the normals of the two triangles that share it. +pub type SilhouetteEdge = [f32; 12]; + +/// Pick geometry and its association with the worker's OCCT topology index. +#[derive(Debug, Default)] +pub struct MeshTopology { + /// Separate pick triangles; normally empty, and the display triangles + /// are picked instead. + pub face_positions: Vec<[f32; 3]>, + pub face_indices: Vec, + /// One 1-based face id per pick triangle: per triangle of + /// `face_indices` when present, otherwise of [`Mesh::indices`]. + pub triangle_faces: Vec, + /// One 1-based edge id per segment in [`Mesh::edges`]. + pub segment_edges: Vec, + /// All OCCT vertices in 1-based id order, including vertices of solids. + pub vertices: Vec<[f32; 3]>, +} + +impl Mesh { + pub fn new( + positions: Vec<[f32; 3]>, + normals: Vec<[f32; 3]>, + indices: Vec, + edges: Vec<[f32; 3]>, + points: Vec<[f32; 3]>, + ) -> Self { + static NEXT_ID: AtomicU64 = AtomicU64::new(1); + let bounds = Aabb::from_points( + positions + .iter() + .chain(&edges) + .chain(&points) + .map(|p| Vec3::from_array(*p)), + ); + Self { + id: NEXT_ID.fetch_add(1, Ordering::Relaxed), + positions, + normals, + indices, + vertex_colors: Vec::new(), + edges, + segment_angles: Vec::new(), + points, + topology: MeshTopology::default(), + bounds, + triangle_bvh: OnceLock::new(), + edge_bvh: OnceLock::new(), + vertex_bvh: OnceLock::new(), + simplified: OnceLock::new(), + silhouette_edges: OnceLock::new(), + } + } + + /// The angle of segment `index` (see [`Mesh::segment_angles`]). + pub fn segment_angle(&self, index: usize) -> f32 { + self.segment_angles + .get(index) + .copied() + .unwrap_or(OUTLINE_ANGLE) + } + + /// Interior mesh edges between two triangles that do not lie in one + /// plane, found once. Drawn where one of the triangles faces the camera + /// and the other does not, they outline curved surfaces, which have no + /// B-rep edge there. Corners at the same place are one corner: the + /// worker meshes each face with vertices of its own. The triangles' + /// normals are those of their corners, oriented as the faces are lit. + pub fn silhouette_edges(&self) -> &[SilhouetteEdge] { + self.silhouette_edges + .get_or_init(|| self.find_silhouette_edges()) + } + + fn find_silhouette_edges(&self) -> Vec { + if self.triangle_count() > MAX_SILHOUETTE_TRIANGLES { + return Vec::new(); + } + // -0.0 and 0.0 are one place. + let place = |p: [f32; 3]| p.map(|c| (c + 0.0).to_bits()); + let mut places: HashMap<[u32; 3], u32> = HashMap::new(); + let corner: Vec = self + .positions + .iter() + .map(|&p| { + let next = places.len() as u32; + *places.entry(place(p)).or_insert(next) + }) + .collect(); + + struct Shared { + ends: [u32; 2], + normals: [Vec3; 2], + triangles: u8, + } + let mut edges: HashMap<(u32, u32), Shared> = HashMap::new(); + for triangle in self.indices.as_chunks::<3>().0 { + let vertices = triangle.map(|i| i as usize); + if vertices.iter().any(|&i| i >= self.positions.len()) { + continue; + } + let position = |i: usize| Vec3::from_array(self.positions[i]); + let geometric = (position(vertices[1]) - position(vertices[0])) + .cross(position(vertices[2]) - position(vertices[0])); + let smooth: Vec3 = vertices + .iter() + .filter_map(|&i| self.normals.get(i)) + .map(|&n| Vec3::from_array(n)) + .sum(); + // Oriented as lit; the geometric normal where corners have none. + let normal = if smooth.length_squared() > 1e-12 { + smooth.normalize() + } else { + geometric.normalize_or_zero() + }; + if normal == Vec3::ZERO || geometric.length_squared() <= 0.0 { + continue; + } + for (a, b) in [(0, 1), (1, 2), (2, 0)] { + let (ca, cb) = (corner[vertices[a]], corner[vertices[b]]); + if ca == cb { + continue; + } + let key = (ca.min(cb), ca.max(cb)); + edges + .entry(key) + .and_modify(|shared| { + if shared.triangles == 1 { + shared.normals[1] = normal; + } + shared.triangles = shared.triangles.saturating_add(1); + }) + .or_insert(Shared { + ends: [vertices[a] as u32, vertices[b] as u32], + normals: [normal, Vec3::ZERO], + triangles: 1, + }); + } + } + edges + .into_values() + .filter(|shared| { + shared.triangles == 2 && shared.normals[0].dot(shared.normals[1]) < 0.999_99 + }) + .map(|shared| { + let [a, b] = shared.ends.map(|i| self.positions[i as usize]); + let [na, nb] = shared.normals.map(|normal| normal.to_array()); + [ + a[0], a[1], a[2], b[0], b[1], b[2], na[0], na[1], na[2], nb[0], nb[1], nb[2], + ] + }) + .collect() + } + + /// A coarser copy for drawing the mesh small, made once: vertices are + /// merged per cell of a grid of [`SIMPLIFIED_CELLS`] cells along the + /// longest side, and triangles and edges that collapse are dropped. + /// `None` for small meshes and when that would not halve the triangles. + /// It is for drawing only: picking always uses the full mesh. + pub fn simplified(&self) -> Option<&Arc> { + self.simplified + .get_or_init(|| self.simplify().map(Arc::new)) + .as_ref() + } + + /// A render-only copy with triangle corners separated at face borders. + /// Geometry stays content-addressed in `Part::mesh` for picking and + /// instancing; this copy exists only when an assembly colors a face. + fn with_face_colors(&self, attributes: &[protocol::FaceAttribute]) -> Option> { + let colors: HashMap = attributes + .iter() + .filter_map(|attribute| { + attribute.color.map(|rgb| { + let bytes = rgb.map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u32); + ( + attribute.id, + 0xff00_0000 | bytes[0] | bytes[1] << 8 | bytes[2] << 16, + ) + }) + }) + .collect(); + if colors.is_empty() { + return None; + } + let (positions, indices, use_display_normals) = if self.topology.face_indices.is_empty() { + (&self.positions, &self.indices, true) + } else { + ( + &self.topology.face_positions, + &self.topology.face_indices, + false, + ) + }; + if self.topology.triangle_faces.len() != indices.len() / 3 { + return None; + } + let mut result = Mesh::new( + Vec::new(), + Vec::new(), + Vec::new(), + self.edges.clone(), + self.points.clone(), + ); + for (triangle, &face) in indices + .as_chunks::<3>() + .0 + .iter() + .zip(&self.topology.triangle_faces) + { + let Some(corners) = triangle + .iter() + .map(|&index| positions.get(index as usize).copied()) + .collect::>>() + else { + continue; + }; + let normal = (Vec3::from_array(corners[1]) - Vec3::from_array(corners[0])) + .cross(Vec3::from_array(corners[2]) - Vec3::from_array(corners[0])) + .normalize_or_zero() + .to_array(); + for (&index, &position) in triangle.iter().zip(&corners) { + result.positions.push(position); + result.normals.push(if use_display_normals { + self.normals.get(index as usize).copied().unwrap_or(normal) + } else { + normal + }); + result.vertex_colors.push(*colors.get(&face).unwrap_or(&0)); + result.indices.push((result.indices.len()) as u32); + } + } + result.bounds = self.bounds; + Some(Arc::new(result)) + } + + fn simplify(&self) -> Option { + let triangles = self.triangle_count(); + let size = self.bounds.size().max_element(); + if triangles < SIMPLIFY_FROM_TRIANGLES || !size.is_finite() || size <= 0.0 { + return None; + } + let cell_size = size / SIMPLIFIED_CELLS; + let origin = self.bounds.min; + let cell_of = |point: [f32; 3]| { + let cell = ((Vec3::from_array(point) - origin) / cell_size).floor(); + (cell.x as i32, cell.y as i32, cell.z as i32) + }; + + // One vertex per occupied cell: the mean of its positions and + // normals. + let mut cells: HashMap<(i32, i32, i32), u32> = HashMap::new(); + let mut sums: Vec<(Vec3, Vec3, f32)> = Vec::new(); + let merged: Vec = self + .positions + .iter() + .zip(&self.normals) + .map(|(&position, &normal)| { + let index = *cells.entry(cell_of(position)).or_insert_with(|| { + sums.push((Vec3::ZERO, Vec3::ZERO, 0.0)); + (sums.len() - 1) as u32 + }); + let sum = &mut sums[index as usize]; + sum.0 += Vec3::from_array(position); + sum.1 += Vec3::from_array(normal); + sum.2 += 1.0; + index + }) + .collect(); + + let mut seen = HashSet::new(); + let mut indices = Vec::new(); + for triangle in self.indices.as_chunks::<3>().0 { + let Some(corners) = triangle + .iter() + .map(|&index| merged.get(index as usize).copied()) + .collect::>>() + else { + continue; + }; + let [a, b, c] = [corners[0], corners[1], corners[2]]; + let mut key = [a, b, c]; + key.sort_unstable(); + if a != b && b != c && a != c && seen.insert(key) { + indices.extend([a, b, c]); + } + } + if indices.len() / 3 * 2 > triangles { + return None; + } + + let positions: Vec<[f32; 3]> = sums + .iter() + .map(|(position, _, count)| (*position / *count).to_array()) + .collect(); + let normals = sums + .iter() + .map(|(_, normal, _)| normal.normalize_or_zero().to_array()) + .collect(); + // Edges join the vertices of the cells their ends fall in. + let mut seen = HashSet::new(); + let mut edges = Vec::new(); + let mut segment_angles = Vec::new(); + for (index, segment) in self.edges.as_chunks::<2>().0.iter().enumerate() { + let ends = segment.map(|point| { + cells + .get(&cell_of(point)) + .map_or(point, |&index| positions[index as usize]) + }); + let (start, end) = (cell_of(ends[0]), cell_of(ends[1])); + if start != end + && seen.insert(if start < end { + (start, end) + } else { + (end, start) + }) + { + edges.extend(ends); + segment_angles.push(self.segment_angle(index)); + } + } + Some(Mesh { + segment_angles, + ..Mesh::new(positions, normals, indices, edges, self.points.clone()) + }) + } + + /// Only edges, e.g. for helper lines and grids. + pub fn lines(segments: Vec<[f32; 3]>) -> Self { + Self::new(Vec::new(), Vec::new(), Vec::new(), segments, Vec::new()) + } + + pub fn triangle_count(&self) -> usize { + self.indices.len() / 3 + } + + /// Bytes held by the vertex, index and topology arrays. + pub fn byte_size(&self) -> usize { + let topology = &self.topology; + let points = self.positions.len() + + self.normals.len() + + self.edges.len() + + self.points.len() + + topology.face_positions.len() + + topology.vertices.len(); + let integers = self.indices.len() + + self.vertex_colors.len() + + topology.face_indices.len() + + topology.triangle_faces.len() + + topology.segment_edges.len() + + self.segment_angles.len(); + points * size_of::<[f32; 3]>() + integers * size_of::() + } + + fn pick_triangles(&self) -> (&[[f32; 3]], &[u32]) { + if self.topology.face_indices.is_empty() { + (&self.positions, &self.indices) + } else { + (&self.topology.face_positions, &self.topology.face_indices) + } + } + + /// The nearest triangle hit with a ray parameter in `range`. + pub(crate) fn nearest_triangle_within( + &self, + origin: Vec3, + direction: Vec3, + range: (f32, f32), + ) -> Option<(f32, usize)> { + let (positions, indices) = self.pick_triangles(); + self.triangle_bvh + .get_or_init(|| TriangleBvh::build(positions, indices)) + .nearest_within(origin, direction, positions, indices, range) + .0 + } + + pub(crate) fn edge_bvh(&self) -> &BoundsBvh { + self.edge_bvh.get_or_init(|| { + BoundsBvh::build(self.edges.as_chunks::<2>().0.iter().map(|[a, b]| { + let (a, b) = (Vec3::from_array(*a), Vec3::from_array(*b)); + (a.min(b), a.max(b)) + })) + }) + } + + pub(crate) fn pick_vertices(&self) -> &[[f32; 3]] { + if self.topology.vertices.is_empty() { + &self.points + } else { + &self.topology.vertices + } + } + + pub(crate) fn vertex_bvh(&self) -> &BoundsBvh { + self.vertex_bvh.get_or_init(|| { + BoundsBvh::build(self.pick_vertices().iter().map(|point| { + let point = Vec3::from_array(*point); + (point, point) + })) + }) + } + + #[cfg(test)] + pub(crate) fn nearest_triangle_with_stats( + &self, + origin: Vec3, + direction: Vec3, + ) -> (Option<(f32, usize)>, usize) { + let (positions, indices) = self.pick_triangles(); + self.triangle_bvh + .get_or_init(|| TriangleBvh::build(positions, indices)) + .nearest_with_count(origin, direction, positions, indices) + } + + /// Builds a small render mesh that highlights exactly one CAD entity. + pub fn topology_mesh(&self, entity: TopologyEntity) -> Option { + match entity { + TopologyEntity::Face(identifier) => { + let (pick_positions, pick_indices) = self.pick_triangles(); + let mut positions = Vec::new(); + let mut normals = Vec::new(); + let mut indices = Vec::new(); + for (triangle, &face) in pick_indices + .as_chunks::<3>() + .0 + .iter() + .zip(&self.topology.triangle_faces) + { + if face != identifier { + continue; + } + let [Some(a), Some(b), Some(c)] = + triangle.map(|index| pick_positions.get(index as usize).copied()) + else { + continue; + }; + let normal = (Vec3::from_array(b) - Vec3::from_array(a)) + .cross(Vec3::from_array(c) - Vec3::from_array(a)) + .normalize_or(Vec3::Z) + .to_array(); + let start = positions.len() as u32; + positions.extend([a, b, c]); + normals.extend([normal; 3]); + indices.extend([start, start + 1, start + 2]); + } + (!indices.is_empty()) + .then(|| Mesh::new(positions, normals, indices, Vec::new(), Vec::new())) + } + TopologyEntity::Edge(identifier) => { + let mut segments = Vec::new(); + for (segment, &edge) in self + .edges + .as_chunks::<2>() + .0 + .iter() + .zip(&self.topology.segment_edges) + { + if edge == identifier { + segments.extend(*segment); + } + } + (!segments.is_empty()).then(|| Mesh::lines(segments)) + } + TopologyEntity::Vertex(identifier) => self + .topology + .vertices + .get(identifier.checked_sub(1)? as usize) + .copied() + .map(|point| { + Mesh::new(Vec::new(), Vec::new(), Vec::new(), Vec::new(), vec![point]) + }), + } + } +} + +impl From for Mesh { + fn from(mesh: protocol::Mesh) -> Self { + let mut normals = mesh.normals; + normals.resize(mesh.positions.len(), [0.0, 0.0, 1.0]); + let bounds = mesh.bbox.map_or_else( + || { + Aabb::from_points( + mesh.positions + .iter() + .chain(&mesh.edges) + .chain(&mesh.points) + .map(|point| Vec3::from_array(*point)), + ) + }, + |[min, max]| Aabb { + min: Vec3::from_array(min), + max: Vec3::from_array(max), + }, + ); + // One angle per segment, or none. + let segment_angles = if mesh.segment_angles.len() * 2 == mesh.edges.len() { + mesh.segment_angles + } else { + Vec::new() + }; + let topology = MeshTopology { + face_positions: mesh.topology.face_positions, + face_indices: mesh.topology.face_indices, + triangle_faces: mesh.topology.triangle_faces, + segment_edges: mesh.topology.segment_edges, + vertices: mesh.topology.vertices, + }; + Mesh { + // The worker already measured the geometry. + bounds, + topology, + segment_angles, + ..Mesh::new( + mesh.positions, + normals, + mesh.indices, + mesh.edges, + mesh.points, + ) + } + } +} + +#[derive(Clone, Debug)] +pub struct Part { + pub mesh: Arc, + pub transform: Mat4, + pub color: Option, + pub alpha: Option, + pub face_attributes: Vec, + pub material: Option, + pub render_mesh: Option>, +} + +impl Part { + fn from_message( + part: protocol::Part, + library: &mut MeshLibrary, + request: Option, + ) -> Result { + let mesh = library.resolve(part.mesh, request)?; + let render_mesh = mesh.with_face_colors(&part.face_attributes); + Ok(Self { + mesh, + transform: Mat4::from_cols_array(&part.transform), + color: part.color, + alpha: part.alpha, + face_attributes: part.face_attributes, + material: part.material, + render_mesh, + }) + } +} + +/// Display properties the user can change in the Objects panel. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Overrides { + pub color: Option, + pub alpha: Option, + /// Edges shown or hidden for this object only, whatever the preference. + pub edges: Option, + /// The material chosen in the Objects panel, over the script's. + pub finish: Option, +} + +#[derive(Debug)] +pub struct SceneNode { + pub key: NodeKey, + pub name: String, + pub kind: String, + /// Workplanes whose construction stack the inspector can show. + pub inspectable: bool, + pub parts: Vec, + pub children: Vec, + pub visible: bool, + /// From `show_object` options. + pub color: Option, + pub alpha: Option, + pub edge_color: Option, + /// From `show_object`'s `material` option. + pub finish: Option, + pub overrides: Overrides, + /// The script line that created the object, 1-based, in `script`. + pub line: Option, + /// The script as the run that made this node executed it. + pub script: Option>, +} + +/// The script a run executed: the lines of its objects refer to this text, +/// which the editor may have changed since. +#[derive(Debug)] +pub struct RunScript { + /// The document that ran; lines of another one mean nothing in it. + pub document: u64, + pub text: String, +} + +impl SceneNode { + /// Gives the node and its subtree the script their lines refer to. + pub fn attach_script(&mut self, script: &Arc) { + self.visit_mut(&mut |node| node.script = Some(script.clone())); + } + + fn from_message( + message: protocol::SceneNode, + library: &mut MeshLibrary, + request: Option, + ) -> Result { + let mut parts = Vec::with_capacity(message.parts.len()); + for part in message.parts { + parts.push(Part::from_message(part, library, request)?); + } + let mut children = Vec::with_capacity(message.children.len()); + for child in message.children { + children.push(Self::from_message(child, library, request)?); + } + Ok(Self { + key: message.key, + name: message.name, + kind: message.kind, + inspectable: message.inspectable, + parts, + children, + visible: true, + color: message.color, + alpha: message.alpha, + edge_color: message.edge_color, + finish: message.finish.as_deref().and_then(Finish::from_name), + overrides: Overrides::default(), + line: message.line, + script: None, + }) + } + + /// Bounds of this node's own parts (not its children). + pub fn own_bounds(&self) -> Aabb { + self.parts.iter().fold(Aabb::EMPTY, |b, part| { + b.union(part.mesh.bounds.transformed(part.transform)) + }) + } + + pub fn subtree_bounds(&self) -> Aabb { + self.children.iter().fold(self.own_bounds(), |b, child| { + b.union(child.subtree_bounds()) + }) + } + + pub fn triangle_count(&self) -> usize { + self.parts + .iter() + .map(|p| p.mesh.triangle_count()) + .sum::() + + self + .children + .iter() + .map(SceneNode::triangle_count) + .sum::() + } + + /// The material its faces are shaded with: the Objects panel's choice, + /// then the script's. + pub fn finish(&self) -> Finish { + self.overrides.finish.or(self.finish).unwrap_or_default() + } + + /// The color a part is drawn with, without selection highlighting: + /// user override, then the assembly part color, then `show_object` + /// options, then the material's own color (a metal's grey), then + /// `default`. + pub fn part_color(&self, part: &Part, default: Rgb) -> (Rgb, f32) { + let color = self + .overrides + .color + .or(part.color) + .or(self.color) + .or(self.finish().natural_color()) + .unwrap_or(default); + let alpha = self + .overrides + .alpha + .or(part.alpha) + .or(self.alpha) + .unwrap_or(1.0); + (color, alpha.clamp(0.0, 1.0)) + } + + /// Color for the tree swatch. + pub fn display_color(&self, default: Rgb) -> Option<(Rgb, f32)> { + self.parts + .first() + .map(|part| self.part_color(part, default)) + .or_else(|| self.children.first().and_then(|c| c.display_color(default))) + } + + fn visit<'a>(&'a self, f: &mut impl FnMut(&'a SceneNode)) { + f(self); + for child in &self.children { + child.visit(f); + } + } + + fn visit_mut(&mut self, f: &mut impl FnMut(&mut SceneNode)) { + f(self); + for child in &mut self.children { + child.visit_mut(f); + } + } +} + +/// One of the X/Y/Z axis lines through the origin. +#[derive(Clone, Debug)] +pub struct AxisHelper { + pub name: &'static str, + pub direction: Vec3, + pub color: Rgb, + pub visible: bool, +} + +/// Construction plane shown by the inspector. +#[derive(Clone, Debug)] +pub struct Grid { + pub origin: Vec3, + pub x_dir: Vec3, + pub z_dir: Vec3, + pub size: f32, +} + +/// Geometry highlighted by the CQ object inspector. +#[derive(Default)] +pub struct Overlay { + pub meshes: Vec>, + pub grid: Option, +} + +/// Entities Ctrl+click can gather, e.g. for one selector of many edges. +pub const MAX_TOPOLOGY_SELECTIONS: usize = 64; +/// Meshes with fewer triangles are never simplified. +const SIMPLIFY_FROM_TRIANGLES: usize = 2_000; +/// Cells along the longest side of a mesh when it is simplified. +const SIMPLIFIED_CELLS: f32 = 40.0; + +/// The widest exploded view: parts three times as far from the centre as +/// when assembled. +pub const MAX_EXPLODE: f32 = 2.0; + +/// Bytes of recently used worker meshes kept alive after the scene drops +/// them. The renderer keeps their GPU buffers for as long. +pub const RETAINED_MESH_BYTES: usize = 128 * 1024 * 1024; + +/// Worker meshes by content-addressed geometry id. +/// +/// The worker answers a request with references to meshes the request said +/// the GUI holds (`known_geometry`) and to meshes it sent earlier in the same +/// request, such as a previous pause of a debugging session. Both are pinned +/// until the request ends, whatever the scene drops meanwhile. Recently used +/// meshes are also retained within a byte budget, so the next run, a +/// debugging session or a render after Clear reuses them, and their GPU +/// buffers, instead of transferring and uploading them again. +pub struct MeshLibrary { + meshes: HashMap>, + /// Strong references by geometry id with their last use. + recent: HashMap, u64)>, + recent_bytes: usize, + budget: usize, + clock: u64, + /// Meshes a running request may still reference, by [`Mesh::id`]. + pins: HashMap>>, +} + +impl Default for MeshLibrary { + fn default() -> Self { + Self::with_budget(RETAINED_MESH_BYTES) + } +} + +impl MeshLibrary { + pub fn with_budget(budget: usize) -> Self { + Self { + meshes: HashMap::new(), + recent: HashMap::new(), + recent_bytes: 0, + budget, + clock: 0, + pins: HashMap::new(), + } + } + + /// Geometry ids the worker may send as references, sorted. + pub fn known(&self) -> Vec { + let mut ids: Vec = self + .meshes + .iter() + .filter(|(_, mesh)| mesh.strong_count() > 0) + .map(|(id, _)| id.clone()) + .collect(); + ids.sort_unstable(); + ids + } + + /// Keeps the meshes of `ids` alive until `request` is released. + pub fn pin(&mut self, request: RequestId, ids: &[String]) { + let pinned = self.pins.entry(request).or_default(); + for mesh in ids + .iter() + .filter_map(|id| self.meshes.get(id).and_then(Weak::upgrade)) + { + pinned.insert(mesh.id, mesh); + } + } + + /// Unpins every request for which `active` is false. + pub fn release_pins(&mut self, mut active: impl FnMut(RequestId) -> bool) { + let before = self.pins.len(); + self.pins.retain(|request, _| active(*request)); + if self.pins.len() != before { + self.meshes.retain(|_, mesh| mesh.strong_count() > 0); + } + } + + /// The shared mesh for a worker message: a reference, a full mesh, or a + /// full mesh whose geometry is already held, which keeps its GPU buffers. + fn resolve( + &mut self, + message: protocol::Mesh, + request: Option, + ) -> Result, String> { + let id = message.id.clone(); + let held = (!id.is_empty()) + .then(|| self.meshes.get(&id).and_then(Weak::upgrade)) + .flatten(); + let mesh = match held { + Some(mesh) => mesh, + None if message.bbox.is_some() => { + let mesh = Arc::new(Mesh::from(message)); + if !id.is_empty() { + self.meshes.insert(id.clone(), Arc::downgrade(&mesh)); + } + mesh + } + None => return Err(format!("worker referenced unavailable mesh {id}")), + }; + if !id.is_empty() { + if let Some(request) = request { + self.pins + .entry(request) + .or_default() + .insert(mesh.id, mesh.clone()); + } + self.touch(id, &mesh); + } + Ok(mesh) + } + + fn touch(&mut self, id: String, mesh: &Arc) { + self.clock += 1; + if let Some(entry) = self.recent.get_mut(&id) { + entry.1 = self.clock; + } else { + self.recent_bytes += mesh.byte_size(); + self.recent.insert(id, (mesh.clone(), self.clock)); + } + } + + /// Drops the least recently used meshes beyond the budget. + fn evict(&mut self) { + if self.recent_bytes <= self.budget { + return; + } + let mut by_age: Vec<(u64, String, usize)> = self + .recent + .iter() + .map(|(id, (mesh, used))| (*used, id.clone(), mesh.byte_size())) + .collect(); + by_age.sort_unstable(); + for (_, id, bytes) in by_age { + if self.recent_bytes <= self.budget { + break; + } + self.recent.remove(&id); + self.recent_bytes -= bytes; + } + self.meshes.retain(|_, mesh| mesh.strong_count() > 0); + } +} + +pub struct Scene { + pub nodes: Vec, + /// Parts of a run still being built; drawn progressively, never picked. + pub preview_parts: Vec, + pub axes: [AxisHelper; 3], + /// Selected node keys; the last one is the "current" object. + pub selection: Vec, + /// Exact entities, at most [`MAX_TOPOLOGY_SELECTIONS`], oldest first. + /// Measurements relate the last two; selectors describe them all. + pub topology_selections: Vec, + topology_highlights: Vec, + selector_preview: Vec<(NodeKey, usize, Part)>, + pub overlay: Overlay, + meshes: MeshLibrary, + /// Changes only when the set, placement or visibility of pickable parts + /// changes. Camera and selection changes deliberately leave it alone. + pick_revision: u64, + /// How far parts are moved away from `explode_center`, as a multiple of + /// their distance to it; 0 is assembled. + explode: f32, + /// The centre of the shown parts as assembled. + explode_center: Vec3, + /// Name paths of the isolated nodes: while it is not empty, only they + /// and their descendants are shown. Unlike keys, paths survive a run. + isolated: Vec, + /// Text filter for the Objects panel tree (does not alter 3D visibility). + pub filter: String, +} + +/// Process-wide, so two scenes never share a revision and an index built +/// for one scene is never mistaken for an index of another. +fn next_pick_revision() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + +impl Default for Scene { + fn default() -> Self { + let axis = |name, direction, color| AxisHelper { + name, + direction, + color, + visible: true, + }; + Self { + nodes: Vec::new(), + preview_parts: Vec::new(), + axes: [ + axis("X", Vec3::X, [1.0, 0.0, 0.0]), + // "lawngreen", as in the original editor. + axis("Y", Vec3::Y, [124.0 / 255.0, 252.0 / 255.0, 0.0]), + axis("Z", Vec3::Z, [0.0, 0.0, 1.0]), + ], + selection: Vec::new(), + topology_selections: Vec::new(), + topology_highlights: Vec::new(), + selector_preview: Vec::new(), + overlay: Overlay::default(), + meshes: MeshLibrary::default(), + pick_revision: next_pick_revision(), + explode: 0.0, + explode_center: Vec3::ZERO, + isolated: Vec::new(), + filter: String::new(), + } + } +} + +/// Visibility and overrides of nodes, keyed by their name path, so they can +/// be carried over to the next run. +pub type PreservedProperties = HashMap; + +impl Scene { + pub fn add_preview_part( + &mut self, + request: RequestId, + part: protocol::Part, + ) -> Result<(), String> { + self.preview_parts + .push(Part::from_message(part, &mut self.meshes, Some(request))?); + self.meshes.evict(); + Ok(()) + } + + pub fn clear_preview(&mut self) { + self.preview_parts.clear(); + } + /// Resolves full content-addressed meshes and references in one worker + /// response to `request`, whose meshes stay pinned until it ends. + pub fn decode_nodes( + &mut self, + request: Option, + messages: Vec, + ) -> Result, String> { + let nodes = messages + .into_iter() + .map(|message| SceneNode::from_message(message, &mut self.meshes, request)) + .collect(); + self.meshes.evict(); + nodes + } + + /// Geometry the worker may send as references: everything in the scene + /// and the recently used meshes the library still retains. + pub fn known_geometry(&self) -> Vec { + self.meshes.known() + } + + /// Guarantees that `request` can reference `ids` until it is released. + pub fn pin_geometry(&mut self, request: RequestId, ids: &[String]) { + self.meshes.pin(request, ids); + } + + /// Ends the guarantee of [`Scene::pin_geometry`] and of decoded meshes + /// for every request that is no longer `active`. + pub fn release_geometry(&mut self, active: impl FnMut(RequestId) -> bool) { + self.meshes.release_pins(active); + } + + pub fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + /// Replaces all objects; returns the keys of the removed top-level nodes. + pub fn replace( + &mut self, + nodes: Vec, + preserved: Option<&PreservedProperties>, + ) -> Vec { + let removed = self.clear(); + self.append(nodes, preserved); + removed + } + + pub fn append(&mut self, mut nodes: Vec, preserved: Option<&PreservedProperties>) { + self.clear_selector_preview(); + if let Some(preserved) = preserved { + for node in &mut nodes { + restore(node, "", preserved); + } + } + self.nodes.extend(nodes); + self.prune_isolation(); + self.shown_parts_changed(); + } + + /// Removes all objects; returns the removed top-level keys. + pub fn clear(&mut self) -> Vec { + self.clear_preview(); + self.clear_selector_preview(); + self.clear_selection(); + let removed: Vec<_> = self.nodes.drain(..).map(|n| n.key).collect(); + if !removed.is_empty() { + self.shown_parts_changed(); + } + removed + } + + /// Removes the given top-level nodes (keys of nested nodes are ignored). + pub fn remove_top_level(&mut self, keys: &[NodeKey]) -> Vec { + self.clear_selector_preview(); + let mut removed = Vec::new(); + self.nodes.retain(|node| { + let remove = keys.contains(&node.key); + if remove { + removed.push(node.key.clone()); + } + !remove + }); + if !removed.is_empty() { + self.prune_isolation(); + self.shown_parts_changed(); + } + self.prune_selection(); + removed + } + + pub fn snapshot_properties(&self) -> PreservedProperties { + let mut properties = HashMap::new(); + for node in &self.nodes { + snapshot(node, "", &mut properties); + } + properties + } + + pub fn find(&self, key: &str) -> Option<&SceneNode> { + self.iter().find(|node| node.key == key) + } + + pub fn find_mut(&mut self, key: &str) -> Option<&mut SceneNode> { + fn search<'a>(nodes: &'a mut [SceneNode], key: &str) -> Option<&'a mut SceneNode> { + for node in nodes { + if node.key == key { + return Some(node); + } + if let Some(found) = search(&mut node.children, key) { + return Some(found); + } + } + None + } + search(&mut self.nodes, key) + } + + /// All nodes, depth first. + pub fn iter(&self) -> impl Iterator { + let mut all = Vec::new(); + for node in &self.nodes { + node.visit(&mut |n| all.push(n)); + } + all.into_iter() + } + + /// The nodes whose parts are shown: visible ones (a hidden parent hides + /// its children) and, while isolating, only inside an isolated node. + pub fn visible_nodes(&self) -> Vec<&SceneNode> { + self.shown_nodes() + .into_iter() + .map(|(_, node)| node) + .collect() + } + + /// [`Scene::visible_nodes`] with their index paths from the top level. + pub(crate) fn shown_nodes(&self) -> Vec<(Vec, &SceneNode)> { + struct Walk<'a, 's> { + isolated: &'s [String], + indices: Vec, + out: Vec<(Vec, &'a SceneNode)>, + } + fn collect<'a>( + walk: &mut Walk<'a, '_>, + nodes: &'a [SceneNode], + parent: &str, + inside: bool, + ) { + for (index, node) in nodes.iter().enumerate().filter(|(_, n)| n.visible) { + let path = if walk.isolated.is_empty() { + String::new() + } else { + format!("{parent}/{}", node.name) + }; + let inside = inside || walk.isolated.contains(&path); + walk.indices.push(index); + if inside { + walk.out.push((walk.indices.clone(), node)); + } + collect(walk, &node.children, &path, inside); + walk.indices.pop(); + } + } + let mut walk = Walk { + isolated: &self.isolated, + indices: Vec::new(), + out: Vec::new(), + }; + collect(&mut walk, &self.nodes, "", self.isolated.is_empty()); + walk.out + } + + /// Bounds of everything visible except the helpers, as shown (exploded). + pub fn visible_bounds(&self) -> Aabb { + if !self.preview_parts.is_empty() { + return self.preview_parts.iter().fold(Aabb::EMPTY, |bounds, part| { + bounds.union(part.mesh.bounds.transformed(part.transform)) + }); + } + let mut bounds = self + .visible_nodes() + .iter() + .fold(Aabb::EMPTY, |b, node| b.union(self.placed_bounds(node))); + for mesh in &self.overlay.meshes { + bounds = bounds.union(mesh.bounds); + } + bounds + } + + /// Bounds of selected nodes and their subtrees, as shown (exploded). + pub fn selection_bounds(&self) -> Aabb { + fn subtree(scene: &Scene, node: &SceneNode) -> Aabb { + node.children + .iter() + .fold(scene.placed_bounds(node), |b, child| { + b.union(subtree(scene, child)) + }) + } + self.selection + .iter() + .filter_map(|key| self.find(key)) + .fold(Aabb::EMPTY, |b, node| b.union(subtree(self, node))) + } + + /// Bounds of a node's own parts where they are shown. + fn placed_bounds(&self, node: &SceneNode) -> Aabb { + node.parts.iter().fold(Aabb::EMPTY, |b, part| { + b.union(part.mesh.bounds.transformed(self.part_transform(part))) + }) + } + + /// Shows or hides a node and its whole subtree. + pub fn set_visible(&mut self, key: &str, visible: bool) { + let mut changed = false; + if let Some(node) = self.find_mut(key) { + node.visit_mut(&mut |n| { + changed |= n.visible != visible; + n.visible = visible; + }); + } + if changed { + self.shown_parts_changed(); + } + } + + pub(crate) fn pick_revision(&self) -> u64 { + self.pick_revision + } + + /// After a change of the parts shown or of where they are: the picking + /// index is rebuilt and the exploded view recentred. + fn shown_parts_changed(&mut self) { + let assembled = self + .visible_nodes() + .iter() + .fold(Aabb::EMPTY, |b, node| b.union(node.own_bounds())); + self.explode_center = if assembled.is_empty() { + Vec3::ZERO + } else { + assembled.center() + }; + self.pick_revision = next_pick_revision(); + } + + // -- exploded view and isolation ----------------------------------------- + + pub fn explode(&self) -> f32 { + self.explode + } + + /// Moves every shown part away from the centre of the shown parts by + /// `factor` times its distance to it; 0 assembles them again. + pub fn set_explode(&mut self, factor: f32) { + let factor = if factor.is_finite() { + factor.clamp(0.0, MAX_EXPLODE) + } else { + 0.0 + }; + if factor != self.explode { + self.explode = factor; + self.shown_parts_changed(); + } + } + + /// Where a part is drawn and picked: its placement, moved outwards in an + /// exploded view. Measurements and exports use the placement alone. + pub fn part_transform(&self, part: &Part) -> Mat4 { + if self.explode == 0.0 || part.mesh.bounds.is_empty() { + return part.transform; + } + let center = part.mesh.bounds.transformed(part.transform).center(); + Mat4::from_translation((center - self.explode_center) * self.explode) * part.transform + } + + pub fn is_isolating(&self) -> bool { + !self.isolated.is_empty() + } + + /// The number of isolated nodes. + pub fn isolated_count(&self) -> usize { + self.isolated.len() + } + + /// Shows only the nodes `keys` and their descendants until + /// [`Scene::end_isolation`]; visibility flags are left as they are. + /// Unknown keys are ignored, so isolating nothing changes nothing. + pub fn isolate(&mut self, keys: &[NodeKey]) { + fn collect(node: &SceneNode, parent: &str, keys: &[NodeKey], out: &mut Vec) { + let path = format!("{parent}/{}", node.name); + for child in &node.children { + collect(child, &path, keys, out); + } + if keys.contains(&node.key) && !out.contains(&path) { + out.push(path); + } + } + let mut paths = Vec::new(); + for node in &self.nodes { + collect(node, "", keys, &mut paths); + } + if !paths.is_empty() && paths != self.isolated { + self.isolated = paths; + self.shown_parts_changed(); + } + } + + pub fn end_isolation(&mut self) { + if !self.isolated.is_empty() { + self.isolated.clear(); + self.shown_parts_changed(); + } + } + + /// Ends the isolation and makes every object visible again. + pub fn show_all(&mut self) { + self.isolated.clear(); + for node in &mut self.nodes { + node.visit_mut(&mut |n| n.visible = true); + } + self.shown_parts_changed(); + } + + /// While isolating, the keys of the isolated nodes and their + /// descendants, whatever their own visibility. + pub fn isolation_members(&self) -> Option> { + fn collect<'a>( + nodes: &'a [SceneNode], + parent: &str, + isolated: &[String], + inside: bool, + out: &mut HashSet<&'a str>, + ) { + for node in nodes { + let path = format!("{parent}/{}", node.name); + let inside = inside || isolated.contains(&path); + if inside { + out.insert(&node.key); + } + collect(&node.children, &path, isolated, inside, out); + } + } + self.is_isolating().then(|| { + let mut members = HashSet::new(); + collect(&self.nodes, "", &self.isolated, false, &mut members); + members + }) + } + + /// Drops isolated paths that no longer name a node; isolating only + /// those would show nothing at all. + fn prune_isolation(&mut self) { + if self.isolated.is_empty() { + return; + } + let mut paths = HashSet::new(); + for node in &self.nodes { + node_paths(node, "", &mut paths); + } + self.isolated.retain(|path| paths.contains(path)); + } + + // -- selection --------------------------------------------------------- + + pub fn is_selected(&self, key: &str) -> bool { + self.selection.iter().any(|k| k == key) + } + + pub fn select_only(&mut self, key: &str) { + self.clear_topology_selection(); + self.selection = vec![key.to_owned()]; + } + + pub fn toggle_selected(&mut self, key: &str) { + self.clear_topology_selection(); + if let Some(index) = self.selection.iter().position(|k| k == key) { + self.selection.remove(index); + } else { + self.selection.push(key.to_owned()); + } + } + + pub fn ensure_selected(&mut self, key: &str) { + if let Some(index) = self.selection.iter().position(|candidate| candidate == key) { + self.selection.remove(index); + } + self.selection.push(key.to_owned()); + } + + pub fn clear_selection(&mut self) { + self.selection.clear(); + self.clear_topology_selection(); + } + + pub fn select_topology(&mut self, selection: TopologySelection, extend: bool) -> bool { + let highlight = self + .find(&selection.node) + .and_then(|node| node.parts.get(selection.part)) + .and_then(|part| { + part.mesh.topology_mesh(selection.entity).map(|mesh| Part { + mesh: Arc::new(mesh), + transform: part.transform, + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + render_mesh: None, + }) + }); + let Some(highlight) = highlight else { + if !extend { + self.clear_topology_selection(); + } + return false; + }; + + let same_entity = |candidate: &TopologySelection| { + candidate.node == selection.node + && candidate.part == selection.part + && candidate.entity == selection.entity + }; + if extend && let Some(index) = self.topology_selections.iter().position(same_entity) { + self.topology_selections.remove(index); + self.topology_highlights.remove(index); + return true; + } + if !extend { + self.clear_topology_selection(); + } else if self.topology_selections.len() == MAX_TOPOLOGY_SELECTIONS { + self.topology_selections.remove(0); + self.topology_highlights.remove(0); + } + self.topology_selections.push(selection); + self.topology_highlights.push(highlight); + true + } + + pub fn clear_topology_selection(&mut self) { + self.topology_selections.clear(); + self.topology_highlights.clear(); + } + + /// Highlights selector results without replacing the user's selection. + pub fn set_selector_preview(&mut self, references: &[protocol::TopologyReference]) { + self.clear_selector_preview(); + for reference in references.iter().take(64) { + let entity = match reference.kind { + protocol::TopologyKind::Face => TopologyEntity::Face(reference.identifier), + protocol::TopologyKind::Edge => TopologyEntity::Edge(reference.identifier), + protocol::TopologyKind::Vertex => TopologyEntity::Vertex(reference.identifier), + }; + let Some(part) = self + .find(&reference.key) + .and_then(|node| node.parts.get(reference.part)) + else { + continue; + }; + let Some(mesh) = part.mesh.topology_mesh(entity) else { + continue; + }; + self.selector_preview.push(( + reference.key.clone(), + reference.part, + Part { + mesh: Arc::new(mesh), + transform: part.transform, + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + render_mesh: None, + }, + )); + } + } + + pub fn clear_selector_preview(&mut self) { + self.selector_preview.clear(); + } + + pub fn selector_preview_count(&self) -> usize { + self.selector_preview.len() + } + + pub fn current_topology(&self) -> Option<&TopologySelection> { + self.topology_selections.last() + } + + #[cfg(test)] + pub fn topology_highlights(&self) -> &[Part] { + &self.topology_highlights + } + + /// The highlights with where they are shown: on their part, exploded. + pub fn placed_topology_highlights(&self) -> Vec<(&Part, Mat4)> { + let selected = self + .topology_selections + .iter() + .zip(&self.topology_highlights) + .map(|(selection, highlight)| { + let transform = self + .find(&selection.node) + .and_then(|node| node.parts.get(selection.part)) + .map_or(highlight.transform, |part| self.part_transform(part)); + (highlight, transform) + }); + let previewed = self.selector_preview.iter().map(|(key, index, highlight)| { + let transform = self + .find(key) + .and_then(|node| node.parts.get(*index)) + .map_or(highlight.transform, |part| self.part_transform(part)); + (highlight, transform) + }); + selected.chain(previewed).collect() + } + + pub fn current(&self) -> Option<&SceneNode> { + self.selection.last().and_then(|key| self.find(key)) + } + + /// Keys of selected nodes that are not inside another selected node, + /// in tree order. + pub fn selected_roots(&self) -> Vec { + fn collect(nodes: &[SceneNode], scene: &Scene, out: &mut Vec) { + for node in nodes { + if scene.is_selected(&node.key) { + out.push(node.key.clone()); + } else { + collect(&node.children, scene, out); + } + } + } + let mut out = Vec::new(); + collect(&self.nodes, self, &mut out); + out + } + + /// Top-level keys, e.g. for exporting everything. + pub fn top_level_keys(&self) -> Vec { + self.nodes.iter().map(|n| n.key.clone()).collect() + } + + /// Top-level nodes that are selected or contain a selected node. + pub fn selected_top_level(&self) -> Vec { + self.nodes + .iter() + .filter(|top| { + let mut hit = false; + top.visit(&mut |n| hit |= self.is_selected(&n.key)); + hit + }) + .map(|n| n.key.clone()) + .collect() + } + + fn prune_selection(&mut self) { + let selection = std::mem::take(&mut self.selection); + self.selection = selection + .into_iter() + .filter(|k| self.find(k).is_some()) + .collect(); + let selected: HashSet<_> = self.selection.iter().cloned().collect(); + let mut index = 0; + self.topology_selections.retain(|selection| { + let keep = selected.contains(&selection.node); + if !keep { + self.topology_highlights.remove(index); + } else { + index += 1; + } + keep + }); + } +} + +fn node_paths(node: &SceneNode, parent: &str, out: &mut HashSet) { + let path = format!("{parent}/{}", node.name); + for child in &node.children { + node_paths(child, &path, out); + } + out.insert(path); +} + +fn snapshot(node: &SceneNode, parent: &str, out: &mut PreservedProperties) { + let path = format!("{parent}/{}", node.name); + out.insert(path.clone(), (node.visible, node.overrides.clone())); + for child in &node.children { + snapshot(child, &path, out); + } +} + +fn restore(node: &mut SceneNode, parent: &str, preserved: &PreservedProperties) { + let path = format!("{parent}/{}", node.name); + if let Some((visible, overrides)) = preserved.get(&path) { + node.visible = *visible; + node.overrides = overrides.clone(); + } + for child in &mut node.children { + restore(child, &path, preserved); + } +} + +#[cfg(test)] +#[path = "../tests/rust/scene/test_scene.rs"] +mod tests; diff --git a/src/settings.rs b/src/settings.rs new file mode 100644 index 000000000..bb6d2b247 --- /dev/null +++ b/src/settings.rs @@ -0,0 +1,971 @@ +//! User preferences, persisted by eframe between sessions. +//! +//! Defaults follow the original CQ-editor where practical. Compatibility- +//! relevant deviations are recorded in `docs/development/compatibility.md`. + +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::worker::protocol::{Release, RunSettings, SceneSettings}; + +const MAX_RECENT_FILES: usize = 10; +/// Files whose breakpoints are remembered, most recently used first. +const MAX_BREAKPOINT_FILES: usize = 100; +/// Files whose named views are remembered, most recently used first. +const MAX_VIEW_FILES: usize = 100; +/// Project folders remembered, most recently opened first. +const MAX_PROJECTS: usize = 20; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct Settings { + pub general: General, + pub viewer: Viewer, + pub rendering: Rendering, + pub editor: Editor, + pub objects: Objects, + pub execution: Execution, + pub recent_files: Vec, + /// File shown on startup: the active tab of the last session. + pub last_file: Option, + /// Files open in tabs when the editor was last closed, in tab order. + pub open_files: Vec, + /// The folder shown in the Project panel. + pub project: Option, + /// Recently opened project folders and their state, most recent first. + pub projects: Vec, + /// Breakpoints of recently edited files, most recent first. + pub breakpoints: Vec, + /// Named views of recently edited files, most recent first. + pub views: Vec, + /// Favorite commands pinned to the top of the Command Palette. + pub favorite_commands: Vec, +} + +/// What is remembered of a project folder. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct ProjectState { + pub root: PathBuf, + /// The script F5 runs while a file of the project is shown; `None` + /// once cleared, so it is not guessed again. + pub main: Option, + /// Folders expanded in the Project panel. + pub expanded: Vec, +} + +/// The named views of one file. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct FileViews { + pub path: PathBuf, + pub views: Vec, +} + +/// A camera saved under a name: the point it looks at, its orientation, +/// how much it shows and its projection. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct NamedView { + pub name: String, + pub target: [f32; 3], + /// Unit quaternion (x, y, z, w). + pub rotation: [f32; 4], + /// Half the height of the view, in model units. + pub extent: f32, + pub projection: Projection, +} + +/// The breakpoints of one file. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct FileBreakpoints { + pub path: PathBuf, + pub lines: Vec, +} + +/// A breakpoint as remembered between sessions: its 1-based line and the +/// trimmed text of that line, to find it again if the file changed. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(default)] +pub struct SavedBreakpoint { + pub line: usize, + pub text: String, +} + +impl Settings { + pub fn add_recent_file(&mut self, path: &Path) { + self.recent_files.retain(|p| p != path); + self.recent_files.insert(0, path.to_path_buf()); + self.recent_files.truncate(MAX_RECENT_FILES); + } + + pub fn project_state(&self, root: &Path) -> Option<&ProjectState> { + self.projects.iter().find(|project| project.root == root) + } + + /// Remembers a project folder's state and moves it to the front of the + /// recent folders. + pub fn remember_project(&mut self, state: ProjectState) { + self.projects.retain(|project| project.root != state.root); + self.projects.insert(0, state); + self.projects.truncate(MAX_PROJECTS); + } + + /// Follows a file or folder renamed from `from` to `to`: what is + /// remembered under the old path is kept under the new one. + pub fn relocate(&mut self, from: &Path, to: &Path) { + let moved = |path: &mut PathBuf| { + if let Some(new) = crate::project::relocated(path, from, to) { + *path = new; + } + }; + self.recent_files.iter_mut().for_each(moved); + self.open_files.iter_mut().for_each(moved); + self.last_file.iter_mut().for_each(moved); + self.breakpoints + .iter_mut() + .for_each(|file| moved(&mut file.path)); + self.views.iter_mut().for_each(|file| moved(&mut file.path)); + for project in &mut self.projects { + project.main.iter_mut().for_each(moved); + project.expanded.iter_mut().for_each(moved); + } + } + + pub fn breakpoints_of(&self, path: &Path) -> &[SavedBreakpoint] { + self.breakpoints + .iter() + .find(|file| file.path == path) + .map_or(&[], |file| &file.lines) + } + + /// Remembers the breakpoints of `path`; none forgets the file. + pub fn remember_breakpoints(&mut self, path: &Path, lines: Vec) { + if self.breakpoints_of(path) == lines.as_slice() + && self + .breakpoints + .first() + .is_some_and(|file| file.path == path) + { + return; + } + self.breakpoints.retain(|file| file.path != path); + if !lines.is_empty() { + self.breakpoints.insert( + 0, + FileBreakpoints { + path: path.to_path_buf(), + lines, + }, + ); + self.breakpoints.truncate(MAX_BREAKPOINT_FILES); + } + } + + pub fn views_of(&self, path: &Path) -> &[NamedView] { + self.views + .iter() + .find(|file| file.path == path) + .map_or(&[], |file| &file.views) + } + + /// Remembers the named views of `path`; none forgets the file. + pub fn remember_views(&mut self, path: &Path, views: Vec) { + if self.views_of(path) == views.as_slice() + && self.views.first().is_some_and(|file| file.path == path) + { + return; + } + self.views.retain(|file| file.path != path); + if !views.is_empty() { + self.views.insert( + 0, + FileViews { + path: path.to_path_buf(), + views, + }, + ); + self.views.truncate(MAX_VIEW_FILES); + } + } + + pub fn run_settings(&self) -> RunSettings { + RunSettings { + reload_cq: self.execution.reload_cq, + add_script_dir_to_path: self.execution.add_script_dir_to_path, + change_working_dir: self.execution.change_working_dir, + reload_imported_modules: self.execution.reload_imported_modules, + } + } + + pub fn scene_settings(&self) -> SceneSettings { + SceneSettings { + linear_tolerance: self.viewer.linear_tolerance, + angular_tolerance: self.viewer.angular_tolerance, + merge_assemblies: self.objects.merge_assemblies, + units: self.viewer.units.export_code().to_owned(), + } + } + + pub fn is_favorite_command(&self, id: &str) -> bool { + self.favorite_commands.iter().any(|fav| fav == id) + } + + /// Toggles a command in `favorite_commands`; returns `true` when it is now a favorite. + pub fn toggle_favorite_command(&mut self, id: &str) -> bool { + if let Some(pos) = self.favorite_commands.iter().position(|fav| fav == id) { + self.favorite_commands.remove(pos); + false + } else { + self.favorite_commands.push(id.to_owned()); + true + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Theme { + /// Follow the operating system. + #[default] + System, + Light, + Dark, +} + +impl Theme { + pub const ALL: [Theme; 3] = [Theme::System, Theme::Light, Theme::Dark]; + + pub fn label(self) -> &'static str { + match self { + Theme::System => "System", + Theme::Light => "Light", + Theme::Dark => "Dark", + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct General { + pub theme: Theme, + /// Python interpreter with CadQuery; empty means auto-detect. + pub python: String, + /// Scale factor on top of the system's. + pub ui_scale: f32, + /// Look for a newer CQ-editor once a day, when Python starts. + pub check_updates: bool, + /// When it last looked, in seconds since the Unix epoch. + pub last_update_check: u64, + /// The newest release it found then (see `updates::available`). + pub newer_release: Option, +} + +impl Default for General { + fn default() -> Self { + Self { + theme: Theme::System, + python: String::new(), + ui_scale: 1.0, + check_updates: true, + last_update_check: 0, + newer_release: None, + } + } +} + +/// The original editor's projection types, under the same names. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Projection { + #[default] + Orthographic, + Perspective, + /// Perspective seen by two eyes, composed as [`Viewer::stereo_mode`] + /// says. + Stereo, + /// Perspective from the left eye of the stereo pair alone. + MonoLeftEye, + MonoRightEye, +} + +impl Projection { + pub const ALL: [Projection; 5] = [ + Projection::Orthographic, + Projection::Perspective, + Projection::Stereo, + Projection::MonoLeftEye, + Projection::MonoRightEye, + ]; + + pub fn label(self) -> &'static str { + match self { + Projection::Orthographic => "Orthographic", + Projection::Perspective => "Perspective", + Projection::Stereo => "Stereo", + Projection::MonoLeftEye => "Mono Left Eye", + Projection::MonoRightEye => "Mono Right Eye", + } + } + + /// All but orthographic projection have a vanishing point. + pub fn is_perspective(self) -> bool { + self != Projection::Orthographic + } +} + +/// How the two images of the stereo projection are combined, under the +/// original editor's names. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum StereoMode { + /// Hardware stereo (one buffer per eye), which this renderer cannot + /// present: shown as [`StereoMode::Anaglyph`] instead. + QuadBuffer, + /// Red-cyan glasses. + #[default] + Anaglyph, + /// Even rows for the left eye, odd ones for the right (passive 3D + /// displays). + RowInterlaced, + ColumnInterlaced, + ChessBoard, + /// The left eye's image on the left half, the right eye's on the right. + SideBySide, + /// The left eye's image on the top half. + OverUnder, +} + +impl StereoMode { + pub const ALL: [StereoMode; 7] = [ + StereoMode::QuadBuffer, + StereoMode::Anaglyph, + StereoMode::RowInterlaced, + StereoMode::ColumnInterlaced, + StereoMode::ChessBoard, + StereoMode::SideBySide, + StereoMode::OverUnder, + ]; + + pub fn label(self) -> &'static str { + match self { + StereoMode::QuadBuffer => "Quad Buffer", + StereoMode::Anaglyph => "Anaglyph (red-cyan)", + StereoMode::RowInterlaced => "Row Interlaced", + StereoMode::ColumnInterlaced => "Column Interlaced", + StereoMode::ChessBoard => "Chess Board", + StereoMode::SideBySide => "Side by Side", + StereoMode::OverUnder => "Over Under", + } + } + + /// The mode actually shown: quad-buffered stereo needs a stereo + /// swap chain, which wgpu does not offer on any platform. + pub fn shown(self) -> StereoMode { + match self { + StereoMode::QuadBuffer => StereoMode::Anaglyph, + mode => mode, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum OrbitMethod { + /// Rotation about the world Z axis and the screen's horizontal axis; + /// Z stays up. + #[default] + Turntable, + /// Free rotation, like rolling a ball under the mouse. + Trackball, +} + +impl OrbitMethod { + pub const ALL: [OrbitMethod; 2] = [OrbitMethod::Turntable, OrbitMethod::Trackball]; + + pub fn label(self) -> &'static str { + match self { + OrbitMethod::Turntable => "Turntable", + OrbitMethod::Trackball => "Trackball", + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Viewer { + pub fit_automatically: bool, + pub show_navigation_cube: bool, + pub show_axes_indicator: bool, + pub use_gradient: bool, + /// sRGB. + pub background: [u8; 3], + /// Bottom color of the gradient, sRGB. + pub background_aux: [u8; 3], + pub default_color: [u8; 3], + pub edge_color: [u8; 3], + pub show_edges: bool, + /// Hidden edges as faint dashes in the hidden-line display mode. + pub hidden_edges: bool, + pub edge_width: f32, + /// Chordal deviation of the mesh relative to the object size. + pub linear_tolerance: f64, + /// Radians. + pub angular_tolerance: f64, + pub projection: Projection, + pub orbit_method: OrbitMethod, + /// Animate view changes (standard views, navigation cube, fit). + pub animate: bool, + /// When parts drawn small are simplified. + pub large_models: LargeModels, + /// The grid on the XY plane. + pub ground_grid: bool, + pub scale_bar: bool, + /// What a model unit is called in the scale bar. + pub units: Units, + /// How the stereo projection shows its two images. + pub stereo_mode: StereoMode, + /// Configurable keyboard shortcuts for switching 3D selection modes. + pub selection_shortcuts: SelectionShortcuts, +} + +/// Configurable keyboard shortcuts for switching between 3D selection modes +/// when no text field has keyboard focus (or anytime if combined with Ctrl/Alt). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct SelectionShortcuts { + pub auto: String, + pub object: String, + pub face: String, + pub edge: String, + pub vertex: String, +} + +impl Default for SelectionShortcuts { + fn default() -> Self { + Self { + auto: "1".to_owned(), + object: "2".to_owned(), + face: "3".to_owned(), + edge: "4".to_owned(), + vertex: "5".to_owned(), + } + } +} + +impl SelectionShortcuts { + pub fn get(&self, mode: crate::viewer::SelectionMode) -> &str { + use crate::viewer::SelectionMode; + match mode { + SelectionMode::Auto => &self.auto, + SelectionMode::Object => &self.object, + SelectionMode::Face => &self.face, + SelectionMode::Edge => &self.edge, + SelectionMode::Vertex => &self.vertex, + } + } + + pub fn get_mut(&mut self, mode: crate::viewer::SelectionMode) -> &mut String { + use crate::viewer::SelectionMode; + match mode { + SelectionMode::Auto => &mut self.auto, + SelectionMode::Object => &mut self.object, + SelectionMode::Face => &mut self.face, + SelectionMode::Edge => &mut self.edge, + SelectionMode::Vertex => &mut self.vertex, + } + } +} + +/// What a model unit is: CadQuery has no units, so the editor supplies this +/// interpretation to exports and measurement labels. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Units { + #[default] + Millimeters, + Centimeters, + Meters, + Inches, + /// Plain numbers. + None, +} + +impl Units { + pub const ALL: [Units; 5] = [ + Units::Millimeters, + Units::Centimeters, + Units::Meters, + Units::Inches, + Units::None, + ]; + + pub fn label(self) -> &'static str { + match self { + Units::Millimeters => "Millimeters", + Units::Centimeters => "Centimeters", + Units::Meters => "Meters", + Units::Inches => "Inches", + Units::None => "None", + } + } + + pub fn suffix(self) -> &'static str { + match self { + Units::Millimeters => "mm", + Units::Centimeters => "cm", + Units::Meters => "m", + Units::Inches => "in", + Units::None => "", + } + } + + pub fn export_code(self) -> &'static str { + match self { + Units::Millimeters => "millimeter", + Units::Centimeters => "centimeter", + Units::Meters => "meter", + Units::Inches => "inch", + Units::None => "none", + } + } +} + +/// When the view simplifies the parts it draws small (large-model mode). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum LargeModels { + /// From a couple of million triangles shown. + #[default] + Automatic, + Always, + Off, +} + +impl LargeModels { + pub const ALL: [LargeModels; 3] = [ + LargeModels::Automatic, + LargeModels::Always, + LargeModels::Off, + ]; + + pub fn label(self) -> &'static str { + match self { + LargeModels::Automatic => "Automatic", + LargeModels::Always => "Always", + LargeModels::Off => "Off", + } + } +} + +impl Default for Viewer { + fn default() -> Self { + Self { + fit_automatically: true, + show_navigation_cube: true, + show_axes_indicator: true, + use_gradient: false, + background: [95, 95, 95], + background_aux: [30, 30, 30], + default_color: [255, 215, 0], + edge_color: [0, 0, 0], + show_edges: true, + hidden_edges: true, + edge_width: 1.5, + linear_tolerance: 1e-3, + angular_tolerance: 0.2, + projection: Projection::Orthographic, + orbit_method: OrbitMethod::Turntable, + animate: true, + large_models: LargeModels::Automatic, + ground_grid: true, + scale_bar: true, + units: Units::Millimeters, + stereo_mode: StereoMode::Anaglyph, + selection_shortcuts: SelectionShortcuts::default(), + } + } +} + +/// How the 3D view lights the faces it draws, and which of their edges it +/// draws. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Rendering { + pub lighting: Lighting, + /// Which edges the Shaded, X-Ray and Hidden Line modes draw. + pub edges: EdgeStyle, + /// Edges whose faces meet at less than this many degrees are smooth: + /// the Sharp and Outline styles leave them out. + pub sharp_angle: f32, + /// The Presentation display mode's own settings. + pub presentation: Presentation, +} + +impl Default for Rendering { + fn default() -> Self { + Self { + lighting: Lighting::default(), + edges: EdgeStyle::All, + sharp_angle: 30.0, + presentation: Presentation::default(), + } + } +} + +/// The Presentation display mode, for showing a model rather than working +/// on it: lights, edges, a material for objects without one, a background +/// and helpers of its own, so switching back to Shaded restores the +/// modeling view untouched. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Presentation { + pub lighting: Lighting, + /// Edges are drawn at all; off, the shapes speak alone. + pub show_edges: bool, + /// Which edges, when they are drawn. + pub edges: EdgeStyle, + /// The material of objects whose script and Objects panel choose none. + pub material: Finish, + /// The background, a vertical gradient from top to bottom (sRGB). + pub background_top: [u8; 3], + pub background_bottom: [u8; 3], + /// The axes and the ground grid are drawn. + pub helpers: bool, + /// A soft shadow on the ground under the model. + pub shadow: bool, + /// How dark the shadow is where the model touches the ground, 0 to 1. + pub shadow_strength: f32, + /// How far the shadow's edge spreads, 0 (crisp) to 1 (very soft). + pub shadow_softness: f32, +} + +impl Default for Presentation { + fn default() -> Self { + Self { + lighting: LightingPreset::Studio.lighting(), + show_edges: false, + edges: EdgeStyle::Outline, + material: Finish::MattePlastic, + background_top: [236, 237, 240], + background_bottom: [188, 191, 198], + helpers: false, + shadow: true, + shadow_strength: 0.6, + shadow_softness: 0.5, + } + } +} + +/// The look of a surface: the plain shading of a CAD view, or a material +/// shaded by its metalness and roughness. Scripts choose one with +/// `show_object(..., material="matte plastic")`, the Objects panel per +/// object. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum Finish { + /// The shading of earlier releases, with the lighting's highlights. + #[default] + Default, + MattePlastic, + GlossyPlastic, + BrushedSteel, + Aluminum, + /// Plain wood with a procedural grain around the part's Z axis. + Wood, +} + +impl Finish { + pub const ALL: [Finish; 6] = [ + Finish::Default, + Finish::MattePlastic, + Finish::GlossyPlastic, + Finish::BrushedSteel, + Finish::Aluminum, + Finish::Wood, + ]; + + pub fn label(self) -> &'static str { + match self { + Finish::Default => "Default", + Finish::MattePlastic => "Matte plastic", + Finish::GlossyPlastic => "Glossy plastic", + Finish::BrushedSteel => "Brushed steel", + Finish::Aluminum => "Aluminum", + Finish::Wood => "Wood", + } + } + + /// The name the worker sends for `show_object`'s `material` option. + pub fn name(self) -> &'static str { + match self { + Finish::Default => "default", + Finish::MattePlastic => "matte_plastic", + Finish::GlossyPlastic => "glossy_plastic", + Finish::BrushedSteel => "brushed_steel", + Finish::Aluminum => "aluminum", + Finish::Wood => "wood", + } + } + + pub fn from_name(name: &str) -> Option { + Finish::ALL.into_iter().find(|finish| finish.name() == name) + } + + /// How the shader draws it: model (0 plain, 1 physically based, 2 the + /// same with a wood grain), metalness and roughness. + pub fn surface(self) -> [f32; 4] { + let (model, metallic, roughness) = match self { + Finish::Default => (0.0, 0.0, 0.0), + Finish::MattePlastic => (1.0, 0.0, 0.75), + Finish::GlossyPlastic => (1.0, 0.0, 0.2), + Finish::BrushedSteel => (1.0, 1.0, 0.55), + Finish::Aluminum => (1.0, 1.0, 0.3), + Finish::Wood => (2.0, 0.0, 0.65), + }; + [model, metallic, roughness, 0.0] + } + + /// The color of the material itself (sRGB), for objects without a + /// color of their own; plastics take the default object color. + pub fn natural_color(self) -> Option<[f32; 3]> { + match self { + Finish::BrushedSteel => Some([0.62, 0.63, 0.64]), + Finish::Aluminum => Some([0.91, 0.92, 0.93]), + Finish::Wood => Some([0.72, 0.52, 0.32]), + Finish::Default | Finish::MattePlastic | Finish::GlossyPlastic => None, + } + } +} + +/// Which edges of a model are drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum EdgeStyle { + /// Every edge of every face, as in earlier releases. + #[default] + All, + /// The edges where faces meet at an angle, and the borders of open + /// faces: not those between faces that continue smoothly (a fillet's + /// borders, seams of cylinders), which clutter curved and fluted + /// models. + Sharp, + /// The sharp edges plus the outline of curved surfaces seen from the + /// camera, as a drawing has them. + Outline, +} + +impl EdgeStyle { + pub const ALL: [EdgeStyle; 3] = [EdgeStyle::All, EdgeStyle::Sharp, EdgeStyle::Outline]; + + pub fn label(self) -> &'static str { + match self { + EdgeStyle::All => "All edges", + EdgeStyle::Sharp => "Sharp edges", + EdgeStyle::Outline => "Outline", + } + } + + /// The smallest angle (degrees) an edge must have to be drawn, with a + /// sharp angle of `sharp`. + pub fn minimum_angle(self, sharp: f32) -> f32 { + match self { + EdgeStyle::All => 0.0, + EdgeStyle::Sharp | EdgeStyle::Outline => sharp.clamp(0.0, 179.0), + } + } +} + +/// The lights of the 3D view. They are attached to the camera, as a +/// photographer's lights are to the subject: the model is lit the same way +/// from every side it is seen from. The defaults are the look of earlier +/// releases. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Lighting { + /// The main light, from the upper left. + pub key: f32, + /// A softer light from the lower right, which keeps shadows readable. + pub fill: f32, + /// Light from everywhere: the darkest a face can be. + pub ambient: f32, + /// Light grazing the outline of curved surfaces. + pub rim: f32, + /// Strength of the highlights of the key light. + pub specular: f32, + /// Sharpness of the highlights: higher is glossier. + pub shininess: f32, + /// Where the key light comes from, in degrees: around the line of + /// sight (negative is left) and above it. + pub azimuth: f32, + pub elevation: f32, + /// Brightness in photographic stops: +1 doubles the light. + pub exposure: f32, + /// 1 leaves the lit colors as they are; above 1 darkens the shadows and + /// brightens the lights around middle grey. + pub contrast: f32, +} + +impl Default for Lighting { + fn default() -> Self { + LightingPreset::Default.lighting() + } +} + +impl Lighting { + /// Direction of the key light in the camera's frame: right, up, and + /// towards the viewer. + pub fn key_direction(&self) -> [f32; 3] { + let (azimuth, elevation) = (self.azimuth.to_radians(), self.elevation.to_radians()); + [ + elevation.cos() * azimuth.sin(), + elevation.sin(), + elevation.cos() * azimuth.cos(), + ] + } + + /// The preset these values are, if any. + pub fn preset(&self) -> Option { + LightingPreset::ALL + .into_iter() + .find(|preset| preset.lighting() == *self) + } +} + +/// Starting points for [`Lighting`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LightingPreset { + /// The look of earlier releases: crisp, for modeling. + Default, + /// Soft and even, with gentle highlights, for showing a model. + Studio, + /// Lighter overall, for dark colors. + Bright, + /// One strong light from the side, deep shadows, sharp highlights. + Dramatic, +} + +impl LightingPreset { + pub const ALL: [LightingPreset; 4] = [ + LightingPreset::Default, + LightingPreset::Studio, + LightingPreset::Bright, + LightingPreset::Dramatic, + ]; + + pub fn label(self) -> &'static str { + match self { + LightingPreset::Default => "Default", + LightingPreset::Studio => "Studio", + LightingPreset::Bright => "Bright", + LightingPreset::Dramatic => "Dramatic", + } + } + + pub fn lighting(self) -> Lighting { + let (key, fill, ambient, rim, specular, shininess) = match self { + LightingPreset::Default => (0.62, 0.24, 0.24, 0.10, 0.22, 48.0), + LightingPreset::Studio => (0.52, 0.34, 0.30, 0.16, 0.28, 64.0), + LightingPreset::Bright => (0.70, 0.36, 0.36, 0.10, 0.20, 32.0), + LightingPreset::Dramatic => (0.95, 0.08, 0.10, 0.24, 0.45, 96.0), + }; + let (azimuth, elevation, exposure, contrast) = match self { + // The key light of earlier releases: (-0.35, 0.55, 0.76). + LightingPreset::Default => (-24.7, 33.3, 0.0, 1.0), + LightingPreset::Studio => (-35.0, 40.0, 0.15, 1.05), + LightingPreset::Bright => (-25.0, 35.0, 0.35, 0.95), + LightingPreset::Dramatic => (-60.0, 25.0, 0.0, 1.3), + }; + Lighting { + key, + fill, + ambient, + rim, + specular, + shininess, + azimuth, + elevation, + exposure, + contrast, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Editor { + pub font_size: f32, + /// Re-run the script whenever its file changes on disk. + pub autoreload: bool, + /// Wait this long after a change, so the file is completely written. + pub autoreload_delay_ms: u64, + pub watch_imported_modules: bool, + pub line_wrap: bool, + /// Column of the vertical ruler; 0 hides it. + pub max_line_length: usize, + pub highlight_current_line: bool, + pub auto_indent: bool, + /// Offer completions after this many characters of a name; 0 offers + /// them only after `.` and on Ctrl+Space. + pub completion_min_chars: usize, +} + +impl Default for Editor { + fn default() -> Self { + Self { + font_size: 13.0, + autoreload: false, + autoreload_delay_ms: 50, + watch_imported_modules: false, + line_wrap: false, + max_line_length: 79, + highlight_current_line: true, + auto_indent: true, + completion_min_chars: 3, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Objects { + /// Keep visibility and colors of objects across runs (matched by name). + pub preserve_properties: bool, + pub clear_before_run: bool, + /// Show assemblies as one object instead of one per part. + pub merge_assemblies: bool, + /// STL export chordal tolerance, model units. + pub stl_tolerance: f64, + /// STL export angular tolerance, radians. + pub stl_angular_tolerance: f64, +} + +impl Default for Objects { + fn default() -> Self { + Self { + preserve_properties: false, + clear_before_run: true, + merge_assemblies: false, + stl_tolerance: 0.1, + stl_angular_tolerance: 0.1, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Execution { + pub reload_cq: bool, + pub add_script_dir_to_path: bool, + pub change_working_dir: bool, + pub reload_imported_modules: bool, +} + +impl Default for Execution { + fn default() -> Self { + Self { + reload_cq: false, + add_script_dir_to_path: true, + change_working_dir: true, + reload_imported_modules: true, + } + } +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_settings.rs"] +mod tests; diff --git a/src/spatial.rs b/src/spatial.rs new file mode 100644 index 000000000..b2bf34966 --- /dev/null +++ b/src/spatial.rs @@ -0,0 +1,371 @@ +//! Spatial acceleration structures shared by scene queries. + +use glam::Vec3; + +const LEAF_TRIANGLES: usize = 8; +const LEAF_BOUNDS: usize = 8; + +#[derive(Clone, Copy, Debug)] +struct Bounds { + min: Vec3, + max: Vec3, +} + +impl Bounds { + const EMPTY: Self = Self { + min: Vec3::splat(f32::INFINITY), + max: Vec3::splat(f32::NEG_INFINITY), + }; + + fn include(mut self, point: Vec3) -> Self { + self.min = self.min.min(point); + self.max = self.max.max(point); + self + } + + fn union(self, other: Self) -> Self { + Self { + min: self.min.min(other.min), + max: self.max.max(other.max), + } + } +} + +#[derive(Debug)] +enum NodeKind { + Leaf { start: usize, count: usize }, + Branch { left: usize, right: usize }, +} + +#[derive(Debug)] +struct Node { + bounds: Bounds, + kind: NodeKind, +} + +#[derive(Debug)] +struct Triangle { + index: usize, + bounds: Bounds, + center: Vec3, +} + +/// BVH over arbitrary axis-aligned primitive bounds. It is used for scene +/// parts, line segments and points, whose exact pick tests live elsewhere. +#[derive(Debug, Default)] +pub(crate) struct BoundsBvh { + nodes: Vec, + primitives: Vec, + bounds: Vec, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct QueryStats { + pub(crate) visited_nodes: usize, + pub(crate) tested_bounds: usize, +} + +impl BoundsBvh { + pub(crate) fn build(bounds: impl IntoIterator) -> Self { + let bounds: Vec = bounds + .into_iter() + .map(|(min, max)| Bounds { min, max }) + .collect(); + let mut primitives: Vec = bounds + .iter() + .copied() + .enumerate() + .map(|(index, bounds)| Triangle { + index, + bounds, + center: (bounds.min + bounds.max) * 0.5, + }) + .collect(); + if primitives.is_empty() { + return Self::default(); + } + + let mut result = Self { + bounds, + ..Self::default() + }; + build_node( + &mut result.nodes, + &mut result.primitives, + &mut primitives, + LEAF_BOUNDS, + ); + result + } + + pub(crate) fn query( + &self, + intersects: impl FnMut(Vec3, Vec3) -> bool, + output: &mut Vec, + ) { + self.query_with_stats(intersects, output); + } + + /// Appends the primitives whose bounds pass `intersects` in ascending + /// index order, so callers resolve ties exactly as a linear scan would. + pub(crate) fn query_with_stats( + &self, + mut intersects: impl FnMut(Vec3, Vec3) -> bool, + output: &mut Vec, + ) -> QueryStats { + let mut stats = QueryStats::default(); + if self.nodes.is_empty() { + return stats; + } + + let first = output.len(); + let mut stack = vec![0usize]; + while let Some(node_index) = stack.pop() { + stats.visited_nodes += 1; + let node = &self.nodes[node_index]; + if !intersects(node.bounds.min, node.bounds.max) { + continue; + } + match node.kind { + NodeKind::Leaf { start, count } => { + for &primitive in &self.primitives[start..start + count] { + stats.tested_bounds += 1; + let bounds = self.bounds[primitive]; + if intersects(bounds.min, bounds.max) { + output.push(primitive); + } + } + } + NodeKind::Branch { left, right } => { + stack.push(right); + stack.push(left); + } + } + } + output[first..].sort_unstable(); + stats + } +} + +/// Bounding-volume hierarchy over a mesh's triangle list. +#[derive(Debug, Default)] +pub(crate) struct TriangleBvh { + nodes: Vec, + triangles: Vec, +} + +impl TriangleBvh { + pub(crate) fn build(positions: &[[f32; 3]], indices: &[u32]) -> Self { + let vertex = |index: u32| positions.get(index as usize).copied().map(Vec3::from_array); + let mut triangles: Vec = indices + .as_chunks::<3>() + .0 + .iter() + .enumerate() + .filter_map(|(index, triangle)| { + let (Some(a), Some(b), Some(c)) = ( + vertex(triangle[0]), + vertex(triangle[1]), + vertex(triangle[2]), + ) else { + return None; + }; + let bounds = Bounds::EMPTY.include(a).include(b).include(c); + Some(Triangle { + index, + bounds, + center: (a + b + c) / 3.0, + }) + }) + .collect(); + if triangles.is_empty() { + return Self::default(); + } + + let mut result = Self::default(); + build_node( + &mut result.nodes, + &mut result.triangles, + &mut triangles, + LEAF_TRIANGLES, + ); + result + } + + #[cfg(test)] + pub(crate) fn nearest_with_count( + &self, + origin: Vec3, + direction: Vec3, + positions: &[[f32; 3]], + indices: &[u32], + ) -> (Option<(f32, usize)>, usize) { + self.nearest_within(origin, direction, positions, indices, (0.0, f32::INFINITY)) + } + + /// The nearest hit whose ray parameter lies in `range` (inclusive), e.g. + /// the part of the ray a section plane keeps, and the triangles tested. + pub(crate) fn nearest_within( + &self, + origin: Vec3, + direction: Vec3, + positions: &[[f32; 3]], + indices: &[u32], + range: (f32, f32), + ) -> (Option<(f32, usize)>, usize) { + if self.nodes.is_empty() { + return (None, 0); + } + let mut stack = vec![0usize]; + let mut nearest = None; + let mut tested = 0; + while let Some(node_index) = stack.pop() { + let node = &self.nodes[node_index]; + let limit = nearest.map_or(range.1, |(distance, _)| distance); + if ray_box(origin, direction, node.bounds).is_none_or(|near| near > limit) { + continue; + } + match node.kind { + NodeKind::Leaf { start, count } => { + for &triangle_index in &self.triangles[start..start + count] { + tested += 1; + let Some(triangle) = indices + .get(triangle_index * 3..triangle_index * 3 + 3) + .and_then(|slice| <&[u32; 3]>::try_from(slice).ok()) + else { + continue; + }; + let vertex = |index: u32| { + positions.get(index as usize).copied().map(Vec3::from_array) + }; + let (Some(a), Some(b), Some(c)) = ( + vertex(triangle[0]), + vertex(triangle[1]), + vertex(triangle[2]), + ) else { + continue; + }; + if let Some(distance) = ray_triangle(origin, direction, a, b, c) + && (range.0..=range.1).contains(&distance) + && nearest.is_none_or(|hit| distance < hit.0) + { + nearest = Some((distance, triangle_index)); + } + } + } + NodeKind::Branch { left, right } => { + let left_distance = ray_box(origin, direction, self.nodes[left].bounds); + let right_distance = ray_box(origin, direction, self.nodes[right].bounds); + match (left_distance, right_distance) { + (Some(a), Some(b)) if a <= b => { + stack.push(right); + stack.push(left); + } + (Some(_), Some(_)) => { + stack.push(left); + stack.push(right); + } + (Some(_), None) => stack.push(left), + (None, Some(_)) => stack.push(right), + (None, None) => {} + } + } + } + } + (nearest, tested) + } +} + +fn build_node( + nodes: &mut Vec, + ordered: &mut Vec, + triangles: &mut [Triangle], + leaf_size: usize, +) -> usize { + let bounds = triangles.iter().fold(Bounds::EMPTY, |bounds, triangle| { + bounds.union(triangle.bounds) + }); + let index = nodes.len(); + nodes.push(Node { + bounds, + kind: NodeKind::Leaf { start: 0, count: 0 }, + }); + + if triangles.len() <= leaf_size { + let start = ordered.len(); + ordered.extend(triangles.iter().map(|triangle| triangle.index)); + nodes[index].kind = NodeKind::Leaf { + start, + count: triangles.len(), + }; + return index; + } + + let centers = triangles.iter().fold(Bounds::EMPTY, |bounds, triangle| { + bounds.include(triangle.center) + }); + let size = centers.max - centers.min; + let axis = if size.x >= size.y && size.x >= size.z { + 0 + } else if size.y >= size.z { + 1 + } else { + 2 + }; + triangles.sort_unstable_by(|a, b| a.center[axis].total_cmp(&b.center[axis])); + let middle = triangles.len() / 2; + let (left_triangles, right_triangles) = triangles.split_at_mut(middle); + let left = build_node(nodes, ordered, left_triangles, leaf_size); + let right = build_node(nodes, ordered, right_triangles, leaf_size); + nodes[index].kind = NodeKind::Branch { left, right }; + index +} + +/// Slab intersection returning the first non-negative distance. +fn ray_box(origin: Vec3, direction: Vec3, bounds: Bounds) -> Option { + let mut near: f32 = 0.0; + let mut far = f32::INFINITY; + for axis in 0..3 { + if direction[axis].abs() < 1e-12 { + if origin[axis] < bounds.min[axis] || origin[axis] > bounds.max[axis] { + return None; + } + continue; + } + let inverse = 1.0 / direction[axis]; + let mut a = (bounds.min[axis] - origin[axis]) * inverse; + let mut b = (bounds.max[axis] - origin[axis]) * inverse; + if a > b { + std::mem::swap(&mut a, &mut b); + } + near = near.max(a); + far = far.min(b); + if near > far { + return None; + } + } + (far >= 0.0).then_some(near) +} + +/// Moller-Trumbore intersection, accepting both triangle sides. +fn ray_triangle(origin: Vec3, direction: Vec3, a: Vec3, b: Vec3, c: Vec3) -> Option { + let (ab, ac) = (b - a, c - a); + let p = direction.cross(ac); + let determinant = ab.dot(p); + if determinant.abs() < 1e-12 { + return None; + } + let inverse = 1.0 / determinant; + let s = origin - a; + let u = s.dot(p) * inverse; + if !(0.0..=1.0).contains(&u) { + return None; + } + let q = s.cross(ab); + let v = direction.dot(q) * inverse; + if v < 0.0 || u + v > 1.0 { + return None; + } + let distance = ac.dot(q) * inverse; + (distance > 0.0).then_some(distance) +} diff --git a/src/theme.rs b/src/theme.rs new file mode 100644 index 000000000..dd2338f97 --- /dev/null +++ b/src/theme.rs @@ -0,0 +1,388 @@ +//! Look and feel: egui visuals for the light and dark themes plus the colors +//! of the editor, syntax highlighting and 3D view that go with them. + +use egui::{ + Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Margin, Shadow, Stroke, + Theme, Vec2, Visuals, +}; + +use crate::editor::EditorColors; +use crate::editor::highlight::SyntaxColors; +use crate::settings; +use crate::viewer::{CubeColors, ViewerColors}; + +/// Colors shared across the UI. +#[derive(Clone, Copy, Debug)] +pub struct Palette { + pub dark: bool, + pub window: Color32, + pub panel: Color32, + pub surface: Color32, + pub border: Color32, + pub text: Color32, + pub text_weak: Color32, + pub accent: Color32, + pub error: Color32, + pub warning: Color32, + pub success: Color32, +} + +impl Palette { + pub const DARK: Palette = Palette { + dark: true, + window: Color32::from_rgb(30, 31, 34), + panel: Color32::from_rgb(43, 45, 48), + surface: Color32::from_rgb(30, 31, 34), + border: Color32::from_rgb(57, 59, 64), + text: Color32::from_rgb(223, 225, 229), + text_weak: Color32::from_rgb(140, 143, 148), + accent: Color32::from_rgb(53, 116, 240), + error: Color32::from_rgb(247, 84, 100), + warning: Color32::from_rgb(242, 197, 92), + success: Color32::from_rgb(95, 184, 101), + }; + + pub const LIGHT: Palette = Palette { + dark: false, + window: Color32::from_rgb(247, 248, 250), + panel: Color32::from_rgb(235, 236, 240), + surface: Color32::from_rgb(255, 255, 255), + border: Color32::from_rgb(211, 213, 219), + text: Color32::from_rgb(31, 35, 40), + text_weak: Color32::from_rgb(108, 112, 126), + accent: Color32::from_rgb(53, 116, 240), + error: Color32::from_rgb(211, 47, 47), + warning: Color32::from_rgb(184, 134, 11), + success: Color32::from_rgb(46, 125, 50), + }; + + pub fn of(theme: Theme) -> Palette { + match theme { + Theme::Dark => Palette::DARK, + Theme::Light => Palette::LIGHT, + } + } + + pub fn editor(&self) -> EditorColors { + if self.dark { + EditorColors { + syntax: SyntaxColors { + text: Color32::from_rgb(212, 212, 212), + keyword: Color32::from_rgb(86, 156, 214), + constant: Color32::from_rgb(86, 156, 214), + builtin: Color32::from_rgb(78, 201, 176), + editor_api: Color32::from_rgb(220, 220, 170), + self_param: Color32::from_rgb(156, 220, 254), + string: Color32::from_rgb(206, 145, 120), + number: Color32::from_rgb(181, 206, 168), + comment: Color32::from_rgb(106, 153, 85), + decorator: Color32::from_rgb(197, 134, 192), + function: Color32::from_rgb(220, 220, 170), + class: Color32::from_rgb(78, 201, 176), + operator: Color32::from_rgb(180, 180, 180), + }, + gutter_text: Color32::from_rgb(98, 101, 108), + gutter_text_current: Color32::from_rgb(170, 173, 180), + current_line: Color32::from_rgb(38, 40, 46), + ruler: Color32::from_rgb(55, 57, 63), + breakpoint: Color32::from_rgb(229, 83, 83), + debug_line: Color32::from_rgba_unmultiplied(242, 197, 92, 38), + debug_marker: Color32::from_rgb(242, 197, 92), + error_line: Color32::from_rgba_unmultiplied(247, 84, 100, 40), + error_text: self.error, + search_match: Color32::from_rgba_unmultiplied(255, 210, 60, 55), + search_current: Color32::from_rgba_unmultiplied(255, 140, 0, 130), + } + } else { + EditorColors { + syntax: SyntaxColors { + text: Color32::from_rgb(31, 31, 31), + keyword: Color32::from_rgb(0, 0, 255), + constant: Color32::from_rgb(0, 0, 255), + builtin: Color32::from_rgb(38, 127, 153), + editor_api: Color32::from_rgb(121, 94, 38), + self_param: Color32::from_rgb(0, 16, 128), + string: Color32::from_rgb(163, 21, 21), + number: Color32::from_rgb(9, 134, 88), + comment: Color32::from_rgb(0, 128, 0), + decorator: Color32::from_rgb(175, 0, 219), + function: Color32::from_rgb(121, 94, 38), + class: Color32::from_rgb(38, 127, 153), + operator: Color32::from_rgb(70, 70, 70), + }, + gutter_text: Color32::from_rgb(160, 164, 171), + gutter_text_current: Color32::from_rgb(60, 64, 72), + current_line: Color32::from_rgb(242, 245, 250), + ruler: Color32::from_rgb(226, 228, 233), + breakpoint: Color32::from_rgb(224, 62, 62), + debug_line: Color32::from_rgba_unmultiplied(255, 200, 0, 60), + debug_marker: Color32::from_rgb(232, 164, 0), + error_line: Color32::from_rgba_unmultiplied(230, 60, 60, 36), + error_text: self.error, + search_match: Color32::from_rgba_unmultiplied(255, 220, 0, 100), + search_current: Color32::from_rgba_unmultiplied(255, 150, 0, 160), + } + } + } + + pub fn viewer(&self) -> ViewerColors { + let cube = if self.dark { + CubeColors { + face: Color32::from_rgb(205, 208, 214), + chamfer: Color32::from_rgb(170, 174, 182), + outline: Color32::from_rgb(70, 73, 80), + text: Color32::from_rgb(40, 42, 46), + highlight: Color32::from_rgb(90, 160, 255), + } + } else { + CubeColors { + face: Color32::from_rgb(222, 224, 229), + chamfer: Color32::from_rgb(190, 193, 200), + outline: Color32::from_rgb(110, 113, 120), + text: Color32::from_rgb(35, 37, 41), + highlight: Color32::from_rgb(70, 140, 255), + } + }; + ViewerColors { + selection: Color32::from_rgb(90, 170, 255), + hover: Color32::from_rgb(140, 195, 255), + overlay: Color32::from_rgb(255, 92, 54), + grid: Color32::from_rgb(178, 178, 178), + cube, + overlay_text: Color32::from_rgb(240, 240, 242), + overlay_background: Color32::from_rgba_unmultiplied(22, 23, 26, 210), + } + } +} + +/// Font family of headings. +const SEMIBOLD: &str = "semibold"; + +/// Inter for the interface, JetBrains Mono for code, Phosphor for icons; +/// egui's built-in fonts remain as fallbacks for other characters. +pub fn fonts() -> FontDefinitions { + let mut fonts = FontDefinitions::default(); + for (name, bytes) in [ + ( + "inter", + &include_bytes!("../assets/fonts/Inter-Regular.ttf")[..], + ), + ( + "inter-semibold", + &include_bytes!("../assets/fonts/Inter-SemiBold.ttf")[..], + ), + ( + "jetbrains-mono", + &include_bytes!("../assets/fonts/JetBrainsMono-Regular.ttf")[..], + ), + ] { + fonts.font_data.insert( + name.to_owned(), + std::sync::Arc::new(FontData::from_static(bytes)), + ); + } + fonts + .families + .entry(FontFamily::Proportional) + .or_default() + .insert(0, "inter".to_owned()); + fonts + .families + .entry(FontFamily::Monospace) + .or_default() + .insert(0, "jetbrains-mono".to_owned()); + // After the text fonts, so icons are found without shadowing letters. + egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); + // Cloned only now, so headings (window titles) have the icons too. + let mut semibold = fonts.families[&FontFamily::Proportional].clone(); + semibold.insert(0, "inter-semibold".to_owned()); + fonts + .families + .insert(FontFamily::Name(SEMIBOLD.into()), semibold); + fonts +} + +/// Installs the light and dark visuals and selects the preferred theme. +pub fn apply(ctx: &egui::Context, theme: settings::Theme) { + for egui_theme in [Theme::Light, Theme::Dark] { + ctx.set_visuals_of(egui_theme, visuals(&Palette::of(egui_theme))); + } + ctx.all_styles_mut(|style| { + use egui::TextStyle; + style.text_styles = [ + (TextStyle::Small, FontId::proportional(10.5)), + (TextStyle::Body, FontId::proportional(13.0)), + (TextStyle::Button, FontId::proportional(13.0)), + (TextStyle::Monospace, FontId::monospace(12.5)), + ( + TextStyle::Heading, + FontId::new(17.0, FontFamily::Name(SEMIBOLD.into())), + ), + ] + .into(); + let spacing = &mut style.spacing; + spacing.item_spacing = Vec2::new(8.0, 5.0); + spacing.button_padding = Vec2::new(7.0, 3.0); + spacing.menu_margin = Margin::same(6); + spacing.window_margin = Margin::same(12); + spacing.interact_size.y = 22.0; + spacing.scroll = egui::style::ScrollStyle::thin(); + }); + ctx.set_theme(match theme { + settings::Theme::System => egui::ThemePreference::System, + settings::Theme::Light => egui::ThemePreference::Light, + settings::Theme::Dark => egui::ThemePreference::Dark, + }); +} + +fn visuals(p: &Palette) -> Visuals { + let mut v = if p.dark { + Visuals::dark() + } else { + Visuals::light() + }; + let radius = CornerRadius::same(5); + + v.override_text_color = Some(p.text); + v.weak_text_color = Some(p.text_weak); + v.hyperlink_color = p.accent; + v.window_fill = p.panel; + v.panel_fill = p.window; + v.faint_bg_color = if p.dark { + Color32::from_rgb(36, 38, 41) + } else { + Color32::from_rgb(241, 242, 245) + }; + v.extreme_bg_color = p.surface; + v.code_bg_color = if p.dark { + Color32::from_rgb(38, 40, 44) + } else { + Color32::from_rgb(238, 240, 244) + }; + v.error_fg_color = p.error; + v.warn_fg_color = p.warning; + v.window_corner_radius = CornerRadius::same(8); + v.menu_corner_radius = CornerRadius::same(6); + v.window_stroke = Stroke::new(1.0, p.border); + let shadow_alpha = if p.dark { 110 } else { 40 }; + v.window_shadow = Shadow { + offset: [0, 6], + blur: 18, + spread: 0, + color: Color32::from_black_alpha(shadow_alpha), + }; + v.popup_shadow = Shadow { + offset: [0, 4], + blur: 12, + spread: 0, + color: Color32::from_black_alpha(shadow_alpha), + }; + v.selection.bg_fill = p.accent.gamma_multiply(if p.dark { 0.55 } else { 0.35 }); + v.selection.stroke = Stroke::new(1.0, p.accent); + v.striped = true; + v.indent_has_left_vline = false; + v.collapsing_header_frame = false; + + let hover_fill = if p.dark { + Color32::from_rgb(58, 61, 66) + } else { + Color32::from_rgb(223, 225, 231) + }; + let idle_fill = if p.dark { + Color32::from_rgb(49, 51, 56) + } else { + Color32::from_rgb(230, 232, 236) + }; + + let widgets = &mut v.widgets; + widgets.noninteractive.bg_fill = p.panel; + widgets.noninteractive.weak_bg_fill = p.panel; + widgets.noninteractive.bg_stroke = Stroke::new(1.0, p.border); + widgets.noninteractive.fg_stroke = Stroke::new(1.0, p.text); + widgets.noninteractive.corner_radius = radius; + + widgets.inactive.bg_fill = idle_fill; + widgets.inactive.weak_bg_fill = Color32::TRANSPARENT; + widgets.inactive.bg_stroke = Stroke::NONE; + widgets.inactive.fg_stroke = Stroke::new(1.0, p.text); + widgets.inactive.corner_radius = radius; + + widgets.hovered.bg_fill = hover_fill; + widgets.hovered.weak_bg_fill = hover_fill; + widgets.hovered.bg_stroke = Stroke::NONE; + widgets.hovered.fg_stroke = Stroke::new(1.5, p.text); + widgets.hovered.corner_radius = radius; + widgets.hovered.expansion = 0.0; + + widgets.active.bg_fill = p.accent.gamma_multiply(0.6); + widgets.active.weak_bg_fill = p.accent.gamma_multiply(0.45); + widgets.active.bg_stroke = Stroke::NONE; + widgets.active.fg_stroke = Stroke::new(1.5, p.text); + widgets.active.corner_radius = radius; + widgets.active.expansion = 0.0; + + widgets.open.bg_fill = hover_fill; + widgets.open.weak_bg_fill = hover_fill; + widgets.open.bg_stroke = Stroke::NONE; + widgets.open.fg_stroke = Stroke::new(1.0, p.text); + widgets.open.corner_radius = radius; + v +} + +/// The dock area style matching the palette. +pub fn dock_style(style: &egui::Style, p: &Palette) -> egui_dock::Style { + let mut dock = egui_dock::Style::from_egui(style); + dock.main_surface_border_stroke = Stroke::NONE; + dock.separator.width = 3.0; + dock.separator.extra_interact_width = 4.0; + dock.separator.color_idle = p.window; + dock.separator.color_hovered = p.accent.gamma_multiply(0.7); + dock.separator.color_dragged = p.accent; + + dock.tab_bar.bg_fill = p.window; + dock.tab_bar.hline_color = p.border; + dock.tab_bar.height = 30.0; + dock.tab_bar.corner_radius = CornerRadius::ZERO; + + dock.tab.tab_body.bg_fill = p.surface; + dock.tab.tab_body.stroke = Stroke::new(1.0, p.border); + dock.tab.tab_body.corner_radius = CornerRadius::same(0); + dock.tab.tab_body.inner_margin = Margin::same(0); + dock.tab.hline_below_active_tab_name = true; + let corner = CornerRadius { + nw: 6, + ne: 6, + sw: 0, + se: 0, + }; + for interaction in [ + &mut dock.tab.active, + &mut dock.tab.focused, + &mut dock.tab.active_with_kb_focus, + &mut dock.tab.focused_with_kb_focus, + ] { + interaction.bg_fill = p.surface; + interaction.text_color = p.text; + interaction.outline_color = p.border; + interaction.corner_radius = corner; + } + for interaction in [&mut dock.tab.inactive, &mut dock.tab.inactive_with_kb_focus] { + interaction.bg_fill = p.window; + interaction.text_color = p.text_weak; + interaction.outline_color = Color32::TRANSPARENT; + interaction.corner_radius = corner; + } + dock.tab.hovered.bg_fill = if p.dark { + Color32::from_rgb(40, 42, 46) + } else { + Color32::from_rgb(240, 241, 244) + }; + dock.tab.hovered.text_color = p.text; + dock.tab.hovered.corner_radius = corner; + dock.overlay.selection_color = p.accent.gamma_multiply(0.35); + dock +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_theme.rs"] +mod tests; diff --git a/src/ui/command_palette.rs b/src/ui/command_palette.rs new file mode 100644 index 000000000..7c0f14c06 --- /dev/null +++ b/src/ui/command_palette.rs @@ -0,0 +1,517 @@ +//! The command palette (Ctrl+Shift+P): a search over every command, so a +//! command can be found without knowing its menu, and run without the mouse. +//! It lists the commands of the menus, plus the open tabs, recent files and +//! folders, examples, panels and named views. Only the commands that can be +//! used right now are offered. + +use egui::{Key, RichText}; +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::{self, Action}; +use crate::panels::Tab; +use crate::viewer::camera::StandardView; +use crate::viewer::{DisplayMode, SelectionMode}; +use crate::worker::protocol::{DebugAction, ExportFormat}; + +/// Most commands listed at once; typing narrows them down. +const MAX_SHOWN: usize = 12; + +/// The palette while it is open. +#[derive(Default)] +pub struct Palette { + pub query: String, + /// Index into the matches of `query`. + pub selected: usize, +} + +/// A command of the palette. +#[derive(Clone, Debug, PartialEq)] +pub struct Command { + /// Where it is found otherwise, such as `File` or `Tab`. + pub category: &'static str, + pub label: String, + pub action: Action, +} + +impl Command { + fn new(category: &'static str, label: impl Into, action: Action) -> Self { + Self { + category, + label: label.into(), + action, + } + } + + /// What the query is matched against, and the identifier stored for + /// favorite commands. + pub fn id(&self) -> String { + format!("{}: {}", self.category, self.label) + } + + fn text(&self) -> String { + self.id() + } +} + +/// The commands of the menus, whether usable now or not. +pub fn menu_commands() -> Vec { + let c = Command::new; + let mut list = vec![ + c("File", "New", Action::NewFile), + c("File", "Open…", Action::OpenFile), + c("File", "Open Folder…", Action::OpenFolder), + c("File", "Save", Action::Save), + c("File", "Save As…", Action::SaveAs), + c("File", "Save All", Action::SaveAll), + c("File", "Local History…", Action::LocalHistory), + c("File", "Close Tab", Action::CloseTab), + c("File", "Close All Tabs", Action::CloseAllTabs), + c("File", "Close Folder", Action::CloseFolder), + c("File", "Refresh Project Folder", Action::RefreshProject), + c( + "File", + "Automatic Reload and Preview", + Action::ToggleAutoreload, + ), + c("File", "Quit", Action::Quit), + c("Tab", "Next Tab", Action::NextTab), + c("Tab", "Previous Tab", Action::PreviousTab), + c("Edit", "Undo", Action::Undo), + c("Edit", "Redo", Action::Redo), + c("Edit", "Toggle Comment", Action::ToggleComment), + c("Edit", "Duplicate Line", Action::DuplicateLine), + c("Edit", "Move Line Up", Action::MoveLineUp), + c("Edit", "Move Line Down", Action::MoveLineDown), + c("Edit", "Auto-Complete", Action::Autocomplete), + c("Edit", "Search", Action::Find), + c("Edit", "Find Next", Action::FindNext), + c("Edit", "Find Previous", Action::FindPrevious), + c("Edit", "Replace", Action::Replace), + c("Edit", "Go to Line…", Action::GoToLinePrompt), + c("Edit", "Show Outline", Action::ShowOutline), + c("Edit", "Go to Definition", Action::GoToDefinition), + c("Edit", "Find References", Action::FindReferences), + c("Edit", "Copy Selector", Action::CopySelector), + c("Edit", "Insert Selector", Action::InsertSelector), + c( + "Edit", + "Copy Measurement as Code", + Action::CopyMeasurementCode, + ), + c( + "Edit", + "Copy Measurement as Text", + Action::CopyMeasurement(commands::MeasurementFormat::Text), + ), + c( + "Edit", + "Copy Measurement as JSON", + Action::CopyMeasurement(commands::MeasurementFormat::Json), + ), + c( + "Edit", + "Copy Measurement as CSV", + Action::CopyMeasurement(commands::MeasurementFormat::Csv), + ), + c("Edit", "Reset Modified Parameters", Action::ResetParameters), + c("Edit", "Go to Source", Action::GoToSelectionSource), + c("Edit", "Preferences…", Action::Preferences), + c("Run", "Render", Action::Render), + c("Run", "Profile", Action::Profile), + c("Run", "Clear Profile", Action::ClearProfile), + c("Run", "Debug / Stop Debugging", Action::ToggleDebug), + c("Run", "Step", Action::Debug(DebugAction::Step)), + c("Run", "Step In", Action::Debug(DebugAction::StepIn)), + c("Run", "Step Out", Action::Debug(DebugAction::StepOut)), + c("Run", "Continue", Action::Debug(DebugAction::Continue)), + c("Run", "Stop", Action::Stop), + c("Run", "Clear Console", Action::ClearConsole), + c("Tools", "Check Geometry", Action::CheckGeometry), + c("Run", "Reset Console", Action::ResetConsole), + c("Run", "Clear Log", Action::ClearLog), + c("Run", "Restart Python", Action::RestartPython), + c( + "Run", + "Create Python Environment…", + Action::CreateEnvironment, + ), + c("Run", "Install Packages…", Action::InstallPackages), + c("Tools", "Inspect CQ Object", Action::ToggleInspect), + c("Tools", "Screenshot…", Action::Screenshot), + c("Tools", "Copy Screenshot to Clipboard", Action::CopyImage), + c("Tools", "Upload Model…", Action::Upload), + c("View", "Fit", Action::Fit), + c("View", "Zoom to Selection", Action::FitSelection), + c("View", "Perspective Projection", Action::ToggleProjection), + c("View", "Section View", Action::ToggleSection), + c("View", "Exploded View", Action::ToggleExplode), + c("View", "Ground Grid", Action::ToggleGroundGrid), + c("View", "Scale Bar", Action::ToggleScaleBar), + c( + "View", + "Isolate Selection / End Isolation", + Action::ToggleIsolate, + ), + c("View", "Show All", Action::ShowAll), + c("View", "Save Current View", Action::SaveView(None)), + c( + "View", + "Maximize Panel / Restore Layout", + Action::ToggleMaximize(None), + ), + c("View", "Reset Layout", Action::ResetLayout), + c("View", "Command Palette…", Action::CommandPalette), + c("Objects", "Clear All Objects", Action::ClearObjects), + c("Objects", "Remove Selected Objects", Action::RemoveSelected), + c("Help", "Documentation", Action::Documentation), + c("Help", "Installation Guide", Action::InstallationGuide), + c( + "Help", + "CadQuery Documentation", + Action::CadQueryDocumentation, + ), + c("Help", "Check for Updates", Action::CheckUpdates), + c("Help", "Download the New Release…", Action::DownloadUpdate), + c("Help", "About", Action::About), + ]; + list.extend( + StandardView::ALL + .into_iter() + .map(|view| Command::new("View", format!("{} View", view.label()), Action::View(view))), + ); + list.extend( + DisplayMode::ALL + .into_iter() + .map(|mode| Command::new("Display", mode.label(), Action::Display(mode))), + ); + list.extend(SelectionMode::ALL.into_iter().map(|mode| { + Command::new( + "Select", + format!("Select {}", mode.label()), + Action::SelectionMode(mode), + ) + })); + list.extend(ExportFormat::ALL.into_iter().map(|format| { + Command::new( + "Tools", + format!("Export as {}…", format.label()), + Action::Export(format), + ) + })); + list.extend( + Tab::ALL + .into_iter() + .filter(|tab| *tab != Tab::Viewer) + .map(|tab| { + Command::new( + "Panel", + format!("Show / Hide {}", tab.title()), + Action::TogglePanel(tab), + ) + }), + ); + list.extend( + crate::editor::snippets::SNIPPETS + .iter() + .enumerate() + .map(|(index, snippet)| { + Command::new( + "Snippet", + format!("Insert {}", snippet.title), + Action::InsertSnippet(index), + ) + }), + ); + list +} + +/// Whether `action` can be used now; the palette hides the others, as the +/// menus disable them. +fn available(state: &AppState, action: &Action) -> bool { + let picked = !state.scene.topology_selections.is_empty(); + let has_objects = !state.scene.is_empty(); + match action { + Action::Undo => state.editor.can_undo(), + Action::Redo => state.editor.can_redo(), + Action::SaveAll => state.any_modified(), + Action::CloseFolder | Action::RefreshProject => state.project.is_some(), + Action::CopySelector | Action::InsertSelector | Action::CopyMeasurementCode => picked, + Action::CopyMeasurement(_) => state.measurements.result.is_some(), + Action::GoToSelectionSource => state.scene.current().is_some_and(|n| n.line.is_some()), + Action::ClearProfile => !state.editor.line_profile.is_empty(), + Action::Debug(_) => state.is_paused(), + Action::Stop => state.can_stop(), + Action::Export(_) | Action::ClearObjects | Action::FitSelection => has_objects, + Action::RemoveSelected => !state.scene.selection.is_empty(), + Action::ToggleIsolate => state.scene.is_isolating() || !state.scene.selection.is_empty(), + Action::DownloadUpdate => crate::updates::available(&state.settings.general).is_some(), + Action::CommandPalette => false, + _ => true, + } +} + +/// Every command usable now: those of the menus, then the open tabs, +/// named views, recent files and folders and the examples. +pub fn commands(state: &AppState) -> Vec { + let mut list: Vec = menu_commands() + .into_iter() + .filter(|command| available(state, &command.action)) + .collect(); + for tab in state.tabs().into_iter().filter(|tab| !tab.active) { + list.push(Command::new( + "Tab", + tab.name, + Action::ActivateTab(tab.generation), + )); + } + for (index, view) in state.viewer.named_views.iter().enumerate() { + list.push(Command::new( + "Named View", + &view.name, + Action::GoToView(index), + )); + } + for path in &state.settings.recent_files { + let name = path.file_name().map_or_else( + || path.display().to_string(), + |name| name.to_string_lossy().into_owned(), + ); + list.push(Command::new( + "Open Recent", + name, + Action::OpenPath(path.clone()), + )); + } + for project in &state.settings.projects { + let name = project.root.file_name().map_or_else( + || project.root.display().to_string(), + |name| name.to_string_lossy().into_owned(), + ); + list.push(Command::new( + "Open Recent Folder", + name, + Action::OpenFolderPath(project.root.clone()), + )); + } + for (index, example) in state.examples().iter().enumerate() { + list.push(Command::new( + "Example", + &example.title, + Action::OpenExample(index), + )); + } + list +} + +/// How well `text` matches `query`: every character of the query, in +/// order and regardless of case, with more points for characters at the +/// start of a word or right after the previous match, and for the whole +/// query in one piece. `None` when it does not match. +pub fn score(query: &str, text: &str) -> Option { + let query: Vec = query + .chars() + .filter(|c| !c.is_whitespace()) + .flat_map(char::to_lowercase) + .collect(); + if query.is_empty() { + return Some(0); + } + let text: Vec = text.chars().flat_map(char::to_lowercase).collect(); + let mut score = 0; + let mut next = 0; + let mut previous: Option = None; + for wanted in &query { + let found = (next..text.len()).find(|&i| text[i] == *wanted)?; + score += 1; + if found == 0 || !text[found - 1].is_alphanumeric() { + score += 8; + } + match previous { + Some(previous) if previous + 1 == found => score += 5, + Some(previous) => score -= (found - previous - 1).min(5) as i32, + None => {} + } + previous = Some(found); + next = found + 1; + } + let joined: String = query.iter().collect(); + if text.iter().collect::().contains(&joined) { + score += 20; + } + Some(score) +} + +/// The commands matching `query`, best first; equally good ones keep their +/// order. +#[cfg(test)] +pub fn matches(commands: Vec, query: &str) -> Vec { + matches_with_favorites(commands, query, &[]) +} + +/// The commands matching `query`, prioritizing `favorites` at the top when +/// the query is empty (and breaking score ties in favor of favorites). +pub fn matches_with_favorites( + commands: Vec, + query: &str, + favorites: &[String], +) -> Vec { + let is_fav = |cmd: &Command| favorites.iter().any(|fav| fav == &cmd.id()); + if query.trim().is_empty() { + let mut favs: Vec = Vec::new(); + let mut rest: Vec = Vec::new(); + for cmd in commands { + if is_fav(&cmd) { + favs.push(cmd); + } else { + rest.push(cmd); + } + } + // Keep favorites in the order they were pinned. + favs.sort_by_key(|cmd| { + favorites + .iter() + .position(|fav| fav == &cmd.id()) + .unwrap_or(usize::MAX) + }); + favs.extend(rest); + return favs; + } + + let mut scored: Vec<((i32, bool), Command)> = commands + .into_iter() + .filter_map(|command| { + let s = score(query, &command.text())?; + let fav = is_fav(&command); + Some(((s, fav), command)) + }) + .collect(); + scored.sort_by_key(|(key, _)| std::cmp::Reverse(*key)); + scored.into_iter().map(|(_, command)| command).collect() +} + +/// Shows the palette at the top of the window. Returns the command chosen, +/// or `Some(None)` once it was dismissed. +pub fn window( + ctx: &egui::Context, + palette: &mut Palette, + commands: Vec, + settings: &mut crate::settings::Settings, +) -> Option> { + let found = matches_with_favorites(commands, &palette.query, &settings.favorite_commands); + palette.selected = palette.selected.min(found.len().saturating_sub(1)); + let mut chosen = None; + let (up, down, enter, toggle_fav) = ctx.input_mut(|input| { + ( + input.consume_key(egui::Modifiers::NONE, Key::ArrowUp), + input.consume_key(egui::Modifiers::NONE, Key::ArrowDown), + input.consume_key(egui::Modifiers::NONE, Key::Enter), + input.consume_key(egui::Modifiers::COMMAND, Key::D), + ) + }); + if up { + palette.selected = palette.selected.saturating_sub(1); + } + if down { + palette.selected = (palette.selected + 1).min(found.len().saturating_sub(1)); + } + if toggle_fav && let Some(command) = found.get(palette.selected) { + settings.toggle_favorite_command(&command.id()); + } + if enter && let Some(command) = found.get(palette.selected) { + chosen = Some(command.action.clone()); + } + + let area = egui::Modal::default_area(egui::Id::new("command_palette")) + .anchor(egui::Align2::CENTER_TOP, [0.0, 60.0]); + let response = egui::Modal::new(egui::Id::new("command_palette")) + .area(area) + .frame(egui::Frame::popup(&ctx.style_of(ctx.theme())).inner_margin(10)) + .show(ctx, |ui| { + ui.set_width(520.0); + let field = ui.add( + egui::TextEdit::singleline(&mut palette.query) + .hint_text("Type a command, a file, a snippet or a panel") + .desired_width(f32::INFINITY), + ); + if !field.has_focus() { + field.request_focus(); + } + if field.changed() { + palette.selected = 0; + } + ui.add_space(4.0); + if found.is_empty() { + ui.weak("No command matches"); + } + let empty_query = palette.query.trim().is_empty(); + // The page of results around the selected one. + let first = palette.selected.saturating_sub(MAX_SHOWN - 1); + let mut prev_was_favorite = false; + for (index, command) in found.iter().enumerate().skip(first).take(MAX_SHOWN) { + let id = command.id(); + let is_favorite = settings.is_favorite_command(&id); + if empty_query && index > first && prev_was_favorite && !is_favorite { + ui.separator(); + } + prev_was_favorite = is_favorite; + let selected = index == palette.selected; + let mut star_clicked = false; + let row = ui + .horizontal(|ui| { + ui.set_min_width(ui.available_width()); + let star_text = if is_favorite { + RichText::new("★").color(egui::Color32::from_rgb(235, 180, 40)) + } else { + RichText::new("☆").weak() + }; + let star_hint = if is_favorite { + "Remove from Favorite Commands (Ctrl+D)" + } else { + "Add to Favorite Commands (Ctrl+D)" + }; + if ui + .add(egui::Button::new(star_text).frame(false)) + .on_hover_text(star_hint) + .clicked() + { + star_clicked = true; + } + let label = ui.selectable_label(selected, &command.label); + ui.weak(command.category); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if let Some(shortcut) = commands::shortcut(&command.action) { + ui.weak(ctx.format_shortcut(&shortcut)); + } + }); + label + }) + .inner; + if star_clicked { + settings.toggle_favorite_command(&id); + } else if row.clicked() { + chosen = Some(command.action.clone()); + } + if row.hovered() && ui.input(|i| i.pointer.delta() != egui::Vec2::ZERO) { + palette.selected = index; + } + } + ui.add_space(4.0); + ui.label( + RichText::new(format!( + "{} ↑↓ choose · Enter runs · Ctrl+D ★ favorite · Esc closes", + icon::KEYBOARD + )) + .small() + .weak(), + ); + }); + if chosen.is_some() { + return Some(chosen); + } + response.should_close().then_some(None) +} + +#[cfg(test)] +#[path = "../../tests/rust/app/test_command_palette.rs"] +mod tests; diff --git a/src/ui/editor_tabs.rs b/src/ui/editor_tabs.rs new file mode 100644 index 000000000..8a3036c30 --- /dev/null +++ b/src/ui/editor_tabs.rs @@ -0,0 +1,123 @@ +//! The tab strip above the editor, shown while more than one document is +//! open: a click shows a tab, the middle button or its × closes it, and its +//! context menu closes others or makes it the project's main script. + +use egui::RichText; +use egui_phosphor::regular as icon; + +use crate::app::TabInfo; +use crate::commands::{self, Action}; +use crate::project; + +pub fn ui(ui: &mut egui::Ui, tabs: &[TabInfo], actions: &mut Vec) { + let shown = tabs.iter().find(|tab| tab.active).map(|tab| tab.generation); + // Scrolls to the shown tab when another one is shown. + let memory = ui.id().with("editor_tabs_shown"); + let changed = ui.data_mut(|data| { + let previous = data.get_temp::>(memory); + data.insert_temp(memory, shown); + previous != Some(shown) + }); + + egui::ScrollArea::horizontal() + .id_salt("editor_tabs") + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden) + .show(ui, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + for tab in tabs { + tab_ui(ui, tab, tabs.len(), changed, actions); + } + }); + }); + ui.add_space(2.0); +} + +fn tab_ui( + ui: &mut egui::Ui, + tab: &TabInfo, + count: usize, + scroll_to_shown: bool, + actions: &mut Vec, +) { + let glyph = if tab.main { + icon::PLAY_CIRCLE + } else if tab.path.as_deref().is_none_or(project::is_script) { + icon::FILE_PY + } else { + icon::FILE_TEXT + }; + let modified = if tab.modified { " •" } else { "" }; + let mut text = RichText::new(format!("{glyph} {}{modified}", tab.name)); + if tab.active { + text = text.strong(); + } + let response = ui.selectable_label(tab.active, text); + let mut hint = tab.path.as_ref().map_or_else( + || "Not saved yet".to_owned(), + |path| path.display().to_string(), + ); + if tab.main { + hint.push_str("\nThe project's main script: F5 renders it"); + } + let response = response.on_hover_text(hint); + if tab.active && scroll_to_shown { + response.scroll_to_me(None); + } + if response.clicked() { + actions.push(Action::ActivateTab(tab.generation)); + } + if response.middle_clicked() { + actions.push(Action::CloseDocument(tab.generation)); + } + response.context_menu(|ui| menu(ui, tab, count, actions)); + + let close = ui + .add(egui::Button::new(RichText::new(icon::X).small()).frame(false)) + .on_hover_text(match commands::shortcut(&Action::CloseTab) { + Some(shortcut) if tab.active => { + format!("Close ({})", ui.ctx().format_shortcut(&shortcut)) + } + _ => "Close".to_owned(), + }); + if close.clicked() { + actions.push(Action::CloseDocument(tab.generation)); + } + ui.add_space(6.0); +} + +fn menu(ui: &mut egui::Ui, tab: &TabInfo, count: usize, actions: &mut Vec) { + let mut item = |ui: &mut egui::Ui, label: &str, action: Action, enabled: bool| { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + actions.push(action); + ui.close(); + } + }; + item(ui, "Close", Action::CloseDocument(tab.generation), true); + item( + ui, + "Close Others", + Action::CloseOtherTabs(tab.generation), + count > 1, + ); + item(ui, "Close All", Action::CloseAllTabs, true); + if let Some(path) = &tab.path { + ui.separator(); + if project::is_script(path) { + if tab.main { + item(ui, "Clear Main Script", Action::SetMainScript(None), true); + } else { + item( + ui, + "Set as Main Script", + Action::SetMainScript(Some(path.clone())), + true, + ); + } + } + if ui.button("Copy Path").clicked() { + ui.ctx().copy_text(path.display().to_string()); + ui.close(); + } + } +} diff --git a/src/ui/menu_bar.rs b/src/ui/menu_bar.rs new file mode 100644 index 000000000..d8627acb7 --- /dev/null +++ b/src/ui/menu_bar.rs @@ -0,0 +1,626 @@ +//! The main menu, organized like the original editor's. + +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::{self, Action}; +use crate::panels::Tab; +use crate::viewer::DisplayMode; +use crate::viewer::camera::StandardView; +use crate::worker::protocol::{DebugAction, ExportFormat}; + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState, open_panels: &[Tab], maximized: bool) { + let mut actions = Vec::new(); + egui::MenuBar::new().ui(ui, |ui| { + ui.menu_button("File", |ui| file_menu(ui, state, &mut actions)); + ui.menu_button("Edit", |ui| edit_menu(ui, state, &mut actions)); + ui.menu_button("Tools", |ui| tools_menu(ui, state, &mut actions)); + ui.menu_button("Run", |ui| run_menu(ui, state, &mut actions)); + ui.menu_button("View", |ui| { + view_menu(ui, state, open_panels, maximized, &mut actions) + }); + ui.menu_button("Help", |ui| help_menu(ui, state, &mut actions)); + }); + state.queue(actions); +} + +/// A menu entry showing its keyboard shortcut. +fn item(ui: &mut egui::Ui, actions: &mut Vec, icon: &str, label: &str, action: Action) { + item_enabled(ui, actions, icon, label, action, true); +} + +fn item_enabled( + ui: &mut egui::Ui, + actions: &mut Vec, + icon: &str, + label: &str, + action: Action, + enabled: bool, +) { + let mut button = egui::Button::new(format!("{icon} {label}")); + if let Some(shortcut) = commands::shortcut(&action) { + button = button.shortcut_text(ui.ctx().format_shortcut(&shortcut)); + } + if ui.add_enabled(enabled, button).clicked() { + actions.push(action); + ui.close(); + } +} + +fn check_item( + ui: &mut egui::Ui, + actions: &mut Vec, + checked: bool, + label: &str, + action: Action, +) { + let mut button = egui::Button::new(format!( + "{} {label}", + if checked { + icon::CHECK_SQUARE + } else { + icon::SQUARE + } + )); + if let Some(shortcut) = commands::shortcut(&action) { + button = button.shortcut_text(ui.ctx().format_shortcut(&shortcut)); + } + if ui.add(button).clicked() { + actions.push(action); + ui.close(); + } +} + +fn file_menu(ui: &mut egui::Ui, state: &AppState, actions: &mut Vec) { + item(ui, actions, icon::FILE_PLUS, "New", Action::NewFile); + item(ui, actions, icon::FILE_ARROW_UP, "Open…", Action::OpenFile); + item( + ui, + actions, + icon::FOLDER_OPEN, + "Open Folder…", + Action::OpenFolder, + ); + ui.menu_button( + format!("{} Open Recent", icon::CLOCK_COUNTER_CLOCKWISE), + |ui| { + if state.settings.recent_files.is_empty() && state.settings.projects.is_empty() { + ui.weak("No recent files"); + } + for path in &state.settings.recent_files { + let name = path.file_name().map_or_else( + || path.display().to_string(), + |n| n.to_string_lossy().into_owned(), + ); + if ui + .button(name) + .on_hover_text(path.display().to_string()) + .clicked() + { + actions.push(Action::OpenPath(path.clone())); + ui.close(); + } + } + if !state.settings.projects.is_empty() { + ui.separator(); + } + for project in &state.settings.projects { + let root = &project.root; + let name = root.file_name().map_or_else( + || root.display().to_string(), + |n| n.to_string_lossy().into_owned(), + ); + if ui + .button(format!("{} {name}", icon::FOLDER)) + .on_hover_text(root.display().to_string()) + .clicked() + { + actions.push(Action::OpenFolderPath(root.clone())); + ui.close(); + } + } + }, + ); + item(ui, actions, icon::FLOPPY_DISK, "Save", Action::Save); + item( + ui, + actions, + icon::FLOPPY_DISK_BACK, + "Save As…", + Action::SaveAs, + ); + item_enabled( + ui, + actions, + icon::FLOPPY_DISK, + "Save All", + Action::SaveAll, + state.any_modified(), + ); + item( + ui, + actions, + icon::CLOCK_COUNTER_CLOCKWISE, + "Local History…", + Action::LocalHistory, + ); + ui.separator(); + item(ui, actions, icon::X, "Close Tab", Action::CloseTab); + item_enabled( + ui, + actions, + icon::FOLDER_SIMPLE, + "Close Folder", + Action::CloseFolder, + state.project.is_some(), + ); + ui.separator(); + check_item( + ui, + actions, + state.settings.editor.autoreload, + "Automatic Reload and Preview", + Action::ToggleAutoreload, + ); + ui.separator(); + ui.menu_button(format!("{} Examples", icon::BOOK_OPEN), |ui| { + for (index, example) in state.examples().iter().enumerate() { + if ui.button(&example.title).clicked() { + actions.push(Action::OpenExample(index)); + ui.close(); + } + } + }); + ui.separator(); + item(ui, actions, icon::SIGN_OUT, "Quit", Action::Quit); +} + +fn edit_menu(ui: &mut egui::Ui, state: &AppState, actions: &mut Vec) { + item_enabled( + ui, + actions, + icon::ARROW_U_UP_LEFT, + "Undo", + Action::Undo, + state.editor.can_undo(), + ); + item_enabled( + ui, + actions, + icon::ARROW_U_UP_RIGHT, + "Redo", + Action::Redo, + state.editor.can_redo(), + ); + ui.separator(); + item( + ui, + actions, + icon::HASH, + "Toggle Comment", + Action::ToggleComment, + ); + item( + ui, + actions, + icon::COPY_SIMPLE, + "Duplicate Line", + Action::DuplicateLine, + ); + item( + ui, + actions, + icon::ARROW_UP, + "Move Line Up", + Action::MoveLineUp, + ); + item( + ui, + actions, + icon::ARROW_DOWN, + "Move Line Down", + Action::MoveLineDown, + ); + ui.menu_button(format!("{} Insert Snippet", icon::CODE), |ui| { + for (index, snippet) in crate::editor::snippets::SNIPPETS.iter().enumerate() { + if ui + .button(snippet.title) + .on_hover_text(snippet.description) + .clicked() + { + actions.push(Action::InsertSnippet(index)); + ui.close(); + } + } + }); + item( + ui, + actions, + icon::LIGHTNING, + "Auto-Complete", + Action::Autocomplete, + ); + item(ui, actions, icon::MAGNIFYING_GLASS, "Search", Action::Find); + item(ui, actions, icon::SWAP, "Replace", Action::Replace); + item( + ui, + actions, + icon::LIST_NUMBERS, + "Go to Line…", + Action::GoToLinePrompt, + ); + item( + ui, + actions, + icon::TREE_STRUCTURE, + "Show Outline", + Action::ShowOutline, + ); + item( + ui, + actions, + icon::ARROW_SQUARE_OUT, + "Go to Definition", + Action::GoToDefinition, + ); + item( + ui, + actions, + icon::MAGNIFYING_GLASS, + "Find References", + Action::FindReferences, + ); + ui.separator(); + let picked = !state.scene.topology_selections.is_empty(); + item_enabled( + ui, + actions, + icon::COPY, + "Copy Selector", + Action::CopySelector, + picked, + ); + item_enabled( + ui, + actions, + icon::CURSOR_TEXT, + "Insert Selector", + Action::InsertSelector, + picked, + ); + item_enabled( + ui, + actions, + icon::ARROW_SQUARE_OUT, + "Go to Source", + Action::GoToSelectionSource, + state + .scene + .current() + .is_some_and(|node| node.line.is_some()), + ); + ui.separator(); + item( + ui, + actions, + icon::GEAR_SIX, + "Preferences…", + Action::Preferences, + ); +} + +fn tools_menu(ui: &mut egui::Ui, state: &AppState, actions: &mut Vec) { + let has_objects = !state.scene.is_empty(); + item_enabled( + ui, + actions, + icon::CHECK_CIRCLE, + "Check Geometry", + Action::CheckGeometry, + has_objects, + ); + ui.separator(); + for format in ExportFormat::ALL { + item_enabled( + ui, + actions, + icon::EXPORT, + &format!("Export as {}…", format.label()), + Action::Export(format), + has_objects, + ); + } + ui.separator(); + check_item( + ui, + actions, + state.inspector.show_in_view, + "Inspect CQ Object", + Action::ToggleInspect, + ); + item(ui, actions, icon::CAMERA, "Screenshot…", Action::Screenshot); + item( + ui, + actions, + icon::UPLOAD_SIMPLE, + "Upload Model…", + Action::Upload, + ); +} + +fn run_menu(ui: &mut egui::Ui, state: &AppState, actions: &mut Vec) { + let paused = state.is_paused(); + let debugging = state.is_debugging(); + item(ui, actions, icon::PLAY, "Render", Action::Render); + main_script_item(ui, state, actions); + item(ui, actions, icon::TIMER, "Profile", Action::Profile); + item_enabled( + ui, + actions, + icon::ERASER, + "Clear Profile", + Action::ClearProfile, + !state.editor.line_profile.is_empty(), + ); + item( + ui, + actions, + icon::BUG, + if debugging { "Stop Debugging" } else { "Debug" }, + Action::ToggleDebug, + ); + item_enabled( + ui, + actions, + icon::ARROW_BEND_DOWN_RIGHT, + "Step", + Action::Debug(DebugAction::Step), + paused, + ); + item_enabled( + ui, + actions, + icon::ARROW_ELBOW_DOWN_RIGHT, + "Step In", + Action::Debug(DebugAction::StepIn), + paused, + ); + item_enabled( + ui, + actions, + icon::ARROW_ELBOW_UP_LEFT, + "Step Out", + Action::Debug(DebugAction::StepOut), + paused, + ); + item_enabled( + ui, + actions, + icon::FAST_FORWARD, + "Continue", + Action::Debug(DebugAction::Continue), + paused, + ); + item_enabled( + ui, + actions, + icon::STOP, + "Stop", + Action::Stop, + state.can_stop(), + ); + ui.separator(); + item( + ui, + actions, + icon::BROOM, + "Clear Console", + Action::ClearConsole, + ); + item(ui, actions, icon::ERASER, "Clear Log", Action::ClearLog); + ui.separator(); + item( + ui, + actions, + icon::ARROW_CLOCKWISE, + "Restart Python", + Action::RestartPython, + ); +} + +/// Makes the shown script the project's main script, or lets F5 render the +/// shown file again. +fn main_script_item(ui: &mut egui::Ui, state: &AppState, actions: &mut Vec) { + let shown = state.document.path(); + let in_project = state + .project + .as_ref() + .zip(shown) + .is_some_and(|(project, path)| project.contains(path) && crate::project::is_script(path)); + match state.main_script() { + Some(main) if Some(main) == shown => item( + ui, + actions, + icon::PLAY_CIRCLE, + "Clear Main Script", + Action::SetMainScript(None), + ), + _ => item_enabled( + ui, + actions, + icon::PLAY_CIRCLE, + "Set as Main Script", + Action::SetMainScript(shown.map(std::path::Path::to_path_buf)), + in_project, + ), + } +} + +fn view_menu( + ui: &mut egui::Ui, + state: &AppState, + open_panels: &[Tab], + maximized: bool, + actions: &mut Vec, +) { + item( + ui, + actions, + icon::MAGNIFYING_GLASS, + "Command Palette…", + Action::CommandPalette, + ); + ui.separator(); + item(ui, actions, icon::CORNERS_OUT, "Fit", Action::Fit); + item( + ui, + actions, + icon::MAGNIFYING_GLASS_PLUS, + "Zoom to Selection", + Action::FitSelection, + ); + for view in StandardView::ALL { + item(ui, actions, icon::CUBE, view.label(), Action::View(view)); + } + ui.menu_button(format!("{} Named Views", icon::BOOKMARKS_SIMPLE), |ui| { + super::named_views::submenu(ui, state, actions); + }); + ui.separator(); + for mode in DisplayMode::ALL { + check_item( + ui, + actions, + state.viewer.display_mode == mode, + mode.label(), + Action::Display(mode), + ); + } + ui.menu_button(format!("{} Selection Mode", icon::CURSOR_CLICK), |ui| { + for mode in crate::viewer::SelectionMode::ALL { + check_item( + ui, + actions, + state.viewer.selection_mode == mode, + mode.label(), + Action::SelectionMode(mode), + ); + } + }); + check_item( + ui, + actions, + state.settings.viewer.projection == crate::settings::Projection::Perspective, + "Perspective Projection", + Action::ToggleProjection, + ); + check_item( + ui, + actions, + state.viewer.section.enabled, + "Section View", + Action::ToggleSection, + ); + check_item( + ui, + actions, + state.viewer.explode_controls, + "Exploded View", + Action::ToggleExplode, + ); + check_item( + ui, + actions, + state.settings.viewer.ground_grid, + "Ground Grid", + Action::ToggleGroundGrid, + ); + check_item( + ui, + actions, + state.settings.viewer.scale_bar, + "Scale Bar", + Action::ToggleScaleBar, + ); + ui.separator(); + let isolating = state.scene.is_isolating(); + item_enabled( + ui, + actions, + icon::SELECTION_FOREGROUND, + if isolating { + "End Isolation" + } else { + "Isolate Selection" + }, + Action::ToggleIsolate, + isolating || !state.scene.selection.is_empty(), + ); + item(ui, actions, icon::EYE, "Show All", Action::ShowAll); + ui.separator(); + for tab in Tab::ALL.into_iter().filter(|t| *t != Tab::Viewer) { + check_item( + ui, + actions, + open_panels.contains(&tab), + tab.title(), + Action::TogglePanel(tab), + ); + } + ui.separator(); + check_item( + ui, + actions, + maximized, + "Maximize Panel", + Action::ToggleMaximize(None), + ); + item( + ui, + actions, + icon::LAYOUT, + "Reset Layout", + Action::ResetLayout, + ); +} + +fn help_menu(ui: &mut egui::Ui, state: &AppState, actions: &mut Vec) { + item( + ui, + actions, + icon::LIFEBUOY, + "Documentation", + Action::Documentation, + ); + item( + ui, + actions, + icon::BOOK_OPEN_TEXT, + "Installation Guide", + Action::InstallationGuide, + ); + item( + ui, + actions, + icon::BOOKS, + "CadQuery Documentation", + Action::CadQueryDocumentation, + ); + ui.separator(); + if let Some(release) = crate::updates::available(&state.settings.general) { + item( + ui, + actions, + icon::DOWNLOAD_SIMPLE, + &format!("Download CQ-editor {}…", release.tag), + Action::DownloadUpdate, + ); + } + item( + ui, + actions, + icon::ARROW_CIRCLE_UP, + "Check for Updates", + Action::CheckUpdates, + ); + item(ui, actions, icon::INFO, "About", Action::About); +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs new file mode 100644 index 000000000..188bd18a2 --- /dev/null +++ b/src/ui/mod.rs @@ -0,0 +1,9 @@ +//! Window chrome around the dock area: menu bar, toolbar and status bar, +//! and the editor's tab strip. + +pub mod command_palette; +pub mod editor_tabs; +pub mod menu_bar; +mod named_views; +pub mod status_bar; +pub mod toolbar; diff --git a/src/ui/named_views.rs b/src/ui/named_views.rs new file mode 100644 index 000000000..bd7018b0b --- /dev/null +++ b/src/ui/named_views.rs @@ -0,0 +1,91 @@ +//! The named views of the document, as a toolbar popup and a View submenu. + +use egui_phosphor::regular as icon; + +use crate::app::AppState; +use crate::commands::Action; + +/// The full list: go to, update or delete each view, and save the current +/// camera under a typed name. +pub fn manager(ui: &mut egui::Ui, state: &AppState, actions: &mut Vec) { + ui.set_min_width(240.0); + ui.strong("Named views"); + let views = &state.viewer.named_views; + if views.is_empty() { + ui.weak("None yet: save the current view below."); + } + for (index, view) in views.iter().enumerate() { + ui.horizontal(|ui| { + let go = ui + .add(egui::Button::new(&view.name).frame(false)) + .on_hover_text(format!( + "Go to this view ({})", + view.projection.label().to_lowercase() + )); + if go.clicked() { + actions.push(Action::GoToView(index)); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .small_button(icon::TRASH) + .on_hover_text("Delete") + .clicked() + { + actions.push(Action::DeleteView(index)); + } + if ui + .small_button(icon::ARROWS_CLOCKWISE) + .on_hover_text("Replace with the current view") + .clicked() + { + actions.push(Action::UpdateView(index)); + } + }); + }); + } + ui.separator(); + let id = ui.id().with("new_view_name"); + let mut name = ui.data_mut(|data| data.get_temp::(id).unwrap_or_default()); + let mut save = false; + ui.horizontal(|ui| { + let field = ui.add( + egui::TextEdit::singleline(&mut name) + .hint_text("Name") + .desired_width(150.0), + ); + save |= field.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); + save |= ui + .button(format!("{} Save", icon::BOOKMARK_SIMPLE)) + .on_hover_text("Save the current view; an existing name is replaced") + .clicked(); + }); + if save { + actions.push(Action::SaveView( + Some(name.trim().to_owned()).filter(|name| !name.is_empty()), + )); + name.clear(); + } + ui.data_mut(|data| data.insert_temp(id, name)); +} + +/// View > Named Views: the views to go to, and saving under the next +/// free name. +pub fn submenu(ui: &mut egui::Ui, state: &AppState, actions: &mut Vec) { + for (index, view) in state.viewer.named_views.iter().enumerate() { + if ui.button(&view.name).clicked() { + actions.push(Action::GoToView(index)); + ui.close(); + } + } + if !state.viewer.named_views.is_empty() { + ui.separator(); + } + if ui + .button(format!("{} Save Current View", icon::BOOKMARK_SIMPLE)) + .on_hover_text("As \"View N\"; rename or delete views from the toolbar") + .clicked() + { + actions.push(Action::SaveView(None)); + ui.close(); + } +} diff --git a/src/ui/status_bar.rs b/src/ui/status_bar.rs new file mode 100644 index 000000000..0c1af69e2 --- /dev/null +++ b/src/ui/status_bar.rs @@ -0,0 +1,115 @@ +//! The status bar: last message on the left; Python worker state, cursor +//! position and file format on the right. + +use egui::RichText; +use egui_phosphor::regular as icon; + +use crate::app::{AppState, StatusKind}; +use crate::document::Encoding; +use crate::worker; + +pub fn ui(ui: &mut egui::Ui, state: &AppState) { + let visuals = ui.visuals().clone(); + let success = state.palette().success; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 14.0; + // The fixed indicators are laid out first, from the right; the + // message gets what remains, so a long error cannot push them out. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let (glyph, text, color) = match state.worker.status() { + worker::Status::Ready(info) => ( + icon::CIRCLE, + format!("Python {} · CadQuery {}", info.python, info.cadquery), + success, + ), + worker::Status::Starting => ( + icon::HOURGLASS, + "Starting Python…".to_owned(), + visuals.warn_fg_color, + ), + worker::Status::NotStarted => ( + icon::CIRCLE_DASHED, + "Python not started".to_owned(), + visuals.weak_text_color(), + ), + worker::Status::Failed(_) => ( + icon::WARNING_OCTAGON, + "Python unavailable".to_owned(), + visuals.error_fg_color, + ), + }; + let python = state + .worker + .config() + .map(|c| c.python.display().to_string()) + .unwrap_or_default(); + let tooltip = match state.worker.status() { + worker::Status::Failed(reason) => format!("{reason}\n{python}"), + worker::Status::Ready(info) => { + format!("CadQuery {} · OCP {}\n{python}", info.cadquery, info.ocp) + } + _ => python, + }; + ui.label(RichText::new(text).small()) + .on_hover_text(&tooltip); + ui.label(RichText::new(glyph).color(color).small()) + .on_hover_text(&tooltip); + + match state.document.encoding() { + Encoding::Utf8 => { + ui.label(RichText::new("UTF-8").small().weak()); + } + legacy => { + ui.label( + RichText::new(format!("{} → UTF-8", legacy.label())) + .small() + .color(visuals.warn_fg_color), + ) + .on_hover_text(format!( + "The file was read as {}; saving converts it to UTF-8", + legacy.label() + )); + } + } + ui.label( + RichText::new(state.document.line_ending().label()) + .small() + .weak(), + ); + let (line, column) = state.editor.cursor_position(&state.document.text); + ui.label(RichText::new(format!("Ln {line}, Col {column}")).small()); + if let Some(main) = state.main_script() + && Some(main) != state.document.path() + { + let name = main.file_name().unwrap_or_default().to_string_lossy(); + ui.label(RichText::new(format!("{} {name}", icon::PLAY_CIRCLE)).small()) + .on_hover_text(format!( + "F5 renders the project's main script:\n{}", + main.display() + )); + } + if state.settings.editor.autoreload { + ui.label( + RichText::new(format!("{} Autoreload", icon::ARROWS_CLOCKWISE)) + .small() + .weak(), + ) + .on_hover_text("The script re-runs whenever its file changes on disk"); + } + + if let Some(status) = &state.status { + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + let (glyph, color) = match status.kind { + StatusKind::Info => (icon::INFO, visuals.weak_text_color()), + StatusKind::Success => (icon::CHECK_CIRCLE, success), + StatusKind::Warning => (icon::WARNING, visuals.warn_fg_color), + StatusKind::Error => (icon::X_CIRCLE, visuals.error_fg_color), + }; + ui.label(RichText::new(glyph).color(color)); + // Shows the whole text on hover when truncated. + ui.add(egui::Label::new(&status.text).truncate()); + }); + } + }); + }); +} diff --git a/src/ui/toolbar.rs b/src/ui/toolbar.rs new file mode 100644 index 000000000..d2c7c1cfa --- /dev/null +++ b/src/ui/toolbar.rs @@ -0,0 +1,629 @@ +//! The toolbar below the menu, with the same groups as the original: +//! file, objects, run/debug, inspection and view commands. + +use egui::{Color32, Pos2, Rect, Response, Sense, Shape, Stroke, Vec2}; +use egui_phosphor::regular as icon; +use glam::Vec3; + +use crate::app::AppState; +use crate::commands::{self, Action}; +use crate::viewer::camera::StandardView; +use crate::viewer::{DisplayMode, SelectionMode}; +use crate::worker::protocol::DebugAction; + +const BUTTON_SIZE: Vec2 = Vec2::new(28.0, 26.0); + +/// Space between buttons, in points. +const SPACING: f32 = 2.0; +/// A separator with the space around it. +const SEPARATOR_WIDTH: f32 = 17.0; +/// "Select:" and its drop-down. +const SELECTION_WIDTH: f32 = 125.0; + +/// The toolbar's groups, in the original's order. Those that do not fit the +/// window go, from the last one, to the » menu at its end. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Group { + File, + Objects, + Run, + Inspect, + View, + Display, + Selection, +} + +impl Group { + const ALL: [Group; 7] = [ + Group::File, + Group::Objects, + Group::Run, + Group::Inspect, + Group::View, + Group::Display, + Group::Selection, + ]; + + /// Width of the group in the toolbar, in points. + fn width(self) -> f32 { + let buttons = match self { + Group::File => 5, + Group::Objects => 2, + Group::Run => 8, + Group::Inspect => 1, + // Fit, the standard views and the named views. + Group::View => StandardView::ALL.len() + 2, + // The display modes, section, exploded view and screenshot. + Group::Display => DisplayMode::ALL.len() + 3, + Group::Selection => return SELECTION_WIDTH, + }; + buttons as f32 * (BUTTON_SIZE.x + SPACING) + } +} + +/// How many groups, from the first, fit in `width`. When some do not, the +/// » button takes room too. +fn fitting_groups(width: f32) -> usize { + let widths: Vec = Group::ALL + .iter() + .enumerate() + .map(|(index, group)| group.width() + if index > 0 { SEPARATOR_WIDTH } else { 0.0 }) + .collect(); + if widths.iter().sum::() <= width { + return Group::ALL.len(); + } + let budget = width - SEPARATOR_WIDTH - BUTTON_SIZE.x - SPACING; + let mut used = 0.0; + widths + .iter() + .take_while(|group| { + used += *group; + used <= budget + }) + .count() +} + +pub fn ui(ui: &mut egui::Ui, state: &mut AppState) { + let mut actions = Vec::new(); + let shown = fitting_groups(ui.available_width()); + + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = SPACING; + for (index, group) in Group::ALL[..shown].iter().enumerate() { + if index > 0 { + separator(ui); + } + group_ui(ui, *group, state, &mut actions, false); + } + if shown < Group::ALL.len() { + if shown > 0 { + separator(ui); + } + let more = icon_button(ui, icon::CARET_DOUBLE_RIGHT, true, false) + .on_hover_text("More tools: the window is too narrow for them all"); + egui::Popup::menu(&more) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + for group in &Group::ALL[shown..] { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = SPACING; + group_ui(ui, *group, state, &mut actions, true); + }); + } + }); + } + }); + + state.queue(actions); +} + +/// The buttons of `group`. In the » menu (`overflow`), the controls that +/// open popups of their own become submenus and plain buttons. +fn group_ui( + ui: &mut egui::Ui, + group: Group, + state: &AppState, + actions: &mut Vec, + overflow: bool, +) { + let paused = state.is_paused(); + match group { + Group::File => { + tool( + ui, + actions, + icon::FILE_PLUS, + "New", + Action::NewFile, + true, + false, + ); + tool( + ui, + actions, + icon::FOLDER_OPEN, + "Open", + Action::OpenFile, + true, + false, + ); + tool( + ui, + actions, + icon::FLOPPY_DISK, + "Save", + Action::Save, + true, + false, + ); + tool( + ui, + actions, + icon::FLOPPY_DISK_BACK, + "Save as", + Action::SaveAs, + true, + false, + ); + tool( + ui, + actions, + icon::ARROWS_CLOCKWISE, + "Automatic reload and preview", + Action::ToggleAutoreload, + true, + state.settings.editor.autoreload, + ); + } + Group::Objects => { + let has_objects = !state.scene.is_empty(); + tool( + ui, + actions, + icon::TRASH, + "Clear all objects", + Action::ClearObjects, + has_objects, + false, + ); + tool( + ui, + actions, + icon::X_SQUARE, + "Clear current object", + Action::RemoveSelected, + !state.scene.selection.is_empty(), + false, + ); + } + Group::Run => { + // Names the project's main script when another file is shown. + let render = match state.main_script() { + Some(main) if Some(main) != state.document.path() => format!( + "Render {}", + main.file_name().unwrap_or_default().to_string_lossy() + ), + _ => "Render".to_owned(), + }; + // Green, as the run button of most editors: the first thing to + // press. + let run = state.palette().success; + if icon_button_colored(ui, icon::PLAY, true, false, Some(run)) + .on_hover_text(tooltip_text(ui, &render, &Action::Render)) + .clicked() + { + actions.push(Action::Render); + } + tool( + ui, + actions, + icon::TIMER, + "Profile: render and show each line's time in the gutter", + Action::Profile, + true, + !state.editor.line_profile.is_empty(), + ); + tool( + ui, + actions, + icon::BUG, + "Debug", + Action::ToggleDebug, + true, + state.is_debugging(), + ); + tool( + ui, + actions, + icon::ARROW_BEND_DOWN_RIGHT, + "Step", + Action::Debug(DebugAction::Step), + paused, + false, + ); + tool( + ui, + actions, + icon::ARROW_ELBOW_DOWN_RIGHT, + "Step in", + Action::Debug(DebugAction::StepIn), + paused, + false, + ); + tool( + ui, + actions, + icon::ARROW_ELBOW_UP_LEFT, + "Step out", + Action::Debug(DebugAction::StepOut), + paused, + false, + ); + tool( + ui, + actions, + icon::FAST_FORWARD, + "Continue", + Action::Debug(DebugAction::Continue), + paused, + false, + ); + tool( + ui, + actions, + icon::STOP, + "Stop", + Action::Stop, + state.can_stop(), + false, + ); + } + Group::Inspect => tool( + ui, + actions, + icon::STACK, + "Inspect CQ object", + Action::ToggleInspect, + true, + state.inspector.show_in_view, + ), + Group::View => { + tool( + ui, + actions, + icon::CORNERS_OUT, + "Fit", + Action::Fit, + true, + false, + ); + for view in StandardView::ALL { + let action = Action::View(view); + let tooltip = tooltip_text(ui, view.label(), &action); + if view_button(ui, view).on_hover_text(tooltip).clicked() { + actions.push(action); + } + } + let hint = "Named views: save the camera and come back to it"; + if overflow { + ui.menu_button(icon::BOOKMARKS_SIMPLE, |ui| { + super::named_views::manager(ui, state, actions); + }) + .response + .on_hover_text(hint); + } else { + let views = + icon_button(ui, icon::BOOKMARKS_SIMPLE, true, false).on_hover_text(hint); + egui::Popup::menu(&views) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| super::named_views::manager(ui, state, actions)); + } + } + Group::Display => { + for mode in DisplayMode::ALL { + let (glyph, tooltip) = match mode { + DisplayMode::Wireframe => (icon::CUBE_TRANSPARENT, "Wireframe"), + DisplayMode::Shaded => (icon::CUBE, "Shaded"), + DisplayMode::XRay => (icon::INTERSECT_SQUARE, "X-ray: see-through faces"), + DisplayMode::HiddenLine => ( + icon::RECTANGLE_DASHED, + "Hidden line: visible edges, hidden ones dashed", + ), + DisplayMode::Presentation => ( + icon::SPARKLE, + "Presentation: the model for showing, with the lights, material \ + and background of Preferences > Presentation", + ), + }; + tool( + ui, + actions, + glyph, + tooltip, + Action::Display(mode), + true, + state.viewer.display_mode == mode, + ); + } + tool( + ui, + actions, + icon::SCISSORS, + "Section view: cut the model with a plane", + Action::ToggleSection, + true, + state.viewer.section.enabled, + ); + tool( + ui, + actions, + icon::ARROWS_OUT, + "Exploded view: move the parts apart", + Action::ToggleExplode, + true, + state.viewer.explode_controls, + ); + tool( + ui, + actions, + icon::CAMERA, + "Screenshot", + Action::Screenshot, + true, + false, + ); + } + Group::Selection => { + ui.label("Select:"); + let hint = |mode| match mode { + SelectionMode::Auto => "Nearest vertex, edge or face", + SelectionMode::Object => "Whole displayed object", + SelectionMode::Face => "Faces only", + SelectionMode::Edge => "Edges only", + SelectionMode::Vertex => "Vertices only", + }; + let mut choices = |ui: &mut egui::Ui| { + for mode in SelectionMode::ALL { + let action = Action::SelectionMode(mode); + let custom = state.settings.viewer.selection_shortcuts.get(mode).trim(); + let label = if custom.is_empty() { + hint(mode).to_owned() + } else { + format!("{} ({custom})", hint(mode)) + }; + let tooltip = tooltip_text(ui, &label, &action); + if ui + .selectable_label(state.viewer.selection_mode == mode, mode.label()) + .on_hover_text(tooltip) + .clicked() + { + actions.push(action); + } + } + }; + if overflow { + choices(ui); + } else { + egui::ComboBox::from_id_salt("topology_selection_mode") + .width(72.0) + .selected_text(state.viewer.selection_mode.label()) + .show_ui(ui, choices); + } + } + } +} + +fn tool( + ui: &mut egui::Ui, + actions: &mut Vec, + glyph: &str, + tooltip: &str, + action: Action, + enabled: bool, + selected: bool, +) { + if icon_button(ui, glyph, enabled, selected) + .on_hover_text(tooltip_text(ui, tooltip, &action)) + .clicked() + { + actions.push(action); + } +} + +fn tooltip_text(ui: &egui::Ui, label: &str, action: &Action) -> String { + match commands::shortcut(action) { + Some(shortcut) => format!("{label} ({})", ui.ctx().format_shortcut(&shortcut)), + None => label.to_owned(), + } +} + +fn separator(ui: &mut egui::Ui) { + ui.add_space(4.0); + ui.separator(); + ui.add_space(4.0); +} + +fn button_frame(ui: &mut egui::Ui, enabled: bool, selected: bool) -> (Rect, Response) { + let sense = if enabled { + Sense::click() + } else { + Sense::hover() + }; + let (rect, response) = ui.allocate_exact_size(BUTTON_SIZE, sense); + let visuals = ui.visuals(); + let fill = if selected { + visuals.selection.bg_fill + } else if enabled && response.is_pointer_button_down_on() { + visuals.widgets.active.weak_bg_fill + } else if enabled && response.hovered() { + visuals.widgets.hovered.weak_bg_fill + } else { + Color32::TRANSPARENT + }; + ui.painter().rect_filled(rect, 5.0, fill); + (rect, response) +} + +fn icon_button(ui: &mut egui::Ui, glyph: &str, enabled: bool, selected: bool) -> Response { + icon_button_colored(ui, glyph, enabled, selected, None) +} + +/// An icon button whose glyph has `color` when it is enabled. +fn icon_button_colored( + ui: &mut egui::Ui, + glyph: &str, + enabled: bool, + selected: bool, + color: Option, +) -> Response { + let (rect, response) = button_frame(ui, enabled, selected); + let color = if enabled { + color.unwrap_or_else(|| ui.visuals().text_color()) + } else { + ui.visuals().weak_text_color().gamma_multiply(0.6) + }; + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + glyph, + egui::FontId::proportional(17.0), + color, + ); + response +} + +/// A small isometric cube with the face of `view` highlighted; hidden faces +/// (back, left, bottom) are drawn through the cube with dashed edges. +fn view_button(ui: &mut egui::Ui, view: StandardView) -> Response { + let (rect, response) = button_frame(ui, true, false); + let text = ui.visuals().text_color(); + let accent = ui.visuals().hyperlink_color; + paint_view_icon(ui.painter(), rect.shrink(5.0), view, text, accent); + response +} + +fn paint_view_icon( + painter: &egui::Painter, + rect: Rect, + view: StandardView, + line: Color32, + accent: Color32, +) { + let rotation = StandardView::Iso.rotation().inverse(); + let scale = rect.height() / 3.2; + let project = |p: Vec3| { + let v = rotation * (p * 2.0 - Vec3::ONE); + Pos2::new(rect.center().x + v.x * scale, rect.center().y - v.y * scale) + }; + // Faces as (outward normal, corners). + let faces: [(Vec3, [Vec3; 4]); 6] = [ + ( + Vec3::Z, + [ + Vec3::new(0.0, 0.0, 1.0), + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(1.0, 1.0, 1.0), + Vec3::new(0.0, 1.0, 1.0), + ], + ), + ( + Vec3::NEG_Z, + [ + Vec3::new(0.0, 0.0, 0.0), + Vec3::new(0.0, 1.0, 0.0), + Vec3::new(1.0, 1.0, 0.0), + Vec3::new(1.0, 0.0, 0.0), + ], + ), + ( + Vec3::NEG_Y, + [ + Vec3::new(0.0, 0.0, 0.0), + Vec3::new(1.0, 0.0, 0.0), + Vec3::new(1.0, 0.0, 1.0), + Vec3::new(0.0, 0.0, 1.0), + ], + ), + ( + Vec3::Y, + [ + Vec3::new(0.0, 1.0, 0.0), + Vec3::new(0.0, 1.0, 1.0), + Vec3::new(1.0, 1.0, 1.0), + Vec3::new(1.0, 1.0, 0.0), + ], + ), + ( + Vec3::X, + [ + Vec3::new(1.0, 0.0, 0.0), + Vec3::new(1.0, 1.0, 0.0), + Vec3::new(1.0, 1.0, 1.0), + Vec3::new(1.0, 0.0, 1.0), + ], + ), + ( + Vec3::NEG_X, + [ + Vec3::new(0.0, 0.0, 0.0), + Vec3::new(0.0, 0.0, 1.0), + Vec3::new(0.0, 1.0, 1.0), + Vec3::new(0.0, 1.0, 0.0), + ], + ), + ]; + let eye = StandardView::Iso.orientation().0; + let highlighted = match view { + StandardView::Iso => None, + other => Some(other.orientation().0), + }; + + // Hidden geometry first, so visible faces cover it. + for (normal, corners) in &faces { + let visible = normal.dot(eye) > 0.0; + let points: Vec = corners.iter().map(|c| project(*c)).collect(); + let is_target = highlighted.is_some_and(|h| h == *normal); + if !visible { + if is_target { + painter.add(Shape::convex_polygon( + points.clone(), + accent.gamma_multiply(0.55), + Stroke::NONE, + )); + } + for i in 0..4 { + let dashes = Shape::dashed_line( + &[points[i], points[(i + 1) % 4]], + Stroke::new(0.8, line.gamma_multiply(0.45)), + 1.5, + 1.5, + ); + painter.extend(dashes); + } + } + } + for (normal, corners) in &faces { + if normal.dot(eye) <= 0.0 { + continue; + } + let mut points: Vec = corners.iter().map(|c| project(*c)).collect(); + let area: f32 = points + .iter() + .zip(points.iter().cycle().skip(1)) + .map(|(a, b)| a.x * b.y - b.x * a.y) + .sum(); + if area < 0.0 { + points.reverse(); + } + let fill = if highlighted.is_some_and(|h| h == *normal) || view == StandardView::Iso { + accent.gamma_multiply(if view == StandardView::Iso { 0.45 } else { 0.9 }) + } else { + Color32::TRANSPARENT + }; + painter.add(Shape::convex_polygon(points, fill, Stroke::new(1.0, line))); + } +} + +#[cfg(test)] +#[path = "../../tests/rust/app/test_toolbar.rs"] +mod tests; diff --git a/src/updates.rs b/src/updates.rs new file mode 100644 index 000000000..da77cdb42 --- /dev/null +++ b/src/updates.rs @@ -0,0 +1,48 @@ +//! Knowing when a newer CQ-editor is out (FEAT-E5). +//! +//! The worker asks GitHub for CQ-editor's releases (the GUI has no HTTP +//! client of its own); this decides when to ask and what an answer means. + +use crate::settings::General; +use crate::worker::protocol::Release; + +/// This CQ-editor's version. +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); +/// The daily check waits this long between two checks, in seconds. +pub const CHECK_INTERVAL: u64 = 24 * 60 * 60; +/// Release pages are opened only on this site. +const RELEASES_SITE: &str = "https://github.com/"; + +/// `"v1.2.3-rc1"` -> `(1, 2, 3)`: the first three numbers, missing ones 0. +pub fn version_key(version: &str) -> (u64, u64, u64) { + let mut numbers = version + .split(|c: char| !c.is_ascii_digit()) + .filter(|part| !part.is_empty()) + .map(|part| part.parse().unwrap_or(u64::MAX)); + let mut next = || numbers.next().unwrap_or(0); + (next(), next(), next()) +} + +/// Whether the release `tag` is newer than the version `than`. +pub fn is_newer(tag: &str, than: &str) -> bool { + version_key(tag) > version_key(than) +} + +/// Whether the daily check is due `now` (seconds since the Unix epoch). +pub fn check_due(general: &General, now: u64) -> bool { + general.check_updates && now.saturating_sub(general.last_update_check) >= CHECK_INTERVAL +} + +/// The release to offer: the newest one found, while it is newer than this +/// CQ-editor (which may have been updated since) and its page is on GitHub. +pub fn available(general: &General) -> Option<&Release> { + general + .newer_release + .as_ref() + .filter(|release| is_newer(&release.tag, VERSION)) + .filter(|release| release.url.starts_with(RELEASES_SITE)) +} + +#[cfg(test)] +#[path = "../tests/rust/app/test_updates.rs"] +mod tests; diff --git a/src/viewer/camera.rs b/src/viewer/camera.rs new file mode 100644 index 000000000..43ba3fe14 --- /dev/null +++ b/src/viewer/camera.rs @@ -0,0 +1,476 @@ +//! Orbit camera for the 3D view. +//! +//! The camera orbits around `target`. `rotation` maps camera space to world +//! space; the camera looks down its local -Z axis with +Y up. Zoom is +//! expressed as `extent`, the half height of the visible area at the target, +//! which keeps the framing identical when switching between orthographic and +//! perspective projection. + +use glam::camera::rh::{proj::directx, view}; +use glam::{Mat3, Mat4, Quat, Vec2, Vec3, Vec4}; + +use crate::scene::Aabb; +use crate::settings::Projection; + +/// Radians of rotation per pixel of mouse motion (turntable). +const ROTATE_SPEED: f32 = 0.008; +const MIN_EXTENT: f32 = 1e-4; +const MAX_EXTENT: f32 = 1e7; +/// Empty space left around the model by "fit". +const FIT_MARGIN: f32 = 1.08; +/// Distance between the eyes of the stereo pair, relative to the distance +/// to the target (the default of OpenCASCADE's camera, used by the original +/// editor). +pub const STEREO_SEPARATION: f32 = 0.05; + +/// Where a view is seen from: the camera itself, or one eye of the stereo +/// pair. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Eye { + #[default] + Center, + Left, + Right, +} + +/// The fixed views of the View menu and toolbar. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StandardView { + Iso, + Top, + Bottom, + Front, + Back, + Left, + Right, +} + +impl StandardView { + pub const ALL: [StandardView; 7] = [ + StandardView::Iso, + StandardView::Top, + StandardView::Bottom, + StandardView::Front, + StandardView::Back, + StandardView::Left, + StandardView::Right, + ]; + + pub fn label(self) -> &'static str { + match self { + StandardView::Iso => "Iso", + StandardView::Top => "Top", + StandardView::Bottom => "Bottom", + StandardView::Front => "Front", + StandardView::Back => "Back", + StandardView::Left => "Left", + StandardView::Right => "Right", + } + } + + /// Direction from the target towards the eye, and the up vector. + pub fn orientation(self) -> (Vec3, Vec3) { + match self { + StandardView::Iso => (Vec3::new(1.0, -1.0, 1.0), Vec3::Z), + StandardView::Top => (Vec3::Z, Vec3::Y), + StandardView::Bottom => (Vec3::NEG_Z, Vec3::NEG_Y), + StandardView::Front => (Vec3::NEG_Y, Vec3::Z), + StandardView::Back => (Vec3::Y, Vec3::Z), + StandardView::Left => (Vec3::NEG_X, Vec3::Z), + StandardView::Right => (Vec3::X, Vec3::Z), + } + } + + pub fn rotation(self) -> Quat { + let (eye, up) = self.orientation(); + look_rotation(eye, up) + } +} + +/// Rotation of a camera whose eye lies in direction `eye_dir` from the +/// target, with `up` projected to the screen's vertical. +pub fn look_rotation(eye_dir: Vec3, up: Vec3) -> Quat { + let back = eye_dir.normalize(); + let mut right = up.cross(back); + if right.length_squared() < 1e-10 { + // `up` is parallel to the view direction: pick any perpendicular. + right = Vec3::X.cross(back); + if right.length_squared() < 1e-10 { + right = Vec3::Y.cross(back); + } + } + let right = right.normalize(); + Quat::from_mat3(&Mat3::from_cols(right, back.cross(right), back)).normalize() +} + +/// The animatable part of the camera state. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + pub target: Vec3, + pub rotation: Quat, + pub extent: f32, +} + +#[derive(Clone, Debug)] +pub struct Camera { + pub target: Vec3, + pub rotation: Quat, + pub extent: f32, + pub projection: Projection, + /// Vertical field of view of the perspective projection, radians. + pub fov_y: f32, + /// Bounding sphere of the scene, used to place the clipping planes. + pub scene_center: Vec3, + pub scene_radius: f32, +} + +impl Default for Camera { + fn default() -> Self { + Self { + target: Vec3::ZERO, + rotation: StandardView::Iso.rotation(), + extent: 20.0, + projection: Projection::Orthographic, + fov_y: 30f32.to_radians(), + scene_center: Vec3::ZERO, + scene_radius: 20.0, + } + } +} + +impl Camera { + pub fn pose(&self) -> Pose { + Pose { + target: self.target, + rotation: self.rotation, + extent: self.extent, + } + } + + pub fn set_pose(&mut self, pose: Pose) { + self.target = pose.target; + self.rotation = pose.rotation.normalize(); + self.extent = pose.extent.clamp(MIN_EXTENT, MAX_EXTENT); + } + + pub fn forward(&self) -> Vec3 { + self.rotation * Vec3::NEG_Z + } + + pub fn up(&self) -> Vec3 { + self.rotation * Vec3::Y + } + + pub fn right(&self) -> Vec3 { + self.rotation * Vec3::X + } + + pub fn is_perspective(&self) -> bool { + self.projection.is_perspective() + } + + /// The eye a mono-eye projection draws from; the centre otherwise + /// (stereo draws both eyes, but picks from the centre). + pub fn mono_eye(&self) -> Eye { + match self.projection { + Projection::MonoLeftEye => Eye::Left, + Projection::MonoRightEye => Eye::Right, + _ => Eye::Center, + } + } + + /// How far `eye` is to the right of the camera. + fn eye_shift(&self, eye: Eye) -> f32 { + let half = STEREO_SEPARATION * self.distance() / 2.0; + match eye { + Eye::Center => 0.0, + Eye::Left => -half, + Eye::Right => half, + } + } + + pub fn eye_position(&self, eye: Eye) -> Vec3 { + self.eye() + self.right() * self.eye_shift(eye) + } + + /// What `eye` sees: moved sideways, with its frustum shifted back so + /// that both eyes see the target's plane in the same place (zero + /// parallax there; nearer things stand out of the screen). + pub fn eye_view_projection(&self, aspect: f32, eye: Eye) -> Mat4 { + let projection = self.projection_matrix(aspect); + let shift = self.eye_shift(eye); + if shift == 0.0 { + return projection * self.view_matrix(); + } + let view = view::look_to_mat4(self.eye_position(eye), self.forward(), self.up()); + // x_clip += converge · w_clip, so the target plane lands where the + // centre eye sees it. + let converge = shift * projection.x_axis.x / self.distance(); + Mat4::from_cols( + Vec4::X, + Vec4::Y, + Vec4::Z, + Vec4::new(converge, 0.0, 0.0, 1.0), + ) * projection + * view + } + + /// Distance from the eye to the target; for orthographic projection it + /// only matters for the clipping planes. + pub fn distance(&self) -> f32 { + self.extent / (self.fov_y * 0.5).tan() + } + + pub fn eye(&self) -> Vec3 { + self.target - self.forward() * self.distance() + } + + pub fn view_matrix(&self) -> Mat4 { + view::look_to_mat4(self.eye(), self.forward(), self.up()) + } + + pub fn projection_matrix(&self, aspect: f32) -> Mat4 { + let (near, far) = self.clip_planes(); + match self.projection { + // WebGPU clip space: depth in 0..1, y up. + Projection::Orthographic => { + let (h, w) = (self.extent, self.extent * aspect); + directx::orthographic(-w, w, -h, h, near, far) + } + _ => directx::perspective(self.fov_y, aspect, near, far), + } + } + + /// What the view shows: from the mono eye of a mono-eye projection. + pub fn view_projection(&self, aspect: f32) -> Mat4 { + self.eye_view_projection(aspect, self.mono_eye()) + } + + /// Near and far planes enclosing the scene's bounding sphere. + fn clip_planes(&self) -> (f32, f32) { + let distance = self.distance(); + let center_depth = (self.scene_center - self.eye()).dot(self.forward()); + let radius = self.scene_radius.max(self.extent).max(1e-3) * 1.5; + if self.is_perspective() { + let near = (center_depth - radius).max(distance * 1e-3); + let far = (center_depth + radius).max(near * 2.0); + (near, far) + } else { + // Negative near planes are fine for orthographic projection + // and keep geometry behind the eye position visible. + let near = center_depth.min(distance) - radius; + let far = center_depth.max(distance) + radius; + (near, far) + } + } + + /// World-space ray through a point given in normalized device + /// coordinates (x right, y up, both in -1..1). + pub fn ray(&self, ndc: Vec2, aspect: f32) -> (Vec3, Vec3) { + let (right, up, forward) = (self.right(), self.up(), self.forward()); + if self.is_perspective() { + let tan = (self.fov_y * 0.5).tan(); + let dir = forward + right * (ndc.x * tan * aspect) + up * (ndc.y * tan); + // From the mono eye, through the point of the target's plane the + // centre eye sees there (both eyes agree on that plane). + let eye = self.eye_position(self.mono_eye()); + let on_target_plane = self.eye() + dir * self.distance(); + (eye, (on_target_plane - eye).normalize()) + } else { + let on_target = + self.target + right * (ndc.x * self.extent * aspect) + up * (ndc.y * self.extent); + let back_off = self.distance() + 2.0 * self.scene_radius + self.extent; + (on_target - forward * back_off, forward) + } + } + + /// Turntable orbit: horizontal motion spins around the world Z axis, + /// vertical motion tilts around the screen's horizontal axis. + pub fn orbit_turntable(&mut self, delta_px: Vec2) { + let yaw = Quat::from_rotation_z(-delta_px.x * ROTATE_SPEED); + let pitch = Quat::from_axis_angle(self.right(), -delta_px.y * ROTATE_SPEED); + self.rotation = (yaw * pitch * self.rotation).normalize(); + } + + /// Turntable orbit around `pivot`, which keeps its place on screen. + pub fn orbit_turntable_about(&mut self, delta_px: Vec2, pivot: Vec3) { + self.turn_about(pivot, |camera| camera.orbit_turntable(delta_px)); + } + + /// Turns the camera with `turn`, then moves the target so that `pivot` + /// keeps the same screen position and depth (a panned view stays panned). + fn turn_about(&mut self, pivot: Vec3, turn: impl FnOnce(&mut Self)) { + let offset = pivot - self.target; + let (right, up, forward) = ( + offset.dot(self.right()), + offset.dot(self.up()), + offset.dot(self.forward()), + ); + turn(self); + self.target = pivot - self.right() * right - self.up() * up - self.forward() * forward; + } + + /// Virtual trackball between two pointer positions given in coordinates + /// normalized by the viewport (y up, roughly -1..1). + pub fn orbit_trackball(&mut self, from: Vec2, to: Vec2) { + let (a, b) = (trackball_point(from), trackball_point(to)); + let axis = a.cross(b); + if axis.length_squared() < 1e-12 { + return; + } + let angle = a.dot(b).clamp(-1.0, 1.0).acos() * 2.0; + // The model turns with the pointer, so the camera turns the other way. + let model_turn = Quat::from_axis_angle(axis.normalize(), angle); + self.rotation = (self.rotation * model_turn.inverse()).normalize(); + } + + /// Trackball orbit around `pivot`, which keeps its place on screen. + pub fn orbit_trackball_about(&mut self, from: Vec2, to: Vec2, pivot: Vec3) { + self.turn_about(pivot, |camera| camera.orbit_trackball(from, to)); + } + + /// Removes any roll so that world Z points up on screen (used when + /// switching to turntable mode). + pub fn level(&mut self) { + let back = -self.forward(); + let up = if back.cross(Vec3::Z).length_squared() < 1e-8 { + self.up() + } else { + Vec3::Z + }; + self.rotation = look_rotation(back, up); + } + + /// Moves the view so the scene follows the pointer. + pub fn pan(&mut self, delta_px: Vec2, viewport_height_px: f32) { + let units_per_px = 2.0 * self.extent / viewport_height_px.max(1.0); + self.target += (-self.right() * delta_px.x + self.up() * delta_px.y) * units_per_px; + } + + /// Scales the view by `factor` (< 1 zooms in), keeping the point under + /// `anchor_ndc` fixed on screen. + pub fn zoom(&mut self, factor: f32, anchor_ndc: Vec2, aspect: f32) { + let new_extent = (self.extent * factor).clamp(MIN_EXTENT, MAX_EXTENT); + let factor = new_extent / self.extent; + let anchor = self.target + + self.right() * (anchor_ndc.x * self.extent * aspect) + + self.up() * (anchor_ndc.y * self.extent); + self.target = anchor + (self.target - anchor) * factor; + self.extent = new_extent; + } + + /// The pose that frames `bounds` with the current orientation. + pub fn fit_pose(&self, bounds: Aabb, aspect: f32) -> Pose { + let bounds = if bounds.is_empty() { + Aabb { + min: Vec3::splat(-10.0), + max: Vec3::splat(10.0), + } + } else { + bounds + }; + let center = bounds.center(); + let (right, up) = (self.right(), self.up()); + let (mut half_width, mut half_height) = (0f32, 0f32); + for i in 0..8 { + let corner = Vec3::new( + if i & 1 == 0 { + bounds.min.x + } else { + bounds.max.x + }, + if i & 2 == 0 { + bounds.min.y + } else { + bounds.max.y + }, + if i & 4 == 0 { + bounds.min.z + } else { + bounds.max.z + }, + ) - center; + half_width = half_width.max(corner.dot(right).abs()); + half_height = half_height.max(corner.dot(up).abs()); + } + let mut extent = half_height.max(half_width / aspect.max(1e-3)) * FIT_MARGIN; + if self.is_perspective() { + // Parts in front of the target plane appear larger. + extent *= 1.15; + } + Pose { + target: center, + rotation: self.rotation, + extent: extent.max(MIN_EXTENT * 10.0), + } + } +} + +/// Projects a world point to normalized device coordinates with a +/// [`Camera::view_projection`]; `None` behind the eye. Callers projecting +/// many points compute the matrix once. +pub fn project_with(view_projection: Mat4, point: Vec3) -> Option { + let clip = view_projection * point.extend(1.0); + (clip.w > 1e-6).then(|| clip.truncate() / clip.w) +} + +/// Holroyd's trackball: a sphere blended into a hyperbolic sheet, so the +/// rotation stays smooth away from the center. +fn trackball_point(p: Vec2) -> Vec3 { + let d2 = p.length_squared(); + if d2 <= 0.5 { + Vec3::new(p.x, p.y, (1.0 - d2).sqrt()) + } else { + Vec3::new(p.x, p.y, 0.5 / d2.sqrt()).normalize() + } +} + +/// Smooth transition between two poses. +#[derive(Clone, Debug)] +pub struct Animation { + from: Pose, + to: Pose, + start: f64, + duration: f64, +} + +impl Animation { + pub fn new(from: Pose, to: Pose, now: f64, duration: f64) -> Self { + Self { + from, + to, + start: now, + duration, + } + } + + pub fn target(&self) -> Pose { + self.to + } + + /// The pose at time `now`, and whether the animation is over. + pub fn sample(&self, now: f64) -> (Pose, bool) { + let t = if self.duration > 0.0 { + ((now - self.start) / self.duration).clamp(0.0, 1.0) as f32 + } else { + 1.0 + }; + // Cubic ease in-out. + let e = if t < 0.5 { + 4.0 * t * t * t + } else { + 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0 + }; + let pose = Pose { + target: self.from.target.lerp(self.to.target, e), + rotation: self.from.rotation.slerp(self.to.rotation, e), + extent: (self.from.extent.ln() + (self.to.extent.ln() - self.from.extent.ln()) * e) + .exp(), + }; + (pose, t >= 1.0) + } +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_camera.rs"] +mod tests; diff --git a/src/viewer/capture.rs b/src/viewer/capture.rs new file mode 100644 index 000000000..d66eb291f --- /dev/null +++ b/src/viewer/capture.rs @@ -0,0 +1,407 @@ +//! Saving the view as images: screenshots of any size, with or without the +//! background, and turntable animations (FEAT-C5). + +use std::fs::File; +use std::io::BufWriter; +use std::path::{Path, PathBuf}; + +use glam::Quat; + +use super::camera::Pose; + +/// The largest side of a capture. Larger images than the GPU can draw at +/// once are drawn in tiles, so the limit is memory: 256 MB at 8192 × 8192. +pub const MAX_IMAGE_SIDE: u32 = 8192; +pub const MAX_TURNTABLE_FRAMES: u32 = 720; +pub const MAX_FRAMES_PER_SECOND: u32 = 60; + +/// Standard resolution presets for screenshots and turntable exports. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ResolutionPreset { + Hd, + FullHd, + Qhd, + Uhd4k, + Square, +} + +impl ResolutionPreset { + pub const ALL: [Self; 5] = [Self::Hd, Self::FullHd, Self::Qhd, Self::Uhd4k, Self::Square]; + + pub const fn size(self) -> [u32; 2] { + match self { + Self::Hd => [1280, 720], + Self::FullHd => [1920, 1080], + Self::Qhd => [2560, 1440], + Self::Uhd4k => [3840, 2160], + Self::Square => [1080, 1080], + } + } + + pub const fn label(self) -> &'static str { + match self { + Self::Hd => "1280 × 720 — HD (16:9)", + Self::FullHd => "1920 × 1080 — Full HD (16:9)", + Self::Qhd => "2560 × 1440 — QHD (16:9)", + Self::Uhd4k => "3840 × 2160 — 4K (16:9)", + Self::Square => "1080 × 1080 — Square (1:1)", + } + } + + pub const fn short_label(self) -> &'static str { + match self { + Self::Hd => "HD", + Self::FullHd => "Full HD", + Self::Qhd => "QHD", + Self::Uhd4k => "4K", + Self::Square => "1:1", + } + } + + #[cfg(test)] + pub fn from_size(size: [u32; 2]) -> Option { + Self::ALL.into_iter().find(|preset| preset.size() == size) + } +} + +/// Simplifies `[width, height]` to an aspect-ratio string such as `"16:9"` or `"1:1"`. +pub fn aspect_ratio_label([width, height]: [u32; 2]) -> String { + let w = width.max(1); + let h = height.max(1); + let divisor = gcd(w, h); + format!("{}:{}", w / divisor, h / divisor) +} + +const fn gcd(mut a: u32, mut b: u32) -> u32 { + while b != 0 { + let t = b; + b = a % b; + a = t; + } + a +} + +/// How large a capture is and whether it has the background. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CaptureOptions { + /// Exact size in pixels; `None` for the view's size times `scale`. + pub size: Option<[u32; 2]>, + pub scale: u32, + /// Leaves the background transparent (PNG alpha). + pub transparent: bool, +} + +impl Default for CaptureOptions { + fn default() -> Self { + Self { + size: None, + scale: 1, + transparent: false, + } + } +} + +impl CaptureOptions { + /// The size of the image for a view of `view` pixels. Both sides + /// shrink by the same factor when one would exceed [`MAX_IMAGE_SIDE`]. + pub fn image_size(&self, view: [u32; 2]) -> [u32; 2] { + let [width, height] = match self.size { + Some(size) => size.map(|side| side.max(1)), + None => view.map(|side| side.max(1).saturating_mul(self.scale.max(1))), + }; + let largest = width.max(height); + if largest <= MAX_IMAGE_SIDE { + return [width, height]; + } + let shrink = f64::from(MAX_IMAGE_SIDE) / f64::from(largest); + [width, height] + .map(|side| ((f64::from(side) * shrink).round() as u32).clamp(1, MAX_IMAGE_SIDE)) + } + + /// How much wider edges and points are drawn, so that the image looks + /// like the view: what is shown is set by its height. + pub fn pixel_scale(&self, view: [u32; 2]) -> f32 { + self.image_size(view)[1] as f32 / view[1].max(1) as f32 + } +} + +/// The renderer blends over a transparent black background, which leaves +/// premultiplied colors; PNG stores straight alpha. Colors are sRGB, so +/// they are divided in linear space. +pub fn unpremultiply(pixels: &mut [u8]) { + let linear: Vec = (0..=255u8).map(srgb_to_linear).collect(); + for pixel in pixels.as_chunks_mut::<4>().0 { + let alpha = pixel[3]; + if alpha == 0 || alpha == 255 { + continue; + } + let alpha = f32::from(alpha) / 255.0; + for channel in &mut pixel[..3] { + *channel = linear_to_srgb((linear[usize::from(*channel)] / alpha).min(1.0)); + } + } +} + +fn srgb_to_linear(c: u8) -> f32 { + let c = f32::from(c) / 255.0; + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } +} + +fn linear_to_srgb(c: f32) -> u8 { + let c = if c <= 0.003_130_8 { + c * 12.92 + } else { + 1.055 * c.powf(1.0 / 2.4) - 0.055 + }; + (c * 255.0).round().clamp(0.0, 255.0) as u8 +} + +/// Saves a rendered image as PNG, straightening the alpha of a capture +/// with a transparent background. +pub fn save_png( + path: &Path, + size: [u32; 2], + mut pixels: Vec, + transparent: bool, +) -> Result<(), String> { + if transparent { + unpremultiply(&mut pixels); + } + image::save_buffer( + path, + &pixels, + size[0], + size[1], + image::ExtendedColorType::Rgba8, + ) + .map_err(|error| format!("Cannot write {}: {error}", path.display())) +} + +/// Prepares a rendered RGBA buffer for the system clipboard, straightening +/// premultiplied alpha when `transparent` is set. +pub fn prepare_clipboard_image( + size: [u32; 2], + mut pixels: Vec, + transparent: bool, +) -> egui::ColorImage { + if transparent { + unpremultiply(&mut pixels); + } + egui::ColorImage::from_rgba_unmultiplied([size[0] as usize, size[1] as usize], &pixels) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum AnimationFormat { + /// One animated PNG, which browsers play. + #[default] + AnimatedPng, + /// One PNG per frame, `name_0001.png` and on, for video tools. + PngFiles, +} + +/// One turn of the camera around the model. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct TurntableOptions { + pub frames: u32, + pub frames_per_second: u32, + /// The model turns clockwise seen from above (the camera goes the + /// other way round). + pub clockwise: bool, + pub format: AnimationFormat, +} + +impl Default for TurntableOptions { + fn default() -> Self { + Self { + frames: 72, + frames_per_second: 24, + clockwise: false, + format: AnimationFormat::AnimatedPng, + } + } +} + +/// The camera of frame `index` of `frames`: `start` turned about the +/// vertical (Z) axis through the point it looks at. +pub fn turntable_pose(start: Pose, index: u32, frames: u32, clockwise: bool) -> Pose { + let turn = std::f32::consts::TAU * index as f32 / frames.max(1) as f32; + // Turning the camera one way turns the model the other way. + let angle = if clockwise { turn } else { -turn }; + Pose { + rotation: (Quat::from_rotation_z(angle) * start.rotation).normalize(), + ..start + } +} + +/// `turntable.png` → `turntable_0001.png` for the first frame. +pub fn frame_path(path: &Path, index: u32) -> PathBuf { + let stem = path + .file_stem() + .map_or_else(|| "frame".into(), |stem| stem.to_string_lossy()); + path.with_file_name(format!("{stem}_{:04}.png", index + 1)) +} + +enum Output { + Animated(png::Writer>), + Files(Vec), +} + +/// A turntable animation being written, one frame at a time so that the +/// application stays responsive and the export can be cancelled. +pub struct TurntableExport { + path: PathBuf, + turntable: TurntableOptions, + transparent: bool, + start: Pose, + size: [u32; 2], + pixel_scale: f32, + next: u32, + output: Output, +} + +impl TurntableExport { + /// Starts an export of the view of `view` pixels seen from `start`. + pub fn start( + path: PathBuf, + options: CaptureOptions, + turntable: TurntableOptions, + start: Pose, + view: [u32; 2], + ) -> Result { + let turntable = TurntableOptions { + frames: turntable.frames.clamp(1, MAX_TURNTABLE_FRAMES), + frames_per_second: turntable.frames_per_second.clamp(1, MAX_FRAMES_PER_SECOND), + ..turntable + }; + let size = options.image_size(view); + let output = match turntable.format { + AnimationFormat::AnimatedPng => { + let error = + |error: png::EncodingError| format!("Cannot write {}: {error}", path.display()); + let file = File::create(&path) + .map_err(|error| format!("Cannot create {}: {error}", path.display()))?; + let mut encoder = png::Encoder::new(BufWriter::new(file), size[0], size[1]); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + // Played in a loop, each frame replacing the previous one + // (which matters with a transparent background). + encoder.set_animated(turntable.frames, 0).map_err(error)?; + encoder + .set_frame_delay(1, turntable.frames_per_second as u16) + .map_err(error)?; + encoder.set_blend_op(png::BlendOp::Source).map_err(error)?; + encoder + .set_dispose_op(png::DisposeOp::Background) + .map_err(error)?; + Output::Animated(encoder.write_header().map_err(error)?) + } + AnimationFormat::PngFiles => Output::Files(Vec::new()), + }; + Ok(Self { + path, + turntable, + transparent: options.transparent, + start, + size, + pixel_scale: options.pixel_scale(view), + next: 0, + output, + }) + } + + /// Frames written and frames in all. + pub fn progress(&self) -> (u32, u32) { + (self.next, self.turntable.frames) + } + + pub fn size(&self) -> [u32; 2] { + self.size + } + + pub fn pixel_scale(&self) -> f32 { + self.pixel_scale + } + + pub fn transparent(&self) -> bool { + self.transparent + } + + /// The camera of the next frame to write. + pub fn next_pose(&self) -> Pose { + turntable_pose( + self.start, + self.next, + self.turntable.frames, + self.turntable.clockwise, + ) + } + + /// Writes the next frame and tells whether it was the last one. + pub fn write_frame(&mut self, mut pixels: Vec) -> Result { + if self.transparent { + unpremultiply(&mut pixels); + } + match &mut self.output { + Output::Animated(writer) => writer + .write_image_data(&pixels) + .map_err(|error| format!("Cannot write {}: {error}", self.path.display()))?, + Output::Files(written) => { + let path = frame_path(&self.path, self.next); + image::save_buffer( + &path, + &pixels, + self.size[0], + self.size[1], + image::ExtendedColorType::Rgba8, + ) + .map_err(|error| format!("Cannot write {}: {error}", path.display()))?; + written.push(path); + } + } + self.next += 1; + Ok(self.next >= self.turntable.frames) + } + + /// Completes the file once every frame is written, and says where it is. + pub fn finish(self) -> Result { + let frames = self.turntable.frames; + match self.output { + Output::Animated(writer) => { + writer + .finish() + .map_err(|error| format!("Cannot write {}: {error}", self.path.display()))?; + Ok(format!( + "Turntable saved to {} ({frames} frames)", + self.path.display() + )) + } + Output::Files(_) => Ok(format!( + "Turntable saved as {frames} images, {} and on", + frame_path(&self.path, 0).display() + )), + } + } + + /// Stops and removes what was written. + pub fn cancel(self) { + match self.output { + Output::Animated(writer) => { + drop(writer); + let _ = std::fs::remove_file(&self.path); + } + Output::Files(written) => { + for path in written { + let _ = std::fs::remove_file(path); + } + } + } + } +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_capture.rs"] +mod tests; diff --git a/src/viewer/culling.rs b/src/viewer/culling.rs new file mode 100644 index 000000000..67fceec37 --- /dev/null +++ b/src/viewer/culling.rs @@ -0,0 +1,106 @@ +//! What is drawn of a large model: parts outside the view are skipped and +//! parts drawn small use a simplified mesh (FEAT-C6). + +use glam::{Mat4, Vec2, Vec3, Vec4}; + +use super::camera::Camera; +use crate::scene::Aabb; +use crate::settings::LargeModels; + +/// From this many triangles shown, `LargeModels::Automatic` simplifies. +pub const LARGE_MODEL_TRIANGLES: usize = 2_000_000; +/// Parts smaller than this on screen, in pixels, use a simplified mesh. +const SMALL_PART_PX: f32 = 80.0; +/// Parts smaller than this are drawn without their edges and vertices. +const TINY_PART_PX: f32 = 6.0; + +/// The planes bounding what a view-projection matrix shows (WebGPU clip +/// space: depth 0 to 1). +#[derive(Clone, Copy, Debug)] +pub struct Frustum { + /// `dot(plane.xyz, p) + plane.w >= 0` inside. + planes: [Vec4; 6], +} + +impl Frustum { + /// The view widened by `margin` on each side, in normalized device + /// coordinates: edges and points are widened on screen, so their + /// geometry may lie just outside the view and still show. + pub fn new(view_projection: Mat4, margin: Vec2) -> Self { + let [x, y, z, w] = [0, 1, 2, 3].map(|row| view_projection.row(row)); + let (wide, high) = (w * (1.0 + margin.x), w * (1.0 + margin.y)); + Self { + planes: [wide + x, wide - x, high + y, high - y, z, w - z], + } + } + + /// Whether some of `bounds` may be in view. It can say yes for a box + /// near a corner that is not, never no for one that is. + pub fn intersects(&self, bounds: Aabb) -> bool { + !bounds.is_empty() + && self.planes.iter().all(|plane| { + // The corner furthest along the plane's normal. + let normal = plane.truncate(); + let corner = Vec3::select(normal.cmpge(Vec3::ZERO), bounds.max, bounds.min); + normal.dot(corner) + plane.w >= 0.0 + }) + } +} + +impl LargeModels { + /// Whether small parts are simplified with `triangles` shown. + pub fn active(self, triangles: usize) -> bool { + match self { + LargeModels::Automatic => triangles >= LARGE_MODEL_TRIANGLES, + LargeModels::Always => true, + LargeModels::Off => false, + } + } +} + +/// How much of a part to draw. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Detail { + Full, + /// The simplified mesh, with its edges and vertices. + Simplified, + /// The simplified mesh alone. + Faint, +} + +impl Detail { + /// The detail for a part `size_px` across on screen. + pub fn for_size(size_px: f32) -> Self { + if size_px < TINY_PART_PX { + Detail::Faint + } else if size_px < SMALL_PART_PX { + Detail::Simplified + } else { + Detail::Full + } + } +} + +/// How many pixels across `bounds` (world space) appears in a view +/// `view_height` pixels high: the diameter of its bounding sphere. Parts +/// the eye is inside of count as huge. +pub fn projected_size(camera: &Camera, view_height: f32, bounds: Aabb) -> f32 { + if bounds.is_empty() { + return 0.0; + } + let diameter = bounds.diagonal(); + let pixels_per_unit = if camera.is_perspective() { + let depth = (bounds.center() - camera.eye()).dot(camera.forward()); + if depth <= diameter / 2.0 { + return f32::INFINITY; + } + view_height / (2.0 * depth * (camera.fov_y / 2.0).tan()) + } else { + view_height / (2.0 * camera.extent) + }; + diameter * pixels_per_unit +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_culling.rs"] +mod tests; diff --git a/src/viewer/ground.rs b/src/viewer/ground.rs new file mode 100644 index 000000000..1f7b94bdb --- /dev/null +++ b/src/viewer/ground.rs @@ -0,0 +1,230 @@ +//! The ground grid and the scale bar (FEAT-C7). The grid is a floor on the +//! XY plane under the shown model: its height and spacing follow the model, +//! never the camera, so its lines stay put while the view turns and zooms. +//! The floor reaches as far as the view needs and fades into the distance; +//! lines that would crowd together on screen fade out instead of changing +//! spacing. The scale bar follows the zoom and shows a round length (1, 2 or +//! 5 × 10^k). + +use glam::{Vec2, Vec3}; + +use super::camera::Camera; +use crate::scene::{Aabb, Mesh}; +use crate::settings::Units; + +/// Minor cells across the largest dimension of the model, at least. +const CELLS_ACROSS_MODEL: f32 = 20.0; +/// Major lines are every this many minor lines. +const MAJOR_EVERY: i32 = 5; +/// How far the floor reaches past the model's footprint, in model sizes, +/// at least. +const FLOOR_REACH: f32 = 1.5; +/// The fully visible rings of the floor cover the view at least this far +/// from the middle, in half diagonals of the view. +const VIEW_COVER: f32 = 1.4; +/// Views flatter than this (the sine of their elevation) see the floor as +/// if from this elevation: farther lines are faded out anyway. +const MIN_SLANT: f32 = 0.2; +/// Lines from the centre to each side, at most. +const MAX_LINES_PER_SIDE: i32 = 300; +/// The size taken for the model when nothing is shown, in model units. +const EMPTY_SCENE_SIZE: f32 = 100.0; +/// Lines closer than this on screen, in points, are not drawn... +const HIDDEN_SPACING: f32 = 3.0; +/// ...and lines this far apart are fully visible. +const CLEAR_SPACING: f32 = 15.0; +/// The scale bar is at least this long on screen, in points. +const MIN_SCALE_BAR: f32 = 60.0; +/// Opacity of the rings of the floor, from its centre outward. +pub const GRID_FADE: [f32; 4] = [1.0, 0.6, 0.25, 0.025]; +/// Where each ring starts and ends, as a fraction of the floor's radius. +const RING_LIMITS: [f32; 5] = [0.0, 0.5, 0.7, 0.85, 1.0]; + +/// Model units per screen point at the point the camera looks at. +pub fn units_per_point(camera: &Camera, view_height: f32) -> f32 { + let half_height = if camera.is_perspective() { + camera.distance() * (camera.fov_y / 2.0).tan() + } else { + camera.extent + }; + 2.0 * half_height / view_height.max(1.0) +} + +/// The smallest of 1, 2 and 5 × 10^k that is at least `length`. +pub fn round_length(length: f32) -> f32 { + let length = if length.is_finite() && length > 0.0 { + length + } else { + 1.0 + }; + let exponent = length.log10().floor() as i32; + [1.0, 2.0, 5.0, 10.0] + .into_iter() + .map(|mantissa| decimal(mantissa, exponent)) + .find(|&step| step >= length * (1.0 - 1e-5)) + .unwrap_or_else(|| decimal(1.0, exponent + 1)) +} + +/// `mantissa` × 10^`exponent`, as close to the decimal as an f32 gets +/// (`5 × 10⁻²` is the literal `0.05`, which f32 arithmetic would miss). +fn decimal(mantissa: f64, exponent: i32) -> f32 { + (mantissa * 10f64.powi(exponent)) as f32 +} + +/// A length with its unit, without needless decimals: `2.5 mm`, `100 in`. +pub fn format_length(length: f32, units: Units) -> String { + let text = format!("{:.6}", length); + let text = text.trim_end_matches('0').trim_end_matches('.'); + match units.suffix() { + "" => text.to_owned(), + suffix => format!("{text} {suffix}"), + } +} + +/// How visible lines `spacing` apart are at `units_per_point`: 0 when they +/// would blur together on screen, 1 when they are well apart. +pub fn line_opacity(spacing: f32, units_per_point: f32) -> f32 { + let points = spacing / units_per_point.max(f32::MIN_POSITIVE); + ((points - HIDDEN_SPACING) / (CLEAR_SPACING - HIDDEN_SPACING)).clamp(0.0, 1.0) +} + +/// The floor under the model: spacing, where it is centred and how far it +/// reaches. Two grids are drawn with the same lines when they are equal +/// apart from their opacities. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GroundGrid { + /// Distance between minor lines, a round 1, 2 or 5 step. + pub minor: f32, + /// On a major line under the middle of the model, at its lowest point. + pub center: Vec3, + /// How far the floor reaches from its centre. + pub radius: f32, + /// How visible minor lines are at the current zoom (0 to 1). + pub minor_opacity: f32, + /// How visible major lines are at the current zoom (0 to 1). + pub major_opacity: f32, +} + +impl GroundGrid { + /// The floor under a model with `bounds`, or around the origin when + /// nothing is shown, for `camera` in a view `view` points wide and high. + pub fn under(bounds: Aabb, camera: &Camera, view: Vec2) -> Self { + let size = bounds.size(); + let shown = !bounds.is_empty() && size.is_finite() && size.max_element() > 0.0; + let (largest, footprint, middle, floor) = if shown { + ( + size.max_element(), + size.truncate().length() * 0.5, + bounds.center().truncate(), + bounds.min.z, + ) + } else { + (EMPTY_SCENE_SIZE, 0.0, Vec2::ZERO, 0.0) + }; + let minor = round_length(largest / CELLS_ACROSS_MODEL); + let major = minor * MAJOR_EVERY as f32; + // On a major line, so that every line keeps a round coordinate. + let center = (middle / major).round() * major; + let units_per_point = units_per_point(camera, view.y); + // Far enough for the view, whatever it looks at, in doublings of the + // model's own floor so that the lines are not rebuilt at every zoom. + let own = footprint + largest * FLOOR_REACH + (middle - center).length(); + let slant = camera.forward().z.abs().max(MIN_SLANT); + let needed = (camera.target.truncate() - center).length() + + view.length() * 0.5 * units_per_point * VIEW_COVER / slant; + let mut radius = own; + while radius < needed && radius < minor * MAX_LINES_PER_SIDE as f32 { + radius *= 2.0; + } + let radius = radius.min(minor * MAX_LINES_PER_SIDE as f32); + Self { + minor, + center: center.extend(floor), + radius, + minor_opacity: line_opacity(minor, units_per_point), + major_opacity: line_opacity(major, units_per_point), + } + } + + /// Whether `other` has the same lines, whatever their opacities. + pub fn same_lines(&self, other: &Self) -> bool { + Self { + minor_opacity: other.minor_opacity, + major_opacity: other.major_opacity, + ..*self + } == *other + } + + /// The lines inside the floor's circle, split into rings so that its edge + /// fades away instead of ending in a visible square. One minor/major pair + /// per ring of [`GRID_FADE`]. + pub fn faded_meshes(&self) -> Vec<(Mesh, Mesh)> { + let mut minor_rings = GRID_FADE.map(|_| Vec::new()); + let mut major_rings = GRID_FADE.map(|_| Vec::new()); + let limits = RING_LIMITS.map(|fraction| fraction * self.radius); + let lines = (self.radius / self.minor).ceil() as i32; + for index in -lines..=lines { + let offset = index as f32 * self.minor; + let is_major = index % MAJOR_EVERY == 0; + for (across, along) in [(Vec3::X, Vec3::Y), (Vec3::Y, Vec3::X)] { + for ring in 0..GRID_FADE.len() { + let outer = limits[ring + 1]; + if offset.abs() >= outer { + continue; + } + let inner = limits[ring]; + let low = (inner * inner - offset * offset).max(0.0).sqrt(); + let high = (outer * outer - offset * offset).sqrt(); + let points: &mut Vec<[f32; 3]> = if is_major { + &mut major_rings[ring] + } else { + &mut minor_rings[ring] + }; + for (start, end) in [(-high, -low), (low, high)] { + if end - start > 1e-5 { + points.push((self.center + across * offset + along * start).to_array()); + points.push((self.center + across * offset + along * end).to_array()); + } + } + } + } + } + minor_rings + .into_iter() + .zip(major_rings) + .map(|(minor, major)| (Mesh::lines(minor), Mesh::lines(major))) + .collect() + } + + /// Bounds of the floor, for the clipping planes. + pub fn corners(&self) -> [Vec3; 2] { + let reach = Vec3::new(self.radius, self.radius, 0.0); + [self.center - reach, self.center + reach] + } +} + +/// A scale bar: a round length and how long it is on screen. +#[derive(Clone, Debug, PartialEq)] +pub struct ScaleBar { + pub length: f32, + /// In points. + pub width: f32, + pub label: String, +} + +impl ScaleBar { + /// The bar for a view with `units_per_point`, at least + /// [`MIN_SCALE_BAR`] points long. + pub fn new(units_per_point: f32, units: Units) -> Self { + let length = round_length(MIN_SCALE_BAR * units_per_point); + Self { + length, + width: length / units_per_point, + label: format_length(length, units), + } + } +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_ground.rs"] +mod tests; diff --git a/src/viewer/mod.rs b/src/viewer/mod.rs new file mode 100644 index 000000000..59013e157 --- /dev/null +++ b/src/viewer/mod.rs @@ -0,0 +1,1960 @@ +//! The interactive 3D view. +//! +//! Mouse controls (as in the original editor, except the right button): +//! * left or right drag: orbit (turntable or trackball) around the model +//! point under the pointer, or the view centre over empty space +//! * left click: select +//! * middle drag or Ctrl + left drag: pan +//! * Shift + left drag: zoom; mouse wheel: zoom at the pointer +//! * Ctrl + click: add to / remove from the selection + +pub mod camera; +pub mod capture; +mod culling; +mod ground; +mod overlays; +mod picking; +mod renderer; +mod section; +mod shadow; +mod stereo; +mod views; + +use std::path::PathBuf; +use std::sync::Arc; + +use egui::{Color32, Pos2, Rect, Sense, Vec2}; +use egui_phosphor::regular as icon; +use glam::{Mat4 as GMat4, Vec2 as GVec2, Vec3}; + +use crate::commands::Action; +use crate::scene::{Aabb, Grid, MAX_EXPLODE, Mesh, NodeKey, Scene, TopologySelection}; +use crate::settings::{self, NamedView, OrbitMethod}; +use camera::{Animation, Camera, StandardView}; +use capture::{CaptureOptions, TurntableExport, TurntableOptions}; +use culling::Detail; +use ground::{GRID_FADE, GroundGrid, ScaleBar}; +pub use overlays::CubeColors; +use overlays::{NavAction, NavigationCube}; +use renderer::{DrawItem, FrameInput, Layer, SceneRenderer, Style}; +pub use section::{Section, SectionAxis}; +use shadow::GroundShadow; + +/// Zoom factor per point of scrolling (a wheel notch is about 50 points). +const ZOOM_PER_SCROLL_POINT: f32 = 0.9978; +/// Zoom factor per point of vertical drag with the zoom button. +const ZOOM_PER_DRAG_POINT: f32 = 1.006; +/// Each overlay button changes the magnification by this ratio. +const ZOOM_BUTTON_STEP: f32 = 1.25; +/// Slider range relative to the framing established by the last Fit command. +const MIN_ZOOM_PERCENT: f32 = 10.0; +const MAX_ZOOM_PERCENT: f32 = 1600.0; +const ZOOM_CONTROLS_MARGIN: f32 = 12.0; +const ZOOM_CONTROLS_HEIGHT: f32 = 42.0; +const ZOOM_CONTROLS_WIDTH: f32 = 280.0; +const MIN_VIEW_WIDTH_FOR_ZOOM_CONTROLS: f32 = 220.0; +const SECTION_CONTROLS_WIDTH: f32 = 430.0; +const EXPLODE_CONTROLS_WIDTH: f32 = 340.0; +const ISOLATION_CONTROLS_WIDTH: f32 = 330.0; +const CAPTURE_CONTROLS_WIDTH: f32 = 360.0; +const MESHING_CONTROLS_WIDTH: f32 = 360.0; +/// How far the exploded view first spreads the parts. +const DEFAULT_EXPLODE: f32 = 0.5; +/// Duration of camera transitions, seconds. +const ANIMATION_SECONDS: f64 = 0.25; +const POINT_SIZE: f32 = 7.0; +/// Face opacity in the X-ray display mode. +const XRAY_OPACITY: f32 = 0.3; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum DisplayMode { + #[default] + Shaded, + Wireframe, + /// See-through faces, so that every edge shows. + XRay, + /// Faces filled with the background: the visible edges are drawn, the + /// hidden ones as faint dashes (unless turned off in the preferences). + HiddenLine, + /// For showing the model rather than working on it: the settings of + /// Preferences > Presentation (no edges, studio lights, a material for + /// objects without one, a light background, no helpers by default). + Presentation, +} + +impl DisplayMode { + pub const ALL: [DisplayMode; 5] = [ + DisplayMode::Wireframe, + DisplayMode::Shaded, + DisplayMode::XRay, + DisplayMode::HiddenLine, + DisplayMode::Presentation, + ]; + + pub fn label(self) -> &'static str { + match self { + DisplayMode::Shaded => "Shaded", + DisplayMode::Wireframe => "Wireframe", + DisplayMode::XRay => "X-Ray", + DisplayMode::HiddenLine => "Hidden Line", + DisplayMode::Presentation => "Presentation", + } + } + + /// How a scene part is drawn in this mode. Wireframe draws every edge; + /// the other modes draw those the edge style keeps, and the outline of + /// curved surfaces with the Outline style. Wires are drawn whole. + fn style( + self, + look: PartLook, + settings: &settings::Viewer, + rendering: &settings::Rendering, + ) -> Style { + let presentation = &rendering.presentation; + let edge_style = if self == DisplayMode::Presentation { + presentation.edges + } else { + rendering.edges + }; + let filtered = look.has_faces && self != DisplayMode::Wireframe; + let (edge_min_angle, silhouettes) = if filtered { + ( + edge_style.minimum_angle(rendering.sharp_angle), + edge_style == settings::EdgeStyle::Outline, + ) + } else { + (0.0, false) + }; + let edges = match self { + // The edges are all there is to see. + DisplayMode::Wireframe | DisplayMode::HiddenLine => true, + DisplayMode::Shaded | DisplayMode::XRay => look.edges.unwrap_or(settings.show_edges), + DisplayMode::Presentation => look.edges.unwrap_or(presentation.show_edges), + } || !look.has_faces; + let mut face_color = look.face_color; + match self { + DisplayMode::XRay => face_color[3] = face_color[3].min(XRAY_OPACITY), + // Transparent faces would not hide the edges behind them. + DisplayMode::HiddenLine => face_color[3] = 1.0, + DisplayMode::Shaded | DisplayMode::Wireframe | DisplayMode::Presentation => {} + } + let edge_width = if look.has_faces { + settings.edge_width + } else { + settings.edge_width + 1.0 + }; + Style { + face_color, + edge_color: look.edge_color, + highlight: look.highlight, + edge_width: edge_width + if look.emphasized { 0.5 } else { 0.0 }, + point_size: POINT_SIZE, + faces: self != DisplayMode::Wireframe, + edges, + points: true, + clipped: true, + background_fill: self == DisplayMode::HiddenLine, + hidden_edges: self == DisplayMode::HiddenLine && settings.hidden_edges, + edge_min_angle, + silhouettes, + surface: look.finish.surface(), + } + } +} + +/// What a frame is drawn on and lit with, by display mode. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Backdrop { + lighting: settings::Lighting, + /// Top and bottom of the background gradient, linear. + top: [f32; 4], + bottom: [f32; 4], + shadow: Option, +} + +/// What a scene part looks like before the display mode applies. +struct PartLook { + face_color: [f32; 4], + edge_color: [f32; 4], + /// Selection or hover tint. + highlight: [f32; 4], + has_faces: bool, + /// Selected or hovered: drawn with wider edges. + emphasized: bool, + /// The object's own edge visibility, when set in the Objects panel. + edges: Option, + finish: settings::Finish, +} + +/// Restricts which entity type a click may select. `Auto` preserves the +/// vertex-before-edge-before-face behavior used by earlier releases. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SelectionMode { + #[default] + Auto, + Object, + Face, + Edge, + Vertex, +} + +impl SelectionMode { + pub const ALL: [Self; 5] = [ + Self::Auto, + Self::Object, + Self::Face, + Self::Edge, + Self::Vertex, + ]; + + pub fn label(self) -> &'static str { + match self { + Self::Auto => "Auto", + Self::Object => "Object", + Self::Face => "Face", + Self::Edge => "Edge", + Self::Vertex => "Vertex", + } + } + + fn allows_faces(self) -> bool { + matches!(self, Self::Auto | Self::Object | Self::Face) + } + + fn allows_edges(self) -> bool { + matches!(self, Self::Auto | Self::Object | Self::Edge) + } + + fn allows_vertices(self) -> bool { + matches!(self, Self::Auto | Self::Object | Self::Vertex) + } + + fn accepts(self, entity: Option) -> bool { + match self { + Self::Auto | Self::Object => true, + Self::Face => matches!(entity, Some(crate::scene::TopologyEntity::Face(_))), + Self::Edge => matches!(entity, Some(crate::scene::TopologyEntity::Edge(_))), + Self::Vertex => matches!(entity, Some(crate::scene::TopologyEntity::Vertex(_))), + } + } + + fn entity( + self, + entity: Option, + ) -> Option { + (self != Self::Object).then_some(entity).flatten() + } +} + +/// Colors the view takes from the UI theme. +#[derive(Clone)] +pub struct ViewerColors { + pub selection: Color32, + pub hover: Color32, + pub overlay: Color32, + pub grid: Color32, + pub cube: CubeColors, + pub overlay_text: Color32, + pub overlay_background: Color32, +} + +/// What happened in the view this frame. +pub enum ViewerEvent { + /// A click selected `key` (or nothing); `extend` toggles instead of + /// replacing the selection. + Picked { + key: Option, + topology: Option, + extend: bool, + }, + /// The user double-clicked an object. + FocusRequested, + /// A screenshot or an animation was saved (with a message saying + /// where), or could not be. + Captured(Result), + /// A control in the view asks for this. + Command(Action), +} + +/// Per-frame inputs from the application. +pub struct ViewInput<'a> { + pub scene: &'a Scene, + pub settings: &'a settings::Viewer, + pub rendering: &'a settings::Rendering, + pub colors: &'a ViewerColors, + /// Shown as a status pill while the worker is busy. + pub busy: Option<&'a str>, + /// Shown in the middle of an empty view. + pub empty_hint: Option<&'a str>, + /// Parts meshed and parts in all, while a render's meshing takes long. + pub meshing: Option<(u32, u32)>, +} + +#[derive(Clone, Copy, PartialEq)] +enum DragMode { + Orbit, + Pan, + Zoom, +} + +impl DragMode { + fn cursor(self) -> egui::CursorIcon { + match self { + Self::Orbit | Self::Pan => egui::CursorIcon::Grabbing, + Self::Zoom => egui::CursorIcon::ResizeVertical, + } + } +} + +struct Drag { + mode: DragMode, + start: Pos2, + last: Pos2, + pivot: Option, +} + +impl Drag { + /// Returns only the motion since the previous frame. + fn advance(&mut self, current: Pos2) -> Vec2 { + let delta = current - self.last; + self.last = current; + delta + } +} + +pub struct Viewer { + pub camera: Camera, + pub display_mode: DisplayMode, + pub selection_mode: SelectionMode, + pub section: Section, + /// The exploded-view controls are shown. + pub explode_controls: bool, + /// The named views of the document, in the order they were saved. + pub named_views: Vec, + animation: Option, + renderer: Option, + nav_cube: NavigationCube, + drag: Option, + hovered: Option, + last_pointer: Option, + orbit_method: OrbitMethod, + aspect: f32, + /// Camera extent treated as 100% by the zoom controls. + zoom_reference_extent: f32, + capture: Option, + /// Size of the view in physical pixels, as last drawn. + view_px: [u32; 2], + /// Small parts are drawn simplified (large-model mode). + simplifying: bool, + axis_meshes: Option<(f32, [Arc; 3])>, + /// The dot marking the world origin where the axes start. + origin_mesh: Arc, + grid_mesh: Option<(GridKey, Arc)>, + /// The ground grid with its lines, ring by ring from the middle out. + ground: Option<(GroundGrid, Vec)>, + pick_index: picking::SceneIndex, +} + +/// The minor and the major lines of one fading ring of the ground grid. +type GroundRing = (Arc, Arc); + +#[derive(Clone, Copy, PartialEq)] +struct GridKey([f32; 10]); + +impl Default for Viewer { + fn default() -> Self { + Self { + camera: Camera::default(), + display_mode: DisplayMode::Shaded, + selection_mode: SelectionMode::Auto, + section: Section::default(), + explode_controls: false, + named_views: Vec::new(), + animation: None, + renderer: None, + nav_cube: NavigationCube::default(), + drag: None, + hovered: None, + last_pointer: None, + orbit_method: OrbitMethod::Turntable, + aspect: 1.5, + zoom_reference_extent: Camera::default().extent, + capture: None, + view_px: [1, 1], + simplifying: false, + axis_meshes: None, + origin_mesh: Arc::new(Mesh::new( + Vec::new(), + Vec::new(), + Vec::new(), + Vec::new(), + vec![[0.0; 3]], + )), + grid_mesh: None, + ground: None, + pick_index: picking::SceneIndex::default(), + } + } +} + +impl Viewer { + /// Frames everything visible. + pub fn fit(&mut self, scene: &Scene, animate: bool, now: f64) { + let pose = self.camera.fit_pose(scene.visible_bounds(), self.aspect); + self.zoom_reference_extent = pose.extent; + self.animate_to(pose, animate, now); + } + + /// Frames the selection, or everything when nothing is selected. + pub fn fit_selection(&mut self, scene: &Scene, animate: bool, now: f64) { + let bounds = scene.selection_bounds(); + if bounds.is_empty() { + self.fit(scene, animate, now); + } else { + let pose = self.camera.fit_pose(bounds, self.aspect); + self.zoom_reference_extent = pose.extent; + self.animate_to(pose, animate, now); + } + } + + pub fn set_standard_view(&mut self, view: StandardView, animate: bool, now: f64) { + let mut pose = self.settled_pose(); + pose.rotation = view.rotation(); + self.animate_to(pose, animate, now); + } + + /// Saves the next frame as a PNG image of the given size and kind, + /// unless a turntable is being exported (`false`). + pub fn request_image(&mut self, path: PathBuf, options: CaptureOptions) -> bool { + if self.turntable_progress().is_some() { + return false; + } + self.capture = Some(Capture::Image { + path: Some(path), + options, + }); + true + } + + /// Copies the next frame to the system clipboard as an image of the given + /// size and kind, unless a turntable is being exported (`false`). + pub fn request_clipboard_image(&mut self, options: CaptureOptions) -> bool { + if self.turntable_progress().is_some() { + return false; + } + self.capture = Some(Capture::Image { + path: None, + options, + }); + true + } + + /// Starts writing a turntable animation, one frame per frame of the + /// view, from where the camera is heading. + pub fn start_turntable( + &mut self, + path: PathBuf, + options: CaptureOptions, + turntable: TurntableOptions, + ) -> Result<(), String> { + self.cancel_turntable(); + let export = + TurntableExport::start(path, options, turntable, self.settled_pose(), self.view_px)?; + self.capture = Some(Capture::Turntable(Box::new(export))); + Ok(()) + } + + /// Stops a turntable export and removes what it wrote. + pub fn cancel_turntable(&mut self) { + if let Some(Capture::Turntable(export)) = self.capture.take() { + export.cancel(); + } + } + + /// Frames written and frames in all, while a turntable is exported. + pub fn turntable_progress(&self) -> Option<(u32, u32)> { + match &self.capture { + Some(Capture::Turntable(export)) => Some(export.progress()), + _ => None, + } + } + + /// The size of the view in physical pixels, as last drawn. + pub fn view_px(&self) -> [u32; 2] { + self.view_px + } + + /// Turns the section plane on, inside the model, or off. + pub fn toggle_section(&mut self, scene: &Scene) { + self.section.enabled = !self.section.enabled; + if self.section.enabled { + self.section.center_in(scene.visible_bounds()); + } + } + + /// Spreads the parts and shows the exploded-view controls, or closes + /// them and assembles the parts again. + pub fn toggle_explode(&mut self, scene: &mut Scene) { + self.explode_controls = !self.explode_controls; + scene.set_explode(if self.explode_controls { + DEFAULT_EXPLODE + } else { + 0.0 + }); + } + + /// The pose the camera is heading to (the current one when idle). + fn settled_pose(&self) -> camera::Pose { + self.animation + .as_ref() + .map_or_else(|| self.camera.pose(), Animation::target) + } + + fn animate_to(&mut self, pose: camera::Pose, animate: bool, now: f64) { + if animate { + self.animation = Some(Animation::new( + self.camera.pose(), + pose, + now, + ANIMATION_SECONDS, + )); + } else { + self.animation = None; + self.camera.set_pose(pose); + } + } + + pub fn ui( + &mut self, + ui: &mut egui::Ui, + frame: &eframe::Frame, + input: ViewInput<'_>, + ) -> Vec { + let rect = ui.available_rect_before_wrap(); + let response = ui.allocate_rect(rect, Sense::click_and_drag()); + let now = ui.input(|i| i.time); + self.aspect = (rect.width() / rect.height().max(1.0)).max(1e-3); + + self.apply_settings(input.settings); + let bounds = input.scene.visible_bounds(); + self.update_scene_extent(input.scene, bounds); + let zoom_controls = zoom_controls_rect(rect); + let mut row = 0; + let mut bar = |shown: bool, width: f32| { + let bar = shown.then(|| bottom_bar_rect(rect, row, width)).flatten(); + row += usize::from(bar.is_some()); + bar + }; + let section_controls = bar(self.section.enabled, SECTION_CONTROLS_WIDTH); + let explode_controls = bar(self.explode_controls, EXPLODE_CONTROLS_WIDTH); + let isolation_controls = bar(input.scene.is_isolating(), ISOLATION_CONTROLS_WIDTH); + let capture_controls = bar(self.turntable_progress().is_some(), CAPTURE_CONTROLS_WIDTH); + let meshing_controls = bar(input.meshing.is_some(), MESHING_CONTROLS_WIDTH); + let controls: Vec = [ + zoom_controls, + section_controls, + explode_controls, + isolation_controls, + capture_controls, + meshing_controls, + ] + .into_iter() + .flatten() + .collect(); + let mut events = self.handle_input(ui, &response, rect, &controls, &input, now); + + if let Some(animation) = &self.animation { + let (pose, done) = animation.sample(now); + self.camera.set_pose(pose); + if done { + self.animation = None; + } else { + ui.ctx().request_repaint(); + } + } + + self.update_ground(input.settings.ground_grid, bounds, rect); + self.update_scene_extent(input.scene, bounds); + + let painter = ui.painter_at(rect); + match frame.wgpu_render_state() { + Some(render_state) => { + let shown_triangles = input + .scene + .visible_nodes() + .iter() + .flat_map(|node| &node.parts) + .map(|part| part.mesh.triangle_count()) + .sum(); + self.simplifying = input.settings.large_models.active(shown_triangles); + let items = self.draw_items(&input, self.simplifying); + // Captures show every part in full, whatever its size here. + let full_items = (self.simplifying && self.capture.is_some()) + .then(|| self.draw_items(&input, false)); + let backdrop = self.backdrop(&input); + let renderer = self + .renderer + .get_or_insert_with(|| SceneRenderer::new(render_state)); + let ppp = ui.ctx().pixels_per_point(); + let size = [ + (rect.width() * ppp).round().max(1.0) as u32, + (rect.height() * ppp).round().max(1.0) as u32, + ]; + self.view_px = size; + let settings = input.settings; + let frame_input = FrameInput { + camera: &self.camera, + size, + background_top: backdrop.top, + background_bottom: backdrop.bottom, + items: &items, + section: self.section.renderer_plane(bounds), + pixel_scale: 1.0, + eye: self.camera.mono_eye(), + lighting: backdrop.lighting, + ground_shadow: backdrop.shadow, + }; + let stereo = (settings.projection == settings::Projection::Stereo) + .then_some(settings.stereo_mode); + let texture = { + let mut egui_renderer = render_state.renderer.write(); + match stereo { + Some(mode) => { + renderer.render_stereo(&mut egui_renderer, &frame_input, mode) + } + None => renderer.render(&mut egui_renderer, &frame_input), + } + }; + let mut render_pixels = |frame: &FrameInput<'_>| match stereo { + Some(mode) => renderer.render_stereo_pixels(frame, mode), + None => renderer.render_pixels(frame), + }; + painter.image( + texture, + rect, + Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)), + Color32::WHITE, + ); + let capture_frame = FrameInput { + items: full_items.as_deref().unwrap_or(&items), + ..frame_input + }; + match self.capture.take() { + Some(Capture::Image { path, options }) => { + let image = FrameInput { + size: options.image_size(size), + pixel_scale: options.pixel_scale(size), + ..capture_input(capture_frame, options.transparent) + }; + let captured = match (render_pixels(&image), path) { + (Some((size, pixels)), Some(path)) => { + capture::save_png(&path, size, pixels, options.transparent) + .map(|()| format!("Screenshot saved to {}", path.display())) + } + (Some((size, pixels)), None) => { + let color_image = capture::prepare_clipboard_image( + size, + pixels, + options.transparent, + ); + ui.ctx().copy_image(color_image); + Ok(format!( + "Screenshot copied to clipboard ({} × {} px)", + size[0], size[1] + )) + } + (None, _) => Err("the GPU did not return the image".to_owned()), + }; + events.push(ViewerEvent::Captured(captured)); + } + Some(Capture::Turntable(mut export)) => { + let mut camera = self.camera.clone(); + camera.set_pose(export.next_pose()); + let frame = FrameInput { + camera: &camera, + size: export.size(), + pixel_scale: export.pixel_scale(), + ..capture_input(capture_frame, export.transparent()) + }; + let written = render_pixels(&frame) + .ok_or_else(|| "the GPU did not return the image".to_owned()) + .and_then(|(_, pixels)| export.write_frame(pixels)); + match written { + Ok(false) => { + self.capture = Some(Capture::Turntable(export)); + ui.ctx().request_repaint(); + } + Ok(true) => events.push(ViewerEvent::Captured(export.finish())), + Err(error) => { + export.cancel(); + events.push(ViewerEvent::Captured(Err(error))); + } + } + } + None => {} + } + } + None => { + painter.rect_filled(rect, 0.0, Color32::from_gray(40)); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + "3D view unavailable: no GPU renderer", + egui::FontId::proportional(14.0), + Color32::LIGHT_GRAY, + ); + } + } + + self.paint_overlays(&painter, rect, &input); + if let Some(controls) = zoom_controls { + self.show_zoom_controls(ui, rect, controls); + } + if let Some(controls) = section_controls { + self.show_section_controls(ui, rect, controls, bounds); + } + if let Some(controls) = explode_controls { + show_explode_controls(ui, rect, controls, input.scene, &mut events); + } + if let Some(controls) = isolation_controls { + show_isolation_controls(ui, rect, controls, input.scene, &mut events); + } + if let (Some(controls), Some(progress)) = (capture_controls, self.turntable_progress()) { + show_capture_controls(ui, rect, controls, progress, &mut events); + } + if let (Some(controls), Some(progress)) = (meshing_controls, input.meshing) { + show_meshing_controls(ui, rect, controls, progress, &mut events); + } + events + } + + /// The lights, the background and the ground shadow of the display + /// mode: Presentation has its own. + fn backdrop(&self, input: &ViewInput<'_>) -> Backdrop { + if self.display_mode == DisplayMode::Presentation { + let presentation = &input.rendering.presentation; + return Backdrop { + lighting: presentation.lighting, + top: linear_rgba(presentation.background_top, 1.0), + bottom: linear_rgba(presentation.background_bottom, 1.0), + shadow: presentation.shadow.then_some(GroundShadow { + strength: presentation.shadow_strength, + softness: presentation.shadow_softness, + }), + }; + } + let settings = input.settings; + let top = linear_rgba(settings.background, 1.0); + let bottom = if settings.use_gradient { + linear_rgba(settings.background_aux, 1.0) + } else { + top + }; + Backdrop { + lighting: input.rendering.lighting, + top, + bottom, + shadow: None, + } + } + + fn apply_settings(&mut self, settings: &settings::Viewer) { + self.camera.projection = settings.projection; + if settings.orbit_method != self.orbit_method { + self.orbit_method = settings.orbit_method; + if self.orbit_method == OrbitMethod::Turntable { + self.camera.level(); + } + } + } + + /// The ground grid under what is shown (`bounds`). Its lines are rebuilt + /// only when the model changes or the view needs a larger floor. + fn update_ground(&mut self, shown: bool, bounds: Aabb, rect: Rect) { + if !shown { + self.ground = None; + return; + } + let grid = GroundGrid::under( + bounds, + &self.camera, + GVec2::new(rect.width(), rect.height()), + ); + match &mut self.ground { + Some((old, _)) if old.same_lines(&grid) => *old = grid, + _ => { + let bands = grid + .faded_meshes() + .into_iter() + .map(|(minor, major)| (Arc::new(minor), Arc::new(major))) + .collect(); + self.ground = Some((grid, bands)); + } + } + } + + /// Keeps the clipping planes around everything that can be drawn. + fn update_scene_extent(&mut self, scene: &Scene, bounds: Aabb) { + let mut radius = if bounds.is_empty() { + 10.0 + } else { + bounds.diagonal() * 0.5 + }; + let mut center = if bounds.is_empty() { + Vec3::ZERO + } else { + bounds.center() + }; + if scene.axes.iter().any(|a| a.visible) { + // The helpers run through the origin. + let half = self.camera.extent * 0.45; + radius = radius.max(half + center.length()); + center *= 0.5; + } + if let Some(grid) = &scene.overlay.grid { + radius = radius.max(grid.size * 1.5 + (grid.origin - center).length()); + } + if let Some((ground, _)) = &self.ground { + let reach = ground + .corners() + .iter() + .map(|corner| (*corner - center).length()) + .fold(0.0, f32::max); + radius = radius.max(reach); + } + self.camera.scene_center = center; + self.camera.scene_radius = radius.max(1e-3); + } + + fn handle_input( + &mut self, + ui: &egui::Ui, + response: &egui::Response, + rect: Rect, + controls: &[Rect], + input: &ViewInput<'_>, + now: f64, + ) -> Vec { + let mut events = Vec::new(); + let show_cube = input.settings.show_navigation_cube; + let pointer = response.hover_pos(); + let over_cube = |p: Pos2| show_cube && NavigationCube::contains(rect, p); + // The floating controls (zoom, section) take their own input. + let over_zoom_controls = |p: Pos2| controls.iter().any(|area| area.contains(p)); + + if show_cube { + let hover_pos = pointer.filter(|_| self.drag.is_none()); + if self.nav_cube.hover(rect, self.camera.rotation, hover_pos) { + ui.ctx().request_repaint(); + } + } else { + self.nav_cube.clear_hover(); + } + + // Dragging. + if response.drag_started() { + let start = ui + .input(|i| i.pointer.press_origin()) + .or(pointer) + .unwrap_or(rect.center()); + let (modifiers, primary, middle, secondary) = ui.input(|i| { + ( + i.modifiers, + i.pointer.button_down(egui::PointerButton::Primary), + i.pointer.button_down(egui::PointerButton::Middle), + i.pointer.button_down(egui::PointerButton::Secondary), + ) + }); + let mode = if over_zoom_controls(start) || over_cube(start) { + None + } else { + requested_drag_mode(modifiers, primary, middle, secondary) + }; + self.drag = None; + if let Some(mode) = mode { + self.start_drag(input.scene, rect, mode, start); + } + } + if response.dragged() + && let Some(current) = response.interact_pointer_pos() + && let Some(drag) = &mut self.drag + { + let (mode, start, previous, pivot) = (drag.mode, drag.start, drag.last, drag.pivot); + let delta = drag.advance(current); + match mode { + DragMode::Orbit => match self.orbit_method { + OrbitMethod::Turntable => self.camera.orbit_turntable_about( + GVec2::new(delta.x, delta.y), + pivot.unwrap_or(self.camera.target), + ), + OrbitMethod::Trackball => { + self.camera.orbit_trackball_about( + trackball_coords(rect, previous), + trackball_coords(rect, current), + pivot.unwrap_or(self.camera.target), + ); + } + }, + DragMode::Pan => self.camera.pan(GVec2::new(delta.x, delta.y), rect.height()), + DragMode::Zoom => { + let anchor = ndc(rect, start); + self.camera + .zoom(ZOOM_PER_DRAG_POINT.powf(delta.y), anchor, self.aspect); + } + } + } + if response.drag_stopped() { + self.drag = None; + } + + // Wheel and pinch zoom at the pointer. + if let Some(pos) = pointer.filter(|p| response.hovered() && !over_zoom_controls(*p)) { + let (scroll, pinch) = ui.input(|i| (i.smooth_scroll_delta.y, i.zoom_delta())); + let factor = ZOOM_PER_SCROLL_POINT.powf(scroll) / pinch; + if (factor - 1.0).abs() > 1e-6 { + self.settle_animation(); + self.camera.zoom(factor, ndc(rect, pos), self.aspect); + } + } + + // Clicks: the cube, then object selection. + if response.clicked() + && let Some(pos) = response.interact_pointer_pos() + && !over_zoom_controls(pos) + { + if over_cube(pos) { + if let Some(action) = self.nav_cube.click(rect, self.camera.rotation, pos) { + self.apply_nav_action(action, input.settings.animate, now); + } + } else { + let extend = ui.input(|i| i.modifiers.command); + let picked = self.pick(input.scene, rect, pos); + events.push(ViewerEvent::Picked { + key: picked.as_ref().map(|(key, _)| key.clone()), + topology: picked.and_then(|(_, topology)| topology), + extend, + }); + } + } + if response.double_clicked() + && pointer.is_some_and(|p| !over_cube(p) && !over_zoom_controls(p)) + { + events.push(ViewerEvent::FocusRequested); + } + + // Hover highlighting, recomputed only when the pointer moves. + let hover_pos = + pointer.filter(|p| self.drag.is_none() && !over_cube(*p) && !over_zoom_controls(*p)); + if hover_pos != self.last_pointer { + self.last_pointer = hover_pos; + let hovered = hover_pos + .and_then(|p| self.pick(input.scene, rect, p)) + .map(|(key, _)| key); + if hovered != self.hovered { + self.hovered = hovered; + ui.ctx().request_repaint(); + } + } + + // Give immediate feedback on mouse-down, before the movement is large + // enough for egui to classify it as a drag. Once dragging starts, keep + // the cursor even if the pointer leaves the viewport. + let cursor_mode = self.drag.as_ref().map(|drag| drag.mode).or_else(|| { + let (origin, modifiers, primary, middle, secondary) = ui.input(|i| { + ( + i.pointer.press_origin(), + i.modifiers, + i.pointer.button_down(egui::PointerButton::Primary), + i.pointer.button_down(egui::PointerButton::Middle), + i.pointer.button_down(egui::PointerButton::Secondary), + ) + }); + origin + .filter(|p| rect.contains(*p) && !over_cube(*p) && !over_zoom_controls(*p)) + .and_then(|_| requested_drag_mode(modifiers, primary, middle, secondary)) + }); + if let Some(mode) = cursor_mode { + ui.ctx().set_cursor_icon(mode.cursor()); + } + events + } + + fn apply_nav_action(&mut self, action: NavAction, animate: bool, now: f64) { + let mut pose = self.settled_pose(); + match action { + NavAction::LookFrom { eye_dir, up } => { + pose.rotation = camera::look_rotation(eye_dir, up) + } + NavAction::Roll(angle) => { + let forward = pose.rotation * Vec3::NEG_Z; + pose.rotation = + (glam::Quat::from_axis_angle(forward, angle) * pose.rotation).normalize(); + } + } + self.settle_animation(); + self.animate_to(pose, animate, now); + } + + /// Jumps to the end of a running animation, so user input starts from a + /// stable camera. + fn settle_animation(&mut self) { + if let Some(animation) = self.animation.take() { + self.camera.set_pose(animation.target()); + } + } + + fn zoom_percent(&self) -> f32 { + self.zoom_reference_extent / self.camera.extent * 100.0 + } + + /// Sets magnification relative to the last Fit framing. The center of the + /// view stays fixed; pointer-oriented zoom remains available on the wheel. + fn set_zoom_percent(&mut self, percent: f32) { + let percent = percent.clamp(MIN_ZOOM_PERCENT, MAX_ZOOM_PERCENT); + let desired_extent = self.zoom_reference_extent * 100.0 / percent; + self.camera.zoom( + desired_extent / self.camera.extent, + GVec2::ZERO, + self.aspect, + ); + } + + fn show_zoom_controls(&mut self, parent: &mut egui::Ui, view: Rect, controls: Rect) { + let mut requested_zoom = self + .zoom_percent() + .clamp(MIN_ZOOM_PERCENT, MAX_ZOOM_PERCENT); + let mut changed = false; + let mut controls_ui = parent.new_child( + egui::UiBuilder::new() + .max_rect(controls) + .layout(egui::Layout::left_to_right(egui::Align::Center)), + ); + controls_ui.set_clip_rect(view); + + egui::Frame::popup(parent.style()) + .corner_radius(6) + .inner_margin(egui::Margin::symmetric(6, 5)) + .show(&mut controls_ui, |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + let zoom_out = ui + .add_sized( + [28.0, 28.0], + egui::Button::new( + egui::RichText::new(icon::MAGNIFYING_GLASS_MINUS).size(17.0), + ), + ) + .on_hover_text("Zoom out"); + + let slider_width = + (ui.available_width() - 28.0 - 48.0 - 3.0 * ui.spacing().item_spacing.x) + .max(60.0); + let slider = ui + .add_sized( + [slider_width, 28.0], + egui::Slider::new(&mut requested_zoom, MIN_ZOOM_PERCENT..=MAX_ZOOM_PERCENT) + .logarithmic(true) + .show_value(false), + ) + .on_hover_text("Zoom level (100% = last Fit)"); + + let zoom_in = ui + .add_sized( + [28.0, 28.0], + egui::Button::new( + egui::RichText::new(icon::MAGNIFYING_GLASS_PLUS).size(17.0), + ), + ) + .on_hover_text("Zoom in"); + + if zoom_out.clicked() { + requested_zoom /= ZOOM_BUTTON_STEP; + changed = true; + } + if zoom_in.clicked() { + requested_zoom *= ZOOM_BUTTON_STEP; + changed = true; + } + changed |= slider.changed(); + ui.add_sized( + [48.0, 28.0], + egui::Label::new(format!("{requested_zoom:.0}%")), + ) + .on_hover_text("Magnification relative to the last Fit command"); + }); + + if changed { + self.settle_animation(); + self.set_zoom_percent(requested_zoom); + parent.ctx().request_repaint(); + } + } + + fn show_section_controls( + &mut self, + parent: &mut egui::Ui, + view: Rect, + controls: Rect, + bounds: Aabb, + ) { + let section = &mut self.section; + let before = section.clone(); + control_bar(parent, view, controls, |ui| { + ui.label(format!("{} Section", icon::SCISSORS)); + for axis in SectionAxis::ALL { + if ui + .selectable_label(section.axis == axis, axis.label()) + .on_hover_text(format!("Cut across the {} axis", axis.label())) + .clicked() + && section.axis != axis + { + section.axis = axis; + section.offset = f32::NAN; + section.center_in(bounds); + } + } + ui.toggle_value(&mut section.flipped, icon::ARROWS_DOWN_UP) + .on_hover_text("Keep the other side"); + let range = section.range(bounds); + ui.add_sized( + [(ui.available_width() - 90.0).max(60.0), 24.0], + egui::Slider::new(&mut section.offset, range) + .show_value(true) + .max_decimals(3) + .clamping(egui::SliderClamping::Never), + ) + .on_hover_text("Position of the plane along the axis"); + ui.checkbox(&mut section.caps, "Fill") + .on_hover_text("Fill the cut faces of solids"); + if ui + .small_button(icon::X) + .on_hover_text("Remove the section (View > Section View)") + .clicked() + { + section.enabled = false; + } + }); + if self.section != before { + parent.ctx().request_repaint(); + } + } + + fn pick( + &mut self, + scene: &Scene, + rect: Rect, + pos: Pos2, + ) -> Option<(NodeKey, Option)> { + if !scene.preview_parts.is_empty() { + return None; + } + self.pick_index.update(scene); + let candidate_indices = self.pick_index.query( + &self.camera, + self.aspect, + ndc(rect, pos), + GVec2::new(rect.width(), rect.height()), + self.selection_mode, + ); + let candidates = candidate_indices + .into_iter() + .filter_map(|index| self.pick_index.candidate(scene, index)); + picking::pick_clipped( + &self.camera, + self.aspect, + ndc(rect, pos), + GVec2::new(rect.width(), rect.height()), + self.selection_mode, + candidates, + self.section.clip_plane(), + ) + .map(|hit| { + let (node, part) = hit.id; + let topology = hit.entity.map(|entity| TopologySelection { + node: node.clone(), + part, + entity, + position: hit.position, + }); + (node, topology) + }) + } + + /// Starts a drag in `mode` from `start`. A camera transition still under + /// way ends first: an orbit then turns around what is under the pointer + /// in the view the drag moves, not in a frame of the transition. + fn start_drag(&mut self, scene: &Scene, rect: Rect, mode: DragMode, start: Pos2) { + self.settle_animation(); + let pivot = (mode == DragMode::Orbit).then(|| self.orbit_pivot(scene, rect, start)); + self.drag = Some(Drag { + mode, + start, + last: start, + pivot, + }); + } + + /// Choose the orbit point once per gesture. A hit stays under the cursor; + /// empty space keeps the current view centre, including after panning. + fn orbit_pivot(&mut self, scene: &Scene, rect: Rect, pos: Pos2) -> Vec3 { + if scene.preview_parts.is_empty() { + self.pick_index.update(scene); + let pointer = ndc(rect, pos); + let viewport = GVec2::new(rect.width(), rect.height()); + let candidates = self + .pick_index + .query( + &self.camera, + self.aspect, + pointer, + viewport, + SelectionMode::Object, + ) + .into_iter() + .filter_map(|index| self.pick_index.candidate(scene, index)); + if let Some(hit) = picking::pick_clipped( + &self.camera, + self.aspect, + pointer, + viewport, + SelectionMode::Object, + candidates, + self.section.clip_plane(), + ) { + return hit.position; + } + } + self.camera.target + } + + /// What to draw; `simplify` draws parts that are small on screen with + /// their simplified meshes (large-model mode), unless they are selected + /// or hovered. + fn draw_items(&mut self, input: &ViewInput<'_>, simplify: bool) -> Vec { + let (scene, settings, colors) = (input.scene, input.settings, input.colors); + let default_color = srgb_unit(settings.default_color); + let default_edge = linear_rgba(settings.edge_color, 1.0); + let presentation = &input.rendering.presentation; + let presenting = self.display_mode == DisplayMode::Presentation; + // The axes and the ground grid, which Presentation leaves out. + let helpers = !presenting || presentation.helpers; + let mut items = Vec::new(); + + // Selecting an assembly highlights all of its parts. + let mut highlighted = std::collections::HashSet::new(); + for key in &scene.selection { + if let Some(node) = scene.find(key) { + collect_keys(node, &mut highlighted); + } + } + + let topology_nodes: std::collections::HashSet<_> = scene + .topology_selections + .iter() + .map(|selection| selection.node.as_str()) + .collect(); + for node in scene + .visible_nodes() + .into_iter() + .filter(|_| scene.preview_parts.is_empty()) + { + let selected = + highlighted.contains(&node.key) && !topology_nodes.contains(node.key.as_str()); + let hovered = self.hovered.as_deref() == Some(node.key.as_str()); + // Presentation gives objects without a material its own, and + // that material's color to those without a color either. + let own_finish = node.overrides.finish.or(node.finish); + let (finish, fallback_color) = match own_finish { + None if presenting => ( + presentation.material, + presentation + .material + .natural_color() + .unwrap_or(default_color), + ), + _ => (node.finish(), default_color), + }; + for part in &node.parts { + let (rgb, alpha) = node.part_color(part, fallback_color); + let has_faces = !part.mesh.indices.is_empty(); + let highlight = if selected { + with_alpha(colors.selection, 0.6) + } else if hovered { + with_alpha(colors.hover, 0.25) + } else { + [0.0; 4] + }; + let edge_color = if selected { + linear_color(colors.selection, 1.0) + } else if !has_faces { + // Wires and points have no faces to carry the color. + rgb_to_linear(rgb, alpha) + } else { + node.edge_color + .map_or(default_edge, |c| rgb_to_linear(c, 1.0)) + }; + let look = PartLook { + face_color: rgb_to_linear(rgb, alpha), + edge_color, + highlight, + has_faces, + emphasized: selected || hovered, + edges: node.overrides.edges, + finish, + }; + let transform = scene.part_transform(part); + let mut mesh = if node.overrides.color.is_some() { + &part.mesh + } else { + part.render_mesh.as_ref().unwrap_or(&part.mesh) + }; + let mut style = self.display_mode.style(look, settings, input.rendering); + if simplify && !selected && !hovered && part.render_mesh.is_none() { + let bounds = part.mesh.bounds.transformed(transform); + let size = + culling::projected_size(&self.camera, self.view_px[1] as f32, bounds); + let detail = Detail::for_size(size); + if detail != Detail::Full + && let Some(simplified) = part.mesh.simplified() + { + mesh = simplified; + } + if detail == Detail::Faint { + // Specks: their edges would only add noise. + style.edges &= !has_faces; + style.points = false; + } + } + items.push(DrawItem { + mesh: mesh.clone(), + transform, + style, + layer: Layer::Scene, + }); + } + } + + for part in &scene.preview_parts { + let rgb = part.color.unwrap_or(default_color); + let alpha = part.alpha.unwrap_or(1.0); + let has_faces = !part.mesh.indices.is_empty(); + let look = PartLook { + face_color: rgb_to_linear(rgb, alpha), + edge_color: default_edge, + highlight: [0.0; 4], + has_faces, + emphasized: false, + edges: None, + finish: if presenting { + presentation.material + } else { + crate::settings::Finish::Default + }, + }; + items.push(DrawItem { + mesh: part.render_mesh.as_ref().unwrap_or(&part.mesh).clone(), + transform: part.transform, + style: self.display_mode.style(look, settings, input.rendering), + layer: Layer::Scene, + }); + } + + for (part, transform) in scene + .placed_topology_highlights() + .into_iter() + .filter(|_| scene.preview_parts.is_empty()) + { + let color = linear_color(colors.selection, 1.0); + items.push(DrawItem { + mesh: part.mesh.clone(), + transform, + style: Style { + face_color: linear_color(colors.selection, 0.55), + edge_color: color, + highlight: [0.0; 4], + edge_width: settings.edge_width + 2.0, + point_size: POINT_SIZE + 5.0, + faces: true, + edges: true, + points: true, + clipped: true, + background_fill: false, + hidden_edges: false, + edge_min_angle: 0.0, + silhouettes: false, + surface: [0.0; 4], + }, + layer: Layer::Overlay, + }); + } + + // Short positive origin axes give a consistent X/Y/Z reference at + // every zoom. Where the model hides them they are dashed, so that a + // part built around the origin never makes them disappear. + let half_length = self.camera.extent * 0.45; + if self + .axis_meshes + .as_ref() + .is_none_or(|(len, _)| *len != half_length) + { + let line = |dir: Vec3| { + Arc::new(Mesh::lines(vec![ + Vec3::ZERO.to_array(), + (dir * half_length).to_array(), + ])) + }; + let [x, y, z] = &scene.axes; + self.axis_meshes = Some(( + half_length, + [line(x.direction), line(y.direction), line(z.direction)], + )); + } + if let Some((_, meshes)) = &self.axis_meshes + && helpers + { + for (axis, mesh) in scene.axes.iter().zip(meshes) { + if axis.visible { + let mut item = line_item( + mesh.clone(), + rgb_to_linear(axis.color, 1.0), + 1.5, + Layer::Scene, + ); + item.style.hidden_edges = true; + items.push(item); + } + } + if scene.axes.iter().any(|axis| axis.visible) { + // A light dot in a dark ring, visible on any background. + for (color, size) in [(colors.cube.outline, 9.0), (colors.overlay_text, 6.0)] { + let mut item = line_item( + self.origin_mesh.clone(), + linear_color(color, 1.0), + 1.0, + Layer::Overlay, + ); + item.style.edges = false; + item.style.points = true; + item.style.point_size = size; + items.push(item); + } + } + } + + if let Some((ground, bands)) = &self.ground + && helpers + { + let color = |alpha| linear_color(colors.grid, alpha); + for ((minor, major), opacity) in bands.iter().zip(GRID_FADE) { + items.push(line_item( + minor.clone(), + color(0.35 * ground.minor_opacity * opacity), + 1.0, + Layer::Reference, + )); + items.push(line_item( + major.clone(), + color(0.7 * ground.major_opacity * opacity), + 1.0, + Layer::Reference, + )); + } + } + + if let Some(grid) = &scene.overlay.grid { + let key = grid_key(grid); + if self.grid_mesh.as_ref().is_none_or(|(k, _)| *k != key) { + self.grid_mesh = Some((key, Arc::new(grid_mesh(grid)))); + } + if let Some((_, mesh)) = &self.grid_mesh { + items.push(line_item( + mesh.clone(), + linear_color(colors.grid, 0.8), + 1.0, + Layer::Scene, + )); + } + } + + for mesh in &scene.overlay.meshes { + items.push(DrawItem { + mesh: mesh.clone(), + transform: GMat4::IDENTITY, + style: Style { + face_color: linear_color(colors.overlay, 0.55), + edge_color: linear_color(colors.overlay, 1.0), + highlight: [0.0; 4], + edge_width: 3.0, + point_size: POINT_SIZE + 3.0, + faces: true, + edges: true, + points: true, + clipped: false, + background_fill: false, + hidden_edges: false, + edge_min_angle: 0.0, + silhouettes: false, + surface: [0.0; 4], + }, + layer: Layer::Overlay, + }); + } + items + } + + fn paint_overlays(&self, painter: &egui::Painter, rect: Rect, input: &ViewInput<'_>) { + let colors = input.colors; + if input.settings.show_navigation_cube { + self.nav_cube + .paint(painter, rect, self.camera.rotation, &colors.cube); + } + if input.settings.show_axes_indicator { + overlays::paint_axes_indicator( + painter, + rect, + self.camera.rotation, + [ + Color32::from_rgb(230, 60, 60), + Color32::from_rgb(90, 200, 60), + Color32::from_rgb(70, 120, 240), + ], + colors.overlay_text, + ); + } + + if input.settings.projection == settings::Projection::Stereo + && input.settings.stereo_mode.shown() != input.settings.stereo_mode + { + painter.text( + Pos2::new(rect.center().x, rect.top() + 54.0), + egui::Align2::CENTER_TOP, + "Quad-buffered stereo cannot be shown here: showing a red-cyan anaglyph", + egui::FontId::proportional(12.0), + colors.overlay_text, + ); + } + + let mut bottom = rect.bottom() - 10.0; + let presenting = self.display_mode == DisplayMode::Presentation; + if input.settings.scale_bar && (!presenting || input.rendering.presentation.helpers) { + let units_per_point = ground::units_per_point(&self.camera, rect.height()); + let bar = ScaleBar::new(units_per_point, input.settings.units); + let mut label = bar.label.clone(); + if let Some((grid, _)) = &self.ground { + label += &format!( + " · grid {}", + ground::format_length(grid.minor, input.settings.units) + ); + } + let right = rect.right() - 14.0; + let y = bottom - 4.0; + let stroke = egui::Stroke::new(1.5, colors.overlay_text); + let left = right - bar.width; + painter.line_segment([Pos2::new(left, y), Pos2::new(right, y)], stroke); + for x in [left, right] { + painter.line_segment([Pos2::new(x, y - 5.0), Pos2::new(x, y)], stroke); + } + painter.text( + Pos2::new(right, y - 7.0), + egui::Align2::RIGHT_BOTTOM, + label, + egui::FontId::proportional(11.0), + colors.overlay_text, + ); + bottom = y - 24.0; + } + if self.simplifying { + painter.text( + Pos2::new(rect.right() - 10.0, bottom), + egui::Align2::RIGHT_BOTTOM, + "Large model: small parts simplified", + egui::FontId::proportional(11.0), + colors.overlay_text.gamma_multiply(0.7), + ); + } + + if let Some(text) = input.busy { + let galley = painter.layout_no_wrap( + text.to_owned(), + egui::FontId::proportional(13.0), + colors.overlay_text, + ); + let size = galley.size() + Vec2::new(44.0, 14.0); + let pill = Rect::from_center_size(Pos2::new(rect.center().x, rect.top() + 24.0), size); + painter.rect_filled(pill, size.y / 2.0, colors.overlay_background); + let spinner_center = Pos2::new(pill.left() + 18.0, pill.center().y); + paint_spinner( + painter, + spinner_center, + 6.0, + colors.overlay_text, + painter.ctx().input(|i| i.time), + ); + painter.galley( + Pos2::new(pill.left() + 32.0, pill.center().y - galley.size().y / 2.0), + galley, + colors.overlay_text, + ); + painter.ctx().request_repaint(); + } else if let Some(hint) = input.empty_hint.filter(|_| input.scene.is_empty()) { + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + hint, + egui::FontId::proportional(15.0), + colors.overlay_text.gamma_multiply(0.75), + ); + } + } +} + +fn requested_drag_mode( + modifiers: egui::Modifiers, + primary: bool, + middle: bool, + secondary: bool, +) -> Option { + if middle || (primary && (modifiers.ctrl || modifiers.command)) { + Some(DragMode::Pan) + } else if primary && modifiers.shift { + Some(DragMode::Zoom) + } else if primary || secondary { + Some(DragMode::Orbit) + } else { + None + } +} + +fn zoom_controls_rect(view: Rect) -> Option { + if view.width() < MIN_VIEW_WIDTH_FOR_ZOOM_CONTROLS + || view.height() < ZOOM_CONTROLS_HEIGHT + 2.0 * ZOOM_CONTROLS_MARGIN + { + return None; + } + let size = Vec2::new( + ZOOM_CONTROLS_WIDTH.min(view.width() - 2.0 * ZOOM_CONTROLS_MARGIN), + ZOOM_CONTROLS_HEIGHT, + ); + Some(Rect::from_min_size( + view.left_top() + Vec2::splat(ZOOM_CONTROLS_MARGIN), + size, + )) +} + +/// The `row`th control bar up from the bottom left of the view (section, +/// exploded view, isolation), unless the view is too small to hold it +/// below the zoom controls. +fn bottom_bar_rect(view: Rect, row: usize, width: f32) -> Option { + let rows = row as f32 + 1.0; + if view.width() < MIN_VIEW_WIDTH_FOR_ZOOM_CONTROLS + || view.height() < (rows + 1.0) * ZOOM_CONTROLS_HEIGHT + (rows + 2.0) * ZOOM_CONTROLS_MARGIN + { + return None; + } + let size = Vec2::new( + width.min(view.width() - 2.0 * ZOOM_CONTROLS_MARGIN), + ZOOM_CONTROLS_HEIGHT, + ); + Some(Rect::from_min_size( + Pos2::new( + view.left() + ZOOM_CONTROLS_MARGIN, + view.bottom() - rows * (ZOOM_CONTROLS_MARGIN + size.y), + ), + size, + )) +} + +/// A bar of controls floating over the view. +fn control_bar( + parent: &mut egui::Ui, + view: Rect, + rect: Rect, + add_contents: impl FnOnce(&mut egui::Ui), +) { + let mut bar = parent.new_child( + egui::UiBuilder::new() + .max_rect(rect) + .layout(egui::Layout::left_to_right(egui::Align::Center)), + ); + bar.set_clip_rect(view); + egui::Frame::popup(parent.style()) + .corner_radius(6) + .inner_margin(egui::Margin::symmetric(6, 5)) + .show(&mut bar, |ui| { + ui.spacing_mut().item_spacing.x = 4.0; + add_contents(ui); + }); +} + +fn show_explode_controls( + parent: &mut egui::Ui, + view: Rect, + rect: Rect, + scene: &Scene, + events: &mut Vec, +) { + control_bar(parent, view, rect, |ui| { + ui.label(format!("{} Explode", icon::ARROWS_OUT)); + let mut percent = scene.explode() * 100.0; + let slider = ui + .add_sized( + [(ui.available_width() - 30.0).max(60.0), 24.0], + egui::Slider::new(&mut percent, 0.0..=MAX_EXPLODE * 100.0) + .suffix("%") + .max_decimals(0), + ) + .on_hover_text("How far the parts move away from the centre of the model"); + if slider.changed() { + events.push(ViewerEvent::Command(Action::SetExplode(percent / 100.0))); + } + if ui + .small_button(icon::X) + .on_hover_text("Assemble the parts again (View > Exploded View)") + .clicked() + { + events.push(ViewerEvent::Command(Action::ToggleExplode)); + } + }); +} + +fn show_capture_controls( + parent: &mut egui::Ui, + view: Rect, + rect: Rect, + (written, frames): (u32, u32), + events: &mut Vec, +) { + control_bar(parent, view, rect, |ui| { + ui.label(format!("{} Turntable {written}/{frames}", icon::FILM_STRIP)); + ui.add( + egui::ProgressBar::new(written as f32 / frames.max(1) as f32) + .desired_width((ui.available_width() - 30.0).max(40.0)), + ); + if ui + .small_button(icon::X) + .on_hover_text("Stop and delete what was written") + .clicked() + { + events.push(ViewerEvent::Command(Action::CancelTurntable)); + } + }); +} + +fn show_meshing_controls( + parent: &mut egui::Ui, + view: Rect, + rect: Rect, + (done, total): (u32, u32), + events: &mut Vec, +) { + control_bar(parent, view, rect, |ui| { + ui.label(format!("{} Meshing {done}/{total}", icon::POLYGON)); + ui.add( + egui::ProgressBar::new(done as f32 / total.max(1) as f32) + .desired_width((ui.available_width() - 30.0).max(40.0)), + ); + if ui + .small_button(icon::X) + .on_hover_text("Stop meshing and keep the model shown now") + .clicked() + { + events.push(ViewerEvent::Command(Action::CancelMeshing)); + } + }); +} + +fn show_isolation_controls( + parent: &mut egui::Ui, + view: Rect, + rect: Rect, + scene: &Scene, + events: &mut Vec, +) { + control_bar(parent, view, rect, |ui| { + let count = scene.isolated_count(); + ui.label(format!( + "{} Isolated: {count} object{}", + icon::SELECTION_FOREGROUND, + if count == 1 { "" } else { "s" } + )); + if ui + .button("End") + .on_hover_text("Show the other objects again (View > End Isolation)") + .clicked() + { + events.push(ViewerEvent::Command(Action::ToggleIsolate)); + } + if ui + .button("Show All") + .on_hover_text("End the isolation and show the hidden objects too") + .clicked() + { + events.push(ViewerEvent::Command(Action::ShowAll)); + } + }); +} + +fn collect_keys<'a>( + node: &'a crate::scene::SceneNode, + out: &mut std::collections::HashSet<&'a NodeKey>, +) { + out.insert(&node.key); + for child in &node.children { + collect_keys(child, out); + } +} + +fn line_item(mesh: Arc, color: [f32; 4], width: f32, layer: Layer) -> DrawItem { + DrawItem { + mesh, + transform: GMat4::IDENTITY, + style: Style { + face_color: color, + edge_color: color, + highlight: [0.0; 4], + edge_width: width, + point_size: POINT_SIZE, + faces: false, + edges: true, + points: false, + clipped: false, + background_fill: false, + hidden_edges: false, + edge_min_angle: 0.0, + silhouettes: false, + surface: [0.0; 4], + }, + layer, + } +} + +fn grid_key(grid: &Grid) -> GridKey { + GridKey([ + grid.origin.x, + grid.origin.y, + grid.origin.z, + grid.x_dir.x, + grid.x_dir.y, + grid.x_dir.z, + grid.z_dir.x, + grid.z_dir.y, + grid.z_dir.z, + grid.size, + ]) +} + +/// A square grid on the plane, `size` wide on each side of the origin, +/// with 20 cells per side as in the original editor. +fn grid_mesh(grid: &Grid) -> Mesh { + let x = grid.x_dir.normalize_or(Vec3::X); + let y = grid.z_dir.normalize_or(Vec3::Z).cross(x); + let size = grid.size.max(1e-3); + let step = size / 20.0; + let mut segments = Vec::new(); + for i in -20..=20 { + let offset = i as f32 * step; + for (a, b) in [ + ( + grid.origin + x * offset - y * size, + grid.origin + x * offset + y * size, + ), + ( + grid.origin + y * offset - x * size, + grid.origin + y * offset + x * size, + ), + ] { + segments.push(a.to_array()); + segments.push(b.to_array()); + } + } + Mesh::lines(segments) +} + +/// Normalized device coordinates of `pos` within `rect` (y up). +fn ndc(rect: Rect, pos: Pos2) -> GVec2 { + GVec2::new( + (pos.x - rect.left()) / rect.width() * 2.0 - 1.0, + 1.0 - (pos.y - rect.top()) / rect.height() * 2.0, + ) +} + +fn trackball_coords(rect: Rect, pos: Pos2) -> GVec2 { + let half = rect.width().min(rect.height()) / 2.0; + let offset = pos - rect.center(); + GVec2::new(offset.x / half, -offset.y / half) +} + +fn paint_spinner(painter: &egui::Painter, center: Pos2, radius: f32, color: Color32, time: f64) { + let start = (time * 5.0) as f32; + let points: Vec = (0..=16) + .map(|i| { + let angle = start + i as f32 / 16.0 * std::f32::consts::PI * 1.4; + center + Vec2::angled(angle) * radius + }) + .collect(); + painter.add(egui::Shape::line(points, egui::Stroke::new(2.0, color))); +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_navigation.rs"] +mod tests; + +/// A capture to make with the next frame of the view. +enum Capture { + Image { + path: Option, + options: CaptureOptions, + }, + /// Written one frame per frame of the view. + Turntable(Box), +} + +/// The frame as captured: without the background when it is transparent +/// (premultiplied black, which `capture::save_png` straightens). +fn capture_input(frame: FrameInput<'_>, transparent: bool) -> FrameInput<'_> { + if transparent { + FrameInput { + background_top: [0.0; 4], + background_bottom: [0.0; 4], + ..frame + } + } else { + frame + } +} + +// -- colors ------------------------------------------------------------------ + +fn srgb_unit(color: [u8; 3]) -> [f32; 3] { + color.map(|c| f32::from(c) / 255.0) +} + +fn srgb_to_linear(c: f32) -> f32 { + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } +} + +fn rgb_to_linear(rgb: [f32; 3], alpha: f32) -> [f32; 4] { + [ + srgb_to_linear(rgb[0]), + srgb_to_linear(rgb[1]), + srgb_to_linear(rgb[2]), + alpha, + ] +} + +fn linear_rgba(color: [u8; 3], alpha: f32) -> [f32; 4] { + rgb_to_linear(srgb_unit(color), alpha) +} + +fn linear_color(color: Color32, alpha: f32) -> [f32; 4] { + linear_rgba([color.r(), color.g(), color.b()], alpha) +} + +/// Highlight tint: linear RGB with the mix factor in alpha. +fn with_alpha(color: Color32, amount: f32) -> [f32; 4] { + let [r, g, b, _] = linear_color(color, 1.0); + [r, g, b, amount] +} diff --git a/src/viewer/overlays.rs b/src/viewer/overlays.rs new file mode 100644 index 000000000..d30153ec3 --- /dev/null +++ b/src/viewer/overlays.rs @@ -0,0 +1,481 @@ +//! 2D overlays of the 3D view: the navigation cube with its roll arrows and +//! the axes indicator. +//! +//! The navigation cube is a chamfered cube in the top-right corner that +//! always shows the camera orientation. Its 6 faces, 12 edges and 8 corners +//! are clickable and turn the camera to look from that direction; the two +//! curved arrows above it roll the view by 45 degrees. + +use std::f32::consts::FRAC_PI_4; +use std::sync::OnceLock; + +use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, Vec2, epaint::TextShape}; +use glam::{Quat, Vec3}; + +/// Distance of the cube center from the view's top-right corner (points). +const CORNER_OFFSET: f32 = 85.0; +/// Half the cube's edge length (points). +const CUBE_HALF_SIZE: f32 = 29.0; +/// Half size of the face squares relative to the cube; the rest is chamfer. +const FACE_INSET: f32 = 0.68; +const ARROW_INNER_RADIUS: f32 = 56.0; +const ARROW_OUTER_RADIUS: f32 = 66.0; +/// Angles (degrees from the screen's x axis) where an arrow's tail starts +/// and where its head begins. +const ARROW_TAIL_ANGLE: f32 = 76.0; +const ARROW_HEAD_ANGLE: f32 = 52.0; +const ARROW_TIP_SWEEP: f32 = 13.0; +const ARROW_HEAD_OVERHANG: f32 = 5.0; +const ARC_SEGMENTS: usize = 12; + +const AXES_LENGTH: f32 = 34.0; +const AXES_MARGIN: f32 = 52.0; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum FacetKind { + Face, + Edge, + Corner, +} + +struct Facet { + normal: Vec3, + vertices: Vec, + kind: FacetKind, + /// Text and its reading direction, for the six faces. + label: Option<(&'static str, Vec3)>, +} + +fn facets() -> &'static [Facet] { + static FACETS: OnceLock> = OnceLock::new(); + FACETS.get_or_init(build_facets) +} + +fn build_facets() -> Vec { + let a = FACE_INSET; + let axis = |i: usize| Vec3::AXES[i]; + let mut facets = Vec::new(); + + for (normal, label, reading) in [ + (Vec3::Z, "TOP", Vec3::X), + (Vec3::NEG_Z, "BOTTOM", Vec3::X), + (Vec3::NEG_Y, "FRONT", Vec3::X), + (Vec3::Y, "BACK", Vec3::NEG_X), + (Vec3::X, "RIGHT", Vec3::Y), + (Vec3::NEG_X, "LEFT", Vec3::NEG_Y), + ] { + let (u, v) = (reading, normal.cross(reading)); + facets.push(Facet { + normal, + vertices: vec![ + normal + (-u - v) * a, + normal + (u - v) * a, + normal + (u + v) * a, + normal + (-u + v) * a, + ], + kind: FacetKind::Face, + label: Some((label, reading)), + }); + } + + for i in 0..3 { + for j in (i + 1)..3 { + let k = 3 - i - j; + for si in [-1.0f32, 1.0] { + for sj in [-1.0f32, 1.0] { + let (ei, ej, ek) = (axis(i) * si, axis(j) * sj, axis(k)); + facets.push(Facet { + normal: (ei + ej).normalize(), + vertices: vec![ + ei + ej * a - ek * a, + ei + ej * a + ek * a, + ei * a + ej + ek * a, + ei * a + ej - ek * a, + ], + kind: FacetKind::Edge, + label: None, + }); + } + } + } + } + + for sx in [-1.0f32, 1.0] { + for sy in [-1.0f32, 1.0] { + for sz in [-1.0f32, 1.0] { + let (x, y, z) = (Vec3::X * sx, Vec3::Y * sy, Vec3::Z * sz); + facets.push(Facet { + normal: Vec3::new(sx, sy, sz).normalize(), + vertices: vec![x + (y + z) * a, y + (x + z) * a, z + (x + y) * a], + kind: FacetKind::Corner, + label: None, + }); + } + } + } + facets +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Hover { + Facet(usize), + /// +1: counter-clockwise (left arrow), -1: clockwise (right arrow). + Roll(f32), +} + +/// What a click on the navigation cube asks for. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NavAction { + /// Look from `eye_dir` (pointing from the target to the eye). + LookFrom { + eye_dir: Vec3, + up: Vec3, + }, + Roll(f32), +} + +#[derive(Default)] +pub struct NavigationCube { + hover: Option, +} + +#[derive(Clone)] +pub struct CubeColors { + pub face: Color32, + pub chamfer: Color32, + pub outline: Color32, + pub text: Color32, + pub highlight: Color32, +} + +impl NavigationCube { + fn center(view: Rect) -> Pos2 { + Pos2::new(view.right() - CORNER_OFFSET, view.top() + CORNER_OFFSET) + } + + /// Whether `pos` is over the cube or its arrows (so the view should not + /// orbit or select there). + pub fn contains(view: Rect, pos: Pos2) -> bool { + Self::center(view).distance(pos) <= ARROW_OUTER_RADIUS + ARROW_HEAD_OVERHANG + 4.0 + } + + pub fn clear_hover(&mut self) { + self.hover = None; + } + + /// Updates hover state from the pointer; returns whether it changed. + pub fn hover(&mut self, view: Rect, rotation: Quat, pointer: Option) -> bool { + let hover = pointer.and_then(|p| self.hit(view, rotation, p)); + let changed = hover != self.hover; + self.hover = hover; + changed + } + + /// The action for a click at `pos`, given the current camera. + pub fn click(&self, view: Rect, rotation: Quat, pos: Pos2) -> Option { + match self.hit(view, rotation, pos)? { + Hover::Roll(sense) => Some(NavAction::Roll(sense * FRAC_PI_4)), + Hover::Facet(index) => { + let eye_dir = facets()[index].normal; + Some(NavAction::LookFrom { + eye_dir, + up: up_for(eye_dir, rotation), + }) + } + } + } + + fn hit(&self, view: Rect, rotation: Quat, pos: Pos2) -> Option { + let center = Self::center(view); + let offset = pos - center; + let radius = offset.length(); + if (ARROW_INNER_RADIUS - ARROW_HEAD_OVERHANG..=ARROW_OUTER_RADIUS + ARROW_HEAD_OVERHANG) + .contains(&radius) + { + let angle = (-offset.y).atan2(offset.x).to_degrees(); + let (low, high) = (ARROW_HEAD_ANGLE - ARROW_TIP_SWEEP, ARROW_TAIL_ANGLE); + if (low..=high).contains(&angle) { + return Some(Hover::Roll(-1.0)); + } + if (180.0 - high..=180.0 - low).contains(&angle) { + return Some(Hover::Roll(1.0)); + } + } + + let inverse = rotation.inverse(); + for (index, facet) in facets().iter().enumerate() { + if (inverse * facet.normal).z <= 1e-3 { + continue; + } + let polygon: Vec = facet + .vertices + .iter() + .map(|v| project(center, inverse, *v)) + .collect(); + if point_in_convex_polygon(pos, &polygon) { + return Some(Hover::Facet(index)); + } + } + None + } + + pub fn paint(&self, painter: &Painter, view: Rect, rotation: Quat, colors: &CubeColors) { + let center = Self::center(view); + let inverse = rotation.inverse(); + + for (index, facet) in facets().iter().enumerate() { + let facing = (inverse * facet.normal).z; + if facing <= 1e-3 { + continue; + } + let mut polygon: Vec = facet + .vertices + .iter() + .map(|v| project(center, inverse, *v)) + .collect(); + make_clockwise(&mut polygon); + + let base = if self.hover == Some(Hover::Facet(index)) { + colors.highlight + } else if facet.kind == FacetKind::Face { + colors.face + } else { + colors.chamfer + }; + let fill = shade(base, 0.62 + 0.38 * facing); + painter.add(Shape::convex_polygon( + polygon, + fill, + Stroke::new(1.0, colors.outline), + )); + + if let Some((text, reading)) = facet.label + && facing > 0.3 + { + let alpha = ((facing - 0.3) / 0.25).clamp(0.0, 1.0); + let face_center = project(center, inverse, facet.normal); + let along = project(center, inverse, facet.normal + reading) - face_center; + paint_rotated_text( + painter, + face_center, + along.y.atan2(along.x), + text, + // Labels shrink with the face's foreshortening. + CUBE_HALF_SIZE * 0.31 * (0.7 + 0.3 * facing), + colors.text.gamma_multiply(alpha), + ); + } + } + + for sense in [1.0f32, -1.0] { + let color = if self.hover == Some(Hover::Roll(sense)) { + colors.highlight + } else { + colors.chamfer + }; + paint_arrow( + painter, + &arrow_outline(center, sense), + color, + colors.outline, + ); + } + } +} + +/// Up vector when jumping to `eye_dir`: world Z, except when looking along +/// Z, where the current screen orientation is kept, snapped to an axis. +fn up_for(eye_dir: Vec3, rotation: Quat) -> Vec3 { + if eye_dir.z.abs() < 0.99 { + return Vec3::Z; + } + let (up, forward) = (rotation * Vec3::Y, rotation * Vec3::NEG_Z); + let mut candidate = Vec3::new(up.x, up.y, 0.0); + if candidate.length_squared() < 0.05 { + // Coming from a side view: tilting towards the top keeps the former + // forward direction at the top of the screen, and the opposite for + // the bottom. + let flat_forward = Vec3::new(forward.x, forward.y, 0.0); + candidate = if eye_dir.z > 0.0 { + flat_forward + } else { + -flat_forward + }; + } + let standard = if eye_dir.z > 0.0 { + Vec3::Y + } else { + Vec3::NEG_Y + }; + if candidate.length_squared() < 1e-6 { + return standard; + } + // From a corner view both axes are equally close; the standard + // orientation is the least surprising choice. + if (candidate.x.abs() - candidate.y.abs()).abs() < 1e-3 * candidate.length() { + return standard; + } + if candidate.x.abs() > candidate.y.abs() { + Vec3::X * candidate.x.signum() + } else { + Vec3::Y * candidate.y.signum() + } +} + +fn project(center: Pos2, inverse_rotation: Quat, point: Vec3) -> Pos2 { + let v = inverse_rotation * point; + Pos2::new( + center.x + v.x * CUBE_HALF_SIZE, + center.y - v.y * CUBE_HALF_SIZE, + ) +} + +fn shade(color: Color32, factor: f32) -> Color32 { + let f = |c: u8| (f32::from(c) * factor).round().clamp(0.0, 255.0) as u8; + Color32::from_rgba_unmultiplied(f(color.r()), f(color.g()), f(color.b()), color.a()) +} + +/// egui anti-aliases convex polygons correctly only in clockwise order. +fn make_clockwise(points: &mut [Pos2]) { + let area: f32 = points + .iter() + .zip(points.iter().cycle().skip(1)) + .map(|(a, b)| a.x * b.y - b.x * a.y) + .sum(); + // Screen y points down, so a positive shoelace sum is clockwise. + if area < 0.0 { + points.reverse(); + } +} + +fn point_in_convex_polygon(p: Pos2, polygon: &[Pos2]) -> bool { + let mut sign = 0.0f32; + for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)) { + let cross = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x); + if cross.abs() < 1e-6 { + continue; + } + if sign == 0.0 { + sign = cross.signum(); + } else if cross.signum() != sign { + return false; + } + } + sign != 0.0 +} + +/// Outline of a curved arrow; `sense` +1 is the left one. +fn arrow_outline(center: Pos2, sense: f32) -> Vec { + let polar = |radius: f32, angle: f32| { + let angle = if sense > 0.0 { 180.0 - angle } else { angle }.to_radians(); + Pos2::new( + center.x + radius * angle.cos(), + center.y - radius * angle.sin(), + ) + }; + let mid = (ARROW_INNER_RADIUS + ARROW_OUTER_RADIUS) / 2.0; + let mut points = Vec::new(); + for i in 0..=ARC_SEGMENTS { + let t = i as f32 / ARC_SEGMENTS as f32; + points.push(polar( + ARROW_OUTER_RADIUS, + ARROW_TAIL_ANGLE + (ARROW_HEAD_ANGLE - ARROW_TAIL_ANGLE) * t, + )); + } + points.push(polar( + ARROW_OUTER_RADIUS + ARROW_HEAD_OVERHANG, + ARROW_HEAD_ANGLE, + )); + points.push(polar(mid, ARROW_HEAD_ANGLE - ARROW_TIP_SWEEP)); + points.push(polar( + ARROW_INNER_RADIUS - ARROW_HEAD_OVERHANG, + ARROW_HEAD_ANGLE, + )); + for i in 0..=ARC_SEGMENTS { + let t = i as f32 / ARC_SEGMENTS as f32; + points.push(polar( + ARROW_INNER_RADIUS, + ARROW_HEAD_ANGLE + (ARROW_TAIL_ANGLE - ARROW_HEAD_ANGLE) * t, + )); + } + points +} + +/// Fills the (concave) arrow from convex pieces: one quad per arc segment +/// between the outer and inner arcs, plus the head triangle. +fn paint_arrow(painter: &Painter, outline: &[Pos2], fill: Color32, stroke: Color32) { + // Layout of `arrow_outline`: outer arc, three head points, inner arc + // running backwards. + let n = ARC_SEGMENTS + 1; + let outer = &outline[..n]; + let head = &outline[n..n + 3]; + let inner: Vec = outline[n + 3..].iter().rev().copied().collect(); + for i in 0..ARC_SEGMENTS { + let mut quad = vec![outer[i], outer[i + 1], inner[i + 1], inner[i]]; + make_clockwise(&mut quad); + painter.add(Shape::convex_polygon(quad, fill, Stroke::NONE)); + } + let mut tip = head.to_vec(); + make_clockwise(&mut tip); + painter.add(Shape::convex_polygon(tip, fill, Stroke::NONE)); + painter.add(Shape::closed_line( + outline.to_vec(), + Stroke::new(1.0, stroke), + )); +} + +fn paint_rotated_text( + painter: &Painter, + center: Pos2, + angle: f32, + text: &str, + size: f32, + color: Color32, +) { + let galley = painter.layout_no_wrap(text.to_owned(), egui::FontId::proportional(size), color); + let half = galley.size() / 2.0; + let (sin, cos) = angle.sin_cos(); + // The text pivots around its top-left corner. + let offset = Vec2::new(half.x * cos - half.y * sin, half.x * sin + half.y * cos); + painter.add(TextShape::new(center - offset, galley, color).with_angle(angle)); +} + +/// Paints the X/Y/Z indicator in the bottom-right corner. +pub fn paint_axes_indicator( + painter: &Painter, + view: Rect, + rotation: Quat, + colors: [Color32; 3], + text: Color32, +) { + let origin = Pos2::new(view.right() - AXES_MARGIN, view.bottom() - AXES_MARGIN); + let inverse = rotation.inverse(); + let mut axes: Vec<(f32, Vec3, &str, Color32)> = + [("X", Vec3::X), ("Y", Vec3::Y), ("Z", Vec3::Z)] + .into_iter() + .zip(colors) + .map(|((name, axis), color)| { + let v = inverse * axis; + (v.z, v, name, color) + }) + .collect(); + // Farthest first, so nearer axes are drawn over them. + axes.sort_by(|a, b| a.0.total_cmp(&b.0)); + for (_, v, name, color) in axes { + let tip = origin + Vec2::new(v.x, -v.y) * AXES_LENGTH; + painter.line_segment([origin, tip], Stroke::new(2.0, color)); + painter.circle_filled(tip, 2.5, color); + let label_pos = origin + Vec2::new(v.x, -v.y) * (AXES_LENGTH + 10.0); + painter.text( + label_pos, + egui::Align2::CENTER_CENTER, + name, + egui::FontId::proportional(11.0), + text, + ); + } +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_overlays.rs"] +mod tests; diff --git a/src/viewer/picking.rs b/src/viewer/picking.rs new file mode 100644 index 000000000..add4592ab --- /dev/null +++ b/src/viewer/picking.rs @@ -0,0 +1,445 @@ +//! Finding the object under the mouse pointer. +//! +//! Faces are hit-tested exactly with a ray. Topological edges and vertices +//! are matched in screen space within a few pixels, since a ray would +//! practically never touch them. A front face occludes entities behind it. + +use glam::{Mat4, Vec2, Vec3}; + +use super::SelectionMode; +use super::camera::{Camera, project_with}; +use super::section::ClipPlane; +use crate::scene::{Aabb, Mesh, NodeKey, Scene, TopologyEntity}; +use crate::spatial::{BoundsBvh, QueryStats}; + +/// How close to an edge or point the pointer must be, in pixels. +const PICK_TOLERANCE_PX: f32 = 6.0; +/// NDC depth allowance for an edge or vertex lying on the hit face. +const OCCLUSION_EPSILON: f32 = 1e-3; + +#[derive(Debug)] +struct ScenePart { + path: Vec, + part: usize, + key: NodeKey, + world_bounds: Aabb, +} + +/// World-space broad phase for all visible scene parts. The viewer retains +/// this index across pointer moves and rebuilds it only when the scene's +/// geometry, placement or visibility revision changes. +#[derive(Debug, Default)] +pub(crate) struct SceneIndex { + revision: Option, + parts: Vec, + bvh: BoundsBvh, + rebuilds: u64, +} + +impl SceneIndex { + pub(crate) fn update(&mut self, scene: &Scene) -> bool { + let revision = scene.pick_revision(); + if self.revision == Some(revision) { + return false; + } + + self.parts.clear(); + for (path, node) in scene.shown_nodes() { + for (part, geometry) in node.parts.iter().enumerate() { + if !geometry.mesh.bounds.is_empty() { + self.parts.push(ScenePart { + path: path.clone(), + part, + key: node.key.clone(), + world_bounds: geometry + .mesh + .bounds + .transformed(scene.part_transform(geometry)), + }); + } + } + } + self.bvh = BoundsBvh::build( + self.parts + .iter() + .map(|entry| (entry.world_bounds.min, entry.world_bounds.max)), + ); + self.revision = Some(revision); + self.rebuilds += 1; + true + } + + pub(crate) fn query( + &self, + camera: &Camera, + aspect: f32, + pointer_ndc: Vec2, + viewport_px: Vec2, + mode: SelectionMode, + ) -> Vec { + self.query_with_stats(camera, aspect, pointer_ndc, viewport_px, mode) + .0 + } + + fn query_with_stats( + &self, + camera: &Camera, + aspect: f32, + pointer_ndc: Vec2, + viewport_px: Vec2, + mode: SelectionMode, + ) -> (Vec, QueryStats) { + let (origin, direction) = camera.ray(pointer_ndc, aspect); + let view_projection = camera.view_projection(aspect); + let pointer_px = ndc_to_px(pointer_ndc, viewport_px); + let screen_pick = mode.allows_edges() || mode.allows_vertices(); + let mut candidates = Vec::new(); + let stats = self.bvh.query_with_stats( + |min, max| { + ray_hits_box(origin, direction, min, max) + || (screen_pick + && projected_bounds_hit( + view_projection, + viewport_px, + pointer_px, + Mat4::IDENTITY, + min, + max, + )) + }, + &mut candidates, + ); + (candidates, stats) + } + + pub(crate) fn candidate<'a>( + &self, + scene: &'a Scene, + index: usize, + ) -> Option> { + let entry = self.parts.get(index)?; + // Guards against a tree changed without a new pick revision: a + // missed pick is better than reporting another node's part. + let node = node_at_path(&scene.nodes, &entry.path).filter(|node| node.key == entry.key)?; + let part = node.parts.get(entry.part)?; + Some(Candidate { + id: (entry.key.clone(), entry.part), + mesh: &part.mesh, + transform: scene.part_transform(part), + }) + } + + #[cfg(test)] + fn rebuild_count(&self) -> u64 { + self.rebuilds + } +} + +fn node_at_path<'a>( + mut nodes: &'a [crate::scene::SceneNode], + path: &[usize], +) -> Option<&'a crate::scene::SceneNode> { + let mut result = None; + for &index in path { + let node = nodes.get(index)?; + result = Some(node); + nodes = &node.children; + } + result +} + +/// Something to test against, tagged with a caller-defined id. +pub struct Candidate<'a, T> { + pub id: T, + pub mesh: &'a Mesh, + pub transform: Mat4, +} + +/// Exact result of a view pick. `entity` is absent only for legacy meshes +/// without worker-supplied topology metadata. +#[derive(Clone, Debug, PartialEq)] +pub struct Hit { + pub id: T, + pub entity: Option, + pub position: Vec3, +} + +struct RankedHit { + hit: Hit, + depth: f32, + screen_distance: f32, + priority: u8, + surface: bool, +} + +/// Picks the candidate closest to the viewer under `pointer_ndc` +/// (normalized device coordinates; `viewport_px` converts to pixels). +#[cfg(test)] +pub fn pick<'a, T: Clone>( + camera: &Camera, + aspect: f32, + pointer_ndc: Vec2, + viewport_px: Vec2, + mode: SelectionMode, + candidates: impl IntoIterator>, +) -> Option> { + pick_clipped( + camera, + aspect, + pointer_ndc, + viewport_px, + mode, + candidates, + None, + ) +} + +/// [`pick`] when a section plane removes part of the model: what it +/// removes can neither be picked nor hide what lies behind it. +pub fn pick_clipped<'a, T: Clone>( + camera: &Camera, + aspect: f32, + pointer_ndc: Vec2, + viewport_px: Vec2, + mode: SelectionMode, + candidates: impl IntoIterator>, + clip: Option, +) -> Option> { + let (origin, dir) = camera.ray(pointer_ndc, aspect); + // In world ray parameters, which local rays share (affine transforms). + let kept = match clip { + Some(plane) => match plane.kept_range(origin, dir) { + Some((start, end)) => (start.max(0.0), end), + None => (f32::INFINITY, f32::NEG_INFINITY), + }, + None => (0.0, f32::INFINITY), + }; + let removed = |point: Vec3| clip.is_some_and(|plane| plane.removes(point)); + // Computed once: projecting thousands of points per pick dominates the + // cost when every projection rebuilds the camera matrices. + let view_projection = camera.view_projection(aspect); + let pointer_px = ndc_to_px(pointer_ndc, viewport_px); + + let mut hits = Vec::new(); + let mut front_surface: Option = None; + + for candidate in candidates { + let mesh = candidate.mesh; + if mesh.bounds.is_empty() { + continue; + } + let inverse = candidate.transform.inverse(); + let local_origin = inverse.transform_point3(origin); + let local_dir = inverse.transform_vector3(dir); + + if ray_hits_box(local_origin, local_dir, mesh.bounds.min, mesh.bounds.max) { + let topology_faces = !mesh.topology.triangle_faces.is_empty(); + if let Some((distance, triangle)) = + mesh.nearest_triangle_within(local_origin, local_dir, kept) + { + let local_position = local_origin + local_dir * distance; + let position = candidate.transform.transform_point3(local_position); + if let Some(depth) = projected_depth(view_projection, position) { + front_surface = Some(front_surface.map_or(depth, |front| front.min(depth))); + let entity = topology_faces + .then(|| mesh.topology.triangle_faces.get(triangle).copied()) + .flatten() + .map(TopologyEntity::Face); + if mode.allows_faces() && mode.accepts(entity) { + hits.push(RankedHit { + hit: Hit { + id: candidate.id.clone(), + entity: mode.entity(entity), + position, + }, + depth, + screen_distance: 0.0, + priority: 2, + surface: true, + }); + } + } + } + } + + let screen = |p: &[f32; 3]| { + let world = candidate.transform.transform_point3(Vec3::from_array(*p)); + project_with(view_projection, world) + .map(|ndc| (ndc_to_px(ndc.truncate(), viewport_px), world, ndc.z)) + }; + let mut primitive_candidates = Vec::new(); + if mode.allows_edges() { + mesh.edge_bvh().query( + |min, max| { + projected_bounds_hit( + view_projection, + viewport_px, + pointer_px, + candidate.transform, + min, + max, + ) + }, + &mut primitive_candidates, + ); + } + for segment_index in primitive_candidates.drain(..) { + let Some(segment) = mesh.edges.as_chunks::<2>().0.get(segment_index) else { + continue; + }; + let (Some((a, wa, _)), Some((b, wb, _))) = (screen(&segment[0]), screen(&segment[1])) + else { + continue; + }; + let (distance, t) = distance_to_segment(pointer_px, a, b); + if distance <= PICK_TOLERANCE_PX && !removed(wa.lerp(wb, t)) { + let position = wa.lerp(wb, t); + if let Some(depth) = projected_depth(view_projection, position) { + let entity = mesh + .topology + .segment_edges + .get(segment_index) + .copied() + .map(TopologyEntity::Edge); + if mode.accepts(entity) { + hits.push(RankedHit { + hit: Hit { + id: candidate.id.clone(), + entity: mode.entity(entity), + position, + }, + depth, + screen_distance: distance, + priority: 1, + surface: false, + }); + } + } + } + } + let topology_vertices = !mesh.topology.vertices.is_empty(); + let vertices = mesh.pick_vertices(); + if mode.allows_vertices() { + mesh.vertex_bvh().query( + |min, max| { + projected_bounds_hit( + view_projection, + viewport_px, + pointer_px, + candidate.transform, + min, + max, + ) + }, + &mut primitive_candidates, + ); + } + for index in primitive_candidates.drain(..) { + let Some(point) = vertices.get(index) else { + continue; + }; + if let Some((screen_pos, position, depth)) = screen(point) + && let distance = screen_pos.distance(pointer_px) + && distance <= PICK_TOLERANCE_PX + && !removed(position) + { + let entity = topology_vertices.then_some(TopologyEntity::Vertex(index as u32 + 1)); + if mode.accepts(entity) { + hits.push(RankedHit { + hit: Hit { + id: candidate.id.clone(), + entity: mode.entity(entity), + position, + }, + depth, + screen_distance: distance, + priority: 0, + surface: false, + }); + } + } + } + } + + hits.into_iter() + .filter(|hit| { + hit.surface || front_surface.is_none_or(|depth| hit.depth <= depth + OCCLUSION_EPSILON) + }) + .min_by(|a, b| { + a.priority + .cmp(&b.priority) + .then_with(|| a.depth.total_cmp(&b.depth)) + .then_with(|| a.screen_distance.total_cmp(&b.screen_distance)) + }) + .map(|ranked| ranked.hit) +} + +fn ndc_to_px(ndc: Vec2, viewport_px: Vec2) -> Vec2 { + ndc * viewport_px * 0.5 +} + +/// Conservatively checks whether a transformed 3D AABB can overlap the +/// pointer's screen-space tolerance. If any corner is behind the eye, keep +/// the node: pruning an eye-crossing box would risk a false negative. +fn projected_bounds_hit( + view_projection: Mat4, + viewport_px: Vec2, + pointer_px: Vec2, + transform: Mat4, + min: Vec3, + max: Vec3, +) -> bool { + let mut screen_min = Vec2::splat(f32::INFINITY); + let mut screen_max = Vec2::splat(f32::NEG_INFINITY); + for corner in 0..8 { + let local = Vec3::new( + if corner & 1 == 0 { min.x } else { max.x }, + if corner & 2 == 0 { min.y } else { max.y }, + if corner & 4 == 0 { min.z } else { max.z }, + ); + let world = transform.transform_point3(local); + let Some(ndc) = project_with(view_projection, world) else { + return true; + }; + let screen = ndc_to_px(ndc.truncate(), viewport_px); + screen_min = screen_min.min(screen); + screen_max = screen_max.max(screen); + } + pointer_px.x >= screen_min.x - PICK_TOLERANCE_PX + && pointer_px.x <= screen_max.x + PICK_TOLERANCE_PX + && pointer_px.y >= screen_min.y - PICK_TOLERANCE_PX + && pointer_px.y <= screen_max.y + PICK_TOLERANCE_PX +} + +fn projected_depth(view_projection: Mat4, point: Vec3) -> Option { + project_with(view_projection, point) + .map(|projected| projected.z) + .filter(|depth| (0.0..=1.0).contains(depth)) +} + +/// Slab test. +fn ray_hits_box(origin: Vec3, dir: Vec3, min: Vec3, max: Vec3) -> bool { + let inv = dir.recip(); + let t1 = (min - origin) * inv; + let t2 = (max - origin) * inv; + let near = t1.min(t2).max_element(); + let far = t1.max(t2).min_element(); + // NaN (ray parallel to a slab, starting on its border) counts as a hit. + !(near > far || far < 0.0) +} + +/// Distance from `p` to segment `ab`, and the parameter of the closest point. +fn distance_to_segment(p: Vec2, a: Vec2, b: Vec2) -> (f32, f32) { + let ab = b - a; + let length2 = ab.length_squared(); + let t = if length2 > 0.0 { + ((p - a).dot(ab) / length2).clamp(0.0, 1.0) + } else { + 0.0 + }; + (p.distance(a + ab * t), t) +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_picking.rs"] +mod tests; diff --git a/src/viewer/present.wgsl b/src/viewer/present.wgsl new file mode 100644 index 000000000..51760d678 --- /dev/null +++ b/src/viewer/present.wgsl @@ -0,0 +1,28 @@ +// Copies the view's sRGB texture into a plain 8-bit one for egui, which +// expects gamma-encoded colors. Only for devices that cannot view an sRGB +// texture as plain (the OpenGL backend): elsewhere egui reads the sRGB +// texture through a plain view and this pass is not needed. +// +// Reading the sRGB texture decodes to linear light, so the shader encodes +// again by hand; the plain target stores that unchanged. + +@group(0) @binding(0) var scene: texture_2d; + +@vertex +fn vs_present(@builtin(vertex_index) index: u32) -> @builtin(position) vec4 { + // One triangle covering the whole viewport. + let uv = vec2(f32((index << 1u) & 2u), f32(index & 2u)); + return vec4(uv * 2.0 - 1.0, 0.0, 1.0); +} + +fn encode(linear: vec3) -> vec3 { + let low = linear * 12.92; + let high = 1.055 * pow(linear, vec3(1.0 / 2.4)) - 0.055; + return select(high, low, linear <= vec3(0.0031308)); +} + +@fragment +fn fs_present(@builtin(position) position: vec4) -> @location(0) vec4 { + let color = textureLoad(scene, vec2(floor(position.xy)), 0); + return vec4(encode(color.rgb), color.a); +} diff --git a/src/viewer/renderer.rs b/src/viewer/renderer.rs new file mode 100644 index 000000000..14f3780ef --- /dev/null +++ b/src/viewer/renderer.rs @@ -0,0 +1,1966 @@ +//! GPU renderer of the 3D view. +//! +//! The scene is drawn off screen (4x MSAA when available) into an sRGB +//! texture that egui then shows like an image. egui samples textures as +//! gamma-encoded values, so it is handed a non-sRGB view of the same +//! texture, or, on devices that cannot view a texture in another format +//! (the OpenGL backend), a plain copy encoded by `present.wgsl`. +//! +//! Draw order: background, opaque faces (each followed by its section cap), +//! edges and points, hidden edges (hidden-line mode), transparent faces +//! (back to front, with their caps), then the inspector overlay, which is +//! drawn on top. + +use std::collections::HashMap; +use std::num::NonZeroU64; +use std::sync::{Arc, Weak}; +use std::time::Instant; + +use bytemuck::{Pod, Zeroable}; +use eframe::egui_wgpu::{self, wgpu}; +use glam::{Mat4, Vec2, Vec3, Vec4}; +use wgpu::util::DeviceExt as _; + +use super::camera::{Camera, Eye}; +use super::culling::Frustum; +use super::shadow::{GroundShadow, ShadowPass}; +use super::stereo; +use crate::scene::Mesh; +use crate::settings::{Lighting, StereoMode}; + +const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb; +/// Same texels as `COLOR_FORMAT`, read without sRGB decoding (for egui). +const EGUI_VIEW_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; +/// With a stencil, for the caps of section planes. +const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth24PlusStencil8; +const PREFERRED_SAMPLES: u32 = 4; +/// Captures larger than this, on either side, are drawn in tiles. +const TILE_SIDE: u32 = 2048; +const OBJECT_UNIFORM_SIZE: u64 = std::mem::size_of::() as u64; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct CameraUniform { + view_proj: [[f32; 4]; 4], + eye: [f32; 4], + forward: [f32; 4], + right: [f32; 4], + up: [f32; 4], + viewport: [f32; 4], + background_top: [f32; 4], + background_bottom: [f32; 4], + clip_plane: [f32; 4], + section: [f32; 4], + cap_corners: [[f32; 4]; 4], + frame: [f32; 4], + key_light: [f32; 4], + light_levels: [f32; 4], + finish: [f32; 4], +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct ObjectUniform { + model: [[f32; 4]; 4], + face_color: [f32; 4], + edge_color: [f32; 4], + highlight: [f32; 4], + params: [f32; 4], + edge_filter: [f32; 4], + surface: [f32; 4], +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct MeshVertex { + position: [f32; 3], + normal: [f32; 3], + face_color: u32, +} + +/// How one mesh is drawn. Colors are linear RGBA. +#[derive(Clone, Copy, Debug)] +pub struct Style { + pub face_color: [f32; 4], + pub edge_color: [f32; 4], + /// RGB tint mixed into faces, with the mix factor in alpha. + pub highlight: [f32; 4], + pub edge_width: f32, + pub point_size: f32, + pub faces: bool, + pub edges: bool, + pub points: bool, + /// The section plane cuts it (helpers such as the axes are not cut). + pub clipped: bool, + /// Faces are filled with the background instead of being lit, so they + /// only hide what is behind them (hidden-line mode). + pub background_fill: bool, + /// Edges hidden behind faces are drawn too, as faint dashes. + pub hidden_edges: bool, + /// Edges whose faces meet at a smaller angle (degrees) are left out; 0 + /// draws every edge (see [`crate::scene::Mesh::segment_angles`]). + pub edge_min_angle: f32, + /// The outline of curved surfaces is drawn too, with the edges (see + /// [`crate::scene::Mesh::silhouette_edges`]). + pub silhouettes: bool, + /// How faces are shaded: [`crate::settings::Finish::surface`]. + pub surface: [f32; 4], +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layer { + /// Reference guides drawn behind the model without writing depth. Opaque + /// scene geometry therefore always covers axes and ground grids. + Reference, + Scene, + /// Drawn after the scene, faces pulled towards the viewer and edges and + /// points always visible. + Overlay, +} + +pub struct DrawItem { + pub mesh: Arc, + pub transform: Mat4, + pub style: Style, + pub layer: Layer, +} + +/// A section plane as the renderer draws it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SectionPlane { + /// Unit normal; everything with `normal · p > offset` is removed. + pub normal: Vec3, + pub offset: f32, + /// Fill the cut faces of solids. + pub caps: bool, + /// A quad on the plane around the whole scene, for the caps. + pub cap_corners: [Vec3; 4], +} + +/// Everything needed to draw one frame. +#[derive(Clone, Copy)] +pub struct FrameInput<'a> { + pub camera: &'a Camera, + /// Physical pixels. + pub size: [u32; 2], + /// Linear RGBA. + pub background_top: [f32; 4], + pub background_bottom: [f32; 4], + pub items: &'a [DrawItem], + pub section: Option, + /// Multiplies edge widths and point sizes, so that a capture larger + /// than the view looks like the view. + pub pixel_scale: f32, + /// Seen from the camera, or from one eye of the stereo pair. + pub eye: Eye, + pub lighting: Lighting, + /// A soft shadow on the ground under the model (Presentation mode). + pub ground_shadow: Option, +} + +/// Mode and eye size of the stereo composition (`stereo.wgsl`). +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct ComposeUniform { + mode: u32, + eye_width: u32, + eye_height: u32, + padding: u32, +} + +/// What composes the two eyes of the stereo projection. +struct Compose { + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + uniform: wgpu::Buffer, +} + +/// The part of an image one pass draws: `size` pixels at `offset` in an +/// image of `image` pixels. Large captures are drawn tile by tile. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Tile { + offset: [u32; 2], + size: [u32; 2], + image: [u32; 2], +} + +impl Tile { + fn whole(size: [u32; 2]) -> Self { + Self { + offset: [0, 0], + size, + image: size, + } + } + + /// Maps the clip space of the whole image to this tile's: a scale and + /// a shift after the projection, so it works for both projections and + /// keeps screen-space sizes in pixels. + fn projection(&self) -> Mat4 { + let [width, height] = self.image.map(|v| v as f32); + let [tile_width, tile_height] = self.size.map(|v| v as f32); + let [x, y] = self.offset.map(|v| v as f32); + let (scale_x, scale_y) = (width / tile_width, height / tile_height); + // The tile's centre in normalized device coordinates (y up). + let center_x = (x + tile_width / 2.0) / width * 2.0 - 1.0; + let center_y = 1.0 - (y + tile_height / 2.0) / height * 2.0; + Mat4::from_cols( + Vec4::new(scale_x, 0.0, 0.0, 0.0), + Vec4::new(0.0, scale_y, 0.0, 0.0), + Vec4::Z, + Vec4::new(-center_x * scale_x, -center_y * scale_y, 0.0, 1.0), + ) + } +} + +struct GpuMesh { + source: Weak, + vertices: Option, + indices: Option, + index_count: u32, + segments: Option, + segment_count: u32, + points: Option, + point_count: u32, + /// Made when an outline is first drawn. + silhouettes: std::cell::OnceCell>, +} + +struct Target { + size: [u32; 2], + multisampled: Option, + resolved: wgpu::Texture, + resolved_view: wgpu::TextureView, + depth_view: wgpu::TextureView, + /// What egui shows; only the view's own target has it. + egui: Option, +} + +/// The view's image as egui reads it: gamma-encoded 8-bit values. +enum EguiTexture { + /// A plain view of the sRGB texture: the same texels, not decoded. + View(wgpu::TextureView), + /// For devices without `DownlevelFlags::VIEW_FORMATS` (OpenGL): a + /// plain texture that `present.wgsl` fills after each frame. + Encoded { + view: wgpu::TextureView, + bind_group: wgpu::BindGroup, + }, +} + +impl Target { + fn egui_view(&self) -> &wgpu::TextureView { + match self.egui.as_ref().expect("the view's target") { + EguiTexture::View(view) | EguiTexture::Encoded { view, .. } => view, + } + } +} + +/// Fills an `EguiTexture::Encoded` (`present.wgsl`). +struct Present { + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, +} + +struct Pipelines { + background: wgpu::RenderPipeline, + reference_edges: wgpu::RenderPipeline, + faces: wgpu::RenderPipeline, + transparent_faces: wgpu::RenderPipeline, + /// Inverts the stencil per remaining surface of a clipped object. + section_count: wgpu::RenderPipeline, + /// Fills the plane where the stencil is set, and clears it. + caps: wgpu::RenderPipeline, + transparent_caps: wgpu::RenderPipeline, + overlay_faces: wgpu::RenderPipeline, + edges: wgpu::RenderPipeline, + /// Edges where the depth test fails, dashed (hidden-line mode). + hidden_edges: wgpu::RenderPipeline, + silhouettes: wgpu::RenderPipeline, + overlay_edges: wgpu::RenderPipeline, + points: wgpu::RenderPipeline, + overlay_points: wgpu::RenderPipeline, +} + +pub struct SceneRenderer { + device: wgpu::Device, + queue: wgpu::Queue, + samples: u32, + camera_buffer: wgpu::Buffer, + camera_bind_group: wgpu::BindGroup, + object_layout: wgpu::BindGroupLayout, + object_buffer: wgpu::Buffer, + object_bind_group: wgpu::BindGroup, + object_capacity: usize, + object_stride: u64, + pipelines: Pipelines, + meshes: HashMap, + target: Option, + texture_id: Option, + /// Largest side of one pass of `render_pixels`. + tile_side: u32, + stats: std::cell::Cell, + compose: Compose, + /// What the eyes of the stereo projection are drawn into. + eye_targets: Option<[Target; 2]>, + present: Present, + /// The device can view the sRGB target as plain for egui. + view_formats: bool, + /// Made when a ground shadow is first asked for. + shadow: Option, + /// The frame being drawn has a ground shadow ready. + shadow_shown: bool, +} + +/// Items of the last pass drawn, and skipped as out of view. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RenderStats { + pub drawn: usize, + pub culled: usize, +} + +impl SceneRenderer { + pub fn new(render_state: &egui_wgpu::RenderState) -> Self { + Self::with_device( + render_state.device.clone(), + render_state.queue.clone(), + &render_state.adapter, + ) + } + + /// A renderer on any device, including one without a window. + pub fn with_device(device: wgpu::Device, queue: wgpu::Queue, adapter: &wgpu::Adapter) -> Self { + // Both attachments must support the sample count (software + // OpenGL, for one, may not). + let multisampled = [COLOR_FORMAT, DEPTH_FORMAT].into_iter().all(|format| { + adapter + .get_texture_format_features(format) + .flags + .sample_count_supported(PREFERRED_SAMPLES) + }); + let samples = if multisampled { PREFERRED_SAMPLES } else { 1 }; + + let shader = device.create_shader_module(wgpu::include_wgsl!("shaders.wgsl")); + + let camera_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("camera"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }], + }); + let object_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("object"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: true, + min_binding_size: NonZeroU64::new(OBJECT_UNIFORM_SIZE), + }, + count: None, + }], + }); + + let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("camera"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let camera_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("camera"), + layout: &camera_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: camera_buffer.as_entire_binding(), + }], + }); + + let alignment = u64::from(device.limits().min_uniform_buffer_offset_alignment); + let object_stride = OBJECT_UNIFORM_SIZE.div_ceil(alignment) * alignment; + let object_capacity = 64; + let (object_buffer, object_bind_group) = + create_object_buffer(&device, &object_layout, object_stride, object_capacity); + + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("scene"), + bind_group_layouts: &[Some(&camera_layout), Some(&object_layout)], + immediate_size: 0, + }); + let pipelines = Pipelines::new(&device, &layout, &shader, samples); + let compose = Compose::new(&device); + let present = Present::new(&device); + let view_formats = adapter + .get_downlevel_capabilities() + .flags + .contains(wgpu::DownlevelFlags::VIEW_FORMATS); + + Self { + device, + queue, + samples, + camera_buffer, + camera_bind_group, + object_layout, + object_buffer, + object_bind_group, + object_capacity, + object_stride, + pipelines, + meshes: HashMap::new(), + target: None, + texture_id: None, + tile_side: TILE_SIDE, + stats: Default::default(), + compose, + eye_targets: None, + present, + view_formats, + shadow: None, + shadow_shown: false, + } + } + + /// Draws the ground shadow's occlusion again when the frame asks for a + /// shadow and its items or settings changed (see `shadow.rs`). + fn update_shadow(&mut self, input: &FrameInput<'_>) { + self.shadow_shown = false; + let Some(ground) = input.ground_shadow else { + return; + }; + let mut shadow = self.shadow.take().unwrap_or_else(|| { + ShadowPass::new( + &self.device, + &self.object_layout, + &self.camera_buffer, + COLOR_FORMAT, + DEPTH_FORMAT, + self.samples, + ) + }); + let shown = shadow.update( + &self.device, + &self.queue, + input.items, + &ground, + |pass, index| self.draw_occluder(pass, input, index), + ); + self.shadow = Some(shadow); + self.shadow_shown = shown; + } + + /// The faces of an item in the shadow's occlusion pass, whose pipeline + /// is set. + fn draw_occluder(&self, pass: &mut wgpu::RenderPass<'_>, input: &FrameInput<'_>, index: usize) { + let item = &input.items[index]; + let Some(mesh) = self.meshes.get(&item.mesh.id) else { + return; + }; + let (Some(vertices), Some(indices)) = (&mesh.vertices, &mesh.indices) else { + return; + }; + pass.set_bind_group(1, &self.object_bind_group, &[self.object_offset(index)]); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..mesh.index_count, 0, 0..1); + } + + /// Draws a frame and returns the egui texture showing it. + pub fn render( + &mut self, + egui_renderer: &mut egui_wgpu::Renderer, + input: &FrameInput<'_>, + ) -> egui::TextureId { + let size = [input.size[0].max(1), input.size[1].max(1)]; + let texture_id = self.ensure_target(egui_renderer, size); + self.upload_meshes(input); + self.write_objects(input.items, input.pixel_scale); + self.update_shadow(input); + let view_projection = self.write_camera(input, Tile::whole(size)); + let target = self.target.as_ref().expect("target created above"); + self.draw(target, input, view_projection); + self.present(target); + texture_id + } + + /// Draws a frame into textures of its own and reads it back as tightly + /// packed sRGB RGBA rows, so its size does not depend on the view or on + /// the largest texture of the device: large images are drawn in tiles. + /// `None` when the read-back fails. + pub fn render_pixels(&mut self, input: &FrameInput<'_>) -> Option<([u32; 2], Vec)> { + let [width, height] = [input.size[0].max(1), input.size[1].max(1)]; + let side = self + .tile_side + .min(self.device.limits().max_texture_dimension_2d); + let tile_size = [width.min(side), height.min(side)]; + let target = create_target(&self.device, tile_size, self.samples); + self.upload_meshes(input); + self.write_objects(input.items, input.pixel_scale); + self.update_shadow(input); + let row_bytes = width as usize * 4; + let mut image = vec![0u8; row_bytes * height as usize]; + for y in (0..height).step_by(tile_size[1] as usize) { + for x in (0..width).step_by(tile_size[0] as usize) { + // Edge tiles reach past the image; that part is dropped. + let view_projection = self.write_camera( + input, + Tile { + offset: [x, y], + size: tile_size, + image: [width, height], + }, + ); + self.draw(&target, input, view_projection); + let (_, pixels) = self.read_target(&target)?; + let tile_row = tile_size[0] as usize * 4; + let columns = (width - x).min(tile_size[0]) as usize * 4; + for row in 0..(height - y).min(tile_size[1]) as usize { + let from = row * tile_row; + let to = (y as usize + row) * row_bytes + x as usize * 4; + image[to..to + columns].copy_from_slice(&pixels[from..from + columns]); + } + } + } + Some(([width, height], image)) + } + + /// Draws both eyes of the stereo projection, composes them on the GPU + /// as `mode` says (`StereoMode::shown`) and returns the egui texture. + pub fn render_stereo( + &mut self, + egui_renderer: &mut egui_wgpu::Renderer, + input: &FrameInput<'_>, + mode: StereoMode, + ) -> egui::TextureId { + let size = [input.size[0].max(1), input.size[1].max(1)]; + let texture_id = self.ensure_target(egui_renderer, size); + self.draw_eyes(input, mode); + let target = self.target.as_ref().expect("target created above"); + self.compose_eyes(mode, &target.resolved_view); + self.present(target); + texture_id + } + + /// The stereo image as [`SceneRenderer::render_pixels`] reads a plain + /// one: each eye drawn by itself (in tiles when large), then composed + /// by `stereo::compose`. + pub fn render_stereo_pixels( + &mut self, + input: &FrameInput<'_>, + mode: StereoMode, + ) -> Option<([u32; 2], Vec)> { + let size = [input.size[0].max(1), input.size[1].max(1)]; + let eye_size = stereo::eye_size(mode, size); + let mut eye = |eye| { + self.render_pixels(&FrameInput { + size: eye_size, + eye, + ..*input + }) + .map(|(_, pixels)| pixels) + }; + let (left, right) = (eye(Eye::Left)?, eye(Eye::Right)?); + Some((size, stereo::compose(mode, size, &left, &right))) + } + + /// The live view's GPU composition, read back (for the tests). + #[cfg(test)] + fn render_stereo_gpu_pixels( + &mut self, + input: &FrameInput<'_>, + mode: StereoMode, + ) -> Option<([u32; 2], Vec)> { + let size = [input.size[0].max(1), input.size[1].max(1)]; + let output = create_target(&self.device, size, self.samples); + self.draw_eyes(input, mode); + self.compose_eyes(mode, &output.resolved_view); + self.read_target(&output) + } + + /// Draws the left and the right eye into `eye_targets`. + fn draw_eyes(&mut self, input: &FrameInput<'_>, mode: StereoMode) { + let size = [input.size[0].max(1), input.size[1].max(1)]; + let eye_size = stereo::eye_size(mode, size); + if self + .eye_targets + .as_ref() + .is_none_or(|targets| targets[0].size != eye_size) + { + let target = || create_target(&self.device, eye_size, self.samples); + self.eye_targets = Some([target(), target()]); + } + self.upload_meshes(input); + self.write_objects(input.items, input.pixel_scale); + self.update_shadow(input); + let targets = self.eye_targets.as_ref().expect("created above"); + for (eye, target) in [Eye::Left, Eye::Right].into_iter().zip(targets) { + let input = FrameInput { + size: eye_size, + eye, + ..*input + }; + let view_projection = self.write_camera(&input, Tile::whole(eye_size)); + self.draw(target, &input, view_projection); + } + } + + /// Composes the eyes drawn by `draw_eyes` into `output`. + fn compose_eyes(&self, mode: StereoMode, output: &wgpu::TextureView) { + let targets = self.eye_targets.as_ref().expect("eyes drawn first"); + let [eye_width, eye_height] = targets[0].size; + let uniform = ComposeUniform { + mode: stereo::shader_mode(mode), + eye_width, + eye_height, + padding: 0, + }; + self.queue + .write_buffer(&self.compose.uniform, 0, bytemuck::bytes_of(&uniform)); + let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("stereo"), + layout: &self.compose.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&targets[0].resolved_view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&targets[1].resolved_view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.compose.uniform.as_entire_binding(), + }, + ], + }); + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("stereo"), + }); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("stereo"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: output, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.compose.pipeline); + pass.set_bind_group(0, &bind_group, &[]); + pass.draw(0..3, 0..1); + } + self.queue.submit([encoder.finish()]); + } + + fn upload_meshes(&mut self, input: &FrameInput<'_>) { + self.meshes.retain(|_, mesh| mesh.source.strong_count() > 0); + let uploading = Instant::now(); + let (mut uploaded, mut bytes) = (0, 0); + for item in input.items { + if !self.meshes.contains_key(&item.mesh.id) { + let gpu = upload(&self.device, &item.mesh); + self.meshes.insert(item.mesh.id, gpu); + uploaded += 1; + bytes += item.mesh.byte_size(); + } + } + if uploaded > 0 { + log::debug!( + "Uploaded {uploaded} mesh(es) to the GPU ({:.2} MB of mesh data) in {:.1} ms", + bytes as f64 / 1e6, + uploading.elapsed().as_secs_f64() * 1e3 + ); + } + } + + /// What the last pass drew, and what it skipped as out of view. + #[cfg(test)] + pub fn last_stats(&self) -> RenderStats { + self.stats.get() + } + + /// Samples per pixel: 4 with multisampling, else 1. + #[cfg(test)] + fn samples(&self) -> u32 { + self.samples + } + + fn draw(&self, target: &Target, input: &FrameInput<'_>, view_projection: Mat4) { + // Items wholly outside the view are skipped, faces, edges and caps, + // allowing for the widest edge or point drawn across the border. + let widest = input + .items + .iter() + .map(|item| item.style.edge_width.max(item.style.point_size)) + .fold(0.0, f32::max); + let margin_px = widest * input.pixel_scale + 2.0; + let margin = Vec2::from_array(target.size.map(|side| margin_px * 2.0 / side as f32)); + let frustum = Frustum::new(view_projection, margin); + let in_view: Vec = input + .items + .iter() + .map(|item| frustum.intersects(item.mesh.bounds.transformed(item.transform))) + .collect(); + let drawn = in_view.iter().filter(|&&shown| shown).count(); + self.stats.set(RenderStats { + drawn, + culled: input.items.len() - drawn, + }); + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("scene"), + }); + { + let (view, resolve_target) = match &target.multisampled { + Some(multisampled) => (multisampled, Some(&target.resolved_view)), + None => (&target.resolved_view, None), + }; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("scene"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: &target.depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(1.0), + store: wgpu::StoreOp::Discard, + }), + // The section caps count surfaces in the stencil. + stencil_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0), + store: wgpu::StoreOp::Discard, + }), + }), + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_bind_group(0, &self.camera_bind_group, &[]); + pass.set_stencil_reference(0); + + pass.set_pipeline(&self.pipelines.background); + pass.set_bind_group(1, &self.object_bind_group, &[0]); + pass.draw(0..3, 0..1); + + let is_opaque = |item: &DrawItem| item.style.face_color[3] >= 0.999; + let order = draw_order(input); + let in_view = &in_view; + let scene = |pass_layer: Layer| { + order + .iter() + .copied() + .filter(move |&(index, layer)| layer == pass_layer && in_view[index]) + }; + + // Reference guides are deliberately painted before scene geometry + // and do not write depth. This keeps axes and grids visible around + // a model without making them look as if they pass through it. + for (index, _) in scene(Layer::Reference) { + self.draw_edges(&mut pass, &self.pipelines.reference_edges, input, index); + } + + let caps = input.section.is_some_and(|section| section.caps); + for (index, _) in scene(Layer::Scene).filter(|&(i, _)| is_opaque(&input.items[i])) { + self.draw_faces(&mut pass, &self.pipelines.faces, input, index); + if caps { + self.draw_cap(&mut pass, &self.pipelines.caps, input, index); + } + } + // The ground shadow, behind the opaque faces drawn so far. + if self.shadow_shown + && let Some(shadow) = &self.shadow + { + shadow.draw_floor(&mut pass); + pass.set_bind_group(0, &self.camera_bind_group, &[]); + } + for (index, _) in scene(Layer::Scene) { + self.draw_edges(&mut pass, &self.pipelines.edges, input, index); + self.draw_silhouettes(&mut pass, input, index); + self.draw_points(&mut pass, &self.pipelines.points, input, index); + } + // After every opaque face, so that they all hide edges. + for (index, _) in + scene(Layer::Scene).filter(|&(i, _)| input.items[i].style.hidden_edges) + { + self.draw_edges(&mut pass, &self.pipelines.hidden_edges, input, index); + } + for (index, _) in scene(Layer::Scene).filter(|&(i, _)| !is_opaque(&input.items[i])) { + self.draw_faces(&mut pass, &self.pipelines.transparent_faces, input, index); + if caps { + self.draw_cap(&mut pass, &self.pipelines.transparent_caps, input, index); + } + } + for (index, _) in scene(Layer::Overlay) { + self.draw_faces(&mut pass, &self.pipelines.overlay_faces, input, index); + self.draw_edges(&mut pass, &self.pipelines.overlay_edges, input, index); + self.draw_points(&mut pass, &self.pipelines.overlay_points, input, index); + } + } + self.queue.submit([encoder.finish()]); + } + + /// Reads a target back as tightly packed sRGB RGBA rows. + fn read_target(&self, target: &Target) -> Option<([u32; 2], Vec)> { + self.read_texture(&target.resolved, target.size) + } + + /// The view's target drawn, as the sRGB texture and as egui's plain + /// copy encoded by `present.wgsl` (for the tests, on any device). + #[cfg(test)] + fn presented_pixels(&mut self, input: &FrameInput<'_>) -> Option<(Vec, Vec)> { + let size = [input.size[0].max(1), input.size[1].max(1)]; + let target = create_view_target(&self.device, &self.present, size, self.samples, false); + self.upload_meshes(input); + self.write_objects(input.items, input.pixel_scale); + self.update_shadow(input); + let view_projection = self.write_camera(input, Tile::whole(size)); + self.draw(&target, input, view_projection); + self.present(&target); + let Some(EguiTexture::Encoded { view, .. }) = &target.egui else { + unreachable!("created encoded"); + }; + Some(( + self.read_target(&target)?.1, + self.read_texture(view.texture(), size)?.1, + )) + } + + /// Fills egui's plain copy of `target`, when it has one. + fn present(&self, target: &Target) { + let Some(EguiTexture::Encoded { + view, bind_group, .. + }) = &target.egui + else { + return; + }; + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("present"), + }); + { + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("present"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + pass.set_pipeline(&self.present.pipeline); + pass.set_bind_group(0, bind_group, &[]); + pass.draw(0..3, 0..1); + } + self.queue.submit([encoder.finish()]); + } + + /// Reads a color texture back as tightly packed RGBA rows. + fn read_texture(&self, texture: &wgpu::Texture, size: [u32; 2]) -> Option<([u32; 2], Vec)> { + let [width, height] = size; + let row_bytes = width * 4; + let padded_row = row_bytes.div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) + * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT; + let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("screenshot"), + size: u64::from(padded_row) * u64::from(height), + usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, + mapped_at_creation: false, + }); + let mut encoder = self + .device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("screenshot"), + }); + encoder.copy_texture_to_buffer( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d::ZERO, + aspect: wgpu::TextureAspect::All, + }, + wgpu::TexelCopyBufferInfo { + buffer: &buffer, + layout: wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(padded_row), + rows_per_image: Some(height), + }, + }, + wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + ); + self.queue.submit([encoder.finish()]); + + let slice = buffer.slice(..); + let (sender, receiver) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |result| { + let _ = sender.send(result); + }); + self.device + .poll(wgpu::PollType::Wait { + submission_index: None, + timeout: Some(std::time::Duration::from_secs(5)), + }) + .ok()?; + receiver.recv().ok()?.ok()?; + + let mapped = slice.get_mapped_range().ok()?; + let mut pixels = Vec::with_capacity((row_bytes * height) as usize); + for row in mapped.chunks(padded_row as usize) { + pixels.extend_from_slice(&row[..row_bytes as usize]); + } + drop(mapped); + buffer.unmap(); + Some(([width, height], pixels)) + } + + fn ensure_target( + &mut self, + egui_renderer: &mut egui_wgpu::Renderer, + size: [u32; 2], + ) -> egui::TextureId { + if self.target.as_ref().is_none_or(|t| t.size != size) { + let target = create_view_target( + &self.device, + &self.present, + size, + self.samples, + self.view_formats, + ); + match self.texture_id { + Some(id) => egui_renderer.update_egui_texture_from_wgpu_texture( + &self.device, + target.egui_view(), + wgpu::FilterMode::Linear, + id, + ), + None => { + self.texture_id = Some(egui_renderer.register_native_texture( + &self.device, + target.egui_view(), + wgpu::FilterMode::Linear, + )); + } + } + self.target = Some(target); + } + self.texture_id.expect("texture registered") + } + + /// Writes the camera of `tile` and returns its view-projection matrix. + fn write_camera(&self, input: &FrameInput<'_>, tile: Tile) -> Mat4 { + let camera = input.camera; + let [image_width, image_height] = tile.image.map(|v| v as f32); + let [width, height] = tile.size.map(|v| v as f32); + let [x, y] = tile.offset.map(|v| v as f32); + let vec4 = |v: Vec3, w: f32| [v.x, v.y, v.z, w]; + let section = input.section; + let view_projection = + tile.projection() * camera.eye_view_projection(image_width / image_height, input.eye); + let uniform = CameraUniform { + clip_plane: section.map_or([0.0; 4], |s| vec4(s.normal, s.offset)), + section: [f32::from(u8::from(section.is_some())), 0.0, 0.0, 0.0], + cap_corners: section.map_or([[0.0; 4]; 4], |s| s.cap_corners.map(|c| vec4(c, 1.0))), + view_proj: view_projection.to_cols_array_2d(), + eye: vec4( + camera.eye_position(input.eye), + if camera.is_perspective() { 1.0 } else { 0.0 }, + ), + forward: vec4(camera.forward(), 0.0), + right: vec4(camera.right(), 0.0), + up: vec4(camera.up(), 0.0), + viewport: [width, height, 1.0 / width, 1.0 / height], + background_top: input.background_top, + background_bottom: input.background_bottom, + frame: [x, y, image_width, image_height], + ..lighting_uniform(&input.lighting) + }; + self.queue + .write_buffer(&self.camera_buffer, 0, bytemuck::bytes_of(&uniform)); + view_projection + } + + /// One uniform block per item, at `object_stride` intervals; slot 0 is + /// reserved for the background pass, so item `i` lives in slot `i + 1`. + fn write_objects(&mut self, items: &[DrawItem], pixel_scale: f32) { + let needed = items.len() + 1; + if needed > self.object_capacity { + self.object_capacity = needed.next_power_of_two(); + let (buffer, bind_group) = create_object_buffer( + &self.device, + &self.object_layout, + self.object_stride, + self.object_capacity, + ); + self.object_buffer = buffer; + self.object_bind_group = bind_group; + } + let stride = self.object_stride as usize; + let mut data = vec![0u8; needed * stride]; + for (slot, item) in items.iter().enumerate() { + let style = &item.style; + let uniform = ObjectUniform { + model: item.transform.to_cols_array_2d(), + face_color: style.face_color, + edge_color: style.edge_color, + highlight: style.highlight, + params: [ + style.edge_width * pixel_scale, + style.point_size * pixel_scale, + f32::from(u8::from(style.clipped)), + f32::from(u8::from(style.background_fill)), + ], + edge_filter: [style.edge_min_angle, 0.0, 0.0, 0.0], + surface: style.surface, + }; + let offset = (slot + 1) * stride; + data[offset..offset + OBJECT_UNIFORM_SIZE as usize] + .copy_from_slice(bytemuck::bytes_of(&uniform)); + } + self.queue.write_buffer(&self.object_buffer, 0, &data); + } + + fn object_offset(&self, index: usize) -> u32 { + ((index + 1) as u64 * self.object_stride) as u32 + } + + fn draw_faces( + &self, + pass: &mut wgpu::RenderPass<'_>, + pipeline: &wgpu::RenderPipeline, + input: &FrameInput<'_>, + index: usize, + ) { + let item = &input.items[index]; + let Some(mesh) = self.meshes.get(&item.mesh.id) else { + return; + }; + if !item.style.faces || mesh.index_count == 0 { + return; + } + let (Some(vertices), Some(indices)) = (&mesh.vertices, &mesh.indices) else { + return; + }; + pass.set_pipeline(pipeline); + pass.set_bind_group(1, &self.object_bind_group, &[self.object_offset(index)]); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..mesh.index_count, 0, 0..1); + } + + /// Fills where the section plane cuts a clipped item: counts its + /// remaining surfaces into the stencil, then draws the plane there. + fn draw_cap( + &self, + pass: &mut wgpu::RenderPass<'_>, + cap: &wgpu::RenderPipeline, + input: &FrameInput<'_>, + index: usize, + ) { + let item = &input.items[index]; + if !item.style.clipped { + return; + } + let Some(mesh) = self.meshes.get(&item.mesh.id) else { + return; + }; + let (Some(vertices), Some(indices)) = (&mesh.vertices, &mesh.indices) else { + return; + }; + if !item.style.faces || mesh.index_count == 0 { + return; + } + pass.set_bind_group(1, &self.object_bind_group, &[self.object_offset(index)]); + pass.set_pipeline(&self.pipelines.section_count); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..mesh.index_count, 0, 0..1); + pass.set_pipeline(cap); + pass.draw(0..6, 0..1); + } + + fn draw_edges( + &self, + pass: &mut wgpu::RenderPass<'_>, + pipeline: &wgpu::RenderPipeline, + input: &FrameInput<'_>, + index: usize, + ) { + let item = &input.items[index]; + let Some(mesh) = self.meshes.get(&item.mesh.id) else { + return; + }; + let Some(segments) = &mesh.segments else { + return; + }; + if !item.style.edges || mesh.segment_count == 0 { + return; + } + pass.set_pipeline(pipeline); + pass.set_bind_group(1, &self.object_bind_group, &[self.object_offset(index)]); + pass.set_vertex_buffer(0, segments.slice(..)); + pass.draw(0..6, 0..mesh.segment_count); + } + + /// The outline of the curved surfaces of an item drawn with one. + fn draw_silhouettes( + &self, + pass: &mut wgpu::RenderPass<'_>, + input: &FrameInput<'_>, + index: usize, + ) { + let item = &input.items[index]; + if !(item.style.edges && item.style.silhouettes && item.style.faces) { + return; + } + let Some(mesh) = self.meshes.get(&item.mesh.id) else { + return; + }; + let silhouettes = mesh.silhouettes.get_or_init(|| { + let edges = item.mesh.silhouette_edges(); + (!edges.is_empty()).then(|| { + let buffer = self + .device + .create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("silhouettes"), + contents: bytemuck::cast_slice(edges), + usage: wgpu::BufferUsages::VERTEX, + }); + (buffer, edges.len() as u32) + }) + }); + let Some((buffer, count)) = silhouettes else { + return; + }; + pass.set_pipeline(&self.pipelines.silhouettes); + pass.set_bind_group(1, &self.object_bind_group, &[self.object_offset(index)]); + pass.set_vertex_buffer(0, buffer.slice(..)); + pass.draw(0..6, 0..*count); + } + + fn draw_points( + &self, + pass: &mut wgpu::RenderPass<'_>, + pipeline: &wgpu::RenderPipeline, + input: &FrameInput<'_>, + index: usize, + ) { + let item = &input.items[index]; + let Some(mesh) = self.meshes.get(&item.mesh.id) else { + return; + }; + let Some(points) = &mesh.points else { return }; + if !item.style.points || mesh.point_count == 0 { + return; + } + pass.set_pipeline(pipeline); + pass.set_bind_group(1, &self.object_bind_group, &[self.object_offset(index)]); + pass.set_vertex_buffer(0, points.slice(..)); + pass.draw(0..6, 0..mesh.point_count); + } +} + +/// The lighting fields of the camera uniform, the others zero. Values stay +/// in ranges the shader handles: no negative light and no NaN, whatever the +/// settings file says. +fn lighting_uniform(lighting: &Lighting) -> CameraUniform { + let bounded = |value: f32, min: f32, max: f32, fallback: f32| { + if value.is_finite() { + value.clamp(min, max) + } else { + fallback + } + }; + let defaults = Lighting::default(); + let direction = Lighting { + azimuth: bounded(lighting.azimuth, -180.0, 180.0, defaults.azimuth), + elevation: bounded(lighting.elevation, -90.0, 90.0, defaults.elevation), + ..defaults + }; + let [x, y, z] = direction.key_direction(); + CameraUniform { + key_light: [x, y, z, 0.0], + light_levels: [ + bounded(lighting.key, 0.0, 4.0, defaults.key), + bounded(lighting.fill, 0.0, 4.0, defaults.fill), + bounded(lighting.ambient, 0.0, 4.0, defaults.ambient), + bounded(lighting.rim, 0.0, 4.0, defaults.rim), + ], + finish: [ + bounded(lighting.specular, 0.0, 4.0, defaults.specular), + bounded(lighting.shininess, 1.0, 1024.0, defaults.shininess), + 2f32.powf(bounded(lighting.exposure, -6.0, 6.0, 0.0)), + bounded(lighting.contrast, 0.2, 5.0, 1.0), + ], + ..CameraUniform::zeroed() + } +} + +/// Item indices with their layers: opaque order is irrelevant, transparent +/// faces need back-to-front order. +fn draw_order(input: &FrameInput<'_>) -> Vec<(usize, Layer)> { + let camera = input.camera; + let eye = camera.eye(); + let forward = camera.forward(); + let mut order: Vec<(usize, f32)> = input + .items + .iter() + .enumerate() + .map(|(i, item)| { + let center = item.transform.transform_point3(item.mesh.bounds.center()); + (i, (center - eye).dot(forward)) + }) + .collect(); + order.sort_by(|a, b| b.1.total_cmp(&a.1)); + order + .into_iter() + .map(|(i, _)| (i, input.items[i].layer)) + .collect() +} + +fn create_object_buffer( + device: &wgpu::Device, + layout: &wgpu::BindGroupLayout, + stride: u64, + capacity: usize, +) -> (wgpu::Buffer, wgpu::BindGroup) { + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("objects"), + size: stride * capacity as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("objects"), + layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &buffer, + offset: 0, + size: NonZeroU64::new(OBJECT_UNIFORM_SIZE), + }), + }], + }); + (buffer, bind_group) +} + +/// A target drawn off screen and read back (captures, stereo eyes). +fn create_target(device: &wgpu::Device, size: [u32; 2], samples: u32) -> Target { + create_target_with(device, size, samples, &[]) +} + +/// The view's target, which egui shows: through a plain view of the sRGB +/// texture when the device can make one (`view_formats`), else through a +/// plain copy that `SceneRenderer::present` fills. +fn create_view_target( + device: &wgpu::Device, + present: &Present, + size: [u32; 2], + samples: u32, + view_formats: bool, +) -> Target { + if view_formats { + let mut target = create_target_with(device, size, samples, &[EGUI_VIEW_FORMAT]); + target.egui = Some(EguiTexture::View(target.resolved.create_view( + &wgpu::TextureViewDescriptor { + format: Some(EGUI_VIEW_FORMAT), + ..Default::default() + }, + ))); + return target; + } + let mut target = create_target(device, size, samples); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("scene for egui"), + size: wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: EGUI_VIEW_FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("present"), + layout: &present.layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(&target.resolved_view), + }], + }); + target.egui = Some(EguiTexture::Encoded { + view: texture.create_view(&wgpu::TextureViewDescriptor::default()), + bind_group, + }); + target +} + +fn create_target_with( + device: &wgpu::Device, + size: [u32; 2], + samples: u32, + view_formats: &[wgpu::TextureFormat], +) -> Target { + let extent = wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }; + let texture = |label, format, samples, usage, view_formats: &[wgpu::TextureFormat]| { + device.create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: extent, + mip_level_count: 1, + sample_count: samples, + dimension: wgpu::TextureDimension::D2, + format, + usage, + view_formats, + }) + }; + + let resolved = texture( + "scene color", + COLOR_FORMAT, + 1, + wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::COPY_SRC, + view_formats, + ); + let resolved_view = resolved.create_view(&wgpu::TextureViewDescriptor::default()); + let multisampled = (samples > 1).then(|| { + texture( + "scene msaa", + COLOR_FORMAT, + samples, + wgpu::TextureUsages::RENDER_ATTACHMENT, + &[], + ) + .create_view(&wgpu::TextureViewDescriptor::default()) + }); + let depth_view = texture( + "scene depth", + DEPTH_FORMAT, + samples, + wgpu::TextureUsages::RENDER_ATTACHMENT, + &[], + ) + .create_view(&wgpu::TextureViewDescriptor::default()); + + Target { + size, + multisampled, + resolved, + resolved_view, + depth_view, + egui: None, + } +} + +fn upload(device: &wgpu::Device, mesh: &Arc) -> GpuMesh { + let buffer = |label, contents: &[u8], usage| { + (!contents.is_empty()).then(|| { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some(label), + contents, + usage, + }) + }) + }; + let interleaved: Vec = mesh + .positions + .iter() + .zip(&mesh.normals) + .enumerate() + .map(|(index, (p, n))| MeshVertex { + position: *p, + normal: *n, + face_color: mesh.vertex_colors.get(index).copied().unwrap_or(0), + }) + .collect(); + let has_triangles = !interleaved.is_empty() && !mesh.indices.is_empty(); + // Each segment: its two ends and the angle its edge's faces meet at. + let segments: Vec<[f32; 7]> = mesh + .edges + .as_chunks::<2>() + .0 + .iter() + .enumerate() + .map(|(index, [a, b])| { + [ + a[0], + a[1], + a[2], + b[0], + b[1], + b[2], + mesh.segment_angle(index), + ] + }) + .collect(); + GpuMesh { + source: Arc::downgrade(mesh), + vertices: has_triangles + .then(|| { + buffer( + "vertices", + bytemuck::cast_slice(&interleaved), + wgpu::BufferUsages::VERTEX, + ) + }) + .flatten(), + indices: has_triangles + .then(|| { + buffer( + "indices", + bytemuck::cast_slice(&mesh.indices), + wgpu::BufferUsages::INDEX, + ) + }) + .flatten(), + index_count: if has_triangles { + mesh.indices.len() as u32 + } else { + 0 + }, + segments: buffer( + "segments", + bytemuck::cast_slice(&segments), + wgpu::BufferUsages::VERTEX, + ), + segment_count: segments.len() as u32, + points: buffer( + "points", + bytemuck::cast_slice(&mesh.points), + wgpu::BufferUsages::VERTEX, + ), + point_count: mesh.points.len() as u32, + silhouettes: std::cell::OnceCell::new(), + } +} + +impl Present { + fn new(device: &wgpu::Device) -> Self { + let shader = device.create_shader_module(wgpu::include_wgsl!("present.wgsl")); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("present"), + entries: &[wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("present"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("present"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_present"), + compilation_options: Default::default(), + buffers: &[], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_present"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: EGUI_VIEW_FORMAT, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + Self { pipeline, layout } + } +} + +impl Compose { + fn new(device: &wgpu::Device) -> Self { + let shader = device.create_shader_module(wgpu::include_wgsl!("stereo.wgsl")); + let texture = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: false }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("stereo"), + entries: &[ + texture(0), + texture(1), + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("stereo"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("stereo"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_compose"), + compilation_options: Default::default(), + buffers: &[], + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_compose"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: COLOR_FORMAT, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + primitive: wgpu::PrimitiveState::default(), + depth_stencil: None, + multisample: wgpu::MultisampleState::default(), + multiview_mask: None, + cache: None, + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("stereo"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + Self { + pipeline, + layout, + uniform, + } + } +} + +impl Pipelines { + fn new( + device: &wgpu::Device, + layout: &wgpu::PipelineLayout, + shader: &wgpu::ShaderModule, + samples: u32, + ) -> Self { + const MESH_ATTRIBUTES: [wgpu::VertexAttribute; 3] = + wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Uint32]; + const SEGMENT_ATTRIBUTES: [wgpu::VertexAttribute; 3] = + wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32]; + const SILHOUETTE_ATTRIBUTES: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![ + 0 => Float32x3, 1 => Float32x3, 2 => Float32x3, 3 => Float32x3 + ]; + const POINT_ATTRIBUTES: [wgpu::VertexAttribute; 1] = + wgpu::vertex_attr_array![0 => Float32x3]; + + let mesh_buffers = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &MESH_ATTRIBUTES, + })]; + let segment_buffers = [Some(wgpu::VertexBufferLayout { + array_stride: 28, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &SEGMENT_ATTRIBUTES, + })]; + let silhouette_buffers = [Some(wgpu::VertexBufferLayout { + array_stride: 48, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &SILHOUETTE_ATTRIBUTES, + })]; + let point_buffers = [Some(wgpu::VertexBufferLayout { + array_stride: 12, + step_mode: wgpu::VertexStepMode::Instance, + attributes: &POINT_ATTRIBUTES, + })]; + + let builder = PipelineBuilder { + device, + layout, + shader, + samples, + }; + // Faces are pushed slightly back so that edges lying on them win the + // depth test; overlay faces are pulled forward instead. + let push_back = wgpu::DepthBiasState { + constant: 2, + slope_scale: 1.5, + clamp: 0.0, + }; + let pull_forward = wgpu::DepthBiasState { + constant: -4, + slope_scale: -2.0, + clamp: 0.0, + }; + let no_bias = wgpu::DepthBiasState::default(); + use wgpu::CompareFunction::{Always, Greater, Less, LessEqual, NotEqual}; + use wgpu::StencilOperation::{Invert, Keep, Zero}; + + // Section caps: parity of the remaining surfaces, then a quad where + // it is odd that also resets the stencil, even where it is hidden. + let face = |compare, depth_fail_op, pass_op| wgpu::StencilFaceState { + compare, + fail_op: Keep, + depth_fail_op, + pass_op, + }; + let stencil = |face: wgpu::StencilFaceState| wgpu::StencilState { + front: face, + back: face, + read_mask: 0xff, + write_mask: 0xff, + }; + let count = stencil(face(Always, Invert, Invert)); + let fill = stencil(face(NotEqual, Zero, Zero)); + + Self { + section_count: builder.build_with(Spec { + stencil: count, + write_mask: wgpu::ColorWrites::empty(), + ..Spec::new( + "section count", + "vs_mesh", + "fs_section_count", + &mesh_buffers, + None, + Always, + false, + no_bias, + ) + }), + caps: builder.build_with(Spec { + stencil: fill.clone(), + ..Spec::new("caps", "vs_cap", "fs_cap", &[], None, Less, true, push_back) + }), + transparent_caps: builder.build_with(Spec { + stencil: fill.clone(), + ..Spec::new( + "transparent caps", + "vs_cap", + "fs_cap", + &[], + Some(wgpu::BlendState::ALPHA_BLENDING), + Less, + false, + push_back, + ) + }), + background: builder.build( + "background", + "vs_background", + "fs_background", + &[], + None, + Always, + false, + no_bias, + ), + reference_edges: builder.build( + "reference edges", + "vs_edge", + "fs_edge", + &segment_buffers, + Some(wgpu::BlendState::ALPHA_BLENDING), + Always, + false, + no_bias, + ), + faces: builder.build( + "faces", + "vs_mesh", + "fs_mesh", + &mesh_buffers, + None, + Less, + true, + push_back, + ), + transparent_faces: builder.build( + "transparent faces", + "vs_mesh", + "fs_mesh", + &mesh_buffers, + Some(wgpu::BlendState::ALPHA_BLENDING), + Less, + false, + push_back, + ), + overlay_faces: builder.build( + "overlay faces", + "vs_mesh", + "fs_mesh", + &mesh_buffers, + Some(wgpu::BlendState::ALPHA_BLENDING), + LessEqual, + false, + pull_forward, + ), + edges: builder.build( + "edges", + "vs_edge", + "fs_edge", + &segment_buffers, + Some(wgpu::BlendState::ALPHA_BLENDING), + LessEqual, + true, + no_bias, + ), + silhouettes: builder.build( + "silhouettes", + "vs_silhouette", + "fs_edge", + &silhouette_buffers, + Some(wgpu::BlendState::ALPHA_BLENDING), + LessEqual, + true, + no_bias, + ), + hidden_edges: builder.build( + "hidden edges", + "vs_edge", + "fs_hidden_edge", + &segment_buffers, + Some(wgpu::BlendState::ALPHA_BLENDING), + Greater, + false, + no_bias, + ), + overlay_edges: builder.build( + "overlay edges", + "vs_edge", + "fs_edge", + &segment_buffers, + Some(wgpu::BlendState::ALPHA_BLENDING), + Always, + false, + no_bias, + ), + points: builder.build( + "points", + "vs_point", + "fs_point", + &point_buffers, + None, + LessEqual, + true, + no_bias, + ), + overlay_points: builder.build( + "overlay points", + "vs_point", + "fs_point", + &point_buffers, + None, + Always, + false, + no_bias, + ), + } + } +} + +struct PipelineBuilder<'a> { + device: &'a wgpu::Device, + layout: &'a wgpu::PipelineLayout, + shader: &'a wgpu::ShaderModule, + samples: u32, +} + +/// One pipeline's state. +struct Spec<'a> { + label: &'a str, + vertex: &'a str, + fragment: &'a str, + buffers: &'a [Option>], + blend: Option, + depth_compare: wgpu::CompareFunction, + depth_write: bool, + bias: wgpu::DepthBiasState, + stencil: wgpu::StencilState, + write_mask: wgpu::ColorWrites, +} + +impl<'a> Spec<'a> { + #[allow(clippy::too_many_arguments)] + fn new( + label: &'a str, + vertex: &'a str, + fragment: &'a str, + buffers: &'a [Option>], + blend: Option, + depth_compare: wgpu::CompareFunction, + depth_write: bool, + bias: wgpu::DepthBiasState, + ) -> Self { + Self { + label, + vertex, + fragment, + buffers, + blend, + depth_compare, + depth_write, + bias, + stencil: wgpu::StencilState::default(), + write_mask: wgpu::ColorWrites::ALL, + } + } +} + +impl PipelineBuilder<'_> { + #[allow(clippy::too_many_arguments)] + fn build( + &self, + label: &str, + vertex_entry: &str, + fragment_entry: &str, + buffers: &[Option>], + blend: Option, + depth_compare: wgpu::CompareFunction, + depth_write: bool, + bias: wgpu::DepthBiasState, + ) -> wgpu::RenderPipeline { + self.build_with(Spec::new( + label, + vertex_entry, + fragment_entry, + buffers, + blend, + depth_compare, + depth_write, + bias, + )) + } + + fn build_with(&self, spec: Spec<'_>) -> wgpu::RenderPipeline { + let Spec { + label, + vertex: vertex_entry, + fragment: fragment_entry, + buffers, + blend, + depth_compare, + depth_write, + bias, + stencil, + write_mask, + } = spec; + self.device + .create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(self.layout), + vertex: wgpu::VertexState { + module: self.shader, + entry_point: Some(vertex_entry), + compilation_options: Default::default(), + buffers, + }, + primitive: wgpu::PrimitiveState { + topology: wgpu::PrimitiveTopology::TriangleList, + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(depth_write), + depth_compare: Some(depth_compare), + stencil, + bias, + }), + multisample: wgpu::MultisampleState { + count: self.samples, + mask: !0, + alpha_to_coverage_enabled: false, + }, + fragment: Some(wgpu::FragmentState { + module: self.shader, + entry_point: Some(fragment_entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: COLOR_FORMAT, + blend: blend.or(Some(wgpu::BlendState::REPLACE)), + write_mask, + })], + }), + multiview_mask: None, + cache: None, + }) + } +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_renderer.rs"] +mod tests; diff --git a/src/viewer/section.rs b/src/viewer/section.rs new file mode 100644 index 000000000..9d8a390d2 --- /dev/null +++ b/src/viewer/section.rs @@ -0,0 +1,164 @@ +//! The section plane of the 3D view: an axis-aligned plane that cuts the +//! model away on one side, with the cut faces filled. + +use std::ops::RangeInclusive; + +use glam::Vec3; + +use super::renderer::SectionPlane; +use crate::scene::Aabb; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SectionAxis { + X, + Y, + #[default] + Z, +} + +impl SectionAxis { + pub const ALL: [Self; 3] = [Self::X, Self::Y, Self::Z]; + + pub fn label(self) -> &'static str { + match self { + Self::X => "X", + Self::Y => "Y", + Self::Z => "Z", + } + } + + pub fn direction(self) -> Vec3 { + match self { + Self::X => Vec3::X, + Self::Y => Vec3::Y, + Self::Z => Vec3::Z, + } + } +} + +/// A plane normal to an axis that removes the model on one side of it. +#[derive(Clone, Debug, PartialEq)] +pub struct Section { + pub enabled: bool, + pub axis: SectionAxis, + /// Position of the plane along the axis, in model units. + pub offset: f32, + /// Remove the other side: what lies below the plane instead of above. + pub flipped: bool, + /// Fill the cut faces of solids. + pub caps: bool, +} + +impl Default for Section { + fn default() -> Self { + Self { + enabled: false, + axis: SectionAxis::Z, + offset: 0.0, + flipped: false, + caps: true, + } + } +} + +/// The removed half-space: points with `normal · p > offset`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ClipPlane { + pub normal: Vec3, + pub offset: f32, +} + +impl ClipPlane { + pub fn removes(&self, point: Vec3) -> bool { + self.normal.dot(point) > self.offset + } + + /// The parameters `t` for which `origin + t * direction` is kept, as + /// an inclusive range; `None` when the whole ray is removed. + pub fn kept_range(&self, origin: Vec3, direction: Vec3) -> Option<(f32, f32)> { + let start = self.normal.dot(origin) - self.offset; + let rate = self.normal.dot(direction); + if rate.abs() < 1e-12 { + return (start <= 0.0).then_some((f32::NEG_INFINITY, f32::INFINITY)); + } + let crossing = -start / rate; + Some(if rate > 0.0 { + (f32::NEG_INFINITY, crossing) + } else { + (crossing, f32::INFINITY) + }) + } +} + +impl Section { + /// The plane while the section is on. + pub fn clip_plane(&self) -> Option { + self.enabled.then(|| { + let direction = self.axis.direction(); + if self.flipped { + ClipPlane { + normal: -direction, + offset: -self.offset, + } + } else { + ClipPlane { + normal: direction, + offset: self.offset, + } + } + }) + } + + /// Where the plane can usefully be: across the model along the axis. + pub fn range(&self, bounds: Aabb) -> RangeInclusive { + if bounds.is_empty() { + return -10.0..=10.0; + } + let axis = self.axis.direction(); + let (low, high) = (bounds.min.dot(axis), bounds.max.dot(axis)); + if high - low < 1e-6 { + low - 1.0..=high + 1.0 + } else { + low..=high + } + } + + /// Moves the plane into the model when it is outside, e.g. when the + /// section is turned on or the axis changes. + pub fn center_in(&mut self, bounds: Aabb) { + let range = self.range(bounds); + if !range.contains(&self.offset) { + self.offset = (range.start() + range.end()) / 2.0; + } + } + + /// The plane for the renderer, with a cap quad covering every place + /// where it can cut the model. + pub fn renderer_plane(&self, bounds: Aabb) -> Option { + let plane = self.clip_plane()?; + let (center, radius) = if bounds.is_empty() { + (Vec3::ZERO, 10.0) + } else { + (bounds.center(), (bounds.diagonal() * 0.5).max(1e-3)) + }; + let on_plane = center - plane.normal * (plane.normal.dot(center) - plane.offset); + let u = plane.normal.any_orthonormal_vector(); + let v = plane.normal.cross(u); + let half = radius * 1.5; + Some(SectionPlane { + normal: plane.normal, + offset: plane.offset, + caps: self.caps, + cap_corners: [ + on_plane - u * half - v * half, + on_plane + u * half - v * half, + on_plane + u * half + v * half, + on_plane - u * half + v * half, + ], + }) + } +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_section.rs"] +mod tests; diff --git a/src/viewer/shaders.wgsl b/src/viewer/shaders.wgsl new file mode 100644 index 000000000..daf18b151 --- /dev/null +++ b/src/viewer/shaders.wgsl @@ -0,0 +1,540 @@ +// Shaders of the 3D view. +// +// Colors arrive in linear space; the render target is sRGB, so the hardware +// encodes on write. Edges and points are camera-facing quads expanded in +// screen space, which gives constant pixel widths at any zoom. +// +// A section plane removes everything in front of it (dot(n, p) > d) from +// the objects that are clipped. The cut faces are filled ("capped") with +// the stencil buffer: each clipped object is drawn once more into the +// stencil only, inverting it per surface, so the pixels where the plane +// lies inside the solid end with an odd count; a quad on the plane is then +// drawn where the stencil is set, which also clears it. +// +// In the hidden-line display mode faces are filled with the background, so +// they only hide what is behind them; the hidden edges are drawn again as +// faint dashes where the depth test fails, and section caps are hatched. + +struct Camera { + view_proj: mat4x4, + // xyz: eye position; w: 1 for perspective projection, 0 for orthographic. + eye: vec4, + forward: vec4, + right: vec4, + up: vec4, + // Width and height in pixels, then their reciprocals. + viewport: vec4, + background_top: vec4, + background_bottom: vec4, + // xyz: normal of the section plane; w: its offset d. + clip_plane: vec4, + // x: 1 while a section plane is active. + section: vec4, + // Corners of the quad covering the section plane around the scene. + cap_corners: array, 4>, + // xy: offset of this pass in the whole image (large captures are drawn + // in tiles); zw: size of the whole image, in pixels. + frame: vec4, + // xyz: direction of the key light in the camera's frame (right, up, + // towards the viewer). + key_light: vec4, + // Strength of the key, fill, ambient and rim lights. + light_levels: vec4, + // x: highlight strength; y: shininess; z: exposure factor; w: contrast. + finish: vec4, +}; + +struct Object { + model: mat4x4, + face_color: vec4, + edge_color: vec4, + // rgb: highlight color; a: how strongly faces are tinted with it. + highlight: vec4, + // x: edge width (px); y: point diameter (px); z: 1 when the section + // plane clips this object; w: 1 to fill faces with the background + // (hidden-line mode). + params: vec4, + // x: edges whose faces meet at a smaller angle (degrees) are left out. + edge_filter: vec4, + // x: shading model (0 plain, 1 physically based, 2 the same with a + // wood grain); y: metalness; z: roughness. + surface: vec4, +}; + +@group(0) @binding(0) var camera: Camera; +@group(1) @binding(0) var object: Object; + +// Whether the section plane removes this point of the current object. +fn is_cut_away(world: vec3) -> bool { + return camera.section.x > 0.5 && object.params.z > 0.5 + && dot(camera.clip_plane.xyz, world) > camera.clip_plane.w; +} + +// The background behind a fragment at framebuffer row `y`, alpha included +// (0 for captures with a transparent background). +fn background_at(y: f32) -> vec4 { + let height = clamp(1.0 - (y + camera.frame.y) / camera.frame.w, 0.0, 1.0); + return mix(camera.background_bottom, camera.background_top, height); +} + +fn fills_with_background() -> bool { + return object.params.w > 0.5; +} + +// Normal facing the viewer, for two-sided lighting. +fn facing_normal(normal: vec3, world: vec3) -> vec3 { + var to_eye = -camera.forward.xyz; + if (camera.eye.w > 0.5) { + to_eye = normalize(camera.eye.xyz - world); + } + var n = normal; + let length_n = length(n); + if (length_n < 1e-6) { + n = to_eye; + } else { + n = n / length_n; + } + // Light both sides: open shells and inverted faces look the same as + // closed solids. + if (dot(n, to_eye) < 0.0) { + n = -n; + } + return n; +} + +// Three-point lighting attached to the camera, as the lighting settings +// say: a key light (from the upper left by default), a dimmer fill from the +// lower right and a little rim light. +fn lit(base: vec3, n: vec3, world: vec3) -> vec3 { + var to_eye = -camera.forward.xyz; + if (camera.eye.w > 0.5) { + to_eye = normalize(camera.eye.xyz - world); + } + let back = -camera.forward.xyz; + let key = normalize( + camera.key_light.x * camera.right.xyz + camera.key_light.y * camera.up.xyz + + camera.key_light.z * back, + ); + let fill = normalize(0.65 * camera.right.xyz - 0.25 * camera.up.xyz + 0.72 * back); + let levels = camera.light_levels; + let diffuse = levels.x * max(dot(n, key), 0.0) + levels.y * max(dot(n, fill), 0.0); + let rim = levels.w * pow(1.0 - max(dot(n, to_eye), 0.0), 3.0); + let half_vector = normalize(key + to_eye); + let specular = camera.finish.x * pow(max(dot(n, half_vector), 0.0), camera.finish.y); + return finished(base * (levels.z + diffuse) + vec3(specular + rim)); +} + +// The object's shading model: the plain one, or a material. +fn shaded(base: vec3, n: vec3, world: vec3) -> vec3 { + if (object.surface.x > 0.5) { + return lit_material(base, n, world, object.surface.y, object.surface.z); + } + return lit(base, n, world); +} + +const PI: f32 = 3.14159265; + +// GGX distribution of microfacet normals. +fn ggx(n_dot_h: f32, alpha: f32) -> f32 { + let a2 = alpha * alpha; + let d = n_dot_h * n_dot_h * (a2 - 1.0) + 1.0; + return a2 / (PI * d * d); +} + +// Shadowing of microfacets (Smith, with the Schlick approximation). +fn smith(n_dot_v: f32, n_dot_l: f32, roughness: f32) -> f32 { + let k = (roughness + 1.0) * (roughness + 1.0) / 8.0; + return n_dot_v / (n_dot_v * (1.0 - k) + k) * n_dot_l / (n_dot_l * (1.0 - k) + k); +} + +fn fresnel(f0: vec3, cosine: f32) -> vec3 { + return f0 + (vec3(1.0) - f0) * pow(1.0 - clamp(cosine, 0.0, 1.0), 5.0); +} + +// A photo studio around the model, attached to the camera like the lights, +// for what metals and glossy surfaces reflect: bright above, darker below, +// a soft box where the key light is. Rough surfaces see it blurred. +fn studio(direction: vec3, key: vec3, roughness: f32) -> vec3 { + let height = dot(direction, camera.up.xyz); + let sky = mix(0.16, 1.0, smoothstep(-0.4, 0.7, height)); + let spread = mix(300.0, 4.0, roughness); + let softbox = pow(max(dot(direction, key), 0.0), spread) * mix(3.0, 0.3, roughness); + return vec3(mix(sky + softbox, 0.55, roughness * roughness)); +} + +// The same lights as the plain shading, for a material of the given +// metalness and roughness: microfacet highlights (scaled by the Highlights +// setting, 1 at its default), a diffuse part that metals lack, and +// reflections of the studio, which the ambient light sets. +fn lit_material( + base: vec3, + n: vec3, + world: vec3, + metallic: f32, + roughness: f32, +) -> vec3 { + var to_eye = -camera.forward.xyz; + if (camera.eye.w > 0.5) { + to_eye = normalize(camera.eye.xyz - world); + } + let back = -camera.forward.xyz; + let key = normalize( + camera.key_light.x * camera.right.xyz + camera.key_light.y * camera.up.xyz + + camera.key_light.z * back, + ); + let fill = normalize(0.65 * camera.right.xyz - 0.25 * camera.up.xyz + 0.72 * back); + let levels = camera.light_levels; + let alpha = max(roughness * roughness, 0.002); + let f0 = mix(vec3(0.04), base, metallic); + let diffuse = base * (1.0 - metallic); + let n_dot_v = max(dot(n, to_eye), 1e-3); + let highlights = camera.finish.x / 0.22; + + var color = vec3(0.0); + var lights = array, 2>(vec4(key, levels.x), vec4(fill, levels.y)); + for (var i = 0; i < 2; i++) { + let light = lights[i].xyz; + let n_dot_l = dot(n, light); + if (n_dot_l > 0.0) { + let half_vector = normalize(light + to_eye); + let f = fresnel(f0, dot(half_vector, to_eye)); + let specular = ggx(max(dot(n, half_vector), 0.0), alpha) + * smith(n_dot_v, n_dot_l, roughness) / (4.0 * n_dot_v * n_dot_l); + color += lights[i].w * n_dot_l + * ((vec3(1.0) - f) * diffuse + PI * specular * f * highlights); + } + } + + // Fresnel with roughness for the reflections; a sky above for the + // diffuse ambient light. + let grazing = pow(1.0 - n_dot_v, 5.0); + let f_ambient = f0 + (max(vec3(1.0 - roughness), f0) - f0) * grazing; + let sky_light = 0.8 + 0.2 * dot(n, camera.up.xyz); + let reflected = studio(reflect(-to_eye, n), key, roughness); + color += levels.z * (diffuse * sky_light * (vec3(1.0) - f_ambient) + + reflected * f_ambient * 2.4); + color += vec3(levels.w * pow(1.0 - n_dot_v, 3.0) * (1.0 - 0.5 * roughness)); + return finished(color); +} + +// Hash of a point in space, in 0..1 (no trigonometry, so it is the same +// on every GPU). +fn hash(point: vec3) -> f32 { + var q = fract(point * vec3(0.1031, 0.1030, 0.0973)); + q += dot(q, q.yzx + 33.33); + return fract((q.x + q.y) * q.z); +} + +// Smooth value noise in 0..1. +fn noise(point: vec3) -> f32 { + let cell = floor(point); + let t = fract(point); + let w = t * t * (3.0 - 2.0 * t); + let x00 = mix(hash(cell), hash(cell + vec3(1.0, 0.0, 0.0)), w.x); + let x10 = mix(hash(cell + vec3(0.0, 1.0, 0.0)), hash(cell + vec3(1.0, 1.0, 0.0)), w.x); + let x01 = mix(hash(cell + vec3(0.0, 0.0, 1.0)), hash(cell + vec3(1.0, 0.0, 1.0)), w.x); + let x11 = mix(hash(cell + vec3(0.0, 1.0, 1.0)), hash(cell + vec3(1.0, 1.0, 1.0)), w.x); + return mix(mix(x00, x10, w.y), mix(x01, x11, w.y), w.z); +} + +// Wood of the color `light` around the part's Z axis: growth rings about +// 2.5 units apart, wavering, darker latewood, and a fine grain along Z. +fn wood(local: vec3, light: vec3) -> vec3 { + let p = local * 0.4; + let wobble = noise(p * vec3(0.5, 0.5, 0.06)) * 0.9; + let ring = fract(length(p.xy) + wobble); + let latewood = smoothstep(0.55, 0.85, ring) * (1.0 - smoothstep(0.9, 1.0, ring)); + let grain = noise(local * vec3(4.0, 4.0, 0.25)); + let dark = light * vec3(0.62, 0.52, 0.44); + return mix(light, dark, clamp(latewood * 0.7 + grain * 0.2, 0.0, 1.0)); +} + +// Exposure, then contrast around middle grey (0.18 in linear light). Both +// leave the color as it is at their defaults (1 and 1). +fn finished(color: vec3) -> vec3 { + let exposed = max(color * camera.finish.z, vec3(0.0)); + return 0.18 * pow(exposed / 0.18, vec3(camera.finish.w)); +} + +// --- Background --------------------------------------------------------- + +struct BackgroundOut { + @builtin(position) position: vec4, +}; + +@vertex +fn vs_background(@builtin(vertex_index) index: u32) -> BackgroundOut { + // One triangle covering the whole viewport. + let uv = vec2(f32((index << 1u) & 2u), f32(index & 2u)); + var out: BackgroundOut; + out.position = vec4(uv * 2.0 - 1.0, 0.0, 1.0); + return out; +} + +@fragment +fn fs_background(in: BackgroundOut) -> @location(0) vec4 { + return background_at(in.position.y); +} + +// --- Faces -------------------------------------------------------------- + +struct MeshIn { + @location(0) position: vec3, + @location(1) normal: vec3, + @location(2) face_color: u32, +}; + +struct MeshOut { + @builtin(position) clip: vec4, + @location(0) world: vec3, + @location(1) normal: vec3, + // In the part's own frame, for the wood grain. + @location(2) local: vec3, + @location(3) @interpolate(flat) face_color: u32, +}; + +@vertex +fn vs_mesh(in: MeshIn) -> MeshOut { + var out: MeshOut; + let world = object.model * vec4(in.position, 1.0); + out.clip = camera.view_proj * world; + out.world = world.xyz; + let rotation = mat3x3(object.model[0].xyz, object.model[1].xyz, object.model[2].xyz); + out.normal = rotation * in.normal; + out.local = in.position; + out.face_color = in.face_color; + return out; +} + +@fragment +fn fs_mesh(in: MeshOut) -> @location(0) vec4 { + if (is_cut_away(in.world)) { + discard; + } + if (fills_with_background()) { + let background = background_at(in.clip.y); + let tint = object.highlight.a * 0.5; + return vec4( + mix(background.rgb, object.highlight.rgb, tint), + mix(background.a, 1.0, tint), + ); + } + let n = facing_normal(in.normal, in.world); + var color = object.face_color.rgb; + if (in.face_color != 0u) { + let srgb = vec3( + f32(in.face_color & 255u), + f32((in.face_color >> 8u) & 255u), + f32((in.face_color >> 16u) & 255u), + ) / 255.0; + color = select(srgb / 12.92, pow((srgb + 0.055) / 1.055, vec3(2.4)), srgb > vec3(0.04045)); + } + if (object.surface.x > 1.5) { + color = wood(in.local, color); + } + let base = mix(color, object.highlight.rgb, object.highlight.a); + return vec4(shaded(base, n, in.world), object.face_color.a); +} + +// Counts the object's remaining surfaces into the stencil; no color. +@fragment +fn fs_section_count(in: MeshOut) { + if (is_cut_away(in.world)) { + discard; + } +} + +// --- Section caps ------------------------------------------------------- + +struct CapOut { + @builtin(position) clip: vec4, + @location(0) world: vec3, +}; + +@vertex +fn vs_cap(@builtin(vertex_index) index: u32) -> CapOut { + var corner_of = array(0u, 1u, 2u, 0u, 2u, 3u); + let world = camera.cap_corners[corner_of[index]].xyz; + var out: CapOut; + out.clip = camera.view_proj * vec4(world, 1.0); + out.world = world; + return out; +} + +@fragment +fn fs_cap(in: CapOut) -> @location(0) vec4 { + if (fills_with_background()) { + // Hatched, as a section on a drawing, as wide apart as the edges + // are wide. + let spacing = max(object.params.x, 1.0) * 5.0; + let position = in.clip.xy + camera.frame.xy; + if (fract((position.x + position.y) / spacing) < 0.2) { + return vec4(object.edge_color.rgb, 1.0); + } + return background_at(in.clip.y); + } + // A little darker than the outside, so the cut reads as a cut. + let n = facing_normal(camera.clip_plane.xyz, in.world); + let base = mix(object.face_color.rgb, object.highlight.rgb, object.highlight.a) * 0.78; + return vec4(shaded(base, n, in.world), object.face_color.a); +} + +// --- Edges -------------------------------------------------------------- + +struct SegmentIn { + @location(0) start: vec3, + @location(1) end: vec3, + // Degrees between the faces that meet at the edge; 180 for an outline. + @location(2) angle: f32, +}; + +// Pulls a clip-space point in front of the near plane, along the segment. +fn clip_to_near(point: vec4, other: vec4) -> vec4 { + let min_w = 1e-5; + if (point.w >= min_w || camera.eye.w < 0.5) { + return point; + } + let t = (min_w - point.w) / (other.w - point.w); + return mix(point, other, t); +} + +struct EdgeOut { + @builtin(position) clip: vec4, + @location(0) world: vec3, + // Pixels from the start of the segment, for dashes. + @location(1) @interpolate(linear) along_px: f32, +}; + +// A vertex outside the view, for edges that are left out: all six land on +// it, so nothing is drawn. +fn left_out() -> EdgeOut { + var out: EdgeOut; + out.clip = vec4(0.0, 0.0, 2.0, 1.0); + out.world = vec3(0.0); + out.along_px = 0.0; + return out; +} + +@vertex +fn vs_edge(@builtin(vertex_index) index: u32, in: SegmentIn) -> EdgeOut { + if (in.angle < object.edge_filter.x) { + return left_out(); + } + return edge_quad(index, object.model * vec4(in.start, 1.0), object.model * vec4(in.end, 1.0)); +} + +struct SilhouetteIn { + @location(0) start: vec3, + @location(1) end: vec3, + // Normals of the two triangles that share the edge. + @location(2) normal_a: vec3, + @location(3) normal_b: vec3, +}; + +// A mesh edge drawn where one of its triangles faces the camera and the +// other faces away: the outline of a curved surface. +@vertex +fn vs_silhouette(@builtin(vertex_index) index: u32, in: SilhouetteIn) -> EdgeOut { + let start_world = object.model * vec4(in.start, 1.0); + let end_world = object.model * vec4(in.end, 1.0); + var to_eye = -camera.forward.xyz; + if (camera.eye.w > 0.5) { + to_eye = camera.eye.xyz - 0.5 * (start_world.xyz + end_world.xyz); + } + let rotation = mat3x3(object.model[0].xyz, object.model[1].xyz, object.model[2].xyz); + let facing_a = dot(rotation * in.normal_a, to_eye); + let facing_b = dot(rotation * in.normal_b, to_eye); + if (facing_a * facing_b > 0.0) { + return left_out(); + } + return edge_quad(index, start_world, end_world); +} + +// The two triangles of a segment from `start_world` to `end_world`, +// expanded to the edge width in screen space. +fn edge_quad(index: u32, start_world: vec4, end_world: vec4) -> EdgeOut { + let start_raw = camera.view_proj * start_world; + let end_raw = camera.view_proj * end_world; + let start = clip_to_near(start_raw, end_raw); + let end = clip_to_near(end_raw, start_raw); + + let half_size = camera.viewport.xy * 0.5; + let start_px = start.xy / start.w * half_size; + let end_px = end.xy / end.w * half_size; + var along = end_px - start_px; + let length_px = length(along); + if (length_px > 1e-4) { + along = along / length_px; + } else { + along = vec2(1.0, 0.0); + } + let across = vec2(-along.y, along.x); + + // Two triangles: (start,-), (end,-), (end,+), (start,-), (end,+), (start,+). + var at_end = array(0.0, 1.0, 1.0, 0.0, 1.0, 0.0); + var side = array(-1.0, -1.0, 1.0, -1.0, 1.0, 1.0); + let t = at_end[index]; + var clip = mix(start, end, t); + let half_width = object.params.x * 0.5; + // Extending past the endpoints by half a width gives square caps that + // close the gaps between consecutive segments. + let offset_px = across * side[index] * half_width + along * (t * 2.0 - 1.0) * half_width; + clip = vec4(clip.xy + offset_px * camera.viewport.zw * 2.0 * clip.w, clip.zw); + var out: EdgeOut; + out.clip = clip; + out.world = mix(start_world.xyz, end_world.xyz, t); + out.along_px = t * length_px + (t * 2.0 - 1.0) * half_width; + return out; +} + +@fragment +fn fs_edge(in: EdgeOut) -> @location(0) vec4 { + if (is_cut_away(in.world)) { + discard; + } + return object.edge_color; +} + +// Edges behind faces, in hidden-line mode: faint dashes. +@fragment +fn fs_hidden_edge(in: EdgeOut) -> @location(0) vec4 { + let period = max(object.params.x, 1.0) * 6.5; + if (is_cut_away(in.world) || fract(in.along_px / period) > 0.55) { + discard; + } + return vec4(object.edge_color.rgb, object.edge_color.a * 0.45); +} + +// --- Points ------------------------------------------------------------- + +struct PointOut { + @builtin(position) clip: vec4, + @location(0) local: vec2, + @location(1) world: vec3, +}; + +@vertex +fn vs_point(@builtin(vertex_index) index: u32, @location(0) position: vec3) -> PointOut { + var corners = array, 6>( + vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), + vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0), + ); + let corner = corners[index]; + let world = object.model * vec4(position, 1.0); + var clip = camera.view_proj * world; + let radius_px = object.params.y * 0.5; + clip = vec4(clip.xy + corner * radius_px * camera.viewport.zw * 2.0 * clip.w, clip.zw); + var out: PointOut; + out.clip = clip; + out.local = corner; + out.world = world.xyz; + return out; +} + +@fragment +fn fs_point(in: PointOut) -> @location(0) vec4 { + if (dot(in.local, in.local) > 1.0 || is_cut_away(in.world)) { + discard; + } + return object.edge_color; +} diff --git a/src/viewer/shadow.rs b/src/viewer/shadow.rs new file mode 100644 index 000000000..79a930c17 --- /dev/null +++ b/src/viewer/shadow.rs @@ -0,0 +1,577 @@ +//! The soft shadow a model casts on the ground in the Presentation mode, +//! the contact shadow of a product photograph (`shadow.wgsl`). +//! +//! It does not depend on the camera: the faces are drawn once from straight +//! above, blurred, and laid on the ground under the model, so the shadow is +//! the same in every view, in every tile of a large capture and for both +//! eyes of the stereo projection. It is drawn again only when the shadowed +//! items or the settings change. + +use std::hash::{Hash, Hasher}; + +use bytemuck::{Pod, Zeroable}; +use eframe::egui_wgpu::wgpu; +use glam::camera::rh::{proj::directx, view}; +use glam::{Mat4, Vec3}; + +use super::renderer::{DrawItem, Layer, MeshVertex}; +use crate::scene::Aabb; + +/// Side of the occlusion textures, in texels. +const SIZE: u32 = 256; +/// Red: the contact shadow; green: the ambient one. +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rg8Unorm; +/// How far the shadow spreads past the model (the standard deviation of its +/// blur) as a fraction of the model's width, from crisp (softness 0) to very +/// soft (1): a dark contact shadow where the model meets the ground, and a +/// wide, faint ambient one around it. +const CONTACT: [f32; 2] = [0.015, 0.06]; +const AMBIENT: [f32; 2] = [0.06, 0.3]; +/// The square of ground under the model is this many times as wide as the +/// model: room for the softest ambient shadow on each side. +const SIDE: f32 = 1.0 + 6.0 * AMBIENT[1]; + +/// A shadow on the ground, as the Presentation settings ask for it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GroundShadow { + /// Darkness where the model touches the ground, 0 to 1. + pub strength: f32, + /// How far the edge spreads, 0 (crisp) to 1 (very soft). + pub softness: f32, +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct ViewUniform { + view_proj: [[f32; 4]; 4], + ground: [f32; 4], +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct BlurUniform { + step: [f32; 4], + spread: [f32; 4], +} + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +struct FloorUniform { + area: [f32; 4], + look: [f32; 4], +} + +/// Where the shadow lies: a square of the ground under the model. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ShadowArea { + /// The corner with the smallest x and y. + pub corner: [f32; 2], + pub side: f32, + /// Height of the ground: the bottom of the model. + pub ground: f32, + /// Faces this far above the ground no longer cast a shadow. + pub fade: f32, +} + +impl ShadowArea { + /// The square of ground around `bounds` (world space, Z up) that the + /// shadow of a model with those bounds needs, its edge blur included. + pub fn around(bounds: Aabb) -> Option { + let size = bounds.size(); + if !size.is_finite() || bounds.is_empty() { + return None; + } + let across = size.x.max(size.y).max(size.z * 0.25).max(1e-3); + let side = across * SIDE; + let center = bounds.center(); + Some(Self { + corner: [center.x - side * 0.5, center.y - side * 0.5], + side, + ground: bounds.min.z, + fade: (size.z * 0.6).max(across * 0.15), + }) + } + + /// Looking straight down at the square, +Y up. + fn view_projection(&self) -> Mat4 { + let half = self.side * 0.5; + let center = Vec3::new(self.corner[0] + half, self.corner[1] + half, 0.0); + let top = self.ground + self.fade * 4.0 + self.side; + let view = view::look_to_mat4(Vec3::new(center.x, center.y, top), Vec3::NEG_Z, Vec3::Y); + // Everything from just under the ground to far above it. + let depth = top - self.ground + self.side; + directx::orthographic(-half, half, -half, half, 0.0, depth) * view + } +} + +/// The items whose faces cast the shadow: the model's opaque enough faces. +pub fn casts_shadow(item: &DrawItem) -> bool { + item.layer == Layer::Scene + && item.style.faces + && !item.style.background_fill + && item.style.face_color[3] >= 0.3 + && !item.mesh.indices.is_empty() +} + +/// The world bounds of the items that cast the shadow. +pub fn shadow_bounds(items: &[DrawItem]) -> Aabb { + items + .iter() + .filter(|item| casts_shadow(item)) + .fold(Aabb::EMPTY, |bounds, item| { + bounds.union(item.mesh.bounds.transformed(item.transform)) + }) +} + +/// What the shadow was drawn from, to know when to draw it again. +fn shadow_key(items: &[DrawItem], area: &ShadowArea, shadow: &GroundShadow) -> u64 { + let mut hasher = std::hash::DefaultHasher::new(); + for item in items.iter().filter(|item| casts_shadow(item)) { + item.mesh.id.hash(&mut hasher); + for value in item.transform.to_cols_array() { + value.to_bits().hash(&mut hasher); + } + } + for value in [ + area.corner[0], + area.corner[1], + area.side, + area.ground, + area.fade, + shadow.softness, + ] { + value.to_bits().hash(&mut hasher); + } + hasher.finish() +} + +/// The GPU side: pipelines, the two occlusion textures (drawn into, then +/// blurred back and forth) and the floor's bind group. +pub struct ShadowPass { + occlusion: wgpu::RenderPipeline, + blur: wgpu::RenderPipeline, + floor: wgpu::RenderPipeline, + view_buffer: wgpu::Buffer, + view_group: wgpu::BindGroup, + blur_buffers: [wgpu::Buffer; 2], + blur_groups: [wgpu::BindGroup; 2], + floor_buffer: wgpu::Buffer, + floor_group: wgpu::BindGroup, + textures: [wgpu::TextureView; 2], + /// What the textures hold now. + key: Option, + area: Option, +} + +impl ShadowPass { + /// `object_layout` is the scene's per-item uniform block, whose model + /// matrix places the faces; `camera_buffer` the scene's camera, which + /// places the floor; `samples` and `depth_format` those of the scene + /// pass the floor is drawn in. + pub fn new( + device: &wgpu::Device, + object_layout: &wgpu::BindGroupLayout, + camera_buffer: &wgpu::Buffer, + color_format: wgpu::TextureFormat, + depth_format: wgpu::TextureFormat, + samples: u32, + ) -> Self { + let shader = device.create_shader_module(wgpu::include_wgsl!("shadow.wgsl")); + let uniform = |binding, stage| wgpu::BindGroupLayoutEntry { + binding, + visibility: stage, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }; + let texture = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }; + let sampler = |binding| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }; + let layout = |label, entries: &[wgpu::BindGroupLayoutEntry]| { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some(label), + entries, + }) + }; + let view_layout = layout( + "shadow view", + &[uniform(0, wgpu::ShaderStages::VERTEX_FRAGMENT)], + ); + let blur_layout = layout( + "shadow blur", + &[ + texture(1), + sampler(2), + uniform(3, wgpu::ShaderStages::FRAGMENT), + ], + ); + let floor_layout = layout( + "shadow floor", + &[ + uniform(4, wgpu::ShaderStages::VERTEX), + texture(5), + sampler(6), + uniform(7, wgpu::ShaderStages::VERTEX_FRAGMENT), + ], + ); + + let pipeline = |label, + layouts: &[Option<&wgpu::BindGroupLayout>], + vertex: &str, + fragment: &str, + buffers: &[Option>], + target: wgpu::ColorTargetState, + depth: Option, + samples: u32, + cull_mode: Option| { + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some(label), + bind_group_layouts: layouts, + immediate_size: 0, + }); + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some(vertex), + compilation_options: Default::default(), + buffers, + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(fragment), + compilation_options: Default::default(), + targets: &[Some(target)], + }), + primitive: wgpu::PrimitiveState { + cull_mode, + ..Default::default() + }, + depth_stencil: depth, + multisample: wgpu::MultisampleState { + count: samples, + ..Default::default() + }, + multiview_mask: None, + cache: None, + }) + }; + let max = wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Max, + }; + // Positions of the scene's interleaved vertices. + let positions = [Some(wgpu::VertexBufferLayout { + array_stride: size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![0 => Float32x3], + })]; + let occlusion = pipeline( + "shadow occlusion", + &[Some(&view_layout), Some(object_layout)], + "vs_occlusion", + "fs_occlusion", + &positions, + wgpu::ColorTargetState { + format: FORMAT, + blend: Some(wgpu::BlendState { + color: max, + alpha: max, + }), + write_mask: wgpu::ColorWrites::ALL, + }, + None, + 1, + None, + ); + let blur = pipeline( + "shadow blur", + &[Some(&blur_layout)], + "vs_fullscreen", + "fs_blur", + &[], + wgpu::ColorTargetState { + format: FORMAT, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + }, + None, + 1, + None, + ); + let floor = pipeline( + "shadow floor", + &[Some(&floor_layout)], + "vs_floor", + "fs_floor", + &[], + wgpu::ColorTargetState { + format: color_format, + blend: Some(wgpu::BlendState::ALPHA_BLENDING), + write_mask: wgpu::ColorWrites::ALL, + }, + // Behind the model, which hides it; written nowhere. + Some(wgpu::DepthStencilState { + format: depth_format, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::Less), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + samples, + // Seen from under the ground, it would cover the model's bottom. + Some(wgpu::Face::Back), + ); + + let buffer = |label, size: usize| { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: size as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) + }; + let view_buffer = buffer("shadow view", size_of::()); + let blur_buffers = [ + buffer("shadow blur across", size_of::()), + buffer("shadow blur along", size_of::()), + ]; + let floor_buffer = buffer("shadow floor", size_of::()); + let textures = [0, 1].map(|_| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some("shadow occlusion"), + size: wgpu::Extent3d { + width: SIZE, + height: SIZE, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&wgpu::TextureViewDescriptor::default()) + }); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("shadow"), + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let view_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("shadow view"), + layout: &view_layout, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: view_buffer.as_entire_binding(), + }], + }); + // Across: from the drawn texture into the other; along: back. + let blur_group = |source: &wgpu::TextureView, buffer: &wgpu::Buffer| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("shadow blur"), + layout: &blur_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(source), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + wgpu::BindGroupEntry { + binding: 3, + resource: buffer.as_entire_binding(), + }, + ], + }) + }; + let blur_groups = [ + blur_group(&textures[0], &blur_buffers[0]), + blur_group(&textures[1], &blur_buffers[1]), + ]; + let floor_group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("shadow floor"), + layout: &floor_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 4, + resource: camera_buffer.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 5, + resource: wgpu::BindingResource::TextureView(&textures[0]), + }, + wgpu::BindGroupEntry { + binding: 6, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + wgpu::BindGroupEntry { + binding: 7, + resource: floor_buffer.as_entire_binding(), + }, + ], + }); + Self { + occlusion, + blur, + floor, + view_buffer, + view_group, + blur_buffers, + blur_groups, + floor_buffer, + floor_group, + textures, + key: None, + area: None, + } + } + + /// Draws the occlusion of `items` again when they or the settings + /// changed, and updates the floor. `draw_faces` draws an item's faces in + /// a pass with the occlusion pipeline set (the scene's own object + /// uniforms place them). Returns whether there is a shadow to draw. + pub fn update( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + items: &[DrawItem], + shadow: &GroundShadow, + draw_faces: impl Fn(&mut wgpu::RenderPass<'_>, usize), + ) -> bool { + let Some(area) = ShadowArea::around(shadow_bounds(items)) else { + self.area = None; + return false; + }; + let floor = FloorUniform { + // Just under the bottom faces, so they keep the depth test. + area: [ + area.corner[0], + area.corner[1], + area.side, + area.ground - area.side * 1e-3, + ], + look: [shadow.strength.clamp(0.0, 1.0), 0.0, 0.0, 0.0], + }; + queue.write_buffer(&self.floor_buffer, 0, bytemuck::bytes_of(&floor)); + self.area = Some(area); + let key = shadow_key(items, &area, shadow); + if self.key == Some(key) { + return true; + } + self.key = Some(key); + + queue.write_buffer( + &self.view_buffer, + 0, + bytemuck::bytes_of(&ViewUniform { + view_proj: area.view_projection().to_cols_array_2d(), + ground: [area.ground, area.fade, 0.0, 0.0], + }), + ); + // The square is as many times as wide as the model whatever its + // size, so the spread in texels depends on the softness alone. + let softness = shadow.softness.clamp(0.0, 1.0); + let texels = + |[crisp, soft]: [f32; 2]| (crisp + (soft - crisp) * softness) / SIDE * SIZE as f32; + let (contact, ambient) = (texels(CONTACT), texels(AMBIENT)); + let texel = 1.0 / SIZE as f32; + for (buffer, step) in self.blur_buffers.iter().zip([[texel, 0.0], [0.0, texel]]) { + queue.write_buffer( + buffer, + 0, + bytemuck::bytes_of(&BlurUniform { + step: [step[0], step[1], 0.0, 0.0], + spread: [contact, ambient, (ambient * 3.0).ceil(), 0.0], + }), + ); + } + + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("ground shadow"), + }); + { + let mut occlusion = texture_pass(&mut encoder, &self.textures[0], "shadow occlusion"); + occlusion.set_pipeline(&self.occlusion); + occlusion.set_bind_group(0, &self.view_group, &[]); + for (index, item) in items.iter().enumerate() { + if casts_shadow(item) { + draw_faces(&mut occlusion, index); + } + } + } + for (source, target, label) in [(0, 1, "shadow blur across"), (1, 0, "shadow blur along")] { + let mut blur = texture_pass(&mut encoder, &self.textures[target], label); + blur.set_pipeline(&self.blur); + blur.set_bind_group(0, &self.blur_groups[source], &[]); + blur.draw(0..3, 0..1); + } + queue.submit([encoder.finish()]); + true + } + + /// Draws the floor in the scene pass. It replaces the bind group 0 of + /// the pass, which the caller sets back. + pub fn draw_floor(&self, pass: &mut wgpu::RenderPass<'_>) { + if self.area.is_none() { + return; + } + pass.set_pipeline(&self.floor); + pass.set_bind_group(0, &self.floor_group, &[]); + pass.draw(0..6, 0..1); + } +} + +/// A pass drawing into `view`, cleared first. +fn texture_pass<'a>( + encoder: &'a mut wgpu::CommandEncoder, + view: &'a wgpu::TextureView, + label: &'a str, +) -> wgpu::RenderPass<'a> { + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(label), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), + store: wgpu::StoreOp::Store, + }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }) +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_shadow.rs"] +mod tests; diff --git a/src/viewer/shadow.wgsl b/src/viewer/shadow.wgsl new file mode 100644 index 000000000..74eef6116 --- /dev/null +++ b/src/viewer/shadow.wgsl @@ -0,0 +1,150 @@ +// The soft shadow a model casts on the ground in the Presentation mode. +// +// 1. Occlusion: the faces of the model are drawn from straight above into a +// two-channel texture. Each texel keeps (by max blending) how close to +// the ground the lowest face over it is: 1 where it touches the ground, +// 0 at the fade height and above. +// 2. Blur: two passes, across and then along, soften the edges: a little in +// the red channel, for the contact shadow, much in the green one, for +// the ambient shadow. +// 3. Floor: a quad on the ground under the model, drawn in the scene pass +// after the opaque faces, darkens the background by both shadows; the +// depth test keeps it behind the model. +// +// The passes use distinct bindings, as they share this module. + +// --- Occlusion ------------------------------------------------------------ + +struct ShadowView { + view_proj: mat4x4, + // x: ground height; y: fade height. + ground: vec4, +}; + +// The first member of the scene's object block (`shaders.wgsl`). +struct Object { + model: mat4x4, +}; + +@group(0) @binding(0) var shadow_view: ShadowView; +@group(1) @binding(0) var object: Object; + +struct OcclusionOut { + @builtin(position) clip: vec4, + @location(0) height: f32, +}; + +@vertex +fn vs_occlusion(@location(0) position: vec3) -> OcclusionOut { + let world = object.model * vec4(position, 1.0); + var out: OcclusionOut; + out.clip = shadow_view.view_proj * world; + out.height = world.z - shadow_view.ground.x; + return out; +} + +@fragment +fn fs_occlusion(in: OcclusionOut) -> @location(0) vec4 { + let occlusion = clamp(1.0 - in.height / max(shadow_view.ground.y, 1e-6), 0.0, 1.0); + return vec4(occlusion, occlusion, 0.0, 1.0); +} + +// --- Blur ------------------------------------------------------------------- + +struct Blur { + // xy: one texel along the blur, in texture coordinates. + step: vec4, + // The standard deviations, in texels: x of the contact shadow, y of the + // ambient one; z: how many texels are read on each side. + spread: vec4, +}; + +@group(0) @binding(1) var blur_source: texture_2d; +@group(0) @binding(2) var blur_sampler: sampler; +@group(0) @binding(3) var blur: Blur; + +struct FullscreenOut { + @builtin(position) position: vec4, + @location(0) uv: vec2, +}; + +@vertex +fn vs_fullscreen(@builtin(vertex_index) index: u32) -> FullscreenOut { + // One triangle covering the whole texture. + let corner = vec2(f32((index << 1u) & 2u), f32(index & 2u)); + var out: FullscreenOut; + out.position = vec4(corner * 2.0 - 1.0, 0.0, 1.0); + out.uv = vec2(corner.x, 1.0 - corner.y); + return out; +} + +@fragment +fn fs_blur(in: FullscreenOut) -> @location(0) vec4 { + // Two Gaussians read texel by texel, without the bands of sparse taps. + let reach = i32(blur.spread.z); + let deviations = max(blur.spread.xy, vec2(1e-3)); + var total = vec2(0.0); + var weights = vec2(0.0); + for (var i = -reach; i <= reach; i++) { + let offset = f32(i) / deviations; + let weight = exp(-0.5 * offset * offset); + let uv = in.uv + blur.step.xy * f32(i); + total += weight * textureSampleLevel(blur_source, blur_sampler, uv, 0.0).rg; + weights += weight; + } + return vec4(total / weights, 0.0, 1.0); +} + +// --- Floor ------------------------------------------------------------------ + +// The first member of the scene's camera block (`shaders.wgsl`). +struct Camera { + view_proj: mat4x4, +}; + +struct Floor { + // xy: the corner of the shadowed square with the smallest x and y; z: its + // side; w: the height of the floor. + area: vec4, + // x: darkness where the model touches the ground. + look: vec4, +}; + +@group(0) @binding(4) var camera: Camera; +@group(0) @binding(5) var floor_occlusion: texture_2d; +@group(0) @binding(6) var floor_sampler: sampler; +@group(0) @binding(7) var floor: Floor; + +struct FloorOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; + +@vertex +fn vs_floor(@builtin(vertex_index) index: u32) -> FloorOut { + var corners = array, 6>( + vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(1.0, 1.0), + vec2(0.0, 0.0), vec2(1.0, 1.0), vec2(0.0, 1.0), + ); + let corner = corners[index]; + let world = vec3(floor.area.xy + corner * floor.area.z, floor.area.w); + var out: FloorOut; + out.clip = camera.view_proj * vec4(world, 1.0); + // The occlusion texture was drawn looking down with +Y up. + out.uv = vec2(corner.x, 1.0 - corner.y); + return out; +} + +@fragment +fn fs_floor(in: FloorOut) -> @location(0) vec4 { + let shadows = textureSample(floor_occlusion, floor_sampler, in.uv).rg; + // The ambient shadow fades slowly, like the sky the model hides from the + // ground: a long tail rather than the quick end of a Gaussian, smooth down + // to the last levels of the texture. + let ambient = 1.0 - pow(1.0 - shadows.g, 3.0); + let occlusion = 0.45 * shadows.r + 0.55 * ambient; + // Faded out towards the border of the square, never cut off. + let border = smoothstep(vec2(0.0), vec2(0.08), in.uv) + * (vec2(1.0) - smoothstep(vec2(0.92), vec2(1.0), in.uv)); + return vec4(0.0, 0.0, 0.0, occlusion * floor.look.x * border.x * border.y); +} diff --git a/src/viewer/stereo.rs b/src/viewer/stereo.rs new file mode 100644 index 000000000..c28859ed6 --- /dev/null +++ b/src/viewer/stereo.rs @@ -0,0 +1,89 @@ +//! Composing the two eyes of the stereo projection into one image, as the +//! original editor's stereo modes did (FEAT-C8). +//! +//! The live view composes on the GPU (`stereo.wgsl`); captures compose here, +//! from images drawn the usual way (tiles included). The tests check that +//! both give the same pixels. + +use crate::settings::StereoMode; + +/// The size each eye is drawn at for an image of `size` pixels: half of it +/// side by side or over-under, all of it otherwise. +pub fn eye_size(mode: StereoMode, size: [u32; 2]) -> [u32; 2] { + let [width, height] = size.map(|side| side.max(1)); + match mode.shown() { + StereoMode::SideBySide => [width.div_ceil(2), height], + StereoMode::OverUnder => [width, height.div_ceil(2)], + _ => [width, height], + } +} + +/// The mode's number in `stereo.wgsl`. +pub fn shader_mode(mode: StereoMode) -> u32 { + match mode.shown() { + StereoMode::QuadBuffer | StereoMode::Anaglyph => 1, + StereoMode::RowInterlaced => 2, + StereoMode::ColumnInterlaced => 3, + StereoMode::ChessBoard => 4, + StereoMode::SideBySide => 5, + StereoMode::OverUnder => 6, + } +} + +/// Composes `left` and `right`, tightly packed sRGB RGBA images of +/// `eye_size(mode, size)`, into one of `size`. +pub fn compose(mode: StereoMode, size: [u32; 2], left: &[u8], right: &[u8]) -> Vec { + let [width, height] = size.map(|side| side.max(1)); + let [eye_width, eye_height] = eye_size(mode, size); + let pixel = |image: &[u8], x: u32, y: u32| { + let start = ((y * eye_width + x) * 4) as usize; + <[u8; 4]>::try_from(&image[start..start + 4]).expect("in the image") + }; + let linear: Vec = (0..=255u8).map(srgb_to_linear).collect(); + let mut image = Vec::with_capacity((width * height * 4) as usize); + for y in 0..height { + for x in 0..width { + let rgba = match mode.shown() { + StereoMode::QuadBuffer | StereoMode::Anaglyph => { + let (l, r) = (pixel(left, x, y), pixel(right, x, y)); + // Optimized red-cyan, in linear light: the left eye's red + // channel is made of its green and blue, so red objects + // do not flicker between the eyes. + let red = 0.7 * linear[usize::from(l[1])] + 0.3 * linear[usize::from(l[2])]; + [linear_to_srgb(red), r[1], r[2], l[3].max(r[3])] + } + StereoMode::RowInterlaced => pixel(if y % 2 == 0 { left } else { right }, x, y), + StereoMode::ColumnInterlaced => pixel(if x % 2 == 0 { left } else { right }, x, y), + StereoMode::ChessBoard => pixel(if (x + y) % 2 == 0 { left } else { right }, x, y), + StereoMode::SideBySide if x < eye_width => pixel(left, x, y), + StereoMode::SideBySide => pixel(right, x - eye_width, y), + StereoMode::OverUnder if y < eye_height => pixel(left, x, y), + StereoMode::OverUnder => pixel(right, x, y - eye_height), + }; + image.extend(rgba); + } + } + image +} + +fn srgb_to_linear(c: u8) -> f32 { + let c = f32::from(c) / 255.0; + if c <= 0.04045 { + c / 12.92 + } else { + ((c + 0.055) / 1.055).powf(2.4) + } +} + +fn linear_to_srgb(c: f32) -> u8 { + let c = if c <= 0.003_130_8 { + c * 12.92 + } else { + 1.055 * c.powf(1.0 / 2.4) - 0.055 + }; + (c * 255.0).round().clamp(0.0, 255.0) as u8 +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_stereo.rs"] +mod tests; diff --git a/src/viewer/stereo.wgsl b/src/viewer/stereo.wgsl new file mode 100644 index 000000000..a2e24b255 --- /dev/null +++ b/src/viewer/stereo.wgsl @@ -0,0 +1,72 @@ +// Composition of the two eyes of the stereo projection into one image. +// `viewer/stereo.rs` composes the same way on the CPU for captures, and the +// tests compare the two. +// +// Both eyes are read texel by texel (no filtering). The textures are sRGB, +// so the anaglyph mixes in linear light, and the sRGB target encodes again. + +struct Compose { + // 1 anaglyph, 2 rows, 3 columns, 4 chess board, 5 side by side, + // 6 over-under. + mode: u32, + // Size of each eye's image, in pixels. + eye_width: u32, + eye_height: u32, + padding: u32, +}; + +@group(0) @binding(0) var left: texture_2d; +@group(0) @binding(1) var right: texture_2d; +@group(0) @binding(2) var compose: Compose; + +@vertex +fn vs_compose(@builtin(vertex_index) index: u32) -> @builtin(position) vec4 { + // One triangle covering the whole viewport. + let uv = vec2(f32((index << 1u) & 2u), f32(index & 2u)); + return vec4(uv * 2.0 - 1.0, 0.0, 1.0); +} + +@fragment +fn fs_compose(@builtin(position) position: vec4) -> @location(0) vec4 { + let p = vec2(floor(position.xy)); + let eye = vec2(i32(compose.eye_width), i32(compose.eye_height)); + switch compose.mode { + case 1u: { + let l = textureLoad(left, p, 0); + let r = textureLoad(right, p, 0); + // Optimized red-cyan: the left eye's red is made of its green + // and blue, so red objects do not flicker between the eyes. + return vec4(0.7 * l.g + 0.3 * l.b, r.g, r.b, max(l.a, r.a)); + } + case 2u: { + if (p.y % 2 == 0) { + return textureLoad(left, p, 0); + } + return textureLoad(right, p, 0); + } + case 3u: { + if (p.x % 2 == 0) { + return textureLoad(left, p, 0); + } + return textureLoad(right, p, 0); + } + case 4u: { + if ((p.x + p.y) % 2 == 0) { + return textureLoad(left, p, 0); + } + return textureLoad(right, p, 0); + } + case 5u: { + if (p.x < eye.x) { + return textureLoad(left, p, 0); + } + return textureLoad(right, vec2(p.x - eye.x, p.y), 0); + } + default: { + if (p.y < eye.y) { + return textureLoad(left, p, 0); + } + return textureLoad(right, vec2(p.x, p.y - eye.y), 0); + } + } +} diff --git a/src/viewer/views.rs b/src/viewer/views.rs new file mode 100644 index 000000000..f5a2c964d --- /dev/null +++ b/src/viewer/views.rs @@ -0,0 +1,81 @@ +//! Named views: cameras saved under a name with the document, to come back +//! to the same framing (FEAT-C4). + +use glam::{Quat, Vec3}; + +use super::Viewer; +use super::camera::Pose; +use crate::settings::{NamedView, Projection}; + +impl Viewer { + /// Saves where the camera is heading as a named view and returns its + /// name: `name` trimmed, or the first free "View N" without one. A view + /// with the same name is replaced in place. + pub fn save_view(&mut self, name: Option<&str>, projection: Projection) -> String { + let name = match name.map(str::trim).filter(|name| !name.is_empty()) { + Some(name) => name.to_owned(), + None => (1..) + .map(|n| format!("View {n}")) + .find(|name| !self.named_views.iter().any(|view| &view.name == name)) + .expect("a free name"), + }; + let view = capture(name.clone(), self.settled_pose(), projection); + match self.named_views.iter_mut().find(|view| view.name == name) { + Some(existing) => *existing = view, + None => self.named_views.push(view), + } + name + } + + /// Stores where the camera is heading in the view at `index`. + pub fn update_view(&mut self, index: usize, projection: Projection) -> Option<&str> { + let pose = self.settled_pose(); + let view = self.named_views.get_mut(index)?; + *view = capture(std::mem::take(&mut view.name), pose, projection); + Some(&view.name) + } + + pub fn delete_view(&mut self, index: usize) -> Option { + (index < self.named_views.len()).then(|| self.named_views.remove(index)) + } + + /// Moves the camera to the view at `index` and returns the projection + /// it was saved with; `None` for an unknown index or a damaged entry + /// (the settings file is user-editable). + pub fn go_to_view(&mut self, index: usize, animate: bool, now: f64) -> Option { + let view = self.named_views.get(index)?; + let (pose, projection) = (pose_of(view)?, view.projection); + self.animate_to(pose, animate, now); + Some(projection) + } +} + +fn capture(name: String, pose: Pose, projection: Projection) -> NamedView { + NamedView { + name, + target: pose.target.to_array(), + rotation: pose.rotation.normalize().to_array(), + extent: pose.extent, + projection, + } +} + +/// The camera pose of a saved view, if its numbers make one. +fn pose_of(view: &NamedView) -> Option { + let target = Vec3::from_array(view.target); + let rotation = Quat::from_array(view.rotation); + let valid = target.is_finite() + && rotation.is_finite() + && rotation.length() > 1e-3 + && view.extent.is_finite() + && view.extent > 0.0; + valid.then(|| Pose { + target, + rotation: rotation.normalize(), + extent: view.extent, + }) +} + +#[cfg(test)] +#[path = "../../tests/rust/viewer/test_views.rs"] +mod tests; diff --git a/src/worker/launch.rs b/src/worker/launch.rs new file mode 100644 index 000000000..a0724c45c --- /dev/null +++ b/src/worker/launch.rs @@ -0,0 +1,211 @@ +//! Finding a Python interpreter that has CadQuery. + +use std::path::{Path, PathBuf}; + +#[cfg(windows)] +const VENV_PYTHON: &[&str] = &["Scripts", "python.exe"]; +#[cfg(not(windows))] +const VENV_PYTHON: &[&str] = &["bin", "python3"]; + +#[cfg(windows)] +const CONDA_PYTHON: &[&str] = &["python.exe"]; +#[cfg(not(windows))] +const CONDA_PYTHON: &[&str] = &["bin", "python3"]; + +#[cfg(windows)] +const PATH_PYTHON: &str = "python"; +#[cfg(not(windows))] +const PATH_PYTHON: &str = "python3"; + +/// Picks the interpreter, in order of preference: +/// +/// 1. `explicit` (command line or preferences), when not empty; +/// 2. the `CQ_EDITOR_PYTHON` environment variable; +/// 3. the Python bundled by an installed CQ-editor distribution; +/// 4. the active virtual or conda environment (`VIRTUAL_ENV`, `CONDA_PREFIX`); +/// 5. a `.venv` next to the executable, in the working directory or (for +/// development builds) in the source tree; +/// 6. `python`/`python3` from `PATH`. +pub fn find_python(explicit: Option<&str>) -> PathBuf { + if let Some(path) = explicit.map(str::trim).filter(|p| !p.is_empty()) { + return PathBuf::from(path); + } + if let Some(path) = std::env::var_os("CQ_EDITOR_PYTHON") { + return PathBuf::from(path); + } + if let Some(python) = std::env::current_exe() + .ok() + .as_deref() + .and_then(bundled_python_for) + { + return python; + } + + let environments = [ + std::env::var_os("VIRTUAL_ENV").map(|p| (PathBuf::from(p), VENV_PYTHON)), + std::env::var_os("CONDA_PREFIX").map(|p| (PathBuf::from(p), CONDA_PYTHON)), + ]; + for (root, relative) in environments.into_iter().flatten() { + if let Some(python) = existing(&root, relative) { + return python; + } + } + + let mut roots = Vec::new(); + if let Some(dir) = std::env::current_exe() + .ok() + .and_then(|p| p.parent().map(Path::to_path_buf)) + { + roots.push(dir); + } + if let Ok(dir) = std::env::current_dir() { + roots.push(dir); + } + if cfg!(debug_assertions) { + roots.push(PathBuf::from(env!("CARGO_MANIFEST_DIR"))); + } + for root in roots { + if let Some(python) = existing(&root.join(".venv"), VENV_PYTHON) { + return python; + } + } + + PathBuf::from(PATH_PYTHON) +} + +/// The interpreter of the virtual environment in `folder`. +pub fn venv_python(folder: &Path) -> PathBuf { + VENV_PYTHON + .iter() + .fold(folder.to_path_buf(), |path, part| path.join(part)) +} + +/// Interpreters on this computer, for the user to choose from when the +/// detected one has no CadQuery: the places [`find_python`] looks at, conda +/// and mamba environments in the usual folders, Python installs from +/// python.org (Windows) and `python` on `PATH`. Only existing files, each +/// once; whether they have CadQuery is only known by starting them. +pub fn candidates() -> Vec { + let mut found: Vec = Vec::new(); + let mut add = |path: PathBuf| { + if path.is_file() && !found.iter().any(|other| same_path(other, &path)) { + found.push(path); + } + }; + + if let Some(path) = std::env::var_os("CQ_EDITOR_PYTHON") { + add(PathBuf::from(path)); + } + if let Ok(executable) = std::env::current_exe() + && let Some(python) = bundled_python_for(&executable) + { + add(python); + } + for (variable, relative) in [("VIRTUAL_ENV", VENV_PYTHON), ("CONDA_PREFIX", CONDA_PYTHON)] { + if let Some(root) = std::env::var_os(variable) { + add(relative + .iter() + .fold(PathBuf::from(root), |p, part| p.join(part))); + } + } + for root in [std::env::current_dir().ok(), std::env::current_exe().ok()] + .into_iter() + .flatten() + { + for directory in root.ancestors().take(2) { + add(VENV_PYTHON + .iter() + .fold(directory.join(".venv"), |p, part| p.join(part))); + } + } + + let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }); + if let Some(home) = home.map(PathBuf::from) { + for distribution in [ + "miniforge3", + "mambaforge", + "miniconda3", + "anaconda3", + "micromamba", + ] { + environments_in(&home.join(distribution)) + .into_iter() + .for_each(&mut add); + } + } + if cfg!(windows) + && let Some(programs) = std::env::var_os("LOCALAPPDATA") + && let Ok(entries) = + std::fs::read_dir(PathBuf::from(programs).join("Programs").join("Python")) + { + let mut installs: Vec = entries.flatten().map(|entry| entry.path()).collect(); + installs.sort(); + // The newest first. + for install in installs.into_iter().rev() { + add(install.join("python.exe")); + } + } + if let Some(path) = std::env::var_os("PATH") { + for directory in std::env::split_paths(&path) { + // The Microsoft Store placeholder is not an interpreter. + if directory.ends_with("WindowsApps") { + continue; + } + add(directory.join(if cfg!(windows) { + "python.exe" + } else { + PATH_PYTHON + })); + } + } + found +} + +/// Whether two paths name the same file; Windows paths ignore case, so a +/// working directory with a lowercase drive letter adds nothing new. +fn same_path(a: &Path, b: &Path) -> bool { + if cfg!(windows) { + a.to_string_lossy().to_lowercase() == b.to_string_lossy().to_lowercase() + } else { + a == b + } +} + +/// The base interpreter of a conda-like distribution at `root` and those of +/// its environments, sorted by name. +fn environments_in(root: &Path) -> Vec { + let interpreter = |environment: &Path| existing(environment, CONDA_PYTHON); + let mut environments: Vec = std::fs::read_dir(root.join("envs")) + .map(|entries| entries.flatten().map(|entry| entry.path()).collect()) + .unwrap_or_default(); + environments.sort(); + std::iter::once(root.to_path_buf()) + .chain(environments) + .filter_map(|environment| interpreter(&environment)) + .collect() +} + +fn existing(root: &Path, relative: &[&str]) -> Option { + let path = relative + .iter() + .fold(root.to_path_buf(), |path, part| path.join(part)); + path.is_file().then_some(path) +} + +/// Finds the base Python in a constructor installation. On Windows the GUI +/// and `python.exe` live in the prefix root. On Unix the GUI and Python live +/// in `/bin`, so the second candidate is the prefix itself. +fn bundled_python_for(executable: &Path) -> Option { + let executable_dir = executable.parent()?; + [Some(executable_dir), executable_dir.parent()] + .into_iter() + .flatten() + // Do not mistake `/usr/local/bin/python3` for a bundled interpreter + // when someone copies only the portable executable to `/usr/local/bin`. + .filter(|root| root.join(".installer.info").is_file()) + .find_map(|root| existing(root, CONDA_PYTHON)) +} + +#[cfg(test)] +#[path = "../../tests/rust/protocol/test_launch.rs"] +mod tests; diff --git a/src/worker/mod.rs b/src/worker/mod.rs new file mode 100644 index 000000000..6904be67a --- /dev/null +++ b/src/worker/mod.rs @@ -0,0 +1,504 @@ +//! The Python worker process that runs CadQuery. +//! +//! The worker is started as `python -m cq_worker` and speaks the line-based +//! JSON protocol of [`protocol`]. Three helper threads keep the UI thread +//! non-blocking: one writes requests, one parses messages from stdout (mesh +//! decoding included) and one forwards stderr lines to the log. +//! +//! Stopping a runaway script is done by killing the process and starting a +//! fresh one, which is also how the GUI recovers from a crashed worker. + +pub mod launch; +pub mod protocol; + +use std::io::{self, BufRead, BufReader, Write}; +use std::path::PathBuf; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::thread; +use std::time::{Instant, SystemTime}; + +use protocol::{Message, ReadyInfo, Request, RequestId}; + +/// Text, completion and other control messages are expected to stay small. +const MAX_CONTROL_MESSAGE_BYTES: usize = 2 * 1024 * 1024; +/// A rich result may contain one base64-encoded 4 MiB image. +const MAX_DISPLAY_MESSAGE_BYTES: usize = 8 * 1024 * 1024; +/// Mesh-bearing replies need a separate, deliberately larger wire ceiling. +const MAX_MESH_MESSAGE_BYTES: usize = 512 * 1024 * 1024; +/// Native libraries can write directly to stderr, so bound those lines too. +const MAX_STDERR_LINE_BYTES: usize = 256 * 1024; + +/// How to start the worker. +#[derive(Clone, Debug, PartialEq)] +pub struct LaunchConfig { + pub python: PathBuf, + /// Directory containing the `cq_worker` package. + pub worker_dir: PathBuf, +} + +#[derive(Clone, Debug)] +pub enum Status { + NotStarted, + /// Process started, CadQuery still importing. + Starting, + Ready(ReadyInfo), + /// The worker could not start or exited; holds a user-facing reason. + Failed(String), +} + +/// Why the worker is not available, so the first-run dialog can say what +/// to do about it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Problem { + /// The interpreter could not be started at all. + NoPython, + /// Python started but could not import CadQuery. + NoCadQuery, + /// The worker exited before it was ready. + Exited, +} + +/// Windows' `python.exe` placeholder (an App Execution Alias) only offers +/// to install Python from the Microsoft Store and exits with this code. +const STORE_PLACEHOLDER_EXIT_CODE: i32 = 9009; + +/// What an exit before the worker was ready means. +pub fn exit_problem(code: Option) -> Problem { + if cfg!(windows) && code == Some(STORE_PLACEHOLDER_EXIT_CODE) { + Problem::NoPython + } else { + Problem::Exited + } +} + +/// Something that happened in the worker process. +#[derive(Debug)] +pub enum Event { + Message(Message), + /// A line the worker printed on stderr (native library warnings, crashes). + Stderr(String), + /// The worker sent a message that cannot be read, larger than its + /// limit. Nothing it sends afterwards is read, so it must be + /// restarted; this is not a failed start. + ProtocolError(String), + /// The process ended (or its stdout closed). + Exited, +} + +pub struct Worker { + ctx: egui::Context, + config: Option, + process: Option, + status: Status, + /// Set together with [`Status::Failed`]. + problem: Option, + next_id: RequestId, + /// Distinguishes events of the current process from those of killed ones. + generation: u64, + events_tx: Sender<(u64, Event)>, + events_rx: Receiver<(u64, Event)>, +} + +struct Process { + child: Child, + requests: Sender, +} + +impl Worker { + pub fn new(ctx: egui::Context) -> Self { + let (events_tx, events_rx) = mpsc::channel(); + Self { + ctx, + config: None, + process: None, + status: Status::NotStarted, + problem: None, + next_id: 1, + generation: 0, + events_tx, + events_rx, + } + } + + pub fn status(&self) -> &Status { + &self.status + } + + pub fn info(&self) -> Option<&ReadyInfo> { + match &self.status { + Status::Ready(info) => Some(info), + _ => None, + } + } + + pub fn is_ready(&self) -> bool { + matches!(self.status, Status::Ready(_)) + } + + /// Why the worker failed, while it is [`Status::Failed`]. + pub fn problem(&self) -> Option { + self.problem + .filter(|_| matches!(self.status, Status::Failed(_))) + } + + pub fn config(&self) -> Option<&LaunchConfig> { + self.config.as_ref() + } + + /// (Re)starts the worker with `config`. + pub fn start(&mut self, config: LaunchConfig) { + self.kill(); + self.generation += 1; + self.config = Some(config.clone()); + match self.spawn(&config) { + Ok(process) => { + log::info!( + "Starting the CadQuery worker with {}", + config.python.display() + ); + self.process = Some(process); + self.status = Status::Starting; + } + Err(err) => { + let reason = format!( + "Could not start Python ({}): {err}", + config.python.display() + ); + log::error!("{reason}"); + self.status = Status::Failed(reason); + self.problem = Some(Problem::NoPython); + } + } + } + + pub fn next_id(&mut self) -> RequestId { + let id = self.next_id; + self.next_id += 1; + id + } + + /// Queues `request` for the worker. Returns `false` when no worker runs. + pub fn send(&mut self, request: &Request) -> bool { + let Some(process) = &self.process else { + return false; + }; + let line = match serde_json::to_string(request) { + Ok(line) => line, + Err(err) => { + log::error!("Cannot encode worker request: {err}"); + return false; + } + }; + process.requests.send(line).is_ok() + } + + /// Drains pending events of the current process, updating the status. + pub fn poll(&mut self) -> Vec { + let mut events = Vec::new(); + while let Ok((generation, event)) = self.events_rx.try_recv() { + if generation != self.generation { + continue; // from a process we already killed + } + match &event { + Event::Message(Message::Ready(info)) => { + if info.protocol != protocol::PROTOCOL_VERSION { + log::warn!( + "Worker protocol {} differs from the GUI's {}", + info.protocol, + protocol::PROTOCOL_VERSION + ); + } + self.status = Status::Ready(info.clone()); + } + Event::Message(Message::Fatal { message, .. }) => { + self.status = Status::Failed(message.clone()); + self.problem = Some(Problem::NoCadQuery); + } + Event::Exited => { + let code = self + .process + .take() + .and_then(|mut p| p.child.wait().ok()) + .and_then(|status| status.code()); + if !matches!(self.status, Status::Failed(_)) { + self.problem = Some(exit_problem(code)); + self.status = Status::Failed(match code { + Some(code) => format!("The Python worker exited (code {code})"), + None => "The Python worker stopped unexpectedly".to_owned(), + }); + } + } + _ => {} + } + events.push(event); + } + events + } + + /// Asks the worker to exit, giving it a moment to clean up before it is + /// killed. + pub fn shutdown(&mut self) { + if let Some(process) = &mut self.process { + let _ = process + .requests + .send(serde_json::to_string(&Request::Shutdown).unwrap_or_default()); + let deadline = std::time::Instant::now() + std::time::Duration::from_millis(500); + while std::time::Instant::now() < deadline { + if matches!(process.child.try_wait(), Ok(Some(_))) { + break; + } + thread::sleep(std::time::Duration::from_millis(20)); + } + } + self.kill(); + } + + fn kill(&mut self) { + if let Some(mut process) = self.process.take() { + let _ = process.child.kill(); + let _ = process.child.wait(); + } + self.status = Status::NotStarted; + } + + fn spawn(&self, config: &LaunchConfig) -> std::io::Result { + let mut command = Command::new(&config.python); + command + .args(["-u", "-m", "cq_worker"]) + .env("PYTHONPATH", python_path(&config.worker_dir)) + .env("PYTHONIOENCODING", "utf-8") + // Namespaces the worker's scene keys: objects of a killed worker + // stay on screen, and a new worker must not reuse their keys. + .env("CQ_EDITOR_SESSION", self.generation.to_string()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt as _; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + command.creation_flags(CREATE_NO_WINDOW); + } + + let mut child = command.spawn()?; + let stdin = child.stdin.take().expect("piped stdin"); + let stdout = child.stdout.take().expect("piped stdout"); + let stderr = child.stderr.take().expect("piped stderr"); + + let (requests, pending) = mpsc::channel::(); + thread::Builder::new() + .name("worker-writer".into()) + .spawn(move || write_requests(stdin, pending))?; + + let (tx, ctx, generation) = (self.events_tx.clone(), self.ctx.clone(), self.generation); + thread::Builder::new() + .name("worker-reader".into()) + .spawn(move || { + let mut reader = BufReader::new(stdout); + let mut protocol_failed = false; + loop { + match read_limited_line(&mut reader, MAX_MESH_MESSAGE_BYTES) { + Ok(LimitedLine::Line(line)) => { + if protocol_failed { + continue; + } + if line.iter().all(u8::is_ascii_whitespace) { + continue; + } + let limit = worker_message_limit(&line); + if line.len() > limit { + let _ = tx.send(( + generation, + Event::ProtocolError(oversized_message(line.len(), limit)), + )); + ctx.request_repaint(); + protocol_failed = true; + continue; + } + let received_at = SystemTime::now(); + let started = Instant::now(); + match serde_json::from_slice::(&line) { + Ok(mut message) => { + if let Message::RunFinished(result) = &mut message { + result.receipt = protocol::Receipt { + received_at: Some(received_at), + parse: started.elapsed(), + }; + } + let _ = tx.send((generation, Event::Message(message))); + } + Err(err) => log::warn!( + "Unreadable worker message ({err}): {}", + String::from_utf8_lossy(&line[..line.len().min(200)]) + ), + } + ctx.request_repaint(); + } + Ok(LimitedLine::TooLong(_)) => { + if !protocol_failed { + let _ = tx.send(( + generation, + Event::ProtocolError(oversized_message( + MAX_MESH_MESSAGE_BYTES + 1, + MAX_MESH_MESSAGE_BYTES, + )), + )); + ctx.request_repaint(); + protocol_failed = true; + } + } + Ok(LimitedLine::Eof) | Err(_) => break, + } + } + let _ = tx.send((generation, Event::Exited)); + ctx.request_repaint(); + })?; + + let (tx, ctx) = (self.events_tx.clone(), self.ctx.clone()); + thread::Builder::new() + .name("worker-stderr".into()) + .spawn(move || { + let mut reader = BufReader::new(stderr); + loop { + let line = match read_limited_line(&mut reader, MAX_STDERR_LINE_BYTES) { + Ok(LimitedLine::Line(line)) => String::from_utf8_lossy(&line).into_owned(), + Ok(LimitedLine::TooLong(prefix)) => format!( + "{}\n[stderr line truncated after {MAX_STDERR_LINE_BYTES} bytes]", + String::from_utf8_lossy(&prefix) + ), + Ok(LimitedLine::Eof) | Err(_) => break, + }; + let _ = tx.send((generation, Event::Stderr(line))); + ctx.request_repaint(); + } + })?; + + Ok(Process { child, requests }) + } +} + +impl Drop for Worker { + fn drop(&mut self) { + self.shutdown(); + } +} + +fn write_requests(mut stdin: ChildStdin, pending: Receiver) { + for line in pending { + if stdin + .write_all(line.as_bytes()) + .and_then(|()| stdin.write_all(b"\n")) + .and_then(|()| stdin.flush()) + .is_err() + { + break; // the process is gone; the reader reports it + } + } +} + +/// `worker_dir` in front of any `PYTHONPATH` the user already has. +fn python_path(worker_dir: &std::path::Path) -> std::ffi::OsString { + let mut paths = vec![worker_dir.to_path_buf()]; + if let Some(existing) = std::env::var_os("PYTHONPATH") { + paths.extend(std::env::split_paths(&existing)); + } + std::env::join_paths(paths).unwrap_or_else(|_| worker_dir.as_os_str().to_owned()) +} + +#[derive(Debug, PartialEq, Eq)] +enum LimitedLine { + Line(Vec), + /// The retained value is only the bounded prefix; the remainder was drained. + TooLong(Vec), + Eof, +} + +/// Reads and drains one line while retaining at most `limit` bytes. +fn read_limited_line(reader: &mut impl BufRead, limit: usize) -> io::Result { + let mut line = Vec::new(); + let mut too_long = false; + loop { + let available = reader.fill_buf()?; + if available.is_empty() { + return Ok(if too_long { + LimitedLine::TooLong(line) + } else if line.is_empty() { + LimitedLine::Eof + } else { + LimitedLine::Line(line) + }); + } + + let newline = available.iter().position(|byte| *byte == b'\n'); + let content_len = newline.unwrap_or(available.len()); + if !too_long { + let retained = content_len.min(limit.saturating_sub(line.len())); + line.extend_from_slice(&available[..retained]); + too_long = retained < content_len; + } + let consumed = newline.map_or(available.len(), |position| position + 1); + reader.consume(consumed); + if newline.is_some() { + return Ok(if too_long { + LimitedLine::TooLong(line) + } else { + LimitedLine::Line(line) + }); + } + } +} + +fn worker_message_limit(line: &[u8]) -> usize { + if line.len() <= MAX_CONTROL_MESSAGE_BYTES { + return MAX_CONTROL_MESSAGE_BYTES; + } + // Channel.send emits compact JSON and puts the top-level type near the + // start. Looking only at that bounded prefix avoids parsing a large mesh + // message twice. Quotes inside a JSON string are escaped and therefore + // cannot match these field encodings. + const HEADER_BYTES: usize = 1024; + const MESH_TYPES: [&[u8]; 5] = [ + br#""type":"run_finished""#, + br#""type":"run_part""#, + br#""type":"debug_paused""#, + br#""type":"inspection_geometry""#, + br#""type":"scene_add""#, + ]; + let header = &line[..line.len().min(HEADER_BYTES)]; + if header + .windows(br#""type":"display""#.len()) + .any(|window| window == br#""type":"display""#) + { + return MAX_DISPLAY_MESSAGE_BYTES; + } + if MESH_TYPES + .iter() + .any(|kind| header.windows(kind.len()).any(|window| window == *kind)) + { + MAX_MESH_MESSAGE_BYTES + } else { + MAX_CONTROL_MESSAGE_BYTES + } +} + +/// What the user is told about a message over its limit. Mesh replies are +/// the large ones: a finer tolerance or more objects make them grow. +fn oversized_message(actual: usize, limit: usize) -> String { + const MIB: usize = 1024 * 1024; + let advice = if limit >= MAX_MESH_MESSAGE_BYTES { + "; the model is too large to transfer: raise Deviation in \ + Preferences > 3D View, or show fewer objects" + } else { + "" + }; + format!( + "Python sent a message of at least {:.1} MiB, over its {} MiB limit{advice}", + actual as f64 / MIB as f64, + limit / MIB + ) +} + +#[cfg(test)] +#[path = "../../tests/rust/protocol/test_worker_io.rs"] +mod tests; diff --git a/src/worker/protocol.rs b/src/worker/protocol.rs new file mode 100644 index 000000000..d8971293f --- /dev/null +++ b/src/worker/protocol.rs @@ -0,0 +1,1120 @@ +//! Message types exchanged with the Python worker (`worker/cq_worker`). +//! +//! Every message is one JSON object per line. Requests carry a `cmd` tag, +//! worker messages a `type` tag. Mesh arrays travel as base64-encoded +//! little-endian binary and are decoded on the reader thread, off the UI +//! thread. + +use std::collections::BTreeMap; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use base64::Engine as _; +use serde::{Deserialize, Deserializer, Serialize}; + +/// The worker's protocol version this build understands. +pub const PROTOCOL_VERSION: u32 = 13; + +pub type RequestId = u64; + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum NavigationMode { + Definition, + References, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct OutlineSymbol { + pub name: String, + pub kind: String, + pub line: usize, + pub depth: usize, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct NavigationLocation { + pub name: String, + pub kind: String, + pub path: Option, + pub line: usize, + pub column: usize, +} + +#[derive(Serialize, Debug, Clone)] +#[serde(tag = "cmd", rename_all = "snake_case")] +pub enum Request { + Run { + id: RequestId, + script: String, + path: Option, + debug: bool, + breakpoints: Vec, + project_root: Option, + module_breakpoints: BTreeMap>, + settings: RunSettings, + scene: SceneSettings, + /// Content-addressed meshes the GUI holds and pins for this request. + /// The worker may answer with lightweight references to these ids. + known_geometry: Vec, + /// Measure the time of each line (not with `debug`). + profile: bool, + }, + /// Only valid while a debugging session is paused. + Debug { + action: DebugAction, + breakpoints: Vec, + module_breakpoints: BTreeMap>, + }, + /// Scene keys the GUI no longer shows; lets the worker free them. + Release { + keys: Vec, + }, + Complete { + id: RequestId, + source: String, + /// 1-based. + line: usize, + /// 0-based, in characters. + column: usize, + path: Option, + target: CompletionTarget, + }, + /// Documentation of the name at a position of the editor's script. + Describe { + id: RequestId, + source: String, + /// 1-based. + line: usize, + /// 0-based, in characters. + column: usize, + path: Option, + }, + Outline { + id: RequestId, + source: String, + }, + Navigate { + id: RequestId, + source: String, + line: usize, + column: usize, + path: Option, + project_root: Option, + mode: NavigationMode, + }, + Inspect { + id: RequestId, + key: String, + }, + InspectGeometry { + id: RequestId, + key: String, + frame: usize, + item: Option, + scene: SceneSettings, + }, + InterferenceGeometry { + id: RequestId, + first: InterferencePart, + second: InterferencePart, + scene: SceneSettings, + }, + /// Measures one entity, or the exact relationship between two entities, + /// against the live OCCT shapes retained by the worker. + Measure { + id: RequestId, + selections: Vec, + /// Measured instead when no entity is selected. + objects: Vec, + }, + /// Python that repeats a measurement with the script's variables. + MeasurementCode { + id: RequestId, + selections: Vec, + objects: Vec, + }, + /// CadQuery selectors that select exactly these entities of one object. + Selector { + id: RequestId, + selections: Vec, + }, + /// Read-only preview of a literal selector at the editor caret. + SelectorPreview { + id: RequestId, + run_id: RequestId, + line: usize, + column: usize, + preferred_key: Option, + }, + Console { + id: RequestId, + source: String, + scene: SceneSettings, + known_geometry: Vec, + /// What `selected()` returns while this command runs. + selection: ConsoleSelection, + }, + ConsoleReset { + id: RequestId, + }, + Export { + id: RequestId, + keys: Vec, + format: ExportFormat, + path: String, + tolerance: f64, + angular_tolerance: f64, + step_mode: String, + step_schema: String, + stl_ascii: bool, + flat_parts: bool, + unit: String, + on_invalid: String, + on_interference: String, + }, + Check { + id: RequestId, + keys: Vec, + flat_parts: bool, + }, + Upload { + id: RequestId, + url: String, + file_type: String, + keys: Vec, + source: String, + }, + CheckUpdates { + id: RequestId, + /// The running CQ-editor's version: its newer releases are listed. + editor: String, + /// Also list newer CadQuery releases. + cadquery: bool, + }, + Imports { + id: RequestId, + path: String, + }, + /// Stops the meshing of the run `target` (the worker reads it while + /// busy); the run then finishes as `cancelled`. + Cancel { + target: RequestId, + }, + /// Raises `KeyboardInterrupt` in the run or console command `target` + /// (the worker reads it while busy), as Ctrl+C would. + Interrupt { + target: RequestId, + }, + Shutdown, +} + +#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum DebugAction { + Continue, + Step, + StepIn, + StepOut, + Stop, +} + +#[derive(Serialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CompletionTarget { + Editor, + Console, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum ExportFormat { + Step, + Stl, + Brep, + #[serde(rename = "3mf")] + ThreeMf, + Gltf, + Glb, + Amf, + Vrml, + Vtkjs, + Xbf, + Svg, + Dxf, +} + +impl ExportFormat { + pub const ALL: [ExportFormat; 12] = [ + ExportFormat::Step, + ExportFormat::Stl, + ExportFormat::Brep, + ExportFormat::ThreeMf, + ExportFormat::Gltf, + ExportFormat::Glb, + ExportFormat::Amf, + ExportFormat::Vrml, + ExportFormat::Vtkjs, + ExportFormat::Xbf, + ExportFormat::Svg, + ExportFormat::Dxf, + ]; + + pub fn extension(self) -> &'static str { + match self { + ExportFormat::Step => "step", + ExportFormat::Stl => "stl", + ExportFormat::Brep => "brep", + ExportFormat::ThreeMf => "3mf", + ExportFormat::Gltf => "gltf", + ExportFormat::Glb => "glb", + ExportFormat::Amf => "amf", + ExportFormat::Vrml => "vrml", + ExportFormat::Vtkjs => "vtkjs", + ExportFormat::Xbf => "xbf", + ExportFormat::Svg => "svg", + ExportFormat::Dxf => "dxf", + } + } + + pub fn label(self) -> &'static str { + match self { + ExportFormat::Step => "STEP", + ExportFormat::Stl => "STL", + ExportFormat::Brep => "BREP", + ExportFormat::ThreeMf => "3MF", + ExportFormat::Gltf => "glTF", + ExportFormat::Glb => "GLB", + ExportFormat::Amf => "AMF", + ExportFormat::Vrml => "VRML", + ExportFormat::Vtkjs => "VTK.js", + ExportFormat::Xbf => "XBF", + ExportFormat::Svg => "SVG", + ExportFormat::Dxf => "DXF", + } + } +} + +#[derive(Serialize, Debug, Clone, PartialEq)] +pub struct RunSettings { + pub reload_cq: bool, + pub add_script_dir_to_path: bool, + pub change_working_dir: bool, + pub reload_imported_modules: bool, +} + +#[derive(Serialize, Debug, Clone, PartialEq)] +pub struct SceneSettings { + pub linear_tolerance: f64, + pub angular_tolerance: f64, + pub merge_assemblies: bool, + pub units: String, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct GeometryReport { + pub key: String, + pub name: String, + pub valid: bool, + pub solids: usize, + pub open_shells: usize, + pub non_manifold_edges: usize, + pub issues: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct InterferencePart { + pub key: String, + pub name: String, + pub part: usize, + pub solid: usize, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct InterferenceReport { + pub first: InterferencePart, + pub second: InterferencePart, + pub kind: String, + pub overlap_volume: Option, + pub distance: Option, + pub point: Option<[f64; 3]>, + pub reason: Option, + #[serde(default)] + pub allowance_reason: Option, +} + +#[derive(Deserialize, Debug)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Message { + Ready(ReadyInfo), + /// The worker could not start (typically: CadQuery is not installed). + Fatal { + message: String, + #[serde(default)] + detail: Option, + }, + Output { + id: Option, + stream: OutputStream, + text: String, + }, + Log { + level: String, + source: String, + message: String, + }, + RunFinished(Box), + /// One mesh and its placement, sent before the final scene hierarchy. + RunPart { + id: RequestId, + name: String, + part: Box, + }, + /// How far a request is, e.g. parts meshed of all. + Progress { + id: RequestId, + stage: String, + done: u32, + total: u32, + }, + DebugPaused { + id: RequestId, + line: usize, + path: Option, + variables: Vec, + objects: Vec, + }, + Completions { + id: RequestId, + available: bool, + items: Vec, + signatures: Vec, + }, + Description { + id: RequestId, + #[serde(flatten)] + documentation: Documentation, + }, + Outline { + id: RequestId, + symbols: Vec, + }, + Navigation { + id: RequestId, + available: bool, + mode: NavigationMode, + locations: Vec, + truncated: bool, + }, + Inspection { + id: RequestId, + key: String, + frames: Vec, + }, + InspectionGeometry { + id: RequestId, + meshes: Vec, + plane: Option, + }, + InterferenceGeometry { + id: RequestId, + mesh: Box, + }, + Measurement(Box), + MeasurementCode { + id: RequestId, + code: String, + /// The worker ran the code and it reproduced every value. + verified: bool, + /// Why it is not verified. + problem: Option, + }, + Selector(SelectorReply), + SelectorPreview { + id: RequestId, + active: bool, + count: usize, + matches: Vec, + message: Option, + }, + SceneAdd { + #[serde(default)] + id: Option, + objects: Vec, + }, + ConsoleResult { + id: RequestId, + more: bool, + }, + /// A rich result of a console command: its text and, perhaps, an image + /// already decoded (on the reader thread, not the one that draws). + Display(DisplayOutput), + ExportFinished { + id: RequestId, + path: String, + }, + GeometryChecked { + id: RequestId, + reports: Vec, + #[serde(default)] + interferences: Vec, + }, + GeometryInvalid { + id: RequestId, + reports: Vec, + #[serde(default)] + interferences: Vec, + }, + UploadFinished { + id: RequestId, + status: u16, + body: String, + }, + Updates { + id: RequestId, + /// CadQuery's version, and its newer release tags. + current: String, + newer: Vec, + #[serde(default)] + editor: Option, + }, + Imports { + id: RequestId, + paths: Vec, + }, + Error { + id: Option, + message: String, + }, +} + +#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum OutputStream { + Stdout, + Stderr, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct ReadyInfo { + pub protocol: u32, + pub python: String, + pub cadquery: String, + #[serde(default = "unknown_version")] + pub ocp: String, + pub executable: String, + pub completion: bool, +} + +fn unknown_version() -> String { + "unknown".to_owned() +} + +#[derive(Deserialize, Debug)] +pub struct RunFinished { + pub id: RequestId, + pub ok: bool, + pub debug: bool, + pub stopped: bool, + /// Meshing was cancelled; the current scene stays. + #[serde(default)] + pub cancelled: bool, + /// Stop interrupted the script; `error` says where. + #[serde(default)] + pub interrupted: bool, + /// Where the time went, for a run asked to `profile`. + #[serde(default)] + pub profile: Option, + /// `None` when a failed run should keep the current scene. + pub objects: Option>, + pub variables: Option>, + pub error: Option, + /// Requirements declared with expect() during this run. + #[serde(default)] + pub checks: Vec, + pub duration: f64, + #[serde(default)] + pub timings: Option, + /// Filled in by the reader thread, not sent by the worker. + #[serde(skip)] + pub receipt: Receipt, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct CadCheck { + pub name: String, + pub kind: String, + pub ok: bool, + pub detail: String, + pub line: Option, +} + +/// The largest image the console shows, on either side, in pixels. +pub const MAX_DISPLAY_SIDE: u32 = 4096; +/// Decoded image bytes accepted, matching the worker-side limit. +const MAX_DISPLAY_IMAGE_BYTES: usize = 4 * 1024 * 1024; +/// Largest base64 string that can encode [`MAX_DISPLAY_IMAGE_BYTES`]. +const MAX_DISPLAY_DATA: usize = 4 * MAX_DISPLAY_IMAGE_BYTES.div_ceil(3); + +/// A console result as the worker sends it. +#[derive(Deserialize)] +struct RawDisplay { + id: RequestId, + #[serde(default)] + text: String, + #[serde(default)] + image: Option, +} + +#[derive(Deserialize)] +struct RawImage { + format: String, + data: String, +} + +/// A console result: text, and an image checked and decoded, or a note in +/// the text saying why it is not shown. +#[derive(Deserialize, Debug, Clone, PartialEq)] +#[serde(from = "RawDisplay")] +pub struct DisplayOutput { + pub id: RequestId, + pub text: String, + pub image: Option, +} + +/// Decoded pixels, RGBA, row by row. +#[derive(Debug, Clone, PartialEq)] +pub struct DisplayImage { + pub size: [usize; 2], + pub rgba: Vec, +} + +impl From for DisplayOutput { + fn from(raw: RawDisplay) -> Self { + let mut text = raw.text; + let image = raw + .image + .and_then(|image| match decode_display_image(&image) { + Ok(image) => Some(image), + Err(problem) => { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(&format!("[image not shown: {problem}]")); + None + } + }); + Self { + id: raw.id, + text, + image, + } + } +} + +/// Only PNG and JPEG, within [`MAX_DISPLAY_SIDE`] and a memory limit: the +/// worker runs user code, so its images are not trusted. +fn decode_display_image(image: &RawImage) -> Result { + let format = match image.format.as_str() { + "png" => image::ImageFormat::Png, + "jpeg" => image::ImageFormat::Jpeg, + other => return Err(format!("{other} is not shown")), + }; + if image.data.len() > MAX_DISPLAY_DATA { + return Err("too large".to_owned()); + } + let bytes = base64::engine::general_purpose::STANDARD + .decode(&image.data) + .map_err(|error| format!("bad data ({error})"))?; + if bytes.len() > MAX_DISPLAY_IMAGE_BYTES { + return Err("too large".to_owned()); + } + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes), format); + let mut limits = image::Limits::default(); + limits.max_image_width = Some(MAX_DISPLAY_SIDE); + limits.max_image_height = Some(MAX_DISPLAY_SIDE); + limits.max_alloc = Some(128 * 1024 * 1024); + reader.limits(limits); + let decoded = reader + .decode() + .map_err(|error| error.to_string())? + .to_rgba8(); + let size = [decoded.width() as usize, decoded.height() as usize]; + Ok(DisplayImage { + size, + rgba: decoded.into_raw(), + }) +} + +/// CQ-editor's releases newer than the running one, newest first. +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct EditorUpdates { + pub current: String, + pub newer: Vec, +} + +/// A published release of CQ-editor; also kept in the preferences. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct Release { + pub tag: String, + pub name: String, + /// Its page, with the installers. + pub url: String, +} + +/// The time a profiled run spent on each line of the script, with +/// everything the line called, and on its calls into CadQuery. +#[derive(Deserialize, Debug, Clone, Default, PartialEq)] +#[serde(default)] +pub struct RunProfile { + /// In line order. + pub lines: Vec, + /// The slowest calls of each line, slowest first. + pub operations: Vec, + pub sources: BTreeMap, +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct LineTime { + #[serde(default)] + pub file: Option, + /// 1-based. + pub line: usize, + pub seconds: f64, + /// How many times the line started. + pub hits: u64, +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct OperationTime { + #[serde(default)] + pub file: Option, + pub line: usize, + /// For example `Workplane.fillet`. + pub name: String, + pub seconds: f64, + pub calls: u64, +} + +/// Where the worker spent a run's time, in seconds, and what it sent. +#[derive(Deserialize, Debug, Clone, Default, PartialEq)] +#[serde(default)] +pub struct RunTimings { + pub script: f64, + /// Content ids: hashing each shape's BREP. + pub identify: f64, + pub tessellate: f64, + /// Base64 encoding of the mesh arrays. + pub encode: f64, + pub meshed: usize, + pub cached: usize, + pub referenced: usize, + pub mesh_bytes: usize, + /// Worker wall clock (seconds since the Unix epoch) just before sending. + pub sent_at: f64, +} + +/// When the GUI read a message and how long parsing it took. +#[derive(Debug, Clone, Default)] +pub struct Receipt { + pub received_at: Option, + pub parse: Duration, +} + +impl RunTimings { + /// Time from the worker finishing the reply until the GUI read it: + /// serialization and the pipe. `None` if the clocks disagree. + pub fn transfer(&self, receipt: &Receipt) -> Option { + let sent = UNIX_EPOCH.checked_add(Duration::try_from_secs_f64(self.sent_at).ok()?)?; + receipt.received_at?.duration_since(sent).ok() + } + + /// One log line covering every stage of a run. + pub fn report(&self, receipt: &Receipt, decode: Duration) -> String { + let transfer = self + .transfer(receipt) + .map_or_else(|| "?".to_owned(), |d| format!("{:.3}", d.as_secs_f64())); + format!( + "Run timings (s): script {:.3}, content ids {:.3}, meshing {:.3}, encoding {:.3}, \ + transfer {transfer}, parsing {:.3}, scene {:.3}; meshes: {} meshed, {} cached, \ + {} reused by reference, {:.2} MB sent", + self.script, + self.identify, + self.tessellate, + self.encode, + receipt.parse.as_secs_f64(), + decode.as_secs_f64(), + self.meshed, + self.cached, + self.referenced, + self.mesh_bytes as f64 / 1e6, + ) + } +} + +#[derive(Deserialize, Debug, Clone)] +pub struct Variable { + pub name: String, + #[serde(rename = "type")] + pub type_name: String, + pub value: String, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct ScriptError { + pub type_name: String, + pub message: String, + pub frames: Vec, + /// Last line of the editor buffer involved, if any. + pub line: Option, + /// Python's own formatting of the traceback. + pub text: String, + /// Conservative troubleshooting hints tied to a CAD call in the script. + #[serde(default)] + pub diagnostic: Option, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct CadDiagnostic { + pub operation: String, + pub receiver: Option, + pub line: usize, + pub hints: Vec, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct TracebackFrame { + pub file: String, + pub line: usize, + pub function: String, + pub code: String, +} + +/// Pseudo file name of the editor buffer in worker tracebacks. +pub const SCRIPT_FILENAME: &str = ""; + +/// Documentation of a name, for the editor's hover tooltip. Both parts are +/// empty when there is nothing to show. +#[derive(Deserialize, Debug, Clone, Default, PartialEq)] +pub struct Documentation { + /// Call signatures, or `name: type` for a variable. + #[serde(default)] + pub signatures: Vec, + /// The docstring, cut to a tooltip's length. + #[serde(default)] + pub text: String, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct CompletionItem { + pub name: String, + /// Text to insert at the cursor to complete `name`. + pub insert: String, + pub kind: String, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct StackFrame { + #[serde(rename = "type")] + pub type_name: String, + pub value: String, + pub items: Vec, + /// The script line that made this step. + #[serde(default)] + pub line: Option, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct StackItem { + #[serde(rename = "type")] + pub type_name: String, + pub value: String, + pub displayable: bool, + #[serde(default)] + pub line: Option, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct Plane { + pub origin: [f32; 3], + pub x_dir: [f32; 3], + pub z_dir: [f32; 3], + pub size: f32, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum TopologyKind { + Face, + Edge, + Vertex, +} + +/// The GUI's selection for the console's `selected()`. +#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct ConsoleSelection { + /// Picked faces, edges and vertices, in the order they were picked. + pub entities: Vec, + /// Selected objects, outermost first; used when no entity is picked. + pub objects: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct TopologyReference { + pub key: String, + pub part: usize, + pub kind: TopologyKind, + pub identifier: u32, +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct Measurement { + pub id: RequestId, + pub identity: TopologyIdentity, + pub entities: Vec, + pub pair: Option, + /// The selected objects, measured when no entity is selected. + #[serde(default)] + pub objects: Vec, + /// Around everything measured. + #[serde(default)] + pub bounding_box: Option, +} + +/// An axis-aligned box from the exact geometry, in world coordinates. +#[derive(Deserialize, Debug, Clone, Copy, PartialEq)] +pub struct BoundingBox { + pub min: [f64; 3], + pub max: [f64; 3], + pub size: [f64; 3], + pub center: [f64; 3], +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct ObjectMeasurement { + pub key: String, + /// `solid`, `compound`, `face` … + pub shape_type: String, + pub volume: Option, + pub area: Option, + /// Of the edges, for objects without faces. + pub length: Option, + /// Center of mass. + pub center: [f64; 3], + pub bounding_box: Option, + pub solids: usize, + pub faces: usize, + pub edges: usize, + pub vertices: usize, + #[serde(default)] + pub mass_g: Option, + #[serde(default)] + pub materials: Vec, +} + +#[derive(Deserialize, Debug, Clone, PartialEq, Eq)] +pub struct TopologyIdentity { + pub scope: String, + pub persistent: bool, +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct EntityMeasurement { + pub key: String, + pub part: usize, + pub kind: TopologyKind, + pub identifier: u32, + pub geometry_type: String, + pub center: [f64; 3], + pub position: Option<[f64; 3]>, + pub length: Option, + pub area: Option, + pub radius: Option, + pub diameter: Option, + #[serde(default)] + pub bounding_box: Option, +} + +/// Selector expressions for a topology selection, verified by the worker +/// against CadQuery itself. +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct SelectorReply { + pub id: RequestId, + /// `faces`, `edges` or `vertices`. + pub method: String, + /// Best first; never empty. + pub candidates: Vec, +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct SelectorCandidate { + /// Ready to append to the object, e.g. `.faces(">Z")`. + pub expression: String, + /// What it means, e.g. "the faces with the largest Z". + #[serde(default)] + pub description: String, + /// Relies on CadQuery's entity order rather than on geometry, so it + /// can select another entity once the model changes. + #[serde(default)] + pub index_based: bool, +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct PairMeasurement { + pub distance: f64, + pub first_point: [f64; 3], + pub second_point: [f64; 3], + pub angle_degrees: Option, + pub angle_kind: Option, +} + +#[derive(Deserialize, Debug)] +pub struct SceneNode { + pub key: String, + pub name: String, + pub kind: String, + pub inspectable: bool, + /// The script line that created the object (or showed it). + #[serde(default)] + pub line: Option, + pub color: Option<[f32; 3]>, + pub alpha: Option, + pub edge_color: Option<[f32; 3]>, + /// The `material` option of `show_object`, as `Finish::name` spells it. + #[serde(default)] + pub finish: Option, + pub parts: Vec, + pub children: Vec, +} + +#[derive(Deserialize, Debug)] +pub struct Part { + pub mesh: Mesh, + #[serde(default = "identity_transform")] + pub transform: [f32; 16], + pub color: Option<[f32; 3]>, + pub alpha: Option, + #[serde(default)] + pub face_attributes: Vec, + pub material: Option, +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct FaceAttribute { + pub id: u32, + pub name: Option, + pub layer: Option, + pub color: Option<[f32; 3]>, + pub alpha: Option, +} + +#[derive(Deserialize, Debug, Clone, PartialEq)] +pub struct Material { + pub name: String, + pub density: f64, + pub density_unit: String, +} + +/// Triangulated geometry, already decoded. +#[derive(Deserialize, Debug, Default)] +pub struct Mesh { + /// Stable digest of the local CAD geometry and tessellation settings. + #[serde(default)] + pub id: String, + #[serde(default, deserialize_with = "vec3_f32")] + pub positions: Vec<[f32; 3]>, + #[serde(default, deserialize_with = "vec3_f32")] + pub normals: Vec<[f32; 3]>, + #[serde(default, deserialize_with = "u32_array")] + pub indices: Vec, + /// Line segments, two points each. + #[serde(default, deserialize_with = "vec3_f32")] + pub edges: Vec<[f32; 3]>, + #[serde(default, deserialize_with = "vec3_f32")] + pub points: Vec<[f32; 3]>, + /// Degrees between the faces that meet at each segment's edge. + #[serde(default, deserialize_with = "f32_array")] + pub segment_angles: Vec, + #[serde(default)] + pub topology: MeshTopology, + /// Absent only for a content-addressed reference. + #[serde(default)] + pub bbox: Option<[[f32; 3]; 2]>, +} + +/// OCCT subshape associations for precise face, edge and vertex picking. +#[derive(Deserialize, Debug, Default)] +pub struct MeshTopology { + #[serde(default, deserialize_with = "vec3_f32")] + pub face_positions: Vec<[f32; 3]>, + #[serde(default, deserialize_with = "u32_array")] + pub face_indices: Vec, + #[serde(default, deserialize_with = "u32_array")] + pub triangle_faces: Vec, + #[serde(default, deserialize_with = "u32_array")] + pub segment_edges: Vec, + #[serde(default, deserialize_with = "vec3_f32")] + pub vertices: Vec<[f32; 3]>, +} + +fn identity_transform() -> [f32; 16] { + glam::Mat4::IDENTITY.to_cols_array() +} + +fn base64_bytes<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let text = >::deserialize(deserializer)?; + base64::engine::general_purpose::STANDARD + .decode(text.as_bytes()) + .map_err(serde::de::Error::custom) +} + +fn vec3_f32<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let bytes = base64_bytes(deserializer)?; + if bytes.len() % 12 != 0 { + return Err(serde::de::Error::custom( + "vector array length is not a multiple of 12", + )); + } + Ok(bytes + .as_chunks::<12>() + .0 + .iter() + .map(|c| { + let f = |i: usize| f32::from_le_bytes([c[i], c[i + 1], c[i + 2], c[i + 3]]); + [f(0), f(4), f(8)] + }) + .collect()) +} + +fn f32_array<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let bytes = base64_bytes(deserializer)?; + if bytes.len() % 4 != 0 { + return Err(serde::de::Error::custom( + "float array length is not a multiple of 4", + )); + } + Ok(bytes + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect()) +} + +fn u32_array<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let bytes = base64_bytes(deserializer)?; + if bytes.len() % 4 != 0 { + return Err(serde::de::Error::custom( + "index array length is not a multiple of 4", + )); + } + Ok(bytes + .as_chunks::<4>() + .0 + .iter() + .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect()) +} + +#[cfg(test)] +#[path = "../../tests/rust/protocol/test_protocol.rs"] +mod tests; diff --git a/tests/fixtures/protocol/messages.json b/tests/fixtures/protocol/messages.json new file mode 100644 index 000000000..7bbd82d5e --- /dev/null +++ b/tests/fixtures/protocol/messages.json @@ -0,0 +1,93 @@ +{ + "valid": [ + { + "name": "ready", + "message": { + "type": "ready", + "protocol": 13, + "python": "3.12.15", + "cadquery": "2.8.0", + "ocp": "7.9.3.1", + "executable": "python", + "completion": true + } + }, + { + "name": "binary_part", + "message": { + "type": "run_part", + "id": 7, + "name": "triangle", + "part": { + "mesh": { + "id": "triangle-geometry", + "positions": "AAAAAAAAAAAAAAAAAACAPwAAAAAAAAAAAAAAAAAAgD8AAAAA", + "normals": "AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/", + "indices": "AAAAAAEAAAACAAAA", + "bbox": [[0, 0, 0], [1, 1, 0]] + }, + "color": null, + "alpha": null, + "material": null + } + } + }, + { + "name": "referenced_part", + "message": { + "type": "run_part", + "id": 7, + "name": "triangle again", + "part": { + "mesh": {"id": "triangle-geometry"}, + "color": null, + "alpha": null, + "material": null + } + } + }, + { + "name": "finished_scene", + "message": { + "type": "run_finished", + "id": 7, + "ok": true, + "debug": false, + "stopped": false, + "objects": [ + { + "key": "n1", + "name": "triangle", + "kind": "Workplane", + "inspectable": true, + "color": null, + "alpha": null, + "edge_color": null, + "parts": [ + { + "mesh": {"id": "triangle-geometry"}, + "color": null, + "alpha": null, + "material": null + } + ], + "children": [] + } + ], + "variables": [], + "error": null, + "duration": 0.01 + } + } + ], + "invalid": [ + { + "name": "nonfinite_alpha", + "wire": "{\"type\":\"run_part\",\"id\":7,\"name\":\"bad\",\"part\":{\"mesh\":{\"id\":\"bad\"},\"color\":null,\"alpha\":NaN,\"material\":null}}" + } + ], + "oversized_control": { + "type": "output", + "repeat": 2097153 + } +} diff --git a/tests/packaging/test_release.py b/tests/packaging/test_release.py new file mode 100644 index 000000000..85b99bb69 --- /dev/null +++ b/tests/packaging/test_release.py @@ -0,0 +1,215 @@ +import json +import re +import tomllib +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +CONSTRUCT = ROOT / "packaging" / "constructor" / "construct.yaml" +MENU = ROOT / "packaging" / "constructor" / "menu" / "cq-editor_menu.json" +WORKFLOW = ROOT / ".github" / "workflows" / "release.yml" + + +class ReleasePackagingTests(unittest.TestCase): + def test_release_version_is_synchronized(self): + cargo_version = tomllib.loads( + (ROOT / "Cargo.toml").read_text(encoding="utf-8") + )["package"]["version"] + worker_version = tomllib.loads( + (ROOT / "worker" / "pyproject.toml").read_text(encoding="utf-8") + )["project"]["version"] + worker_init = (ROOT / "worker" / "cq_worker" / "__init__.py").read_text( + encoding="utf-8" + ) + construct = CONSTRUCT.read_text(encoding="utf-8") + menu = json.loads(MENU.read_text(encoding="utf-8")) + + self.assertEqual(cargo_version, "0.9.0") + self.assertEqual(worker_version, cargo_version) + self.assertIn(f'__version__ = "{cargo_version}"', worker_init) + self.assertRegex(construct, rf"(?m)^version: {re.escape(cargo_version)}$") + self.assertEqual( + menu["menu_items"][0]["platforms"]["osx"]["CFBundleVersion"], + cargo_version, + ) + self.assertIn( + f"## {cargo_version}", (ROOT / "docs" / "changelog.md").read_text() + ) + + def test_installer_contains_a_pinned_cadquery_runtime(self): + construct = CONSTRUCT.read_text(encoding="utf-8") + for package in ( + "python=3.12.15", + "cadquery=2.8.0", + "ocp=7.9.3.1", + "jedi=0.19.2", + "menuinst=2.5.2", + "nomkl", + ): + self.assertIn(f" - {package}", construct) + self.assertIn("target/release/cq-editor: bin/cq-editor", construct) + self.assertIn("target/release/cq-editor.exe: cq-editor.exe", construct) + self.assertIn("lockfile", construct) + self.assertIn("licenses", construct) + + def test_installer_leaves_out_only_files_for_compiling_against_vtk(self): + construct = CONSTRUCT.read_text(encoding="utf-8") + block = re.search(r"(?m)^exclude:\n((?: - \S+\n)+)", construct) + self.assertIsNotNone(block) + excluded = {line.strip()[2:] for line in block.group(1).splitlines()} + # Headers, CMake files and import libraries, and Boost's DLLs that + # nothing installed links. A runtime library must never be listed. + self.assertEqual( + excluded, + { + "libboost-devel", + "libboost-headers", + "libboost", + "eigen", + "tbb-devel", + "liblzma-devel", + }, + ) + + def test_native_shortcuts_launch_the_bundled_executable(self): + construct = CONSTRUCT.read_text(encoding="utf-8") + workflow = WORKFLOW.read_text(encoding="utf-8") + menu = json.loads(MENU.read_text(encoding="utf-8")) + item = menu["menu_items"][0] + self.assertFalse(item["activate"]) + self.assertEqual( + item["platforms"]["win"]["command"], + ["{{ PREFIX }}/cq-editor.exe"], + ) + self.assertEqual(item["platforms"]["win"]["file_extensions"], [".py"]) + self.assertEqual( + item["platforms"]["linux"]["command"][-1], + "%F", + ) + self.assertIn("text/x-python", item["platforms"]["linux"]["MimeType"]) + self.assertEqual( + item["platforms"]["osx"]["CFBundleIdentifier"], + "io.github.igors93.cq-editor", + ) + + # Constructor rejects macOS PKG prefixes with spaces because its + # embedded conda runtime cannot be safely relocated into such paths. + mac_location = next( + line.split(":", 1)[1].split("#", 1)[0].strip() + for line in construct.splitlines() + if line.startswith("default_location_pkg:") + ) + self.assertNotIn(" ", mac_location) + self.assertIn('prefix="$HOME/Library/CQ-editor"', workflow) + + def test_release_workflow_builds_and_smoke_tests_every_installer(self): + workflow = WORKFLOW.read_text(encoding="utf-8") + for platform in ( + "linux-x86_64", + "windows-x86_64", + "macos-arm64", + "macos-x86_64", + ): + self.assertIn(f"platform: {platform}", workflow) + self.assertIn("constructor=3.17.3", workflow) + self.assertIn("Name build manifests for the platform", workflow) + self.assertIn("Smoke test installed runtime", workflow) + self.assertIn("softprops/action-gh-release@v2", workflow) + self.assertIn("SHA256SUMS.txt", workflow) + + def test_release_requires_signed_and_notarized_platform_artifacts(self): + workflow = WORKFLOW.read_text(encoding="utf-8") + construct = CONSTRUCT.read_text(encoding="utf-8") + windows_signer = (ROOT / "packaging" / "sign_windows.ps1").read_text( + encoding="utf-8" + ) + mac_notary = (ROOT / "packaging" / "notarize_macos.sh").read_text( + encoding="utf-8" + ) + + self.assertIn( + 'signing_identity_name: {{ environ["CQ_MAC_INSTALLER_IDENTITY"]', construct + ) + self.assertIn( + 'notarization_identity_name: {{ environ["CQ_MAC_APPLICATION_IDENTITY"]', + construct, + ) + for secret in ( + "WINDOWS_SIGNING_PFX_BASE64", + "WINDOWS_SIGNING_PFX_PASSWORD", + "MACOS_APPLICATION_P12_BASE64", + "MACOS_INSTALLER_P12_BASE64", + "MACOS_NOTARY_KEY_P8_BASE64", + "MACOS_NOTARY_KEY_ID", + "MACOS_NOTARY_ISSUER_ID", + ): + self.assertIn(f"secrets.{secret}", workflow) + for step, platform in ( + ("Sign native editor (Windows)", "Windows"), + ("Sign installer (Windows)", "Windows"), + ("Prepare Developer ID identities (macOS)", "macOS"), + ("Sign native editor (macOS)", "macOS"), + ("Notarize and staple installer (macOS)", "macOS"), + ): + self.assertIn( + f"- name: {step}\n if: runner.os == '{platform}' " + "&& github.ref_name != '0.9.0'", + workflow, + ) + self.assertIn( + "runner.os == 'macOS' && github.ref_name != '0.9.0' " + "&& secrets.MACOS_APPLICATION_IDENTITY", + workflow, + ) + self.assertIn( + "runner.os == 'macOS' && github.ref_name != '0.9.0' " + "&& secrets.MACOS_INSTALLER_IDENTITY", + workflow, + ) + self.assertLess( + workflow.index("Sign native editor (Windows)"), + workflow.index("Build installer"), + ) + self.assertLess( + workflow.index("Sign native editor (macOS)"), + workflow.index("Build installer"), + ) + self.assertLess( + workflow.index("Sign installer (Windows)"), + workflow.index("Upload installer"), + ) + self.assertLess( + workflow.index("Notarize and staple installer (macOS)"), + workflow.index("Upload installer"), + ) + self.assertIn( + "/fd SHA256 /tr https://timestamp.digicert.com /td SHA256", windows_signer + ) + self.assertIn("verify /pa /all /v /tw", windows_signer) + for command in ( + "notarytool submit", + "stapler staple", + "stapler validate", + "pkgutil --check-signature", + "spctl --assess --type install", + ): + self.assertIn(command, mac_notary) + + def test_packaging_scripts_and_static_inputs_exist(self): + for relative in ( + "packaging/constructor/post_install.sh", + "packaging/constructor/post_install.bat", + "packaging/constructor/pre_uninstall.bat", + "assets/icons/cadquery_logo_dark.svg", + "assets/icons/cadquery_logo_dark.ico", + "LICENSE", + ): + self.assertTrue((ROOT / relative).is_file(), relative) + self.assertIn( + "--install cq-editor_menu.json", + (ROOT / "packaging" / "constructor" / "post_install.sh").read_text(), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/rust/app/test_app.rs b/tests/rust/app/test_app.rs new file mode 100644 index 000000000..5341cd07f --- /dev/null +++ b/tests/rust/app/test_app.rs @@ -0,0 +1,1322 @@ +use super::*; + +#[test] +fn only_web_links_are_opened() { + assert!(is_web_url("https://cadquery.readthedocs.io/en/latest/")); + assert!(is_web_url("HTTP://example.com/model?id=1")); + // Links from an upload service's reply must not start local programs. + assert!(!is_web_url(r"C:\Windows\System32\calc.exe")); + assert!(!is_web_url("file:///etc/passwd")); + assert!(!is_web_url("javascript:alert(1)")); + assert!(!is_web_url("https://")); + assert!(!is_web_url("https://example.com/\nsecond line")); +} + +#[test] +fn the_documentation_link_points_to_these_docs() { + assert!(DOCUMENTATION_URL.ends_with("/docs/README.md")); + assert!(!DOCUMENTATION_URL.contains("/wiki")); + assert!(is_web_url(DOCUMENTATION_URL)); +} + +#[test] +fn links_clicked_in_widgets_are_taken_from_the_platform_output() { + let ctx = egui::Context::default(); + let mut urls = Vec::new(); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.ctx() + .open_url(egui::OpenUrl::new_tab("https://example.com/a")); + ui.ctx().copy_text("kept".to_owned()); + urls = take_requested_urls(ui.ctx()); + }); + output.textures_delta.clear(); + + assert_eq!(urls, ["https://example.com/a"]); + // Other commands, such as copying, still reach the platform. + assert_eq!( + output.platform_output.commands, + [egui::OutputCommand::CopyText("kept".to_owned())] + ); +} + +// -- application state without a window ---------------------------------------- + +/// An `AppState` with defaults and no Python, for exercising actions and +/// worker replies directly. +pub(crate) fn test_state(text: &str) -> AppState { + let ctx = egui::Context::default(); + let cache_dir = std::env::temp_dir().join("cq-editor-app-tests"); + AppState { + worker: Worker::new(ctx.clone()), + ctx, + settings: Settings::default(), + document: Document::untitled(text), + editor: CodeEditor::default(), + tabs: EditorTabs::new(0), + project: None, + scene: Scene::default(), + viewer: Viewer::default(), + variables: Vec::new(), + traceback: None, + traceback_document: None, + inspector: InspectorState::default(), + measurements: MeasurementState::default(), + selector: SelectorState::default(), + selector_preview: SelectorPreviewState::default(), + navigation: NavigationState::default(), + parameters: ParametersState::default(), + parameter_render_at: None, + document_generation: 0, + run_script: None, + console: ConsoleState::default(), + log_view: LogView::default(), + status: None, + dialogs: Dialogs::default(), + geometry_checks: std::collections::HashMap::new(), + cad_checks: Vec::new(), + cad_checks_document: None, + export_job: None, + execution: Execution::default(), + actions: Vec::new(), + watcher: FileWatcher::default(), + watch_key: None, + focused_last_frame: false, + imports: Vec::new(), + examples: Vec::new(), + palette: Palette::DARK, + recovery: RecoveryStore::new(cache_dir.join("recovery")), + cache_dir, + next_recovery: Instant::now() + CHECKPOINT_INTERVAL, + recovery_error_reported: false, + python_override: None, + worker_was_ready: false, + allow_close: false, + title: String::new(), + applied_theme: None, + applied_scale: 1.0, + logo: None, + editor_panel_open: true, + } +} + +fn selector_reply(id: crate::worker::protocol::RequestId) -> crate::worker::protocol::Message { + use crate::worker::protocol::{Message, SelectorCandidate, SelectorReply}; + let candidate = |expression: &str, index_based| SelectorCandidate { + expression: expression.to_owned(), + description: String::new(), + index_based, + }; + Message::Selector(SelectorReply { + id, + method: "faces".into(), + candidates: vec![ + candidate(r#".faces(">Z")"#, false), + candidate(".faces()[5]", true), + ], + }) +} + +/// A face picked in the view, as `select` records it. +fn pick_face(state: &mut AppState) { + use crate::scene::{TopologyEntity, TopologySelection}; + let mut mesh = crate::scene::Mesh::new( + vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + vec![[0.0, 0.0, 1.0]; 3], + vec![0, 1, 2], + Vec::new(), + Vec::new(), + ); + mesh.topology.triangle_faces = vec![6]; + let node = crate::scene::SceneNode { + key: "n1".into(), + name: "box".into(), + kind: "Workplane".into(), + inspectable: false, + parts: vec![crate::scene::Part { + mesh: std::sync::Arc::new(mesh), + transform: glam::Mat4::IDENTITY, + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + render_mesh: None, + }], + children: Vec::new(), + visible: true, + color: None, + alpha: None, + edge_color: None, + finish: None, + overrides: Default::default(), + line: None, + script: None, + }; + state.scene.append(vec![node], None); + state.scene.select_only("n1"); + assert!(state.scene.select_topology( + TopologySelection { + node: "n1".into(), + part: 0, + entity: TopologyEntity::Face(6), + position: Default::default(), + }, + false, + )); +} + +/// Pretends a selector request is out, as `request_selector` sends it. +fn awaiting_selector(state: &mut AppState, id: crate::worker::protocol::RequestId) { + state.execution.track(id, Pending::Selector); + state.selector.loading = true; + state.selector.request_id = Some(id); +} + +#[test] +fn stale_selector_preview_replies_do_not_replace_the_current_caret() { + let mut state = test_state("part.faces(\">Z\")"); + state.execution.track(7, Pending::SelectorPreview); + state.selector_preview.request_id = Some(7); + state.handle_message(crate::worker::protocol::Message::SelectorPreview { + id: 6, + active: true, + count: 4, + matches: Vec::new(), + message: None, + }); + assert!(!state.selector_preview.active); + state.handle_message(crate::worker::protocol::Message::SelectorPreview { + id: 7, + active: true, + count: 1, + matches: Vec::new(), + message: Some("No displayed match".into()), + }); + assert_eq!(state.selector_preview.count, 1); + assert_eq!( + state.selector_preview.message.as_deref(), + Some("No displayed match") + ); +} + +#[test] +fn navigation_discards_replies_for_edited_source_and_old_outline_requests() { + use crate::worker::protocol::{Message, NavigationLocation, NavigationMode, OutlineSymbol}; + + let mut state = test_state("old_name = 1\n"); + state.navigation.document = 0; + state.navigation.source = state.document.text.clone(); + state.navigation.outline_request = Some(8); + state.execution.track(7, Pending::Outline { document: 0 }); + state.execution.track(8, Pending::Outline { document: 0 }); + let symbols = vec![OutlineSymbol { + name: "old_name".into(), + kind: "variable".into(), + line: 1, + depth: 0, + }]; + state.handle_message(Message::Outline { + id: 7, + symbols: symbols.clone(), + }); + assert!(state.navigation.symbols.is_empty()); + state.document.text = "new_name = 1\n".into(); + state.handle_message(Message::Outline { id: 8, symbols }); + assert!(state.navigation.symbols.is_empty()); + + state.navigation.navigation_request = Some(9); + state.navigation.navigation_source = "old_name = 1\n".into(); + state.execution.track(9, Pending::Navigate { document: 0 }); + state.handle_message(Message::Navigation { + id: 9, + available: true, + mode: NavigationMode::References, + locations: vec![NavigationLocation { + name: "old_name".into(), + kind: "statement".into(), + path: None, + line: 1, + column: 0, + }], + truncated: false, + }); + assert!(state.navigation.locations.is_empty()); +} + +#[test] +fn a_selector_asked_for_while_loading_is_inserted_when_it_arrives() { + let mut state = test_state("result = cq.Workplane().box(1, 1, 1)\n"); + pick_face(&mut state); + awaiting_selector(&mut state, 7); + state.use_selector(SelectorUse::Insert); + assert_eq!(state.selector.then, Some(SelectorUse::Insert)); + assert!(!state.document.text.contains("faces")); + + // A late reply to an earlier selection changes nothing. + state.handle_message(selector_reply(3)); + assert!(state.selector.reply.is_none()); + + state.handle_message(selector_reply(7)); + assert_eq!(state.selector.then, None); + assert!(!state.selector.loading); + assert_eq!( + state.document.text, ".faces(\">Z\")result = cq.Workplane().box(1, 1, 1)\n", + "inserted at the caret, at the start of a fresh document" + ); + assert_eq!(state.status.as_ref().unwrap().kind, StatusKind::Success); + + // One undo step takes it out again. + state.editor.undo(&mut state.document); + assert_eq!( + state.document.text, + "result = cq.Workplane().box(1, 1, 1)\n" + ); +} + +#[test] +fn copying_a_selector_puts_it_on_the_clipboard_and_flags_index_fallbacks() { + let mut state = test_state(""); + pick_face(&mut state); + awaiting_selector(&mut state, 4); + state.handle_message(selector_reply(4)); + + let ctx = state.ctx.clone(); + let mut output = ctx.run_ui(egui::RawInput::default(), |_| { + state.use_selector(SelectorUse::Copy); + }); + output.textures_delta.clear(); + assert_eq!( + output.platform_output.commands, + [egui::OutputCommand::CopyText(r#".faces(">Z")"#.to_owned())] + ); + assert!(!state.status.as_ref().unwrap().text.contains("index")); + + // The alternative chosen in the panel is used, with a caution. + state.selector.chosen = 1; + let mut output = ctx.run_ui(egui::RawInput::default(), |_| { + state.use_selector(SelectorUse::Copy); + }); + output.textures_delta.clear(); + assert_eq!( + output.platform_output.commands, + [egui::OutputCommand::CopyText(".faces()[5]".to_owned())] + ); + assert!(state.status.as_ref().unwrap().text.contains("by index")); +} + +#[test] +fn a_selector_error_is_kept_and_reported_to_a_waiting_copy() { + let mut state = test_state(""); + pick_face(&mut state); + awaiting_selector(&mut state, 9); + state.use_selector(SelectorUse::Copy); + state.request_failed(Some(9), "Selectors are generated for workplanes".into()); + + assert_eq!( + state.selector.error.as_deref(), + Some("Selectors are generated for workplanes") + ); + assert!(!state.selector.loading); + let status = state.status.as_ref().unwrap(); + assert_eq!(status.kind, StatusKind::Warning); + assert!(status.text.contains("workplanes")); +} + +#[test] +fn selector_actions_need_picked_entities() { + let mut state = test_state(""); + state.use_selector(SelectorUse::Insert); + assert_eq!(state.status.as_ref().unwrap().kind, StatusKind::Warning); + assert!(state.document.text.is_empty()); +} + +#[test] +fn the_console_gets_the_picked_entities_and_the_selected_objects() { + use crate::worker::protocol::TopologyKind; + let mut state = test_state(""); + assert_eq!(state.console_selection(), Default::default()); + + pick_face(&mut state); + let selection = state.console_selection(); + assert_eq!(selection.objects, ["n1"]); + let [entity] = selection.entities.as_slice() else { + panic!("one picked face"); + }; + assert_eq!( + (entity.key.as_str(), entity.kind, entity.identifier), + ("n1", TopologyKind::Face, 6) + ); +} + +#[test] +fn a_parameter_change_rewrites_its_literal_and_renders_once_it_settles() { + let script = "width = 40 # [10, 100]\nheight = 12.5\nresult = box(width, height)\n"; + let mut state = test_state(script); + + state.set_parameter("height", 2, 20.25); + assert_eq!( + state.document.text, + "width = 40 # [10, 100]\nheight = 20.2\nresult = box(width, height)\n" + ); + assert!(state.document.is_modified()); + let due = state.parameter_render_at.expect("a render is scheduled"); + + // Not yet: the drag may go on. + state.parameter_render_at = Some(f64::MAX); + let ctx = state.ctx.clone(); + state.poll_parameter_render(&ctx); + assert!(state.parameter_render_at.is_some()); + assert!(state.status.is_none()); + + // Once due, it renders (here: reports that Python is not running). + state.parameter_render_at = Some(due - 10.0); + state.poll_parameter_render(&ctx); + assert!(state.parameter_render_at.is_none()); + assert!(state.status.as_ref().unwrap().text.contains("Python")); +} + +#[test] +fn a_parameter_is_found_again_by_line_and_name() { + let mut state = test_state("width = 40\n"); + state.set_parameter("width", 1, 55.0); + assert_eq!(state.document.text, "width = 55\n"); + // Edited meanwhile into something that is no longer a parameter. + state.document.text = "width = w0\n".to_owned(); + state.set_parameter("width", 1, 60.0); + assert_eq!(state.document.text, "width = w0\n"); + // Another name on that line is another parameter. + state.document.text = "depth = 3\n".to_owned(); + state.set_parameter("width", 1, 60.0); + assert_eq!(state.document.text, "depth = 3\n"); +} + +#[test] +fn a_commented_range_bounds_the_written_value() { + let mut state = test_state("width = 40 # [10, 100]\n"); + state.set_parameter("width", 1, 400.0); + assert_eq!(state.document.text, "width = 100 # [10, 100]\n"); +} + +/// A scene with one node made on `line` by a run of `ran`. +fn shown_from_run(state: &mut AppState, ran: &str, line: usize) { + pick_face(state); + let script = std::sync::Arc::new(crate::scene::RunScript { + document: state.document_generation, + text: ran.to_owned(), + }); + let node = state.scene.find_mut("n1").unwrap(); + node.line = Some(line); + node.attach_script(&script); +} + +fn status_text(state: &AppState) -> &str { + &state.status.as_ref().unwrap().text +} + +#[test] +fn going_to_the_source_follows_the_edits_made_since_the_run() { + let ran = "import cadquery as cq\nbox = cq.Workplane().box(1, 2, 3)\n"; + let mut state = test_state(ran); + shown_from_run(&mut state, ran, 2); + + state.go_to_source("n1", None); + assert_eq!(status_text(&state), "Line 2"); + assert_eq!(state.status.as_ref().unwrap().kind, StatusKind::Info); + + state.document.text = format!("# a box\n{ran}"); + state.go_to_source("n1", None); + assert_eq!(status_text(&state), "Line 3 (line 2 when the script ran)"); + + state.document.text = state.document.text.replace("box(1, 2, 3)", "box(1, 2, 4)"); + state.go_to_source("n1", None); + assert_eq!(state.status.as_ref().unwrap().kind, StatusKind::Warning); + assert!(status_text(&state).contains("edited since the last run")); + + state.document.text = "import cadquery as cq\n".to_owned(); + state.go_to_source("n1", None); + assert!(status_text(&state).contains("deleted")); +} + +#[test] +fn objects_of_another_document_or_the_console_have_no_source_here() { + let ran = "box = cq.Workplane().box(1, 1, 1)\n"; + let mut state = test_state(ran); + shown_from_run(&mut state, ran, 1); + state.document_generation += 1; + state.go_to_source("n1", None); + assert!(status_text(&state).contains("another script")); + + let node = state.scene.find_mut("n1").unwrap(); + node.script = None; + state.go_to_source("n1", None); + assert!(status_text(&state).contains("console")); +} + +#[test] +fn inspector_steps_go_to_the_line_that_made_them() { + use crate::worker::protocol::{StackFrame, StackItem}; + let ran = "plate = (\n cq.Workplane()\n .box(4, 4, 1)\n .faces(\">Z\")\n)\n"; + let mut state = test_state(ran); + shown_from_run(&mut state, ran, 4); + state.inspector.key = Some("n1".into()); + state.inspector.frames = vec![StackFrame { + type_name: "Workplane".into(), + value: String::new(), + line: Some(4), + items: vec![StackItem { + type_name: "Solid".into(), + value: String::new(), + displayable: true, + line: Some(3), + }], + }]; + + state.go_to_source("n1", Some((0, Some(0)))); + assert_eq!(status_text(&state), "Line 3"); + state.go_to_source("n1", Some((0, None))); + assert_eq!(status_text(&state), "Line 4"); + // A step of another object's stack is not this node's. + state.inspector.key = Some("other".into()); + state.go_to_source("n1", Some((0, None))); + assert!(status_text(&state).contains("No script line")); +} + +#[test] +fn only_the_run_that_made_the_nodes_gives_them_its_script() { + let mut state = test_state("x = 1\n"); + let script = std::sync::Arc::new(crate::scene::RunScript { + document: 0, + text: "x = 1\n".into(), + }); + state.run_script = Some((7, script)); + pick_face(&mut state); + let mut nodes = std::mem::take(&mut state.scene.nodes); + state.attach_run_script(6, &mut nodes); + assert!(nodes[0].script.is_none()); + state.attach_run_script(7, &mut nodes); + assert!(nodes[0].script.is_some()); +} + +#[test] +fn objects_are_measured_when_no_entity_is_picked() { + let mut state = test_state(""); + pick_face(&mut state); + let (selections, objects) = state.measured(); + assert_eq!(selections.len(), 1); + assert!(objects.is_empty(), "picked entities come first"); + + state.scene.clear_topology_selection(); + let (selections, objects) = state.measured(); + assert!(selections.is_empty()); + assert_eq!(objects, ["n1"]); +} + +#[test] +fn measurement_code_goes_to_the_clipboard_with_its_check() { + use crate::worker::protocol::Message; + let mut state = test_state(""); + state.request_measurement_code(); + assert!(status_text(&state).contains("Select objects")); + + let ctx = state.ctx.clone(); + state.execution.track(11, Pending::MeasurementCode); + let mut output = ctx.run_ui(egui::RawInput::default(), |_| { + state.handle_message(Message::MeasurementCode { + id: 11, + code: "area_1 = face_1.Area() # 40\n".into(), + verified: true, + problem: None, + }); + }); + output.textures_delta.clear(); + assert_eq!( + output.platform_output.commands, + [egui::OutputCommand::CopyText( + "area_1 = face_1.Area() # 40\n".into() + )] + ); + assert_eq!(state.status.as_ref().unwrap().kind, StatusKind::Success); + + state.execution.track(12, Pending::MeasurementCode); + let mut output = ctx.run_ui(egui::RawInput::default(), |_| { + state.handle_message(Message::MeasurementCode { + id: 12, + code: "shape_1 = obj.val()\n".into(), + verified: false, + problem: Some("the Workplane is not a variable of the script".into()), + }); + }); + output.textures_delta.clear(); + assert_eq!(state.status.as_ref().unwrap().kind, StatusKind::Warning); + assert!(status_text(&state).contains("not a variable")); + + // A reply nobody asked for is not copied. + let mut output = ctx.run_ui(egui::RawInput::default(), |_| { + state.handle_message(Message::MeasurementCode { + id: 99, + code: "stale\n".into(), + verified: true, + problem: None, + }); + }); + output.textures_delta.clear(); + assert!(output.platform_output.commands.is_empty()); + + state.execution.track(13, Pending::MeasurementCode); + state.request_failed(Some(13), "Not available while debugging".into()); + assert!(status_text(&state).contains("Cannot write the measurement as code")); +} + +#[test] +fn explode_and_isolate_commands_change_what_the_view_shows() { + let mut state = test_state(""); + + // Isolating needs a selection. + state.execute(Action::ToggleIsolate); + assert!(!state.scene.is_isolating()); + assert_eq!(state.status.as_ref().unwrap().kind, StatusKind::Info); + + pick_face(&mut state); + state.execute(Action::ToggleIsolate); + assert!(state.scene.is_isolating()); + state.execute(Action::ToggleIsolate); + assert!(!state.scene.is_isolating(), "the same command ends it"); + + state.execute(Action::ToggleIsolate); + state.scene.set_visible("n1", false); + state.execute(Action::ShowAll); + assert!(!state.scene.is_isolating()); + assert!(state.scene.find("n1").unwrap().visible); + + state.execute(Action::ToggleExplode); + assert!(state.viewer.explode_controls); + assert!(state.scene.explode() > 0.0, "opening spreads the parts"); + state.execute(Action::SetExplode(1.5)); + assert_eq!(state.scene.explode(), 1.5); + state.execute(Action::ToggleExplode); + assert!(!state.viewer.explode_controls); + assert_eq!(state.scene.explode(), 0.0, "closing assembles them"); +} + +#[test] +fn named_views_follow_their_file() { + use crate::document::Encoding; + let dir = std::env::temp_dir().join(format!("cq-editor-views-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (a, b) = (dir.join("a.py"), dir.join("b.py")); + std::fs::write(&a, "a = 1\n").unwrap(); + std::fs::write(&b, "b = 2\n").unwrap(); + + let mut state = test_state(""); + state.open_path_with(&a, Encoding::Utf8); + state.execute(Action::SaveView(Some("front".into()))); + assert_eq!(state.viewer.named_views.len(), 1); + assert_eq!(state.status.as_ref().unwrap().kind, StatusKind::Success); + + state.open_path_with(&b, Encoding::Utf8); + assert!(state.viewer.named_views.is_empty(), "b has no views"); + state.open_path_with(&a, Encoding::Utf8); + assert_eq!(state.viewer.named_views[0].name, "front"); + + // Going to a view brings its projection back. + state.settings.viewer.projection = crate::settings::Projection::Perspective; + state.execute(Action::GoToView(0)); + assert_eq!( + state.settings.viewer.projection, + crate::settings::Projection::Orthographic + ); + + // A new document starts without views. + state.execute(Action::DeleteView(0)); + state.execute(Action::SaveView(None)); + state.open_path_with(&b, Encoding::Utf8); + state.open_path_with(&a, Encoding::Utf8); + assert_eq!(state.viewer.named_views[0].name, "View 1"); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_ground_grid_and_scale_bar_are_toggled_from_the_view_menu() { + let mut state = test_state(""); + assert!(state.settings.viewer.ground_grid && state.settings.viewer.scale_bar); + state.execute(Action::ToggleGroundGrid); + state.execute(Action::ToggleScaleBar); + assert!(!state.settings.viewer.ground_grid && !state.settings.viewer.scale_bar); +} + +#[test] +fn an_interrupted_run_is_reported_as_stopped_not_as_an_error() { + let mut state = test_state("while True:\n pass\n"); + state.execution.started(4, false); + let message: crate::worker::protocol::Message = serde_json::from_str( + r#"{"type":"run_finished","id":4,"ok":false,"debug":false,"stopped":false, + "cancelled":false,"interrupted":true,"objects":null,"variables":null, + "error":{"type_name":"KeyboardInterrupt","message":"","frames":[],"line":2, + "text":"Traceback (most recent call last):\nKeyboardInterrupt\n"}, + "duration":1.0}"#, + ) + .unwrap(); + state.handle_message(message); + + let status = state.status.as_ref().unwrap(); + assert_eq!(status.kind, StatusKind::Info); + assert_eq!(status.text, "Stopped at line 2"); + assert_eq!(state.editor.error_line, None, "no error marker"); + assert!( + state.traceback.is_none(), + "the view does not offer it as an error" + ); + assert!(!state.is_busy()); +} + +#[test] +fn a_profiled_run_puts_its_times_in_the_gutter_of_the_edited_script() { + let run_text = "import time\ntime.sleep(1)\nx = 1\n"; + let mut state = test_state(run_text); + state.execution.started(4, false); + state.run_script = Some(( + 4, + std::sync::Arc::new(crate::scene::RunScript { + document: 0, + text: run_text.to_owned(), + }), + )); + state.editor.sync_markers(run_text); + // A line was added while it ran. + state.document.text = format!("# timing\n{run_text}"); + let message: crate::worker::protocol::Message = serde_json::from_str( + r#"{"type":"run_finished","id":4,"ok":true,"debug":false,"stopped":false, + "objects":[],"variables":[],"error":null,"duration":1.0, + "profile":{"lines":[{"line":1,"seconds":0.002,"hits":1}, + {"line":2,"seconds":1.001,"hits":1},{"line":3,"seconds":0.0001,"hits":1}], + "operations":[]}}"#, + ) + .unwrap(); + state.handle_message(message); + + let lines: Vec<_> = state.editor.line_profile.keys().copied().collect(); + assert_eq!(lines, [2, 3, 4]); + assert_eq!(state.editor.line_profile[&3].seconds, 1.001); + let status = state.status.as_ref().unwrap(); + assert!( + status.text.contains("slowest line is untitled:3 (1.0 s)"), + "{}", + status.text + ); + + state.execute(Action::ClearProfile); + assert!(state.editor.line_profile.is_empty()); +} + +#[test] +fn a_pause_in_a_module_opens_its_tab_and_closing_it_ends_debugging() { + let dir = std::env::temp_dir().join(format!("cq-editor-debug-modules-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let main = dir.join("main.py"); + let module = dir.join("helper.py"); + std::fs::write(&main, "import helper\nhelper.work()\n").unwrap(); + std::fs::write(&module, "def work():\n return 4\n").unwrap(); + let mut state = test_state(""); + state.open_path(&main); + let main_generation = state.document_generation; + state.open_path(&module); + let module_generation = state.document_generation; + state.editor.breakpoints.insert(2); + state.activate(main_generation); + let (main_breaks, modules) = state.open_breakpoints(main_generation); + assert!(main_breaks.is_empty()); + assert_eq!(modules[&module.display().to_string()], [2]); + + state.execution.started(17, true); + state.run_script = Some(( + 17, + std::sync::Arc::new(crate::scene::RunScript { + document: main_generation, + text: state.document.text.clone(), + }), + )); + let message: crate::worker::protocol::Message = serde_json::from_value(serde_json::json!({ + "type": "debug_paused", "id": 17, "line": 2, + "path": module.display().to_string(), "variables": [], "objects": [] + })) + .unwrap(); + state.handle_message(message); + assert_eq!(state.document_generation, module_generation); + assert_eq!(state.editor.debug_line, Some(2)); + state.close_now(module_generation); + assert!(!state.is_debugging()); + assert_eq!(state.document_generation, main_generation); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn closing_the_paused_run_document_ends_the_session() { + let mut state = test_state("a = 1\n"); + state.execution.started(19, true); + state.run_script = Some(( + 19, + std::sync::Arc::new(crate::scene::RunScript { + document: state.document_generation, + text: state.document.text.clone(), + }), + )); + assert!(!state.execution.paused(19)); + state.close_now(state.document_generation); + assert!(!state.is_debugging()); +} + +#[test] +fn module_profile_lines_appear_in_the_module_gutter() { + let dir = + std::env::temp_dir().join(format!("cq-editor-profile-modules-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let main = dir.join("main.py"); + let module = dir.join("helper.py"); + std::fs::write(&main, "import helper\nhelper.work()\n").unwrap(); + std::fs::write(&module, "def work():\n return 4\n").unwrap(); + let mut state = test_state(""); + state.open_path(&main); + let main_generation = state.document_generation; + state.open_path(&module); + let module_generation = state.document_generation; + state.activate(main_generation); + state.execution.started(18, false); + state.run_script = Some(( + 18, + std::sync::Arc::new(crate::scene::RunScript { + document: main_generation, + text: state.document.text.clone(), + }), + )); + let message: crate::worker::protocol::Message = serde_json::from_value(serde_json::json!({ + "type": "run_finished", "id": 18, "ok": true, "debug": false, "stopped": false, + "objects": [], "variables": [], "error": null, "duration": 0.1, + "profile": {"lines": [{"file": module.display().to_string(), "line": 2, + "seconds": 0.1, "hits": 1}], "operations": [], + "sources": {}} + })) + .unwrap(); + state.handle_message(message); + assert!( + state + .open_mut(module_generation) + .unwrap() + .1 + .line_profile + .contains_key(&2) + ); + state.execute(Action::ClearProfile); + assert!( + state + .open_mut(module_generation) + .unwrap() + .1 + .line_profile + .is_empty() + ); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn new_environments_go_to_a_free_folder() { + let root = std::env::temp_dir().join(format!("cq-editor-free-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let preferred = root.join("cadquery"); + assert_eq!(unused_folder(&preferred), preferred, "missing: free"); + std::fs::create_dir_all(&preferred).unwrap(); + assert_eq!(unused_folder(&preferred), preferred, "empty: free"); + std::fs::write(preferred.join("pyvenv.cfg"), "").unwrap(); + assert_eq!(unused_folder(&preferred), root.join("cadquery-2")); + std::fs::create_dir_all(root.join("cadquery-2/bin")).unwrap(); + assert_eq!(unused_folder(&preferred), root.join("cadquery-3")); + let _ = std::fs::remove_dir_all(&root); + + let mut state = test_state(""); + state.execute(Action::InstallPackages); + assert!(state.dialogs.environment.is_some()); +} + +fn updates_reply(id: u64, editor: &str) -> crate::worker::protocol::Message { + serde_json::from_str(&format!( + r#"{{"type":"updates","id":{id},"current":"2.8.0","newer":[],"editor":{editor}}}"# + )) + .unwrap() +} + +#[test] +fn the_daily_check_only_speaks_when_a_newer_cq_editor_is_out() { + let mut state = test_state(""); + let newer = r#"{"current":"0.8.0","newer":[{"tag":"v99.0.0","name":"99", + "url":"https://github.com/igors93/CQ-editor/releases/tag/v99.0.0"}]}"#; + + state + .execution + .track(1, Pending::Updates { automatic: true }); + state.handle_message(updates_reply(1, r#"{"current":"0.8.0","newer":[]}"#)); + assert!( + state.status.is_none() && state.dialogs.message.is_none(), + "silent" + ); + + state + .execution + .track(2, Pending::Updates { automatic: true }); + state.handle_message(updates_reply(2, newer)); + assert!(state.dialogs.message.is_none()); + assert!(state.status.as_ref().unwrap().text.contains("v99.0.0")); + assert_eq!( + state.settings.general.newer_release.as_ref().unwrap().tag, + "v99.0.0" + ); + + // A failed daily check is only logged. + state + .execution + .track(3, Pending::Updates { automatic: true }); + state.handle_message(crate::worker::protocol::Message::Error { + id: Some(3), + message: "offline".into(), + }); + assert!(state.dialogs.message.is_none()); +} + +#[test] +fn checking_by_hand_reports_cq_editor_and_cadquery() { + let mut state = test_state(""); + state + .execution + .track(4, Pending::Updates { automatic: false }); + state.handle_message(updates_reply(4, r#"{"current":"0.8.0","newer":[]}"#)); + let message = state.dialogs.message.as_ref().unwrap(); + assert_eq!(message.title, "No updates available"); + assert!(message.text.contains("is the latest version")); + assert!(message.text.contains("CadQuery 2.8.0")); +} + +#[test] +fn console_results_from_the_worker_reach_the_console() { + use crate::app::execution::Pending; + use crate::worker::protocol::{DisplayImage, DisplayOutput, Message}; + + let mut state = test_state(""); + state.execution.track(3, Pending::Console); + state.handle_message(Message::Display(DisplayOutput { + id: 3, + text: "
".into(), + image: Some(DisplayImage { + size: [2, 1], + rgba: vec![255; 8], + }), + })); + let entry = state.console.entries.last().unwrap(); + assert!(entry.image.is_some()); + assert_eq!(entry.text, "
\n"); + + state.handle_message(Message::Display(DisplayOutput { + id: 4, + text: "stale".into(), + image: None, + })); + assert_eq!(state.console.entries.len(), 1, "stale output is ignored"); +} + +// -- the dock layout --------------------------------------------------------- + +fn test_app() -> CqEditorApp { + let mut dock = panels::default_layout(); + label_tab_menus(&mut dock); + CqEditorApp { + dock, + maximized: None, + state: test_state(""), + } +} + +fn panels_shown(app: &CqEditorApp) -> Vec { + let mut tabs: Vec = app.dock.iter_all_tabs().map(|(_, tab)| *tab).collect(); + tabs.sort_by_key(|tab| Tab::ALL.iter().position(|t| t == tab)); + tabs +} + +#[test] +fn a_maximized_panel_fills_the_window_until_it_is_restored() { + let mut app = test_app(); + let layout = panels_shown(&app); + assert_eq!( + app.dock.translations.tab_context_menu.eject_button, + "Float in a Window" + ); + + app.execute(Action::ToggleMaximize(Some(Tab::Viewer))); + assert_eq!(panels_shown(&app), [Tab::Viewer]); + assert!( + app.state + .status + .as_ref() + .unwrap() + .text + .contains("double-click") + ); + app.execute(Action::ToggleMaximize(None)); + assert_eq!(panels_shown(&app), layout); + + // Going to a line needs the editor: the layout comes back. + app.execute(Action::ToggleMaximize(Some(Tab::Objects))); + app.execute(Action::GoToLine(1)); + assert_eq!(panels_shown(&app), layout); + + // So does showing or hiding a panel, and resetting the layout. + app.execute(Action::ToggleMaximize(Some(Tab::Console))); + app.execute(Action::TogglePanel(Tab::Log)); + assert!(app.maximized.is_none()); + assert!(!panels_shown(&app).contains(&Tab::Log)); + app.execute(Action::ToggleMaximize(Some(Tab::Console))); + app.execute(Action::ResetLayout); + assert_eq!(panels_shown(&app), layout); +} + +#[derive(Default)] +struct MemoryStorage(std::collections::HashMap); + +impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} +} + +#[test] +fn a_closed_editor_comes_back_whenever_a_file_or_a_line_is_shown() { + let dir = std::env::temp_dir().join(format!("cq-editor-editor-panel-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.py"), "a = 1\n").unwrap(); + let mut app = test_app(); + app.state.recovery = RecoveryStore::new(dir.join(".recovery")); + + for action in [ + Action::OpenPath(dir.join("a.py")), + Action::NewFile, + Action::PreviousTab, + Action::GoToLine(1), + ] { + app.execute(Action::TogglePanel(Tab::Editor)); + assert!(!panels_shown(&app).contains(&Tab::Editor)); + app.execute(action.clone()); + assert!(panels_shown(&app).contains(&Tab::Editor), "{action:?}"); + } + // Next to the 3D view, not inside its panel. + let editor = app.dock.find_tab(&Tab::Editor).unwrap(); + let viewer = app.dock.find_tab(&Tab::Viewer).unwrap(); + assert_ne!(editor.node_path(), viewer.node_path()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_layout_saved_without_the_editor_gets_it_back() { + let without = |tabs: &[Tab]| { + let mut dock = panels::default_layout(); + for tab in tabs { + let path = dock.find_tab(tab).unwrap(); + dock.remove_tab(path); + } + dock + }; + let restored = restored_layout(Some(without(&[Tab::Editor, Tab::Console]))); + assert!(restored.find_tab(&Tab::Editor).is_some()); + assert!( + restored.find_tab(&Tab::Console).is_none(), + "the rest of the layout is kept" + ); + // Without the 3D view, or without a saved layout: the default one. + for saved in [Some(without(&[Tab::Viewer])), None] { + let restored = restored_layout(saved); + assert!(restored.find_tab(&Tab::Viewer).is_some()); + assert!(restored.find_tab(&Tab::Console).is_some()); + } +} + +#[test] +fn restored_dock_draws_the_editor_and_viewer_without_a_window() { + struct Titles(Vec); + impl egui_dock::TabViewer for Titles { + type Tab = Tab; + + fn id(&mut self, tab: &mut Tab) -> egui::Id { + egui::Id::new(*tab) + } + + fn title(&mut self, tab: &mut Tab) -> egui::WidgetText { + self.0.push(*tab); + tab.title().into() + } + + fn ui(&mut self, ui: &mut egui::Ui, tab: &mut Tab) { + ui.label(tab.title()); + } + } + + let mut saved = panels::default_layout(); + let editor = saved.find_tab(&Tab::Editor).unwrap(); + saved.remove_tab(editor); + let mut dock = restored_layout(Some(saved)); + let ctx = egui::Context::default(); + let mut titles = Titles(Vec::new()); + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { + egui_dock::DockArea::new(&mut dock).show_inside(ui, &mut titles); + }); + output.textures_delta.clear(); + assert!(titles.0.contains(&Tab::Editor)); + assert!(titles.0.contains(&Tab::Viewer)); + assert!(!output.shapes.is_empty()); +} + +#[test] +fn a_drawn_modal_blocks_global_shortcuts_behind_it() { + let mut state = test_state("value = 1\n"); + state.dialogs.info( + "File changed on disk", + "Resolve this before closing the tab", + ); + let ctx = state.ctx.clone(); + let press_close = || egui::RawInput { + events: vec![egui::Event::Key { + key: egui::Key::W, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::COMMAND, + }], + ..Default::default() + }; + let mut output = ctx.run_ui(press_close(), |_| { + state.begin_frame(&ctx); + crate::dialogs::show(&ctx, &mut state); + }); + output.textures_delta.clear(); + assert!(!output.shapes.is_empty(), "the modal is actually rendered"); + assert!(state.dialogs.modal_open()); + assert!(state.actions.is_empty()); + + state.dialogs.message = None; + let mut output = ctx.run_ui(press_close(), |_| state.begin_frame(&ctx)); + output.textures_delta.clear(); + assert_eq!(state.actions, [Action::CloseTab]); +} + +#[test] +fn required_panels_return_to_their_workspace() { + let mut app = test_app(); + for tab in [Tab::Console, Tab::Traceback, Tab::Project] { + if let Some(path) = app.dock.find_tab(&tab) { + app.dock.remove_tab(path); + } + app.show_panel(tab); + assert!(app.dock.find_tab(&tab).is_some()); + } + let console = app.dock.find_tab(&Tab::Console).unwrap(); + let traceback = app.dock.find_tab(&Tab::Traceback).unwrap(); + assert_eq!(console.node_path(), traceback.node_path()); + let project = app.dock.find_tab(&Tab::Project).unwrap(); + let editor = app.dock.find_tab(&Tab::Editor).unwrap(); + assert_ne!(project.node_path(), editor.node_path()); + + app.execute(Action::TogglePanel(Tab::Console)); + app.execute(Action::ResetConsole); + assert!(app.dock.find_tab(&Tab::Console).is_some()); +} + +#[test] +fn a_result_too_large_to_transfer_ends_the_run_and_restarts_python() { + let mut state = test_state(""); + // No process is started in tests. + state.python_override = Some("no-such-python-for-tests".into()); + state.execution.started(5, false); + assert!(state.is_busy()); + + state.worker_protocol_failed("Python sent a message too large to transfer".into()); + assert!(!state.is_busy(), "the run no longer waits for an answer"); + let message = state.dialogs.message.as_ref().expect("told why"); + assert_eq!(message.title, "Cannot show the result"); + assert!(message.text.contains("too large to transfer")); + assert_ne!(state.worker.problem(), Some(worker::Problem::NoCadQuery)); +} + +#[test] +fn invalid_geometry_stops_export_for_a_user_decision() { + use crate::worker::protocol::{GeometryReport, Message}; + let mut state = test_state(""); + state.execution.track(17, Pending::Export); + state.handle_message(Message::GeometryInvalid { + id: 17, + reports: vec![GeometryReport { + key: "n1".into(), + name: "open shell".into(), + valid: false, + solids: 0, + open_shells: 1, + non_manifold_edges: 0, + issues: vec!["1 open shell(s)".into()], + }], + interferences: vec![], + }); + assert!( + state + .dialogs + .geometry + .as_ref() + .is_some_and(|dialog| dialog.for_export) + ); + assert!(!state.geometry_checks["n1"].valid); + assert!(state.dialogs.modal_open()); +} + +#[test] +fn interference_check_keeps_both_parts_in_the_review() { + use crate::worker::protocol::{InterferencePart, InterferenceReport, Message}; + let mut state = test_state(""); + state.execution.track(18, Pending::Check); + state.handle_message(Message::GeometryChecked { + id: 18, + reports: vec![], + interferences: vec![InterferenceReport { + first: InterferencePart { + key: "plate".into(), + name: "plate".into(), + part: 0, + solid: 0, + }, + second: InterferencePart { + key: "pin".into(), + name: "pin".into(), + part: 0, + solid: 0, + }, + kind: "interference".into(), + overlap_volume: Some(43.2), + distance: Some(0.0), + point: Some([0.0, 0.0, 0.0]), + reason: None, + allowance_reason: None, + }], + }); + let review = state.dialogs.geometry.as_ref().expect("review opened"); + assert_eq!(review.interferences.len(), 1); + assert_eq!(review.interferences[0].second.name, "pin"); +} + +#[test] +fn overlap_mesh_reply_only_applies_to_the_pair_still_selected() { + use crate::worker::protocol::{InterferencePart, InterferenceReport, Mesh, Message}; + let mut state = test_state(""); + let first = InterferencePart { + key: "plate".into(), + name: "plate".into(), + part: 0, + solid: 0, + }; + let second = InterferencePart { + key: "pin".into(), + name: "pin".into(), + part: 0, + solid: 0, + }; + state.execution.track(20, Pending::Check); + state.handle_message(Message::GeometryChecked { + id: 20, + reports: vec![], + interferences: vec![InterferenceReport { + first: first.clone(), + second: second.clone(), + kind: "interference".into(), + overlap_volume: Some(1.0), + distance: Some(0.0), + point: Some([0.0, 0.0, 0.0]), + reason: None, + allowance_reason: None, + }], + }); + let review = state.dialogs.geometry.as_mut().unwrap(); + let mut other_pair = review.interferences[0].clone(); + other_pair.second.key = "other".into(); + other_pair.second.name = "other".into(); + review.interferences.push(other_pair); + review.selected_pair = Some(1); + state.execution.track( + 21, + Pending::InterferenceGeometry { + first: first.clone(), + second: second.clone(), + }, + ); + state.handle_message(Message::InterferenceGeometry { + id: 21, + mesh: Box::::default(), + }); + assert!(state.scene.overlay.meshes.is_empty()); + + state.dialogs.geometry.as_mut().unwrap().selected_pair = Some(0); + state + .execution + .track(22, Pending::InterferenceGeometry { first, second }); + state.handle_message(Message::InterferenceGeometry { + id: 22, + mesh: Box::::default(), + }); + assert_eq!(state.scene.overlay.meshes.len(), 1); +} + +#[test] +fn the_empty_view_says_when_the_editor_is_closed() { + let mut state = test_state(""); + assert_eq!(state.empty_view_hint(), "Press F5 to render the script"); + state.editor_panel_open = false; + assert!( + state + .empty_view_hint() + .ends_with("the editor is closed: View > Editor") + ); +} + +#[test] +fn the_whole_layout_is_saved_while_a_panel_is_maximized() { + let mut app = test_app(); + app.execute(Action::ToggleMaximize(Some(Tab::Editor))); + let mut storage = MemoryStorage::default(); + eframe::App::save(&mut app, &mut storage); + let saved: DockState = eframe::get_value(&storage, LAYOUT_KEY).unwrap(); + assert!(saved.find_tab(&Tab::Viewer).is_some()); + assert!(saved.find_tab(&Tab::Console).is_some()); +} + +#[test] +fn modified_parameters_can_be_restored_to_their_initial_values_and_undone() { + let initial = "width = 40\nheight = 20.5\n"; + let mut state = test_state(initial); + state.execute(Action::SetParameter { + name: "width".into(), + line: 1, + value: 65.0, + }); + state.execute(Action::SetParameter { + name: "height".into(), + line: 2, + value: 30.0, + }); + assert_eq!(state.document.text, "width = 65\nheight = 30.0\n"); + + state.execute(Action::ResetParameters); + assert_eq!(state.document.text, initial); + + state.execute(Action::Undo); + assert_eq!(state.document.text, "width = 65\nheight = 30.0\n"); +} diff --git a/tests/rust/app/test_cli.rs b/tests/rust/app/test_cli.rs new file mode 100644 index 000000000..bb10ee1c1 --- /dev/null +++ b/tests/rust/app/test_cli.rs @@ -0,0 +1,30 @@ +use super::*; + +fn parse(args: &[&str]) -> Result { + parse_args(args.iter().map(|s| s.to_string())) +} + +#[test] +fn parses_file_and_python() { + let options = parse(&["--python", "/opt/py", "part.py"]).unwrap(); + assert_eq!(options.python.as_deref(), Some("/opt/py")); + assert_eq!(options.file, Some(PathBuf::from("part.py"))); + assert!(parse(&["--bogus"]).is_err()); + assert!(parse(&["a.py", "b.py"]).is_err()); + assert!(parse(&["--python"]).is_err()); +} + +#[test] +fn window_icon_decodes_the_embedded_logo() { + // The 256 px frame (PNG, like the 64 to 192 px ones) is the one decoded. + let logo = image::load_from_memory_with_format(app::LOGO_ICO, image::ImageFormat::Ico) + .unwrap() + .to_rgba8(); + assert_eq!(logo.dimensions(), (256, 256)); + let corner = *logo.get_pixel(0, 0); + assert!(logo.pixels().any(|pixel| *pixel != corner)); + + let icon = window_icon(); + assert_eq!((icon.width, icon.height), (128, 128)); + assert_eq!(icon.rgba.len(), 128 * 128 * 4); +} diff --git a/tests/rust/app/test_command_palette.rs b/tests/rust/app/test_command_palette.rs new file mode 100644 index 000000000..8ba4ddb50 --- /dev/null +++ b/tests/rust/app/test_command_palette.rs @@ -0,0 +1,81 @@ +use super::*; + +fn labels(found: &[Command]) -> Vec<&str> { + found.iter().map(|command| command.label.as_str()).collect() +} + +#[test] +fn every_command_with_a_shortcut_can_be_found() { + let listed = menu_commands(); + for (action, _) in commands::shortcuts() { + assert!( + listed.iter().any(|command| command.action == action), + "{action:?} is missing from the palette" + ); + } +} + +#[test] +fn queries_match_letters_in_order_and_ignore_case() { + assert!(score("rnd", "Run: Render").is_some()); + assert!(score("RENDER", "Run: Render").is_some()); + assert!(score("rendr", "Run: Render").is_some()); + assert_eq!(score("xyz", "Run: Render"), None); + // Out of order is not a match. + assert_eq!(score("redner", "Run: Render"), None); + // An empty query lists everything. + assert_eq!(score(" ", "anything"), Some(0)); + // A word start beats letters scattered inside words. + assert!(score("st", "Run: Stop") > score("st", "View: Show Last")); +} + +#[test] +fn whole_words_and_word_starts_come_first() { + let found = matches(menu_commands(), "step"); + assert_eq!(labels(&found)[..3], ["Step", "Step In", "Step Out"]); + + let found = matches(menu_commands(), "save as"); + assert_eq!(found[0].label, "Save As…"); + + // The category counts too: "run stop" finds Run: Stop. + let found = matches(menu_commands(), "run stop"); + assert_eq!(found[0].action, Action::Stop); + + let found = matches(menu_commands(), "exp stl"); + assert_eq!(found[0].action, Action::Export(ExportFormat::Stl)); + + let found = matches(menu_commands(), "max"); + assert_eq!(found[0].action, Action::ToggleMaximize(None)); +} + +#[test] +fn only_commands_usable_now_are_offered() { + let state = crate::app::tests::test_state("x = 1\n"); + let offered = commands(&state); + let has = |action: &Action| offered.iter().any(|command| command.action == *action); + assert!(has(&Action::Render)); + assert!(has(&Action::OpenFolder)); + assert!(!has(&Action::Debug(DebugAction::Step)), "not paused"); + assert!( + !has(&Action::Export(ExportFormat::Step)), + "nothing to export" + ); + assert!(!has(&Action::CloseFolder), "no folder"); + assert!(!has(&Action::CommandPalette), "already open"); +} + +#[test] +fn favorite_commands_appear_first_and_persist_in_settings() { + let mut settings = crate::settings::Settings::default(); + let id = "Tools: Check Geometry"; + assert!(!settings.is_favorite_command(id)); + assert!(settings.toggle_favorite_command(id)); + assert!(settings.is_favorite_command(id)); + + let ordered = matches_with_favorites(menu_commands(), "", &settings.favorite_commands); + assert_eq!(ordered[0].id(), id); + assert_eq!(ordered[0].action, Action::CheckGeometry); + + assert!(!settings.toggle_favorite_command(id)); + assert!(!settings.is_favorite_command(id)); +} diff --git a/tests/rust/app/test_commands.rs b/tests/rust/app/test_commands.rs new file mode 100644 index 000000000..cc744d4cd --- /dev/null +++ b/tests/rust/app/test_commands.rs @@ -0,0 +1,145 @@ +use super::*; + +#[test] +fn specific_shortcuts_come_first() { + let all = shortcuts(); + let position = |action: &Action| all.iter().position(|(a, _)| a == action).unwrap(); + assert!(position(&Action::View(StandardView::Front)) < position(&Action::Render)); + assert!(position(&Action::SaveAs) < position(&Action::Save)); + assert!(position(&Action::Stop) < position(&Action::ToggleDebug)); +} + +#[test] +fn menus_find_their_shortcuts() { + assert_eq!(shortcut(&Action::Render), Some(key(Key::F5))); + assert_eq!(shortcut(&Action::Autocomplete), Some(ctrl(Key::Space))); + assert_eq!(shortcut(&Action::FindPrevious), Some(alt(Key::F3))); + assert_eq!(shortcut(&Action::FindNext), Some(key(Key::F3))); + assert_eq!(shortcut(&Action::Upload), None); +} + +#[test] +fn selector_commands_have_menu_entries_and_a_free_shortcut() { + assert_eq!(shortcut(&Action::InsertSelector), Some(ctrl_shift(Key::I))); + // Copy has none: Ctrl+Shift+C would also copy the editor's text. + assert_eq!(shortcut(&Action::CopySelector), None); + let taken = shortcuts() + .iter() + .filter(|(_, binding)| *binding == ctrl_shift(Key::I)) + .count(); + assert_eq!(taken, 1, "Ctrl+Shift+I is bound once"); +} + +#[test] +fn legacy_shortcuts_are_preserved() { + let all = shortcuts(); + let has = |action: Action, binding: KeyboardShortcut| { + assert!( + all.contains(&(action.clone(), binding)), + "missing legacy shortcut for {action:?}" + ); + }; + + has(Action::NewFile, ctrl(Key::N)); + has(Action::OpenFile, ctrl(Key::O)); + has(Action::Save, ctrl(Key::S)); + has(Action::SaveAs, ctrl_shift(Key::S)); + has(Action::Quit, ctrl(Key::Q)); + has(Action::ToggleComment, ctrl(Key::Slash)); + has(Action::Autocomplete, alt(Key::Slash)); + has(Action::Find, ctrl(Key::F)); + + has(Action::Render, key(Key::F5)); + has(Action::ToggleDebug, ctrl(Key::F5)); + has(Action::Debug(DebugAction::Step), ctrl(Key::F10)); + has(Action::Debug(DebugAction::StepIn), ctrl(Key::F11)); + has(Action::Debug(DebugAction::Continue), ctrl(Key::F12)); + + has(Action::Fit, shift(Key::F1)); + for (view, key) in [ + (StandardView::Iso, Key::F2), + (StandardView::Top, Key::F3), + (StandardView::Bottom, Key::F4), + (StandardView::Front, Key::F5), + (StandardView::Back, Key::F6), + (StandardView::Left, Key::F7), + (StandardView::Right, Key::F8), + ] { + has(Action::View(view), shift(key)); + } + has(Action::Display(DisplayMode::Wireframe), shift(Key::F9)); + has(Action::Display(DisplayMode::Shaded), shift(Key::F10)); +} + +#[test] +fn the_new_display_modes_follow_on_the_next_function_keys() { + let has = |action: Action, expected| assert_eq!(shortcut(&action), Some(expected)); + has(Action::Display(DisplayMode::XRay), shift(Key::F11)); + has(Action::Display(DisplayMode::HiddenLine), shift(Key::F12)); + // Stepping out keeps Ctrl+Shift+F11: the more specific match wins. + let order: Vec<_> = shortcuts().into_iter().map(|(action, _)| action).collect(); + let position = |action: &Action| order.iter().position(|a| a == action).unwrap(); + assert!( + position(&Action::Debug(DebugAction::StepOut)) + < position(&Action::Display(DisplayMode::XRay)) + ); +} + +#[test] +fn go_to_source_has_its_own_shortcut() { + assert_eq!( + shortcut(&Action::GoToSelectionSource), + Some(ctrl_shift(Key::G)) + ); + let taken = shortcuts() + .iter() + .filter(|(_, binding)| *binding == ctrl_shift(Key::G)) + .count(); + assert_eq!(taken, 1); +} + +#[test] +fn profiling_has_its_own_shortcut_next_to_render() { + assert_eq!(shortcut(&Action::Profile), Some(alt(Key::F5))); + // Alt+F5 is matched before the plain F5 of Render. + let order: Vec<_> = shortcuts().into_iter().map(|(action, _)| action).collect(); + let position = |action: &Action| order.iter().position(|a| a == action).unwrap(); + assert!(position(&Action::Profile) < position(&Action::Render)); +} + +#[test] +fn tabs_have_the_usual_shortcuts_and_none_is_bound_twice() { + assert_eq!(shortcut(&Action::CloseTab), Some(ctrl(Key::W))); + assert_eq!(shortcut(&Action::NextTab), Some(ctrl(Key::Tab))); + assert_eq!(shortcut(&Action::PreviousTab), Some(ctrl_shift(Key::Tab))); + assert_eq!(shortcut(&Action::OpenFolder), Some(ctrl_shift(Key::O))); + let all = shortcuts(); + let position = |action: &Action| all.iter().position(|(a, _)| a == action).unwrap(); + assert!(position(&Action::PreviousTab) < position(&Action::NextTab)); + // Ctrl+PageUp and Ctrl+PageDown switch tabs too. + assert!(all.contains(&(Action::NextTab, ctrl(Key::PageDown)))); + assert!(all.contains(&(Action::PreviousTab, ctrl(Key::PageUp)))); + + let mut bindings: Vec<_> = all.iter().map(|(_, binding)| *binding).collect(); + let count = bindings.len(); + bindings.sort_by_key(|binding| format!("{binding:?}")); + bindings.dedup(); + assert_eq!(bindings.len(), count, "a key combination is bound twice"); +} + +#[test] +fn selection_modes_have_default_and_configurable_shortcuts() { + for (mode, digit) in [ + (SelectionMode::Auto, Key::Num1), + (SelectionMode::Object, Key::Num2), + (SelectionMode::Face, Key::Num3), + (SelectionMode::Edge, Key::Num4), + (SelectionMode::Vertex, Key::Num5), + ] { + assert_eq!(shortcut(&Action::SelectionMode(mode)), Some(alt(digit))); + } + assert_eq!(parse_shortcut("3"), Some(key(Key::Num3))); + assert_eq!(parse_shortcut("Alt+4"), Some(alt(Key::Num4))); + assert_eq!(parse_shortcut("Ctrl+Shift+F"), Some(ctrl_shift(Key::F))); + assert_eq!(parse_shortcut(""), None); +} diff --git a/tests/rust/app/test_compatibility.rs b/tests/rust/app/test_compatibility.rs new file mode 100644 index 000000000..a447aa365 --- /dev/null +++ b/tests/rust/app/test_compatibility.rs @@ -0,0 +1,114 @@ +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::Path; + +const MATRIX: &str = include_str!("../../../docs/development/compatibility.md"); + +const REQUIRED_CONTRACTS: &[&str] = &[ + "file.lifecycle", + "file.autoreload", + "file.recovery", + "editor.syntax", + "editor.editing", + "editor.search", + "editor.completion", + "script.examples", + "script.show-object", + "script.discovery", + "script.logging", + "script.execution-settings", + "debugger.controls", + "debugger.breakpoints", + "debugger.errors", + "console.state", + "console.rich-output", + "inspector.workplane", + "objects.tree", + "objects.properties", + "objects.assemblies", + "export.step-stl", + "tools.upload", + "tools.update", + "viewer.standard-views", + "viewer.display-modes", + "viewer.projection", + "viewer.mouse", + "viewer.navigation-cube", + "viewer.selection", + "viewer.screenshot", + "viewer.stereo", + "panels.docking", + "preferences.persistence", + "preferences.defaults", + "shortcuts.legacy", + "behavior.rand-color", + "ui.theme", + "packaging.distribution", + "worker.isolation", +]; + +#[test] +fn compatibility_matrix_is_complete_and_evidenced() { + let mut rows = BTreeMap::new(); + for line in MATRIX.lines() { + let cells: Vec<_> = line.split('|').map(str::trim).collect(); + if cells.len() != 6 || !cells[1].starts_with('`') || !cells[1].ends_with('`') { + continue; + } + let id = cells[1].trim_matches('`').to_owned(); + assert!( + rows.insert(id.clone(), (cells[3], cells[4])).is_none(), + "duplicate compatibility row {id}" + ); + } + + let expected: BTreeSet<_> = REQUIRED_CONTRACTS.iter().copied().collect(); + let actual: BTreeSet<_> = rows.keys().map(String::as_str).collect(); + assert_eq!(actual, expected, "compatibility inventory changed silently"); + + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + for (id, (status, evidence)) in rows { + match status { + "Verified" | "Enhanced" => { + let reference = first_code_span(evidence) + .unwrap_or_else(|| panic!("{id} has no automated evidence")); + let (relative_path, test_name) = reference + .rsplit_once("::") + .unwrap_or_else(|| panic!("invalid evidence for {id}: {reference}")); + assert!( + relative_path.starts_with("tests/"), + "{id} evidence must name a test file" + ); + let source_path = root.join(relative_path); + let source = fs::read_to_string(&source_path).unwrap_or_else(|error| { + panic!( + "cannot read evidence for {id} at {}: {error}", + source_path.display() + ) + }); + assert!( + source.contains(&format!("{test_name}(")), + "evidence function {test_name} for {id} is missing from {relative_path}" + ); + } + "Changed" | "Gap" => assert!( + evidence.starts_with("Decision:"), + "{id} needs an explicit decision" + ), + "Unverified" => assert!( + evidence.starts_with("Follow-up:"), + "{id} needs an explicit verification follow-up" + ), + other => panic!("unknown compatibility state {other} for {id}"), + } + } + + assert!(MATRIX.contains("commit [`71903d5`]")); + assert!(MATRIX.contains("## Change policy")); +} + +fn first_code_span(text: &str) -> Option<&str> { + let start = text.find('`')? + 1; + let end = start + text[start..].find('`')?; + Some(&text[start..end]) +} diff --git a/tests/rust/app/test_embedded.rs b/tests/rust/app/test_embedded.rs new file mode 100644 index 000000000..ceca2af60 --- /dev/null +++ b/tests/rust/app/test_embedded.rs @@ -0,0 +1,46 @@ +use super::*; + +#[test] +fn titles_drop_numbering_and_capitalize() { + assert_eq!(example_title("01_hello_box.py"), "Hello Box"); + assert_eq!( + example_title("selectors_and_fillets.py"), + "Selectors And Fillets" + ); + assert_eq!(example_title("loft.py"), "Loft"); +} + +#[test] +fn everything_needed_is_embedded() { + let names: Vec<_> = WORKER_FILES.iter().map(|(name, _)| *name).collect(); + assert!(names.contains(&"cq_worker/__main__.py")); + assert!(names.contains(&"cq_worker/server.py")); + assert!(!examples().is_empty()); +} + +#[test] +fn extracting_a_new_worker_removes_the_other_versions() { + let cache = + std::env::temp_dir().join(format!("cq-editor-embedded-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&cache); + let old = extract(&cache, &[("cq_worker/__init__.py", "old = True\n")]).unwrap(); + std::fs::create_dir_all(cache.join("worker-interrupted")).unwrap(); + std::fs::write(cache.join("settings.ron"), "kept").unwrap(); + + let new = extract(&cache, &[("cq_worker/__init__.py", "new = True\n")]).unwrap(); + + assert_ne!(old, new); + assert!(!old.exists(), "the previous version is gone"); + assert!(!cache.join("worker-interrupted").exists()); + assert!(cache.join("settings.ron").exists(), "other data stays"); + assert_eq!( + std::fs::read_to_string(new.join("cq_worker/__init__.py")).unwrap(), + "new = True\n" + ); + // Starting the same version again changes nothing. + assert_eq!( + extract(&cache, &[("cq_worker/__init__.py", "new = True\n")]).unwrap(), + new + ); + std::fs::remove_dir_all(cache).unwrap(); +} diff --git a/tests/rust/app/test_environments.rs b/tests/rust/app/test_environments.rs new file mode 100644 index 000000000..4f147c05f --- /dev/null +++ b/tests/rust/app/test_environments.rs @@ -0,0 +1,169 @@ +use std::time::{Duration, Instant}; + +use super::*; +use crate::worker::launch::find_python; + +#[test] +fn package_lists_are_names_versions_or_wheels_never_options() { + assert_eq!( + parse_packages(" cadquery, jedi\n ocp-vscode>=2.0 trimesh[easy] ").unwrap(), + ["cadquery", "jedi", "ocp-vscode>=2.0", "trimesh[easy]"] + ); + assert_eq!( + parse_packages(r"C:\wheels\demo-1.0-py3-none-any.whl").unwrap(), + [r"C:\wheels\demo-1.0-py3-none-any.whl"] + ); + assert!(parse_packages(" ").is_err()); + for refused in [ + "--index-url http://x", + "cadquery -e .", + "a;b", + "a|b", + "a&b", + "$(rm)", + "\"a\"", + ] { + assert!(parse_packages(refused).is_err(), "{refused}"); + } +} + +#[test] +fn creating_an_environment_runs_venv_then_its_own_pip() { + let packages = vec!["cadquery".to_owned(), "jedi".to_owned()]; + let folder = Path::new("envs").join("cq"); + let steps = create_steps(Path::new("base-python"), &folder, &packages); + assert_eq!(steps.len(), 2); + assert_eq!(steps[0].program, Path::new("base-python")); + assert_eq!(steps[0].args, ["-m", "venv", folder.to_str().unwrap()]); + let python = venv_python(&folder); + assert!(python.starts_with(&folder)); + assert_eq!(steps[1].program, python); + assert_eq!(steps[1].args, ["-m", "pip", "install", "cadquery", "jedi"]); +} + +/// The Python CQ-editor itself would start, when there is one. +fn python() -> Option { + let python = find_python(None); + let works = Command::new(&python) + .args(["-c", "pass"]) + .status() + .is_ok_and(|status| status.success()); + if !works { + eprintln!("no Python: skipping the job test"); + } + works.then_some(python) +} + +fn run(step: &Path, code: &str) -> Step { + Step { + title: format!("python -c {code}"), + program: step.to_path_buf(), + args: vec!["-c".into(), code.into()], + } +} + +fn finish(job: &mut Job, limit: Duration) -> JobState { + let started = Instant::now(); + while *job.poll() == JobState::Running { + assert!(started.elapsed() < limit, "the job did not finish"); + thread::sleep(Duration::from_millis(20)); + } + job.state().clone() +} + +#[test] +fn a_job_runs_its_steps_in_order_and_stops_at_a_failure() { + let Some(python) = python() else { return }; + let mut job = Job::start(vec![ + run(&python, "print('first')"), + run(&python, "import sys; print('to stderr', file=sys.stderr)"), + run(&python, "import sys; sys.exit(3)"), + run(&python, "print('never')"), + ]); + let state = finish(&mut job, Duration::from_secs(60)); + let JobState::Failed(problem) = state else { + panic!("{state:?}"); + }; + assert!(problem.contains("code 3"), "{problem}"); + let output = job.output().join("\n"); + assert!(output.contains("first") && output.contains("to stderr")); + assert!(!output.contains("never"), "later steps are skipped"); + assert!(output.find("first") < output.find("to stderr")); + + let mut job = Job::start(vec![run(&python, "print('ok')")]); + assert_eq!( + finish(&mut job, Duration::from_secs(60)), + JobState::Succeeded + ); +} + +#[test] +fn a_cancelled_job_stops_its_command_and_skips_the_rest() { + let Some(python) = python() else { return }; + let mut job = Job::start(vec![ + run( + &python, + "print('started', flush=True); import time; time.sleep(60)", + ), + run(&python, "print('never')"), + ]); + let started = Instant::now(); + while !job.output().iter().any(|line| line == "started") { + job.poll(); + assert!(started.elapsed() < Duration::from_secs(30)); + thread::sleep(Duration::from_millis(20)); + } + job.cancel(); + assert_eq!( + finish(&mut job, Duration::from_secs(20)), + JobState::Cancelled + ); + assert!(!job.output().iter().any(|line| line == "never")); +} + +#[test] +fn an_environment_is_created_and_gets_a_package_without_the_network() { + let Some(base) = python() else { return }; + let can_create = Command::new(&base) + .args(["-c", "import ensurepip, venv"]) + .status() + .is_ok_and(|status| status.success()); + if !can_create { + eprintln!("this Python cannot create environments (no ensurepip): skipping"); + return; + } + let dir = std::env::temp_dir().join(format!("cq-editor-env-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // A minimal wheel, so pip installs it from the file alone. + let wheel = dir.join("demo_package-1.0-py3-none-any.whl"); + let build = format!( + "import zipfile\n\ + files = {{\n\ + 'demo_package/__init__.py': 'VALUE = 42\\n',\n\ + 'demo_package-1.0.dist-info/METADATA': 'Metadata-Version: 2.1\\nName: demo-package\\nVersion: 1.0\\n',\n\ + 'demo_package-1.0.dist-info/WHEEL': 'Wheel-Version: 1.0\\nGenerator: test\\nRoot-Is-Purelib: true\\nTag: py3-none-any\\n',\n\ + 'demo_package-1.0.dist-info/RECORD': '',\n\ + }}\n\ + with zipfile.ZipFile(r'{}', 'w') as archive:\n\ + \x20 for name, text in files.items():\n\ + \x20 archive.writestr(name, text)\n", + wheel.display() + ); + let built = Command::new(&base).args(["-c", &build]).status().unwrap(); + assert!(built.success()); + + let folder = dir.join("env"); + let packages = vec![wheel.display().to_string()]; + let mut job = Job::start(create_steps(&base, &folder, &packages)); + let state = finish(&mut job, Duration::from_secs(300)); + assert_eq!(state, JobState::Succeeded, "{}", job.output().join("\n")); + + let output = Command::new(venv_python(&folder)) + .args(["-c", "import demo_package; print(demo_package.VALUE)"]) + .output() + .unwrap(); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "42"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/tests/rust/app/test_execution.rs b/tests/rust/app/test_execution.rs new file mode 100644 index 000000000..027faf8e6 --- /dev/null +++ b/tests/rust/app/test_execution.rs @@ -0,0 +1,303 @@ +use std::time::Instant; + +use super::*; + +use WorkerAvailability::{Ready, Starting, Unavailable}; + +/// An execution with the render `id` running. +fn rendering(id: RequestId) -> Execution { + let mut execution = Execution::default(); + assert_eq!(execution.request_run(false, Ready), RunRequest::Start); + execution.started(id, false); + execution +} + +#[test] +fn a_render_starts_when_idle_and_is_tracked_until_it_ends() { + let mut execution = rendering(1); + + assert_eq!( + execution.phase(), + Phase::Running { + id: 1, + debug: false + } + ); + assert!(execution.is_busy() && !execution.is_debugging()); + assert_eq!(execution.pending(1), Some(&Pending::Run)); + + assert_eq!(execution.ended(1), RunEnd::default()); + assert_eq!(execution.phase(), Phase::Idle); + assert!(!execution.is_pending(1)); +} + +#[test] +fn renders_asked_for_during_a_render_collapse_into_one_rerun() { + let mut execution = rendering(1); + + assert_eq!(execution.request_run(false, Ready), RunRequest::Queued); + assert_eq!(execution.request_run(false, Ready), RunRequest::Queued); + assert_eq!( + execution.ended(1), + RunEnd { + stale: false, + rerun: true + } + ); + // The rerun is reported once. + execution.started(2, false); + assert_eq!(execution.ended(2), RunEnd::default()); +} + +#[test] +fn debugging_never_queues_behind_or_in_front_of_another_run() { + let mut execution = rendering(1); + assert_eq!(execution.request_run(true, Ready), RunRequest::Busy); + execution.ended(1); + + execution.started(2, true); + assert!(execution.is_debugging()); + assert_eq!(execution.request_run(false, Ready), RunRequest::Busy); + assert_eq!(execution.request_run(true, Ready), RunRequest::Busy); + assert!(!execution.ended(2).rerun); +} + +#[test] +fn a_run_asked_for_while_python_starts_follows_once_it_is_ready() { + let mut execution = Execution::default(); + + assert_eq!( + execution.request_run(false, Starting), + RunRequest::WhenReady + ); + // The last request wins: debugging was asked for after rendering. + assert_eq!(execution.request_run(true, Starting), RunRequest::WhenReady); + assert!(!execution.is_busy()); + assert_eq!(execution.worker_ready(), Some(true)); + assert_eq!(execution.worker_ready(), None); +} + +#[test] +fn no_run_starts_without_python() { + let mut execution = Execution::default(); + + assert_eq!( + execution.request_run(false, Unavailable), + RunRequest::Unavailable + ); + assert_eq!(execution.worker_ready(), None); + assert!(!execution.is_busy()); +} + +#[test] +fn worker_status_maps_to_availability() { + assert_eq!( + WorkerAvailability::from(&worker::Status::Starting), + Starting + ); + assert_eq!( + WorkerAvailability::from(&worker::Status::NotStarted), + Unavailable + ); + assert_eq!( + WorkerAvailability::from(&worker::Status::Failed("no Python".into())), + Unavailable + ); +} + +#[test] +fn a_paused_session_resumes_as_a_running_debug_session() { + let mut execution = Execution::default(); + execution.started(4, true); + + assert!(!execution.paused(4), "the session of this document"); + assert!(execution.is_paused() && execution.is_debugging()); + // Paused, the run is not running but still goes on. + assert_eq!(execution.phase().running_id(), None); + assert_eq!(execution.phase().run_id(), Some(4)); + assert_eq!(execution.resume(), Some(4)); + assert_eq!(execution.phase().run_id(), Some(4)); + assert_eq!(execution.phase(), Phase::Running { id: 4, debug: true }); + // Only a paused session can be resumed. + assert_eq!(execution.resume(), None); +} + +#[test] +fn replacing_the_document_discards_the_running_render_and_queued_runs() { + let mut execution = rendering(1); + execution.request_run(false, Ready); + + assert!(!execution.abandon(), "a running render needs no stop"); + assert_eq!( + execution.ended(1), + RunEnd { + stale: true, + rerun: false + } + ); + // The stale mark does not outlive its run. + execution.started(2, false); + assert!(!execution.ended(2).stale); +} + +#[test] +fn replacing_the_document_drops_a_run_waiting_for_python() { + let mut execution = Execution::default(); + execution.request_run(false, Starting); + + assert!(!execution.abandon()); + assert_eq!(execution.worker_ready(), None); +} + +#[test] +fn replacing_the_document_stops_a_paused_session() { + let mut execution = Execution::default(); + execution.started(3, true); + execution.paused(3); + + assert!(execution.abandon(), "the paused session must be stopped"); + assert_eq!(execution.resume(), Some(3)); + assert!(execution.ended(3).stale); +} + +#[test] +fn a_stale_session_reaching_a_breakpoint_is_reported_as_stale() { + let mut execution = Execution::default(); + execution.started(5, true); + execution.abandon(); + + assert!(execution.paused(5)); +} + +#[test] +fn a_failed_run_still_starts_the_render_queued_behind_it() { + // BUG-27: a run request that failed in the worker dropped a queued render. + let mut execution = rendering(1); + execution.request_run(false, Ready); + + assert_eq!(execution.answer(1), Some(Pending::Run)); + assert_eq!( + execution.ended(1), + RunEnd { + stale: false, + rerun: true + } + ); + assert_eq!(execution.phase(), Phase::Idle); +} + +#[test] +fn a_worker_restart_forgets_its_requests_but_not_a_render_asked_for_meanwhile() { + let mut execution = rendering(1); + execution.request_run(false, Ready); + execution.abandon(); + execution.track(2, Pending::Console); + execution.reset(); + + assert_eq!(execution.phase(), Phase::Idle); + assert!(!execution.is_pending(1) && !execution.is_pending(2)); + execution.started(3, false); + assert_eq!( + execution.ended(3), + RunEnd::default(), + "no stale mark, no rerun" + ); + + // F5 while the restarted Python is still importing CadQuery. + execution.request_run(false, Starting); + execution.reset(); + assert_eq!(execution.worker_ready(), Some(false)); +} + +#[test] +fn every_reply_is_routed_once() { + let mut execution = Execution::default(); + let entry = (1, Some(2)); + execution.track( + 7, + Pending::InspectGeometry { + key: "s1-n1".into(), + entry, + }, + ); + + assert!(execution.is_pending(7)); + assert_eq!( + execution.answer(7), + Some(Pending::InspectGeometry { + key: "s1-n1".into(), + entry + }) + ); + assert_eq!(execution.answer(7), None); + assert_eq!(execution.answer(8), None, "unknown ids are ignored"); +} + +#[test] +fn meshing_progress_is_kept_for_the_running_render_only() { + let start = std::time::Instant::now(); + let later = start + std::time::Duration::from_millis(500); + let mut execution = rendering(3); + assert_eq!(execution.meshing(), None); + + execution.meshing_progress(2, 1, 10, start); + assert_eq!(execution.meshing(), None, "another request"); + execution.meshing_progress(3, 0, 10, start); + execution.meshing_progress(3, 4, 10, later); + let meshing = execution.meshing().unwrap(); + assert_eq!((meshing.done, meshing.total), (4, 10)); + assert_eq!(meshing.since, start, "since the first report"); + + execution.meshing_progress(3, 10, 10, later); + assert_eq!(execution.meshing(), None, "done"); + execution.meshing_progress(3, 5, 10, later); + execution.ended(3); + assert_eq!(execution.meshing(), None); + assert_eq!(execution.phase().running_id(), None); + + let mut execution = rendering(4); + execution.meshing_progress(4, 1, 10, start); + execution.reset(); + assert_eq!( + execution.meshing(), + None, + "a restarted worker answers nothing" + ); +} + +#[test] +fn stop_interrupts_first_and_restarts_python_only_when_pressed_again() { + let now = Instant::now(); + let mut execution = rendering(5); + assert_eq!(execution.stop(now), StopPlan::Interrupt(5)); + assert!(execution.is_stopping()); + assert_eq!(execution.stop_deadline(), Some(now + STOP_GRACE)); + assert_eq!(execution.stop(now), StopPlan::Restart, "pressed again"); + + // Stopped in time: nothing more to do. + let mut execution = rendering(6); + execution.stop(now); + execution.ended(6); + assert!(!execution.is_stopping() && execution.stop_deadline().is_none()); + assert_eq!(execution.stop(now), StopPlan::Nothing); + + // Without a script, a console command is what Stop stops. + let mut execution = Execution::default(); + execution.track( + 9, + Pending::Completion { + automatic: false, + document: 0, + }, + ); + execution.track(8, Pending::Console); + assert_eq!(execution.stop(now), StopPlan::Interrupt(8)); + execution.answer(8); + assert!(!execution.is_stopping()); + + // A restarted worker answers nothing more. + let mut execution = rendering(10); + execution.stop(now); + execution.reset(); + assert!(!execution.is_stopping()); +} diff --git a/tests/rust/app/test_file_watcher.rs b/tests/rust/app/test_file_watcher.rs new file mode 100644 index 000000000..07f4bb778 --- /dev/null +++ b/tests/rust/app/test_file_watcher.rs @@ -0,0 +1,79 @@ +use super::*; + +#[test] +fn reports_settled_changes_once() { + let dir = std::env::temp_dir().join(format!("cq-editor-watch-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("watched.py"); + std::fs::write(&path, "a").unwrap(); + + let mut watcher = FileWatcher::default(); + watcher.set_files(vec![path.clone()]); + assert!(watcher.poll(Duration::ZERO).is_empty()); + + std::fs::write(&path, "changed").unwrap(); + watcher.last_poll = None; + assert_eq!(watcher.poll(Duration::ZERO), std::slice::from_ref(&path)); + watcher.last_poll = None; + assert!(watcher.poll(Duration::ZERO).is_empty()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn absent_file_is_waited_for_until_it_is_created() { + let path = + std::env::temp_dir().join(format!("cq-editor-watch-created-{}.py", std::process::id())); + let mut watcher = FileWatcher::default(); + watcher.set_files(vec![path.clone()]); + assert!(watcher.poll(Duration::ZERO).is_empty()); + std::fs::write(&path, "created").unwrap(); + watcher.last_poll = None; + assert_eq!(watcher.poll(Duration::ZERO), std::slice::from_ref(&path)); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn replacing_watched_files_keeps_known_stamps() { + let path = + std::env::temp_dir().join(format!("cq-editor-watch-stamps-{}.py", std::process::id())); + std::fs::write(&path, "initial").unwrap(); + let mut watcher = FileWatcher::default(); + watcher.set_files(vec![path.clone()]); + std::fs::write(&path, "longer contents").unwrap(); + watcher.set_files(vec![path.clone()]); + assert_eq!(watcher.poll(Duration::ZERO), std::slice::from_ref(&path)); + assert_eq!(watcher.watched().collect::>(), vec![&path]); + assert_eq!(watcher.next_poll_in(), POLL_INTERVAL); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn clear_stops_watching_and_discards_pending_changes() { + let mut watcher = FileWatcher::default(); + watcher.set_files(vec![PathBuf::from("missing.py")]); + watcher.changed_at = Some(Instant::now()); + watcher.clear(); + assert!(!watcher.is_watching()); + assert!(watcher.watched().next().is_none()); + assert!(watcher.poll(Duration::ZERO).is_empty()); + assert!(watcher.changed_at.is_none()); + assert!(watcher.pending.is_empty()); +} + +#[test] +fn reports_which_watched_files_changed() { + let dir = std::env::temp_dir().join(format!("cq-editor-watch-paths-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let main = dir.join("main.py"); + let imported = dir.join("profile.py"); + std::fs::write(&main, "main").unwrap(); + std::fs::write(&imported, "profile").unwrap(); + let mut watcher = FileWatcher::default(); + watcher.set_files(vec![main.clone(), imported.clone()]); + + std::fs::write(&imported, "changed profile").unwrap(); + watcher.last_poll = None; + assert_eq!(watcher.poll(Duration::ZERO), [imported]); + + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/tests/rust/app/test_headless.rs b/tests/rust/app/test_headless.rs new file mode 100644 index 000000000..329290549 --- /dev/null +++ b/tests/rust/app/test_headless.rs @@ -0,0 +1,21 @@ +use super::*; + +#[test] +fn routes_commands_and_interpreter_without_swallowing_gui_files() { + let args = [ + "--python", + "custom-python", + "build", + "part.py", + "--export", + "part.step", + ] + .map(str::to_owned); + let command = invocation(&args).unwrap().unwrap(); + assert_eq!(command.python.as_deref(), Some("custom-python")); + assert_eq!( + command.arguments, + ["build", "part.py", "--export", "part.step"] + ); + assert!(invocation(&["part.py".into()]).unwrap().is_none()); +} diff --git a/tests/rust/app/test_logging.rs b/tests/rust/app/test_logging.rs new file mode 100644 index 000000000..cb56a07bd --- /dev/null +++ b/tests/rust/app/test_logging.rs @@ -0,0 +1,74 @@ +use super::*; + +#[test] +fn strips_color_codes() { + assert_eq!(strip_ansi("\x1b[31mred\x1b[0m text"), "red text"); + assert_eq!(strip_ansi("plain"), "plain"); +} + +#[test] +fn splits_multiline_messages() { + let before = with_entries(|e| e.len()); + push(Level::Info, "test", "one\ntwo\r\n"); + let lines: Vec = + with_entries(|e| e.iter().skip(before).map(|e| e.text.clone()).collect()); + // Other tests log concurrently into the same global log. + assert!( + lines.windows(2).any(|pair| pair == ["one", "two"]), + "{lines:?}" + ); +} + +fn temporary_directory(name: &str) -> PathBuf { + std::env::temp_dir().join(format!( + "cq-editor-logging-test-{}-{name}", + std::process::id() + )) +} + +#[test] +fn the_log_file_rotates_and_keeps_one_previous_file() { + let directory = temporary_directory("rotate"); + let _ = std::fs::remove_dir_all(&directory); + let mut file = LogFile::open(&directory).unwrap(); + let line = format!("{}\n", "x".repeat(1023)); + for _ in 0..MAX_FILE_BYTES / 1024 + 10 { + file.write_line(&line, false); + } + file.flush(); + + let size = |name| std::fs::metadata(directory.join(name)).unwrap().len(); + assert!(size(PREVIOUS_LOG_FILE) >= MAX_FILE_BYTES); + assert!((1..MAX_FILE_BYTES).contains(&size(LOG_FILE))); + + // A new session appends to the current file. + drop(file); + let reopened = LogFile::open(&directory).unwrap(); + assert_eq!(reopened.size, size(LOG_FILE)); + drop(reopened); + std::fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn messages_reach_the_log_file_with_their_date_and_level() { + let directory = temporary_directory("push"); + let _ = std::fs::remove_dir_all(&directory); + lock().file = Some(LogFile::open(&directory).unwrap()); + push( + Level::Warn, + "python", + "worker \x1b[33mwarning\x1b[0m\nsecond line", + ); + let file = lock().file.take(); + drop(file); + + let text = std::fs::read_to_string(directory.join(LOG_FILE)).unwrap(); + let lines: Vec<&str> = text.lines().filter(|l| l.contains("python:")).collect(); + assert_eq!(lines.len(), 2, "{text}"); + assert!(lines[0].ends_with("WARN python: worker warning")); + assert!(lines[1].ends_with("WARN python: second line")); + // "YYYY-MM-DD HH:MM:SS " in front. + assert_eq!(lines[0].as_bytes()[4], b'-'); + assert_eq!(lines[0].as_bytes()[19], b' '); + std::fs::remove_dir_all(directory).unwrap(); +} diff --git a/tests/rust/app/test_parameters.rs b/tests/rust/app/test_parameters.rs new file mode 100644 index 000000000..5e6fdcb71 --- /dev/null +++ b/tests/rust/app/test_parameters.rs @@ -0,0 +1,119 @@ +use super::*; + +fn names(text: &str) -> Vec { + parameters(text).into_iter().map(|p| p.name).collect() +} + +fn only(text: &str) -> Parameter { + let mut found = parameters(text); + assert_eq!(found.len(), 1, "{found:?}"); + found.remove(0) +} + +#[test] +fn top_level_number_assignments_are_parameters() { + let text = "import cadquery as cq\n\ + width = 40\n\ + height=12.5\n\ + wall: float = 2.0 # thickness\n\ + count: int = 3\n\ + offset = -1.25\n\ + big = 1_000\n\ + tiny = 1e-3\n\ + half = .5\n\ + whole = 5.\n\ + result = cq.Workplane().box(width, width, height)\n"; + let found = parameters(text); + let summary: Vec<(&str, f64, bool, usize)> = found + .iter() + .map(|p| (p.name.as_str(), p.value, p.integer, p.decimals)) + .collect(); + assert_eq!( + summary, + [ + ("width", 40.0, true, 0), + ("height", 12.5, false, 1), + ("wall", 2.0, false, 1), + ("count", 3.0, true, 0), + ("offset", -1.25, false, 2), + ("big", 1000.0, true, 0), + ("tiny", 0.001, false, 0), + ("half", 0.5, false, 1), + ("whole", 5.0, false, 0), + ] + ); + assert_eq!(found[0].line, 2); + assert_eq!(&text[found[0].literal.clone()], "40"); + assert_eq!(&text[found[4].literal.clone()], "-1.25"); + assert!(found[6].exponent); +} + +#[test] +fn nested_continued_and_non_literal_lines_are_skipped() { + let text = "def part(size=3):\n depth = 4\n return size\n\ + if True:\n inner = 1\n\ + doc = \"\"\"\nquoted = 5\n\"\"\"\n\ + call = dict(\n keyword = 6,\n)\n\ + joined = 1 + \\\n 2\n\ + after = 7\n\ + expression = 1 + 2\n\ + chained = other = 8\n\ + several = 1; more = 2\n\ + compared == 9\n\ + flag = True\n\ + hexadecimal = 0x10\n\ + imaginary = 2j\n\ + text = \"10\"\n\ + annotated: str = 3\n\ + __version__ = 1\n\ + last = 10"; + assert_eq!(names(text), ["after", "last"]); +} + +#[test] +fn strings_and_comments_do_not_open_brackets() { + let text = "label = \"(\"\nfirst = 1\nnote = 'a [ b' # also ( here\nsecond = 2\n\ + raw = r\"\\\"(\"\nthird = 3\n"; + assert_eq!(names(text), ["first", "second", "third"]); +} + +#[test] +fn a_comment_can_give_the_slider_range_and_step() { + assert_eq!(only("width = 40 # [10, 100]").range, Some(10.0..=100.0)); + let stepped = only("hole = 2.5 # diameter [0.5, 5, 0.25]"); + assert_eq!(stepped.range, Some(0.5..=5.0)); + assert_eq!(stepped.step, Some(0.25)); + assert_eq!(only("n = 3 # 1..12 copies").range, Some(1.0..=12.0)); + // Not a range: kept as a plain comment. + assert_eq!(only("x = 3 # [12, 1]").range, None); + assert_eq!(only("x = 3 # see [docs]").range, None); +} + +#[test] +fn new_values_keep_the_style_of_the_literal() { + assert_eq!(only("n = 3").literal_for(4.6), "5"); + assert_eq!(only("w = 40.0").literal_for(41.25), "41.2"); + assert_eq!(only("w = 2.50").literal_for(3.0), "3.00"); + assert_eq!(only("w = 2.5 # [0, 5, 0.25]").literal_for(3.75), "3.75"); + assert_eq!(only("t = 1e-3").literal_for(0.0025), "2.5e-3"); + assert_eq!(only("o = -1.5").literal_for(-0.0), "0.0"); + assert_eq!(only("o = 1.5").literal_for(-2.0), "-2.0"); + // Within the commented range. + assert_eq!(only("w = 40 # [10, 100]").literal_for(250.0), "100"); +} + +#[test] +fn drag_speed_follows_the_written_precision() { + assert_eq!(only("n = 3").drag_speed(), 1.0); + assert_eq!(only("w = 2.50").drag_speed(), 0.01); + assert_eq!(only("w = 2.5 # [0, 5, 0.25]").drag_speed(), 0.25); + assert_eq!(only("big = 4000").drag_speed(), 20.0); +} + +#[test] +fn windows_line_endings_are_parsed() { + let text = "a = 1\r\nb = 2.5\r\n"; + let found = parameters(text); + assert_eq!(names(text), ["a", "b"]); + assert_eq!(&text[found[1].literal.clone()], "2.5"); +} diff --git a/tests/rust/app/test_project.rs b/tests/rust/app/test_project.rs new file mode 100644 index 000000000..435582910 --- /dev/null +++ b/tests/rust/app/test_project.rs @@ -0,0 +1,255 @@ +use super::*; + +fn temporary_folder(name: &str) -> PathBuf { + let folder = + std::env::temp_dir().join(format!("cq-editor-project-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder +} + +fn names(rows: &[Row]) -> Vec<(usize, &str)> { + rows.iter() + .map(|row| (row.depth, row.entry.name.as_str())) + .collect() +} + +#[test] +fn the_tree_lists_folders_first_and_hides_caches_and_hidden_files() { + let root = temporary_folder("tree"); + std::fs::create_dir_all(root.join("parts/__pycache__")).unwrap(); + std::fs::create_dir_all(root.join(".git")).unwrap(); + std::fs::write(root.join("parts/Bracket.py"), "").unwrap(); + std::fs::write(root.join("parts/axle.py"), "").unwrap(); + std::fs::write(root.join("parts/axle.cpython-312.pyc"), "").unwrap(); + std::fs::write(root.join("main.py"), "").unwrap(); + std::fs::write(root.join(".env"), "").unwrap(); + std::fs::write(root.join("Notes.md"), "").unwrap(); + + let mut project = Project::open(&root).unwrap(); + assert_eq!(project.name(), root.file_name().unwrap().to_string_lossy()); + assert_eq!( + names(&project.rows()), + [(0, "parts"), (0, "main.py"), (0, "Notes.md")] + ); + + project.toggle(&root.join("parts")); + let rows = project.rows(); + assert_eq!( + names(&rows), + [ + (0, "parts"), + (1, "axle.py"), + (1, "Bracket.py"), + (0, "main.py"), + (0, "Notes.md") + ] + ); + assert!(rows[0].expanded && rows[0].entry.is_dir); + + project.collapse_all(); + assert_eq!(project.rows().len(), 3); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn files_created_by_other_programs_appear_once_the_folder_changed() { + let root = temporary_folder("listing"); + std::fs::write(root.join("a.py"), "").unwrap(); + let mut project = Project::open(&root).unwrap(); + assert_eq!(project.rows().len(), 1); + + std::fs::write(root.join("b.py"), "").unwrap(); + // Checked again once the interval passed, as the next frames would. + for listing in project.listings.values_mut() { + listing.checked -= RECHECK_INTERVAL; + listing.modified = None; + } + assert_eq!(names(&project.rows()), [(0, "a.py"), (0, "b.py")]); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn revealing_a_file_expands_the_folders_above_it() { + let root = temporary_folder("reveal"); + std::fs::create_dir_all(root.join("a/b")).unwrap(); + std::fs::write(root.join("a/b/deep.py"), "").unwrap(); + let mut project = Project::open(&root).unwrap(); + project.reveal(&root.join("a/b/deep.py")); + assert!(project.is_expanded(&root.join("a"))); + assert!(project.is_expanded(&root.join("a/b"))); + assert_eq!(names(&project.rows()), [(0, "a"), (1, "b"), (2, "deep.py")]); + // Outside the project nothing changes. + project.reveal(Path::new("/elsewhere/x.py")); + assert_eq!(project.expanded().len(), 2); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn the_main_script_is_guessed_only_when_it_is_clear() { + let root = temporary_folder("main"); + std::fs::write(root.join("helpers.py"), "def bolt(): ...\n").unwrap(); + std::fs::write(root.join("bracket.py"), "show_object(result)\n").unwrap(); + assert_eq!(guess_main(&root), Some(root.join("bracket.py"))); + + std::fs::write(root.join("plate.py"), "show_object(plate)\n").unwrap(); + assert_eq!(guess_main(&root), None, "two scripts show objects"); + + let named = root.join(format!( + "{}.py", + root.file_name().unwrap().to_string_lossy() + )); + std::fs::write(&named, "").unwrap(); + assert_eq!(guess_main(&root), Some(named), "named after the folder"); + + std::fs::write(root.join("main.py"), "").unwrap(); + assert_eq!(guess_main(&root), Some(root.join("main.py"))); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn names_that_some_systems_refuse_are_refused() { + assert_eq!(check_name(" bracket.py "), Ok("bracket.py")); + assert!(check_name("").is_err()); + assert!(check_name("..").is_err()); + assert!(check_name("parts/axle.py").is_err()); + assert!(check_name("a:b").is_err()); + assert!(check_name("trailing.").is_err()); + assert!(check_name("con.py").is_err()); + assert!(check_name("console.py").is_ok()); +} + +#[test] +fn files_and_folders_are_created_renamed_and_deleted_without_replacing_anything() { + let root = temporary_folder("operations"); + let script = create_file(&root, "bracket").unwrap(); + assert_eq!(script, root.join("bracket.py"), "Python by default"); + assert!(script.is_file()); + let notes = create_file(&root, "notes.txt").unwrap(); + assert_eq!(notes, root.join("notes.txt")); + let error = create_file(&root, "bracket.py").unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::AlreadyExists); + assert!(error.to_string().contains("bracket.py already exists")); + + let folder = create_folder(&root, "parts").unwrap(); + assert!(folder.is_dir()); + assert!(create_folder(&root, "parts").is_err()); + + std::fs::write(&script, "x = 1\n").unwrap(); + assert!(rename(&script, "notes.txt").is_err(), "no replacing"); + let renamed = rename(&script, "plate.py").unwrap(); + assert_eq!(renamed, root.join("plate.py")); + assert_eq!(std::fs::read_to_string(&renamed).unwrap(), "x = 1\n"); + assert!(!script.exists()); + // Only the case changes. + let upper = rename(&renamed, "Plate.py").unwrap(); + assert_eq!(upper, root.join("Plate.py")); + + std::fs::write(folder.join("axle.py"), "").unwrap(); + delete(&folder).unwrap(); + assert!(!folder.exists()); + delete(&upper).unwrap(); + assert!(!upper.exists()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn changing_only_the_case_never_replaces_another_file() { + let root = temporary_folder("case"); + std::fs::write(root.join("part.py"), "lower\n").unwrap(); + std::fs::write(root.join("Part.py"), "upper\n").unwrap(); + let files = std::fs::read_dir(&root).unwrap().count(); + + let result = rename(&root.join("part.py"), "Part.py"); + if files == 2 { + // Case matters here (Linux, case-sensitive folders): two files. + let error = result.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::AlreadyExists); + assert_eq!( + std::fs::read_to_string(root.join("part.py")).unwrap(), + "lower\n" + ); + assert_eq!( + std::fs::read_to_string(root.join("Part.py")).unwrap(), + "upper\n" + ); + } else { + // One file under either name: only its case changes. + assert_eq!(result.unwrap(), root.join("Part.py")); + let names: Vec = std::fs::read_dir(&root) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, ["Part.py"]); + } + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn paths_follow_a_renamed_folder() { + let from = Path::new("/p/parts"); + let to = Path::new("/p/components"); + assert_eq!(relocated(from, from, to), Some(to.to_path_buf())); + assert_eq!( + relocated(Path::new("/p/parts/axle.py"), from, to), + Some(PathBuf::from("/p/components/axle.py")) + ); + assert_eq!(relocated(Path::new("/p/partsbin/x.py"), from, to), None); + + let root = temporary_folder("relocate"); + std::fs::create_dir_all(root.join("parts")).unwrap(); + let mut project = Project::open(&root).unwrap(); + project.main = Some(root.join("parts/main.py")); + project.toggle(&root.join("parts")); + project.relocate(&root.join("parts"), &root.join("components")); + assert_eq!(project.main, Some(root.join("components/main.py"))); + assert!(project.is_expanded(&root.join("components"))); + + project.forget(&root.join("components")); + assert_eq!(project.main, None); + assert!(project.expanded().is_empty()); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn scripts_and_text_files_open_in_the_editor() { + assert!(is_editable(Path::new("a/main.py"))); + assert!(is_editable(Path::new("README.MD"))); + assert!(!is_editable(Path::new("part.step"))); + assert!(!is_editable(Path::new("Makefile"))); + assert!(is_script(Path::new("main.PY"))); + assert!(!is_script(Path::new("notes.txt"))); +} + +#[test] +fn project_search_finds_files_inside_collapsed_folders_without_expanding_them() { + let root = temporary_folder("search"); + std::fs::create_dir_all(root.join("assemblies/drive")).unwrap(); + std::fs::write(root.join("main.py"), "").unwrap(); + std::fs::write(root.join("gear.py"), "").unwrap(); + std::fs::write(root.join("assemblies/drive/gearbox.py"), "").unwrap(); + + let mut project = Project::open(&root).unwrap(); + assert!(project.expanded().is_empty()); + + let found = project.search_rows("gear"); + let found_paths: Vec = found + .iter() + .map(|row| { + project + .relative(&row.entry.path) + .to_string_lossy() + .replace('\\', "/") + }) + .collect(); + assert_eq!(found_paths, ["assemblies/drive/gearbox.py", "gear.py"]); + assert!( + project.expanded().is_empty(), + "searching does not mutate folder expansion state" + ); + + let by_folder = project.search_rows("drive/gear"); + assert_eq!(by_folder.len(), 1); + assert_eq!(by_folder[0].entry.name, "gearbox.py"); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/tests/rust/app/test_settings.rs b/tests/rust/app/test_settings.rs new file mode 100644 index 000000000..d773e87ea --- /dev/null +++ b/tests/rust/app/test_settings.rs @@ -0,0 +1,254 @@ +use super::*; + +#[test] +fn recent_files_are_unique_and_bounded() { + let mut settings = Settings::default(); + for i in 0..15 { + settings.add_recent_file(Path::new(&format!("{i}.py"))); + } + settings.add_recent_file(Path::new("12.py")); + assert_eq!(settings.recent_files.len(), MAX_RECENT_FILES); + assert_eq!(settings.recent_files[0], Path::new("12.py")); + assert_eq!( + settings + .recent_files + .iter() + .filter(|p| *p == Path::new("12.py")) + .count(), + 1 + ); +} + +#[test] +fn missing_fields_take_defaults() { + let settings: Settings = serde_json::from_str(r#"{"viewer": {"show_edges": false}}"#).unwrap(); + assert!(!settings.viewer.show_edges); + assert!(settings.viewer.fit_automatically); + assert_eq!(settings.editor, Editor::default()); +} + +#[test] +fn preferences_round_trip_through_json() { + let mut settings = Settings::default(); + settings.general.theme = Theme::Dark; + settings.general.python = "python-custom".into(); + settings.viewer.projection = Projection::Perspective; + settings.viewer.orbit_method = OrbitMethod::Trackball; + settings.editor.autoreload = true; + settings.objects.preserve_properties = true; + settings.execution.reload_imported_modules = false; + settings.add_recent_file(Path::new("part.py")); + settings.open_files = vec!["part.py".into(), "parts/axle.py".into()]; + settings.project = Some("project".into()); + settings.remember_project(ProjectState { + root: "project".into(), + main: Some("project/main.py".into()), + expanded: vec!["project/parts".into()], + }); + + let json = serde_json::to_string(&settings).unwrap(); + let loaded: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!(loaded, settings); +} + +#[test] +fn execution_and_scene_settings_are_sent_to_worker() { + let mut settings = Settings::default(); + settings.execution.reload_cq = true; + settings.execution.add_script_dir_to_path = false; + settings.execution.change_working_dir = false; + settings.execution.reload_imported_modules = false; + settings.viewer.linear_tolerance = 0.005; + settings.viewer.angular_tolerance = 0.4; + settings.objects.merge_assemblies = true; + + assert_eq!( + settings.run_settings(), + RunSettings { + reload_cq: true, + add_script_dir_to_path: false, + change_working_dir: false, + reload_imported_modules: false, + } + ); + assert_eq!( + settings.scene_settings(), + SceneSettings { + linear_tolerance: 0.005, + angular_tolerance: 0.4, + merge_assemblies: true, + units: "millimeter".into(), + } + ); +} + +#[test] +fn breakpoints_are_remembered_per_file_and_bounded() { + let mut settings = Settings::default(); + let breakpoint = |line: usize| SavedBreakpoint { + line, + text: format!("line {line}"), + }; + settings.remember_breakpoints(Path::new("a.py"), vec![breakpoint(3)]); + settings.remember_breakpoints(Path::new("b.py"), vec![breakpoint(7), breakpoint(9)]); + assert_eq!(settings.breakpoints_of(Path::new("a.py")), [breakpoint(3)]); + assert_eq!( + settings.breakpoints[0].path, + Path::new("b.py"), + "the latest first" + ); + + // Clearing every breakpoint forgets the file. + settings.remember_breakpoints(Path::new("a.py"), Vec::new()); + assert!(settings.breakpoints_of(Path::new("a.py")).is_empty()); + assert_eq!(settings.breakpoints.len(), 1); + + for file in 0..MAX_BREAKPOINT_FILES + 5 { + let path = format!("{file}.py"); + settings.remember_breakpoints(Path::new(&path), vec![breakpoint(1)]); + } + assert_eq!(settings.breakpoints.len(), MAX_BREAKPOINT_FILES); + + let json = serde_json::to_string(&settings).unwrap(); + let loaded: Settings = serde_json::from_str(&json).unwrap(); + assert_eq!(loaded.breakpoints, settings.breakpoints); +} + +#[test] +fn reopening_a_recent_file_moves_it_to_the_front() { + let mut settings = Settings::default(); + settings.add_recent_file(Path::new("first.py")); + settings.add_recent_file(Path::new("second.py")); + settings.add_recent_file(Path::new("first.py")); + assert_eq!( + settings.recent_files, + vec![PathBuf::from("first.py"), PathBuf::from("second.py")] + ); +} + +#[test] +fn named_views_are_remembered_per_file_and_bounded() { + let mut settings = Settings::default(); + let view = |name: &str| NamedView { + name: name.into(), + rotation: [0.0, 0.0, 0.0, 1.0], + extent: 5.0, + ..NamedView::default() + }; + settings.remember_views(Path::new("a.py"), vec![view("front")]); + settings.remember_views(Path::new("b.py"), vec![view("top"), view("detail")]); + assert_eq!(settings.views_of(Path::new("a.py")), [view("front")]); + assert_eq!( + settings.views[0].path, + Path::new("b.py"), + "the latest first" + ); + + // Deleting every view forgets the file. + settings.remember_views(Path::new("a.py"), Vec::new()); + assert!(settings.views_of(Path::new("a.py")).is_empty()); + assert_eq!(settings.views.len(), 1); + + for file in 0..MAX_VIEW_FILES + 5 { + let path = format!("{file}.py"); + settings.remember_views(Path::new(&path), vec![view("v")]); + } + assert_eq!(settings.views.len(), MAX_VIEW_FILES); + + // Saved settings without views, or with older view entries, still load. + let old: Settings = serde_json::from_str(r#"{"viewer": {}}"#).unwrap(); + assert!(old.views.is_empty()); + let partial: Settings = + serde_json::from_str(r#"{"views": [{"path": "c.py", "views": [{"name": "x"}]}]}"#).unwrap(); + assert_eq!(partial.views_of(Path::new("c.py"))[0].name, "x"); +} + +#[test] +fn the_original_projection_and_stereo_names_are_kept() { + let settings: Settings = serde_json::from_str( + r#"{"viewer": {"projection": "MonoLeftEye", "stereo_mode": "OverUnder"}}"#, + ) + .unwrap(); + assert_eq!(settings.viewer.projection, Projection::MonoLeftEye); + assert_eq!(settings.viewer.stereo_mode, StereoMode::OverUnder); + for (projection, name) in Projection::ALL.into_iter().zip([ + "Orthographic", + "Perspective", + "Stereo", + "MonoLeftEye", + "MonoRightEye", + ]) { + assert_eq!(serde_json::to_value(projection).unwrap(), name); + } + for (mode, name) in StereoMode::ALL.into_iter().zip([ + "QuadBuffer", + "Anaglyph", + "RowInterlaced", + "ColumnInterlaced", + "ChessBoard", + "SideBySide", + "OverUnder", + ]) { + assert_eq!(serde_json::to_value(mode).unwrap(), name); + } +} + +#[test] +fn project_folders_are_remembered_most_recent_first_and_bounded() { + let mut settings = Settings::default(); + for i in 0..MAX_PROJECTS + 3 { + settings.remember_project(ProjectState { + root: format!("p{i}").into(), + ..ProjectState::default() + }); + } + settings.remember_project(ProjectState { + root: "p5".into(), + main: Some("p5/main.py".into()), + expanded: Vec::new(), + }); + assert_eq!(settings.projects.len(), MAX_PROJECTS); + assert_eq!(settings.projects[0].root, Path::new("p5")); + let p5 = settings.project_state(Path::new("p5")).unwrap(); + assert_eq!(p5.main.as_deref(), Some(Path::new("p5/main.py"))); + assert_eq!( + settings + .projects + .iter() + .filter(|p| p.root == Path::new("p5")) + .count(), + 1 + ); +} + +#[test] +fn what_is_remembered_of_a_file_follows_its_rename() { + let mut settings = Settings::default(); + let old = Path::new("/p/parts/axle.py"); + settings.add_recent_file(old); + settings.open_files = vec![old.into(), "/p/main.py".into()]; + settings.last_file = Some(old.into()); + settings.remember_breakpoints( + old, + vec![SavedBreakpoint { + line: 2, + text: "x = 1".into(), + }], + ); + settings.remember_project(ProjectState { + root: "/p".into(), + main: Some(old.into()), + expanded: vec!["/p/parts".into()], + }); + + settings.relocate(Path::new("/p/parts"), Path::new("/p/components")); + let new = Path::new("/p/components/axle.py"); + assert_eq!(settings.recent_files[0], new); + assert_eq!(settings.open_files[0], new); + assert_eq!(settings.open_files[1], Path::new("/p/main.py")); + assert_eq!(settings.last_file.as_deref(), Some(new)); + assert_eq!(settings.breakpoints_of(new).len(), 1); + let project = settings.project_state(Path::new("/p")).unwrap(); + assert_eq!(project.main.as_deref(), Some(new)); + assert_eq!(project.expanded, [PathBuf::from("/p/components")]); +} diff --git a/tests/rust/app/test_tabs.rs b/tests/rust/app/test_tabs.rs new file mode 100644 index 000000000..23c0efdb6 --- /dev/null +++ b/tests/rust/app/test_tabs.rs @@ -0,0 +1,869 @@ +use super::*; +use crate::app::tests::test_state; +use crate::commands::Action; +use crate::document::{DEFAULT_SCRIPT, Encoding}; +use crate::recovery::RecoveryStore; + +/// A folder of its own for each test, with `files` written in it. +fn folder(name: &str, files: &[(&str, &str)]) -> PathBuf { + let folder = std::env::temp_dir().join(format!("cq-editor-tabs-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + for (path, text) in files { + let path = folder.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + std::fs::create_dir_all(&folder).unwrap(); + folder +} + +/// The startup state, with recovery files kept in `folder`. +fn state_in(folder: &Path) -> AppState { + let mut state = test_state(DEFAULT_SCRIPT); + state.recovery = RecoveryStore::new(folder.join(".recovery")); + state.cache_dir = folder.join(".cache"); + state +} + +fn open(state: &mut AppState, path: &Path) { + state.execute(Action::OpenPath(path.to_path_buf())); +} + +fn names(state: &AppState) -> Vec { + state.tabs().into_iter().map(|tab| tab.name).collect() +} + +fn shown_name(state: &AppState) -> String { + state.document.display_name() +} + +fn generation_of(state: &AppState, name: &str) -> u64 { + state + .tabs() + .into_iter() + .find(|tab| tab.name == name) + .unwrap() + .generation +} + +#[test] +fn files_open_in_tabs_and_the_first_replaces_the_startup_script() { + let dir = folder("open", &[("a.py", "a = 1\n"), ("b.py", "b = 2\n")]); + let mut state = state_in(&dir); + assert_eq!(names(&state), ["untitled"]); + + open(&mut state, &dir.join("a.py")); + assert_eq!( + names(&state), + ["a.py"], + "the untouched startup script gave way" + ); + open(&mut state, &dir.join("b.py")); + assert_eq!(names(&state), ["a.py", "b.py"]); + assert_eq!(shown_name(&state), "b.py"); + + // An open file is shown, not opened twice. + open(&mut state, &dir.join("a.py")); + assert_eq!(names(&state), ["a.py", "b.py"]); + assert_eq!(shown_name(&state), "a.py"); + + // New and examples add tabs after the shown one. + state.execute(Action::NewFile); + assert_eq!(names(&state), ["a.py", "untitled", "b.py"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn each_tab_keeps_its_text_breakpoints_and_undo_history() { + let dir = folder("state", &[("a.py", "a = 1\n"), ("b.py", "b = 2\nc = 3\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + state.document.text = "a = 10\n".into(); + state.editor.toggle_breakpoint(1); + let a_cursor = state.editor.cursor_position(&state.document.text); + + open(&mut state, &dir.join("b.py")); + assert_eq!(state.document.text, "b = 2\nc = 3\n"); + assert!(state.editor.breakpoints.is_empty(), "b has its own editor"); + state.editor.toggle_breakpoint(2); + state.execute(Action::ToggleComment); + assert_eq!(state.document.text, "# b = 2\nc = 3\n"); + + state.execute(Action::PreviousTab); + assert_eq!(state.document.text, "a = 10\n", "unsaved edits stay"); + assert!(state.document.is_modified()); + assert_eq!( + state.editor.breakpoints.iter().copied().collect::>(), + [1] + ); + assert_eq!(state.editor.cursor_position(&state.document.text), a_cursor); + + state.execute(Action::NextTab); + assert_eq!( + state.editor.breakpoints.iter().copied().collect::>(), + [2] + ); + state.execute(Action::Undo); + assert_eq!( + state.document.text, "b = 2\nc = 3\n", + "b's own undo history" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn tabs_cycle_both_ways_and_wrap_around() { + let dir = folder("cycle", &[("a.py", ""), ("b.py", ""), ("c.py", "")]); + let mut state = state_in(&dir); + for name in ["a.py", "b.py", "c.py"] { + open(&mut state, &dir.join(name)); + } + state.execute(Action::NextTab); + assert_eq!(shown_name(&state), "a.py"); + state.execute(Action::PreviousTab); + assert_eq!(shown_name(&state), "c.py"); + state.execute(Action::ActivateTab(generation_of(&state, "b.py"))); + assert_eq!(shown_name(&state), "b.py"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn tabs_of_files_with_the_same_name_show_their_folder() { + let dir = folder( + "twins", + &[("left/part.py", ""), ("right/part.py", ""), ("main.py", "")], + ); + let mut state = state_in(&dir); + open(&mut state, &dir.join("left/part.py")); + open(&mut state, &dir.join("right/part.py")); + open(&mut state, &dir.join("main.py")); + assert_eq!( + names(&state), + ["part.py — left", "part.py — right", "main.py"] + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn closing_a_modified_tab_asks_first_then_saves_or_discards() { + let dir = folder("close", &[("a.py", "a = 1\n"), ("b.py", "b = 2\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + open(&mut state, &dir.join("b.py")); + + state.document.text = "b = 20\n".into(); + state.execute(Action::CloseTab); + let b = generation_of(&state, "b.py"); + assert_eq!(state.dialogs.unsaved, Some(Intent::Close(vec![b]))); + assert_eq!(names(&state), ["a.py", "b.py"], "nothing closed yet"); + state.resolve_unsaved( + Intent::Close(vec![b]), + crate::dialogs::UnsavedChoice::Cancel, + ); + assert_eq!(names(&state), ["a.py", "b.py"]); + + state.resolve_unsaved( + Intent::Close(vec![b]), + crate::dialogs::UnsavedChoice::Discard, + ); + assert_eq!(names(&state), ["a.py"]); + assert_eq!(shown_name(&state), "a.py", "its neighbor is shown"); + assert_eq!( + std::fs::read_to_string(dir.join("b.py")).unwrap(), + "b = 2\n" + ); + + state.document.text = "a = 10\n".into(); + let a = state.document_generation; + state.execute(Action::CloseDocument(a)); + state.resolve_unsaved(Intent::Close(vec![a]), crate::dialogs::UnsavedChoice::Save); + assert_eq!( + std::fs::read_to_string(dir.join("a.py")).unwrap(), + "a = 10\n" + ); + // There is always a document. + assert_eq!(names(&state), ["untitled"]); + assert!(state.document.text.is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn unmodified_tabs_close_without_a_question() { + let dir = folder("close-clean", &[("a.py", ""), ("b.py", ""), ("c.py", "")]); + let mut state = state_in(&dir); + for name in ["a.py", "b.py", "c.py"] { + open(&mut state, &dir.join(name)); + } + state.execute(Action::CloseOtherTabs(generation_of(&state, "b.py"))); + assert!(state.dialogs.unsaved.is_none()); + assert_eq!(names(&state), ["b.py"]); + state.execute(Action::CloseAllTabs); + assert_eq!(names(&state), ["untitled"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn closing_the_script_paused_in_the_debugger_ends_its_session() { + let dir = folder("paused", &[("a.py", "a = 1\nb = 2\n"), ("b.py", "c = 3\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + open(&mut state, &dir.join("b.py")); + let a = generation_of(&state, "a.py"); + let text = state.document_of(a).unwrap().text.clone(); + + // A debugging session of a.py, paused at a breakpoint. + let id = 7; + state.run_script = Some(( + id, + std::sync::Arc::new(crate::scene::RunScript { document: a, text }), + )); + state.execution.started(id, true); + assert!(!state.execution.paused(id)); + assert!(state.is_paused()); + + state.execute(Action::CloseDocument(a)); + assert!(state.document_of(a).is_none()); + assert!( + !state.is_debugging(), + "a disconnected worker leaves no paused session" + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn quitting_asks_about_every_modified_tab_at_once() { + let dir = folder("quit", &[("a.py", "a\n"), ("b.py", "b\n"), ("c.py", "c\n")]); + let mut state = state_in(&dir); + for name in ["a.py", "b.py", "c.py"] { + open(&mut state, &dir.join(name)); + } + state.document.text = "c changed\n".into(); + state.execute(Action::ActivateTab(generation_of(&state, "a.py"))); + state.document.text = "a changed\n".into(); + assert!(state.any_modified()); + + state.execute(Action::Quit); + assert_eq!(state.dialogs.unsaved, Some(Intent::Quit)); + let unsaved = state.unsaved_of(&Intent::Quit); + assert_eq!(state.names_of(&unsaved), ["a.py", "c.py"], "in tab order"); + + state.resolve_unsaved(Intent::Quit, crate::dialogs::UnsavedChoice::Save); + assert_eq!( + std::fs::read_to_string(dir.join("a.py")).unwrap(), + "a changed\n" + ); + assert_eq!( + std::fs::read_to_string(dir.join("c.py")).unwrap(), + "c changed\n" + ); + assert!(!state.any_modified()); + assert!(state.allow_close); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_session_reopens_the_tabs_and_shows_the_last_file() { + let dir = folder( + "session", + &[("a.py", "a\n"), ("b.py", "b\n"), ("c.py", "c\n")], + ); + let mut state = state_in(&dir); + for name in ["a.py", "b.py"] { + open(&mut state, &dir.join(name)); + } + state.execute(Action::PreviousTab); + state.remember_session(); + assert_eq!( + state.settings.open_files, + [dir.join("a.py"), dir.join("b.py")] + ); + assert_eq!( + state.settings.last_file.as_deref(), + Some(dir.join("a.py").as_path()) + ); + + let mut next = state_in(&dir); + next.settings = state.settings.clone(); + std::fs::remove_file(dir.join("b.py")).unwrap(); + let problems = next.restore_session(None); + assert!(problems.is_empty(), "{problems:?}"); + assert_eq!(names(&next), ["a.py"], "a deleted file is skipped"); + assert_eq!(shown_name(&next), "a.py"); + + // A file given on the command line joins them and is shown. + let mut next = state_in(&dir); + next.settings = state.settings.clone(); + next.restore_session(Some(dir.join("c.py"))); + assert_eq!(names(&next), ["a.py", "c.py"]); + assert_eq!(shown_name(&next), "c.py"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn settings_of_a_release_without_tabs_reopen_their_last_file() { + let dir = folder("legacy", &[("a.py", "a\n")]); + let mut state = state_in(&dir); + state.settings.last_file = Some(dir.join("a.py")); + state.restore_session(None); + assert_eq!(names(&state), ["a.py"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn f5_renders_the_main_script_while_a_project_file_is_shown() { + let dir = folder( + "main", + &[ + ("main.py", "from part import plate\nshow_object(plate)\n"), + ("part.py", "plate = 1\n"), + ], + ); + let outside = folder("outside", &[("other.py", "x = 1\n")]); + let mut state = state_in(&dir); + state.open_project(&dir).unwrap(); + let project = state.project.as_ref().unwrap(); + assert_eq!(project.main, Some(dir.join("main.py")), "guessed"); + + open(&mut state, &dir.join("part.py")); + assert_eq!(state.main_script(), Some(dir.join("main.py").as_path())); + let part = state.document_generation; + assert_eq!(state.run_target(), part, "not open yet"); + + let target = state.prepare_run_target(); + assert_ne!(target, part); + assert_eq!(shown_name(&state), "part.py", "opened without being shown"); + assert_eq!(names(&state), ["part.py", "main.py"]); + assert_eq!(state.run_target(), target); + assert!( + state + .tabs() + .iter() + .any(|tab| tab.main && tab.generation == target) + ); + + // A file outside the project renders itself. + open(&mut state, &outside.join("other.py")); + assert_eq!(state.main_script(), None); + assert_eq!(state.run_target(), state.document_generation); + + // Without a main script, F5 renders the file shown. + state.execute(Action::ActivateTab(part)); + state.execute(Action::SetMainScript(None)); + assert_eq!(state.run_target(), part); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&outside); +} + +#[test] +fn errors_and_parameters_belong_to_the_script_that_runs() { + let dir = folder( + "errors", + &[ + ("main.py", "width = 4\nboom()\n"), + ("part.py", "plate = 1\n"), + ], + ); + let mut state = state_in(&dir); + state.open_project(&dir).unwrap(); + open(&mut state, &dir.join("part.py")); + let main = state.prepare_run_target(); + state.execution.started(4, false); + state.run_script = Some(( + 4, + std::sync::Arc::new(crate::scene::RunScript { + document: main, + text: "width = 4\nboom()\n".into(), + }), + )); + let message: crate::worker::protocol::Message = serde_json::from_str( + r#"{"type":"run_finished","id":4,"ok":false,"debug":false,"stopped":false, + "objects":null,"variables":null,"duration":0.1, + "error":{"type_name":"NameError","message":"name 'boom' is not defined", + "frames":[{"file":"","line":2,"function":"","code":"boom()"}], + "line":2,"text":"NameError\n"}}"#, + ) + .unwrap(); + state.handle_message(message); + + assert_eq!(shown_name(&state), "part.py", "the shown file stays"); + assert_eq!(state.editor.error_line, None); + assert_eq!(state.traceback_document, Some(main)); + let status = state.status.as_ref().unwrap(); + assert!( + status.text.starts_with("main.py: NameError"), + "{}", + status.text + ); + + // The traceback's line is in main.py. + state.execute(Action::GoToScriptLine { + document: main, + line: 2, + }); + assert_eq!(shown_name(&state), "main.py"); + assert_eq!(state.editor.error_line, Some(2)); + + // Parameters are the main script's, even from another tab. + state.execute(Action::PreviousTab); + assert_eq!(shown_name(&state), "part.py"); + state.set_parameter("width", 1, 6.0); + assert_eq!(state.document_of(main).unwrap().text, "width = 6\nboom()\n"); + assert_eq!(state.document.text, "plate = 1\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn unsaved_modules_next_to_the_script_are_reported_after_a_render() { + let dir = folder("modules", &[("main.py", "x = 1\n"), ("part.py", "p = 1\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("main.py")); + let main = state.document_generation; + open(&mut state, &dir.join("part.py")); + assert!(state.unsaved_modules(main).is_empty()); + state.document.text = "p = 2\n".into(); + assert_eq!(state.unsaved_modules(main), ["part.py"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_traceback_frame_in_a_module_opens_it() { + let dir = folder("module-frame", &[("main.py", ""), ("part.py", "a\nb\nc\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("main.py")); + state.execute(Action::OpenFileAt { + path: dir.join("part.py"), + line: 3, + }); + assert_eq!(shown_name(&state), "part.py"); + assert_eq!(names(&state), ["main.py", "part.py"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_file_changed_on_disk_reloads_its_tab_unless_it_has_unsaved_edits() { + let dir = folder("reload", &[("a.py", "a\n"), ("b.py", "b\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + let a = state.document_generation; + open(&mut state, &dir.join("b.py")); + + std::fs::write(dir.join("a.py"), "a from elsewhere\n").unwrap(); + assert_eq!(state.reload_tab(a), Some(ExternalUpdateKind::Reload)); + assert_eq!(state.document_of(a).unwrap().text, "a from elsewhere\n"); + + state.document.text = "b edited here\n".into(); + std::fs::write(dir.join("b.py"), "b from elsewhere\n").unwrap(); + let b = state.document_generation; + assert_eq!(state.reload_tab(b), Some(ExternalUpdateKind::Conflict)); + assert_eq!(state.document.text, "b edited here\n", "never lost"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Runs a frame's shortcut handling with `key` pressed. +fn press(state: &mut AppState, key: egui::Key, modifiers: egui::Modifiers) { + let ctx = state.ctx.clone(); + let input = egui::RawInput { + events: vec![egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers, + }], + ..Default::default() + }; + let mut output = ctx.run_ui(input, |_| state.begin_frame(&ctx)); + output.textures_delta.clear(); +} + +#[test] +fn shortcuts_wait_while_a_modal_dialog_is_open() { + let dir = folder("modal", &[("a.py", "a\n"), ("b.py", "b\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + open(&mut state, &dir.join("b.py")); + let ctrl = egui::Modifiers::COMMAND; + press(&mut state, egui::Key::Tab, ctrl); + assert_eq!(std::mem::take(&mut state.actions), [Action::NextTab]); + + // Any modal question: nothing may change behind it. + state.dialogs.info("Updates", "No updates available"); + press(&mut state, egui::Key::Tab, ctrl); + press(&mut state, egui::Key::W, ctrl); + press(&mut state, egui::Key::F5, egui::Modifiers::NONE); + assert!(state.actions.is_empty(), "{:?}", state.actions); + + state.dialogs.message = None; + press(&mut state, egui::Key::W, ctrl); + assert_eq!(state.actions, [Action::CloseTab]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_conflict_is_resolved_on_its_own_document_whichever_tab_is_shown() { + use crate::dialogs::{ExternalChange, ExternalChangeChoice}; + let dir = folder("conflict-tab", &[("a.py", "a = 1\n"), ("b.py", "b = 2\n")]); + let file = dir.join("a.py"); + let mut state = state_in(&dir); + open(&mut state, &file); + let a = state.document_generation; + state.document.text = "a = 10 # mine\n".into(); + open(&mut state, &dir.join("b.py")); + let b = state.document_generation; + + let conflict = |state: &mut AppState| { + assert_eq!(state.reload_tab(a), Some(ExternalUpdateKind::Conflict)); + let disk = state + .document_of(a) + .unwrap() + .disk_version() + .unwrap() + .unwrap(); + state.execute(Action::ActivateTab(b)); + ExternalChange { + document: a, + path: file.clone(), + disk, + show_comparison: false, + rerun_after_resolution: false, + on_save: false, + } + }; + + // Keeping my version works on a.py although b.py is shown. + std::fs::write(&file, "a = 98 # theirs\n").unwrap(); + let change = conflict(&mut state); + state.resolve_external_change(change, ExternalChangeChoice::KeepLocal); + assert_eq!(state.document_generation, a, "its tab is shown"); + assert_eq!(state.document.text, "a = 10 # mine\n"); + state.execute(Action::Save); + assert!(state.dialogs.external_change.is_none(), "already decided"); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "a = 10 # mine\n"); + + // Reloading replaces a.py's buffer, not the one shown. + state.document.text = "a = 11 # mine again\n".into(); + std::fs::write(&file, "a = 99 # theirs\n").unwrap(); + let change = conflict(&mut state); + state.resolve_external_change(change, ExternalChangeChoice::Reload); + assert_eq!(state.document_of(a).unwrap().text, "a = 99 # theirs\n"); + assert_eq!(state.document_of(b).unwrap().text, "b = 2\n"); + + // A conflict of a tab closed meanwhile is dropped. + state.document.text = "a = 12\n".into(); + std::fs::write(&file, "a = 100\n").unwrap(); + let change = conflict(&mut state); + state.close_now(a); + state.resolve_external_change(change, ExternalChangeChoice::Reload); + assert_eq!(names(&state), ["b.py"]); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn saving_never_replaces_a_version_another_program_wrote_unseen() { + use crate::dialogs::ExternalChangeChoice; + let dir = folder("save-conflict", &[("part.py", "width = 1\n")]); + let file = dir.join("part.py"); + let mut state = state_in(&dir); + open(&mut state, &file); + assert!( + !state.settings.editor.autoreload, + "nothing watches the file" + ); + + // Another program saves; a habitual Ctrl+S must not undo it. + std::fs::write(&file, "width = 2 # theirs\n").unwrap(); + state.execute(Action::Save); + assert_eq!( + std::fs::read_to_string(&file).unwrap(), + "width = 2 # theirs\n" + ); + let change = state.dialogs.external_change.take().expect("asked"); + assert!(change.on_save); + assert_eq!(change.disk.text, "width = 2 # theirs\n"); + + // Cancel saves nothing. + state.resolve_external_change(change, ExternalChangeChoice::Cancel); + assert_eq!( + std::fs::read_to_string(&file).unwrap(), + "width = 2 # theirs\n" + ); + + // Saving my version replaces it, keeping it in the local history. + state.document.text = "width = 3 # mine\n".into(); + state.execute(Action::Save); + let change = state.dialogs.external_change.take().expect("asked again"); + state.resolve_external_change(change, ExternalChangeChoice::KeepLocal); + assert_eq!( + std::fs::read_to_string(&file).unwrap(), + "width = 3 # mine\n" + ); + assert!(!state.document.is_modified()); + let history = state.recovery.history(Some(&file)).unwrap(); + assert!(history.iter().any(|v| v.text == "width = 2 # theirs\n")); + + // Reloading takes the other version instead. + std::fs::write(&file, "width = 4 # theirs again\n").unwrap(); + state.execute(Action::Save); + let change = state.dialogs.external_change.take().expect("asked"); + state.resolve_external_change(change, ExternalChangeChoice::Reload); + assert_eq!(state.document.text, "width = 4 # theirs again\n"); + assert_eq!( + std::fs::read_to_string(&file).unwrap(), + "width = 4 # theirs again\n" + ); + + // Without a change elsewhere, saving asks nothing. + state.document.text = "width = 5\n".into(); + state.execute(Action::Save); + assert!(state.dialogs.external_change.is_none()); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "width = 5\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn focus_checks_all_tabs_even_without_automatic_reload() { + let dir = folder("focus-disk", &[("a.py", "a = 1\n"), ("b.py", "b = 1\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + let a = generation_of(&state, "a.py"); + state.document.text = "a = 3 # local\n".into(); + open(&mut state, &dir.join("b.py")); + assert!(!state.settings.editor.autoreload); + + std::fs::write(dir.join("a.py"), "a = 2 # disk\n").unwrap(); + std::fs::write(dir.join("b.py"), "b = 2 # disk\n").unwrap(); + state.check_disk_on_focus(); + assert_eq!(state.document_of(a).unwrap().text, "a = 3 # local\n"); + let change = state + .dialogs + .external_change + .take() + .expect("conflict in hidden tab"); + assert_eq!(change.document, a); + assert_eq!(change.disk.text, "a = 2 # disk\n"); + let b = generation_of(&state, "b.py"); + assert_eq!(state.document_of(b).unwrap().text, "b = 2 # disk\n"); + + state.resolve_external_change(change, crate::dialogs::ExternalChangeChoice::Cancel); + std::fs::remove_file(dir.join("a.py")).unwrap(); + state.check_disk_on_focus(); + assert!(state.document_of(a).unwrap().is_missing_on_disk()); + assert!( + state + .tabs() + .iter() + .any(|tab| tab.name.contains("deleted on disk")) + ); + std::fs::write(dir.join("a.py"), "a = 4\n").unwrap(); + state.check_disk_on_focus(); + assert!(!state.document_of(a).unwrap().is_missing_on_disk()); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn local_history_restores_the_tab_that_opened_it() { + let dir = folder( + "history-dialog", + &[("a.py", "a = 1\n"), ("b.py", "b = 1\n")], + ); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + let a = state.document_generation; + state.recovery.archive(&state.document).unwrap(); + state.document.text = "a = 2\n".into(); + state.show_local_history(); + let history = state.dialogs.history.take().expect("history dialog"); + assert_eq!(history.document, a); + let old = history + .versions + .into_iter() + .find(|version| version.text == "a = 1\n") + .unwrap(); + + open(&mut state, &dir.join("b.py")); + let b = state.document_generation; + state.restore_history(a, old); + assert_eq!(state.document_generation, a); + assert_eq!(state.document.text, "a = 1\n"); + assert_eq!(state.document_of(b).unwrap().text, "b = 1\n"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn completions_asked_for_in_another_tab_are_dropped() { + use crate::app::execution::Pending; + let dir = folder("completions", &[("a.py", "import cadquery as cq\ncq.\n")]); + let mut state = state_in(&dir); + state.execute(Action::NewFile); + let untitled = state.document_generation; + open(&mut state, &dir.join("a.py")); + state.execution.track( + 5, + Pending::Completion { + automatic: false, + document: untitled, + }, + ); + let message: crate::worker::protocol::Message = serde_json::from_str( + r#"{"type":"completions","id":5,"available":true, + "items":[{"name":"Workplane","insert":"Workplane","kind":"class"}],"signatures":[]}"#, + ) + .unwrap(); + state.status = None; + state.handle_message(message); + assert!(state.status.is_none(), "no message about it either"); + assert!(!state.execution.is_pending(5), "answered"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn recovered_work_returns_to_the_tabs_of_its_files() { + let dir = folder("recover", &[("a.py", "a\n"), ("b.py", "b\n")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + let snapshot = |path: Option, text: &str| { + let mut document = match &path { + Some(path) => Document::open(path).unwrap(), + None => Document::untitled(""), + }; + document.text = text.into(); + let mut store = RecoveryStore::new(dir.join(".snapshots")); + store.checkpoint(&document).unwrap(); + store.load_session().unwrap().remove(0) + }; + let session = crate::dialogs::RecoverySession { + documents: vec![ + snapshot(Some(dir.join("a.py")), "a recovered\n"), + snapshot(None, "draft\n"), + ], + selected: 0, + }; + state.resolve_recovery_session(session, true); + assert_eq!(names(&state), ["a.py", "untitled"]); + let a = generation_of(&state, "a.py"); + assert_eq!(state.document_of(a).unwrap().text, "a recovered\n"); + assert!(state.document_of(a).unwrap().is_modified()); + assert_eq!(state.document.text, "draft\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn renaming_or_deleting_files_keeps_the_tabs_in_step() { + let dir = folder( + "rename", + &[ + ("main.py", "m\n"), + ("parts/axle.py", "a\n"), + ("parts/gear.py", "g\n"), + ], + ); + let mut state = state_in(&dir); + state.open_project(&dir).unwrap(); + open(&mut state, &dir.join("parts/axle.py")); + state.document.text = "a edited\n".into(); + open(&mut state, &dir.join("parts/gear.py")); + + state + .rename_project_path(&dir.join("parts"), "components") + .unwrap(); + let axle = generation_of(&state, "axle.py"); + let renamed = state.document_of(axle).unwrap(); + assert_eq!( + renamed.path(), + Some(dir.join("components/axle.py").as_path()) + ); + assert!(renamed.is_modified(), "unsaved edits stay unsaved"); + assert_eq!( + state.settings.recent_files[0], + dir.join("components/gear.py") + ); + + // Names that exist, or that are invalid, are refused with a reason. + let error = state + .rename_project_path(&dir.join("main.py"), "components") + .unwrap_err(); + assert!(error.contains("already exists"), "{error}"); + + state + .create_project_file(&dir.join("components"), "bolt") + .unwrap(); + assert_eq!(shown_name(&state), "bolt.py"); + assert!(dir.join("components/bolt.py").is_file()); + + assert_eq!(state.unsaved_below(&dir.join("components")), ["axle.py"]); + state.delete_project_path(&dir.join("components")).unwrap(); + assert!(!dir.join("components").exists()); + assert_eq!(names(&state), ["untitled"], "their tabs closed"); + // The deleted edits stay in the local history. + let history = state + .recovery + .history(Some(&dir.join("components/axle.py"))) + .unwrap(); + assert!(history.iter().any(|version| version.text == "a edited\n")); + assert!( + state + .delete_project_path(&dir) + .unwrap_err() + .contains("project folder") + ); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_reopened_project_keeps_its_main_script_and_folders() { + let dir = folder( + "reopen", + &[ + ("a.py", "show_object(a)\n"), + ("b.py", "show_object(b)\n"), + ("sub/c.py", ""), + ], + ); + let mut state = state_in(&dir); + state.open_project(&dir).unwrap(); + assert_eq!( + state.project.as_ref().unwrap().main, + None, + "not clear which" + ); + state.execute(Action::SetMainScript(Some(dir.join("b.py")))); + state.project.as_mut().unwrap().toggle(&dir.join("sub")); + state.execute(Action::CloseFolder); + assert!(state.project.is_none()); + + state.execute(Action::OpenFolderPath(dir.clone())); + let project = state.project.as_ref().unwrap(); + assert_eq!(project.main, Some(dir.join("b.py"))); + assert!(project.is_expanded(&dir.join("sub"))); + assert_eq!(state.settings.projects[0].root, project.root()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn named_views_follow_the_shown_tab() { + let dir = folder("views", &[("a.py", ""), ("b.py", "")]); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + state.execute(Action::SaveView(Some("front".into()))); + open(&mut state, &dir.join("b.py")); + assert!(state.viewer.named_views.is_empty()); + state.execute(Action::PreviousTab); + assert_eq!(state.viewer.named_views[0].name, "front"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_legacy_encoded_file_opens_in_its_own_tab() { + let dir = folder("legacy-encoding", &[("a.py", "a\n")]); + std::fs::write(dir.join("old.py"), b"# caf\xe9\n").unwrap(); + let mut state = state_in(&dir); + open(&mut state, &dir.join("a.py")); + open(&mut state, &dir.join("old.py")); + assert_eq!(state.dialogs.legacy_encoding, Some(dir.join("old.py"))); + state.open_path_with(&dir.join("old.py"), Encoding::Windows1252); + assert_eq!(names(&state), ["a.py", "old.py"]); + assert_eq!(state.document.text, "# café\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +use crate::document::ExternalUpdate as ExternalUpdateKind; diff --git a/tests/rust/app/test_theme.rs b/tests/rust/app/test_theme.rs new file mode 100644 index 000000000..eabb96aca --- /dev/null +++ b/tests/rust/app/test_theme.rs @@ -0,0 +1,24 @@ +use super::*; +use egui_phosphor::regular as icon; + +#[test] +fn headings_render_icons_like_body_text() { + let definitions = fonts(); + let heading_family = &definitions.families[&FontFamily::Name(SEMIBOLD.into())]; + // Letters still come from the semibold face, icons from Phosphor. + assert_eq!(heading_family[0], "inter-semibold"); + assert!(heading_family.iter().any(|font| font == "phosphor")); + + let ctx = egui::Context::default(); + ctx.set_fonts(definitions); + let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); + // No renderer here to upload the font atlas to. + output.textures_delta.clear(); + + let glyph = icon::GEAR_SIX.chars().next().unwrap(); + let heading = FontId::new(17.0, FontFamily::Name(SEMIBOLD.into())); + ctx.fonts_mut(|fonts| { + assert!(fonts.has_glyph(&FontId::proportional(13.0), glyph)); + assert!(fonts.has_glyph(&heading, glyph), "dialog titles show icons"); + }); +} diff --git a/tests/rust/app/test_toolbar.rs b/tests/rust/app/test_toolbar.rs new file mode 100644 index 000000000..5b6e7177b --- /dev/null +++ b/tests/rust/app/test_toolbar.rs @@ -0,0 +1,32 @@ +use super::*; + +fn total_width() -> f32 { + Group::ALL.iter().map(|group| group.width()).sum::() + + SEPARATOR_WIDTH * (Group::ALL.len() - 1) as f32 +} + +#[test] +fn every_group_shows_when_the_window_is_wide_enough() { + assert_eq!(fitting_groups(total_width()), Group::ALL.len()); + assert_eq!(fitting_groups(4000.0), Group::ALL.len()); +} + +#[test] +fn groups_that_do_not_fit_go_to_the_overflow_menu_from_the_last() { + // The narrowest window CQ-editor allows (760 points). + let shown = fitting_groups(760.0); + assert!(shown > 0 && shown < Group::ALL.len()); + let used: f32 = Group::ALL[..shown] + .iter() + .map(|group| group.width()) + .sum::() + + SEPARATOR_WIDTH * shown as f32 + + BUTTON_SIZE.x; + assert!(used <= 760.0, "the shown groups and » fit: {used}"); + // The file and run commands stay in view. + assert!(shown >= 3, "{shown}"); + + // A point short of the whole toolbar moves only the last group. + assert_eq!(fitting_groups(total_width() - 1.0), Group::ALL.len() - 1); + assert_eq!(fitting_groups(0.0), 0); +} diff --git a/tests/rust/app/test_updates.rs b/tests/rust/app/test_updates.rs new file mode 100644 index 000000000..022fb6685 --- /dev/null +++ b/tests/rust/app/test_updates.rs @@ -0,0 +1,53 @@ +use super::*; + +fn release(tag: &str, url: &str) -> Release { + Release { + tag: tag.to_owned(), + name: tag.to_owned(), + url: url.to_owned(), + } +} + +#[test] +fn versions_compare_by_their_numbers() { + assert_eq!(version_key("v1.2.3-rc1"), (1, 2, 3)); + assert_eq!(version_key("0.8"), (0, 8, 0)); + assert_eq!(version_key("release"), (0, 0, 0)); + assert!(is_newer("v0.10.1", "0.9.9"), "numbers, not text"); + assert!(!is_newer("v0.8.0", "0.8.0")); + assert!(!is_newer("0.7.9", "0.8.0")); +} + +#[test] +fn the_check_runs_once_a_day_unless_turned_off() { + let mut general = General::default(); + assert!(general.check_updates, "on by default"); + let now = 1_800_000_000; + assert!(check_due(&general, now), "never checked"); + general.last_update_check = now - CHECK_INTERVAL + 60; + assert!(!check_due(&general, now)); + general.last_update_check = now - CHECK_INTERVAL; + assert!(check_due(&general, now)); + general.last_update_check = now + 3600; + assert!(!check_due(&general, now), "a clock set back waits"); + general.last_update_check = 0; + general.check_updates = false; + assert!(!check_due(&general, now)); +} + +#[test] +fn only_a_newer_release_with_a_github_page_is_offered() { + let mut general = General::default(); + assert!(available(&general).is_none()); + let page = "https://github.com/igors93/CQ-editor/releases/tag/v99.0.0"; + general.newer_release = Some(release("v99.0.0", page)); + assert_eq!(available(&general).unwrap().url, page); + // Updated since it was found. + general.newer_release = Some(release(VERSION, page)); + assert!(available(&general).is_none()); + general.newer_release = Some(release("v99.0.0", "https://example.com/setup.exe")); + assert!( + available(&general).is_none(), + "pages elsewhere are not opened" + ); +} diff --git a/tests/rust/editor/test_document.rs b/tests/rust/editor/test_document.rs new file mode 100644 index 000000000..f3688a07f --- /dev/null +++ b/tests/rust/editor/test_document.rs @@ -0,0 +1,414 @@ +use super::*; + +fn temporary_file(name: &str) -> PathBuf { + use std::sync::atomic::{AtomicUsize, Ordering}; + static NEXT: AtomicUsize = AtomicUsize::new(0); + std::env::temp_dir().join(format!( + "cq-editor-document-test-{}-{}-{name}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )) +} + +#[test] +fn detects_line_endings() { + assert_eq!(LineEnding::detect("a\r\nb"), LineEnding::CrLf); + assert_eq!(LineEnding::detect("a\nb"), LineEnding::Lf); + assert_eq!(LineEnding::detect("a\rb"), LineEnding::Cr); +} + +#[test] +fn preserves_line_endings_and_tracks_modification() { + let dir = std::env::temp_dir().join(format!("cq-editor-doc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("script.py"); + std::fs::write(&path, "a = 1\r\nb = 2\r\n").unwrap(); + + let mut doc = Document::open(&path).unwrap(); + assert_eq!(doc.text, "a = 1\nb = 2\n"); + assert!(!doc.is_modified()); + + doc.text.push_str("c = 3\n"); + assert!(doc.is_modified()); + assert!(doc.save().unwrap()); + assert!(!doc.is_modified()); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "a = 1\r\nb = 2\r\nc = 3\r\n" + ); + + std::fs::write(&path, "x = 1\r\n").unwrap(); + let external = doc.disk_version().unwrap().unwrap(); + assert!(doc.reload(external).unwrap()); + assert_eq!(doc.text, "x = 1\n"); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn examples_and_untitled_buffers_need_save_as() { + let mut example = Document::example("Hello Box", "x = 1\n"); + assert!(!example.save().unwrap()); + assert_eq!(example.display_name(), "Hello Box (example)"); + assert!(!Document::untitled(DEFAULT_SCRIPT).is_modified()); +} + +#[test] +fn save_as_changes_an_example_into_an_editable_file() { + let path = temporary_file("example.py"); + let mut doc = Document::example("A Box", "x = 1\r\ny = 2\r\n"); + assert_eq!(doc.text, "x = 1\ny = 2\n"); + doc.text.push_str("z = 3\n"); + doc.save_as(&path).unwrap(); + + assert_eq!(doc.path(), Some(path.as_path())); + assert_eq!(doc.example_title(), None); + assert_eq!( + doc.display_name(), + path.file_name().unwrap().to_string_lossy() + ); + assert!(!doc.is_modified()); + let eol = LineEnding::NATIVE.as_str(); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + format!("x = 1{eol}y = 2{eol}z = 3{eol}") + ); + assert!(doc.save().unwrap()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn opens_and_saves_classic_mac_line_endings() { + let path = temporary_file("cr.py"); + std::fs::write(&path, "first\rsecond\r").unwrap(); + let mut doc = Document::open(&path).unwrap(); + assert_eq!(doc.line_ending(), LineEnding::Cr); + assert_eq!(doc.text, "first\nsecond\n"); + doc.text.push_str("third\n"); + assert!(doc.save().unwrap()); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "first\rsecond\rthird\r" + ); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn preserves_a_utf8_bom_without_exposing_it_in_the_editor() { + let path = temporary_file("bom.py"); + std::fs::write(&path, b"\xef\xbb\xbfx = 1\r\n").unwrap(); + let mut doc = Document::open(&path).unwrap(); + assert_eq!(doc.text, "x = 1\n"); + assert!(doc.has_utf8_bom()); + + doc.text.push_str("y = 2\n"); + assert!(doc.save().unwrap()); + assert_eq!( + std::fs::read(&path).unwrap(), + b"\xef\xbb\xbfx = 1\r\ny = 2\r\n" + ); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn reload_refuses_to_discard_unsaved_changes() { + let path = temporary_file("reload.py"); + std::fs::write(&path, "x = 1\n").unwrap(); + let mut doc = Document::open(&path).unwrap(); + let unchanged = doc.disk_version().unwrap().unwrap(); + assert!(!doc.reload(unchanged).unwrap()); + doc.text = "unsaved change".into(); + assert!(doc.is_modified()); + std::fs::write(&path, "external change\n").unwrap(); + + let disk = doc.disk_version().unwrap().unwrap(); + let error = doc.reload(disk.clone()).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::WouldBlock); + assert_eq!(doc.text, "unsaved change"); + assert!(doc.is_modified()); + + assert!(!doc.disk_matches_saved(&disk)); + assert!(doc.apply_disk_version(disk).unwrap()); + assert_eq!(doc.text, "external change\n"); + assert!(!doc.is_modified()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn classifies_external_updates_without_mutating_the_buffer() { + let path = temporary_file("external-update.py"); + std::fs::write(&path, "original\n").unwrap(); + let mut doc = Document::open(&path).unwrap(); + + let unchanged = doc.disk_version().unwrap().unwrap(); + assert_eq!( + doc.classify_external_update(&unchanged), + ExternalUpdate::Unchanged + ); + + std::fs::write(&path, "external\n").unwrap(); + let external = doc.disk_version().unwrap().unwrap(); + assert_eq!( + doc.classify_external_update(&external), + ExternalUpdate::Reload + ); + assert_eq!(doc.text, "original\n"); + + doc.text = "local\n".into(); + assert_eq!( + doc.classify_external_update(&external), + ExternalUpdate::Conflict + ); + assert_eq!(doc.text, "local\n"); + + std::fs::write(&path, "local\n").unwrap(); + let matching = doc.disk_version().unwrap().unwrap(); + assert_eq!( + doc.classify_external_update(&matching), + ExternalUpdate::MatchesBuffer + ); + assert_eq!(doc.text, "local\n"); + assert!(doc.is_modified()); + + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn a_save_finds_the_version_another_program_wrote() { + let path = temporary_file("unseen.py"); + std::fs::write(&path, "original\n").unwrap(); + let mut doc = Document::open(&path).unwrap(); + assert!(doc.unseen_disk_version().unwrap().is_none()); + + // Even an unedited buffer would replace it. + std::fs::write(&path, "theirs\n").unwrap(); + let unseen = doc.unseen_disk_version().unwrap().unwrap(); + assert_eq!(unseen.text, "theirs\n"); + + // Contents equal to the buffer lose nothing. + doc.text = "theirs\n".into(); + assert!(doc.unseen_disk_version().unwrap().is_none()); + + // Once seen and kept, the buffer stays modified and saving goes ahead. + doc.text = "mine\n".into(); + doc.adopt_disk_baseline(&unseen); + assert!(doc.is_modified()); + assert!(doc.unseen_disk_version().unwrap().is_none()); + assert!(doc.save().unwrap()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "mine\n"); + + // A deleted file is simply written again. + std::fs::remove_file(&path).unwrap(); + assert!(doc.unseen_disk_version().unwrap().is_none()); + assert!( + Document::untitled("x") + .unseen_disk_version() + .unwrap() + .is_none() + ); +} + +#[test] +fn recovery_backup_preserves_edits_without_marking_them_saved() { + let path = temporary_file("recovery.py"); + let recovery_dir = temporary_file("recovery-dir"); + std::fs::write(&path, "original\r\n").unwrap(); + let mut doc = Document::open(&path).unwrap(); + doc.text = "local edit\nsecond line\n".into(); + + let backup = doc.create_recovery_backup(&recovery_dir).unwrap(); + assert_eq!( + std::fs::read_to_string(&backup).unwrap(), + "local edit\r\nsecond line\r\n" + ); + assert_eq!(doc.path(), Some(path.as_path())); + assert!(doc.is_modified()); + + std::fs::remove_file(path).unwrap(); + std::fs::remove_dir_all(recovery_dir).unwrap(); +} + +#[test] +fn saving_a_copy_does_not_change_document_identity_or_saved_state() { + let path = temporary_file("source.py"); + let copy = temporary_file("copy.py"); + std::fs::write(&path, "original\n").unwrap(); + let mut doc = Document::open(&path).unwrap(); + doc.text = "local edit\n".into(); + + doc.save_copy(©).unwrap(); + assert_eq!(std::fs::read_to_string(©).unwrap(), "local edit\n"); + assert_eq!(doc.path(), Some(path.as_path())); + assert!(doc.is_modified()); + assert_eq!( + doc.save_copy(&path).unwrap_err().kind(), + std::io::ErrorKind::InvalidInput + ); + + std::fs::remove_file(path).unwrap(); + std::fs::remove_file(copy).unwrap(); +} + +#[test] +fn applying_a_disk_snapshot_rejects_another_document() { + let first = temporary_file("first.py"); + let second = temporary_file("second.py"); + std::fs::write(&first, "first\n").unwrap(); + std::fs::write(&second, "second\n").unwrap(); + let snapshot = Document::open(&first) + .unwrap() + .disk_version() + .unwrap() + .unwrap(); + let mut doc = Document::open(&second).unwrap(); + + assert_eq!( + doc.apply_disk_version(snapshot).unwrap_err().kind(), + std::io::ErrorKind::InvalidInput + ); + assert_eq!(doc.text, "second\n"); + std::fs::remove_file(first).unwrap(); + std::fs::remove_file(second).unwrap(); +} + +#[test] +fn invalid_utf8_is_rejected_without_changing_the_file() { + let path = temporary_file("invalid.py"); + // Latin-1 "café" is intentionally not valid UTF-8. + let original = [b'c', b'a', b'f', 0xe9, b'\n']; + std::fs::write(&path, original).unwrap(); + let error = Document::open(&path).unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::InvalidData); + assert!(error.to_string().contains("not valid UTF-8")); + assert!(is_not_utf8(&error), "the GUI can offer another encoding"); + let missing = Document::open(&temporary_file("missing.py")).unwrap_err(); + assert!(!is_not_utf8(&missing)); + assert_eq!(std::fs::read(&path).unwrap(), original); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn windows_1252_files_open_on_request_and_are_saved_as_utf8() { + let path = temporary_file("legacy.py"); + // "café € “x”" in Windows-1252, with Windows line endings. + let original = b"s = 'caf\xe9 \x80 \x93x\x94'\r\nshow_object(s)\r\n"; + std::fs::write(&path, original).unwrap(); + + let mut document = Document::open_with(&path, Encoding::Windows1252).unwrap(); + assert_eq!(document.text, "s = 'café € “x”'\nshow_object(s)\n"); + assert_eq!(document.encoding(), Encoding::Windows1252); + assert_eq!(document.line_ending(), LineEnding::CrLf); + assert!(!document.is_modified()); + // The file watcher keeps reading it the same way. + let disk = document.disk_version().unwrap().unwrap(); + assert_eq!( + document.classify_external_update(&disk), + ExternalUpdate::Unchanged + ); + assert_eq!( + std::fs::read(&path).unwrap(), + original, + "opening never writes" + ); + + assert!(document.save().unwrap()); + assert_eq!(document.encoding(), Encoding::Utf8); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "s = 'café € “x”'\r\nshow_object(s)\r\n" + ); + assert!(!document.is_modified()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn windows_1252_decodes_every_byte() { + let all: Vec = (0..=255).collect(); + let text = decode_windows_1252(&all); + assert_eq!(text.chars().count(), 256); + assert!(text.starts_with("\0\u{1}")); + let high: Vec = text.chars().skip(0x80).take(4).collect(); + assert_eq!(high, ['€', '\u{81}', '‚', 'ƒ']); + assert_eq!(text.chars().nth(0xe9), Some('é')); + assert_eq!(text.chars().last(), Some('ÿ')); +} + +#[test] +fn a_recovered_legacy_file_keeps_its_encoding_for_the_watcher() { + let path = temporary_file("recovered-legacy.py"); + std::fs::write(&path, b"x = '\xe9'\n").unwrap(); + let document = Document::recovered( + "x = 'é'\ny = 1\n".to_owned(), + Some(path.clone()), + LineEnding::Lf, + false, + ); + assert_eq!(document.encoding(), Encoding::Windows1252); + assert!(document.is_modified()); + assert!(document.disk_version().unwrap().is_some()); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn interrupted_atomic_write_keeps_the_original_file_intact() { + let directory = temporary_file("atomic-write-dir"); + std::fs::create_dir_all(&directory).unwrap(); + let path = directory.join("script.py"); + std::fs::write(&path, "original\n").unwrap(); + + let error = atomic_write_with(&path, true, |file| { + file.write_all(b"partial replacement")?; + Err(std::io::Error::new( + std::io::ErrorKind::Interrupted, + "simulated interruption", + )) + }) + .unwrap_err(); + assert_eq!(error.kind(), std::io::ErrorKind::Interrupted); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "original\n"); + assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 1); + + std::fs::remove_dir_all(directory).unwrap(); +} + +#[cfg(unix)] +#[test] +fn atomic_save_preserves_unix_permissions() { + use std::os::unix::fs::PermissionsExt as _; + + let path = temporary_file("permissions.py"); + std::fs::write(&path, "original\n").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap(); + let mut doc = Document::open(&path).unwrap(); + doc.text = "replacement\n".into(); + doc.save().unwrap(); + + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o640 + ); + std::fs::remove_file(path).unwrap(); +} + +#[cfg(windows)] +#[test] +fn atomic_save_preserves_windows_creation_time() { + let path = temporary_file("windows-metadata.py"); + std::fs::write(&path, "original\n").unwrap(); + let created = std::fs::metadata(&path).unwrap().created().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(20)); + let mut doc = Document::open(&path).unwrap(); + doc.text = "replacement\n".into(); + doc.save().unwrap(); + + assert_eq!( + std::fs::metadata(&path).unwrap().created().unwrap(), + created + ); + std::fs::remove_file(path).unwrap(); +} + +#[test] +fn missing_file_returns_an_error() { + let path = temporary_file("absent.py"); + assert!(Document::open(&path).is_err()); +} diff --git a/tests/rust/editor/test_editor.rs b/tests/rust/editor/test_editor.rs new file mode 100644 index 000000000..b98088468 --- /dev/null +++ b/tests/rust/editor/test_editor.rs @@ -0,0 +1,464 @@ +use super::*; + +#[test] +fn finds_matches_with_and_without_case() { + let text = "Box box BOX"; + assert_eq!(find_all(text, "box", true, false), vec![4..7]); + assert_eq!(find_all(text, "box", false, false), vec![0..3, 4..7, 8..11]); + assert_eq!(find_all("aé é", "É", false, false), vec![1..3, 4..6]); + assert!(find_all(text, "", false, false).is_empty()); +} + +#[test] +fn whole_word_search_skips_parts_of_longer_names() { + let text = "box = boxes(box_2) + box"; + assert_eq!(find_all(text, "box", true, false).len(), 4); + assert_eq!(find_all(text, "box", true, true), vec![0..3, 21..24]); + // Accented letters are name characters too. + assert!(find_all("caixaé", "caixa", true, true).is_empty()); +} + +#[test] +fn the_first_search_step_goes_to_the_first_match_after_the_caret() { + let matches = [4..7, 10..13, 20..23]; + // The query was just typed; nothing is selected yet. + assert_eq!(next_match(&matches, &(0..0), true), Some(0)); + assert_eq!(next_match(&matches, &(4..7), true), Some(1)); + assert_eq!(next_match(&matches, &(20..23), true), Some(0), "wraps"); + assert_eq!(next_match(&matches, &(15..15), true), Some(2)); + assert_eq!(next_match(&matches, &(15..15), false), Some(1)); + assert_eq!(next_match(&matches, &(4..7), false), Some(2), "wraps"); + assert_eq!(next_match(&[], &(0..0), true), None); +} + +#[test] +fn completion_is_offered_once_a_name_reaches_the_threshold() { + assert!(completes_name("res = cq.Wor", 12, 3)); + assert!(!completes_name("res = cq.Wo", 11, 3), "too short"); + assert!( + !completes_name("res = cq.Work", 13, 3), + "already offered at 3" + ); + assert!(!completes_name("x = 123", 7, 3), "a number"); + assert!(!completes_name("box", 3, 0), "turned off"); + assert!(!completes_name("boxes", 3, 3), "inside a longer name"); + assert!(!completes_name("# Exa", 5, 3), "a comment"); + assert!( + !completes_name("name = 'wor", 11, 3), + "a string being typed" + ); + assert!( + !completes_name("doc = '''one\ntwo", 16, 3), + "a docstring's next line" + ); + assert!( + completes_name("x = 'a' + sho", 13, 3), + "after a closed string" + ); +} + +#[test] +fn typed_text_is_empty_after_moving_back() { + assert_eq!(typed_since("cq.Wor", 3, 6), "Wor"); + assert_eq!(typed_since("cq.Wor", 3, 2), ""); +} + +#[test] +fn breakpoints_and_the_error_line_follow_inserted_and_deleted_lines() { + let mut editor = CodeEditor::default(); + editor.sync_markers("a = 1\nb = 2\nc = 3\n"); + editor.breakpoints.extend([2, 3]); + editor.error_line = Some(3); + + editor.sync_markers("import x\na = 1\nb = 2\nc = 3\n"); + assert_eq!( + editor.breakpoints.iter().copied().collect::>(), + [3, 4] + ); + assert_eq!(editor.error_line, Some(4)); + + // Deleting the line under a breakpoint removes the breakpoint. + editor.sync_markers("import x\na = 1\nc = 3\n"); + assert_eq!(editor.breakpoints.iter().copied().collect::>(), [3]); + assert_eq!(editor.error_line, Some(3)); +} + +#[test] +fn a_new_document_does_not_inherit_line_moves() { + let mut editor = CodeEditor::default(); + editor.sync_markers("a\nb\nc\n"); + editor.reset(); + editor.breakpoints.insert(2); + + // The first text after a reset is the reference, not an edit. + editor.sync_markers("x\n"); + assert_eq!(editor.breakpoints.iter().copied().collect::>(), [2]); +} + +#[test] +fn completion_survives_edits_that_move_its_anchor_inside_a_character() { + let mut editor = CodeEditor { + completion: Completion { + items: vec![CompletionItem { + name: "box".to_owned(), + insert: "box".to_owned(), + kind: "function".to_owned(), + }], + // Byte 1 is inside "é" once the text below replaced the buffer. + anchor: 1, + open: true, + ..Completion::default() + }, + selection: Selection::caret(4), + ..CodeEditor::default() + }; + + editor.close_popups_if_left("éé = 1"); + + assert!(!editor.completion.open); + assert_eq!(typed_since("éé", 1, 4), ""); + assert_eq!(typed_text("éé", 2, 4), Some("é")); + assert_eq!(typed_text("abc", 1, 9), None); +} + +fn document(text: &str) -> Document { + Document::untitled(text) +} + +#[test] +fn indent_comment_and_completion_are_undone_as_one_step_each() { + let mut editor = CodeEditor::default(); + let mut doc = document("a = 1\nb = 2\n"); + + editor.selection = Selection { + anchor: 0, + cursor: 9, + }; + let indented = text_ops::indent(&doc.text, &editor.selection); + editor.apply(&mut doc, indented); + editor.toggle_comment(&mut doc); + assert_eq!(doc.text, " # a = 1\n # b = 2\n"); + + editor.completion = Completion { + items: vec![CompletionItem { + name: "box".to_owned(), + insert: "box".to_owned(), + kind: "function".to_owned(), + }], + anchor: doc.text.len(), + open: true, + ..Completion::default() + }; + editor.selection = Selection::caret(doc.text.len()); + editor.accept_completion(&mut doc, 0); + assert!(doc.text.ends_with("box")); + + editor.undo(&mut doc); + assert_eq!(doc.text, " # a = 1\n # b = 2\n", "the completion"); + editor.undo(&mut doc); + assert_eq!(doc.text, " a = 1\n b = 2\n", "the comment"); + editor.undo(&mut doc); + assert_eq!(doc.text, "a = 1\nb = 2\n", "the indent"); + assert!(!editor.can_undo()); + + editor.redo(&mut doc); + assert_eq!(doc.text, " a = 1\n b = 2\n"); + assert!(editor.can_redo()); +} + +#[test] +fn inserted_text_replaces_the_selection_as_one_step() { + let mut editor = CodeEditor::default(); + let mut doc = document("top = box.faces(\"Z\")"); + assert_eq!(doc.text, "top = box.faces(\">Z\")\n"); + assert_eq!(editor.selection, Selection::caret(doc.text.len() - 1)); + + editor.undo(&mut doc); + assert_eq!(doc.text, "top = box.faces(\">(), + [4, 5] + ); + // The restored lines are the reference for later edits. + editor.sync_markers(&changed); + assert_eq!(editor.breakpoints.len(), 2); +} + +#[test] +fn documentation_is_shown_only_for_the_name_still_under_the_pointer() { + let mut editor = CodeEditor::default(); + let documentation = Documentation { + signatures: vec!["box(length: float)".into()], + text: "Return a 3d box.".into(), + }; + editor.hover.target = Some((4..7, 0.0)); + editor.hover.requested = Some(4..7); + editor.show_documentation(documentation.clone()); + assert_eq!(editor.hover.text, Some(documentation.clone())); + + // The pointer moved on before the answer came. + editor.hover = Hover { + target: Some((10..12, 1.0)), + requested: Some(4..7), + text: None, + }; + editor.show_documentation(documentation); + assert_eq!(editor.hover.text, None); +} + +#[test] +fn adjusting_a_literal_keeps_the_caret_on_its_text_and_the_focus() { + let mut editor = CodeEditor::default(); + let mut doc = document("width = 40\nbox(width)\n"); + editor.selection = Selection::caret(doc.text.len() - 1); + + editor.adjust_text(&mut doc, 8..10, "125", 1.0); + editor.adjust_text(&mut doc, 8..11, "7", 1.1); + assert_eq!(doc.text, "width = 7\nbox(width)\n"); + // The caret stays at the end of "box(width)". + assert_eq!(editor.selection, Selection::caret(doc.text.len() - 1)); + assert!(!editor.pending_focus, "the panel keeps the keyboard"); + + // The same value again changes nothing. + editor.adjust_text(&mut doc, 8..9, "7", 1.2); + editor.undo(&mut doc); + assert_eq!(doc.text, "width = 40\nbox(width)\n"); + assert!(!editor.can_undo()); +} + +fn timing(seconds: f64) -> LineTiming { + LineTiming { + seconds, + hits: 1, + operations: Vec::new(), + } +} + +#[test] +fn profile_times_are_written_for_the_gutter() { + assert_eq!(format_seconds(0.0004), "<1 ms"); + assert_eq!(format_seconds(0.0123), "12 ms"); + assert_eq!(format_seconds(0.9994), "999 ms"); + assert_eq!(format_seconds(0.9996), "1.0 s"); + assert_eq!(format_seconds(2.345), "2.3 s"); + assert_eq!(format_seconds(73.2), "73 s"); +} + +#[test] +fn profile_times_land_on_the_edited_text_and_follow_later_edits() { + let run_text = "a = 1\nb = slow()\nc = 3\n"; + let mut editor = CodeEditor::default(); + editor.sync_markers(run_text); + // Edited while it ran: a line was added on top. + let now = "import x\na = 1\nb = slow()\nc = 3\n"; + let profile = [(1, timing(0.001)), (2, timing(2.5)), (3, timing(0.002))]; + editor.set_line_profile(profile.into_iter().collect(), run_text, now); + assert_eq!( + editor.line_profile.keys().copied().collect::>(), + [2, 3, 4] + ); + assert_eq!(editor.line_profile[&3].seconds, 2.5); + + // Like breakpoints: they move with the lines, and go with them. + editor.sync_markers("import x\n\na = 1\nb = slow()\nc = 3\n"); + assert_eq!( + editor.line_profile.keys().copied().collect::>(), + [3, 4, 5] + ); + editor.sync_markers("import x\n\na = 1\nc = 3\n"); + assert_eq!( + editor.line_profile.keys().copied().collect::>(), + [3, 4] + ); + editor.reset(); + assert!(editor.line_profile.is_empty()); +} + +/// The texts an editor paints for `document`. +fn painted_texts(editor: &mut CodeEditor, document: &mut Document) -> Vec { + let ctx = egui::Context::default(); + let colors = crate::theme::Palette::DARK.editor(); + let options = EditorOptions { + font_size: 13.0, + line_wrap: false, + ruler: 0, + highlight_current_line: true, + auto_indent: true, + completion_min_chars: 3, + colors: &colors, + }; + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(800.0, 400.0), + )), + ..Default::default() + }; + let mut texts = Vec::new(); + // Twice: the first frame lays out the text the gutter follows. + for _ in 0..2 { + let mut output = ctx.run_ui(input.clone(), |ui| { + editor.ui(ui, document, &options); + }); + output.textures_delta.clear(); + texts.clear(); + fn collect(shape: &egui::Shape, texts: &mut Vec) { + match shape { + egui::Shape::Text(text) => texts.push(text.galley.text().to_owned()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, texts)), + _ => {} + } + } + for clipped in &output.shapes { + collect(&clipped.shape, &mut texts); + } + } + texts +} + +#[test] +fn the_gutter_shows_profiled_times_and_skips_the_fastest_lines() { + let text = "import time\ntime.sleep(2.5)\nx = 1\n"; + let mut document = Document::untitled(text); + let mut editor = CodeEditor::default(); + assert!( + !painted_texts(&mut editor, &mut document) + .iter() + .any(|t| t.ends_with(" s")) + ); + + let profile = [(1, timing(0.0004)), (2, timing(2.5)), (3, timing(0.012))]; + editor.set_line_profile(profile.into_iter().collect(), text, text); + let texts = painted_texts(&mut editor, &mut document); + assert!(texts.iter().any(|t| t == "2.5 s"), "{texts:?}"); + assert!(texts.iter().any(|t| t == "12 ms")); + assert!( + !texts.iter().any(|t| t == "<1 ms"), + "below a millisecond: blank" + ); +} + +#[test] +fn moving_and_duplicating_lines_are_undoable_and_preserve_markers() { + let initial = "a = 1\nb = 2\nc = 3\n"; + let mut document = Document::untitled(initial); + let mut editor = CodeEditor::default(); + editor.breakpoints.insert(2); + editor.error_line = Some(2); + editor.debug_line = Some(3); + editor.set_line_profile([(2, timing(1.2))].into_iter().collect(), initial, initial); + + editor.go_to_line(&document.text, 2); + editor.selection = Selection::caret(text_ops::line_start(&document.text, 1)); + editor.move_lines(&mut document, false); + assert_eq!(document.text, "a = 1\nc = 3\nb = 2\n"); + assert!(editor.breakpoints.contains(&3)); + assert_eq!(editor.error_line, Some(3)); + assert_eq!(editor.debug_line, Some(2)); + assert!(editor.line_profile.contains_key(&3)); + + editor.undo(&mut document); + assert_eq!(document.text, initial); + assert!(editor.breakpoints.contains(&2)); + assert_eq!(editor.error_line, Some(2)); + assert_eq!(editor.debug_line, Some(3)); + assert!(editor.line_profile.contains_key(&2)); + + editor.duplicate_line(&mut document); + assert_eq!(document.text, "a = 1\nb = 2\nb = 2\nc = 3\n"); + editor.undo(&mut document); + assert_eq!(document.text, initial); +} + +#[test] +fn inserting_a_snippet_from_the_library_is_undoable() { + let mut document = Document::untitled(""); + let mut editor = CodeEditor::default(); + let box_snippet = &crate::editor::snippets::SNIPPETS[1]; + editor.insert_snippet(&mut document, box_snippet); + assert!(document.text.contains("import cadquery as cq")); + assert!(document.text.contains(".box(40, 30, 10)")); + editor.undo(&mut document); + assert_eq!(document.text, ""); +} diff --git a/tests/rust/editor/test_highlight.rs b/tests/rust/editor/test_highlight.rs new file mode 100644 index 000000000..adea556d9 --- /dev/null +++ b/tests/rust/editor/test_highlight.rs @@ -0,0 +1,77 @@ +use super::*; + +fn kinds(text: &str) -> Vec<(&str, TokenKind)> { + tokenize(text) + .into_iter() + .filter(|(_, kind)| *kind != TokenKind::Whitespace) + .map(|(range, kind)| (&text[range], kind)) + .collect() +} + +#[test] +fn covers_the_whole_text() { + let text = "x = f'a{b}' # hé\n\"\"\"doc\nmore\"\"\" 1.5e-3"; + let tokens = tokenize(text); + assert_eq!(tokens.first().unwrap().0.start, 0); + assert_eq!(tokens.last().unwrap().0.end, text.len()); + for pair in tokens.windows(2) { + assert_eq!(pair[0].0.end, pair[1].0.start); + } +} + +#[test] +fn recognizes_python_constructs() { + use TokenKind::*; + assert_eq!( + kinds("def box(self, size=1.5): # comment"), + [ + ("def", Keyword), + ("box", FunctionName), + ("(", Bracket), + ("self", SelfParam), + (",", Operator), + ("size", Identifier), + ("=", Operator), + ("1.5", Number), + (")", Bracket), + (":", Operator), + ("# comment", Comment), + ] + ); + assert_eq!(kinds("class Part:")[1], ("Part", ClassName)); + assert_eq!( + kinds("@cq.Workplane.method")[0], + ("@cq.Workplane.method", Decorator) + ); + assert_eq!(kinds("show_object(result)")[0], ("show_object", EditorApi)); + assert_eq!(kinds("x.print()")[2], ("print", Identifier)); + assert_eq!(kinds("None")[0], ("None", Constant)); +} + +#[test] +fn handles_strings() { + use TokenKind::*; + assert_eq!( + kinds(r#"rb'\d' "a\"b""#), + [(r"rb'\d'", String), (r#""a\"b""#, String)] + ); + assert_eq!(kinds("'''one\ntwo''' x")[0].1, String); + assert_eq!(kinds("'open\nx")[0], ("'open", String)); + // An identifier ending in a prefix letter is not a string prefix. + assert_eq!(kinds("bar'x'")[0], ("bar", Identifier)); +} + +#[test] +fn handles_numbers() { + use TokenKind::*; + assert_eq!( + kinds("0x1F 1_000 2.5e+10 .5 3j"), + [ + ("0x1F", Number), + ("1_000", Number), + ("2.5e+10", Number), + (".5", Number), + ("3j", Number), + ] + ); +} diff --git a/tests/rust/editor/test_history.rs b/tests/rust/editor/test_history.rs new file mode 100644 index 000000000..af71abe87 --- /dev/null +++ b/tests/rust/editor/test_history.rs @@ -0,0 +1,270 @@ +use super::*; + +fn caret(at: usize) -> Selection { + Selection::caret(at) +} + +/// A history that has seen `text` with the caret at its end. +fn seen(text: &str) -> History { + let mut history = History::default(); + history.record( + text, + &caret(text.len()), + &caret(text.len()), + EditKind::Typing, + 0.0, + ); + history +} + +/// Types `typed` one character at a time at the end of `text`. +fn type_text(history: &mut History, text: &mut String, typed: &str, mut time: f64) -> f64 { + for c in typed.chars() { + let before = caret(text.len()); + text.push(c); + history.record(text, &before, &caret(text.len()), EditKind::Typing, time); + time += 0.1; + } + time +} + +#[test] +fn the_first_record_is_the_starting_point_not_a_step() { + let history = seen("box = 1\n"); + assert!(!history.can_undo() && !history.can_redo()); +} + +#[test] +fn continuous_typing_is_one_step() { + let mut text = String::from("x = "); + let mut history = seen(&text); + type_text(&mut history, &mut text, "cq.Workplane", 1.0); + + let (text, selection) = history.undo(&text).unwrap(); + assert_eq!(text, "x = "); + assert_eq!(selection, caret(4)); + assert!(!history.can_undo()); +} + +#[test] +fn a_pause_a_caret_move_or_a_new_line_starts_a_new_step() { + let mut text = String::new(); + let mut history = seen(&text); + let time = type_text(&mut history, &mut text, "ab", 1.0); + // A pause. + let time = type_text(&mut history, &mut text, "cd", time + 5.0); + // A new line, then more typing. + let time = type_text(&mut history, &mut text, "\nef", time); + // A caret move: the next character is typed elsewhere. + let before = caret(0); + text.insert(0, '#'); + history.record(&text, &before, &caret(1), EditKind::Typing, time); + + let mut undone = Vec::new(); + while let Some((previous, _)) = history.undo(&text) { + text = previous; + undone.push(text.clone()); + } + assert_eq!(undone, ["abcd\nef", "abcd\n", "abcd", "ab", ""]); +} + +#[test] +fn deleting_after_typing_is_a_step_of_its_own() { + let mut text = String::from("box"); + let mut history = seen(&text); + let time = type_text(&mut history, &mut text, "es", 1.0); + for _ in 0..2 { + let before = caret(text.len()); + text.pop(); + history.record(&text, &before, &caret(text.len()), EditKind::Typing, time); + } + + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "boxes", "both backspaces at once"); + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "box"); +} + +#[test] +fn commands_are_single_steps_even_amid_typing() { + let mut text = String::from("a"); + let mut history = seen(&text); + let time = type_text(&mut history, &mut text, "bc", 1.0); + // An indent, at once, between keystrokes. + let before = caret(text.len()); + text.insert_str(0, " "); + history.record(&text, &before, &caret(text.len()), EditKind::Command, time); + type_text(&mut history, &mut text, "de", time + 0.1); + + let (text, selection) = history.undo(&text).unwrap(); + assert_eq!(text, " abc"); + let (text, selection_after_indent) = history.undo(&text).unwrap(); + assert_eq!(text, "abc", "the indent alone"); + assert_eq!(selection_after_indent, caret(3)); + assert_eq!(selection, caret(7)); + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "a"); +} + +#[test] +fn a_paste_is_one_step() { + let mut text = String::from("ab"); + let mut history = seen(&text); + let before = caret(1); + text.insert_str(1, "pasted"); + history.record(&text, &before, &caret(7), EditKind::Typing, 1.0); + type_text(&mut history, &mut text, "x", 1.1); + + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "apastedb"); + let (text, selection) = history.undo(&text).unwrap(); + assert_eq!(text, "ab"); + assert_eq!(selection, caret(1)); +} + +#[test] +fn redo_reapplies_and_a_new_edit_drops_it() { + let mut text = String::from("abc"); + let mut history = seen(&text); + let before = caret(3); + text = "# abc".to_owned(); + history.record(&text, &before, &caret(5), EditKind::Command, 1.0); + + let (undone, _) = history.undo(&text).unwrap(); + assert_eq!(undone, "abc"); + let (redone, selection) = history.redo(&undone).unwrap(); + assert_eq!(redone, "# abc"); + assert_eq!(selection, caret(5)); + + let (mut text, _) = history.undo(&redone).unwrap(); + assert!(history.can_redo()); + type_text(&mut history, &mut text, "d", 2.0); + assert!(!history.can_redo()); +} + +#[test] +fn typing_after_an_undo_starts_a_new_step() { + let mut text = String::new(); + let mut history = seen(&text); + type_text(&mut history, &mut text, "ab", 1.0); + type_text(&mut history, &mut text, "c", 9.0); + let (mut text, _) = history.undo(&text).unwrap(); + type_text(&mut history, &mut text, "x", 9.1); + + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "ab"); +} + +#[test] +fn undo_refuses_a_text_it_has_not_seen() { + let mut text = String::from("a"); + let mut history = seen(&text); + type_text(&mut history, &mut text, "b", 1.0); + + assert!(history.undo("changed elsewhere").is_none()); + assert!(history.can_undo()); +} + +#[test] +fn multibyte_characters_are_never_split() { + let mut text = String::from("ação"); + let mut history = seen(&text); + // "ã" → "á": both start with the same byte. + let before = caret(3); + text = "açáo".to_owned(); + history.record(&text, &before, &caret(5), EditKind::Command, 1.0); + assert_eq!( + diff("ação", "açáo"), + Change { + start: 3, + removed: "ã".into(), + inserted: "á".into() + } + ); + + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "ação"); +} + +#[test] +fn clear_forgets_the_previous_document() { + let mut text = String::from("first file"); + let mut history = seen(&text); + type_text(&mut history, &mut text, "!", 1.0); + history.clear(); + let other = "second file"; + history.record(other, &caret(0), &caret(0), EditKind::Command, 2.0); + + assert!(!history.can_undo()); + assert!(history.undo(other).is_none()); +} + +#[test] +fn old_steps_are_dropped_beyond_the_limit() { + let mut text = String::new(); + let mut history = seen(&text); + for step in 0..MAX_STEPS + 10 { + let before = caret(text.len()); + text.push('x'); + history.record( + &text, + &before, + &caret(text.len()), + EditKind::Command, + step as f64, + ); + } + let mut count = 0; + while let Some((previous, _)) = history.undo(&text) { + text = previous; + count += 1; + } + assert_eq!(count, MAX_STEPS); + assert_eq!(text.len(), 10); +} + +/// Sets the literal at `start` to `value` as an adjustment. +fn adjust( + history: &mut History, + text: &mut String, + start: usize, + end: usize, + value: &str, + time: f64, +) -> usize { + text.replace_range(start..end, value); + history.record(text, &caret(0), &caret(0), EditKind::Adjust(start), time); + start + value.len() +} + +#[test] +fn successive_values_of_one_literal_are_one_step() { + let mut text = String::from("width = 40\nheight = 12\n"); + let mut history = seen(&text); + history.record(&text, &caret(0), &caret(0), EditKind::Command, 0.0); + let mut end = 10; + for (value, time) in [("41", 1.0), ("45", 1.2), ("100", 1.4), ("90", 1.6)] { + end = adjust(&mut history, &mut text, 8, end, value, time); + } + assert_eq!(text, "width = 90\nheight = 12\n"); + + let (undone, _) = history.undo(&text).unwrap(); + assert_eq!(undone, "width = 40\nheight = 12\n"); + assert!(!history.can_undo()); +} + +#[test] +fn another_literal_or_a_pause_starts_a_new_adjustment_step() { + let mut text = String::from("width = 40\nheight = 12\n"); + let mut history = seen(&text); + adjust(&mut history, &mut text, 8, 10, "41", 1.0); + adjust(&mut history, &mut text, 20, 22, "13", 1.1); + adjust(&mut history, &mut text, 20, 22, "14", 9.0); + + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "width = 41\nheight = 13\n", "after the pause"); + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "width = 41\nheight = 12\n", "the other literal"); + let (text, _) = history.undo(&text).unwrap(); + assert_eq!(text, "width = 40\nheight = 12\n"); +} diff --git a/tests/rust/editor/test_recovery.rs b/tests/rust/editor/test_recovery.rs new file mode 100644 index 000000000..9fa908507 --- /dev/null +++ b/tests/rust/editor/test_recovery.rs @@ -0,0 +1,346 @@ +use super::*; + +fn temporary_directory(name: &str) -> PathBuf { + use std::sync::atomic::{AtomicUsize, Ordering}; + static NEXT: AtomicUsize = AtomicUsize::new(0); + std::env::temp_dir().join(format!( + "cq-editor-recovery-test-{}-{}-{name}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )) +} + +#[test] +fn checkpoint_restores_unsaved_work_after_a_simulated_crash() { + let root = temporary_directory("crash"); + let source = root.join("source.py"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(&source, "saved\n").unwrap(); + let mut document = Document::open(&source).unwrap(); + document.text = "unsaved work\n".into(); + + let mut running_store = RecoveryStore::new(root.join("store")); + assert!(running_store.checkpoint(&document).unwrap()); + drop(running_store); + + let restarted_store = RecoveryStore::new(root.join("store")); + let mut session = restarted_store.load_session().unwrap(); + assert_eq!(session.len(), 1); + let snapshot = session.remove(0); + assert_eq!(snapshot.path.as_deref(), Some(source.as_path())); + assert_eq!(snapshot.text, "unsaved work\n"); + let recovered = snapshot.into_document(); + assert_eq!(recovered.text, "unsaved work\n"); + assert!(recovered.is_modified()); + + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn checkpoint_recovers_an_unsaved_untitled_document() { + let root = temporary_directory("untitled"); + let mut document = Document::untitled("initial\n"); + document.text = "draft without a file\n".into(); + + let mut running_store = RecoveryStore::new(root.clone()); + running_store.checkpoint(&document).unwrap(); + drop(running_store); + + let restarted_store = RecoveryStore::new(root.clone()); + let recovered = restarted_store.load_session().unwrap()[0] + .clone() + .into_document(); + assert_eq!(recovered.path(), None); + assert_eq!(recovered.text, "draft without a file\n"); + assert!(recovered.is_modified()); + + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn checkpoints_are_deduplicated_and_available_as_local_history() { + let root = temporary_directory("history"); + let source = root.join("source.py"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(&source, "saved\n").unwrap(); + let mut document = Document::open(&source).unwrap(); + let mut store = RecoveryStore::new(root.join("store")); + + document.text = "version one\n".into(); + assert!(store.checkpoint(&document).unwrap()); + assert!(!store.checkpoint(&document).unwrap()); + document.text = "version two\n".into(); + assert!(store.checkpoint(&document).unwrap()); + + let history = store.history(Some(&source)).unwrap(); + assert_eq!(history.len(), 3); + assert_eq!(history[0].text, "version two\n"); + assert!(history.iter().any(|entry| entry.text == "saved\n")); + assert!(history.iter().any(|entry| entry.text == "version one\n")); + assert!(history.iter().any(|entry| entry.text == "version two\n")); + + store.clear_session().unwrap(); + assert!(store.load_session().unwrap().is_empty()); + assert_eq!(store.history(Some(&source)).unwrap().len(), 3); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn local_history_is_bounded_per_document() { + let root = temporary_directory("bounded"); + let source = root.join("source.py"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(&source, "saved\n").unwrap(); + let mut document = Document::open(&source).unwrap(); + let mut store = RecoveryStore::new(root.join("store")); + + for version in 0..MAX_HISTORY_PER_DOCUMENT + 5 { + document.text = format!("version {version}\n"); + assert!(store.checkpoint(&document).unwrap()); + } + + assert_eq!( + store.history(Some(&source)).unwrap().len(), + MAX_HISTORY_PER_DOCUMENT + ); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn an_unmodified_document_clears_only_the_active_session() { + let root = temporary_directory("clean"); + let source = root.join("source.py"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(&source, "saved\n").unwrap(); + let mut document = Document::open(&source).unwrap(); + let mut store = RecoveryStore::new(root.join("store")); + + document.text = "unsaved\n".into(); + store.checkpoint(&document).unwrap(); + let disk = document.disk_version().unwrap().unwrap(); + document.apply_disk_version(disk).unwrap(); + assert!(!store.checkpoint(&document).unwrap()); + assert!(store.load_session().unwrap().is_empty()); + assert_eq!(store.history(Some(&source)).unwrap().len(), 2); + + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn the_session_keeps_every_unsaved_tab_and_versions_only_what_changed() { + let root = temporary_directory("tabs"); + let (first_path, mut first) = saved_document(&root, "first.py"); + let (second_path, mut second) = saved_document(&root, "second.py"); + let clean = Document::untitled(""); + let mut store = RecoveryStore::new(root.join("store")); + + first.text = "first edit\n".into(); + second.text = "second edit\n".into(); + assert!(store.checkpoint_all(&[&first, &clean, &second]).unwrap()); + assert!(!store.checkpoint_all(&[&first, &clean, &second]).unwrap()); + second.text = "second edit again\n".into(); + assert!(store.checkpoint_all(&[&first, &clean, &second]).unwrap()); + + let session = RecoveryStore::new(root.join("store")) + .load_session() + .unwrap(); + let texts: Vec<&str> = session.iter().map(|s| s.text.as_str()).collect(); + assert_eq!( + texts, + ["first edit\n", "second edit again\n"], + "in tab order" + ); + assert_eq!(session[0].path.as_deref(), Some(first_path.as_path())); + + // The unchanged document got no second version: a baseline and an edit. + assert_eq!(store.history(Some(&first_path)).unwrap().len(), 2); + assert_eq!(store.history(Some(&second_path)).unwrap().len(), 3); + + // Saving one keeps the other in the session. + let disk = first.disk_version().unwrap().unwrap(); + first.apply_disk_version(disk).unwrap(); + assert!(store.checkpoint_all(&[&first, &second]).unwrap()); + let session = store.load_session().unwrap(); + assert_eq!(session.len(), 1); + assert_eq!(session[0].path.as_deref(), Some(second_path.as_path())); + + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn a_session_of_an_earlier_release_is_still_recovered() { + let root = temporary_directory("legacy-session"); + std::fs::create_dir_all(&root).unwrap(); + let legacy = snapshot(None, "draft\n", 1); + std::fs::write( + root.join("active-session.json"), + serde_json::to_vec(&legacy).unwrap(), + ) + .unwrap(); + let session = RecoveryStore::new(root.clone()).load_session().unwrap(); + assert_eq!(session.len(), 1); + assert_eq!(session[0].text, "draft\n"); + std::fs::remove_dir_all(root).unwrap(); +} + +fn saved_document(root: &Path, name: &str) -> (PathBuf, Document) { + std::fs::create_dir_all(root).unwrap(); + let source = root.join(name); + std::fs::write(&source, "saved\n").unwrap(); + let document = Document::open(&source).unwrap(); + (source, document) +} + +fn write_version(directory: &Path, snapshot: &RecoverySnapshot) -> PathBuf { + std::fs::create_dir_all(directory).unwrap(); + let path = directory.join(version_name(snapshot.timestamp_ms, 0)); + std::fs::write(&path, serde_json::to_vec(snapshot).unwrap()).unwrap(); + path +} + +fn snapshot(path: Option<&Path>, text: &str, timestamp_ms: u64) -> RecoverySnapshot { + RecoverySnapshot { + schema: SCHEMA_VERSION, + timestamp_ms, + path: path.map(Path::to_path_buf), + text: text.to_owned(), + line_ending: LineEnding::Lf, + utf8_bom: false, + } +} + +#[test] +fn each_document_keeps_its_history_in_its_own_folder() { + let root = temporary_directory("folders"); + let (first_path, mut first) = saved_document(&root, "first.py"); + let (second_path, mut second) = saved_document(&root, "second.py"); + let mut untitled = Document::untitled(""); + let mut store = RecoveryStore::new(root.join("store")); + + // Like the app, which clears the session whenever the document changes. + first.text = "first edit\n".into(); + store.checkpoint(&first).unwrap(); + store.clear_session().unwrap(); + second.text = "second edit\n".into(); + store.checkpoint(&second).unwrap(); + store.clear_session().unwrap(); + untitled.text = "draft\n".into(); + store.checkpoint(&untitled).unwrap(); + + let history = root.join("store").join("history"); + let folder = |path: Option<&Path>| history.join(document_folder(path)); + // A baseline and an edit each; a checkpoint only lists its own folder. + assert_eq!(version_files(&folder(Some(&first_path))).unwrap().len(), 2); + assert_eq!(version_files(&folder(Some(&second_path))).unwrap().len(), 2); + assert_eq!(version_files(&folder(None)).unwrap().len(), 1); + assert!(version_files(&history).unwrap().is_empty(), "no flat files"); + + let mut texts = |path| -> Vec { + store + .history(path) + .unwrap() + .into_iter() + .map(|version| version.text) + .collect() + }; + assert_eq!(texts(Some(&first_path)), ["first edit\n", "saved\n"]); + assert_eq!(texts(None), ["draft\n"]); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn folder_names_are_stable_across_releases() { + // The paths of the system's file dialogs, as earlier releases hashed them. + #[cfg(not(windows))] + let (native, folder) = ("scripts/part.py", "doc-58d2002fe837b7f2"); + #[cfg(windows)] + let (native, folder) = ("scripts\\part.py", "doc-d3fbd233f36653b9"); + assert_eq!(document_folder(Some(Path::new(native))), folder); + assert_eq!(document_folder(None), "untitled"); + assert_eq!( + version_timestamp("version-1700000000000-3.json"), + Some(1_700_000_000_000) + ); + assert_eq!(version_timestamp("notes.json"), None); +} + +#[test] +fn a_file_has_one_history_however_its_path_is_written() { + let written = Path::new("scripts").join("part.py"); + assert_eq!( + document_folder(Some(Path::new("scripts/part.py"))), + document_folder(Some(&written)) + ); + assert_eq!( + document_folder(Some(Path::new("scripts/./part.py"))), + document_folder(Some(&written)) + ); + #[cfg(windows)] + assert_eq!( + document_folder(Some(Path::new(r"C:/Users/me/part.py"))), + document_folder(Some(Path::new(r"C:\Users\me\part.py"))) + ); +} + +#[test] +fn flat_history_of_earlier_releases_is_migrated() { + let root = temporary_directory("migrate"); + let (source, document) = saved_document(&root, "legacy.py"); + let history = root.join("store").join("history"); + let old = write_version( + &history, + &snapshot(Some(&source), "old version\n", timestamp_ms()), + ); + + let mut store = RecoveryStore::new(root.join("store")); + let versions = store.history(document.path()).unwrap(); + assert_eq!(versions.len(), 1); + assert_eq!(versions[0].text, "old version\n"); + assert!(!old.exists(), "moved into the document's folder"); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn old_versions_and_histories_of_deleted_files_expire() { + let root = temporary_directory("expire"); + let store = RecoveryStore::new(root.clone()); + let now = timestamp_ms(); + let expired_ms = now - MAX_HISTORY_AGE.as_millis() as u64 - 1; + let deleted = Path::new("deleted-long-ago.py"); + let kept = Path::new("still-edited.py"); + let deleted_dir = store.document_dir(Some(deleted)); + let kept_dir = store.document_dir(Some(kept)); + write_version(&deleted_dir, &snapshot(Some(deleted), "gone\n", expired_ms)); + let old = write_version(&kept_dir, &snapshot(Some(kept), "old\n", expired_ms)); + let recent = write_version(&kept_dir, &snapshot(Some(kept), "recent\n", now)); + + store.prune_all(now).unwrap(); + + assert!(!deleted_dir.exists(), "an emptied folder is removed"); + assert!(!old.exists()); + assert!(recent.exists()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn the_oldest_versions_go_first_beyond_the_size_budget() { + let root = temporary_directory("budget"); + let mut store = RecoveryStore::new(root.clone()); + let now = timestamp_ms(); + let text = "x".repeat(1000); + let files: Vec = (0..6) + .map(|age| { + let path = PathBuf::from(format!("part-{age}.py")); + let version = snapshot(Some(&path), &text, now - 1000 * age); + write_version(&store.document_dir(Some(&path)), &version) + }) + .collect(); + let size = std::fs::metadata(&files[0]).unwrap().len(); + store.max_history_bytes = 3 * size; + + store.prune_all(now).unwrap(); + + let remaining: Vec = files.iter().map(|path| path.exists()).collect(); + assert_eq!(remaining, [true, true, true, false, false, false]); + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/tests/rust/editor/test_text_ops.rs b/tests/rust/editor/test_text_ops.rs new file mode 100644 index 000000000..8706d4143 --- /dev/null +++ b/tests/rust/editor/test_text_ops.rs @@ -0,0 +1,349 @@ +use super::*; + +fn sel(anchor: usize, cursor: usize) -> Selection { + Selection { anchor, cursor } +} + +#[test] +fn line_helpers() { + let text = "ab\ncd\n\nef"; + assert_eq!(line_of(text, 4), 1); + assert_eq!(line_start(text, 2), 6); + assert_eq!(line_range(text, 3), 7..9); + assert_eq!(line_column("é\nxyz", 5), (1, 2)); + assert_eq!(char_to_byte("aé b", 2), 3); + assert_eq!(byte_to_char("aé b", 3), 2); +} + +#[test] +fn comments_a_single_line_and_moves_the_caret() { + let edited = toggle_comment(" x = 1\n", &Selection::caret(6)); + assert_eq!(edited.text, " # x = 1\n"); + assert_eq!(edited.selection, Selection::caret(8)); + let back = toggle_comment(&edited.text, &edited.selection); + assert_eq!(back.text, " x = 1\n"); + assert_eq!(back.selection, Selection::caret(6)); +} + +#[test] +fn comments_blocks_at_the_common_indentation() { + let text = "if a:\n b = 1\n\n # c\n"; + let edited = toggle_comment(text, &sel(0, text.len())); + assert_eq!(edited.text, "# if a:\n# b = 1\n\n# # c\n"); + // All lines commented now, so toggling again uncomments them. + let back = toggle_comment(&edited.text, &sel(0, edited.text.len())); + assert_eq!(back.text, text); +} + +#[test] +fn selection_ending_at_line_start_excludes_that_line() { + let text = "a\nb\nc\n"; + let edited = toggle_comment(text, &sel(0, 4)); + assert_eq!(edited.text, "# a\n# b\nc\n"); +} + +#[test] +fn indents_to_tab_stops_or_whole_lines() { + let edited = indent("ab", &Selection::caret(1)); + assert_eq!(edited.text, "a b"); + assert_eq!(edited.selection, Selection::caret(4)); + + let edited = indent("a\n\nb\n", &sel(0, 4)); + assert_eq!(edited.text, " a\n\n b\n"); + // Insertions at a selection end push it forward. + assert_eq!(edited.selection, sel(4, 12)); +} + +#[test] +fn unindents_to_the_previous_tab_stop() { + let edited = unindent(" a\n\tb\nc", &sel(0, 11)); + assert_eq!(edited.text, " a\nb\nc"); + let edited = unindent(" x", &Selection::caret(9)); + assert_eq!(edited.text, " x"); + assert_eq!(edited.selection, Selection::caret(5)); +} + +#[test] +fn newline_indentation() { + assert_eq!(newline_with_indent("def f(x):", 9), "\n "); + assert_eq!(newline_with_indent(" x = 1", 9), "\n "); + assert_eq!(newline_with_indent(" return x", 12), "\n"); + assert_eq!( + newline_with_indent("for c in 'a:b': # loop:", 24), + "\n " + ); + assert_eq!(newline_with_indent("x = 'a#:'", 9), "\n"); +} + +#[test] +fn unicode_offsets_round_trip_at_character_boundaries() { + let text = "á中\n🙂x"; + for index in 0..=text.chars().count() { + let byte = char_to_byte(text, index); + assert_eq!(byte_to_char(text, byte), index); + } + assert_eq!(line_column(text, char_to_byte(text, 4)), (1, 1)); + assert_eq!(char_to_byte(text, 100), text.len()); +} + +#[test] +fn commenting_blank_lines_is_a_noop() { + let text = " \n\n"; + let selection = sel(0, text.len()); + assert_eq!( + toggle_comment(text, &selection), + Edited { + text: text.into(), + selection, + } + ); +} + +#[test] +fn uncommenting_hash_without_space_only_removes_hash() { + let edited = toggle_comment(" #value\n", &Selection::caret(4)); + assert_eq!(edited.text, " value\n"); + assert_eq!(edited.selection, Selection::caret(3)); +} + +#[test] +fn indent_replaces_single_line_selection_at_next_tab_stop() { + let edited = indent("abCD", &sel(2, 4)); + assert_eq!(edited.text, "ab "); + assert_eq!(edited.selection, Selection::caret(4)); +} + +#[test] +fn unindent_leaves_unindented_text_unchanged() { + let text = "first\nsecond"; + let selection = sel(0, text.len()); + assert_eq!( + unindent(text, &selection), + Edited { + text: text.into(), + selection, + } + ); +} + +#[test] +fn newline_dedents_after_control_flow_statements() { + for keyword in ["pass", "break", "continue", "raise", "return"] { + let line = format!(" {keyword}"); + assert_eq!(newline_with_indent(&line, line.len()), "\n "); + } + assert_eq!(newline_with_indent(" return_value", 16), "\n "); +} + +#[test] +fn newline_ignores_colons_inside_comments_and_strings() { + let comment = " value = 1 # note:"; + assert_eq!(newline_with_indent(comment, comment.len()), "\n "); + let string = " label = 'x:'"; + assert_eq!(newline_with_indent(string, string.len()), "\n "); + let block = " if ready: # note"; + assert_eq!(newline_with_indent(block, block.len()), "\n "); +} + +#[test] +fn line_map_keeps_lines_while_typing_inside_a_line() { + let map = LineMap::new("a\nb\nc", "a\nbx\nc"); + assert_eq!([1, 2, 3].map(|l| map.map(l)), [Some(1), Some(2), Some(3)]); +} + +#[test] +fn line_map_moves_lines_below_inserted_lines() { + let map = LineMap::new("a\nb\nc", "a\nnew\nb\nc"); + assert_eq!([1, 2, 3].map(|l| map.map(l)), [Some(1), Some(3), Some(4)]); + + // Enter at the start of a line pushes it down; in its middle it stays. + assert_eq!(LineMap::new("x\ny", "x\n\ny").map(2), Some(3)); + let split = LineMap::new("x = 1\ny", "x =\n 1\ny"); + assert_eq!((split.map(1), split.map(2)), (Some(1), Some(3))); +} + +#[test] +fn line_map_follows_the_statement_rather_than_similar_text() { + // The new line resembles the old one; the old line still moves down. + let map = LineMap::new("y\nx = 1\nz", "y\nx = 0\nx = 1\nz"); + assert_eq!(map.map(2), Some(3)); +} + +#[test] +fn line_map_drops_deleted_lines_and_keeps_merged_ones() { + let deleted = LineMap::new("a\nb\nc\nd", "a\nd"); + assert_eq!( + [1, 2, 3, 4].map(|l| deleted.map(l)), + [Some(1), None, None, Some(2)] + ); + + let merged = LineMap::new("a\nb\nc", "ab\nc"); + assert_eq!( + [1, 2, 3].map(|l| merged.map(l)), + [Some(1), Some(1), Some(2)] + ); +} + +#[test] +fn line_map_keeps_positions_when_a_block_is_indented() { + let map = LineMap::new("if x:\na\nb\nc", "if x:\n a\n b\nc"); + assert_eq!( + [1, 2, 3, 4].map(|l| map.map(l)), + [Some(1), Some(2), Some(3), Some(4)] + ); +} + +#[test] +fn names_are_found_around_any_of_their_characters() { + let text = "r = cq.Workplane().box(1)"; + assert_eq!(word_at(text, 7), Some(7..16)); + assert_eq!(word_at(text, 15), Some(7..16)); + assert_eq!(word_at(text, 6), None, "the dot"); + assert_eq!(word_at(text, text.len()), None); + assert_eq!(word_at("área = 1", 2), Some(0..5), "accents are letters"); +} + +#[test] +fn the_name_before_the_caret_counts_only_at_its_end() { + assert_eq!(name_before("x = cq.Wor", 10), "Wor"); + assert_eq!(name_before("x = cq.Workplane", 9), "", "inside the name"); + assert_eq!(name_before("x = ", 4), ""); + assert_eq!(name_before("éé", 1), "", "not a character boundary"); +} + +#[test] +fn go_to_line_accepts_a_line_and_an_optional_column() { + let text = "first\nsecond line\nthird"; + assert_eq!(go_to_target(text, "2"), Some((1, 6))); + assert_eq!(go_to_target(text, " 2:8 "), Some((1, 13))); + assert_eq!(go_to_target(text, "2:99"), Some((1, 17)), "end of the line"); + assert_eq!(go_to_target(text, "40"), Some((2, 18)), "the last line"); + assert_eq!(go_to_target(text, "0"), None); + assert_eq!(go_to_target(text, "two"), None); + assert_eq!(go_to_target(text, ""), None); +} + +#[test] +fn replacing_ranges_keeps_the_selection_on_the_same_text() { + let edited = replace_ranges("a b a", &sel(4, 5), &[0..1, 4..5], "xyz"); + assert_eq!(edited.text, "xyz b xyz"); + assert_eq!( + edited.selection, + sel(6, 9), + "the replacement of the selection" + ); +} + +#[test] +fn breakpoints_are_relocated_by_the_text_of_their_line() { + let text = "a = 1\nb = 2\n\nb = 2\nc = 3"; + let saved = |line: usize, content: &str| (line, content.to_owned()); + // Unchanged line. + assert_eq!(relocate_lines(text, &[saved(5, "c = 3")]), [5].into()); + // Moved: the nearest line with that text wins. + assert_eq!(relocate_lines(text, &[saved(5, "b = 2")]), [4].into()); + assert_eq!(relocate_lines(text, &[saved(1, "b = 2")]), [2].into()); + // Gone, or a blank line. + assert!(relocate_lines(text, &[saved(1, "d = 4"), saved(3, "")]).is_empty()); +} + +#[test] +fn a_line_of_the_run_is_found_again_after_edits() { + let ran = "import cadquery as cq\nplate = cq.Workplane().box(4, 4, 1)\nhole = plate.hole(1)\n"; + // Unchanged. + assert_eq!(locate_line(ran, 2, ran), Some(Located::Unchanged(2))); + // Lines added above move it. + let added = format!("# A plate\n\n{ran}"); + assert_eq!(locate_line(ran, 2, &added), Some(Located::Moved(4))); + // Its own text was edited: where the edit left it. + let edited = ran.replace("box(4, 4, 1)", "box(5, 4, 1)"); + assert_eq!(locate_line(ran, 2, &edited), Some(Located::Changed(2))); + // Moved elsewhere by a cut and paste: found by its text. + let pasted = + "import cadquery as cq\nhole = plate.hole(1)\nplate = cq.Workplane().box(4, 4, 1)\n"; + assert_eq!(locate_line(ran, 2, pasted), Some(Located::Moved(3))); + // Deleted with its neighbours. + assert_eq!(locate_line(ran, 2, "import cadquery as cq\n"), None); + // Not a line of the run. + assert_eq!(locate_line(ran, 0, ran), None); + assert_eq!(locate_line(ran, 99, ran), None); +} + +#[test] +fn a_repeated_line_is_found_nearest_to_where_it_was() { + let ran = "a = f()\nb = 1\na = f()\nc = 2\n"; + let edited = "a = f()\nb = 10\nx = 0\na = f()\nc = 2\n"; + assert_eq!(locate_line(ran, 3, edited), Some(Located::Moved(4))); + assert_eq!(locate_line(ran, 1, edited), Some(Located::Unchanged(1))); +} + +#[test] +fn duplicating_lines_copies_the_line_or_block_and_keeps_the_selection_on_the_copy() { + let edited = duplicate_lines("a = 1\nb = 2\n", &Selection::caret(2)); + assert_eq!(edited.text, "a = 1\na = 1\nb = 2\n"); + assert_eq!(edited.selection, Selection::caret(8)); + + let block = "first\nsecond\nthird"; + let edited = duplicate_lines(block, &sel(1, 9)); + assert_eq!(edited.text, "first\nsecond\nfirst\nsecond\nthird"); + assert_eq!(&edited.text[edited.selection.range()], "irst\nsec"); +} + +#[test] +fn moving_lines_up_and_down_swaps_neighbours_and_preserves_selection() { + let text = "line 1\nline 2\nline 3"; + let up = move_lines_up(text, &Selection::caret(9)); + assert_eq!(up.text, "line 2\nline 1\nline 3"); + assert_eq!(up.selection, Selection::caret(2)); + + let down = move_lines_down(&up.text, &up.selection); + assert_eq!(down.text, text); + assert_eq!(down.selection, Selection::caret(9)); + + // At the boundaries nothing changes. + assert_eq!(move_lines_up(text, &Selection::caret(0)).text, text); + assert_eq!(move_lines_down(text, &Selection::caret(16)).text, text); + + // Moving a multi-line block down. + let block_down = move_lines_down("a\nb\nc\nd", &sel(0, 3)); + assert_eq!(block_down.text, "c\na\nb\nd"); + assert_eq!(&block_down.text[block_down.selection.range()], "a\nb"); +} + +#[test] +fn line_map_tracks_rotated_lines_when_moving_up_or_down() { + let before = "alpha\nbeta\ngamma\ndelta\n"; + let moved_up = "alpha\ngamma\nbeta\ndelta\n"; + let map = LineMap::new(before, moved_up); + assert_eq!(map.map(1), Some(1)); + assert_eq!(map.map(2), Some(3)); + assert_eq!(map.map(3), Some(2)); + assert_eq!(map.map(4), Some(4)); +} + +#[test] +fn inserting_snippets_adds_import_once_and_indents_inner_blocks() { + let empty = insert_snippet( + "", + &Selection::caret(0), + "box = cq.Workplane(\"XY\").box(10, 10, 10)", + true, + ); + assert_eq!( + empty.text, + "import cadquery as cq\n\nbox = cq.Workplane(\"XY\").box(10, 10, 10)" + ); + + let with_import = "import cadquery as cq\n\ndef build():\n "; + let indented = insert_snippet( + with_import, + &Selection::caret(with_import.len()), + "wp = (\n cq.Workplane(\"XY\")\n .box(10, 10, 10)\n)", + true, + ); + assert_eq!( + indented.text, + "import cadquery as cq\n\ndef build():\n wp = (\n cq.Workplane(\"XY\")\n .box(10, 10, 10)\n )" + ); + assert_eq!(indented.text.matches("import cadquery").count(), 1); +} diff --git a/tests/rust/panels/test_console.rs b/tests/rust/panels/test_console.rs new file mode 100644 index 000000000..f2c946d86 --- /dev/null +++ b/tests/rust/panels/test_console.rs @@ -0,0 +1,160 @@ +use super::*; + +#[test] +fn completion_inserts_unique_matches_and_common_prefixes() { + let mut console = ConsoleState { + input: "cq.Work".to_owned(), + ..Default::default() + }; + console.complete(&[("Workplane".into(), "plane".into())], &[]); + assert_eq!(console.input, "cq.Workplane"); + + let mut console = ConsoleState::default(); + console.complete( + &[ + ("box".into(), "ox".into()), + ("bounding".into(), "ounding".into()), + ], + &[], + ); + assert_eq!(console.input, "o"); + + let mut console = ConsoleState::default(); + console.complete( + &[("abc".into(), "abc".into()), ("xyz".into(), "xyz".into())], + &[], + ); + assert_eq!(console.entries[0].text, "abc xyz\n"); +} + +fn picture(text: &str) -> DisplayOutput { + DisplayOutput { + id: 1, + text: text.to_owned(), + image: Some(DisplayImage { + size: [1, 1], + rgba: vec![255; 4], + }), + } +} + +#[test] +fn rich_results_show_their_image_then_their_text() { + let mut console = ConsoleState::default(); + console.push(EntryKind::Output, "printed "); + console.push_display(picture("
")); + console.push_display(DisplayOutput { + id: 1, + text: "42".to_owned(), + image: None, + }); + console.push(EntryKind::Output, "after"); + let entries: Vec<_> = console + .entries + .iter() + .map(|e| (e.text.as_str(), e.image.is_some())) + .collect(); + assert_eq!( + entries, + [ + ("printed ", false), + ("
\n", true), + ("42\n", false), + ("after", false) + ], + "nothing is appended to an image's entry, nor after a result" + ); + // An empty result adds nothing. + console.push_display(DisplayOutput { + id: 1, + text: String::new(), + image: None, + }); + assert_eq!(console.entries.len(), 4); +} + +#[test] +fn only_the_latest_images_are_kept() { + let mut console = ConsoleState::default(); + for n in 0..MAX_IMAGES + 3 { + console.push_display(picture(&n.to_string())); + } + let kept = console.entries.iter().filter(|e| e.image.is_some()).count(); + assert_eq!(kept, MAX_IMAGES); + assert_eq!(console.entries[0].text, "[image]\n0\n"); + assert!(console.entries[3].image.is_some()); + assert!(console.entries.last().unwrap().image.is_some()); +} + +#[test] +fn the_image_memory_budget_drops_oldest_pixels() { + let mut console = ConsoleState::default(); + console.push_display(picture("old")); + console.push_display(picture("new")); + + console.trim_images(MAX_IMAGES, 4); + + assert!(console.entries[0].image.is_none()); + assert_eq!(console.entries[0].text, "[image]\nold\n"); + assert!(console.entries[1].image.is_some()); +} + +#[test] +fn images_are_uploaded_once_and_kept_between_frames() { + let mut console = ConsoleState::default(); + console.push_display(DisplayOutput { + id: 1, + text: String::new(), + image: Some(DisplayImage { + size: [3, 2], + rgba: vec![255; 24], + }), + }); + let ctx = egui::Context::default(); + let mut frame = || { + let mut drawn = ctx.run_ui(egui::RawInput::default(), |ui| { + let colors = Colors::new(ui.visuals()); + output(ui, &mut console, &colors); + }); + let uploads = drawn + .textures_delta + .set + .values() + .flatten() + .filter(|delta| delta.image.size() == [3, 2]) + .count(); + drawn.textures_delta.clear(); + uploads + }; + assert_eq!(frame(), 1); + assert_eq!(frame(), 0, "the texture is kept"); +} + +#[test] +fn history_search_finds_commands_cycles_matches_and_restores_draft_on_cancel() { + let mut console = ConsoleState::default(); + console.record_input("a = cq.Workplane('XY').box(10, 10, 10)"); + console.record_input("show_object(a, name='box_a')"); + console.record_input("b = cq.Workplane('XY').cylinder(20, 5)"); + console.record_input("show_object(b, name='cyl_b')"); + assert_eq!(console.history().len(), 4); + + console.input = "draft_expr".to_owned(); + console.open_history_search(); + console.set_history_search_query("show_object"); + assert_eq!(console.history_matches("show_object"), vec![3, 1]); + assert_eq!(console.input, "show_object(b, name='cyl_b')"); + + console.step_history_search(true); + assert_eq!(console.input, "show_object(a, name='box_a')"); + + console.cancel_history_search(); + assert!(!console.search_open); + assert_eq!(console.input, "draft_expr"); + + console.open_history_search(); + console.set_history_search_query("cylinder"); + console.accept_history_search(); + assert!(!console.search_open); + assert_eq!(console.input, "b = cq.Workplane('XY').cylinder(20, 5)"); +} diff --git a/tests/rust/panels/test_empty_state.rs b/tests/rust/panels/test_empty_state.rs new file mode 100644 index 000000000..aa16090fd --- /dev/null +++ b/tests/rust/panels/test_empty_state.rs @@ -0,0 +1,66 @@ +use super::*; + +#[test] +fn tab_content_cannot_paint_outside_its_assigned_body() { + let ctx = egui::Context::default(); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(500.0, 400.0)); + let body = egui::Rect::from_min_size(egui::pos2(300.0, 40.0), egui::vec2(180.0, 130.0)); + let input = egui::RawInput { + screen_rect: Some(screen), + ..Default::default() + }; + let mut clipped = egui::Rect::NOTHING; + + let mut output = ctx.run_ui(input, |_root| { + // Reproduce the fresh UI used for an egui_dock tab: its layout is + // bounded by `body`, while its paint clip initially covers the screen. + let mut tab = egui::Ui::new( + ctx.clone(), + egui::Id::new("tab_clip_regression"), + egui::UiBuilder::new().max_rect(body), + ); + tab.set_clip_rect(screen); + constrain_to_tab(&mut tab); + clipped = tab.clip_rect(); + }); + output.textures_delta.clear(); + + assert_eq!(clipped, body); +} + +#[test] +fn empty_state_rows_are_centered_with_natural_spacing() { + let ctx = egui::Context::default(); + // A first pass loads the fonts. + let mut output = ctx.run_ui(egui::RawInput::default(), |_| {}); + output.textures_delta.clear(); + + let style = egui::Style::default(); + let text = "Select a workplane in Objects to inspect it"; + let job = empty_state_job(&style, text, egui::Color32::GRAY, 150.0); + let mut plain = job.clone(); + plain.halign = egui::Align::LEFT; + let mut justified = plain.clone(); + justified.justify = true; + let [centered, plain, justified] = + [job, plain, justified].map(|job| ctx.fonts_mut(|fonts| fonts.layout_job(job))); + let widths = |galley: &egui::Galley| -> Vec { + galley.rows.iter().map(|row| row.rect().width()).collect() + }; + + assert!(centered.rows.len() > 1, "the text wraps in a narrow panel"); + for row in ¢ered.rows { + let rect = row.rect(); + assert!(rect.center().x.abs() < 1.0, "row centered: {rect:?}"); + } + // Each row keeps the width of ordinary text (without its trailing + // space), where the old justified layout stretched it to the full width. + let (centered, plain, justified) = (widths(¢ered), widths(&plain), widths(&justified)); + for (row, (natural, plain)) in centered.iter().zip(&plain).enumerate() { + assert!(natural <= plain, "row {row}: {natural} > {plain}"); + } + assert!( + centered[0] < justified[0] - 2.0, + "{centered:?} vs {justified:?}" + ); +} diff --git a/tests/rust/panels/test_objects.rs b/tests/rust/panels/test_objects.rs new file mode 100644 index 000000000..3aa82b863 --- /dev/null +++ b/tests/rust/panels/test_objects.rs @@ -0,0 +1,101 @@ +use super::*; + +/// Lays out a property sheet much taller than a pane of `height` points. +/// Returns the pane, the sheet and what is left for the tree. +fn layout(height: f32) -> (egui::Rect, egui::Rect, egui::Rect) { + let ctx = egui::Context::default(); + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(300.0, height), + )), + ..Default::default() + }; + let mut rects = ( + egui::Rect::NOTHING, + egui::Rect::NOTHING, + egui::Rect::NOTHING, + ); + // Panels settle their size over passes, like real frames. + for _ in 0..3 { + let mut output = ctx.run_ui(input.clone(), |ui| { + let pane = ui.available_rect_before_wrap(); + let sheet = property_sheet(ui, |ui| { + for row in 0..40 { + ui.label(format!("Property {row}")); + } + }); + rects = (pane, sheet, ui.available_rect_before_wrap()); + }); + // No renderer here to upload the font atlas to. + output.textures_delta.clear(); + } + rects +} + +#[test] +fn a_tall_property_sheet_scrolls_instead_of_covering_the_tree() { + let (pane, sheet, tree) = layout(300.0); + + assert!(tree.height() >= TREE_MIN_HEIGHT - 0.5, "tree {tree:?}"); + assert!( + sheet.height() <= pane.height() - TREE_MIN_HEIGHT + 0.5, + "sheet {sheet:?}" + ); + assert!( + tree.max.y <= sheet.min.y + 0.5, + "the tree ends above the sheet" + ); +} + +#[test] +fn a_very_short_pane_keeps_most_of_its_height_for_the_tree() { + let (pane, sheet, tree) = layout(100.0); + + assert!( + sheet.height() <= pane.height() * 0.4 + 0.5, + "sheet {sheet:?}" + ); + assert!(tree.height() >= pane.height() * 0.6 - 0.5, "tree {tree:?}"); +} + +#[test] +fn the_property_sheet_shows_short_numbers_without_rounding_noise() { + assert_eq!(compact(100.0), "100"); + assert_eq!(compact(2.5), "2.5"); + assert_eq!(compact(-6.938_893_9e-18), "0"); + assert_eq!(compact(std::f64::consts::PI), "3.1416"); + assert_eq!(compact(-12.25), "-12.25"); +} + +#[test] +fn object_name_filter_matches_nodes_and_subassemblies_without_changing_visibility() { + fn sample_node(key: &str, name: &str, children: Vec) -> SceneNode { + SceneNode { + key: key.to_owned(), + name: name.to_owned(), + kind: "shape".to_owned(), + inspectable: false, + parts: Vec::new(), + children, + visible: true, + color: None, + alpha: None, + edge_color: None, + finish: None, + overrides: Default::default(), + line: None, + script: None, + } + } + + let bolt = sample_node("n-bolt", "M6_Bolt", Vec::new()); + let nut = sample_node("n-nut", "Hex_Nut", Vec::new()); + let subassembly = sample_node("n-fasteners", "Fasteners", vec![bolt, nut]); + let housing = sample_node("n-housing", "Main_Housing", Vec::new()); + + assert!(node_matches_filter(&subassembly, "bolt")); + assert!(node_matches_filter(&subassembly, "FASTEN")); + assert!(!node_matches_filter(&housing, "bolt")); + assert!(subassembly.visible && housing.visible); +} diff --git a/tests/rust/panels/test_parameters.rs b/tests/rust/panels/test_parameters.rs new file mode 100644 index 000000000..1f926f374 --- /dev/null +++ b/tests/rust/panels/test_parameters.rs @@ -0,0 +1,54 @@ +use super::*; + +#[test] +fn parameters_are_parsed_once_per_text() { + let mut state = ParametersState::default(); + let text = "a = 1\nb = 2.5\n"; + assert_eq!(state.of(text).len(), 2); + let first = state.parsed.as_ref().map(|(hash, _)| *hash); + state.of(text); + assert_eq!(state.parsed.as_ref().map(|(hash, _)| *hash), first); + assert_eq!(state.of("a = 1\n").len(), 1); +} + +#[test] +fn sliders_keep_their_range_during_a_drag() { + let mut state = ParametersState::default(); + let width = |text: &str| crate::parameters::parameters(text).remove(0); + + assert_eq!(state.slider_range(&width("width = 40")), 0.0..=80.0); + // Dragging changes the value, not the range under the pointer. + assert_eq!(state.slider_range(&width("width = 70")), 0.0..=80.0); + // A value typed outside widens it. + assert_eq!(state.slider_range(&width("width = 120")), 0.0..=120.0); + // A commented range wins. + assert_eq!( + state.slider_range(&width("width = 40 # [10, 50]")), + 10.0..=50.0 + ); +} + +#[test] +fn automatic_ranges_suit_the_sign_and_size() { + assert_eq!(automatic_range(2.5, false), 0.0..=10.0); + assert_eq!(automatic_range(-30.0, false), -60.0..=0.0); + assert_eq!(automatic_range(0.0, true), -5.0..=5.0); + assert_eq!(automatic_range(7.0, true), 0.0..=14.0); +} + +#[test] +fn modified_parameters_are_tracked_against_the_saved_baseline() { + let mut state = ParametersState::default(); + let baseline = "width = 40\nheight = 20\n"; + let edited = "width = 55\nheight = 20\ndepth = 10\n"; + let current = crate::parameters::parameters(edited); + + state.update_references(baseline, ¤t); + assert_eq!(state.reference_value("width"), Some(40.0)); + assert_eq!(state.reference_value("height"), Some(20.0)); + assert_eq!(state.reference_value("depth"), Some(10.0)); + assert!(state.is_modified(¤t[0])); + assert!(!state.is_modified(¤t[1])); + assert!(!state.is_modified(¤t[2])); + assert!(state.any_modified(¤t)); +} diff --git a/tests/rust/panels/test_variables.rs b/tests/rust/panels/test_variables.rs new file mode 100644 index 000000000..641dcc47c --- /dev/null +++ b/tests/rust/panels/test_variables.rs @@ -0,0 +1,103 @@ +use super::*; + +#[test] +fn the_value_column_keeps_room_in_narrow_panes() { + // The default layout gives the panel about 280 points. + for width in [180.0, 220.0, 280.0, 400.0, 900.0] { + let (name, type_name) = column_widths(width); + let value = width - name - type_name; + assert!( + value >= MIN_VALUE_WIDTH, + "{width} wide: only {value} for values" + ); + } + // The former fixed widths (120 and 90) left 70 points at 280. + let (name, type_name) = column_widths(280.0); + assert!(280.0 - name - type_name > 120.0); +} + +#[test] +fn clicking_the_text_of_a_row_selects_it() { + let variable = Variable { + name: "a_rather_long_variable_name".to_owned(), + type_name: "Workplane".to_owned(), + value: "x".repeat(500), + }; + let rows = [&variable]; + let ctx = egui::Context::default(); + let mut selected = None; + // Returns where the rows are. + let run = |events: Vec, selected: &mut Option| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(400.0, 200.0), + )), + events, + ..Default::default() + }; + let mut body = egui::Rect::NOTHING; + let mut output = ctx.run_ui(input, |ui| body = table(ui, &rows, selected)); + output.textures_delta.clear(); + body + }; + let body = run(Vec::new(), &mut selected); + + // On the name's text, which a selectable label used to take. + let pos = body.left_top() + egui::vec2(12.0, 6.0); + let button = |pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }; + run(vec![egui::Event::PointerMoved(pos)], &mut selected); + run(vec![button(true)], &mut selected); + run(vec![button(false)], &mut selected); + assert_eq!(selected.as_deref(), Some("a_rather_long_variable_name")); +} + +#[test] +fn the_rows_stay_above_the_detail_view_in_a_short_pane() { + let variables: Vec = (0..12) + .map(|index| Variable { + name: format!("value_{index}"), + type_name: "str".to_owned(), + value: "x".repeat(400), + }) + .collect(); + let rows: Vec<&Variable> = variables.iter().collect(); + let mut selected = Some("value_1".to_owned()); + let ctx = egui::Context::default(); + // As short as the Variables pane of the default layout can get. + let height = 130.0; + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(280.0, height), + )), + ..Default::default() + }; + let mut rects = (egui::Rect::NOTHING, None); + // Panels settle their size over passes, like real frames. + for _ in 0..3 { + let mut output = ctx.run_ui(input.clone(), |ui| { + rects = table_and_detail(ui, &rows, &mut selected); + }); + output.textures_delta.clear(); + } + + let (table, detail) = rects; + let detail = detail.expect("the selected row has a detail view"); + // Its contents fit its size instead of growing it over the rows. + assert!( + detail.height() <= height * 0.6 + 0.5, + "detail view {detail:?}" + ); + assert!( + table.max.y <= detail.min.y + 0.5, + "the rows {table:?} end above the detail view {detail:?}" + ); + assert!(table.height() > 0.0); + assert_eq!(selected.as_deref(), Some("value_1")); +} diff --git a/tests/rust/protocol/test_launch.rs b/tests/rust/protocol/test_launch.rs new file mode 100644 index 000000000..d4cc2c946 --- /dev/null +++ b/tests/rust/protocol/test_launch.rs @@ -0,0 +1,107 @@ +use super::*; + +#[test] +fn explicit_interpreter_overrides_auto_detection() { + assert_eq!( + find_python(Some(" custom/python ")), + PathBuf::from("custom/python") + ); + assert_eq!( + find_python(Some("C:/tools/python.exe")), + PathBuf::from("C:/tools/python.exe") + ); +} + +#[test] +fn conda_environments_are_listed_after_the_base_interpreter() { + let root = std::env::temp_dir().join(format!("cq-editor-conda-test-{}", std::process::id())); + let interpreter = |environment: &Path| { + CONDA_PYTHON + .iter() + .fold(environment.to_path_buf(), |path, part| path.join(part)) + }; + for environment in [ + root.clone(), + root.join("envs").join("cadquery"), + root.join("envs").join("broken"), + ] { + std::fs::create_dir_all(interpreter(&environment).parent().unwrap()).unwrap(); + } + std::fs::write(interpreter(&root), b"").unwrap(); + std::fs::write(interpreter(&root.join("envs").join("cadquery")), b"").unwrap(); + + assert_eq!( + environments_in(&root), + [ + interpreter(&root), + interpreter(&root.join("envs").join("cadquery")) + ] + ); + assert!(environments_in(&root.join("missing")).is_empty()); + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn candidates_exist_and_are_listed_once() { + let found = candidates(); + assert!(found.iter().all(|path| path.is_file())); + let unique: std::collections::BTreeSet<_> = found.iter().collect(); + assert_eq!(unique.len(), found.len()); +} + +#[test] +fn existing_interpreter_requires_a_regular_file() { + let directory = + std::env::temp_dir().join(format!("cq-editor-launch-test-{}", std::process::id())); + std::fs::create_dir_all(directory.join("bin")).unwrap(); + let python = directory.join("bin").join("python-test"); + assert_eq!(existing(&directory, &["bin", "python-test"]), None); + std::fs::write(&python, b"").unwrap(); + assert_eq!(existing(&directory, &["bin", "python-test"]), Some(python)); + assert_eq!(existing(&directory, &["bin"]), None); + std::fs::remove_dir_all(directory).unwrap(); +} + +#[test] +fn installed_executable_finds_its_bundled_python() { + let root = std::env::temp_dir().join(format!("cq-editor-bundled-test-{}", std::process::id())); + let executable = if cfg!(windows) { + root.join("cq-editor.exe") + } else { + root.join("bin").join("cq-editor") + }; + let python = CONDA_PYTHON + .iter() + .fold(root.clone(), |path, part| path.join(part)); + std::fs::create_dir_all(executable.parent().unwrap()).unwrap(); + std::fs::create_dir_all(python.parent().unwrap()).unwrap(); + std::fs::write(&executable, b"").unwrap(); + std::fs::write(&python, b"").unwrap(); + std::fs::write(root.join(".installer.info"), b"").unwrap(); + + assert_eq!(bundled_python_for(&executable), Some(python)); + + std::fs::remove_dir_all(root).unwrap(); +} + +#[test] +fn unrelated_executable_does_not_invent_a_bundled_python() { + let root = + std::env::temp_dir().join(format!("cq-editor-unbundled-test-{}", std::process::id())); + let executable = root.join("app").join(if cfg!(windows) { + "cq-editor.exe" + } else { + "cq-editor" + }); + std::fs::create_dir_all(executable.parent().unwrap()).unwrap(); + std::fs::write(&executable, b"").unwrap(); + let unmarked_python = CONDA_PYTHON + .iter() + .fold(root.clone(), |path, part| path.join(part)); + std::fs::create_dir_all(unmarked_python.parent().unwrap()).unwrap(); + std::fs::write(unmarked_python, b"").unwrap(); + + assert_eq!(bundled_python_for(&executable), None); + + std::fs::remove_dir_all(root).unwrap(); +} diff --git a/tests/rust/protocol/test_protocol.rs b/tests/rust/protocol/test_protocol.rs new file mode 100644 index 000000000..f5dbfcaa0 --- /dev/null +++ b/tests/rust/protocol/test_protocol.rs @@ -0,0 +1,787 @@ +use super::*; + +fn b64(bytes: &[u8]) -> String { + base64::engine::general_purpose::STANDARD.encode(bytes) +} + +#[test] +fn decodes_meshes() { + let positions: Vec = [0.0f32, 1.0, 2.0, 3.0, 4.0, 5.0] + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect(); + let indices: Vec = [0u32, 1, 1].iter().flat_map(|v| v.to_le_bytes()).collect(); + let json = format!( + r#"{{"type":"inspection_geometry","id":3,"plane":null,"meshes":[{{ + "positions":"{p}","normals":"{p}","indices":"{i}","edges":"","points":"", + "topology":{{"face_positions":"{p}","face_indices":"{i}", + "triangle_faces":"{f}","segment_edges":"","vertices":""}}, + "bbox":[[0,1,2],[3,4,5]]}}]}}"#, + p = b64(&positions), + i = b64(&indices), + f = b64(&1u32.to_le_bytes()), + ); + let Message::InspectionGeometry { id, meshes, plane } = serde_json::from_str(&json).unwrap() + else { + panic!("wrong message type"); + }; + assert_eq!(id, 3); + assert!(plane.is_none()); + assert_eq!(meshes[0].positions, vec![[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]); + assert_eq!(meshes[0].indices, vec![0, 1, 1]); + assert!(meshes[0].edges.is_empty()); + assert_eq!(meshes[0].topology.triangle_faces, vec![1]); +} + +#[test] +fn serializes_requests_with_command_tags() { + let request = Request::Debug { + action: DebugAction::StepIn, + breakpoints: vec![3], + module_breakpoints: [("/project/helper.py".into(), vec![7])].into(), + }; + assert_eq!( + serde_json::to_string(&request).unwrap(), + r#"{"cmd":"debug","action":"step_in","breakpoints":[3],"module_breakpoints":{"/project/helper.py":[7]}}"# + ); + assert_eq!( + serde_json::to_string(&Request::Shutdown).unwrap(), + r#"{"cmd":"shutdown"}"# + ); +} + +#[test] +fn hover_documentation_travels_as_describe_and_description() { + let request = Request::Describe { + id: 4, + source: "len(x)".into(), + line: 1, + column: 0, + path: None, + }; + assert_eq!( + serde_json::to_string(&request).unwrap(), + r#"{"cmd":"describe","id":4,"source":"len(x)","line":1,"column":0,"path":null}"# + ); + + let message: Message = serde_json::from_str( + r#"{"type":"description","id":4,"available":true, + "signatures":["len(obj: Sized, /) -> int"],"text":"Return the length."}"#, + ) + .unwrap(); + let Message::Description { id, documentation } = message else { + panic!("not a description: {message:?}"); + }; + assert_eq!(id, 4); + assert_eq!(documentation.signatures, ["len(obj: Sized, /) -> int"]); + assert_eq!(documentation.text, "Return the length."); + + // Nothing to say about the name. + let empty: Message = + serde_json::from_str(r#"{"type":"description","id":5,"available":false}"#).unwrap(); + assert!(matches!( + empty, + Message::Description { id: 5, documentation } if documentation == Documentation::default() + )); +} + +#[test] +fn source_navigation_uses_current_text_and_project_locations() { + let request = serde_json::to_value(Request::Navigate { + id: 7, + source: "value = make_part()".into(), + line: 1, + column: 14, + path: Some("/project/main.py".into()), + project_root: Some("/project".into()), + mode: NavigationMode::Definition, + }) + .unwrap(); + assert_eq!(request["cmd"], "navigate"); + assert_eq!(request["mode"], "definition"); + assert_eq!(request["source"], "value = make_part()"); + assert_eq!(request["project_root"], "/project"); + + let message: Message = serde_json::from_value(serde_json::json!({ + "type": "navigation", "id": 7, "mode": "definition", "available": true, + "locations": [{"name": "make_part", "kind": "function", "path": "/project/helper.py", + "line": 2, "column": 4}], "truncated": false + })) + .unwrap(); + let Message::Navigation { + locations, mode, .. + } = message + else { + panic!("expected navigation response"); + }; + assert_eq!(mode, NavigationMode::Definition); + assert_eq!(locations[0].line, 2); + assert_eq!(locations[0].path.as_deref(), Some("/project/helper.py")); +} + +#[test] +fn measurement_request_and_exact_response_share_topology_references() { + let request = Request::Measure { + id: 12, + selections: vec![TopologyReference { + key: "s1-n2".into(), + part: 0, + kind: TopologyKind::Vertex, + identifier: 3, + }], + objects: Vec::new(), + }; + let json = serde_json::to_value(request).unwrap(); + assert_eq!(json["cmd"], "measure"); + assert_eq!(json["selections"][0]["kind"], "vertex"); + assert_eq!(json["selections"][0]["identifier"], 3); + + let message: Message = serde_json::from_value(serde_json::json!({ + "type": "measurement", + "id": 12, + "identity": {"scope": "scene_entry", "persistent": false}, + "entities": [{ + "key": "s1-n2", "part": 0, "kind": "vertex", "identifier": 3, + "geometry_type": "vertex", "center": [3.0, 4.0, 0.0], + "position": [3.0, 4.0, 0.0], "length": null, "area": null, + "radius": null, "diameter": null + }], + "pair": null + })) + .unwrap(); + let Message::Measurement(measurement) = message else { + panic!("expected measurement"); + }; + assert_eq!(measurement.entities[0].position, Some([3.0, 4.0, 0.0])); + assert!(!measurement.identity.persistent); +} + +#[test] +fn selector_preview_transfers_exact_topology_ids() { + let request = serde_json::to_value(Request::SelectorPreview { + id: 9, + run_id: 4, + line: 7, + column: 18, + preferred_key: Some("n1".into()), + }) + .unwrap(); + assert_eq!(request["cmd"], "selector_preview"); + assert_eq!(request["run_id"], 4); + let message: Message = serde_json::from_value(serde_json::json!({ + "type": "selector_preview", "id": 9, "active": true, "count": 1, + "matches": [{"key":"n1","part":0,"kind":"face","identifier":6}], + "message": null + })) + .unwrap(); + let Message::SelectorPreview { matches, .. } = message else { + panic!("expected selector preview"); + }; + assert_eq!(matches[0].identifier, 6); +} + +#[test] +fn parses_errors_and_output() { + let message: Message = + serde_json::from_str(r#"{"type":"output","id":null,"stream":"stderr","text":"x"}"#) + .unwrap(); + assert!(matches!( + message, + Message::Output { + id: None, + stream: OutputStream::Stderr, + .. + } + )); +} + +#[test] +fn overlap_geometry_request_and_mesh_reply_round_trip() { + use crate::worker::protocol::InterferencePart; + let first = InterferencePart { + key: "n1".into(), + name: "plate".into(), + part: 0, + solid: 0, + }; + let request = Request::InterferenceGeometry { + id: 8, + first: first.clone(), + second: InterferencePart { + key: "n2".into(), + name: "pin".into(), + part: 0, + solid: 0, + }, + scene: SceneSettings { + linear_tolerance: 0.001, + angular_tolerance: 0.2, + merge_assemblies: false, + units: "millimeter".into(), + }, + }; + let json = serde_json::to_value(request).unwrap(); + assert_eq!(json["cmd"], "interference_geometry"); + assert_eq!(json["first"]["name"], "plate"); + let reply: Message = serde_json::from_value(serde_json::json!({ + "type": "interference_geometry", "id": 8, "mesh": {} + })) + .unwrap(); + assert!(matches!(reply, Message::InterferenceGeometry { id: 8, .. })); +} + +#[test] +fn serializes_run_request_with_worker_settings() { + let request = Request::Run { + id: 9, + script: "show_object(cq.Workplane())".into(), + path: None, + debug: false, + breakpoints: vec![4], + project_root: Some("/project".into()), + module_breakpoints: [("/project/helper.py".into(), vec![7])].into(), + settings: RunSettings { + reload_cq: false, + add_script_dir_to_path: true, + change_working_dir: true, + reload_imported_modules: true, + }, + scene: SceneSettings { + linear_tolerance: 0.001, + angular_tolerance: 0.2, + merge_assemblies: false, + units: "millimeter".into(), + }, + known_geometry: vec!["abc".into()], + profile: true, + }; + let json = serde_json::to_value(request).unwrap(); + assert_eq!(json["cmd"], "run"); + assert_eq!(json["id"], 9); + assert_eq!(json["path"], serde_json::Value::Null); + assert_eq!(json["project_root"], "/project"); + assert_eq!( + json["module_breakpoints"]["/project/helper.py"], + serde_json::json!([7]) + ); + assert_eq!(json["breakpoints"], serde_json::json!([4])); + assert_eq!(json["settings"]["add_script_dir_to_path"], true); + assert_eq!(json["scene"]["linear_tolerance"], 0.001); + assert_eq!(json["known_geometry"], serde_json::json!(["abc"])); + assert_eq!(json["profile"], true); +} + +#[test] +fn parses_worker_readiness_and_optional_fatal_detail() { + let ready: Message = serde_json::from_value(serde_json::json!({ + "type": "ready", "protocol": PROTOCOL_VERSION, + "python": "3.12", "cadquery": "2.8", "ocp": "7.9.3.1.1", + "executable": "python", + "completion": true, "pid": 123 + })) + .unwrap(); + let Message::Ready(info) = ready else { + panic!("expected ready"); + }; + assert_eq!(info.protocol, PROTOCOL_VERSION); + assert_eq!(info.ocp, "7.9.3.1.1"); + assert!(info.completion); + + let old_ready: Message = serde_json::from_value(serde_json::json!({ + "type": "ready", "protocol": PROTOCOL_VERSION, + "python": "3.10", "cadquery": "2.7", "executable": "python", + "completion": false + })) + .unwrap(); + let Message::Ready(old_info) = old_ready else { + panic!("expected ready"); + }; + assert_eq!(old_info.ocp, "unknown"); + + let fatal: Message = + serde_json::from_str(r#"{"type":"fatal","message":"no cadquery"}"#).unwrap(); + assert!(matches!(fatal, Message::Fatal { detail: None, .. })); +} + +#[test] +fn rejects_corrupt_base64_mesh_data() { + let base = serde_json::json!({ + "positions": "!!!", "normals": "", "indices": "", + "edges": "", "points": "", + "topology": { + "face_positions": "", "face_indices": "", "triangle_faces": "", + "segment_edges": "", "vertices": "" + }, + "bbox": [[0,0,0],[1,1,1]] + }); + assert!(serde_json::from_value::(base.clone()).is_err()); + + let mut short_vector = base.clone(); + short_vector["positions"] = b64(&[0; 8]).into(); + assert!(serde_json::from_value::(short_vector).is_err()); + + let mut short_index = base; + short_index["positions"] = "".into(); + short_index["indices"] = b64(&[0; 3]).into(); + assert!(serde_json::from_value::(short_index).is_err()); + + let mut short_topology = serde_json::json!({ + "positions": "", "normals": "", "indices": "", "edges": "", "points": "", + "topology": { + "face_positions": b64(&[0; 8]), "face_indices": "", "triangle_faces": "", + "segment_edges": "", "vertices": "" + }, + "bbox": [[0,0,0],[1,1,1]] + }); + assert!(serde_json::from_value::(short_topology.clone()).is_err()); + short_topology["topology"]["face_positions"] = "".into(); + short_topology["topology"]["triangle_faces"] = b64(&[0; 3]).into(); + assert!(serde_json::from_value::(short_topology).is_err()); +} + +#[test] +fn export_formats_have_distinct_extensions_and_wire_values() { + let expected = [ + (ExportFormat::Step, "step", "STEP"), + (ExportFormat::Stl, "stl", "STL"), + (ExportFormat::Brep, "brep", "BREP"), + (ExportFormat::ThreeMf, "3mf", "3MF"), + (ExportFormat::Gltf, "gltf", "glTF"), + (ExportFormat::Glb, "glb", "GLB"), + (ExportFormat::Amf, "amf", "AMF"), + (ExportFormat::Vrml, "vrml", "VRML"), + (ExportFormat::Vtkjs, "vtkjs", "VTK.js"), + (ExportFormat::Xbf, "xbf", "XBF"), + (ExportFormat::Svg, "svg", "SVG"), + (ExportFormat::Dxf, "dxf", "DXF"), + ]; + for (format, extension, label) in expected { + assert_eq!(format.extension(), extension); + assert_eq!(format.label(), label); + assert_eq!( + serde_json::to_string(&format).unwrap(), + format!("\"{extension}\"") + ); + } +} + +#[test] +fn selector_requests_and_replies_round_trip() { + let request = Request::Selector { + id: 3, + selections: vec![TopologyReference { + key: "s1-n2".into(), + part: 0, + kind: TopologyKind::Edge, + identifier: 7, + }], + }; + let json = serde_json::to_value(&request).unwrap(); + assert_eq!(json["cmd"], "selector"); + assert_eq!(json["selections"][0]["kind"], "edge"); + assert_eq!(json["selections"][0]["identifier"], 7); + + let reply = r#"{"type":"selector","id":3,"method":"edges","candidates":[ + {"expression":".edges(\"|Z and >Y\")","selector":"|Z and >Y", + "description":"parallel to Z, largest Y","index_based":false}, + {"expression":".edges()[6]","selector":null, + "description":"by position","index_based":true}]}"#; + let Ok(Message::Selector(reply)) = serde_json::from_str::(reply) else { + panic!("not a selector reply"); + }; + assert_eq!(reply.method, "edges"); + assert_eq!(reply.candidates[0].expression, r#".edges("|Z and >Y")"#); + assert!(reply.candidates[1].index_based); +} + +#[test] +fn console_commands_carry_the_selection_for_selected() { + let request = Request::Console { + id: 5, + source: "selected()".into(), + scene: SceneSettings { + linear_tolerance: 0.001, + angular_tolerance: 0.2, + merge_assemblies: false, + units: "millimeter".into(), + }, + known_geometry: Vec::new(), + selection: ConsoleSelection { + entities: vec![TopologyReference { + key: "s1-n1".into(), + part: 0, + kind: TopologyKind::Face, + identifier: 6, + }], + objects: vec!["s1-n1".into()], + }, + }; + let json = serde_json::to_value(&request).unwrap(); + assert_eq!(json["cmd"], "console"); + assert_eq!(json["selection"]["entities"][0]["kind"], "face"); + assert_eq!(json["selection"]["objects"][0], "s1-n1"); +} + +#[test] +fn scene_additions_name_their_request() { + let added = |text| match serde_json::from_str::(text) { + Ok(Message::SceneAdd { id, objects }) => (id, objects.len()), + other => panic!("not a scene addition: {other:?}"), + }; + assert_eq!( + added(r#"{"type":"scene_add","id":5,"objects":[]}"#), + (Some(5), 0) + ); + assert_eq!(added(r#"{"type":"scene_add","objects":[]}"#), (None, 0)); +} + +fn run_finished(extra: &str) -> RunFinished { + let text = format!( + r#"{{"type":"run_finished","id":4,"ok":true,"debug":false,"stopped":false, + "objects":[],"variables":[],"error":null,"duration":1.5{extra}}}"# + ); + match serde_json::from_str::(&text) { + Ok(Message::RunFinished(result)) => *result, + other => panic!("not a run result: {other:?}"), + } +} + +#[test] +fn cad_advice_is_optional_and_keeps_the_original_traceback() { + let error: ScriptError = serde_json::from_value(serde_json::json!({ + "type_name": "StdFail_NotDone", "message": "BRep_API: command not done", + "frames": [], "line": 2, "text": "original traceback", + "diagnostic": {"operation":"fillet", "receiver":"part", "line":2, + "hints":["Try a smaller radius"]} + })) + .unwrap(); + assert_eq!(error.text, "original traceback"); + assert_eq!(error.diagnostic.unwrap().operation, "fillet"); + let old: ScriptError = serde_json::from_value(serde_json::json!({ + "type_name": "ValueError", "message": "x", "frames": [], + "line": null, "text": "old traceback" + })) + .unwrap(); + assert!(old.diagnostic.is_none()); +} + +#[test] +fn run_results_carry_script_requirements() { + let result = run_finished( + r#","checks":[{"name":"wall","kind":"volume","ok":false, + "detail":"Volume 4; expected [5, 6]","line":12}]"#, + ); + assert_eq!(result.checks.len(), 1); + assert_eq!(result.checks[0].line, Some(12)); + assert!(!result.checks[0].ok); + assert!(run_finished("").checks.is_empty()); +} + +#[test] +fn run_results_carry_stage_timings() { + let result = run_finished( + r#","timings":{"script":1.5,"identify":0.01,"tessellate":0.25,"encode":0.02, + "meshed":1,"cached":2,"referenced":3,"mesh_bytes":2500000,"sent_at":1000.0}"#, + ); + let timings = result.timings.unwrap(); + assert_eq!( + (timings.meshed, timings.cached, timings.referenced), + (1, 2, 3) + ); + + let receipt = Receipt { + received_at: Some(UNIX_EPOCH + Duration::from_millis(1_000_040)), + parse: Duration::from_millis(6), + }; + let transfer = timings.transfer(&receipt).unwrap(); + assert!((transfer.as_secs_f64() - 0.04).abs() < 1e-6); + + let report = timings.report(&receipt, Duration::from_millis(2)); + for part in [ + "script 1.500", + "meshing 0.250", + "encoding 0.020", + "transfer 0.040", + "parsing 0.006", + "scene 0.002", + "1 meshed, 2 cached, 3 reused by reference, 2.50 MB sent", + ] { + assert!(report.contains(part), "{part:?} missing from {report:?}"); + } +} + +#[test] +fn transfer_time_is_unknown_when_the_clocks_disagree() { + let timings = RunTimings { + sent_at: 2000.0, + ..RunTimings::default() + }; + let early = Receipt { + received_at: Some(UNIX_EPOCH + Duration::from_secs(1000)), + parse: Duration::ZERO, + }; + assert_eq!(timings.transfer(&early), None); + assert_eq!(timings.transfer(&Receipt::default()), None); + assert!( + timings + .report(&early, Duration::ZERO) + .contains("transfer ?") + ); +} + +#[test] +fn run_results_without_timings_still_decode() { + assert_eq!(run_finished("").timings, None); +} + +#[test] +fn unknown_worker_message_is_rejected() { + assert!(serde_json::from_str::(r#"{"type":"unknown"}"#).is_err()); +} + +#[test] +fn nodes_and_stack_frames_carry_their_script_lines() { + let node: SceneNode = serde_json::from_str( + r#"{"key":"n1","name":"plate","kind":"Workplane","inspectable":true,"line":4, + "color":null,"alpha":null,"edge_color":null,"parts":[],"children":[]}"#, + ) + .unwrap(); + assert_eq!(node.line, Some(4)); + let older: SceneNode = serde_json::from_str( + r#"{"key":"n1","name":"plate","kind":"Workplane","inspectable":true, + "color":null,"alpha":null,"edge_color":null,"parts":[],"children":[]}"#, + ) + .unwrap(); + assert_eq!(older.line, None); + + let frame: StackFrame = serde_json::from_str( + r#"{"type":"Workplane","value":"origin (0, 0, 0)","line":2, + "items":[{"type":"Solid","value":"1 solid(s)","displayable":true,"line":2}]}"#, + ) + .unwrap(); + assert_eq!((frame.line, frame.items[0].line), (Some(2), Some(2))); +} + +#[test] +fn object_measurements_bounding_boxes_and_measurement_code_decode() { + let message: Message = serde_json::from_value(serde_json::json!({ + "type": "measurement", "id": 5, + "identity": {"scope": "scene_entry", "persistent": false}, + "entities": [], "pair": null, + "objects": [{ + "key": "s1-n1", "shape_type": "solid", "volume": 6.0, "area": 22.0, + "length": null, "center": [0.0, 0.0, 0.0], + "bounding_box": {"min": [-0.5, -1.0, -1.5], "max": [0.5, 1.0, 1.5], + "size": [1.0, 2.0, 3.0], "center": [0.0, 0.0, 0.0]}, + "solids": 1, "faces": 6, "edges": 12, "vertices": 8 + }], + "bounding_box": {"min": [-0.5, -1.0, -1.5], "max": [0.5, 1.0, 1.5], + "size": [1.0, 2.0, 3.0], "center": [0.0, 0.0, 0.0]} + })) + .unwrap(); + let Message::Measurement(result) = message else { + panic!("not a measurement"); + }; + assert_eq!(result.objects[0].volume, Some(6.0)); + assert_eq!(result.objects[0].faces, 6); + assert_eq!(result.bounding_box.unwrap().size, [1.0, 2.0, 3.0]); + + let request = Request::MeasurementCode { + id: 6, + selections: Vec::new(), + objects: vec!["s1-n1".into()], + }; + let json = serde_json::to_value(&request).unwrap(); + assert_eq!(json["cmd"], "measurement_code"); + assert_eq!(json["objects"][0], "s1-n1"); + + let message: Message = serde_json::from_str( + r#"{"type":"measurement_code","id":6,"code":"x = 1\n","verified":false, + "problem":"The Workplane is not a variable of the script"}"#, + ) + .unwrap(); + let Message::MeasurementCode { + verified, problem, .. + } = message + else { + panic!("not measurement code"); + }; + assert!(!verified); + assert!(problem.unwrap().contains("variable")); +} + +#[test] +fn meshing_progress_and_cancellation_cross_the_protocol() { + let message: Message = + serde_json::from_str(r#"{"type":"progress","id":7,"stage":"meshing","done":3,"total":40}"#) + .unwrap(); + let Message::Progress { + id, + stage, + done, + total, + } = message + else { + panic!("not progress: {message:?}"); + }; + assert_eq!((id, stage.as_str(), done, total), (7, "meshing", 3, 40)); + + assert_eq!( + serde_json::to_value(Request::Cancel { target: 7 }).unwrap(), + serde_json::json!({"cmd": "cancel", "target": 7}) + ); + assert!(run_finished(r#","cancelled":true"#).cancelled); + assert!(!run_finished("").cancelled, "older workers never cancel"); +} + +#[test] +fn stop_interrupts_cross_the_protocol() { + assert_eq!( + serde_json::to_value(Request::Interrupt { target: 4 }).unwrap(), + serde_json::json!({"cmd": "interrupt", "target": 4}) + ); + assert!(run_finished(r#","interrupted":true"#).interrupted); + assert!( + !run_finished("").interrupted, + "older workers never interrupt" + ); +} + +#[test] +fn the_worker_declares_the_same_protocol_version() { + let worker = include_str!("../../../worker/cq_worker/protocol.py"); + let declared = worker + .lines() + .find_map(|line| line.strip_prefix("PROTOCOL_VERSION = ")) + .expect("protocol.py declares PROTOCOL_VERSION"); + assert_eq!(declared.trim().parse::().unwrap(), PROTOCOL_VERSION); +} + +#[test] +fn profiles_cross_the_protocol() { + let result = run_finished( + r#","profile":{"lines":[{"line":2,"seconds":1.5,"hits":3}], + "operations":[{"line":2,"name":"Workplane.fillet","seconds":1.2,"calls":3}]}"#, + ); + let profile = result.profile.unwrap(); + assert_eq!( + profile.lines, + [LineTime { + file: None, + line: 2, + seconds: 1.5, + hits: 3 + }] + ); + assert_eq!(profile.operations[0].name, "Workplane.fillet"); + assert!(run_finished("").profile.is_none()); +} + +#[test] +fn update_checks_name_the_running_cq_editor() { + assert_eq!( + serde_json::to_value(Request::CheckUpdates { + id: 3, + editor: "0.8.0".into(), + cadquery: false, + }) + .unwrap(), + serde_json::json!({"cmd": "check_updates", "id": 3, "editor": "0.8.0", "cadquery": false}) + ); + // An older worker answers without CQ-editor's releases. + let reply: Message = + serde_json::from_str(r#"{"type":"updates","id":3,"current":"2.8","newer":[]}"#).unwrap(); + assert!(matches!(reply, Message::Updates { editor: None, .. })); +} + +fn png(width: u32, height: u32) -> String { + let pixels = + image::RgbaImage::from_fn(width, height, |x, _| image::Rgba([x as u8, 128, 255, 255])); + let mut bytes = std::io::Cursor::new(Vec::new()); + pixels + .write_to(&mut bytes, image::ImageFormat::Png) + .unwrap(); + b64(&bytes.into_inner()) +} + +fn jpeg(width: u32, height: u32) -> String { + let pixels = image::RgbImage::from_pixel(width, height, image::Rgb([32, 64, 128])); + let mut bytes = std::io::Cursor::new(Vec::new()); + pixels + .write_to(&mut bytes, image::ImageFormat::Jpeg) + .unwrap(); + b64(&bytes.into_inner()) +} + +fn display(image: &str) -> DisplayOutput { + let line = format!(r#"{{"type":"display","id":4,"text":"figure","image":{image}}}"#); + match serde_json::from_str(&line).unwrap() { + Message::Display(output) => output, + other => panic!("not a display: {other:?}"), + } +} + +#[test] +fn console_images_are_decoded_when_they_arrive() { + let output = display(&format!(r#"{{"format":"png","data":"{}"}}"#, png(2, 1))); + assert_eq!(output.id, 4); + assert_eq!(output.text, "figure"); + let image = output.image.unwrap(); + assert_eq!(image.size, [2, 1]); + assert_eq!(image.rgba, [0, 128, 255, 255, 1, 128, 255, 255]); + + let text_only = display("null"); + assert!(text_only.image.is_none()); + assert_eq!(text_only.text, "figure"); + + let jpeg = display(&format!(r#"{{"format":"jpeg","data":"{}"}}"#, jpeg(3, 2))); + assert_eq!(jpeg.image.unwrap().size, [3, 2]); + + let missing_id = r#"{"type":"display","text":"orphan","image":null}"#; + assert!(serde_json::from_str::(missing_id).is_err()); +} + +#[test] +fn console_images_that_cannot_be_trusted_become_a_note() { + let cases = [ + ( + r#"{"format":"svg","data":"PHN2Zy8+"}"#.to_owned(), + "svg is not shown", + ), + ( + r#"{"format":"png","data":"not base64!"}"#.to_owned(), + "bad data", + ), + ( + format!(r#"{{"format":"jpeg","data":"{}"}}"#, png(1, 1)), + "image not shown", + ), + ( + format!( + r#"{{"format":"png","data":"{}"}}"#, + png(MAX_DISPLAY_SIDE + 1, 1) + ), + "image not shown", + ), + ( + format!( + r#"{{"format":"png","data":"{}"}}"#, + b64(&vec![0; MAX_DISPLAY_IMAGE_BYTES + 1]) + ), + "too large", + ), + ]; + for (image, note) in cases { + let output = display(&image); + assert!(output.image.is_none(), "{image:.60}"); + assert!(output.text.starts_with("figure\n[image not shown: ")); + assert!(output.text.contains(note), "{}", output.text); + } + + let without_text = + r#"{"type":"display","id":4,"text":"","image":{"format":"svg","data":"PHN2Zy8+"}}"#; + let Message::Display(output) = serde_json::from_str(without_text).unwrap() else { + panic!("not a display message"); + }; + assert_eq!(output.text, "[image not shown: svg is not shown]"); +} diff --git a/tests/rust/protocol/test_worker_io.rs b/tests/rust/protocol/test_worker_io.rs new file mode 100644 index 000000000..8cd6241cd --- /dev/null +++ b/tests/rust/protocol/test_worker_io.rs @@ -0,0 +1,183 @@ +use super::*; +use std::io::{BufReader, Cursor}; + +#[test] +fn shared_golden_messages_cross_the_python_rust_boundary() { + let fixtures: serde_json::Value = + serde_json::from_str(include_str!("../../fixtures/protocol/messages.json")).unwrap(); + for case in fixtures["valid"].as_array().unwrap() { + let raw = serde_json::to_vec(&case["message"]).unwrap(); + assert!(raw.len() <= worker_message_limit(&raw), "{}", case["name"]); + let message: Message = serde_json::from_slice(&raw).unwrap(); + match case["name"].as_str().unwrap() { + "ready" => assert!( + matches!(message, Message::Ready(info) if info.protocol == protocol::PROTOCOL_VERSION) + ), + "binary_part" => assert!( + matches!(message, Message::RunPart { part, .. } if part.mesh.positions.len() == 3 && part.mesh.indices == [0, 1, 2]) + ), + "referenced_part" => assert!( + matches!(message, Message::RunPart { part, .. } if part.mesh.id == "triangle-geometry" && part.mesh.positions.is_empty()) + ), + "finished_scene" => assert!( + matches!(message, Message::RunFinished(result) if result.objects.as_ref().unwrap()[0].parts[0].mesh.id == "triangle-geometry") + ), + other => panic!("Unknown shared fixture: {other}"), + } + } + + for case in fixtures["invalid"].as_array().unwrap() { + assert!( + serde_json::from_str::(case["wire"].as_str().unwrap()).is_err(), + "{}", + case["name"] + ); + } + let oversized = &fixtures["oversized_control"]; + let payload = format!( + r#"{{"type":"output","id":7,"stream":"stdout","text":"{}"}}"#, + "x".repeat(oversized["repeat"].as_u64().unwrap() as usize) + ); + assert_eq!( + worker_message_limit(payload.as_bytes()), + MAX_CONTROL_MESSAGE_BYTES + ); + let mut reader = Cursor::new(payload.into_bytes()); + assert!(matches!( + read_limited_line(&mut reader, MAX_CONTROL_MESSAGE_BYTES).unwrap(), + LimitedLine::TooLong(_) + )); +} + +#[test] +fn limited_line_reader_caps_memory_and_resumes_at_the_next_line() { + let input = Cursor::new(b"123456\nok\nlast".to_vec()); + let mut reader = BufReader::with_capacity(3, input); + + assert_eq!( + read_limited_line(&mut reader, 4).unwrap(), + LimitedLine::TooLong(b"1234".to_vec()) + ); + assert_eq!( + read_limited_line(&mut reader, 4).unwrap(), + LimitedLine::Line(b"ok".to_vec()) + ); + assert_eq!( + read_limited_line(&mut reader, 4).unwrap(), + LimitedLine::Line(b"last".to_vec()) + ); + assert_eq!(read_limited_line(&mut reader, 4).unwrap(), LimitedLine::Eof); +} + +#[test] +fn exact_line_limit_is_accepted() { + let mut reader = Cursor::new(b"1234\n".to_vec()); + assert_eq!( + read_limited_line(&mut reader, 4).unwrap(), + LimitedLine::Line(b"1234".to_vec()) + ); +} + +#[test] +fn image_and_mesh_messages_have_separate_larger_limits() { + let control = br#"{"type":"output","text":"hello"}"#; + let display = format!( + r#"{{"type":"display","image":{{"data":"{}"}}}}"#, + "x".repeat(MAX_CONTROL_MESSAGE_BYTES) + ); + let run = format!( + r#"{{"id":1,"type":"run_finished","padding":"{}"}}"#, + "x".repeat(MAX_CONTROL_MESSAGE_BYTES) + ); + let inspection = format!( + r#"{{"type":"inspection_geometry","padding":"{}"}}"#, + "x".repeat(MAX_CONTROL_MESSAGE_BYTES) + ); + + assert_eq!(worker_message_limit(control), MAX_CONTROL_MESSAGE_BYTES); + assert_eq!( + worker_message_limit(display.as_bytes()), + MAX_DISPLAY_MESSAGE_BYTES + ); + assert_eq!(worker_message_limit(run.as_bytes()), MAX_MESH_MESSAGE_BYTES); + assert_eq!( + worker_message_limit(inspection.as_bytes()), + MAX_MESH_MESSAGE_BYTES + ); +} + +#[test] +fn a_large_unknown_or_malformed_message_keeps_the_control_limit() { + let unknown = format!( + r#"{{"type":"future","data":"{}"}}"#, + "x".repeat(2 * 1024 * 1024) + ); + let malformed = vec![b'x'; MAX_CONTROL_MESSAGE_BYTES + 1]; + + assert_eq!( + worker_message_limit(unknown.as_bytes()), + MAX_CONTROL_MESSAGE_BYTES + ); + assert!(unknown.len() > worker_message_limit(unknown.as_bytes())); + assert_eq!(worker_message_limit(&malformed), MAX_CONTROL_MESSAGE_BYTES); + + let deceptive_output = format!( + r#"{{"type":"output","text":"\"type\":\"run_finished\"{}"}}"#, + "x".repeat(MAX_CONTROL_MESSAGE_BYTES) + ); + assert_eq!( + worker_message_limit(deceptive_output.as_bytes()), + MAX_CONTROL_MESSAGE_BYTES + ); +} + +#[test] +fn an_unreadable_message_is_not_a_failed_start() { + let mut worker = Worker::new(egui::Context::default()); + worker.generation = 1; + let ready: Message = serde_json::from_str( + r#"{"type":"ready","protocol":7,"python":"3.12","cadquery":"2.8.0", + "ocp":"7.9","executable":"python","completion":true,"pid":1}"#, + ) + .unwrap(); + worker.events_tx.send((1, Event::Message(ready))).unwrap(); + worker.poll(); + assert!(worker.is_ready()); + + let message = oversized_message(MAX_MESH_MESSAGE_BYTES + 1, MAX_MESH_MESSAGE_BYTES); + worker + .events_tx + .send((1, Event::ProtocolError(message.clone()))) + .unwrap(); + let events = worker.poll(); + assert!(matches!(&events[..], [Event::ProtocolError(m)] if *m == message)); + // CadQuery is not said to be missing: the app restarts the worker. + assert!(worker.is_ready()); + assert_eq!(worker.problem(), None); + assert!(message.contains("too large to transfer"), "{message}"); + assert!(message.contains("Deviation"), "{message}"); + assert!(message.contains("512.0 MiB, over its 512 MiB"), "{message}"); + + let control = oversized_message(3 * 1024 * 1024, MAX_CONTROL_MESSAGE_BYTES); + assert!(!control.contains("Deviation"), "{control}"); +} + +#[test] +fn a_failed_start_says_whether_python_or_cadquery_is_missing() { + // The Microsoft Store placeholder for python.exe exits with 9009. + let expected = if cfg!(windows) { + Problem::NoPython + } else { + Problem::Exited + }; + assert_eq!(exit_problem(Some(9009)), expected); + assert_eq!(exit_problem(Some(1)), Problem::Exited); + assert_eq!(exit_problem(None), Problem::Exited); + + // Only a failed worker has a problem. + let mut worker = Worker::new(egui::Context::default()); + worker.problem = Some(Problem::NoCadQuery); + assert_eq!(worker.problem(), None); + worker.status = Status::Failed("Cannot load CadQuery".into()); + assert_eq!(worker.problem(), Some(Problem::NoCadQuery)); +} diff --git a/tests/rust/scene/test_scene.rs b/tests/rust/scene/test_scene.rs new file mode 100644 index 000000000..1f8190a30 --- /dev/null +++ b/tests/rust/scene/test_scene.rs @@ -0,0 +1,1034 @@ +use super::*; + +fn node(key: &str, name: &str, children: Vec) -> SceneNode { + SceneNode { + key: key.into(), + name: name.into(), + kind: "Workplane".into(), + inspectable: false, + parts: vec![Part { + mesh: Arc::new(Mesh::lines(vec![[0.0; 3], [1.0, 2.0, 3.0]])), + transform: Mat4::IDENTITY, + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + render_mesh: None, + }], + children, + visible: true, + color: None, + alpha: None, + edge_color: None, + finish: None, + overrides: Overrides::default(), + line: None, + script: None, + } +} + +fn scene() -> Scene { + let mut scene = Scene::default(); + scene.append( + vec![ + node( + "a", + "assy", + vec![node("a1", "plate", vec![]), node("a2", "pin", vec![])], + ), + node("b", "box", vec![]), + ], + None, + ); + scene +} + +#[test] +fn hiding_a_parent_hides_the_subtree() { + let mut scene = scene(); + scene.set_visible("a", false); + let visible: Vec<_> = scene + .visible_nodes() + .iter() + .map(|n| n.key.as_str()) + .collect(); + assert_eq!(visible, ["b"]); +} + +#[test] +fn selection_roots_skip_nested_selections() { + let mut scene = scene(); + scene.select_only("a2"); + scene.toggle_selected("a"); + scene.toggle_selected("b"); + assert_eq!(scene.selected_roots(), ["a", "b"]); + assert_eq!(scene.selected_top_level(), ["a", "b"]); + assert_eq!(scene.current().unwrap().key, "b"); +} + +#[test] +fn properties_survive_a_reload_by_name() { + let mut scene = scene(); + scene.set_visible("a1", false); + scene.find_mut("b").unwrap().overrides.color = Some([1.0, 0.0, 0.0]); + let preserved = scene.snapshot_properties(); + + let removed = scene.replace( + vec![ + node("x", "assy", vec![node("x1", "plate", vec![])]), + node("y", "box", vec![]), + ], + Some(&preserved), + ); + assert_eq!(removed, ["a", "b"]); + assert!(!scene.find("x1").unwrap().visible); + assert_eq!( + scene.find("y").unwrap().overrides.color, + Some([1.0, 0.0, 0.0]) + ); +} + +#[test] +fn colors_resolve_in_priority_order() { + let mut n = node("n", "n", vec![]); + let default = [0.5; 3]; + assert_eq!(n.part_color(&n.parts[0], default), (default, 1.0)); + n.color = Some([0.0, 0.0, 1.0]); + n.alpha = Some(0.5); + assert_eq!(n.part_color(&n.parts[0], default), ([0.0, 0.0, 1.0], 0.5)); + n.overrides.color = Some([1.0, 0.0, 0.0]); + assert_eq!(n.part_color(&n.parts[0], default).0, [1.0, 0.0, 0.0]); +} + +#[test] +fn a_material_without_a_color_has_its_own() { + use crate::settings::Finish; + let mut n = node("n", "n", vec![]); + let default = [0.5; 3]; + assert_eq!(n.finish(), Finish::Default); + + // The script's material, then the Objects panel's. + n.finish = Some(Finish::Aluminum); + assert_eq!(n.finish(), Finish::Aluminum); + let aluminum = Finish::Aluminum.natural_color().unwrap(); + assert_eq!(n.part_color(&n.parts[0], default).0, aluminum); + n.overrides.finish = Some(Finish::MattePlastic); + assert_eq!(n.finish(), Finish::MattePlastic); + assert_eq!( + n.part_color(&n.parts[0], default).0, + default, + "plastics take any color" + ); + + // A color of the object's own wins over the material's. + n.overrides.finish = Some(Finish::Wood); + n.color = Some([0.0, 0.0, 1.0]); + assert_eq!(n.part_color(&n.parts[0], default).0, [0.0, 0.0, 1.0]); +} + +#[test] +fn the_material_of_show_object_reaches_the_node() { + use crate::settings::Finish; + let message = |finish: Option<&str>| protocol::SceneNode { + finish: finish.map(str::to_owned), + ..worker_node("k", triangle_mesh("material"), Mat4::IDENTITY) + }; + let mut library = MeshLibrary::default(); + let decode = |library: &mut MeshLibrary, finish| { + SceneNode::from_message(message(finish), library, None) + .unwrap() + .finish + }; + assert_eq!( + decode(&mut library, Some("brushed_steel")), + Some(Finish::BrushedSteel) + ); + assert_eq!(decode(&mut library, None), None); + assert_eq!( + decode(&mut library, Some("unobtainium")), + None, + "unknown: plain" + ); + for finish in Finish::ALL { + assert_eq!(Finish::from_name(finish.name()), Some(finish)); + } +} + +#[test] +fn bounding_boxes_include_all_points_and_ignore_empty_boxes() { + let box_a = Aabb::from_points([Vec3::new(-2.0, 1.0, 3.0), Vec3::new(4.0, 5.0, 7.0)]); + assert_eq!(Aabb::EMPTY.union(box_a), box_a); + assert_eq!(box_a.center(), Vec3::new(1.0, 3.0, 5.0)); + assert_eq!(box_a.size(), Vec3::new(6.0, 4.0, 4.0)); + assert!(Aabb::from_points([]).is_empty()); +} + +#[test] +fn mesh_bounds_include_edges_and_free_points() { + let mesh = Mesh::new( + vec![[0.0, 0.0, 0.0]], + vec![[0.0, 0.0, 1.0]], + vec![0, 0, 0], + vec![[-3.0, 1.0, 2.0]], + vec![[1.0, 4.0, 5.0]], + ); + assert_eq!(mesh.bounds.min, Vec3::new(-3.0, 0.0, 0.0)); + assert_eq!(mesh.bounds.max, Vec3::new(1.0, 4.0, 5.0)); + assert_eq!(mesh.triangle_count(), 1); +} + +#[test] +fn removing_top_level_nodes_prunes_nested_selection() { + let mut scene = scene(); + scene.select_only("a1"); + scene.toggle_selected("b"); + assert_eq!(scene.remove_top_level(&["a1".into()]), Vec::::new()); + assert_eq!(scene.remove_top_level(&["a".into()]), ["a"]); + assert_eq!(scene.selection, ["b"]); + assert_eq!(scene.top_level_keys(), ["b"]); +} + +#[test] +fn clearing_scene_returns_keys_and_removes_selection() { + let mut scene = scene(); + scene.select_only("a2"); + assert_eq!(scene.clear(), ["a", "b"]); + assert!(scene.is_empty()); + assert!(scene.selection.is_empty()); + assert!(scene.current().is_none()); +} + +#[test] +fn visibility_can_be_restored_for_an_entire_subtree() { + let mut scene = scene(); + scene.set_visible("a", false); + scene.set_visible("a", true); + assert_eq!( + scene + .visible_nodes() + .iter() + .map(|n| n.key.as_str()) + .collect::>(), + ["a", "a1", "a2", "b"] + ); +} + +#[test] +fn selection_bounds_include_children_and_overlay_affects_visible_bounds() { + let mut scene = scene(); + scene.select_only("a"); + let selected = scene.selection_bounds(); + assert_eq!(selected.max, Vec3::new(1.0, 2.0, 3.0)); + scene.overlay.meshes.push(Arc::new(Mesh::lines(vec![ + [20.0, 0.0, 0.0], + [21.0, 0.0, 0.0], + ]))); + assert_eq!(scene.visible_bounds().max.x, 21.0); +} + +#[test] +fn hidden_nodes_are_excluded_from_visible_bounds() { + let mut scene = scene(); + scene.set_visible("a", false); + scene.set_visible("b", false); + assert!(scene.visible_bounds().is_empty()); + scene.select_only("a"); + assert!(!scene.selection_bounds().is_empty()); +} + +#[test] +fn topology_selection_builds_and_clears_an_exact_highlight() { + let mut mesh = Mesh::new( + vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + vec![[0.0, 0.0, 1.0]; 3], + vec![0, 1, 2], + vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]], + Vec::new(), + ); + mesh.topology.face_positions = mesh.positions.clone(); + mesh.topology.face_indices = mesh.indices.clone(); + mesh.topology.triangle_faces = vec![4]; + mesh.topology.segment_edges = vec![7]; + mesh.topology.vertices = vec![[0.0, 0.0, 0.0]]; + + let mut part_node = node("n", "part", vec![]); + part_node.parts[0].mesh = Arc::new(mesh); + let mut scene = Scene::default(); + scene.append(vec![part_node], None); + scene.select_only("n"); + + let selection = TopologySelection { + node: "n".into(), + part: 0, + entity: TopologyEntity::Face(4), + position: Vec3::new(0.25, 0.25, 0.0), + }; + assert!(scene.select_topology(selection.clone(), false)); + assert_eq!(scene.topology_selections, vec![selection.clone()]); + assert_eq!(scene.topology_highlights()[0].mesh.triangle_count(), 1); + + let edge = TopologySelection { + entity: TopologyEntity::Edge(7), + ..selection + }; + assert!(scene.select_topology(edge.clone(), true)); + assert_eq!(scene.topology_selections.len(), 2); + assert_eq!(scene.current_topology(), Some(&edge)); + + // Ctrl-selecting the same topology toggles only that entity. + assert!(scene.select_topology(edge, true)); + assert_eq!(scene.topology_selections.len(), 1); + + scene.select_only("n"); + assert!(scene.topology_selections.is_empty()); + assert!(scene.topology_highlights().is_empty()); +} + +#[test] +fn selector_preview_highlights_without_changing_selection() { + let mut mesh = Mesh::new( + vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + vec![[0.0, 0.0, 1.0]; 3], + vec![0, 1, 2], + Vec::new(), + Vec::new(), + ); + mesh.topology.triangle_faces = vec![4]; + let mut part = node("n", "part", vec![]); + part.parts[0].mesh = Arc::new(mesh); + let mut scene = Scene::default(); + scene.append(vec![part], None); + scene.select_only("n"); + scene.set_selector_preview(&[protocol::TopologyReference { + key: "n".into(), + part: 0, + kind: protocol::TopologyKind::Face, + identifier: 4, + }]); + assert_eq!(scene.selector_preview_count(), 1); + assert_eq!(scene.placed_topology_highlights().len(), 1); + assert_eq!(scene.selected_roots(), ["n"]); + assert!(scene.topology_selections.is_empty()); + scene.clear(); + assert_eq!(scene.selector_preview_count(), 0); +} + +#[test] +fn ctrl_click_gathers_up_to_the_topology_selection_limit() { + // One triangle per face id, so each id has a highlight. + let faces = MAX_TOPOLOGY_SELECTIONS as u32 + 1; + let mut positions = Vec::new(); + let mut indices = Vec::new(); + for i in 0..faces { + let x = i as f32; + let start = positions.len() as u32; + positions.extend([[x, 0.0, 0.0], [x + 0.5, 0.0, 0.0], [x, 0.5, 0.0]]); + indices.extend([start, start + 1, start + 2]); + } + let normals = vec![[0.0, 0.0, 1.0]; positions.len()]; + let mut mesh = Mesh::new(positions, normals, indices, Vec::new(), Vec::new()); + mesh.topology.triangle_faces = (1..=faces).collect(); + let mut part_node = node("n", "part", vec![]); + part_node.parts[0].mesh = Arc::new(mesh); + let mut scene = Scene::default(); + scene.append(vec![part_node], None); + scene.select_only("n"); + + let face = |id| TopologySelection { + node: "n".into(), + part: 0, + entity: TopologyEntity::Face(id), + position: Vec3::ZERO, + }; + for id in 1..=faces { + assert!(scene.select_topology(face(id), id > 1)); + } + // The oldest made room for the newest. + assert_eq!(scene.topology_selections.len(), MAX_TOPOLOGY_SELECTIONS); + assert_eq!(scene.topology_selections[0].entity, TopologyEntity::Face(2)); + assert_eq!(scene.current_topology(), Some(&face(faces))); + assert_eq!(scene.topology_highlights().len(), MAX_TOPOLOGY_SELECTIONS); +} + +#[test] +fn face_highlights_use_display_triangles_without_separate_pick_triangles() { + let mut mesh = Mesh::new( + vec![ + [0.0, 0.0, 0.0], + [1.0, 0.0, 0.0], + [1.0, 1.0, 0.0], + [0.0, 1.0, 0.0], + ], + vec![[0.0, 0.0, 1.0]; 4], + vec![0, 1, 2, 0, 2, 3], + Vec::new(), + Vec::new(), + ); + mesh.topology.triangle_faces = vec![2, 5]; + + let highlight = mesh.topology_mesh(TopologyEntity::Face(5)).unwrap(); + assert_eq!(highlight.triangle_count(), 1); + assert_eq!( + highlight.positions, + [[0.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]] + ); + assert!(mesh.topology_mesh(TopologyEntity::Face(9)).is_none()); +} + +fn worker_node(key: &str, mesh: protocol::Mesh, transform: Mat4) -> protocol::SceneNode { + protocol::SceneNode { + key: key.into(), + name: key.into(), + kind: "Shape".into(), + inspectable: false, + line: None, + color: None, + alpha: None, + edge_color: None, + finish: None, + parts: vec![protocol::Part { + mesh, + transform: transform.to_cols_array(), + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + }], + children: Vec::new(), + } +} + +#[test] +fn content_addressed_mesh_references_reuse_cpu_geometry() { + let mut scene = Scene::default(); + let full = protocol::Mesh { + id: "same-geometry".into(), + positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + normals: vec![[0.0, 0.0, 1.0]; 3], + indices: vec![0, 1, 2], + bbox: Some([[0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]), + ..Default::default() + }; + let first = scene + .decode_nodes(None, vec![worker_node("first", full, Mat4::IDENTITY)]) + .unwrap(); + scene.append(first, None); + assert_eq!(scene.known_geometry(), ["same-geometry"]); + + let reference = protocol::Mesh { + id: "same-geometry".into(), + ..Default::default() + }; + let second = scene + .decode_nodes( + None, + vec![worker_node( + "second", + reference, + Mat4::from_translation(Vec3::X * 10.0), + )], + ) + .unwrap(); + assert!(Arc::ptr_eq( + &scene.nodes[0].parts[0].mesh, + &second[0].parts[0].mesh + )); + assert_eq!(second[0].own_bounds().min.x, 10.0); + assert_eq!(second[0].own_bounds().max.x, 11.0); +} + +#[test] +fn streamed_part_is_visible_before_finish_and_resolves_in_final_scene() { + let mut scene = Scene::default(); + let message = worker_node("part", triangle_mesh("streamed"), Mat4::IDENTITY); + scene + .add_preview_part(7, message.parts.into_iter().next().unwrap()) + .unwrap(); + assert_eq!(scene.preview_parts.len(), 1); + assert_eq!(scene.visible_bounds().max.x, 1.0); + + let nodes = scene + .decode_nodes( + Some(7), + vec![worker_node( + "part", + mesh_reference("streamed"), + Mat4::IDENTITY, + )], + ) + .unwrap(); + assert!(Arc::ptr_eq( + &scene.preview_parts[0].mesh, + &nodes[0].parts[0].mesh + )); + scene.clear_preview(); + scene.append(nodes, None); + scene.release_geometry(|_| false); + assert!(scene.preview_parts.is_empty()); + assert_eq!(scene.nodes[0].parts[0].mesh.indices, [0, 1, 2]); +} + +#[test] +fn face_colors_are_instance_local_and_preserve_picking_geometry() { + let mut scene = Scene::default(); + let mut first = worker_node("first", triangle_mesh("shared"), Mat4::IDENTITY); + first.parts[0].mesh.topology.triangle_faces = vec![1]; + first.parts[0].face_attributes = vec![protocol::FaceAttribute { + id: 1, + name: Some("painted".into()), + layer: Some("finish".into()), + color: Some([1.0, 0.0, 0.0]), + alpha: Some(1.0), + }]; + let nodes = scene.decode_nodes(None, vec![first]).unwrap(); + scene.append(nodes, None); + + let mut second = worker_node("second", mesh_reference("shared"), Mat4::IDENTITY); + second.parts[0].face_attributes = vec![protocol::FaceAttribute { + color: Some([0.0, 1.0, 0.0]), + ..scene.nodes[0].parts[0].face_attributes[0].clone() + }]; + let nodes = scene.decode_nodes(None, vec![second]).unwrap(); + assert!(Arc::ptr_eq( + &scene.nodes[0].parts[0].mesh, + &nodes[0].parts[0].mesh + )); + let first_color = scene.nodes[0].parts[0] + .render_mesh + .as_ref() + .unwrap() + .vertex_colors[0]; + let second_color = nodes[0].parts[0] + .render_mesh + .as_ref() + .unwrap() + .vertex_colors[0]; + assert_eq!(first_color, 0xff00_00ff); + assert_eq!(second_color, 0xff00_ff00); + assert_eq!(scene.nodes[0].parts[0].mesh.indices, vec![0, 1, 2]); +} + +#[test] +fn an_unknown_mesh_reference_is_rejected() { + let mut scene = Scene::default(); + let reference = protocol::Mesh { + id: "missing".into(), + ..Default::default() + }; + let error = scene + .decode_nodes(None, vec![worker_node("node", reference, Mat4::IDENTITY)]) + .unwrap_err(); + assert!(error.contains("missing")); +} + +/// A full one-triangle worker mesh of 84 bytes. +fn triangle_mesh(id: &str) -> protocol::Mesh { + protocol::Mesh { + id: id.into(), + positions: vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + normals: vec![[0.0, 0.0, 1.0]; 3], + indices: vec![0, 1, 2], + bbox: Some([[0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]), + ..Default::default() + } +} + +fn mesh_reference(id: &str) -> protocol::Mesh { + protocol::Mesh { + id: id.into(), + ..Default::default() + } +} + +/// Decodes a one-part node answering `request`. +fn decode_part( + scene: &mut Scene, + request: Option, + mesh: protocol::Mesh, +) -> Result, String> { + let mut nodes = scene.decode_nodes(request, vec![worker_node("n", mesh, Mat4::IDENTITY)])?; + Ok(nodes.remove(0).parts.remove(0).mesh) +} + +fn without_retention() -> Scene { + Scene { + meshes: MeshLibrary::with_budget(0), + ..Scene::default() + } +} + +#[test] +fn a_debugging_session_resolves_meshes_its_paused_views_dropped() { + // Without retention only the request's own pins can keep the mesh. + let mut scene = without_retention(); + let run = 7; + // Pause 1 shows `a`; the worker now treats it as known to the GUI. + let first = decode_part(&mut scene, Some(run), triangle_mesh("a")).unwrap(); + let nodes = scene + .decode_nodes( + Some(run), + vec![worker_node("a", mesh_reference("a"), Mat4::IDENTITY)], + ) + .unwrap(); + scene.replace(nodes, None); + drop(first); + // Pause 2, inside a function, shows nothing. + scene.replace(Vec::new(), None); + + // Pause 3 shows `a` again, as a reference. + let again = decode_part(&mut scene, Some(run), mesh_reference("a")) + .expect("a mesh sent earlier in the session stays available"); + assert_eq!(again.positions.len(), 3); + drop(again); + + // Once the request ends, the worker may no longer rely on it. + scene.release_geometry(|_| false); + assert!(scene.known_geometry().is_empty()); + assert!(decode_part(&mut scene, Some(8), mesh_reference("a")).is_err()); +} + +#[test] +fn advertised_geometry_survives_clearing_the_view_until_its_request_ends() { + let mut scene = without_retention(); + let shown = scene + .decode_nodes( + None, + vec![worker_node("a", triangle_mesh("a"), Mat4::IDENTITY)], + ) + .unwrap(); + scene.append(shown, None); + let known = scene.known_geometry(); + assert_eq!(known, ["a"]); + + // A debugging run clears the view right after sending its request. + scene.pin_geometry(3, &known); + scene.clear(); + assert!(decode_part(&mut scene, Some(3), mesh_reference("a")).is_ok()); + + scene.release_geometry(|request| request != 3); + assert!(scene.known_geometry().is_empty()); +} + +#[test] +fn recently_used_meshes_are_retained_within_the_byte_budget() { + // Room for two 84-byte meshes. + let mut scene = Scene { + meshes: MeshLibrary::with_budget(200), + ..Scene::default() + }; + let first = decode_part(&mut scene, Some(1), triangle_mesh("a")).unwrap(); + let first_id = first.id; + drop(first); + for (request, id) in [(2, "b"), (3, "c")] { + decode_part(&mut scene, Some(request), triangle_mesh(id)).unwrap(); + } + scene.release_geometry(|_| false); + + // Nothing is shown, yet the two newest meshes remain known. + assert_eq!(scene.known_geometry(), ["b", "c"]); + assert!(decode_part(&mut scene, None, mesh_reference("a")).is_err()); + + // Using `b` again makes `c` the oldest, so a new mesh evicts `c`. + decode_part(&mut scene, None, mesh_reference("b")).unwrap(); + decode_part(&mut scene, None, triangle_mesh("d")).unwrap(); + assert_eq!(scene.known_geometry(), ["b", "d"]); + + // A fresh copy of evicted geometry is a new mesh with its own buffers. + assert_ne!( + decode_part(&mut scene, None, triangle_mesh("a")) + .unwrap() + .id, + first_id + ); +} + +#[test] +fn a_full_mesh_for_held_geometry_keeps_the_existing_mesh_and_gpu_buffers() { + let mut scene = Scene::default(); + let first = decode_part(&mut scene, None, triangle_mesh("a")).unwrap(); + let resent = decode_part(&mut scene, None, triangle_mesh("a")).unwrap(); + assert!(Arc::ptr_eq(&first, &resent)); + // The renderer keys GPU buffers by this id. + assert_eq!(first.id, resent.id); +} + +#[test] +fn mesh_byte_size_counts_every_array() { + let mut mesh = Mesh::from(triangle_mesh("a")); + assert_eq!(mesh.byte_size(), 3 * 12 + 3 * 12 + 3 * 4); + mesh.topology.triangle_faces = vec![1]; + mesh.topology.vertices = vec![[0.0; 3]; 2]; + assert_eq!(mesh.byte_size(), 84 + 4 + 2 * 12); +} + +// -- exploded view and isolation --------------------------------------------- + +/// `node` with its part moved by `offset`. +fn placed(key: &str, name: &str, offset: Vec3, children: Vec) -> SceneNode { + let mut node = node(key, name, children); + node.parts[0].transform = Mat4::from_translation(offset); + node +} + +/// An assembly of two plates left and right of the origin, and a box. +fn assembly(prefix: &str, right: &str) -> Vec { + vec![ + SceneNode { + parts: Vec::new(), + ..node( + &format!("{prefix}a"), + "assy", + vec![ + placed( + &format!("{prefix}a1"), + "left", + Vec3::new(-10.0, 0.0, 0.0), + vec![], + ), + placed( + &format!("{prefix}a2"), + right, + Vec3::new(10.0, 0.0, 0.0), + vec![], + ), + ], + ) + }, + placed( + &format!("{prefix}b"), + "box", + Vec3::new(0.0, 0.0, 20.0), + vec![], + ), + ] +} + +fn assembly_scene() -> Scene { + let mut scene = Scene::default(); + scene.append(assembly("", "right"), None); + scene +} + +fn part_center(scene: &Scene, key: &str) -> Vec3 { + let part = &scene.find(key).unwrap().parts[0]; + part.mesh + .bounds + .transformed(scene.part_transform(part)) + .center() +} + +fn shown(scene: &Scene) -> Vec { + scene + .visible_nodes() + .iter() + .map(|node| node.key.clone()) + .collect() +} + +#[test] +fn exploding_moves_parts_away_from_the_centre_and_back() { + let mut scene = assembly_scene(); + let assembled = scene.visible_bounds(); + let center = assembled.center(); + let before = part_center(&scene, "a1"); + let revision = scene.pick_revision(); + + scene.set_explode(1.0); + assert_ne!(scene.pick_revision(), revision, "picking follows the parts"); + let after = part_center(&scene, "a1"); + // Twice as far from the centre, in the same direction. + assert!((after - center).abs_diff_eq((before - center) * 2.0, 1e-4)); + assert!(scene.visible_bounds().size().x > assembled.size().x * 1.5); + // The placements, which measurements and exports use, stay put. + assert_eq!( + scene.find("a1").unwrap().parts[0].transform, + Mat4::from_translation(Vec3::new(-10.0, 0.0, 0.0)) + ); + + scene.set_explode(100.0); + assert_eq!(scene.explode(), MAX_EXPLODE); + scene.set_explode(f32::NAN); + assert_eq!(scene.explode(), 0.0); + assert_eq!(part_center(&scene, "a1"), before); + assert_eq!(scene.visible_bounds(), assembled); +} + +#[test] +fn selection_bounds_and_highlights_follow_the_exploded_parts() { + let mut scene = assembly_scene(); + scene.set_explode(1.0); + scene.select_only("a2"); + assert!( + (scene.selection_bounds().center() - part_center(&scene, "a2")).length() < 1e-4, + "zoom to selection frames the part where it is shown" + ); + + let mut mesh = Mesh::new( + vec![[0.0; 3], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], + vec![[0.0, 0.0, 1.0]; 3], + vec![0, 1, 2], + Vec::new(), + Vec::new(), + ); + mesh.topology.triangle_faces = vec![1]; + scene.find_mut("a2").unwrap().parts[0].mesh = Arc::new(mesh); + assert!(scene.select_topology( + TopologySelection { + node: "a2".into(), + part: 0, + entity: TopologyEntity::Face(1), + position: Vec3::ZERO, + }, + false, + )); + let part = &scene.find("a2").unwrap().parts[0]; + let highlights = scene.placed_topology_highlights(); + assert_eq!(highlights.len(), 1); + assert_eq!(highlights[0].1, scene.part_transform(part)); + assert_ne!(highlights[0].1, part.transform); +} + +#[test] +fn isolating_shows_only_the_isolated_subtrees() { + let mut scene = assembly_scene(); + assert_eq!(shown(&scene), ["a", "a1", "a2", "b"]); + + scene.isolate(&["a2".to_owned()]); + assert!(scene.is_isolating()); + assert_eq!(scene.isolated_count(), 1); + assert_eq!(shown(&scene), ["a2"]); + let members = scene.isolation_members().unwrap(); + assert!(members.contains("a2") && !members.contains("a") && !members.contains("b")); + assert!( + (scene.visible_bounds().center() - part_center(&scene, "a2")).length() < 1e-4, + "fit frames what is isolated" + ); + + // A whole assembly, with a hidden part that stays hidden. + scene.set_visible("a1", false); + scene.isolate(&["a".to_owned()]); + assert_eq!(shown(&scene), ["a", "a2"]); + // Nothing known to isolate: no change. + scene.isolate(&["missing".to_owned()]); + assert_eq!(shown(&scene), ["a", "a2"]); + + scene.end_isolation(); + assert!(!scene.is_isolating() && scene.isolation_members().is_none()); + assert_eq!(shown(&scene), ["a", "a2", "b"], "visibility flags are kept"); + + scene.isolate(&["b".to_owned()]); + scene.show_all(); + assert!(!scene.is_isolating()); + assert_eq!(shown(&scene), ["a", "a1", "a2", "b"]); +} + +#[test] +fn isolation_survives_a_new_run_by_name_and_ends_without_a_match() { + let mut scene = assembly_scene(); + scene.isolate(&["a2".to_owned()]); + + // The next run has new keys for the same names. + scene.replace(assembly("2", "right"), None); + assert_eq!(shown(&scene), ["2a2"]); + + // Renamed: isolating nothing would show nothing, so the isolation ends. + scene.replace(assembly("3", "renamed"), None); + assert!(!scene.is_isolating()); + assert_eq!(shown(&scene), ["3a", "3a1", "3a2", "3b"]); +} + +// -- simplified meshes --------------------------------------------------------- + +/// A sphere of `rings` × `segments` quads, each corner with its own normal. +fn sphere(radius: f32, rings: u32, segments: u32) -> Mesh { + let mut positions = Vec::new(); + let mut normals = Vec::new(); + for ring in 0..=rings { + let polar = std::f32::consts::PI * ring as f32 / rings as f32; + for segment in 0..=segments { + let azimuth = std::f32::consts::TAU * segment as f32 / segments as f32; + let normal = Vec3::new( + polar.sin() * azimuth.cos(), + polar.sin() * azimuth.sin(), + polar.cos(), + ); + positions.push((normal * radius).to_array()); + normals.push(normal.to_array()); + } + } + let mut indices = Vec::new(); + let row = segments + 1; + for ring in 0..rings { + for segment in 0..segments { + let a = ring * row + segment; + let (b, c, d) = (a + 1, a + row, a + row + 1); + indices.extend([a, c, b, b, c, d]); + } + } + let edges = (0..segments) + .flat_map(|segment| { + let at = |s: u32| { + let azimuth = std::f32::consts::TAU * s as f32 / segments as f32; + [radius * azimuth.cos(), radius * azimuth.sin(), 0.0] + }; + [at(segment), at(segment + 1)] + }) + .collect(); + Mesh::new(positions, normals, indices, edges, vec![[0.0, 0.0, radius]]) +} + +#[test] +fn fine_meshes_get_a_coarser_copy_for_drawing_small() { + let fine = sphere(10.0, 120, 240); + let simplified = fine.simplified().expect("a fine mesh is simplified"); + assert!( + std::ptr::eq(simplified, fine.simplified().unwrap()), + "made once" + ); + assert!(simplified.triangle_count() * 4 < fine.triangle_count()); + assert!(simplified.triangle_count() > 100, "still a sphere"); + + // Within a cell of the original everywhere, with valid indices and + // unit or zero normals. + let cell = 20.0 / 40.0; + assert!( + (simplified.bounds.min - fine.bounds.min) + .abs() + .max_element() + <= cell + ); + assert!( + (simplified.bounds.max - fine.bounds.max) + .abs() + .max_element() + <= cell + ); + for position in &simplified.positions { + let radius = Vec3::from_array(*position).length(); + assert!((radius - 10.0).abs() <= cell, "{radius}"); + } + assert!( + simplified + .indices + .iter() + .all(|&index| (index as usize) < simplified.positions.len()) + ); + for normal in &simplified.normals { + let length = Vec3::from_array(*normal).length(); + assert!(length < 1e-6 || (length - 1.0).abs() < 1e-4); + } + assert!(!simplified.edges.is_empty() && simplified.edges.len() <= fine.edges.len()); + assert_eq!(simplified.points, fine.points); + // Only for drawing: no picking data. + assert!(simplified.topology.triangle_faces.is_empty()); + + // Small meshes are left alone. + assert!(sphere(10.0, 10, 20).simplified().is_none()); +} + +#[test] +fn the_coarser_copy_keeps_the_angle_of_each_edge() { + let mut fine = sphere(10.0, 120, 240); + // Every other segment smooth. + fine.segment_angles = (0..fine.edges.len() / 2) + .map(|i| if i % 2 == 0 { 0.0 } else { 90.0 }) + .collect(); + let simplified = fine.simplified().unwrap(); + assert_eq!(simplified.segment_angles.len() * 2, simplified.edges.len()); + assert!(simplified.segment_angles.contains(&0.0)); + assert!(simplified.segment_angles.contains(&90.0)); +} + +// -- edge angles and silhouettes --------------------------------------------- + +#[test] +fn segments_without_an_angle_count_as_outlines() { + let mut mesh = Mesh::lines(vec![[0.0; 3], [1.0, 0.0, 0.0], [0.0; 3], [0.0, 1.0, 0.0]]); + assert_eq!(mesh.segment_angle(1), OUTLINE_ANGLE); + mesh.segment_angles = vec![12.0, 90.0]; + assert_eq!((mesh.segment_angle(0), mesh.segment_angle(1)), (12.0, 90.0)); +} + +#[test] +fn worker_angles_are_kept_only_when_there_is_one_per_segment() { + let lines = |angles: Vec| { + Mesh::from(protocol::Mesh { + edges: vec![[0.0; 3], [1.0, 0.0, 0.0], [0.0; 3], [0.0, 1.0, 0.0]], + segment_angles: angles, + ..Default::default() + }) + }; + assert_eq!(lines(vec![0.0, 90.0]).segment_angles, [0.0, 90.0]); + assert!(lines(vec![0.0]).segment_angles.is_empty(), "damaged: none"); +} + +/// Four corners of the square [0, 1]² at height `z`, normals up. +fn square(z: f32) -> (Vec<[f32; 3]>, Vec<[f32; 3]>) { + let positions = vec![[0.0, 0.0, z], [1.0, 0.0, z], [1.0, 1.0, z], [0.0, 1.0, z]]; + (positions, vec![[0.0, 0.0, 1.0]; 4]) +} + +#[test] +fn a_flat_face_has_no_silhouette() { + let (positions, normals) = square(0.0); + let mesh = Mesh::new( + positions, + normals, + vec![0, 1, 2, 0, 2, 3], + Vec::new(), + Vec::new(), + ); + assert!( + mesh.silhouette_edges().is_empty(), + "the diagonal lies in the plane" + ); +} + +#[test] +fn silhouette_edges_join_faces_meshed_apart_at_a_crease() { + // A roof: two faces with vertices of their own, meeting along x = 0.5 + // at a right angle; corners at the same place are one corner. + let positions = vec![ + [0.0, 0.0, 0.0], + [0.5, 0.0, 0.5], + [0.5, 1.0, 0.5], + [0.0, 1.0, 0.0], + [0.5, 0.0, 0.5], + [1.0, 0.0, 0.0], + [1.0, 1.0, 0.0], + [0.5, 1.0, 0.5], + ]; + let left = Vec3::new(-1.0, 0.0, 1.0).normalize().to_array(); + let right = Vec3::new(1.0, 0.0, 1.0).normalize().to_array(); + let normals = vec![left, left, left, left, right, right, right, right]; + let indices = vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7]; + let mesh = Mesh::new(positions, normals, indices, Vec::new(), Vec::new()); + + let edges = mesh.silhouette_edges(); + assert_eq!(edges.len(), 1, "only the ridge: {edges:?}"); + let ridge = edges[0]; + let ends = [&ridge[0..3], &ridge[3..6]]; + assert!(ends.iter().all(|end| end[0] == 0.5 && end[2] == 0.5)); + let normals = [ + Vec3::from_slice(&ridge[6..9]), + Vec3::from_slice(&ridge[9..12]), + ]; + assert!((normals[0].dot(normals[1])).abs() < 1e-5, "a right angle"); + assert!(std::ptr::eq(edges, mesh.silhouette_edges()), "found once"); +} + +#[test] +fn a_smooth_surface_offers_its_mesh_edges_as_silhouettes() { + let sphere = sphere(1.0, 12, 24); + let edges = sphere.silhouette_edges(); + // Every edge between two quads' triangles across the curved surface, + // not the diagonals inside a flat quad. + assert!(edges.len() > 12 * 24); + for edge in edges { + let (a, b) = ( + Vec3::from_slice(&edge[6..9]), + Vec3::from_slice(&edge[9..12]), + ); + assert!(a.dot(b) < 0.999_99); + } +} diff --git a/tests/rust/viewer/test_camera.rs b/tests/rust/viewer/test_camera.rs new file mode 100644 index 000000000..d5b7e23b8 --- /dev/null +++ b/tests/rust/viewer/test_camera.rs @@ -0,0 +1,204 @@ +use super::*; + +fn close(a: Vec3, b: Vec3) -> bool { + (a - b).length() < 1e-4 +} + +fn looking(view: StandardView) -> Camera { + Camera { + rotation: view.rotation(), + ..Camera::default() + } +} + +#[test] +fn standard_views_look_where_expected() { + let mut camera = looking(StandardView::Top); + assert!(close(camera.forward(), Vec3::NEG_Z)); + assert!(close(camera.up(), Vec3::Y)); + assert!(close(camera.right(), Vec3::X)); + + camera.rotation = StandardView::Front.rotation(); + assert!(close(camera.forward(), Vec3::Y)); + assert!(close(camera.up(), Vec3::Z)); + + // From below, X still points right. + camera.rotation = StandardView::Bottom.rotation(); + assert!(close(camera.right(), Vec3::X)); +} + +#[test] +fn turntable_keeps_z_up() { + let mut camera = looking(StandardView::Front); + camera.orbit_turntable(Vec2::new(120.0, 0.0)); + assert!(close(camera.up(), Vec3::Z)); + camera.orbit_turntable(Vec2::new(0.0, 50.0)); + assert!(camera.up().z > 0.5); + assert!(camera.right().z.abs() < 1e-5); +} + +#[test] +fn orbit_keeps_a_picked_point_fixed_in_both_projections() { + for projection in [Projection::Orthographic, Projection::Perspective] { + let mut camera = Camera { + projection, + target: Vec3::new(4.0, -3.0, 7.0), + ..Camera::default() + }; + let pivot = camera.target + camera.right() * 5.0 + camera.up() * 2.0; + let before = project_with(camera.view_projection(1.4), pivot).unwrap(); + let original_extent = camera.extent; + camera.orbit_turntable_about(Vec2::new(38.0, -21.0), pivot); + let after = project_with(camera.view_projection(1.4), pivot).unwrap(); + assert!( + (before.truncate() - after.truncate()).length() < 1e-4, + "{projection:?}" + ); + assert_eq!(camera.extent, original_extent); + + let before = project_with(camera.view_projection(1.4), pivot).unwrap(); + camera.orbit_trackball_about(Vec2::new(-0.2, 0.1), Vec2::new(0.2, -0.1), pivot); + let after = project_with(camera.view_projection(1.4), pivot).unwrap(); + assert!( + (before.truncate() - after.truncate()).length() < 1e-4, + "{projection:?}" + ); + } +} + +#[test] +fn zoom_keeps_the_anchor_fixed() { + let mut camera = Camera::default(); + let anchor = Vec2::new(0.5, -0.25); + let aspect = 1.5; + let (before, _) = camera.ray(anchor, aspect); + let before_on_plane = + before + camera.forward() * (camera.target - before).dot(camera.forward()); + camera.zoom(0.5, anchor, aspect); + let (after, _) = camera.ray(anchor, aspect); + let after_on_plane = after + camera.forward() * (camera.target - after).dot(camera.forward()); + assert!(close(before_on_plane, after_on_plane)); + assert!((camera.extent - 10.0).abs() < 1e-4); +} + +#[test] +fn fit_centers_and_contains_the_box() { + let camera = looking(StandardView::Front); + let bounds = Aabb { + min: Vec3::new(10.0, -1.0, 0.0), + max: Vec3::new(30.0, 1.0, 5.0), + }; + let pose = camera.fit_pose(bounds, 2.0); + assert!(close(pose.target, Vec3::new(20.0, 0.0, 2.5))); + // 20 wide at aspect 2 needs a half height of at least 5. + assert!(pose.extent >= 5.0 && pose.extent < 6.0); +} + +#[test] +fn projection_round_trips_through_rays() { + for projection in Projection::ALL { + let camera = Camera { + projection, + ..Camera::default() + }; + let ndc = project_with(camera.view_projection(1.3), Vec3::new(3.0, 4.0, 5.0)).unwrap(); + assert!( + ndc.z >= 0.0 && ndc.z <= 1.0, + "{projection:?} depth {}", + ndc.z + ); + let (origin, dir) = camera.ray(ndc.truncate(), 1.3); + let to_point = Vec3::new(3.0, 4.0, 5.0) - origin; + let off_ray = to_point - dir * to_point.dot(dir); + assert!(off_ray.length() < 1e-3, "{projection:?}"); + } +} + +#[test] +fn animation_reaches_its_target() { + let from = Camera::default().pose(); + let to = Pose { + target: Vec3::ONE, + rotation: StandardView::Top.rotation(), + extent: 5.0, + }; + let animation = Animation::new(from, to, 0.0, 0.25); + let (mid, done) = animation.sample(0.125); + assert!(!done && mid.extent < 20.0 && mid.extent > 5.0); + let (end, done) = animation.sample(1.0); + assert!(done && close(end.target, Vec3::ONE)); +} + +fn stereo_camera(projection: Projection) -> Camera { + let mut camera = Camera { + projection, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::new(1.0, 2.0, 3.0), + rotation: StandardView::Iso.rotation(), + extent: 10.0, + }); + camera +} + +#[test] +fn the_eyes_of_the_stereo_pair_agree_on_the_target_plane() { + let camera = stereo_camera(Projection::Stereo); + let (left, right) = ( + camera.eye_position(Eye::Left), + camera.eye_position(Eye::Right), + ); + assert!(((left - right).length() - STEREO_SEPARATION * camera.distance()).abs() < 1e-3); + assert!(close((left + right) / 2.0, camera.eye())); + assert!((right - left).normalize().dot(camera.right()) > 0.999); + + let x = |eye: Eye, point: Vec3| { + project_with(camera.eye_view_projection(1.5, eye), point) + .unwrap() + .x + }; + // No parallax at the target, or anywhere on its plane. + let on_plane = camera.target + camera.right() * 4.0 + camera.up() * 2.0; + for point in [camera.target, on_plane] { + assert!((x(Eye::Left, point) - x(Eye::Right, point)).abs() < 1e-4); + assert!((x(Eye::Left, point) - x(Eye::Center, point)).abs() < 1e-4); + } + // Nearer points stand out of the screen (crossed disparity: the left + // eye sees them further right), farther ones sink behind it. + let near = camera.target - camera.forward() * camera.distance() * 0.5; + let far = camera.target + camera.forward() * camera.distance(); + assert!(x(Eye::Left, near) > x(Eye::Right, near) + 1e-3); + assert!(x(Eye::Left, far) < x(Eye::Right, far) - 1e-3); + // Stereo picks and culls from the centre. + assert_eq!(camera.mono_eye(), Eye::Center); + assert!(camera.is_perspective()); +} + +#[test] +fn mono_eye_projections_draw_and_pick_from_one_eye() { + for (projection, eye) in [ + (Projection::MonoLeftEye, Eye::Left), + (Projection::MonoRightEye, Eye::Right), + ] { + let camera = stereo_camera(projection); + assert_eq!(camera.mono_eye(), eye); + assert_eq!( + camera.view_projection(1.5), + camera.eye_view_projection(1.5, eye) + ); + // A pick ray leaves the eye and meets what the eye draws there. + let ndc = Vec2::new(0.3, -0.2); + let (origin, direction) = camera.ray(ndc, 1.5); + assert!(close(origin, camera.eye_position(eye))); + let point = origin + direction * camera.distance() * 1.7; + let projected = project_with(camera.view_projection(1.5), point).unwrap(); + assert!( + (projected.truncate() - ndc).length() < 1e-4, + "{projected:?}" + ); + } + let orthographic = stereo_camera(Projection::Orthographic); + assert_eq!(orthographic.mono_eye(), Eye::Center); + assert!(!orthographic.is_perspective()); +} diff --git a/tests/rust/viewer/test_capture.rs b/tests/rust/viewer/test_capture.rs new file mode 100644 index 000000000..c97700cc0 --- /dev/null +++ b/tests/rust/viewer/test_capture.rs @@ -0,0 +1,229 @@ +use super::*; +use crate::viewer::camera::StandardView; +use glam::Vec3; + +fn scratch_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("cq-editor-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn image_sizes_follow_the_view_and_stay_within_the_limit() { + let view = [800, 600]; + let at = |scale| CaptureOptions { + scale, + ..CaptureOptions::default() + }; + assert_eq!(at(1).image_size(view), [800, 600]); + assert_eq!(at(4).image_size(view), [3200, 2400]); + assert_eq!(at(4).pixel_scale(view), 4.0); + + let custom = CaptureOptions { + size: Some([1920, 1080]), + ..CaptureOptions::default() + }; + assert_eq!(custom.image_size(view), [1920, 1080]); + assert_eq!(custom.pixel_scale(view), 1.8, "set by the heights"); + + // Too large: both sides shrink together. + let huge = at(16).image_size([3000, 1500]); + assert_eq!(huge, [MAX_IMAGE_SIDE, MAX_IMAGE_SIDE / 2]); + let degenerate = CaptureOptions { + size: Some([0, 20_000]), + ..CaptureOptions::default() + }; + assert_eq!(degenerate.image_size(view), [1, MAX_IMAGE_SIDE]); +} + +#[test] +fn transparent_pixels_get_straight_alpha_in_srgb() { + let mut pixels = vec![ + 0, 0, 0, 0, // background + 200, 100, 50, 255, // opaque + 0, 0, 0, 128, // half covered by black + // White at 50% coverage over transparent black, premultiplied in + // linear space: 0.5 linear is 188 in sRGB. + 188, 188, 188, 128, + ]; + unpremultiply(&mut pixels); + assert_eq!(&pixels[..12], [0, 0, 0, 0, 200, 100, 50, 255, 0, 0, 0, 128]); + assert!( + pixels[12..15].iter().all(|&c| c >= 253), + "white again: {:?}", + &pixels[12..] + ); + assert_eq!(pixels[15], 128); +} + +#[test] +fn the_turntable_turns_the_camera_once_around_the_vertical_axis() { + let start = Pose { + target: Vec3::new(1.0, 2.0, 3.0), + rotation: StandardView::Front.rotation(), + extent: 5.0, + }; + let back = |pose: Pose| pose.rotation * Vec3::Z; + assert_eq!(turntable_pose(start, 0, 8, false), start); + + // A quarter turn: same target, distance and height, eye 90° around Z. + for clockwise in [false, true] { + let quarter = turntable_pose(start, 2, 8, clockwise); + assert_eq!(quarter.target, start.target); + assert_eq!(quarter.extent, start.extent); + let (from, to) = (back(start), back(quarter)); + assert!((from.z - to.z).abs() < 1e-5, "the eye stays at its height"); + assert!(from.dot(to).abs() < 1e-5, "a right angle"); + // Seen from above, the camera goes counterclockwise when the model + // turns clockwise. + let turn = from.cross(to).z; + assert_eq!(turn > 0.0, clockwise); + } + // The last frame stops one step short of the first. + let last = turntable_pose(start, 7, 8, false); + assert!(back(last).angle_between(back(start)) > 0.7); +} + +#[test] +fn frames_are_numbered_after_the_chosen_name() { + assert_eq!( + frame_path(Path::new("out/spin.png"), 0), + Path::new("out/spin_0001.png") + ); + assert_eq!( + frame_path(Path::new("spin.png"), 71), + Path::new("spin_0072.png") + ); +} + +fn small_export(path: PathBuf, format: AnimationFormat, transparent: bool) -> TurntableExport { + TurntableExport::start( + path, + CaptureOptions { + transparent, + ..CaptureOptions::default() + }, + TurntableOptions { + frames: 3, + frames_per_second: 12, + clockwise: false, + format, + }, + Pose { + target: Vec3::ZERO, + rotation: StandardView::Iso.rotation(), + extent: 1.0, + }, + [4, 2], + ) + .unwrap() +} + +#[test] +fn an_animated_png_holds_every_frame_and_loops() { + let dir = scratch_dir("apng"); + let path = dir.join("spin.png"); + let mut export = small_export(path.clone(), AnimationFormat::AnimatedPng, true); + assert_eq!(export.size(), [4, 2]); + for frame in 0..3u8 { + assert_eq!(export.progress(), (u32::from(frame), 3)); + let done = export + .write_frame([frame * 80, 0, 0, 255].repeat(8)) + .unwrap(); + assert_eq!(done, frame == 2); + } + assert!(export.finish().unwrap().contains("3 frames")); + + let decoder = png::Decoder::new(std::io::BufReader::new(File::open(&path).unwrap())); + let mut reader = decoder.read_info().unwrap(); + let control = reader.info().animation_control.unwrap(); + assert_eq!((control.num_frames, control.num_plays), (3, 0)); + let mut buffer = vec![0; reader.output_buffer_size().unwrap()]; + let mut reds = Vec::new(); + for _ in 0..3 { + reader.next_frame(&mut buffer).unwrap(); + reds.push(buffer[0]); + let frame = reader.info().frame_control.unwrap(); + assert_eq!((frame.delay_num, frame.delay_den), (1, 12)); + } + assert_eq!(reds, [0, 80, 160]); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn png_files_are_written_per_frame_and_a_cancel_removes_them() { + let dir = scratch_dir("frames"); + let path = dir.join("spin.png"); + let mut export = small_export(path.clone(), AnimationFormat::PngFiles, false); + for _ in 0..3 { + export.write_frame([10, 20, 30, 255].repeat(8)).unwrap(); + } + assert!(export.finish().unwrap().contains("spin_0001.png")); + for index in 0..3 { + let image = image::open(frame_path(&path, index)).unwrap().to_rgba8(); + assert_eq!(image.dimensions(), (4, 2)); + assert_eq!(image.get_pixel(0, 0).0, [10, 20, 30, 255]); + } + + // Cancelled half-way: nothing is left behind, in either format. + let cancelled = dir.join("cancelled.png"); + let mut export = small_export(cancelled.clone(), AnimationFormat::PngFiles, false); + export.write_frame(vec![0; 32]).unwrap(); + assert!(frame_path(&cancelled, 0).exists()); + export.cancel(); + assert!(!frame_path(&cancelled, 0).exists()); + let mut export = small_export(cancelled.clone(), AnimationFormat::AnimatedPng, false); + export.write_frame(vec![0; 32]).unwrap(); + export.cancel(); + assert!(!cancelled.exists()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn a_screenshot_does_not_interrupt_a_turntable_export() { + let dir = scratch_dir("busy"); + let mut viewer = crate::viewer::Viewer::default(); + let turntable = TurntableOptions { + frames: 4, + ..TurntableOptions::default() + }; + let path = dir.join("spin.png"); + viewer + .start_turntable(path.clone(), CaptureOptions::default(), turntable) + .unwrap(); + assert_eq!(viewer.turntable_progress(), Some((0, 4))); + assert!(!viewer.request_image(dir.join("shot.png"), CaptureOptions::default())); + assert_eq!(viewer.turntable_progress(), Some((0, 4))); + viewer.cancel_turntable(); + assert_eq!(viewer.turntable_progress(), None); + assert!(!path.exists(), "the partial animation is deleted"); + assert!(viewer.request_image(dir.join("shot.png"), CaptureOptions::default())); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn resolution_presets_and_clipboard_preparation_preserve_dimensions_and_aspect_ratio() { + assert_eq!(ResolutionPreset::Hd.size(), [1280, 720]); + assert_eq!(ResolutionPreset::FullHd.size(), [1920, 1080]); + assert_eq!(ResolutionPreset::Qhd.size(), [2560, 1440]); + assert_eq!(ResolutionPreset::Uhd4k.size(), [3840, 2160]); + assert_eq!(ResolutionPreset::Square.size(), [1080, 1080]); + assert_eq!( + ResolutionPreset::from_size([1920, 1080]), + Some(ResolutionPreset::FullHd) + ); + assert_eq!(aspect_ratio_label([1920, 1080]), "16:9"); + assert_eq!(aspect_ratio_label([1080, 1080]), "1:1"); + + let image = prepare_clipboard_image([2, 1], vec![188, 188, 188, 128, 10, 20, 30, 255], true); + assert_eq!(image.size, [2, 1]); + assert!(image.pixels[0].to_srgba_unmultiplied()[0] >= 253); + assert_eq!( + image.pixels[1], + egui::Color32::from_rgba_unmultiplied(10, 20, 30, 255) + ); + + let mut viewer = crate::viewer::Viewer::default(); + assert!(viewer.request_clipboard_image(CaptureOptions::default())); +} diff --git a/tests/rust/viewer/test_culling.rs b/tests/rust/viewer/test_culling.rs new file mode 100644 index 000000000..bbf819021 --- /dev/null +++ b/tests/rust/viewer/test_culling.rs @@ -0,0 +1,94 @@ +use super::*; +use crate::settings::Projection; +use crate::viewer::camera::{Pose, StandardView}; + +fn cube_at(center: Vec3, half: f32) -> Aabb { + Aabb { + min: center - Vec3::splat(half), + max: center + Vec3::splat(half), + } +} + +fn top_camera(projection: Projection) -> Camera { + let mut camera = Camera { + projection, + scene_radius: 50.0, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::ZERO, + rotation: StandardView::Top.rotation(), + extent: 10.0, + }); + camera +} + +#[test] +fn the_frustum_keeps_what_may_be_seen_and_drops_the_rest() { + for projection in [Projection::Orthographic, Projection::Perspective] { + let camera = top_camera(projection); + let frustum = Frustum::new(camera.view_projection(1.0), Vec2::ZERO); + assert!( + frustum.intersects(cube_at(Vec3::ZERO, 1.0)), + "{projection:?}" + ); + // Straddling the right edge of the view. + let edge = if projection == Projection::Orthographic { + 10.0 + } else { + camera.distance() * (camera.fov_y / 2.0).tan() + }; + assert!(frustum.intersects(cube_at(Vec3::new(edge, 0.0, 0.0), 0.5))); + assert!(!frustum.intersects(cube_at(Vec3::new(edge + 2.0, 0.0, 0.0), 0.5))); + assert!(!frustum.intersects(cube_at(Vec3::new(0.0, -3.0 * edge, 0.0), 1.0))); + // Behind the camera. + assert!(!frustum.intersects(cube_at(camera.eye() + Vec3::Z * 500.0, 1.0))); + assert!(!frustum.intersects(Aabb::EMPTY)); + } +} + +#[test] +fn large_model_mode_and_detail_follow_their_thresholds() { + assert!(!LargeModels::Automatic.active(LARGE_MODEL_TRIANGLES - 1)); + assert!(LargeModels::Automatic.active(LARGE_MODEL_TRIANGLES)); + assert!(LargeModels::Always.active(0)); + assert!(!LargeModels::Off.active(usize::MAX)); + + assert_eq!(Detail::for_size(500.0), Detail::Full); + assert_eq!(Detail::for_size(SMALL_PART_PX), Detail::Full); + assert_eq!(Detail::for_size(40.0), Detail::Simplified); + assert_eq!(Detail::for_size(2.0), Detail::Faint); + assert_eq!(Detail::for_size(f32::INFINITY), Detail::Full); +} + +#[test] +fn parts_are_measured_in_pixels_on_screen() { + // Orthographic: 20 units high on 1000 pixels, 50 pixels per unit. + let camera = top_camera(Projection::Orthographic); + let part = cube_at(Vec3::new(3.0, 0.0, 0.0), 1.0); + let size = projected_size(&camera, 1000.0, part); + assert!((size - part.diagonal() * 50.0).abs() < 1e-3, "{size}"); + + // Perspective: smaller further away, huge around the eye. + let camera = top_camera(Projection::Perspective); + let near = projected_size(&camera, 1000.0, cube_at(Vec3::ZERO, 1.0)); + let far = projected_size(&camera, 1000.0, cube_at(Vec3::new(0.0, 0.0, -100.0), 1.0)); + assert!(far < near / 2.0, "{near} then {far}"); + assert_eq!( + projected_size(&camera, 1000.0, cube_at(camera.eye(), 1.0)), + f32::INFINITY + ); + assert_eq!(projected_size(&camera, 1000.0, Aabb::EMPTY), 0.0); +} + +#[test] +fn a_margin_keeps_what_borders_the_view() { + let camera = top_camera(Projection::Orthographic); + let just_outside = cube_at(Vec3::new(10.6, 0.0, 0.0), 0.5); + let tight = Frustum::new(camera.view_projection(1.0), Vec2::ZERO); + assert!(!tight.intersects(just_outside)); + // 2% of the half-width is 0.2 units here. + let widened = Frustum::new(camera.view_projection(1.0), Vec2::splat(0.02)); + assert!(widened.intersects(just_outside)); + assert!(!widened.intersects(cube_at(Vec3::new(11.0, 0.0, 0.0), 0.5))); +} diff --git a/tests/rust/viewer/test_ground.rs b/tests/rust/viewer/test_ground.rs new file mode 100644 index 000000000..aa71b7d3a --- /dev/null +++ b/tests/rust/viewer/test_ground.rs @@ -0,0 +1,209 @@ +use super::*; +use crate::settings::Projection; +use crate::viewer::camera::{Pose, StandardView}; + +fn camera(projection: Projection, target: Vec3, extent: f32, view: StandardView) -> Camera { + let mut camera = Camera { + projection, + ..Camera::default() + }; + camera.set_pose(Pose { + target, + rotation: view.rotation(), + extent, + }); + camera +} + +/// The DIN 912 M8x60 screw: the origin is under its head. +fn screw() -> Aabb { + Aabb::from_points([Vec3::new(-6.5, -6.5, -60.0), Vec3::new(6.5, 6.5, 8.0)]) +} + +/// The floor for a model in the Iso view, `extent` units from the middle of +/// the view to its top. +fn floor(bounds: Aabb, extent: f32) -> GroundGrid { + let camera = camera( + Projection::Orthographic, + Vec3::ZERO, + extent, + StandardView::Iso, + ); + GroundGrid::under(bounds, &camera, VIEW) +} + +const VIEW: Vec2 = Vec2::new(800.0, 600.0); + +fn points(meshes: &[(Mesh, Mesh)]) -> impl Iterator + '_ { + meshes + .iter() + .flat_map(|(minor, major)| minor.edges.iter().chain(&major.edges)) + .map(|point| Vec3::from_array(*point)) +} + +#[test] +fn lengths_are_rounded_to_one_two_or_five_and_printed_plainly() { + let rounded: Vec = [0.03, 0.7, 1.0, 1.2, 3.0, 7.0, 120.0] + .into_iter() + .map(round_length) + .collect(); + assert_eq!(rounded, [0.05, 1.0, 1.0, 2.0, 5.0, 10.0, 200.0]); + assert_eq!(round_length(0.0), 1.0); + assert_eq!(round_length(f32::NAN), 1.0); + + assert_eq!(format_length(2.5, Units::Millimeters), "2.5 mm"); + assert_eq!(format_length(100.0, Units::Inches), "100 in"); + assert_eq!(format_length(0.05, Units::None), "0.05"); + assert_eq!(format_length(1000.0, Units::Meters), "1000 m"); +} + +#[test] +fn units_per_point_follow_the_zoom_in_both_projections() { + let orthographic = camera( + Projection::Orthographic, + Vec3::ZERO, + 10.0, + StandardView::Top, + ); + assert!((units_per_point(&orthographic, 500.0) - 0.04).abs() < 1e-6); + let perspective = camera(Projection::Perspective, Vec3::ZERO, 10.0, StandardView::Top); + let expected = 2.0 * perspective.distance() * (perspective.fov_y / 2.0).tan() / 500.0; + assert!((units_per_point(&perspective, 500.0) - expected).abs() < 1e-6); +} + +#[test] +fn the_floor_lies_flat_under_the_model() { + let grid = floor(screw(), 60.0); + assert_eq!(grid.center.z, -60.0, "at the screw's tip, not at Z = 0"); + let meshes = grid.faded_meshes(); + assert!(points(&meshes).all(|point| point.z == -60.0)); + + // It reaches well past the model on every side. + let footprint = Aabb::from_points(points(&meshes)); + assert!(footprint.min.x < -60.0 && footprint.max.x > 60.0); + assert!(footprint.min.y < -60.0 && footprint.max.y > 60.0); + + // A model above the origin stands on its own lowest point. + let raised = Aabb::from_points([Vec3::new(40.0, 10.0, 5.0), Vec3::new(60.0, 30.0, 25.0)]); + let grid = floor(raised, 60.0); + assert_eq!(grid.center.z, 5.0); + assert!((grid.center.truncate() - Vec2::new(50.0, 20.0)).length() <= grid.minor * 5.0); +} + +#[test] +fn the_spacing_follows_the_model_and_not_the_zoom() { + let grid = floor(screw(), 40.0); + assert_eq!(grid.minor, 5.0, "68 mm long: 5 mm cells"); + let mut radius = 0.0; + for extent in [0.5, 15.0, 40.0, 300.0, 12000.0] { + let zoomed = floor(screw(), extent); + assert_eq!((zoomed.minor, zoomed.center), (grid.minor, grid.center)); + assert!(zoomed.radius >= radius, "zooming out never shrinks it"); + radius = zoomed.radius; + } + + for (size, minor) in [(10.0, 0.5), (68.0, 5.0), (100.0, 5.0), (1000.0, 50.0)] { + let model = Aabb::from_points([Vec3::ZERO, Vec3::new(size * 0.5, size * 0.2, size)]); + let grid = floor(model, size); + assert_eq!(grid.minor, minor, "{size} units tall"); + assert_eq!(round_length(grid.minor), grid.minor); + // Centred on a major line, so that every line has a round coordinate. + let major = grid.minor * 5.0; + let center = grid.center.truncate(); + assert!(((center / major).round() * major - center).length() < 1e-3); + assert!(grid.radius <= grid.minor * 300.0); + } +} + +#[test] +fn an_empty_scene_has_a_floor_through_the_origin() { + for bounds in [ + Aabb::EMPTY, + Aabb::from_points([Vec3::new(3.0, 4.0, 5.0)]), + Aabb::from_points([Vec3::ZERO, Vec3::new(f32::INFINITY, 1.0, 1.0)]), + ] { + let grid = floor(bounds, 20.0); + assert_eq!(grid.center, Vec3::ZERO); + assert_eq!(grid.minor, 5.0); + assert!(grid.radius > 100.0); + } +} + +#[test] +fn the_floor_reaches_the_edge_of_the_view_in_whole_doublings() { + let own = floor(screw(), 1.0).radius; + for (extent, view) in [ + (300.0, StandardView::Top), + (200.0, StandardView::Iso), + (40.0, StandardView::Front), + ] { + let camera = camera(Projection::Orthographic, Vec3::ZERO, extent, view); + let grid = GroundGrid::under(screw(), &camera, VIEW); + let half_view = VIEW.length() * 0.5 * units_per_point(&camera, VIEW.y); + assert!(grid.radius >= half_view, "{view:?} at {extent}"); + let doublings = (grid.radius / own).log2(); + assert!((doublings - doublings.round()).abs() < 1e-4); + } + // Never more lines than the cap, however far the view zooms out. + let farthest = floor(screw(), 1e6); + assert_eq!(farthest.radius, farthest.minor * 300.0); +} + +#[test] +fn crowded_lines_fade_out_as_the_view_zooms_out() { + // 600 points high: an extent of 15 is 0.05 units per point. + let close = floor(screw(), 15.0); + assert_eq!((close.minor_opacity, close.major_opacity), (1.0, 1.0)); + let far = floor(screw(), 240.0); + assert!(far.minor_opacity < 0.5 && far.major_opacity == 1.0); + let very_far = floor(screw(), 1500.0); + assert_eq!(very_far.minor_opacity, 0.0); + assert!(very_far.major_opacity < far.major_opacity); + assert_eq!(line_opacity(1.0, 0.0), 1.0); +} + +#[test] +fn the_floor_fades_into_a_circle_with_every_fifth_line_major() { + let grid = floor(screw(), 60.0); + let meshes = grid.faded_meshes(); + assert_eq!(meshes.len(), GRID_FADE.len()); + assert!( + meshes + .iter() + .all(|(minor, major)| !minor.edges.is_empty() && !major.edges.is_empty()) + ); + for point in points(&meshes) { + assert!((point - grid.center).length() <= grid.radius + 1e-3); + } + // Each line runs along X or Y at a multiple of the spacing. + for (minor, major) in &meshes { + for (lines, step) in [(&minor.edges, grid.minor), (&major.edges, grid.minor * 5.0)] { + for pair in lines.chunks(2) { + let (a, b) = (Vec3::from_array(pair[0]), Vec3::from_array(pair[1])); + let across = if a.x == b.x { a.x } else { a.y }; + assert!(a.x == b.x || a.y == b.y); + assert!(((across / step).round() * step - across).abs() < 1e-3); + } + } + } + let [low, high] = grid.corners(); + let footprint = Aabb::from_points(points(&meshes)); + assert!(low.x <= footprint.min.x && high.y >= footprint.max.y); + assert_eq!((low.z, high.z), (-60.0, -60.0)); +} + +#[test] +fn the_scale_bar_shows_a_round_length_at_least_sixty_points_long() { + for units_per_point in [0.0003, 0.04, 0.7, 13.0] { + let bar = ScaleBar::new(units_per_point, Units::Millimeters); + assert!( + (60.0..150.0).contains(&bar.width), + "{} points for {units_per_point}", + bar.width + ); + assert_eq!(round_length(bar.length), bar.length); + assert!((bar.width * units_per_point - bar.length).abs() < bar.length * 1e-4); + assert_eq!(bar.label, format_length(bar.length, Units::Millimeters)); + } + assert_eq!(ScaleBar::new(0.1, Units::Inches).label, "10 in"); +} diff --git a/tests/rust/viewer/test_navigation.rs b/tests/rust/viewer/test_navigation.rs new file mode 100644 index 000000000..582e07658 --- /dev/null +++ b/tests/rust/viewer/test_navigation.rs @@ -0,0 +1,768 @@ +use super::*; + +#[test] +fn drag_motion_is_incremental_instead_of_reapplying_the_whole_drag() { + let mut drag = Drag { + mode: DragMode::Pan, + start: Pos2::new(10.0, 20.0), + last: Pos2::new(10.0, 20.0), + pivot: None, + }; + + assert_eq!(drag.advance(Pos2::new(14.0, 23.0)), Vec2::new(4.0, 3.0)); + assert_eq!(drag.advance(Pos2::new(17.0, 25.0)), Vec2::new(3.0, 2.0)); + assert_eq!(drag.last, Pos2::new(17.0, 25.0)); + + let mut incremental = Camera::default(); + incremental.pan(GVec2::new(4.0, 3.0), 600.0); + incremental.pan(GVec2::new(3.0, 2.0), 600.0); + let mut once = Camera::default(); + once.pan(GVec2::new(7.0, 5.0), 600.0); + assert!((incremental.target - once.target).length() < 1e-5); +} + +/// The original editor's gestures, except the right button: it orbits like +/// the left one instead of zooming. +#[test] +fn mouse_gestures_choose_their_navigation_modes() { + use egui::{Modifiers, PointerButton}; + + let mode = |modifiers, button| { + requested_drag_mode( + modifiers, + button == PointerButton::Primary, + button == PointerButton::Middle, + button == PointerButton::Secondary, + ) + }; + + assert!(matches!( + mode(Modifiers::NONE, PointerButton::Primary), + Some(DragMode::Orbit) + )); + assert!(matches!( + mode(Modifiers::NONE, PointerButton::Middle), + Some(DragMode::Pan) + )); + assert!(matches!( + mode(Modifiers::CTRL, PointerButton::Primary), + Some(DragMode::Pan) + )); + assert!(matches!( + mode(Modifiers::COMMAND, PointerButton::Primary), + Some(DragMode::Pan) + )); + assert!(matches!( + mode(Modifiers::NONE, PointerButton::Secondary), + Some(DragMode::Orbit) + )); + assert!(matches!( + mode(Modifiers::SHIFT, PointerButton::Primary), + Some(DragMode::Zoom) + )); +} + +#[test] +fn zoom_percentage_is_relative_to_the_last_fit_extent() { + let mut viewer = Viewer::default(); + viewer.camera.extent = 20.0; + viewer.zoom_reference_extent = 20.0; + + viewer.set_zoom_percent(200.0); + assert!((viewer.camera.extent - 10.0).abs() < 1e-5); + assert!((viewer.zoom_percent() - 200.0).abs() < 1e-4); + + viewer.set_zoom_percent(50.0); + assert!((viewer.camera.extent - 40.0).abs() < 1e-5); + assert!((viewer.zoom_percent() - 50.0).abs() < 1e-4); +} + +#[test] +fn zoom_controls_stay_inside_the_view_and_hide_when_it_is_too_small() { + let view = Rect::from_min_size(Pos2::new(50.0, 80.0), Vec2::new(800.0, 600.0)); + let controls = zoom_controls_rect(view).unwrap(); + assert!(view.contains_rect(controls)); + assert_eq!(controls.left(), view.left() + ZOOM_CONTROLS_MARGIN); + assert_eq!(controls.top(), view.top() + ZOOM_CONTROLS_MARGIN); + + let narrow = Rect::from_min_size(Pos2::ZERO, Vec2::new(180.0, 600.0)); + assert!(zoom_controls_rect(narrow).is_none()); +} + +#[test] +fn zoom_overlay_buttons_are_interactive_over_the_viewer() { + fn frame(ctx: &egui::Context, viewer: &mut Viewer, events: Vec) -> Rect { + let input = egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), + events, + ..Default::default() + }; + let mut controls = Rect::NOTHING; + let mut output = ctx.run_ui(input, |ui| { + let view = ui.available_rect_before_wrap(); + ui.allocate_rect(view, Sense::click_and_drag()); + controls = zoom_controls_rect(view).unwrap(); + viewer.show_zoom_controls(ui, view, controls); + }); + // This headless test has no renderer to upload the font atlas to. + output.textures_delta.clear(); + controls + } + + let ctx = egui::Context::default(); + let mut viewer = Viewer::default(); + let controls = frame(&ctx, &mut viewer, Vec::new()); + // First button: frame margin (6, 5), then a 28-point button. + let zoom_out = controls.min + Vec2::new(20.0, 19.0); + frame( + &ctx, + &mut viewer, + vec![ + egui::Event::PointerMoved(zoom_out), + egui::Event::PointerButton { + pos: zoom_out, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }, + ], + ); + frame( + &ctx, + &mut viewer, + vec![egui::Event::PointerButton { + pos: zoom_out, + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }], + ); + + assert!((viewer.zoom_percent() - 80.0).abs() < 1e-4); + assert!((viewer.camera.extent - 25.0).abs() < 1e-4); +} + +#[test] +fn pressing_the_view_uses_a_closed_hand_cursor_for_navigation() { + fn frame( + ctx: &egui::Context, + viewer: &mut Viewer, + events: Vec, + ) -> egui::CursorIcon { + let input = egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0))), + events, + ..Default::default() + }; + let scene = Scene::default(); + let settings = crate::settings::Viewer::default(); + let colors = crate::theme::Palette::DARK.viewer(); + let mut output = ctx.run_ui(input, |ui| { + let rect = ui.available_rect_before_wrap(); + let response = ui.allocate_rect(rect, Sense::click_and_drag()); + viewer.handle_input( + ui, + &response, + rect, + &zoom_controls_rect(rect).into_iter().collect::>(), + &ViewInput { + scene: &scene, + settings: &settings, + rendering: &crate::settings::Rendering::default(), + colors: &colors, + busy: None, + empty_hint: None, + meshing: None, + }, + 0.0, + ); + }); + output.textures_delta.clear(); + output.platform_output.cursor_icon + } + + let ctx = egui::Context::default(); + let mut viewer = Viewer::default(); + frame(&ctx, &mut viewer, Vec::new()); + let position = Pos2::new(400.0, 300.0); + let cursor = frame( + &ctx, + &mut viewer, + vec![ + egui::Event::PointerMoved(position), + egui::Event::PointerButton { + pos: position, + button: egui::PointerButton::Primary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }, + ], + ); + + assert_eq!(cursor, egui::CursorIcon::Grabbing); + assert_eq!( + requested_drag_mode(egui::Modifiers::NONE, false, false, true).map(DragMode::cursor), + Some(egui::CursorIcon::Grabbing) + ); +} + +#[test] +fn orbit_changes_only_the_view_direction() { + let mut camera = Camera::default(); + let before = camera.pose(); + + camera.orbit_turntable(GVec2::new(24.0, -12.0)); + + assert_eq!(camera.target, before.target); + assert_eq!(camera.extent, before.extent); + assert_ne!(camera.rotation, before.rotation); +} + +#[test] +fn control_bars_stack_up_from_the_bottom_without_overlapping() { + let view = Rect::from_min_size(Pos2::new(100.0, 50.0), Vec2::new(900.0, 600.0)); + let zoom = zoom_controls_rect(view).unwrap(); + let bars: Vec = (0..3) + .map(|row| bottom_bar_rect(view, row, 400.0).unwrap()) + .collect(); + assert!((bars[0].bottom() - (view.bottom() - ZOOM_CONTROLS_MARGIN)).abs() < 1e-3); + for (row, bar) in bars.iter().enumerate() { + assert!(view.contains_rect(*bar)); + assert!(!bar.intersects(zoom), "bar {row} under the zoom controls"); + if row > 0 { + assert!( + bar.bottom() < bars[row - 1].top(), + "bar {row} above the previous" + ); + } + } + // Narrow views clamp the width, short ones drop the upper bars. + let narrow = Rect::from_min_size(Pos2::ZERO, Vec2::new(300.0, 600.0)); + assert!( + bottom_bar_rect(narrow, 0, 430.0).unwrap().width() <= 300.0 - 2.0 * ZOOM_CONTROLS_MARGIN + ); + let short = Rect::from_min_size(Pos2::ZERO, Vec2::new(900.0, 150.0)); + assert!(bottom_bar_rect(short, 0, 400.0).is_some()); + assert!(bottom_bar_rect(short, 1, 400.0).is_none()); +} + +fn red_look(edges: Option) -> PartLook { + PartLook { + face_color: [1.0, 0.0, 0.0, 0.8], + edge_color: [0.0, 0.0, 0.0, 1.0], + highlight: [0.0; 4], + has_faces: true, + emphasized: false, + edges, + finish: settings::Finish::Default, + } +} + +#[test] +fn the_edge_style_chooses_the_edges_of_faces_outside_wireframe() { + use DisplayMode::{HiddenLine, Shaded, Wireframe, XRay}; + use settings::{EdgeStyle, Rendering}; + let settings = settings::Viewer::default(); + let with = |edges| Rendering { + edges, + sharp_angle: 25.0, + ..Rendering::default() + }; + + for mode in [Shaded, XRay, HiddenLine] { + let all = mode.style(red_look(None), &settings, &with(EdgeStyle::All)); + assert_eq!((all.edge_min_angle, all.silhouettes), (0.0, false)); + let sharp = mode.style(red_look(None), &settings, &with(EdgeStyle::Sharp)); + assert_eq!((sharp.edge_min_angle, sharp.silhouettes), (25.0, false)); + let outline = mode.style(red_look(None), &settings, &with(EdgeStyle::Outline)); + assert_eq!((outline.edge_min_angle, outline.silhouettes), (25.0, true)); + } + // Wireframe draws every edge, and a wire has no faces to judge by. + let wireframe = Wireframe.style(red_look(None), &settings, &with(EdgeStyle::Outline)); + assert_eq!( + (wireframe.edge_min_angle, wireframe.silhouettes), + (0.0, false) + ); + let wire = PartLook { + has_faces: false, + ..red_look(None) + }; + let wire = Shaded.style(wire, &settings, &with(EdgeStyle::Outline)); + assert_eq!((wire.edge_min_angle, wire.silhouettes), (0.0, false)); +} + +#[test] +fn display_modes_and_object_edges_shape_how_parts_are_drawn() { + use DisplayMode::{HiddenLine, Shaded, Wireframe, XRay}; + let settings = settings::Viewer::default(); + let no_edges = settings::Viewer { + show_edges: false, + ..settings.clone() + }; + + // Shaded and X-ray follow the object's own choice, then the preference. + for mode in [Shaded, XRay] { + assert!( + mode.style(red_look(None), &settings, &Default::default()) + .edges + ); + assert!( + !mode + .style(red_look(Some(false)), &settings, &Default::default()) + .edges + ); + assert!( + !mode + .style(red_look(None), &no_edges, &Default::default()) + .edges + ); + assert!( + mode.style(red_look(Some(true)), &no_edges, &Default::default()) + .edges + ); + } + // Edges are the drawing in wireframe and hidden-line modes, and all + // there is of a wire. + for mode in [Wireframe, HiddenLine] { + assert!( + mode.style(red_look(Some(false)), &no_edges, &Default::default()) + .edges + ); + } + let wire = PartLook { + has_faces: false, + ..red_look(Some(false)) + }; + assert!(Shaded.style(wire, &no_edges, &Default::default()).edges); + + let shaded = Shaded.style(red_look(None), &settings, &Default::default()); + assert!(shaded.faces && !shaded.background_fill && !shaded.hidden_edges); + assert_eq!(shaded.face_color[3], 0.8); + assert!( + !Wireframe + .style(red_look(None), &settings, &Default::default()) + .faces + ); + assert_eq!( + XRay.style(red_look(None), &settings, &Default::default()) + .face_color[3], + XRAY_OPACITY + ); + + let hidden_line = HiddenLine.style(red_look(None), &settings, &Default::default()); + assert!(hidden_line.faces && hidden_line.background_fill && hidden_line.hidden_edges); + assert_eq!( + hidden_line.face_color[3], 1.0, + "opaque, to hide what is behind" + ); + let solid_only = settings::Viewer { + hidden_edges: false, + ..settings.clone() + }; + assert!( + !HiddenLine + .style(red_look(None), &solid_only, &Default::default()) + .hidden_edges + ); +} + +/// A grid of `side` × `side` vertices: 2 (side - 1)² triangles, enough to be +/// simplified when `side` is large. +fn fine_plate(side: u32) -> Mesh { + let mut positions = Vec::new(); + for y in 0..side { + for x in 0..side { + positions.push([x as f32 / side as f32, y as f32 / side as f32, 0.0]); + } + } + let mut indices = Vec::new(); + for y in 0..side - 1 { + for x in 0..side - 1 { + let a = y * side + x; + indices.extend([a, a + 1, a + side, a + 1, a + side + 1, a + side]); + } + } + let normals = vec![[0.0, 0.0, 1.0]; positions.len()]; + let edges = vec![[0.0; 3], [1.0, 0.0, 0.0]]; + Mesh::new(positions, normals, indices, edges, Vec::new()) +} + +#[test] +fn an_orbit_turns_around_the_model_point_under_the_pointer() { + use crate::scene::{Part, SceneNode}; + use crate::viewer::camera::Pose; + // A 0.75-unit plate on z = 0, from the origin. + let node = SceneNode { + key: "plate".into(), + name: "plate".into(), + kind: "Workplane".into(), + inspectable: false, + parts: vec![Part { + mesh: Arc::new(fine_plate(4)), + transform: GMat4::IDENTITY, + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + render_mesh: None, + }], + children: Vec::new(), + visible: true, + color: None, + alpha: None, + edge_color: None, + finish: None, + overrides: Default::default(), + line: None, + script: None, + }; + let mut scene = Scene::default(); + scene.append(vec![node], None); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0)); + let mut viewer = Viewer { + aspect: 800.0 / 600.0, + ..Viewer::default() + }; + let top = |target| Pose { + target, + rotation: StandardView::Top.rotation(), + extent: 2.0, + }; + let (far, plate) = (Vec3::new(100.0, 100.0, 0.0), Vec3::new(0.375, 0.375, 0.0)); + + // Pressed while the view still moves from far away to the plate: the + // move ends first, and the point is picked in the view the drag turns. + viewer.camera.set_pose(top(far)); + viewer.animation = Some(Animation::new(top(far), top(plate), 0.0, ANIMATION_SECONDS)); + // 30 points right of the middle: 0.2 units at 2 units per 300 points. + viewer.start_drag( + &scene, + rect, + DragMode::Orbit, + rect.center() + Vec2::new(30.0, 0.0), + ); + assert!(viewer.animation.is_none()); + assert_eq!(viewer.camera.target, plate); + let pivot = viewer.drag.as_ref().unwrap().pivot.unwrap(); + assert!( + (pivot - Vec3::new(0.575, 0.375, 0.0)).length() < 1e-3, + "{pivot}" + ); + + // Over empty space it turns around the middle of the view; a pan has none. + viewer.start_drag(&scene, rect, DragMode::Orbit, rect.min + Vec2::splat(5.0)); + assert_eq!(viewer.drag.as_ref().unwrap().pivot, Some(plate)); + viewer.start_drag(&scene, rect, DragMode::Pan, rect.center()); + assert_eq!(viewer.drag.as_ref().unwrap().pivot, None); +} + +#[test] +fn large_models_draw_small_parts_simplified_but_never_the_selection() { + use crate::scene::{Part, SceneNode}; + let mesh = Arc::new(fine_plate(80)); + let simplified_id = mesh.simplified().expect("fine enough").id; + let node = SceneNode { + key: "plate".into(), + name: "plate".into(), + kind: "Workplane".into(), + inspectable: false, + parts: vec![Part { + mesh: mesh.clone(), + transform: GMat4::IDENTITY, + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + render_mesh: None, + }], + children: Vec::new(), + visible: true, + color: None, + alpha: None, + edge_color: None, + finish: None, + overrides: Default::default(), + line: None, + script: None, + }; + let mut scene = Scene::default(); + scene.append(vec![node], None); + let settings = crate::settings::Viewer::default(); + let colors = crate::theme::Palette::DARK.viewer(); + let mut viewer = Viewer { + view_px: [1000, 1000], + ..Viewer::default() + }; + let drawn = |viewer: &mut Viewer, scene: &Scene, simplify: bool| { + let input = ViewInput { + scene, + settings: &settings, + rendering: &crate::settings::Rendering::default(), + colors: &colors, + busy: None, + empty_hint: None, + meshing: None, + }; + let item = viewer.draw_items(&input, simplify).remove(0); + (item.mesh.id, item.style.edges) + }; + + // The 1.4-unit plate seen 2 units high: hundreds of pixels, in full. + viewer.camera.extent = 1.0; + assert_eq!(drawn(&mut viewer, &scene, true), (mesh.id, true)); + // 50 units high: about 28 pixels, simplified with its edges. + viewer.camera.extent = 25.0; + assert_eq!(drawn(&mut viewer, &scene, true), (simplified_id, true)); + assert_eq!(drawn(&mut viewer, &scene, false), (mesh.id, true)); + // 1000 units high: a speck, without edges. + viewer.camera.extent = 500.0; + assert_eq!(drawn(&mut viewer, &scene, true), (simplified_id, false)); + // Selected, it is drawn as it is. + scene.select_only("plate"); + assert_eq!(drawn(&mut viewer, &scene, true), (mesh.id, true)); +} + +#[test] +fn presentation_shows_the_model_alone_in_its_own_material_and_lights() { + use crate::scene::{Part, SceneNode}; + use crate::settings::{EdgeStyle, Finish, Rendering}; + let part = |name: &str, finish: Option| SceneNode { + key: name.into(), + name: name.into(), + kind: "Workplane".into(), + inspectable: false, + parts: vec![Part { + mesh: Arc::new(fine_plate(4)), + transform: GMat4::IDENTITY, + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + render_mesh: None, + }], + children: Vec::new(), + visible: true, + color: None, + alpha: None, + edge_color: None, + finish, + overrides: Default::default(), + line: None, + script: None, + }; + let mut scene = Scene::default(); + scene.append( + vec![ + part("plain", None), + part("steel", Some(Finish::BrushedSteel)), + ], + None, + ); + let settings = crate::settings::Viewer::default(); + let colors = crate::theme::Palette::DARK.viewer(); + let mut viewer = Viewer::default(); + viewer.update_ground( + true, + scene.visible_bounds(), + Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0)), + ); + let mut rendering = Rendering::default(); + rendering.presentation.material = Finish::Aluminum; + let items = |viewer: &mut Viewer, rendering: &Rendering| { + let input = ViewInput { + scene: &scene, + settings: &settings, + rendering, + colors: &colors, + busy: None, + empty_hint: None, + meshing: None, + }; + viewer.draw_items(&input, false) + }; + + // Shaded: the plain shading, every edge, the axes with the origin dot + // (two points) and the grid. + let shaded = items(&mut viewer, &rendering); + assert_eq!(shaded.len(), 2 + 3 + 2 + GRID_FADE.len() * 2); + assert_eq!(shaded[0].style.surface, Finish::Default.surface()); + assert!(shaded[0].style.edges); + + viewer.display_mode = DisplayMode::Presentation; + let presented = items(&mut viewer, &rendering); + assert_eq!(presented.len(), 2, "no axes, no grid"); + let (plain, steel) = (&presented[0].style, &presented[1].style); + assert_eq!(plain.surface, Finish::Aluminum.surface(), "its default"); + assert_eq!(steel.surface, Finish::BrushedSteel.surface(), "its own"); + // The default material's color for an object without one. + let aluminum = Finish::Aluminum.natural_color().unwrap(); + assert_eq!(plain.face_color, super::rgb_to_linear(aluminum, 1.0)); + assert!(!plain.edges && !steel.edges, "no edges by default"); + + rendering.presentation.show_edges = true; + rendering.presentation.helpers = true; + rendering.presentation.edges = EdgeStyle::Outline; + let outlined = items(&mut viewer, &rendering); + assert_eq!(outlined.len(), 2 + 3 + 2 + GRID_FADE.len() * 2); + assert!(outlined[0].style.edges && outlined[0].style.silhouettes); + + // Its own lights and background; Shaded keeps the others. + let input = ViewInput { + scene: &scene, + settings: &settings, + rendering: &rendering, + colors: &colors, + busy: None, + empty_hint: None, + meshing: None, + }; + let presented = viewer.backdrop(&input); + assert_eq!(presented.lighting, rendering.presentation.lighting); + assert_ne!(presented.lighting, rendering.lighting); + let presentation = &rendering.presentation; + assert_eq!( + presented.top, + super::linear_rgba(presentation.background_top, 1.0) + ); + assert_eq!( + presented.bottom, + super::linear_rgba(presentation.background_bottom, 1.0) + ); + assert_eq!( + presented.shadow, + Some(super::GroundShadow { + strength: presentation.shadow_strength, + softness: presentation.shadow_softness, + }) + ); + viewer.display_mode = DisplayMode::Shaded; + let shaded = viewer.backdrop(&input); + assert_eq!(shaded.lighting, rendering.lighting); + let plain = super::linear_rgba(settings.background, 1.0); + assert_eq!((shaded.top, shaded.bottom), (plain, plain)); + assert_eq!(shaded.shadow, None, "only Presentation has a ground shadow"); +} + +#[test] +fn the_ground_grid_follows_its_setting_and_the_model() { + let mut viewer = Viewer::default(); + let rect = Rect::from_min_size(Pos2::ZERO, Vec2::new(800.0, 600.0)); + let screw = Aabb::from_points([Vec3::new(-6.5, -6.5, -60.0), Vec3::new(6.5, 6.5, 8.0)]); + viewer.update_ground(false, screw, rect); + assert!(viewer.ground.is_none()); + + viewer.update_ground(true, screw, rect); + let (grid, rings) = viewer.ground.clone().unwrap(); + assert_eq!(grid.center.z, -60.0, "a floor under the model"); + + viewer.update_ground(true, screw, rect); + let kept = viewer.ground.as_ref().unwrap(); + assert!( + Arc::ptr_eq(&kept.1[0].0, &rings[0].0), + "same lines, same meshes" + ); + + // Turning and zooming leave the floor where it is: at most it reaches + // farther, and zooming out fades the lines that crowd together. + for view in [StandardView::Front, StandardView::Right, StandardView::Top] { + viewer.camera.rotation = view.rotation(); + viewer.update_ground(true, screw, rect); + let turned = viewer.ground.as_ref().unwrap().0; + assert_eq!((turned.minor, turned.center), (grid.minor, grid.center)); + assert!(turned.radius >= grid.radius); + } + viewer.camera.rotation = StandardView::Iso.rotation(); + viewer.camera.extent *= 20.0; + viewer.update_ground(true, screw, rect); + let far = viewer.ground.as_ref().unwrap().0; + assert_eq!((far.minor, far.center), (grid.minor, grid.center)); + assert!( + far.radius > grid.radius, + "the floor reaches the edge of the view" + ); + assert!(far.minor_opacity < grid.minor_opacity); + viewer.camera.extent /= 20.0; + viewer.update_ground(true, screw, rect); + assert_eq!(viewer.ground.as_ref().unwrap().0, grid); + + // Another model gets its own floor. + let plate = Aabb::from_points([Vec3::ZERO, Vec3::new(400.0, 300.0, 10.0)]); + viewer.update_ground(true, plate, rect); + let (moved, _) = viewer.ground.as_ref().unwrap(); + assert_eq!(moved.center.z, 0.0); + assert!(moved.minor > grid.minor); + viewer.update_ground(true, screw, rect); + + // The clipping planes enclose it, and its lines fade toward the edge. + let scene = Scene::default(); + viewer.update_scene_extent(&scene, screw); + for corner in grid.corners() { + let distance = (corner - viewer.camera.scene_center).length(); + assert!(distance <= viewer.camera.scene_radius + 1e-3); + } + let settings = crate::settings::Viewer::default(); + let colors = crate::theme::Palette::DARK.viewer(); + let input = ViewInput { + scene: &scene, + settings: &settings, + rendering: &crate::settings::Rendering::default(), + colors: &colors, + busy: None, + empty_hint: None, + meshing: None, + }; + let items = viewer.draw_items(&input, false); + let z_axis = viewer.axis_meshes.as_ref().unwrap().1[2].id; + let z_points = &viewer.axis_meshes.as_ref().unwrap().1[2].edges; + assert_eq!(z_points[0], Vec3::ZERO.to_array()); + assert!((z_points[1][2] - viewer.camera.extent * 0.45).abs() < 1e-5); + let z_item = items.iter().find(|item| item.mesh.id == z_axis).unwrap(); + assert_eq!(z_item.layer, Layer::Scene); + assert!( + z_item.style.hidden_edges, + "the Z axis is dashed where a model built around the origin hides it" + ); + let origin: Vec<_> = items + .iter() + .filter(|item| item.mesh.id == viewer.origin_mesh.id) + .collect(); + assert_eq!(origin.len(), 2, "a light dot in a dark ring"); + assert!( + origin + .iter() + .all(|item| { item.layer == Layer::Overlay && item.style.points && !item.style.edges }) + ); + assert!(origin[0].style.point_size > origin[1].style.point_size); + let grid_items: Vec<_> = items + .iter() + .filter(|item| { + viewer + .ground + .as_ref() + .unwrap() + .1 + .iter() + .any(|(minor, major)| item.mesh.id == minor.id || item.mesh.id == major.id) + }) + .collect(); + assert_eq!(grid_items.len(), GRID_FADE.len() * 2); + assert!(grid_items.iter().all(|item| { + item.layer == Layer::Reference && !item.style.clipped && !item.style.faces + })); + let major_opacity: Vec = viewer + .ground + .as_ref() + .unwrap() + .1 + .iter() + .map(|(_, major)| { + items + .iter() + .find(|item| item.mesh.id == major.id) + .unwrap() + .style + .edge_color[3] + }) + .collect(); + assert!(major_opacity.windows(2).all(|pair| pair[0] > pair[1])); +} diff --git a/tests/rust/viewer/test_overlays.rs b/tests/rust/viewer/test_overlays.rs new file mode 100644 index 000000000..3992b1465 --- /dev/null +++ b/tests/rust/viewer/test_overlays.rs @@ -0,0 +1,59 @@ +use super::*; +use crate::viewer::camera::StandardView; + +#[test] +fn cube_has_26_facets_with_outward_normals() { + let facets = facets(); + assert_eq!(facets.len(), 26); + for facet in facets { + for v in &facet.vertices { + assert!(v.dot(facet.normal) > 0.0); + } + } +} + +#[test] +fn clicking_the_front_face_looks_from_the_front() { + let view = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + let rotation = StandardView::Front.rotation(); + let center = NavigationCube::center(view); + let action = NavigationCube::default().click(view, rotation, center); + assert_eq!( + action, + Some(NavAction::LookFrom { + eye_dir: Vec3::NEG_Y, + up: Vec3::Z + }) + ); +} + +#[test] +fn tilting_to_the_top_keeps_orientation() { + let front = StandardView::Front.rotation(); + assert_eq!(up_for(Vec3::Z, front), Vec3::Y); + assert_eq!(up_for(Vec3::NEG_Z, front), Vec3::NEG_Y); + let right = StandardView::Right.rotation(); + assert_eq!(up_for(Vec3::Z, right), Vec3::NEG_X); + // From the iso view the regular top view comes out. + assert_eq!(up_for(Vec3::Z, StandardView::Iso.rotation()), Vec3::Y); +} + +#[test] +fn arrows_are_hit_on_both_sides() { + let view = Rect::from_min_size(Pos2::ZERO, Vec2::splat(400.0)); + let center = NavigationCube::center(view); + let radius = (ARROW_INNER_RADIUS + ARROW_OUTER_RADIUS) / 2.0; + let angle = 64f32.to_radians(); + let right = center + Vec2::new(radius * angle.cos(), -radius * angle.sin()); + let left = center + Vec2::new(-radius * angle.cos(), -radius * angle.sin()); + let cube = NavigationCube::default(); + let rotation = StandardView::Iso.rotation(); + assert_eq!( + cube.click(view, rotation, right), + Some(NavAction::Roll(-FRAC_PI_4)) + ); + assert_eq!( + cube.click(view, rotation, left), + Some(NavAction::Roll(FRAC_PI_4)) + ); +} diff --git a/tests/rust/viewer/test_picking.rs b/tests/rust/viewer/test_picking.rs new file mode 100644 index 000000000..65f681153 --- /dev/null +++ b/tests/rust/viewer/test_picking.rs @@ -0,0 +1,1116 @@ +use super::*; +use crate::viewer::camera::StandardView; + +fn square(z: f32, size: f32) -> Mesh { + let mut mesh = Mesh::new( + vec![ + [-size, -size, z], + [size, -size, z], + [size, size, z], + [-size, size, z], + ], + vec![[0.0, 0.0, 1.0]; 4], + vec![0, 1, 2, 0, 2, 3], + vec![ + [-size, -size, z], + [size, -size, z], + [size, -size, z], + [size, size, z], + [size, size, z], + [-size, size, z], + [-size, size, z], + [-size, -size, z], + ], + Vec::new(), + ); + mesh.topology.face_positions = mesh.positions.clone(); + mesh.topology.face_indices = mesh.indices.clone(); + mesh.topology.triangle_faces = vec![1, 1]; + mesh.topology.segment_edges = vec![1, 2, 3, 4]; + mesh.topology.vertices = mesh.positions.clone(); + mesh +} + +fn top_camera() -> Camera { + Camera { + rotation: StandardView::Top.rotation(), + extent: 10.0, + ..Camera::default() + } +} + +#[test] +fn picks_the_nearest_face() { + let (low, high) = (square(0.0, 5.0), square(3.0, 1.0)); + let candidates = || { + [ + Candidate { + id: "low", + mesh: &low, + transform: Mat4::IDENTITY, + }, + Candidate { + id: "high", + mesh: &high, + transform: Mat4::IDENTITY, + }, + ] + }; + let camera = top_camera(); + let viewport = Vec2::new(800.0, 800.0); + assert_eq!( + pick( + &camera, + 1.0, + Vec2::ZERO, + viewport, + SelectionMode::Auto, + candidates(), + ) + .map(|hit| (hit.id, hit.entity)), + Some(("high", Some(TopologyEntity::Face(1)))) + ); + assert_eq!( + pick( + &camera, + 1.0, + Vec2::new(0.3, 0.3), + viewport, + SelectionMode::Auto, + candidates(), + ) + .map(|hit| (hit.id, hit.entity)), + Some(("low", Some(TopologyEntity::Face(1)))) + ); + assert_eq!( + pick( + &camera, + 1.0, + Vec2::new(0.9, 0.9), + viewport, + SelectionMode::Auto, + candidates(), + ), + None + ); +} + +#[test] +fn picks_wires_within_tolerance() { + let wire = Mesh::lines(vec![[-5.0, 0.0, 0.0], [5.0, 0.0, 0.0]]); + let mut wire = wire; + wire.topology.segment_edges = vec![7]; + let camera = top_camera(); + let viewport = Vec2::new(1000.0, 1000.0); + // 1 world unit = 50 px here; 0.1 units off the line is 5 px. + let near = Vec2::new(0.0, 0.1 / camera.extent); + let far = Vec2::new(0.0, 0.5 / camera.extent); + let candidates = |m| { + [Candidate { + id: 1, + mesh: m, + transform: Mat4::IDENTITY, + }] + }; + assert_eq!( + pick( + &camera, + 1.0, + near, + viewport, + SelectionMode::Auto, + candidates(&wire), + ) + .map(|hit| (hit.id, hit.entity)), + Some((1, Some(TopologyEntity::Edge(7)))) + ); + assert_eq!( + pick( + &camera, + 1.0, + far, + viewport, + SelectionMode::Auto, + candidates(&wire), + ), + None + ); +} + +#[test] +fn prioritizes_vertices_then_edges_then_faces() { + let mesh = square(0.0, 5.0); + let camera = top_camera(); + let viewport = Vec2::splat(1000.0); + let pick_entity = |pointer| { + pick( + &camera, + 1.0, + pointer, + viewport, + SelectionMode::Auto, + [Candidate { + id: (), + mesh: &mesh, + transform: Mat4::IDENTITY, + }], + ) + .and_then(|hit| hit.entity) + }; + + assert_eq!(pick_entity(Vec2::ZERO), Some(TopologyEntity::Face(1))); + assert_eq!( + pick_entity(Vec2::new(0.0, -0.5)), + Some(TopologyEntity::Edge(1)) + ); + assert_eq!( + pick_entity(Vec2::new(0.5, 0.5)), + Some(TopologyEntity::Vertex(3)) + ); +} + +#[test] +fn a_front_face_occludes_a_back_edge() { + let face = square(3.0, 2.0); + let mut back_edge = Mesh::lines(vec![[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]]); + back_edge.topology.segment_edges = vec![9]; + let camera = top_camera(); + let hit = pick( + &camera, + 1.0, + Vec2::ZERO, + Vec2::splat(800.0), + SelectionMode::Auto, + [ + Candidate { + id: "face", + mesh: &face, + transform: Mat4::IDENTITY, + }, + Candidate { + id: "edge", + mesh: &back_edge, + transform: Mat4::IDENTITY, + }, + ], + ) + .unwrap(); + assert_eq!(hit.id, "face"); + assert_eq!(hit.entity, Some(TopologyEntity::Face(1))); +} + +#[test] +fn picks_a_transformed_mesh_in_world_space() { + let mesh = square(0.0, 1.0); + let hit = pick( + &top_camera(), + 1.0, + Vec2::ZERO, + Vec2::splat(800.0), + SelectionMode::Auto, + [Candidate { + id: "moved", + mesh: &mesh, + transform: Mat4::from_translation(Vec3::new(0.0, 0.0, 4.0)), + }], + ) + .unwrap(); + assert_eq!(hit.id, "moved"); + assert!((hit.position.z - 4.0).abs() < 1e-5); +} + +#[test] +fn explicit_selection_modes_only_return_the_requested_topology() { + let mesh = square(0.0, 5.0); + let camera = top_camera(); + let viewport = Vec2::splat(1000.0); + let pick_entity = |pointer, mode| { + pick( + &camera, + 1.0, + pointer, + viewport, + mode, + [Candidate { + id: (), + mesh: &mesh, + transform: Mat4::IDENTITY, + }], + ) + .map(|hit| hit.entity) + }; + + let corner = Vec2::new(0.5, 0.5); + assert_eq!( + pick_entity(corner, SelectionMode::Vertex), + Some(Some(TopologyEntity::Vertex(3))) + ); + assert!(matches!( + pick_entity(corner, SelectionMode::Edge), + Some(Some(TopologyEntity::Edge(_))) + )); + assert_eq!( + pick_entity(Vec2::ZERO, SelectionMode::Face), + Some(Some(TopologyEntity::Face(1))) + ); + assert_eq!( + pick_entity(corner, SelectionMode::Object), + Some(None), + "object mode must not leak a subshape id" + ); +} + +#[test] +fn display_triangles_carry_face_ids_without_separate_pick_triangles() { + // The worker's normal output: face ids for the display triangles only. + let mut mesh = square(0.0, 5.0); + mesh.topology.face_positions.clear(); + mesh.topology.face_indices.clear(); + mesh.topology.triangle_faces = vec![3, 4]; + let pick_at = |pointer| { + pick( + &top_camera(), + 1.0, + pointer, + Vec2::splat(1000.0), + SelectionMode::Face, + [Candidate { + id: (), + mesh: &mesh, + transform: Mat4::IDENTITY, + }], + ) + .and_then(|hit| hit.entity) + }; + // Triangle 0 is (0, 1, 2) below the diagonal, triangle 1 above it. + assert_eq!(pick_at(Vec2::new(0.2, -0.2)), Some(TopologyEntity::Face(3))); + assert_eq!(pick_at(Vec2::new(-0.2, 0.2)), Some(TopologyEntity::Face(4))); +} + +#[test] +fn triangle_bvh_prunes_a_large_mesh() { + let mut positions = Vec::new(); + let mut indices = Vec::new(); + for y in 0..64 { + for x in 0..64 { + let start = positions.len() as u32; + positions.extend([ + [x as f32, y as f32, 0.0], + [x as f32 + 0.8, y as f32, 0.0], + [x as f32, y as f32 + 0.8, 0.0], + ]); + indices.extend([start, start + 1, start + 2]); + } + } + let mesh = Mesh::new( + positions.clone(), + vec![[0.0, 0.0, 1.0]; positions.len()], + indices, + Vec::new(), + Vec::new(), + ); + let (hit, tested) = mesh.nearest_triangle_with_stats(Vec3::new(32.2, 32.2, 10.0), Vec3::NEG_Z); + + assert!(hit.is_some()); + assert!(tested <= 16, "BVH tested {tested} of 4096 triangles"); +} + +// -- broad phase and primitive indexes --------------------------------------- + +use std::f32::consts::TAU; +use std::hint::black_box; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use glam::{EulerRot, Quat}; + +use crate::scene::{Overrides, Part, SceneNode}; +use crate::settings::Projection; + +const MODES: [SelectionMode; 5] = [ + SelectionMode::Auto, + SelectionMode::Object, + SelectionMode::Face, + SelectionMode::Edge, + SelectionMode::Vertex, +]; + +/// Small deterministic generator, so the tests need no extra dependency. +struct Lcg(u64); + +impl Lcg { + fn range(&mut self, min: f32, max: f32) -> f32 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + let unit = (self.0 >> 40) as f32 / (1u64 << 24) as f32; + min + (max - min) * unit + } + + fn point(&mut self, min: f32, max: f32) -> Vec3 { + Vec3::new( + self.range(min, max), + self.range(min, max), + self.range(min, max), + ) + } +} + +fn part(mesh: &Arc, transform: Mat4) -> Part { + Part { + mesh: mesh.clone(), + transform, + color: None, + alpha: None, + face_attributes: Vec::new(), + material: None, + render_mesh: None, + } +} + +fn node(key: &str, parts: Vec, children: Vec) -> SceneNode { + SceneNode { + key: key.into(), + name: key.into(), + kind: "Workplane".into(), + inspectable: false, + parts, + children, + visible: true, + color: None, + alpha: None, + edge_color: None, + finish: None, + overrides: Overrides::default(), + line: None, + script: None, + } +} + +fn scene_of(nodes: Vec) -> Scene { + let mut scene = Scene::default(); + scene.append(nodes, None); + scene +} + +fn translated(key: &str, mesh: &Arc, offset: Vec3) -> SceneNode { + node( + key, + vec![part(mesh, Mat4::from_translation(offset))], + Vec::new(), + ) +} + +/// Every visible part in scene order, as the viewer passed them before the +/// broad phase existed. +fn all_candidates(scene: &Scene) -> Vec> { + scene + .visible_nodes() + .into_iter() + .flat_map(|node| { + node.parts + .iter() + .enumerate() + .map(move |(part_index, part)| Candidate { + id: (node.key.clone(), part_index), + mesh: &part.mesh, + transform: part.transform, + }) + }) + .collect() +} + +fn indexed_candidates<'a>( + index: &SceneIndex, + scene: &'a Scene, + camera: &Camera, + aspect: f32, + pointer: Vec2, + viewport: Vec2, + mode: SelectionMode, +) -> Vec> { + index + .query(camera, aspect, pointer, viewport, mode) + .into_iter() + .filter_map(|found| index.candidate(scene, found)) + .collect() +} + +fn pointer_grid(steps: usize) -> impl Iterator { + let at = move |step: usize| -0.95 + 1.9 * step as f32 / (steps - 1) as f32; + (0..steps * steps).map(move |i| Vec2::new(at(i % steps), at(i / steps))) +} + +/// Orthographic and perspective views from several sides, plus a +/// perspective close-up in which some parts lie behind the eye. +fn test_cameras() -> Vec { + let mut cameras = Vec::new(); + for view in [StandardView::Top, StandardView::Iso, StandardView::Front] { + for projection in [Projection::Orthographic, Projection::Perspective] { + cameras.push(Camera { + rotation: view.rotation(), + extent: 12.0, + projection, + ..Camera::default() + }); + } + } + cameras.push(Camera { + rotation: StandardView::Iso.rotation(), + extent: 2.0, + projection: Projection::Perspective, + ..Camera::default() + }); + cameras +} + +/// Plates and wire crosses at random placements, nested one level deep, +/// with a hidden node and a duplicate coinciding with the first plate. +fn mixed_assembly() -> Scene { + let plate = Arc::new(square(0.0, 0.6)); + let mut cross = Mesh::lines(vec![ + [-0.8, 0.0, 0.0], + [0.8, 0.0, 0.0], + [0.0, -0.8, 0.0], + [0.0, 0.8, 0.0], + ]); + cross.topology.segment_edges = vec![1, 2]; + let cross = Arc::new(cross); + + let mut random = Lcg(7); + let mut parts = Vec::new(); + for index in 0..120 { + let mesh = if index % 9 == 4 { &cross } else { &plate }; + let transform = Mat4::from_scale_rotation_translation( + Vec3::splat(random.range(0.5, 2.0)), + Quat::from_euler( + EulerRot::XYZ, + random.range(-1.0, 1.0), + random.range(-1.0, 1.0), + random.range(-3.0, 3.0), + ), + Vec3::new( + random.range(-8.0, 8.0), + random.range(-8.0, 8.0), + random.range(-4.0, 4.0), + ), + ); + parts.push(part(mesh, transform)); + } + let duplicate = parts[0].clone(); + let mut nodes: Vec<_> = parts + .into_iter() + .enumerate() + .map(|(index, part)| node(&format!("p{index}"), vec![part], Vec::new())) + .collect(); + let children = nodes.split_off(60); + nodes.push(node("assembly", Vec::new(), children)); + nodes.push(node("duplicate", vec![duplicate], Vec::new())); + let mut scene = scene_of(nodes); + scene.set_visible("p5", false); + scene +} + +#[test] +fn bounds_bvh_query_matches_a_linear_scan() { + let mut random = Lcg(3); + let boxes: Vec<(Vec3, Vec3)> = (0..500) + .map(|_| { + let min = random.point(-50.0, 50.0); + (min, min + random.point(0.0, 4.0)) + }) + .collect(); + let bvh = BoundsBvh::build(boxes.iter().copied()); + + let mut tested = 0; + for _ in 0..200 { + let query_min = random.point(-55.0, 50.0); + let query_max = query_min + random.point(0.0, 10.0); + let overlaps = + |min: Vec3, max: Vec3| min.cmple(query_max).all() && max.cmpge(query_min).all(); + let mut found = Vec::new(); + tested += bvh.query_with_stats(overlaps, &mut found).tested_bounds; + let expected: Vec = boxes + .iter() + .enumerate() + .filter(|(_, (min, max))| overlaps(*min, *max)) + .map(|(index, _)| index) + .collect(); + assert_eq!(found, expected, "BVH results must be complete and ordered"); + } + assert!(tested < 200 * 500 / 10, "BVH tested {tested} boxes"); + + let mut found = vec![42]; + BoundsBvh::build([]).query(|_, _| true, &mut found); + assert_eq!(found, [42], "an empty BVH adds nothing"); +} + +#[test] +fn edge_and_vertex_bvhs_keep_every_primitive_within_tolerance() { + let mut random = Lcg(11); + let mut segments = Vec::new(); + for _ in 0..600 { + let start = random.point(-8.0, 8.0); + let end = start + random.point(-1.5, 1.5); + segments.extend([start.to_array(), end.to_array()]); + } + let points: Vec<[f32; 3]> = (0..400) + .map(|_| random.point(-8.0, 8.0).to_array()) + .collect(); + let mesh = Mesh::new(Vec::new(), Vec::new(), Vec::new(), segments, points); + let transform = Mat4::from_scale_rotation_translation( + Vec3::new(1.2, 0.8, 1.0), + Quat::from_euler(EulerRot::XYZ, 0.4, -0.3, 0.9), + Vec3::new(1.0, -2.0, 0.5), + ); + let (aspect, viewport) = (1.5, Vec2::new(900.0, 600.0)); + + let (mut kept, mut total) = (0, 0); + for camera in test_cameras() { + let view_projection = camera.view_projection(aspect); + let screen = |point: &[f32; 3]| { + project_with( + view_projection, + transform.transform_point3(Vec3::from_array(*point)), + ) + .map(|ndc| ndc_to_px(ndc.truncate(), viewport)) + }; + for pointer in pointer_grid(15) { + let pointer_px = ndc_to_px(pointer, viewport); + let near_pointer = |min, max| { + projected_bounds_hit(view_projection, viewport, pointer_px, transform, min, max) + }; + let (mut edges, mut vertices) = (Vec::new(), Vec::new()); + mesh.edge_bvh().query(near_pointer, &mut edges); + mesh.vertex_bvh().query(near_pointer, &mut vertices); + + for (index, segment) in mesh.edges.as_chunks::<2>().0.iter().enumerate() { + if let (Some(a), Some(b)) = (screen(&segment[0]), screen(&segment[1])) + && distance_to_segment(pointer_px, a, b).0 <= PICK_TOLERANCE_PX + { + assert!(edges.contains(&index), "edge {index} pruned at {pointer}"); + } + } + for (index, point) in mesh.pick_vertices().iter().enumerate() { + if screen(point).is_some_and(|p| p.distance(pointer_px) <= PICK_TOLERANCE_PX) { + assert!( + vertices.contains(&index), + "vertex {index} pruned at {pointer}" + ); + } + } + kept += edges.len() + vertices.len(); + total += mesh.edges.len() / 2 + mesh.pick_vertices().len(); + } + } + assert!(kept * 5 < total, "kept {kept} of {total} primitives"); +} + +#[test] +fn indexed_picking_matches_a_linear_scan() { + let scene = mixed_assembly(); + let mut index = SceneIndex::default(); + index.update(&scene); + let (aspect, viewport) = (1.5, Vec2::new(900.0, 600.0)); + + let mut hits = 0; + for camera in test_cameras() { + for mode in MODES { + for pointer in pointer_grid(11) { + let linear = pick( + &camera, + aspect, + pointer, + viewport, + mode, + all_candidates(&scene), + ); + let candidates = + indexed_candidates(&index, &scene, &camera, aspect, pointer, viewport, mode); + let indexed = pick(&camera, aspect, pointer, viewport, mode, candidates); + assert_eq!(indexed, linear, "{mode:?} at {pointer} with {camera:?}"); + hits += usize::from(linear.is_some()); + } + } + } + assert!(hits > 400, "the sweep must hit geometry, got {hits} hits"); +} + +#[test] +fn coincident_parts_resolve_to_scene_order() { + let scene = mixed_assembly(); + let mut index = SceneIndex::default(); + index.update(&scene); + let camera = top_camera(); + let first = scene.nodes[0].parts[0] + .transform + .transform_point3(Vec3::ZERO); + let pointer = project_with(camera.view_projection(1.0), first) + .unwrap() + .truncate(); + let viewport = Vec2::splat(800.0); + + let candidates = indexed_candidates( + &index, + &scene, + &camera, + 1.0, + pointer, + viewport, + SelectionMode::Face, + ); + let hit = pick( + &camera, + 1.0, + pointer, + viewport, + SelectionMode::Face, + candidates, + ); + assert_eq!(hit.map(|hit| hit.id.0), Some("p0".to_string())); +} + +#[test] +fn scene_index_returns_candidates_in_scene_order() { + // Later parts sit lower, so a spatial sort alone would reverse them. + let plate = Arc::new(square(0.0, 1.0)); + let scene = scene_of( + (0..32) + .map(|i| translated(&format!("p{i}"), &plate, Vec3::Z * (i as f32 * -0.25))) + .collect(), + ); + let mut index = SceneIndex::default(); + index.update(&scene); + let found = index.query( + &top_camera(), + 1.0, + Vec2::ZERO, + Vec2::splat(800.0), + SelectionMode::Face, + ); + assert_eq!(found, (0..32).collect::>()); +} + +#[test] +fn scene_index_rebuilds_only_when_pickable_geometry_changes() { + let plate = Arc::new(square(0.0, 1.0)); + let camera = top_camera(); + let viewport = Vec2::splat(1000.0); + // 1 world unit is 50 px with the top camera. + let at = |x: f32| Vec2::new(x / camera.extent, 0.0); + let keys = |index: &SceneIndex, scene: &Scene, x: f32| -> Vec { + index + .query(&camera, 1.0, at(x), viewport, SelectionMode::Auto) + .into_iter() + .filter_map(|found| index.candidate(scene, found)) + .map(|candidate| candidate.id.0) + .collect() + }; + + let mut scene = scene_of(vec![ + translated("a", &plate, Vec3::X * -3.0), + translated("b", &plate, Vec3::X * 3.0), + ]); + let mut index = SceneIndex::default(); + assert!(index.update(&scene)); + assert!(!index.update(&scene), "an unchanged scene keeps its index"); + scene.select_only("a"); + scene.set_visible("a", true); + assert!( + !index.update(&scene), + "selection and no-op visibility changes keep the index" + ); + assert_eq!(index.rebuild_count(), 1); + assert_eq!(keys(&index, &scene, -3.0), ["a"]); + + scene.set_visible("a", false); + assert!(index.update(&scene)); + assert!( + keys(&index, &scene, -3.0).is_empty(), + "hidden parts are skipped" + ); + + scene.append(vec![translated("c", &plate, Vec3::ZERO)], None); + assert!(index.update(&scene)); + assert_eq!(keys(&index, &scene, 0.0), ["c"]); + + scene.remove_top_level(&["c".to_string()]); + assert!(index.update(&scene)); + assert!(keys(&index, &scene, 0.0).is_empty()); + + scene.clear(); + assert!(index.update(&scene)); + assert!(keys(&index, &scene, 3.0).is_empty()); + assert_eq!(index.rebuild_count(), 5); + + // Two scenes built the same way never share a revision. + let left = scene_of(vec![translated("left", &plate, Vec3::X * -3.0)]); + let right = scene_of(vec![translated("right", &plate, Vec3::X * 3.0)]); + assert!(index.update(&left)); + assert!(index.update(&right), "another scene must rebuild the index"); + assert_eq!(keys(&index, &right, 3.0), ["right"]); +} + +#[test] +fn scene_index_never_returns_a_part_under_another_key() { + let plate = Arc::new(square(0.0, 1.0)); + let mut scene = scene_of(vec![ + translated("a", &plate, Vec3::X * -3.0), + translated("b", &plate, Vec3::X * 3.0), + ]); + let mut index = SceneIndex::default(); + index.update(&scene); + // Bypasses the pick revision on purpose, as a future caller might. + scene.nodes.swap(0, 1); + assert!(index.candidate(&scene, 0).is_none()); + assert!(index.candidate(&scene, 1).is_none()); +} + +/// `side` x `side` instances of one shared mesh, spaced 3 units apart. +fn instanced_grid(mesh: &Arc, side: usize) -> Scene { + scene_of( + (0..side * side) + .map(|i| { + let offset = Vec3::new((i % side) as f32 * 3.0, (i / side) as f32 * 3.0, 0.0); + let transform = + Mat4::from_rotation_translation(Quat::from_rotation_z(i as f32 * 0.37), offset); + node(&format!("p{i}"), vec![part(mesh, transform)], Vec::new()) + }) + .collect(), + ) +} + +/// An isometric view fitting the whole grid. +fn grid_camera(side: usize) -> Camera { + let center = Vec3::new(1.5, 1.5, 0.0) * (side as f32 - 1.0); + Camera { + target: center, + rotation: StandardView::Iso.rotation(), + extent: side as f32 * 2.2, + scene_center: center, + scene_radius: side as f32 * 2.2, + ..Camera::default() + } +} + +#[test] +fn scene_index_work_grows_slowly_with_the_part_count() { + let plate = Arc::new(square(0.0, 1.0)); + let mut work = Vec::new(); + for side in [16, 64] { + let scene = instanced_grid(&plate, side); + let mut index = SceneIndex::default(); + index.update(&scene); + let camera = grid_camera(side); + let mut total = 0; + for pointer in pointer_grid(9) { + let (_, stats) = index.query_with_stats( + &camera, + 1.0, + pointer, + Vec2::splat(1000.0), + SelectionMode::Auto, + ); + total += stats.visited_nodes + stats.tested_bounds; + } + work.push(total / 81); + } + let (small, large) = (work[0], work[1]); + // 16x more parts (256 -> 4096) must cost far less than 16x the work. + assert!(large < small * 3, "{small} -> {large} visited per query"); + assert!(large < 4096 / 20, "{large} visited per query of 4096 parts"); +} + +/// A meshed cylinder shaped like worker output: side and caps are faces +/// 1-3, both circles and the seam are edges 1-3, plus two vertices. +fn cylinder(segments: u32) -> Mesh { + let ring_point = |i: u32, z: f32| { + let angle = i as f32 / segments as f32 * TAU; + [angle.cos(), angle.sin(), z] + }; + let positions: Vec<[f32; 3]> = (0..segments) + .map(|i| ring_point(i, 0.0)) + .chain((0..segments).map(|i| ring_point(i, 2.0))) + .collect(); + let n = segments; + let (mut indices, mut triangle_faces) = (Vec::new(), Vec::new()); + for i in 0..n { + let j = (i + 1) % n; + indices.extend([i, j, n + j, i, n + j, n + i]); + triangle_faces.extend([1, 1]); + } + for i in 1..n - 1 { + indices.extend([0, i + 1, i, n, n + i, n + i + 1]); + triangle_faces.extend([2, 3]); + } + let (mut edges, mut segment_edges) = (Vec::new(), Vec::new()); + for (edge, z) in [(1, 0.0), (2, 2.0)] { + for i in 0..n { + edges.extend([ring_point(i, z), ring_point(i + 1, z)]); + segment_edges.push(edge); + } + } + edges.extend([[1.0, 0.0, 0.0], [1.0, 0.0, 2.0]]); + segment_edges.push(3); + + let normals = vec![[0.0, 0.0, 1.0]; positions.len()]; + let mut mesh = Mesh::new(positions, normals, indices, edges, Vec::new()); + mesh.topology.face_positions = mesh.positions.clone(); + mesh.topology.face_indices = mesh.indices.clone(); + mesh.topology.triangle_faces = triangle_faces; + mesh.topology.segment_edges = segment_edges; + mesh.topology.vertices = vec![[1.0, 0.0, 0.0], [1.0, 0.0, 2.0]]; + mesh +} + +/// A pointer sweeping across the view, as during a mouse move. +fn sweep() -> Vec { + (0..240) + .map(|i| { + let t = i as f32 / 239.0; + Vec2::new(-0.6 + 1.2 * t, 0.3 * (t * 15.0).sin()) + }) + .collect() +} + +fn latency_summary(mut samples: Vec) -> String { + samples.sort_unstable(); + let micros = |d: Duration| d.as_secs_f64() * 1e6; + format!( + "{:>10.1} {:>10.1} {:>10.1}", + micros(samples[samples.len() / 2]), + micros(samples[samples.len() * 95 / 100]), + micros(samples[samples.len() - 1]), + ) +} + +/// Hover latency on growing assemblies, linear scan against the indexed +/// broad phase. Run with +/// `cargo test --release pick_latency -- --ignored --nocapture`. +#[test] +#[ignore = "benchmark; run explicitly in release mode"] +fn pick_latency_on_growing_assemblies() { + println!( + "environment: cq-editor={} os={} arch={} profile={} logical_cpus={}", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS, + std::env::consts::ARCH, + if cfg!(debug_assertions) { + "debug" + } else { + "release" + }, + std::thread::available_parallelism().map_or(1, usize::from), + ); + let mesh = Arc::new(cylinder(48)); + let (aspect, viewport) = (1.6, Vec2::new(1600.0, 1000.0)); + let path = sweep(); + println!( + "{:>7} | {:>32} | {:>32} | {:>10}", + "parts", "linear p50 / p95 / max (us)", "indexed p50 / p95 / max (us)", "index (ms)" + ); + for side in [8, 16, 32, 64, 128] { + let scene = instanced_grid(&mesh, side); + let camera = grid_camera(side); + // Build the shared mesh's lazy BVHs outside the measurements. + pick( + &camera, + aspect, + Vec2::ZERO, + viewport, + SelectionMode::Auto, + all_candidates(&scene), + ); + + let linear: Vec<_> = path + .iter() + .map(|&pointer| { + let start = Instant::now(); + black_box(pick( + &camera, + aspect, + pointer, + viewport, + SelectionMode::Auto, + all_candidates(&scene), + )); + start.elapsed() + }) + .collect(); + + let mut index = SceneIndex::default(); + let start = Instant::now(); + index.update(&scene); + let build = start.elapsed(); + let indexed: Vec<_> = path + .iter() + .map(|&pointer| { + let start = Instant::now(); + let candidates = indexed_candidates( + &index, + &scene, + &camera, + aspect, + pointer, + viewport, + SelectionMode::Auto, + ); + black_box(pick( + &camera, + aspect, + pointer, + viewport, + SelectionMode::Auto, + candidates, + )); + start.elapsed() + }) + .collect(); + + println!( + "{:>7} | {} | {} | {:>10.2}", + side * side, + latency_summary(linear), + latency_summary(indexed), + build.as_secs_f64() * 1e3, + ); + } +} + +#[test] +fn a_section_plane_hides_what_it_removes_from_picking() { + use crate::viewer::section::ClipPlane; + let (low, high) = (square(0.0, 5.0), square(3.0, 5.0)); + let candidates = || { + [ + Candidate { + id: "low", + mesh: &low, + transform: Mat4::IDENTITY, + }, + Candidate { + id: "high", + mesh: &high, + transform: Mat4::IDENTITY, + }, + ] + }; + let camera = top_camera(); + let viewport = Vec2::splat(800.0); + let pick_with = |clip, mode| { + pick_clipped( + &camera, + 1.0, + Vec2::new(0.1, 0.1), + viewport, + mode, + candidates(), + clip, + ) + .map(|hit| hit.id) + }; + + assert_eq!(pick_with(None, SelectionMode::Face), Some("high")); + // Everything above z = 1 is removed: the low square is picked. + let top_off = Some(ClipPlane { + normal: Vec3::Z, + offset: 1.0, + }); + assert_eq!(pick_with(top_off, SelectionMode::Face), Some("low")); + // Everything below z = 1 removed instead. + let bottom_off = Some(ClipPlane { + normal: Vec3::NEG_Z, + offset: -1.0, + }); + assert_eq!(pick_with(bottom_off, SelectionMode::Face), Some("high")); + // Removing everything leaves nothing to pick, edges included. + let all_off = Some(ClipPlane { + normal: Vec3::Z, + offset: -10.0, + }); + assert_eq!(pick_with(all_off, SelectionMode::Auto), None); +} + +#[test] +fn removed_edges_and_vertices_cannot_be_picked() { + use crate::viewer::section::ClipPlane; + let mesh = square(3.0, 5.0); + let camera = top_camera(); + let viewport = Vec2::splat(1000.0); + let corner = Vec2::new(0.5, 0.5); + let pick_at = |clip| { + pick_clipped( + &camera, + 1.0, + corner, + viewport, + SelectionMode::Vertex, + [Candidate { + id: (), + mesh: &mesh, + transform: Mat4::IDENTITY, + }], + clip, + ) + .and_then(|hit| hit.entity) + }; + assert_eq!(pick_at(None), Some(TopologyEntity::Vertex(3))); + let removed = Some(ClipPlane { + normal: Vec3::Z, + offset: 1.0, + }); + assert_eq!(pick_at(removed), None); +} + +#[test] +fn exploded_and_isolated_parts_are_picked_where_they_are_shown() { + let plate = Arc::new(square(0.0, 1.0)); + let mut scene = scene_of(vec![ + translated("left", &plate, Vec3::new(-3.0, 0.0, 0.0)), + translated("right", &plate, Vec3::new(3.0, 0.0, 0.0)), + ]); + let camera = Camera { + rotation: StandardView::Top.rotation(), + extent: 20.0, + ..Camera::default() + }; + let viewport = Vec2::splat(800.0); + let mut index = SceneIndex::default(); + let mut pick_at = |scene: &Scene, x: f32| { + index.update(scene); + // 20 units from the centre to the edge: x / 20 in NDC. + let pointer = Vec2::new(x / 20.0, 0.0); + let candidates = indexed_candidates( + &index, + scene, + &camera, + 1.0, + pointer, + viewport, + SelectionMode::Object, + ); + pick( + &camera, + 1.0, + pointer, + viewport, + SelectionMode::Object, + candidates, + ) + .map(|hit| hit.id.0) + }; + assert_eq!(pick_at(&scene, 3.5).as_deref(), Some("right")); + assert_eq!(pick_at(&scene, 9.5), None); + + // Three times as far from the centre: the right plate is around x = 9. + scene.set_explode(2.0); + assert_eq!(pick_at(&scene, 3.5), None); + assert_eq!(pick_at(&scene, 9.5).as_deref(), Some("right")); + + scene.isolate(&["left".to_owned()]); + assert_eq!(pick_at(&scene, 9.5), None, "isolated out"); + // The explosion centres on what is shown: alone, the plate is at home. + assert_eq!(pick_at(&scene, -9.5), None); + assert_eq!(pick_at(&scene, -3.5).as_deref(), Some("left")); +} diff --git a/tests/rust/viewer/test_renderer.rs b/tests/rust/viewer/test_renderer.rs new file mode 100644 index 000000000..0b4975768 --- /dev/null +++ b/tests/rust/viewer/test_renderer.rs @@ -0,0 +1,1325 @@ +use super::*; + +/// WGSL source parsed and validated by wgpu's own front end. +fn validated(source: &str) -> naga::Module { + let module = naga::front::wgsl::parse_str(source) + .unwrap_or_else(|error| panic!("{}", error.emit_to_string(source))); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::empty(), + ) + .validate(&module) + .unwrap_or_else(|error| panic!("invalid WGSL: {error:?}")); + module +} + +/// The scene shaders. +fn scene_module() -> naga::Module { + validated(include_str!("../../../src/viewer/shaders.wgsl")) +} + +/// The size WGSL lays out for the uniform variable `name`. +fn uniform_size(module: &naga::Module, name: &str) -> u32 { + let mut layouter = naga::proc::Layouter::default(); + layouter.update(module.to_ctx()).unwrap(); + let (_, variable) = module + .global_variables + .iter() + .find(|(_, variable)| variable.name.as_deref() == Some(name)) + .unwrap_or_else(|| panic!("no uniform {name}")); + layouter[variable.ty].size +} + +#[test] +fn the_scene_shaders_are_valid_wgsl_with_every_entry_point() { + let module = scene_module(); + let entry_points: Vec<&str> = module + .entry_points + .iter() + .map(|entry| entry.name.as_str()) + .collect(); + for name in [ + "vs_background", + "fs_background", + "vs_mesh", + "fs_mesh", + "fs_section_count", + "vs_cap", + "fs_cap", + "vs_edge", + "fs_edge", + "fs_hidden_edge", + "vs_point", + "fs_point", + ] { + assert!(entry_points.contains(&name), "missing entry point {name}"); + } +} + +#[test] +fn uniform_blocks_match_their_wgsl_layout() { + let module = scene_module(); + assert_eq!( + uniform_size(&module, "camera") as usize, + std::mem::size_of::() + ); + assert_eq!( + uniform_size(&module, "object") as usize, + std::mem::size_of::() + ); +} + +#[test] +fn the_stereo_shader_is_valid_wgsl_matching_its_uniform() { + let module = validated(include_str!("../../../src/viewer/stereo.wgsl")); + let entry_points: Vec<&str> = module + .entry_points + .iter() + .map(|entry| entry.name.as_str()) + .collect(); + assert_eq!(entry_points, ["vs_compose", "fs_compose"]); + assert_eq!( + uniform_size(&module, "compose") as usize, + std::mem::size_of::() + ); +} + +#[test] +fn the_present_shader_is_valid_wgsl() { + let module = validated(include_str!("../../../src/viewer/present.wgsl")); + let entry_points: Vec<&str> = module + .entry_points + .iter() + .map(|entry| entry.name.as_str()) + .collect(); + assert_eq!(entry_points, ["vs_present", "fs_present"]); +} + +// -- on a GPU ------------------------------------------------------------------ + +use std::sync::{Mutex, OnceLock, PoisonError}; + +use crate::viewer::camera::{Eye, Pose, StandardView}; +use crate::viewer::section::{Section, SectionAxis}; +use crate::viewer::{DisplayMode, PartLook}; + +const BACKGROUND: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const BACKGROUND_SRGB: [u8; 4] = [0, 0, 255, 255]; +/// Image size; the 2-unit cube spans half of it. +const SIZE: u32 = 128; + +/// A renderer on the adapter `WGPU_ADAPTER_NAME` names, or else the best +/// one wgpu finds, software adapters included (`WGPU_BACKEND` limits the +/// backends). Without any adapter there is nothing to draw on and the GPU +/// tests pass without checking anything, unless `CQ_EDITOR_REQUIRE_GPU` is +/// set to something other than `0`, as in CI on Windows, whose software +/// adapter (WARP) is always there. +fn gpu() -> Option { + let instance = + wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle().with_env()); + let adapter = match block_on(wgpu::util::initialize_adapter_from_env_or_default( + &instance, None, + )) { + Ok(adapter) => adapter, + Err(error) => { + let required = std::env::var("CQ_EDITOR_REQUIRE_GPU") + .is_ok_and(|value| !value.is_empty() && value != "0"); + assert!(!required, "no GPU adapter: {error}"); + eprintln!("no GPU adapter ({error}): skipping the rendering test"); + return None; + } + }; + eprintln!("rendering on {:?}", adapter.get_info()); + let (device, queue) = block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())) + .expect("the adapter provides a device"); + Some(SceneRenderer::with_device(device, queue, &adapter)) +} + +/// Runs a GPU test on the renderer the GPU tests share, one test at a time: +/// creating devices concurrently has crashed the software DX12 adapter. +fn with_gpu(test: impl FnOnce(&mut SceneRenderer)) { + static GPU: OnceLock>> = OnceLock::new(); + let mut gpu = GPU + .get_or_init(|| Mutex::new(gpu())) + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(renderer) = gpu.as_mut() { + test(renderer); + } +} + +/// wgpu's native futures are ready once polled; this is all they need. +fn block_on(future: F) -> F::Output { + let mut future = std::pin::pin!(future); + let mut context = std::task::Context::from_waker(std::task::Waker::noop()); + loop { + if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut context) { + return output; + } + std::thread::yield_now(); + } +} + +/// A closed cube with flat faces and its 12 edges, centred on the origin. +fn cube(half: f32) -> Mesh { + let mut positions = Vec::new(); + let mut normals = Vec::new(); + let mut indices = Vec::new(); + for axis in 0..3 { + for sign in [-1.0f32, 1.0] { + let mut normal = [0.0; 3]; + normal[axis] = sign; + let (u, v) = ((axis + 1) % 3, (axis + 2) % 3); + let base = positions.len() as u32; + for (a, b) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] { + let mut corner = [0.0; 3]; + corner[axis] = sign * half; + corner[u] = a * half; + corner[v] = b * half; + positions.push(corner); + normals.push(normal); + } + indices.extend([base, base + 1, base + 2, base, base + 2, base + 3]); + } + } + let mut edges = Vec::new(); + let corner = |bits: u32| [0, 1, 2].map(|i| if bits >> i & 1 == 1 { half } else { -half }); + for bits in 0..8u32 { + for axis in 0..3 { + if bits >> axis & 1 == 0 { + edges.extend([corner(bits), corner(bits | 1 << axis)]); + } + } + } + assert_eq!(edges.len(), 24); + Mesh::new(positions, normals, indices, edges, Vec::new()) +} + +/// A red cube with black edges, as `DisplayMode::Shaded` draws it. +fn red() -> Style { + Style { + face_color: [1.0, 0.0, 0.0, 1.0], + edge_color: [0.0, 0.0, 0.0, 1.0], + highlight: [0.0; 4], + edge_width: 1.5, + point_size: 1.0, + faces: true, + edges: false, + points: false, + clipped: true, + background_fill: false, + hidden_edges: false, + edge_min_angle: 0.0, + silhouettes: false, + surface: [0.0; 4], + } +} + +/// The style a display mode gives the red cube. +fn in_mode(mode: DisplayMode) -> Style { + let settings = crate::settings::Viewer::default(); + let look = PartLook { + face_color: [1.0, 0.0, 0.0, 1.0], + edge_color: [0.0, 0.0, 0.0, 1.0], + highlight: [0.0; 4], + has_faces: true, + emphasized: false, + edges: None, + finish: crate::settings::Finish::Default, + }; + mode.style(look, &settings, &crate::settings::Rendering::default()) +} + +struct Frame { + side: u32, + pixels: Vec, +} + +impl Frame { + fn at(&self, x: u32, y: u32) -> [u8; 4] { + let start = ((y * self.side + x) * 4) as usize; + <[u8; 4]>::try_from(&self.pixels[start..start + 4]).unwrap() + } +} + +/// Renders the 2-unit cube from `view` in a `SIZE` square image whose +/// half-height is 2 units. +fn draw( + renderer: &mut SceneRenderer, + view: StandardView, + style: Style, + section: Option
, +) -> Frame { + draw_sized(renderer, view, style, section, SIZE, 1.0, BACKGROUND) +} + +/// `draw` in a `side` square image, with widths times `pixel_scale`. +fn draw_sized( + renderer: &mut SceneRenderer, + view: StandardView, + style: Style, + section: Option
, + side: u32, + pixel_scale: f32, + background: [f32; 4], +) -> Frame { + draw_lit( + renderer, + view, + style, + section, + side, + pixel_scale, + background, + Lighting::default(), + ) +} + +/// `draw_sized` with `lighting`. +#[allow(clippy::too_many_arguments)] +fn draw_lit( + renderer: &mut SceneRenderer, + view: StandardView, + style: Style, + section: Option
, + side: u32, + pixel_scale: f32, + background: [f32; 4], + lighting: Lighting, +) -> Frame { + let mesh = Arc::new(cube(1.0)); + let bounds = mesh.bounds; + let mut camera = Camera { + scene_radius: 2.0, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::ZERO, + rotation: view.rotation(), + extent: 2.0, + }); + let items = [DrawItem { + mesh, + transform: Mat4::IDENTITY, + style, + layer: Layer::Scene, + }]; + let (size, pixels) = renderer + .render_pixels(&FrameInput { + camera: &camera, + size: [side, side], + background_top: background, + background_bottom: background, + items: &items, + section: section.and_then(|section| section.renderer_plane(bounds)), + pixel_scale, + eye: Eye::Center, + lighting, + ground_shadow: None, + }) + .expect("the frame is read back"); + assert_eq!(size, [side, side]); + Frame { side, pixels } +} + +fn cut(offset: f32, caps: bool) -> Option
{ + Some(Section { + enabled: true, + axis: SectionAxis::Z, + offset, + flipped: false, + caps, + }) +} + +const CENTER: u32 = SIZE / 2; + +#[test] +fn reference_guides_stay_behind_opaque_models_on_the_gpu() { + with_gpu(|renderer| { + let solid = Arc::new(cube(1.0)); + let guide = Arc::new(Mesh::lines(vec![[-2.0, 0.0, 2.0], [2.0, 0.0, 2.0]])); + let guide_style = Style { + face_color: [0.0; 4], + edge_color: [0.0, 1.0, 0.0, 1.0], + highlight: [0.0; 4], + edge_width: 7.0, + point_size: 1.0, + faces: false, + edges: true, + points: false, + clipped: false, + background_fill: false, + hidden_edges: false, + edge_min_angle: 0.0, + silhouettes: false, + surface: [0.0; 4], + }; + let mut camera = Camera { + scene_radius: 4.0, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::ZERO, + rotation: StandardView::Top.rotation(), + extent: 2.0, + }); + let render = |renderer: &mut SceneRenderer, guide_layer: Option| { + let mut items = vec![DrawItem { + mesh: solid.clone(), + transform: Mat4::IDENTITY, + style: red(), + layer: Layer::Scene, + }]; + if let Some(layer) = guide_layer { + items.push(DrawItem { + mesh: guide.clone(), + transform: Mat4::IDENTITY, + style: guide_style, + layer, + }); + } + renderer + .render_pixels(&FrameInput { + camera: &camera, + size: [SIZE, SIZE], + background_top: BACKGROUND, + background_bottom: BACKGROUND, + items: &items, + section: None, + pixel_scale: 1.0, + eye: Eye::Center, + lighting: Lighting::default(), + ground_shadow: None, + }) + .unwrap() + .1 + }; + + let model = render(renderer, None); + let reference = render(renderer, Some(Layer::Reference)); + let scene_line = render(renderer, Some(Layer::Scene)); + let center = ((CENTER * SIZE + CENTER) * 4) as usize; + let pixel = |frame: &[u8]| <[u8; 4]>::try_from(&frame[center..center + 4]).unwrap(); + + assert_eq!(pixel(&reference), pixel(&model)); + assert_ne!(pixel(&scene_line), pixel(&model)); + assert!( + pixel(&scene_line)[1] > pixel(&scene_line)[0], + "the control line should be green and visible over the model" + ); + }); +} + +#[test] +fn a_section_plane_cuts_the_model_and_fills_the_cut_on_the_gpu() { + with_gpu(|renderer| { + let top = |renderer: &mut SceneRenderer, style: Style, section: Option
| { + let frame = draw(renderer, StandardView::Top, style, section); + (frame.at(CENTER, CENTER), frame.at(2, 2)) + }; + + let (whole, outside) = top(renderer, red(), None); + assert_eq!(outside, BACKGROUND_SRGB); + assert!( + whole[0] > 100 && whole[2] < 50, + "the red top face: {whole:?}" + ); + + // Cut through the middle: the cap, flat and darker than a face, covers + // the opening, and the stencil leaves nothing outside the cube. + let (capped, outside) = top(renderer, red(), cut(0.0, true)); + assert_eq!(outside, BACKGROUND_SRGB); + assert!(capped[0] > 50 && capped[2] < 50, "a red cap: {capped:?}"); + assert!(capped[0] < whole[0], "the cap is darker than the top face"); + + // Without caps the inside of the bottom face shows through instead. + let (open, _) = top(renderer, red(), cut(0.0, false)); + assert_ne!(open, capped); + + // A plane under the cube removes all of it, caps included. + let (gone, _) = top(renderer, red(), cut(-5.0, true)); + assert_eq!(gone, BACKGROUND_SRGB); + + // Helpers that are not clipped stay whole. + let helper = Style { + clipped: false, + ..red() + }; + let (kept, _) = top(renderer, helper, cut(-5.0, true)); + assert_eq!(kept, whole); + }); +} + +#[test] +fn display_modes_render_faces_edges_and_fills_as_documented() { + with_gpu(|renderer| { + use DisplayMode::{HiddenLine, Shaded, Wireframe, XRay}; + + // Seen from (1, -1, 1), the near corner (1, -1, 1) and the hidden one + // (-1, 1, -1) are both at the centre. The right face (+X) is a rhombus + // to the right, cut along its diagonal by a hidden edge; (94, 62) is + // inside it, away from every edge. Another hidden edge runs straight up + // from the centre, behind the top face. + let face = |frame: &Frame| frame.at(94, 62); + let behind_top_face = |frame: &Frame| -> Vec<[u8; 4]> { + (25..52) + .flat_map(|y| [frame.at(CENTER - 1, y), frame.at(CENTER, y)]) + .collect() + }; + let iso = |renderer: &mut SceneRenderer, style: Style| { + draw(renderer, StandardView::Iso, style, None) + }; + + let shaded = iso(renderer, in_mode(Shaded)); + let lit = face(&shaded); + assert!(lit[0] > 60 && lit[2] < 40, "a lit red face: {lit:?}"); + assert!( + behind_top_face(&shaded) + .iter() + .all(|p| p[0] > 60 && p[2] < 40), + "the top face hides the edge behind it" + ); + + let wireframe = iso(renderer, in_mode(Wireframe)); + assert_eq!(face(&wireframe), BACKGROUND_SRGB, "no faces"); + assert!( + behind_top_face(&wireframe).iter().any(|p| p[2] < 200), + "every edge, the hidden one included" + ); + + let xray = iso(renderer, in_mode(XRay)); + let see_through = face(&xray); + assert!( + see_through[0] > 10 && see_through[2] > 60 && see_through != BACKGROUND_SRGB, + "red faces over the background: {see_through:?}" + ); + assert!(see_through[0] < lit[0] || see_through[2] > lit[2]); + // Through the red faces the dark edge takes out the blue background. + let blue = |frame: &Frame, x: u32| { + (25..52).map(|y| u32::from(frame.at(x, y)[2])).sum::() / 27 + }; + assert!( + blue(&xray, CENTER) + 20 < blue(&xray, CENTER + 4), + "the hidden edge shows through: {} vs {}", + blue(&xray, CENTER), + blue(&xray, CENTER + 4) + ); + + let hidden_line = iso(renderer, in_mode(HiddenLine)); + assert_eq!( + face(&hidden_line), + BACKGROUND_SRGB, + "faces are filled with the background" + ); + let dashes = behind_top_face(&hidden_line); + assert!( + dashes.iter().any(|p| *p != BACKGROUND_SRGB) && dashes.contains(&BACKGROUND_SRGB), + "the hidden edge is dashed" + ); + // The visible edge from the centre straight down is solid and dark. + assert!((80..100).all(|y| hidden_line.at(CENTER, y)[2] < 200)); + + let without_hidden = Style { + hidden_edges: false, + ..in_mode(HiddenLine) + }; + let hidden_line = iso(renderer, without_hidden); + assert!( + behind_top_face(&hidden_line) + .iter() + .all(|p| *p == BACKGROUND_SRGB), + "hidden edges removed" + ); + + // A section in hidden-line mode is hatched with the edge color. + let section = draw( + renderer, + StandardView::Top, + in_mode(HiddenLine), + cut(0.0, true), + ); + let mut hatch = Vec::new(); + for y in CENTER - 8..CENTER + 8 { + for x in CENTER - 8..CENTER + 8 { + hatch.push(section.at(x, y)); + } + } + assert!(hatch.contains(&BACKGROUND_SRGB), "between the hatch lines"); + assert!( + hatch.iter().any(|p| p[2] < 60), + "hatch lines in the edge color" + ); + }); +} + +#[test] +fn the_lights_follow_the_lighting_settings() { + with_gpu(|renderer| { + // Seen from the iso view: the top face (+Z) at (64, 40), the right + // face (+X) at (94, 62) and the left one (-Y) at (34, 62). + let iso = |renderer: &mut SceneRenderer, lighting: Lighting| { + let frame = draw_lit( + renderer, + StandardView::Iso, + red(), + None, + SIZE, + 1.0, + BACKGROUND, + lighting, + ); + [frame.at(64, 40), frame.at(94, 62), frame.at(34, 62)].map(|p| u32::from(p[0])) + }; + let defaults = Lighting::default(); + let lit = iso(renderer, defaults); + + // Nothing but ambient light: every face the same, darker red. + let flat = iso( + renderer, + Lighting { + key: 0.0, + fill: 0.0, + rim: 0.0, + specular: 0.0, + ..defaults + }, + ); + assert!(flat[0].abs_diff(flat[1]) <= 1 && flat[1].abs_diff(flat[2]) <= 1); + assert!( + flat.iter().zip(&lit).all(|(f, l)| f < l), + "{flat:?} {lit:?}" + ); + + // One stop more light, or more contrast, changes what is lit. + let exposed = iso( + renderer, + Lighting { + exposure: 1.0, + ..defaults + }, + ); + assert!(exposed.iter().zip(&lit).all(|(e, l)| e > l || *l == 255)); + let contrasted = iso( + renderer, + Lighting { + contrast: 2.0, + ..defaults + }, + ); + assert_ne!(contrasted, lit); + + // The key light moved to the right lights the right face more than + // the left one, and the other way round. + let from = |renderer: &mut SceneRenderer, azimuth: f32| { + iso( + renderer, + Lighting { + azimuth, + elevation: 0.0, + fill: 0.0, + rim: 0.0, + specular: 0.0, + ..defaults + }, + ) + }; + let (left, right) = (from(renderer, -60.0), from(renderer, 60.0)); + assert!( + right[1] > right[2] && left[2] > left[1], + "{left:?} {right:?}" + ); + }); +} + +/// An open tube of radius 1 along Z, from -1 to 1, with smooth normals. +fn tube(sides: u32) -> Mesh { + let mut positions = Vec::new(); + let mut normals = Vec::new(); + for side in 0..sides { + let angle = side as f32 / sides as f32 * std::f32::consts::TAU; + let (y, x) = angle.sin_cos(); + for z in [-1.0, 1.0] { + positions.push([x, y, z]); + normals.push([x, y, 0.0]); + } + } + let mut indices = Vec::new(); + for side in 0..sides { + let (a, b) = (side * 2, (side + 1) % sides * 2); + indices.extend([a, b, b + 1, a, b + 1, a + 1]); + } + Mesh::new(positions, normals, indices, Vec::new(), Vec::new()) +} + +/// Renders `mesh` from `view` with `style` in a `SIZE` image, 32 pixels per +/// unit. +fn render_mesh( + renderer: &mut SceneRenderer, + mesh: Mesh, + view: StandardView, + style: Style, +) -> Frame { + render_placed(renderer, mesh, Mat4::IDENTITY, view, style) +} + +/// `render_mesh` with the mesh placed by `transform`. +fn render_placed( + renderer: &mut SceneRenderer, + mesh: Mesh, + transform: Mat4, + view: StandardView, + style: Style, +) -> Frame { + let mut camera = Camera { + scene_radius: 2.0, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::ZERO, + rotation: view.rotation(), + extent: 2.0, + }); + let items = [DrawItem { + mesh: Arc::new(mesh), + transform, + style, + layer: Layer::Scene, + }]; + let (_, pixels) = renderer + .render_pixels(&FrameInput { + camera: &camera, + size: [SIZE, SIZE], + background_top: BACKGROUND, + background_bottom: BACKGROUND, + items: &items, + section: None, + pixel_scale: 1.0, + eye: Eye::Center, + lighting: Lighting::default(), + ground_shadow: None, + }) + .expect("the frame is read back"); + Frame { side: SIZE, pixels } +} + +#[test] +fn edges_whose_faces_meet_smoothly_are_left_out_on_the_gpu() { + with_gpu(|renderer| { + // Two edges seen from the top: y = 1 between faces meeting smoothly + // (0°), y = -1 at a right angle (90°). + let lines = || { + let mut mesh = Mesh::lines(vec![ + [-1.5, 1.0, 0.0], + [1.5, 1.0, 0.0], + [-1.5, -1.0, 0.0], + [1.5, -1.0, 0.0], + ]); + mesh.segment_angles = vec![0.0, 90.0]; + mesh + }; + let style = |edge_min_angle| Style { + faces: false, + edges: true, + edge_width: 3.0, + edge_min_angle, + ..red() + }; + // Rows 32 (y = 1) and 96 (y = -1) of the top view. + let drawn = |frame: &Frame, row: u32| frame.at(CENTER, row) != BACKGROUND_SRGB; + + let every = render_mesh(renderer, lines(), StandardView::Top, style(0.0)); + assert!(drawn(&every, 32) && drawn(&every, 96), "every edge"); + let sharp = render_mesh(renderer, lines(), StandardView::Top, style(30.0)); + assert!(!drawn(&sharp, 32), "the smooth edge is left out"); + assert!(drawn(&sharp, 96), "the sharp edge stays"); + }); +} + +#[test] +fn curved_surfaces_get_an_outline_on_the_gpu() { + with_gpu(|renderer| { + // From the front the tube spans x = 32…96 and its outline is the + // two vertical sides, where its surface turns away. + let dark_columns = |frame: &Frame| -> Vec { + (16..112) + .filter(|&x| { + let p = frame.at(x, CENTER); + p[0] < 40 && p[2] < 40 + }) + .collect() + }; + let style = |silhouettes| Style { + edges: true, + silhouettes, + edge_width: 2.0, + ..red() + }; + let plain = render_mesh(renderer, tube(48), StandardView::Front, style(false)); + assert!(dark_columns(&plain).is_empty(), "no outline without it"); + + let outlined = render_mesh(renderer, tube(48), StandardView::Front, style(true)); + let dark = dark_columns(&outlined); + assert!( + dark.iter().any(|&x| (29..=35).contains(&x)), + "the left side: {dark:?}" + ); + assert!( + dark.iter().any(|&x| (93..=99).contains(&x)), + "the right side: {dark:?}" + ); + assert!( + dark.iter().all(|&x| x <= 35 || x >= 93), + "nothing across the surface: {dark:?}" + ); + // Outlines follow edges: no edges, no outline. + let hidden = render_mesh( + renderer, + tube(48), + StandardView::Front, + Style { + edges: false, + ..style(true) + }, + ); + assert!(dark_columns(&hidden).is_empty()); + }); +} + +/// A ball of `radius` with smooth normals. +fn ball(radius: f32) -> Mesh { + let (rings, segments) = (32u32, 64u32); + let mut positions = Vec::new(); + let mut normals = Vec::new(); + for ring in 0..=rings { + let polar = std::f32::consts::PI * ring as f32 / rings as f32; + for segment in 0..=segments { + let azimuth = std::f32::consts::TAU * segment as f32 / segments as f32; + let normal = [ + polar.sin() * azimuth.cos(), + polar.sin() * azimuth.sin(), + polar.cos(), + ]; + positions.push(normal.map(|c| c * radius)); + normals.push(normal); + } + } + let mut indices = Vec::new(); + let row = segments + 1; + for ring in 0..rings { + for segment in 0..segments { + let a = ring * row + segment; + let (b, c, d) = (a + 1, a + row, a + row + 1); + indices.extend([a, c, b, b, c, d]); + } + } + Mesh::new(positions, normals, indices, Vec::new(), Vec::new()) +} + +#[test] +fn materials_change_how_faces_are_shaded_on_the_gpu() { + use crate::settings::Finish; + with_gpu(|renderer| { + // A grey ball of radius 1.2 (38 px), or a 40-unit one drawn as + // small, whose wood grain is in its own units. + let grey = [0.3, 0.3, 0.3, 1.0]; + let shade = |renderer: &mut SceneRenderer, finish: Finish, big: bool| { + let style = Style { + face_color: grey, + surface: finish.surface(), + ..red() + }; + let (mesh, scale) = if big { + (ball(40.0), 0.03) + } else { + (ball(1.2), 1.0) + }; + let frame = render_placed( + renderer, + mesh, + Mat4::from_scale(Vec3::splat(scale)), + StandardView::Front, + style, + ); + // The square inside the ball, row by row. + (CENTER - 26..CENTER + 26) + .flat_map(|y| (CENTER - 26..CENTER + 26).map(move |x| (x, y))) + .map(|(x, y)| frame.at(x, y)) + .collect::>() + }; + let brightest = |pixels: &[[u8; 4]]| pixels.iter().map(|p| p[1]).max().unwrap(); + let unevenness = |row: &[[u8; 4]]| { + row.windows(2) + .map(|pair| u32::from(pair[0][1].abs_diff(pair[1][1]))) + .sum::() + }; + + let matte = shade(renderer, Finish::MattePlastic, false); + let glossy = shade(renderer, Finish::GlossyPlastic, false); + assert!( + brightest(&glossy) > brightest(&matte) + 40, + "a glossy highlight: {} vs {}", + brightest(&glossy), + brightest(&matte) + ); + // A metal reflects the studio around it in its own color. + let steel = shade(renderer, Finish::BrushedSteel, false); + assert_ne!(steel, matte); + // Default stays the plain shading. + let plain = shade(renderer, Finish::Default, false); + let red_style = in_mode(DisplayMode::Shaded); + assert_eq!(red_style.surface, [0.0; 4]); + assert_ne!(plain, matte); + // Wood has a grain where matte plastic of its color is even. + let wood = shade(renderer, Finish::Wood, true); + let matte_big = shade(renderer, Finish::MattePlastic, true); + assert!( + unevenness(&wood) > 2 * unevenness(&matte_big) + 20, + "a grain: {} vs {}", + unevenness(&wood), + unevenness(&matte_big) + ); + }); +} + +#[test] +fn annotated_face_color_overrides_the_part_color_on_the_gpu() { + with_gpu(|renderer| { + let style = Style { + face_color: [0.3, 0.3, 0.3, 1.0], + ..red() + }; + let plain = render_placed( + renderer, + cube(1.0), + Mat4::IDENTITY, + StandardView::Iso, + style, + ); + let mut painted = cube(1.0); + painted.vertex_colors = vec![0xff00_00ff; painted.positions.len()]; + let colored = render_placed(renderer, painted, Mat4::IDENTITY, StandardView::Iso, style); + // A single pixel at the center can land on a dark triangle edge on + // software renderers. Check the visible face instead. + let colored_face_pixels = plain + .pixels + .as_chunks::<4>() + .0 + .iter() + .zip(colored.pixels.as_chunks::<4>().0) + .filter(|(plain, colored)| { + plain != colored && colored[0] > colored[1].saturating_add(50) + }) + .count(); + let changed_pixels = plain + .pixels + .as_chunks::<4>() + .0 + .iter() + .zip(colored.pixels.as_chunks::<4>().0) + .filter(|(plain, colored)| plain != colored) + .count(); + assert!( + colored_face_pixels > 100, + "{colored_face_pixels} colored face pixels; {changed_pixels} changed pixels" + ); + }); +} + +#[test] +fn a_ground_shadow_darkens_the_floor_around_the_model_on_the_gpu() { + use crate::viewer::shadow::GroundShadow; + with_gpu(|renderer| { + let grey = [0.7, 0.7, 0.7, 1.0]; + let render = |renderer: &mut SceneRenderer, + shadow: Option, + background: [f32; 4], + side: u32| { + let mut camera = Camera { + scene_radius: 3.0, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::ZERO, + rotation: StandardView::Iso.rotation(), + extent: 2.5, + }); + let items = [DrawItem { + mesh: Arc::new(cube(0.8)), + transform: Mat4::IDENTITY, + style: Style { + face_color: grey, + ..red() + }, + layer: Layer::Scene, + }]; + renderer + .render_pixels(&FrameInput { + camera: &camera, + size: [side, side], + background_top: background, + background_bottom: background, + items: &items, + section: None, + pixel_scale: 1.0, + eye: Eye::Center, + lighting: Lighting::default(), + ground_shadow: shadow, + }) + .unwrap() + .1 + }; + let shadow = Some(GroundShadow { + strength: 0.8, + softness: 0.5, + }); + let light = [0.9, 0.9, 0.9, 1.0]; + let plain = render(renderer, None, light, SIZE); + let shaded = render(renderer, shadow, light, SIZE); + let background = plain[0..4].to_vec(); + let pixels = |frame: &[u8]| frame.chunks(4).map(<[u8]>::to_vec).collect::>(); + let (plain, shaded) = (pixels(&plain), pixels(&shaded)); + // Outside the cube, the floor darkens under and around it. + let darkened = plain + .iter() + .zip(&shaded) + .filter(|(p, s)| **p == background && s[0] < background[0] - 20) + .count(); + assert!(darkened > 300, "{darkened} darkened floor pixels"); + // The cube is drawn as before, in front of its shadow: only the + // smoothed pixels of its outline take some of the darker floor. + let side = SIZE as usize; + let inside = |index: usize| { + let (x, y) = (index % side, index / side); + (x.saturating_sub(2)..=(x + 2).min(side - 1)).all(|nx| { + (y.saturating_sub(2)..=(y + 2).min(side - 1)) + .all(|ny| plain[ny * side + nx] != background) + }) + }; + let cube_changed = (0..plain.len()) + .filter(|&index| inside(index) && plain[index] != shaded[index]) + .count(); + assert_eq!(cube_changed, 0, "cube pixels changed"); + // The corners of the image stay background. + assert_eq!(shaded[0], background); + + // On a transparent background the shadow has an alpha of its own, + // to lay the picture on anything. + let clear = render(renderer, shadow, [0.0; 4], SIZE); + let translucent = pixels(&clear) + .iter() + .filter(|p| p[3] > 20 && p[3] < 255) + .count(); + assert!(translucent > 300, "{translucent} shadow pixels"); + + // A capture drawn in tiles has the same shadow as one pass. + renderer.tile_side = SIZE / 2; + let tiled = render(renderer, shadow, light, SIZE); + renderer.tile_side = TILE_SIDE; + let whole = render(renderer, shadow, light, SIZE); + // Tiled projections may round one channel by one sRGB level on a + // different GPU backend. + assert_eq!(tiled.len(), whole.len()); + let changed_channels = tiled + .iter() + .zip(&whole) + .filter(|(a, b)| a.abs_diff(**b) > 1) + .count(); + assert_eq!( + changed_channels, 0, + "shadow tiles differ by more than one level" + ); + }); +} + +#[test] +fn large_captures_are_drawn_in_tiles_that_match_one_pass() { + with_gpu(|renderer| { + let style = in_mode(DisplayMode::Shaded); + let whole = draw(renderer, StandardView::Iso, style, None); + // Tiles of 48 pixels: three by three, the last ones reaching past + // the image. + renderer.tile_side = 48; + let tiled = draw(renderer, StandardView::Iso, style, None); + let hatched = draw( + renderer, + StandardView::Top, + in_mode(DisplayMode::HiddenLine), + cut(0.0, true), + ); + renderer.tile_side = TILE_SIDE; + let hatched_whole = draw( + renderer, + StandardView::Top, + in_mode(DisplayMode::HiddenLine), + cut(0.0, true), + ); + + for (a, b) in [(&whole, &tiled), (&hatched_whole, &hatched)] { + let differences = a + .pixels + .as_chunks::<4>() + .0 + .iter() + .zip(b.pixels.as_chunks::<4>().0) + .filter(|(a, b)| a.iter().zip(b.iter()).any(|(a, b)| a.abs_diff(*b) > 2)) + .count(); + assert!( + differences <= (SIZE * SIZE / 500) as usize, + "{differences} pixels differ between the tiled and the whole image" + ); + } + }); +} + +#[test] +fn captures_leave_out_a_transparent_background_and_scale_edges() { + with_gpu(|renderer| { + let style = in_mode(DisplayMode::Shaded); + let transparent = draw_sized( + renderer, + StandardView::Iso, + style, + None, + SIZE, + 1.0, + [0.0; 4], + ); + assert_eq!(transparent.at(2, 2), [0, 0, 0, 0], "no background"); + assert_eq!(transparent.at(94, 62)[3], 255, "an opaque face"); + let silhouette = transparent + .pixels + .as_chunks::<4>() + .0 + .iter() + .filter(|pixel| (1..255).contains(&pixel[3])) + .count(); + // Without multisampling a pixel is covered or not. + if renderer.samples() > 1 { + assert!(silhouette > 0, "antialiased edges are partly transparent"); + } + + // Twice the size with twice the width: the visible edge straight + // down from the centre is twice as wide. Its width is measured as + // its coverage over the faces on either side, in linear space, so + // it does not depend on how the edge falls on the pixels. + let edge_width = |frame: &Frame, y: u32| -> f32 { + let linear = |c: u8| (f32::from(c) / 255.0).powf(2.2); + let (center, reach) = (frame.side / 2, frame.side / 16); + let face = |x: u32| linear(frame.at(x, y)[0]); + let (left, right) = (face(center - reach), face(center + reach)); + (center - reach..center + reach) + .map(|x| 1.0 - face(x) / if x < center { left } else { right }) + .sum() + }; + let small = draw(renderer, StandardView::Iso, style, None); + let large = draw_sized( + renderer, + StandardView::Iso, + style, + None, + SIZE * 2, + 2.0, + BACKGROUND, + ); + let (thin, thick) = (edge_width(&small, 90), edge_width(&large, 180)); + // Whole pixels without multisampling: 2 for 1.5, 3 or 4 for 3. + let (expected, tolerance) = if renderer.samples() > 1 { + ((1.5, 0.4), 0.25) + } else { + ((2.0, 0.6), 0.6) + }; + assert!( + (thin - expected.0).abs() < expected.1, + "a 1.5 pixel edge: {thin}" + ); + assert!( + (thick / thin - 2.0).abs() < tolerance, + "{thin} then {thick}" + ); + }); +} + +#[test] +fn parts_out_of_view_are_not_drawn() { + with_gpu(|renderer| { + let mesh = Arc::new(cube(1.0)); + let mut camera = Camera { + scene_radius: 2.0, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::ZERO, + rotation: StandardView::Iso.rotation(), + extent: 2.0, + }); + let at = |offset: Vec3| DrawItem { + mesh: mesh.clone(), + transform: Mat4::from_translation(offset), + style: in_mode(DisplayMode::Shaded), + layer: Layer::Scene, + }; + let mut render = |items: &[DrawItem]| { + let pixels = renderer + .render_pixels(&FrameInput { + camera: &camera, + size: [SIZE, SIZE], + background_top: BACKGROUND, + background_bottom: BACKGROUND, + items, + section: None, + pixel_scale: 1.0, + eye: Eye::Center, + lighting: Lighting::default(), + ground_shadow: None, + }) + .unwrap() + .1; + (pixels, renderer.last_stats()) + }; + let (alone, stats) = render(&[at(Vec3::ZERO)]); + assert_eq!( + stats, + RenderStats { + drawn: 1, + culled: 0 + } + ); + let far = [ + at(Vec3::ZERO), + at(Vec3::new(100.0, 0.0, 0.0)), + at(Vec3::new(0.0, -50.0, 30.0)), + ]; + let (with_far, stats) = render(&far); + assert_eq!( + stats, + RenderStats { + drawn: 1, + culled: 2 + } + ); + assert!(alone == with_far, "skipping them changes nothing on screen"); + }); +} + +#[test] +fn stereo_modes_compose_on_the_gpu_as_the_reference_does() { + with_gpu(|renderer| { + let mesh = Arc::new(cube(1.0)); + let mut camera = Camera { + projection: crate::settings::Projection::Stereo, + scene_radius: 2.0, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::ZERO, + rotation: StandardView::Iso.rotation(), + extent: 2.0, + }); + let items = [DrawItem { + mesh, + transform: Mat4::IDENTITY, + style: in_mode(DisplayMode::Shaded), + layer: Layer::Scene, + }]; + // An odd width, so that the halves of side by side differ. + let input = FrameInput { + camera: &camera, + size: [SIZE + 1, SIZE], + background_top: BACKGROUND, + background_bottom: BACKGROUND, + items: &items, + section: None, + pixel_scale: 1.0, + eye: Eye::Center, + lighting: Lighting::default(), + ground_shadow: None, + }; + + // The eyes see the cube from places 5% of the distance apart. + let eye = |renderer: &mut SceneRenderer, eye| { + renderer + .render_pixels(&FrameInput { eye, ..input }) + .unwrap() + .1 + }; + let (left, right) = (eye(renderer, Eye::Left), eye(renderer, Eye::Right)); + let differing = left + .as_chunks::<4>() + .0 + .iter() + .zip(right.as_chunks::<4>().0) + .filter(|(a, b)| a != b) + .count(); + assert!(differing > 50, "{differing} pixels differ between the eyes"); + + for mode in crate::settings::StereoMode::ALL { + let (size, gpu) = renderer.render_stereo_gpu_pixels(&input, mode).unwrap(); + let (reference_size, reference) = renderer.render_stereo_pixels(&input, mode).unwrap(); + assert_eq!(size, reference_size); + let worst = gpu + .iter() + .zip(&reference) + .map(|(a, b)| a.abs_diff(*b)) + .max() + .unwrap(); + // Choosing texels is exact; mixing (the anaglyph) rounds. + let tolerance = if mode.shown() == crate::settings::StereoMode::Anaglyph { + 1 + } else { + 0 + }; + assert!(worst <= tolerance, "{mode:?}: off by {worst}"); + } + }); +} + +#[test] +fn egui_gets_the_same_texels_where_textures_cannot_be_viewed_as_plain() { + // OpenGL cannot view the sRGB target as plain 8-bit values, so egui is + // given a copy encoded by hand; it must hold exactly the same bytes. + with_gpu(|renderer| { + let mesh = Arc::new(cube(1.0)); + let mut camera = Camera { + scene_radius: 2.0, + ..Camera::default() + }; + camera.set_pose(Pose { + target: Vec3::ZERO, + rotation: StandardView::Iso.rotation(), + extent: 2.0, + }); + let items = [DrawItem { + mesh, + transform: Mat4::IDENTITY, + style: Style { + face_color: [1.0, 0.0, 0.0, 0.6], + ..in_mode(DisplayMode::Shaded) + }, + layer: Layer::Scene, + }]; + let (srgb, encoded) = renderer + .presented_pixels(&FrameInput { + camera: &camera, + size: [SIZE, SIZE], + // A gradient, so many levels go through the encoding. + background_top: [1.0, 0.5, 0.0, 1.0], + background_bottom: [0.0, 0.1, 0.9, 0.5], + items: &items, + section: None, + pixel_scale: 1.0, + eye: Eye::Center, + lighting: Lighting::default(), + ground_shadow: None, + }) + .unwrap(); + assert_eq!(srgb.len(), encoded.len()); + let worst = srgb + .iter() + .zip(&encoded) + .map(|(a, b)| a.abs_diff(*b)) + .max() + .unwrap(); + assert_eq!(worst, 0, "the encoded copy differs by up to {worst}"); + }); +} diff --git a/tests/rust/viewer/test_section.rs b/tests/rust/viewer/test_section.rs new file mode 100644 index 000000000..5af6d8370 --- /dev/null +++ b/tests/rust/viewer/test_section.rs @@ -0,0 +1,107 @@ +use super::*; + +fn bounds(min: [f32; 3], max: [f32; 3]) -> Aabb { + Aabb { + min: Vec3::from_array(min), + max: Vec3::from_array(max), + } +} + +fn section(axis: SectionAxis, offset: f32, flipped: bool) -> Section { + Section { + enabled: true, + axis, + offset, + flipped, + caps: true, + } +} + +#[test] +fn the_plane_removes_one_side_of_its_axis() { + let top_off = section(SectionAxis::Z, 2.0, false).clip_plane().unwrap(); + assert!(top_off.removes(Vec3::new(0.0, 0.0, 2.5))); + assert!(!top_off.removes(Vec3::new(5.0, -5.0, 1.5))); + + let bottom_off = section(SectionAxis::Z, 2.0, true).clip_plane().unwrap(); + assert!(!bottom_off.removes(Vec3::new(0.0, 0.0, 2.5))); + assert!(bottom_off.removes(Vec3::new(0.0, 0.0, 1.5))); + + let x = section(SectionAxis::X, -1.0, false).clip_plane().unwrap(); + assert!(x.removes(Vec3::new(0.0, 0.0, 0.0))); + assert!(!x.removes(Vec3::new(-2.0, 0.0, 0.0))); + + assert!(Section::default().clip_plane().is_none(), "off by default"); +} + +#[test] +fn rays_keep_only_the_part_on_the_kept_side() { + let plane = section(SectionAxis::Z, 1.0, false).clip_plane().unwrap(); + // Looking down from z = 11: the first 10 units are removed. + let (start, end) = plane + .kept_range(Vec3::new(0.0, 0.0, 11.0), Vec3::NEG_Z) + .unwrap(); + assert!((start - 10.0).abs() < 1e-5 && end == f32::INFINITY); + // Looking up from below: kept until the plane. + let (start, end) = plane.kept_range(Vec3::ZERO, Vec3::Z).unwrap(); + assert!(start == f32::NEG_INFINITY && (end - 1.0).abs() < 1e-6); + // Parallel to the plane: all or nothing. + assert!( + plane + .kept_range(Vec3::new(0.0, 0.0, 5.0), Vec3::X) + .is_none() + ); + assert_eq!( + plane.kept_range(Vec3::ZERO, Vec3::X), + Some((f32::NEG_INFINITY, f32::INFINITY)) + ); +} + +#[test] +fn the_plane_moves_into_the_model_when_needed() { + let model = bounds([-5.0, -5.0, 0.0], [5.0, 5.0, 10.0]); + let mut cut = section(SectionAxis::Z, 50.0, false); + assert_eq!(cut.range(model), 0.0..=10.0); + cut.center_in(model); + assert_eq!(cut.offset, 5.0); + // Inside already: left where the user put it. + cut.offset = 2.0; + cut.center_in(model); + assert_eq!(cut.offset, 2.0); + // A flat model still gets a usable range. + let flat = bounds([0.0, 0.0, 3.0], [1.0, 1.0, 3.0]); + assert_eq!(cut.range(flat), 2.0..=4.0); +} + +#[test] +fn the_cap_quad_lies_on_the_plane_around_the_whole_cross_section() { + let model = bounds([-5.0, -2.0, 0.0], [5.0, 2.0, 10.0]); + for (axis, flipped) in [ + (SectionAxis::X, false), + (SectionAxis::Y, true), + (SectionAxis::Z, false), + ] { + let mut cut = section(axis, 0.0, flipped); + cut.center_in(model); + let plane = cut.renderer_plane(model).unwrap(); + for corner in plane.cap_corners { + assert!((plane.normal.dot(corner) - plane.offset).abs() < 1e-4); + } + // Every corner of the model, projected on the plane, is inside. + let center = (plane.cap_corners[0] + plane.cap_corners[2]) / 2.0; + let half = (plane.cap_corners[1] - plane.cap_corners[0]).length() / 2.0; + let u = (plane.cap_corners[1] - plane.cap_corners[0]).normalize(); + let v = (plane.cap_corners[3] - plane.cap_corners[0]).normalize(); + for i in 0..8 { + let corner = Vec3::new( + if i & 1 == 0 { model.min.x } else { model.max.x }, + if i & 2 == 0 { model.min.y } else { model.max.y }, + if i & 4 == 0 { model.min.z } else { model.max.z }, + ); + let offset = corner - center; + assert!(offset.dot(u).abs() <= half && offset.dot(v).abs() <= half); + } + } + let off = Section::default(); + assert!(off.renderer_plane(model).is_none()); +} diff --git a/tests/rust/viewer/test_shadow.rs b/tests/rust/viewer/test_shadow.rs new file mode 100644 index 000000000..99bba5e65 --- /dev/null +++ b/tests/rust/viewer/test_shadow.rs @@ -0,0 +1,171 @@ +use super::*; +use crate::scene::Mesh; +use crate::viewer::renderer::Style; +use std::sync::Arc; + +fn item(mesh: Mesh, transform: Mat4, style: Style, layer: Layer) -> DrawItem { + DrawItem { + mesh: Arc::new(mesh), + transform, + style, + layer, + } +} + +fn opaque() -> Style { + Style { + face_color: [1.0, 0.0, 0.0, 1.0], + edge_color: [0.0; 4], + highlight: [0.0; 4], + edge_width: 1.0, + point_size: 1.0, + faces: true, + edges: false, + points: false, + clipped: true, + background_fill: false, + hidden_edges: false, + edge_min_angle: 0.0, + silhouettes: false, + surface: [0.0; 4], + } +} + +/// A triangle spanning x and y in -1..1 at height `z`. +fn triangle(z: f32) -> Mesh { + Mesh::new( + vec![[-1.0, -1.0, z], [1.0, -1.0, z], [0.0, 1.0, z]], + vec![[0.0, 0.0, 1.0]; 3], + vec![0, 1, 2], + Vec::new(), + Vec::new(), + ) +} + +#[test] +fn the_shadow_lies_on_the_ground_under_the_model_with_room_for_its_blur() { + let bounds = Aabb { + min: Vec3::new(-1.0, -2.0, 3.0), + max: Vec3::new(1.0, 2.0, 5.0), + }; + let area = ShadowArea::around(bounds).unwrap(); + assert_eq!(area.ground, 3.0, "at the bottom of the model"); + // Wider than the model across, centred under it. + assert!(area.side > 4.0); + assert!((area.corner[0] + area.side * 0.5).abs() < 1e-5); + assert!((area.corner[1] + area.side * 0.5).abs() < 1e-5); + assert!(area.fade > 0.0); + assert!(ShadowArea::around(Aabb::EMPTY).is_none()); +} + +#[test] +fn only_faces_that_would_darken_the_ground_cast_a_shadow() { + let solid = item(triangle(0.0), Mat4::IDENTITY, opaque(), Layer::Scene); + assert!(casts_shadow(&solid)); + let wire = item( + Mesh::lines(vec![[0.0; 3], [1.0, 0.0, 0.0]]), + Mat4::IDENTITY, + opaque(), + Layer::Scene, + ); + assert!(!casts_shadow(&wire), "no faces"); + let ghost = Style { + face_color: [1.0, 0.0, 0.0, 0.1], + ..opaque() + }; + assert!(!casts_shadow(&item( + triangle(0.0), + Mat4::IDENTITY, + ghost, + Layer::Scene + ))); + let helper = item(triangle(0.0), Mat4::IDENTITY, opaque(), Layer::Overlay); + assert!(!casts_shadow(&helper), "highlights and guides cast none"); + let outline = Style { + faces: false, + ..opaque() + }; + assert!(!casts_shadow(&item( + triangle(0.0), + Mat4::IDENTITY, + outline, + Layer::Scene + ))); +} + +#[test] +fn the_shadow_is_drawn_again_only_when_its_casters_move() { + let shadow = GroundShadow { + strength: 0.5, + softness: 0.5, + }; + let solid = item(triangle(1.0), Mat4::IDENTITY, opaque(), Layer::Scene); + let guide = item(triangle(0.0), Mat4::IDENTITY, opaque(), Layer::Overlay); + let items = [solid, guide]; + let area = ShadowArea::around(shadow_bounds(&items)).unwrap(); + let key = shadow_key(&items, &area, &shadow); + assert_eq!(area.ground, 1.0, "the guide does not count"); + + // The same items: the same shadow. + assert_eq!(shadow_key(&items, &area, &shadow), key); + // A moved caster or softer edges: drawn again. + let moved = [item( + triangle(1.0), + Mat4::from_translation(Vec3::X), + opaque(), + Layer::Scene, + )]; + assert_ne!(shadow_key(&moved, &area, &shadow), key); + let softer = GroundShadow { + softness: 0.9, + ..shadow + }; + assert_ne!(shadow_key(&items, &area, &softer), key); + // A darker shadow is only the floor's uniform: nothing to redraw. + let darker = GroundShadow { + strength: 0.9, + ..shadow + }; + assert_eq!(shadow_key(&items, &area, &darker), key); +} + +#[test] +fn the_shadow_shaders_are_valid_wgsl_matching_their_uniforms() { + let source = include_str!("../../../src/viewer/shadow.wgsl"); + let module = naga::front::wgsl::parse_str(source) + .unwrap_or_else(|error| panic!("{}", error.emit_to_string(source))); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::empty(), + ) + .validate(&module) + .unwrap_or_else(|error| panic!("invalid WGSL: {error:?}")); + let entry_points: Vec<&str> = module + .entry_points + .iter() + .map(|entry| entry.name.as_str()) + .collect(); + for name in [ + "vs_occlusion", + "fs_occlusion", + "vs_fullscreen", + "fs_blur", + "vs_floor", + "fs_floor", + ] { + assert!(entry_points.contains(&name), "{name}"); + } + let mut layouter = naga::proc::Layouter::default(); + layouter.update(module.to_ctx()).unwrap(); + let size = |name: &str| { + let (_, variable) = module + .global_variables + .iter() + .find(|(_, variable)| variable.name.as_deref() == Some(name)) + .unwrap(); + layouter[variable.ty].size as usize + }; + assert_eq!(size("shadow_view"), size_of::()); + assert_eq!(size("blur"), size_of::()); + assert_eq!(size("floor"), size_of::()); +} diff --git a/tests/rust/viewer/test_stereo.rs b/tests/rust/viewer/test_stereo.rs new file mode 100644 index 000000000..5137d1d7d --- /dev/null +++ b/tests/rust/viewer/test_stereo.rs @@ -0,0 +1,100 @@ +use super::*; + +/// An image of `size` whose pixels say which eye and where: red is the +/// eye (10 left, 20 right), green and blue the coordinates. +fn coded(eye: u8, size: [u32; 2]) -> Vec { + let mut image = Vec::new(); + for y in 0..size[1] { + for x in 0..size[0] { + image.extend([eye, x as u8, y as u8, 255]); + } + } + image +} + +fn at(image: &[u8], width: u32, x: u32, y: u32) -> [u8; 4] { + let start = ((y * width + x) * 4) as usize; + <[u8; 4]>::try_from(&image[start..start + 4]).unwrap() +} + +fn composed(mode: StereoMode, size: [u32; 2]) -> Vec { + let eye = eye_size(mode, size); + compose(mode, size, &coded(10, eye), &coded(20, eye)) +} + +#[test] +fn each_eye_is_drawn_at_the_size_its_half_or_whole_image_needs() { + assert_eq!(eye_size(StereoMode::SideBySide, [9, 4]), [5, 4]); + assert_eq!(eye_size(StereoMode::OverUnder, [9, 5]), [9, 3]); + for mode in [ + StereoMode::QuadBuffer, + StereoMode::Anaglyph, + StereoMode::RowInterlaced, + StereoMode::ColumnInterlaced, + StereoMode::ChessBoard, + ] { + assert_eq!(eye_size(mode, [9, 5]), [9, 5]); + } + assert_eq!(eye_size(StereoMode::Anaglyph, [0, 0]), [1, 1]); +} + +#[test] +fn interlaced_modes_alternate_the_eyes_pixel_by_pixel() { + let size = [4, 4]; + let rows = composed(StereoMode::RowInterlaced, size); + let columns = composed(StereoMode::ColumnInterlaced, size); + let chess = composed(StereoMode::ChessBoard, size); + for y in 0..4 { + for x in 0..4 { + let eye = |even: bool| if even { 10 } else { 20 }; + assert_eq!(at(&rows, 4, x, y), [eye(y % 2 == 0), x as u8, y as u8, 255]); + assert_eq!(at(&columns, 4, x, y)[0], eye(x % 2 == 0)); + assert_eq!(at(&chess, 4, x, y)[0], eye((x + y) % 2 == 0)); + } + } +} + +#[test] +fn side_by_side_and_over_under_place_each_eye_in_its_half() { + let image = composed(StereoMode::SideBySide, [9, 2]); + assert_eq!(image.len(), 9 * 2 * 4); + // Columns 0-4 are the left eye's, 5-8 the right eye's first four. + assert_eq!(at(&image, 9, 4, 1), [10, 4, 1, 255]); + assert_eq!(at(&image, 9, 5, 1), [20, 0, 1, 255]); + assert_eq!(at(&image, 9, 8, 0), [20, 3, 0, 255]); + + let image = composed(StereoMode::OverUnder, [3, 5]); + assert_eq!(at(&image, 3, 2, 2), [10, 2, 2, 255]); + assert_eq!(at(&image, 3, 2, 3), [20, 2, 0, 255]); + assert_eq!(at(&image, 3, 0, 4), [20, 0, 1, 255]); +} + +#[test] +fn the_anaglyph_takes_red_from_the_left_eye_and_cyan_from_the_right() { + let one = |pixel: [u8; 4]| pixel.to_vec(); + let mix = |left: [u8; 4], right: [u8; 4]| { + compose(StereoMode::Anaglyph, [1, 1], &one(left), &one(right)) + }; + // White on the left: full red. The right eye gives green and blue. + assert_eq!( + mix([255, 255, 255, 255], [9, 40, 50, 255]), + [255, 40, 50, 255] + ); + // Red on the left gives no red: the optimized anaglyph reads the left + // eye's green and blue, so red objects do not flicker. + assert_eq!(mix([255, 0, 0, 255], [0, 0, 0, 0]), [0, 0, 0, 255]); + // 0.7 · green, in linear light: green 255 is 0.7 linear, 218 in sRGB. + assert_eq!(mix([0, 255, 0, 100], [0, 0, 0, 30])[0], 218); + assert_eq!(mix([0, 255, 0, 100], [0, 0, 0, 30])[3], 100); + // Quad buffer cannot be shown and composes as the anaglyph. + let (left, right) = (coded(10, [3, 2]), coded(20, [3, 2])); + assert_eq!( + compose(StereoMode::QuadBuffer, [3, 2], &left, &right), + compose(StereoMode::Anaglyph, [3, 2], &left, &right) + ); + assert_eq!(StereoMode::QuadBuffer.shown(), StereoMode::Anaglyph); + assert_eq!( + shader_mode(StereoMode::QuadBuffer), + shader_mode(StereoMode::Anaglyph) + ); +} diff --git a/tests/rust/viewer/test_views.rs b/tests/rust/viewer/test_views.rs new file mode 100644 index 000000000..142eaa5b1 --- /dev/null +++ b/tests/rust/viewer/test_views.rs @@ -0,0 +1,103 @@ +use super::*; +use crate::viewer::camera::StandardView; + +fn viewer_at(view: StandardView, target: Vec3, extent: f32) -> Viewer { + let mut viewer = Viewer::default(); + viewer.camera.set_pose(Pose { + target, + rotation: view.rotation(), + extent, + }); + viewer +} + +#[test] +fn views_are_saved_named_and_replaced_by_name() { + let mut viewer = viewer_at(StandardView::Top, Vec3::new(1.0, 2.0, 3.0), 7.0); + assert_eq!(viewer.save_view(None, Projection::Orthographic), "View 1"); + assert_eq!( + viewer.save_view(Some(" Detail "), Projection::Perspective), + "Detail" + ); + assert_eq!( + viewer.save_view(Some(" "), Projection::Orthographic), + "View 2" + ); + let names: Vec<_> = viewer.named_views.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, ["View 1", "Detail", "View 2"]); + + let detail = &viewer.named_views[1]; + assert_eq!(detail.target, [1.0, 2.0, 3.0]); + assert_eq!(detail.extent, 7.0); + assert_eq!(detail.projection, Projection::Perspective); + + // The same name replaces that view where it is. + viewer.camera.extent = 2.0; + viewer.save_view(Some("Detail"), Projection::Orthographic); + assert_eq!(viewer.named_views.len(), 3); + assert_eq!(viewer.named_views[1].extent, 2.0); + assert_eq!(viewer.named_views[1].projection, Projection::Orthographic); + + // A freed name is reused. + assert_eq!(viewer.delete_view(0).unwrap().name, "View 1"); + assert!(viewer.delete_view(5).is_none()); + assert_eq!(viewer.save_view(None, Projection::Orthographic), "View 1"); +} + +#[test] +fn going_to_a_view_restores_its_camera_and_projection() { + let mut viewer = viewer_at(StandardView::Front, Vec3::new(5.0, 0.0, 0.0), 3.0); + viewer.save_view(Some("front"), Projection::Perspective); + viewer.set_standard_view(StandardView::Iso, false, 0.0); + viewer.camera.target = Vec3::ZERO; + viewer.camera.extent = 50.0; + + assert_eq!( + viewer.go_to_view(0, false, 0.0), + Some(Projection::Perspective) + ); + let pose = viewer.camera.pose(); + assert_eq!(pose.target, Vec3::new(5.0, 0.0, 0.0)); + assert_eq!(pose.extent, 3.0); + assert!(pose.rotation.angle_between(StandardView::Front.rotation()) < 1e-4); + assert_eq!(viewer.go_to_view(1, false, 0.0), None); + + // Animated, the view is reached at the end and saved as the target. + viewer.set_standard_view(StandardView::Top, false, 0.0); + assert!(viewer.go_to_view(0, true, 10.0).is_some()); + let (pose, done) = viewer.animation.as_ref().unwrap().sample(10.0 + 1.0); + assert!(done && pose.target == Vec3::new(5.0, 0.0, 0.0)); + viewer.update_view(0, Projection::Orthographic); + assert_eq!(viewer.named_views[0].target, [5.0, 0.0, 0.0]); + assert_eq!(viewer.named_views[0].name, "front"); + assert!(viewer.update_view(3, Projection::Orthographic).is_none()); +} + +#[test] +fn damaged_views_from_the_settings_file_are_refused() { + let mut viewer = Viewer::default(); + let before = viewer.camera.pose(); + for damaged in [ + NamedView { + name: "zero rotation".into(), + extent: 1.0, + ..NamedView::default() + }, + NamedView { + name: "no extent".into(), + rotation: [0.0, 0.0, 0.0, 1.0], + ..NamedView::default() + }, + NamedView { + name: "not a number".into(), + rotation: [0.0, 0.0, 0.0, 1.0], + target: [f32::NAN, 0.0, 0.0], + extent: 1.0, + ..NamedView::default() + }, + ] { + viewer.named_views = vec![damaged]; + assert_eq!(viewer.go_to_view(0, false, 0.0), None); + assert_eq!(viewer.camera.pose().target, before.target); + } +} diff --git a/tests/test_app.py b/tests/test_app.py deleted file mode 100644 index e64acb0c2..000000000 --- a/tests/test_app.py +++ /dev/null @@ -1,2238 +0,0 @@ -from path import Path -import os, sys, asyncio -from time import perf_counter - -if sys.platform == "win32": - asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) - -from multiprocessing import Process - -import pytest -import pytestqt -import cadquery as cq - -from PyQt5.QtCore import Qt, QSettings, QPoint, QEvent, QSize -from PyQt5.QtWidgets import ( - QApplication, - QFileDialog, - QMessageBox, - QStyle, - QStyleFactory, -) -from PyQt5.QtGui import QMouseEvent - -from cq_editor.__main__ import MainWindow -from cq_editor.main_window import DockSeparatorStyle -from cq_editor.widgets.editor import Editor -from cq_editor.cq_utils import export, get_occ_color - -code = """import cadquery as cq -result = cq.Workplane("XY" ) -result = result.box(3, 3, 0.5) -result = result.edges("|Z").fillet(0.125)""" - -code_bigger_object = """import cadquery as cq -result = cq.Workplane("XY" ) -result = result.box(20, 20, 0.5) -result = result.edges("|Z").fillet(0.125) -""" - -code_show_Workplane = """import cadquery as cq -result = cq.Workplane("XY" ) -result = result.box(3, 3, 0.5) -result = result.edges("|Z").fillet(0.125) - -show_object(result) -""" - -code_show_Workplane_named = """import cadquery as cq -result = cq.Workplane("XY" ) -result = result.box(3, 3, 0.5) -result = result.edges("|Z").fillet(0.125) - -log('test') -show_object(result,name='test') -""" - -code_show_Shape = """import cadquery as cq -result = cq.Workplane("XY" ) -result = result.box(3, 3, 0.5) -result = result.edges("|Z").fillet(0.125) - -show_object(result.val()) -""" - -code_debug_Workplane = """import cadquery as cq -result = cq.Workplane("XY" ) -result = result.box(3, 3, 0.5) -result = result.edges("|Z").fillet(0.125) - -debug(result) -""" - -code_multi = """import cadquery as cq -result1 = cq.Workplane("XY" ).box(3, 3, 0.5) -result2 = cq.Workplane("XY" ).box(3, 3, 0.5).translate((0,15,0)) -""" - -code_nested_top = """import test_nested_bottom -""" - -code_many_shapes = """from cadquery.func import * - -num = 20 - -for i in range(1, num + 1, 1): - for j in range(1, num + 1, 1): - globals()[f"b_{i}_{j}"] = box(1, 1, 1).move( - x=1.1 * i, - y=1.1 * j, - z=0, - ) -""" - -code_nested_bottom = """a=1 -""" - -code_reload_issue = """wire0 = cq.Workplane().lineTo(5, 5).lineTo(10, 0).close().val() -solid1 = cq.Solid.extrudeLinear(cq.Face.makeFromWires(wire0), cq.Vector(0, 0, 1)) -r1 = cq.Workplane(solid1).translate((10, 0, 0)) -""" - -code_show_all = """import cadquery as cq -b = cq.Workplane().box(1,1,1) -sh = b.val() -a = cq.Assembly().add(sh) -sk = cq.Sketch().rect(1,1) -""" - - -def _modify_file(code, path="test.py"): - with open(path, "w", 1) as f: - f.write(code) - - -def modify_file(code, path="test.py"): - p = Process(target=_modify_file, args=(code, path)) - p.start() - p.join() - - -def get_center(widget): - - pos = widget.pos() - pos.setX(pos.x() + widget.width() // 2) - pos.setY(pos.y() + widget.height() // 2) - - return pos - - -def get_bottom_left(widget): - - pos = widget.pos() - pos.setY(pos.y() + widget.height()) - - return pos - - -def get_rgba(ais): - - alpha = ais.Transparency() - color = get_occ_color(ais) - - return color.redF(), color.greenF(), color.blueF(), alpha - - -@pytest.fixture -def main(qtbot, mocker): - - mocker.patch.object(QMessageBox, "question", return_value=QMessageBox.Yes) - mocker.patch.object(QMessageBox, "warning", return_value=QMessageBox.Discard) - - win = MainWindow() - win.show() - - qtbot.addWidget(win) - - editor = win.components["editor"] - editor.set_text(code) - - debugger = win.components["debugger"] - debugger._actions["Run"][0].triggered.emit() - - return qtbot, win - - -@pytest.fixture -def main_clean(qtbot, mocker): - - mocker.patch.object(QMessageBox, "question", return_value=QMessageBox.Yes) - mocker.patch.object(QMessageBox, "warning", return_value=QMessageBox.Discard) - - win = MainWindow() - win.show() - - qtbot.addWidget(win) - - with qtbot.waitExposed(win): - editor = win.components["editor"] - editor.set_text(code) - - return qtbot, win - - -@pytest.fixture -def main_clean_do_not_close(qtbot, mocker): - - mocker.patch.object(QMessageBox, "question", return_value=QMessageBox.No) - mocker.patch.object(QMessageBox, "warning", return_value=QMessageBox.Cancel) - - win = MainWindow() - win.show() - - qtbot.addWidget(win) - - with qtbot.waitExposed(win): - editor = win.components["editor"] - editor.set_text(code) - - return qtbot, win - - -@pytest.fixture -def main_multi(qtbot, mocker): - - mocker.patch.object(QMessageBox, "question", return_value=QMessageBox.Yes) - mocker.patch.object(QMessageBox, "warning", return_value=QMessageBox.Discard) - mocker.patch.object(QFileDialog, "getSaveFileName", return_value=("out.step", "")) - - win = MainWindow() - win.show() - - qtbot.addWidget(win) - - with qtbot.waitExposed(win): - editor = win.components["editor"] - editor.set_text(code_multi) - - debugger = win.components["debugger"] - debugger._actions["Run"][0].triggered.emit() - - return qtbot, win - - -def test_render(main): - - qtbot, win = main - - obj_tree_comp = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - console = win.components["console"] - log = win.components["log"] - - # enable CQ reloading - debugger.preferences["Reload CQ"] = False - - # check that object was rendered - assert obj_tree_comp.CQ.childCount() == 1 - - # check that object was removed - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # check that object was rendered usin explicit show_object call - editor.set_text(code_show_Workplane) - debugger._actions["Run"][0].triggered.emit() - - assert obj_tree_comp.CQ.childCount() == 1 - - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # check that cq.Shape object was rendered using explicit show_object call - editor.set_text(code_show_Shape) - debugger._actions["Run"][0].triggered.emit() - - assert obj_tree_comp.CQ.childCount() == 1 - - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # test rendering via console - console.execute(code_show_Workplane) - assert obj_tree_comp.CQ.childCount() == 1 - - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - console.execute(code_show_Shape) - assert obj_tree_comp.CQ.childCount() == 1 - - # check object rendering using show_object call with a name specified and - # debug call - editor.set_text(code_show_Workplane_named) - debugger._actions["Run"][0].triggered.emit() - - qtbot.wait(100) - assert obj_tree_comp.CQ.child(0).text(0) == "test" - assert "test" in log.toPlainText().splitlines()[-1] - - # cq reloading check - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - editor.set_text(code_reload_issue) - debugger._actions["Run"][0].triggered.emit() - - qtbot.wait(100) - assert obj_tree_comp.CQ.childCount() == 3 - - debugger._actions["Run"][0].triggered.emit() - qtbot.wait(100) - assert obj_tree_comp.CQ.childCount() == 3 - - -def test_many_shapes_render_and_erase_time(main_clean): - qtbot, win = main_clean - - editor = win.components["editor"] - debugger = win.components["debugger"] - object_tree = win.components["object_tree"] - viewer = win.components["viewer"] - - debugger.preferences["Reload CQ"] = False - object_tree.preferences["Clear all before each run"] = True - viewer.preferences["Fit automatically"] = True - editor.set_text(code_many_shapes) - - start = perf_counter() - debugger._actions["Run"][0].triggered.emit() - render_elapsed = perf_counter() - start - - assert object_tree.CQ.childCount() == 20 * 20 - - start = perf_counter() - object_tree.removeObjects() - erase_elapsed = perf_counter() - start - - assert object_tree.CQ.childCount() == 0 - assert render_elapsed < 2, f"400-shape render took {render_elapsed:.3f}s" - assert erase_elapsed < 2, f"400-shape erase took {erase_elapsed:.3f}s" - - -def test_export(main, mocker): - - qtbot, win = main - - debugger = win.components["debugger"] - debugger._actions["Run"][0].triggered.emit() - - # set focus - obj_tree = win.components["object_tree"].tree - obj_tree_comp = win.components["object_tree"] - qtbot.mouseClick(obj_tree, Qt.LeftButton) - qtbot.keyClick(obj_tree, Qt.Key_Down) - qtbot.keyClick(obj_tree, Qt.Key_Down) - - # export STL - mocker.patch.object(QFileDialog, "getSaveFileName", return_value=("out.stl", "")) - obj_tree_comp._export_STL_action.triggered.emit() - assert os.path.isfile("out.stl") - - # export STEP - mocker.patch.object(QFileDialog, "getSaveFileName", return_value=("out.step", "")) - obj_tree_comp._export_STEP_action.triggered.emit() - assert os.path.isfile("out.step") - - # clean - os.remove("out.step") - os.remove("out.stl") - - -def number_visible_items(viewer): - - from OCP.AIS import AIS_ListOfInteractive - - l = AIS_ListOfInteractive() - - viewer_ctx = viewer._get_context() - viewer_ctx.DisplayedObjects(l) - - # exclude the navigation cube and its rotation arrows - they are always - # displayed furniture, not rendered CQ objects - furniture = [viewer.canvas.view_cube, *viewer.canvas.rotate_arrows] - return sum(1 for o in l if all(o != f for f in furniture)) - - -def test_inspect(main): - - qtbot, win = main - - # set focus and make invisible - obj_tree = win.components["object_tree"].tree - qtbot.mouseClick(obj_tree, Qt.LeftButton) - qtbot.keyClick(obj_tree, Qt.Key_Down) - qtbot.keyClick(obj_tree, Qt.Key_Down) - qtbot.keyClick(obj_tree, Qt.Key_Space) - - # enable object inspector - insp = win.components["cq_object_inspector"] - insp._toolbar_actions[0].toggled.emit(True) - - # check if all stack items are visible in the tree - assert insp.root.childCount() == 3 - - # check if correct number of items is displayed - viewer = win.components["viewer"] - - insp.setCurrentItem(insp.root.child(0)) - assert number_visible_items(viewer) == 4 - - insp.setCurrentItem(insp.root.child(1)) - assert number_visible_items(viewer) == 7 - - insp.setCurrentItem(insp.root.child(2)) - assert number_visible_items(viewer) == 4 - - insp._toolbar_actions[0].toggled.emit(False) - assert number_visible_items(viewer) == 3 - - -class event_loop(object): - """Used to mock the QEventLoop for the debugger component""" - - def __init__(self, callbacks): - - self.callbacks = callbacks - self.i = 0 - - def exec_(self): - - if self.i < len(self.callbacks): - self.callbacks[self.i]() - self.i += 1 - - def exit(self, *args): - - pass - - -def patch_debugger(debugger, event_loop_mock): - - debugger.inner_event_loop.exec_ = event_loop_mock.exec_ - debugger.inner_event_loop.exit = event_loop_mock.exit - - -def test_debug(main, mocker): - - # store the tracing function - trace_function = sys.gettrace() - - def assert_func(x): - """Neddedd to perform asserts in lambdas""" - assert x - - qtbot, win = main - - # clear all - obj_tree = win.components["object_tree"] - obj_tree.toolbarActions()[0].triggered.emit() - - editor = win.components["editor"] - editor.set_text(code) - - debugger = win.components["debugger"] - actions = debugger._actions["Run"] - run, debug, step, step_in, cont = actions - - variables = win.components["variables_viewer"] - - traceback_view = win.components["traceback_viewer"] - - def check_no_error_occured(): - """check that no error occured while stepping through the debugger""" - assert "" == traceback_view.current_exception.text() - - viewer = win.components["viewer"] - assert number_visible_items(viewer) == 3 - - # check breakpoints - assert debugger.set_breakpoints([]) - - # check _frames - assert debugger._frames == [] - - # test step through - ev = event_loop( - [ - lambda: ( - assert_func(variables.model().rowCount() == 5), - assert_func(number_visible_items(viewer) == 3), - step.triggered.emit(), - ), - lambda: ( - assert_func(variables.model().rowCount() == 5), - assert_func(number_visible_items(viewer) == 3), - step.triggered.emit(), - ), - lambda: ( - assert_func(variables.model().rowCount() == 6), - assert_func(number_visible_items(viewer) == 3), - step.triggered.emit(), - ), - lambda: ( - assert_func(variables.model().rowCount() == 6), - assert_func(number_visible_items(viewer) == 4), - cont.triggered.emit(), - ), - ] - ) - - patch_debugger(debugger, ev) - - debug.triggered.emit(True) - - check_no_error_occured() - - assert variables.model().rowCount() == 2 - assert number_visible_items(viewer) == 4 - - # test exit debug - ev = event_loop( - [ - lambda: (step.triggered.emit(),), - lambda: ( - assert_func(variables.model().rowCount() == 5), - assert_func(number_visible_items(viewer) == 3), - debug.triggered.emit(False), - ), - ] - ) - - patch_debugger(debugger, ev) - - debug.triggered.emit(True) - - check_no_error_occured() - - assert variables.model().rowCount() == 2 - assert number_visible_items(viewer) == 4 - - # test breakpoint - ev = event_loop( - [ - lambda: (cont.triggered.emit(),), - lambda: ( - assert_func(variables.model().rowCount() == 6), - assert_func(number_visible_items(viewer) == 4), - cont.triggered.emit(), - ), - ] - ) - - patch_debugger(debugger, ev) - - editor.debugger.set_breakpoints([(4, None)]) - - debug.triggered.emit(True) - - check_no_error_occured() - - assert variables.model().rowCount() == 2 - assert number_visible_items(viewer) == 4 - - # test breakpoint without using signals - ev = event_loop( - [ - lambda: (cont.triggered.emit(),), - lambda: ( - assert_func(variables.model().rowCount() == 6), - assert_func(number_visible_items(viewer) == 4), - cont.triggered.emit(), - ), - ] - ) - - patch_debugger(debugger, ev) - - editor.debugger.set_breakpoints([(4, None)]) - - debugger.debug(True) - - check_no_error_occured() - - assert variables.model().rowCount() == 2 - assert number_visible_items(viewer) == 4 - - # test debug() without using singals - ev = event_loop( - [ - lambda: (cont.triggered.emit(),), - lambda: ( - assert_func(variables.model().rowCount() == 6), - assert_func(number_visible_items(viewer) == 4), - cont.triggered.emit(), - ), - ] - ) - - patch_debugger(debugger, ev) - - editor.set_text(code_debug_Workplane) - editor.debugger.set_breakpoints([(4, None)]) - - debugger.debug(True) - - check_no_error_occured() - - CQ = obj_tree.CQ - - # object 1 (defualt color) - r, g, b, a = get_rgba(CQ.child(0).ais) - # assert a == pytest.approx(0.2) - assert r == 1.0 - - assert variables.model().rowCount() == 2 - assert number_visible_items(viewer) == 4 - - # restore the tracing function - sys.settrace(trace_function) - - -code_err1 = """import cadquery as cq -( -result = cq.Workplane("XY" ).box(3, 3, 0.5).edges("|Z").fillet(0.125) -""" - -code_err2 = """import cadquery as cq -result = cq.Workplane("XY" ).box(3, 3, 0.5).edges("|Z").fillet(0.125) -f() -""" -code_err3 = """import cadquery as cq -result = cq.Workplane("XY" ).box(3, 3, 0) -""" - -base_editor_text = """import cadquery as cq -result = cq.Workplane().box(10, 10, 10) -""" - - -def test_traceback(main): - - # store the tracing function - trace_function = sys.gettrace() - - qtbot, win = main - - editor = win.components["editor"] - debugger = win.components["debugger"] - traceback_view = win.components["traceback_viewer"] - - actions = debugger._actions["Run"] - run, debug, step, step_in, cont = actions - - editor.set_text(code_err1) - run.triggered.emit() - - assert "SyntaxError" in traceback_view.current_exception.text() - - debug.triggered.emit() - - assert "SyntaxError" in traceback_view.current_exception.text() - assert debug.isChecked() == False - - editor.set_text(code_err2) - run.triggered.emit() - - assert "NameError" in traceback_view.current_exception.text() - assert hasattr(sys, "last_traceback") - - del sys.last_traceback - assert not hasattr(sys, "last_traceback") - - # test last_traceback with debug - ev = event_loop([lambda: (cont.triggered.emit(),)]) - patch_debugger(debugger, ev) - - debugger.debug(True) - - assert "NameError" in traceback_view.current_exception.text() - assert hasattr(sys, "last_traceback") - assert traceback_view.tree.root.childCount() == 1 - - # restore the tracing function - sys.settrace(trace_function) - - # check if errors deeper in CQ are reported too - editor.set_text(code_err3) - run.triggered.emit() - - assert "Standard_DomainError" in traceback_view.current_exception.text() - assert traceback_view.tree.root.childCount() == 3 # 1 in user code + 2 in CQ code - - -@pytest.fixture -def editor(qtbot): - - win = Editor() - win.show() - - qtbot.addWidget(win) - - return qtbot, win - - -def conv_line_ends(text): - - return "\n".join(text.splitlines()) - - -def test_editor(monkeypatch, editor): - - qtbot, editor = editor - - with open("test.py", "w") as f: - f.write(code) - - # check that no text is present - assert editor.get_text_with_eol() == "" - - # check that loading from file works properly - editor.load_from_file("test.py") - assert len(editor.get_text_with_eol()) > 0 - assert conv_line_ends(editor.get_text_with_eol()) == code - - # check that loading from file works properly - editor.new() - assert editor.get_text_with_eol() == "" - - # monkeypatch QFileDialog methods - def filename(*args, **kwargs): - return "test.py", None - - def filename2(*args, **kwargs): - return "test2.py", None - - monkeypatch.setattr(QFileDialog, "getOpenFileName", staticmethod(filename)) - - monkeypatch.setattr(QFileDialog, "getSaveFileName", staticmethod(filename2)) - - # check that open file works properly - editor.open() - assert conv_line_ends(editor.get_text_with_eol()) == code - - # check that save file works properly - editor.new() - qtbot.mouseClick(editor, Qt.LeftButton) - qtbot.keyClick(editor, Qt.Key_A) - - assert editor.document().isModified() == True - - editor.filename = "test2.py" - editor.save() - - assert editor.document().isModified() == False - - monkeypatch.setattr(QFileDialog, "getOpenFileName", staticmethod(filename2)) - - editor.open() - assert editor.get_text_with_eol() == "a" - - # check that save as works properly - os.remove("test2.py") - editor.save_as() - assert os.path.exists(filename2()[0]) - - # test persistance - settings = QSettings("test") - editor.saveComponentState(settings) - - editor.new() - assert editor.get_text_with_eol() == "" - - editor.restoreComponentState(settings) - assert editor.get_text_with_eol() == "a" - - # test error handling - os.remove("test2.py") - assert not os.path.exists("test2.py") - editor.restoreComponentState(settings) - - -def test_size_hint(editor): - """ - Tests the ability to get the size hit from the code editor widget. - """ - qtbot, editor = editor - - size_hint = editor.sizeHint() - - assert size_hint == QSize(256, 192) - - -def test_clear_selection(editor): - """ - Tests the ability to clear selected text. - """ - qtbot, editor = editor - - # Set a block of text and make sure it is visible - editor.set_text(base_editor_text) - editor.document().setModified(False) - assert editor.get_text_with_eol() == base_editor_text - - # Remove all the text and make sure it was removed - editor.selectAll() - cursor = editor.textCursor() - cursor.removeSelectedText() - editor.setTextCursor(cursor) - editor.document().setModified(False) - assert editor.get_text_with_eol() == "" - - # Test the ability to deselect a selected area - editor.set_text(base_editor_text) - editor.selectAll() - assert editor.get_selection_range() == (0, 2) - editor.clear_selection() - assert editor.get_selection_range() == (0, 0) - - -def test_insert_remove_line_start(editor): - """ - Tests the ability to remove and insert characters from/to the beginning of a line. - """ - qtbot, editor = editor - - # Set a block of text and make sure it is visible - editor.set_text(base_editor_text) - editor.insert_line_start("# ", 0) - editor.document().setModified(False) - assert editor.get_text_with_eol() == "# " + base_editor_text - - # Remove the comment character from the line - editor.remove_line_start("# ", 0) - editor.document().setModified(False) - assert editor.get_text_with_eol() == base_editor_text - - -def test_indent_unindent(editor): - """ - Check to make sure that indent and un-indent work properly. - """ - qtbot, editor = editor - - # Set the base text - editor.set_text(base_editor_text) - - # Indent the text and check - editor.selectAll() - qtbot.keyClick(editor, Qt.Key_Tab) - editor.document().setModified(False) - assert editor.get_text_with_eol() != base_editor_text - - # Unindent the code with a direct method call and check - editor.selectAll() - start_line, end_line = editor.get_selection_range() - # +1 here to compesate for how black wants the multi-line string - editor.undo_indent(list(range(start_line, end_line + 1))) - editor.document().setModified(False) - assert editor.get_text_with_eol() == base_editor_text - - # Indent the code again with a direct method call and check - editor.selectAll() - start_line, end_line = editor.get_selection_range() - editor.do_indent(list(range(start_line, end_line))) - editor.document().setModified(False) - assert editor.get_text_with_eol() != base_editor_text - - # Unindent the code again with a keystroke - editor.selectAll() - qtbot.keyClick(editor, Qt.Key_Backtab) - editor.document().setModified(False) - assert editor.get_text_with_eol() == base_editor_text - - # Indent just the second line - editor.clear_selection() - editor.do_indent([1]) - assert editor.get_text_with_eol() != base_editor_text - - -def test_set_color_scheme(editor): - """ - Make sure that the color theme can be switched without error. - """ - qtbot, editor = editor - - editor.set_color_scheme("Light") - editor.set_color_scheme("Dark") - - -def test_go_to_line(editor): - """ - Tests to make sure the caller can set the current line of the code. - """ - qtbot, editor = editor - - # Set the base text - editor.set_text(base_editor_text) - - # Make sure the line changes - editor.go_to_line(1) - cursor = editor.textCursor() - block = cursor.block() - assert (block.blockNumber() + 1) == 1 - editor.go_to_line(2) - cursor = editor.textCursor() - block = cursor.block() - assert (block.blockNumber() + 1) == 2 - - -def test_toggle_comment(editor): - """ - Tests to make sure that lines can be commented/uncommented. - """ - qtbot, editor = editor - - # Set the base text - editor.set_text(base_editor_text) - - # Try commenting and uncommenting a single line - editor.go_to_line(1) - editor.toggle_comment() - assert editor.get_text_with_eol() != base_editor_text - editor.toggle_comment() - assert editor.get_text_with_eol() == base_editor_text - - # Try commenting and uncommenting multiple lines - editor.selectAll() - editor.toggle_comment() - assert editor.get_text_with_eol() != base_editor_text - editor.selectAll() - editor.toggle_comment() - assert editor.get_text_with_eol() == base_editor_text - - -def test_highlight_current_line(editor): - """ - Make sure the current line can be highlighted without error. - """ - qtbot, editor = editor - - # Set the base text - editor.set_text(base_editor_text) - - # Highlight the first line - editor.go_to_line(1) - editor.highlight_current_line() - - -def test_set_remove_breakpoints(editor): - """ - Make sure the breakpoints can be added and removed without error. - """ - qtbot, editor = editor - - # Set the base text - editor.set_text(base_editor_text) - - # Toggle breakpoints and check that they are there - assert not editor.line_has_breakpoint(2) - editor.toggle_breakpoint(2) - assert editor.line_has_breakpoint(2) - editor.toggle_breakpoint(2) - assert not editor.line_has_breakpoint(2) - - -def test_search(editor): - """ - Tests the search functionality. - """ - qtbot, editor = editor - - # Set the base text - editor.set_text(base_editor_text) - - # Test with no search match - editor.search_widget.on_search_text_changed("~") - assert editor.search_widget.match_label.text() == "0 matches" - - # Check to see that various search texts change the search controls - editor.search_widget.on_search_text_changed("cq") - assert editor.search_widget.match_label.text() == "1 of 2" - - # Make sure advancing to the next and previous matches works properly - editor.search_widget.find_next() - assert editor.search_widget.match_label.text() == "2 of 2" - editor.search_widget.find_previous() - assert editor.search_widget.match_label.text() == "1 of 2" - - # Make sure the show and hide search works - editor.search_widget.show_search() - assert editor.search_widget.isVisible() - editor.search_widget.hide_search() - assert not editor.search_widget.isVisible() - - # Test hotkeys - qtbot.keyClick(editor, Qt.Key_F, modifier=Qt.ControlModifier) - assert editor.search_widget.isVisible() - qtbot.keyClick(editor, Qt.Key_F3) - qtbot.keyClick(editor, Qt.Key_F3, modifier=Qt.AltModifier) - - -def test_line_number_area(editor): - """ - Tests to make sure the line number area on the left of the editor is working correctly. - """ - qtbot, editor = editor - - # Set the base text - editor.set_text(base_editor_text) - - # Make sure the size hint can be retrieved without error - editor.line_number_area.sizeHint() - - # Try to simulate a mouse click in the line number area - pos = QPoint(10, 10) - qtbot.mouseClick(editor.line_number_area, Qt.LeftButton, pos=pos) - - -def test_console(main): - qtbot, win = main - - console = win.components["console"] - - # test execute_command - a = [] - console.push_vars({"a": a}) - console.execute_command("a.append(1)") - assert len(a) == 1 - - # test print_text - pos_orig = console._prompt_pos - console.print_text("a") - assert console._prompt_pos == pos_orig + len("a") - - # test reset of the console contents - console.reset_console() - assert len(console._control.toPlainText()) <= 10 - - -def test_viewer(main): - - qtbot, win = main - - viewer = win.components["viewer"] - - # not sure how to test this, so only smoke tests - - # trigger all 'View' actions - actions = viewer._actions["View"] - for a in actions: - a.trigger() - - -code_module = """def dummy(): return True""" - -code_import = """from module import dummy -assert(dummy())""" - - -def test_module_import(main, tmp_path, monkeypatch): - - qtbot, win = main - - editor = win.components["editor"] - debugger = win.components["debugger"] - traceback_view = win.components["traceback_viewer"] - - # isolate test files in a temp directory - monkeypatch.chdir(tmp_path) - - # save the dummy module - module_file = tmp_path / "module.py" - module_file.write_text(code_module) - - # run the code importing this module - script_file = tmp_path / "main.py" - script_file.write_text(code_import) - editor.load_from_file(str(script_file)) - debugger._actions["Run"][0].triggered.emit() - - # verify that no exception was generated - assert traceback_view.current_exception.text() == "" - - -def test_auto_fit_view(main_clean): - - def concat(eye, proj, scale): - return eye + proj + (scale,) - - def approx_view_properties(eye, proj, scale): - - return pytest.approx(eye + proj + (scale,)) - - qtbot, win = main_clean - - editor = win.components["editor"] - debugger = win.components["debugger"] - viewer = win.components["viewer"] - object_tree = win.components["object_tree"] - - view = viewer.canvas.view - viewer.preferences["Fit automatically"] = False - eye0, proj0, scale0 = view.Eye(), view.Proj(), view.Scale() - # check if camera position is adjusted automatically when rendering for the - # first time - debugger.render() - eye1, proj1, scale1 = view.Eye(), view.Proj(), view.Scale() - assert concat(eye0, proj0, scale0) != approx_view_properties(eye1, proj1, scale1) - - # check if camera position is not changed fter code change - editor.set_text(code_bigger_object) - debugger.render() - eye2, proj2, scale2 = view.Eye(), view.Proj(), view.Scale() - assert concat(eye1, proj1, scale1) == approx_view_properties(eye2, proj2, scale2) - - # check if position is adjusted automatically after erasing all objects - object_tree.removeObjects() - debugger.render() - eye3, proj3, scale3 = view.Eye(), view.Proj(), view.Scale() - assert concat(eye2, proj2, scale2) != approx_view_properties(eye3, proj3, scale3) - - # check if position is adjusted automatically if settings are changed - viewer.preferences["Fit automatically"] = True - editor.set_text(code) - debugger.render() - eye4, proj4, scale4 = view.Eye(), view.Proj(), view.Scale() - assert concat(eye3, proj3, scale3) != approx_view_properties(eye4, proj4, scale4) - - -def test_preserve_properties(main): - qtbot, win = main - - debugger = win.components["debugger"] - debugger._actions["Run"][0].triggered.emit() - - object_tree = win.components["object_tree"] - object_tree.preferences["Preserve properties on reload"] = True - - assert object_tree.CQ.childCount() == 1 - props = object_tree.CQ.child(0).properties - props["Visible"] = False - # props["Color"] = "#caffee" - # props["Alpha"] = 0.5 - - debugger._actions["Run"][0].triggered.emit() - - assert object_tree.CQ.childCount() == 1 - props = object_tree.CQ.child(0).properties - assert props["Visible"] == False - # assert props["Color"].name() == "#caffee" - # assert props["Alpha"] == 0.5 - - -def test_selection(main_multi, mocker): - - qtbot, win = main_multi - - viewer = win.components["viewer"] - object_tree = win.components["object_tree"] - - CQ = object_tree.CQ - obj1 = CQ.child(0) - obj2 = CQ.child(1) - - # export with two selected objects - obj1.setSelected(True) - obj2.setSelected(True) - - object_tree._export_STEP_action.triggered.emit() - imported = cq.importers.importStep("out.step") - assert len(imported.solids().vals()) == 2 - - # export with one selected objects - obj2.setSelected(False) - - object_tree._export_STEP_action.triggered.emit() - imported = cq.importers.importStep("out.step") - assert len(imported.solids().vals()) == 1 - - # export with one selected objects - obj1.setSelected(False) - CQ.setSelected(True) - - object_tree._export_STEP_action.triggered.emit() - imported = cq.importers.importStep("out.step") - assert len(imported.solids().vals()) == 2 - - # check if viewer and object tree are properly connected - CQ.setSelected(False) - obj1.setSelected(True) - obj2.setSelected(True) - ctx = viewer._get_context() - ctx.InitSelected() - shapes = [] - - while ctx.MoreSelected(): - shapes.append(ctx.SelectedShape()) - ctx.NextSelected() - assert len(shapes) == 2 - - viewer.fit() - qtbot.mouseClick(viewer.canvas, Qt.LeftButton) - - assert len(object_tree.tree.selectedItems()) == 0 - - viewer.sigObjectSelected.emit([obj1.shape_display.wrapped]) - assert len(object_tree.tree.selectedItems()) == 1 - - # go through different handleSelection paths - qtbot.mouseClick(object_tree.tree, Qt.LeftButton) - qtbot.keyClick(object_tree.tree, Qt.Key_Down) - qtbot.keyClick(object_tree.tree, Qt.Key_Down) - qtbot.keyClick(object_tree.tree, Qt.Key_Down) - qtbot.keyClick(object_tree.tree, Qt.Key_Down) - - assert object_tree._export_STL_action.isEnabled() == False - assert object_tree._export_STEP_action.isEnabled() == False - assert object_tree._clear_current_action.isEnabled() == False - assert object_tree.properties_editor.isEnabled() == False - - -def test_closing(main_clean_do_not_close): - - qtbot, win = main_clean_do_not_close - - editor = win.components["editor"] - - # make sure that windows is visible - assert win.isVisible() - - # should not quit - win.close() - assert win.isVisible() - - # should quit - editor.reset_modified() - win.close() - assert not win.isVisible() - - -def test_check_for_updates(main, mocker): - - qtbot, win = main - - # patch requests - import requests - - mocker.patch.object( - requests.models.Response, - "json", - return_value=[{"tag_name": "0.0.2", "draft": False}], - ) - - # stub QMessageBox about - about_stub = mocker.stub() - mocker.patch.object(QMessageBox, "about", about_stub) - - import cadquery - - cadquery.__version__ = "0.0.1" - win.check_for_cq_updates() - assert about_stub.call_args[0][1] == "Updates available" - - cadquery.__version__ = "0.0.3" - win.check_for_cq_updates() - assert about_stub.call_args[0][1] == "No updates available" - - -@pytest.mark.skipif( - sys.platform.startswith("linux"), reason="Segfault workaround for linux" -) -def test_screenshot(main, mocker): - - qtbot, win = main - - mocker.patch.object(QFileDialog, "getSaveFileName", return_value=("out.png", "")) - - viewer = win.components["viewer"] - viewer._actions["Tools"][0].triggered.emit() - - assert os.path.exists("out.png") - - -def test_resize(main): - - qtbot, win = main - editor = win.components["editor"] - - editor.hide() - qtbot.wait(50) - editor.show() - qtbot.wait(50) - - -code_simple_step = """import cadquery as cq -imported = cq.importers.importStep('shape.step') -""" - - -def test_relative_references(main): - - # create code with a relative reference in a subdirectory - p = Path("test_relative_references") - p.mkdir_p() - p_code = p.joinpath("code.py") - p_code.write_text(code_simple_step) - # create the referenced step file - shape = cq.Workplane("XY").box(1, 1, 1) - p_step = p.joinpath("shape.step") - export(shape, "step", p_step) - # open code - qtbot, win = main - editor = win.components["editor"] - editor.load_from_file(p_code) - # render - debugger = win.components["debugger"] - debugger._actions["Run"][0].triggered.emit() - # assert no errors - traceback_view = win.components["traceback_viewer"] - assert traceback_view.current_exception.text() == "" - # assert one object has been rendered - obj_tree_comp = win.components["object_tree"] - assert obj_tree_comp.CQ.childCount() == 1 - # clean up - p_code.remove_p() - p_step.remove_p() - p.rmdir_p() - - -code_color = """ -import cadquery as cq -result = cq.Workplane("XY" ).box(1, 1, 1) - -show_object(result, name ='1') -show_object(result, name ='2', options=dict(alpha=0.5,color='red',edgecolor="white")) -show_object(result, name ='3', options=dict(alpha=0.5,color='#ff0000',edgecolor="#ff0000")) -show_object(result, name ='4', options=dict(alpha=0.5,color=(255,0,0),edgecolor=(0,0,255))) -show_object(result, name ='5', options=dict(alpha=0.5,color=(1.0,0,0),edgecolor=(0.0,0.0,1.0))) -show_object(result, name ='6', options=dict(rgba=(1.0,0,0,0.5),edgecolor=(0.0,0.0,1.0))) -show_object(result, name ='7', options=dict(color=('ff','cc','dd'))) -""" - - -def test_render_colors(main_clean): - - qtbot, win = main_clean - - obj_tree = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - log = win.components["log"] - - editor.set_text(code_color) - debugger._actions["Run"][0].triggered.emit() - - CQ = obj_tree.CQ - - # object 1 (defualt color) - assert not CQ.child(0).ais.HasColor() - - # object 2 - r, g, b, a = get_rgba(CQ.child(1).ais) - assert a == 0.5 - assert r == 1.0 - assert g == 0.0 - - # object 3 - r, g, b, a = get_rgba(CQ.child(2).ais) - assert a == 0.5 - assert r == 1.0 - - # object 4 - r, g, b, a = get_rgba(CQ.child(3).ais) - assert a == 0.5 - assert r == 1.0 - - # object 5 - r, g, b, a = get_rgba(CQ.child(4).ais) - assert a == 0.5 - assert r == 1.0 - - # object 6 - r, g, b, a = get_rgba(CQ.child(5).ais) - assert a == 0.5 - assert r == 1.0 - - # check if error occured - qtbot.wait(100) - assert "Unknown color format" in log.toPlainText().splitlines()[-1] - - -def test_render_colors_console(main_clean): - - qtbot, win = main_clean - - obj_tree = win.components["object_tree"] - log = win.components["log"] - console = win.components["console"] - - console.execute_command(code_color) - - CQ = obj_tree.CQ - - # object 1 (defualt color) - assert not CQ.child(0).ais.HasColor() - - # object 2 - r, g, b, a = get_rgba(CQ.child(1).ais) - assert a == 0.5 - assert r == 1.0 - - # object 3 - r, g, b, a = get_rgba(CQ.child(2).ais) - assert a == 0.5 - assert r == 1.0 - - # object 4 - r, g, b, a = get_rgba(CQ.child(3).ais) - assert a == 0.5 - assert r == 1.0 - - # object 5 - r, g, b, a = get_rgba(CQ.child(4).ais) - assert a == 0.5 - assert r == 1.0 - - # object 6 - r, g, b, a = get_rgba(CQ.child(5).ais) - assert a == 0.5 - assert r == 1.0 - - # check if error occured - qtbot.wait(100) - assert "Unknown color format" in log.toPlainText().splitlines()[-1] - - -code_shading = """ -import cadquery as cq - -res1 = cq.Workplane('XY').box(5, 7, 5) -res2 = cq.Workplane('XY').box(8, 5, 4) -show_object(res1) -show_object(res2,options={"alpha":0}) -""" - - -def test_shading_aspect(main_clean): - - qtbot, win = main_clean - - obj_tree = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - - editor.set_text(code_shading) - debugger._actions["Run"][0].triggered.emit() - - CQ = obj_tree.CQ - - # get material aspects - ma1 = CQ.child(0).ais.Attributes().ShadingAspect().Material() - ma2 = CQ.child(1).ais.Attributes().ShadingAspect().Material() - - # verify that they are the same - assert ma1.Shininess() == ma2.Shininess() - - -def test_confirm_new(monkeypatch, editor): - - qtbot, editor = editor - - # check that initial state is as expected - assert editor.modified == False - - editor.document().setPlainText(code) - assert editor.modified == True - - # monkeypatch the confirmation dialog and run both scenarios - def cancel(*args, **kwargs): - return QMessageBox.No - - def ok(*args, **kwargs): - return QMessageBox.Yes - - monkeypatch.setattr(QMessageBox, "question", staticmethod(cancel)) - - editor.new() - assert editor.modified == True - assert conv_line_ends(editor.get_text_with_eol()) == code - - monkeypatch.setattr(QMessageBox, "question", staticmethod(ok)) - - editor.new() - assert editor.modified == False - assert editor.get_text_with_eol() == "" - - -code_show_topods = """ -import cadquery as cq -result = cq.Workplane("XY" ).box(1, 1, 1) - -show_object(result.val().wrapped) -""" - - -def test_render_topods(main): - - qtbot, win = main - - obj_tree_comp = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - console = win.components["console"] - - # check that object was rendered - assert obj_tree_comp.CQ.childCount() == 1 - - # check that object was removed - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # check that object was rendered usin explicit show_object call - editor.set_text(code_show_topods) - debugger._actions["Run"][0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 1 - - # test rendering of topods object via console - console.execute("show(result.val().wrapped)") - assert obj_tree_comp.CQ.childCount() == 2 - - # test rendering of list of topods object via console - console.execute("show([result.val().wrapped,result.val().wrapped])") - assert obj_tree_comp.CQ.childCount() == 3 - - -code_show_shape_list = """ -import cadquery as cq -result1 = cq.Workplane("XY" ).box(1, 1, 1).val() -result2 = cq.Workplane("XY",origin=(0,1,1)).box(1, 1, 1).val() - -show_object(result1) -show_object([result1,result2]) -""" - - -def test_render_shape_list(main): - - qtbot, win = main - - log = win.components["log"] - - obj_tree_comp = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - console = win.components["console"] - - # check that object was removed - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # check that object was rendered usin explicit show_object call - editor.set_text(code_show_shape_list) - debugger._actions["Run"][0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 2 - - # test rendering of Shape via console - console.execute("show(result1)") - console.execute("show([result1,result2])") - assert obj_tree_comp.CQ.childCount() == 4 - - # smoke test exception in show - console.execute('show("a")') - - -code_show_assy = """import cadquery as cq -result1 = cq.Workplane("XY" ).box(3, 3, 0.5) -assy = cq.Assembly() -assy.add(result1) - -show_object(assy) -""" - - -def test_render_assy(main): - - qtbot, win = main - - obj_tree_comp = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - console = win.components["console"] - - # check that object was removed - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # check that object was rendered usin explicit show_object call - editor.set_text(code_show_assy) - debugger._actions["Run"][0].triggered.emit() - qtbot.wait(500) - assert obj_tree_comp.CQ.childCount() == 1 - - # test rendering via console - console.execute("show(assy)") - qtbot.wait(500) - assert obj_tree_comp.CQ.childCount() == 2 - - -code_show_ais = """import cadquery as cq -from cadquery.occ_impl.assembly import toCAF - -import OCP - -result1 = cq.Workplane("XY" ).box(3, 3, 0.5) -assy = cq.Assembly() -assy.add(result1) - -lab, doc = toCAF(assy) -ais = OCP.XCAFPrs.XCAFPrs_AISObject(lab) - -show_object(ais) -""" - - -def test_render_ais(main): - - qtbot, win = main - - obj_tree_comp = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - console = win.components["console"] - - # check that object was removed - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # check that object was rendered usin explicit show_object call - editor.set_text(code_show_ais) - debugger._actions["Run"][0].triggered.emit() - qtbot.wait(500) - assert obj_tree_comp.CQ.childCount() == 1 - - # test rendering via console - console.execute("show(ais)") - qtbot.wait(500) - assert obj_tree_comp.CQ.childCount() == 2 - - -code_show_sketch = """import cadquery as cq - -s1 = cq.Sketch().rect(1,1) -s2 = cq.Sketch().segment((0,0), (0,3.),"s1") - -show_object(s1) -show_object(s2) -""" - - -def test_render_sketch(main): - - qtbot, win = main - - obj_tree_comp = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - console = win.components["console"] - - # check that object was removed - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # check that object was rendered usin explicit show_object call - editor.set_text(code_show_sketch) - debugger._actions["Run"][0].triggered.emit() - qtbot.wait(500) - assert obj_tree_comp.CQ.childCount() == 2 - - # test rendering via console - console.execute("show(s1); show(s2)") - qtbot.wait(500) - assert obj_tree_comp.CQ.childCount() == 4 - - -def test_window_title(monkeypatch, main): - - fname = "test_window_title.py" - - with open(fname, "w") as f: - f.write(code) - - qtbot, win = main - - # monkeypatch QFileDialog methods - def filename(*args, **kwargs): - return fname, None - - monkeypatch.setattr(QFileDialog, "getOpenFileName", staticmethod(filename)) - - win.components["editor"].open() - assert win.windowTitle().endswith(fname) - - # handle a new file - win.components["editor"].new() - # I don't really care what the title is, as long as it's not a filename - assert not win.windowTitle().endswith(".py") - - -def test_module_discovery(tmp_path, editor): - - qtbot, editor = editor - with open(tmp_path.joinpath("main.py"), "w") as f: - f.write("import b") - - assert editor.get_imported_module_paths(str(tmp_path.joinpath("main.py"))) == [] - - tmp_path.joinpath("b.py").touch() - - assert editor.get_imported_module_paths(str(tmp_path.joinpath("main.py"))) == [ - str(tmp_path.joinpath("b.py")) - ] - - -def test_launch_syntax_error(tmp_path): - - # verify app launches when input file is bad - win = MainWindow() - - inputfile = Path(tmp_path).joinpath("syntax_error.py") - modify_file("print(", inputfile) - editor = win.components["editor"] - editor.autoreload(True) - editor.preferences["Autoreload: watch imported modules"] = True - editor.load_from_file(inputfile) - - win.show() - assert win.isVisible() - - -def test_dock_separator_width(main_clean): - - qtbot, win = main_clean - - # separators are widened through a style proxy, not a stylesheet: a - # stylesheet on the main window would break palette based theming (#595) - assert win.styleSheet() == "" - assert win.style().pixelMetric(QStyle.PM_DockWidgetSeparatorExtent, None, win) >= 6 - - # child widgets keep the application style - editor = win.components["editor"] - assert editor.style().objectName() == QApplication.instance().style().objectName() - - -def test_dock_separator_style_widens_small_extents(qtbot): - - base = QStyleFactory.create("Windows") - assert base.pixelMetric(QStyle.PM_DockWidgetSeparatorExtent) < 6 - - style = DockSeparatorStyle(base) - - assert style.pixelMetric(QStyle.PM_DockWidgetSeparatorExtent) == 6 - - -code_import_module_makebox = """ -from module_makebox import * -z = 1 -r = makebox(z) -""" - -code_module_makebox = """ -import cadquery as cq -def makebox(z): - zval = z + 1 - return cq.Workplane().box(1, 1, zval) -""" - - -def test_reload_import_handle_error(tmp_path, main): - - TIMEOUT = 500 - qtbot, win = main - editor = win.components["editor"] - debugger = win.components["debugger"] - traceback_view = win.components["traceback_viewer"] - - editor.autoreload(True) - editor.preferences["Autoreload: watch imported modules"] = True - - # save the module and top level script files - module_file = Path(tmp_path).joinpath("module_makebox.py") - script = Path(tmp_path).joinpath("main.py") - modify_file(code_module_makebox, module_file) - modify_file(code_import_module_makebox, script) - - # run, verify that no exception was generated - editor.load_from_file(script) - debugger._actions["Run"][0].triggered.emit() - assert traceback_view.current_exception.text() == "" - - # save the module with an error - with qtbot.waitSignal(editor.triggerRerender, timeout=TIMEOUT): - lines = code_module_makebox.splitlines() - lines.remove(" zval = z + 1") # introduce NameError - lines = "\n".join(lines) - modify_file(lines, module_file) - - # verify NameError is generated - debugger._actions["Run"][0].triggered.emit() - assert "NameError" in traceback_view.current_exception.text() - - # revert the error, verify rerender is triggered - with qtbot.waitSignal(editor.triggerRerender, timeout=TIMEOUT): - modify_file(code_module_makebox, module_file) - - # verify that no exception was generated - debugger._actions["Run"][0].triggered.emit() - assert traceback_view.current_exception.text() == "" - - -def test_modulefinder(tmp_path, main): - - TIMEOUT = 500 - qtbot, win = main - editor = win.components["editor"] - debugger = win.components["debugger"] - traceback_view = win.components["traceback_viewer"] - log = win.components["log"] - - editor.autoreload(True) - editor.preferences["Autoreload: watch imported modules"] = True - - script = Path(tmp_path).joinpath("main.py") - Path(tmp_path).joinpath("emptydir").mkdir() - modify_file("#import emptydir", script) - editor.load_from_file(script) - with qtbot.waitSignal(editor.triggerRerender, timeout=TIMEOUT): - modify_file("import emptydir", script) - - qtbot.wait(100) - assert "Cannot determine imported modules" in log.toPlainText().splitlines()[-1] - - -def test_show_all(main): - - qtbot, win = main - - editor = win.components["editor"] - debugger = win.components["debugger"] - object_tree = win.components["object_tree"] - - # remove all objects - object_tree.removeObjects() - assert object_tree.CQ.childCount() == 0 - - # add code wtih Shape, Workplane, Assy, Sketch - editor.set_text(code_show_all) - - # Run and check if all are shown - debugger._actions["Run"][0].triggered.emit() - - assert object_tree.CQ.childCount() == 4 - - -code_randcolor = """import cadquery as cq -b = cq.Workplane().box(8, 3, 4) -for i in range(10): - show_object(b.translate((0,5*i,0)), options=rand_color(alpha=0)) - show_object(b.translate((0,5*i,0)), options=rand_color(0, True)) -""" - - -def test_randcolor(main): - - qtbot, win = main - - obj_tree_comp = win.components["object_tree"] - editor = win.components["editor"] - debugger = win.components["debugger"] - console = win.components["console"] - - # check that object was removed - obj_tree_comp._toolbar_actions[0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 0 - - # check that object was rendered usin explicit show_object call - editor.set_text(code_randcolor) - debugger._actions["Run"][0].triggered.emit() - assert obj_tree_comp.CQ.childCount() == 2 * 10 - - -code_show_wo_name = """ -import cadquery as cq - -res = cq.Workplane().box(1,1,1) - -show_object(res) -show_object(cq.Workplane().box(1,1,1)) -""" - - -def test_show_without_name(main): - - qtbot, win = main - - editor = win.components["editor"] - debugger = win.components["debugger"] - object_tree = win.components["object_tree"] - - # remove all objects - object_tree.removeObjects() - assert object_tree.CQ.childCount() == 0 - - # add code wtih Shape, Workplane, Assy, Sketch - editor.set_text(code_show_wo_name) - - # Run and check if all are shown - debugger._actions["Run"][0].triggered.emit() - - assert object_tree.CQ.childCount() == 2 - - # Check the name of the first object - assert object_tree.CQ.child(0).text(0) == "res" - - # Check that the name of the seconf object is an int - int(object_tree.CQ.child(1).text(0)) - - -def test_print_redirect(main): - qtbot, win = main - - editor = win.components["editor"] - debugger = win.components["debugger"] - log = win.components["log"] - - editor.set_text(r"""print("\x1b[1mfoo\x1b[0m\nbar")""") - debugger._actions["Run"][0].triggered.emit() - - qtbot.wait(100) - assert "foo\nbar" in log.toPlainText() - - -def test_log_clear(main): - """ - Makes sure that the log can be cleared. - """ - qtbot, win = main - - log = win.components["log"] - log.clear_log() - assert log.toPlainText() == "" - - -def test_light_dark_mode(main): - """ - Tests that the app does switch between light and dark mode. - """ - from PyQt5.QtGui import QPalette - - qtbot, win = main - - # Change to dark mode - win.preferences["Light/Dark Theme"] = "Dark" - win.preferencesChanged(None, None) - - # Retireve the toolbar so that we can check its style - toolbar = win.toolbar - - # Get the dark mode stylesheet for the toolbar - dark_pal = win.toolbar.palette() - dark_bg = dark_pal.color(QPalette.Background).rgb() - - # Change to light mode - win.preferences["Light/Dark Theme"] = "Light" - win.preferencesChanged(None, None) - - # Get the light mode stylesheet for the toolbar - light_pal = win.toolbar.palette() - light_bg = light_pal.color(QPalette.Background).rgb() - - # Check that the dark mode stylesheet is different from the light mode stylesheet - assert dark_bg != light_bg - - -def test_autocomplete(main): - qtbot, win = main - - editor = win.components["editor"] - - # Set some text that should give a couple of auto-complete options - editor.set_text(r"""import cadquery as cq\nres = cq.W""") - - # Set the cursor position to the end of the text - editor.set_cursor_position(len(editor.get_text_with_eol())) - - # Trigger auto-complete - editor._trigger_autocomplete() - qtbot.wait(100) - - # Check that the completion list has two items - assert len(editor.completion_list) == 2 - - # Select the first item in the completion list - editor.completion_list.setCurrentRow(1) - - # Wait for the completion to be applied - qtbot.wait(100) - - # Simulate a click on the second item in the list - editor.completion_list.itemClicked.emit(editor.completion_list.item(1)) - - # Wait for the completion to be applied - qtbot.wait(100) - - # Check that the text has been completed - assert ( - editor.get_text_with_eol() == r"""import cadquery as cq\nres = cq.Workplane""" - ) - - # Set some text that should give a couple of auto-complete options - editor.set_text(r"""import cadquery as cq\nres = cq.Workplane()""") - - # Set the cursor position to the end of the text - editor.set_cursor_position(len(editor.get_text_with_eol()) - 1) - - # Trigger auto-complete - editor._trigger_autocomplete() - qtbot.wait(100) - - # Check to make sure that the auto-complete trigger removed the last ")" - assert ( - editor.get_text_with_eol() == r"""import cadquery as cq\nres = cq.Workplane(""" - ) - - -# Skip this test on Linux due to a known issue with Qt and keystrokes -@pytest.mark.skipif( - sys.platform.startswith("linux"), reason="Known issue with Qt keystrokes" -) -def test_autocomplete_keystrokes(main): - """ - Tests that the user keystrokes will have the intended effect on the UI. - """ - - qtbot, win = main - - editor = win.components["editor"] - - # Make sure the editor is focused - editor.setFocus() - qtbot.waitExposed(editor) - - # Set some text that should give a couple of auto-complete options - editor.set_text(r"""import cadquery as cq\nres = cq.""") - - # Set the cursor position to the end of the text - editor.set_cursor_position(len(editor.get_text_with_eol())) - - # Inject the Alt+/ key combo - qtbot.keyClick(editor, Qt.Key_Slash, modifier=Qt.AltModifier) - qtbot.wait(250) - - # Check that the completion list is visible - assert editor.completion_list.isVisible() - - # Select the first item in the completion list with the Return key - qtbot.keyClick(editor.completion_list, Qt.Key_Return) - qtbot.wait(250) - # Check that the text has been completed - assert editor.get_text_with_eol() == r"""import cadquery as cq\nres = cq.Assembly""" - - # Reset for the next test - editor.set_text(r"""import cadquery as cq\nres = cq.Workplane().box(""") - - # Set the cursor position to the end of the text - editor.set_cursor_position(len(editor.get_text_with_eol())) - - # Inject the Alt+/ key combo - qtbot.keyClick(editor, Qt.Key_Slash, modifier=Qt.AltModifier) - qtbot.wait(250) - - # Check that the completion list is visible - assert editor.completion_list.isVisible() - - # Select the first item in the completion list with the Tab key - qtbot.keyClick(editor.completion_list, Qt.Key_Tab) - qtbot.wait(250) - - # Check that the text has been completed - assert ( - editor.get_text_with_eol() - == r"""import cadquery as cq\nres = cq.Workplane().box(length,width,height,centered=True,combine=True,clean=True)""" - ) - - # Reset for the next test - editor.set_text(r"""import cadquery as cq\nres = cq.Workplane().box(""") - - # Trigger autocomplete again - qtbot.keyClick(editor, Qt.Key_Slash, modifier=Qt.AltModifier) - qtbot.wait(250) - - # Check that the completion list is visible - assert editor.completion_list.isVisible() - - # Make sure the Escape key closes the completion list - qtbot.keyClick(editor.completion_list, Qt.Key_Escape) - qtbot.wait(250) - assert not editor.completion_list.isVisible() - - # Trigger autocomplete again - qtbot.keyClick(editor, Qt.Key_Slash, modifier=Qt.AltModifier) - qtbot.wait(250) - - # Trigger a key press that is not handled by the completion list - qtbot.keyClick(editor.completion_list, Qt.Key_A) - qtbot.wait(250) - # Check that the completion list is still visible - assert editor.completion_list.isVisible() - - -def test_viewer_orbit_methods(main): - """ - Tests that mouse movements in the viewer work as expected. - """ - - qtbot, win = main - - viewer = win.components["viewer"] - - # Make sure the editor is focused - viewer.setFocus() - qtbot.waitExposed(viewer) - - # Simulate a drag to rotate - qtbot.mousePress(viewer, Qt.LeftButton) - qtbot.mouseMove(viewer, QPoint(100, 100)) - qtbot.mouseMove(viewer, QPoint(300, 300)) - qtbot.mouseRelease(viewer, Qt.LeftButton) - - # Simulate a drag to pan - qtbot.mousePress(viewer, Qt.MiddleButton) - event = QMouseEvent( - QEvent.MouseMove, - QPoint(100, 100), - Qt.RightButton, - Qt.RightButton, - Qt.NoModifier, - ) - viewer.mouseMoveEvent(event) - event = QMouseEvent( - QEvent.MouseMove, - QPoint(300, 300), - Qt.RightButton, - Qt.RightButton, - Qt.NoModifier, - ) - viewer.mouseMoveEvent(event) - qtbot.mouseRelease(viewer, Qt.MiddleButton) - - # Simulate drag to zoom - qtbot.mousePress(viewer, Qt.RightButton) - event = QMouseEvent( - QEvent.MouseMove, - QPoint(100, 100), - Qt.RightButton, - Qt.RightButton, - Qt.NoModifier, - ) - viewer.mouseMoveEvent(event) - event = QMouseEvent( - QEvent.MouseMove, - QPoint(300, 300), - Qt.RightButton, - Qt.RightButton, - Qt.NoModifier, - ) - viewer.mouseMoveEvent(event) - qtbot.mouseRelease(viewer, Qt.RightButton) - - assert True - - -# @pytest.mark.repeat(1) -def test_editor_autoreload(editor): - - qtbot, editor = editor - - TIMEOUT = 500 - - # start out with autoreload enabled - editor.autoreload(True) - - with open("test.py", "w") as f: - f.write(code) - - assert editor.get_text_with_eol() == "" - - editor.load_from_file("test.py") - assert len(editor.get_text_with_eol()) > 0 - - # wait for reload. - with qtbot.waitSignal(editor.triggerRerender, timeout=TIMEOUT): - # modify file - NB: separate process is needed to avoid Widows quirks - modify_file(code_bigger_object) - - # check that editor has updated file contents - assert code_bigger_object.splitlines()[2] in editor.get_text_with_eol() - - # disable autoreload - editor.autoreload(False) - - # Wait for reload in case it incorrectly happens. A timeout should occur - # instead because a re-render should not be triggered with autoreload - # disabled. - with pytest.raises(pytestqt.exceptions.TimeoutError): - with qtbot.waitSignal(editor.triggerRerender, timeout=TIMEOUT): - # re-write original file contents - modify_file(code) - - # editor should continue showing old contents since autoreload is disabled. - assert code_bigger_object.splitlines()[2] in editor.get_text_with_eol() - - # Saving a file with autoreload disabled should not trigger a rerender. - with pytest.raises(pytestqt.exceptions.TimeoutError): - with qtbot.waitSignal(editor.triggerRerender, timeout=TIMEOUT): - editor.save() - - editor.autoreload(True) - - # Saving a file with autoreload enabled should trigger a rerender. - with qtbot.waitSignal(editor.triggerRerender, timeout=TIMEOUT): - editor.save() - - -# def test_autoreload_nested(editor): - -# qtbot, editor = editor - -# TIMEOUT = 500 - -# editor.autoreload(True) -# editor.preferences["Autoreload: watch imported modules"] = True - -# with open("test_nested_top.py", "w") as f: -# f.write(code_nested_top) - -# with open("test_nested_bottom.py", "w") as f: -# f.write("") - -# assert editor.get_text_with_eol() == "" - -# editor.load_from_file("test_nested_top.py") -# assert len(editor.get_text_with_eol()) > 0 - -# # wait for reload. -# with qtbot.waitSignal(editor.triggerRerender, timeout=TIMEOUT): -# # modify file - NB: separate process is needed to avoid Windows quirks -# modify_file(code_nested_bottom, "test_nested_bottom.py") diff --git a/tests/test_cq_utils.py b/tests/test_cq_utils.py deleted file mode 100644 index d545ff156..000000000 --- a/tests/test_cq_utils.py +++ /dev/null @@ -1,22 +0,0 @@ -import cadquery as cq -import pytest - -from cq_editor.cq_utils import to_compound - - -def test_to_compound_applies_sketch_placement(): - sk = cq.Sketch().rect(1, 1) - placed = cq.Workplane("XZ").placeSketch(sk).val() - f = to_compound(placed).face() - - assert f.Area() == pytest.approx(1) - assert f.normalAt().toTuple() == pytest.approx((0, -1, 0)) - - -def test_to_compound_empty_list(): - # #600: to_compound([]) used to raise IndexError while type-checking obj[0]. - result = to_compound([]) - - assert isinstance(result, cq.Compound) - assert result.Solids() == [] - assert result.Faces() == [] diff --git a/tests/test_main_window.py b/tests/test_main_window.py deleted file mode 100644 index fef7fe1ed..000000000 --- a/tests/test_main_window.py +++ /dev/null @@ -1,37 +0,0 @@ -import sys - -from PyQt5.QtWidgets import QMessageBox -from PyQt5 import sip - -from cq_editor.__main__ import MainWindow -from cq_editor.main_window import PRINT_REDIRECTOR - - -def test_print_redirector_released_with_window(qtbot, mocker): - """ - PRINT_REDIRECTOR is a module-level singleton that outlives any MainWindow. - Once a window's LogViewer is destroyed, a write must be dropped rather than - delivered to the now-deleted C++ object (which raises "wrapped C/C++ object - of type LogViewer has been deleted"). - """ - - mocker.patch.object(QMessageBox, "question", return_value=QMessageBox.Yes) - mocker.patch.object(QMessageBox, "warning", return_value=QMessageBox.Discard) - - win = MainWindow() - qtbot.addWidget(win) - - # destroy this window's LogViewer, as tearing the window down would - sip.delete(win.components["log"]) - - # PyQt routes an exception raised inside a slot to sys.excepthook rather - # than propagating it, so capture it there while emitting - errors = [] - original_hook = sys.excepthook - sys.excepthook = lambda exc_type, *rest: errors.append(exc_type) - try: - PRINT_REDIRECTOR.sigStdoutWrite.emit("stray output after close") - finally: - sys.excepthook = original_hook - - assert errors == [] diff --git a/tests/test_navigation_cube.py b/tests/test_navigation_cube.py deleted file mode 100644 index c8f512e82..000000000 --- a/tests/test_navigation_cube.py +++ /dev/null @@ -1,327 +0,0 @@ -import pytest - -from PyQt5.QtCore import QPoint, Qt, QEvent, QPointF -from PyQt5.QtGui import QMouseEvent -from PyQt5.QtWidgets import QDialog - -from OCP.AIS import AIS_ViewCube, AIS_ViewCubeOwner, AIS_ColoredShape -from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox -from OCP.V3d import V3d_TypeOfOrientation - -from cq_editor.utils import layout -from cq_editor.widgets.navigation_cube import ( - NavigationCube, - RotationArrow, - CORNER_OFFSET, -) -from cq_editor.widgets.viewer import OCCViewer - - -def test_hit_region(): - - cube = NavigationCube() - region = cube.hit_region(600) - - assert region.contains(QPoint(600 - CORNER_OFFSET, CORNER_OFFSET)) - assert region.contains(QPoint(600 - 1, 0)) - assert not region.contains(QPoint(600 - 2 * CORNER_OFFSET - 1, 10)) - assert not region.contains(QPoint(300, 200)) - assert not region.contains(QPoint(600 - CORNER_OFFSET, 2 * CORNER_OFFSET + 1)) - - -def test_cube_front_matches_toolbar_front(): - - # FreeCAD convention: the toolbar's Front action looks from -Y - # (OCCViewer.front_view uses SetProj(0, -1, 0)), so the cube face seen - # from -Y must be labeled FRONT - cube = NavigationCube() - - assert cube.BoxSideLabel(V3d_TypeOfOrientation.V3d_Yneg).ToCString() == "FRONT" - assert cube.BoxSideLabel(V3d_TypeOfOrientation.V3d_Ypos).ToCString() == "BACK" - - -@pytest.fixture -def viewer(qtbot): - - win = QDialog() - win.setFixedSize(600, 400) - - v = OCCViewer() - layout(win, (v,), win) - - qtbot.addWidget(win) - with qtbot.waitExposed(win): - win.show() - - v.canvas.repaint() - - # generator fixture: keeps `win` referenced for the test's duration - # (qtbot.addWidget holds only a weakref) - yield qtbot, v - - -def test_cube_displayed(viewer): - - qtbot, v = viewer - - cube = v.canvas.view_cube - assert isinstance(cube, AIS_ViewCube) - assert v.canvas.context.IsDisplayed(cube) - assert cube.ViewAnimation().View() is not None - - -def test_cube_click_reorients_camera(viewer): - - qtbot, v = viewer - canvas = v.canvas - - # a displayed shape is required for the click's scene-fit to be - # observable (empty scenes have nothing to re-fit to) - box = AIS_ColoredShape(BRepPrimAPI_MakeBox(20, 20, 30).Shape()) - v.display(box) - - canvas.view_cube.SetDuration(0) - owner = AIS_ViewCubeOwner(canvas.view_cube, V3d_TypeOfOrientation.V3d_Xpos) - - # register the view as the context's last active view, as the MoveTo in - # mouseReleaseEvent does before any real cube click (StartAnimation - # silently no-ops when LastActiveView is unset) - canvas.context.MoveTo(0, 0, canvas.view, True) - - canvas.view.SetZoom(3.0) - scale_before = canvas.view.Scale() - camera = canvas.view.Camera() - distance_before = camera.Distance() - center_before = camera.Center() - - canvas._handle_cube_click(owner) - qtbot.waitUntil(lambda: not canvas._cube_timer.isActive(), timeout=2000) - - camera = canvas.view.Camera() - assert canvas.view.Proj() == pytest.approx((1, 0, 0), abs=1e-6) - assert canvas.view.Scale() == pytest.approx(scale_before, rel=1e-6) - assert camera.Distance() == pytest.approx(distance_before, rel=1e-6) - assert camera.Center().Distance(center_before) == pytest.approx(0, abs=1e-6) - - -def test_cube_click_reorients_camera_after_pan(viewer): - - qtbot, v = viewer - canvas = v.canvas - - box = AIS_ColoredShape(BRepPrimAPI_MakeBox(20, 20, 30).Shape()) - v.display(box) - - canvas.view_cube.SetDuration(0) - owner = AIS_ViewCubeOwner(canvas.view_cube, V3d_TypeOfOrientation.V3d_Xpos) - - canvas.context.MoveTo(0, 0, canvas.view, True) - - canvas.view.Pan(80, 50) - scale_before = canvas.view.Scale() - camera = canvas.view.Camera() - distance_before = camera.Distance() - center_before = camera.Center() - - canvas._handle_cube_click(owner) - qtbot.waitUntil(lambda: not canvas._cube_timer.isActive(), timeout=2000) - - camera = canvas.view.Camera() - assert canvas.view.Proj() == pytest.approx((1, 0, 0), abs=1e-6) - assert canvas.view.Scale() == pytest.approx(scale_before, rel=1e-6) - assert camera.Distance() == pytest.approx(distance_before, rel=1e-6) - assert camera.Center().Distance(center_before) == pytest.approx(0, abs=1e-6) - - -def test_cube_click_final_frame_redrawn(viewer): - - qtbot, v = viewer - canvas = v.canvas - - box = AIS_ColoredShape(BRepPrimAPI_MakeBox(20, 20, 30).Shape()) - v.display(box) - - canvas.view_cube.SetDuration(0.15) - owner = AIS_ViewCubeOwner(canvas.view_cube, V3d_TypeOfOrientation.V3d_Xpos) - canvas.context.MoveTo(0, 0, canvas.view, True) - - canvas._handle_cube_click(owner) - qtbot.waitUntil(lambda: not canvas._cube_timer.isActive(), timeout=2000) - - # the last animation frame must actually reach the screen; a view left - # invalidated shows the previous frame until an unrelated repaint - assert not canvas.view.IsInvalidated() - - -def test_cube_click_during_animation_settles_previous(viewer): - - qtbot, v = viewer - canvas = v.canvas - - box = AIS_ColoredShape(BRepPrimAPI_MakeBox(20, 20, 30).Shape()) - v.display(box) - - canvas.view_cube.SetDuration(0.15) - corner = AIS_ViewCubeOwner(canvas.view_cube, V3d_TypeOfOrientation.V3d_XposYposZpos) - canvas.context.MoveTo(0, 0, canvas.view, True) - - v.top_view() - - # second click lands mid-animation; it must behave as a repeated click - # on the settled orientation, which snaps up to the canonical value - canvas._handle_cube_click(corner) - qtbot.wait(50) - canvas._handle_cube_click(corner) - qtbot.waitUntil(lambda: not canvas._cube_timer.isActive(), timeout=2000) - - up = canvas.view.Camera().Up() - assert (up.X(), up.Y(), up.Z()) == pytest.approx( - (-0.408248, -0.408248, 0.816497), abs=1e-5 - ) - - -def _move(canvas, x, y): - - event = QMouseEvent( - QEvent.MouseMove, - QPointF(x, y), - Qt.NoButton, - Qt.MouseButtons(Qt.NoButton), - Qt.KeyboardModifiers(Qt.NoModifier), - ) - canvas.mouseMoveEvent(event) - - -def test_cube_hover_highlight(viewer): - - qtbot, v = viewer - canvas = v.canvas - - assert canvas.hasMouseTracking() - - _move(canvas, canvas.width() - 85, 85) - assert canvas.context.HasDetected() - - _move(canvas, canvas.width() // 2, canvas.height() // 2) - assert not canvas.context.HasDetected() - - -def test_arrow_hover_fill(viewer): - - from math import cos, radians, sin - - from OCP.Quantity import Quantity_Color - - from cq_editor.widgets.navigation_cube import ( - ARROW_INNER_RADIUS, - ARROW_OUTER_RADIUS, - ARROW_TAIL_ANGLE, - ARROW_HEAD_ANGLE, - ) - - qtbot, v = viewer - canvas = v.canvas - ccw, cw = canvas.rotate_arrows - - # middle of the right (cw) arrow's band - r = (ARROW_INNER_RADIUS + ARROW_OUTER_RADIUS) / 2 - a = radians((ARROW_TAIL_ANGLE + ARROW_HEAD_ANGLE) / 2) - x = canvas.width() - 85 + r * cos(a) - y = 85 - r * sin(a) - - _move(canvas, x, y) - assert canvas._hovered_arrow is cw - color = Quantity_Color() - cw.Color(color) - assert (color.Red(), color.Green(), color.Blue()) == pytest.approx((0, 1, 1)) - - _move(canvas, canvas.width() // 2, canvas.height() // 2) - assert canvas._hovered_arrow is None - cw.Color(color) - assert color.Blue() == pytest.approx(0.75, abs=0.01) - - -def test_cube_highlight_cleared_on_leave(viewer): - - qtbot, v = viewer - canvas = v.canvas - - _move(canvas, canvas.width() - 85, 85) - assert canvas.context.HasDetected() - - canvas.leaveEvent(None) - assert not canvas.context.HasDetected() - - -def test_cube_visibility_preference(viewer): - - qtbot, v = viewer - ctx = v.canvas.context - cube = v.canvas.view_cube - overlays = (cube,) + v.canvas.rotate_arrows - - v.preferences["Show navigation cube"] = False - assert not any(ctx.IsDisplayed(obj) for obj in overlays) - - v.preferences["Show navigation cube"] = True - assert all(ctx.IsDisplayed(obj) for obj in overlays) - - -def test_rotate_arrows_displayed(viewer): - - qtbot, v = viewer - ctx = v.canvas.context - - ccw, cw = v.canvas.rotate_arrows - assert isinstance(ccw, RotationArrow) and isinstance(cw, RotationArrow) - assert ctx.IsDisplayed(ccw) and ctx.IsDisplayed(cw) - assert (ccw.sense, cw.sense) == (1, -1) - - -def test_rotate_click_rolls_in_45_degree_steps(viewer): - - qtbot, v = viewer - canvas = v.canvas - - v.top_view() - proj_before = canvas.view.Proj() - scale_before = canvas.view.Scale() - - # top view: direction is (0, 0, -1), up starts at (0, 1, 0); - # sense +1 rotates up by +45 deg around the view direction - canvas._handle_rotate_click(1) - qtbot.waitUntil(lambda: not canvas._cube_timer.isActive(), timeout=2000) - up = canvas.view.Camera().Up() - s = 2**-0.5 - assert (up.X(), up.Y(), up.Z()) == pytest.approx((s, s, 0), abs=1e-6) - - canvas._handle_rotate_click(1) - qtbot.waitUntil(lambda: not canvas._cube_timer.isActive(), timeout=2000) - up = canvas.view.Camera().Up() - assert (up.X(), up.Y(), up.Z()) == pytest.approx((1, 0, 0), abs=1e-6) - - canvas._handle_rotate_click(-1) - qtbot.waitUntil(lambda: not canvas._cube_timer.isActive(), timeout=2000) - up = canvas.view.Camera().Up() - assert (up.X(), up.Y(), up.Z()) == pytest.approx((s, s, 0), abs=1e-6) - - assert canvas.view.Proj() == pytest.approx(proj_before, abs=1e-6) - assert canvas.view.Scale() == pytest.approx(scale_before, rel=1e-6) - - -def test_fit_ignores_cube(viewer): - - qtbot, v = viewer - view = v.canvas.view - - box = AIS_ColoredShape(BRepPrimAPI_MakeBox(20, 20, 30).Shape()) - v.display(box) - - v.preferences["Show navigation cube"] = False - v.fit() - scale_without_cube = view.Scale() - - v.preferences["Show navigation cube"] = True - v.fit() - - assert view.Scale() == pytest.approx(scale_without_cube, rel=1e-6) diff --git a/tests/worker/conftest.py b/tests/worker/conftest.py new file mode 100644 index 000000000..f5af2b31a --- /dev/null +++ b/tests/worker/conftest.py @@ -0,0 +1,65 @@ +import base64 +import io +import json +import sys + +import numpy as np +import pytest + +from cq_worker.protocol import Channel, OutputStream + + +def pytest_report_header(config): + """Make every saved test or benchmark log identify its CAD runtime.""" + + from cq_worker.environment import summary + + return f"worker environment: {summary()}" + + +def decode(text: str, dtype: str, columns: int) -> np.ndarray: + return np.frombuffer(base64.b64decode(text), dtype=dtype).reshape(-1, columns) + + +class Conversation: + """Feeds scripted requests to a server and collects its messages.""" + + def __init__(self, requests: list[dict], session: str | None = None) -> None: + payload = "".join(json.dumps(r) + "\n" for r in requests).encode() + self._output = io.BytesIO() + self.channel = Channel(io.BytesIO(payload), self._output) + self.session = session + + def serve(self) -> None: + """Run a server over the scripted requests with stdout redirected.""" + + from cq_worker.server import Server + + saved = sys.stdout, sys.stderr + sys.stdout = OutputStream(self.channel, "stdout") + sys.stderr = OutputStream(self.channel, "stderr") + try: + Server(self.channel, session=self.session).serve_forever() + finally: + sys.stdout, sys.stderr = saved + + def output(self, request_id: int) -> str: + return "".join( + m["text"] for m in self.of_type("output") if m["id"] == request_id + ) + + @property + def messages(self) -> list[dict]: + lines = self._output.getvalue().decode().splitlines() + return [json.loads(line) for line in lines] + + def of_type(self, kind: str) -> list[dict]: + return [m for m in self.messages if m["type"] == kind] + + +@pytest.fixture +def conversation(): + def make(*requests: dict, session: str | None = None) -> Conversation: + return Conversation(list(requests), session) + + return make diff --git a/tests/worker/execution/test_completion.py b/tests/worker/execution/test_completion.py new file mode 100644 index 000000000..9c38e3cf1 --- /dev/null +++ b/tests/worker/execution/test_completion.py @@ -0,0 +1,121 @@ +"""Editor completion behavior with and without the optional Jedi package.""" + +from types import SimpleNamespace + +import pytest + +from cq_worker import completion + + +def test_completion_reports_unavailable_without_jedi(monkeypatch): + monkeypatch.setattr(completion, "jedi", None) + assert completion.complete("value.", 1, 6, None, {}) == { + "available": False, + "items": [], + "signatures": [], + } + + +@pytest.mark.skipif(not completion.is_available(), reason="jedi is optional") +def test_completion_uses_live_namespace_values(): + result = completion.complete("value.upp", 1, 9, None, {"value": "hello"}) + assert result["available"] + assert "upper" in {item["name"] for item in result["items"]} + + +def test_completion_limits_results_and_filters_private_names(monkeypatch): + class FakeInterpreter: + def __init__(self, *_args, **_kwargs): + pass + + def get_signatures(self, *_args): + return [] + + def complete(self, *_args): + return [SimpleNamespace(name="__private", complete="", type="function")] + [ + SimpleNamespace(name=f"item_{n}", complete=str(n), type="instance") + for n in range(205) + ] + + monkeypatch.setattr( + completion, "jedi", SimpleNamespace(Interpreter=FakeInterpreter) + ) + result = completion.complete("object.", 1, 7, None, {}) + assert len(result["items"]) == completion.MAX_COMPLETIONS - 1 + assert result["items"][0] == {"name": "item_0", "insert": "0", "kind": "instance"} + + +def test_call_arguments_return_signatures_instead_of_names(monkeypatch): + class FakeInterpreter: + def __init__(self, *_args, **_kwargs): + pass + + def get_signatures(self, *_args): + return [SimpleNamespace(to_string=lambda: "make(size)")] + + def complete(self, *_args): + raise AssertionError("name completion should not run for arguments") + + monkeypatch.setattr( + completion, "jedi", SimpleNamespace(Interpreter=FakeInterpreter) + ) + assert completion.complete("make(", 1, 5, None, {}) == { + "available": True, + "items": [], + "signatures": ["make(size)"], + } + + +def test_documentation_reports_unavailable_without_jedi(monkeypatch): + monkeypatch.setattr(completion, "jedi", None) + assert completion.describe("len", 1, 0, None, {}) == { + "available": False, + "signatures": [], + "text": "", + } + + +@pytest.mark.skipif(not completion.is_available(), reason="jedi is optional") +def test_documentation_gives_signatures_and_docstrings(): + import cadquery as cq + + source = "box = cq.Workplane().box(1, 2, 3)\nlen(box)\n" + namespace = {"cq": cq} + + method = completion.describe(source, 1, source.index("box(") + 1, None, namespace) + assert method["available"] + assert method["signatures"][0].startswith("box(length: float") + assert "box" in method["text"].lower() + + builtin = completion.describe(source, 2, 0, None, namespace) + assert builtin["signatures"] == ["len(obj: Sized, /) -> int"] + assert builtin["text"] == "Return the number of items in a container." + + +@pytest.mark.skipif(not completion.is_available(), reason="jedi is optional") +def test_documentation_of_a_variable_is_its_type(): + import cadquery as cq + + source = "box = cq.Workplane().box(1, 2, 3)\nlen(box)\n" + result = completion.describe(source, 2, 4, None, {"cq": cq}) + assert result == { + "available": True, + "signatures": ["box: Workplane"], + "text": "", + } + + +@pytest.mark.skipif(not completion.is_available(), reason="jedi is optional") +def test_documentation_skips_keywords_and_blank_space(): + empty = {"available": True, "signatures": [], "text": ""} + assert completion.describe("import math\n", 1, 0, None, {}) == empty + assert completion.describe("x = 1\n\n", 2, 0, None, {}) == empty + + +def test_long_documentation_is_cut(): + text = "\n".join(f"line {n}" for n in range(100)) + cut = completion._cut(text) + assert cut.endswith(" …") + assert len(cut.splitlines()) == completion.MAX_DOCUMENTATION_LINES + assert completion._cut("short") == "short" + assert len(completion._cut("x" * 10_000)) <= completion.MAX_DOCUMENTATION_CHARS + 2 diff --git a/tests/worker/execution/test_console.py b/tests/worker/execution/test_console.py new file mode 100644 index 000000000..de261a4bb --- /dev/null +++ b/tests/worker/execution/test_console.py @@ -0,0 +1,114 @@ +"""Persistent console state and its connection to the scene.""" + +import cadquery as cq +import pytest + +from cq_worker.console import ConsoleSession +from cq_worker.display import Displayer + + +def test_console_keeps_variables_between_commands(): + console = ConsoleSession() + assert console.execute("size = 3") is False + assert console.execute("volume = size ** 3") is False + assert console.namespace["volume"] == 27 + + +def test_console_deactivates_rich_output_even_when_a_command_exits(): + sent = [] + console = ConsoleSession(Displayer(sent.append)) + + assert console.execute("display('during')", request_id=21) is False + assert sent == [{"id": 21, "type": "display", "text": "'during'", "image": None}] + console.namespace["display"]("late") + assert len(sent) == 1 + + with pytest.raises(SystemExit): + console.execute("raise SystemExit", request_id=22) + console.namespace["display"]("late after exit") + assert len(sent) == 1 + + +def test_console_reports_incomplete_multiline_statement(): + console = ConsoleSession() + assert console.execute("for n in range(3):") is True + assert console.execute(" total = n") is True + assert console.execute("") is False + assert console.namespace["total"] == 2 + + +def test_reset_discards_user_state_and_restores_script_api(): + console = ConsoleSession() + console.execute("custom = 42") + console.reset() + assert "custom" not in console.namespace + assert console.namespace["cq"] is cq + assert callable(console.namespace["show_object"]) + assert callable(console.namespace["debug"]) + + +def test_update_variables_ignores_dunder_names(): + console = ConsoleSession() + console.update_variables({"part_count": 4, "__name__": "overwritten"}) + assert console.namespace["part_count"] == 4 + assert console.namespace["__name__"] == "__console__" + + +def test_take_shown_returns_objects_once(): + console = ConsoleSession() + part = cq.Workplane().box(1, 2, 3) + console.namespace["show_object"](part, name="box", color="red") + shown = console.take_shown() + assert list(shown) == ["box"] + assert shown["box"].obj is part + assert shown["box"].options["color"] == "red" + assert not console.take_shown() + + +def test_debug_api_uses_current_scene_after_take_shown(): + console = ConsoleSession() + console.take_shown() + console.namespace["debug"](cq.Workplane().box(1, 1, 1), name="debug-box") + assert list(console.take_shown()) == ["debug-box"] + + +def test_console_names_shown_and_debugged_objects_after_their_variables(): + console = ConsoleSession() + console.execute("plate = cq.Workplane().box(4, 4, 1)") + console.execute("show_object(plate)") + console.execute("probe = cq.Workplane().sphere(1)") + console.execute("debug(probe)") + shown = console.take_shown() + assert list(shown) == ["plate", "probe"] + assert shown["probe"].options == {"color": "red", "alpha": 0.2} + + # The wrapper keeps working after the scene was handed over. + console.execute("debug(plate)") + assert list(console.take_shown()) == ["plate"] + + +def test_selected_returns_what_the_gui_selected_when_called(): + console = ConsoleSession() + assert console.execute("nothing = selected()") is False + assert console.namespace["nothing"] == [] + + face = cq.Workplane().box(2, 2, 2).faces(">Z").val() + calls = [] + + def resolve(): + calls.append(1) + return [face] + + console.set_selection(resolve) + assert not calls, "resolved only when the command calls selected()" + console.execute("top = selected()[0]") + assert console.namespace["top"] is face + assert "picked in the 3D view" in console.namespace["selected"].__doc__ + + +def test_selected_survives_script_variables_but_not_a_reset(): + console = ConsoleSession() + console.update_variables({"part": 1}) + assert callable(console.namespace["selected"]) + console.reset() + assert callable(console.namespace["selected"]) diff --git a/tests/worker/execution/test_debugger.py b/tests/worker/execution/test_debugger.py new file mode 100644 index 000000000..a4d53e24b --- /dev/null +++ b/tests/worker/execution/test_debugger.py @@ -0,0 +1,112 @@ +import textwrap + +from cq_worker.debugger import Action, Debugger +from cq_worker.execution import SCRIPT_FILENAME, compile_script +from cq_worker.execution import Execution, RunSettings + +SOURCE = textwrap.dedent("""\ + def helper(x): + y = x * 2 + return y + + a = 1 + b = helper(a) + c = b + 1 + """) + + +def trace(breakpoints, actions): + """Run SOURCE, answering each pause with the next action; return pause lines.""" + + lines = [] + script_actions = iter(actions) + + def on_pause(frame): + lines.append(frame.f_lineno) + return next(script_actions, Action.CONTINUE) + + namespace = {} + Debugger(SCRIPT_FILENAME, breakpoints, on_pause).run( + compile_script(SOURCE), namespace + ) + return lines, namespace + + +def test_runs_to_breakpoints_only(): + lines, namespace = trace({6}, []) + assert lines == [6] + assert namespace["c"] == 3 + + +def test_step_over_skips_function_bodies(): + lines, _ = trace({5}, [Action.STEP, Action.STEP, Action.CONTINUE]) + assert lines == [5, 6, 7] + + +def test_step_in_and_out(): + lines, _ = trace({6}, [Action.STEP_IN, Action.STEP_OUT, Action.CONTINUE]) + # Step in lands on the first line of helper, step out back in the caller. + assert lines[:2] == [6, 2] + assert lines[2] in (6, 7) + + +def test_stop_aborts_the_script(): + from cq_worker.debugger import DebugStop + + try: + trace({5}, [Action.STOP]) + except DebugStop: + pass + else: + raise AssertionError("DebugStop expected") + + +def test_stop_is_not_swallowed_by_the_scripts_exception_handlers(): + from cq_worker.debugger import DebugStop + + source = textwrap.dedent("""\ + reached = [] + for attempt in range(3): + try: + reached.append(attempt) + except Exception: + pass + """) + namespace = {} + pauses = [] + + def on_pause(frame): + pauses.append(frame.f_lineno) + return Action.STOP + + try: + Debugger(SCRIPT_FILENAME, {4}, on_pause).run(compile_script(source), namespace) + except DebugStop: + pass + else: + raise AssertionError("DebugStop expected") + assert pauses == [4] + assert namespace["reached"] == [] + + +def test_project_module_breakpoints_pause_and_can_be_updated(tmp_path): + module = tmp_path / "helper_req08.py" + module.write_text("def work(value):\n doubled = value * 2\n return doubled\n") + execution = Execution( + "import helper_req08\nanswer = helper_req08.work(4)\n", + str(tmp_path / "main.py"), + RunSettings(), + ) + pauses = [] + + def on_pause(frame): + pauses.append((frame.f_code.co_filename, frame.f_lineno)) + debugger.set_breakpoints([], {}) + return Action.CONTINUE + + debugger = Debugger( + SCRIPT_FILENAME, [], on_pause, str(tmp_path), {str(module): [2, 3]} + ) + assert execution.run(debugger.run), execution.error + assert pauses == [(str(module), 2)] + assert execution.namespace["answer"] == 8 diff --git a/tests/worker/execution/test_diagnostics.py b/tests/worker/execution/test_diagnostics.py new file mode 100644 index 000000000..dcc85663d --- /dev/null +++ b/tests/worker/execution/test_diagnostics.py @@ -0,0 +1,54 @@ +"""CAD advice supplements, but never replaces, the Python traceback.""" + +import json + +from cq_worker.cli import main +from cq_worker.diagnostics import diagnose +from cq_worker.execution import Execution, RunSettings + + +def test_failed_fillet_keeps_the_traceback_and_links_the_cad_call(): + source = ( + "part = cq.Workplane().box(1, 1, 1)\n" "result = part.edges().fillet(100)\n" + ) + execution = Execution(source, None, RunSettings()) + assert not execution.run() + error = execution.error + assert error is not None + assert "BRep_API: command not done" in error["text"] + assert error["line"] == 2 + advice = error["diagnostic"] + assert advice["operation"] == "fillet" + assert advice["line"] == 2 + assert any("radius" in hint for hint in advice["hints"]) + + +def test_selector_advice_needs_a_related_error(): + source = 'selected = part.faces(">Z")' + advice = diagnose(ValueError("Nothing selected"), source, 1) + assert advice is not None + assert advice["operation"] == "faces" + assert advice["receiver"] == "part" + assert diagnose(RuntimeError("unrelated failure"), source, 1) is None + assert diagnose(ValueError("Nothing selected"), source, None) is None + + +def test_syntax_errors_and_unrelated_python_lines_get_no_cad_advice(): + assert diagnose(SyntaxError("invalid syntax"), 'part.faces(">Z")', 1) is None + assert diagnose(RuntimeError("fillet example"), "part.fillet(1)", 1) is None + assert ( + diagnose(RuntimeError("BRep_API: command not done"), "raise RuntimeError()", 1) + is None + ) + + +def test_headless_json_includes_advice_with_the_original_error(tmp_path, capsys): + script = tmp_path / "failed_fillet.py" + script.write_text( + "part = cq.Workplane().box(1, 1, 1)\n" "part.edges().fillet(100)\n", + encoding="utf-8", + ) + assert main(["check", str(script), "--json"]) == 1 + payload = json.loads(capsys.readouterr().out) + assert payload["diagnostic"]["operation"] == "fillet" + assert "StdFail_NotDone" in payload["traceback"] diff --git a/tests/worker/execution/test_display.py b/tests/worker/execution/test_display.py new file mode 100644 index 000000000..ed7db2b9c --- /dev/null +++ b/tests/worker/execution/test_display.py @@ -0,0 +1,191 @@ +"""Rich console output: bundles gathered, checked and bounded in the worker.""" + +import base64 +import builtins +import threading + +import pytest + +from cq_worker import display +from cq_worker.display import Displayer, message, mime_bundle + +#: A 1×1 PNG. +PNG = base64.b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==" +) +JPEG = b"\xff\xd8\xff\xe0" + b"\x00" * 16 + + +class Rich: + def __init__(self, **reprs): + for name, value in reprs.items(): + setattr(self, f"_repr_{name}_", value) + + def __repr__(self): + return "Rich()" + + +def test_bundles_are_gathered_as_jupyter_does(): + bundle = mime_bundle( + Rich(mimebundle=lambda include, exclude: ({"text/html": "x"}, {})) + ) + assert bundle == {"text/html": "x", "text/plain": "Rich()"} + assert mime_bundle(Rich(png=lambda: PNG))["image/png"] == PNG + assert mime_bundle(Rich(png=lambda: (PNG, {"width": 1})))["image/png"] == PNG + # A broken representation hides nothing else. + broken = mime_bundle(Rich(png=lambda: 1 / 0)) + assert broken == {"text/plain": "Rich()"} + empty_tuple = mime_bundle(Rich(png=lambda: ())) + assert empty_tuple == {"text/plain": "Rich()"} + + invalid_plain = mime_bundle( + Rich(mimebundle=lambda include, exclude: {"text/plain": b"not text"}) + ) + assert invalid_plain["text/plain"] == "Rich()" + + class Bad: + def __repr__(self): + raise RuntimeError("no") + + assert mime_bundle(Bad())["text/plain"].startswith("<") + + class BrokenAttribute: + def __getattr__(self, _name): + raise RuntimeError("broken descriptor") + + assert "BrokenAttribute" in mime_bundle(BrokenAttribute())["text/plain"] + # Classes have the methods unbound: they are not called. + assert mime_bundle(Rich) == {"text/plain": repr(Rich)} + + +def test_only_checked_images_and_plain_text_leave_the_worker(): + fields = message({"text/plain": "x", "image/png": PNG}, images_left=1) + assert fields["image"] == { + "format": "png", + "data": base64.b64encode(PNG).decode(), + } + assert set(fields) == {"text", "image"}, "no HTML, SVG or other markup" + # Bundles from _repr_mimebundle_ hold base64 text. + as_text = message({"image/jpeg": base64.b64encode(JPEG).decode()}, images_left=1) + assert as_text["image"]["format"] == "jpeg" + # Not what it claims to be. + assert message({"image/png": b""}, images_left=1)["image"] is None + assert message({"image/png": "not base64!"}, images_left=1)["image"] is None + + +def test_results_are_bounded(monkeypatch): + monkeypatch.setattr(display, "MAX_IMAGE_BYTES", len(PNG) + 10) + big = PNG + b"\x00" * 64 + fields = message({"text/plain": "big", "image/png": big}, images_left=1) + assert fields["image"] is None and "over the limit" in fields["text"] + encoded = message( + {"text/plain": "encoded", "image/png": base64.b64encode(big).decode()}, + images_left=1, + ) + assert encoded["image"] is None and "over the limit" in encoded["text"] + fields = message({"text/plain": "one more", "image/png": PNG}, images_left=0) + assert fields["image"] is None and "too many images" in fields["text"] + long = message({"text/plain": "x" * (display.MAX_TEXT_CHARS + 10)}, images_left=1) + assert long["text"].endswith("characters]") + assert len(long["text"]) < display.MAX_TEXT_CHARS + 100 + + +def test_the_displayer_counts_images_per_command_and_keeps_underscore(monkeypatch): + monkeypatch.setattr(display, "MAX_IMAGES_PER_REQUEST", 2) + sent = [] + displayer = Displayer(sent.append) + displayer.start(7) + displayer.display(*[Rich(png=lambda: PNG)] * 3) + assert [m["image"] is not None for m in sent] == [True, True, False] + assert {m["id"] for m in sent} == {7} + displayer.start(8) + displayer.display(Rich(png=lambda: PNG)) + assert sent[-1]["image"] is not None, "a new command, a new allowance" + + displayer.displayhook(None) + assert len(sent) == 4, "None is not shown" + displayer.displayhook(41) + assert sent[-1] == { + "id": 8, + "type": "display", + "text": "41", + "image": None, + } + assert builtins._ == 41 + + +def test_the_displayer_bounds_text_only_results_per_command(monkeypatch): + monkeypatch.setattr(display, "MAX_RESULTS_PER_REQUEST", 2) + represented = 0 + + class Counted: + def __repr__(self): + nonlocal represented + represented += 1 + return "value" + + sent = [] + displayer = Displayer(sent.append) + displayer.start(10) + displayer.display(Counted(), Counted(), Counted()) + displayer.display(Counted()) + + assert represented == 2, "discarded values do not run user representation code" + assert len(sent) == 3 + assert "truncated after 2 results" in sent[-1]["text"] + + displayer.start(11) + displayer.display(Counted()) + assert represented == 3 and sent[-1]["text"] == "value" + + +def test_displayer_rejects_late_and_background_results(): + sent = [] + displayer = Displayer(sent.append) + + displayer.display("before") + displayer.start(17) + background = threading.Thread(target=displayer.display, args=("background",)) + background.start() + background.join() + assert sent == [], "another thread cannot impersonate the active command" + + displayer.display("current") + assert sent == [{"id": 17, "type": "display", "text": "'current'", "image": None}] + displayer.finish() + displayer.display("late") + assert len(sent) == 1, "a retained display call cannot leak into a later request" + + +def test_matplotlib_figures_are_shown_as_images(): + pyplot = pytest.importorskip("matplotlib.pyplot") + figure, axes = pyplot.subplots(figsize=(2, 1)) + axes.plot([0, 1], [1, 0]) + image = mime_bundle(figure)["image/png"] + assert image.startswith(b"\x89PNG") + pyplot.close(figure) + + +def test_the_console_sends_results_and_images_after_what_was_printed(conversation): + png = base64.b64encode(PNG).decode() + source = ( + "print('first', end='')\n" + "class Picture:\n" + " def _repr_png_(self):\n" + f" import base64; return base64.b64decode('{png}')\n" + "\n" + "display(Picture(), 'a text')" + ) + talk = conversation( + {"cmd": "console", "id": 1, "source": "6 * 7"}, + {"cmd": "console", "id": 2, "source": source}, + ) + talk.serve() + + (result,) = [m for m in talk.of_type("display") if m["id"] == 1] + assert result["text"] == "42" and result["image"] is None + kinds = [m["type"] for m in talk.messages if m.get("id") == 2] + assert kinds == ["output", "display", "display", "console_result"] + picture, text = [m for m in talk.of_type("display") if m["id"] == 2] + assert picture["image"]["format"] == "png" + assert text == {"type": "display", "id": 2, "text": "'a text'", "image": None} diff --git a/tests/worker/execution/test_environment.py b/tests/worker/execution/test_environment.py new file mode 100644 index 000000000..a60224aea --- /dev/null +++ b/tests/worker/execution/test_environment.py @@ -0,0 +1,79 @@ +"""Script isolation, imports, and variable inspection.""" + +import linecache +import os +import sys + +import pytest + +from cq_worker.execution import ( + SCRIPT_FILENAME, + RunSettings, + compile_script, + describe_variables, + script_environment, +) + + +def test_compile_script_populates_linecache_for_tracebacks(): + code = compile_script("a = 1\nraise RuntimeError('broken')\n") + assert code.co_filename == SCRIPT_FILENAME + assert linecache.getline(SCRIPT_FILENAME, 2) == "raise RuntimeError('broken')\n" + + +def test_script_environment_restores_cwd_and_path_after_exception(tmp_path): + script = tmp_path / "part.py" + old_cwd = os.getcwd() + old_path = list(sys.path) + + with pytest.raises(RuntimeError, match="stop"): + with script_environment(str(script), RunSettings()): + assert os.getcwd() == str(tmp_path) + assert sys.path[0] == str(tmp_path) + raise RuntimeError("stop") + + assert os.getcwd() == old_cwd + assert sys.path == old_path + + +def test_script_environment_respects_disabled_path_and_cwd_changes(tmp_path): + old_cwd = os.getcwd() + old_path = list(sys.path) + settings = RunSettings( + add_script_dir_to_path=False, + change_working_dir=False, + reload_imported_modules=False, + ) + with script_environment(str(tmp_path / "part.py"), settings): + assert os.getcwd() == old_cwd + assert sys.path == old_path + + +def test_script_environment_without_file_does_not_change_cwd_or_path(): + old_cwd = os.getcwd() + old_path = list(sys.path) + with script_environment(None, RunSettings()): + assert os.getcwd() == old_cwd + assert sys.path == old_path + + +def test_describe_variables_skips_private_and_hidden_values(): + rows = describe_variables({"_private": 1, "secret": 2, "visible": 3}, {"secret"}) + assert rows == [{"name": "visible", "type": "int", "value": "3"}] + + +def test_describe_variables_handles_broken_string_conversion(): + class Broken: + def __str__(self): + raise ValueError("cannot display") + + (row,) = describe_variables({"bad": Broken()}, set()) + assert row["name"] == "bad" + assert row["type"] == "Broken" + assert row["value"] == "" + + +@pytest.mark.parametrize("message", [None, {}, {"unknown": 1}]) +def test_run_settings_defaults_for_missing_fields(message): + settings = RunSettings.from_message(message) + assert settings == RunSettings() diff --git a/tests/worker/execution/test_examples.py b/tests/worker/execution/test_examples.py new file mode 100644 index 000000000..cf02d08f6 --- /dev/null +++ b/tests/worker/execution/test_examples.py @@ -0,0 +1,23 @@ +"""Smoke tests for every bundled example. + +The examples 01 to 08 shipped before the Rust rewrite and are compatibility +fixtures; later examples are additions held to the same standard. +""" + +from pathlib import Path + +import pytest + +from cq_worker.execution import Execution, RunSettings + +EXAMPLES = Path(__file__).parents[3] / "examples" +LEGACY_EXAMPLES = sorted(EXAMPLES.glob("*.py")) + + +@pytest.mark.parametrize("path", LEGACY_EXAMPLES, ids=lambda path: path.name) +def test_legacy_example_executes_and_produces_a_model(path): + execution = Execution(path.read_text(encoding="utf-8"), str(path), RunSettings()) + execution.run() + + assert execution.error is None, execution.error + assert execution.shown, f"{path.name} did not produce a visible model" diff --git a/tests/worker/execution/test_execution.py b/tests/worker/execution/test_execution.py new file mode 100644 index 000000000..872a59d69 --- /dev/null +++ b/tests/worker/execution/test_execution.py @@ -0,0 +1,139 @@ +import sys +import textwrap + +from cq_worker.execution import SCRIPT_FILENAME, Execution, RunSettings, rand_color + + +def run(source: str, path=None, **settings) -> Execution: + execution = Execution(textwrap.dedent(source), path, RunSettings(**settings)) + execution.run() + return execution + + +def test_show_object_names_from_variables(): + execution = run(""" + result = cq.Workplane().box(1, 1, 1) + show_object(result) + show_object(cq.Workplane().sphere(1), name="ball", options={"color": "red"}) + show_object(cq.Workplane().sphere(2), alpha=0.5) + """) + + assert execution.error is None + assert list(execution.shown) == ["result", "ball", "Workplane 1"] + assert execution.shown["ball"].options == {"color": "red"} + assert execution.shown["Workplane 1"].options == {"alpha": 0.5} + + +def test_injected_api_is_removed_afterwards(): + execution = run("x = 1") + assert "show_object" not in execution.namespace + assert "cq" in execution.namespace + assert execution.namespace["__name__"] == "__cq_main__" + + +def test_debug_overlays_in_translucent_red(): + execution = run("debug(cq.Workplane().box(1, 1, 1), name='probe')") + assert execution.shown["probe"].options == {"color": "red", "alpha": 0.2} + + +def test_runtime_errors_point_at_the_script_line(): + execution = run(""" + a = 1 + b = a / 0 + """) + + error = execution.error + assert error["type_name"] == "ZeroDivisionError" + assert error["line"] == 3 + assert error["frames"][0]["file"] == SCRIPT_FILENAME + assert error["frames"][0]["code"] == "b = a / 0" + + +def test_syntax_errors_are_reported(): + execution = run("x = (1,\n") + assert execution.error["type_name"] == "SyntaxError" + assert execution.error["line"] is not None + + +def test_errors_inside_script_functions_keep_the_call_chain(): + execution = run(""" + def inner(): + raise ValueError("boom") + + inner() + """) + lines = [f["line"] for f in execution.error["frames"]] + assert lines == [5, 3] + assert execution.error["message"] == "boom" + + +def test_sys_exit_ends_the_script_quietly(): + execution = run("import sys\nx = 1\nsys.exit()\ny = 2") + assert execution.error is None + assert "x" in execution.namespace and "y" not in execution.namespace + + +def test_rand_color_is_reproducible(): + first = run("c = rand_color()").namespace["c"] + second = run("c = rand_color()").namespace["c"] + assert first == second + assert first["alpha"] == 1.0 + assert all(10 <= v < 100 for v in first["color"]) + assert len(rand_color(cfloat=True)) == 4 + + +def test_script_directory_and_module_reloading(tmp_path): + helper = tmp_path / "helper_module_for_test.py" + script = tmp_path / "main.py" + helper.write_text("VALUE = 1\n") + + source = "import os, helper_module_for_test\nvalue = helper_module_for_test.VALUE\ncwd = os.getcwd()" + first = run(source, path=str(script)) + assert first.error is None + assert first.namespace["value"] == 1 + assert first.namespace["cwd"] == str(tmp_path) + assert "helper_module_for_test" not in sys.modules + assert str(tmp_path) not in sys.path + + # A different length, so the stale bytecode cache cannot match even when + # both writes fall within the same second. + helper.write_text("VALUE = 22\n") + assert run(source, path=str(script)).namespace["value"] == 22 + + +def test_settings_from_message_ignore_unknown_keys(): + settings = RunSettings.from_message({"reload_cq": True, "bogus": 1}) + assert settings.reload_cq is True + assert settings.change_working_dir is True + + +def test_long_values_are_truncated(): + from cq_worker.execution import MAX_VALUE_LENGTH, describe_variables + + (row,) = describe_variables({"long": "x" * 5000}, hidden=set()) + assert len(row["value"]) == MAX_VALUE_LENGTH + assert row["value"].endswith("…") + + +def test_duplicate_show_object_names_emit_a_warning_once_per_name(caplog): + import logging + + with caplog.at_level(logging.WARNING, logger="script"): + execution = run(""" + for i in range(5): + part = cq.Workplane("XY").box(10, 10, 10) + show_object(part, name="part") + inferred = cq.Workplane("XY").sphere(2) + show_object(inferred) + """) + + assert execution.error is None + assert list(execution.shown) == ["part", "inferred"] + warnings = [r.getMessage() for r in caplog.records if r.name == "script"] + assert len(warnings) == 2 + assert '"part"' in warnings[0] + assert '"inferred"' in warnings[1] + assert "replaced" in warnings[0] + assert "distinct names" in warnings[0] + + diff --git a/tests/worker/execution/test_navigation.py b/tests/worker/execution/test_navigation.py new file mode 100644 index 000000000..b91e4701f --- /dev/null +++ b/tests/worker/execution/test_navigation.py @@ -0,0 +1,73 @@ +from pathlib import Path + +import pytest + +from cq_worker import navigation + + +def test_outline_lists_nested_symbols_without_running_script(): + source = """ +VALUE = 4 +class Fixture: + def make(self): + raise RuntimeError("must not run") +async def build(): + pass +""" + assert [(s["name"], s["kind"], s["depth"]) for s in navigation.outline(source)] == [ + ("VALUE", "variable", 0), + ("Fixture", "class", 0), + ("make", "function", 1), + ("build", "function", 0), + ] + + +@pytest.mark.skipif(navigation.jedi is None, reason="jedi is optional") +def test_definition_and_references_cross_project_files(tmp_path: Path): + helper = tmp_path / "helper.py" + helper.write_text("def make_box():\n return 1\n", encoding="utf-8") + source = "from helper import make_box\nresult = make_box()\n" + main = tmp_path / "main.py" + main.write_text(source, encoding="utf-8") + + definition = navigation.navigate( + source, str(main), str(tmp_path), 2, 13, "definition" + ) + assert definition["available"] + assert definition["locations"] == [ + { + "name": "make_box", + "kind": "function", + "path": str(helper.resolve()), + "line": 1, + "column": 4, + } + ] + references = navigation.navigate( + source, str(main), str(tmp_path), 2, 13, "references" + ) + assert {(item["path"], item["line"]) for item in references["locations"]} == { + (str(helper.resolve()), 1), + (None, 1), + (None, 2), + } + + +def test_invalid_cursor_and_optional_jedi(tmp_path: Path, monkeypatch): + assert ( + navigation.navigate("x = 1", None, str(tmp_path), 5, 0, "definition")[ + "locations" + ] + == [] + ) + monkeypatch.setattr(navigation, "jedi", None) + assert ( + navigation.navigate("x = 1", None, None, 1, 0, "definition")["available"] + is False + ) + assert navigation.outline("def f():\n pass\n")[0]["name"] == "f" + + +def test_rejects_unknown_mode(): + with pytest.raises(ValueError, match="Unknown navigation mode"): + navigation.navigate("", None, None, 1, 0, "rename") diff --git a/tests/worker/execution/test_profiling.py b/tests/worker/execution/test_profiling.py new file mode 100644 index 000000000..cf41613d4 --- /dev/null +++ b/tests/worker/execution/test_profiling.py @@ -0,0 +1,123 @@ +"""Per-line profiling of script runs.""" + +import os +import sys +import textwrap + +from cq_worker.execution import SCRIPT_FILENAME, Execution, RunSettings +from cq_worker.profiling import OPERATIONS_PER_LINE, LineProfiler + + +def profile(source: str) -> tuple[Execution, dict]: + execution = Execution(textwrap.dedent(source), None, RunSettings()) + profiler = LineProfiler(SCRIPT_FILENAME) + execution.run(profiler.run) + return execution, profiler.result() + + +def by_line(result: dict) -> dict[int, dict]: + return {entry["line"]: entry for entry in result["lines"]} + + +def test_each_line_gets_the_time_it_took_with_everything_it_called(): + execution, result = profile("""\ + import time + + def slow(): + time.sleep(0.12) + return 1 + + total = 0 + for _ in range(3): + total += slow() + time.sleep(0.05) + """) + + assert execution.error is None + lines = by_line(result) + # The function's own line, three times. + assert lines[4]["hits"] == 3 and lines[4]["seconds"] >= 0.3 + # The line calling it includes what it called. + assert lines[9]["hits"] == 3 and lines[9]["seconds"] >= lines[4]["seconds"] + assert lines[8]["hits"] == 4, "the loop's own line, once more at the end" + assert 0.04 <= lines[10]["seconds"] < 0.3 + assert lines[7]["seconds"] < 0.01 + assert [entry["line"] for entry in result["lines"]] == sorted(lines) + + +def test_calls_into_cadquery_are_timed_per_line_and_operation(): + _, result = profile("""\ + box = cq.Workplane().box(4, 4, 4) + for size in (0.3, 0.4): + rounded = box.edges("|Z").fillet(size) + """) + + operations = {(op["line"], op["name"]): op for op in result["operations"]} + assert operations[(1, "Workplane.box")]["calls"] == 1 + fillet = operations[(3, "Workplane.fillet")] + assert fillet["calls"] == 2 and fillet["seconds"] > 0 + assert operations[(3, "Workplane.edges")]["calls"] == 2 + # Operations are the script's calls, not CadQuery's calls to itself. + assert all(op["line"] in (1, 3) for op in result["operations"]) + # Each is included in its line's time. + assert by_line(result)[3]["seconds"] >= fillet["seconds"] + + +def test_only_the_slowest_operations_of_a_line_are_kept(): + _, result = profile(""" w = cq.Workplane() + made = [w.box(1, 1, 1), w.sphere(1), w.cylinder(1, 1), w.rect(1, 1), w.circle(1), w.polygon(5, 1), w.ellipse(1, 0.5), w.slot2D(2, 1), w.text("a", 1, 1), w.wedge(1, 1, 1, 0, 0, 1, 1)] + """) + line = [op for op in result["operations"] if op["line"] == 2] + assert len(line) == OPERATIONS_PER_LINE, "ten operations, the slowest kept" + seconds = [op["seconds"] for op in line] + assert seconds == sorted(seconds, reverse=True) + assert "Workplane.text" in {op["name"] for op in line}, "text is the slowest" + + +def test_a_failing_script_keeps_the_profile_up_to_the_error(): + tracer = sys.gettrace() + execution, result = profile("""\ + import time + time.sleep(0.05) + 1 / 0 + never = 1 + """) + + assert execution.error["type_name"] == "ZeroDivisionError" + lines = by_line(result) + assert lines[2]["seconds"] >= 0.04 and 3 in lines and 4 not in lines + assert sys.gettrace() is tracer, "the previous trace function is restored" + + +def test_profiling_is_part_of_a_run_on_request(conversation): + script = "box = cq.Workplane().box(1, 2, 3)\nshow_object(box)\n" + talk = conversation( + {"cmd": "run", "id": 1, "script": script, "profile": True}, + {"cmd": "run", "id": 2, "script": script}, + {"cmd": "run", "id": 3, "script": script, "profile": True, "debug": True}, + ) + talk.serve() + + profiled, plain, debugged = talk.of_type("run_finished") + assert [entry["line"] for entry in profiled["profile"]["lines"]] == [1, 2] + assert profiled["profile"]["operations"][0]["name"] == "Workplane.box" + assert plain["profile"] is None + # The debugger traces the script itself: it is not profiled too. + assert debugged["profile"] is None + + +def test_project_module_lines_have_paths_and_source_snapshots(tmp_path): + module = tmp_path / "timed_helper_req08.py" + module.write_text("def work(value):\n result = value * 2\n return result\n") + execution = Execution( + "import timed_helper_req08\nanswer = timed_helper_req08.work(4)\n", + str(tmp_path / "main.py"), + RunSettings(), + ) + profiler = LineProfiler(SCRIPT_FILENAME, str(tmp_path)) + assert execution.run(profiler.run), execution.error + result = profiler.result() + path = os.path.normcase(os.path.realpath(module)) + module_lines = {entry["line"] for entry in result["lines"] if entry["file"] == path} + assert {2, 3} <= module_lines + assert result["sources"][path] == module.read_text() diff --git a/tests/worker/execution/test_provenance.py b/tests/worker/execution/test_provenance.py new file mode 100644 index 000000000..0438363b4 --- /dev/null +++ b/tests/worker/execution/test_provenance.py @@ -0,0 +1,116 @@ +"""The script lines that created CadQuery objects (Go to source).""" + +import textwrap + +import cadquery as cq + +from cq_worker import inspector +from cq_worker.execution import Execution, RunSettings +from cq_worker.provenance import creation_line +from cq_worker.scene import Registry, SceneBuilder +from cq_worker.tessellation import Tolerance + + +def run(source, path=None): + execution = Execution(textwrap.dedent(source), path, RunSettings()) + assert execution.run(), execution.error + return execution + + +def test_each_object_remembers_the_line_that_created_it(): + execution = run("""\ + base = cq.Workplane("XY") + plate = ( + base.box(10, 10, 2) + .faces(">Z") + .workplane() + .hole(3) + ) + solid = cq.Solid.makeBox(1, 2, 3) + sketch = cq.Sketch().rect(2, 2) + """) + names = execution.namespace + assert creation_line(names["base"]) == 1 + # Each step of a chain points to its own line. + assert creation_line(names["plate"]) == 6 + assert creation_line(names["plate"].parent) == 5 + assert creation_line(names["plate"].parent.parent.parent) == 3 + assert creation_line(names["plate"].val()) == 6 + assert creation_line(names["solid"]) == 8 + assert creation_line(names["sketch"]) == 9 + + +def test_objects_made_in_functions_and_modules_point_into_the_script(tmp_path): + (tmp_path / "helpers.py").write_text( + "import cadquery as cq\n\n\ndef peg():\n return cq.Workplane().cylinder(4, 1)\n" + ) + script = tmp_path / "part.py" + source = """\ + import helpers + + def tab(width): + return cq.Workplane().box(width, 1, 1) + + made_here = tab(3) + made_there = helpers.peg() + """ + script.write_text(textwrap.dedent(source)) + names = run(source, str(script)).namespace + # Inside the script's own function... + assert creation_line(names["made_here"]) == 4 + # ...and, for a helper module, the script line that called it. + assert creation_line(names["made_there"]) == 7 + + +def test_assembly_children_point_to_their_add_call(): + names = run("""\ + box = cq.Workplane().box(1, 1, 1) + assembly = cq.Assembly() + assembly.add(box, name="first") + assembly.add( + cq.Workplane().sphere(1), + name="second", + ) + """).namespace + assembly = names["assembly"] + assert creation_line(assembly) == 2 + assert [creation_line(child) for child in assembly.children] == [3, 4] + + +def test_constructors_are_restored_after_a_run_even_a_failing_one(): + originals = (cq.Workplane.__init__, cq.Shape.__init__, cq.Assembly.__init__) + run("x = cq.Workplane().box(1, 1, 1)") + failing = Execution("cq.Workplane().box(1, 1, 1)\n1 / 0\n", None, RunSettings()) + assert not failing.run() + assert (cq.Workplane.__init__, cq.Shape.__init__, cq.Assembly.__init__) == originals + # Outside a run nothing is recorded. + assert creation_line(cq.Workplane().box(1, 1, 1)) is None + + +def test_scene_nodes_and_stack_frames_carry_their_lines(): + execution = run("""\ + plate = cq.Workplane().box(4, 4, 1).faces(">Z").workplane().hole(1) + assembly = cq.Assembly().add(cq.Workplane().sphere(1), name="ball") + show_object(plate) + show_object(assembly) + """) + builder = SceneBuilder(Registry(), Tolerance()) + plate, assembly = builder.build(execution.shown) + assert plate["line"] == 1 + assert assembly["line"] == 2 + assert assembly["children"][0]["line"] == 2 + + frames = inspector.describe_stack( + inspector.stack_frames(execution.namespace["plate"]) + ) + assert {frame["line"] for frame in frames} == {1} + assert frames[0]["items"][0]["line"] == 1 + + +def test_a_node_without_a_creation_line_points_to_its_show_object_call(): + made_before = cq.Workplane().box(1, 1, 1) # created outside any run + execution = Execution("\nshow_object(prebuilt)\n", None, RunSettings()) + execution.namespace["prebuilt"] = made_before + assert execution.run(), execution.error + (node,) = SceneBuilder(Registry(), Tolerance()).build(execution.shown) + assert node["line"] == 2 diff --git a/tests/worker/geometry/test_assembly_checks.py b/tests/worker/geometry/test_assembly_checks.py new file mode 100644 index 000000000..ee9a94658 --- /dev/null +++ b/tests/worker/geometry/test_assembly_checks.py @@ -0,0 +1,64 @@ +import cadquery as cq +import pytest + +from cq_worker.assembly_checks import ( + AssemblyError, + assembly_diagnostics, + require_constrained_assembly, +) + + +def test_unconstrained_assembly_reports_free_dof_and_overlap(): + box = cq.Workplane().box(2, 2, 2) + assembly = cq.Assembly().add(box, name="first").add(box, name="second") + report = assembly_diagnostics(assembly) + assert report["minimum_free_dof"] == 6 + assert report["unconstrained_components"] == ["first", "second"] + assert "underconstrained" in report["issues"] + assert "interference" in report["issues"] + with pytest.raises(AssemblyError): + require_constrained_assembly(assembly) + + +def test_solved_fixed_assembly_reports_no_free_dof_or_interference(): + box = cq.Workplane().box(1, 1, 1) + assembly = ( + cq.Assembly() + .add(box, name="first") + .add(box, name="second", loc=cq.Location((3, 0, 0))) + .constrain("first", "Fixed") + .constrain("second", "Fixed") + .solve() + ) + report = require_constrained_assembly(assembly) + assert report["solver_success"] is True + assert report["minimum_free_dof"] == 0 + assert report["interferences"] == [] + + +def test_plane_mate_alone_leaves_one_rotational_degree_of_freedom(): + box = cq.Workplane().box(1, 1, 1) + assembly = ( + cq.Assembly() + .add(box, name="base") + .add(box, name="top", loc=cq.Location((0, 0, 3))) + .constrain("base", "Fixed") + .constrain("base@faces@>Z", "top@faces@ 100 + + +def test_interfering_parts_pause_export_before_the_writer_opens_file(tmp_path): + plate = cq.Workplane().box(20, 20, 5).faces(">Z").workplane().hole(5).val() + pin = cq.Workplane().circle(3).extrude(10).translate((0, 0, -5)).val() + registry = Registry() + plate_key = registry.add(RegistryEntry(plate, plate, name="plate")) + pin_key = registry.add(RegistryEntry(pin, pin, name="pin")) + path = tmp_path / "joint.step" + with pytest.raises(checking.GeometryInvalid) as error: + exporting.export(registry, [plate_key, pin_key], "step", str(path)) + assert error.value.reports == [] + assert error.value.interferences[0]["kind"] == "interference" + assert not path.exists() + + exporting.export( + registry, + [plate_key, pin_key], + "step", + str(path), + on_interference="ignore", + ) + assert path.stat().st_size > 100 diff --git a/tests/worker/geometry/test_display_options.py b/tests/worker/geometry/test_display_options.py new file mode 100644 index 000000000..ef9fc9ae5 --- /dev/null +++ b/tests/worker/geometry/test_display_options.py @@ -0,0 +1,104 @@ +"""Color and opacity inputs accepted by show_object.""" + +import math + +import pytest + +from cq_worker.scene import DisplayOptions, non_finite, parse_color + + +@pytest.mark.parametrize( + ("color", "rgb", "alpha"), + [ + ("#f00", (1, 0, 0), None), + ("#11223344", (0x11 / 255, 0x22 / 255, 0x33 / 255), 0x44 / 255), + ([0, 128, 255], (0, 128 / 255, 1), None), + ((0.2, 0.4, 0.6, 0.8), (0.2, 0.4, 0.6), 0.8), + ], +) +def test_supported_color_forms(color, rgb, alpha): + actual_rgb, actual_alpha = parse_color(color) + assert actual_rgb == pytest.approx(rgb) + assert actual_alpha == (pytest.approx(alpha) if alpha is not None else None) + + +@pytest.mark.parametrize("color", ["#12", "#zzzzzz", (-1, 0, 0), (0.0, 1.1, 0.0)]) +def test_invalid_color_forms_are_rejected(color): + with pytest.raises(ValueError): + parse_color(color) + + +@pytest.mark.parametrize(("input_alpha", "expected"), [(-2, 0), (0.25, 0.25), (5, 1)]) +def test_display_opacity_is_clamped(input_alpha, expected): + assert DisplayOptions.parse({"alpha": input_alpha}).alpha == expected + + +@pytest.mark.parametrize( + "options", + [ + {"alpha": math.nan}, + {"alpha": math.inf}, + {"rgba": (1, 0, 0, math.nan)}, + ], +) +def test_non_finite_opacity_is_ignored(options, caplog): + parsed = DisplayOptions.parse(options) + assert parsed.alpha is None + assert "finite number" in caplog.text + assert non_finite(parsed.to_message()) is None + + +def test_one_invalid_option_keeps_the_others(caplog): + parsed = DisplayOptions.parse({"color": "#zz", "alpha": 0.5, "edgecolor": "blue"}) + assert parsed.color is None + assert parsed.alpha == 0.5 + assert parsed.edge_color == pytest.approx((0, 0, 1), abs=1e-3) + assert "Ignoring invalid display option" in caplog.text + + +def test_non_finite_numbers_are_found_where_they_are(): + assert non_finite({"parts": [{"transform": [1.0, 2.0]}]}) is None + assert non_finite({"parts": [{"transform": [1.0, math.nan]}]}) == ( + "parts[0].transform[1]" + ) + assert non_finite({"alpha": math.inf, "mesh": "AAAA"}) == "alpha" + + +def test_explicit_opacity_overrides_color_opacity(): + options = DisplayOptions.parse({"color": "#ff000080", "alpha": 0.9}) + assert options.color == pytest.approx((1, 0, 0)) + assert options.alpha == 0.9 + + +def test_display_options_message_has_all_fields(): + assert DisplayOptions.parse(None).to_message() == { + "color": None, + "alpha": None, + "edge_color": None, + "finish": None, + } + + +@pytest.mark.parametrize( + ("material", "finish"), + [ + ("matte plastic", "matte_plastic"), + ("Glossy-Plastic", "glossy_plastic"), + ("brushed_steel", "brushed_steel"), + (" ALUMINIUM ", "aluminum"), + ("wood", "wood"), + ("default", "default"), + ], +) +def test_materials_are_named_loosely(material, finish): + assert DisplayOptions.parse({"material": material}).finish == finish + assert DisplayOptions.parse({"material": material}).to_message()["finish"] == finish + + +@pytest.mark.parametrize("material", ["unobtainium", 3, None]) +def test_an_unknown_material_is_ignored_and_the_rest_applies(material, caplog): + parsed = DisplayOptions.parse({"material": material, "color": "red"}) + assert parsed.finish is None + assert parsed.color == pytest.approx((1, 0, 0), abs=1e-3) + assert "material" in caplog.text + assert parsed.to_message()["finish"] is None diff --git a/tests/worker/geometry/test_engineering.py b/tests/worker/geometry/test_engineering.py new file mode 100644 index 000000000..96a68b4e6 --- /dev/null +++ b/tests/worker/geometry/test_engineering.py @@ -0,0 +1,89 @@ +import cadquery as cq +import pytest + +from cq_worker.engineering import ( + BeamSection, + EngineeringError, + EngineeringMaterial, + beam_check, + require_beam, + tool_access, +) +from cq_worker.execution import Execution, RunSettings + +STEEL = EngineeringMaterial("Steel", 7.85, 210_000, 250, expansion_per_c=12e-6) + + +def test_hollow_tube_section_and_self_weight_have_explicit_units(): + section = BeamSection.hollow_rectangle(20, 20, 1.5) + assert section.area_mm2 == pytest.approx(111) + assert section.inertia_mm4 == pytest.approx(6373.25) + assert section.minimum_wall_mm == 1.5 + report = beam_check(section=section, material=STEEL, length_mm=700) + assert report["mass_kg"] == pytest.approx(0.609945) + assert report["maximum_stress_mpa"] > 0 + + +def test_load_deflection_wall_and_yield_requirements_are_checked(): + section = BeamSection.hollow_rectangle(20, 20, 1.5) + safe = beam_check( + section=section, + material=STEEL, + length_mm=700, + transverse_load_n=100, + maximum_deflection_mm=10, + required_wall_mm=1.2, + required_safety_factor=2, + ) + assert safe["ok"] + assert safe["deflection_mm"] > 8 + failed = beam_check( + section=section, + material=STEEL, + length_mm=700, + transverse_load_n=100, + maximum_deflection_mm=5, + required_wall_mm=2, + ) + assert not failed["ok"] + assert len(failed["issues"]) == 2 + with pytest.raises(EngineeringError): + require_beam( + section=section, + material=STEEL, + length_mm=700, + transverse_load_n=1000, + ) + + +def test_compression_and_restrained_temperature_add_conservative_stress(): + section = BeamSection.round_tube(20, 2) + report = beam_check( + section=section, + material=STEEL, + length_mm=1500, + axial_compression_n=3000, + temperature_change_c=60, + thermally_restrained=True, + ) + assert report["thermal_expansion_mm"] == pytest.approx(1.08) + assert report["maximum_stress_mpa"] > 150 + + +def test_tool_access_finds_an_obstruction_on_the_approach(): + wall = cq.Workplane().box(2, 10, 10) + report = tool_access(1, 2, [wall], [(-4, 0, 0, 0, 90, 0), (4, 0, 0, 0, 90, 0)]) + assert report["status"] == "blocked" + + +def test_beam_requirement_fails_the_script_on_unacceptable_deflection(): + execution = Execution( + "steel=EngineeringMaterial('steel',7.85,210000,250)\n" + "tube=BeamSection.hollow_rectangle(20,20,1.5)\n" + "require_beam(section=tube,material=steel,length_mm=700," + "transverse_load_n=100,maximum_deflection_mm=1)\n", + None, + RunSettings(), + ) + assert not execution.run() + assert execution.error["type_name"] == "EngineeringError" diff --git a/tests/worker/geometry/test_exporting.py b/tests/worker/geometry/test_exporting.py new file mode 100644 index 000000000..11a87e00e --- /dev/null +++ b/tests/worker/geometry/test_exporting.py @@ -0,0 +1,210 @@ +"""Exports put shapes where the view shows them.""" + +import json +from xml.etree import ElementTree as ET +from zipfile import ZipFile + +import cadquery as cq +import pytest +from cq_worker import exporting +from cq_worker.scene import Registry, SceneBuilder, ShownObject +from cq_worker.tessellation import Tolerance + + +def nested_assembly(): + """A box 50 mm along x in ``sub``, itself at x = 1000 in a red root at + y = 500: in the world the box spans x 1045…1055, y 495…505.""" + + child = cq.Assembly( + cq.Workplane().box(10, 10, 10), name="child", loc=cq.Location((50, 0, 0)) + ) + sub = cq.Assembly(name="sub", loc=cq.Location((1000, 0, 0))) + sub.add(child) + root = cq.Assembly( + name="root", loc=cq.Location((0, 500, 0)), color=cq.Color(1, 0, 0) + ) + root.add(sub) + return root + + +def build(obj): + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build({"assy": ShownObject(obj)}) + return registry, nodes + + +def bounds(shape): + box = shape.BoundingBox() + return [round(value, 3) for value in (box.xmin, box.xmax, box.ymin, box.ymax)] + + +@pytest.mark.parametrize("level", ["root", "sub", "child"]) +def test_any_assembly_node_is_exported_where_the_view_shows_it(tmp_path, level): + registry, nodes = build(nested_assembly()) + node = nodes[0] + for _ in range(["root", "sub", "child"].index(level)): + node = node["children"][0] + key = node["key"] + + step, brep = tmp_path / "part.step", tmp_path / "part.brep" + exporting.export(registry, [key], "step", str(step)) + exporting.export(registry, [key], "brep", str(brep)) + + world = [1045.0, 1055.0, 495.0, 505.0] + assert bounds(cq.Shape.importBrep(str(brep))) == world + assert bounds(cq.importers.importStep(str(step)).val()) == world + + +def step_part_colors(path): + """The colors of the parts (nodes with a shape) of a STEP file.""" + + return [ + node.color.toTuple()[:3] if node.color else None + for _, node in cq.Assembly.importStep(str(path)).traverse() + if node.obj is not None + ] + + +@pytest.mark.parametrize("level", ["root", "sub"]) +def test_parts_are_exported_in_the_color_they_inherit(tmp_path, level): + # The view draws the box red, as its root; so must the file. + root = nested_assembly() + registry, nodes = build(root) + node = nodes[0] if level == "root" else nodes[0]["children"][0] + step = tmp_path / "part.step" + exporting.export(registry, [node["key"]], "step", str(step)) + + colors = step_part_colors(step) + assert colors and all( + color == pytest.approx((1, 0, 0), abs=1e-3) for color in colors + ), colors + # The script's own assembly is not touched. + assert root.children[0].color is None + assert root.children[0].children[0].color is None + + +def test_several_shown_objects_keep_names_colors_and_positions_in_step(tmp_path): + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build( + { + "base": ShownObject(cq.Workplane().box(10, 10, 2), {"color": "steelblue"}), + "pin": ShownObject( + cq.Workplane().center(50, 0).cylinder(10, 2), + {"color": "red"}, + ), + } + ) + path = tmp_path / "parts.step" + exporting.export(registry, [node["key"] for node in nodes], "step", str(path)) + imported = cq.Assembly.importStep(str(path)) + parts = {node.name: node for _, node in imported.traverse() if node.obj is not None} + assert set(parts) == {"base", "pin"} + assert bounds(parts["base"].obj) == [-5, 5, -5, 5] + assert bounds(parts["pin"].obj.moved(parts["pin"].loc)) == [48, 52, -2, 2] + assert parts["pin"].color.toTuple()[:3] == pytest.approx((1, 0, 0)) + + +@pytest.mark.parametrize( + "schema,header", + [ + ("ap214", "AUTOMOTIVE_DESIGN"), + ("ap242", "AP242_MANAGED_MODEL"), + ], +) +def test_step_schema_is_written_into_the_file(tmp_path, schema, header): + registry, nodes = build(cq.Workplane().box(1, 1, 1)) + path = tmp_path / "part.step" + exporting.export(registry, [nodes[0]["key"]], "step", str(path), step_schema=schema) + assert header in path.read_text(errors="ignore") + + +def test_fused_step_is_an_explicit_export_option(tmp_path): + registry, nodes = build(cq.Workplane().box(2, 2, 2)) + path = tmp_path / "fused.step" + exporting.export(registry, [nodes[0]["key"]], "step", str(path), step_mode="fused") + assert bounds(cq.importers.importStep(str(path)).val()) == [-1, 1, -1, 1] + + +@pytest.mark.parametrize( + "file_format", + ["stl", "brep", "3mf", "gltf", "glb", "amf", "vrml", "xbf", "svg", "dxf"], +) +def test_other_export_formats_write_a_nonempty_file(tmp_path, file_format): + registry, nodes = build(cq.Workplane().box(1, 1, 1)) + path = tmp_path / f"part.{file_format}" + exporting.export(registry, [nodes[0]["key"]], file_format, str(path)) + assert path.stat().st_size > 100 + + +def test_3mf_carries_each_shown_name_and_color(tmp_path): + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build( + { + "base": ShownObject(cq.Workplane().box(2, 2, 2), {"color": "red"}), + "pin": ShownObject( + cq.Workplane().center(10, 0).box(1, 1, 1), {"color": "blue"} + ), + } + ) + path = tmp_path / "parts.3mf" + exporting.export(registry, [node["key"] for node in nodes], "3mf", str(path)) + with ZipFile(path) as archive: + model = ET.fromstring(archive.read("3D/3dmodel.model")) + core = "{http://schemas.microsoft.com/3dmanufacturing/core/2015/02}" + resources = model.find(f"{core}resources") + materials = resources.find(f"{core}basematerials") + colors = {base.get("name"): base.get("displaycolor") for base in materials} + assert colors == {"base": "#FF0000", "pin": "#0000FF"} + objects = [ + node + for node in resources.findall(f"{core}object") + if node.find(f"{core}mesh") is not None + ] + assert {node.get("name") for node in objects} == {"base", "pin"} + + +@pytest.mark.parametrize( + "unit,millimeters,meters", + [ + ("millimeter", 1.0, 0.001), + ("centimeter", 10.0, 0.01), + ("meter", 1000.0, 1.0), + ("inch", 25.4, 0.0254), + ], +) +def test_units_reach_step_3mf_and_gltf(tmp_path, unit, millimeters, meters): + registry, nodes = build(cq.Workplane().box(1, 1, 1)) + key = nodes[0]["key"] + step = tmp_path / "part.step" + three_mf = tmp_path / "part.3mf" + gltf = tmp_path / "part.gltf" + exporting.export(registry, [key], "step", str(step), unit=unit) + exporting.export(registry, [key], "3mf", str(three_mf), unit=unit) + exporting.export(registry, [key], "gltf", str(gltf), unit=unit) + + assert cq.importers.importStep(str(step)).val().BoundingBox().xlen == pytest.approx( + millimeters + ) + with ZipFile(three_mf) as archive: + model = ET.fromstring(archive.read("3D/3dmodel.model")) + assert model.get("unit") == unit + accessors = json.loads(gltf.read_text())["accessors"] + x_coordinates = [ + bound[0] + for accessor in accessors + for bound in (accessor.get("min", []), accessor.get("max", [])) + if len(bound) == 3 + ] + assert max(x_coordinates) - min(x_coordinates) == pytest.approx(meters) + + +def test_export_requires_a_known_model_unit(tmp_path): + registry, nodes = build(cq.Workplane().box(1, 1, 1)) + with pytest.raises(ValueError, match="Choose the model unit"): + exporting.export( + registry, + [nodes[0]["key"]], + "step", + str(tmp_path / "part.step"), + unit="none", + ) diff --git a/tests/worker/geometry/test_fit.py b/tests/worker/geometry/test_fit.py new file mode 100644 index 000000000..fd51a6a32 --- /dev/null +++ b/tests/worker/geometry/test_fit.py @@ -0,0 +1,63 @@ +import math + +import pytest + +from cq_worker.execution import Execution, RunSettings +from cq_worker.fit import FitError, cylindrical_fit, require_fit + + +def test_worst_case_fit_uses_both_tolerance_limits_and_axis_offset(): + report = cylindrical_fit( + hole_diameter=6.5, + pin_diameter=6, + hole_lower=-0.1, + hole_upper=0.1, + pin_lower=-0.05, + pin_upper=0.05, + center_offset=0.1, + required_clearance=0.1, + ) + assert report["minimum_clearance"] == pytest.approx(0.15) + assert report["maximum_clearance"] == pytest.approx(0.45) + assert report["ok"] + + +def test_oversize_pin_and_shallow_counterbore_are_rejected(): + report = cylindrical_fit( + hole_diameter=5, + pin_diameter=6, + insertion_depth=6, + hole_depth=5, + head_diameter=10, + counterbore_diameter=9, + head_height=3, + counterbore_depth=2, + ) + assert len(report["issues"]) == 4 + with pytest.raises(FitError, match="Worst-case"): + require_fit(hole_diameter=5, pin_diameter=6) + + +@pytest.mark.parametrize( + "options", + [ + {"hole_diameter": math.nan, "pin_diameter": 6}, + {"hole_diameter": 6, "pin_diameter": 0}, + {"hole_diameter": 6, "pin_diameter": 5, "hole_lower": 0.1, "hole_upper": -0.1}, + {"hole_diameter": 6, "pin_diameter": 5, "insertion_depth": 3}, + ], +) +def test_invalid_fit_declarations_fail_explicitly(options): + with pytest.raises(ValueError): + cylindrical_fit(**options) + + +def test_fit_requirement_fails_the_script_and_headless_build(): + execution = Execution( + "require_fit(hole_diameter=5, pin_diameter=6)\n" + "show_object(cq.Workplane().box(1,1,1))\n", + None, + RunSettings(), + ) + assert not execution.run() + assert execution.error["type_name"] == "FitError" diff --git a/tests/worker/geometry/test_glb_reader.py b/tests/worker/geometry/test_glb_reader.py new file mode 100644 index 000000000..e772d06ea --- /dev/null +++ b/tests/worker/geometry/test_glb_reader.py @@ -0,0 +1,80 @@ +"""Small binary glTF fixtures cover mesh decoding and world transforms.""" + +import json +import math +import struct + +import numpy as np +import pytest + +from cq_worker.tessellation import TessellationError, _node_matrix, read_glb + + +def chunk(payload, kind, padding): + payload += padding * (-len(payload) % 4) + return struct.pack("Z") + frames = stack_frames(face) + assert frames[0] is face + assert any(frame is box for frame in frames) + assert stack_frames(cq.Workplane()) == [] + + +def test_described_stack_marks_shapes_as_displayable(): + frame = cq.Workplane().box(1, 1, 1) + (description,) = describe_stack([frame]) + assert description["type"] == "Workplane" + assert description["items"][0]["type"] == "Solid" + assert description["items"][0]["displayable"] is True + assert "origin" in description["value"] + + +def test_vector_is_not_displayable_but_shape_is(): + assert not is_displayable(cq.Vector(1, 2, 3)) + assert is_displayable(cq.Workplane().box(1, 1, 1).val()) + + +def test_point_only_frame_provides_grid_without_mesh(): + frame = cq.Workplane().pushPoints([(1, 2)]) + whole = frame_geometry(frame, None, Tolerance()) + single = frame_geometry(frame, 0, Tolerance()) + assert whole["meshes"] == [] + assert whole["plane"]["size"] > 0 + assert single == {"meshes": [], "plane": None} + + +def test_long_fallback_description_is_bounded(): + assert len(_text("x" * (MAX_VALUE_LENGTH + 20))) == MAX_VALUE_LENGTH diff --git a/tests/worker/geometry/test_interference.py b/tests/worker/geometry/test_interference.py new file mode 100644 index 000000000..a14f5a5b4 --- /dev/null +++ b/tests/worker/geometry/test_interference.py @@ -0,0 +1,157 @@ +"""Interference checks use the placed solids, never their display meshes.""" + +import cadquery as cq +import pytest +from cq_worker.interference import ( + analyze_interferences, + apply_allowances, + overlap_shape, + summarize, +) +from cq_worker.scene import Registry, SceneBuilder, ShownObject +from cq_worker.tessellation import Tolerance + + +def assembly_report(hole_diameter, pin_diameter, *, merged=False, pin_x=0): + plate = cq.Workplane().box(20, 20, 5).faces(">Z").workplane().hole(hole_diameter) + pin = cq.Workplane().circle(pin_diameter / 2).extrude(10).translate((0, 0, -5)) + assembly = cq.Assembly(name="joint") + assembly.add(plate, name="plate") + assembly.add(pin, name="pin", loc=cq.Location((pin_x, 0, 0))) + registry = Registry() + (node,) = SceneBuilder(registry, Tolerance(), merge_assemblies=merged).build( + {"joint": ShownObject(assembly)} + ) + return analyze_interferences(registry, [node["key"]]) + + +@pytest.mark.parametrize("merged", [False, True]) +def test_oversize_pin_interferes_with_hole_in_both_display_modes(merged): + (report,) = assembly_report(5, 6, merged=merged) + assert report["kind"] == "interference" + assert report["overlap_volume"] == pytest.approx(43.1968989869) + assert { + report["first"]["name"].split("/")[-1], + report["second"]["name"].split("/")[-1], + } == { + "plate", + "pin", + } + + +def test_smaller_pin_passes_through_exact_hole_without_interference(): + assert assembly_report(6.5, 6) == [] + + +def test_misaligned_pin_interferes_even_when_its_diameter_is_smaller(): + reports = assembly_report(6.5, 6, pin_x=0.5) + assert len(reports) == 1 and reports[0]["kind"] == "interference" + + +def test_overlap_shape_matches_report_and_rejects_stale_pair(): + first = cq.Workplane().box(2, 2, 2) + second = cq.Workplane().box(2, 2, 2).translate((1, 0, 0)) + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build( + {"first": ShownObject(first), "second": ShownObject(second)} + ) + (report,) = analyze_interferences(registry, [node["key"] for node in nodes]) + common = overlap_shape(registry, report["first"], report["second"]) + assert common.Volume() == pytest.approx(report["overlap_volume"]) + stale = {**report["first"], "solid": 99} + with pytest.raises(ValueError, match="no longer in the live scene"): + overlap_shape(registry, stale, report["second"]) + + +def test_face_contact_is_separate_from_penetration(): + first = cq.Workplane().box(2, 2, 2) + second = cq.Workplane().box(2, 2, 2).translate((2, 0, 0)) + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build( + {"first": ShownObject(first), "second": ShownObject(second)} + ) + (report,) = analyze_interferences(registry, [node["key"] for node in nodes]) + assert report["kind"] == "contact" + assert report["overlap_volume"] == pytest.approx(0) + + +def test_two_instances_of_same_shape_are_not_deduplicated_inside_assembly(): + cube = cq.Workplane().box(2, 2, 2) + assembly = cq.Assembly().add(cube, name="one").add(cube, name="two") + registry = Registry() + (node,) = SceneBuilder(registry, Tolerance()).build( + {"assembly": ShownObject(assembly)} + ) + (report,) = analyze_interferences(registry, [node["key"]]) + assert report["kind"] == "interference" + assert report["overlap_volume"] == pytest.approx(8) + + +def test_equal_diameters_are_contact_not_assured_manufacturing_clearance(): + reports = assembly_report(6, 6) + assert len(reports) == 1 + assert reports[0]["kind"] == "contact" + assert summarize(reports)["status"] == "clear" + + +def test_failed_exact_operation_is_inconclusive_not_safe(monkeypatch): + def fail(*_args): + raise RuntimeError("boolean operation failed") + + monkeypatch.setattr(cq.Shape, "intersect", fail) + (report,) = assembly_report(5, 6) + assert report["kind"] == "inconclusive" + assert "boolean operation failed" in report["reason"] + assert summarize([report])["status"] == "inconclusive" + + +def test_summary_prioritizes_interference_over_uncertainty(): + reports = [{"kind": "inconclusive"}, {"kind": "interference"}] + assert summarize(reports) == { + "status": "interference", + "counts": { + "interference": 1, + "inconclusive": 1, + "contact": 0, + "clearance": 0, + }, + "accepted": 0, + } + + +def test_explicit_allowance_accepts_only_one_unambiguous_pair(): + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build( + { + "plate": ShownObject(cq.Workplane().box(4, 4, 4)), + "pin": ShownObject(cq.Workplane().box(2, 2, 2)), + "other": ShownObject(cq.Workplane().box(1, 1, 1)), + } + ) + keys = [node["key"] for node in nodes] + reports = analyze_interferences(registry, keys) + assert len(reports) == 3 + apply_allowances(registry, keys, reports, [("plate", "pin", "press fit")]) + assert summarize(reports)["status"] == "interference" + assert summarize(reports)["accepted"] == 1 + assert sum(bool(report.get("allowance_reason")) for report in reports) == 1 + + +def test_allowance_does_not_accept_inconclusive_boolean(monkeypatch): + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build( + { + "plate": ShownObject(cq.Workplane().box(4, 4, 4)), + "pin": ShownObject(cq.Workplane().box(2, 2, 2)), + } + ) + keys = [node["key"] for node in nodes] + + def fail(*_args): + raise RuntimeError("boolean failed") + + monkeypatch.setattr(cq.Shape, "intersect", fail) + reports = analyze_interferences(registry, keys) + apply_allowances(registry, keys, reports, [("plate", "pin", "press fit")]) + assert summarize(reports)["status"] == "inconclusive" + assert reports[0].get("allowance_reason") is None diff --git a/tests/worker/geometry/test_measurement.py b/tests/worker/geometry/test_measurement.py new file mode 100644 index 000000000..a2e9a53c9 --- /dev/null +++ b/tests/worker/geometry/test_measurement.py @@ -0,0 +1,231 @@ +import math + +import cadquery as cq +import pytest + +from cq_worker.measurement import MeasurementError, measure +from cq_worker.scene import Registry, RegistryEntry, SceneBuilder, ShownObject +from cq_worker.tessellation import Tolerance, TopologyIndex + + +def add_shape(registry, shape): + topology = TopologyIndex.build(shape.wrapped) + return registry.add(RegistryEntry(shape, shape, topologies=[topology])) + + +def reference(key, kind, identifier=1): + return {"key": key, "part": 0, "kind": kind, "identifier": identifier} + + +def test_two_vertices_have_an_exact_five_unit_distance(): + registry = Registry() + first = add_shape(registry, cq.Vertex.makeVertex(0, 0, 0)) + second = add_shape(registry, cq.Vertex.makeVertex(3, 4, 0)) + + result = measure( + registry, [reference(first, "vertex"), reference(second, "vertex")] + ) + + assert result["pair"]["distance"] == pytest.approx(5.0, abs=1e-12) + assert result["pair"]["first_point"] == pytest.approx([0.0, 0.0, 0.0]) + assert result["pair"]["second_point"] == pytest.approx([3.0, 4.0, 0.0]) + assert result["identity"] == {"scope": "scene_entry", "persistent": False} + + +def test_material_density_produces_mass_for_mixed_assembly(): + registry = Registry() + box = cq.Workplane().box(10, 10, 10).val() + steel = registry.add( + RegistryEntry(box, box, material=cq.Material("Steel", density=7.8)) + ) + aluminium = registry.add( + RegistryEntry(box, box, material=cq.Material("Al", density=2.7)) + ) + root = registry.add(RegistryEntry(None, None, children=[steel, aluminium])) + + (result,) = measure(registry, [], [root])["objects"] + + assert result["mass_g"] == pytest.approx(10.5) + assert result["materials"] == ["Al", "Steel"] + + +def test_merged_assembly_keeps_each_part_material_for_mass(): + assembly = cq.Assembly(name="mixed") + box = cq.Workplane().box(10, 10, 10) + assembly.add(box, name="steel", material=cq.Material("Steel", density=7.8)) + assembly.add(box, name="al", material=cq.Material("Al", density=2.7)) + registry = Registry() + (node,) = SceneBuilder(registry, Tolerance(), merge_assemblies=True).build( + {"mixed": ShownObject(assembly)} + ) + + (result,) = measure(registry, [], [node["key"]])["objects"] + + assert result["mass_g"] == pytest.approx(10.5) + assert result["materials"] == ["Al", "Steel"] + + +def test_curved_edge_reports_occt_length_radius_and_diameter(): + registry = Registry() + key = add_shape(registry, cq.Edge.makeCircle(2.5)) + + (entity,) = measure(registry, [reference(key, "edge")])["entities"] + + assert entity["geometry_type"] == "circle" + assert entity["length"] == pytest.approx(5.0 * math.pi) + assert entity["radius"] == pytest.approx(2.5) + assert entity["diameter"] == pytest.approx(5.0) + + +def test_circular_planar_face_reports_area_and_boundary_radius(): + wire = cq.Wire.makeCircle(3, cq.Vector(), cq.Vector(0, 0, 1)) + face = cq.Face.makeFromWires(wire) + registry = Registry() + key = add_shape(registry, face) + + (entity,) = measure(registry, [reference(key, "face")])["entities"] + + assert entity["geometry_type"] == "plane" + assert entity["area"] == pytest.approx(9.0 * math.pi) + assert entity["radius"] == pytest.approx(3.0) + assert entity["diameter"] == pytest.approx(6.0) + + +def test_cylindrical_face_reports_surface_type_and_radius(): + face = cq.Workplane("XY").cylinder(5, 2).faces("%CYLINDER").val() + registry = Registry() + key = add_shape(registry, face) + + (entity,) = measure(registry, [reference(key, "face")])["entities"] + + assert entity["geometry_type"] == "cylinder" + assert entity["radius"] == pytest.approx(2.0) + assert entity["diameter"] == pytest.approx(4.0) + + +def test_angles_are_measured_for_straight_edges_and_planar_faces(): + registry = Registry() + horizontal = add_shape(registry, cq.Edge.makeLine(cq.Vector(), cq.Vector(4, 0, 0))) + vertical = add_shape(registry, cq.Edge.makeLine(cq.Vector(), cq.Vector(0, 4, 0))) + edge_angle = measure( + registry, + [reference(horizontal, "edge"), reference(vertical, "edge")], + )["pair"] + + assert edge_angle["angle_kind"] == "edge_edge" + assert edge_angle["angle_degrees"] == pytest.approx(90.0) + + +def test_planar_face_angle_and_edge_to_plane_angle(): + registry = Registry() + xy_face = cq.Workplane("XY").rect(2, 2).extrude(0.1).faces(">Z").val() + yz_face = cq.Workplane("YZ").rect(2, 2).extrude(0.1).faces(">X").val() + edge = cq.Edge.makeLine(cq.Vector(), cq.Vector(0, 0, 4)) + xy_key = add_shape(registry, xy_face) + yz_key = add_shape(registry, yz_face) + edge_key = add_shape(registry, edge) + + faces = measure(registry, [reference(xy_key, "face"), reference(yz_key, "face")])[ + "pair" + ] + edge_face = measure( + registry, [reference(edge_key, "edge"), reference(xy_key, "face")] + )["pair"] + + assert faces["angle_kind"] == "face_face" + assert faces["angle_degrees"] == pytest.approx(90.0) + assert edge_face["angle_kind"] == "edge_face" + assert edge_face["angle_degrees"] == pytest.approx(90.0) + + +def test_rejects_empty_or_oversized_selections_and_stale_references(): + registry = Registry() + key = add_shape(registry, cq.Vertex.makeVertex(0, 0, 0)) + ref = reference(key, "vertex") + + with pytest.raises(MeasurementError, match="between one and 64"): + measure(registry, []) + with pytest.raises(MeasurementError, match="between one and 64"): + measure(registry, [ref] * 65) + registry.release([key]) + with pytest.raises(MeasurementError, match="previous Python session"): + measure(registry, [ref]) + + +def test_more_than_two_entities_are_described_without_a_pair(): + registry = Registry() + box = cq.Workplane().box(1, 2, 3).val() + key = add_shape(registry, box) + + result = measure(registry, [reference(key, "face", i) for i in (1, 2, 3)]) + + assert [entity["identifier"] for entity in result["entities"]] == [1, 2, 3] + assert all(entity["area"] > 0 for entity in result["entities"]) + assert result["pair"] is None + + +def _shown(registry, obj): + """Shows ``obj`` as the GUI does, which meshes it.""" + + from cq_worker.scene import SceneBuilder, ShownObject + from cq_worker.tessellation import Tolerance + + (node,) = SceneBuilder(registry, Tolerance()).build({"obj": ShownObject(obj)}) + return node["key"] + + +def test_bounding_boxes_are_exact_even_on_meshed_shapes(): + registry = Registry() + sphere = cq.Workplane().sphere(5) + key = _shown(registry, sphere) + # CadQuery's own BoundingBox() now includes the display mesh. + assert sphere.val().BoundingBox().xmax > 5.01 + + (face,) = measure(registry, [reference(key, "face")])["entities"] + box = face["bounding_box"] + assert box["min"] == pytest.approx([-5, -5, -5], abs=1e-6) + assert box["max"] == pytest.approx([5, 5, 5], abs=1e-6) + assert box["size"] == pytest.approx([10, 10, 10], abs=1e-6) + assert box["center"] == pytest.approx([0, 0, 0], abs=1e-6) + + +def test_the_selection_has_one_bounding_box_around_all_entities(): + registry = Registry() + key = _shown(registry, cq.Workplane().box(2, 4, 6)) + result = measure(registry, [reference(key, "face", 1), reference(key, "face", 2)]) + # The two faces normal to X span the whole box. + assert result["bounding_box"]["size"] == pytest.approx([2, 4, 6]) + assert result["objects"] == [] + + +def test_selected_objects_are_measured_when_no_entity_is_picked(): + registry = Registry() + key = _shown(registry, cq.Workplane().box(1, 2, 3)) + wire = _shown(registry, cq.Workplane().rect(2, 2)) + + result = measure(registry, [], [key, wire]) + + assert result["entities"] == [] and result["pair"] is None + box, square = result["objects"] + assert box["key"] == key and box["shape_type"] == "solid" + assert box["volume"] == pytest.approx(6) + assert box["area"] == pytest.approx(22) + assert box["center"] == pytest.approx([0, 0, 0]) + assert (box["solids"], box["faces"], box["edges"], box["vertices"]) == (1, 6, 12, 8) + assert box["bounding_box"]["size"] == pytest.approx([1, 2, 3]) + assert square["volume"] is None and square["area"] is None + assert square["length"] == pytest.approx(8) + assert result["bounding_box"]["size"] == pytest.approx([2, 2, 3]) + + +def test_picked_entities_take_precedence_over_selected_objects(): + registry = Registry() + key = _shown(registry, cq.Workplane().box(1, 2, 3)) + result = measure(registry, [reference(key, "face", 1)], [key]) + assert len(result["entities"]) == 1 and result["objects"] == [] + + +@pytest.mark.parametrize("objects", [[""], "n1", [1], ["n1"] * 65]) +def test_invalid_object_lists_are_rejected(objects): + with pytest.raises(MeasurementError, match="scene keys"): + measure(Registry(), [], objects) diff --git a/tests/worker/geometry/test_measurement_code.py b/tests/worker/geometry/test_measurement_code.py new file mode 100644 index 000000000..7b1ddb8c8 --- /dev/null +++ b/tests/worker/geometry/test_measurement_code.py @@ -0,0 +1,209 @@ +"""Copy as code: Python that measures the selection again, verified.""" + +import textwrap + +import cadquery as cq +import pytest + +from cq_worker import measurement_code as module +from cq_worker.execution import Execution, RunSettings +from cq_worker.measurement import MeasurementError +from cq_worker.measurement_code import measurement_code +from cq_worker.scene import Registry, SceneBuilder +from cq_worker.tessellation import Tolerance + +SCRIPT = """\ +plate = cq.Workplane().box(20, 10, 4).faces(">Z").workplane().hole(3) +assy = cq.Assembly().add( + plate, name="plate", loc=cq.Location((0, 0, 50), (0, 0, 1), 30) +) +assy.add(cq.Workplane().cylinder(6, 2), name="pin", loc=cq.Location((30, 0, 0))) +show_object(plate) +show_object(assy) +""" + + +@pytest.fixture +def shown(): + """The script run, shown and meshed as the GUI shows it.""" + + execution = Execution(SCRIPT, None, RunSettings()) + assert execution.run(), execution.error + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build(execution.shown) + return registry, dict(execution.namespace), nodes + + +def entity(key, kind, identifier): + return {"key": key, "part": 0, "kind": kind, "identifier": identifier} + + +def body(code): + """The measuring lines, without the imports and the helper.""" + + return [ + line + for line in code.splitlines() + if line and not line.startswith(("from ", "import ", "def ", " ", '"""')) + ] + + +def test_two_entities_become_selectors_measurements_and_their_relationship(shown): + registry, namespace, (plate, _) = shown + top = entity(plate["key"], "face", 6) + edge = entity(plate["key"], "edge", 1) + + result = measurement_code(registry, namespace, [top, edge]) + + assert result["verified"] and result["problem"] is None + lines = body(result["code"]) + assert lines[0] == 'face_1 = plate.faces(">X").val()' + assert "area_1 = face_1.Area() # 40" in lines + assert "bounds_1 = exact_bounds(face_1) # (10, -5, -2, 10, 5, 2)" in lines + assert any(line.startswith("edge_2 = plate.edges(") for line in lines) + assert "distance = face_1.distance(edge_2) # 20" in lines + assert result["code"].startswith("import math\n") + + +def test_the_code_runs_in_the_console_and_gives_the_measured_values(shown): + registry, namespace, (plate, _) = shown + result = measurement_code(registry, namespace, [entity(plate["key"], "face", 6)]) + scope = dict(namespace) + exec(result["code"], scope) + assert scope["area_1"] == pytest.approx(40) + assert scope["bounds_1"] == pytest.approx((10, -5, -2, 10, 5, 2)) + + +def test_assembly_parts_are_placed_where_the_assembly_puts_them(shown): + registry, namespace, (_, assembly) = shown + plate_part, pin_part = assembly["children"] + + rotated = measurement_code(registry, namespace, [], [plate_part["key"]]) + assert rotated["verified"], rotated["problem"] + assert body(rotated["code"])[0] == ( + "shape_1 = plate.val().moved(cq.Location((0, 0, 50), (0, 0, 30)))" + ) + + pin = measurement_code(registry, namespace, [entity(pin_part["key"], "face", 1)]) + assert pin["verified"], pin["problem"] + # Added without a variable: reached through the assembly. + assert body(pin["code"])[0].startswith("face_1 = assy.objects['pin'].obj.faces(") + assert body(pin["code"])[0].endswith(".val().moved(cq.Location((30, 0, 0)))") + + +def test_named_assembly_face_is_referenced_by_its_script_name(): + script = """\ +block = cq.Workplane().box(10, 10, 10) +model = cq.Assembly(block, name='block') +model.addSubshape(block.faces('>Z').val(), name='lid', color=cq.Color('red'), layer='finish') +show_object(model) +""" + execution = Execution(script, None, RunSettings()) + assert execution.run(), execution.error + registry = Registry() + (node,) = SceneBuilder(registry, Tolerance()).build(execution.shown) + (attribute,) = node["parts"][0]["face_attributes"] + + result = measurement_code( + registry, + dict(execution.namespace), + [entity(node["key"], "face", attribute["id"])], + ) + + assert result["verified"], result["problem"] + assert "name == 'lid'" in result["code"] + scope = dict(execution.namespace) + exec(result["code"], scope) + assert scope["area_1"] == pytest.approx(100) + + +def test_objects_are_measured_whole(shown): + registry, namespace, (plate, assembly) = shown + result = measurement_code(registry, namespace, [], [plate["key"], assembly["key"]]) + assert result["verified"], result["problem"] + lines = body(result["code"]) + assert "shape_1 = plate.val()" in lines + assert "shape_2 = assy.toCompound()" in lines + assert any(line.startswith("volume_2 = shape_2.Volume() # ") for line in lines) + + +def test_index_fallbacks_are_marked_in_the_code(shown, monkeypatch): + from cq_worker import selection + + monkeypatch.setattr(selection, "search", lambda features, targets: []) + registry, namespace, (plate, _) = shown + result = measurement_code(registry, namespace, [entity(plate["key"], "face", 6)]) + assert result["verified"], result["problem"] + assert "# By index: this may name another entity" in result["code"] + assert "face_1 = plate.faces()[5].val()" in result["code"] + + +def test_objects_without_a_variable_are_left_to_the_user(): + execution = Execution( + "show_object(cq.Workplane().box(1, 2, 3))\n", None, RunSettings() + ) + assert execution.run(), execution.error + registry = Registry() + (node,) = SceneBuilder(registry, Tolerance()).build(execution.shown) + result = measurement_code(registry, dict(execution.namespace), [], [node["key"]]) + assert not result["verified"] + assert "replace obj" in result["problem"] + assert "shape_1 = obj.val()" in result["code"] + + +def test_a_variable_rebound_in_the_console_is_not_used(shown): + registry, namespace, (plate, _) = shown + namespace["plate"] = cq.Workplane().box(1, 1, 1) + result = measurement_code(registry, namespace, [entity(plate["key"], "face", 6)]) + # The shown plate is still reachable, through the assembly holding it. + assert result["verified"], result["problem"] + assert "face_1 = assy.objects['plate'].obj.faces(" in result["code"] + + del namespace["assy"] + result = measurement_code(registry, namespace, [entity(plate["key"], "face", 6)]) + assert not result["verified"] + assert "face_1 = obj.faces(" in result["code"] + + +def test_verification_reports_code_that_disagrees(): + assert module._verify("x = 1.0\n", {}, {"x": 1.0}) is None + assert "x came out as 2" in module._verify("x = 2.0\n", {}, {"x": 1.0}) + assert "ZeroDivisionError" in module._verify("x = 1 / 0\n", {}, {"x": 1.0}) + assert "(1, 2, 3)" in module._verify( + "v = cq.Vector(1, 2, 4)\n", {"cq": cq}, {"v": [1.0, 2.0, 3.0]} + ) + + +def test_stale_selections_are_errors(shown): + registry, namespace, (plate, _) = shown + registry.release([plate["key"]]) + with pytest.raises(MeasurementError, match="previous Python session"): + measurement_code(registry, namespace, [entity(plate["key"], "face", 1)]) + with pytest.raises(MeasurementError, match="or objects"): + measurement_code(registry, namespace, [], []) + + +def test_numbers_are_written_short_when_rounding_noise_allows(): + assert module._number(29.999999999999993) == "30" + assert module._number(-0.0) == "0" + assert module._number(2.5) == "2.5" + assert module._number(1 / 3) == repr(1 / 3) + assert module._text(2.7755575615628914e-17) == "0" + + +def test_placements_drop_what_is_zero(): + assert module._placement(cq.Location()) == "" + assert module._placement(cq.Location((1, 2, 3))) == ".moved(cq.Location((1, 2, 3)))" + rotated = module._placement(cq.Location((0, 0, 0), (0, 0, 1), 90)) + assert rotated == ".moved(cq.Location((0, 0, 0), (0, 0, 90)))" + + +def test_code_text_is_valid_python_with_and_without_helpers(): + code = module._Code() + code.assign("x", "1", 1.0) + compile(code.text(), "", "exec") + code.uses_math = True + code.uses_bounds = True + text = code.text() + compile(text, "", "exec") + assert textwrap.dedent(text).count("def exact_bounds") == 1 diff --git a/tests/worker/geometry/test_motion.py b/tests/worker/geometry/test_motion.py new file mode 100644 index 000000000..a7e253079 --- /dev/null +++ b/tests/worker/geometry/test_motion.py @@ -0,0 +1,50 @@ +import cadquery as cq + +from cq_worker.execution import Execution, RunSettings +from cq_worker.motion import trace_path + + +def test_path_detects_wall_between_two_clear_end_positions(): + wall = cq.Workplane().box(2, 10, 10) + ball = cq.Workplane().sphere(0.5) + report = trace_path(ball, [wall], [(-3, 0, 0, 0, 0, 0), (3, 0, 0, 0, 0, 0)]) + assert report["status"] == "blocked" + assert report["overlap_volume"] > 0 + + +def test_pin_can_follow_a_path_through_a_larger_hole(): + plate = cq.Workplane().box(10, 10, 2).faces(">Z").workplane().hole(2) + pin = cq.Workplane().circle(0.5).extrude(2) + report = trace_path(pin, [plate], [(0, 0, -4, 0, 0, 0), (0, 0, 4, 0, 0, 0)]) + assert report["status"] == "clear", report + + +def test_rotating_arm_hits_obstacle_between_clear_end_angles(): + arm = cq.Workplane().box(2, 0.2, 0.2) + obstacle = cq.Workplane().sphere(0.2).translate((0.7, 0.7, 0)) + report = trace_path(arm, [obstacle], [(0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 90)]) + assert report["status"] == "blocked" + + +def test_depth_limit_cannot_turn_uncertainty_into_clearance(): + wall = cq.Workplane().box(2, 10, 2) + ball = cq.Workplane().sphere(1) + report = trace_path( + ball, + [wall], + [(-3, 0, 2, 0, 0, 0), (3, 0, 2, 0, 0, 0)], + max_depth=0, + ) + assert report["status"] == "inconclusive" + + +def test_path_requirement_stops_a_script_that_would_cross_a_wall(): + execution = Execution( + "wall=cq.Workplane().box(2,10,10)\n" + "ball=cq.Workplane().sphere(.5)\n" + "require_clear_path(ball,[wall],[(-3,0,0,0,0,0),(3,0,0,0,0,0)])\n", + None, + RunSettings(), + ) + assert not execution.run() + assert execution.error["type_name"] == "PathError" diff --git a/tests/worker/geometry/test_registry.py b/tests/worker/geometry/test_registry.py new file mode 100644 index 000000000..4af649996 --- /dev/null +++ b/tests/worker/geometry/test_registry.py @@ -0,0 +1,72 @@ +"""Scene key lifecycle and export selection.""" + +import cadquery as cq +import pytest + +from cq_worker.scene import Registry, RegistryEntry +from cq_worker.tessellation import TopologyIndex + + +def test_subtree_shapes_deduplicates_overlapping_selection(): + registry = Registry() + first = cq.Workplane().box(1, 1, 1).val() + second = cq.Workplane().sphere(1).val() + child = registry.add(RegistryEntry(second, second)) + parent = registry.add(RegistryEntry(first, first, [child])) + + assert registry.subtree_shapes([parent, child, parent]) == [first, second] + + +def test_release_removes_children_but_keeps_other_roots(): + registry = Registry() + child = registry.add(RegistryEntry("child", None)) + parent = registry.add(RegistryEntry("parent", None, [child])) + other = registry.add(RegistryEntry("other", None)) + registry.release([parent, "unknown"]) + + assert registry.get(other).obj == "other" + for key in (parent, child): + with pytest.raises(KeyError, match="may have been cleared"): + registry.get(key) + + +def test_clear_drops_entries_without_reusing_old_keys(): + registry = Registry() + old = registry.add(RegistryEntry("old", None)) + registry.clear() + new = registry.add(RegistryEntry("new", None)) + assert old != new + with pytest.raises(KeyError): + registry.get(old) + + +def test_prefixed_registries_never_share_keys(): + old = Registry("s1-n") + new = Registry("s2-n") + stale = old.add(RegistryEntry("old", None)) + fresh = new.add(RegistryEntry("new", None)) + + assert (stale, fresh) == ("s1-n1", "s2-n1") + # The GUI releases the stale key after a restart; the new object survives. + new.release([stale]) + assert new.get(fresh).obj == "new" + + +def test_subtree_shapes_skips_nodes_without_geometry(): + registry = Registry() + shape = cq.Workplane().box(1, 1, 1).val() + child = registry.add(RegistryEntry(shape, shape)) + parent = registry.add(RegistryEntry("group", None, [child])) + assert registry.subtree_shapes([parent]) == [shape] + + +def test_topology_ids_resolve_to_the_live_occt_subshapes(): + shape = cq.Workplane().box(1, 2, 3).val() + topology = TopologyIndex.build(shape.wrapped) + entry = RegistryEntry(shape, shape, topologies=[topology]) + + assert entry.subshape(0, "face", 1).ShapeType() == "Face" + assert entry.subshape(0, "edge", 12).ShapeType() == "Edge" + assert entry.subshape(0, "vertex", 8).ShapeType() == "Vertex" + with pytest.raises(IndexError, match="Unknown face id"): + entry.subshape(0, "face", 7) diff --git a/tests/worker/geometry/test_scene.py b/tests/worker/geometry/test_scene.py new file mode 100644 index 000000000..9251b761f --- /dev/null +++ b/tests/worker/geometry/test_scene.py @@ -0,0 +1,277 @@ +import cadquery as cq +import pytest + +from cq_worker.scene import ( + BuildCancelled, + DisplayOptions, + Registry, + RegistryEntry, + SceneBuilder, + ShownObject, + find_cq_objects, + parse_color, + to_compound, +) +from cq_worker.tessellation import GeometryCache, Tolerance + + +def test_to_compound_applies_sketch_placement(): + sketch = cq.Sketch().rect(1, 1) + placed = cq.Workplane("XZ").placeSketch(sketch).val() + (face,) = to_compound(placed).Faces() + + assert face.Area() == pytest.approx(1) + assert face.normalAt().toTuple() == pytest.approx((0, -1, 0)) + + +def test_assembly_face_attributes_and_material_follow_instances(): + shape = cq.Workplane().box(10, 10, 10).val() + material = cq.Material("Aluminium", density=2.7) + child = cq.Assembly(shape, name="block", material=material) + child.addSubshape( + shape.Faces()[0], name="top face", color=cq.Color("red"), layer="finish" + ) + root = cq.Assembly(name="root") + root.add(child, name="first") + root.add(child, name="second", loc=cq.Location((20, 0, 0))) + registry = Registry() + scene = SceneBuilder(registry, Tolerance()).build({"result": ShownObject(root)}) + first, second = scene[0]["children"] + for node in (first, second): + part = node["parts"][0] + assert part["face_attributes"][0]["name"] == "top face" + assert part["face_attributes"][0]["layer"] == "finish" + assert part["face_attributes"][0]["color"] == pytest.approx([1, 0, 0]) + assert part["material"] == { + "name": "Aluminium", + "density": 2.7, + "density_unit": "g/cm^3", + } + assert registry.get(node["key"]).material.name == "Aluminium" + + +def test_to_compound_empty_list(): + # #600: an empty list must give an empty compound instead of raising. + result = to_compound([]) + + assert isinstance(result, cq.Compound) + assert result.Solids() == [] + + +def test_to_compound_skips_non_shape_stack_entries(): + points_only = cq.Workplane().pushPoints([(0, 0), (1, 1)]) + assert to_compound(points_only).Vertices() == [] + + +def test_to_compound_accepts_mixed_lists(): + box = cq.Workplane().box(1, 1, 1) + sphere = cq.Workplane().sphere(1).val() + assert len(to_compound([box, sphere]).Solids()) == 2 + + +def test_to_compound_rejects_unknown_types(): + with pytest.raises(ValueError): + to_compound(42) + + +@pytest.mark.parametrize( + "spec, expected", + [ + ("#ff0000", ((1.0, 0.0, 0.0), None)), + ("#0f08", ((0.0, 1.0, 0.0), 0x88 / 255)), + ((255, 0, 0), ((1.0, 0.0, 0.0), None)), + ((0.5, 0.25, 1.0, 0.5), ((0.5, 0.25, 1.0), 0.5)), + ], +) +def test_parse_color(spec, expected): + rgb, alpha = parse_color(spec) + assert rgb == pytest.approx(expected[0]) + assert alpha == (pytest.approx(expected[1]) if expected[1] is not None else None) + + +def test_parse_color_names_and_cq_colors_are_srgb(): + rgb, alpha = parse_color("lightgray") + assert rgb == pytest.approx((211 / 255,) * 3, abs=1e-3) + assert parse_color(cq.Color("lightgray"))[0] == pytest.approx(rgb) + + +def test_parse_color_rejects_garbage(): + with pytest.raises(ValueError): + parse_color((300, 0, 0)) + with pytest.raises(ValueError): + parse_color(object()) + + +def test_display_options(): + options = DisplayOptions.parse( + {"color": "red", "alpha": 0.5, "edgecolor": (0, 0, 255)} + ) + assert options.color == pytest.approx((1, 0, 0)) + assert options.alpha == 0.5 + assert options.edge_color == pytest.approx((0, 0, 1)) + + rgba = DisplayOptions.parse({"rgba": (0.1, 0.2, 0.3, 0.4)}) + assert rgba.color == pytest.approx((0.1, 0.2, 0.3)) and rgba.alpha == 0.4 + + # Invalid entries are dropped instead of failing the whole run. + assert DisplayOptions.parse({"color": "no-such-color"}).color is None + + +def test_find_cq_objects_ignores_private_and_plain_values(): + found = find_cq_objects( + {"box": cq.Workplane().box(1, 1, 1), "_hidden": cq.Workplane(), "n": 3} + ) + assert list(found) == ["box"] + + +def build(objects, merge=False): + registry = Registry() + builder = SceneBuilder(registry, Tolerance(), merge_assemblies=merge) + nodes = builder.build({name: ShownObject(obj) for name, obj in objects.items()}) + return registry, nodes + + +def test_builder_creates_one_node_per_object(): + registry, nodes = build( + { + "box": cq.Workplane().box(1, 2, 3), + "empty": cq.Workplane().pushPoints([(0, 0)]), + } + ) + + assert [n["name"] for n in nodes] == ["box"] + node = nodes[0] + assert node["kind"] == "Workplane" + assert node["inspectable"] is True + assert len(node["parts"]) == 1 + entry = registry.get(node["key"]) + assert entry.shape is not None + assert len(entry.topologies) == 1 + + +def make_assembly(): + plate = cq.Workplane().box(10, 10, 1) + pin = cq.Workplane().cylinder(5, 1) + sub = cq.Assembly(name="pins").add(pin, name="pin", color=cq.Color("red")) + return ( + cq.Assembly(name="top") + .add(plate, name="plate") + .add(sub, loc=cq.Location(cq.Vector(0, 0, 3)), color=cq.Color("blue")) + ) + + +def test_builder_explodes_assemblies(): + registry, nodes = build({"assy": make_assembly()}) + + (root,) = nodes + assert [c["name"] for c in root["children"]] == ["plate", "pins"] + pins = root["children"][1] + pin = pins["children"][0] + # The part's own color wins over the inherited one. + assert pin["parts"][0]["color"] == pytest.approx((1, 0, 0)) + # Geometry stays in local coordinates and locations accumulate in the + # instance transform, allowing identical parts to share one mesh. + bbox = pin["parts"][0]["mesh"]["bbox"] + assert bbox[0][2] == pytest.approx(-2.5, abs=1e-3) + assert bbox[1][2] == pytest.approx(2.5, abs=1e-3) + assert pin["parts"][0]["transform"][14] == pytest.approx(3) + assert len(registry.subtree_shapes([root["key"]])) == 2 + + +def test_builder_can_merge_assemblies(): + registry, nodes = build({"assy": make_assembly()}, merge=True) + + (root,) = nodes + assert root["children"] == [] + assert len(root["parts"]) == 2 + entry = registry.get(root["key"]) + assert len(entry.topologies) == len(root["parts"]) + assert entry.subshape(1, "face", 1).ShapeType() == "Face" + + +def test_registry_release_drops_subtrees(): + registry, nodes = build({"assy": make_assembly()}) + root = nodes[0] + registry.release([root["key"]]) + with pytest.raises(KeyError): + registry.get(root["children"][0]["key"]) + + +def test_known_geometry_is_sent_as_a_reference_without_tessellating_again( + monkeypatch, +): + cache = GeometryCache() + first_builder = SceneBuilder(Registry(), Tolerance(), geometry_cache=cache) + first = first_builder.build({"box": ShownObject(cq.Workplane().box(1, 2, 3))}) + geometry_id = first[0]["parts"][0]["mesh"]["id"] + + def unexpected(*_args, **_kwargs): + raise AssertionError("known geometry was tessellated again") + + monkeypatch.setattr(cache, "tessellate", unexpected) + second_builder = SceneBuilder( + Registry(), + Tolerance(), + geometry_cache=cache, + known_geometry=[geometry_id], + ) + second = second_builder.build({"box": ShownObject(cq.Workplane().box(1, 2, 3))}) + + assert second[0]["parts"][0]["mesh"] == {"id": geometry_id} + + +def test_repeated_assembly_parts_share_local_geometry(): + profile = cq.Workplane().box(40, 20, 1000) + assembly = ( + cq.Assembly() + .add(profile, name="left", loc=cq.Location(cq.Vector(0, 0, 0))) + .add(profile, name="right", loc=cq.Location(cq.Vector(5000, 0, 0))) + ) + _, nodes = build({"frame": assembly}) + left, right = nodes[0]["children"] + left_part, right_part = left["parts"][0], right["parts"][0] + + assert left_part["mesh"]["id"] == right_part["mesh"]["id"] + assert "bbox" in left_part["mesh"] + assert right_part["mesh"] == {"id": left_part["mesh"]["id"]} + assert left_part["transform"][12:15] == pytest.approx([0, 0, 0]) + assert right_part["transform"][12:15] == pytest.approx([5000, 0, 0]) + + +def test_building_reports_progress_per_part(): + registry = Registry() + builder = SceneBuilder(registry, Tolerance()) + reports = [] + builder.progress = lambda done, total: reports.append((done, total)) + assembly = ( + cq.Assembly() + .add(cq.Workplane().box(1, 1, 1), name="a") + .add(cq.Workplane().sphere(1), name="b") + ) + builder.build( + { + "box": ShownObject(cq.Workplane().box(1, 2, 3)), + "assembly": ShownObject(assembly), + } + ) + assert reports == [(0, 3), (1, 3), (2, 3), (3, 3)] + + +def test_a_cancelled_build_frees_what_it_registered(): + registry = Registry() + kept = registry.add(RegistryEntry(cq.Workplane(), None)) + builder = SceneBuilder(registry, Tolerance()) + asked = [] + + def cancelled(): + asked.append(True) + return len(asked) > 2 + + builder.cancelled = cancelled + objects = { + f"box{i}": ShownObject(cq.Workplane().box(1 + i, 1, 1)) for i in range(4) + } + with pytest.raises(BuildCancelled): + builder.build(objects) + assert len(asked) == 3, "asked before each part, stopped at the third" + assert registry.keys() == [kept], "the two finished nodes are released" diff --git a/tests/worker/geometry/test_selection.py b/tests/worker/geometry/test_selection.py new file mode 100644 index 000000000..e057c62e4 --- /dev/null +++ b/tests/worker/geometry/test_selection.py @@ -0,0 +1,327 @@ +"""Selectors generated for picked faces, edges and vertices.""" + +import cadquery as cq +import pytest +from OCP.TopAbs import TopAbs_EDGE, TopAbs_FACE, TopAbs_VERTEX +from OCP.TopExp import TopExp + +from cq_worker import selection +from cq_worker.measurement import MeasurementError +from cq_worker.selection import ( + Features, + PickedSelection, + Receiver, + SelectorError, + atoms, + selector_candidates, +) +from cq_worker.scene import Registry, SceneBuilder, ShownObject, to_compound +from cq_worker.tessellation import ShapeMap, Tolerance + +_KINDS = {"face": TopAbs_FACE, "edge": TopAbs_EDGE, "vertex": TopAbs_VERTEX} +_LISTS = {"face": "Faces", "edge": "Edges", "vertex": "Vertices"} + + +def show(objects, merge_assemblies=False): + registry = Registry() + builder = SceneBuilder(registry, Tolerance(), merge_assemblies=merge_assemblies) + nodes = builder.build({name: ShownObject(obj) for name, obj in objects.items()}) + return registry, nodes + + +def topology_ids(obj, kind, shapes): + """The 1-based ids the GUI picks for ``shapes`` of ``obj``.""" + + # The worker's map type: OCP 8 dropped the TopTools_IndexedMapOfShape alias. + index = ShapeMap() + TopExp.MapShapes_s(to_compound(obj).wrapped, _KINDS[kind], index) + return [index.FindIndex(shape.wrapped) for shape in shapes] + + +def references(key, kind, ids, part=0): + return [ + {"key": key, "part": part, "kind": kind, "identifier": identifier} + for identifier in ids + ] + + +def apply(obj, expression): + """Runs the expression the way a script does: appended to the object.""" + + result = eval("obj" + expression, {"obj": obj, "cq": cq}) + return result.vals() if isinstance(result, cq.Workplane) else [result] + + +def entities(obj, kind): + shape = to_compound(obj) + return getattr(shape, _LISTS[kind])() + + +def selected(obj, kind, expression): + found = [] + for shape in apply(obj, expression): + found.extend(getattr(shape, _LISTS[kind])()) + return set(found) + + +MODELS = { + "box": lambda: cq.Workplane().box(10, 20, 30), + "cylinder": lambda: cq.Workplane().cylinder(10, 5), + "plate with holes": lambda: cq.Workplane() + .box(40, 40, 5) + .faces(">Z") + .workplane() + .rarray(10, 10, 3, 3) + .hole(3) + .edges("|Z") + .fillet(0.5), + "chamfered box": lambda: cq.Workplane().box(10, 10, 10).edges(">Z").chamfer(2), + "bracket": lambda: cq.Workplane() + .box(30, 20, 4) + .faces(">Y") + .workplane() + .rect(30, 4) + .extrude(15) + .edges("|X") + .fillet(1), +} + + +@pytest.mark.parametrize("model", MODELS) +@pytest.mark.parametrize("kind", ["face", "edge", "vertex"]) +def test_every_entity_gets_a_selector_that_selects_exactly_it(model, kind): + obj = MODELS[model]() + registry, (node,) = show({"part": obj}) + for shape in entities(obj, kind): + (identifier,) = topology_ids(obj, kind, [shape]) + result = selector_candidates( + registry, references(node["key"], kind, [identifier]) + ) + assert result["method"] == {"face": "faces", "edge": "edges"}.get( + kind, "vertices" + ) + for candidate in result["candidates"]: + assert selected(obj, kind, candidate["expression"]) == {shape}, candidate + # These models never need the index fallback. + assert not result["candidates"][0]["index_based"] + + +def test_simple_selectors_are_preferred(): + box = cq.Workplane().box(10, 20, 30) + registry, (node,) = show({"box": box}) + + def best(kind, selector): + picked = getattr(box, {"face": "faces", "edge": "edges"}[kind])(selector) + ids = topology_ids(box, kind, picked.vals()) + result = selector_candidates(registry, references(node["key"], kind, ids)) + return result["candidates"][0]["expression"] + + assert best("face", ">Z") == '.faces(">Z")' + assert best("face", "Z") == '.edges(">Z")' + assert best("edge", "|Z and >Y and >X") == '.edges(">X and >Y")' + assert best("face", ">X or Z and >X").chamfer(*distances) + registry, (node,) = show({"wedge": wedge}) + chamfer = wedge.faces("not (|X or |Y or |Z)").vals() + assert len(chamfer) == 1 + result = selector_candidates( + registry, + references(node["key"], "face", topology_ids(wedge, "face", chamfer)), + ) + for candidate in result["candidates"]: + assert selected(wedge, "face", candidate["expression"]) == set(chamfer) + # What the face is, not where it ranks among its neighbors. + assert result["candidates"][0]["expression"] == f'.faces("+{direction}")' + + +def test_selectors_of_an_assembly_part_use_its_own_coordinates(): + plate = cq.Workplane().box(10, 10, 2) + assembly = cq.Assembly().add( + plate, name="plate", loc=cq.Location((0, 0, 50), (1, 0, 0), 90) + ) + for merge in (False, True): + registry, (node,) = show({"assembly": assembly}, merge_assemblies=merge) + key = node["key"] if merge else node["children"][0]["key"] + top = topology_ids(plate, "face", plate.faces(">Z").vals()) + result = selector_candidates(registry, references(key, "face", top)) + assert result["candidates"][0]["expression"] == '.faces(">Z")' + + +def test_shapes_are_receivers_too(): + solid = cq.Workplane().box(4, 6, 8).val() + registry, (node,) = show({"solid": solid}) + top = solid.faces(">Z") + result = selector_candidates( + registry, references(node["key"], "face", topology_ids(solid, "face", [top])) + ) + assert result["candidates"][0]["expression"] == '.faces(">Z")' + for candidate in result["candidates"]: + assert selected(solid, "face", candidate["expression"]) == {top} + + +@pytest.mark.parametrize( + "obj", + [cq.Workplane().box(4, 6, 8), cq.Workplane().box(4, 6, 8).val()], + ids=["workplane", "shape"], +) +def test_the_index_fallback_selects_exactly_the_picked_entity(obj, monkeypatch): + monkeypatch.setattr(selection, "search", lambda features, targets: []) + registry, (node,) = show({"part": obj}) + face = entities(obj, "face")[3] + result = selector_candidates( + registry, references(node["key"], "face", topology_ids(obj, "face", [face])) + ) + + (candidate,) = result["candidates"] + assert candidate["index_based"] + assert "may change with the model" in candidate["description"] + assert selected(obj, "face", candidate["expression"]) == {face} + + +def test_several_entities_of_a_workplane_have_an_index_fallback(monkeypatch): + monkeypatch.setattr(selection, "search", lambda features, targets: []) + box = cq.Workplane().box(4, 6, 8) + registry, (node,) = show({"box": box}) + picked = entities(box, "edge")[2:4] + result = selector_candidates( + registry, references(node["key"], "edge", topology_ids(box, "edge", picked)) + ) + (candidate,) = result["candidates"] + assert candidate["expression"] == ".edges()[[2, 3]]" + assert selected(box, "edge", candidate["expression"]) == set(picked) + + +@pytest.mark.parametrize("model", ["box", "plate with holes", "chamfered box"]) +@pytest.mark.parametrize("kind", ["face", "edge", "vertex"]) +def test_simple_selectors_are_evaluated_exactly_as_cadquery_does(model, kind): + obj = MODELS[model]() + receiver = Receiver(obj, kind) + features = Features.of(receiver.entities()) + for atom in atoms(features): + expected = set(receiver.select(atom.expression)) + found = { + features.entities[i] + for i in range(len(features.entities)) + if atom.mask >> i & 1 + } + assert found == expected, atom.expression + + +def test_entities_of_two_objects_or_two_kinds_have_no_selector(): + box = cq.Workplane().box(1, 1, 1) + registry, nodes = show({"a": box, "b": cq.Workplane().sphere(1)}) + with pytest.raises(SelectorError, match="one object"): + selector_candidates( + registry, + references(nodes[0]["key"], "face", [1]) + + references(nodes[1]["key"], "face", [1]), + ) + with pytest.raises(SelectorError, match="one kind"): + selector_candidates( + registry, + references(nodes[0]["key"], "face", [1]) + + references(nodes[0]["key"], "edge", [1]), + ) + with pytest.raises(SelectorError, match="Select faces"): + selector_candidates(registry, []) + + +def test_stale_or_unsupported_objects_report_why(): + registry, (node,) = show({"sketch": cq.Sketch().rect(2, 2)}) + with pytest.raises(SelectorError, match="not for a Sketch"): + selector_candidates(registry, references(node["key"], "face", [1])) + registry.release([node["key"]]) + with pytest.raises(SelectorError, match="Unknown object"): + selector_candidates(registry, references(node["key"], "face", [1])) + + registry, (node,) = show({"box": cq.Workplane().box(1, 1, 1)}) + with pytest.raises(SelectorError, match="Unknown face id 7"): + selector_candidates(registry, references(node["key"], "face", [7])) + + +# -- the console's selected() --------------------------------------------------- + + +def test_picked_entities_resolve_to_live_shapes_placed_as_shown(): + plate = cq.Workplane().box(10, 10, 2) + assembly = cq.Assembly().add(plate, name="plate", loc=cq.Location((0, 0, 50))) + registry, (node,) = show({"assembly": assembly}) + key = node["children"][0]["key"] + top = topology_ids(plate, "face", plate.faces(">Z").vals()) + edge = topology_ids(plate, "edge", plate.edges("|Z and >X and >Y").vals()) + + picked = PickedSelection.from_message( + { + "entities": references(key, "face", top) + references(key, "edge", edge), + "objects": [node["key"]], + } + ) + face, line = picked.resolve(registry) + + assert isinstance(face, cq.Face) and isinstance(line, cq.Edge) + assert face.Area() == pytest.approx(100) + # In the assembly's coordinates, as the 3D view shows it. + assert face.Center().z == pytest.approx(51) + assert line.Length() == pytest.approx(2) + + +def test_without_picked_entities_the_selected_objects_are_returned(): + box = cq.Workplane().box(1, 2, 3) + assembly = ( + cq.Assembly() + .add(cq.Workplane().box(1, 1, 1), name="a") + .add(cq.Workplane().sphere(1), name="b", loc=cq.Location((5, 0, 0))) + ) + registry, (box_node, assembly_node) = show({"box": box, "assembly": assembly}) + + solid, both = PickedSelection.from_message( + {"objects": [box_node["key"], assembly_node["key"]]} + ).resolve(registry) + + # A shown workplane holding one solid is that solid, not a compound. + assert isinstance(solid, cq.Solid) and solid.Volume() == pytest.approx(6) + assert isinstance(both, cq.Compound) and len(both.Solids()) == 2 + assert PickedSelection.from_message(None).resolve(registry) == [] + + +def test_a_stale_selection_explains_itself(): + box = cq.Workplane().box(1, 1, 1) + registry, (node,) = show({"box": box}) + gone = PickedSelection.from_message( + {"entities": references(node["key"], "face", [9])} + ) + with pytest.raises(LookupError, match="pick it again"): + gone.resolve(registry) + registry.release([node["key"]]) + stale = PickedSelection.from_message({"objects": [node["key"]]}) + with pytest.raises(LookupError, match="previous Python session"): + stale.resolve(registry) + + +@pytest.mark.parametrize( + "message", + [[], {"entities": {}}, {"objects": [3]}, {"entities": [{"key": "n1"}]}], +) +def test_malformed_selections_are_rejected(message): + with pytest.raises(MeasurementError): + PickedSelection.from_message(message) diff --git a/tests/worker/geometry/test_selector_preview.py b/tests/worker/geometry/test_selector_preview.py new file mode 100644 index 000000000..61630519b --- /dev/null +++ b/tests/worker/geometry/test_selector_preview.py @@ -0,0 +1,71 @@ +"""The caret preview reads selectors without evaluating source expressions.""" + +import cadquery as cq + +from cq_worker.scene import Registry, SceneBuilder, ShownObject +from cq_worker.selector_preview import preview +from cq_worker.tessellation import Tolerance + + +def displayed(obj): + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build({"part": ShownObject(obj)}) + return registry, nodes[0]["key"] + + +def test_literal_selector_matches_exact_displayed_topology(): + part = cq.Workplane().box(2, 3, 4) + registry, key = displayed(part) + source = 'part.faces(">Z")\n' + result = preview(registry, {"part": part}, source, 1, 12) + assert result["active"] + assert result["count"] == 1 + assert len(result["matches"]) == 1 + match = result["matches"][0] + assert match["key"] == key + assert match["kind"] == "face" + selected = registry.get(key).subshape(match["part"], "face", match["identifier"]) + assert selected.wrapped.IsSame(part.faces(">Z").val().wrapped) + + +def test_empty_and_invalid_selectors_report_without_stale_highlights(): + part = cq.Workplane().box(2, 3, 4) + registry, _ = displayed(part) + empty = preview(registry, {"part": part}, 'part.faces(">X and Z")\nx = 1', 2, 2) + assert not outside["active"] + + +def test_caret_column_counts_characters_before_non_ascii_text(): + part = cq.Workplane().box(2, 3, 4) + registry, _ = displayed(part) + source = 'label = "peça"; part.faces(">Z")' + column = source.index("faces") + 2 + result = preview(registry, {"part": part}, source, 1, column) + assert result["active"] and result["count"] == 1 + + +def test_dynamic_receiver_and_argument_are_never_executed(): + part = cq.Workplane().box(2, 3, 4) + registry, _ = displayed(part) + calls = [] + + def dangerous(): + calls.append(1) + return part + + dynamic_receiver = preview( + registry, + {"part": part, "dangerous": dangerous}, + 'dangerous().faces(">Z")', + 1, + 18, + ) + dynamic_argument = preview( + registry, {"part": part}, "part.faces(dangerous())", 1, 16 + ) + assert dynamic_receiver["message"] and dynamic_argument["message"] + assert calls == [] diff --git a/tests/worker/geometry/test_tessellation.py b/tests/worker/geometry/test_tessellation.py new file mode 100644 index 000000000..4f50277f5 --- /dev/null +++ b/tests/worker/geometry/test_tessellation.py @@ -0,0 +1,350 @@ +import os +import time + +import cadquery as cq +import numpy as np +import OCP +import pytest + +from conftest import decode +from cq_worker import tessellation +from cq_worker.tessellation import GeometryCache, Tolerance, TopologyIndex, tessellate + + +def test_box_mesh(): + mesh = tessellate(cq.Workplane().box(2, 4, 6).val().wrapped, Tolerance()) + + assert len(mesh.indices) == 12 * 3 # two triangles per face + assert mesh.indices.max() < len(mesh.positions) + assert len(mesh.edges) == 12 # straight edges need one segment each + assert len(mesh.points) == 0 + assert sorted(set(mesh.triangle_faces)) == [1, 2, 3, 4, 5, 6] + assert sorted(set(mesh.segment_edges)) == list(range(1, 13)) + assert len(mesh.topology_vertices) == 8 + # The display triangles are the pick triangles: no second copy. + assert len(mesh.triangle_faces) == len(mesh.indices) // 3 + assert len(mesh.face_positions) == len(mesh.face_indices) == 0 + assert len(mesh.segment_edges) == len(mesh.edges) + lo, hi = mesh.bounds() + assert lo == pytest.approx([-1, -2, -3]) + assert hi == pytest.approx([1, 2, 3]) + + +def test_normals_are_unit_and_point_outwards(): + mesh = tessellate(cq.Workplane().sphere(5).val().wrapped, Tolerance()) + + lengths = np.linalg.norm(mesh.normals, axis=1) + assert lengths == pytest.approx(np.ones_like(lengths), abs=1e-4) + # On a sphere centered at the origin the outward normal is the position. + radial = mesh.positions / np.linalg.norm(mesh.positions, axis=1, keepdims=True) + assert np.einsum("ij,ij->i", radial, mesh.normals).min() > 0.99 + + +def test_transformed_shapes_are_meshed_in_world_space(): + shape = cq.Workplane().box(10, 20, 30).val() + moved = shape.moved(cq.Location(cq.Vector(100, 0, 0), cq.Vector(1, 0, 0), 90)) + mesh = tessellate(moved.wrapped, Tolerance()) + + lo, hi = mesh.bounds() + assert lo == pytest.approx([95, -15, -10], abs=1e-4) + assert hi == pytest.approx([105, 15, 10], abs=1e-4) + assert sorted(set(mesh.triangle_faces)) == [1, 2, 3, 4, 5, 6] + assert mesh.topology_vertices.min(axis=0) == pytest.approx(lo, abs=1e-4) + assert mesh.topology_vertices.max(axis=0) == pytest.approx(hi, abs=1e-4) + + +def test_wires_and_vertices(): + wire = tessellate(cq.Workplane().circle(5).val().wrapped, Tolerance()) + assert len(wire.indices) == 0 and len(wire.edges) > 8 + assert set(wire.segment_edges) == {1} + + vertex = tessellate(cq.Vertex.makeVertex(1, 2, 3).wrapped, Tolerance()) + assert vertex.points.tolist() == [[1, 2, 3]] + assert vertex.topology_vertices.tolist() == [[1, 2, 3]] + + +def test_empty_shapes_have_no_mesh(): + assert tessellate(cq.Compound.makeCompound([]).wrapped, Tolerance()) is None + + +def test_message_round_trip(): + mesh = tessellate(cq.Workplane().box(1, 1, 1).val().wrapped, Tolerance()) + message = mesh.to_message() + + assert decode(message["positions"], " list[float]: + wrapped = shape.val().wrapped if isinstance(shape, cq.Workplane) else shape.wrapped + return [ + round(float(a), 1) + for a in tessellation.edge_angles(TopologyIndex.build(wrapped)) + ] + + +def test_edges_know_the_angle_their_faces_meet_at(): + # A box's edges are right angles. + assert set(edge_angles_of(cq.Workplane().box(10, 10, 10))) == {90.0} + # A fillet meets its faces smoothly; its far ends are still corners. + filleted = cq.Workplane().box(10, 10, 10).edges("|Z").fillet(2) + assert set(edge_angles_of(filleted)) == {0.0, 90.0} + # A cylinder: two circles at right angles and a smooth seam. + assert sorted(edge_angles_of(cq.Workplane().cylinder(10, 5))) == [0.0, 90.0, 90.0] + # Faces split in one plane meet flat. + split = ( + cq.Workplane() + .box(10, 10, 1) + .union(cq.Workplane().box(10, 10, 1).translate((10, 0, 0)), clean=False) + ) + assert 0.0 in edge_angles_of(split) + + +def test_open_edges_and_wires_are_outlines(): + outline = tessellation.OPEN_EDGE_ANGLE + assert set(edge_angles_of(cq.Workplane().rect(4, 4).val())) == {outline} + wire = cq.Workplane().polyline([(0, 0), (1, 0), (1, 1)]).val() + assert edge_angles_of(wire) == [outline] + + +def test_every_segment_carries_the_angle_of_its_edge(): + mesh = tessellate( + cq.Workplane().box(10, 10, 10).edges("|Z").fillet(2).val().wrapped, Tolerance() + ) + assert len(mesh.segment_angles) == len(mesh.edges) + angles = tessellation.edge_angles( + TopologyIndex.build( + cq.Workplane().box(10, 10, 10).edges("|Z").fillet(2).val().wrapped + ) + ) + assert mesh.segment_angles.tolist() == angles[mesh.segment_edges - 1].tolist() + assert mesh.segment_angles.dtype == np.float32 + + +def test_finer_tolerance_gives_more_triangles(): + shape = cq.Workplane().sphere(5).val().wrapped + coarse = tessellate(shape, Tolerance(linear=1e-2, angular=0.5)) + fine = tessellate( + cq.Workplane().sphere(5).val().wrapped, Tolerance(linear=1e-4, angular=0.1) + ) + assert len(fine.indices) > len(coarse.indices) + + +def test_geometry_cache_survives_occt_meshing_side_effects(): + shape = cq.Workplane().sphere(5).val().wrapped + tolerance = Tolerance() + cache = GeometryCache() + first_id, first = cache.tessellate(shape, tolerance, TopologyIndex.build(shape)) + + # Meshing changes internal OCCT flags and therefore the raw BREP digest. + # The cache aliases that post-mesh representation back to the original. + second_id, second = cache.tessellate(shape, tolerance, TopologyIndex.build(shape)) + assert second_id == first_id + assert second is first + + rebuilt = cq.Workplane().sphere(5).val().wrapped + rebuilt_id, rebuilt_mesh = cache.tessellate( + rebuilt, tolerance, TopologyIndex.build(rebuilt) + ) + assert rebuilt_id == first_id + assert rebuilt_mesh is first + + +def test_geometry_ids_name_the_mesher_that_made_them(): + # The GUI keeps meshes across worker restarts, also when Python moves to + # another OCP build; a mesh of that other build must never be reused. + shape = cq.Workplane().box(1, 2, 3).val().wrapped + tolerance = Tolerance() + current = GeometryCache().identifier(shape, tolerance) + + assert GeometryCache().identifier(shape, tolerance) == current + assert GeometryCache(generator="another OCP").identifier(shape, tolerance) != ( + current + ) + generator = tessellation.mesh_generator() + assert f"cq-editor-mesh {tessellation.MESH_FORMAT};" in generator + assert OCP.__version__ in generator + # The installed binary, which tells environments with equal versions apart. + assert os.path.normcase(os.path.abspath(OCP.OCP.__file__)) in generator + + +def test_large_structural_dimensions_keep_submillimeter_cross_sections(): + mesh = tessellate( + cq.Workplane().box(1_000_000, 0.5, 0.25).val().wrapped, Tolerance() + ) + lo, hi = mesh.bounds() + + assert hi[0] - lo[0] == pytest.approx(1_000_000, abs=0.05) + assert hi[1] - lo[1] == pytest.approx(0.5, abs=1e-6) + assert hi[2] - lo[2] == pytest.approx(0.25, abs=1e-6) + + +def _face_centroids(positions, indices, faces) -> set: + corners = positions[np.asarray(indices).reshape(-1, 3)] + centers = np.round(corners.mean(axis=1), 3) + return {(int(face), *map(float, center)) for face, center in zip(faces, centers)} + + +def _sketch_faces(): + sketch = cq.Sketch().circle(4).rect(3, 3, mode="s") + return cq.Compound.makeCompound(list(sketch.moved(cq.Location(cq.Vector(0, 0, 2))))) + + +_BOX = cq.Solid.makeBox(1, 1, 1) +FACE_ID_SHAPES = { + "box": lambda: cq.Workplane().box(2, 4, 6).val(), + "sphere": lambda: cq.Workplane().sphere(5).val(), + "torus": lambda: cq.Solid.makeTorus(10, 2), + "filleted holes": lambda: cq.Workplane() + .box(40, 40, 5) + .faces(">Z") + .workplane() + .rarray(10, 10, 3, 3) + .hole(3) + .edges("|Z") + .fillet(0.5) + .val(), + "reversed faces of a cut": lambda: cq.Workplane() + .box(10, 10, 10) + .cut(cq.Workplane().sphere(6)) + .val(), + "two solids": lambda: cq.Compound.makeCompound( + [_BOX, cq.Solid.makeBox(1, 1, 1, cq.Vector(1, 0, 0))] + ), + "a solid listed twice": lambda: cq.Compound.makeCompound([_BOX, _BOX]), + "sketch faces": _sketch_faces, + "moved and rotated": lambda: cq.Workplane() + .box(3, 3, 3) + .val() + .moved(cq.Location(cq.Vector(5, 0, 0), cq.Vector(0, 1, 0), 30)), + "open shell": lambda: cq.Shell.makeShell( + cq.Workplane().box(1, 2, 3).faces().vals()[:3] + ), +} + + +@pytest.mark.parametrize("name", FACE_ID_SHAPES) +def test_display_triangles_carry_the_face_ids_of_separate_pick_triangles(name): + shape = FACE_ID_SHAPES[name]().wrapped + mesh = tessellate(shape, Tolerance()) + assert len(mesh.face_indices) == 0, "display triangles must be matched" + assert len(mesh.triangle_faces) == len(mesh.indices) // 3 + + # The former extraction, walking every face's triangulation, is the + # oracle: each face must own exactly the same triangles. + topology = TopologyIndex.build(shape) + positions, indices, faces = tessellation._topology_faces(topology.faces) + assert _face_centroids( + mesh.positions, mesh.indices, mesh.triangle_faces + ) == _face_centroids(positions, indices, faces) + + +def test_unmatched_display_triangles_fall_back_to_separate_pick_triangles( + monkeypatch, +): + monkeypatch.setattr(tessellation, "_display_triangle_faces", lambda *_: None) + mesh = tessellate(cq.Workplane().box(1, 1, 1).val().wrapped, Tolerance()) + + assert len(mesh.face_indices) == 12 * 3 + assert len(mesh.triangle_faces) == len(mesh.face_indices) // 3 + assert sorted(set(mesh.triangle_faces)) == [1, 2, 3, 4, 5, 6] + + +def test_face_ids_need_matching_triangle_counts(): + shape = cq.Workplane().box(1, 1, 1).val().wrapped + mesh = tessellate(shape, Tolerance()) # triangulates the faces + + assert ( + len(tessellation._display_triangle_faces(shape, mesh.positions, mesh.indices)) + == len(mesh.indices) // 3 + ) + extra_triangle = np.concatenate((mesh.indices, mesh.indices[:3])) + assert ( + tessellation._display_triangle_faces(shape, mesh.positions, extra_triangle) + is None + ) + invalid_indices = mesh.indices.astype(np.int64) + invalid_indices[0] = -1 + assert ( + tessellation._display_triangle_faces(shape, mesh.positions, invalid_indices) + is None + ) + + +def test_equal_triangle_counts_do_not_hide_reordered_face_groups(monkeypatch): + """A changed glTF face order must select the independent fallback mesh.""" + + original = tessellation._mesh_faces + + def reordered(*args): + positions, normals, indices = original(*args) + triangles = indices.reshape(-1, 3).copy() + # Every box face has two triangles. Swap the first two complete face + # groups, preserving both the per-face and total triangle counts. + triangles[:4] = triangles[[2, 3, 0, 1]] + return positions, normals, triangles.reshape(-1) + + monkeypatch.setattr(tessellation, "_mesh_faces", reordered) + mesh = tessellate(cq.Workplane().box(1, 2, 3).val().wrapped, Tolerance()) + + assert len(mesh.face_indices) == 12 * 3 + assert len(mesh.triangle_faces) == len(mesh.face_indices) // 3 + assert sorted(set(mesh.triangle_faces)) == [1, 2, 3, 4, 5, 6] + + +def test_triangle_order_inside_one_face_group_is_irrelevant(monkeypatch): + original = tessellation._mesh_faces + + def reordered(*args): + positions, normals, indices = original(*args) + triangles = indices.reshape(-1, 3).copy() + triangles[:2] = triangles[[1, 0]] + return positions, normals, triangles.reshape(-1) + + monkeypatch.setattr(tessellation, "_mesh_faces", reordered) + mesh = tessellate(cq.Workplane().box(1, 2, 3).val().wrapped, Tolerance()) + + assert len(mesh.face_indices) == 0 + assert len(mesh.triangle_faces) == len(mesh.indices) // 3 + + +def test_glb_round_trips_leave_only_an_empty_scratch_directory(): + tessellate(cq.Workplane().box(1, 1, 1).val().wrapped, Tolerance()) + first = tessellation._scratch_dir + tessellate(cq.Workplane().sphere(1).val().wrapped, Tolerance()) + + # One directory per worker process, reused and emptied after each mesh. + assert tessellation._scratch_dir == first + assert os.listdir(first) == [] + + +def test_scratch_left_by_killed_workers_is_removed_once_stale(tmp_path): + stale_dir = tmp_path / "cq-editor-mesh-killed" + stale_dir.mkdir() + (stale_dir / "mesh-1.glb").write_bytes(b"glTF") + stale_file = tmp_path / "cq-editor-abc123.glb" # older releases + stale_file.write_bytes(b"glTF") + fresh_dir = tmp_path / "cq-editor-mesh-running" + fresh_dir.mkdir() + unrelated = tmp_path / "notes.glb" + unrelated.write_bytes(b"glTF") + old = time.time() - 2 * tessellation.STALE_SCRATCH_SECONDS + for path in (stale_dir, stale_file, unrelated): + os.utime(path, (old, old)) + + tessellation._remove_stale_scratch(str(tmp_path)) + + assert not stale_dir.exists() + assert not stale_file.exists() + assert fresh_dir.exists() + assert unrelated.exists() diff --git a/tests/worker/protocol/test_channel.py b/tests/worker/protocol/test_channel.py new file mode 100644 index 000000000..4b64ea163 --- /dev/null +++ b/tests/worker/protocol/test_channel.py @@ -0,0 +1,208 @@ +"""Wire format and stream isolation regressions.""" + +import io +import json +import os +import time + +import pytest + +from cq_worker.protocol import ( + OUTPUT_CAPTURE_CHARS, + OUTPUT_CHUNK_CHARS, + Channel, + OutputStream, +) + + +def messages(writer): + return [json.loads(line) for line in writer.getvalue().splitlines()] + + +def test_receive_skips_empty_lines_and_returns_none_at_eof(): + channel = Channel(io.BytesIO(b'\n \n{"cmd":"run","id":4}\n'), io.BytesIO()) + assert channel.receive() == {"cmd": "run", "id": 4} + assert channel.receive() is None + + +def test_receive_rejects_malformed_json(): + channel = Channel(io.BytesIO(b"{broken}\n"), io.BytesIO()) + with pytest.raises(json.JSONDecodeError): + channel.receive() + + +def test_send_writes_one_utf8_message_per_line(): + writer = io.BytesIO() + channel = Channel(io.BytesIO(), writer) + channel.send({"type": "output", "text": "ação\n新"}) + channel.send({"type": "ready", "id": 3}) + assert messages(writer) == [ + {"type": "output", "text": "ação\n新"}, + {"type": "ready", "id": 3}, + ] + assert writer.getvalue().count(b"\n") == 2 + + +def test_send_rejects_non_json_floats_without_writing(): + writer = io.BytesIO() + channel = Channel(io.BytesIO(), writer) + with pytest.raises(ValueError): + channel.send({"value": float("nan")}) + assert writer.getvalue() == b"" + + +def test_output_stream_buffers_fragments_until_newline(): + writer = io.BytesIO() + channel = Channel(io.BytesIO(), writer) + channel.current_id = 17 + stream = OutputStream(channel, "stdout") + assert stream.writable() and stream.encoding == "utf-8" + assert stream.write("first ") == 6 + assert writer.getvalue() == b"" + stream.write("line\n") + assert messages(writer) == [ + {"type": "output", "id": 17, "stream": "stdout", "text": "first line\n"} + ] + + +def test_output_stream_flushes_partial_line_and_ignores_empty_write(): + writer = io.BytesIO() + stream = OutputStream(Channel(io.BytesIO(), writer), "stderr") + assert stream.write("") == 0 + stream.flush() + assert writer.getvalue() == b"" + stream.write("partial") + stream.flush() + stream.flush() + assert messages(writer) == [ + {"type": "output", "id": None, "stream": "stderr", "text": "partial"} + ] + + +def test_output_stream_flushes_by_size_without_waiting_for_a_newline(): + writer = io.BytesIO() + stream = OutputStream(Channel(io.BytesIO(), writer), "stdout") + text = "x" * (OUTPUT_CHUNK_CHARS + 1) + + stream.write(text) + + assert [message["text"] for message in messages(writer)] == [text[:-1]] + stream.flush() + assert "".join(message["text"] for message in messages(writer)) == text + + +def test_output_stream_truncates_excessive_output_per_request(): + writer = io.BytesIO() + channel = Channel(io.BytesIO(), writer) + channel.current_id = 4 + stream = OutputStream(channel, "stdout") + limit = OUTPUT_CAPTURE_CHARS + + text = "x" * (limit + 10) + assert stream.write(text) == len(text) + stream.write("discarded too") + stream.flush() + + first_request = [message["text"] for message in messages(writer)] + assert sum(part.count("x") for part in first_request) == limit + assert sum("output truncated" in part for part in first_request) == 1 + + channel.current_id = 5 + stream.write("new request\n") + assert messages(writer)[-1]["id"] == 5 + assert messages(writer)[-1]["text"] == "new request\n" + + +def test_output_stream_requires_text(): + stream = OutputStream(Channel(io.BytesIO(), io.BytesIO()), "stdout") + with pytest.raises(TypeError): + stream.write(b"bytes") + + +@pytest.mark.parametrize("error", [BrokenPipeError, ValueError]) +def test_output_stream_survives_disconnected_gui(error): + class BrokenWriter: + def write(self, _data): + raise error("gone") + + stream = OutputStream(Channel(io.BytesIO(), BrokenWriter()), "stdout") + stream.write("done\n") + stream.flush() + + +def test_cancellations_are_seen_while_a_request_is_handled(): + read_fd, write_fd = os.pipe() + with os.fdopen(read_fd, "rb", buffering=0) as reader: + channel = Channel(reader, io.BytesIO()) + os.write(write_fd, b'{"cmd":"run","id":1}\n') + assert channel.receive() == {"cmd": "run", "id": 1} + # Nothing more has arrived: asking does not wait. + assert not channel.cancel_requested(1) + + os.write( + write_fd, + b'{"cmd":"inspect","id":2}\n{"cmd":"cancel","target":1}\n{"cmd":"canc', + ) + assert channel.cancel_requested(1) + os.write(write_fd, b'el","target":2}\n') + assert channel.cancel_requested(2) + channel.forget_cancel(1) + assert not channel.cancel_requested(1) + + # What was read meanwhile is served in order, then the end. + assert channel.receive() == {"cmd": "inspect", "id": 2} + os.write(write_fd, b'{"cmd":"shutdown"}') + os.close(write_fd) + assert not channel.cancel_requested(3) + assert channel.receive() == {"cmd": "shutdown"} + assert channel.receive() is None + assert channel.receive() is None + + +def test_malformed_requests_are_raised_in_order(): + payload = b'{"cmd":"a"}\n{broken}\n{"cmd":"b"}\n' + channel = Channel(io.BytesIO(payload), io.BytesIO()) + + assert channel.receive() == {"cmd": "a"} + with pytest.raises(json.JSONDecodeError): + channel.receive() + assert channel.receive() == {"cmd": "b"} + + +def test_cancellations_are_recorded_between_requests_too(): + payload = b'{"cmd":"cancel","target":9}\n{"cmd":"run","id":9}\n' + channel = Channel(io.BytesIO(payload), io.BytesIO()) + assert channel.receive() == {"cmd": "run", "id": 9} + assert channel.cancel_requested(9) + + +def test_an_interrupt_stops_the_request_it_names_and_no_other(): + channel = Channel(io.BytesIO(b'{"cmd":"interrupt","target":3}\n'), io.BytesIO()) + assert channel.receive() is None, "recorded, not handed out" + + with channel.interruptible(4): + time.sleep(0.3) # not this request + with pytest.raises(KeyboardInterrupt): + with channel.interruptible(3): + while True: + pass + assert not channel.interrupt_requested(3), "forgotten once handled" + + +def test_an_interrupt_arriving_during_a_request_raises_in_it(): + read_fd, write_fd = os.pipe() + with os.fdopen(read_fd, "rb", buffering=0) as reader: + channel = Channel(reader, io.BytesIO()) + with pytest.raises(KeyboardInterrupt): + with channel.interruptible(5): + os.write( + write_fd, + b'{"cmd":"inspect","id":6}\n{"cmd":"interrupt","target":5}\n', + ) + while True: + pass + # What arrived with it is kept for later, in order. + os.write(write_fd, b'{"cmd":"shutdown"}\n') + os.close(write_fd) + assert channel.receive() == {"cmd": "inspect", "id": 6} + assert channel.receive() == {"cmd": "shutdown"} diff --git a/tests/worker/protocol/test_golden_messages.py b/tests/worker/protocol/test_golden_messages.py new file mode 100644 index 000000000..3a12f630f --- /dev/null +++ b/tests/worker/protocol/test_golden_messages.py @@ -0,0 +1,61 @@ +"""Wire examples shared with the Rust reader tests.""" + +import io +import json +from pathlib import Path + +import pytest + +from cq_worker.protocol import OUTPUT_CAPTURE_CHARS, Channel, OutputStream + +FIXTURE = ( + Path(__file__).resolve().parents[2] / "fixtures" / "protocol" / "messages.json" +) + + +def examples(): + return json.loads(FIXTURE.read_text(encoding="utf-8")) + + +def test_worker_emits_golden_messages_as_strict_json_lines(): + writer = io.BytesIO() + channel = Channel(io.BytesIO(), writer) + cases = examples()["valid"] + for case in cases: + channel.send(case["message"]) + + lines = writer.getvalue().splitlines() + assert len(lines) == len(cases) + assert [json.loads(line) for line in lines] == [case["message"] for case in cases] + assert json.loads(lines[1])["part"]["mesh"]["positions"] + assert list(json.loads(lines[2])["part"]["mesh"]) == ["id"] + + +def test_nonfinite_golden_message_cannot_cross_the_pipe(): + wire = examples()["invalid"][0]["wire"] + + def reject_constant(value): + raise ValueError(f"Non-finite JSON number: {value}") + + with pytest.raises(ValueError, match="NaN"): + json.loads(wire, parse_constant=reject_constant) + writer = io.BytesIO() + channel = Channel(io.BytesIO(), writer) + with pytest.raises(ValueError): + channel.send(json.loads(wire)) + assert not writer.getvalue() + + +def test_oversized_golden_output_is_split_and_bounded_before_the_pipe(): + spec = examples()["oversized_control"] + writer = io.BytesIO() + channel = Channel(io.BytesIO(), writer) + channel.current_id = 7 + stream = OutputStream(channel, "stdout") + stream.write("x" * spec["repeat"]) + messages = [json.loads(line) for line in writer.getvalue().splitlines()] + assert all(message["type"] == spec["type"] for message in messages) + assert ( + sum(message["text"].count("x") for message in messages) == OUTPUT_CAPTURE_CHARS + ) + assert sum("output truncated" in message["text"] for message in messages) == 1 diff --git a/tests/worker/protocol/test_network.py b/tests/worker/protocol/test_network.py new file mode 100644 index 000000000..d480459e9 --- /dev/null +++ b/tests/worker/protocol/test_network.py @@ -0,0 +1,154 @@ +"""Network requests are checked without contacting external services.""" + +import io +import json + +import pytest + +from cq_worker import network + + +class Response(io.BytesIO): + status = 201 + + +def test_upload_sends_file_as_binary_multipart(monkeypatch): + captured = {} + + def urlopen(request, timeout): + captured.update(request=request, timeout=timeout) + return Response(b"received") + + monkeypatch.setattr(network.urllib.request, "urlopen", urlopen) + result = network.upload( + "https://example.test/upload", b"\x00\xffshape", "part.step" + ) + request = captured["request"] + content_type = request.get_header("Content-type") + boundary = content_type.split("boundary=", 1)[1].encode() + + assert result == {"status": 201, "body": "received"} + assert request.full_url == "https://example.test/upload" + assert request.get_method() == "POST" + assert request.get_header("User-agent") == network.USER_AGENT + assert captured["timeout"] == network.TIMEOUT + assert b'name="file"; filename="part.step"' in request.data + assert b"\x00\xffshape" in request.data + assert request.data.startswith(b"--" + boundary + b"\r\n") + assert request.data.endswith(b"--" + boundary + b"--\r\n") + + +def test_upload_replaces_invalid_response_bytes(monkeypatch): + monkeypatch.setattr( + network.urllib.request, + "urlopen", + lambda *_args, **_kwargs: Response(b"bad \xff"), + ) + assert network.upload("https://example.test", b"x", "x") == { + "status": 201, + "body": "bad \ufffd", + } + + +def test_upload_response_is_bounded_before_it_enters_the_protocol(monkeypatch): + excess = b"x" * (network.MAX_UPLOAD_RESPONSE_BYTES + 100) + monkeypatch.setattr( + network.urllib.request, + "urlopen", + lambda *_args, **_kwargs: Response(excess), + ) + + result = network.upload("https://example.test", b"x", "x") + + assert result["body"].startswith("x" * network.MAX_UPLOAD_RESPONSE_BYTES) + assert result["body"].endswith( + f"[response truncated after {network.MAX_UPLOAD_RESPONSE_BYTES} bytes]" + ) + + +def test_newer_releases_ignores_drafts_and_older_versions(monkeypatch): + captured = {} + releases = [ + {"tag_name": "v2.3.0", "draft": False}, + {"tag_name": "v2.2.1", "draft": True}, + {"tag_name": "v2.2.0"}, + {"tag_name": "v1.99.0"}, + ] + + def urlopen(request, timeout): + captured.update(request=request, timeout=timeout) + return Response(json.dumps(releases).encode()) + + monkeypatch.setattr(network.urllib.request, "urlopen", urlopen) + assert network.newer_releases("2.2", "acme", "modeler") == ["v2.3.0"] + assert captured["request"].full_url.endswith("/acme/modeler/releases") + assert captured["timeout"] == network.TIMEOUT + + +def test_release_response_has_a_size_limit(monkeypatch): + excess = b"[" + b" " * network.MAX_RELEASES_RESPONSE_BYTES + monkeypatch.setattr( + network.urllib.request, + "urlopen", + lambda *_args, **_kwargs: Response(excess), + ) + + with pytest.raises(ValueError, match="Release response exceeds"): + network.newer_releases("2.2") + + +def test_release_response_must_be_a_list(monkeypatch): + monkeypatch.setattr( + network.urllib.request, + "urlopen", + lambda *_args, **_kwargs: Response(b'{"tag_name":"v9.0.0"}'), + ) + + with pytest.raises(ValueError, match="must be a JSON list"): + network.newer_releases("2.2") + + +@pytest.mark.parametrize( + ("version", "expected"), + [ + ("v2.4.0", (2, 4, 0)), + ("2.4", (2, 4, 0)), + ("v2.4.1-rc1", (2, 4, 1)), + ("release-10.0.12", (10, 0, 12)), + ], +) +def test_version_key_orders_numeric_components(version, expected): + assert network._version_key(version) == expected + + +def test_editor_releases_are_newer_published_ones_newest_first(monkeypatch): + captured = {} + releases = [ + { + "tag_name": "v0.9.0", + "name": "CQ-editor 0.9", + "html_url": "https://github.com/igors93/CQ-editor/releases/tag/v0.9.0", + }, + {"tag_name": "v0.10.0-rc1", "prerelease": True}, + {"tag_name": "v0.11.0", "draft": True}, + {"tag_name": "v0.10.1"}, + {"tag_name": "v0.8.0"}, + {"tag_name": "v0.7.5"}, + ] + + def urlopen(request, timeout): + captured.update(request=request) + return Response(json.dumps(releases).encode()) + + monkeypatch.setattr(network.urllib.request, "urlopen", urlopen) + newer = network.editor_releases("0.8.0") + assert captured["request"].full_url.endswith("/igors93/CQ-editor/releases") + assert [release["tag"] for release in newer] == ["v0.10.1", "v0.9.0"] + assert newer[1] == { + "tag": "v0.9.0", + "name": "CQ-editor 0.9", + "url": "https://github.com/igors93/CQ-editor/releases/tag/v0.9.0", + } + # Without a name or a page, the tag and the usual page stand in. + assert newer[0]["name"] == "v0.10.1" + assert newer[0]["url"].endswith("/igors93/CQ-editor/releases/tag/v0.10.1") diff --git a/tests/worker/protocol/test_server.py b/tests/worker/protocol/test_server.py new file mode 100644 index 000000000..b5b9307db --- /dev/null +++ b/tests/worker/protocol/test_server.py @@ -0,0 +1,560 @@ +"""End-to-end tests of the request/response protocol.""" + +import time + +import cadquery as cq +import pytest + +from cq_worker import completion + +BOX_SCRIPT = ( + "result = cq.Workplane().box(1, 2, 3)\nshow_object(result)\nprint('hello')\n" +) + + +def test_ready_and_run(conversation): + talk = conversation( + {"cmd": "run", "id": 1, "script": BOX_SCRIPT}, {"cmd": "shutdown"} + ) + talk.serve() + + ready = talk.of_type("ready")[0] + assert ready["cadquery"] + assert ready["ocp"] + (finished,) = talk.of_type("run_finished") + assert finished["id"] == 1 and finished["ok"] is True + assert [o["name"] for o in finished["objects"]] == ["result"] + variables = {row["name"]: row["type"] for row in finished["variables"]} + assert variables["result"] == "Workplane" + assert "show_object" not in variables + + (output,) = talk.of_type("output") + assert output == {"type": "output", "id": 1, "stream": "stdout", "text": "hello\n"} + + +def test_selector_preview_uses_only_the_completed_run(conversation): + script = 'part = cq.Workplane().box(1, 2, 3)\nselected = part.faces(">Z")\nshow_object(part)' + talk = conversation( + {"cmd": "run", "id": 1, "script": script}, + {"cmd": "selector_preview", "id": 2, "run_id": 1, "line": 2, "column": 18}, + {"cmd": "run", "id": 3, "script": "raise RuntimeError('broken')"}, + {"cmd": "selector_preview", "id": 4, "run_id": 1, "line": 2, "column": 18}, + ) + talk.serve() + first, stale = talk.of_type("selector_preview") + assert first["id"] == 2 and first["active"] and first["count"] == 1 + assert first["matches"][0]["kind"] == "face" + assert stale["id"] == 4 and not stale["active"] + + +def test_failed_run_keeps_previous_scene(conversation): + talk = conversation({"cmd": "run", "id": 7, "script": "1 / 0"}) + talk.serve() + + (finished,) = talk.of_type("run_finished") + assert finished["ok"] is False + assert finished["objects"] is None + assert finished["error"]["type_name"] == "ZeroDivisionError" + + +def test_a_non_finite_number_never_loses_the_whole_run(conversation, caplog): + # A NaN option is ignored; a NaN placement drops only that object. + script = ( + "import math\n" + "good = cq.Workplane().sphere(1)\n" + "show_object(good)\n" + "faded = cq.Workplane().box(1, 1, 1)\n" + "show_object(faded, options={'alpha': math.nan, 'color': 'red'})\n" + "lost = cq.Workplane().box(1, 1, 1).val().moved(cq.Location((math.nan, 0, 0)))\n" + "show_object(lost)\n" + ) + talk = conversation({"cmd": "run", "id": 3, "script": script}) + talk.serve() + + assert not talk.of_type("error") + (finished,) = talk.of_type("run_finished") + assert finished["ok"] is True + objects = {node["name"]: node for node in finished["objects"]} + assert list(objects) == ["good", "faded"] + assert objects["faded"]["alpha"] is None + assert objects["faded"]["color"] == pytest.approx([1, 0, 0], abs=1e-3) + assert "Cannot display lost:" in caplog.text + assert "NaN or infinity" in caplog.text + + +def test_script_log_reaches_the_gui(conversation): + talk = conversation({"cmd": "run", "id": 2, "script": "log('from script')"}) + import logging + + from cq_worker.server import ChannelLogHandler + + root = logging.getLogger() + handler, level = ChannelLogHandler(talk.channel), root.level + root.addHandler(handler) + root.setLevel(logging.INFO) + try: + talk.serve() + finally: + root.removeHandler(handler) + root.setLevel(level) + + messages = [m["message"] for m in talk.of_type("log")] + assert "from script" in messages + + +def test_script_log_truncates_an_excessive_record(conversation): + talk = conversation() + from cq_worker.protocol import LOG_MESSAGE_CHARS + from cq_worker.server import ChannelLogHandler + import logging + + handler = ChannelLogHandler(talk.channel) + record = logging.LogRecord( + "script", logging.INFO, __file__, 1, "x" * (LOG_MESSAGE_CHARS + 10), (), None + ) + + handler.emit(record) + + (message,) = talk.of_type("log") + assert message["message"].count("x") == LOG_MESSAGE_CHARS + assert "log truncated" in message["message"] + + +def test_script_log_has_a_total_limit_per_request(conversation): + talk = conversation() + from cq_worker.protocol import LOG_CAPTURE_CHARS, LOG_MESSAGE_CHARS + from cq_worker.server import ChannelLogHandler + import logging + + talk.channel.current_id = 3 + handler = ChannelLogHandler(talk.channel) + for _ in range(LOG_CAPTURE_CHARS // LOG_MESSAGE_CHARS): + handler.emit( + logging.LogRecord( + "script", logging.INFO, __file__, 1, "x" * LOG_MESSAGE_CHARS, (), None + ) + ) + handler.emit( + logging.LogRecord("script", logging.INFO, __file__, 1, "lost", (), None) + ) + handler.emit( + logging.LogRecord("script", logging.INFO, __file__, 1, "lost again", (), None) + ) + + first_request = talk.of_type("log") + assert ( + sum(message["message"].count("x") for message in first_request) + == LOG_CAPTURE_CHARS + ) + assert ( + sum("log output truncated" in message["message"] for message in first_request) + == 1 + ) + + talk.channel.current_id = 4 + handler.emit( + logging.LogRecord("script", logging.INFO, __file__, 1, "new", (), None) + ) + assert talk.of_type("log")[-1]["id"] == 4 + assert talk.of_type("log")[-1]["message"] == "new" + + +def test_restarted_worker_keeps_objects_when_stale_keys_are_released(conversation): + # After Stop or Restart Python the GUI still shows the old objects, and + # releases their keys once the first run of the new worker finishes. + old = conversation({"cmd": "run", "id": 1, "script": BOX_SCRIPT}, session="1") + old.serve() + (stale_key,) = [o["key"] for o in old.of_type("run_finished")[0]["objects"]] + + new = conversation( + {"cmd": "run", "id": 1, "script": BOX_SCRIPT}, + {"cmd": "release", "keys": [stale_key]}, + {"cmd": "inspect", "id": 2, "key": "s2-n1"}, + session="2", + ) + new.serve() + + assert stale_key == "s1-n1" + (finished,) = new.of_type("run_finished") + assert [o["key"] for o in finished["objects"]] == ["s2-n1"] + assert new.of_type("inspection")[0]["key"] == "s2-n1" + assert not new.of_type("error") + + +def test_debug_session(conversation): + script = "a = cq.Workplane().box(1, 1, 1)\nb = 2\nc = 3\n" + talk = conversation( + {"cmd": "run", "id": 3, "script": script, "debug": True, "breakpoints": [2]}, + {"cmd": "inspect", "id": 4, "key": "n1"}, + {"cmd": "debug", "action": "step"}, + {"cmd": "debug", "action": "continue"}, + ) + talk.serve() + + paused = talk.of_type("debug_paused") + assert [p["line"] for p in paused] == [2, 3] + assert [o["name"] for o in paused[0]["objects"]] == ["a"] + # Requests keep being served while paused. + assert talk.of_type("inspection")[0]["id"] == 4 + (finished,) = talk.of_type("run_finished") + assert finished["debug"] is True and finished["ok"] is True + + +def test_debug_stop(conversation): + talk = conversation( + { + "cmd": "run", + "id": 1, + "script": "a = 1\nb = 2\n", + "debug": True, + "breakpoints": [1], + }, + {"cmd": "debug", "action": "stop"}, + ) + talk.serve() + (finished,) = talk.of_type("run_finished") + assert finished["stopped"] is True + + +def test_inspection(conversation): + script = "w = cq.Workplane().box(1, 1, 1).faces('>Z').workplane().hole(0.2)\n" + talk = conversation( + {"cmd": "run", "id": 1, "script": script}, + {"cmd": "inspect", "id": 2, "key": "n1"}, + {"cmd": "inspect_geometry", "id": 3, "key": "n1", "frame": 0, "item": None}, + {"cmd": "inspect_geometry", "id": 4, "key": "n1", "frame": 2, "item": 0}, + ) + talk.serve() + + frames = talk.of_type("inspection")[0]["frames"] + assert len(frames) == 4 + assert frames[0]["type"] == "Workplane" + whole, single = talk.of_type("inspection_geometry") + assert whole["plane"]["size"] > 0 and len(whole["meshes"]) == 1 + assert single["plane"] is None + + +def test_console(conversation): + talk = conversation( + {"cmd": "run", "id": 1, "script": "size = 3"}, + {"cmd": "console", "id": 2, "source": "print(size * 2)"}, + {"cmd": "console", "id": 3, "source": "for i in range(2):"}, + {"cmd": "console", "id": 4, "source": " print(i)"}, + {"cmd": "console", "id": 5, "source": ""}, + ) + talk.serve() + + assert talk.output(2) == "6\n" + assert talk.output(5) == "0\n1\n" + results = {m["id"]: m["more"] for m in talk.of_type("console_result")} + assert results == {2: False, 3: True, 4: True, 5: False} + + +def test_console_show_object(conversation): + talk = conversation( + { + "cmd": "console", + "id": 1, + "source": "show_object(cq.Workplane().box(1, 1, 1))", + } + ) + talk.serve() + (added,) = talk.of_type("scene_add") + assert len(added["objects"]) == 1 + + +def test_export(conversation, tmp_path): + step, stl = tmp_path / "out.step", tmp_path / "out.stl" + talk = conversation( + {"cmd": "run", "id": 1, "script": BOX_SCRIPT}, + {"cmd": "export", "id": 2, "keys": ["n1"], "format": "step", "path": str(step)}, + {"cmd": "export", "id": 3, "keys": ["n1"], "format": "stl", "path": str(stl)}, + {"cmd": "export", "id": 4, "keys": ["n1"], "format": "obj", "path": str(stl)}, + ) + talk.serve() + + assert [m["id"] for m in talk.of_type("export_finished")] == [2, 3] + assert step.stat().st_size > 0 and stl.stat().st_size > 0 + (error,) = talk.of_type("error") + assert error["id"] == 4 + + +def test_unknown_commands_and_bad_keys_report_errors(conversation): + talk = conversation( + {"cmd": "bogus", "id": 1}, {"cmd": "inspect", "id": 2, "key": "nope"} + ) + talk.serve() + assert [e["id"] for e in talk.of_type("error")] == [1, 2] + + +def test_imports(conversation, tmp_path): + (tmp_path / "local_part.py").write_text("X = 1\n") + script = tmp_path / "main.py" + script.write_text("import local_part\nimport os\n") + talk = conversation({"cmd": "imports", "id": 1, "path": str(script)}) + talk.serve() + + (reply,) = talk.of_type("imports") + assert [p.replace("\\", "/").rsplit("/", 1)[-1] for p in reply["paths"]] == [ + "local_part.py" + ] + + +@pytest.mark.skipif(not completion.is_available(), reason="jedi is not installed") +def test_completion(conversation): + source = "result = cq.Workplane().bo" + talk = conversation( + { + "cmd": "complete", + "id": 1, + "source": source, + "line": 1, + "column": len(source), + }, + {"cmd": "complete", "id": 2, "source": "show_object(", "line": 1, "column": 12}, + ) + talk.serve() + + names, signatures = talk.of_type("completions") + assert "box" in [item["name"] for item in names["items"]] + assert signatures["items"] == [] and signatures["signatures"] + + +@pytest.mark.skipif(not completion.is_available(), reason="jedi is not installed") +def test_description_of_the_name_under_the_pointer(conversation): + source = "result = cq.Workplane().box(1, 2, 3)" + talk = conversation( + { + "cmd": "describe", + "id": 1, + "source": source, + "line": 1, + "column": source.index("box"), + }, + ) + talk.serve() + + (reply,) = talk.of_type("description") + assert reply["id"] == 1 + assert reply["signatures"][0].startswith("box(") + assert reply["text"] + + +def test_stack_descriptions_are_readable(): + from cq_worker.inspector import describe + + box = cq.Workplane().box(2, 2, 2) + assert describe(cq.Vector(1, 2.5, 0)) == "(1, 2.5, 0)" + assert describe(box.val()) == "1 solid(s), volume 8" + assert describe(box.faces(">Z").val()) == "plane, area 4" + assert describe(box.edges().val()).startswith("line, length 2") + assert describe(cq.Location(cq.Vector(1, 0, 0))) == "at (1, 0, 0)" + assert "object at 0x" not in describe(box.val()) + + +ASSEMBLY_SCRIPT = """\ +assy = cq.Assembly() +assy.add(cq.Workplane().box(1, 1, 1), name="a") +assy.add(cq.Workplane().sphere({radius}), name="b", loc=cq.Location((5, 0, 0))) +assy.add(cq.Workplane().cylinder(2, 0.5), name="c", loc=cq.Location((-5, 0, 0))) +show_object(assy) +""" + + +def _meshes(nodes: list[dict]) -> dict[str, dict]: + """Mesh messages by node name, through the assembly tree.""" + + found = {} + for node in nodes: + for part in node["parts"]: + found[node["name"]] = part["mesh"] + found.update(_meshes(node["children"])) + return found + + +def _assembly_run(request_id: int, radius: float, known=()) -> dict: + return { + "cmd": "run", + "id": request_id, + "script": ASSEMBLY_SCRIPT.format(radius=radius), + "known_geometry": list(known), + } + + +def test_run_reports_where_the_time_went(conversation): + talk = conversation({"cmd": "run", "id": 1, "script": BOX_SCRIPT}) + talk.serve() + + (finished,) = talk.of_type("run_finished") + timings = finished["timings"] + assert timings["script"] == finished["duration"] + assert timings["meshed"] == 1 + assert timings["cached"] == timings["referenced"] == 0 + assert timings["mesh_bytes"] > 0 + assert timings["tessellate"] > 0 and timings["identify"] > 0 + assert timings["encode"] > 0 + assert abs(timings["sent_at"] - time.time()) < 60 + + +def test_editing_one_assembly_part_meshes_and_sends_only_that_part(conversation): + first = conversation(_assembly_run(1, radius=1)) + first.serve() + (finished,) = first.of_type("run_finished") + before = {part["name"]: part["part"]["mesh"] for part in first.of_type("run_part")} + assert all("bbox" in mesh for mesh in before.values()) + assert all(list(mesh) == ["id"] for mesh in _meshes(finished["objects"]).values()) + assert finished["timings"]["meshed"] == 3 + + # The GUI advertises what it holds; only the edited sphere is new. + known = [mesh["id"] for mesh in before.values()] + edited = conversation(_assembly_run(2, radius=2, known=known)) + edited.serve() + (finished,) = edited.of_type("run_finished") + after = {part["name"]: part["part"]["mesh"] for part in edited.of_type("run_part")} + assert after["a"] == {"id": before["a"]["id"]} + assert after["c"] == {"id": before["c"]["id"]} + assert "bbox" in after["b"] and after["b"]["id"] != before["b"]["id"] + assert all(list(mesh) == ["id"] for mesh in _meshes(finished["objects"]).values()) + timings = finished["timings"] + assert (timings["meshed"], timings["cached"], timings["referenced"]) == (1, 0, 2) + + +def test_a_worker_remeshes_only_edited_parts_even_without_gui_geometry( + conversation, +): + # A GUI that holds nothing (e.g. after a restart) still saves meshing + # time through the worker's cache. + talk = conversation(_assembly_run(1, radius=1), _assembly_run(2, radius=2)) + talk.serve() + + first, second = talk.of_type("run_finished") + assert first["timings"]["meshed"] == 3 + timings = second["timings"] + assert (timings["meshed"], timings["cached"], timings["referenced"]) == (1, 2, 0) + + +def test_objects_and_inspector_steps_report_their_script_lines(conversation): + script = ( + "import cadquery as cq\n" + "plate = (\n" + " cq.Workplane()\n" + " .box(4, 4, 1)\n" + " .faces('>Z')\n" + ")\n" + "show_object(plate)\n" + ) + talk = conversation( + {"cmd": "run", "id": 1, "script": script}, + {"cmd": "inspect", "id": 2, "key": "n1"}, + {"cmd": "console", "id": 3, "source": "show_object(cq.Workplane().sphere(1))"}, + ) + talk.serve() + + (finished,) = talk.of_type("run_finished") + assert finished["objects"][0]["line"] == 5 + (inspection,) = talk.of_type("inspection") + # Newest first; the root Workplane() is not a step. + assert [frame["line"] for frame in inspection["frames"]] == [5, 4] + assert inspection["frames"][1]["items"][0]["line"] == 4 + # Objects made in the console have no script line. + (added,) = talk.of_type("scene_add") + assert added["objects"][0]["line"] is None + + +def test_meshing_progress_is_reported_before_the_result(conversation): + script = ( + "for i in range(3):\n" + " show_object(cq.Workplane().box(1 + i, 1, 1), name=f'box{i}')\n" + ) + talk = conversation({"cmd": "run", "id": 3, "script": script}) + talk.serve() + + progress = talk.of_type("progress") + assert progress[0] == { + "type": "progress", + "id": 3, + "stage": "meshing", + "done": 0, + "total": 3, + } + assert progress[-1]["done"] == 3 + done = [message["done"] for message in progress] + assert done == sorted(done) + types = [message["type"] for message in talk.messages] + assert types.index("run_finished") > types.index("progress") + (finished,) = talk.of_type("run_finished") + assert finished["cancelled"] is False + + +def test_a_cancelled_run_keeps_the_previous_scene(conversation): + talk = conversation( + # The GUI's cancellation is recorded as soon as it is read. + {"cmd": "cancel", "target": 5}, + {"cmd": "run", "id": 5, "script": BOX_SCRIPT}, + {"cmd": "run", "id": 6, "script": BOX_SCRIPT}, + ) + talk.serve() + + cancelled, finished = talk.of_type("run_finished") + assert cancelled["id"] == 5 and cancelled["cancelled"] is True + assert cancelled["ok"] is True and cancelled["objects"] is None + assert "result" in {row["name"] for row in cancelled["variables"]} + # Only that request was cancelled. + assert finished["cancelled"] is False + assert [o["name"] for o in finished["objects"]] == ["result"] + + +def test_stop_interrupts_a_running_script_and_the_worker_carries_on(conversation): + talk = conversation( + {"cmd": "run", "id": 1, "script": BOX_SCRIPT}, + # Stop, read before the script starts in this scripted conversation. + {"cmd": "interrupt", "target": 2}, + {"cmd": "run", "id": 2, "script": "count = 0\nwhile True:\n count += 1\n"}, + {"cmd": "console", "id": 3, "source": "print(type(result).__name__)"}, + {"cmd": "run", "id": 4, "script": BOX_SCRIPT}, + ) + talk.serve() + + first, stopped, again = talk.of_type("run_finished") + assert stopped["id"] == 2 and stopped["interrupted"] is True + assert stopped["ok"] is False and stopped["objects"] is None + assert stopped["error"]["type_name"] == "KeyboardInterrupt" + assert stopped["error"]["line"] in (2, 3), "where it was stopped" + assert first["interrupted"] is False and again["interrupted"] is False + + # The same process goes on: the console kept its namespace, and the + # mesh cache its meshes. + assert talk.output(3) == "Workplane\n" + assert again["timings"]["cached"] == 1 and again["timings"]["meshed"] == 0 + + +def test_stop_interrupts_a_console_command_and_keeps_the_namespace(conversation): + talk = conversation( + {"cmd": "console", "id": 1, "source": "kept = 41"}, + {"cmd": "interrupt", "target": 2}, + # A compound statement ends with a blank line, as typed. + {"cmd": "console", "id": 2, "source": "while True: kept += 0\n"}, + {"cmd": "console", "id": 3, "source": "print(kept + 1)"}, + ) + talk.serve() + + assert "KeyboardInterrupt" in talk.output(2) + assert [result["id"] for result in talk.of_type("console_result")] == [1, 2, 3] + assert talk.output(3) == "42\n" + + +def test_show_object_chooses_the_material_of_an_object(conversation): + script = ( + "plate = cq.Workplane().box(4, 4, 1)\n" + "show_object(plate, material='Brushed Steel')\n" + "knob = cq.Workplane().sphere(1)\n" + "show_object(knob, options={'color': 'green', 'material': 'matte plastic'})\n" + "bare = cq.Workplane().box(1, 1, 1)\n" + "show_object(bare)\n" + ) + talk = conversation({"cmd": "run", "id": 4, "script": script}) + talk.serve() + + (finished,) = talk.of_type("run_finished") + finishes = {node["name"]: node["finish"] for node in finished["objects"]} + assert finishes == {"plate": "brushed_steel", "knob": "matte_plastic", "bare": None} diff --git a/tests/worker/protocol/test_server_commands.py b/tests/worker/protocol/test_server_commands.py new file mode 100644 index 000000000..4fdce9673 --- /dev/null +++ b/tests/worker/protocol/test_server_commands.py @@ -0,0 +1,508 @@ +"""Less common request sequences that must remain safe for the GUI.""" + +from cq_worker import network + +BOX = "part = cq.Workplane().box(1, 2, 3)\nshow_object(part)" + + +def test_editor_navigation_requests_use_unsaved_source(conversation, tmp_path): + source = "def make_part():\n return 1\nvalue = make_part()\n" + path = tmp_path / "main.py" + talk = conversation( + {"cmd": "outline", "id": 1, "source": source}, + { + "cmd": "navigate", + "id": 2, + "source": source, + "path": str(path), + "project_root": str(tmp_path), + "line": 3, + "column": 13, + "mode": "definition", + }, + ) + talk.serve() + assert [symbol["name"] for symbol in talk.of_type("outline")[0]["symbols"]] == [ + "make_part", + "value", + ] + result = talk.of_type("navigation")[0] + assert result["available"] and result["mode"] == "definition" + assert result["locations"][0]["path"] is None + assert result["locations"][0]["line"] == 1 + + +def test_interference_geometry_returns_shared_volume_mesh(conversation): + first = {"key": "n1", "name": "first", "part": 0, "solid": 0} + second = {"key": "n2", "name": "second", "part": 0, "solid": 0} + talk = conversation( + { + "cmd": "run", + "id": 1, + "script": ( + "show_object(cq.Workplane().box(2, 2, 2), name='first')\n" + "show_object(cq.Workplane().box(2, 2, 2).translate((1, 0, 0)), " + "name='second')" + ), + }, + {"cmd": "interference_geometry", "id": 2, "first": first, "second": second}, + { + "cmd": "interference_geometry", + "id": 3, + "first": {**first, "solid": 99}, + "second": second, + }, + ) + talk.serve() + (reply,) = talk.of_type("interference_geometry") + assert reply["id"] == 2 + assert reply["mesh"]["positions"] + assert talk.of_type("error")[0]["id"] == 3 + + +def test_check_and_export_share_the_geometry_report(conversation, tmp_path): + script = ( + "box = cq.Workplane().box(1, 1, 1).val()\n" + "open_shell = cq.Shell.makeShell(box.Faces()[:-1])\n" + "show_object(open_shell)" + ) + path = tmp_path / "shell.step" + talk = conversation( + {"cmd": "run", "id": 1, "script": script}, + {"cmd": "check", "id": 2, "keys": ["n1"]}, + {"cmd": "export", "id": 3, "keys": ["n1"], "format": "step", "path": str(path)}, + { + "cmd": "export", + "id": 4, + "keys": ["n1"], + "format": "step", + "path": str(path), + "on_invalid": "ignore", + }, + ) + talk.serve() + report = talk.of_type("geometry_checked")[0]["reports"][0] + invalid = talk.of_type("geometry_invalid")[0]["reports"][0] + assert report["name"] == invalid["name"] + assert report["open_shells"] == invalid["open_shells"] == 1 + assert talk.of_type("export_finished")[0]["id"] == 4 + assert path.stat().st_size > 100 + + +def test_successful_run_then_failed_run_retains_previous_scene(conversation): + talk = conversation( + {"cmd": "run", "id": 1, "script": BOX}, + {"cmd": "run", "id": 2, "script": "raise ValueError('bad')"}, + ) + talk.serve() + first, second = talk.of_type("run_finished") + assert first["ok"] and len(first["objects"]) == 1 + assert not second["ok"] and second["objects"] is None + assert second["variables"] is None + + +def test_release_removes_objects_from_inspection_registry(conversation): + talk = conversation( + {"cmd": "run", "id": 1, "script": BOX}, + {"cmd": "inspect", "id": 2, "key": "n1"}, + {"cmd": "release", "id": 3, "keys": ["n1"]}, + {"cmd": "inspect", "id": 4, "key": "n1"}, + {"cmd": "inspect_geometry", "id": 5, "key": "n1", "frame": 0}, + ) + talk.serve() + assert talk.of_type("inspection")[0]["id"] == 2 + assert [error["id"] for error in talk.of_type("error")] == [4, 5] + + +def test_measurement_uses_live_occt_vertices_and_rejects_stale_ids(conversation): + talk = conversation( + { + "cmd": "run", + "id": 1, + "script": ( + "first = cq.Vertex.makeVertex(0, 0, 0)\n" + "second = cq.Vertex.makeVertex(3, 4, 0)\n" + ), + }, + { + "cmd": "measure", + "id": 2, + "selections": [ + {"key": "n1", "part": 0, "kind": "vertex", "identifier": 1}, + {"key": "n2", "part": 0, "kind": "vertex", "identifier": 1}, + ], + }, + {"cmd": "release", "keys": ["n1", "n2"]}, + { + "cmd": "measure", + "id": 3, + "selections": [{"key": "n1", "part": 0, "kind": "vertex", "identifier": 1}], + }, + ) + + talk.serve() + + (reply,) = talk.of_type("measurement") + assert reply["id"] == 2 + assert reply["pair"]["distance"] == 5.0 + assert reply["identity"] == {"scope": "scene_entry", "persistent": False} + (error,) = talk.of_type("error") + assert error["id"] == 3 + assert "previous Python session" in error["message"] + + +def test_selector_for_picked_faces_and_its_errors(conversation): + script = "box = cq.Workplane().box(2, 4, 6)\nshow_object(box)\n" + # Face 6 of a box is its top: OCCT's order is deterministic for one box. + top, bottom = 6, 5 + talk = conversation( + {"cmd": "run", "id": 1, "script": script}, + { + "cmd": "selector", + "id": 2, + "selections": [{"key": "n1", "part": 0, "kind": "face", "identifier": top}], + }, + { + "cmd": "selector", + "id": 3, + "selections": [ + {"key": "n1", "part": 0, "kind": "face", "identifier": top}, + {"key": "n1", "part": 0, "kind": "face", "identifier": bottom}, + ], + }, + { + "cmd": "selector", + "id": 4, + "selections": [{"key": "n1", "part": 0, "kind": "face", "identifier": 99}], + }, + ) + talk.serve() + + first, both = talk.of_type("selector") + assert first["id"] == 2 and first["method"] == "faces" + assert first["candidates"][0] == { + "expression": '.faces(">Z")', + "selector": ">Z", + "description": "largest Z", + "index_based": False, + } + assert both["candidates"][0]["expression"] == '.faces("|Z")' + (error,) = talk.of_type("error") + assert error["id"] == 4 and "Unknown face id 99" in error["message"] + + +def test_selectors_are_available_while_debugging(conversation): + talk = conversation( + { + "cmd": "run", + "id": 1, + "script": "box = cq.Workplane().box(1, 1, 1)\nx = 1\n", + "debug": True, + "breakpoints": [2], + }, + { + "cmd": "selector", + "id": 2, + "selections": [{"key": "n1", "part": 0, "kind": "edge", "identifier": 1}], + }, + {"cmd": "debug", "action": "continue"}, + ) + talk.serve() + + (reply,) = talk.of_type("selector") + assert reply["id"] == 2 and reply["candidates"] + assert not talk.of_type("error") + + +def test_console_reset_discards_previous_script_variables(conversation): + talk = conversation( + {"cmd": "run", "id": 1, "script": "value = 7"}, + {"cmd": "console", "id": 2, "source": "print(value)"}, + {"cmd": "console_reset", "id": 3}, + {"cmd": "console", "id": 4, "source": "print('value' in globals())"}, + ) + talk.serve() + assert talk.output(2) == "7\n" + assert talk.output(4) == "False\n" + assert [item["id"] for item in talk.of_type("console_result")] == [2, 3, 4] + + +def test_inspection_geometry_without_prior_inspection_reports_error(conversation): + talk = conversation( + {"cmd": "run", "id": 1, "script": BOX}, + {"cmd": "inspect_geometry", "id": 2, "key": "n1", "frame": 0}, + ) + talk.serve() + (error,) = talk.of_type("error") + assert error["id"] == 2 + assert "no longer inspected" in error["message"] + + +def test_python_upload_uses_utf8_source_and_no_model_selection( + conversation, monkeypatch +): + seen = {} + + def fake_upload(url, data, filename): + seen.update(url=url, data=data, filename=filename) + return {"status": 200, "body": "ok"} + + monkeypatch.setattr(network, "upload", fake_upload) + talk = conversation( + { + "cmd": "upload", + "id": 2, + "url": "https://example.test", + "file_type": "py", + "source": "label = 'ação'", + } + ) + talk.serve() + assert seen == { + "url": "https://example.test", + "data": "label = 'ação'".encode(), + "filename": "model.py", + } + assert talk.of_type("upload_finished") == [ + {"id": 2, "type": "upload_finished", "status": 200, "body": "ok"} + ] + + +def test_model_upload_requires_a_selection(conversation, monkeypatch): + monkeypatch.setattr(network, "upload", lambda *_args: None) + talk = conversation( + {"cmd": "upload", "id": 1, "url": "https://example.test", "file_type": "step"} + ) + talk.serve() + (error,) = talk.of_type("error") + assert error["id"] == 1 + assert "select a model" in error["message"] + + +def test_update_check_returns_current_and_newer_versions(conversation, monkeypatch): + monkeypatch.setattr(network, "newer_releases", lambda _current: ["v99.0.0"]) + talk = conversation({"cmd": "check_updates", "id": 8}) + talk.serve() + (reply,) = talk.of_type("updates") + assert reply["id"] == 8 + assert reply["current"] + assert reply["newer"] == ["v99.0.0"] + + +def test_console_requests_are_blocked_while_debugger_is_paused(conversation): + talk = conversation( + { + "cmd": "run", + "id": 1, + "debug": True, + "breakpoints": [2], + "script": "a = 1\nb = 2\n", + }, + {"cmd": "console", "id": 2, "source": "print(a)"}, + {"cmd": "debug", "action": "continue"}, + ) + talk.serve() + assert talk.of_type("debug_paused")[0]["line"] == 2 + (error,) = talk.of_type("error") + assert error["id"] == 2 + assert "Not available while debugging" in error["message"] + assert talk.of_type("run_finished")[0]["ok"] + + +def test_debug_pause_identifies_the_project_module(conversation, tmp_path): + module = tmp_path / "module_req08.py" + module.write_text("def work():\n result = 7\n return result\n") + talk = conversation( + { + "cmd": "run", + "id": 1, + "script": "import module_req08\nx = module_req08.work()\n", + "path": str(tmp_path / "main.py"), + "project_root": str(tmp_path), + "debug": True, + "breakpoints": [], + "module_breakpoints": {str(module): [2]}, + }, + { + "cmd": "debug", + "action": "continue", + "breakpoints": [], + "module_breakpoints": {}, + }, + ) + talk.serve() + + (pause,) = talk.of_type("debug_paused") + assert pause["path"].lower() == str(module).lower() + assert pause["line"] == 2 + assert talk.of_type("run_finished")[0]["ok"] + + +def test_run_streams_meshes_before_the_final_scene(conversation): + script = ( + "show_object(cq.Workplane().box(1, 1, 1), name='first')\n" + "show_object(cq.Workplane().sphere(2), name='second')\n" + ) + talk = conversation({"cmd": "run", "id": 4, "script": script}) + talk.serve() + + parts = talk.of_type("run_part") + (finished,) = talk.of_type("run_finished") + assert [part["name"] for part in parts] == ["first", "second"] + assert all(part["part"]["mesh"]["indices"] for part in parts) + assert all(list(node["parts"][0]["mesh"]) == ["id"] for node in finished["objects"]) + assert [message["type"] for message in talk.messages].index("run_part") < [ + message["type"] for message in talk.messages + ].index("run_finished") + + +def test_part_limit_reports_the_object_instead_of_breaking_the_pipe( + conversation, monkeypatch +): + from cq_worker import scene + + monkeypatch.setattr(scene, "MAX_STREAMED_MESH_BYTES", 1) + talk = conversation( + { + "cmd": "run", + "id": 9, + "script": "show_object(cq.Workplane().box(1, 1, 1), name='heavy')", + }, + {"cmd": "run", "id": 10, "script": "print('still alive')"}, + ) + talk.serve() + (error,) = talk.of_type("error") + assert error["id"] == 9 + assert "heavy" in error["message"] and "too large" in error["message"] + assert talk.of_type("run_finished")[0]["id"] == 10 + + +def test_brep_export_writes_a_nonempty_file(conversation, tmp_path): + path = tmp_path / "model.brep" + talk = conversation( + {"cmd": "run", "id": 1, "script": BOX}, + {"cmd": "export", "id": 2, "keys": ["n1"], "format": "brep", "path": str(path)}, + ) + talk.serve() + assert talk.of_type("export_finished")[0]["path"] == str(path) + assert path.stat().st_size > 100 + + +def test_step_upload_sends_actual_model_bytes(conversation, monkeypatch): + captured = {} + + def fake_upload(url, data, filename): + captured.update(url=url, data=data, filename=filename) + return {"status": 202, "body": "accepted"} + + monkeypatch.setattr(network, "upload", fake_upload) + talk = conversation( + {"cmd": "run", "id": 1, "script": BOX}, + { + "cmd": "upload", + "id": 2, + "url": "https://example.test", + "file_type": "step", + "keys": ["n1"], + }, + ) + talk.serve() + assert captured["url"] == "https://example.test" + assert captured["filename"] == "model.step" + assert len(captured["data"]) > 100 + assert b"ISO-10303-21" in captured["data"] + assert talk.of_type("upload_finished")[0]["status"] == 202 + + +def test_console_selected_returns_the_picked_entities_and_objects(conversation): + script = "box = cq.Workplane().box(2, 4, 6)\nshow_object(box)\n" + top = {"key": "n1", "part": 0, "kind": "face", "identifier": 6} + talk = conversation( + {"cmd": "run", "id": 1, "script": script}, + { + "cmd": "console", + "id": 2, + "source": "print(type(selected()[0]).__name__, selected()[0].Area())", + "selection": {"entities": [top], "objects": ["n1"]}, + }, + { + "cmd": "console", + "id": 3, + "source": "print(type(selected()[0]).__name__, selected()[0].Volume())", + "selection": {"entities": [], "objects": ["n1"]}, + }, + {"cmd": "console", "id": 4, "source": "print(selected())"}, + {"cmd": "release", "keys": ["n1"]}, + { + "cmd": "console", + "id": 5, + "source": "selected()", + "selection": {"objects": ["n1"]}, + }, + {"cmd": "console", "id": 6, "source": "x = 1", "selection": {"objects": [7]}}, + ) + talk.serve() + + assert talk.output(2) == "Face 8.0\n" + assert talk.output(3) == "Solid 48.0\n" + assert talk.output(4) == "[]\n" + assert "LookupError" in talk.output(5) and "render again" in talk.output(5) + (error,) = talk.of_type("error") + assert error["id"] == 6 and "scene keys" in error["message"] + + +def test_measurement_code_uses_the_scripts_variables(conversation): + script = "box = cq.Workplane().box(2, 4, 6)\nshow_object(box)\n" + talk = conversation( + {"cmd": "run", "id": 1, "script": script}, + {"cmd": "measure", "id": 2, "selections": [], "objects": ["n1"]}, + { + "cmd": "measurement_code", + "id": 3, + "selections": [{"key": "n1", "part": 0, "kind": "face", "identifier": 6}], + }, + ) + talk.serve() + + (measured,) = talk.of_type("measurement") + assert measured["objects"][0]["volume"] == 48 + (code,) = talk.of_type("measurement_code") + assert code["id"] == 3 and code["verified"] and code["problem"] is None + assert 'face_1 = box.faces(">Z").val()' in code["code"] + + +def test_measurement_code_waits_for_the_end_of_a_debugging_session(conversation): + talk = conversation( + { + "cmd": "run", + "id": 1, + "script": "box = cq.Workplane().box(1, 1, 1)\nx = 1\n", + "debug": True, + "breakpoints": [2], + }, + { + "cmd": "measurement_code", + "id": 2, + "selections": [{"key": "n1", "part": 0, "kind": "face", "identifier": 1}], + }, + {"cmd": "debug", "action": "continue"}, + ) + talk.serve() + (error,) = talk.of_type("error") + assert error["id"] == 2 and "debugging" in error["message"] + + +def test_update_checks_can_cover_cq_editor_and_skip_cadquery(conversation, monkeypatch): + monkeypatch.setattr(network, "newer_releases", lambda _current: ["v99.0.0"]) + found = [{"tag": "v0.9.0", "name": "0.9", "url": "https://github.com/x"}] + monkeypatch.setattr(network, "editor_releases", lambda current: found) + talk = conversation( + {"cmd": "check_updates", "id": 1, "editor": "0.8.0"}, + {"cmd": "check_updates", "id": 2, "editor": "0.8.0", "cadquery": False}, + ) + talk.serve() + both, editor_only = talk.of_type("updates") + assert both["newer"] == ["v99.0.0"] + assert both["editor"] == {"current": "0.8.0", "newer": found} + # The daily check of CQ-editor leaves CadQuery's releases alone. + assert editor_only["newer"] == [] and editor_only["editor"]["newer"] == found diff --git a/tests/worker/protocol/test_worker_process.py b/tests/worker/protocol/test_worker_process.py new file mode 100644 index 000000000..4e5e6df7e --- /dev/null +++ b/tests/worker/protocol/test_worker_process.py @@ -0,0 +1,212 @@ +"""The Python worker's real stdin/stdout process boundary.""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import threading +import time + +from cq_worker.protocol import OUTPUT_CAPTURE_CHARS + +PROJECT_ROOT = Path(__file__).resolve().parents[3] + + +def run_worker(*requests, env=None): + environment = os.environ.copy() + environment["PYTHONPATH"] = str(PROJECT_ROOT / "worker") + environment.update(env or {}) + payload = "".join(json.dumps(request) + "\n" for request in requests) + process = subprocess.run( + [sys.executable, "-m", "cq_worker"], + input=payload, + text=True, + encoding="utf-8", + capture_output=True, + cwd=PROJECT_ROOT, + env=environment, + timeout=30, + check=False, + ) + messages = [json.loads(line) for line in process.stdout.splitlines()] + return process, messages + + +def test_worker_process_keeps_native_stdout_out_of_protocol(): + process, messages = run_worker( + { + "cmd": "run", + "id": 12, + "script": "import os\nos.write(1, b'native warning\\n')\nprint('captured')\nresult = cq.Workplane().box(1, 1, 1)\nshow_object(result)", + }, + {"cmd": "shutdown"}, + ) + assert process.returncode == 0 + assert "native warning" in process.stderr + assert messages[0]["type"] == "ready" + assert any( + message.get("type") == "output" + and message.get("id") == 12 + and message.get("text") == "captured\n" + for message in messages + ) + (finished,) = [m for m in messages if m["type"] == "run_finished"] + assert finished["ok"] + assert [obj["name"] for obj in finished["objects"]] == ["result"] + + +def test_worker_process_bounds_output_without_a_newline(): + process, messages = run_worker( + { + "cmd": "run", + "id": 13, + "script": "import sys\nsys.stdout.write('x' * (2 * 1024 * 1024))", + }, + {"cmd": "shutdown"}, + ) + + output = [ + message["text"] + for message in messages + if message.get("type") == "output" and message.get("id") == 13 + ] + assert process.returncode == 0 + assert sum(part.count("x") for part in output) == OUTPUT_CAPTURE_CHARS + assert sum("output truncated" in part for part in output) == 1 + assert any(message.get("type") == "run_finished" for message in messages) + + +def test_worker_namespaces_scene_keys_with_the_gui_session(): + process, messages = run_worker( + {"cmd": "run", "id": 1, "script": "show_object(cq.Workplane().box(1, 1, 1))"}, + {"cmd": "shutdown"}, + env={"CQ_EDITOR_SESSION": "7"}, + ) + assert process.returncode == 0 + (finished,) = [m for m in messages if m["type"] == "run_finished"] + assert [obj["key"] for obj in finished["objects"]] == ["s7-n1"] + + +def test_worker_can_be_restarted_after_a_native_process_exit(): + crashed, messages = run_worker( + {"cmd": "run", "id": 1, "script": "import os; os._exit(7)"} + ) + assert crashed.returncode == 7 + assert messages[0]["type"] == "ready" + + restarted, messages = run_worker( + {"cmd": "run", "id": 2, "script": "value = 42"}, + {"cmd": "shutdown"}, + ) + assert restarted.returncode == 0 + (finished,) = [m for m in messages if m["type"] == "run_finished"] + assert finished["id"] == 2 and finished["ok"] + + +def test_a_running_worker_stops_meshing_when_cancelled(): + """The cancellation arrives while the worker is busy meshing: its reader + thread sees it, and meshing stops at the next shape.""" + + environment = os.environ.copy() + environment["PYTHONPATH"] = str(PROJECT_ROOT / "worker") + process = subprocess.Popen( + [sys.executable, "-m", "cq_worker"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + cwd=PROJECT_ROOT, + env=environment, + ) + script = ( + "for i in range(400):\n" + " show_object(cq.Workplane().sphere(1 + i / 100).translate((3 * i, 0, 0)))\n" + ) + + def send(request): + process.stdin.write(json.dumps(request) + "\n") + process.stdin.flush() + + try: + send({"cmd": "run", "id": 1, "script": script}) + progress = [] + finished = None + for line in process.stdout: + message = json.loads(line) + if message["type"] == "progress": + progress.append(message) + if len(progress) == 2: + send({"cmd": "cancel", "target": 1}) + elif message["type"] == "run_finished": + finished = message + break + send({"cmd": "shutdown"}) + assert process.wait(timeout=30) == 0 + finally: + if process.poll() is None: + process.kill() + + assert finished is not None and finished["cancelled"] is True + assert finished["objects"] is None + assert progress[0]["total"] == 400 + assert progress[-1]["done"] < 400, "stopped before the end" + + +def test_stop_interrupts_a_running_worker_which_keeps_its_session(): + """Interrupts arrive while the worker is busy, in a sleep and in a pure + Python loop; the process, its console namespace and cache survive.""" + + environment = os.environ.copy() + environment["PYTHONPATH"] = str(PROJECT_ROOT / "worker") + process = subprocess.Popen( + [sys.executable, "-m", "cq_worker"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + cwd=PROJECT_ROOT, + env=environment, + ) + + def send(request): + process.stdin.write(json.dumps(request) + "\n") + process.stdin.flush() + + def until(kind, request_id): + for line in process.stdout: + message = json.loads(line) + if message.get("type") == kind and message.get("id") == request_id: + return message + if message.get("type") == "output" and message.get("id") == request_id: + outputs.append(message["text"]) + raise AssertionError(f"no {kind} for {request_id}") + + outputs = [] + timer = threading.Timer(60, process.kill) + timer.start() + try: + send({"cmd": "run", "id": 1, "script": "answer = 41 + 1"}) + assert until("run_finished", 1)["ok"] + for request_id, script in [ + (2, "import time\ntime.sleep(120)"), + (3, "while True:\n pass"), + ]: + send({"cmd": "run", "id": request_id, "script": script}) + time.sleep(1.0) + started = time.monotonic() + send({"cmd": "interrupt", "target": request_id}) + finished = until("run_finished", request_id) + assert finished["interrupted"] is True, script + assert time.monotonic() - started < 10 + send({"cmd": "console", "id": 4, "source": "print(answer)"}) + until("console_result", 4) + assert outputs == ["42\n"] + send({"cmd": "shutdown"}) + assert process.wait(timeout=30) == 0 + finally: + timer.cancel() + if process.poll() is None: + process.kill() diff --git a/tests/worker/test_cli.py b/tests/worker/test_cli.py new file mode 100644 index 000000000..0ddaccb92 --- /dev/null +++ b/tests/worker/test_cli.py @@ -0,0 +1,152 @@ +"""The terminal entry point uses the same run, check and export handlers.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + +import cadquery as cq + +from cq_worker.cli import main + +WORKER_DIR = Path(__file__).resolve().parents[2] / "worker" + + +def invoke(*args: str) -> subprocess.CompletedProcess[str]: + env = os.environ.copy() + env["PYTHONPATH"] = str(WORKER_DIR) + return subprocess.run( + [sys.executable, "-m", "cq_worker.cli", *args], + text=True, + capture_output=True, + env=env, + timeout=45, + check=False, + ) + + +def test_build_overrides_parameter_and_exports_readable_step(tmp_path): + script = tmp_path / "part.py" + script.write_text( + "width = 2\npart = cq.Workplane().box(width, 3, 4)\nshow_object(part)\n", + encoding="utf-8", + ) + output = tmp_path / "part.step" + result = invoke( + "build", str(script), "--export", str(output), "--set", "width=7", "--json" + ) + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout)["ok"] is True + assert cq.importers.importStep(str(output)).val().BoundingBox().xlen == 7 + checked = invoke("check", str(script), "--set", "width=7", "--json") + assert checked.returncode == 0 + assert json.loads(checked.stdout)["reports"][0]["valid"] is True + + +def test_check_reports_invalid_geometry_as_json_and_failure(tmp_path): + script = tmp_path / "open.py" + script.write_text( + "box = cq.Workplane().box(1, 1, 1).val()\n" + "show_object(cq.Shell.makeShell(box.Faces()[:-1]), name='open')\n", + encoding="utf-8", + ) + result = invoke("check", str(script), "--json") + assert result.returncode == 1 + payload = json.loads(result.stdout) + assert payload["reports"][0]["name"] == "open" + assert payload["reports"][0]["open_shells"] == 1 + assert payload["ok"] is False + output = tmp_path / "open.step" + built = invoke("build", str(script), "--export", str(output), "--json") + assert built.returncode == 1 + assert not output.exists() + + +def test_check_rejects_overlapping_solids_and_names_the_pair(tmp_path): + script = tmp_path / "joint.py" + script.write_text( + "plate = cq.Workplane().box(20,20,5).faces('>Z').workplane().hole(5)\n" + "pin = cq.Workplane().circle(3).extrude(10).translate((0,0,-5))\n" + "show_object(cq.Assembly().add(plate,name='plate').add(pin,name='pin'))\n", + encoding="utf-8", + ) + checked = invoke("check", str(script), "--json") + assert checked.returncode == 1, checked.stderr + payload = json.loads(checked.stdout) + assert payload["assessment"]["status"] == "interference" + (pair,) = payload["interferences"] + assert pair["kind"] == "interference" + assert {pair["first"]["name"], pair["second"]["name"]} == {"plate", "pin"} + assert pair["overlap_volume"] > 40 + output = tmp_path / "joint.step" + blocked = invoke("build", str(script), "--export", str(output), "--json") + assert blocked.returncode == 1 + assert not output.exists() + assert json.loads(blocked.stdout)["interferences"][0]["kind"] == "interference" + allowed = invoke( + "build", str(script), "--export", str(output), "--allow-interference", "--json" + ) + assert allowed.returncode == 0, allowed.stderr + assert output.stat().st_size > 100 + script.write_text( + script.read_text(encoding="utf-8") + + "allow_interference('plate', 'pin', reason='specified press fit')\n", + encoding="utf-8", + ) + declared = invoke("check", str(script), "--json") + assert declared.returncode == 0, declared.stderr + assessed = json.loads(declared.stdout) + assert assessed["assessment"]["accepted"] == 1 + assert assessed["interferences"][0]["allowance_reason"] == "specified press fit" + declared_output = tmp_path / "declared.step" + exported = invoke("build", str(script), "--export", str(declared_output), "--json") + assert exported.returncode == 0, exported.stderr + assert declared_output.stat().st_size > 100 + + +def test_check_preserves_script_traceback_and_parameter_errors(tmp_path): + script = tmp_path / "part.py" + script.write_text( + "width = 2\nraise RuntimeError('broken model')\n", encoding="utf-8" + ) + failed = invoke("check", str(script), "--json") + assert failed.returncode == 1 + assert "RuntimeError: broken model" in json.loads(failed.stdout)["traceback"] + + unknown = invoke("check", str(script), "--set", "missing=3", "--json") + assert unknown.returncode == 1 + assert "missing" in json.loads(unknown.stdout)["error"] + + +def test_cli_dispatch_and_reports_in_the_test_process(tmp_path, capsys): + # Process tests above protect the entry point; this exercises the actual + # command handlers under branch coverage in the same Python process. + script = tmp_path / "part.py" + script.write_text( + "width = 2\nshow_object(cq.Workplane().box(width, 3, 4))\n", + encoding="utf-8", + ) + output = tmp_path / "part.brep" + assert ( + main( + [ + "build", + str(script), + "--export", + str(output), + "--set", + "width=5", + "--json", + ] + ) + == 0 + ) + assert json.loads(capsys.readouterr().out)["ok"] is True + assert abs(cq.importers.importBrep(str(output)).val().BoundingBox().xlen - 5) < 1e-5 + + assert main(["check", str(script)]) == 0 + assert "valid" in capsys.readouterr().out + + assert main(["check", str(script), "--set", "missing=1", "--json"]) == 1 + assert "missing" in json.loads(capsys.readouterr().out)["error"] diff --git a/tests/worker/test_compatibility.py b/tests/worker/test_compatibility.py new file mode 100644 index 000000000..dd534926b --- /dev/null +++ b/tests/worker/test_compatibility.py @@ -0,0 +1,53 @@ +"""Compatibility contract for the supported CadQuery/OCP families.""" + +import os +import re +import sys + +import cadquery as cq + +from cq_worker.environment import runtime_environment +from cq_worker.tessellation import Tolerance, TopologyIndex, tessellate + + +def _release(version: str) -> tuple[int, ...]: + return tuple(int(part) for part in re.findall(r"\d+", version)) + + +def test_runtime_is_inside_the_supported_version_families(): + environment = runtime_environment() + + assert (3, 10) <= sys.version_info[:2] < (3, 15) + assert (2, 7) <= _release(environment["cadquery"]) < (2, 10) + assert (7, 8, 1) <= _release(environment["ocp"]) < (8, 1) + + expected_cadquery = os.environ.get("CQ_EDITOR_EXPECT_CADQUERY") + expected_ocp = os.environ.get("CQ_EDITOR_EXPECT_OCP") + if expected_cadquery: + assert environment["cadquery"].startswith(expected_cadquery) + if expected_ocp: + assert environment["ocp"].startswith(expected_ocp) + + +def test_ocp_version_is_known_without_pip_metadata(monkeypatch): + """Conda installs OCP without pip metadata; the bindings know their version.""" + + import OCP + + from cq_worker import environment + + monkeypatch.setattr(environment, "distribution_version", lambda name: "unknown") + assert environment.ocp_version() == OCP.__version__ + + +def test_direct_ocp_calls_work_for_a_real_shape(): + """Exercise the generated APIs that differ between OCP 7 and OCP 8.""" + + shape = cq.Workplane().box(3, 4, 5).val().wrapped + topology = TopologyIndex.build(shape) + mesh = tessellate(shape, Tolerance(), topology) + + assert mesh is not None + assert len(topology.faces) == 6 + assert len(mesh.triangle_faces) == len(mesh.indices) // 3 + assert set(mesh.triangle_faces) == set(range(1, 7)) diff --git a/tests/worker/test_python_support.py b/tests/worker/test_python_support.py new file mode 100644 index 000000000..e0c7f0a9d --- /dev/null +++ b/tests/worker/test_python_support.py @@ -0,0 +1,16 @@ +from pathlib import Path +import tomllib + +from cq_worker.__main__ import supported_python + + +def test_worker_python_window_matches_package_metadata(): + metadata = tomllib.loads( + (Path(__file__).resolve().parents[2] / "worker" / "pyproject.toml").read_text( + encoding="utf-8" + ) + ) + assert metadata["project"]["requires-python"] == ">=3.11,<3.15" + assert not supported_python((3, 10)) + assert all(supported_python((3, minor)) for minor in range(11, 15)) + assert not supported_python((3, 15)) diff --git a/worker/README.md b/worker/README.md new file mode 100644 index 000000000..f439aa92e --- /dev/null +++ b/worker/README.md @@ -0,0 +1,12 @@ +# cq_worker + +The CadQuery execution backend of [CQ-editor](https://github.com/igors93/CQ-editor). +The editor starts it as `python -m cq_worker` and talks to it over +stdin/stdout, one JSON object per line. The package is embedded in the +CQ-editor executable, so users never install it themselves. + +Documentation lives in the repository's `docs/` folder: + +* [Architecture](../docs/development/architecture.md#python-side-workercq_worker): what each module does +* [Worker protocol](../docs/development/protocol.md): requests and messages +* [Testing](../docs/development/testing.md): running `pytest tests/worker` diff --git a/worker/cq_worker/__init__.py b/worker/cq_worker/__init__.py new file mode 100644 index 000000000..1179e9405 --- /dev/null +++ b/worker/cq_worker/__init__.py @@ -0,0 +1,8 @@ +"""CadQuery execution backend of CQ-editor. + +The GUI starts ``python -m cq_worker`` and exchanges JSON messages with it +(see :mod:`cq_worker.protocol`). Keeping CadQuery in its own process means a +crashing or endless script never takes the editor down with it. +""" + +__version__ = "0.9.0" diff --git a/worker/cq_worker/__main__.py b/worker/cq_worker/__main__.py new file mode 100644 index 000000000..d6388f740 --- /dev/null +++ b/worker/cq_worker/__main__.py @@ -0,0 +1,61 @@ +"""Entry point: ``python -m cq_worker``.""" + +import logging +import os +import signal +import sys +import traceback + +from .protocol import Channel, redirect_std_streams + + +def supported_python(version: tuple[int, int]) -> bool: + return (3, 11) <= version < (3, 15) + + +def main() -> int: + # Stop interrupts scripts like Ctrl+C would (``_thread.interrupt_main``), + # which does nothing if SIGINT was inherited as ignored. + signal.signal(signal.SIGINT, signal.default_int_handler) + channel = Channel.from_std_streams() + redirect_std_streams(channel) + + if not supported_python(sys.version_info[:2]): + channel.send( + { + "type": "fatal", + "message": ( + f"Python {sys.version_info.major}.{sys.version_info.minor} is unsupported; " + "use Python 3.11–3.14 with matching CadQuery and OCP packages" + ), + "detail": "The worker package requires Python >=3.11,<3.15.", + "executable": sys.executable, + } + ) + return 1 + + # Importing CadQuery takes a few seconds; the GUI shows a "starting" + # state until the ready message arrives. + try: + # A stale CASROOT from another OpenCascade install breaks OCP. + os.environ.pop("CASROOT", None) + + from .server import ChannelLogHandler, Server + except Exception as error: + channel.send( + { + "type": "fatal", + "message": f"Cannot load CadQuery: {type(error).__name__}: {error}", + "detail": traceback.format_exc(), + "executable": sys.executable, + } + ) + return 1 + + logging.basicConfig(level=logging.INFO, handlers=[ChannelLogHandler(channel)]) + Server(channel, session=os.environ.get("CQ_EDITOR_SESSION")).serve_forever() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/worker/cq_worker/assembly_checks.py b/worker/cq_worker/assembly_checks.py new file mode 100644 index 000000000..99971b121 --- /dev/null +++ b/worker/cq_worker/assembly_checks.py @@ -0,0 +1,128 @@ +"""Conservative diagnostics for CadQuery assembly constraints and fit.""" + +from __future__ import annotations + +import math +from typing import Any + +import cadquery as cq + +from .checking import check_registry, invalid_reports +from .interference import analyze_interferences +from .scene import Registry, SceneBuilder, ShownObject +from .tessellation import Tolerance + +# Upper bounds on independent scalar equations each constraint can impose. +# Their sum gives a *lower* bound on free degrees of freedom: redundancy can +# only make the real assembly less constrained than the reported bound. +_MAX_RANK = { + "Fixed": 6, + "FixedPoint": 3, + "FixedAxis": 2, + "FixedRotation": 3, + "FixedRotationAxis": 1, + "Point": 3, + "Axis": 2, + "Plane": 5, + "PointInPlane": 1, + "PointOnLine": 2, +} +_UNARY = {"Fixed", "FixedPoint", "FixedAxis", "FixedRotation", "FixedRotationAxis"} + + +class AssemblyError(ValueError): + """A strict constraint and interference requirement is not satisfied.""" + + +def assembly_diagnostics(assembly: cq.Assembly) -> dict[str, Any]: + """Describe constraints without moving a part or silently solving it. + + ``minimum_free_dof`` is conservative for a flat assembly. A value above + zero proves underconstraint; zero does not prove that every direction is + constrained, because constraints may be redundant or dependent. + """ + + if not isinstance(assembly, cq.Assembly): + raise TypeError("assembly_diagnostics expects a CadQuery Assembly") + components = { + name: node for name, node in assembly.objects.items() if node.obj is not None + } + constraints: list[dict[str, Any]] = [ + {"kind": str(spec.kind), "objects": list(spec.objects)} + for spec in assembly.constraints + ] + referenced = {name for spec in assembly.constraints for name in spec.objects} + unconstrained = sorted(name for name in components if name not in referenced) + nested = any(node.children for node in assembly.children) + unknown_kinds = sorted({row["kind"] for row in constraints} - _MAX_RANK.keys()) + minimum_free_dof: int | None = None + if not nested and not unknown_kinds: + total = 6 * len(components) + rank_ceiling = sum(_MAX_RANK[row["kind"]] for row in constraints) + # Without a unary ground constraint, one rigid global placement is a + # gauge freedom and does not make the relative assembly underconstrained. + global_gauge = 0 if any(row["kind"] in _UNARY for row in constraints) else 6 + minimum_free_dof = max(0, total - rank_ceiling - global_gauge) + + solved = getattr(assembly, "_solve_result", None) + solver_success: bool | None = None + residual: float | None = None + if isinstance(solved, dict): + solver_success = bool(solved.get("success", False)) + values = solved.get("iterations", {}).get("obj", []) + if values: + candidate = float(values[-1]) + if math.isfinite(candidate): + residual = candidate + + registry = Registry() + nodes = SceneBuilder(registry, Tolerance()).build( + {"assembly": ShownObject(assembly)} + ) + if nodes: + keys = [node["key"] for node in nodes] + topology_issues = invalid_reports(check_registry(registry, keys)) + pairs = analyze_interferences(registry, keys) + else: + topology_issues = [ + {"name": assembly.name, "issues": ["Could not inspect assembly"]} + ] + pairs = [] + + issues = [] + if topology_issues: + issues.append("invalid_geometry") + if any(pair["kind"] == "interference" for pair in pairs): + issues.append("interference") + if any(pair["kind"] == "inconclusive" for pair in pairs): + issues.append("inconclusive_geometry") + if constraints and solver_success is not True: + issues.append("constraints_not_solved") + if residual is not None and residual > 1e-8: + issues.append("constraint_residual") + if minimum_free_dof is not None and minimum_free_dof > 0: + issues.append("underconstrained") + if nested or unknown_kinds: + issues.append("dof_inconclusive") + + return { + "ok": not issues, + "components": sorted(components), + "constraints": constraints, + "unconstrained_components": unconstrained, + "minimum_free_dof": minimum_free_dof, + "solver_success": solver_success, + "solver_residual": residual, + "topology_issues": topology_issues, + "interferences": pairs, + "issues": issues, + } + + +def require_constrained_assembly(assembly: cq.Assembly) -> dict[str, Any]: + """Fail a script when a constrained assembly cannot be certified.""" + + report = assembly_diagnostics(assembly) + if not report["ok"]: + raise AssemblyError(f"Assembly needs review: {', '.join(report['issues'])}") + return report diff --git a/worker/cq_worker/cad_checks.py b/worker/cq_worker/cad_checks.py new file mode 100644 index 000000000..3bd6a4da9 --- /dev/null +++ b/worker/cq_worker/cad_checks.py @@ -0,0 +1,173 @@ +"""Assertions about a model, recorded during a script run for the GUI and CI. + +All distances and volumes use the script's model units. A failed assertion is +recorded rather than raised, so one run can report every unmet requirement. +Invalid assertion arguments still raise immediately as programming errors. +""" + +from __future__ import annotations + +import math +from typing import Any + +import cadquery as cq +from OCP.BRepExtrema import BRepExtrema_DistShapeShape + +from .checking import check_shape +from .scene import to_compound + + +def _finite(value: float, label: str) -> float: + number = float(value) + if not math.isfinite(number): + raise ValueError(f"{label} must be finite") + return number + + +def _range(bounds: tuple[float, float], label: str) -> tuple[float, float]: + if not isinstance(bounds, (tuple, list)) or len(bounds) != 2: + raise ValueError(f"{label} needs a (minimum, maximum) pair") + low, high = _finite(bounds[0], label), _finite(bounds[1], label) + if low > high: + raise ValueError(f"{label} minimum exceeds maximum") + return low, high + + +class CheckSuite: + def __init__(self) -> None: + self.results: list[dict[str, Any]] = [] + + def expect( + self, + obj: cq.Shape | cq.Workplane | cq.Sketch, + name: str | None, + line: int | None, + ) -> Expectation: + if name is not None and (not isinstance(name, str) or not name.strip()): + raise ValueError("Check name must be nonempty text") + if not isinstance(obj, (cq.Shape, cq.Workplane, cq.Sketch)): + raise TypeError("expect() needs a CadQuery shape, workplane or sketch") + return Expectation(self, obj, name or f"Check {len(self.results) + 1}", line) + + @property + def ok(self) -> bool: + return all(result["ok"] for result in self.results) + + +class Expectation: + def __init__( + self, + suite: CheckSuite, + obj: cq.Shape | cq.Workplane | cq.Sketch, + name: str, + line: int | None, + ) -> None: + self.suite = suite + self.obj = obj + self.name = name + self.line = line + + def _record(self, kind: str, ok: bool, detail: str) -> Expectation: + self.suite.results.append( + { + "name": self.name, + "kind": kind, + "ok": bool(ok), + "detail": detail, + "line": self.line, + } + ) + return self + + def _shape(self) -> cq.Compound: + shape = to_compound(self.obj) + if not shape.Solids() and not shape.Faces() and not shape.Edges(): + raise ValueError("The checked object has no geometry") + return shape + + def is_valid(self) -> Expectation: + try: + report = check_shape(self._shape()) + detail = ( + "Valid topology" if report["valid"] else "; ".join(report["issues"]) + ) + return self._record("validity", report["valid"], detail) + except Exception as error: + return self._record("validity", False, f"Could not check topology: {error}") + + def volume_between(self, minimum: float, maximum: float) -> Expectation: + low, high = _range((minimum, maximum), "Volume") + try: + shape = self._shape() + if not shape.Solids(): + raise ValueError("Volume needs at least one solid") + actual = _finite(shape.Volume(), "Measured volume") + return self._record( + "volume", + low <= actual <= high, + f"Volume {actual:g}; expected [{low:g}, {high:g}] model units³", + ) + except Exception as error: + return self._record("volume", False, f"Could not measure volume: {error}") + + def dimensions_within( + self, + *, + x: tuple[float, float] | None = None, + y: tuple[float, float] | None = None, + z: tuple[float, float] | None = None, + ) -> Expectation: + bounds = { + axis: _range(value, axis) + for axis, value in (("x", x), ("y", y), ("z", z)) + if value is not None + } + if not bounds: + raise ValueError("Specify at least one dimension range") + try: + box = self._shape().BoundingBox() + actual = {"x": box.xlen, "y": box.ylen, "z": box.zlen} + detail = "; ".join( + f"{axis.upper()} {actual[axis]:g}; expected [{low:g}, {high:g}] model units" + for axis, (low, high) in bounds.items() + ) + return self._record( + "dimensions", + all( + low <= actual[axis] <= high for axis, (low, high) in bounds.items() + ), + detail, + ) + except Exception as error: + return self._record( + "dimensions", False, f"Could not measure dimensions: {error}" + ) + + def clearance_at_least( + self, other: cq.Shape | cq.Workplane | cq.Sketch, minimum: float + ) -> Expectation: + limit = _finite(minimum, "Clearance") + if limit < 0: + raise ValueError("Clearance cannot be negative") + if not isinstance(other, (cq.Shape, cq.Workplane, cq.Sketch)): + raise TypeError( + "Clearance needs another CadQuery shape, workplane or sketch" + ) + try: + first = self._shape() + second = to_compound(other) + if not second.Solids() and not second.Faces() and not second.Edges(): + raise ValueError("The other object has no geometry") + operation = BRepExtrema_DistShapeShape(first.wrapped, second.wrapped) + if not operation.IsDone() or operation.NbSolution() < 1: + raise ValueError("OpenCascade could not calculate the distance") + actual = _finite(operation.Value(), "Measured clearance") + return self._record( + "clearance", + actual >= limit, + f"Clearance {actual:g}; required at least {limit:g} model units", + ) + except Exception as error: + return self._record( + "clearance", False, f"Could not measure clearance: {error}" + ) diff --git a/worker/cq_worker/checking.py b/worker/cq_worker/checking.py new file mode 100644 index 000000000..a9f3dbb49 --- /dev/null +++ b/worker/cq_worker/checking.py @@ -0,0 +1,91 @@ +"""Geometry checks shared by interactive inspection, export and headless CI.""" + +from __future__ import annotations + +from typing import Any + +import cadquery as cq + +from .scene import Registry, RegistryEntry + + +class GeometryInvalid(Exception): + def __init__( + self, + reports: list[dict[str, Any]], + interferences: list[dict[str, Any]] | None = None, + ) -> None: + self.reports = reports + self.interferences = interferences or [] + names = ", ".join(report["name"] for report in reports) + super().__init__( + f"Geometry needs review before export: {names}" + if names + else "Assembly interference needs review before export" + ) + + +def check_shape(shape: cq.Shape) -> dict[str, Any]: + """Inspect the exact world-space shape that would leave the editor.""" + valid = shape.isValid() + solids = shape.Solids() + shells = shape.Shells() + open_shells = sum(not shell.Closed() for shell in shells) + non_manifold = 0 + # Count each edge within its solid or free shell. Counting over a whole + # compound would incorrectly flag two separately valid touching solids. + checked = solids or shells + for body in checked: + counts: dict[int, int] = {} + for face in body.Faces(): + for edge in face.Edges(): + identifier = edge.hashCode() + counts[identifier] = counts.get(identifier, 0) + 1 + non_manifold += sum(count > 2 for count in counts.values()) + issues: list[str] = [] + if not valid: + issues.append("OpenCascade reports invalid topology") + if open_shells: + issues.append(f"{open_shells} open shell(s)") + if non_manifold: + issues.append(f"{non_manifold} non-manifold edge(s)") + return { + "valid": valid and not open_shells and not non_manifold, + "solids": len(solids), + "open_shells": open_shells, + "non_manifold_edges": non_manifold, + "issues": issues, + } + + +def check_registry( + registry: Registry, keys: list[str], flat_parts: bool = False +) -> list[dict[str, Any]]: + """Report every exported part once, including descendants of selections.""" + reports: list[dict[str, Any]] = [] + seen: set[str] = set() + + def visit(key: str) -> None: + if key in seen: + return + seen.add(key) + entry: RegistryEntry = registry.get(key) + if entry.shape is not None: + reports.append( + { + "key": key, + "name": entry.name or key, + **check_shape(entry.shape), + } + ) + if not flat_parts: + for child in entry.children: + visit(child) + + for key in keys: + visit(key) + return reports + + +def invalid_reports(reports: list[dict[str, Any]]) -> list[dict[str, Any]]: + return [report for report in reports if not report["valid"]] diff --git a/worker/cq_worker/cli.py b/worker/cq_worker/cli.py new file mode 100644 index 000000000..14710b794 --- /dev/null +++ b/worker/cq_worker/cli.py @@ -0,0 +1,327 @@ +"""Headless build and geometry check through the same worker handlers as the GUI.""" + +from __future__ import annotations + +import argparse +import ast +from contextlib import contextmanager, redirect_stdout +import json +import math +import os +from pathlib import Path +import sys +from typing import Iterator, cast + +from .protocol import Channel + + +def replace_parameters(source: str, assignments: list[str]) -> str: + """Replace top-level literal parameters without moving traceback lines.""" + overrides: dict[str, str] = {} + for assignment in assignments: + parameter_name, separator, parameter_value = assignment.partition("=") + if ( + not separator + or not parameter_name.isidentifier() + or parameter_name.startswith("__") + ): + raise ValueError( + f"Invalid parameter assignment {assignment!r}; use name=value" + ) + try: + literal = ast.literal_eval(parameter_value) + except (SyntaxError, ValueError) as error: + raise ValueError( + f"Parameter {parameter_name} needs a Python literal" + ) from error + if type(literal) not in (int, float, bool, str) or ( + isinstance(literal, float) and not math.isfinite(literal) + ): + raise ValueError( + f"Parameter {parameter_name} needs a finite scalar literal" + ) + overrides[parameter_name] = repr(literal) + + if not overrides: + return source + tree = ast.parse(source) + replacements: list[tuple[int, int, str]] = [] + matched: set[str] = set() + lines = source.splitlines(keepends=True) + byte_offsets = [0] + for line in lines: + byte_offsets.append(byte_offsets[-1] + len(line.encode("utf-8"))) + for node in tree.body: + name: str | None = None + value: ast.expr | None = None + if ( + isinstance(node, ast.Assign) + and len(node.targets) == 1 + and isinstance(node.targets[0], ast.Name) + ): + name, value = node.targets[0].id, node.value + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + name, value = node.target.id, node.value + if name not in overrides or value is None: + continue + try: + ast.literal_eval(value) + except (SyntaxError, ValueError): + continue + assert value.end_lineno is not None and value.end_col_offset is not None + start = byte_offsets[value.lineno - 1] + value.col_offset + end = byte_offsets[value.end_lineno - 1] + value.end_col_offset + replacements.append((start, end, overrides[name])) + matched.add(name) + + if matched != set(overrides): + missing = sorted(set(overrides) - matched) + raise ValueError(f"Unknown or non-literal parameter: {', '.join(missing)}") + encoded = source.encode("utf-8") + for start, end, replacement in reversed(replacements): + encoded = encoded[:start] + replacement.encode("utf-8") + encoded[end:] + return encoded.decode("utf-8") + + +class CliChannel: + """Only terminal replies are retained; mesh parts never accumulate.""" + + def __init__(self) -> None: + self.current_id: int | None = None + self.replies: list[dict] = [] + + def send(self, message: dict) -> None: + kind = message.get("type") + if kind in ( + "error", + "run_finished", + "geometry_checked", + "geometry_invalid", + "export_finished", + ): + self.replies.append(message) + elif kind == "log": + print(f"{message['source']}: {message['message']}", file=sys.stderr) + + @contextmanager + def interruptible(self, _request_id: int) -> Iterator[None]: + yield + + def cancel_requested(self, _request_id: int) -> bool: + return False + + def forget_cancel(self, _request_id: int) -> None: + pass + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="cq-editor") + commands = parser.add_subparsers(dest="command", required=True) + for command in ("build", "check"): + sub = commands.add_parser(command) + sub.add_argument("script", type=Path) + sub.add_argument( + "--set", + dest="parameters", + action="append", + default=[], + metavar="NAME=VALUE", + ) + sub.add_argument("--json", action="store_true", help="Print the result as JSON") + if command == "check": + sub.add_argument( + "--clearance", + type=float, + default=0.0, + metavar="MODEL_UNITS", + help="Also report pairs with less than this clearance", + ) + if command == "build": + sub.add_argument("--export", required=True, type=Path) + sub.add_argument( + "--allow-interference", + action="store_true", + help="Export despite interference or an inconclusive pair", + ) + sub.add_argument( + "--unit", + choices=("millimeter", "centimeter", "meter", "inch"), + default="millimeter", + ) + return parser + + +def _report(args: argparse.Namespace, payload: dict, status: int) -> int: + if args.json: + print(json.dumps(payload, ensure_ascii=False, allow_nan=False)) + elif status: + for check in payload.get("checks", []): + if not check["ok"]: + print( + f"{check['name']} (line {check['line']}): {check['detail']}", + file=sys.stderr, + ) + if payload.get("reports") or payload.get("interferences"): + for item in payload["reports"]: + if not item["valid"]: + print( + f"{item['name']}: {', '.join(item['issues'])}", file=sys.stderr + ) + for pair in payload.get("interferences", []): + if pair["kind"] in ("interference", "inconclusive"): + print( + f"{pair['first']['name']} / {pair['second']['name']}: " + f"{pair['kind']} ({pair['overlap_volume']} volume units)", + file=sys.stderr, + ) + else: + print( + payload.get("traceback") or payload.get("error") or payload, + file=sys.stderr, + ) + elif args.command == "check": + for check in payload.get("checks", []): + print( + f"{check['name']}: {'passed' if check['ok'] else 'failed'} — {check['detail']}" + ) + for item in payload["reports"]: + print(f"{item['name']}: valid ({item['solids']} solids)") + for pair in payload.get("interferences", []): + print(f"{pair['first']['name']} / {pair['second']['name']}: {pair['kind']}") + else: + print(payload["path"]) + return status + + +def main(argv: list[str] | None = None) -> int: + args = _parser().parse_args(argv) + try: + os.environ.pop("CASROOT", None) + from .server import Server + + path = args.script.resolve(strict=True) + source = replace_parameters( + path.read_text(encoding="utf-8-sig"), args.parameters + ) + channel = CliChannel() + # CliChannel implements the transport methods used by Server. + server = Server(cast(Channel, channel)) + with redirect_stdout(sys.stderr): + server.dispatch( + {"cmd": "run", "id": 1, "script": source, "path": str(path)} + ) + result = channel.replies[-1] + if result["type"] == "error": + return _report(args, {"ok": False, "error": result["message"]}, 1) + if not result["ok"]: + failure = result.get("error") or {} + return _report( + args, + { + "ok": False, + "error": failure.get("message", "Script failed"), + "traceback": failure.get("text"), + "diagnostic": failure.get("diagnostic"), + "checks": result.get("checks", []), + }, + 1, + ) + keys = [node["key"] for node in result.get("objects") or []] + checks = result.get("checks", []) + if args.command == "build" and any(not check["ok"] for check in checks): + return _report( + args, + {"ok": False, "error": "CAD requirements failed", "checks": checks}, + 1, + ) + if not keys: + return _report( + args, + { + "ok": False, + "error": "Script produced no displayable objects", + "checks": checks, + }, + 1, + ) + + channel.replies.clear() + if args.command == "check": + with redirect_stdout(sys.stderr): + server.dispatch( + { + "cmd": "check", + "id": 2, + "keys": keys, + "clearance": args.clearance, + } + ) + checked = channel.replies[-1] + if checked["type"] == "error": + return _report(args, {"ok": False, "error": checked["message"]}, 1) + reports = checked["reports"] + valid = ( + bool(reports) + and all(report["valid"] for report in reports) + and checked["assessment"]["status"] == "clear" + and all(check["ok"] for check in checks) + ) + return _report( + args, + { + "ok": valid, + "reports": reports, + "interferences": checked["interferences"], + "assessment": checked["assessment"], + "checks": checks, + }, + 0 if valid else 1, + ) + + output = args.export.resolve() + file_format = output.suffix.lstrip(".").lower() + with redirect_stdout(sys.stderr): + server.dispatch( + { + "cmd": "export", + "id": 2, + "keys": keys, + "format": file_format, + "path": str(output), + "unit": args.unit, + "on_interference": "ignore" if args.allow_interference else "check", + } + ) + exported = channel.replies[-1] + if exported["type"] == "export_finished": + return _report( + args, + { + "ok": True, + "path": str(output), + "format": file_format, + "checks": checks, + }, + 0, + ) + if exported["type"] == "geometry_invalid": + return _report( + args, + { + "ok": False, + "error": "Invalid geometry", + "reports": exported["reports"], + "interferences": exported.get("interferences", []), + "checks": checks, + }, + 1, + ) + return _report(args, {"ok": False, "error": exported["message"]}, 1) + except (OSError, ValueError, SyntaxError, ImportError) as error: + return _report( + args, {"ok": False, "error": f"{type(error).__name__}: {error}"}, 1 + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/worker/cq_worker/completion.py b/worker/cq_worker/completion.py new file mode 100644 index 000000000..2ecfc44da --- /dev/null +++ b/worker/cq_worker/completion.py @@ -0,0 +1,108 @@ +"""Code completion, call signatures and documentation, powered by jedi when +installed.""" + +from __future__ import annotations + +from typing import Any + +try: + import jedi +except ImportError: # completion is optional + jedi = None + +MAX_COMPLETIONS = 200 +#: Documentation beyond this is cut: a tooltip is not a manual, and it must +#: fit above or below the line it describes. +MAX_DOCUMENTATION_CHARS = 1200 +MAX_DOCUMENTATION_LINES = 14 + + +def is_available() -> bool: + return jedi is not None + + +def complete( + source: str, + line: int, + column: int, + path: str | None, + namespace: dict[str, Any], +) -> dict: + """Completions at ``line`` (1-based) / ``column`` (0-based, in characters). + + Right after ``(`` or ``,`` the user is typing arguments, so call + signatures are returned instead of names. + """ + + if jedi is None: + return {"available": False, "items": [], "signatures": []} + + interpreter = jedi.Interpreter(source, [namespace], path=path) + current_line = source.split("\n")[line - 1] if source else "" + before_cursor = current_line[:column].rstrip() + + signatures = [ + signature.to_string() for signature in interpreter.get_signatures(line, column) + ] + if before_cursor.endswith(("(", ",")): + return {"available": True, "items": [], "signatures": signatures} + + items = [ + { + "name": completion.name, + "insert": completion.complete or "", + "kind": completion.type, + } + for completion in interpreter.complete(line, column)[:MAX_COMPLETIONS] + if not completion.name.startswith("__") + ] + return {"available": True, "items": items, "signatures": signatures} + + +def describe( + source: str, + line: int, + column: int, + path: str | None, + namespace: dict[str, Any], +) -> dict: + """Documentation of the name at ``line`` (1-based) / ``column`` + (0-based, in characters), for the editor's hover tooltip. + + Functions and classes give their call signatures and docstring, modules + their docstring, and variables the type of what they hold. Keywords + are left out: their help is the language reference. + """ + + empty = {"signatures": [], "text": ""} + if jedi is None: + return {"available": False, **empty} + + interpreter = jedi.Interpreter(source, [namespace], path=path) + for name in interpreter.help(line, column): + if name.type == "keyword": + continue + signatures = [ + signature.to_string().replace("", name.name, 1) + for signature in name.get_signatures() + ] + text = name.docstring(raw=True).strip() + if not signatures and not text: + types = sorted( + {inferred.name for inferred in interpreter.infer(line, column)} + - {name.name} + ) + if types: + signatures = [f"{name.name}: {' | '.join(types)}"] + if signatures or text: + return {"available": True, "signatures": signatures, "text": _cut(text)} + return {"available": True, **empty} + + +def _cut(text: str) -> str: + cut = "\n".join(text.splitlines()[:MAX_DOCUMENTATION_LINES]) + if len(cut) > MAX_DOCUMENTATION_CHARS: + cut = cut[:MAX_DOCUMENTATION_CHARS].rstrip() + if len(cut) < len(text.strip()): + cut += " …" + return cut diff --git a/worker/cq_worker/console.py b/worker/cq_worker/console.py new file mode 100644 index 000000000..dab379c3f --- /dev/null +++ b/worker/cq_worker/console.py @@ -0,0 +1,113 @@ +"""The interactive Python console behind the GUI's console panel.""" + +from __future__ import annotations + +import builtins +import code +import sys +from collections.abc import Callable +from typing import Any + +import cadquery as cq + +from .display import Displayer +from .execution import ShownObjects, rand_color, script_log + + +class ConsoleSession: + """A persistent interpreter. + + Its namespace offers the script API (``show_object`` adds objects to the + viewer), ``selected()`` for what is picked in the 3D view and, after each + run, the variables of the last script run. + """ + + def __init__(self, displayer: Displayer | None = None) -> None: + self.shown = ShownObjects() + self.namespace: dict[str, Any] = {} + #: Resolves the GUI's selection when ``selected()`` is called. + self._selection: Callable[[], list[cq.Shape]] = list + #: Sends rich results to the GUI; without it they are printed. + self._displayer = displayer + self.reset() + + def reset(self) -> None: + def selected() -> list[cq.Shape]: + """The faces, edges and vertices picked in the 3D view, in the + order they were picked, as ``cq.Face``, ``cq.Edge`` or + ``cq.Vertex`` placed as shown. When no entity is picked, the + shapes of the selected objects. An empty list when nothing is + selected.""" + + return list(self._selection()) + + self.namespace.clear() + self.namespace.update( + { + "__name__": "__console__", + "__builtins__": builtins, + "cq": cq, + "show_object": self._show_object, + "show": self._show_object, + "debug": self._debug, + "rand_color": rand_color, + "log": lambda value: script_log.info(str(value)), + "selected": selected, + "display": self._display, + } + ) + self._interpreter = code.InteractiveConsole( + self.namespace, filename="" + ) + + def set_selection(self, resolve: Callable[[], list[cq.Shape]]) -> None: + """What ``selected()`` returns from now on; resolved when called.""" + + self._selection = resolve + + def update_variables(self, variables: dict[str, Any]) -> None: + self.namespace.update( + (name, value) + for name, value in variables.items() + if not name.startswith("__") + ) + + def execute(self, source: str, request_id: int | None = None) -> bool: + """Feed ``source`` line by line; ``True`` if a statement is incomplete.""" + + more = False + previous = sys.displayhook + if self._displayer is not None: + # Expression results become rich output, images included. + self._displayer.start(request_id) + sys.displayhook = self._displayer.displayhook + try: + for line in source.split("\n"): + more = self._interpreter.push(line) + finally: + sys.displayhook = previous + if self._displayer is not None: + self._displayer.finish() + return more + + def take_shown(self) -> ShownObjects: + shown, self.shown = self.shown, ShownObjects() + return shown + + # Both wrappers put exactly one frame between the console line and + # ShownObjects, which looks two frames up for the variable name. + + def _show_object(self, obj, name=None, options=None, **kwargs) -> None: + self.shown.show(obj, name, options, **kwargs) + + def _debug(self, obj, name=None) -> None: + self.shown.debug(obj, name) + + def _display(self, *values) -> None: + """Shows each value in the console, as an image when it has one + (a matplotlib figure, a PIL image, anything with ``_repr_png_``).""" + + if self._displayer is None: + print(*values) + else: + self._displayer.display(*values) diff --git a/worker/cq_worker/debugger.py b/worker/cq_worker/debugger.py new file mode 100644 index 000000000..615b99ee8 --- /dev/null +++ b/worker/cq_worker/debugger.py @@ -0,0 +1,147 @@ +"""Line-level stepping debugger for a script and its project modules. + +Built on ``sys.settrace``: only frames executing the editor buffer or project +files are traced, so library code (CadQuery, OCP) runs at full speed. When it decides +to pause it calls back into the worker, which reports the paused state to the +GUI and blocks until the next command arrives. +""" + +from __future__ import annotations + +import enum +import os +import sys +import types +from collections.abc import Callable, Iterable, Mapping + + +class Action(enum.Enum): + CONTINUE = "continue" + STEP = "step" + STEP_IN = "step_in" + STEP_OUT = "step_out" + STOP = "stop" + + +class DebugStop(BaseException): + """Raised inside the script to end a debugging session early. + + Like ``KeyboardInterrupt``, it is not an ``Exception``: a script's own + ``except Exception`` must not swallow the user's request to stop. + """ + + +class Debugger: + """Runs code objects compiled from ``filename`` under the tracer. + + ``on_pause(frame)`` is invoked whenever execution stops at a line; it + returns the next :class:`Action` and may update :attr:`breakpoints`. + """ + + def __init__( + self, + filename: str, + breakpoints: Iterable[int], + on_pause: Callable[[types.FrameType], Action], + project_root: str | None = None, + module_breakpoints: Mapping[str, Iterable[int]] | None = None, + ) -> None: + self.filename = filename + self.project_root = ( + os.path.normcase(os.path.realpath(project_root)) if project_root else None + ) + self.breakpoints: dict[str, set[int]] = {} + self.set_breakpoints(breakpoints, module_breakpoints) + self._on_pause = on_pause + # Like the original editor, start running until the first breakpoint. + self._action = Action.CONTINUE + self._depth = 0 + self._paths: dict[str, str] = {} + self._traceable: dict[str, bool] = {} + + def set_breakpoints( + self, + main: Iterable[int], + modules: Mapping[str, Iterable[int]] | None = None, + ) -> None: + self.breakpoints = {self.filename: set(main)} + for path, lines in (modules or {}).items(): + normalized = os.path.normcase(os.path.realpath(path)) + if self._in_project(normalized): + self.breakpoints[normalized] = set(lines) + + def source_path(self, frame: types.FrameType) -> str: + path = frame.f_code.co_filename + if path not in self._paths: + self._paths[path] = ( + self.filename + if path == self.filename + else os.path.normcase(os.path.realpath(path)) + ) + return self._paths[path] + + def _in_project(self, path: str) -> bool: + if self.project_root is None: + return False + try: + if os.path.commonpath((self.project_root, path)) != self.project_root: + return False + for prefix in (sys.prefix, sys.base_prefix, sys.exec_prefix): + prefix = os.path.normcase(os.path.realpath(prefix)) + if os.path.commonpath((prefix, path)) == prefix: + return False + return "site-packages" not in path.split(os.sep) + except ValueError: + return False + + def _traced(self, frame: types.FrameType) -> bool: + path = self.source_path(frame) + if path not in self._traceable: + self._traceable[path] = path == self.filename or self._in_project(path) + return self._traceable[path] + + def run(self, code: types.CodeType, namespace: dict) -> None: + previous = sys.gettrace() + sys.settrace(self._trace_calls) + try: + exec(code, namespace) + finally: + sys.settrace(previous) + + def _trace_calls(self, frame: types.FrameType, event: str, arg): + if not self._traced(frame): + return None # don't trace library code + return self._trace_lines + + def _trace_lines(self, frame: types.FrameType, event: str, arg): + if event == "line" and self._should_pause(frame): + self._pause(frame) + return self._trace_lines + + def _should_pause(self, frame: types.FrameType) -> bool: + if frame.f_lineno in self.breakpoints.get(self.source_path(frame), ()): + return True + depth = self._script_depth(frame) + if self._action is Action.STEP_IN: + return True + if self._action is Action.STEP: + return depth <= self._depth + if self._action is Action.STEP_OUT: + return depth < self._depth + return False + + def _pause(self, frame: types.FrameType) -> None: + self._action = self._on_pause(frame) + self._depth = self._script_depth(frame) + if self._action is Action.STOP: + raise DebugStop + + def _script_depth(self, frame: types.FrameType | None) -> int: + """Number of active frames that execute the script or project files.""" + + depth = 0 + while frame is not None: + if self._traced(frame): + depth += 1 + frame = frame.f_back + return depth diff --git a/worker/cq_worker/diagnostics.py b/worker/cq_worker/diagnostics.py new file mode 100644 index 000000000..4d436e8d2 --- /dev/null +++ b/worker/cq_worker/diagnostics.py @@ -0,0 +1,145 @@ +"""Conservative explanations for common CAD kernel failures. + +The traceback remains authoritative. These are troubleshooting hints, never +claims that one geometric cause has been proven from an exception string. +""" + +from __future__ import annotations + +import ast +from typing import Any + +_HINTS = { + "fillet": ( + "Try a smaller radius; adjacent faces may leave too little room.", + "Check that the selected edges belong to the intended solid and do not meet at a problematic corner.", + "Inspect the shape before this operation for invalid or very short edges.", + ), + "chamfer": ( + "Try smaller chamfer distances relative to nearby faces and edges.", + "Check the selected edges and the validity of the solid before chamfering.", + ), + "loft": ( + "Check that each section is a usable closed wire or face and that section order is correct.", + "Look for crossing, coincident or sharply different profiles.", + ), + "sweep": ( + "Check that the path and profile are valid and that the profile follows the intended plane.", + "Look for tight turns or self-intersection along the path.", + ), + "cut": ( + "Check that both operands contain valid solids and overlap where the cut is expected.", + "Look for coincident or nearly tangent faces that may make the boolean ambiguous.", + ), + "union": ( + "Check both solids for valid topology and inspect where they touch or overlap.", + "Nearly coincident faces and very thin intersections can make the boolean unstable.", + ), + "intersect": ( + "Check that the solids actually share volume rather than only touching.", + "Inspect both operands for invalid topology or nearly coincident faces.", + ), + "shell": ( + "Try a smaller wall thickness relative to the smallest local feature.", + "Inspect highly curved areas and the faces chosen for removal.", + ), + "faces": ( + "Preview the selector on the last successful model and check its match count.", + "Check the selector direction and the workplane or shape on which it runs.", + ), + "edges": ( + "Preview the selector on the last successful model and check its match count.", + "Check edge direction, geometry type and the workplane that receives the selector.", + ), + "vertices": ( + "Preview the selector on the last successful model and check its match count.", + "Check the selector direction and the workplane that receives it.", + ), +} + +_SELECTORS = {"faces", "edges", "vertices"} +_KERNEL_MARKERS = ( + "stdfail", + "brep_", + "brepbuilder", + "brepalgo", + "opencascade", + "could not construct", + "could not build", + "failed to create", + "not a valid shape", + "self-intersect", +) +_SELECTOR_MARKERS = ("selector", "selected", "parseexception", "syntax", "no objects") + + +def diagnose( + error: BaseException, source: str, line: int | None +) -> dict[str, Any] | None: + """Attach a hint only when the failing script line names a known CAD call.""" + + if line is None or isinstance(error, SyntaxError): + return None + try: + tree = ast.parse(source) + except SyntaxError: + return None + calls: list[ast.Call] = [] + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in _HINTS + and node.end_lineno is not None + and node.lineno <= line <= node.end_lineno + ): + calls.append(node) + if not calls: + return None + traceback_frame = error.__traceback__ + from_cadquery = False + stack_operations = [] + while traceback_frame is not None: + frame = traceback_frame.tb_frame + filename = frame.f_code.co_filename.replace("\\", "/").lower() + if "/cadquery/" in filename: + from_cadquery = True + if frame.f_code.co_name in _HINTS: + stack_operations.append(frame.f_code.co_name) + traceback_frame = traceback_frame.tb_next + for stack_operation in stack_operations: + matching = [ + call + for call in calls + if isinstance(call.func, ast.Attribute) + and call.func.attr == stack_operation + ] + if matching: + calls = matching + break + # For a chain on one line, the outermost call is the operation being + # applied. For a multiline chain, prefer the call named on this line. + calls.sort( + key=lambda node: ( + node.func.end_lineno == line, + node.end_lineno == line, + node.end_col_offset or 0, + ), + reverse=True, + ) + attribute = calls[0].func + assert isinstance(attribute, ast.Attribute) + operation = attribute.attr + reason = f"{type(error).__name__}: {error}".lower() + markers = _SELECTOR_MARKERS if operation in _SELECTORS else _KERNEL_MARKERS + if not any(marker in reason for marker in markers) and not ( + from_cadquery and not isinstance(error, TypeError) + ): + return None + receiver = attribute.value.id if isinstance(attribute.value, ast.Name) else None + return { + "operation": operation, + "receiver": receiver, + "line": line, + "hints": list(_HINTS[operation]), + } diff --git a/worker/cq_worker/display.py b/worker/cq_worker/display.py new file mode 100644 index 000000000..2043f5241 --- /dev/null +++ b/worker/cq_worker/display.py @@ -0,0 +1,231 @@ +"""Rich results in the console: Jupyter-style MIME bundles (FEAT-E6). + +An object's representations are gathered the way Jupyter does +(``_repr_mimebundle_``, then ``_repr_png_``, ``_repr_jpeg_``…), plus +matplotlib figures. Only what the GUI shows leaves the worker, checked and +bounded here: one PNG or JPEG image (recognized by its signature, at most +:data:`MAX_IMAGE_BYTES`) and the plain text. HTML, Markdown, SVG, LaTeX and +JSON are never sent, so no markup or script reaches the GUI. A broken or +slow ``_repr_*_`` only costs the worker (Stop interrupts it); the GUI decodes +images on its reader thread, never on the one that draws. +""" + +from __future__ import annotations + +import base64 +import binascii +import io +import sys +import threading +from collections.abc import Callable +from typing import Any + +#: Plain text sent per result. +MAX_TEXT_CHARS = 64 * 1024 +#: Image bytes sent per result (before base64). +MAX_IMAGE_BYTES = 4 * 1024 * 1024 +#: Images sent per console command; later ones are only described. +MAX_IMAGES_PER_REQUEST = 20 +#: Rich results sent per console command. This also bounds text-only loops. +MAX_RESULTS_PER_REQUEST = 100 + +_SIGNATURES = { + "png": b"\x89PNG\r\n\x1a\n", + "jpeg": b"\xff\xd8\xff", +} + + +def mime_bundle(value: Any) -> dict[str, Any]: + """The representations a Jupyter front end would get for ``value``; + ``text/plain`` is always there.""" + + data: dict[str, Any] = {} + method = _bound(value, "_repr_mimebundle_") + if method is not None: + result = _call(method, include=None, exclude=None) + result = _representation(result) + if isinstance(result, dict): + data.update(result) + for mime, name in [("image/png", "_repr_png_"), ("image/jpeg", "_repr_jpeg_")]: + if mime not in data: + method = _bound(value, name) + result = _call(method) if method is not None else None + result = _representation(result) + if result is not None and result is not _FAILED: + data[mime] = result + if "image/png" not in data and _is_matplotlib_figure(value): + buffer = io.BytesIO() + if _call(value.savefig, buffer, format="png", dpi=100) is not _FAILED: + data["image/png"] = buffer.getvalue() + # A malformed bundle must not suppress the ordinary representation. + if not isinstance(data.get("text/plain"), str): + plain = _call(repr, value) + data["text/plain"] = object.__repr__(value) if plain is _FAILED else plain + return data + + +def message(data: dict[str, Any], images_left: int) -> dict[str, Any]: + """The ``display`` message fields for a bundle: ``text`` and, when + ``images_left`` allows, an ``image`` (``format``, base64 ``data``).""" + + text = data.get("text/plain") + text = text if isinstance(text, str) else "" + image = None + for mime, kind in [("image/png", "png"), ("image/jpeg", "jpeg")]: + raw = _image_bytes(data.get(mime)) + if raw is _TOO_LARGE: + text += f"\n[{kind.upper()} image left out: over the limit]" + continue + if not isinstance(raw, bytes) or not raw.startswith(_SIGNATURES[kind]): + continue + if len(raw) > MAX_IMAGE_BYTES: + text += f"\n[{kind.upper()} image of {len(raw) // 1024} KB left out: over the limit]" + elif images_left <= 0: + text += f"\n[{kind.upper()} image left out: too many images in one command]" + else: + image = {"format": kind, "data": base64.b64encode(raw).decode("ascii")} + break + if len(text) > MAX_TEXT_CHARS: + text = text[:MAX_TEXT_CHARS] + f"\n[text cut after {MAX_TEXT_CHARS} characters]" + return {"text": text, "image": image} + + +class Displayer: + """Sends ``display`` messages for one console command at a time.""" + + def __init__(self, send: Callable[[dict], None]) -> None: + self._send = send + self._images_left = MAX_IMAGES_PER_REQUEST + self._results_left = MAX_RESULTS_PER_REQUEST + self._result_limit_reported = False + self._request_id: int | None = None + self._owner_thread: int | None = None + self._active = False + + def start(self, request_id: int | None) -> None: + """Begin a command, binding all its results to ``request_id``.""" + + self._images_left = MAX_IMAGES_PER_REQUEST + self._results_left = MAX_RESULTS_PER_REQUEST + self._result_limit_reported = False + self._request_id = request_id + self._owner_thread = threading.get_ident() + self._active = True + + def finish(self) -> None: + """End the command so retained/background ``display`` calls are inert.""" + + self._active = False + self._request_id = None + self._owner_thread = None + + def display(self, *values: Any) -> None: + """Shows each value in the console, an image included.""" + + # User code may retain ``display`` and call it from a background + # thread or after the command ended. Such a result cannot safely be + # associated with a request and must not be mislabeled as the next one. + if not self._active or threading.get_ident() != self._owner_thread: + return + # What was printed before comes first. + sys.stdout.flush() + sys.stderr.flush() + for value in values: + if self._results_left <= 0: + if not self._result_limit_reported: + self._emit( + { + "type": "display", + "text": ( + "[rich output truncated after " + f"{MAX_RESULTS_PER_REQUEST} results; " + "further results from this command were discarded]" + ), + "image": None, + } + ) + self._result_limit_reported = True + break + fields = message(mime_bundle(value), self._images_left) + self._results_left -= 1 + if fields["image"] is not None: + self._images_left -= 1 + self._emit({"type": "display", **fields}) + + def _emit(self, fields: dict[str, Any]) -> None: + self._send({"id": self._request_id, **fields}) + + def displayhook(self, value: Any) -> None: + """``sys.displayhook`` while a console command runs: the value of + an expression statement, shown like ``display`` and kept in ``_``.""" + + if value is None: + return + import builtins + + setattr(builtins, "_", None) + self.display(value) + setattr(builtins, "_", value) + + +_FAILED = object() +_TOO_LARGE = object() + + +def _call(function: Callable, *args: Any, **kwargs: Any) -> Any: + """``function(...)``, or :data:`_FAILED` if it raises (a broken + representation must not hide the result).""" + + try: + return function(*args, **kwargs) + except Exception: + return _FAILED + + +def _bound(value: Any, name: str) -> Callable | None: + """The method ``name`` of an instance; classes have them unbound.""" + + if isinstance(value, type): + return None + try: + method = getattr(value, name, None) + except Exception: + return None + return method if callable(method) else None + + +def _representation(value: Any) -> Any: + """The data part of a Jupyter ``(data, metadata)`` representation.""" + + if isinstance(value, tuple): + return value[0] if value else _FAILED + return value + + +def _is_matplotlib_figure(value: Any) -> bool: + figure = sys.modules.get("matplotlib.figure") + return figure is not None and isinstance(value, figure.Figure) + + +def _image_bytes(value: Any) -> bytes | object | None: + """Image bytes, rejected before decoding/copying when already too large. + + Bundles hold base64 text while ``_repr_png_`` normally returns bytes. + Checking the encoded length first prevents a hostile representation from + making the worker allocate an arbitrarily large decoded buffer. + """ + + if isinstance(value, (bytes, bytearray)): + if len(value) > MAX_IMAGE_BYTES: + return _TOO_LARGE + return bytes(value) + if isinstance(value, str): + encoded_limit = 4 * ((MAX_IMAGE_BYTES + 2) // 3) + if len(value) > encoded_limit: + return _TOO_LARGE + try: + raw = base64.b64decode(value, validate=True) + except (binascii.Error, ValueError): + return None + return raw if len(raw) <= MAX_IMAGE_BYTES else _TOO_LARGE + return None diff --git a/worker/cq_worker/engineering.py b/worker/cq_worker/engineering.py new file mode 100644 index 000000000..275666623 --- /dev/null +++ b/worker/cq_worker/engineering.py @@ -0,0 +1,243 @@ +"""Explicit engineering checks for prismatic beams and tool access. + +Units are millimetres, newtons and megapascals. These are transparent 1-D +linear-elastic calculations, not a finite-element claim about arbitrary CAD. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import Any + +import cadquery as cq + +from .motion import trace_path + +GRAVITY_M_S2 = 9.80665 + + +def _positive(name: str, value: float, *, zero: bool = False) -> float: + number = float(value) + if not math.isfinite(number) or (number < 0 if zero else number <= 0): + raise ValueError( + f"{name} must be finite and {'non-negative' if zero else 'positive'}" + ) + return number + + +@dataclass(frozen=True) +class EngineeringMaterial: + name: str + density_g_cm3: float + youngs_modulus_mpa: float + yield_strength_mpa: float + poisson_ratio: float = 0.3 + expansion_per_c: float = 0.0 + + def __post_init__(self) -> None: + if not self.name.strip(): + raise ValueError("Material needs a name") + for name in ("density_g_cm3", "youngs_modulus_mpa", "yield_strength_mpa"): + _positive(name, getattr(self, name)) + ratio = _positive("poisson_ratio", self.poisson_ratio, zero=True) + if ratio >= 0.5: + raise ValueError("poisson_ratio must be below 0.5") + _positive("expansion_per_c", self.expansion_per_c, zero=True) + + +@dataclass(frozen=True) +class BeamSection: + area_mm2: float + inertia_mm4: float + outer_radius_mm: float + minimum_wall_mm: float | None = None + + def __post_init__(self) -> None: + for name in ("area_mm2", "inertia_mm4", "outer_radius_mm"): + _positive(name, getattr(self, name)) + if self.minimum_wall_mm is not None: + _positive("minimum_wall_mm", self.minimum_wall_mm) + + @classmethod + def rectangle(cls, width_mm: float, height_mm: float) -> BeamSection: + width = _positive("width_mm", width_mm) + height = _positive("height_mm", height_mm) + return cls(width * height, width * height**3 / 12, height / 2) + + @classmethod + def hollow_rectangle( + cls, width_mm: float, height_mm: float, wall_mm: float + ) -> BeamSection: + width = _positive("width_mm", width_mm) + height = _positive("height_mm", height_mm) + wall = _positive("wall_mm", wall_mm) + inside_width, inside_height = width - 2 * wall, height - 2 * wall + if inside_width <= 0 or inside_height <= 0: + raise ValueError("Wall must leave a positive hollow opening") + return cls( + width * height - inside_width * inside_height, + (width * height**3 - inside_width * inside_height**3) / 12, + height / 2, + wall, + ) + + @classmethod + def round_tube(cls, outside_mm: float, wall_mm: float) -> BeamSection: + outside = _positive("outside_mm", outside_mm) + wall = _positive("wall_mm", wall_mm) + inside = outside - 2 * wall + if inside <= 0: + raise ValueError("Wall must leave a positive bore") + return cls( + math.pi * (outside**2 - inside**2) / 4, + math.pi * (outside**4 - inside**4) / 64, + outside / 2, + wall, + ) + + +class EngineeringError(ValueError): + """A declared structural or tool-access requirement is not satisfied.""" + + +def beam_check( + *, + section: BeamSection, + material: EngineeringMaterial, + length_mm: float, + transverse_load_n: float = 0.0, + axial_compression_n: float = 0.0, + support: str = "cantilever", + required_safety_factor: float = 1.5, + maximum_deflection_mm: float | None = None, + required_wall_mm: float | None = None, + temperature_change_c: float = 0.0, + thermally_restrained: bool = False, +) -> dict[str, Any]: + """Check a prismatic Euler-Bernoulli beam under stated simple loads. + + A cantilever has an end point load; a simply supported beam has a center + point load. Both include self-weight as a uniform load. The reported + stress conservatively sums bending, compression and restrained thermal + stress. Local buckling, joint flexibility and 3-D stress are not modeled. + """ + + if not isinstance(section, BeamSection) or not isinstance( + material, EngineeringMaterial + ): + raise TypeError("Provide a BeamSection and EngineeringMaterial") + length = _positive("length_mm", length_mm) + transverse = _positive("transverse_load_n", transverse_load_n, zero=True) + axial = _positive("axial_compression_n", axial_compression_n, zero=True) + safety = _positive("required_safety_factor", required_safety_factor) + if safety < 1: + raise ValueError("required_safety_factor must be at least 1") + if support not in ("cantilever", "simply_supported_center_load"): + raise ValueError("Unknown support case") + limit = ( + _positive("maximum_deflection_mm", maximum_deflection_mm, zero=True) + if maximum_deflection_mm is not None + else None + ) + wall_requirement = ( + _positive("required_wall_mm", required_wall_mm) + if required_wall_mm is not None + else None + ) + temperature = float(temperature_change_c) + if not math.isfinite(temperature): + raise ValueError("temperature_change_c must be finite") + + e = material.youngs_modulus_mpa + inertia = section.inertia_mm4 + # density (g/cm^3) * area (mm^2) / 1e6 -> kg per millimetre. + self_weight_n_per_mm = ( + material.density_g_cm3 * section.area_mm2 * GRAVITY_M_S2 / 1e6 + ) + if support == "cantilever": + moment = transverse * length + self_weight_n_per_mm * length**2 / 2 + deflection = transverse * length**3 / ( + 3 * e * inertia + ) + self_weight_n_per_mm * length**4 / (8 * e * inertia) + effective_length = 2 * length + else: + moment = transverse * length / 4 + self_weight_n_per_mm * length**2 / 8 + deflection = transverse * length**3 / ( + 48 * e * inertia + ) + 5 * self_weight_n_per_mm * length**4 / (384 * e * inertia) + effective_length = length + + thermal_expansion = material.expansion_per_c * temperature * length + thermal_stress = ( + e * material.expansion_per_c * abs(temperature) if thermally_restrained else 0.0 + ) + stress = ( + moment * section.outer_radius_mm / inertia + + axial / section.area_mm2 + + thermal_stress + ) + buckling = math.pi**2 * e * inertia / effective_length**2 + mass_kg = material.density_g_cm3 * section.area_mm2 * length / 1e6 + if not all( + math.isfinite(value) for value in (stress, deflection, buckling, mass_kg) + ): + raise ValueError("Beam result is outside numeric range") + + issues = [] + if stress * safety > material.yield_strength_mpa: + issues.append("Yield strength is below the required safety factor") + if axial > 0 and axial * safety > buckling: + issues.append("Euler column buckling capacity is insufficient") + if limit is not None and deflection > limit: + issues.append("Deflection exceeds the stated limit") + if wall_requirement is not None: + if section.minimum_wall_mm is None: + issues.append("Minimum wall is unknown for this section") + elif section.minimum_wall_mm < wall_requirement: + issues.append("Section wall is below the stated minimum") + + return { + "ok": not issues, + "material": material.name, + "support": support, + "mass_kg": mass_kg, + "maximum_stress_mpa": stress, + "yield_allowable_mpa": material.yield_strength_mpa / safety, + "deflection_mm": deflection, + "buckling_capacity_n": buckling, + "thermal_expansion_mm": thermal_expansion, + "minimum_wall_mm": section.minimum_wall_mm, + "issues": issues, + "model": "1-D linear-elastic Euler-Bernoulli beam; ideal supports and section", + } + + +def require_beam(**conditions: Any) -> dict[str, Any]: + report = beam_check(**conditions) + if not report["ok"]: + raise EngineeringError("; ".join(report["issues"])) + return report + + +def tool_access( + tool_diameter_mm: float, + tool_length_mm: float, + obstacles: list[cq.Shape | cq.Workplane | cq.Assembly], + poses: list[tuple[float, float, float, float, float, float]], + *, + required_clearance: float = 0.0, +) -> dict[str, Any]: + """Check a cylindrical tool envelope along a declared approach path.""" + + diameter = _positive("tool_diameter_mm", tool_diameter_mm) + length = _positive("tool_length_mm", tool_length_mm) + tool = cq.Workplane().circle(diameter / 2).extrude(length) + return trace_path(tool, obstacles, poses, required_clearance=required_clearance) + + +def require_tool_access(*args: Any, **kwargs: Any) -> dict[str, Any]: + report = tool_access(*args, **kwargs) + if report["status"] != "clear": + raise EngineeringError(f"Tool access {report['status']}: {report}") + return report diff --git a/worker/cq_worker/environment.py b/worker/cq_worker/environment.py new file mode 100644 index 000000000..fe8926f91 --- /dev/null +++ b/worker/cq_worker/environment.py @@ -0,0 +1,52 @@ +"""Describe the Python/CadQuery/OCP environment used by the worker.""" + +from __future__ import annotations + +import importlib.metadata +import platform +import sys +from typing import Any + +import cadquery as cq + + +def distribution_version(name: str) -> str: + """Return an installed distribution version without hiding bad metadata.""" + + try: + return importlib.metadata.version(name) + except importlib.metadata.PackageNotFoundError: + return "unknown" + + +def ocp_version() -> str: + """The OCP release, also for conda installs, which carry no pip metadata.""" + + version = distribution_version("cadquery-ocp") + if version != "unknown": + return version + import OCP + + return str(getattr(OCP, "__version__", "unknown")) + + +def runtime_environment() -> dict[str, Any]: + """Versions needed to reproduce worker tests, timings and failures.""" + + return { + "python": platform.python_version(), + "implementation": platform.python_implementation(), + "cadquery": cq.__version__, + "ocp": ocp_version(), + "platform": platform.platform(), + "executable": sys.executable, + } + + +def summary() -> str: + environment = runtime_environment() + return ( + f"Python {environment['python']} ({environment['implementation']}) · " + f"CadQuery {environment['cadquery']} · OCP {environment['ocp']} · " + f"{environment['platform']}" + ) diff --git a/worker/cq_worker/execution.py b/worker/cq_worker/execution.py new file mode 100644 index 000000000..ec96e8c7e --- /dev/null +++ b/worker/cq_worker/execution.py @@ -0,0 +1,468 @@ +"""Compile and run CadQuery scripts the way CQ-editor always has. + +Scripts run as a fresh ``__cq_main__`` module with a small API injected into +their namespace: + +``show_object(obj, name=None, options=None, **options)`` + Display ``obj``; options are ``color``, ``alpha`` (opacity), ``rgba`` and + ``edgecolor``. +``debug(obj, name=None)`` + Display ``obj`` as a translucent red overlay. +``rand_color(alpha=1.0, cfloat=False)`` + A random dark color for ``show_object`` options. +``log(value)`` + Write ``value`` to the GUI log. +``cq`` + The ``cadquery`` module. +""" + +from __future__ import annotations + +import contextlib +import importlib +import linecache +import logging +import os +import random +import sys +import sysconfig +import traceback +import types +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from inspect import currentframe +from typing import Any, cast + +import cadquery as cq + +from .assembly_checks import assembly_diagnostics, require_constrained_assembly +from .cad_checks import CheckSuite +from .engineering import ( + BeamSection, + EngineeringMaterial, + beam_check, + require_beam, + require_tool_access, + tool_access, +) +from . import provenance +from . import diagnostics +from .debugger import DebugStop +from .fit import cylindrical_fit, require_fit +from .motion import require_clear_path, trace_path +from .scene import ShownObject + +#: Pseudo file name of the editor buffer in code objects and tracebacks. +SCRIPT_FILENAME = "" + +#: Seed used before every run, so that ``rand_color`` is reproducible. +RANDOM_SEED = 59798267586177 + +#: Longest value text sent for the variables panel, whose detail view shows +#: it in full. +MAX_VALUE_LENGTH = 2000 + +script_log = logging.getLogger("script") + + +@dataclass +class RunSettings: + reload_cq: bool = False + add_script_dir_to_path: bool = True + change_working_dir: bool = True + reload_imported_modules: bool = True + + @classmethod + def from_message(cls, message: dict | None) -> RunSettings: + message = message or {} + return cls( + **{ + name: bool(message[name]) + for name in cls.__dataclass_fields__ + if name in message + } + ) + + +def rand_color(alpha: float = 1.0, cfloat: bool = False): + """Random, not-too-bright color for ``show_object`` options.""" + + lower, upper = 10, 100 + channels = [random.randrange(lower, upper) for _ in range(3)] + if cfloat: + return (*(c / 255 for c in channels), alpha) + return {"alpha": alpha, "color": tuple(channels)} + + +class ShownObjects(dict[str, ShownObject]): + """Objects passed to ``show_object``, in call order, keyed by name.""" + + def __init__(self) -> None: + super().__init__() + self._warned_duplicates: set[str] = set() + + def clear(self) -> None: + super().clear() + self._warned_duplicates.clear() + + def show(self, obj: Any, name: str | None = None, options=None, **kwargs) -> None: + merged = {**(options or {}), **kwargs} + frame = currentframe() + assert frame is not None and frame.f_back is not None + caller = frame.f_back.f_back + self._store(obj, name, merged, caller) + + def debug(self, obj: Any, name: str | None = None) -> None: + frame = currentframe() + assert frame is not None and frame.f_back is not None + caller = frame.f_back.f_back + self._store(obj, name, {"color": "red", "alpha": 0.2}, caller) + + def _store( + self, + obj: Any, + name: str | None, + options: dict[str, Any], + caller: types.FrameType | None, + ) -> None: + if not name: + name = _variable_name(obj, caller) or self._unique_name(obj) + key = str(name) + if key in self and key not in self._warned_duplicates: + self._warned_duplicates.add(key) + script_log.warning( + 'The name "%s" was used more than once in show_object(); ' + "an earlier object with this name was replaced. " + "Use distinct names to display objects separately.", + key, + ) + self[key] = ShownObject(obj, options, _script_line(caller)) + + def _unique_name(self, obj: Any) -> str: + base = type(obj).__name__ + index = 1 + while f"{base} {index}" in self: + index += 1 + return f"{base} {index}" + + +def _script_line(frame) -> int | None: + """The line of ``frame`` when it runs the editor buffer.""" + + if frame is not None and frame.f_code.co_filename == SCRIPT_FILENAME: + return frame.f_lineno + return None + + +def _variable_name(obj: Any, frame) -> str | None: + """The name ``obj`` is bound to in the calling frame, if any.""" + + if frame is None: + return None + for name, value in frame.f_locals.items(): + if value is obj and not name.startswith("_"): + return name + return None + + +def script_api( + shown: ShownObjects, + allowances: list[tuple[str, str, str]] | None = None, + checks: CheckSuite | None = None, +) -> dict[str, Any]: + """Names injected into the script namespace.""" + + def show_object(obj, name=None, options=None, **kwargs): + shown.show(obj, name, options, **kwargs) + + def debug(obj, name=None): + shown.debug(obj, name) + + def expect(obj, name=None): + frame = currentframe() + assert frame is not None + suite = checks if checks is not None else CheckSuite() + return suite.expect(obj, name, _script_line(frame.f_back)) + + def allow_interference(first: str, second: str, *, reason: str) -> None: + if not all( + isinstance(value, str) and value.strip() + for value in (first, second, reason) + ): + raise ValueError( + "An interference allowance needs two part names and a reason" + ) + first, second, reason = first.strip(), second.strip(), reason.strip() + if first == second: + raise ValueError("An interference allowance needs two distinct part names") + if allowances is None: + raise RuntimeError("Declare interference allowances in the model script") + allowances.append((first, second, reason)) + + return { + "show_object": show_object, + "debug": debug, + "expect": expect, + "rand_color": rand_color, + "cylindrical_fit": cylindrical_fit, + "require_fit": require_fit, + "trace_path": trace_path, + "require_clear_path": require_clear_path, + "assembly_diagnostics": assembly_diagnostics, + "require_constrained_assembly": require_constrained_assembly, + "BeamSection": BeamSection, + "EngineeringMaterial": EngineeringMaterial, + "beam_check": beam_check, + "require_beam": require_beam, + "tool_access": tool_access, + "require_tool_access": require_tool_access, + "allow_interference": allow_interference, + "log": lambda value: script_log.info(str(value)), + "cq": cq, + } + + +def compile_script(source: str) -> types.CodeType: + # Registering the source lets tracebacks show the offending lines. + lines = source.splitlines(keepends=True) + linecache.cache[SCRIPT_FILENAME] = (len(source), None, lines, SCRIPT_FILENAME) + return compile(source, SCRIPT_FILENAME, "exec") + + +def new_module(path: str | None) -> types.ModuleType: + module = types.ModuleType("__cq_main__") + if path: + module.__file__ = path + return module + + +@contextlib.contextmanager +def script_environment(path: str | None, settings: RunSettings) -> Iterator[None]: + """Temporarily adjust ``sys.path``, the working directory and the module + cache according to ``settings``.""" + + script_dir = os.path.dirname(os.path.abspath(path)) if path else None + with contextlib.ExitStack() as stack: + if script_dir and os.path.isdir(script_dir): + if settings.add_script_dir_to_path: + sys.path.insert(0, script_dir) + stack.callback(_remove_path, script_dir) + if settings.change_working_dir: + stack.enter_context(contextlib.chdir(script_dir)) + if settings.reload_imported_modules: + stack.enter_context(unload_new_user_modules()) + yield + + +def _remove_path(entry: str) -> None: + with contextlib.suppress(ValueError): + sys.path.remove(entry) + + +@contextlib.contextmanager +def unload_new_user_modules() -> Iterator[None]: + """Forget modules imported while the context is active, so that edits to + a script's helper modules are picked up by the next run. + + Library modules (standard library and site-packages) stay loaded: + re-importing C extensions such as numpy is not safe. + """ + + before = set(sys.modules) + try: + yield + finally: + for name in set(sys.modules) - before: + module = sys.modules.get(name) + if module is not None and not _is_library_module(module): + del sys.modules[name] + + +_LIBRARY_ROOTS = tuple( + os.path.normcase(os.path.abspath(p)) + for p in { + sys.prefix, + sys.base_prefix, + sys.exec_prefix, + *( + sysconfig.get_paths().get(k, "") + for k in ("stdlib", "platstdlib", "purelib", "platlib") + ), + } + if p +) + + +def _is_library_module(module: types.ModuleType) -> bool: + path = getattr(module, "__file__", None) + if not path: + return True # built-in or namespace package + path = os.path.normcase(os.path.abspath(path)) + return path.startswith(_LIBRARY_ROOTS) + + +def reload_cadquery() -> None: + """Re-import CadQuery itself, for people developing CadQuery.""" + + # Order matters: dependencies first. + for name in ( + "cadquery.types", + "cadquery.occ_impl.geom", + "cadquery.occ_impl.shapes", + "cadquery.occ_impl.importers.dxf", + "cadquery.occ_impl.importers", + "cadquery.occ_impl.solver", + "cadquery.occ_impl.assembly", + "cadquery.occ_impl.sketch_solver", + "cadquery.hull", + "cadquery.selectors", + "cadquery.sketch", + "cadquery.occ_impl.exporters.svg", + "cadquery.cq", + "cadquery.occ_impl.exporters.dxf", + "cadquery.occ_impl.exporters.amf", + "cadquery.occ_impl.exporters.json", + "cadquery.occ_impl.exporters", + "cadquery.assembly", + "cadquery", + ): + module = sys.modules.get(name) + if module is not None: + importlib.reload(module) + + +def describe_variables(namespace: dict[str, Any], hidden: set[str]) -> list[dict]: + """Rows for the variables panel.""" + + rows = [] + for name, value in namespace.items(): + if name.startswith("_") or name in hidden: + continue + try: + text = str(value) + except Exception as error: # a broken __str__ must not break the run + text = f"" + if len(text) > MAX_VALUE_LENGTH: + text = text[: MAX_VALUE_LENGTH - 1] + "…" + rows.append({"name": name, "type": type(value).__name__, "value": text}) + return rows + + +def describe_exception(error: BaseException, source: str = "") -> dict: + """Traceback summary for the GUI, starting at the first script frame.""" + + frames = traceback.extract_tb(error.__traceback__) + while frames and frames[0].filename != SCRIPT_FILENAME: + frames.pop(0) + + rows = [ + { + "file": frame.filename, + "line": frame.lineno, + "function": frame.name, + "code": (frame.line or "").strip(), + } + for frame in frames + ] + if isinstance(error, SyntaxError): + rows.append( + { + "file": error.filename or SCRIPT_FILENAME, + "line": error.lineno or 0, + "function": "", + "code": (error.text or "").strip(), + } + ) + + script_lines = [ + cast(int, row["line"]) for row in rows if row["file"] == SCRIPT_FILENAME + ] + return { + "type_name": type(error).__name__, + "message": str(error), + "frames": rows, + "line": script_lines[-1] if script_lines else None, + "text": "".join(traceback.format_exception(error)), + "diagnostic": diagnostics.diagnose( + error, source, script_lines[-1] if script_lines else None + ), + } + + +class Execution: + """One run of the editor buffer.""" + + def __init__(self, source: str, path: str | None, settings: RunSettings) -> None: + self.source = source + self.path = path + self.settings = settings + self.module = new_module(path) + self.shown = ShownObjects() + self.interference_allowances: list[tuple[str, str, str]] = [] + self.checks = CheckSuite() + self.api = script_api(self.shown, self.interference_allowances, self.checks) + self.error: dict | None = None + #: Set when a debugging session was ended by the user. + self.stopped = False + #: Set when Stop interrupted the script (``KeyboardInterrupt``); + #: :attr:`error` then says where. + self.interrupted = False + + @property + def namespace(self) -> dict[str, Any]: + return self.module.__dict__ + + def run( + self, executor: Callable[[types.CodeType, dict], None] | None = None + ) -> bool: + """Execute the script; returns ``False`` (with :attr:`error` set) on failure. + + ``executor`` replaces the plain ``exec`` call, which is how the + debugger hooks in. + """ + + random.seed(RANDOM_SEED) + # Helper modules may have been created or edited since the last run. + importlib.invalidate_caches() + if self.settings.reload_cq: + reload_cadquery() + + try: + code = compile_script(self.source) + except SyntaxError as error: + self.error = describe_exception(error, self.source) + return False + + self.namespace.update(self.api) + try: + with script_environment(self.path, self.settings): + with provenance.recording(SCRIPT_FILENAME): + (executor or _exec)(code, self.namespace) + except DebugStop: + self.stopped = True + except SystemExit: + pass # a script calling sys.exit() simply ends early + except KeyboardInterrupt as error: + self.interrupted = True + self.error = describe_exception(error, self.source) + return False + except Exception as error: + # Lets the console's %debug-style post mortem tools find it. + sys.last_traceback = error.__traceback__ + self.error = describe_exception(error, self.source) + return False + finally: + self._remove_api() + return True + + def hidden_names(self) -> set[str]: + return set(self.api) - {"cq"} + + def _remove_api(self) -> None: + for name, value in self.api.items(): + if name != "cq" and self.namespace.get(name) is value: + del self.namespace[name] + + +def _exec(code: types.CodeType, namespace: dict) -> None: + exec(code, namespace) diff --git a/worker/cq_worker/exporting.py b/worker/cq_worker/exporting.py new file mode 100644 index 000000000..6a806db7e --- /dev/null +++ b/worker/cq_worker/exporting.py @@ -0,0 +1,437 @@ +"""Write displayed objects to CAD and mesh files.""" + +from __future__ import annotations + +import inspect +import os +import tempfile +from xml.etree import ElementTree as ET +from zipfile import ZipFile + +import cadquery as cq +from OCP.gp import gp_Vec +from OCP.Interface import Interface_Static +from OCP.STEPControl import STEPControl_Controller + +from .checking import GeometryInvalid, check_registry, check_shape, invalid_reports +from .interference import analyze_interferences, apply_allowances +from .scene import Registry, RegistryEntry, to_compound + +FORMATS = ( + "step", + "stl", + "brep", + "3mf", + "gltf", + "glb", + "amf", + "vrml", + "vtkjs", + "xbf", + "svg", + "dxf", +) +UNITS = { + "millimeter": ("MM", 0.001), + "centimeter": ("CM", 0.01), + "meter": ("M", 1.0), + "inch": ("INCH", 0.0254), +} + + +def export( + registry: Registry, + keys: list[str], + file_format: str, + path: str, + tolerance: float = 0.1, + angular_tolerance: float = 0.1, + step_mode: str = "default", + step_schema: str = "ap242", + stl_ascii: bool = False, + flat_parts: bool = False, + unit: str = "millimeter", + on_invalid: str = "check", + on_interference: str = "check", + interference_allowances: list[tuple[str, str, str]] | None = None, +) -> None: + """Export the objects behind ``keys`` (with their descendants). + + STEP always uses a named assembly, including several shown objects. The + original CadQuery objects are never changed by export. + """ + + file_format = file_format.lower() + if file_format not in FORMATS: + raise ValueError(f"Unsupported export format {file_format!r}") + if not keys: + raise ValueError("Nothing to export") + + if step_mode not in ("default", "fused"): + raise ValueError(f"Unsupported STEP mode {step_mode!r}") + if step_schema not in ("ap214", "ap242"): + raise ValueError(f"Unsupported STEP schema {step_schema!r}") + if unit not in UNITS: + raise ValueError("Choose the model unit before exporting") + if on_invalid not in ("check", "ignore", "fix"): + raise ValueError(f"Unsupported invalid-geometry action {on_invalid!r}") + if on_interference not in ("check", "ignore"): + raise ValueError(f"Unsupported interference action {on_interference!r}") + bad = invalid_reports(check_registry(registry, keys, flat_parts)) + if bad and on_invalid == "check": + raise GeometryInvalid(bad) + repaired: dict[str, cq.Shape] = {} + if bad and on_invalid == "fix": + still_bad = [] + for report in bad: + key = report["key"] + shape = registry.get(key).shape + if shape is None: + raise ValueError(f"Cannot repair empty geometry {key!r}") + fixed = shape.fix() + checked = check_shape(fixed) + if checked["valid"]: + repaired[key] = fixed + else: + still_bad.append( + { + **report, + **checked, + "issues": [ + *checked["issues"], + "ShapeFix did not resolve this geometry", + ], + } + ) + if still_bad: + raise GeometryInvalid(still_bad) + + physical = analyze_interferences( + registry, keys, flat_parts=flat_parts, replacements=repaired + ) + apply_allowances( + registry, + keys, + physical, + interference_allowances or [], + flat_parts=flat_parts, + replacements=repaired, + ) + unsafe = [ + pair + for pair in physical + if pair["kind"] == "inconclusive" + or (pair["kind"] == "interference" and not pair.get("allowance_reason")) + ] + if unsafe and on_interference == "check": + raise GeometryInvalid([], unsafe) + + if file_format in ("step", "gltf", "glb", "vrml", "vtkjs", "xbf"): + assembly = export_assembly(registry, keys, flat_parts, repaired) + if file_format == "step": + STEPControl_Controller.Init_s() + previous = Interface_Static.CVal_s("write.step.schema") + previous_unit = Interface_Static.CVal_s("write.step.unit") + previous_source = Interface_Static.CVal_s("xstep.cascade.unit") + schema = "AP242DIS" if step_schema == "ap242" else "AP214IS" + if not Interface_Static.SetCVal_s("write.step.schema", schema): + raise RuntimeError(f"Cannot select STEP schema {schema}") + try: + if not Interface_Static.SetCVal_s("xstep.cascade.unit", "MM"): + raise RuntimeError("Cannot set the STEP source unit") + if not Interface_Static.SetCVal_s("write.step.unit", UNITS[unit][0]): + raise RuntimeError(f"Cannot set the STEP output unit to {unit}") + if "outputUnit" in inspect.signature(cq.Assembly.export).parameters: + # CadQuery 2.8 sets both interface units inside export(). + # Its defaults would overwrite the caller's model unit. + assembly.export( + path, + "STEP", + mode=step_mode, # type: ignore[arg-type] + unit=UNITS[unit][0], # type: ignore[arg-type] + outputUnit=UNITS[unit][0], # type: ignore[arg-type] + ) + else: + assembly.export(path, "STEP", mode=step_mode) # type: ignore[arg-type] + finally: + Interface_Static.SetCVal_s("write.step.schema", previous) + Interface_Static.SetCVal_s("write.step.unit", previous_unit) + Interface_Static.SetCVal_s("xstep.cascade.unit", previous_source) + else: + if file_format in ("gltf", "glb"): + _scale_assembly(assembly, UNITS[unit][1]) + assembly.export( + path, + "GLTF" if file_format == "gltf" else file_format.upper(), # type: ignore[arg-type] + tolerance=tolerance, + angularTolerance=angular_tolerance, + ) + if file_format == "vtkjs": + # CadQuery appends .zip itself. Reject a broken/empty scene + # instead of reporting an export that cannot be opened. + archive = path + ".zip" + try: + with ZipFile(archive) as package: + if not package.namelist(): + raise RuntimeError( + "VTK.js exporter produced an empty scene" + ) + os.replace(archive, path) + except Exception: + if os.path.exists(archive): + os.unlink(archive) + raise + return + + parts = _export_parts(registry, keys, flat_parts) + shapes = [repaired.get(key, entry.shape) for key, entry in parts] + compound = to_compound(shapes) + if file_format == "stl": + compound.exportStl( + path, + tolerance=tolerance, + angularTolerance=angular_tolerance, + ascii=stl_ascii, + ) + elif file_format == "brep": + compound.exportBrep(path) + elif file_format == "3mf": + cq.exporters.export( + compound, + path, + "3MF", + tolerance, + angular_tolerance, + opt={"unit": unit}, + ) + _decorate_3mf(path, [entry for _, entry in parts]) + else: + cq.exporters.export( + compound, + path, + file_format.upper(), # type: ignore[arg-type] + tolerance, + angular_tolerance, + ) + + +def export_assembly( + registry: Registry, + keys: list[str], + flat_parts: bool = False, + repaired: dict[str, cq.Shape] | None = None, +) -> cq.Assembly: + """The requested nodes, with world placement, names and display colors. + + A selected ancestor owns its descendants. Ignoring separately selected + descendants prevents a duplicated solid in the resulting STEP file. + """ + + repaired = repaired or {} + descendants: set[str] = set() + + def mark_children(key: str) -> None: + for child in registry.get(key).children: + descendants.add(child) + mark_children(child) + + if not flat_parts: + for key in keys: + mark_children(key) + + result = cq.Assembly(name="CQ-editor export") + used_names: set[str] = set() + for key in dict.fromkeys(keys): + if key in descendants: + continue + entry = registry.get(key) + name = entry.name or key + original = name + index = 2 + while name in used_names: + name = f"{original} ({index})" + index += 1 + used_names.add(name) + if repaired and not flat_parts: + _add_repaired_node(result, registry, key, name, repaired) + elif flat_parts and entry.shape is not None: + color = ( + entry.display_color + or (entry.obj.color if isinstance(entry.obj, cq.Assembly) else None) + or entry.inherited_color + ) + result.add(repaired.get(key, entry.shape), name=name, color=color) + elif isinstance(entry.obj, cq.Assembly): + result.add(placed_assembly(entry), name=name) + elif entry.shape is not None: + result.add(entry.shape, name=name, color=entry.display_color) + if not result.children: + raise ValueError("No exportable geometry in the chosen objects") + return result + + +def _add_repaired_node( + parent: cq.Assembly, + registry: Registry, + key: str, + name: str, + repaired: dict[str, cq.Shape], +) -> None: + """Rebuild just the export copy from world shapes, retaining hierarchy.""" + entry = registry.get(key) + color = ( + entry.display_color + or (entry.obj.color if isinstance(entry.obj, cq.Assembly) else None) + or entry.inherited_color + ) + if entry.children: + group = cq.Assembly(name=name, color=color) + if entry.shape is not None: + group.add(repaired.get(key, entry.shape), name=f"{name} body", color=color) + for child in entry.children: + child_entry = registry.get(child) + _add_repaired_node( + group, registry, child, child_entry.name or child, repaired + ) + parent.add(group, name=name, color=color) + elif entry.shape is not None: + parent.add(repaired.get(key, entry.shape), name=name, color=color) + + +def _scale_assembly(assembly: cq.Assembly, factor: float) -> None: + """Convert a private export copy from model units to glTF meters.""" + for _, node in assembly.traverse(): + if node.obj is not None: + node.obj = to_compound(node.obj).scale(factor) + transform = node.loc.wrapped.Transformation() + translation = transform.TranslationPart() + transform.SetTranslationPart( + gp_Vec( + translation.X() * factor, + translation.Y() * factor, + translation.Z() * factor, + ) + ) + node.loc = cq.Location(transform) + + +def _export_parts( + registry: Registry, keys: list[str], flat_parts: bool +) -> list[tuple[str, RegistryEntry]]: + """The individual displayed shapes in the order used by 3MF export.""" + parts: list[tuple[str, RegistryEntry]] = [] + seen: set[str] = set() + + def visit(key: str) -> None: + if key in seen: + return + seen.add(key) + entry = registry.get(key) + if entry.shape is not None: + parts.append((key, entry)) + if not flat_parts: + for child in entry.children: + visit(child) + + for key in keys: + visit(key) + return parts + + +def _decorate_3mf(path: str, parts: list[RegistryEntry]) -> None: + """Add shown names and colors to CadQuery's unit-aware 3MF meshes. + + CadQuery's 3MF writer emits the geometry and package but anonymous + uncolored mesh resources. The core 3MF base-material group gives each + mesh a display color without changing its triangles or placement. + """ + core = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" + ET.register_namespace("", core) + model_name = "3D/3dmodel.model" + with ZipFile(path) as package: + files = [(item, package.read(item.filename)) for item in package.infolist()] + model = next(data for item, data in files if item.filename == model_name) + root = ET.fromstring(model) + resources = root.find(f"{{{core}}}resources") + if resources is None: + raise ValueError("3MF export has no resources") + meshes = [ + object_node + for object_node in resources.findall(f"{{{core}}}object") + if object_node.find(f"{{{core}}}mesh") is not None + ] + if len(meshes) != len(parts): + raise ValueError("3MF mesh count differs from the displayed parts") + used_ids = [int(item.get("id", "0")) for item in resources if item.get("id")] + materials = ET.Element( + f"{{{core}}}basematerials", id=str(max(used_ids, default=0) + 1) + ) + for index, (mesh, entry) in enumerate(zip(meshes, parts)): + name = entry.name or f"Part {index + 1}" + mesh.set("name", name) + color = ( + entry.display_color + or (entry.obj.color if isinstance(entry.obj, cq.Assembly) else None) + or entry.inherited_color + ) + if color is None: + color = cq.Color(0.75, 0.75, 0.75) + r, g, b, _ = color.toTuple() + hex_color = "#{:02X}{:02X}{:02X}".format( + *(round(max(0, min(1, value)) * 255) for value in (r, g, b)) + ) + ET.SubElement(materials, f"{{{core}}}base", name=name, displaycolor=hex_color) + material_id = materials.get("id") + assert material_id is not None + mesh.set("pid", material_id) + mesh.set("pindex", str(index)) + resources.insert(0, materials) + encoded = ET.tostring(root, encoding="utf-8", xml_declaration=True) + directory = os.path.dirname(os.path.abspath(path)) + with tempfile.NamedTemporaryFile( + dir=directory, suffix=".3mf", delete=False + ) as temp: + temporary = temp.name + try: + with ZipFile(temporary, "w") as package: + for item, data in files: + package.writestr(item, encoded if item.filename == model_name else data) + os.replace(temporary, path) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def placed_assembly(entry: RegistryEntry) -> cq.Assembly: + """A copy of the assembly of ``entry`` as the view shows it. + + A node below the top of an assembly holds its own ``loc``, relative to + its parent: exported alone, it is placed with its parents' location. + The view also draws a node without a color in the color it inherits, + while CadQuery's STEP writer only colors nodes that have one, so the + copy gives every node its inherited color. The script's own assembly + is left as it is. + """ + + assembly = entry.obj + holder = cq.Assembly() + holder.add( + assembly, + loc=( + None + if entry.parent_location is None + else entry.parent_location * assembly.loc + ), + ) + placed = holder.children[0] + _push_colors(placed, entry.inherited_color, entry.display_color) + return placed + + +def _push_colors( + node: cq.Assembly, inherited: cq.Color | None, override: cq.Color | None = None +) -> None: + color = override or node.color or inherited + node.color = color + for child in node.children: + _push_colors(child, color, override) diff --git a/worker/cq_worker/fit.py b/worker/cq_worker/fit.py new file mode 100644 index 000000000..cc1c05b9a --- /dev/null +++ b/worker/cq_worker/fit.py @@ -0,0 +1,114 @@ +"""Conservative dimensional checks for cylindrical assembly fits. + +These checks use the tolerances declared by the designer. They supplement, +but cannot replace, exact interference checks of the modeled solids. +""" + +from __future__ import annotations + +import math + + +class FitError(ValueError): + """A declared mechanical fit fails its worst-case requirements.""" + + +def _finite(name: str, value: float, *, minimum: float | None = None) -> float: + result = float(value) + if not math.isfinite(result) or (minimum is not None and result < minimum): + raise ValueError(f"{name} must be finite and at least {minimum}") + return result + + +def cylindrical_fit( + *, + hole_diameter: float, + pin_diameter: float, + hole_lower: float = 0.0, + hole_upper: float = 0.0, + pin_lower: float = 0.0, + pin_upper: float = 0.0, + required_clearance: float = 0.0, + center_offset: float = 0.0, + insertion_depth: float | None = None, + hole_depth: float | None = None, + head_diameter: float | None = None, + counterbore_diameter: float | None = None, + head_height: float | None = None, + counterbore_depth: float | None = None, +) -> dict: + """Evaluate the worst-case envelope of a rigid pin and circular hole. + + All dimensions are in the same model unit. Deviations are signed and + ``center_offset`` is the maximum radial axis offset, not a diameter. + Equal nominal diameters with zero deviations have zero clearance, which + is not proof that manufactured parts will assemble. + """ + + hole = _finite("hole_diameter", hole_diameter, minimum=0.0) + pin = _finite("pin_diameter", pin_diameter, minimum=0.0) + if hole == 0 or pin == 0: + raise ValueError("Diameters must be positive") + hole_low = _finite("hole_lower", hole_lower) + hole_high = _finite("hole_upper", hole_upper) + pin_low = _finite("pin_lower", pin_lower) + pin_high = _finite("pin_upper", pin_upper) + if hole_low > hole_high or pin_low > pin_high: + raise ValueError("Lower deviation cannot exceed upper deviation") + hole_min, hole_max = hole + hole_low, hole + hole_high + pin_min, pin_max = pin + pin_low, pin + pin_high + if hole_min <= 0 or pin_min <= 0: + raise ValueError("Tolerance range must keep diameters positive") + required = _finite("required_clearance", required_clearance, minimum=0.0) + offset = _finite("center_offset", center_offset, minimum=0.0) + # A radial offset consumes twice that amount of diametral clearance. + clearance_min = hole_min - pin_max - 2 * offset + clearance_max = hole_max - pin_min - 2 * offset + issues = [] + if clearance_min < required: + issues.append("Worst-case diametral clearance is below the required clearance") + + if (insertion_depth is None) != (hole_depth is None): + raise ValueError("Provide both insertion_depth and hole_depth") + if insertion_depth is not None: + assert hole_depth is not None + insertion = _finite("insertion_depth", insertion_depth, minimum=0.0) + depth = _finite("hole_depth", hole_depth, minimum=0.0) + if insertion > depth: + issues.append("Insertion is deeper than the available hole") + + if (head_diameter is None) != (counterbore_diameter is None): + raise ValueError("Provide both head_diameter and counterbore_diameter") + if head_diameter is not None: + assert counterbore_diameter is not None + head = _finite("head_diameter", head_diameter, minimum=0.0) + counterbore = _finite("counterbore_diameter", counterbore_diameter, minimum=0.0) + if head <= 0 or counterbore <= 0: + raise ValueError("Head and counterbore diameters must be positive") + if head > counterbore: + issues.append("Head is wider than its counterbore") + if (head_height is None) != (counterbore_depth is None): + raise ValueError("Provide both head_height and counterbore_depth") + if head_height is not None: + assert counterbore_depth is not None + height = _finite("head_height", head_height, minimum=0.0) + depth = _finite("counterbore_depth", counterbore_depth, minimum=0.0) + if height > depth: + issues.append("Head is taller than the counterbore depth") + + return { + "ok": not issues, + "minimum_clearance": clearance_min, + "maximum_clearance": clearance_max, + "required_clearance": required, + "issues": issues, + } + + +def require_fit(**dimensions: float) -> dict: + """Fail a CQ-editor script, headless check or build on an unsafe fit.""" + + report = cylindrical_fit(**dimensions) + if not report["ok"]: + raise FitError("; ".join(report["issues"])) + return report diff --git a/worker/cq_worker/inspector.py b/worker/cq_worker/inspector.py new file mode 100644 index 000000000..83c269267 --- /dev/null +++ b/worker/cq_worker/inspector.py @@ -0,0 +1,128 @@ +"""CadQuery object stack inspection. + +A ``Workplane`` remembers the chain of workplanes that produced it through +its ``parent`` attribute. The inspector lists that chain newest first, with +the objects each step holds, and can tessellate a step or a single object so +the GUI can overlay it on the model. +""" + +from __future__ import annotations + +from typing import Any + +import cadquery as cq + +from .provenance import creation_line +from .tessellation import Tolerance, tessellate + +MAX_VALUE_LENGTH = 200 + + +def stack_frames(workplane: cq.Workplane) -> list[cq.Workplane]: + frames = [] + current: cq.Workplane | None = workplane + while current is not None and getattr(current, "parent", None) is not None: + frames.append(current) + current = current.parent + return frames + + +def describe_stack(frames: list[cq.Workplane]) -> list[dict]: + return [ + { + "type": type(frame).__name__, + "value": f"origin {_point(frame.plane.origin)}", + "line": creation_line(frame), + "items": [ + { + "type": type(obj).__name__, + "value": describe(obj), + "displayable": is_displayable(obj), + "line": creation_line(obj), + } + for obj in frame.objects + ], + } + for frame in frames + ] + + +def is_displayable(obj: Any) -> bool: + return isinstance(obj, cq.Shape) or isinstance(obj, cq.Sketch) + + +def describe(obj: Any) -> str: + """A short, human readable summary of a stack object.""" + + try: + if isinstance(obj, cq.Vector): + return _point(obj) + if isinstance(obj, cq.Location): + return f"at {_point(cq.Vector(*obj.toTuple()[0]))}" + if isinstance(obj, cq.Vertex): + return _point(cq.Vector(obj.toTuple())) + if isinstance(obj, cq.Edge): + return f"{obj.geomType().lower()}, length {_number(obj.Length())}" + if isinstance(obj, cq.Wire): + return f"{len(obj.Edges())} edges, length {_number(obj.Length())}" + if isinstance(obj, cq.Face): + return f"{obj.geomType().lower()}, area {_number(obj.Area())}" + if isinstance(obj, cq.Shape): + solids = obj.Solids() + if solids: + return f"{len(solids)} solid(s), volume {_number(obj.Volume())}" + return f"{len(obj.Faces())} faces, {len(obj.Edges())} edges" + if isinstance(obj, cq.Sketch): + return f"{len(list(obj))} faces" + except Exception: # fall back to the plain representation + pass + return _text(obj) + + +def frame_geometry(frame: cq.Workplane, item: int | None, tolerance: Tolerance) -> dict: + """Meshes for one stack frame (all its objects) or for one of its objects. + + Selecting a whole frame also reports its workplane, so the GUI can draw a + grid on it, sized after the frame's largest dimension. + """ + + objects = frame.objects if item is None else [frame.objects[item]] + meshes = [] + for obj in objects: + if not is_displayable(obj): + continue + shapes = list(obj) if isinstance(obj, cq.Sketch) else [obj] + for shape in shapes: + mesh = tessellate(shape.wrapped, tolerance) + if mesh is not None: + meshes.append(mesh.to_message()) + + plane = None + if item is None: + try: + size = float(frame.largestDimension()) + except Exception: # e.g. a workplane holding only points + size = 10.0 + p = frame.plane + plane = { + "origin": list(p.origin.toTuple()), + "x_dir": list(p.xDir.toTuple()), + "z_dir": list(p.zDir.toTuple()), + "size": size if size > 0 and size != float("inf") else 10.0, + } + return {"meshes": meshes, "plane": plane} + + +def _number(value: float) -> str: + return f"{value:.4g}" + + +def _point(vector: cq.Vector) -> str: + return "(" + ", ".join(_number(c) for c in vector.toTuple()) + ")" + + +def _text(value: Any) -> str: + text = str(value) + if len(text) <= MAX_VALUE_LENGTH: + return text + return text[: MAX_VALUE_LENGTH - 1] + "…" diff --git a/worker/cq_worker/interference.py b/worker/cq_worker/interference.py new file mode 100644 index 000000000..abc8e73bb --- /dev/null +++ b/worker/cq_worker/interference.py @@ -0,0 +1,345 @@ +"""Exact, world-space interference checks between displayed solid instances. + +The display mesh is deliberately never used as evidence of clearance. A +compound can be topologically valid while two of its solids occupy the same +space, so this analysis compares the solids individually. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +import cadquery as cq +from OCP.BRepExtrema import BRepExtrema_DistShapeShape + +from .measurement import exact_bounds +from .scene import Registry, RegistryEntry + + +@dataclass(frozen=True) +class SolidInstance: + key: str + name: str + part: int + solid: int + shape: cq.Solid + bounds: tuple[float, float, float, float, float, float] + source: int + placement: tuple[float, ...] + root: str + + def reference(self) -> dict: + return { + "key": self.key, + "name": self.name, + "part": self.part, + "solid": self.solid, + } + + +def _merged_names(assembly: cq.Assembly) -> list[str]: + names: list[str] = [] + + def visit(node: cq.Assembly, parents: tuple[str, ...]) -> None: + path = (*parents, node.name or "part") + if node.obj is not None: + names.append("/".join(path)) + for child in node.children: + visit(child, path) + + visit(assembly, ()) + return names + + +def collect_solids( + registry: Registry, + keys: list[str], + flat_parts: bool = False, + replacements: dict[str, cq.Shape] | None = None, +) -> list[SolidInstance]: + """Flatten actual solids, retaining each assembly occurrence and placement. + + The same source displayed independently and inside an assembly at the same + placement is a display alias, not an extra manufactured part. Two children + of one assembly remain distinct even if they use one source and location. + """ + + result: list[SolidInstance] = [] + visited: set[str] = set() + aliases: dict[tuple[int, tuple[float, ...]], str] = {} + + def visit(key: str, root: str) -> None: + if key in visited: + return + visited.add(key) + entry: RegistryEntry = registry.get(key) + replacement = (replacements or {}).get(key) + shapes = ( + [replacement] + if replacement is not None + else entry.part_shapes or ([entry.shape] if entry.shape is not None else []) + ) + names = ( + _merged_names(entry.obj) + if replacement is None + and entry.part_shapes + and isinstance(entry.obj, cq.Assembly) + else [entry.name or key] * len(shapes) + ) + for part, shape in enumerate(shapes): + if shape is None: + continue + source = entry.sources[part] if part < len(entry.sources) else None + identity = id(source.obj if source is not None else entry.obj) + location = source.location if source is not None else cq.Location() + placement = tuple(round(v, 12) for v in location_matrix(location)) + alias = (identity, placement) + if alias in aliases and aliases[alias] != root: + continue + aliases.setdefault(alias, root) + for solid_index, solid in enumerate(shape.Solids()): + bounds = exact_bounds(solid) + if not all(math.isfinite(value) for value in bounds): + raise ValueError(f"Non-finite bounds for {entry.name or key}") + result.append( + SolidInstance( + key, + names[part] if part < len(names) else entry.name or key, + part, + solid_index, + solid, + bounds, + identity, + placement, + root, + ) + ) + if not flat_parts: + for child in entry.children: + visit(child, root) + + for key in dict.fromkeys(keys): + visit(key, key) + return result + + +def location_matrix(location: cq.Location) -> list[float]: + """Rigid placement identity; the same convention as scene messages.""" + + transform = location.wrapped.Transformation() + return [ + transform.Value(row, column) for column in range(1, 5) for row in range(1, 4) + ] + + +def _candidate(first: SolidInstance, second: SolidInstance, margin: float) -> bool: + a, b = first.bounds, second.bounds + return all( + a[axis] <= b[axis + 3] + margin and b[axis] <= a[axis + 3] + margin + for axis in range(3) + ) + + +def _distance(first: cq.Shape, second: cq.Shape) -> float: + measure = BRepExtrema_DistShapeShape(first.wrapped, second.wrapped) + if not measure.IsDone() or measure.NbSolution() == 0: + raise ValueError("Open Cascade could not measure the pair") + return float(measure.Value()) + + +def inspect_pair(first: SolidInstance, second: SolidInstance, tolerance: float) -> dict: + """Classify a candidate using exact B-rep intersection and distance.""" + + report: dict[str, Any] = { + "first": first.reference(), + "second": second.reference(), + "kind": "inconclusive", + "overlap_volume": None, + "distance": None, + "point": None, + "reason": None, + } + try: + if not first.shape.isValid() or not second.shape.isValid(): + raise ValueError("A solid has invalid topology") + common = first.shape.intersect(second.shape) + if not common.isValid(): + raise ValueError("Open Cascade returned an invalid intersection") + volume = float(common.Volume()) + if not math.isfinite(volume) or volume < 0: + raise ValueError("Open Cascade returned an invalid overlap volume") + report["overlap_volume"] = volume + threshold = max( + tolerance**3, min(first.shape.Volume(), second.shape.Volume()) * 1e-12 + ) + if volume > threshold: + report["kind"] = "interference" + report["distance"] = 0.0 + center = common.Center() + point = [center.x, center.y, center.z] + if not all(math.isfinite(value) for value in point): + raise ValueError("Open Cascade returned a non-finite overlap center") + report["point"] = point + elif volume > 0: + report["reason"] = "Overlap is below the numerical tolerance" + else: + distance = _distance(first.shape, second.shape) + if not math.isfinite(distance): + raise ValueError("Open Cascade returned a non-finite distance") + report["distance"] = distance + report["kind"] = "contact" if distance <= tolerance else "clearance" + except (RuntimeError, ValueError, OverflowError) as error: + report["reason"] = str(error) + return report + + +def analyze_interferences( + registry: Registry, + keys: list[str], + *, + flat_parts: bool = False, + tolerance: float = 1e-6, + clearance: float = 0.0, + replacements: dict[str, cq.Shape] | None = None, + cancelled: Callable[[], bool] | None = None, +) -> list[dict]: + """Report nearby pairs; never claim a failed exact calculation is safe.""" + + if not math.isfinite(tolerance) or tolerance <= 0: + raise ValueError("Interference tolerance must be finite and positive") + if not math.isfinite(clearance) or clearance < 0: + raise ValueError("Clearance limit must be finite and non-negative") + parts = sorted( + collect_solids(registry, keys, flat_parts, replacements), + key=lambda part: part.bounds[0], + ) + active: list[SolidInstance] = [] + reports: list[dict] = [] + margin = max(tolerance, clearance) + for part in parts: + if cancelled is not None and cancelled(): + raise InterruptedError("Interference check cancelled") + active = [ + other for other in active if other.bounds[3] + margin >= part.bounds[0] + ] + for other in active: + if not _candidate(other, part, margin): + continue + report = inspect_pair(other, part, tolerance) + if report["kind"] != "clearance" or report["distance"] <= clearance: + reports.append(report) + active.append(part) + return reports + + +def overlap_shape(registry: Registry, first: dict, second: dict) -> cq.Shape: + """Rebuild the exact common volume for a reported pair of live solids.""" + + keys = list(dict.fromkeys((first["key"], second["key"]))) + instances = collect_solids(registry, keys) + + def resolve(reference: dict) -> SolidInstance: + matches = [ + instance + for instance in instances + if instance.key == reference["key"] + and instance.part == reference["part"] + and instance.solid == reference["solid"] + and instance.name == reference["name"] + ] + if len(matches) != 1: + raise ValueError("Interference pair is no longer in the live scene") + return matches[0] + + a, b = resolve(first), resolve(second) + if a is b: + raise ValueError("An interference pair must contain two distinct solids") + common = a.shape.intersect(b.shape) + volume = float(common.Volume()) + if not common.isValid() or not math.isfinite(volume) or volume <= 0: + raise ValueError("The pair has no valid positive shared volume") + return common + + +def apply_allowances( + registry: Registry, + keys: list[str], + reports: list[dict], + allowances: list[tuple[str, str, str]], + *, + flat_parts: bool = False, + replacements: dict[str, cq.Shape] | None = None, +) -> None: + """Mark only explicitly named, unambiguous interference pairs as accepted. + + A basename is accepted when it identifies exactly one solid. Full paths + from merged assemblies can disambiguate repeated names. Numerical failures + are never accepted, even if the pair was declared. + """ + + if not allowances: + return + instances = collect_solids(registry, keys, flat_parts, replacements) + + def resolve(name: str) -> SolidInstance | None: + matches = [instance for instance in instances if instance.name == name] + if not matches and "/" not in name: + matches = [ + instance + for instance in instances + if instance.name.rsplit("/", 1)[-1] == name + ] + if not matches: + return None + if len(matches) != 1: + raise ValueError( + f"Interference allowance {name!r} identifies {len(matches)} solids; " + "use unique part names or a full assembly path" + ) + return matches[0] + + accepted: dict[frozenset[tuple[str, int, int]], str] = {} + for first, second, reason in allowances: + a, b = resolve(first), resolve(second) + if a is None or b is None: + continue # A geometry check may cover only selected objects. + if a is b: + raise ValueError("An interference allowance must name two distinct solids") + pair = frozenset(((a.key, a.part, a.solid), (b.key, b.part, b.solid))) + if pair in accepted: + raise ValueError("An interference pair was declared more than once") + accepted[pair] = reason + for report in reports: + if report["kind"] != "interference": + continue + pair = frozenset( + ( + (side["key"], side["part"], side["solid"]) + for side in (report["first"], report["second"]) + ) + ) + if pair in accepted: + report["allowance_reason"] = accepted[pair] + + +def summarize(reports: list[dict]) -> dict: + """A tri-state verdict: numerical uncertainty must never count as safe.""" + + counts = { + kind: 0 for kind in ("interference", "inconclusive", "contact", "clearance") + } + for report in reports: + counts[report["kind"]] += 1 + accepted = sum( + report["kind"] == "interference" and bool(report.get("allowance_reason")) + for report in reports + ) + status = ( + "interference" + if counts["interference"] > accepted + else "inconclusive" if counts["inconclusive"] else "clear" + ) + return {"status": status, "counts": counts, "accepted": accepted} diff --git a/worker/cq_worker/measurement.py b/worker/cq_worker/measurement.py new file mode 100644 index 000000000..80c0be339 --- /dev/null +++ b/worker/cq_worker/measurement.py @@ -0,0 +1,383 @@ +"""Exact measurements on the live OCCT subshapes kept by the scene registry. + +The mesh is used only to decide what the user clicked. Every value returned +from this module is calculated from the corresponding OCCT shape, in world +coordinates, so tessellation tolerance and the viewer's ``f32`` coordinates +do not affect the result. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass +from typing import Any, Mapping + +import cadquery as cq +from OCP.Bnd import Bnd_Box +from OCP.BRepAdaptor import BRepAdaptor_Surface +from OCP.BRepBndLib import BRepBndLib +from OCP.BRepExtrema import BRepExtrema_DistShapeShape +from OCP.GeomAbs import GeomAbs_Cylinder, GeomAbs_Sphere +from OCP.TopoDS import TopoDS_Iterator + +from .scene import Registry + +#: Entities the GUI can select at once (``MAX_TOPOLOGY_SELECTIONS``). +MAX_SELECTIONS = 64 + + +class MeasurementError(ValueError): + """Invalid or stale topology selection supplied by the GUI.""" + + +@dataclass(frozen=True) +class TopologyReference: + key: str + part: int + kind: str + identifier: int + + @classmethod + def from_message(cls, value: Any) -> TopologyReference: + if not isinstance(value, Mapping): + raise MeasurementError("Each measurement selection must be an object") + key = value.get("key") + kind = value.get("kind") + part = value.get("part") + identifier = value.get("identifier") + if not isinstance(key, str) or not key: + raise MeasurementError("A measurement selection needs an object key") + if kind not in {"face", "edge", "vertex"}: + raise MeasurementError(f"Unknown topology kind {kind!r}") + if isinstance(part, bool) or not isinstance(part, int) or part < 0: + raise MeasurementError("Topology part must be a non-negative integer") + if ( + isinstance(identifier, bool) + or not isinstance(identifier, int) + or identifier < 1 + ): + raise MeasurementError("Topology identifier must be a positive integer") + return cls(key, part, kind, identifier) + + +def measure( + registry: Registry, raw_selections: Any, raw_objects: Any = None +) -> dict[str, Any]: + """Describe each selected entity; for exactly two, also their relationship. + Without entities, describe the selected objects instead.""" + + references, shapes = resolve(registry, raw_selections, raw_objects) + + result: dict[str, Any] = { + # OCCT's indexed subshape order is deterministic only for this live + # registry entry. It is deliberately not advertised as a persistent + # topological name after the model is rebuilt. + "identity": {"scope": "scene_entry", "persistent": False}, + "entities": ( + [ + _describe(reference, shape) + for reference, shape in zip(references, shapes, strict=True) + ] + if references + else [] + ), + "objects": ( + [] + if references + else [ + _describe_object(registry, key, shape) + for key, shape in zip(_object_keys(raw_objects), shapes, strict=True) + ] + ), + "pair": None, + # Of everything measured together. + "bounding_box": _bounds(*shapes), + } + if len(references) == 2: + result["pair"] = _describe_pair(shapes[0], shapes[1]) + return result + + +def resolve( + registry: Registry, raw_selections: Any, raw_objects: Any = None +) -> tuple[list[TopologyReference], list[cq.Shape]]: + """The picked entities, or else the selected objects, as world shapes.""" + + raw_selections = [] if raw_selections is None else raw_selections + if not isinstance(raw_selections, list) or len(raw_selections) > MAX_SELECTIONS: + raise MeasurementError( + f"Select between one and {MAX_SELECTIONS} topological entities to measure" + ) + if not raw_selections: + keys = _object_keys(raw_objects) + if not keys: + raise MeasurementError( + f"Select between one and {MAX_SELECTIONS} topological entities " + "or objects to measure" + ) + return [], [object_shape(registry, key) for key in keys] + + references = [TopologyReference.from_message(value) for value in raw_selections] + shapes = [] + for reference in references: + try: + shape = registry.get(reference.key).subshape( + reference.part, reference.kind, reference.identifier + ) + except (IndexError, KeyError, ValueError) as error: + raise MeasurementError(str(error)) from None + shapes.append(shape) + return references, shapes + + +def _object_keys(raw_objects: Any) -> list[str]: + if raw_objects is None: + return [] + if ( + not isinstance(raw_objects, list) + or len(raw_objects) > MAX_SELECTIONS + or not all(isinstance(key, str) and key for key in raw_objects) + ): + raise MeasurementError( + f"Objects to measure must be at most {MAX_SELECTIONS} scene keys" + ) + return raw_objects + + +def object_shape(registry: Registry, key: str) -> cq.Shape: + """An object and its assembly children as shown: placed in world + coordinates, and a compound of a single shape is that shape.""" + + try: + shapes = registry.subtree_shapes([key]) + except KeyError as error: + raise MeasurementError(error.args[0]) from None + if not shapes: + raise MeasurementError(f"Object {key!r} has no geometry to measure") + shape = shapes[0] if len(shapes) == 1 else cq.Compound.makeCompound(shapes) + while isinstance(shape, cq.Compound): + children = list(_children(shape)) + if len(children) != 1: + break + shape = children[0] + return shape + + +def _children(shape: cq.Shape) -> list[cq.Shape]: + children = [] + iterator = TopoDS_Iterator(shape.wrapped) + while iterator.More(): + children.append(cq.Shape.cast(iterator.Value())) + iterator.Next() + return children + + +def exact_bounds(shape: cq.Shape) -> tuple[float, float, float, float, float, float]: + """``(xmin, ymin, zmin, xmax, ymax, zmax)`` from the exact geometry. + + ``Shape.BoundingBox()`` uses the triangulation when the shape has one, + and every displayed shape has: a sphere of radius 5 then reports about + 5.04. This ignores the triangulation and the tolerances. + """ + + box = Bnd_Box() + BRepBndLib.AddOptimal_s(shape.wrapped, box, False, False) + # Bnd_Box.Get() returns a struct OCP 8 cannot convert; the corners are + # the same values in every version. + low, high = box.CornerMin(), box.CornerMax() + return (low.X(), low.Y(), low.Z(), high.X(), high.Y(), high.Z()) + + +def _bounds(*shapes: cq.Shape) -> dict[str, list[float]] | None: + if not shapes: + return None + lows, highs = [], [] + for shape in shapes: + bounds = exact_bounds(shape) + lows.append(bounds[:3]) + highs.append(bounds[3:]) + low = [min(axis) for axis in zip(*lows)] + high = [max(axis) for axis in zip(*highs)] + return { + "min": low, + "max": high, + "size": [b - a for a, b in zip(low, high)], + "center": [(a + b) / 2 for a, b in zip(low, high)], + } + + +def _material_mass(registry: Registry, key: str) -> tuple[float | None, list[str]]: + """Mass in grams from each displayed solid's assigned material.""" + entry = registry.get(key) + masses: list[float] = [] + names: list[str] = [] + incomplete = False + + def visit(current) -> None: + nonlocal incomplete + own = ( + zip(current.part_shapes, current.part_materials, strict=True) + if current.part_shapes + else [(current.shape, current.material)] + ) + for shape, material in own: + if shape is None or not shape.Solids(): + continue + factors = {"g/cm^3": 0.001, "kg/m^3": 0.000001, "g/mm^3": 1.0} + factor = factors.get(material.densityUnit) if material is not None else None + if factor is None or not math.isfinite(material.density): + incomplete = True + else: + masses.append(shape.Volume() * material.density * factor) + names.append(material.name) + for child in current.children: + visit(registry.get(child)) + + visit(entry) + return (sum(masses) if masses and not incomplete else None), sorted(set(names)) + + +def _describe_object(registry: Registry, key: str, shape: cq.Shape) -> dict[str, Any]: + solids = shape.Solids() + faces = shape.Faces() + edges = shape.Edges() + mass, materials = _material_mass(registry, key) + return { + "key": key, + "shape_type": shape.ShapeType().lower(), + "volume": float(shape.Volume()) if solids else None, + "area": float(shape.Area()) if faces else None, + "length": ( + float(sum(edge.Length() for edge in edges)) if edges and not faces else None + ), + "center": _point(shape.Center()), + "bounding_box": _bounds(shape), + "solids": len(solids), + "faces": len(faces), + "edges": len(edges), + "vertices": len(shape.Vertices()), + "mass_g": mass, + "materials": materials, + } + + +def _describe(reference: TopologyReference, shape: cq.Shape) -> dict[str, Any]: + geometry_type = shape.geomType().lower() + center = _point(shape.Center()) + result: dict[str, Any] = { + "key": reference.key, + "part": reference.part, + "kind": reference.kind, + "identifier": reference.identifier, + "geometry_type": geometry_type, + "center": center, + "position": center if reference.kind == "vertex" else None, + "length": ( + shape.Length() + if reference.kind == "edge" and isinstance(shape, cq.Edge) + else None + ), + "area": shape.Area() if reference.kind == "face" else None, + "radius": None, + "diameter": None, + "bounding_box": _bounds(shape), + } + radius = _radius(shape, reference.kind, geometry_type) + if radius is not None: + result["radius"] = radius + result["diameter"] = radius * 2.0 + return result + + +def _radius(shape: cq.Shape, kind: str, geometry_type: str) -> float | None: + if kind == "edge" and geometry_type == "circle" and isinstance(shape, cq.Edge): + return float(shape.radius()) + if kind != "face": + return None + + surface = BRepAdaptor_Surface(shape.wrapped) + surface_type = surface.GetType() + if surface_type == GeomAbs_Cylinder: + return float(surface.Cylinder().Radius()) + if surface_type == GeomAbs_Sphere: + return float(surface.Sphere().Radius()) + + # A circular planar face (disc) has a planar surface, so its radius lives + # on the boundary rather than on the surface adaptor. Return a radius + # only when all circular boundaries agree; an annulus is ambiguous. + radii = { + round(float(edge.radius()), 12) + for edge in shape.Edges() + if edge.geomType() == "CIRCLE" + } + return next(iter(radii)) if len(radii) == 1 else None + + +def _describe_pair(first: cq.Shape, second: cq.Shape) -> dict[str, Any]: + distance, first_point, second_point = _distance(first, second) + angle = _angle(first, second) + return { + "distance": distance, + "first_point": first_point, + "second_point": second_point, + "angle_degrees": angle[0] if angle else None, + "angle_kind": angle[1] if angle else None, + } + + +def _distance( + first: cq.Shape, second: cq.Shape +) -> tuple[float, list[float], list[float]]: + operation = BRepExtrema_DistShapeShape(first.wrapped, second.wrapped) + if not operation.IsDone() or operation.NbSolution() < 1: + raise MeasurementError("OCCT could not calculate the distance") + return ( + float(operation.Value()), + _point(operation.PointOnShape1(1)), + _point(operation.PointOnShape2(1)), + ) + + +def _angle(first: cq.Shape, second: cq.Shape) -> tuple[float, str] | None: + if isinstance(first, cq.Edge) and isinstance(second, cq.Edge): + if first.geomType() != "LINE" or second.geomType() != "LINE": + return None + return _vector_angle(first.tangentAt(), second.tangentAt()), "edge_edge" + if isinstance(first, cq.Face) and isinstance(second, cq.Face): + if first.geomType() != "PLANE" or second.geomType() != "PLANE": + return None + return _vector_angle(first.normalAt(), second.normalAt()), "face_face" + if isinstance(first, cq.Edge) and isinstance(second, cq.Face): + return _edge_face_angle(first, second) + if isinstance(first, cq.Face) and isinstance(second, cq.Edge): + return _edge_face_angle(second, first) + return None + + +def _edge_face_angle(edge: cq.Edge, face: cq.Face) -> tuple[float, str] | None: + if edge.geomType() != "LINE" or face.geomType() != "PLANE": + return None + tangent = edge.tangentAt().normalized() + normal = face.normalAt().normalized() + # An edge lying in the plane is 0 degrees; one normal to it is 90. + degrees = math.degrees(math.asin(abs(_clamped_dot(tangent, normal)))) + return degrees, "edge_face" + + +def _vector_angle(first: cq.Vector, second: cq.Vector) -> float: + # Lines and planes are unoriented geometric entities, so report the + # smaller angle regardless of edge direction or face orientation. + dot = abs(_clamped_dot(first.normalized(), second.normalized())) + return math.degrees(math.acos(dot)) + + +def _clamped_dot(first: cq.Vector, second: cq.Vector) -> float: + return max(-1.0, min(1.0, first.dot(second))) + + +def _point(value: Any) -> list[float]: + if hasattr(value, "toTuple"): + value = value.toTuple() + else: + value = (value.X(), value.Y(), value.Z()) + return [float(component) for component in value] diff --git a/worker/cq_worker/measurement_code.py b/worker/cq_worker/measurement_code.py new file mode 100644 index 000000000..85ff1de92 --- /dev/null +++ b/worker/cq_worker/measurement_code.py @@ -0,0 +1,374 @@ +"""*Copy as code* for the Measurements panel. + +The generated Python measures the same entities or objects again from the +script's own variables, with a selector for each picked entity, so it can +be pasted into the console or kept in the script. Every measured value is +written as a comment on its line. + +The code is executed on a copy of the console's namespace (which holds the +variables of the last run) and its results are compared with the exact +measurements before it is called verified. +""" + +from __future__ import annotations + +import math +from typing import Any + +import cadquery as cq + +from . import measurement, selection +from .measurement import TopologyReference +from .scene import Registry + +#: Relative and absolute agreement required between code and measurement. +TOLERANCE = 1e-9 + +_HELPER = '''\ +from OCP.Bnd import Bnd_Box +from OCP.BRepBndLib import BRepBndLib + + +def exact_bounds(shape): + """(xmin, ymin, zmin, xmax, ymax, zmax) of the exact geometry; shapes on + screen are meshed, and BoundingBox() would include the mesh.""" + box = Bnd_Box() + BRepBndLib.AddOptimal_s(shape.wrapped, box, False, False) + low, high = box.CornerMin(), box.CornerMax() + return (low.X(), low.Y(), low.Z(), high.X(), high.Y(), high.Z()) +''' + + +class _Code: + """Lines of code, with the value each assignment must produce.""" + + def __init__(self) -> None: + self.lines: list[str] = [] + self.expected: dict[str, Any] = {} + self.uses_math = False + self.uses_bounds = False + + def assign(self, name: str, expression: str, value: Any = None) -> None: + if value is None: + self.lines.append(f"{name} = {expression}") + return + self.lines.append(f"{name} = {expression} # {_text(value)}") + self.expected[name] = value + + def blank(self) -> None: + if self.lines and self.lines[-1]: + self.lines.append("") + + def text(self) -> str: + header = ["import math"] if self.uses_math else [] + if self.uses_bounds: + header += ([""] if header else []) + _HELPER.splitlines() + body = self.lines[:-1] if self.lines and not self.lines[-1] else self.lines + return "\n".join(header + ([""] if header else []) + body) + "\n" + + +def measurement_code( + registry: Registry, + namespace: dict[str, Any], + raw_selections: Any, + raw_objects: Any = None, +) -> dict[str, Any]: + """Code measuring the selection again, and whether it was verified.""" + + result = measurement.measure(registry, raw_selections, raw_objects) + references, _ = measurement.resolve(registry, raw_selections, raw_objects) + code = _Code() + problems: list[str] = [] + + if references: + names = [] + for number, (reference, entity) in enumerate( + zip(references, result["entities"], strict=True), start=1 + ): + names.append( + _entity(code, registry, namespace, reference, entity, number, problems) + ) + code.blank() + if result["pair"] is not None: + _pair(code, references, names, result["pair"]) + else: + for number, described in enumerate(result["objects"], start=1): + _object(code, registry, namespace, described, number, problems) + code.blank() + + text = code.text() + if problems: + return {"code": text, "verified": False, "problem": problems[0]} + problem = _verify(text, namespace, code.expected) + return {"code": text, "verified": problem is None, "problem": problem} + + +# -- entities --------------------------------------------------------------------- + + +def _entity( + code: _Code, + registry: Registry, + namespace: dict[str, Any], + reference: TopologyReference, + described: dict[str, Any], + number: int, + problems: list[str], +) -> str: + entry = registry.get(reference.key) + source = entry.sources[reference.part] + named = None + if reference.kind == "face" and isinstance(entry.obj, cq.Assembly): + attribute = next( + ( + item + for item in entry.face_attributes + if item["id"] == reference.identifier + ), + None, + ) + if attribute is not None and attribute.get("name"): + label = attribute["name"] + if list(entry.obj._subshape_names.values()).count(label) == 1: + assembly = _variable(namespace, entry.obj) or _assembly_path( + namespace, entry.obj + ) + if assembly is not None: + named = ( + f"next(face for face, name in {assembly}._subshape_names.items() " + f"if name == {label!r})" + ) + if named is not None: + expression = named + else: + receiver = _receiver(namespace, source.obj, problems) + candidate = selection.selector_candidates(registry, [_message(reference)])[ + "candidates" + ][0] + expression = receiver + candidate["expression"] + if isinstance(source.obj, cq.Workplane): + expression += ".val()" + expression += _placement(source.location) + name = f"{reference.kind}_{number}" + if named is None and candidate["index_based"]: + code.lines.append( + "# By index: this may name another entity once the model changes" + ) + code.assign(name, expression) + + if reference.kind == "face": + code.assign(f"area_{number}", f"{name}.Area()", described["area"]) + elif reference.kind == "edge": + code.assign(f"length_{number}", f"{name}.Length()", described["length"]) + if described["geometry_type"] == "circle": + code.assign(f"radius_{number}", f"{name}.radius()", described["radius"]) + if reference.kind == "vertex": + code.assign(f"point_{number}", f"{name}.toTuple()", described["position"]) + else: + code.assign(f"center_{number}", f"{name}.Center()", described["center"]) + box = described["bounding_box"] + code.uses_bounds = True + code.assign(f"bounds_{number}", f"exact_bounds({name})", [*box["min"], *box["max"]]) + return name + + +def _pair( + code: _Code, + references: list[TopologyReference], + names: list[str], + pair: dict[str, Any], +) -> None: + first, second = names + code.assign("distance", f"{first}.distance({second})", pair["distance"]) + kind = pair.get("angle_kind") + if kind is None: + return + code.uses_math = True + direction = {"edge": "tangentAt()", "face": "normalAt()"} + a = f"{first}.{direction[references[0].kind]}" + b = f"{second}.{direction[references[1].kind]}" + between = f"math.degrees({a}.getAngle({b}))" + if kind == "edge_face": + # 0 degrees for an edge lying in the plane, 90 for one normal to it. + code.assign("angle", f"abs(90 - {between})", pair["angle_degrees"]) + else: + # Lines and planes have no direction: the smaller angle. + code.assign("between", between) + code.assign("angle", "min(between, 180 - between)", pair["angle_degrees"]) + + +# -- objects ---------------------------------------------------------------------- + + +def _object( + code: _Code, + registry: Registry, + namespace: dict[str, Any], + described: dict[str, Any], + number: int, + problems: list[str], +) -> None: + entry = registry.get(described["key"]) + expression = _object_expression(entry, namespace, problems) + name = f"shape_{number}" + code.assign(name, expression) + if described["volume"] is not None: + code.assign(f"volume_{number}", f"{name}.Volume()", described["volume"]) + if described["area"] is not None: + code.assign(f"area_{number}", f"{name}.Area()", described["area"]) + code.assign(f"center_{number}", f"{name}.Center()", described["center"]) + box = described["bounding_box"] + code.uses_bounds = True + code.assign(f"bounds_{number}", f"exact_bounds({name})", [*box["min"], *box["max"]]) + + +def _object_expression(entry, namespace: dict[str, Any], problems: list[str]) -> str: + obj = entry.obj + if isinstance(obj, cq.Assembly): + if entry.children or len(entry.sources) != 1: + name = _variable(namespace, obj) or _assembly_path(namespace, obj) + if name is None: + problems.append("The assembly is not a variable of the script") + return "assembly.toCompound()" + # toCompound() applies the node's own location and its children's, + # not those of the assemblies above it. + above = ( + entry.sources[0].location * obj.loc.inverse if entry.sources else None + ) + return f"{name}.toCompound(){_placement(above) if above else ''}" + source = entry.sources[0] + return _shape_of(_receiver(namespace, source.obj, problems), source.obj) + ( + _placement(source.location) + ) + return _shape_of(_receiver(namespace, obj, problems), obj) + + +def _shape_of(receiver: str, obj: Any) -> str: + """One shape for what a shown object holds.""" + + if isinstance(obj, cq.Workplane): + shapes = [value for value in obj.vals() if isinstance(value, cq.Shape)] + if len(shapes) == 1 and len(obj.vals()) == 1: + return f"{receiver}.val()" + return ( + f"cq.Compound.makeCompound([v for v in {receiver}.vals() " + "if isinstance(v, cq.Shape)])" + ) + return receiver + + +# -- names and placements ----------------------------------------------------------- + + +def _receiver(namespace: dict[str, Any], obj: Any, problems: list[str]) -> str: + name = _variable(namespace, obj) or _assembly_path(namespace, obj) + if name is None: + problems.append( + f"The {type(obj).__name__} is not a variable of the script: " + "replace obj with an expression for it" + ) + return "obj" + return name + + +def _variable(namespace: dict[str, Any], obj: Any) -> str | None: + for name, value in namespace.items(): + if value is obj and name.isidentifier() and not name.startswith("_"): + return name + return None + + +def _assembly_path(namespace: dict[str, Any], obj: Any) -> str | None: + """``assembly.objects["name"].obj`` for an object added to an assembly + of the script without a variable of its own.""" + + for name, value in namespace.items(): + if not isinstance(value, cq.Assembly) or name.startswith("_"): + continue + for key, node in value.objects.items(): + if node is obj: + return f"{name}.objects[{key!r}]" + if node.obj is obj: + return f"{name}.objects[{key!r}].obj" + return None + + +def _placement(location: cq.Location) -> str: + translation, angles = location.toTuple() + if all(abs(value) < 1e-12 for value in angles): + if all(abs(value) < 1e-12 for value in translation): + return "" + return f".moved(cq.Location({_vector(translation)}))" + return f".moved(cq.Location({_vector(translation)}, {_vector(angles)}))" + + +def _vector(values) -> str: + return "(" + ", ".join(_number(value) for value in values) + ")" + + +def _number(value: float) -> str: + value = float(value) + # 29.999999999999993 degrees is 30 within rounding noise. + short = round(value, 6) + if math.isclose(short, value, rel_tol=1e-12, abs_tol=1e-12): + value = short + if value == 0: + return "0" + if value == int(value) and abs(value) < 1e15: + return str(int(value)) + return repr(value) + + +def _message(reference: TopologyReference) -> dict: + return { + "key": reference.key, + "part": reference.part, + "kind": reference.kind, + "identifier": reference.identifier, + } + + +# -- verification ----------------------------------------------------------------- + + +def _verify( + text: str, namespace: dict[str, Any], expected: dict[str, Any] +) -> str | None: + """``None`` when the code runs and reproduces every expected value.""" + + scope = dict(namespace) + try: + exec(compile(text, "", "exec"), scope) + except Exception as error: + return f"The code failed: {type(error).__name__}: {error}" + for name, value in expected.items(): + if not _close(scope.get(name), value): + return f"{name} came out as {_text(scope.get(name))}, not {_text(value)}" + return None + + +def _close(actual: Any, expected: Any) -> bool: + if isinstance(actual, cq.Vector): + actual = actual.toTuple() + if isinstance(expected, (list, tuple)): + if not isinstance(actual, (list, tuple)) or len(actual) != len(expected): + return False + return all(_close(a, e) for a, e in zip(actual, expected)) + try: + return math.isclose( + float(actual), float(expected), rel_tol=TOLERANCE, abs_tol=TOLERANCE + ) + except (TypeError, ValueError): + return False + + +def _text(value: Any) -> str: + if isinstance(value, cq.Vector): + value = value.toTuple() + if isinstance(value, (list, tuple)): + return "(" + ", ".join(_text(v) for v in value) + ")" + if isinstance(value, float): + # Exact geometry carries rounding noise such as 2.8e-17. + text = "0" if abs(value) < 1e-12 else f"{value:.10g}" + return text + return repr(value) diff --git a/worker/cq_worker/motion.py b/worker/cq_worker/motion.py new file mode 100644 index 000000000..e164af2fd --- /dev/null +++ b/worker/cq_worker/motion.py @@ -0,0 +1,209 @@ +"""Conservative collision certification along declared rigid-body motion. + +Each segment linearly interpolates translation and XYZ Euler angles. A +Lipschitz displacement bound certifies empty intervals; near contact, the +segment is subdivided. Exhausting the depth is *inconclusive*, never clear. +""" + +from __future__ import annotations + +import math +from collections.abc import Iterable +from typing import Any + +import cadquery as cq +from OCP.BRepExtrema import BRepExtrema_DistShapeShape + +from .measurement import exact_bounds +from .scene import to_compound + +Pose = tuple[float, float, float, float, float, float] + + +class PathError(ValueError): + """A declared assembly path is blocked or cannot be certified.""" + + +def _shape(value: cq.Shape | cq.Workplane | cq.Assembly) -> cq.Shape: + shape = value.toCompound() if isinstance(value, cq.Assembly) else to_compound(value) + if not shape.Solids() or not shape.isValid(): + raise ValueError("Path objects must contain valid closed solids") + return shape + + +def _pose(value: Iterable[float]) -> Pose: + numbers = tuple(float(component) for component in value) + if len(numbers) != 6 or not all(math.isfinite(number) for number in numbers): + raise ValueError("Each pose must contain finite x, y, z, rx, ry, rz") + return numbers # type: ignore[return-value] + + +def _placed(shape: cq.Shape, pose: Pose) -> cq.Shape: + return shape.moved(cq.Location(pose[:3], pose[3:])) + + +def _distance(first: cq.Shape, second: cq.Shape) -> float: + operation = BRepExtrema_DistShapeShape(first.wrapped, second.wrapped) + if not operation.IsDone() or operation.NbSolution() == 0: + raise ValueError("Open Cascade could not measure a path position") + result = float(operation.Value()) + if not math.isfinite(result): + raise ValueError("Open Cascade returned a non-finite path distance") + return result + + +def _radius(shape: cq.Shape) -> float: + x0, y0, z0, x1, y1, z1 = exact_bounds(shape) + return math.sqrt( + max(x0 * x0, x1 * x1) + max(y0 * y0, y1 * y1) + max(z0 * z0, z1 * z1) + ) + + +def _bounds_overlap( + first: tuple[float, float, float, float, float, float], + second: tuple[float, float, float, float, float, float], + margin: float, +) -> bool: + return all( + first[axis] <= second[axis + 3] + margin + and second[axis] <= first[axis + 3] + margin + for axis in range(3) + ) + + +def _midpoint(first: Pose, second: Pose) -> Pose: + return tuple((a + b) / 2 for a, b in zip(first, second, strict=True)) # type: ignore[return-value] + + +def _motion_bound(first: Pose, second: Pose, radius: float) -> float: + translation = math.dist(first[:3], second[:3]) + angles = sum(abs(b - a) for a, b in zip(first[3:], second[3:], strict=True)) + return (translation + radius * math.radians(angles)) / 2 + + +def trace_path( + moving: cq.Shape | cq.Workplane | cq.Assembly, + obstacles: Iterable[cq.Shape | cq.Workplane | cq.Assembly], + poses: Iterable[Iterable[float]], + *, + required_clearance: float = 0.0, + tolerance: float = 1e-6, + max_depth: int = 18, + max_poses: int = 4096, +) -> dict[str, Any]: + """Certify a path or find an intersection, with no unsafe success guess. + + Positions use model units and Euler angles use degrees. The source solid + is local to the path origin; obstacles are fixed in world coordinates. + """ + + body = _shape(moving) + fixed = [_shape(obstacle) for obstacle in obstacles] + fixed_bounds = [exact_bounds(obstacle) for obstacle in fixed] + route = [_pose(pose) for pose in poses] + if len(route) < 2: + raise ValueError("A path needs at least two poses") + if not math.isfinite(required_clearance) or required_clearance < 0: + raise ValueError("Required clearance must be finite and non-negative") + if not math.isfinite(tolerance) or tolerance <= 0: + raise ValueError("Path tolerance must be finite and positive") + if ( + isinstance(max_depth, bool) + or not isinstance(max_depth, int) + or not 0 <= max_depth <= 24 + ): + raise ValueError("max_depth must be an integer between 0 and 24") + if isinstance(max_poses, bool) or not isinstance(max_poses, int) or max_poses < 3: + raise ValueError("max_poses must be an integer of at least 3") + + radius = _radius(body) + checked = 0 + cache: dict[Pose, tuple[float, dict[str, Any] | None]] = {} + + def probe(pose: Pose) -> tuple[float, dict[str, Any] | None]: + nonlocal checked + if pose in cache: + return cache[pose] + if checked >= max_poses: + raise ValueError("Path pose budget exhausted") + placed = _placed(body, pose) + placed_bounds = exact_bounds(placed) + closest = math.inf + collision = None + for index, (obstacle, bounds) in enumerate( + zip(fixed, fixed_bounds, strict=True) + ): + if _bounds_overlap(placed_bounds, bounds, tolerance): + common = placed.intersect(obstacle) + if not common.isValid(): + raise ValueError( + "Open Cascade returned an invalid path intersection" + ) + volume = float(common.Volume()) + if not math.isfinite(volume): + raise ValueError( + "Open Cascade returned a non-finite overlap volume" + ) + if volume > tolerance**3: + collision = {"obstacle": index, "overlap_volume": volume} + break + if volume > 0: + raise ValueError("Path overlap is below numerical tolerance") + distance = _distance(placed, obstacle) + closest = min(closest, distance) + checked += 1 + cache[pose] = closest, collision + return cache[pose] + + for segment, (start, end) in enumerate(zip(route, route[1:])): + try: + for endpoint in (start, end): + _, collision = probe(endpoint) + if collision is not None: + return { + "status": "blocked", + "segment": segment, + "pose": endpoint, + "checked_poses": checked, + **collision, + } + + def certify(a: Pose, b: Pose, depth: int) -> dict[str, Any] | None: + middle = _midpoint(a, b) + distance, collision = probe(middle) + if collision is not None: + return {"status": "blocked", "pose": middle, **collision} + # Distance can decrease by no more than the maximum motion of + # a point on the body from the midpoint to any intermediate pose. + if distance > required_clearance + tolerance + _motion_bound( + a, b, radius + ): + return None + if depth >= max_depth: + return { + "status": "inconclusive", + "pose": middle, + "minimum_distance": distance, + } + return certify(a, middle, depth + 1) or certify(middle, b, depth + 1) + + finding = certify(start, end, 0) + if finding is not None: + return {"segment": segment, "checked_poses": checked, **finding} + except (RuntimeError, ValueError, OverflowError) as error: + return { + "status": "inconclusive", + "segment": segment, + "checked_poses": checked, + "reason": str(error), + } + return {"status": "clear", "segments": len(route) - 1, "checked_poses": checked} + + +def require_clear_path(*args: Any, **kwargs: Any) -> dict[str, Any]: + """Make a CQ-editor script and headless build fail on an unsafe path.""" + + report = trace_path(*args, **kwargs) + if report["status"] != "clear": + raise PathError(f"Assembly path {report['status']}: {report}") + return report diff --git a/worker/cq_worker/navigation.py b/worker/cq_worker/navigation.py new file mode 100644 index 000000000..652a38736 --- /dev/null +++ b/worker/cq_worker/navigation.py @@ -0,0 +1,121 @@ +"""Static navigation of the editor's unsaved Python source. + +Jedi reads source and project files but never executes the CAD script. The +outline uses the standard library so it remains available without Jedi. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +try: + import jedi +except ImportError: # optional editor service + jedi = None + +MAX_LOCATIONS = 200 +MAX_SYMBOLS = 500 + + +def outline(source: str) -> list[dict]: + try: + tree = ast.parse(source) + except SyntaxError: + return [] + symbols: list[dict] = [] + + def visit(body: list[ast.stmt], depth: int = 0) -> None: + for node in body: + if len(symbols) >= MAX_SYMBOLS: + return + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + kind = "class" if isinstance(node, ast.ClassDef) else "function" + symbols.append( + { + "name": node.name, + "kind": kind, + "line": node.lineno, + "depth": depth, + } + ) + visit(node.body, depth + 1) + elif depth == 0 and isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = ( + node.targets if isinstance(node, ast.Assign) else [node.target] + ) + for target in targets: + if isinstance(target, ast.Name) and len(symbols) < MAX_SYMBOLS: + symbols.append( + { + "name": target.id, + "kind": "variable", + "line": node.lineno, + "depth": 0, + } + ) + + visit(tree.body) + return symbols + + +def navigate( + source: str, + path: str | None, + project_root: str | None, + line: int, + column: int, + mode: str, +) -> dict: + if mode not in {"definition", "references"}: + raise ValueError("Unknown navigation mode") + if jedi is None: + return {"available": False, "locations": [], "truncated": False} + lines = source.splitlines() + if line < 1 or line > len(lines) or column < 0 or column > len(lines[line - 1]): + return {"available": True, "locations": [], "truncated": False} + + current = Path(path).resolve() if path else None + root = Path(project_root).resolve() if project_root else None + # A stable path is needed for relative imports and references. This + # synthetic name is never returned as a file to open. + script_path = current or (root or Path.cwd()) / "__cq_untitled__.py" + project = jedi.Project(str(root or script_path.parent)) + script = jedi.Script(source, path=script_path, project=project) + if mode == "definition": + names = script.goto(line, column, follow_imports=True) + else: + names = script.get_references(line, column, include_builtins=False) + + locations: list[dict] = [] + seen: set[tuple[str | None, int, int]] = set() + truncated = False + for name in names: + module = getattr(name, "module_path", None) + if module is None or not name.line: + continue + resolved = Path(module).resolve() + if mode == "references" and root and not resolved.is_relative_to(root): + continue + if resolved != script_path and ( + not resolved.is_file() or resolved.suffix != ".py" + ): + continue + target = None if resolved == script_path else str(resolved) + location = (target, name.line, name.column or 0) + if location in seen: + continue + seen.add(location) + if len(locations) == MAX_LOCATIONS: + truncated = True + break + locations.append( + { + "name": name.name, + "kind": name.type, + "path": target, + "line": name.line, + "column": name.column or 0, + } + ) + return {"available": True, "locations": locations, "truncated": truncated} diff --git a/worker/cq_worker/network.py b/worker/cq_worker/network.py new file mode 100644 index 000000000..4c2728a28 --- /dev/null +++ b/worker/cq_worker/network.py @@ -0,0 +1,118 @@ +"""Model upload and release checks (CadQuery's and CQ-editor's), using only +the standard library.""" + +from __future__ import annotations + +import json +import re +import urllib.request +import uuid + +USER_AGENT = "CQ-editor" +TIMEOUT = 60 +RELEASES_URL = "https://api.github.com/repos/{org}/{project}/releases" +#: Enough for an upload service's useful acknowledgement while keeping the +#: reply comfortably below the control-message limit after JSON escaping. +MAX_UPLOAD_RESPONSE_BYTES = 256 * 1024 +#: GitHub's release list is small; a larger response is malformed or unsafe. +MAX_RELEASES_RESPONSE_BYTES = 2 * 1024 * 1024 +#: Where CQ-editor is published. +EDITOR_ORG, EDITOR_PROJECT = "igors93", "CQ-editor" + + +def upload(url: str, data: bytes, file_name: str) -> dict: + """POST ``data`` as the multipart form field ``file``.""" + + boundary = uuid.uuid4().hex + body = b"".join( + ( + f"--{boundary}\r\n".encode(), + f'Content-Disposition: form-data; name="file"; filename="{file_name}"\r\n'.encode(), + b"Content-Type: application/octet-stream\r\n\r\n", + data, + f"\r\n--{boundary}--\r\n".encode(), + ) + ) + request = urllib.request.Request( + url, + data=body, + method="POST", + headers={ + "Content-Type": f"multipart/form-data; boundary={boundary}", + "User-Agent": USER_AGENT, + }, + ) + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: + raw = response.read(MAX_UPLOAD_RESPONSE_BYTES + 1) + truncated = len(raw) > MAX_UPLOAD_RESPONSE_BYTES + body_text = raw[:MAX_UPLOAD_RESPONSE_BYTES].decode("utf-8", errors="replace") + if truncated: + body_text += ( + "\n[response truncated after " f"{MAX_UPLOAD_RESPONSE_BYTES} bytes]" + ) + return { + "status": response.status, + "body": body_text, + } + + +def newer_releases( + current: str, org: str = "cadquery", project: str = "cadquery" +) -> list[str]: + """Published release tags newer than ``current``.""" + + return [ + release["tag_name"] + for release in _releases(org, project) + if not release.get("draft") + and _version_key(release["tag_name"]) > _version_key(current) + ] + + +def editor_releases(current: str) -> list[dict]: + """CQ-editor's releases newer than ``current``, newest first, each with + its ``tag``, ``name`` and ``url`` (the page with the installers). Drafts + and pre-releases are left out.""" + + newer = [ + release + for release in _releases(EDITOR_ORG, EDITOR_PROJECT) + if not release.get("draft") + and not release.get("prerelease") + and _version_key(release["tag_name"]) > _version_key(current) + ] + newer.sort(key=lambda release: _version_key(release["tag_name"]), reverse=True) + page = f"https://github.com/{EDITOR_ORG}/{EDITOR_PROJECT}/releases/tag/" + return [ + { + "tag": release["tag_name"], + "name": release.get("name") or release["tag_name"], + "url": release.get("html_url") or page + release["tag_name"], + } + for release in newer + ] + + +def _releases(org: str, project: str) -> list[dict]: + request = urllib.request.Request( + RELEASES_URL.format(org=org, project=project), + headers={"User-Agent": USER_AGENT}, + ) + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: + data = response.read(MAX_RELEASES_RESPONSE_BYTES + 1) + if len(data) > MAX_RELEASES_RESPONSE_BYTES: + raise ValueError( + "Release response exceeds " f"{MAX_RELEASES_RESPONSE_BYTES} bytes" + ) + releases = json.loads(data) + if not isinstance(releases, list): + raise ValueError("Release response must be a JSON list") + return releases + + +def _version_key(version: str) -> tuple[int, int, int]: + """``"v2.4.0"`` -> ``(2, 4, 0)``; pre-release suffixes are ignored.""" + + numbers = [int(n) for n in re.findall(r"\d+", version)[:3]] + padded = numbers + [0] * (3 - len(numbers)) + return padded[0], padded[1], padded[2] diff --git a/worker/cq_worker/profiling.py b/worker/cq_worker/profiling.py new file mode 100644 index 000000000..2df5875d5 --- /dev/null +++ b/worker/cq_worker/profiling.py @@ -0,0 +1,190 @@ +"""Per-line profiling of a script run (FEAT-E2). + +``sys.settrace`` follows the editor buffer and project modules line by line: the +time between two events of a frame goes to the line that was running, with +everything that line called, so a line's time is all the time it cost. Calls +from the script straight into CadQuery are also timed, per function, as the +line's *operations*. Code outside the project is not traced line by line, +which keeps the overhead to one Python call per function call. +""" + +from __future__ import annotations + +import linecache +import os +import sys +import time +import types +from collections import defaultdict +from typing import Any + +import cadquery + +#: CadQuery's own files: calls into them are operations. +_CADQUERY = os.path.dirname(os.path.abspath(cadquery.__file__)) + os.sep +#: Operations reported per line, the slowest first. +OPERATIONS_PER_LINE = 8 + + +class LineProfiler: + """Runs a script and measures it; :meth:`result` is the profile.""" + + def __init__(self, filename: str, project_root: str | None = None) -> None: + self.filename = filename + self.project_root = ( + os.path.normcase(os.path.realpath(project_root)) if project_root else None + ) + #: (file, line) -> [seconds, times it started] + self._lines: defaultdict[tuple[str, int], list] = defaultdict(lambda: [0.0, 0]) + #: (file, line, function) -> [seconds, calls] + self._operations: defaultdict[tuple[str, int, str], list] = defaultdict( + lambda: [0.0, 0] + ) + #: Script frames being run -> [file, line, since] + self._running: dict[types.FrameType, list] = {} + self._sources: dict[str, str] = {} + self._paths: dict[str, str] = {} + self._traceable: dict[str, bool] = {} + + def _source_path(self, path: str) -> str: + if path not in self._paths: + self._paths[path] = ( + self.filename + if path == self.filename + else os.path.normcase(os.path.realpath(path)) + ) + return self._paths[path] + + def _traced(self, path: str) -> bool: + if path in self._traceable: + return self._traceable[path] + result = self._in_project(path) + self._traceable[path] = result + return result + + def _in_project(self, path: str) -> bool: + if path == self.filename: + return True + if self.project_root is None: + return False + try: + if os.path.commonpath((self.project_root, path)) != self.project_root: + return False + for prefix in (sys.prefix, sys.base_prefix, sys.exec_prefix): + prefix = os.path.normcase(os.path.realpath(prefix)) + if os.path.commonpath((prefix, path)) == prefix: + return False + return "site-packages" not in path.split(os.sep) + except ValueError: + return False + + def run(self, code: types.CodeType, namespace: dict) -> None: + """Executes ``code`` like ``exec``, measuring it.""" + + previous = sys.gettrace() + sys.settrace(self._call) + try: + exec(code, namespace) + finally: + sys.settrace(previous) + # Frames left without a return event (none in practice). + now = time.perf_counter() + for path, line, since in self._running.values(): + if line is not None: + self._lines[(path, line)][0] += now - since + self._running.clear() + + def result(self) -> dict[str, Any]: + """``lines`` (line, seconds, hits) in line order and, per line, its + slowest ``operations`` (line, name, seconds, calls).""" + + operations: defaultdict[tuple[str, int], list] = defaultdict(list) + for (path, line, name), (seconds, calls) in self._operations.items(): + operations[(path, line)].append( + { + "file": None if path == self.filename else path, + "line": line, + "name": name, + "seconds": seconds, + "calls": calls, + } + ) + slowest = [] + for key in sorted(operations): + ranked = sorted(operations[key], key=lambda op: op["seconds"], reverse=True) + slowest.extend(ranked[:OPERATIONS_PER_LINE]) + return { + "lines": [ + { + "file": None if path == self.filename else path, + "line": line, + "seconds": seconds, + "hits": hits, + } + for (path, line), (seconds, hits) in sorted(self._lines.items()) + if hits + ], + "operations": slowest, + "sources": self._sources, + } + + def _call(self, frame: types.FrameType, event: str, arg: Any): + """The global trace function: picks the frames worth following.""" + + if event != "call": + return None + code = frame.f_code + path = self._source_path(code.co_filename) + if self._traced(path): + self._running[frame] = [path, None, time.perf_counter()] + if path != self.filename and path not in self._sources: + linecache.checkcache(path) + source = "".join(linecache.getlines(path)) + if len(source) <= 2_000_000: + self._sources[path] = source + return self._line + caller = frame.f_back + if ( + caller is not None + and caller in self._running + and code.co_filename.startswith(_CADQUERY) + ): + return self._operation( + frame, self._running[caller][0], caller.f_lineno, code + ) + return None + + def _line(self, frame: types.FrameType, event: str, arg: Any): + """A script frame's trace function: time goes to the running line.""" + + now = time.perf_counter() + running = self._running.get(frame) + if running is None: + return self._line + path, line, since = running + if line is not None: + self._lines[(path, line)][0] += now - since + running[2] = now + if event == "line": + running[1] = frame.f_lineno + self._lines[(path, frame.f_lineno)][1] += 1 + elif event == "return": + del self._running[frame] + return self._line + + def _operation( + self, frame: types.FrameType, path: str, line: int, code: types.CodeType + ): + # Its own lines are not followed, only its return. + frame.f_trace_lines = False + name = code.co_qualname + started = time.perf_counter() + + def returned(frame: types.FrameType, event: str, arg: Any): + if event == "return": + stats = self._operations[(path, line, name)] + stats[0] += time.perf_counter() - started + stats[1] += 1 + return returned + + return returned diff --git a/worker/cq_worker/protocol.py b/worker/cq_worker/protocol.py new file mode 100644 index 000000000..166dbe454 --- /dev/null +++ b/worker/cq_worker/protocol.py @@ -0,0 +1,384 @@ +"""Line-delimited JSON transport between the CQ-editor GUI and the worker. + +Requests arrive on stdin, one JSON object per line. Replies and events leave +through a private duplicate of the original stdout descriptor, also one JSON +object per line. + +The worker handles one request at a time, but ``cancel`` and ``interrupt`` +requests must reach it while it is busy: :meth:`Channel.cancel_requested` and +the watcher of :meth:`Channel.interruptible` read, without waiting, whatever +the GUI sent meanwhile, record cancellations and interruptions and keep the +other requests, in order, for :meth:`Channel.receive`. Nothing ever blocks +reading stdin besides :meth:`Channel.receive` itself: on Windows, a thread +blocked there would also block DLL loading. + +User scripts and native libraries are free to print: descriptor 1 is pointed +at stderr (which the GUI shows in its log), and the Python-level +``sys.stdout`` / ``sys.stderr`` are replaced by :class:`OutputStream` objects +that forward text as ``output`` messages tagged with the request that +produced them. +""" + +from __future__ import annotations + +import collections +import contextlib +import io +import json +import os +import signal +import sys +import threading +import time +from collections.abc import Iterator +from typing import Any, BinaryIO, cast + +Message = dict[str, Any] + +#: Bumped whenever the message format changes incompatibly. +PROTOCOL_VERSION = 13 + +#: How often an interruptible request looks for an ``interrupt`` request. +INTERRUPT_POLL_SECONDS = 0.05 + +#: Captured output is sent regularly even when a script never writes ``\n``. +OUTPUT_CHUNK_CHARS = 64 * 1024 +#: A runaway script cannot fill the GUI and its protocol queue indefinitely. +OUTPUT_CAPTURE_CHARS = 1024 * 1024 +#: One Python logging record may include a traceback, but not arbitrary data. +LOG_MESSAGE_CHARS = 256 * 1024 +#: Repeated logging calls share a per-request ceiling as well. +LOG_CAPTURE_CHARS = 1024 * 1024 + +_UNSET = object() + + +def truncate_text(text: str, limit: int, kind: str) -> str: + """Keep a text protocol field bounded and make the data loss explicit.""" + + if len(text) <= limit: + return text + return text[:limit] + f"\n[{kind} truncated after {limit} characters]\n" + + +class Channel: + """Bidirectional message pipe to the GUI.""" + + def __init__(self, reader: BinaryIO, writer: BinaryIO) -> None: + self._reader = reader + self._writer = writer + self._lock = threading.Lock() + #: Id of the request being handled; attached to output and log messages. + self.current_id: int | None = None + #: Requests the GUI asked to cancel, or to interrupt. + self._cancelled: set[Any] = set() + self._interrupted: set[Any] = set() + #: Requests (or the errors parsing them) read ahead while polling, + #: in arrival order. + self._pending: collections.deque[Message | Exception] = collections.deque() + self._partial = b"" + self._ended = False + #: Guards the reading state: an interruptible request's watcher + #: polls from its own thread. + self._read_lock = threading.Lock() + #: The main thread is blocked reading; nobody else may read then. + self._receiving = False + # Streams with a descriptor are read with os.read, so that what was + # read is never hidden in a buffered reader's buffer; others (tests) + # are read line by line and never polled. + try: + self._fd: int | None = reader.fileno() + except (AttributeError, OSError, io.UnsupportedOperation): + self._fd = None + + @classmethod + def from_std_streams(cls) -> Channel: + """Take over the process' standard streams for the protocol.""" + + sys.stdout.flush() + protocol_fd = os.dup(1) + # Anything written to descriptor 1 from now on (OpenCascade warnings, + # C extensions, child processes) lands in stderr instead of + # corrupting the message stream. + os.dup2(2, 1) + return cls(sys.stdin.buffer, os.fdopen(protocol_fd, "wb")) + + def send(self, message: Message) -> None: + data = json.dumps( + message, ensure_ascii=False, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + with self._lock: + self._writer.write(data + b"\n") + self._writer.flush() + + def receive(self) -> Message | None: + """Block until the next request arrives; ``None`` once the GUI is gone.""" + + while True: + with self._read_lock: + if self._pending: + message = self._pending.popleft() + if isinstance(message, Exception): + raise message + return message + if self._ended: + return None + self._receiving = True + data = b"" + try: + if self._fd is None: + data = self._reader.readline() + else: + data = os.read(self._fd, 65536) + finally: + with self._read_lock: + self._receiving = False + if self._fd is None: + if data: + self._take_line(data) + else: + self._ended = True + else: + self._take(data) + + def cancel_requested(self, request_id: Any) -> bool: + """Whether the GUI cancelled ``request_id``, reading without waiting + whatever it has sent meanwhile.""" + + self._poll() + return request_id in self._cancelled + + def forget_cancel(self, request_id: Any) -> None: + self._cancelled.discard(request_id) + + def interrupt_requested(self, request_id: Any) -> bool: + """Whether the GUI asked to interrupt ``request_id``, reading without + waiting whatever it has sent meanwhile.""" + + self._poll() + return request_id in self._interrupted + + @contextlib.contextmanager + def interruptible(self, request_id: Any) -> Iterator[None]: + """While handling ``request_id``, an ``interrupt`` request raises + ``KeyboardInterrupt`` in the main thread, as Ctrl+C would: pure + Python code stops at once, native code when it returns to Python. + + A thread polls for it every :data:`INTERRUPT_POLL_SECONDS`. An + interrupt raised after the request ended is absorbed here, so it + can never land in the next one.""" + + stop = threading.Event() + + def watch() -> None: + while not stop.wait(INTERRUPT_POLL_SECONDS): + if self.interrupt_requested(request_id): + _interrupt_main_thread() + return + + watcher = threading.Thread(target=watch, name="interrupts", daemon=True) + watcher.start() + try: + yield + finally: + while True: + try: + stop.set() + watcher.join() + # Raises an interrupt the watcher sent too late. + time.sleep(0) + break + except KeyboardInterrupt: + continue + self._interrupted.discard(request_id) + + def _poll(self) -> None: + with self._read_lock: + while not self._ended and not self._receiving and self._fd is not None: + available = _bytes_available(self._fd) + if available == 0: + return + self._take(os.read(self._fd, max(available, 1))) + + def _take(self, data: bytes) -> None: + if not data: + self._ended = True + if self._partial.strip(): + self._take_line(self._partial) + self._partial = b"" + return + *lines, self._partial = (self._partial + data).split(b"\n") + for line in lines: + self._take_line(line) + + def _take_line(self, line: bytes) -> None: + """Records a cancellation or an interruption at once; queues + anything else.""" + + line = line.strip() + if not line: + return + try: + message = json.loads(line) + except ValueError as error: + self._pending.append(error) + return + command = message.get("cmd") if isinstance(message, dict) else None + if command == "cancel": + self._cancelled.add(message.get("target")) + elif command == "interrupt": + self._interrupted.add(message.get("target")) + else: + self._pending.append(message) + + +def _interrupt_main_thread() -> None: + """Sends SIGINT to the main thread, as Ctrl+C would: Python raises + ``KeyboardInterrupt`` there, and waits such as ``time.sleep`` wake up. + + ``_thread.interrupt_main`` is not enough: on Windows it does not set the + event those waits watch, which only the C signal handler does.""" + + if os.name == "nt": + # Runs the handler in this thread; Python acts on it in the main one. + signal.raise_signal(signal.SIGINT) + else: + # The main thread itself, so its blocking calls return with EINTR. + main_ident = threading.main_thread().ident + if main_ident is not None: + getattr(signal, "pthread_kill")(main_ident, signal.SIGINT) + + +def _bytes_available(fd: int) -> int: + """How much can be read from ``fd`` right away (1 at the end of the + stream, which reads as empty); 0 when that cannot be told. A thread + blocked reading stdin is not an option on Windows: loading a DLL then + waits for that read to finish.""" + + if os.name == "nt": + try: + import _winapi + import msvcrt + + # Python versions disagree on the number of trailing values; + # the first is the byte count available without blocking. + available = _winapi.PeekNamedPipe(msvcrt.get_osfhandle(fd), 0)[0] # type: ignore[attr-defined] + return cast(int, available) + except OSError as error: + # The other end is closed: the next read reports the end. + return 1 if getattr(error, "winerror", None) == 109 else 0 + import select + + try: + readable, _, _ = select.select([fd], [], [], 0) + except (OSError, ValueError): + return 0 + return 1 if readable else 0 + + +class OutputStream(io.TextIOBase): + """Text stream that forwards writes to the GUI as ``output`` messages. + + Text is buffered until a newline, an explicit flush or the chunk limit. + Each request also has a total capture limit so runaway output cannot grow + the worker, protocol queue or GUI indefinitely. + """ + + def __init__(self, channel: Channel, name: str) -> None: + super().__init__() + self._channel = channel + self._name = name + self._pending: list[str] = [] + self._pending_chars = 0 + self._captured_chars = 0 + self._request_id: int | None | object = _UNSET + self._truncated = False + self._lock = threading.RLock() + + @property + def encoding(self) -> str: # type: ignore[override] + return "utf-8" + + def writable(self) -> bool: + return True + + def write(self, text: str) -> int: + if not isinstance(text, str): + raise TypeError(f"write() argument must be str, not {type(text).__name__}") + if not text: + return 0 + with self._lock: + self._sync_request() + if self._truncated: + return len(text) + + remaining = OUTPUT_CAPTURE_CHARS - self._captured_chars + accepted = text[:remaining] + was_truncated = len(text) > len(accepted) + self._captured_chars += len(accepted) + while accepted: + room = OUTPUT_CHUNK_CHARS - self._pending_chars + part, accepted = accepted[:room], accepted[room:] + self._pending.append(part) + self._pending_chars += len(part) + if "\n" in part or self._pending_chars == OUTPUT_CHUNK_CHARS: + self._flush_pending() + + if was_truncated: + self._truncate() + return len(text) + + def flush(self) -> None: + with self._lock: + self._sync_request() + self._flush_pending() + + def _sync_request(self) -> None: + request_id = self._channel.current_id + if self._request_id is _UNSET: + self._request_id = request_id + elif self._request_id != request_id: + self._flush_pending() + self._request_id = request_id + self._captured_chars = 0 + self._truncated = False + + def _truncate(self) -> None: + self._flush_pending() + self._send( + f"\n[output truncated after {OUTPUT_CAPTURE_CHARS} characters; " + "further characters from this request were discarded]\n" + ) + self._truncated = True + + def _flush_pending(self) -> None: + if not self._pending: + return + text = "".join(self._pending) + self._pending.clear() + self._pending_chars = 0 + self._send(text) + + def _send(self, text: str) -> None: + try: + self._channel.send( + { + "type": "output", + "id": self._request_id, + "stream": self._name, + "text": text, + } + ) + except (OSError, ValueError): + # The GUI side is gone (typically during interpreter shutdown). + pass + + +def redirect_std_streams(channel: Channel) -> None: + """Route Python-level standard streams through the protocol.""" + + sys.stdout = OutputStream(channel, "stdout") + sys.stderr = OutputStream(channel, "stderr") + # stdin belongs to the protocol: a script calling input() must not eat + # the next request, so it gets an empty stream (input() raises EOFError). + sys.stdin = io.StringIO() diff --git a/worker/cq_worker/provenance.py b/worker/cq_worker/provenance.py new file mode 100644 index 000000000..9aa6c7e08 --- /dev/null +++ b/worker/cq_worker/provenance.py @@ -0,0 +1,85 @@ +"""The line of the script that created each CadQuery object, for the GUI's +*Go to source*. + +While a script runs, :func:`recording` wraps the constructors of +``Workplane`` (every chained operation creates one through ``newObject``), +``Shape`` and its subclasses, ``Assembly`` (``add`` creates the child nodes) +and ``Sketch``. Each new object remembers the line of the innermost frame +of the script: an object made inside a function of the script points into +that function, one made by a helper module points to the script line that +called it. The constructors are restored when the run ends, whatever +happens, so nothing else pays for it. +""" + +from __future__ import annotations + +import contextlib +import functools +import sys +import types +from collections.abc import Iterator +from typing import Any + +import cadquery as cq + +#: Attribute holding the 1-based script line on recorded objects. +LINE_ATTRIBUTE = "_cq_editor_line" + + +def creation_line(obj: Any) -> int | None: + """The script line that created ``obj``, if it was recorded.""" + + line = getattr(obj, "__dict__", {}).get(LINE_ATTRIBUTE) + return line if isinstance(line, int) else None + + +def _recorded_classes() -> list[type]: + """The classes whose ``__init__`` creates script objects: those that + define one themselves, so every constructor runs through a wrapper.""" + + classes: list[type] = [] + pending = [cq.Workplane, cq.Shape, cq.Assembly, cq.Sketch] + while pending: + cls = pending.pop() + if cls in classes: + continue + if "__init__" in cls.__dict__: + classes.append(cls) + pending.extend(cls.__subclasses__()) + return classes + + +@contextlib.contextmanager +def recording(filename: str) -> Iterator[None]: + """Records creation lines in the code of ``filename`` while active.""" + + def script_line() -> int | None: + frame: types.FrameType | None = sys._getframe(2) + while frame is not None: + if frame.f_code.co_filename == filename: + return frame.f_lineno + frame = frame.f_back + return None + + def wrapped(original): + @functools.wraps(original) + def __init__(self, *args, **kwargs): + original(self, *args, **kwargs) + attributes = getattr(self, "__dict__", None) + if attributes is not None and LINE_ATTRIBUTE not in attributes: + line = script_line() + if line is not None: + attributes[LINE_ATTRIBUTE] = line + + return __init__ + + patched = [] + try: + for cls in _recorded_classes(): + original = cls.__dict__["__init__"] + cls.__init__ = wrapped(original) # type: ignore[misc] + patched.append((cls, original)) + yield + finally: + for cls, original in reversed(patched): + cls.__init__ = original diff --git a/worker/cq_worker/scene.py b/worker/cq_worker/scene.py new file mode 100644 index 000000000..560eb9a5c --- /dev/null +++ b/worker/cq_worker/scene.py @@ -0,0 +1,806 @@ +"""Turn the objects a script shows into scene nodes the GUI can draw. + +A scene node carries display options, triangulated geometry and, for +assemblies, child nodes mirroring the assembly hierarchy. Every node gets a +key; the :class:`Registry` maps keys back to the live CadQuery objects so the +GUI can later ask for exports or stack inspection by key. +""" + +from __future__ import annotations + +import itertools +import logging +import math +import time +from collections.abc import Callable, Iterable, Mapping +from dataclasses import asdict, dataclass, field +from typing import Any + +import cadquery as cq +from OCP.TopoDS import TopoDS_Shape + +from .provenance import creation_line +from .tessellation import GeometryCache, Tolerance, TopologyIndex + +log = logging.getLogger(__name__) + +Color = tuple[float, float, float] + + +def location_matrix(location: cq.Location) -> list[float]: + """Return an OCCT rigid transform in column-major order for glam/WebGPU.""" + + transform = location.wrapped.Transformation() + return [ + transform.Value(row, column) if row <= 3 else (1.0 if column == 4 else 0.0) + for column in range(1, 5) + for row in range(1, 5) + ] + + +def is_cq_object(obj: Any) -> bool: + return isinstance(obj, (cq.Workplane, cq.Shape, cq.Assembly, cq.Sketch)) + + +def find_cq_objects(namespace: Mapping[str, Any]) -> dict[str, ShownObject]: + """Every CadQuery object bound to a public name, for scripts that never + call ``show_object``.""" + + return { + name: ShownObject(value) + for name, value in namespace.items() + if not name.startswith("_") and is_cq_object(value) + } + + +def to_compound(obj: Any) -> cq.Compound: + """Fuse anything shape-like into a single compound. + + Accepts workplanes, shapes, sketches, raw ``TopoDS_Shape`` objects and + lists of those. Non-shape stack entries (vectors, locations) are skipped, + and an empty input yields an empty compound. + """ + + shapes: list[cq.Shape] = [] + for item in obj if isinstance(obj, list) else [obj]: + if isinstance(item, cq.Workplane): + for value in item.vals(): + if isinstance(value, cq.Sketch): + shapes.extend(value) + elif isinstance(value, cq.Shape): + shapes.append(value) + elif isinstance(item, cq.Shape): + shapes.append(item) + elif isinstance(item, cq.Sketch): + # Iterating a sketch yields its faces (or edges) with the sketch + # placement applied. + shapes.extend(item) + elif isinstance(item, TopoDS_Shape): + shapes.append(cq.Shape.cast(item)) + else: + raise ValueError(f"Invalid type {type(item)}") + return cq.Compound.makeCompound(shapes) + + +def parse_color(value: Any) -> tuple[Color, float | None]: + """Normalize a user color specification to sRGB floats plus optional alpha. + + Supported: ``cq.Color``, ``"#rgb"``/``"#rrggbb"``/``"#rrggbbaa"``, color + names known to OpenCascade (``"red"``, ``"steelblue"``, ...), and tuples + of 3 or 4 components, either ints in 0..255 or floats in 0..1. + """ + + if isinstance(value, cq.Color): + r, g, b, a = value.toTuple() + return (r, g, b), a + + if isinstance(value, str): + text = value.strip() + if text.startswith("#"): + digits = text[1:] + if len(digits) in (3, 4): + digits = "".join(c * 2 for c in digits) + if len(digits) not in (6, 8): + raise ValueError(f"Invalid hex color {value!r}") + channels = [ + int(digits[i : i + 2], 16) / 255 for i in range(0, len(digits), 2) + ] + alpha = channels[3] if len(channels) == 4 else None + return (channels[0], channels[1], channels[2]), alpha + return parse_color(cq.Color(text)) + + if isinstance(value, (tuple, list)) and len(value) in (3, 4): + if all(isinstance(c, int) for c in value): + channels = [c / 255 for c in value] + else: + channels = [float(c) for c in value] + if not all(0.0 <= c <= 1.0 for c in channels): + raise ValueError(f"Color components out of range: {value!r}") + alpha = channels[3] if len(channels) == 4 else None + return (channels[0], channels[1], channels[2]), alpha + + raise ValueError(f"Unsupported color specification {value!r}") + + +def finite(value: Any, what: str) -> float: + """``value`` as a float; NaN and infinities cannot reach the GUI.""" + + number = float(value) + if not math.isfinite(number): + raise ValueError(f"{what} must be a finite number, not {value!r}") + return number + + +def non_finite(value: Any, where: str = "") -> str | None: + """Where ``value``, a message, holds a number JSON cannot encode (NaN or + an infinity), such as ``parts[0].transform``; ``None`` when it holds + none. Strings, which hold the mesh arrays, are not looked into.""" + + if isinstance(value, float): + return None if math.isfinite(value) else where or "a number" + if isinstance(value, dict): + items = ( + (f"{where}.{key}" if where else str(key), v) for key, v in value.items() + ) + elif isinstance(value, (list, tuple)): + items = ((f"{where}[{index}]", v) for index, v in enumerate(value)) + else: + return None + for place, item in items: + found = non_finite(item, place) + if found is not None: + return found + return None + + +#: The surface looks ``show_object(..., material="matte plastic")`` offers: +#: plastics and metals with their roughness, and a procedural wood grain. +#: ``default`` is the plain shading of a CAD view. +FINISHES = ( + "default", + "matte plastic", + "glossy plastic", + "brushed steel", + "aluminum", + "wood", +) +_FINISH_ALIASES = {"aluminium": "aluminum"} + + +def finish_name(value: Any) -> str: + """The GUI's name of the material ``value`` names: case, spaces, + hyphens and underscores do not matter (``"Matte-Plastic"``).""" + + if not isinstance(value, str): + raise TypeError( + f"material must be a name such as 'matte plastic', not {value!r}" + ) + words = " ".join(value.replace("_", " ").replace("-", " ").lower().split()) + words = _FINISH_ALIASES.get(words, words) + if words not in FINISHES: + known = ", ".join(repr(name) for name in FINISHES) + raise ValueError(f"unknown material {value!r}; known materials: {known}") + return words.replace(" ", "_") + + +@dataclass +class DisplayOptions: + """The ``options`` mapping accepted by ``show_object``.""" + + color: Color | None = None + #: Opacity in 0..1 (1 is opaque). + alpha: float | None = None + edge_color: Color | None = None + #: The look of the surface, from ``material``: one of :data:`FINISHES`, + #: as the GUI names it (``matte_plastic``). + finish: str | None = None + + @classmethod + def parse(cls, options: Mapping[str, Any] | None) -> DisplayOptions: + """Each option on its own: an invalid one is ignored with a warning, + and the others still apply.""" + + result = cls() + if not options: + return result + + def rgba(value) -> None: + r, g, b, a = value + color, _ = parse_color((r, g, b)) + result.color, result.alpha = color, finite(a, "the rgba alpha") + + def color(value) -> None: + result.color, alpha = parse_color(value) + if alpha is not None and alpha < 1.0 and result.alpha is None: + result.alpha = alpha + + def alpha(value) -> None: + result.alpha = finite(value, "alpha") + + def edge_color(value) -> None: + result.edge_color, _ = parse_color(value) + + def material(value) -> None: + result.finish = finish_name(value) + + for key, apply in ( + ("rgba", rgba), + ("color", color), + ("alpha", alpha), + ("edgecolor", edge_color), + ("material", material), + ): + if key in options: + try: + apply(options[key]) + except (TypeError, ValueError) as error: + log.warning("Ignoring invalid display option: %s", error) + if result.alpha is not None: + result.alpha = min(max(result.alpha, 0.0), 1.0) + return result + + def to_message(self) -> dict: + return { + "color": list(self.color) if self.color else None, + "alpha": self.alpha, + "edge_color": list(self.edge_color) if self.edge_color else None, + "finish": self.finish, + } + + +@dataclass +class ShownObject: + obj: Any + options: Mapping[str, Any] = field(default_factory=dict) + #: The script line of the ``show_object`` call, if made by the script. + line: int | None = None + + +@dataclass(frozen=True) +class PartSource: + """What a displayed part was made from, as the script holds it.""" + + #: The workplane, shape or sketch of the script, in its own coordinates. + obj: Any + #: Where an assembly places it; identity for shown objects. + location: cq.Location + + +@dataclass +class RegistryEntry: + obj: Any + #: Geometry to export for this node, already placed in world space. + shape: cq.Shape | None + children: list[str] = field(default_factory=list) + #: Topological indices for each displayed part, in the same order as the + #: scene node's parts. They keep picking ids tied to live OCCT subshapes. + topologies: list[TopologyIndex] = field(default_factory=list) + #: The source of each part, in the same order: what selectors and code + #: generated for a picked entity refer to. + sources: list[PartSource] = field(default_factory=list) + #: Entity features per (part, kind), computed once for selectors. + selector_features: dict[tuple[int, str], Any] = field(default_factory=dict) + #: For a node below the top of an assembly: where its parents place it + #: (world space) and the color it inherits from them. An export of the + #: node alone puts it where the view shows it. + parent_location: cq.Location | None = None + inherited_color: cq.Color | None = None + #: The name and display color of this node as shown by the script. + name: str = "" + display_color: cq.Color | None = None + material: cq.Material | None = None + face_attributes: list[dict] = field(default_factory=list) + part_materials: list[cq.Material | None] = field(default_factory=list) + part_shapes: list[cq.Shape] = field(default_factory=list) + + def subshape(self, part: int, kind: str, identifier: int) -> cq.Shape: + try: + topology = self.topologies[part] + except IndexError: + raise IndexError(f"Unknown part {part}") from None + return cq.Shape.cast(topology.get(kind, identifier)) + + +class Registry: + """Keeps the CadQuery objects behind scene node keys alive. + + ``prefix`` namespaces the keys. The GUI keeps showing objects after it + restarts the worker, so a fresh worker must never hand out the keys of + its predecessor: releasing the stale objects would free the new ones. + """ + + def __init__(self, prefix: str = "n") -> None: + self._prefix = prefix + self._entries: dict[str, RegistryEntry] = {} + self._counter = itertools.count(1) + + def add(self, entry: RegistryEntry) -> str: + key = f"{self._prefix}{next(self._counter)}" + self._entries[key] = entry + return key + + def get(self, key: str) -> RegistryEntry: + try: + return self._entries[key] + except KeyError: + raise KeyError( + f"Unknown object {key!r}; it may have been cleared " + "or come from a previous Python session (render again)" + ) from None + + def release(self, keys: Iterable[str]) -> None: + for key in keys: + entry = self._entries.pop(key, None) + if entry is not None: + self.release(entry.children) + + def keys(self) -> list[str]: + return list(self._entries) + + def clear(self) -> None: + self._entries.clear() + + def subtree_shapes(self, keys: Iterable[str]) -> list[cq.Shape]: + shapes, seen = [], set() + + def visit(key: str) -> None: + if key in seen: + return + seen.add(key) + entry = self.get(key) + if entry.shape is not None: + shapes.append(entry.shape) + for child in entry.children: + visit(child) + + for key in keys: + visit(key) + return shapes + + +@dataclass +class SceneStats: + """Where building the scenes of one request spent its time (seconds).""" + + #: Content ids: hashing each shape's BREP. + identify: float = 0.0 + #: Topology indices and meshing of geometry not sent as a reference. + tessellate: float = 0.0 + #: Base64 encoding of the mesh arrays. + encode: float = 0.0 + #: Meshes triangulated now, served from the worker's cache, or sent as + #: bare references to geometry the GUI holds. + meshed: int = 0 + cached: int = 0 + referenced: int = 0 + #: Raw array bytes of the meshes sent in full. + mesh_bytes: int = 0 + + def to_message(self) -> dict: + return asdict(self) + + +class BuildCancelled(Exception): + """The GUI cancelled the request while its scene was being built.""" + + +class MeshTransferError(Exception): + """A single part cannot be sent within the transport's wire limit.""" + + +# Base64 expands raw arrays by 4/3; leave room for JSON and metadata below +# the GUI's 512 MiB limit for one mesh-bearing message. +MAX_STREAMED_MESH_BYTES = 350 * 1024 * 1024 + + +def count_parts(obj: Any) -> int: + """How many meshes showing ``obj`` takes: one per shape of an assembly.""" + + if isinstance(obj, cq.Assembly): + own = 0 if obj.obj is None else 1 + return own + sum(count_parts(child) for child in obj.children) + return 1 + + +class SceneBuilder: + def __init__( + self, + registry: Registry, + tolerance: Tolerance, + merge_assemblies: bool = False, + geometry_cache: GeometryCache | None = None, + known_geometry: Iterable[str] = (), + ) -> None: + self.registry = registry + self.tolerance = tolerance + self.merge_assemblies = merge_assemblies + self.geometry_cache = geometry_cache or GeometryCache() + # Updated as a response is built, so repeated parts in the same + # assembly become references after the first full mesh. + self.known_geometry = set(known_geometry) + # Tessellation mutates OCCT's polygonal cache. Remember the signature + # by source object so reuse within one run is unaffected by that. + self._source_geometry: dict[int, str] = {} + self.stats = SceneStats() + #: Told (parts done, parts in all) as :meth:`build` goes. + self.progress: Callable[[int, int], None] | None = None + #: Asked before each part; true stops :meth:`build`. + self.cancelled: Callable[[], bool] | None = None + #: Send one complete part before its containing scene node is done. + self.on_part: Callable[[str, dict], None] | None = None + self._done = 0 + self._total = 0 + + def build(self, objects: Mapping[str, ShownObject]) -> list[dict]: + """The scene nodes of ``objects``. Raises :class:`BuildCancelled`, + having released what it registered, when :attr:`cancelled` says so.""" + + self._total = sum(count_parts(shown.obj) for shown in objects.values()) + self._done = 0 + if self.progress is not None: + self.progress(0, self._total) + registered = set(self.registry.keys()) + try: + return self._build(objects) + except (BuildCancelled, MeshTransferError, KeyboardInterrupt): + self.registry.release(set(self.registry.keys()) - registered) + raise + + def _build(self, objects: Mapping[str, ShownObject]) -> list[dict]: + nodes = [] + for name, shown in objects.items(): + try: + node = self.node( + name, shown.obj, DisplayOptions.parse(shown.options), shown.line + ) + except (BuildCancelled, MeshTransferError): + raise + except Exception as error: + log.error( + "Cannot display %s: %s: %s", name, type(error).__name__, error + ) + continue + if node is None: + continue + # One object with a NaN, such as in its placement, must not make + # the whole reply impossible to send. + where = non_finite(node) + if where is not None: + log.error("Cannot display %s: %s is not a finite number", name, where) + self.registry.release([node["key"]]) + continue + nodes.append(node) + return nodes + + def node( + self, + name: str, + obj: Any, + options: DisplayOptions, + shown_line: int | None = None, + ) -> dict | None: + """The node of a shown object. Its ``line`` is where the script + created the object, else where it showed it.""" + + message = self._node(name, obj, options) + if message is not None and message["line"] is None: + message["line"] = shown_line + return message + + def _node(self, name: str, obj: Any, options: DisplayOptions) -> dict | None: + if isinstance(obj, cq.Assembly): + if self.merge_assemblies: + return self._merged_assembly_node(name, obj, options) + return self._assembly_node( + name, obj, options, cq.Location(), None, top=True + ) + + shape = to_compound(obj) + topology = TopologyIndex.build(shape.wrapped) + part = self._part(shape, topology, None, None, cq.Location(), obj, name) + if part is None: + return None + self._emit_part(name, part) + key = self.registry.add( + RegistryEntry( + obj, + shape, + topologies=[topology], + sources=[PartSource(obj, cq.Location())], + name=str(name), + display_color=(cq.Color(*options.color) if options.color else None), + ) + ) + return self._message(key, name, obj, options, [part], []) + + def _assembly_node( + self, + name: str, + assembly: cq.Assembly, + options: DisplayOptions, + parent_location: cq.Location, + inherited_color: cq.Color | None, + top: bool = False, + inherited_material: cq.Material | None = None, + ) -> dict | None: + location = parent_location * assembly.loc + color = assembly.color if assembly.color is not None else inherited_color + material = ( + assembly.material if assembly.material is not None else inherited_material + ) + + shape, parts, topologies, sources = None, [], [], [] + if assembly.obj is not None: + # A node can have both a shape and children. + local_shape = to_compound(assembly.obj) + shape = local_shape.moved(location) + topology = TopologyIndex.build(shape.wrapped) + part = self._part( + local_shape, + None, + *self._part_color(color or self._material_color(material)), + location, + assembly.obj, + name, + ) + if part is not None: + attributes = self._face_attributes(assembly, local_shape) + part["face_attributes"] = attributes + part["material"] = self._material_message(material) + self._emit_part(name, part) + parts.append(part) + topologies.append(topology) + sources.append(PartSource(assembly.obj, location)) + + children = [ + child_node + for child in assembly.children + if ( + child_node := self._assembly_node( + child.name, + child, + options, + location, + color, + inherited_material=material, + ) + ) + is not None + ] + if not parts and not children: + return None + + entry = RegistryEntry( + assembly, + shape, + children=[c["key"] for c in children], + topologies=topologies, + sources=sources, + parent_location=None if top else parent_location, + inherited_color=None if top else inherited_color, + name=str(name), + display_color=(cq.Color(*options.color) if options.color else None), + material=material, + face_attributes=attributes if parts else [], + ) + key = self.registry.add(entry) + message = self._message(key, name, assembly, options, parts, children) + if assembly.obj is not None: + # More telling than "Assembly" for the parts of an assembly. + message["kind"] = type(assembly.obj).__name__ + return message + + def _merged_assembly_node( + self, name: str, assembly: cq.Assembly, options: DisplayOptions + ) -> dict | None: + parts, topologies, sources, materials = [], [], [], [] + shapes: list[cq.Shape] = [] + + def collect( + node: cq.Assembly, parent: cq.Location, inherited, inherited_mat + ) -> None: + location = parent * node.loc + color = node.color if node.color is not None else inherited + material = node.material if node.material is not None else inherited_mat + if node.obj is not None: + local_shape = to_compound(node.obj) + shape = local_shape.moved(location) + shapes.append(shape) + topology = TopologyIndex.build(shape.wrapped) + part = self._part( + local_shape, + None, + *self._part_color(color or self._material_color(material)), + location, + node.obj, + node.name, + ) + if part is not None: + part["face_attributes"] = self._face_attributes(node, local_shape) + part["material"] = self._material_message(material) + self._emit_part(node.name, part) + parts.append(part) + topologies.append(topology) + sources.append(PartSource(node.obj, location)) + materials.append(material) + for child in node.children: + collect(child, location, color, material) + + collect(assembly, cq.Location(), None, None) + if not parts: + return None + key = self.registry.add( + RegistryEntry( + assembly, + cq.Compound.makeCompound(shapes), + topologies=topologies, + sources=sources, + name=str(name), + display_color=(cq.Color(*options.color) if options.color else None), + part_materials=materials, + part_shapes=shapes, + ) + ) + return self._message(key, name, assembly, options, parts, []) + + @staticmethod + def _part_color(color: cq.Color | None) -> tuple[Color | None, float | None]: + if color is None: + return None, None + rgb, alpha = parse_color(color) + return rgb, alpha + + def _emit_part(self, name: str, part: dict) -> None: + if self.on_part is not None: + where = non_finite(part) + if where is not None: + raise ValueError( + f"Cannot display {name}: {where} is not a finite number" + ) + self.on_part(name, part) + part["mesh"] = {"id": part["mesh"]["id"]} + + @staticmethod + def _material_color(material: cq.Material | None) -> cq.Color | None: + if material is None or not ( + material.wrapped_vis.HasPbrMaterial() + or material.wrapped_vis.HasCommonMaterial() + ): + return None + value = material.wrapped_vis.BaseColor() + rgb = value.GetRGB() + return cq.Color(rgb.Red(), rgb.Green(), rgb.Blue(), value.Alpha()) + + @staticmethod + def _material_message(material: cq.Material | None) -> dict | None: + if material is None: + return None + return { + "name": material.name, + "density": finite(material.density, "material density"), + "density_unit": material.densityUnit, + } + + @staticmethod + def _face_attributes(assembly: cq.Assembly, shape: cq.Shape) -> list[dict]: + topology = TopologyIndex.build(shape.wrapped) + index = { + cq.Shape.cast(raw_face): identifier + for identifier, raw_face in enumerate(topology.faces, 1) + } + attributes: dict[int, dict] = {} + for field_name, values in ( + ("name", assembly._subshape_names), + ("layer", assembly._subshape_layers), + ("color", assembly._subshape_colors), + ): + for subshape, value in values.items(): + for face in subshape.Faces(): + identifier = index.get(face) + if identifier is None: + continue + item = attributes.setdefault(identifier, {"id": identifier}) + if field_name == "color": + rgb, alpha = parse_color(value) + item["color"] = list(rgb) + item["alpha"] = alpha + else: + item[field_name] = value + return [attributes[identifier] for identifier in sorted(attributes)] + + def _part( + self, + shape: cq.Shape, + topology: TopologyIndex | None, + color: Color | None, + alpha: float | None, + location: cq.Location, + source: Any, + name: str, + ) -> dict | None: + if self.cancelled is not None and self.cancelled(): + raise BuildCancelled() + try: + return self._mesh_part( + shape, topology, color, alpha, location, source, name + ) + finally: + self._done += 1 + if self.progress is not None: + self.progress(min(self._done, self._total), self._total) + + def _mesh_part( + self, + shape: cq.Shape, + topology: TopologyIndex | None, + color: Color | None, + alpha: float | None, + location: cq.Location, + source: Any, + name: str, + ) -> dict | None: + stats = self.stats + source_id = id(source) + geometry_id = self._source_geometry.get(source_id) + if geometry_id is None: + started = time.perf_counter() + geometry_id = self.geometry_cache.identifier(shape.wrapped, self.tolerance) + geometry_id = self.geometry_cache.canonical_id(geometry_id) + self._source_geometry[source_id] = geometry_id + stats.identify += time.perf_counter() - started + + if geometry_id in self.known_geometry: + mesh_message = {"id": geometry_id} + stats.referenced += 1 + else: + started = time.perf_counter() + cached = self.geometry_cache.get(geometry_id) is not None + topology = topology or TopologyIndex.build(shape.wrapped) + _, mesh = self.geometry_cache.tessellate( + shape.wrapped, self.tolerance, topology, geometry_id + ) + stats.tessellate += time.perf_counter() - started + if mesh is None: + return None + invalid = mesh.non_finite_array() + if invalid is not None: + raise ValueError( + f"Cannot display {name}: mesh {invalid} contains NaN or infinity" + ) + if mesh.byte_size() > MAX_STREAMED_MESH_BYTES: + raise MeshTransferError( + f"{name}: one part is too large to transfer; raise Deviation " + "in Preferences > 3D View or split the part" + ) + started = time.perf_counter() + mesh_message = mesh.to_message(geometry_id) + stats.encode += time.perf_counter() - started + if cached: + stats.cached += 1 + else: + stats.meshed += 1 + stats.mesh_bytes += mesh.byte_size() + self.known_geometry.add(geometry_id) + part = { + "mesh": mesh_message, + "transform": location_matrix(location), + "color": list(color) if color else None, + "alpha": alpha, + } + return part + + @staticmethod + def _message(key, name, obj, options, parts, children) -> dict: + line = creation_line(obj) + if line is None and isinstance(obj, cq.Assembly): + line = creation_line(obj.obj) + return { + "key": key, + "name": str(name), + "kind": type(obj).__name__, + "line": line, + "inspectable": isinstance(obj, cq.Workplane) and obj.parent is not None, + **options.to_message(), + "parts": parts, + "children": children, + } diff --git a/worker/cq_worker/selection.py b/worker/cq_worker/selection.py new file mode 100644 index 000000000..8cc4151f4 --- /dev/null +++ b/worker/cq_worker/selection.py @@ -0,0 +1,642 @@ +"""What is picked in the GUI, as code: selectors and live shapes. + +The GUI picks entities by their 1-based OCCT topology id. +:class:`PickedSelection` resolves its selection to the live shapes that the +console's ``selected()`` returns. A script needs a *selector* instead, such +as ``.faces(">Z")`` or ``.edges("|Z and >Y")``: :func:`selector_candidates` +finds the simplest selector strings that select exactly the picked entities +of one object, and ranks them. + +Candidates are searched cheaply: the center, direction and geometry type of +every entity are read once, and each simple selector (``>Z``, ``|X``, +``%PLANE``, ``>Z[-2]`` ...) is evaluated on them with the same rules as +CadQuery's own selector classes. Combinations are then set operations on +bit masks. Nothing is trusted on that basis alone: every candidate returned +has been applied by CadQuery itself to the object the script applies it to, +and selected exactly the picked entities. When no geometric selector does, +an index into CadQuery's entity order is offered, flagged as such: it may +select another entity once the model changes. +""" + +from __future__ import annotations + +import itertools +import math +from collections.abc import Callable, Iterable, Sequence +from dataclasses import dataclass, field +from fractions import Fraction +from typing import Any + +import cadquery as cq +import numpy as np +from .measurement import MeasurementError, TopologyReference, object_shape +from .scene import Registry, TopologyIndex, to_compound + +#: CadQuery's default selector tolerance (``BaseDirSelector``, ``_NthSelector``). +TOLERANCE = 1e-4 +#: Verified candidates returned, best first (an index fallback may follow). +MAX_CANDIDATES = 3 +#: Candidates tried with CadQuery; each attempt evaluates every entity. +MAX_VERIFIED_ATTEMPTS = 10 +#: Deepest ``>Z[-n]`` / ``>>Z[-n]`` generated. +MAX_NTH = 16 +#: Most terms joined with ``or`` for several picked entities. +MAX_OR_TERMS = 4 +#: Supersets of the picked entities combined three at a time. +MAX_TRIPLE_ATOMS = 30 +#: Inclined directions offered as ``(x,y,z)`` selectors. +MAX_VECTOR_DIRECTIONS = 12 +#: Cost of the index fallback: after every geometric selector. +INDEX_COST = 99.0 + +_METHODS = {"face": "faces", "edge": "edges", "vertex": "vertices"} +_ENTITY_LISTS = {"face": "Faces", "edge": "Edges", "vertex": "Vertices"} +_AXES = {"X": (1.0, 0.0, 0.0), "Y": (0.0, 1.0, 0.0), "Z": (0.0, 0.0, 1.0)} +_DIAGONALS = {"XY": (1.0, 1.0, 0.0), "XZ": (1.0, 0.0, 1.0), "YZ": (0.0, 1.0, 1.0)} + + +class SelectorError(MeasurementError): + """The picked entities cannot be described by a selector.""" + + +@dataclass(frozen=True) +class PickedSelection: + """What the GUI had selected when it sent a console command.""" + + #: Picked faces, edges and vertices, in the order they were picked. + entities: tuple[TopologyReference, ...] = () + #: Keys of the selected objects (outermost first, in tree order). + objects: tuple[str, ...] = () + + @classmethod + def from_message(cls, message: Any) -> PickedSelection: + if message is None: + return cls() + if not isinstance(message, dict): + raise MeasurementError("The selection must be an object") + entities = message.get("entities", []) + objects = message.get("objects", []) + if not isinstance(entities, list) or not isinstance(objects, list): + raise MeasurementError("Selected entities and objects must be lists") + if not all(isinstance(key, str) and key for key in objects): + raise MeasurementError("Selected objects must be scene keys") + return cls( + tuple(TopologyReference.from_message(value) for value in entities), + tuple(objects), + ) + + def resolve(self, registry: Registry) -> list[cq.Shape]: + """The picked entities placed as shown, or, when none is picked, + the shapes of the selected objects.""" + + try: + if self.entities: + return [ + registry.get(r.key).subshape(r.part, r.kind, r.identifier) + for r in self.entities + ] + return [object_shape(registry, key) for key in self.objects] + except KeyError as error: + raise LookupError(error.args[0]) from None + except MeasurementError as error: + raise LookupError(str(error)) from None + except (IndexError, ValueError) as error: + raise LookupError( + f"{error}; the model changed since it was picked, pick it again" + ) from None + + +@dataclass(frozen=True) +class Atom: + """A simple selector and the entities it selects, as a bit mask.""" + + expression: str + mask: int + cost: float + description: str + + +@dataclass(frozen=True) +class Candidate: + """A selector string, or a complete index expression.""" + + selector: str + cost: float + description: str + #: The text to append to the object; set for index expressions. + expression: str | None = None + + @property + def index_based(self) -> bool: + return self.expression is not None + + def to_message(self, method: str) -> dict: + return { + "expression": self.expression or f'.{method}("{self.selector}")', + "selector": None if self.index_based else self.selector, + "description": self.description, + "index_based": self.index_based, + } + + +@dataclass +class Features: + """What simple selectors look at, for every entity of one object.""" + + entities: list[cq.Shape] + centers: np.ndarray # (n, 3) + #: Normal of planar faces, tangent of straight edges; NaN otherwise. + directions: np.ndarray # (n, 3) + types: list[str] + index: dict[cq.Shape, int] = field(default_factory=dict) + + @classmethod + def of(cls, entities: Sequence[cq.Shape]) -> Features: + centers = np.empty((len(entities), 3)) + directions = np.full((len(entities), 3), np.nan) + types = [] + for i, entity in enumerate(entities): + centers[i] = entity.Center().toTuple() + kind = entity.ShapeType() + geometry = entity.geomType() if kind in ("Face", "Edge") else kind.upper() + types.append(geometry) + # The vectors BaseDirSelector tests. + if isinstance(entity, cq.Face) and geometry == "PLANE": + directions[i] = entity.normalAt(None).toTuple() + elif isinstance(entity, cq.Edge) and geometry == "LINE": + directions[i] = entity.tangentAt().toTuple() + return cls( + list(entities), + centers, + directions, + types, + {entity: i for i, entity in enumerate(entities)}, + ) + + +@dataclass +class Receiver: + """The object a selector is appended to in the script.""" + + obj: Any + kind: str # face, edge or vertex + + @property + def method(self) -> str: + return _METHODS[self.kind] + + @property + def is_workplane(self) -> bool: + return isinstance(self.obj, cq.Workplane) + + def entities(self) -> list[cq.Shape]: + """Everything ``obj.()`` starts from, in CadQuery's order.""" + + if self.is_workplane: + return list(getattr(self.obj, self.method)().vals()) + return list(getattr(self.obj, _ENTITY_LISTS[self.kind])()) + + def select(self, selector: str) -> list[cq.Shape]: + """What ``obj.(selector)`` selects, as the script runs it.""" + + result = getattr(self.obj, self.method)(selector) + if self.is_workplane: + return list(result.vals()) + return list(getattr(result, _ENTITY_LISTS[self.kind])()) + + def index_expression(self, indices: Sequence[int]) -> str | None: + if self.is_workplane: + item = str(indices[0]) if len(indices) == 1 else str(list(indices)) + return f".{self.method}()[{item}]" + if len(indices) == 1: + # Shape.faces() is one compound; Shape.Faces() is the list. + return f".{_ENTITY_LISTS[self.kind]}()[{indices[0]}]" + return None + + def select_indices(self, indices: Sequence[int]) -> list[cq.Shape]: + """What :meth:`index_expression` selects.""" + + if self.is_workplane: + selected = getattr(self.obj, self.method)() + item = indices[0] if len(indices) == 1 else list(indices) + return list(selected[item].vals()) + return [getattr(self.obj, _ENTITY_LISTS[self.kind])()[indices[0]]] + + +def selector_candidates(registry: Registry, raw_selections: Any) -> dict[str, Any]: + """Selectors for the picked entities of one object, best first.""" + + if not isinstance(raw_selections, list) or not raw_selections: + raise SelectorError("Select faces, edges or vertices to get a selector") + references = [TopologyReference.from_message(value) for value in raw_selections] + first = references[0] + if any((r.key, r.part) != (first.key, first.part) for r in references): + raise SelectorError( + "A selector describes entities of one object: pick them on a single object" + ) + if any(r.kind != first.kind for r in references): + raise SelectorError( + "A selector describes one kind of entity: pick only faces, edges or vertices" + ) + + try: + entry = registry.get(first.key) + except KeyError as error: + raise SelectorError(error.args[0]) from None + if not 0 <= first.part < len(entry.sources): + raise SelectorError(f"Unknown part {first.part}") + source = entry.sources[first.part] + if not isinstance(source.obj, (cq.Workplane, cq.Shape)): + raise SelectorError( + "Selectors are generated for workplanes and shapes, " + f"not for a {type(source.obj).__name__}" + ) + + receiver = Receiver(source.obj, first.kind) + features = entry.selector_features.get((first.part, first.kind)) + if features is None: + features = Features.of(receiver.entities()) + entry.selector_features[(first.part, first.kind)] = features + + # Topology ids number the subshapes of the object's own (local) shape, + # whatever location an assembly gives it. + local = TopologyIndex.build(to_compound(source.obj).wrapped) + targets = set() + for reference in references: + try: + subshape = cq.Shape.cast(local.get(reference.kind, reference.identifier)) + except (IndexError, ValueError) as error: + raise SelectorError(str(error)) from None + index = features.index.get(subshape) + if index is None: + raise SelectorError( + f"{reference.kind.title()} {reference.identifier} is not among " + f"the object's .{receiver.method}()" + ) + targets.add(index) + + candidates = _verified(receiver, features, targets, search(features, targets)) + if len(candidates) < MAX_CANDIDATES: + fallback = _index_candidate(receiver, features, targets) + if fallback is not None: + candidates.append(fallback) + if not candidates: + raise SelectorError("No selector selects exactly these entities") + messages = [c.to_message(receiver.method) for c in candidates] + if first.kind == "face" and len(references) == 1: + attribute = next( + (a for a in entry.face_attributes if a["id"] == first.identifier), None + ) + if attribute is not None and attribute.get("name"): + for candidate in messages: + candidate["description"] = ( + f"{attribute['name']} · {candidate['description']}" + ) + return {"method": receiver.method, "candidates": messages} + + +# -- simple selectors ------------------------------------------------------------ + + +def atoms(features: Features) -> list[Atom]: + """Every useful simple selector with what it selects.""" + + count = len(features.entities) + found: list[Atom] = [] + if count == 0: + return found + seen: set[str] = set() + + def add(expression: str, mask: int, cost: float, description: str) -> None: + if mask and expression not in seen: + seen.add(expression) + found.append(Atom(expression, mask, cost, description)) + + directions = features.directions + has_direction = ~np.isnan(directions[:, 0]) + + for name, vector in _AXES.items(): + v = np.array(vector) + add(f">{name}", _extreme(features, v, True), 1.0, f"largest {name}") + add(f"<{name}", _extreme(features, v, False), 1.0, f"smallest {name}") + if has_direction.any(): + parallel = _parallel(directions, v) + add(f"|{name}", _bits(parallel), 1.1, f"parallel to {name}") + add( + f"#{name}", + _bits(_perpendicular(directions, v)), + 1.15, + f"perpendicular to {name}", + ) + add(f"+{name}", _bits(_aligned(directions, v)), 1.2, f"facing +{name}") + add(f"-{name}", _bits(_aligned(directions, -v)), 1.2, f"facing -{name}") + # >Z[n] only ranks what is parallel to Z (DirectionNthSelector). + for n, (largest, smallest) in _nth(features, v, np.flatnonzero(parallel)): + among = f"among those parallel to {name}" + cost = 2.0 + 0.05 * n + add( + f">{name}[-{n}]", + largest, + cost, + f"{_ordinal(n)} largest {name} {among}", + ) + add( + f"<{name}[-{n}]", + smallest, + cost, + f"{_ordinal(n)} smallest {name} {among}", + ) + for n, (largest, smallest) in _nth(features, v, np.arange(count), start=2): + cost = 2.1 + 0.05 * n + add(f">>{name}[-{n}]", largest, cost, f"{_ordinal(n)} largest {name}") + add(f"<<{name}[-{n}]", smallest, cost, f"{_ordinal(n)} smallest {name}") + + for name, vector in _DIAGONALS.items(): + v = np.array(vector) + sum_text = f"{name[0]}+{name[1]}" + add(f">{name}", _extreme(features, v, True), 2.3, f"largest {sum_text}") + add(f"<{name}", _extreme(features, v, False), 2.3, f"smallest {sum_text}") + + for geometry in sorted(set(features.types) - {"VERTEX"}): + flags = np.array([t == geometry for t in features.types]) + add(f"%{geometry}", _bits(flags), 1.3, geometry.lower()) + + # Inclined planar faces and straight edges, e.g. a chamfer. + for direction in _distinct_directions(directions[has_direction]): + text = _vector_text(direction) + v = np.array([float(c) for c in text.strip("()").split(",")]) + add(f"+{text}", _bits(_aligned(directions, v)), 1.7, f"facing {text}") + add(f"|{text}", _bits(_parallel(directions, v)), 1.8, f"parallel to {text}") + add(f">{text}", _extreme(features, v, True), 2.6, f"farthest along {text}") + add(f"<{text}", _extreme(features, v, False), 2.6, f"farthest against {text}") + return found + + +def _bits(flags: np.ndarray) -> int: + mask = 0 + for index in np.flatnonzero(flags): + mask |= 1 << int(index) + return mask + + +def _clusters(keys: np.ndarray, indices: Iterable[int]) -> list[list[int]]: + """``_NthSelector.cluster``: ascending keys; a cluster spans the + tolerance from its first key.""" + + order = sorted((int(i) for i in indices), key=lambda i: keys[i]) + clusters: list[list[int]] = [] + start = 0.0 + for i in order: + if not clusters or abs(keys[i] - start) > TOLERANCE: + clusters.append([]) + start = keys[i] + clusters[-1].append(i) + return clusters + + +def _extreme(features: Features, vector: np.ndarray, largest: bool) -> int: + """``>v`` / `` Iterable[tuple[int, tuple[int, int]]]: + """The n-th largest and smallest cluster of ``indices`` along + ``vector``, which ``v[-n]`` selects with ``>`` and ``<``.""" + + if len(indices) == 0: + return + keys = features.centers @ vector + clusters = _clusters(keys, indices) + for n in range(start, min(len(clusters), MAX_NTH) + 1): + yield n, ( + sum(1 << i for i in clusters[-n]), + sum(1 << i for i in clusters[n - 1]), + ) + + +def _cross_length(directions: np.ndarray, vector: np.ndarray) -> np.ndarray: + with np.errstate(invalid="ignore"): + return np.linalg.norm(np.cross(vector, directions), axis=1) + + +def _angles(directions: np.ndarray, vector: np.ndarray) -> np.ndarray: + with np.errstate(invalid="ignore"): + return np.arctan2(_cross_length(directions, vector), directions @ vector) + + +def _parallel(directions: np.ndarray, vector: np.ndarray) -> np.ndarray: + """``|v``: NaN directions (curved faces and edges) never match.""" + + with np.errstate(invalid="ignore"): + return _cross_length(directions, vector) < TOLERANCE + + +def _aligned(directions: np.ndarray, vector: np.ndarray) -> np.ndarray: + with np.errstate(invalid="ignore"): + return _angles(directions, vector) < TOLERANCE + + +def _perpendicular(directions: np.ndarray, vector: np.ndarray) -> np.ndarray: + with np.errstate(invalid="ignore"): + return np.abs(_angles(directions, vector) - math.pi / 2) < TOLERANCE + + +def _distinct_directions(directions: np.ndarray) -> list[np.ndarray]: + """Unit directions off the axes, without duplicates or opposites.""" + + found: list[np.ndarray] = [] + for direction in directions: + if np.count_nonzero(np.abs(direction) > 1e-9) < 2: + continue + if any(abs(abs(float(direction @ other)) - 1.0) < 1e-12 for other in found): + continue + found.append(direction) + if len(found) == MAX_VECTOR_DIRECTIONS: + break + return found + + +def _vector_text(direction: np.ndarray) -> str: + """``(x,y,z)`` for selector strings: small integers when the direction + has a simple ratio, otherwise six decimals.""" + + largest = float(np.max(np.abs(direction))) + for limit in range(1, 11): + ratios = [ + Fraction(float(c) / largest).limit_denominator(limit) for c in direction + ] + denominator = math.lcm(*(r.denominator for r in ratios)) + integers = np.array([float(r * denominator) for r in ratios]) + if float(integers @ direction) / float(np.linalg.norm(integers)) > 1.0 - 1e-14: + return "(" + ",".join(str(int(c)) for c in integers) + ")" + return "(" + ",".join(_decimal(float(c)) for c in direction) + ")" + + +def _decimal(value: float) -> str: + text = f"{value:.6f}".rstrip("0") + return text + "0" if text.endswith(".") else text + + +def _ordinal(n: int) -> str: + return {1: "1st", 2: "2nd", 3: "3rd"}.get(n, f"{n}th") + + +# -- combinations ----------------------------------------------------------------- + + +def search(features: Features, targets: set[int]) -> list[Candidate]: + """Candidate selectors for the entities at ``targets``, cheapest first. + They follow CadQuery's rules but are not verified yet.""" + + target = sum(1 << i for i in targets) + found: dict[str, Candidate] = {} + + def offer(selector: str, cost: float, description: str) -> None: + if selector not in found or found[selector].cost > cost: + found[selector] = Candidate(selector, cost, description) + + simple = atoms(features) + for atom in simple: + if atom.mask == target: + offer(atom.expression, atom.cost, atom.description) + + # "and" narrows selectors that each include every picked entity. + supersets = sorted( + (a for a in simple if a.mask & target == target and a.mask != target), + key=lambda a: a.cost, + ) + conjunctions: list[Atom] = list(supersets) + for first, second in itertools.combinations(supersets[:MAX_TRIPLE_ATOMS], 2): + conjunctions.append(_conjunction(first, second)) + for parts in itertools.combinations(supersets[:MAX_TRIPLE_ATOMS], 3): + if parts[0].mask & parts[1].mask & parts[2].mask == target: + conjunction = _conjunction(*parts) + offer(conjunction.expression, conjunction.cost, conjunction.description) + for conjunction in conjunctions: + if conjunction.mask == target: + offer(conjunction.expression, conjunction.cost, conjunction.description) + + # "exc" removes what a superset should not include ("and" binds + # tighter, so "A and B exc C" is "(A and B) exc C"). + excluded = sorted((a for a in simple if a.mask & target == 0), key=lambda a: a.cost) + for base in conjunctions: + if base.mask & target != target or base.mask == target: + continue + for removed in excluded: + if base.mask & ~removed.mask == target: + offer( + f"{base.expression} exc {removed.expression}", + base.cost + removed.cost + 0.5, + f"{base.description}, except {removed.description}", + ) + break + + if len(targets) > 1: + union = _union(simple, supersets, target) + if union is not None: + offer(union.expression, union.cost, union.description) + + return sorted(found.values(), key=lambda c: (c.cost, len(c.selector), c.selector)) + + +def _conjunction(*parts: Atom) -> Atom: + mask = parts[0].mask + for part in parts[1:]: + mask &= part.mask + return Atom( + " and ".join(part.expression for part in parts), + mask, + sum(part.cost for part in parts) + 0.2 * (len(parts) - 1), + ", ".join(part.description for part in parts), + ) + + +def _union(simple: list[Atom], supersets: list[Atom], target: int) -> Atom | None: + """``a or b or ...`` of terms that each select only picked entities, + chosen greedily.""" + + terms = [atom for atom in simple if atom.mask & ~target == 0] + for first, second in itertools.combinations( + supersets[:MAX_TRIPLE_ATOMS] + simple, 2 + ): + mask = first.mask & second.mask + if mask and mask & ~target == 0: + pair = _conjunction(first, second) + terms.append( + Atom(f"({pair.expression})", mask, pair.cost, pair.description) + ) + chosen: list[Atom] = [] + covered = 0 + while covered != target and len(chosen) < MAX_OR_TERMS: + useful = [term for term in terms if term.mask & ~covered] + if not useful: + return None + best = max( + useful, + key=lambda term: ( + bin(term.mask & ~covered).count("1") / term.cost, + -term.cost, + ), + ) + chosen.append(best) + covered |= best.mask + if covered != target: + return None + return Atom( + " or ".join(term.expression for term in chosen), + target, + sum(term.cost for term in chosen) + 0.3 * (len(chosen) - 1), + " or ".join(term.description for term in chosen), + ) + + +# -- verification --------------------------------------------------------------- + + +def _verified( + receiver: Receiver, + features: Features, + targets: set[int], + candidates: list[Candidate], +) -> list[Candidate]: + """The candidates CadQuery itself confirms, best first.""" + + expected = {features.entities[i] for i in targets} + confirmed: list[Candidate] = [] + for candidate in candidates[:MAX_VERIFIED_ATTEMPTS]: + if _selects(lambda: receiver.select(candidate.selector), expected): + confirmed.append(candidate) + if len(confirmed) == MAX_CANDIDATES: + break + return confirmed + + +def _index_candidate( + receiver: Receiver, features: Features, targets: set[int] +) -> Candidate | None: + indices = sorted(targets) + expression = receiver.index_expression(indices) + if expression is None: + return None + expected = {features.entities[i] for i in targets} + if not _selects(lambda: receiver.select_indices(indices), expected): + return None + return Candidate( + selector="", + cost=INDEX_COST, + description="by position in CadQuery's order; may change with the model", + expression=expression, + ) + + +def _selects(select: Callable[[], list[cq.Shape]], expected: set[cq.Shape]) -> bool: + try: + selected = select() + except Exception: # not valid for this object, e.g. an empty nth cluster + return False + return len(selected) == len(expected) and set(selected) == expected diff --git a/worker/cq_worker/selector_preview.py b/worker/cq_worker/selector_preview.py new file mode 100644 index 000000000..3fecc3edf --- /dev/null +++ b/worker/cq_worker/selector_preview.py @@ -0,0 +1,131 @@ +"""Read-only preview of literal CadQuery selectors in the last completed run. + +No source expression is evaluated. Only a top-level runtime variable and a +literal string argument are resolved, so moving the caret never executes +arbitrary Python from the editor buffer. +""" + +from __future__ import annotations + +import ast +from typing import Any + +import cadquery as cq + +from .scene import Registry +from .selection import Receiver + +_KINDS = {"faces": "face", "edges": "edge", "vertices": "vertex"} +MAX_SELECTOR_LENGTH = 256 +MAX_HIGHLIGHTS = 64 + + +def preview( + registry: Registry, + names: dict[str, cq.Shape | cq.Workplane], + source: str, + line: int, + column: int, + preferred_key: str | None = None, +) -> dict[str, Any]: + """Return exact topology ids for the selector at a 1-based caret position.""" + + lines = source.splitlines() + if not 1 <= line <= len(lines) or not 1 <= column <= len(lines[line - 1]) + 1: + return {"active": False, "count": 0, "matches": [], "message": None} + position = (line, len(lines[line - 1][: column - 1].encode("utf-8"))) + try: + tree = ast.parse(source) + except SyntaxError: + return {"active": False, "count": 0, "matches": [], "message": None} + candidates: list[ast.Call] = [] + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in _KINDS + and node.end_lineno is not None + and node.end_col_offset is not None + and (node.lineno, node.col_offset) <= position + and position <= (node.end_lineno, node.end_col_offset) + ): + candidates.append(node) + if not candidates: + return {"active": False, "count": 0, "matches": [], "message": None} + call = min( + candidates, + key=lambda node: ( + (node.end_lineno or node.lineno) - node.lineno, + (node.end_col_offset or node.col_offset) - node.col_offset, + ), + ) + result: dict[str, Any] = { + "active": True, + "count": 0, + "matches": [], + "message": None, + } + attribute = call.func + assert isinstance(attribute, ast.Attribute) + if ( + not isinstance(attribute.value, ast.Name) + or len(call.args) != 1 + or call.keywords + or not isinstance(call.args[0], ast.Constant) + or not isinstance(call.args[0].value, str) + ): + result["message"] = "Preview supports a variable with a literal selector string" + return result + selector = call.args[0].value + if len(selector) > MAX_SELECTOR_LENGTH: + result["message"] = "Selector is too long to preview" + return result + variable = attribute.value.id + obj = names.get(variable) + if obj is None: + result["message"] = f"{variable} is not a CadQuery object from the last run" + return result + kind = _KINDS[attribute.attr] + sources = [] + for key in registry.keys(): + entry = registry.get(key) + for part, part_source in enumerate(entry.sources): + if part_source.obj is obj and part < len(entry.topologies): + sources.append((key, part, entry.topologies[part])) + if not sources: + result["message"] = f"{variable} is not displayed in the 3D view" + return result + sources.sort(key=lambda item: item[0] != preferred_key) + key, part, topology = sources[0] + try: + selected = Receiver(obj, kind).select(selector) + except Exception as error: + result["message"] = f"Invalid selector: {error}" + return result + result["count"] = len(selected) + collection = getattr( + topology, {"face": "faces", "edge": "edges", "vertex": "vertices"}[kind] + ) + by_hash: dict[int, list[tuple[int, cq.Shape]]] = {} + for identifier, raw in enumerate(collection, 1): + entity = cq.Shape.cast(raw) + by_hash.setdefault(entity.hashCode(), []).append((identifier, entity)) + for shape in selected[:MAX_HIGHLIGHTS]: + match_id = next( + ( + identifier + for identifier, entity in by_hash.get(shape.hashCode(), []) + if entity.wrapped.IsSame(shape.wrapped) + ), + None, + ) + if match_id is None: + result["message"] = ( + "Selected entities do not belong to the displayed object" + ) + result["matches"] = [] + return result + result["matches"].append( + {"key": key, "part": part, "kind": kind, "identifier": match_id} + ) + return result diff --git a/worker/cq_worker/server.py b/worker/cq_worker/server.py new file mode 100644 index 000000000..871404a4d --- /dev/null +++ b/worker/cq_worker/server.py @@ -0,0 +1,721 @@ +"""Request dispatch and session state. + +The worker is single threaded: requests are handled one at a time, in +arrival order. While a debugging session is paused, :meth:`Server.wait_for_debug_action` +keeps serving read-only requests (completion, inspection, export) so the GUI +stays useful, and returns as soon as a debugger action arrives. +""" + +from __future__ import annotations + +import logging +import os +import sys +import tempfile +import time +import traceback +import types +from modulefinder import ModuleFinder + +import cadquery as cq + +from . import ( + completion, + checking, + exporting, + inspector, + measurement, + measurement_code, + navigation, + network, + selection, + selector_preview, +) +from .console import ConsoleSession +from .debugger import Action, Debugger +from .display import Displayer +from .environment import runtime_environment +from .execution import ( + SCRIPT_FILENAME, + Execution, + RunSettings, + ShownObjects, + describe_variables, + script_api, +) +from .profiling import LineProfiler +from .protocol import ( + LOG_CAPTURE_CHARS, + LOG_MESSAGE_CHARS, + PROTOCOL_VERSION, + Channel, + Message, + truncate_text, +) +from .scene import ( + MAX_STREAMED_MESH_BYTES, + BuildCancelled, + Registry, + SceneBuilder, + find_cq_objects, + to_compound, +) +from .tessellation import GeometryCache, Tolerance + +log = logging.getLogger(__name__) + +#: Seconds between two progress messages of one request. +PROGRESS_INTERVAL = 0.1 + +#: Requests the GUI can interrupt (``KeyboardInterrupt``) while they run. +_INTERRUPTIBLE = {"run", "console"} + +#: Requests that are safe to serve while a debugging session is paused. +_ALLOWED_WHILE_PAUSED = { + "complete", + "outline", + "navigate", + "inspect", + "inspect_geometry", + "measure", + "selector", + "export", + "check", + "imports", + "release", + "check_updates", +} + + +class RequestError(Exception): + """A request that cannot be served; reported to the GUI as an error.""" + + +class ChannelLogHandler(logging.Handler): + """Forwards Python log records (including the script's ``log()``) to the GUI.""" + + def __init__(self, channel: Channel) -> None: + super().__init__(logging.INFO) + self._channel = channel + self._request_id = channel.current_id + self._captured_chars = 0 + self._truncated = False + + def emit(self, record: logging.LogRecord) -> None: + try: + request_id = self._channel.current_id + if self._request_id != request_id: + self._request_id = request_id + self._captured_chars = 0 + self._truncated = False + if self._truncated: + return + + message = record.getMessage() + if record.exc_info: + message += "\n" + "".join(traceback.format_exception(*record.exc_info)) + remaining = LOG_CAPTURE_CHARS - self._captured_chars + retained = min(LOG_MESSAGE_CHARS, remaining) + captured = message[:retained] + self._captured_chars += len(captured) + if len(message) > len(captured) and remaining <= LOG_MESSAGE_CHARS: + message = ( + captured + + f"\n[log output truncated after {LOG_CAPTURE_CHARS} characters " + "for this request; further records were discarded]\n" + ) + self._truncated = True + else: + message = truncate_text(message, LOG_MESSAGE_CHARS, "log") + self._channel.send( + { + "type": "log", + "id": self._channel.current_id, + "level": record.levelname.lower(), + "source": record.name, + "message": message, + } + ) + except Exception: + self.handleError(record) + + +class Server: + def __init__(self, channel: Channel, session: str | None = None) -> None: + """``session`` identifies this worker process among the GUI's + successive workers; it makes scene keys unique across restarts.""" + + self.channel = channel + self.registry = Registry(f"s{session}-n" if session else "n") + self.console = ConsoleSession(Displayer(self.channel.send)) + self.geometry_cache = GeometryCache() + #: Stack frames of inspected workplanes, by scene key. + self.inspections: dict[str, list[cq.Workplane]] = {} + self.interference_allowances: list[tuple[str, str, str]] = [] + self.preview_run_id: int | None = None + self.preview_source = "" + self.preview_names: dict[str, cq.Shape | cq.Workplane] = {} + self._debugger: Debugger | None = None + self._handlers = { + "run": self.run, + "release": self.release, + "complete": self.complete, + "describe": self.describe, + "outline": self.outline, + "navigate": self.navigate, + "inspect": self.inspect, + "inspect_geometry": self.inspect_geometry, + "interference_geometry": self.interference_geometry, + "measure": self.measure, + "selector": self.selector, + "selector_preview": self.selector_preview, + "measurement_code": self.measurement_code, + "console": self.run_console, + "console_reset": self.reset_console, + "export": self.export, + "check": self.check, + "upload": self.upload, + "check_updates": self.check_updates, + "imports": self.imports, + } + + # -- main loop --------------------------------------------------------- + + def serve_forever(self) -> None: + environment = runtime_environment() + self.channel.send( + { + "type": "ready", + "protocol": PROTOCOL_VERSION, + "python": environment["python"], + "cadquery": environment["cadquery"], + "ocp": environment["ocp"], + "executable": environment["executable"], + "completion": completion.is_available(), + "pid": os.getpid(), + } + ) + while True: + try: + request = self.channel.receive() + except KeyboardInterrupt: + # A Ctrl+C sent to the whole process group of a terminal; + # only Stop decides what the worker interrupts. + continue + if request is None or request.get("cmd") == "shutdown": + return + self.dispatch(request) + + def dispatch(self, request: Message) -> None: + request_id = request.get("id") + previous_id, self.channel.current_id = self.channel.current_id, request_id + try: + command = request.get("cmd") + handler = self._handlers.get(command) if isinstance(command, str) else None + if handler is None: + raise RequestError(f"Unknown command {request.get('cmd')!r}") + if request.get("cmd") in _INTERRUPTIBLE: + with self.channel.interruptible(request_id): + reply = handler(request) + else: + reply = handler(request) + if reply is not None: + self.channel.send({"id": request_id, **reply}) + except KeyboardInterrupt: + # Stopped outside the script itself (handlers catch it there). + self.channel.send({"type": "error", "id": request_id, "message": "Stopped"}) + except RequestError as error: + self.channel.send( + {"type": "error", "id": request_id, "message": str(error)} + ) + except Exception as error: + log.debug("Request %r failed", request.get("cmd"), exc_info=True) + message = f"{type(error).__name__}: {error}" + self.channel.send({"type": "error", "id": request_id, "message": message}) + finally: + sys.stdout.flush() + sys.stderr.flush() + self.channel.current_id = previous_id + + # -- running scripts --------------------------------------------------- + + def run(self, request: Message) -> Message: + self.preview_run_id = None + self.preview_names.clear() + self.registry.release(request.get("release", [])) + builder = self._scene_builder(request) + builder.on_part = lambda name, part: self.channel.send( + {"type": "run_part", "id": request["id"], "name": name, "part": part} + ) + execution = Execution( + request.get("script", ""), + request.get("path"), + RunSettings.from_message(request.get("settings")), + ) + debug = bool(request.get("debug")) + path = request.get("path") + project_root = request.get("project_root") or ( + os.path.dirname(os.path.abspath(path)) if path else None + ) + executor = None + if debug: + self._debugger = Debugger( + SCRIPT_FILENAME, + request.get("breakpoints", []), + lambda frame: self._pause(frame, execution, builder), + project_root, + request.get("module_breakpoints", {}), + ) + executor = self._debugger.run + # The debugger traces the script itself; it cannot be profiled too. + profiler = None + if request.get("profile") and not debug: + profiler = LineProfiler(SCRIPT_FILENAME, project_root) + executor = profiler.run + + started = time.perf_counter() + try: + ok = execution.run(executor) + finally: + self._debugger = None + duration = time.perf_counter() - started + + hidden = execution.hidden_names() + objects = variables = None + cancelled = False + if ok or debug: + # A failed plain run keeps the previous model on screen, like the + # original editor; a debugging session always shows where it ended. + shown = execution.shown or find_cq_objects(execution.namespace) + variables = describe_variables(execution.namespace, hidden) + self.console.update_variables( + {k: v for k, v in execution.namespace.items() if k not in hidden} + ) + request_id = request.get("id") + builder.progress = self._progress_reporter(request_id) + builder.cancelled = lambda: self.channel.cancel_requested(request_id) + try: + objects = builder.build(shown) + except (BuildCancelled, KeyboardInterrupt): + # Like a failed run: the previous model stays on screen. + cancelled = True + finally: + self.channel.forget_cancel(request_id) + if objects is not None and not cancelled: + self.interference_allowances = execution.interference_allowances.copy() + if ok and not debug: + self.preview_run_id = request.get("id") + self.preview_source = execution.source + self.preview_names = { + name: obj + for name, obj in execution.namespace.items() + if isinstance(obj, (cq.Shape, cq.Workplane)) + } + return { + "type": "run_finished", + "ok": ok, + "debug": debug, + "stopped": execution.stopped, + "cancelled": cancelled, + "interrupted": execution.interrupted, + # Also after a failure: where the time went until then. + "profile": profiler.result() if profiler else None, + "objects": objects, + "variables": variables, + "error": execution.error, + "checks": execution.checks.results, + "duration": duration, + "timings": { + "script": duration, + **builder.stats.to_message(), + # Wall clock, so the GUI can tell how long the reply took + # to serialize and arrive. + "sent_at": time.time(), + }, + } + + def _progress_reporter(self, request_id): + """Sends how far meshing is, at most every :data:`PROGRESS_INTERVAL` + seconds, and always the start and the end.""" + + last = None + + def report(done: int, total: int) -> None: + nonlocal last + now = time.monotonic() + if last is not None and 0 < done < total and now - last < PROGRESS_INTERVAL: + return + last = now + self.channel.send( + { + "type": "progress", + "id": request_id, + "stage": "meshing", + "done": done, + "total": total, + } + ) + + return report + + def _pause( + self, frame: types.FrameType, execution: Execution, builder: SceneBuilder + ) -> Action: + hidden = execution.hidden_names() + local_names = frame.f_locals + assert self._debugger is not None + self.channel.send( + { + "type": "debug_paused", + "id": self.channel.current_id, + "line": frame.f_lineno, + "path": ( + self._debugger.source_path(frame) + if frame.f_code.co_filename != SCRIPT_FILENAME + else None + ), + "variables": describe_variables(local_names, hidden), + "objects": builder.build(find_cq_objects(local_names)), + } + ) + return self.wait_for_debug_action() + + def wait_for_debug_action(self) -> Action: + while True: + request = self.channel.receive() + if request is None: + return Action.STOP + command = request.get("cmd") + if command == "debug": + if "breakpoints" in request and self._debugger is not None: + self._debugger.set_breakpoints( + request["breakpoints"], request.get("module_breakpoints", {}) + ) + return Action(request.get("action", "continue")) + if command == "shutdown": + sys.exit(0) + if command in _ALLOWED_WHILE_PAUSED: + self.dispatch(request) + else: + self.channel.send( + { + "type": "error", + "id": request.get("id"), + "message": "Not available while debugging; continue or stop first", + } + ) + + def release(self, request: Message) -> None: + keys = request.get("keys", []) + self.registry.release(keys) + for key in keys: + self.inspections.pop(key, None) + + # -- console ----------------------------------------------------------- + + def run_console(self, request: Message) -> Message: + try: + picked = selection.PickedSelection.from_message(request.get("selection")) + except measurement.MeasurementError as error: + raise RequestError(str(error)) from None + self.console.set_selection(lambda: picked.resolve(self.registry)) + more = self.console.execute(request.get("source", ""), request.get("id")) + shown = self.console.take_shown() + if shown: + self.channel.send( + { + "type": "scene_add", + "id": request.get("id"), + "objects": self._scene_builder(request).build(shown), + } + ) + return {"type": "console_result", "more": more} + + def reset_console(self, request: Message) -> Message: + self.console.reset() + return {"type": "console_result", "more": False} + + # -- editor services --------------------------------------------------- + + def complete(self, request: Message) -> Message: + if request.get("target") == "console": + namespace = self.console.namespace + else: + namespace = self._script_namespace() + result = completion.complete( + request.get("source", ""), + int(request.get("line", 1)), + int(request.get("column", 0)), + request.get("path"), + namespace, + ) + return {"type": "completions", **result} + + def describe(self, request: Message) -> Message: + """Documentation of the name under the editor's pointer.""" + + result = completion.describe( + request.get("source", ""), + int(request.get("line", 1)), + int(request.get("column", 0)), + request.get("path"), + self._script_namespace(), + ) + return {"type": "description", **result} + + def outline(self, request: Message) -> Message: + return { + "type": "outline", + "symbols": navigation.outline(request.get("source", "")), + } + + def navigate(self, request: Message) -> Message: + result = navigation.navigate( + request.get("source", ""), + request.get("path"), + request.get("project_root"), + int(request.get("line", 1)), + int(request.get("column", 0)), + request.get("mode", ""), + ) + return {"type": "navigation", "mode": request["mode"], **result} + + @staticmethod + def _script_namespace() -> dict: + return {**script_api(ShownObjects()), "__name__": "__cq_main__"} + + def imports(self, request: Message) -> Message: + """Local modules imported by a script, so the GUI can watch them too.""" + + path = request["path"] + finder = ModuleFinder([os.path.dirname(os.path.abspath(path))]) + try: + finder.run_script(path) + except SyntaxError as error: + log.warning("Syntax error in %s: %s", path, error) + except Exception as error: + log.warning("Cannot determine imports of %s: %s", path, error) + paths = [ + file + for name, module in finder.modules.items() + if name != "__main__" + if isinstance(file := getattr(module, "__file__", None), str) + and os.path.isfile(file) + ] + return {"type": "imports", "paths": sorted(set(paths))} + + # -- inspection -------------------------------------------------------- + + def inspect(self, request: Message) -> Message: + key = request["key"] + obj = self.registry.get(key).obj + if not isinstance(obj, cq.Workplane): + raise RequestError("Only workplanes can be inspected") + frames = inspector.stack_frames(obj) + self.inspections[key] = frames + return { + "type": "inspection", + "key": key, + "frames": inspector.describe_stack(frames), + } + + def inspect_geometry(self, request: Message) -> Message: + frames = self.inspections.get(request["key"]) + if frames is None: + raise RequestError("Object is no longer inspected") + frame = frames[int(request["frame"])] + item = request.get("item") + geometry = inspector.frame_geometry( + frame, None if item is None else int(item), self._tolerance(request) + ) + return {"type": "inspection_geometry", **geometry} + + def interference_geometry(self, request: Message) -> Message: + from .interference import overlap_shape + from .tessellation import tessellate + + common = overlap_shape(self.registry, request["first"], request["second"]) + mesh = tessellate(common.wrapped, self._tolerance(request)) + if mesh is None: + raise RequestError("The shared volume could not be drawn") + if mesh.byte_size() > MAX_STREAMED_MESH_BYTES: + raise RequestError("The shared-volume mesh exceeds the transfer limit") + non_finite = mesh.non_finite_array() + if non_finite is not None: + raise RequestError(f"The shared-volume mesh has non-finite {non_finite}") + return {"type": "interference_geometry", "mesh": mesh.to_message()} + + def measure(self, request: Message) -> Message: + try: + result = measurement.measure( + self.registry, request.get("selections"), request.get("objects") + ) + except measurement.MeasurementError as error: + raise RequestError(str(error)) from None + return {"type": "measurement", **result} + + def measurement_code(self, request: Message) -> Message: + """Code repeating a measurement with the script's variables, which + the console holds after a run.""" + + try: + result = measurement_code.measurement_code( + self.registry, + self.console.namespace, + request.get("selections"), + request.get("objects"), + ) + except measurement.MeasurementError as error: + raise RequestError(str(error)) from None + return {"type": "measurement_code", **result} + + def selector(self, request: Message) -> Message: + try: + result = selection.selector_candidates( + self.registry, request.get("selections") + ) + except measurement.MeasurementError as error: + raise RequestError(str(error)) from None + return {"type": "selector", **result} + + def selector_preview(self, request: Message) -> Message: + if request.get("run_id") != self.preview_run_id or self.preview_run_id is None: + return { + "type": "selector_preview", + "active": False, + "count": 0, + "matches": [], + "message": None, + } + return { + "type": "selector_preview", + **selector_preview.preview( + self.registry, + self.preview_names, + self.preview_source, + int(request.get("line", 0)), + int(request.get("column", 0)), + request.get("preferred_key"), + ), + } + + # -- files and network ------------------------------------------------- + + def check(self, request: Message) -> Message: + from .interference import analyze_interferences, apply_allowances, summarize + + keys = request.get("keys", []) + flat_parts = bool(request.get("flat_parts", False)) + interferences = analyze_interferences( + self.registry, + keys, + flat_parts=flat_parts, + tolerance=float(request.get("interference_tolerance", 1e-6)), + clearance=float(request.get("clearance", 0.0)), + ) + apply_allowances( + self.registry, + keys, + interferences, + self.interference_allowances, + flat_parts=flat_parts, + ) + return { + "type": "geometry_checked", + "reports": checking.check_registry( + self.registry, + keys, + flat_parts, + ), + "interferences": interferences, + "assessment": summarize(interferences), + } + + def export(self, request: Message) -> Message: + try: + exporting.export( + self.registry, + request.get("keys", []), + request["format"], + request["path"], + float(request.get("tolerance", 0.1)), + float(request.get("angular_tolerance", 0.1)), + step_mode=request.get("step_mode", "default"), + step_schema=request.get("step_schema", "ap242"), + stl_ascii=bool(request.get("stl_ascii", False)), + flat_parts=bool(request.get("flat_parts", False)), + unit=request.get("unit", "millimeter"), + on_invalid=request.get("on_invalid", "check"), + on_interference=request.get("on_interference", "check"), + interference_allowances=self.interference_allowances, + ) + except checking.GeometryInvalid as error: + return { + "type": "geometry_invalid", + "reports": error.reports, + "interferences": error.interferences, + } + return {"type": "export_finished", "path": request["path"]} + + def upload(self, request: Message) -> Message: + file_type = request.get("file_type", "step").lower() + if file_type == "py": + data = request.get("source", "").encode("utf-8") + else: + shapes = self.registry.subtree_shapes(request.get("keys", [])) + if not shapes: + raise RequestError("Please select a model to upload") + data = _export_to_bytes(to_compound(shapes), file_type) + result = network.upload(request["url"], data, f"model.{file_type}") + return {"type": "upload_finished", **result} + + def check_updates(self, request: Message) -> Message: + """Newer CadQuery releases (unless ``cadquery`` is false) and, given + the running CQ-editor's version as ``editor``, newer CQ-editors.""" + + reply: Message = {"type": "updates", "current": cq.__version__, "newer": []} + if request.get("cadquery", True): + reply["newer"] = network.newer_releases(cq.__version__) + editor = request.get("editor") + if editor: + reply["editor"] = { + "current": editor, + "newer": network.editor_releases(editor), + } + return reply + + # -- helpers ----------------------------------------------------------- + + @staticmethod + def _tolerance(request: Message) -> Tolerance: + scene = request.get("scene") or {} + return Tolerance( + linear=float(scene.get("linear_tolerance", Tolerance.linear)), + angular=float(scene.get("angular_tolerance", Tolerance.angular)), + ) + + def _scene_builder(self, request: Message) -> SceneBuilder: + scene = request.get("scene") or {} + return SceneBuilder( + self.registry, + self._tolerance(request), + merge_assemblies=bool(scene.get("merge_assemblies", False)), + geometry_cache=self.geometry_cache, + known_geometry=request.get("known_geometry", ()), + ) + + +def _export_to_bytes(compound: cq.Compound, file_type: str) -> bytes: + fd, path = tempfile.mkstemp(suffix=f".{file_type}") + os.close(fd) + try: + if file_type == "stl": + compound.exportStl(path) + elif file_type == "step": + compound.exportStep(path) + else: + raise RequestError(f"Unsupported upload type {file_type!r}") + with open(path, "rb") as file: + return file.read() + finally: + os.unlink(path) diff --git a/worker/cq_worker/tessellation.py b/worker/cq_worker/tessellation.py new file mode 100644 index 000000000..4271880d6 --- /dev/null +++ b/worker/cq_worker/tessellation.py @@ -0,0 +1,863 @@ +"""Triangulate OpenCascade shapes into compact, GUI-ready arrays. + +Faces are meshed in parallel by BRepMesh and written out through OCCT's glTF +writer, which emits positions, exact surface normals and indices from C++ in a +single pass. Reading that binary back with numpy is orders of magnitude faster +than walking ``Poly_Triangulation`` nodes from Python. The same triangles serve +picking: each is tagged with its OCCT face id from per-face triangle counts. +Edges and free vertices are discretized directly, since glTF has no notion of +them. + +Every array travels to the GUI as base64-encoded little-endian binary. +""" + +from __future__ import annotations + +import atexit +import base64 +import contextlib +import hashlib +import io +import json +import os +import shutil +import struct +import tempfile +import threading +import time +from collections import OrderedDict +from dataclasses import dataclass +from functools import cache + +import numpy as np +import OCP +from OCP.BRep import BRep_Tool +from OCP.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_Curve2d, BRepAdaptor_Surface +from OCP.BRepBndLib import BRepBndLib +from OCP.BRepLProp import BRepLProp_SLProps +from OCP.BRepMesh import BRepMesh_IncrementalMesh +from OCP.Bnd import Bnd_Box +from OCP.BinTools import BinTools, BinTools_FormatVersion +from OCP.GCPnts import GCPnts_TangentialDeflection +from OCP.Message import Message_ProgressRange +from OCP.RWGltf import RWGltf_CafWriter +from OCP.TCollection import TCollection_AsciiString, TCollection_ExtendedString +from OCP.TDocStd import TDocStd_Document +from OCP.TopAbs import TopAbs_EDGE, TopAbs_FACE, TopAbs_REVERSED, TopAbs_VERTEX +from OCP.TopExp import TopExp, TopExp_Explorer +from OCP.TopLoc import TopLoc_Location +from OCP.TopoDS import TopoDS, TopoDS_Shape +from OCP.XCAFDoc import XCAFDoc_DocumentTool + +# ``ShapeMap`` is the indexed map of shapes that ``TopExp.MapShapes_s`` fills: +# its 1-based indices are the topology ids the GUI picks. Tests use it too. +try: + # OCP 7.x exposes generated collection aliases in their OCCT package. + from OCP.TColStd import TColStd_IndexedDataMapOfStringString as _StringMap + from OCP.TopTools import TopTools_IndexedMapOfShape as ShapeMap +except ImportError: + # OCP 8 generates all collection specializations in one module. + from OCP.collections import ( + IndexedDataMap_TCollection_AsciiString_TCollection_AsciiString as _StringMap, + ) + from OCP.collections import ( + IndexedMap_TopoDS_Shape_TopTools_ShapeMapHasher as ShapeMap, + ) + +from .environment import ocp_version + +#: Bump whenever a change to this module meshes the same shape with the same +#: tolerances differently: the version is part of every geometry id. +MESH_FORMAT = 2 + +#: The angle of an edge with a face on one side only, or none (a wire): an +#: outline, which the GUI always draws. +OPEN_EDGE_ANGLE = 180.0 + +# Never mesh finer than this, whatever the model size (model units). +MIN_DEFLECTION = 1e-4 +# A worker is long-lived, so cached meshes need a hard memory ceiling. The +# serialized arrays dominate the size and this limit is deliberately modest +# compared with the memory normally available to OCCT itself. +DEFAULT_CACHE_BYTES = 256 * 1024 * 1024 +# Scratch files of killed workers older than this are removed. +STALE_SCRATCH_SECONDS = 24 * 3600 + +_SCRATCH_PREFIX = "cq-editor-mesh-" +_scratch_dir: str | None = None + +_GLB_MAGIC = 0x46546C67 # "glTF" +_CHUNK_JSON = 0x4E4F534A +_CHUNK_BIN = 0x004E4942 +_COMPONENT_TYPES = { + 5121: np.uint8, + 5123: np.uint16, + 5125: np.uint32, + 5126: np.float32, +} +_COMPONENT_COUNTS = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16} + + +class TessellationError(RuntimeError): + pass + + +@dataclass(frozen=True) +class Tolerance: + """Mesh quality settings.""" + + #: Chordal deviation, relative to the shape's bounding-box diagonal. + linear: float = 1e-3 + #: Maximum angle between adjacent mesh normals, in radians. + angular: float = 0.2 + + +@dataclass +class Mesh: + positions: np.ndarray # (n, 3) float32 + normals: np.ndarray # (n, 3) float32 + indices: np.ndarray # (m,) uint32, three per triangle + edges: np.ndarray # (k, 6) float32, one line segment per row + points: np.ndarray # (p, 3) float32 + # Separate pick triangles, only when the display triangles cannot be + # matched to their faces; normally empty. + face_positions: np.ndarray # (n, 3) float32, grouped by OCCT face + face_indices: np.ndarray # (m,) uint32, three per triangle + # 1-based OCCT face id per pick triangle: the display triangles, or the + # separate pick triangles when ``face_indices`` is set. + triangle_faces: np.ndarray # (m / 3,) uint32 + segment_edges: np.ndarray # (k,) uint32, 1-based OCCT edge ids + # Degrees between the faces that meet at each segment's edge (see + # ``edge_angles``), so the GUI can leave out smooth edges. + segment_angles: np.ndarray # (k,) float32 + topology_vertices: np.ndarray # (v, 3) float32, in 1-based id order + + def is_empty(self) -> bool: + return not (len(self.indices) or len(self.edges) or len(self.points)) + + def bounds(self) -> tuple[list[float], list[float]]: + coords = [ + a.reshape(-1, 3) + for a in (self.positions, self.edges, self.points) + if a.size + ] + stacked = np.concatenate(coords) + return stacked.min(axis=0).tolist(), stacked.max(axis=0).tolist() + + def byte_size(self) -> int: + return sum( + array.nbytes + for array in ( + self.positions, + self.normals, + self.indices, + self.edges, + self.points, + self.face_positions, + self.face_indices, + self.triangle_faces, + self.segment_edges, + self.segment_angles, + self.topology_vertices, + ) + ) + + def non_finite_array(self) -> str | None: + """Name the first floating mesh array unsafe to put on the wire.""" + for name in ( + "positions", + "normals", + "edges", + "points", + "segment_angles", + "face_positions", + "topology_vertices", + ): + if not np.isfinite(getattr(self, name)).all(): + return name + return None + + def to_message(self, geometry_id: str = "") -> dict: + lo, hi = self.bounds() + return { + "id": geometry_id, + "positions": _encode(self.positions, " str: + """What makes a mesh besides the shape and the tolerances. + + This module's format and the OpenCascade bindings it runs on: their + version and the installed binary itself, so another environment, or OCP + reinstalled with the same version number, is another generator too. + """ + + try: + path = os.path.abspath(getattr(OCP, "OCP", OCP).__file__) + status = os.stat(path) + binary = f"{os.path.normcase(path)} {status.st_size} {status.st_mtime_ns}" + except (AttributeError, TypeError, OSError): + binary = "unknown binary" + version = getattr(OCP, "__version__", "unknown") + return f"cq-editor-mesh {MESH_FORMAT}; OCP {version} ({ocp_version()}); {binary}" + + +class GeometryCache: + """Content-addressed LRU cache of tessellated OCCT shapes. + + The identifier is calculated from a triangle-free BREP representation, + the two tessellation tolerances and the :func:`mesh_generator`. It is + stable when a script recreates the same part, unlike Python object + identity or OCCT's in-process hash code. The GUI keeps meshes across + worker restarts, including a switch to another Python environment, and + the generator ensures an id never names a mesh another mesher made. + """ + + def __init__( + self, max_bytes: int = DEFAULT_CACHE_BYTES, generator: str | None = None + ) -> None: + self.max_bytes = max(0, max_bytes) + generator_bytes = (generator or mesh_generator()).encode() + self._generator = struct.pack(" str: + stream = io.BytesIO() + BinTools.Write_s( + shape, + stream, + False, + False, + BinTools_FormatVersion.BinTools_FormatVersion_CURRENT, + ) + digest = hashlib.blake2b(digest_size=16, person=b"cq-editor-mesh") + digest.update(self._generator) + digest.update(struct.pack(" str: + return self._aliases.get(geometry_id, geometry_id) + + def get(self, geometry_id: str) -> Mesh | None: + geometry_id = self.canonical_id(geometry_id) + mesh = self._meshes.get(geometry_id) + if mesh is not None: + self._meshes.move_to_end(geometry_id) + return mesh + + def put(self, geometry_id: str, mesh: Mesh) -> None: + if self.max_bytes == 0 or mesh.byte_size() > self.max_bytes: + return + previous = self._meshes.pop(geometry_id, None) + if previous is not None: + self._bytes -= previous.byte_size() + self._meshes[geometry_id] = mesh + self._bytes += mesh.byte_size() + while self._bytes > self.max_bytes: + removed_id, removed = self._meshes.popitem(last=False) + self._bytes -= removed.byte_size() + self._aliases = { + alias: target + for alias, target in self._aliases.items() + if target != removed_id + } + + def tessellate( + self, + shape: TopoDS_Shape, + tolerance: Tolerance, + topology: TopologyIndex, + geometry_id: str | None = None, + ) -> tuple[str, Mesh | None]: + geometry_id = self.canonical_id( + geometry_id or self.identifier(shape, tolerance) + ) + cached = self.get(geometry_id) + if cached is not None: + return geometry_id, cached + mesh = tessellate(shape, tolerance, topology) + if mesh is not None: + self.put(geometry_id, mesh) + # OCCT changes internal shape flags while meshing. Treat the + # resulting signature as an alias so the same live part remains + # cacheable in later console/debug requests. + after = self.identifier(shape, tolerance) + if after != geometry_id: + self._aliases[after] = geometry_id + return geometry_id, mesh + + +@dataclass(frozen=True) +class TopologyIndex: + """1-based OCCT subshape order used by picking and the live registry. + + The identifiers remain valid only while this exact registry entry is + alive. OCCT does not guarantee that the same number names the same + semantic feature after the model is rebuilt or remodeled. + """ + + faces: tuple[TopoDS_Shape, ...] + edges: tuple[TopoDS_Shape, ...] + vertices: tuple[TopoDS_Shape, ...] + + @classmethod + def build(cls, shape: TopoDS_Shape) -> TopologyIndex: + def mapped(kind) -> tuple[TopoDS_Shape, ...]: + index = ShapeMap() + TopExp.MapShapes_s(shape, kind, index) + return tuple(index.FindKey(i) for i in range(1, index.Extent() + 1)) + + return cls(mapped(TopAbs_FACE), mapped(TopAbs_EDGE), mapped(TopAbs_VERTEX)) + + def get(self, kind: str, identifier: int) -> TopoDS_Shape: + collection = { + "face": self.faces, + "edge": self.edges, + "vertex": self.vertices, + }.get(kind) + if collection is None: + raise ValueError(f"Unknown topology kind {kind!r}") + if identifier < 1 or identifier > len(collection): + raise IndexError(f"Unknown {kind} id {identifier}") + return collection[identifier - 1] + + +def tessellate( + shape: TopoDS_Shape, + tolerance: Tolerance, + topology: TopologyIndex | None = None, +) -> Mesh | None: + """Mesh ``shape``; returns ``None`` when it has no drawable geometry.""" + + box = Bnd_Box() + BRepBndLib.Add_s(shape, box, False) + if box.IsVoid(): + return None + + diagonal = box.CornerMin().Distance(box.CornerMax()) + deflection = max(tolerance.linear * diagonal, MIN_DEFLECTION) + + topology = topology or TopologyIndex.build(shape) + positions, normals, indices = _mesh_faces(shape, deflection, tolerance.angular) + triangle_faces = _display_triangle_faces(shape, positions, indices) + if triangle_faces is None: + face_positions, face_indices, triangle_faces = _topology_faces(topology.faces) + else: + face_positions, face_indices = _empty(3), np.zeros(0, dtype=np.uint32) + edges, segment_edges = _discretize_edges( + topology.edges, deflection, tolerance.angular + ) + segment_angles = edge_angles(topology)[segment_edges - 1] + mesh = Mesh( + positions=positions, + normals=normals, + indices=indices, + edges=edges, + points=_free_vertices(shape), + face_positions=face_positions, + face_indices=face_indices, + triangle_faces=triangle_faces, + segment_edges=segment_edges, + segment_angles=segment_angles.astype(np.float32), + topology_vertices=_topology_vertices(topology.vertices), + ) + return None if mesh.is_empty() else mesh + + +def _encode(array: np.ndarray, dtype: str) -> str: + data = np.ascontiguousarray(array, dtype=dtype).tobytes() + return base64.b64encode(data).decode("ascii") + + +def _empty(columns: int) -> np.ndarray: + return np.zeros((0, columns), dtype=np.float32) + + +def _topods(kind: str, shape: TopoDS_Shape) -> TopoDS_Shape: + """Downcast a shape with the generated spelling used by OCP 7 or 8.""" + + caster = getattr(TopoDS, f"{kind}_s", None) or getattr(TopoDS, kind) + return caster(shape) + + +def _mesh_faces( + shape: TopoDS_Shape, deflection: float, angular: float +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + if not TopExp_Explorer(shape, TopAbs_FACE).More(): + return _empty(3), _empty(3), np.zeros(0, dtype=np.uint32) + + BRepMesh_IncrementalMesh(shape, deflection, False, angular, True) + + document = TDocStd_Document(TCollection_ExtendedString("XmlOcaf")) + XCAFDoc_DocumentTool.ShapeTool_s(document.Main()).AddShape(shape, False) + + path = _scratch_path() + try: + writer = RWGltf_CafWriter(TCollection_AsciiString(path), True) + writer.SetMergeFaces(True) + ok = writer.Perform(document, _StringMap(), Message_ProgressRange()) + if not ok: + raise TessellationError("the glTF writer failed to export the mesh") + with open(path, "rb") as file: + data = file.read() + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(path) + + return read_glb(data) + + +def _scratch_path() -> str: + """The file of this thread's glTF round trip. + + OCCT's glTF writer only writes files, so every mesh passes through one + private directory per worker process. A worker killed while meshing (Run + > Stop) cannot clean up after itself, so the next worker removes such + leftovers once they are old enough to belong to no running process. + """ + + global _scratch_dir + if _scratch_dir is None or not os.path.isdir(_scratch_dir): + _remove_stale_scratch(tempfile.gettempdir()) + _scratch_dir = tempfile.mkdtemp(prefix=_SCRATCH_PREFIX) + atexit.register(shutil.rmtree, _scratch_dir, True) + return os.path.join(_scratch_dir, f"mesh-{threading.get_ident()}.glb") + + +def _remove_stale_scratch(directory: str, max_age: float = STALE_SCRATCH_SECONDS): + cutoff = time.time() - max_age + with contextlib.suppress(OSError), os.scandir(directory) as entries: + for entry in entries: + # Directories of this module, and the single files that releases + # before it created with the same prefix. + if not entry.name.startswith(_SCRATCH_PREFIX) and not ( + entry.name.startswith("cq-editor-") and entry.name.endswith(".glb") + ): + continue + with contextlib.suppress(OSError): + if entry.stat().st_mtime >= cutoff: + continue + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.path, ignore_errors=True) + else: + os.unlink(entry.path) + + +def read_glb(data: bytes) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Collect every triangle primitive of a binary glTF into world space.""" + + magic, version, _length = struct.unpack_from(" None: + nonlocal vertex_count + node = document["nodes"][node_index] + transform = parent @ _node_matrix(node) + if "mesh" in node: + rotation = transform[:3, :3] + for primitive in document["meshes"][node["mesh"]]["primitives"]: + if primitive.get("mode", 4) != 4: # only triangle lists + continue + attributes = primitive["attributes"] + pos = reader.read(attributes["POSITION"]).reshape(-1, 3) + if "NORMAL" in attributes: + nor = reader.read(attributes["NORMAL"]).reshape(-1, 3) + else: + nor = np.zeros_like(pos) + if "indices" in primitive: + idx = reader.read(primitive["indices"]).astype(np.uint32) + else: + idx = np.arange(len(pos), dtype=np.uint32) + + positions.append(pos @ rotation.T + transform[:3, 3]) + nor = nor @ rotation.T + lengths = np.linalg.norm(nor, axis=1, keepdims=True) + normals.append(nor / np.where(lengths > 0, lengths, 1)) + indices.append(idx + vertex_count) + vertex_count += len(pos) + for child in node.get("children", []): + visit(child, transform) + + scene = document.get("scenes", [{}])[document.get("scene", 0)] + for root in scene.get("nodes", []): + visit(root, np.eye(4)) + + if not positions: + return _empty(3), _empty(3), np.zeros(0, dtype=np.uint32) + return ( + np.concatenate(positions).astype(np.float32), + np.concatenate(normals).astype(np.float32), + np.concatenate(indices), + ) + + +class _AccessorReader: + def __init__(self, document: dict, binary: bytes) -> None: + self._accessors = document.get("accessors", []) + self._views = document.get("bufferViews", []) + self._binary = binary + + def read(self, index: int) -> np.ndarray: + accessor = self._accessors[index] + view = self._views[accessor["bufferView"]] + dtype = np.dtype(_COMPONENT_TYPES[accessor["componentType"]]).newbyteorder("<") + components = _COMPONENT_COUNTS[accessor["type"]] + count = accessor["count"] + start = view.get("byteOffset", 0) + accessor.get("byteOffset", 0) + stride = view.get("byteStride", 0) + element_size = dtype.itemsize * components + + if stride and stride != element_size: + rows = np.frombuffer( + self._binary, + dtype=np.uint8, + count=stride * (count - 1) + element_size, + offset=start, + ) + rows = np.lib.stride_tricks.as_strided( + rows, shape=(count, element_size), strides=(stride, 1) + ) + return np.ascontiguousarray(rows).view(dtype).reshape(-1) + return np.frombuffer( + self._binary, dtype=dtype, count=count * components, offset=start + ) + + +def _node_matrix(node: dict) -> np.ndarray: + if "matrix" in node: + # glTF matrices are column-major. + return np.array(node["matrix"], dtype=float).reshape(4, 4).T + + matrix = np.eye(4) + if "scale" in node: + matrix = np.diag([*node["scale"], 1.0]) @ matrix + if "rotation" in node: + x, y, z, w = node["rotation"] + rotation = np.array( + [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ] + ) + rotated = np.eye(4) + rotated[:3, :3] = rotation + matrix = rotated @ matrix + if "translation" in node: + translated = np.eye(4) + translated[:3, 3] = node["translation"] + matrix = translated @ matrix + return matrix + + +def _display_triangle_faces( + shape: TopoDS_Shape, positions: np.ndarray, indices: np.ndarray +) -> np.ndarray | None: + """The 1-based OCCT face id of every display triangle. + + The glTF writer emits the triangles of each meshed face in explorer + order. Validate every proposed face group against its OCCT triangulation + bounds and a few triangle centroids: equal counts alone cannot detect an + exporter that changed face order. This remains much cheaper than walking + every node from Python. Returns ``None`` on any mismatch, and the caller + extracts separate pick triangles instead of guessing. + """ + + if len(indices) % 3: + return None + triangles = np.asarray(indices).reshape(-1, 3) + if triangles.size and ( + int(triangles.min()) < 0 or int(triangles.max()) >= len(positions) + ): + return None + + index = ShapeMap() + TopExp.MapShapes_s(shape, TopAbs_FACE, index) + identifiers, counts = [], [] + offset = 0 + explorer = TopExp_Explorer(shape, TopAbs_FACE) + while explorer.More(): + face = _topods("Face", explorer.Current()) + location = TopLoc_Location() + triangulation = BRep_Tool.Triangulation_s(face, location) + if triangulation is not None and triangulation.NbTriangles() > 0: + count = triangulation.NbTriangles() + group = triangles[offset : offset + count] + if len(group) != count or not _face_group_matches( + triangulation, location, positions, group + ): + return None + identifiers.append(index.FindIndex(face)) + counts.append(count) + offset += count + explorer.Next() + faces = np.repeat(np.array(identifiers, dtype=np.uint32), counts) + return faces if offset == len(triangles) else None + + +def _face_group_matches( + triangulation, + location: TopLoc_Location, + positions: np.ndarray, + triangles: np.ndarray, +) -> bool: + """Check a glTF triangle group against OCCT geometry, not just its size.""" + + points = positions[triangles] + actual_bounds = np.concatenate((points.min(axis=(0, 1)), points.max(axis=(0, 1)))) + + box = Bnd_Box() + if not triangulation.MinMax(box, location.Transformation(), True): + return False + lo, hi = box.CornerMin(), box.CornerMax() + expected_bounds = np.array( + [lo.X(), lo.Y(), lo.Z(), hi.X(), hi.Y(), hi.Z()], dtype=np.float32 + ) + if not _f32_close(actual_bounds, expected_bounds).all(): + return False + + actual_centers = points.mean(axis=1) + sample_indices = { + 1, + (triangulation.NbTriangles() + 1) // 2, + triangulation.NbTriangles(), + } + transform = location.Transformation() + for triangle_index in sample_indices: + triangle = triangulation.Triangle(triangle_index) + expected_center = np.array( + [ + ( + point.X(), + point.Y(), + point.Z(), + ) + for point in ( + triangulation.Node(triangle.Value(corner)).Transformed(transform) + for corner in (1, 2, 3) + ) + ], + dtype=np.float32, + ).mean(axis=0) + if not _f32_close(actual_centers, expected_center).all(axis=1).any(): + return False + return True + + +def _f32_close(actual: np.ndarray, expected: np.ndarray) -> np.ndarray: + """Compare serialized f32 geometry within two units in the last place.""" + + actual = np.asarray(actual, dtype=np.float32) + expected = np.asarray(expected, dtype=np.float32) + spacing = np.maximum(np.abs(np.spacing(actual)), np.abs(np.spacing(expected))) + tolerance = np.maximum(spacing * 2, np.float32(1e-5)) + return np.abs(actual - expected) <= tolerance + + +def _topology_faces( + faces: tuple[TopoDS_Shape, ...], +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Return separate pick triangles tagged with their 1-based OCCT face id. + + Slow (it walks every node from Python); only a fallback for display + triangles that :func:`_display_triangle_faces` cannot match. + """ + + positions: list[np.ndarray] = [] + indices: list[np.ndarray] = [] + identifiers: list[np.ndarray] = [] + offset = 0 + for identifier, raw_face in enumerate(faces, start=1): + face = _topods("Face", raw_face) + location = TopLoc_Location() + triangulation = BRep_Tool.Triangulation_s(face, location) + if triangulation is None: + continue + + transform = location.Transformation() + nodes = np.array( + [ + (point.X(), point.Y(), point.Z()) + for point in ( + triangulation.Node(i).Transformed(transform) + for i in range(1, triangulation.NbNodes() + 1) + ) + ], + dtype=np.float32, + ).reshape(-1, 3) + triangles = np.array( + [ + [triangle.Value(i) - 1 + offset for i in (1, 2, 3)] + for triangle in triangulation.Triangles() + ], + dtype=np.uint32, + ).reshape(-1, 3) + if face.Orientation() == TopAbs_REVERSED and len(triangles): + triangles[:, [1, 2]] = triangles[:, [2, 1]] + + positions.append(nodes) + indices.append(triangles.reshape(-1)) + identifiers.append(np.full(len(triangles), identifier, dtype=np.uint32)) + offset += len(nodes) + + if not positions: + return _empty(3), np.zeros(0, dtype=np.uint32), np.zeros(0, dtype=np.uint32) + return ( + np.concatenate(positions), + np.concatenate(indices), + np.concatenate(identifiers), + ) + + +def edge_angles(topology: TopologyIndex) -> np.ndarray: + """The angle in degrees between the faces that meet at each edge of + ``topology``, in id order, measured at the middle of the edge. + + 0 where they meet smoothly: a fillet's border, a seam, a face split in + two. 90 at the corner of a box. :data:`OPEN_EDGE_ANGLE` for an edge of + one face only, or of none (a wire), and wherever a normal cannot be + found, so that such edges are always drawn. The GUI leaves out the + edges below an angle the user chooses. + """ + + index = ShapeMap() + for edge in topology.edges: + index.Add(edge) + normals: list[list[np.ndarray | None]] = [[] for _ in topology.edges] + for raw_face in topology.faces: + face = _topods("Face", raw_face) + surface = BRepAdaptor_Surface(face) + properties = BRepLProp_SLProps(surface, 1, 1e-7) + reversed_face = face.Orientation() == TopAbs_REVERSED + explorer = TopExp_Explorer(face, TopAbs_EDGE) + while explorer.More(): + identifier = index.FindIndex(explorer.Current()) + if identifier: + edge = _topods("Edge", explorer.Current()) + normals[identifier - 1].append( + _normal_at_middle(edge, face, properties, reversed_face) + ) + explorer.Next() + + angles = np.full(len(topology.edges), OPEN_EDGE_ANGLE, dtype=np.float32) + for position, found in enumerate(normals): + # A seam is listed twice by its one face, and is smooth. + if len(found) < 2 or any(normal is None for normal in found): + continue + present = [normal for normal in found if normal is not None] + cosines = [ + float(np.dot(a, b)) for i, a in enumerate(present) for b in present[i + 1 :] + ] + angles[position] = np.degrees(np.arccos(np.clip(min(cosines), -1.0, 1.0))) + return angles + + +def _normal_at_middle( + edge, face, properties: BRepLProp_SLProps, reversed_face: bool +) -> np.ndarray | None: + """The outward normal of ``face`` at the middle of ``edge``, one of its + edges, from the edge's curve on the face; ``None`` when it is not + defined there (a cone's apex) or cannot be computed.""" + + try: + curve = BRepAdaptor_Curve2d(edge, face) + uv = curve.Value(0.5 * (curve.FirstParameter() + curve.LastParameter())) + properties.SetParameters(uv.X(), uv.Y()) + if not properties.IsNormalDefined(): + return None + normal = properties.Normal() + except Exception: # no curve on the surface, or an unbounded parameter + return None + vector = np.array((normal.X(), normal.Y(), normal.Z())) + return -vector if reversed_face else vector + + +def _discretize_edges( + edges: tuple[TopoDS_Shape, ...], deflection: float, angular: float +) -> tuple[np.ndarray, np.ndarray]: + + segments: list[np.ndarray] = [] + identifiers: list[np.ndarray] = [] + for identifier, raw_edge in enumerate(edges, start=1): + edge = _topods("Edge", raw_edge) + if BRep_Tool.Degenerated_s(edge): + continue + try: + sampler = GCPnts_TangentialDeflection( + BRepAdaptor_Curve(edge), angular, deflection + ) + except Exception: # an edge without a 3D curve; nothing to draw + continue + count = sampler.NbPoints() + if count < 2: + continue + polyline = np.array( + [ + (p.X(), p.Y(), p.Z()) + for p in (sampler.Value(j) for j in range(1, count + 1)) + ], + dtype=np.float32, + ) + edge_segments = np.hstack((polyline[:-1], polyline[1:])) + segments.append(edge_segments) + identifiers.append(np.full(len(edge_segments), identifier, dtype=np.uint32)) + + if not segments: + return _empty(6), np.zeros(0, dtype=np.uint32) + return np.concatenate(segments), np.concatenate(identifiers) + + +def _topology_vertices(vertices: tuple[TopoDS_Shape, ...]) -> np.ndarray: + points = [] + for raw_vertex in vertices: + point = BRep_Tool.Pnt_s(_topods("Vertex", raw_vertex)) + points.append((point.X(), point.Y(), point.Z())) + return np.array(points, dtype=np.float32).reshape(-1, 3) + + +def _free_vertices(shape: TopoDS_Shape) -> np.ndarray: + """Vertices that are not part of any edge (e.g. a ``.vertices()`` result).""" + + points = [] + explorer = TopExp_Explorer(shape, TopAbs_VERTEX, TopAbs_EDGE) + while explorer.More(): + p = BRep_Tool.Pnt_s(_topods("Vertex", explorer.Current())) + points.append((p.X(), p.Y(), p.Z())) + explorer.Next() + return np.array(points, dtype=np.float32).reshape(-1, 3) diff --git a/worker/pyproject.toml b/worker/pyproject.toml new file mode 100644 index 000000000..5967eecd4 --- /dev/null +++ b/worker/pyproject.toml @@ -0,0 +1,37 @@ +[build-system] +requires = ["setuptools>=61"] +build-backend = "setuptools.build_meta" + +[project] +name = "cq-editor-worker" +version = "0.9.0" +description = "CadQuery execution backend for the CQ-editor GUI" +readme = "README.md" +license = { text = "Apache-2.0" } +requires-python = ">=3.11,<3.15" +dependencies = [ + "cadquery>=2.7,<2.9", + # The worker imports OCP directly. Released CadQuery 2.7/2.8 use + # OCCT 7.8/7.9; the 2.9/OCP 8 development lane is tested separately. + "cadquery-ocp>=7.8.1,<8.0", + "numpy", +] + +[tool.mypy] +python_version = "3.11" +check_untyped_defs = true + +[[tool.mypy.overrides]] +module = ["OCP", "OCP.*", "jedi", "jedi.*"] +ignore_missing_imports = true + +[project.optional-dependencies] +# Code completion in the editor and the console. +completion = ["jedi"] +test = ["pytest", "black", "coverage", "ruff"] + +[tool.setuptools.packages.find] +include = ["cq_worker*"] + +[tool.pytest.ini_options] +testpaths = ["../tests/worker"]