From c40b6a7cd31b26379c2e8d44b64f22af09c2ad79 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:34:52 +0000 Subject: [PATCH] feat: Phase 0 shells, design system, server skeleton, Docker and CI - Titano.Ui: DESIGN.md tokens (dark/light), generated 16-px icon set, styles for all standard controls, custom chrome window with snap layouts, rail, job bar, Auto/manual slider, chips, toasts. - Titano desktop shell with sections, Settings (language, theme), About and a --capture screenshot mode. - Titano Server skeleton: env/server.json configuration, self-signed TLS with fingerprint, /health, /server/info, i18n endpoint and the embedded admin panel; in-process server tests. - Docker image (multi-arch, PUID/PGID, health check), compose file, Unraid template; CI, release and nightly workflows; changelog tool. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .dockerignore | 10 + .github/workflows/ci.yml | 214 +++ .github/workflows/docker.yml | 37 + .github/workflows/release.yml | 206 +++ .gitignore | 3 + Directory.Build.props | 9 + branding/ui-icons/icons.py | 153 ++ branding/ui-icons/icons.svg | 417 +++++ deploy/docker/.env.example | 8 + deploy/docker/Dockerfile | 43 + deploy/docker/docker-compose.yml | 44 + deploy/docker/entrypoint.sh | 19 + deploy/unraid/titano.xml | 41 + docs/CHANGELOG.md | 13 +- docs/DECISIONS.md | 10 + docs/STATUS.md | 14 +- i18n/en/About.resx | 14 + i18n/en/Admin.resx | 37 + i18n/en/Archive.resx | 8 + i18n/en/Common.resx | 15 + i18n/en/Editor.resx | 8 + i18n/en/Errors.resx | 8 + i18n/en/Import.resx | 8 + i18n/en/Jobs.resx | 8 + i18n/en/Library.resx | 11 + i18n/en/Server.resx | 8 + i18n/en/Settings.resx | 25 + i18n/en/Shell.resx | 21 +- i18n/en/Tooltips.resx | 37 + i18n/it/About.it.resx | 14 + i18n/it/Admin.it.resx | 37 + i18n/it/Archive.it.resx | 8 + i18n/it/Common.it.resx | 15 + i18n/it/Editor.it.resx | 8 + i18n/it/Errors.it.resx | 8 + i18n/it/Import.it.resx | 8 + i18n/it/Jobs.it.resx | 8 + i18n/it/Library.it.resx | 11 + i18n/it/Server.it.resx | 8 + i18n/it/Settings.it.resx | 25 + i18n/it/Shell.it.resx | 19 +- i18n/it/Tooltips.it.resx | 37 + src/Titano.App/App.xaml | 10 +- src/Titano.App/App.xaml.cs | 90 ++ .../Infrastructure/AppEnvironment.cs | 35 + src/Titano.App/Infrastructure/AppSettings.cs | 51 + src/Titano.App/Infrastructure/Formatting.cs | 34 + src/Titano.App/Infrastructure/ProductLinks.cs | 14 + src/Titano.App/Infrastructure/ShellActions.cs | 20 + src/Titano.App/Sections/AboutView.xaml | 43 + src/Titano.App/Sections/AboutView.xaml.cs | 8 + src/Titano.App/Sections/ArchiveView.xaml | 9 + src/Titano.App/Sections/ArchiveView.xaml.cs | 8 + src/Titano.App/Sections/ImportView.xaml | 9 + src/Titano.App/Sections/ImportView.xaml.cs | 8 + src/Titano.App/Sections/JobsView.xaml | 9 + src/Titano.App/Sections/JobsView.xaml.cs | 8 + src/Titano.App/Sections/LibraryView.xaml | 15 + src/Titano.App/Sections/LibraryView.xaml.cs | 8 + src/Titano.App/Sections/Sections.cs | 164 ++ src/Titano.App/Sections/SequenceView.xaml | 11 + src/Titano.App/Sections/SequenceView.xaml.cs | 8 + src/Titano.App/Sections/ServerView.xaml | 9 + src/Titano.App/Sections/ServerView.xaml.cs | 8 + src/Titano.App/Sections/SettingsView.xaml | 88 ++ src/Titano.App/Sections/SettingsView.xaml.cs | 22 + src/Titano.App/Shell/MainWindow.xaml | 69 + src/Titano.App/Shell/MainWindow.xaml.cs | 63 + src/Titano.App/Shell/ScreenCapture.cs | 80 + src/Titano.App/Shell/SectionTemplates.xaml | 13 + src/Titano.App/Shell/SectionViewModel.cs | 59 + src/Titano.App/Shell/ShellViewModel.cs | 168 ++ src/Titano.Protocol/Dtos.cs | 33 + src/Titano.Server/Admin/web/admin.css | 100 ++ src/Titano.Server/Admin/web/api.js | 47 + src/Titano.Server/Admin/web/app.js | 102 ++ src/Titano.Server/Admin/web/favicon.svg | 17 + src/Titano.Server/Admin/web/i18n.js | 27 + src/Titano.Server/Admin/web/icons.js | 16 + src/Titano.Server/Admin/web/index.html | 16 +- src/Titano.Server/Admin/web/pages/about.js | 12 + .../Admin/web/pages/dashboard.js | 18 + src/Titano.Server/Api/SystemEndpoints.cs | 66 + .../Configuration/ServerOptions.cs | 130 ++ src/Titano.Server/Hosting/CertificateStore.cs | 79 + .../Hosting/EmbeddedStaticFiles.cs | 70 + .../Hosting/FileLoggerProvider.cs | 54 + src/Titano.Server/Hosting/HealthProbe.cs | 26 + src/Titano.Server/Hosting/ServerHost.cs | 98 ++ src/Titano.Server/Program.cs | 15 +- src/Titano.Tools/Commands/ChangelogCommand.cs | 90 ++ src/Titano.Tools/Commands/I18nCommand.cs | 2 + src/Titano.Tools/Program.cs | 1 + src/Titano.Ui/Controls/AutoSlider.cs | 142 ++ src/Titano.Ui/Controls/BrandMarkIcon.cs | 61 + src/Titano.Ui/Controls/Chip.cs | 29 + src/Titano.Ui/Controls/ControlState.cs | 28 + src/Titano.Ui/Controls/Converters.cs | 44 + src/Titano.Ui/Controls/EmptyState.cs | 17 + src/Titano.Ui/Controls/Field.cs | 32 + src/Titano.Ui/Controls/Icon.cs | 79 + src/Titano.Ui/Controls/IconData.cs | 30 + src/Titano.Ui/Controls/JobBar.cs | 34 + src/Titano.Ui/Controls/NavRail.cs | 43 + src/Titano.Ui/Controls/StatusGlyph.cs | 42 + src/Titano.Ui/Controls/TitanoWindow.cs | 138 ++ src/Titano.Ui/Controls/Toasts.cs | 79 + src/Titano.Ui/Icons/Icons.xaml | 107 ++ src/Titano.Ui/Interop/NativeMethods.cs | 45 + src/Titano.Ui/Localization/LocExtension.cs | 49 + src/Titano.Ui/Mvvm/ObservableObject.cs | 39 + src/Titano.Ui/Mvvm/RelayCommand.cs | 70 + src/Titano.Ui/Themes/Controls.xaml | 1391 +++++++++++++++++ src/Titano.Ui/Themes/Tokens.Dark.xaml | 70 + src/Titano.Ui/Themes/Tokens.Light.xaml | 70 + src/Titano.Ui/Themes/Typography.xaml | 85 + src/Titano.Ui/Theming/ThemeManager.cs | 112 ++ .../Hosting/SystemEndpointTests.cs | 126 ++ tests/Titano.Server.Tests/TestServer.cs | 61 + tests/Titano.Testing/Assert.cs | 8 +- tests/Titano.Testing/ConsoleReporter.cs | 7 + tests/Titano.Testing/TestRunner.cs | 7 +- 122 files changed, 6838 insertions(+), 22 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/docker.yml create mode 100644 .github/workflows/release.yml create mode 100644 branding/ui-icons/icons.py create mode 100644 branding/ui-icons/icons.svg create mode 100644 deploy/docker/.env.example create mode 100644 deploy/docker/Dockerfile create mode 100644 deploy/docker/docker-compose.yml create mode 100755 deploy/docker/entrypoint.sh create mode 100644 deploy/unraid/titano.xml create mode 100644 i18n/en/About.resx create mode 100644 i18n/en/Admin.resx create mode 100644 i18n/en/Archive.resx create mode 100644 i18n/en/Common.resx create mode 100644 i18n/en/Editor.resx create mode 100644 i18n/en/Errors.resx create mode 100644 i18n/en/Import.resx create mode 100644 i18n/en/Jobs.resx create mode 100644 i18n/en/Library.resx create mode 100644 i18n/en/Server.resx create mode 100644 i18n/en/Settings.resx create mode 100644 i18n/en/Tooltips.resx create mode 100644 i18n/it/About.it.resx create mode 100644 i18n/it/Admin.it.resx create mode 100644 i18n/it/Archive.it.resx create mode 100644 i18n/it/Common.it.resx create mode 100644 i18n/it/Editor.it.resx create mode 100644 i18n/it/Errors.it.resx create mode 100644 i18n/it/Import.it.resx create mode 100644 i18n/it/Jobs.it.resx create mode 100644 i18n/it/Library.it.resx create mode 100644 i18n/it/Server.it.resx create mode 100644 i18n/it/Settings.it.resx create mode 100644 i18n/it/Tooltips.it.resx create mode 100644 src/Titano.App/Infrastructure/AppEnvironment.cs create mode 100644 src/Titano.App/Infrastructure/AppSettings.cs create mode 100644 src/Titano.App/Infrastructure/Formatting.cs create mode 100644 src/Titano.App/Infrastructure/ProductLinks.cs create mode 100644 src/Titano.App/Infrastructure/ShellActions.cs create mode 100644 src/Titano.App/Sections/AboutView.xaml create mode 100644 src/Titano.App/Sections/AboutView.xaml.cs create mode 100644 src/Titano.App/Sections/ArchiveView.xaml create mode 100644 src/Titano.App/Sections/ArchiveView.xaml.cs create mode 100644 src/Titano.App/Sections/ImportView.xaml create mode 100644 src/Titano.App/Sections/ImportView.xaml.cs create mode 100644 src/Titano.App/Sections/JobsView.xaml create mode 100644 src/Titano.App/Sections/JobsView.xaml.cs create mode 100644 src/Titano.App/Sections/LibraryView.xaml create mode 100644 src/Titano.App/Sections/LibraryView.xaml.cs create mode 100644 src/Titano.App/Sections/Sections.cs create mode 100644 src/Titano.App/Sections/SequenceView.xaml create mode 100644 src/Titano.App/Sections/SequenceView.xaml.cs create mode 100644 src/Titano.App/Sections/ServerView.xaml create mode 100644 src/Titano.App/Sections/ServerView.xaml.cs create mode 100644 src/Titano.App/Sections/SettingsView.xaml create mode 100644 src/Titano.App/Sections/SettingsView.xaml.cs create mode 100644 src/Titano.App/Shell/MainWindow.xaml create mode 100644 src/Titano.App/Shell/MainWindow.xaml.cs create mode 100644 src/Titano.App/Shell/ScreenCapture.cs create mode 100644 src/Titano.App/Shell/SectionTemplates.xaml create mode 100644 src/Titano.App/Shell/SectionViewModel.cs create mode 100644 src/Titano.App/Shell/ShellViewModel.cs create mode 100644 src/Titano.Protocol/Dtos.cs create mode 100644 src/Titano.Server/Admin/web/admin.css create mode 100644 src/Titano.Server/Admin/web/api.js create mode 100644 src/Titano.Server/Admin/web/app.js create mode 100644 src/Titano.Server/Admin/web/favicon.svg create mode 100644 src/Titano.Server/Admin/web/i18n.js create mode 100644 src/Titano.Server/Admin/web/icons.js create mode 100644 src/Titano.Server/Admin/web/pages/about.js create mode 100644 src/Titano.Server/Admin/web/pages/dashboard.js create mode 100644 src/Titano.Server/Api/SystemEndpoints.cs create mode 100644 src/Titano.Server/Configuration/ServerOptions.cs create mode 100644 src/Titano.Server/Hosting/CertificateStore.cs create mode 100644 src/Titano.Server/Hosting/EmbeddedStaticFiles.cs create mode 100644 src/Titano.Server/Hosting/FileLoggerProvider.cs create mode 100644 src/Titano.Server/Hosting/HealthProbe.cs create mode 100644 src/Titano.Server/Hosting/ServerHost.cs create mode 100644 src/Titano.Tools/Commands/ChangelogCommand.cs create mode 100644 src/Titano.Ui/Controls/AutoSlider.cs create mode 100644 src/Titano.Ui/Controls/BrandMarkIcon.cs create mode 100644 src/Titano.Ui/Controls/Chip.cs create mode 100644 src/Titano.Ui/Controls/ControlState.cs create mode 100644 src/Titano.Ui/Controls/Converters.cs create mode 100644 src/Titano.Ui/Controls/EmptyState.cs create mode 100644 src/Titano.Ui/Controls/Field.cs create mode 100644 src/Titano.Ui/Controls/Icon.cs create mode 100644 src/Titano.Ui/Controls/IconData.cs create mode 100644 src/Titano.Ui/Controls/JobBar.cs create mode 100644 src/Titano.Ui/Controls/NavRail.cs create mode 100644 src/Titano.Ui/Controls/StatusGlyph.cs create mode 100644 src/Titano.Ui/Controls/TitanoWindow.cs create mode 100644 src/Titano.Ui/Controls/Toasts.cs create mode 100644 src/Titano.Ui/Icons/Icons.xaml create mode 100644 src/Titano.Ui/Interop/NativeMethods.cs create mode 100644 src/Titano.Ui/Localization/LocExtension.cs create mode 100644 src/Titano.Ui/Mvvm/ObservableObject.cs create mode 100644 src/Titano.Ui/Mvvm/RelayCommand.cs create mode 100644 src/Titano.Ui/Themes/Controls.xaml create mode 100644 src/Titano.Ui/Themes/Tokens.Dark.xaml create mode 100644 src/Titano.Ui/Themes/Tokens.Light.xaml create mode 100644 src/Titano.Ui/Themes/Typography.xaml create mode 100644 src/Titano.Ui/Theming/ThemeManager.cs create mode 100644 tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs create mode 100644 tests/Titano.Server.Tests/TestServer.cs diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..767471fe --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +**/bin/ +**/obj/ +artifacts/ +out/ +publish/ +tests/ +docs/ +.git/ +.github/ +**/*.user diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..6088ed24 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,214 @@ +name: CI + +on: + push: + branches: ["**"] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + DOTNET_NOLOGO: "1" + DOTNET_CLI_TELEMETRY_OPTOUT: "1" + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1" + TOOLS: src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll + +jobs: + build: + name: Build and test (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [windows-latest, ubuntu-latest] + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: .NET info + run: dotnet --info + + - name: Restore fixtures cache + uses: actions/cache@v4 + with: + path: tests/fixtures/external + key: fixtures-${{ hashFiles('tests/fixtures/manifest.json') }} + + - name: Build (warnings are errors) + run: dotnet build Titano.slnx -c Release + + - name: Zero-package guard + run: dotnet "$TOOLS" package-guard + + - name: Localization check + run: dotnet "$TOOLS" i18n check + + - name: XAML lint + run: dotnet "$TOOLS" xaml-lint + + - name: Format check + if: runner.os == 'Windows' + run: dotnet format whitespace Titano.slnx --verify-no-changes + + - name: Fetch CC0 fixtures + continue-on-error: true + run: | + if dotnet "$TOOLS" --help | grep -q '^ fixtures'; then dotnet "$TOOLS" fixtures; fi + + - name: Test · Core + run: dotnet run --project tests/Titano.Core.Tests -c Release --no-build -- --junit out/junit/core.xml + + - name: Test · Data (SQLite) + run: dotnet run --project tests/Titano.Data.Tests -c Release --no-build -- --junit out/junit/data.xml + + - name: Test · Server + run: dotnet run --project tests/Titano.Server.Tests -c Release --no-build -- --junit out/junit/server.xml + + - name: Test · Core.Windows + if: runner.os == 'Windows' + run: dotnet run --project tests/Titano.Core.Windows.Tests -c Release --no-build -- --junit out/junit/core-windows.xml + + - name: Test · App + if: runner.os == 'Windows' + run: dotnet run --project tests/Titano.App.Tests -c Release --no-build -- --junit out/junit/app.xml + + - name: Screenshots + if: runner.os == 'Windows' + run: | + src/Titano.App/bin/Release/net10.0-windows/Titano.exe --capture out/screenshots & + wait $! + ls -la out/screenshots + + - name: Publish desktop programs (win-x64, self-contained single file) + if: runner.os == 'Windows' + run: | + for p in Titano.App Titano.Uploader; do + dotnet publish "src/$p/$p.csproj" -c Release -r win-x64 --self-contained \ + -p:PublishSingleFile=true -p:PublishReadyToRun=true -p:IncludeNativeLibrariesForSelfExtract=true \ + -o "out/publish/$p" + done + dotnet publish src/Titano.Server/Titano.Server.csproj -c Release -r win-x64 --self-contained \ + -p:PublishSingleFile=true -o out/publish/Titano.Server + + - name: Upload test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-results-${{ matrix.os }} + path: out/junit/ + if-no-files-found: ignore + + - name: Upload screenshots + if: runner.os == 'Windows' && always() + uses: actions/upload-artifact@v4 + with: + name: screenshots + path: out/screenshots/ + if-no-files-found: ignore + + - name: Upload Windows programs + if: runner.os == 'Windows' + uses: actions/upload-artifact@v4 + with: + name: titano-win-x64-${{ github.sha }} + path: out/publish/ + retention-days: 14 + + postgres: + name: PostgreSQL ${{ matrix.pg }} integration + strategy: + fail-fast: false + matrix: + pg: ["16", "17"] + runs-on: ubuntu-latest + services: + postgres: + image: postgres:${{ matrix.pg }} + env: + POSTGRES_USER: titano + POSTGRES_PASSWORD: titano-ci + POSTGRES_DB: titano_test + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U titano -d titano_test" + --health-interval 5s --health-timeout 5s --health-retries 20 + env: + TITANO_TEST_PG: Host=127.0.0.1;Port=5432;Database=titano_test;Username=titano;Password=titano-ci;SslMode=disable + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + - name: Test · Data (PostgreSQL) + run: dotnet run --project tests/Titano.Data.Tests -c Release -- --junit out/junit/data-pg${{ matrix.pg }}.xml + - name: Upload test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-results-pg${{ matrix.pg }} + path: out/junit/ + if-no-files-found: ignore + + docker: + name: Docker image + runs-on: ubuntu-latest + services: + postgres: + image: postgres:17 + env: + POSTGRES_USER: titano + POSTGRES_PASSWORD: titano-ci + POSTGRES_DB: titano + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U titano -d titano" + --health-interval 5s --health-timeout 5s --health-retries 20 + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-buildx-action@v3 + - name: Build image + uses: docker/build-push-action@v6 + with: + context: . + file: deploy/docker/Dockerfile + platforms: linux/amd64 + load: true + push: false + tags: titano-server:ci + build-args: TITANO_VERSION=0.0.0-ci + cache-from: type=gha + cache-to: type=gha,mode=max + - name: Smoke test (/health) + run: | + mkdir -p "$RUNNER_TEMP/archive" "$RUNNER_TEMP/data" + docker run -d --name titano --network host \ + -e TITANO_DB_HOST=127.0.0.1 -e TITANO_DB_USER=titano -e TITANO_DB_PASSWORD=titano-ci -e TITANO_DB_NAME=titano \ + -e TITANO_ADMIN_USER=admin -e TITANO_ADMIN_PASSWORD=ci-password-1234 \ + -e PUID="$(id -u)" -e PGID="$(id -g)" \ + -v "$RUNNER_TEMP/archive:/archive" -v "$RUNNER_TEMP/data:/data" titano-server:ci + for i in $(seq 1 60); do + if curl -fsS http://127.0.0.1:8080/health; then echo; break; fi + sleep 2 + done + curl -fsS http://127.0.0.1:8080/api/v1/server/info + curl -fsSk https://127.0.0.1:8443/health + test "$(docker inspect --format '{{.State.Running}}' titano)" = "true" + - name: Container logs + if: always() + run: docker logs titano || true diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 00000000..3079bf87 --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,37 @@ +name: Nightly image + +on: + schedule: + - cron: "17 2 * * *" + workflow_dispatch: + +permissions: + contents: read + packages: write + +jobs: + nightly: + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Image name + id: image + run: echo "name=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/titano-server" >> "$GITHUB_OUTPUT" + - uses: docker/build-push-action@v6 + with: + context: . + file: deploy/docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.image.outputs.name }}:nightly + build-args: TITANO_VERSION=0.0.0-nightly.${{ github.run_number }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..03ecd78e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,206 @@ +name: Release + +on: + push: + tags: ["v*"] + workflow_dispatch: + inputs: + tag: + description: "Existing tag to (re)publish, e.g. v0.2.0" + required: true + +permissions: + contents: write + packages: write + +env: + DOTNET_NOLOGO: "1" + DOTNET_CLI_TELEMETRY_OPTOUT: "1" + # Public repository that receives releases (BRIEF §19.4). Override with the RELEASES_REPO variable. + RELEASES_REPO: ${{ vars.RELEASES_REPO || format('{0}/titano-releases', github.repository_owner) }} + +jobs: + version: + runs-on: ubuntu-latest + outputs: + tag: ${{ steps.v.outputs.tag }} + version: ${{ steps.v.outputs.version }} + prerelease: ${{ steps.v.outputs.prerelease }} + steps: + - id: v + run: | + tag="${{ github.event.inputs.tag || github.ref_name }}" + version="${tag#v}" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + echo "version=$version" >> "$GITHUB_OUTPUT" + if [[ "$version" == *-* ]]; then echo "prerelease=true" >> "$GITHUB_OUTPUT"; else echo "prerelease=false" >> "$GITHUB_OUTPUT"; fi + + windows: + needs: version + runs-on: windows-latest + defaults: + run: + shell: bash + env: + VERSION: ${{ needs.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.version.outputs.tag }} + fetch-depth: 0 + - uses: actions/setup-dotnet@v4 + with: + global-json-file: global.json + + - name: Build and test + run: | + dotnet build Titano.slnx -c Release -p:TitanoVersion="$VERSION" + for t in Core Data Server Core.Windows App; do + dotnet run --project "tests/Titano.$t.Tests" -c Release --no-build -- --junit "out/junit/$t.xml" + done + + - name: Publish self-contained programs + run: | + common="-c Release -r win-x64 --self-contained -p:TitanoVersion=$VERSION -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=none" + dotnet publish src/Titano.App/Titano.App.csproj $common -p:PublishReadyToRun=true -o out/publish/app + dotnet publish src/Titano.Uploader/Titano.Uploader.csproj $common -p:PublishReadyToRun=true -o out/publish/uploader + dotnet publish src/Titano.Server/Titano.Server.csproj $common -o out/publish/server + dotnet publish src/Titano.Setup/Titano.Setup.csproj $common -p:PublishReadyToRun=true -o out/publish/setup + + - name: Sign binaries + if: env.SIGN_PFX != '' + env: + SIGN_PFX: ${{ secrets.SIGN_PFX_BASE64 }} + SIGN_PASSWORD: ${{ secrets.SIGN_PASSWORD }} + shell: pwsh + run: | + $pfx = Join-Path $env:RUNNER_TEMP "sign.pfx" + [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:SIGN_PFX)) + $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1 + Get-ChildItem out/publish -Recurse -Include *.exe | ForEach-Object { + & $signtool.FullName sign /fd SHA256 /f $pfx /p $env:SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $_.FullName + if ($LASTEXITCODE -ne 0) { throw "signtool failed for $($_.FullName)" } + } + Remove-Item $pfx + + - name: Package installers and archives + run: | + mkdir -p out/release + tools=src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll + dotnet "$tools" pack-installer --setup out/publish/setup/Titano.Setup.exe --product Titano \ + --component "Titano=out/publish/app" --component "Uploader=out/publish/uploader" --component "Server=out/publish/server" \ + --version "$VERSION" --out "out/release/Titano-Setup-$VERSION.exe" + dotnet "$tools" pack-installer --setup out/publish/setup/Titano.Setup.exe --product "Titano Uploader" \ + --component "Uploader=out/publish/uploader" --version "$VERSION" --out "out/release/Titano-Uploader-Setup-$VERSION.exe" + (cd out/publish/server && 7z a -tzip "../../release/Titano-Server-win-x64-$VERSION.zip" . > /dev/null) + (cd out/publish/app && 7z a -tzip "../../release/Titano-win-x64-portable-$VERSION.zip" . > /dev/null) + + - name: Sign installers + if: env.SIGN_PFX != '' + env: + SIGN_PFX: ${{ secrets.SIGN_PFX_BASE64 }} + SIGN_PASSWORD: ${{ secrets.SIGN_PASSWORD }} + shell: pwsh + run: | + $pfx = Join-Path $env:RUNNER_TEMP "sign.pfx" + [IO.File]::WriteAllBytes($pfx, [Convert]::FromBase64String($env:SIGN_PFX)) + $signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName -Descending | Select-Object -First 1 + Get-ChildItem out/release -Filter *.exe | ForEach-Object { & $signtool.FullName sign /fd SHA256 /f $pfx /p $env:SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $_.FullName } + Remove-Item $pfx + + - name: Release notes + run: | + tag="${{ needs.version.outputs.tag }}" + previous="$(git describe --tags --abbrev=0 "$tag^" 2>/dev/null || true)" + range="${previous:+$previous..}$tag" + git log --format='%h%x09%s' "$range" | dotnet src/Titano.Tools/bin/Release/net10.0/Titano.Tools.dll changelog --title "Titano ${{ needs.version.outputs.version }}" --out out/release-notes.md + + - uses: actions/upload-artifact@v4 + with: + name: release-windows + path: | + out/release/ + out/release-notes.md + + docker: + needs: version + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.version.outputs.tag }} + - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v3 + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Image name + id: image + run: echo "name=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/titano-server" >> "$GITHUB_OUTPUT" + - uses: docker/build-push-action@v6 + with: + context: . + file: deploy/docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + build-args: TITANO_VERSION=${{ needs.version.outputs.version }} + tags: | + ${{ steps.image.outputs.name }}:${{ needs.version.outputs.version }} + ${{ needs.version.outputs.prerelease == 'false' && format('{0}:latest', steps.image.outputs.name) || '' }} + cache-from: type=gha + cache-to: type=gha,mode=max + + publish: + needs: [version, windows, docker] + runs-on: ubuntu-latest + env: + TAG: ${{ needs.version.outputs.tag }} + VERSION: ${{ needs.version.outputs.version }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ needs.version.outputs.tag }} + - uses: actions/download-artifact@v4 + with: + name: release-windows + path: out + - name: Checksums + run: | + cd out/release + sha256sum * > SHA256SUMS + cat SHA256SUMS + + - name: Create release in the public releases repository + if: env.RELEASES_TOKEN != '' + env: + RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN }} + GH_TOKEN: ${{ secrets.RELEASES_TOKEN }} + run: | + flags="" + if [ "${{ needs.version.outputs.prerelease }}" = "true" ]; then flags="--prerelease"; fi + gh release create "$TAG" out/release/* --repo "$RELEASES_REPO" --title "Titano $VERSION" --notes-file out/release-notes.md $flags + # Keep the Unraid template, icon and EULA in the public repository up to date. + git clone --depth 1 "https://x-access-token:${RELEASES_TOKEN}@github.com/${RELEASES_REPO}.git" public + mkdir -p public/unraid + cp deploy/unraid/titano.xml public/unraid/titano.xml + dotnet run --project src/Titano.Tools -c Release -- make-icon --out "$RUNNER_TEMP/icons" + cp "$RUNNER_TEMP/icons/titano-server-256.png" public/unraid/titano-server.png + if [ -f docs/legal/EULA.md ]; then cp docs/legal/EULA.md public/EULA.md; fi + cd public + git config user.name "titano-release" + git config user.email "titano-release@users.noreply.github.com" + git add -A + git diff --cached --quiet || git commit -m "chore: update Unraid template and assets for $TAG" + git push + + - name: Create release in this repository (no RELEASES_TOKEN configured) + if: env.RELEASES_TOKEN == '' + env: + RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + flags="" + if [ "${{ needs.version.outputs.prerelease }}" = "true" ]; then flags="--prerelease"; fi + gh release create "$TAG" out/release/* --repo "$GITHUB_REPOSITORY" --title "Titano $VERSION" --notes-file out/release-notes.md $flags diff --git a/.gitignore b/.gitignore index 1732a815..62b03a69 100644 --- a/.gitignore +++ b/.gitignore @@ -435,3 +435,6 @@ tests/fixtures/external/ /artifacts/ *.junit.xml TestResults/ + +# Local agent tooling +.claude/ diff --git a/Directory.Build.props b/Directory.Build.props index 5b59ad91..cda20b1f 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -6,6 +6,7 @@ $([System.Text.RegularExpressions.Regex]::Match($(TitanoVersion), '^\d+\.\d+\.\d+').Value).0 $(AssemblyVersion) $(TitanoVersion) + false Titano Titano © Titano @@ -34,6 +35,14 @@ embedded + + + alby96/titano-releases + + + + + true diff --git a/branding/ui-icons/icons.py b/branding/ui-icons/icons.py new file mode 100644 index 00000000..51aa85d7 --- /dev/null +++ b/branding/ui-icons/icons.py @@ -0,0 +1,153 @@ +"""Titano UI icon set (DESIGN.md §5): 16-px grid, 1.5-px strokes, round caps/joins. +Each icon = stroke path data + optional fill path data. Generates the WPF resource dictionary +src/Titano.Ui/Icons/Icons.xaml and a preview sheet (icons.svg). Run: python3 branding/ui-icons/icons.py""" +import math, os + +def rr(x, y, w, h, r): + return (f"M{x+r} {y} H{x+w-r} A{r} {r} 0 0 1 {x+w} {y+r} V{y+h-r} A{r} {r} 0 0 1 {x+w-r} {y+h} " + f"H{x+r} A{r} {r} 0 0 1 {x} {y+h-r} V{y+r} A{r} {r} 0 0 1 {x+r} {y} Z") + +def circ(cx, cy, r): + return f"M{cx-r} {cy} A{r} {r} 0 1 0 {cx+r} {cy} A{r} {r} 0 1 0 {cx-r} {cy} Z" + +def arc(cx, cy, r, a0, a1): + """Arc clockwise from a0 to a1 degrees (0 = 12 o'clock).""" + p = lambda a: (cx + r * math.sin(math.radians(a)), cy - r * math.cos(math.radians(a))) + x0, y0 = p(a0); x1, y1 = p(a1) + large = 1 if (a1 - a0) % 360 > 180 else 0 + return f"M{x0:.2f} {y0:.2f} A{r} {r} 0 {large} 1 {x1:.2f} {y1:.2f}" + +I = {} +# Navigation +I["Library"] = (rr(1.5,1.5,5.5,5.5,1)+rr(9,1.5,5.5,5.5,1)+rr(1.5,9,5.5,5.5,1)+rr(9,9,5.5,5.5,1), None) +I["Import"] = ("M8 2V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5", None) +I["Sequence"] = ("M2 12.5 L11.5 3 L13 4.5 L3.5 14 H2 Z", None) +I["Archive"] = ("M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10", None) +I["Jobs"] = ("M3 8 H13 M3 4 H13 M3 12 H9", None) +I["Server"] = ("M4.5 12.5 A3 3 0 0 1 4.2 6.5 A4 4 0 0 1 11.9 5.5 A3.5 3.5 0 0 1 12.2 12.5 Z", None) +I["Settings"] = (circ(8,8,2.2)+" M8 1.5 V3.5 M8 12.5 V14.5 M1.5 8 H3.5 M12.5 8 H14.5 M3.4 3.4 L4.8 4.8 M11.2 11.2 L12.6 12.6 M3.4 12.6 L4.8 11.2 M11.2 4.8 L12.6 3.4", None) +I["About"] = (circ(8,8,6.5)+" M8 7 V11 M8 4.8 V5.2", None) +I["Menu"] = ("M2.5 4 H13.5 M2.5 8 H13.5 M2.5 12 H13.5", None) +I["Users"] = (circ(8,5,3)+" M2.5 14 A5.5 5.5 0 0 1 13.5 14", None) +I["User"] = I["Users"] +I["Logs"] = ("M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5", None) +# Toolbar / actions +I["Search"] = (circ(7,7,4.5)+" M10.4 10.4 L14 14", None) +I["Refresh"] = (arc(8,8,5.5,30,320)+" M13.2 2.6 L13.2 5.3 L10.5 5.3", None) +I["ViewGrid"] = I["Library"] +I["ViewList"] = ("M5.5 4 H13.5 M5.5 8 H13.5 M5.5 12 H13.5 M2.5 4 H2.6 M2.5 8 H2.6 M2.5 12 H2.6", None) +I["ViewTimeline"] = ("M2 13.5 H14 M3.5 11 V8 M6 11 V5 M8.5 11 V7 M11 11 V3.5 M13.5 11 V9", None) +I["ChevronDown"] = ("M4 6 L8 10 L12 6", None) +I["ChevronUp"] = ("M4 10 L8 6 L12 10", None) +I["ChevronRight"] = ("M6 4 L10 8 L6 12", None) +I["ChevronLeft"] = ("M10 4 L6 8 L10 12", None) +I["Close"] = ("M4 4 L12 12 M12 4 L4 12", None) +I["Check"] = ("M3 8.5 L6.5 12 L13 4.5", None) +I["Back"] = ("M13 8 H3 M7 4 L3 8 L7 12", None) +I["Forward"] = ("M3 8 H13 M9 4 L13 8 L9 12", None) +I["Plus"] = ("M8 3 V13 M3 8 H13", None) +I["Minus"] = ("M3 8 H13", None) +I["More"] = (None, circ(3.5,8,1.1)+circ(8,8,1.1)+circ(12.5,8,1.1)) +I["Play"] = (None, "M4.5 2.8 L13 8 L4.5 13.2 Z") +I["Pause"] = (None, rr(4,3,2.6,10,0.8)+rr(9.4,3,2.6,10,0.8)) +I["Stop"] = (None, rr(3.5,3.5,9,9,1.5)) +I["Folder"] = ("M1.5 4 A1 1 0 0 1 2.5 3 H6 L7.5 4.5 H13.5 A1 1 0 0 1 14.5 5.5 V12.5 A1 1 0 0 1 13.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z", None) +I["FolderOpen"] = ("M1.5 12.5 V4 A1 1 0 0 1 2.5 3 H6 L7.5 4.5 H12.5 V6.5 M1.5 12.5 L3.5 7 H14.5 L12.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z", None) +I["Card"] = ("M4.5 1.5 H10 L12.5 4 V13.5 A1 1 0 0 1 11.5 14.5 H4.5 A1 1 0 0 1 3.5 13.5 V2.5 A1 1 0 0 1 4.5 1.5 Z M6 3.5 V5.5 M8 3.5 V5.5 M10 4.5 V5.5", None) +I["Drive"] = (rr(1.5,4.5,13,7,1.5)+" M4.5 8 H4.6 M7 8 H11.5", None) +I["Eject"] = ("M3 13 H13", "M8 2.8 L13 9.5 H3 Z") +I["Download"] = ("M8 2 V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5", None) +I["Upload"] = ("M8 10.5 V2.5 M4.5 6 L8 2.5 L11.5 6 M2.5 13.5 H13.5", None) +I["Sync"] = (arc(8,8,5.5,20,160)+" "+arc(8,8,5.5,200,340)+" M13.5 6.5 L13.2 9.4 L10.6 8.4 M2.5 9.5 L2.8 6.6 L5.4 7.6", None) +I["Compare"] = (rr(1.5,2.5,13,11,1.5)+" M8 1 V15", None) +I["Vectors"] = ("M2.5 12.5 L7 8 M7 8 H4.5 M7 8 V10.5 M9 7 L13.5 2.5 M13.5 2.5 H11 M13.5 2.5 V5", None) +I["Regions"] = ("M1.5 9.5 C4 8 6 10.5 8.5 9 C10.5 7.8 12.5 8.5 14.5 9.5 M1.5 13.5 H14.5 M1.5 2.5 H14.5", None) +I["CropMask"] = ("M4 1.5 V12 H14.5 M1.5 4 H12 V14.5", None) +I["Fullscreen"] = ("M2 6 V2 H6 M10 2 H14 V6 M14 10 V14 H10 M6 14 H2 V10", None) +I["ActualSize"] = (rr(1.5,2.5,13,11,1.5)+" M5 6 L6 5.5 V10.5 M9.5 6 L10.5 5.5 V10.5 M8 7 V7.1 M8 9.5 V9.6", None) +I["Reset"] = (arc(8,8.5,5,300,210)+" M3.2 3.2 V6.2 H6.2", None) +I["Warning"] = ("M8 1.8 L14.8 13.8 H1.2 Z M8 6.2 V9.6 M8 11.7 V11.8", None) +I["ErrorCircle"] = (circ(8,8,6.5)+" M5.8 5.8 L10.2 10.2 M10.2 5.8 L5.8 10.2", None) +I["SuccessCircle"] = (circ(8,8,6.5)+" M5 8.3 L7.1 10.3 L11 6", None) +I["Lock"] = (rr(3,7,10,7.5,1.5)+" M5.5 7 V5 A2.5 2.5 0 0 1 10.5 5 V7", None) +I["Key"] = (circ(5,10.5,3)+" M7.2 8.3 L13.5 2 M11.5 4 L13 5.5 M9.8 5.7 L11 6.9", None) +I["Power"] = ("M8 1.8 V7.5 "+arc(8,8.8,5.5,40,320), None) +I["Moon"] = ("M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z", None) +I["Sun"] = (circ(8,8,3)+" M8 1 V2.5 M8 13.5 V15 M1 8 H2.5 M13.5 8 H15 M3 3 L4 4 M12 12 L13 13 M3 13 L4 12 M12 4 L13 3", None) +I["Star"] = ("M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z", None) +I["StarFilled"] = (None, "M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z") +I["Tag"] = ("M1.5 2.5 A1 1 0 0 1 2.5 1.5 H7.5 L14.5 8.5 L8.5 14.5 L1.5 7.5 Z M5 5 H5.1", None) +I["Delete"] = ("M2.5 4 H13.5 M6 4 V2.5 H10 V4 M3.8 4 L4.6 14 H11.4 L12.2 4 M6.6 6.8 V11.2 M9.4 6.8 V11.2", None) +I["Copy"] = (rr(5,5,9.5,9.5,1.5)+" M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5", None) +I["Link"] = ("M6.8 9.2 L9.2 6.8 M7.5 4.5 L9 3 A2.8 2.8 0 0 1 13 7 L11.5 8.5 M8.5 11.5 L7 13 A2.8 2.8 0 0 1 3 9 L4.5 7.5", None) +I["ExternalLink"] = ("M9.5 2 H14 V6.5 M14 2 L7.5 8.5 M12 9.5 V13 A1 1 0 0 1 11 14 H3 A1 1 0 0 1 2 13 V5 A1 1 0 0 1 3 4 H6.5", None) +I["Calendar"] = (rr(1.5,3,13,11.5,1.5)+" M1.5 6.5 H14.5 M5 1.5 V4 M11 1.5 V4", None) +I["Camera"] = ("M1.5 5 A1 1 0 0 1 2.5 4 H4.5 L6 2.5 H10 L11.5 4 H13.5 A1 1 0 0 1 14.5 5 V12.5 A1 1 0 0 1 13.5 13.5 H2.5 A1 1 0 0 1 1.5 12.5 Z "+circ(8,8.5,2.8), None) +I["Chart"] = ("M2 2 V14 H14 M4.5 10.5 L7.5 7 L9.5 9 L13.5 4", None) +I["Filmstrip"] = (rr(1.5,2.5,13,11,1.5)+" M4.5 2.5 V13.5 M11.5 2.5 V13.5 M1.5 6 H4.5 M1.5 10 H4.5 M11.5 6 H14.5 M11.5 10 H14.5", None) +I["Layers"] = ("M8 1.8 L14.5 5.2 L8 8.6 L1.5 5.2 Z M1.5 8.2 L8 11.6 L14.5 8.2 M1.5 11 L8 14.4 L14.5 11", None) +I["Clock"] = (circ(8,8,6.5)+" M8 4.5 V8 L10.5 9.5", None) +I["Exposure"] = (circ(8,8,6.5)+" M3.4 12.6 L12.6 3.4 M4.5 6 H7 M5.75 4.75 V7.25 M9 10 H11.5", None) +I["Motion"] = ("M1.5 8 C3.5 3 5.5 3 7.5 8 C9.5 13 11.5 13 14.5 8", None) +I["Time"] = I["Clock"] +I["Stack"] = I["Layers"] +I["Export"] = ("M8 10 V1.8 M4.8 5 L8 1.8 L11.2 5 M5 7.5 H3 A1 1 0 0 0 2 8.5 V13.5 A1 1 0 0 0 3 14.5 H13 A1 1 0 0 0 14 13.5 V8.5 A1 1 0 0 0 13 7.5 H11", None) +I["Render"] = (rr(1.5,2.5,13,11,1.5), "M6.5 5.5 L10.8 8 L6.5 10.5 Z") +I["Analyse"] = ("M1.5 8.5 H4.5 L6.5 3.5 L9.5 12.5 L11.5 8.5 H14.5", None) +I["Optimise"] = ("M7 2 L8.2 5.8 L12 7 L8.2 8.2 L7 12 L5.8 8.2 L2 7 L5.8 5.8 Z M12.5 10.5 L13 12 L14.5 12.5 L13 13 L12.5 14.5 L12 13 L10.5 12.5 L12 12 Z", None) +I["Duplicate"] = I["Copy"] +I["Verify"] = ("M8 1.5 L13.5 3.5 V7.5 C13.5 11 11 13.3 8 14.5 C5 13.3 2.5 11 2.5 7.5 V3.5 Z M5.5 8 L7.3 9.8 L10.6 6.3", None) +I["Database"] = ("M2.5 3.8 C2.5 2.5 13.5 2.5 13.5 3.8 C13.5 5.1 2.5 5.1 2.5 3.8 Z M2.5 3.8 V12.2 C2.5 13.5 13.5 13.5 13.5 12.2 V3.8 M2.5 8 C2.5 9.3 13.5 9.3 13.5 8", None) +I["Gpu"] = (rr(3.5,3.5,9,9,1.5)+" "+rr(6,6,4,4,0.5)+" M6 1.5 V3.5 M10 1.5 V3.5 M6 12.5 V14.5 M10 12.5 V14.5 M1.5 6 H3.5 M1.5 10 H3.5 M12.5 6 H14.5 M12.5 10 H14.5", None) +I["Network"] = ("M2 6 A8.5 8.5 0 0 1 14 6 M4 8.5 A5.5 5.5 0 0 1 12 8.5 M6 11 A2.6 2.6 0 0 1 10 11", circ(8,13,1.1)) +I["Sort"] = ("M5 2.5 V13.5 M2.5 11 L5 13.5 L7.5 11 M11 13.5 V2.5 M8.5 5 L11 2.5 L13.5 5", None) +I["Filter"] = ("M1.5 2.5 H14.5 L9.5 8.5 V13.5 L6.5 12 V8.5 Z", None) +I["Info"] = I["About"] +I["Image"] = (rr(1.5,2.5,13,11,1.5)+" M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12", circ(10.8,5.6,1.2)) +I["Hero"] = (rr(1.5,2.5,13,11,1.5), "M8 4.8 L8.9 6.9 L11.1 7.1 L9.4 8.5 L9.9 10.7 L8 9.5 L6.1 10.7 L6.6 8.5 L4.9 7.1 L7.1 6.9 Z") +I["Exclude"] = (circ(8,8,6.5)+" M3.4 12.6 L12.6 3.4", None) +I["Eye"] = ("M1.5 8 C3.5 4 12.5 4 14.5 8 C12.5 12 3.5 12 1.5 8 Z "+circ(8,8,2.2), None) +I["Wipe"] = I["Compare"] +I["Spline"] = ("M2 13 C5 13 5 3 8 8 C11 13 11 3 14 3", circ(2,13,1.2)+circ(14,3,1.2)) +I["Keyframe"] = ("M8 2 L13 8 L8 14 L3 8 Z", None) +I["Tray"] = ("M1.5 9.5 H5 L6.5 11.5 H9.5 L11 9.5 H14.5 M1.5 9.5 L3.5 3 H12.5 L14.5 9.5 V13.5 H1.5 Z", None) +I["Window"] = (rr(1.5,2.5,13,11,1.5)+" M1.5 5.5 H14.5", None) +I["Clipboard"] = (rr(2.5,2.5,11,12,1.5)+" "+rr(5.5,1.5,5,2.5,0.8), None) +I["Cancel"] = I["ErrorCircle"] +I["Retry"] = I["Refresh"] +I["Grip"] = (None, circ(6,4,1)+circ(10,4,1)+circ(6,8,1)+circ(10,8,1)+circ(6,12,1)+circ(10,12,1)) +I["Dot"] = (None, circ(8,8,3.5)) +I["Ring"] = (circ(8,8,3.5), None) +I["HalfDot"] = (circ(8,8,3.5), "M8 4.5 A3.5 3.5 0 0 1 8 11.5 Z") +I["Triangle"] = (None, "M8 3 L13.5 12.5 H2.5 Z") +I["TriangleRight"] = (None, "M5 3 L12 8 L5 13 Z") +I["Cross"] = ("M4.5 4.5 L11.5 11.5 M11.5 4.5 L4.5 11.5", None) + +out = os.path.join(os.path.dirname(__file__), "..", "..", "src", "Titano.Ui", "Icons", "Icons.xaml") +with open(out, "w") as f: + f.write('\n') + f.write(' \n') + for name, (stroke, fill) in sorted(I.items()): + attrs = '' + if stroke: attrs += f' Stroke="{stroke}"' + if fill: attrs += f' Fill="{fill}"' + f.write(f' \n') + f.write('\n') + +cols = 10 +names = sorted(I) +rows = (len(names) + cols - 1) // cols +svg = [f''] +for k, name in enumerate(names): + x, y = (k % cols) * 90 + 37, (k // cols) * 70 + 14 + stroke, fill = I[name] + svg.append(f'') + if fill: svg.append(f'') + if stroke: svg.append(f'') + svg.append('') + svg.append(f'{name}') +svg.append('') +open(os.path.join(os.path.dirname(__file__), "icons.svg"), "w").write("\n".join(svg)) +print(len(I), "icons") diff --git a/branding/ui-icons/icons.svg b/branding/ui-icons/icons.svg new file mode 100644 index 00000000..a63e85c2 --- /dev/null +++ b/branding/ui-icons/icons.svg @@ -0,0 +1,417 @@ + + + + +About + + + +ActualSize + + + +Analyse + + + +Archive + + + +Back + + + +Calendar + + + +Camera + + + +Cancel + + + +Card + + + +Chart + + + +Check + + + +ChevronDown + + + +ChevronLeft + + + +ChevronRight + + + +ChevronUp + + + +Clipboard + + + +Clock + + + +Close + + + +Compare + + + +Copy + + + +CropMask + + + +Cross + + + +Database + + + +Delete + + + +Dot + + + +Download + + + +Drive + + + +Duplicate + + + + +Eject + + + +ErrorCircle + + + +Exclude + + + +Export + + + +Exposure + + + +ExternalLink + + + +Eye + + + +Filmstrip + + + +Filter + + + +Folder + + + +FolderOpen + + + +Forward + + + +Fullscreen + + + +Gpu + + + +Grip + + + + +HalfDot + + + + +Hero + + + + +Image + + + +Import + + + +Info + + + +Jobs + + + +Key + + + +Keyframe + + + +Layers + + + +Library + + + +Link + + + +Lock + + + +Logs + + + +Menu + + + +Minus + + + +Moon + + + +More + + + +Motion + + + + +Network + + + +Optimise + + + +Pause + + + +Play + + + +Plus + + + +Power + + + +Refresh + + + +Regions + + + + +Render + + + +Reset + + + +Retry + + + +Ring + + + +Search + + + +Sequence + + + +Server + + + +Settings + + + +Sort + + + + +Spline + + + +Stack + + + +Star + + + +StarFilled + + + +Stop + + + +SuccessCircle + + + +Sun + + + +Sync + + + +Tag + + + +Time + + + +Tray + + + +Triangle + + + +TriangleRight + + + +Upload + + + +User + + + +Users + + + +Vectors + + + +Verify + + + +ViewGrid + + + +ViewList + + + +ViewTimeline + + + +Warning + + + +Window + + + +Wipe + \ No newline at end of file diff --git a/deploy/docker/.env.example b/deploy/docker/.env.example new file mode 100644 index 00000000..f7e438eb --- /dev/null +++ b/deploy/docker/.env.example @@ -0,0 +1,8 @@ +TITANO_ADMIN_PASSWORD=change-me-at-first-login +TITANO_DB_PASSWORD=choose-a-long-random-password +TITANO_ARCHIVE=/mnt/user/Timelapse +TITANO_DATA=./data +TITANO_PGDATA=./pgdata +PUID=1000 +PGID=1000 +TZ=Europe/Rome diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile new file mode 100644 index 00000000..f3bd6889 --- /dev/null +++ b/deploy/docker/Dockerfile @@ -0,0 +1,43 @@ +# syntax=docker/dockerfile:1 +# Titano Server — multi-stage, multi-arch (linux/amd64, linux/arm64). BRIEF §14.9. + +FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build +ARG TARGETARCH +ARG TITANO_VERSION=0.0.0-dev +WORKDIR /src +COPY global.json Directory.Build.props Directory.Build.targets Titano.slnx ./ +COPY i18n/ i18n/ +COPY src/Titano.Core/ src/Titano.Core/ +COPY src/Titano.Data/ src/Titano.Data/ +COPY src/Titano.Protocol/ src/Titano.Protocol/ +COPY src/Titano.Server/ src/Titano.Server/ +RUN dotnet publish src/Titano.Server/Titano.Server.csproj \ + -c Release -a "$TARGETARCH" --no-self-contained \ + -p:TitanoVersion="$TITANO_VERSION" -o /out \ + && rm -f /out/*.pdb + +FROM mcr.microsoft.com/dotnet/aspnet:10.0 +ARG TITANO_VERSION=0.0.0-dev +LABEL org.opencontainers.image.title="Titano Server" \ + org.opencontainers.image.description="Time-lapse archive, uploads, jobs and rendering server" \ + org.opencontainers.image.version="$TITANO_VERSION" \ + org.opencontainers.image.licenses="LicenseRef-Titano-EULA" +ENV TITANO_ARCHIVE_PATH=/archive \ + TITANO_DATA_PATH=/data \ + TITANO_HTTP_PORT=8080 \ + TITANO_HTTPS_PORT=8443 \ + TITANO_DB=postgres \ + PUID=1000 \ + PGID=1000 \ + DOTNET_gcServer=1 \ + DOTNET_GCHeapAffinitizeMask= \ + DOTNET_NOLOGO=1 +WORKDIR /app +COPY --from=build /out/ ./ +COPY deploy/docker/entrypoint.sh /usr/local/bin/titano-entrypoint +RUN chmod 0755 /usr/local/bin/titano-entrypoint && mkdir -p /archive /data +VOLUME ["/archive", "/data"] +EXPOSE 8080 8443 +HEALTHCHECK --interval=30s --timeout=8s --start-period=40s --retries=3 \ + CMD ["dotnet", "/app/Titano.Server.dll", "--healthcheck"] +ENTRYPOINT ["/usr/local/bin/titano-entrypoint"] diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml new file mode 100644 index 00000000..9cc7dd66 --- /dev/null +++ b/deploy/docker/docker-compose.yml @@ -0,0 +1,44 @@ +# Titano Server with PostgreSQL 17. Start: docker compose up -d Admin panel: http://:8080/admin +name: titano + +services: + titano: + image: ghcr.io/alby96/titano-server:latest + restart: unless-stopped + depends_on: + postgres: + condition: service_healthy + ports: + - "8080:8080" + - "8443:8443" + environment: + TITANO_ADMIN_USER: admin + TITANO_ADMIN_PASSWORD: ${TITANO_ADMIN_PASSWORD:?set TITANO_ADMIN_PASSWORD in .env} + TITANO_DB: postgres + TITANO_DB_HOST: postgres + TITANO_DB_NAME: titano + TITANO_DB_USER: titano + TITANO_DB_PASSWORD: ${TITANO_DB_PASSWORD:?set TITANO_DB_PASSWORD in .env} + TITANO_TLS_MODE: auto + TITANO_SERVER_NAME: Titano Server + PUID: ${PUID:-1000} + PGID: ${PGID:-1000} + TZ: ${TZ:-UTC} + volumes: + - ${TITANO_ARCHIVE:-./archive}:/archive + - ${TITANO_DATA:-./data}:/data + + postgres: + image: postgres:17 + restart: unless-stopped + environment: + POSTGRES_DB: titano + POSTGRES_USER: titano + POSTGRES_PASSWORD: ${TITANO_DB_PASSWORD:?set TITANO_DB_PASSWORD in .env} + volumes: + - ${TITANO_PGDATA:-./pgdata}:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U titano -d titano"] + interval: 10s + timeout: 5s + retries: 10 diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh new file mode 100755 index 00000000..9ea31992 --- /dev/null +++ b/deploy/docker/entrypoint.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Runs Titano Server as PUID:PGID (Unraid/NAS convention). /data is owned by that user; /archive is left as +# mounted (it may hold terabytes) and only checked for write access. +set -eu + +PUID="${PUID:-1000}" +PGID="${PGID:-1000}" +umask 002 + +if [ "$(id -u)" = "0" ]; then + mkdir -p /data + chown -R "$PUID:$PGID" /data + if ! setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- test -w "${TITANO_ARCHIVE_PATH:-/archive}"; then + echo "warning: ${TITANO_ARCHIVE_PATH:-/archive} is not writable by $PUID:$PGID" >&2 + fi + exec setpriv --reuid="$PUID" --regid="$PGID" --clear-groups -- dotnet /app/Titano.Server.dll "$@" +fi + +exec dotnet /app/Titano.Server.dll "$@" diff --git a/deploy/unraid/titano.xml b/deploy/unraid/titano.xml new file mode 100644 index 00000000..08649b6a --- /dev/null +++ b/deploy/unraid/titano.xml @@ -0,0 +1,41 @@ + + + titano-server + ghcr.io/alby96/titano-server:latest + https://github.com/alby96/titano-releases + bridge + + sh + false + https://github.com/alby96/titano-releases/issues + https://github.com/alby96/titano-releases + Titano Server keeps a shared, verified archive of time-lapse photo sequences and renders them. Pair it with the official PostgreSQL 17 container. + MediaServer:Photos Tools: + http://[IP]:[PORT:8080]/admin + https://raw.githubusercontent.com/alby96/titano-releases/main/unraid/titano.xml + https://raw.githubusercontent.com/alby96/titano-releases/main/unraid/titano-server.png + --restart unless-stopped + + + + + + A PostgreSQL 16 or 17 container (official "postgres" template) with a database and user for Titano. + 8080 + 8443 + /mnt/user/Timelapse + /mnt/user/appdata/titano + admin + + postgresql17 + 5432 + titano + titano + + prefer + auto + Titano Server + 99 + 100 + Europe/Rome + diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 88a030af..ab7f9c76 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -6,7 +6,12 @@ All notable changes. Format: Keep a Changelog; versions follow SemVer; commits f ### Added - Repository foundation: solution, build rules (warnings as errors, zero-package guard), .NET 10 SDK pin. -- `Titano.Testing`: in-house test framework and runner with JUnit XML output. -- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages) and `i18n check/export`. -- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon`. -- Core contracts: image buffers and decoder providers, video encoder providers, domain model, atomic file writes. +- `Titano.Testing`: in-house test framework and runner with JUnit XML output and GitHub annotations. +- Localization runtime (`Loc`, CLDR plural rules, 38 shipped languages), `en` + `it` catalogs, `i18n check/export`. +- Brand mark geometry, SDF rasteriser, PNG encoder, ICO writer and `make-icon` (program icons generated at build time). +- Core contracts: image buffers and decoder providers, video encoder providers, domain model, TIFF/IFD reader, sRGB helpers, atomic file writes, logging. +- `Titano.Ui` design system: DESIGN.md tokens (dark/light), 100+ stroke icons, styles for every standard control, custom chrome window with snap layouts, navigation rail, job bar, Auto/manual slider, chips, status glyphs, toasts, empty states. +- Titano desktop shell: rail, job bar, status strip, sections, Settings (language, theme) and About; `--capture` screenshot mode. +- Titano Server skeleton: configuration from environment/`server.json`, self-signed TLS with fingerprint, `/health`, `/api/v1/server/info`, `/api/v1/i18n/{culture}`, embedded admin panel (login, dashboard). +- Docker image (multi-arch, PUID/PGID, health check), compose file with PostgreSQL 17, Unraid template. +- CI (Windows + Linux build/test, PostgreSQL 16/17, Docker smoke test, screenshots, Windows program artifacts), release and nightly image workflows. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 4b79c26f..b1074064 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -14,3 +14,13 @@ One line per decision: date · decision · alternative · reason. | 2026-10-02 | In-house CRC-32 (`Titano.Core.Hashing.Crc32`). | System.IO.Hashing | That assembly is a NuGet package, not part of the shared framework. | | 2026-10-02 | Windows projects target `net10.0-windows` (platform version 7.0) without a Windows SDK projection TFM; Windows 10 APIs are reached by P/Invoke/COM. | `net10.0-windows10.0.19041.0` | Avoids the CsWinRT projection; toasts use the in-window toast host plus tray balloon. | | 2026-10-02 | Test projects use an explicit `TestMain` entry point. | Top-level statements | Avoids the `Program` type clash with the server's top-level program. | +| 2026-10-02 | SQLite P/Invoke binding lives in `Titano.Data` with a library resolver (winsqlite3 on Windows, system libsqlite3 elsewhere for tests/dev); the Linux server still refuses SQLite at configuration time. | Binding in Core.Windows only | Lets repository tests run on Linux CI against both dialects. | +| 2026-10-02 | Client preferences needed before the database opens (language, theme, window placement) are stored in `settings.json` next to the database. | Settings table only | Language and theme must apply before the first window appears. | +| 2026-10-02 | Server Windows-service hosting will use an in-house advapi32 P/Invoke host. | Microsoft.Extensions.Hosting.WindowsServices | That assembly is a NuGet package, not part of the shared framework. | +| 2026-10-02 | Admin panel files are embedded resources served by an in-house middleware with ETags and SPA fallback. | ManifestEmbeddedFileProvider | Its manifest generator ships in a NuGet package. | +| 2026-10-02 | Container health check runs `Titano.Server --healthcheck` (in-process HTTP probe). | curl/wget in the image | Keeps the runtime image free of extra tools. | +| 2026-10-02 | Container drops privileges with `setpriv` to PUID:PGID; `/data` is chowned, `/archive` only checked for write access. | Recursive chown of the archive | The archive may hold terabytes on NAS shares. | +| 2026-10-02 | Release workflow publishes to `RELEASES_REPO` (default `/titano-releases`) when the `RELEASES_TOKEN` secret exists, otherwise to this repository. | Fail without the token | First releases work before the public repository is set up. | +| 2026-10-02 | Release notes are generated by `Titano.Tools changelog` from `git log` piped on stdin. | Tool spawning git | Keeps the tool free of external process calls. | +| 2026-10-02 | CI `dotnet format` gate checks whitespace formatting. | Full style/analyzer verification | Analyzer rules already fail the build (warnings as errors); style preferences stay suggestions. | +| 2026-10-02 | Test runner exits 0 for a project with no tests and 2 when a filter matches nothing. | Always 2 | Empty projects during bootstrap are not failures; mistyped filters are. | diff --git a/docs/STATUS.md b/docs/STATUS.md index 992f99a0..32885bdd 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,17 @@ # Status -Current phase: **Phase 0 — Bootstrap** (in progress). +Current phase: **Phase 0 — Bootstrap** complete on Linux; Windows verification runs in CI. +Engine workstreams for Phases 1–2 and 5–6 (metadata, codecs, data, video, analysis, motion, Windows interop) are in progress. + +## How to try it + +``` +dotnet build Titano.slnx -c Release +dotnet run --project src/Titano.Server # http://localhost:8080/admin (set TITANO_DATA_PATH/TITANO_ARCHIVE_PATH) +src/Titano.App/bin/Release/net10.0-windows/Titano.exe # Windows +docker compose -f deploy/docker/docker-compose.yml up -d # server + PostgreSQL 17 +``` + +## Next steps See docs/BRIEF.md §22 for the phase plan. diff --git a/i18n/en/About.resx b/i18n/en/About.resx new file mode 100644 index 00000000..a9d2a50d --- /dev/null +++ b/i18n/en/About.resx @@ -0,0 +1,14 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Data + Data folder + Releases + Runtime + System + Third-party code + None + diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx new file mode 100644 index 00000000..d63f15e8 --- /dev/null +++ b/i18n/en/Admin.resx @@ -0,0 +1,37 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + TLS SHA-256 + Titano Server + API version + Archive + Server + The server did not answer; try again.long + Wrong user name or password.long + Password + Sign in + Sign in to administer this server + User + About + Version and certificate fingerprint + Archive + Archive path, templates, scan and verify + Dashboard + Storage, jobs and render nodes at a glance + Jobs + Queue, history and render nodes + Logs + Recent log lines and downloads + Settings + Server name, ports, TLS, limits and language + Users + Accounts, roles and quotas + Administrator + Editor + Uploader + Viewer + Sign out of the admin panel + diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx new file mode 100644 index 00000000..20ad648e --- /dev/null +++ b/i18n/en/Archive.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + No archive yet + diff --git a/i18n/en/Common.resx b/i18n/en/Common.resx new file mode 100644 index 00000000..5b7c5adf --- /dev/null +++ b/i18n/en/Common.resx @@ -0,0 +1,15 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Auto + {0} d {1} h + {0} h {1} m + {0} min + {0} s + n/a + Open + Open logs + diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx new file mode 100644 index 00000000..2de00b56 --- /dev/null +++ b/i18n/en/Editor.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Pick a sequence in the Library + diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx new file mode 100644 index 00000000..702ea76f --- /dev/null +++ b/i18n/en/Errors.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Something went wrong. + diff --git a/i18n/en/Import.resx b/i18n/en/Import.resx new file mode 100644 index 00000000..1dd4adb7 --- /dev/null +++ b/i18n/en/Import.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Insert a card or pick a folder + diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx new file mode 100644 index 00000000..9be7175a --- /dev/null +++ b/i18n/en/Jobs.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + No jobs yet + diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx new file mode 100644 index 00000000..7db63837 --- /dev/null +++ b/i18n/en/Library.resx @@ -0,0 +1,11 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + No sequences yet + Connect to a server + Import a card + Open an archive + diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx new file mode 100644 index 00000000..b9ba718d --- /dev/null +++ b/i18n/en/Server.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Not connected to a server + diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx new file mode 100644 index 00000000..bd1f5673 --- /dev/null +++ b/i18n/en/Settings.resx @@ -0,0 +1,25 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Data folder + Check on start + Language + Theme + Dark + Light + System + Updates + Advanced + Analysis + Archive + Formats + General + Import + Licence + Rendering + Server + Updates + diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx index dd4fb457..80a2fb84 100644 --- a/i18n/en/Shell.resx +++ b/i18n/en/Shell.resx @@ -4,7 +4,22 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - Titano - {0:N0} photo - {0:N0} photos + Titanoinvariant + Ready · {0} jobs queued + About + Archive + Import + Jobs + Library + Sequence + Server + Settings + Connected to "{0}" + {0:N0} job + {0:N0} jobs + Not connected + {0:N0} photo + {0:N0} photos + {0:N0} sequence + {0:N0} sequences diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx new file mode 100644 index 00000000..b6393fa1 --- /dev/null +++ b/i18n/en/Tooltips.resx @@ -0,0 +1,37 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Open the folder with database, settings and logs + Open the public releases page in the browser + Dismiss + Open the folder with the log files + Return to the advisor's value + Work with the archive of a Titano Server + Copy and verify photos from a memory card + Use an existing archive folder on this PC or the network + Version, diagnostics and links + Scan, verify and maintain the archive · Ctrl+4 + Import photos from a card or folder · Ctrl+2 + Queue and history of long operations · Ctrl+5 + Browse every sequence of the archive · Ctrl+1 + Edit and render the open sequence · Ctrl+3 + Connection, sync and render node · Ctrl+6 + Preferences of this PC · Ctrl+, + Look for a new release when Titano starts · no data is sent + Database, settings, logs and caches of this PC + Language of the interface · applies immediately + Open the data folder in Explorer + Dark interface (default) + Light interface + Follow the Windows app mode + Collapse navigation to icons + Show navigation names + Stop the current job · it can be resumed later + Close + Maximize + Minimize + Restore + diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx new file mode 100644 index 00000000..3f3261ff --- /dev/null +++ b/i18n/it/About.it.resx @@ -0,0 +1,14 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Dati + Cartella dati + Versioni + Runtime + Sistema + Codice di terzi + Nessuno + diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx new file mode 100644 index 00000000..4e1f7a66 --- /dev/null +++ b/i18n/it/Admin.it.resx @@ -0,0 +1,37 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + TLS SHA-256 + Titano Server + Versione API + Archivio + Server + Il server non ha risposto; riprova. + Nome utente o password errati. + Password + Accedi + Accedi per amministrare questo server + Utente + Informazioni + Versione e impronta del certificato + Archivio + Percorso archivio, modelli, scansione e verifica + Panoramica + Spazio, attività e nodi di rendering in sintesi + Attività + Coda, cronologia e nodi di rendering + Log + Ultime righe di log e download + Impostazioni + Nome server, porte, TLS, limiti e lingua + Utenti + Account, ruoli e quote + Amministratore + Editor + Caricamento + Lettore + Esci dal pannello di amministrazione + diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx new file mode 100644 index 00000000..00b325d1 --- /dev/null +++ b/i18n/it/Archive.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Nessun archivio + diff --git a/i18n/it/Common.it.resx b/i18n/it/Common.it.resx new file mode 100644 index 00000000..24f3494c --- /dev/null +++ b/i18n/it/Common.it.resx @@ -0,0 +1,15 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Auto + {0} g {1} h + {0} h {1} m + {0} min + {0} s + n/d + Apri + Apri log + diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx new file mode 100644 index 00000000..a0b523f2 --- /dev/null +++ b/i18n/it/Editor.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Scegli una sequenza in Libreria + diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx new file mode 100644 index 00000000..cc83b7f7 --- /dev/null +++ b/i18n/it/Errors.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Si è verificato un problema. + diff --git a/i18n/it/Import.it.resx b/i18n/it/Import.it.resx new file mode 100644 index 00000000..1d75e138 --- /dev/null +++ b/i18n/it/Import.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Inserisci una scheda o una cartella + diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx new file mode 100644 index 00000000..2495adbd --- /dev/null +++ b/i18n/it/Jobs.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Nessuna attività + diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx new file mode 100644 index 00000000..11ad6451 --- /dev/null +++ b/i18n/it/Library.it.resx @@ -0,0 +1,11 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Nessuna sequenza + Connetti a un server + Importa una scheda + Apri un archivio + diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx new file mode 100644 index 00000000..d80ac2f7 --- /dev/null +++ b/i18n/it/Server.it.resx @@ -0,0 +1,8 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Non connesso a un server + diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx new file mode 100644 index 00000000..bcfe6714 --- /dev/null +++ b/i18n/it/Settings.it.resx @@ -0,0 +1,25 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Cartella dati + Controlla all'avvio + Lingua + Tema + Scuro + Chiaro + Sistema + Aggiornamenti + Avanzate + Analisi + Archivio + Formati + Generale + Importazione + Licenza + Rendering + Server + Aggiornamenti + diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx index 7d948680..471272fb 100644 --- a/i18n/it/Shell.it.resx +++ b/i18n/it/Shell.it.resx @@ -4,6 +4,21 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - {0:N0} foto - {0:N0} foto + Pronto · {0} attività in coda + Informazioni + Archivio + Importa + Attività + Libreria + Sequenza + Server + Impostazioni + Connesso a «{0}» + {0:N0} attività + {0:N0} attività + Non connesso + {0:N0} foto + {0:N0} foto + {0:N0} sequenza + {0:N0} sequenze diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx new file mode 100644 index 00000000..6892a5f4 --- /dev/null +++ b/i18n/it/Tooltips.it.resx @@ -0,0 +1,37 @@ + + + text/microsoft-resx + 2.0 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Apri la cartella con database, impostazioni e log + Apri la pagina pubblica delle versioni nel browser + Chiudi + Apri la cartella dei file di log + Torna al valore consigliato + Lavora con l'archivio di un Titano Server + Copia e verifica le foto da una scheda di memoria + Usa una cartella archivio esistente su questo PC o in rete + Versione, diagnostica e collegamenti + Scansiona, verifica e gestisci l'archivio · Ctrl+4 + Importa foto da una scheda o una cartella · Ctrl+2 + Coda e cronologia delle operazioni lunghe · Ctrl+5 + Sfoglia tutte le sequenze dell'archivio · Ctrl+1 + Modifica e renderizza la sequenza aperta · Ctrl+3 + Connessione, sincronizzazione e nodo di rendering · Ctrl+6 + Preferenze di questo PC · Ctrl+, + Cerca una nuova versione all'avvio di Titano · nessun dato viene inviato + Database, impostazioni, log e cache di questo PC + Lingua dell'interfaccia · si applica subito + Apri la cartella dati in Esplora file + Interfaccia scura (predefinita) + Interfaccia chiara + Segui la modalità app di Windows + Riduci la navigazione alle icone + Mostra i nomi della navigazione + Ferma l'attività in corso · potrai riprenderla + Chiudi + Ingrandisci + Riduci a icona + Ripristina + diff --git a/src/Titano.App/App.xaml b/src/Titano.App/App.xaml index fa7e5103..c70dfc76 100644 --- a/src/Titano.App/App.xaml +++ b/src/Titano.App/App.xaml @@ -1,4 +1,12 @@ + xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" + ShutdownMode="OnMainWindowClose"> + + + + + + + diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs index 83019998..d3122b31 100644 --- a/src/Titano.App/App.xaml.cs +++ b/src/Titano.App/App.xaml.cs @@ -1,7 +1,97 @@ +using System.Globalization; using System.Windows; +using System.Windows.Threading; +using Titano.App.Infrastructure; +using Titano.App.Shell; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Ui.Mvvm; +using Titano.Ui.Theming; namespace Titano.App; public partial class App : Application { + private FileLogSink? _log; + + public AppEnvironment Environment { get; private set; } = null!; + public AppSettings Settings { get; private set; } = null!; + + public static new App Current => (App)Application.Current; + + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + Environment = AppEnvironment.Detect(); + _log = new FileLogSink(Environment.LogDirectory, "titano"); + Log.SetSink(_log); + Log.Info("app", $"Titano {typeof(App).Assembly.GetName().Version} starting; data at {Environment.DataDirectory}"); + + Settings = AppSettings.Load(Environment.SettingsPath); + ApplyLanguage(Settings.Language); + ThemeManager.Initialize(this, Settings.Theme); + + DispatcherUnhandledException += OnUnhandledException; + AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("app", "Unhandled exception", args.ExceptionObject as Exception); + TaskScheduler.UnobservedTaskException += (_, args) => + { + Log.Error("app", "Unobserved task exception", args.Exception); + args.SetObserved(); + }; + + var shell = new ShellViewModel(Settings); + AsyncRelayCommand.Failed += ex => shell.ReportError(ex); + var window = new MainWindow(shell); + MainWindow = window; + + var captureIndex = Array.IndexOf(e.Args, "--capture"); + if (captureIndex >= 0) + { + var dir = captureIndex + 1 < e.Args.Length ? e.Args[captureIndex + 1] : "screenshots"; + ScreenCapture.Run(window, shell, dir); + return; + } + window.Show(); + } + + /// Switches the UI language at run time (BRIEF §16) and remembers the choice. + public void ApplyLanguage(string? code) + { + var culture = Languages.BestMatch(code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code)); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + Loc.SetCulture(culture); + foreach (Window w in Windows) + w.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; + } + + public void SaveSettings() + { + try + { + Settings.Save(Environment.SettingsPath); + } + catch (System.IO.IOException ex) + { + Log.Warning("app", "Settings not saved", ex); + } + } + + protected override void OnExit(ExitEventArgs e) + { + SaveSettings(); + Log.Info("app", "Titano exiting"); + _log?.Dispose(); + base.OnExit(e); + } + + private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) + { + Log.Error("app", "Unhandled UI exception", e.Exception); + if (MainWindow?.DataContext is ShellViewModel shell) + { + shell.ReportError(e.Exception); + e.Handled = true; + } + } } diff --git a/src/Titano.App/Infrastructure/AppEnvironment.cs b/src/Titano.App/Infrastructure/AppEnvironment.cs new file mode 100644 index 00000000..5b0d9db2 --- /dev/null +++ b/src/Titano.App/Infrastructure/AppEnvironment.cs @@ -0,0 +1,35 @@ +using System.IO; + +namespace Titano.App.Infrastructure; + +/// +/// Where the client keeps its data (BRIEF §6.2): %LOCALAPPDATA%\Titano, or .\data next to the +/// executable when portable.txt exists. Never inside Documents/OneDrive (SQLite corrupts in synced folders). +/// +public sealed class AppEnvironment +{ + private AppEnvironment(string dataDirectory, bool portable) + { + DataDirectory = dataDirectory; + IsPortable = portable; + Directory.CreateDirectory(DataDirectory); + Directory.CreateDirectory(LogDirectory); + Directory.CreateDirectory(CacheDirectory); + } + + public string DataDirectory { get; } + public bool IsPortable { get; } + public string LogDirectory => Path.Combine(DataDirectory, "logs"); + public string CacheDirectory => Path.Combine(DataDirectory, "cache"); + public string DatabasePath => Path.Combine(DataDirectory, "titano.db"); + public string SettingsPath => Path.Combine(DataDirectory, "settings.json"); + + public static AppEnvironment Detect() + { + var exeDir = AppContext.BaseDirectory; + if (File.Exists(Path.Combine(exeDir, "portable.txt"))) + return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true); + var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return new AppEnvironment(Path.Combine(local, "Titano"), portable: false); + } +} diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs new file mode 100644 index 00000000..9022de83 --- /dev/null +++ b/src/Titano.App/Infrastructure/AppSettings.cs @@ -0,0 +1,51 @@ +using System.IO; +using System.Text.Json; +using System.Text.Json.Serialization; +using Titano.Core.IO; +using Titano.Ui.Theming; + +namespace Titano.App.Infrastructure; + +/// Per-user preferences needed before the database opens (language, theme, window layout). +public sealed class AppSettings +{ + public string? Language { get; set; } + public AppTheme Theme { get; set; } = AppTheme.Dark; + public bool RailCollapsed { get; set; } + public bool CheckForUpdates { get; set; } = true; + public bool AnonymousUsageCounts { get; set; } + public string? LastArchivePath { get; set; } + public WindowPlacement? Window { get; set; } + + public sealed class WindowPlacement + { + public double Left { get; set; } + public double Top { get; set; } + public double Width { get; set; } + public double Height { get; set; } + public bool Maximized { get; set; } + } + + public static AppSettings Load(string path) + { + try + { + if (File.Exists(path)) + return JsonSerializer.Deserialize(File.ReadAllText(path), AppSettingsJson.Default.AppSettings) ?? new AppSettings(); + } + catch (JsonException) + { + // A corrupt settings file must never block startup; defaults apply. + } + catch (IOException) + { + } + return new AppSettings(); + } + + public void Save(string path) => AtomicFile.WriteAllText(path, JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings)); +} + +[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)] +[JsonSerializable(typeof(AppSettings))] +internal sealed partial class AppSettingsJson : JsonSerializerContext; diff --git a/src/Titano.App/Infrastructure/Formatting.cs b/src/Titano.App/Infrastructure/Formatting.cs new file mode 100644 index 00000000..5a3c2ab8 --- /dev/null +++ b/src/Titano.App/Infrastructure/Formatting.cs @@ -0,0 +1,34 @@ +using Titano.Core.Localization; + +namespace Titano.App.Infrastructure; + +/// Culture-aware number, size and duration formatting for the UI. +public static class Formatting +{ + private static readonly string[] ByteUnits = ["B", "KB", "MB", "GB", "TB", "PB"]; + + /// 1,536 → "1.5 KB" (decimal units, as Explorer shows for drives). + public static string Bytes(long bytes) + { + double value = bytes; + var unit = 0; + while (value >= 1000 && unit < ByteUnits.Length - 1) + { + value /= 1000; + unit++; + } + var format = unit == 0 || value >= 100 ? "0" : "0.#"; + return value.ToString(format, Loc.Culture) + " " + ByteUnits[unit]; + } + + public static string Count(long n) => n.ToString("N0", Loc.Culture); + + /// Compact duration: "2 h 00 m", "5 min", "40 s". + public static string Duration(TimeSpan t) + { + if (t.TotalHours >= 24) return Loc.L("Common.Duration.Days", (int)t.TotalDays, t.Hours); + if (t.TotalHours >= 1) return Loc.L("Common.Duration.Hours", (int)t.TotalHours, t.Minutes.ToString("00", Loc.Culture)); + if (t.TotalMinutes >= 1) return Loc.L("Common.Duration.Minutes", (int)Math.Round(t.TotalMinutes)); + return Loc.L("Common.Duration.Seconds", (int)Math.Round(t.TotalSeconds)); + } +} diff --git a/src/Titano.App/Infrastructure/ProductLinks.cs b/src/Titano.App/Infrastructure/ProductLinks.cs new file mode 100644 index 00000000..abdef10a --- /dev/null +++ b/src/Titano.App/Infrastructure/ProductLinks.cs @@ -0,0 +1,14 @@ +namespace Titano.App.Infrastructure; + +/// Public links (BRIEF §19.4). Overridable at build time via the TitanoReleasesRepo property. +public static class ProductLinks +{ + public static string ReleasesRepository { get; } = + typeof(ProductLinks).Assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyMetadataAttribute), false) + .OfType() + .FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value ?? "alby96/titano-releases"; + + public static string Releases => $"https://github.com/{ReleasesRepository}/releases"; + + public static string LatestReleaseApi => $"https://api.github.com/repos/{ReleasesRepository}/releases/latest"; +} diff --git a/src/Titano.App/Infrastructure/ShellActions.cs b/src/Titano.App/Infrastructure/ShellActions.cs new file mode 100644 index 00000000..ba546bb5 --- /dev/null +++ b/src/Titano.App/Infrastructure/ShellActions.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; +using System.IO; + +namespace Titano.App.Infrastructure; + +/// The only shell launches the product performs (BRIEF §8.6): open a URL, reveal a folder. +public static class ShellActions +{ + public static void OpenUrl(string url) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http" or "ms-windows-store")) return; + Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true }); + } + + public static void OpenFolder(string path) + { + if (!Directory.Exists(path)) return; + Process.Start(new ProcessStartInfo(path) { UseShellExecute = true, Verb = "explore" }); + } +} diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml new file mode 100644 index 00000000..adaa0d17 --- /dev/null +++ b/src/Titano.App/Sections/AboutView.xaml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + `; + applyStrings(app); + const form = app.querySelector("form"); + const error = form.querySelector(".error"); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + error.textContent = ""; + const data = new FormData(form); + try { + await api.signIn(String(data.get("username")), String(data.get("password"))); + render(); + } catch (err) { + error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : t("Admin.Error.Unreachable"); + } + }); + form.querySelector("input").focus(); +} + +function renderShell(page) { + const nav = pages.map((p) => ` + ${icons[pageIcon[p]]}`).join(""); + const user = api.user(); + app.innerHTML = ` +
+ +
+

+
+
+
`; + applyStrings(app); + app.querySelector("#signout").addEventListener("click", async () => { + await api.signOut(); + render(); + }); + const content = app.querySelector("#content"); + import(`./pages/${page}.js`) + .then((m) => m.render(content, { api, t, info, meta: app.querySelector("#meta") })) + .catch(() => { + content.innerHTML = `
`; + applyStrings(content); + }); +} + +export function escapeHtml(s) { + return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +} + +function cap(s) { + return s.charAt(0).toUpperCase() + s.slice(1); +} + +start(); diff --git a/src/Titano.Server/Admin/web/favicon.svg b/src/Titano.Server/Admin/web/favicon.svg new file mode 100644 index 00000000..7cd565b2 --- /dev/null +++ b/src/Titano.Server/Admin/web/favicon.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Titano.Server/Admin/web/i18n.js b/src/Titano.Server/Admin/web/i18n.js new file mode 100644 index 00000000..3b50350c --- /dev/null +++ b/src/Titano.Server/Admin/web/i18n.js @@ -0,0 +1,27 @@ +// Strings come from /api/v1/i18n/{culture}, generated from the same .resx catalog as the desktop apps. +let strings = {}; + +export async function loadStrings(culture) { + try { + const res = await fetch(`/api/v1/i18n/${encodeURIComponent(culture || "en")}`); + strings = await res.json(); + } catch { + strings = {}; + } + document.documentElement.lang = strings.$culture || "en"; + document.documentElement.dir = strings.$rtl === "true" ? "rtl" : "ltr"; +} + +/** Localized string for key with {0}, {1}… placeholders filled from args. */ +export function t(key, ...args) { + const s = strings[key]; + if (s === undefined) return `⟦${key}⟧`; + return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => (args[Number(i)] ?? "")); +} + +/** Fills data-i18n (text), data-i18n-title (tooltip) and data-i18n-placeholder attributes. */ +export function applyStrings(root) { + root.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); }); + root.querySelectorAll("[data-i18n-title]").forEach((el) => { el.title = t(el.dataset.i18nTitle); }); + root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); }); +} diff --git a/src/Titano.Server/Admin/web/icons.js b/src/Titano.Server/Admin/web/icons.js new file mode 100644 index 00000000..1ea443a0 --- /dev/null +++ b/src/Titano.Server/Admin/web/icons.js @@ -0,0 +1,16 @@ +// Generated from branding/ui-icons/icons.py (same 16-px set as the desktop apps). +export const icons = { + dashboard: ``, + users: ``, + archive: ``, + jobs: ``, + settings: ``, + logs: ``, + about: ``, + power: ``, + moon: ``, + refresh: ``, + close: ``, + plus: ``, + search: ``, +}; diff --git a/src/Titano.Server/Admin/web/index.html b/src/Titano.Server/Admin/web/index.html index 7c26771a..12113418 100644 --- a/src/Titano.Server/Admin/web/index.html +++ b/src/Titano.Server/Admin/web/index.html @@ -1 +1,15 @@ -Titano + + + + + + + Titano Server + + + + + +
+ + diff --git a/src/Titano.Server/Admin/web/pages/about.js b/src/Titano.Server/Admin/web/pages/about.js new file mode 100644 index 00000000..1228e1fe --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/about.js @@ -0,0 +1,12 @@ +import { applyStrings } from "../i18n.js"; +import { escapeHtml } from "../app.js"; + +export async function render(root, { info }) { + root.innerHTML = ` +
+

+

Titano Server ${escapeHtml(info?.version ?? "")} · API ${escapeHtml(String(info?.apiVersion ?? ""))}

+

${escapeHtml(info?.tlsFingerprint ?? "–")}

+
`; + applyStrings(root); +} diff --git a/src/Titano.Server/Admin/web/pages/dashboard.js b/src/Titano.Server/Admin/web/pages/dashboard.js new file mode 100644 index 00000000..4a4ab432 --- /dev/null +++ b/src/Titano.Server/Admin/web/pages/dashboard.js @@ -0,0 +1,18 @@ +// Dashboard: storage, archive, jobs, render nodes (BRIEF §14.8). Data from the public API only. +import { applyStrings } from "../i18n.js"; + +export async function render(root, { api, t, info, meta }) { + const health = await api.get("/health").catch(() => null); + meta.textContent = info ? `v${info.version} · TLS ${info.tlsFingerprint ? "auto" : "proxy"}` : ""; + root.innerHTML = ` +
+
+
${health?.status === "ok" ? `●` : `✕`}${health?.status ?? ""}
+
${info?.name ?? ""}
+
+
${health?.checks?.archive === "ok" ? `●` : `▲`}${health?.checks?.archive ?? ""}
+
+
${info?.apiVersion ?? "–"}
${(info?.capabilities ?? []).join(" · ")}
+
`; + applyStrings(root); +} diff --git a/src/Titano.Server/Api/SystemEndpoints.cs b/src/Titano.Server/Api/SystemEndpoints.cs new file mode 100644 index 00000000..a7da0fe4 --- /dev/null +++ b/src/Titano.Server/Api/SystemEndpoints.cs @@ -0,0 +1,66 @@ +using System.Globalization; +using System.Reflection; +using Titano.Core.Localization; +using Titano.Protocol; +using Titano.Server.Configuration; + +namespace Titano.Server.Api; + +/// /health, /api/v1/server/info and /api/v1/i18n/{culture}. +public static class SystemEndpoints +{ + private static readonly string[] AdminAreas = ["Common", "Admin"]; + + public static string Version { get; } = + typeof(SystemEndpoints).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; + + public static void Map(WebApplication app, ServerOptions options, ServerState state) + { + app.MapGet("/health", () => + { + var checks = new Dictionary(StringComparer.Ordinal) + { + ["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing", + ["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing", + }; + return Results.Json(new HealthStatus("ok", Version, checks), ProtocolJson.Default.HealthStatus); + }); + + var api = app.MapGroup("/api/v1"); + api.MapGet("/server/info", () => Results.Json(new ServerInfo( + options.ServerName, + Version, + ApiVersion.Current, + state.Capabilities, + state.TlsFingerprint, + ["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"], + new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes)), ProtocolJson.Default.ServerInfo)); + + api.MapGet("/i18n/{culture}", (string culture) => + { + CultureInfo ci; + try + { + ci = Languages.BestMatch(CultureInfo.GetCultureInfo(culture)); + } + catch (CultureNotFoundException) + { + ci = CultureInfo.GetCultureInfo("en"); + } + var strings = new Dictionary(StringComparer.Ordinal); + foreach (var area in AdminAreas) + foreach (var (k, v) in Loc.GetArea(area, ci)) strings[k] = v; + strings["$culture"] = ci.Name; + strings["$rtl"] = ci.TextInfo.IsRightToLeft ? "true" : "false"; + return Results.Json(strings, ProtocolJson.Default.DictionaryStringString); + }); + } +} + +/// Process-wide facts computed at startup. +public sealed class ServerState +{ + public string? TlsFingerprint { get; set; } + public List Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"]; + public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow; +} diff --git a/src/Titano.Server/Configuration/ServerOptions.cs b/src/Titano.Server/Configuration/ServerOptions.cs new file mode 100644 index 00000000..d1bcbfa8 --- /dev/null +++ b/src/Titano.Server/Configuration/ServerOptions.cs @@ -0,0 +1,130 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Titano.Server.Configuration; + +public enum TlsMode +{ + /// Self-signed certificate generated at first start (stored under /data/tls). + Auto, + + /// Certificate and key from PEM files. + Pem, + + /// Plain HTTP behind a TLS-terminating reverse proxy. + Proxy, +} + +public enum DatabaseKind +{ + Postgres, + Sqlite, +} + +/// +/// Server configuration (BRIEF §14.9): environment variables override /data/server.json, which overrides defaults. +/// +public sealed class ServerOptions +{ + public string ServerName { get; set; } = "Titano Server"; + public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive"; + public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data"; + public string? AdminUser { get; set; } + public string? AdminPassword { get; set; } + public DatabaseKind Database { get; set; } = OperatingSystem.IsWindows() ? DatabaseKind.Sqlite : DatabaseKind.Postgres; + public string DbHost { get; set; } = "postgres"; + public int DbPort { get; set; } = 5432; + public string DbName { get; set; } = "titano"; + public string DbUser { get; set; } = "titano"; + public string? DbPassword { get; set; } + public string DbSslMode { get; set; } = "prefer"; + public int HttpPort { get; set; } = 8080; + public int HttpsPort { get; set; } = 8443; + public TlsMode TlsMode { get; set; } = TlsMode.Auto; + public string? TlsCert { get; set; } + public string? TlsKey { get; set; } + public string Language { get; set; } = "en"; + public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2); + public bool Discovery { get; set; } = true; + public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024; + public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024; + public int JobHistoryDays { get; set; } = 90; + public int TokenLifetimeDays { get; set; } = 30; + + [JsonIgnore] + public string LogPath => Path.Combine(DataPath, "logs"); + + [JsonIgnore] + public string TlsPath => Path.Combine(DataPath, "tls"); + + [JsonIgnore] + public string UploadsPath => Path.Combine(DataPath, "uploads"); + + /// Loads {DataPath}/server.json (if present) then applies TITANO_* environment variables. + public static ServerOptions Load(IReadOnlyDictionary? environment = null) + { + var env = environment ?? ReadEnvironment(); + string? Env(string name) => env.TryGetValue(name, out var v) && !string.IsNullOrWhiteSpace(v) ? v : null; + + var dataPath = Env("TITANO_DATA_PATH") ?? new ServerOptions().DataPath; + var options = new ServerOptions(); + var file = Path.Combine(dataPath, "server.json"); + if (File.Exists(file)) + { + try + { + options = JsonSerializer.Deserialize(File.ReadAllText(file), ServerOptionsJson.Default.ServerOptions) ?? options; + } + catch (JsonException ex) + { + throw new InvalidOperationException($"{file} is not valid JSON: {ex.Message}", ex); + } + } + options.DataPath = dataPath; + + options.ServerName = Env("TITANO_SERVER_NAME") ?? options.ServerName; + options.ArchivePath = Env("TITANO_ARCHIVE_PATH") ?? options.ArchivePath; + options.AdminUser = Env("TITANO_ADMIN_USER") ?? options.AdminUser; + options.AdminPassword = Env("TITANO_ADMIN_PASSWORD") ?? options.AdminPassword; + if (Env("TITANO_DB") is { } db) options.Database = Enum.Parse(db, ignoreCase: true); + options.DbHost = Env("TITANO_DB_HOST") ?? options.DbHost; + if (Env("TITANO_DB_PORT") is { } port) options.DbPort = int.Parse(port, System.Globalization.CultureInfo.InvariantCulture); + options.DbName = Env("TITANO_DB_NAME") ?? options.DbName; + options.DbUser = Env("TITANO_DB_USER") ?? options.DbUser; + options.DbPassword = Env("TITANO_DB_PASSWORD") ?? options.DbPassword; + options.DbSslMode = Env("TITANO_DB_SSLMODE") ?? options.DbSslMode; + if (Env("TITANO_HTTP_PORT") is { } http) options.HttpPort = int.Parse(http, System.Globalization.CultureInfo.InvariantCulture); + if (Env("TITANO_HTTPS_PORT") is { } https) options.HttpsPort = int.Parse(https, System.Globalization.CultureInfo.InvariantCulture); + if (Env("TITANO_TLS_MODE") is { } tls) options.TlsMode = Enum.Parse(tls, ignoreCase: true); + options.TlsCert = Env("TITANO_TLS_CERT") ?? options.TlsCert; + options.TlsKey = Env("TITANO_TLS_KEY") ?? options.TlsKey; + options.Language = Env("TITANO_LANG") ?? options.Language; + if (Env("TITANO_WORKERS") is { } workers) options.Workers = Math.Max(1, int.Parse(workers, System.Globalization.CultureInfo.InvariantCulture)); + if (Env("TITANO_DISCOVERY") is { } discovery) options.Discovery = bool.Parse(discovery); + options.Validate(); + return options; + } + + private static Dictionary ReadEnvironment() + { + // Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins. + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value; + return result; + } + + public void Validate() + { + if (!OperatingSystem.IsWindows() && Database == DatabaseKind.Sqlite) + throw new InvalidOperationException("TITANO_DB=sqlite is supported on Windows only; use postgres (BRIEF §14.9)."); + if (TlsMode == TlsMode.Pem && (string.IsNullOrEmpty(TlsCert) || string.IsNullOrEmpty(TlsKey))) + throw new InvalidOperationException("TITANO_TLS_MODE=pem requires TITANO_TLS_CERT and TITANO_TLS_KEY."); + // Port 0 asks the OS for a free port (used by the in-process test host). + if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535) + throw new InvalidOperationException("Ports must be between 0 and 65535."); + } +} + +[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)] +[JsonSerializable(typeof(ServerOptions))] +internal sealed partial class ServerOptionsJson : JsonSerializerContext; diff --git a/src/Titano.Server/Hosting/CertificateStore.cs b/src/Titano.Server/Hosting/CertificateStore.cs new file mode 100644 index 00000000..bfcf9c24 --- /dev/null +++ b/src/Titano.Server/Hosting/CertificateStore.cs @@ -0,0 +1,79 @@ +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// +/// TLS certificate for Kestrel (BRIEF §14.2): self-signed ECDSA P-256 generated once and kept in /data/tls +/// (mode auto), loaded from PEM files (mode pem), or none (mode proxy). +/// +public static class CertificateStore +{ + public static X509Certificate2? Load(ServerOptions options, ILogger logger) + { + switch (options.TlsMode) + { + case TlsMode.Proxy: + return null; + case TlsMode.Pem: + { + var pem = X509Certificate2.CreateFromPemFile(options.TlsCert!, options.TlsKey); + return Exportable(pem); + } + default: + { + Directory.CreateDirectory(options.TlsPath); + var path = Path.Combine(options.TlsPath, "server.pfx"); + if (File.Exists(path)) + { + var existing = X509CertificateLoader.LoadPkcs12FromFile(path, password: null, X509KeyStorageFlags.Exportable); + if (existing.NotAfter > DateTime.UtcNow.AddDays(30)) return existing; + logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter); + } + var created = CreateSelfSigned(options.ServerName); + File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12)); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created)); + return created; + } + } + } + + /// SHA-256 fingerprint as colon-separated upper-case hex, as shown to users for trust-on-first-use. + public static string Fingerprint(X509Certificate2 certificate) => + string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture))); + + public static X509Certificate2 CreateSelfSigned(string serverName) + { + using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + var request = new CertificateRequest(new X500DistinguishedName($"CN={Sanitize(serverName)}, O=Titano"), key, HashAlgorithmName.SHA256); + var san = new SubjectAlternativeNameBuilder(); + san.AddDnsName("localhost"); + try + { + var host = Dns.GetHostName(); + san.AddDnsName(host); + foreach (var address in Dns.GetHostAddresses(host).Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6)) + san.AddIpAddress(address); + } + catch (SocketException) + { + // Without name resolution the certificate still covers localhost. + } + san.AddIpAddress(IPAddress.Loopback); + request.CertificateExtensions.Add(san.Build()); + request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true)); + request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false)); + using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5)); + return Exportable(certificate); + } + + private static X509Certificate2 Exportable(X509Certificate2 certificate) => + X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12), password: null, X509KeyStorageFlags.Exportable); + + private static string Sanitize(string name) => new(name.Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '.').Take(60).ToArray()); +} diff --git a/src/Titano.Server/Hosting/EmbeddedStaticFiles.cs b/src/Titano.Server/Hosting/EmbeddedStaticFiles.cs new file mode 100644 index 00000000..638aa087 --- /dev/null +++ b/src/Titano.Server/Hosting/EmbeddedStaticFiles.cs @@ -0,0 +1,70 @@ +using System.Collections.Frozen; +using System.Reflection; +using System.Security.Cryptography; + +namespace Titano.Server.Hosting; + +/// +/// Serves the admin panel from embedded resources named admin/… (no build step, single-file friendly), +/// with strong ETags, conditional GET and SPA fallback to index.html. +/// +public sealed class EmbeddedStaticFiles +{ + private static readonly FrozenDictionary ContentTypes = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + [".html"] = "text/html; charset=utf-8", + [".js"] = "text/javascript; charset=utf-8", + [".mjs"] = "text/javascript; charset=utf-8", + [".css"] = "text/css; charset=utf-8", + [".svg"] = "image/svg+xml", + [".png"] = "image/png", + [".json"] = "application/json; charset=utf-8", + [".ico"] = "image/x-icon", + [".woff2"] = "font/woff2", + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + + private readonly FrozenDictionary _files; + + public EmbeddedStaticFiles(Assembly assembly, string prefix) + { + var files = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var name in assembly.GetManifestResourceNames().Where(n => n.StartsWith(prefix, StringComparison.Ordinal))) + { + using var stream = assembly.GetManifestResourceStream(name)!; + using var ms = new MemoryStream(); + stream.CopyTo(ms); + var bytes = ms.ToArray(); + var path = name[prefix.Length..].Replace('\\', '/'); + var etag = "\"" + Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12)) + "\""; + var type = ContentTypes.TryGetValue(Path.GetExtension(path), out var t) ? t : "application/octet-stream"; + files[path] = (bytes, etag, type); + } + _files = files.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + } + + public int Count => _files.Count; + + public async Task TryServeAsync(HttpContext context, string relativePath) + { + var path = relativePath.TrimStart('/'); + if (path.Length == 0) path = "index.html"; + if (!_files.TryGetValue(path, out var file)) + { + // Client-side routes (no extension) fall back to the shell. + if (Path.HasExtension(path) || !_files.TryGetValue("index.html", out file)) return false; + } + var response = context.Response; + response.Headers.ETag = file.ETag; + response.Headers.CacheControl = path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ? "no-cache" : "public, max-age=3600"; + response.Headers.XContentTypeOptions = "nosniff"; + if (context.Request.Headers.IfNoneMatch == file.ETag) + { + response.StatusCode = StatusCodes.Status304NotModified; + return true; + } + response.ContentType = file.ContentType; + response.ContentLength = file.Content.Length; + if (!HttpMethods.IsHead(context.Request.Method)) await response.Body.WriteAsync(file.Content, context.RequestAborted); + return true; + } +} diff --git a/src/Titano.Server/Hosting/FileLoggerProvider.cs b/src/Titano.Server/Hosting/FileLoggerProvider.cs new file mode 100644 index 00000000..7052813b --- /dev/null +++ b/src/Titano.Server/Hosting/FileLoggerProvider.cs @@ -0,0 +1,54 @@ +using Titano.Core.Diagnostics; +using CoreLogLevel = Titano.Core.Diagnostics.LogLevel; +using MsLogLevel = Microsoft.Extensions.Logging.LogLevel; + +namespace Titano.Server.Hosting; + +/// In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs). +public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider +{ + public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName); + + public void Dispose() => sink.Dispose(); + + private sealed class FileLogger(FileLogSink sink, string category) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information; + + public void Log(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (!IsEnabled(logLevel)) return; + var level = logLevel switch + { + MsLogLevel.Trace => CoreLogLevel.Trace, + MsLogLevel.Debug => CoreLogLevel.Debug, + MsLogLevel.Information => CoreLogLevel.Info, + MsLogLevel.Warning => CoreLogLevel.Warning, + _ => CoreLogLevel.Error, + }; + sink.Write(level, category, formatter(state, exception), exception); + } + } +} + +/// Bridges engine logging (Titano.Core.Diagnostics.Log) into ASP.NET Core logging. +public sealed class LoggerSink(ILoggerFactory factory) : ILogSink +{ + public void Write(CoreLogLevel level, string category, string message, Exception? exception) + { + var logger = factory.CreateLogger("Titano." + category); + var ms = level switch + { + CoreLogLevel.Trace => MsLogLevel.Trace, + CoreLogLevel.Debug => MsLogLevel.Debug, + CoreLogLevel.Info => MsLogLevel.Information, + CoreLogLevel.Warning => MsLogLevel.Warning, + _ => MsLogLevel.Error, + }; +#pragma warning disable CA2254 // Engine messages are preformatted. + logger.Log(ms, exception, message); +#pragma warning restore CA2254 + } +} diff --git a/src/Titano.Server/Hosting/HealthProbe.cs b/src/Titano.Server/Hosting/HealthProbe.cs new file mode 100644 index 00000000..336afbaf --- /dev/null +++ b/src/Titano.Server/Hosting/HealthProbe.cs @@ -0,0 +1,26 @@ +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// +/// Titano.Server --healthcheck: probes the local /health endpoint and exits 0/1, so the container +/// HEALTHCHECK needs no curl/wget in the image. +/// +public static class HealthProbe +{ + public static async Task RunAsync() + { + try + { + var port = ServerOptions.Load().HttpPort; + using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }; + using var response = await http.GetAsync(new Uri($"http://127.0.0.1:{port}/health")).ConfigureAwait(false); + return response.IsSuccessStatusCode ? 0 : 1; + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException) + { + await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false); + return 1; + } + } +} diff --git a/src/Titano.Server/Hosting/ServerHost.cs b/src/Titano.Server/Hosting/ServerHost.cs new file mode 100644 index 00000000..592a15d7 --- /dev/null +++ b/src/Titano.Server/Hosting/ServerHost.cs @@ -0,0 +1,98 @@ +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Titano.Core.Diagnostics; +using Titano.Protocol; +using Titano.Server.Api; +using Titano.Server.Configuration; + +namespace Titano.Server.Hosting; + +/// Builds the Titano Server web application from (used by Program and tests). +public static class ServerHost +{ + public static WebApplication Build(ServerOptions options, string[] args) + { + Directory.CreateDirectory(options.DataPath); + Directory.CreateDirectory(options.LogPath); + + var builder = WebApplication.CreateSlimBuilder(args); + builder.Logging.ClearProviders(); + builder.Logging.AddSimpleConsole(c => c.SingleLine = true); + builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server"))); + builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning); + builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", Microsoft.Extensions.Logging.LogLevel.Information); + + using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true)); + var certificate = CertificateStore.Load(options, bootLoggerFactory.CreateLogger("Titano.Server")); + var state = new ServerState { TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate) }; + + builder.WebHost.ConfigureKestrel(k => + { + k.AddServerHeader = false; + k.Limits.MaxRequestBodySize = options.ChunkSizeBytes + 64 * 1024; + k.ListenAnyIP(options.HttpPort); + if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l => + { + l.Protocols = HttpProtocols.Http1AndHttp2; + l.UseHttps(certificate); + }); + }); + builder.Services.AddSingleton(options); + builder.Services.AddSingleton(state); + builder.Services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default)); + if (options.TlsMode == TlsMode.Proxy) + { + builder.Services.Configure(f => + { + f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost; + f.KnownIPNetworks.Clear(); + f.KnownProxies.Clear(); + }); + } + + var app = builder.Build(); + Log.SetSink(new LoggerSink(app.Services.GetRequiredService())); + var logger = app.Logger; + logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}", + SystemEndpoints.Version, options.ArchivePath, options.DataPath, options.TlsMode, + state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint); + + if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders(); + + app.Use(async (context, next) => + { + context.Response.Headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture); + context.Response.Headers.XContentTypeOptions = "nosniff"; + context.Response.Headers["Referrer-Policy"] = "no-referrer"; + try + { + await next(context); + } + catch (Exception ex) when (!context.Response.HasStarted && ex is not OperationCanceledException) + { + logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path); + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + await context.Response.WriteAsJsonAsync(new ApiError("internal", "Unexpected server error."), ProtocolJson.Default.ApiError); + } + }); + + var admin = new EmbeddedStaticFiles(typeof(ServerHost).Assembly, "admin/"); + app.MapGet("/", () => Results.Redirect("/admin/")); + app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) => + { + // Relative asset URLs need the trailing slash. + if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path)) + { + context.Response.Redirect("/admin/"); + return; + } + if (!await admin.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound; + }); + + SystemEndpoints.Map(app, options, state); + + app.MapFallback("/api/{**path}", () => Results.Json(new ApiError("not_found", "No such endpoint."), ProtocolJson.Default.ApiError, statusCode: 404)); + app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("Titano Server stopping")); + return app; + } +} diff --git a/src/Titano.Server/Program.cs b/src/Titano.Server/Program.cs index 14d0787d..9bfebd2c 100644 --- a/src/Titano.Server/Program.cs +++ b/src/Titano.Server/Program.cs @@ -1,4 +1,11 @@ -var builder = WebApplication.CreateBuilder(args); -var app = builder.Build(); -app.MapGet("/health", () => Results.Ok(new { status = "ok" })); -app.Run(); +using Titano.Server.Configuration; +using Titano.Server.Hosting; + +if (args.Contains("--healthcheck")) return await HealthProbe.RunAsync(); + +var app = ServerHost.Build(ServerOptions.Load(), args); +await app.RunAsync(); +return 0; + +/// Entry point type, visible to the in-process test host. +public partial class Program; diff --git a/src/Titano.Tools/Commands/ChangelogCommand.cs b/src/Titano.Tools/Commands/ChangelogCommand.cs new file mode 100644 index 00000000..6e9731bc --- /dev/null +++ b/src/Titano.Tools/Commands/ChangelogCommand.cs @@ -0,0 +1,90 @@ +using System.Text; +using System.Text.RegularExpressions; + +namespace Titano.Tools.Commands; + +/// +/// Builds release notes from Conventional Commits. Reads git log --format=%h%x09%s lines from stdin +/// (or --in file) and writes Markdown grouped by type. +/// +internal sealed partial class ChangelogCommand : ICommand +{ + private static readonly (string Type, string Heading)[] Sections = + [ + ("feat", "Added"), + ("fix", "Fixed"), + ("perf", "Performance"), + ("security", "Security"), + ("i18n", "Localization"), + ("docs", "Documentation"), + ]; + + public string Name => "changelog"; + public string Summary => "Release notes from Conventional Commits on stdin (--title, --out file)"; + + public async Task RunAsync(string[] args) + { + var a = new Args(args); + IReadOnlyList input = a.Get("in") is { } file ? await File.ReadAllLinesAsync(file) : ReadStdin(); + var markdown = Render(input, a.Get("title")); + if (a.Get("out") is { } outFile) + { + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outFile))!); + await File.WriteAllTextAsync(outFile, markdown, new UTF8Encoding(false)); + } + else + { + Console.Write(markdown); + } + return 0; + } + + internal static string Render(IEnumerable lines, string? title) + { + var groups = new Dictionary>(StringComparer.Ordinal); + var breaking = new List(); + foreach (var line in lines) + { + var tab = line.IndexOf('\t'); + var hash = tab > 0 ? line[..tab] : string.Empty; + var subject = tab > 0 ? line[(tab + 1)..] : line; + var m = Conventional().Match(subject); + if (!m.Success) continue; + var type = m.Groups["type"].Value.ToLowerInvariant(); + var scope = m.Groups["scope"].Success ? $"**{m.Groups["scope"].Value}**: " : string.Empty; + var entry = $"- {scope}{m.Groups["desc"].Value.Trim()}{(hash.Length > 0 ? $" ({hash})" : string.Empty)}"; + if (m.Groups["bang"].Success) breaking.Add(entry); + if (!groups.TryGetValue(type, out var list)) groups[type] = list = []; + list.Add(entry); + } + + var sb = new StringBuilder(); + if (title is not null) sb.Append("# ").AppendLine(title).AppendLine(); + if (breaking.Count > 0) + { + sb.AppendLine("### Breaking changes"); + foreach (var e in breaking) sb.AppendLine(e); + sb.AppendLine(); + } + foreach (var (type, heading) in Sections) + { + if (!groups.TryGetValue(type, out var entries)) continue; + sb.Append("### ").AppendLine(heading); + foreach (var e in entries) sb.AppendLine(e); + sb.AppendLine(); + } + if (sb.Length == 0) sb.AppendLine("Maintenance release."); + return sb.ToString(); + } + + private static List ReadStdin() + { + var lines = new List(); + if (!Console.IsInputRedirected) return lines; + while (Console.In.ReadLine() is { } line) lines.Add(line); + return lines; + } + + [GeneratedRegex(@"^(?[a-zA-Z]+)(?:\((?[^)]+)\))?(?!)?:\s*(?.+)$")] + private static partial Regex Conventional(); +} diff --git a/src/Titano.Tools/Commands/I18nCommand.cs b/src/Titano.Tools/Commands/I18nCommand.cs index 2c835d93..fa657663 100644 --- a/src/Titano.Tools/Commands/I18nCommand.cs +++ b/src/Titano.Tools/Commands/I18nCommand.cs @@ -83,6 +83,8 @@ internal sealed partial class I18nCommand : ICommand foreach (var (file, key) in UsedKeys(root)) { if (en.ContainsKey(key)) continue; + // Prefix lookups such as L("Settings.Page." + page) are satisfied by any key under the prefix. + if (key.EndsWith('.') && en.Keys.Any(k => k.StartsWith(key, StringComparison.Ordinal))) continue; // Plural lookups reference the stem; any suffix satisfies them. if (en.Keys.Any(k => k.StartsWith(key + ".", StringComparison.Ordinal) && PluralSuffix().IsMatch(k[(key.Length + 1)..]))) continue; errors.Add($"{Path.GetRelativePath(root, file)}: unknown key {key}"); diff --git a/src/Titano.Tools/Program.cs b/src/Titano.Tools/Program.cs index 5d569615..d5575d16 100644 --- a/src/Titano.Tools/Program.cs +++ b/src/Titano.Tools/Program.cs @@ -7,6 +7,7 @@ var commands = new ICommand[] new I18nCommand(), new XamlLintCommand(), new PackageGuardCommand(), + new ChangelogCommand(), }; if (args.Length == 0 || args[0] is "-h" or "--help" or "help") diff --git a/src/Titano.Ui/Controls/AutoSlider.cs b/src/Titano.Ui/Controls/AutoSlider.cs new file mode 100644 index 00000000..cc2a1bb1 --- /dev/null +++ b/src/Titano.Ui/Controls/AutoSlider.cs @@ -0,0 +1,142 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; + +namespace Titano.Ui.Controls; + +/// +/// Advisor-aware slider (BRIEF §10.4, DESIGN §4): in Auto the track is accent with an "Auto · value" pill whose +/// tooltip carries the advisor's reason; touching the slider switches to manual (sun track, value shown, reset +/// button returns to Auto). When not applicable the value reads "n/a" with the reason in the tooltip. +/// +[TemplatePart(Name = PartSlider, Type = typeof(Slider))] +public class AutoSlider : Control +{ + public const string PartSlider = "PART_Slider"; + + public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(nameof(Header), typeof(string), typeof(AutoSlider)); + public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(double), typeof(AutoSlider), + new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged)); + public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(nameof(Minimum), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.0)); + public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(nameof(Maximum), typeof(double), typeof(AutoSlider), new PropertyMetadata(1.0)); + public static readonly DependencyProperty SmallChangeProperty = DependencyProperty.Register(nameof(SmallChange), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.01)); + public static readonly DependencyProperty IsSnapToTickEnabledProperty = DependencyProperty.Register(nameof(IsSnapToTickEnabled), typeof(bool), typeof(AutoSlider), new PropertyMetadata(false)); + public static readonly DependencyProperty TickFrequencyProperty = DependencyProperty.Register(nameof(TickFrequency), typeof(double), typeof(AutoSlider), new PropertyMetadata(1.0)); + public static readonly DependencyProperty IsAutoProperty = DependencyProperty.Register(nameof(IsAuto), typeof(bool), typeof(AutoSlider), + new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + public static readonly DependencyProperty AutoValueProperty = DependencyProperty.Register(nameof(AutoValue), typeof(double), typeof(AutoSlider), new PropertyMetadata(0.0, OnAutoValueChanged)); + public static readonly DependencyProperty AutoReasonProperty = DependencyProperty.Register(nameof(AutoReason), typeof(string), typeof(AutoSlider)); + public static readonly DependencyProperty IsApplicableProperty = DependencyProperty.Register(nameof(IsApplicable), typeof(bool), typeof(AutoSlider), new PropertyMetadata(true)); + public static readonly DependencyProperty NotApplicableReasonProperty = DependencyProperty.Register(nameof(NotApplicableReason), typeof(string), typeof(AutoSlider)); + public static readonly DependencyProperty ValueFormatProperty = DependencyProperty.Register(nameof(ValueFormat), typeof(string), typeof(AutoSlider), new PropertyMetadata("0.##", OnFormatChanged)); + public static readonly DependencyProperty DisplayValueProperty = DependencyProperty.Register(nameof(DisplayValue), typeof(string), typeof(AutoSlider), new PropertyMetadata(string.Empty)); + public static readonly DependencyProperty AutoTextProperty = DependencyProperty.Register(nameof(AutoText), typeof(string), typeof(AutoSlider), new PropertyMetadata(string.Empty)); + public static readonly DependencyProperty SliderToolTipProperty = DependencyProperty.Register(nameof(SliderToolTip), typeof(object), typeof(AutoSlider)); + + public static readonly RoutedCommand ResetCommand = new(nameof(ResetCommand), typeof(AutoSlider)); + + private Slider? _slider; + private bool _syncing; + + static AutoSlider() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoSlider), new FrameworkPropertyMetadata(typeof(AutoSlider))); + } + + public AutoSlider() + { + CommandBindings.Add(new CommandBinding(ResetCommand, (_, _) => ResetToAuto())); + UpdateTexts(); + } + + public string? Header { get => (string?)GetValue(HeaderProperty); set => SetValue(HeaderProperty, value); } + public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); } + public double Minimum { get => (double)GetValue(MinimumProperty); set => SetValue(MinimumProperty, value); } + public double Maximum { get => (double)GetValue(MaximumProperty); set => SetValue(MaximumProperty, value); } + public double SmallChange { get => (double)GetValue(SmallChangeProperty); set => SetValue(SmallChangeProperty, value); } + public bool IsSnapToTickEnabled { get => (bool)GetValue(IsSnapToTickEnabledProperty); set => SetValue(IsSnapToTickEnabledProperty, value); } + public double TickFrequency { get => (double)GetValue(TickFrequencyProperty); set => SetValue(TickFrequencyProperty, value); } + public bool IsAuto { get => (bool)GetValue(IsAutoProperty); set => SetValue(IsAutoProperty, value); } + public double AutoValue { get => (double)GetValue(AutoValueProperty); set => SetValue(AutoValueProperty, value); } + public string? AutoReason { get => (string?)GetValue(AutoReasonProperty); set => SetValue(AutoReasonProperty, value); } + public bool IsApplicable { get => (bool)GetValue(IsApplicableProperty); set => SetValue(IsApplicableProperty, value); } + public string? NotApplicableReason { get => (string?)GetValue(NotApplicableReasonProperty); set => SetValue(NotApplicableReasonProperty, value); } + public string ValueFormat { get => (string)GetValue(ValueFormatProperty); set => SetValue(ValueFormatProperty, value); } + + /// Formatted current value (read by the template). + public string DisplayValue { get => (string)GetValue(DisplayValueProperty); private set => SetValue(DisplayValueProperty, value); } + + /// "Auto · 41" pill text; the "Auto" word comes from the catalog (Common.Auto). + public string AutoText { get => (string)GetValue(AutoTextProperty); private set => SetValue(AutoTextProperty, value); } + + /// Tooltip of the slider track: what moving it does. + public object? SliderToolTip { get => GetValue(SliderToolTipProperty); set => SetValue(SliderToolTipProperty, value); } + + public override void OnApplyTemplate() + { + if (_slider is not null) + { + _slider.ValueChanged -= OnSliderValueChanged; + _slider.PreviewMouseDown -= OnSliderTouched; + _slider.PreviewKeyDown -= OnSliderTouched; + } + base.OnApplyTemplate(); + _slider = GetTemplateChild(PartSlider) as Slider; + if (_slider is not null) + { + _slider.Value = IsAuto ? AutoValue : Value; + _slider.ValueChanged += OnSliderValueChanged; + _slider.PreviewMouseDown += OnSliderTouched; + _slider.PreviewKeyDown += OnSliderTouched; + } + } + + /// Returns the control to the advisor's value. + public void ResetToAuto() + { + IsAuto = true; + Value = AutoValue; + UpdateTexts(); + } + + private void OnSliderTouched(object sender, RoutedEventArgs e) + { + if (e is KeyEventArgs k && k.Key is not (Key.Left or Key.Right or Key.Up or Key.Down or Key.PageUp or Key.PageDown or Key.Home or Key.End)) return; + IsAuto = false; + } + + private void OnSliderValueChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (_syncing) return; + Value = e.NewValue; + } + + private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var s = (AutoSlider)d; + if (s._slider is not null && !s._syncing) + { + s._syncing = true; + s._slider.Value = (double)e.NewValue; + s._syncing = false; + } + s.UpdateTexts(); + } + + private static void OnAutoValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var s = (AutoSlider)d; + if (s.IsAuto) s.Value = (double)e.NewValue; + s.UpdateTexts(); + } + + private static void OnFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((AutoSlider)d).UpdateTexts(); + + private void UpdateTexts() + { + var culture = Core.Localization.Loc.Culture; + DisplayValue = Value.ToString(ValueFormat, culture); + AutoText = Core.Localization.Loc.L("Common.Auto") + " · " + AutoValue.ToString(ValueFormat, culture); + } +} diff --git a/src/Titano.Ui/Controls/BrandMarkIcon.cs b/src/Titano.Ui/Controls/BrandMarkIcon.cs new file mode 100644 index 00000000..1a95125c --- /dev/null +++ b/src/Titano.Ui/Controls/BrandMarkIcon.cs @@ -0,0 +1,61 @@ +using System.Windows; +using System.Windows.Media; +using Titano.Core.Branding; + +namespace Titano.Ui.Controls; + +/// The Titano mark drawn as vectors from geometry (plate optional). +public sealed class BrandMarkIcon : FrameworkElement +{ + public static readonly DependencyProperty ShowPlateProperty = DependencyProperty.Register( + nameof(ShowPlate), typeof(bool), typeof(BrandMarkIcon), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender)); + + private static readonly Brush Accent = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Accent.R, BrandMark.Accent.G, BrandMark.Accent.B))); + private static readonly Brush Sun = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Sun.R, BrandMark.Sun.G, BrandMark.Sun.B))); + private static readonly Brush Plate = Frozen(new SolidColorBrush(Color.FromRgb(BrandMark.Plate.R, BrandMark.Plate.G, BrandMark.Plate.B))); + + public bool ShowPlate + { + get => (bool)GetValue(ShowPlateProperty); + set => SetValue(ShowPlateProperty, value); + } + + protected override Size MeasureOverride(Size availableSize) + { + var s = double.IsInfinity(availableSize.Width) ? 16 : Math.Min(availableSize.Width, double.IsInfinity(availableSize.Height) ? availableSize.Width : availableSize.Height); + return new Size(s, s); + } + + protected override void OnRender(DrawingContext dc) + { + var size = Math.Min(ActualWidth, ActualHeight); + if (size <= 0) return; + var scale = size / BrandMark.Canvas; + dc.PushTransform(new ScaleTransform(scale, scale)); + if (ShowPlate) + dc.DrawRoundedRectangle(Plate, null, new Rect(0, 0, BrandMark.Canvas, BrandMark.Canvas), BrandMark.PlateRadius, BrandMark.PlateRadius); + // Below ~24 px keep the stroke at least ~1.3 device pixels. + var stroke = Math.Max(BrandMark.StrokeWidth, 1.3 / scale); + for (var i = 0; i < BrandMark.TickCount; i++) + { + var (a0, a1) = BrandMark.TickAngles(i); + var (x0, y0) = BrandMark.Polar(a0); + var (x1, y1) = BrandMark.Polar(a1); + var figure = new PathFigure { StartPoint = new Point(x0, y0) }; + figure.Segments.Add(new ArcSegment(new Point(x1, y1), new Size(BrandMark.RingRadius, BrandMark.RingRadius), 0, false, SweepDirection.Clockwise, true)); + var geometry = new PathGeometry([figure]); + var pen = new Pen(Accent, stroke) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round }; + dc.PushOpacity(BrandMark.TickOpacity(i)); + dc.DrawGeometry(null, pen, geometry); + dc.Pop(); + } + dc.DrawEllipse(Sun, null, new Point(BrandMark.SunX, BrandMark.SunY), BrandMark.SunRadius, BrandMark.SunRadius); + dc.Pop(); + } + + private static Brush Frozen(SolidColorBrush b) + { + b.Freeze(); + return b; + } +} diff --git a/src/Titano.Ui/Controls/Chip.cs b/src/Titano.Ui/Controls/Chip.cs new file mode 100644 index 00000000..78ba79e5 --- /dev/null +++ b/src/Titano.Ui/Controls/Chip.cs @@ -0,0 +1,29 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace Titano.Ui.Controls; + +/// 24-px pill (DESIGN §4). Selected or recommended chips use the accent border and text. +public class Chip : ContentControl +{ + public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register(nameof(IsSelected), typeof(bool), typeof(Chip)); + public static readonly DependencyProperty IsRecommendedProperty = DependencyProperty.Register(nameof(IsRecommended), typeof(bool), typeof(Chip)); + public static readonly DependencyProperty RemoveCommandProperty = DependencyProperty.Register(nameof(RemoveCommand), typeof(ICommand), typeof(Chip)); + public static readonly DependencyProperty RemoveCommandParameterProperty = DependencyProperty.Register(nameof(RemoveCommandParameter), typeof(object), typeof(Chip)); + public static readonly DependencyProperty RemoveToolTipProperty = DependencyProperty.Register(nameof(RemoveToolTip), typeof(object), typeof(Chip)); + + static Chip() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(Chip), new FrameworkPropertyMetadata(typeof(Chip))); + } + + public bool IsSelected { get => (bool)GetValue(IsSelectedProperty); set => SetValue(IsSelectedProperty, value); } + public bool IsRecommended { get => (bool)GetValue(IsRecommendedProperty); set => SetValue(IsRecommendedProperty, value); } + + /// When set, a small ✕ button removes the chip (filters, tags). + public ICommand? RemoveCommand { get => (ICommand?)GetValue(RemoveCommandProperty); set => SetValue(RemoveCommandProperty, value); } + + public object? RemoveCommandParameter { get => GetValue(RemoveCommandParameterProperty); set => SetValue(RemoveCommandParameterProperty, value); } + public object? RemoveToolTip { get => GetValue(RemoveToolTipProperty); set => SetValue(RemoveToolTipProperty, value); } +} diff --git a/src/Titano.Ui/Controls/ControlState.cs b/src/Titano.Ui/Controls/ControlState.cs new file mode 100644 index 00000000..d3e1d837 --- /dev/null +++ b/src/Titano.Ui/Controls/ControlState.cs @@ -0,0 +1,28 @@ +using System.Windows; +using System.Windows.Media; + +namespace Titano.Ui.Controls; + +/// Attached brushes that let one control template serve every button variant (DESIGN §4 states). +public static class ControlState +{ + public static readonly DependencyProperty HoverBackgroundProperty = DependencyProperty.RegisterAttached("HoverBackground", typeof(Brush), typeof(ControlState)); + public static readonly DependencyProperty PressedBackgroundProperty = DependencyProperty.RegisterAttached("PressedBackground", typeof(Brush), typeof(ControlState)); + public static readonly DependencyProperty HoverBorderBrushProperty = DependencyProperty.RegisterAttached("HoverBorderBrush", typeof(Brush), typeof(ControlState)); + public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.RegisterAttached("CornerRadius", typeof(CornerRadius), typeof(ControlState), new FrameworkPropertyMetadata(new CornerRadius(6))); + public static readonly DependencyProperty AccentProperty = DependencyProperty.RegisterAttached("Accent", typeof(Brush), typeof(ControlState), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits)); + + public static Brush? GetHoverBackground(DependencyObject d) => (Brush?)d.GetValue(HoverBackgroundProperty); + public static void SetHoverBackground(DependencyObject d, Brush? v) => d.SetValue(HoverBackgroundProperty, v); + public static Brush? GetPressedBackground(DependencyObject d) => (Brush?)d.GetValue(PressedBackgroundProperty); + public static void SetPressedBackground(DependencyObject d, Brush? v) => d.SetValue(PressedBackgroundProperty, v); + public static Brush? GetHoverBorderBrush(DependencyObject d) => (Brush?)d.GetValue(HoverBorderBrushProperty); + public static void SetHoverBorderBrush(DependencyObject d, Brush? v) => d.SetValue(HoverBorderBrushProperty, v); + public static CornerRadius GetCornerRadius(DependencyObject d) => (CornerRadius)d.GetValue(CornerRadiusProperty); + public static void SetCornerRadius(DependencyObject d, CornerRadius v) => d.SetValue(CornerRadiusProperty, v); + + /// Fill colour of slider tracks and progress (accent = Auto, sun = manual). + public static Brush? GetAccent(DependencyObject d) => (Brush?)d.GetValue(AccentProperty); + + public static void SetAccent(DependencyObject d, Brush? v) => d.SetValue(AccentProperty, v); +} diff --git a/src/Titano.Ui/Controls/Converters.cs b/src/Titano.Ui/Controls/Converters.cs new file mode 100644 index 00000000..8a5f2ace --- /dev/null +++ b/src/Titano.Ui/Controls/Converters.cs @@ -0,0 +1,44 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace Titano.Ui.Controls; + +/// null → Collapsed, otherwise Visible. +public sealed class NullToCollapsedConverter : IValueConverter +{ + public static NullToCollapsedConverter Instance { get; } = new(); + + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => + value is null || value is string { Length: 0 } ? Visibility.Collapsed : Visibility.Visible; + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException(); +} + +/// true → Collapsed (inverse of BooleanToVisibilityConverter). +public sealed class InverseBoolToVisibilityConverter : IValueConverter +{ + public static InverseBoolToVisibilityConverter Instance { get; } = new(); + + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => + value is true ? Visibility.Collapsed : Visibility.Visible; + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException(); +} + +/// 0 → Collapsed, any other number → Visible. +public sealed class ZeroToCollapsedConverter : IValueConverter +{ + public static ZeroToCollapsedConverter Instance { get; } = new(); + + public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => + value switch + { + int i => i == 0 ? Visibility.Collapsed : Visibility.Visible, + long l => l == 0 ? Visibility.Collapsed : Visibility.Visible, + double d => d == 0 ? Visibility.Collapsed : Visibility.Visible, + _ => Visibility.Collapsed, + }; + + public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => throw new NotSupportedException(); +} diff --git a/src/Titano.Ui/Controls/EmptyState.cs b/src/Titano.Ui/Controls/EmptyState.cs new file mode 100644 index 00000000..36753796 --- /dev/null +++ b/src/Titano.Ui/Controls/EmptyState.cs @@ -0,0 +1,17 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Titano.Ui.Controls; + +/// Empty state: the mark, one sentence and the action buttons supplied as content (BRIEF §0.2 rule 6). +public class EmptyState : ContentControl +{ + public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(nameof(Message), typeof(string), typeof(EmptyState)); + + static EmptyState() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(EmptyState), new FrameworkPropertyMetadata(typeof(EmptyState))); + } + + public string? Message { get => (string?)GetValue(MessageProperty); set => SetValue(MessageProperty, value); } +} diff --git a/src/Titano.Ui/Controls/Field.cs b/src/Titano.Ui/Controls/Field.cs new file mode 100644 index 00000000..98477d1e --- /dev/null +++ b/src/Titano.Ui/Controls/Field.cs @@ -0,0 +1,32 @@ +using System.Windows; + +namespace Titano.Ui.Controls; + +/// Attached field helpers: placeholder text and an inline leading icon for text inputs. +public static class Field +{ + public static readonly DependencyProperty PlaceholderProperty = DependencyProperty.RegisterAttached( + "Placeholder", typeof(string), typeof(Field), new FrameworkPropertyMetadata(null)); + + public static readonly DependencyProperty GlyphProperty = DependencyProperty.RegisterAttached( + "Glyph", typeof(IconData), typeof(Field), new FrameworkPropertyMetadata(null)); + + public static string? GetPlaceholder(DependencyObject d) => (string?)d.GetValue(PlaceholderProperty); + + public static void SetPlaceholder(DependencyObject d, string? value) => d.SetValue(PlaceholderProperty, value); + + public static IconData? GetGlyph(DependencyObject d) => (IconData?)d.GetValue(GlyphProperty); + + public static void SetGlyph(DependencyObject d, IconData? value) => d.SetValue(GlyphProperty, value); +} + +/// Attached glyph for buttons: renders an before (or instead of) the content. +public static class ButtonIcon +{ + public static readonly DependencyProperty GlyphProperty = DependencyProperty.RegisterAttached( + "Glyph", typeof(IconData), typeof(ButtonIcon), new FrameworkPropertyMetadata(null)); + + public static IconData? GetGlyph(DependencyObject d) => (IconData?)d.GetValue(GlyphProperty); + + public static void SetGlyph(DependencyObject d, IconData? value) => d.SetValue(GlyphProperty, value); +} diff --git a/src/Titano.Ui/Controls/Icon.cs b/src/Titano.Ui/Controls/Icon.cs new file mode 100644 index 00000000..f87b2542 --- /dev/null +++ b/src/Titano.Ui/Controls/Icon.cs @@ -0,0 +1,79 @@ +using System.Windows; +using System.Windows.Documents; +using System.Windows.Media; + +namespace Titano.Ui.Controls; + +/// Renders an on the 16-unit grid, scaled to the element size, in the inherited foreground. +public sealed class Icon : FrameworkElement +{ + public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register( + nameof(Glyph), typeof(IconData), typeof(Icon), + new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty ForegroundProperty = TextElement.ForegroundProperty.AddOwner( + typeof(Icon), new FrameworkPropertyMetadata(Brushes.Gray, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsRender)); + + public static readonly DependencyProperty SizeProperty = DependencyProperty.Register( + nameof(Size), typeof(double), typeof(Icon), + new FrameworkPropertyMetadata(16.0, FrameworkPropertyMetadataOptions.AffectsMeasure)); + + public static readonly DependencyProperty StrokeWidthProperty = DependencyProperty.Register( + nameof(StrokeWidth), typeof(double), typeof(Icon), + new FrameworkPropertyMetadata(1.5, FrameworkPropertyMetadataOptions.AffectsRender)); + + static Icon() + { + SnapsToDevicePixelsProperty.OverrideMetadata(typeof(Icon), new FrameworkPropertyMetadata(true)); + FocusableProperty.OverrideMetadata(typeof(Icon), new FrameworkPropertyMetadata(false)); + } + + public IconData? Glyph + { + get => (IconData?)GetValue(GlyphProperty); + set => SetValue(GlyphProperty, value); + } + + public Brush Foreground + { + get => (Brush)GetValue(ForegroundProperty); + set => SetValue(ForegroundProperty, value); + } + + /// Edge length in device-independent pixels (default 16). + public double Size + { + get => (double)GetValue(SizeProperty); + set => SetValue(SizeProperty, value); + } + + /// Stroke width on the 16-unit grid (default 1.5). + public double StrokeWidth + { + get => (double)GetValue(StrokeWidthProperty); + set => SetValue(StrokeWidthProperty, value); + } + + protected override Size MeasureOverride(Size availableSize) => new(Size, Size); + + protected override void OnRender(DrawingContext dc) + { + var glyph = Glyph; + if (glyph is null) return; + var scale = Size / 16.0; + dc.PushTransform(new ScaleTransform(scale, scale)); + if (glyph.Fill is not null) dc.DrawGeometry(Foreground, null, glyph.Fill); + if (glyph.Stroke is not null) + { + var pen = new Pen(Foreground, StrokeWidth) + { + StartLineCap = PenLineCap.Round, + EndLineCap = PenLineCap.Round, + LineJoin = PenLineJoin.Round, + }; + pen.Freeze(); + dc.DrawGeometry(null, pen, glyph.Stroke); + } + dc.Pop(); + } +} diff --git a/src/Titano.Ui/Controls/IconData.cs b/src/Titano.Ui/Controls/IconData.cs new file mode 100644 index 00000000..9c756621 --- /dev/null +++ b/src/Titano.Ui/Controls/IconData.cs @@ -0,0 +1,30 @@ +using System.Windows.Media; + +namespace Titano.Ui.Controls; + +/// A 16×16 icon: a stroked outline and an optional filled part (DESIGN.md §5). +public sealed class IconData +{ + private Geometry? _stroke; + private Geometry? _fill; + + /// Outline drawn with a 1.5-px round pen in the foreground colour. + public Geometry? Stroke + { + get => _stroke; + set => _stroke = Freeze(value); + } + + /// Solid part filled with the foreground colour. + public Geometry? Fill + { + get => _fill; + set => _fill = Freeze(value); + } + + private static Geometry? Freeze(Geometry? g) + { + if (g is { CanFreeze: true, IsFrozen: false }) g.Freeze(); + return g; + } +} diff --git a/src/Titano.Ui/Controls/JobBar.cs b/src/Titano.Ui/Controls/JobBar.cs new file mode 100644 index 00000000..e0f232a6 --- /dev/null +++ b/src/Titano.Ui/Controls/JobBar.cs @@ -0,0 +1,34 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; + +namespace Titano.Ui.Controls; + +/// 40-px strip under the title bar: current job, progress, time left and a stop button (DESIGN §4). +public class JobBar : Control +{ + public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(JobBar)); + public static readonly DependencyProperty ProgressProperty = DependencyProperty.Register(nameof(Progress), typeof(double), typeof(JobBar), new PropertyMetadata(0.0)); + public static readonly DependencyProperty IsIndeterminateProperty = DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(JobBar)); + public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(nameof(IsActive), typeof(bool), typeof(JobBar)); + public static readonly DependencyProperty StopCommandProperty = DependencyProperty.Register(nameof(StopCommand), typeof(ICommand), typeof(JobBar)); + public static readonly DependencyProperty StopToolTipProperty = DependencyProperty.Register(nameof(StopToolTip), typeof(object), typeof(JobBar)); + + static JobBar() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(JobBar), new FrameworkPropertyMetadata(typeof(JobBar))); + } + + public string? Text { get => (string?)GetValue(TextProperty); set => SetValue(TextProperty, value); } + + /// 0..1. + public double Progress { get => (double)GetValue(ProgressProperty); set => SetValue(ProgressProperty, value); } + + public bool IsIndeterminate { get => (bool)GetValue(IsIndeterminateProperty); set => SetValue(IsIndeterminateProperty, value); } + + /// A job is running: shows the progress fill and the stop button. + public bool IsActive { get => (bool)GetValue(IsActiveProperty); set => SetValue(IsActiveProperty, value); } + + public ICommand? StopCommand { get => (ICommand?)GetValue(StopCommandProperty); set => SetValue(StopCommandProperty, value); } + public object? StopToolTip { get => GetValue(StopToolTipProperty); set => SetValue(StopToolTipProperty, value); } +} diff --git a/src/Titano.Ui/Controls/NavRail.cs b/src/Titano.Ui/Controls/NavRail.cs new file mode 100644 index 00000000..30e69ca1 --- /dev/null +++ b/src/Titano.Ui/Controls/NavRail.cs @@ -0,0 +1,43 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Titano.Ui.Controls; + +/// Attached state of the navigation rail (DESIGN §3: 128 px, collapses to 48 px icons). +public static class NavRail +{ + public static readonly DependencyProperty IsCollapsedProperty = DependencyProperty.RegisterAttached( + "IsCollapsed", typeof(bool), typeof(NavRail), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits)); + + public static bool GetIsCollapsed(DependencyObject d) => (bool)d.GetValue(IsCollapsedProperty); + + public static void SetIsCollapsed(DependencyObject d, bool value) => d.SetValue(IsCollapsedProperty, value); +} + +/// One rail entry: icon, label, optional attention badge; active = card fill + 3-px accent edge. +public class NavRailButton : RadioButton +{ + public static readonly DependencyProperty GlyphProperty = DependencyProperty.Register( + nameof(Glyph), typeof(IconData), typeof(NavRailButton)); + + public static readonly DependencyProperty BadgeProperty = DependencyProperty.Register( + nameof(Badge), typeof(int), typeof(NavRailButton), new PropertyMetadata(0)); + + static NavRailButton() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(NavRailButton), new FrameworkPropertyMetadata(typeof(NavRailButton))); + } + + public IconData? Glyph + { + get => (IconData?)GetValue(GlyphProperty); + set => SetValue(GlyphProperty, value); + } + + /// Count of things needing attention; hidden when 0. + public int Badge + { + get => (int)GetValue(BadgeProperty); + set => SetValue(BadgeProperty, value); + } +} diff --git a/src/Titano.Ui/Controls/StatusGlyph.cs b/src/Titano.Ui/Controls/StatusGlyph.cs new file mode 100644 index 00000000..d5d13bc1 --- /dev/null +++ b/src/Titano.Ui/Controls/StatusGlyph.cs @@ -0,0 +1,42 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Titano.Ui.Controls; + +/// Status vocabulary of DESIGN §4: colour is always paired with a glyph and a word. +public enum StatusKind +{ + Analysed, + NotAnalysed, + Proxies, + NoProxies, + Rendered, + Synced, + Remote, + Analysing, + Warning, + Error, + Running, + Queued, + Done, + Failed, + Paused, + Online, + Offline, +} + +/// Glyph + text in the colour of the status kind. +public class StatusGlyph : Control +{ + public static readonly DependencyProperty KindProperty = DependencyProperty.Register(nameof(Kind), typeof(StatusKind), typeof(StatusGlyph), new PropertyMetadata(StatusKind.Analysed)); + public static readonly DependencyProperty TextProperty = DependencyProperty.Register(nameof(Text), typeof(string), typeof(StatusGlyph)); + + static StatusGlyph() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusGlyph), new FrameworkPropertyMetadata(typeof(StatusGlyph))); + FocusableProperty.OverrideMetadata(typeof(StatusGlyph), new FrameworkPropertyMetadata(false)); + } + + public StatusKind Kind { get => (StatusKind)GetValue(KindProperty); set => SetValue(KindProperty, value); } + public string? Text { get => (string?)GetValue(TextProperty); set => SetValue(TextProperty, value); } +} diff --git a/src/Titano.Ui/Controls/TitanoWindow.cs b/src/Titano.Ui/Controls/TitanoWindow.cs new file mode 100644 index 00000000..aa79b438 --- /dev/null +++ b/src/Titano.Ui/Controls/TitanoWindow.cs @@ -0,0 +1,138 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Shell; +using Titano.Ui.Interop; +using Titano.Ui.Theming; + +namespace Titano.Ui.Controls; + +/// +/// Window with Titano's custom chrome: 34-px title bar in the Chrome colour, brand mark, title, optional +/// title-bar content and drawn caption buttons. The maximise button answers HTMAXBUTTON so Windows 11 +/// snap layouts appear on hover. +/// +[TemplatePart(Name = PartMaximize, Type = typeof(Button))] +public class TitanoWindow : Window +{ + public const string PartMaximize = "PART_Maximize"; + + public static readonly DependencyProperty TitleBarContentProperty = DependencyProperty.Register( + nameof(TitleBarContent), typeof(object), typeof(TitanoWindow)); + + public static readonly DependencyProperty IsDialogProperty = DependencyProperty.Register( + nameof(IsDialog), typeof(bool), typeof(TitanoWindow), new PropertyMetadata(false)); + + public static readonly DependencyProperty IsMaximizeHoveredProperty = DependencyProperty.Register( + nameof(IsMaximizeHovered), typeof(bool), typeof(TitanoWindow), new PropertyMetadata(false)); + + private Button? _maximize; + + static TitanoWindow() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(TitanoWindow), new FrameworkPropertyMetadata(typeof(TitanoWindow))); + } + + public TitanoWindow() + { + WindowChrome.SetWindowChrome(this, new WindowChrome + { + CaptionHeight = 34, + ResizeBorderThickness = new Thickness(6), + GlassFrameThickness = new Thickness(0), + CornerRadius = new CornerRadius(0), + UseAeroCaptionButtons = false, + }); + CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, (_, _) => SystemCommands.CloseWindow(this))); + CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, (_, _) => SystemCommands.MinimizeWindow(this))); + CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, (_, _) => ToggleMaximize())); + CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, (_, _) => ToggleMaximize())); + UseLayoutRounding = true; + TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display); + } + + /// Extra content placed in the title bar between the title and the caption buttons. + public object? TitleBarContent + { + get => GetValue(TitleBarContentProperty); + set => SetValue(TitleBarContentProperty, value); + } + + /// Dialog windows show only the close button. + public bool IsDialog + { + get => (bool)GetValue(IsDialogProperty); + set => SetValue(IsDialogProperty, value); + } + + /// True while the pointer is over the maximise button (non-client, so tracked from WndProc). + public bool IsMaximizeHovered + { + get => (bool)GetValue(IsMaximizeHoveredProperty); + set => SetValue(IsMaximizeHoveredProperty, value); + } + + public override void OnApplyTemplate() + { + base.OnApplyTemplate(); + _maximize = GetTemplateChild(PartMaximize) as Button; + } + + protected override void OnSourceInitialized(EventArgs e) + { + base.OnSourceInitialized(e); + ThemeManager.ApplyChrome(this); + if (PresentationSource.FromVisual(this) is HwndSource source) source.AddHook(WndProc); + } + + private void ToggleMaximize() + { + if (WindowState == WindowState.Maximized) SystemCommands.RestoreWindow(this); + else SystemCommands.MaximizeWindow(this); + } + + private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + switch (msg) + { + case NativeMethods.WM_NCHITTEST when _maximize is { IsVisible: true } && ResizeMode is ResizeMode.CanResize or ResizeMode.CanResizeWithGrip: + if (IsOverMaximize(lParam)) + { + IsMaximizeHovered = true; + handled = true; + return NativeMethods.HTMAXBUTTON; + } + IsMaximizeHovered = false; + break; + case NativeMethods.WM_NCLBUTTONDOWN when wParam == NativeMethods.HTMAXBUTTON: + handled = true; + break; + case NativeMethods.WM_NCLBUTTONUP when wParam == NativeMethods.HTMAXBUTTON: + handled = true; + ToggleMaximize(); + break; + case NativeMethods.WM_NCMOUSELEAVE: + IsMaximizeHovered = false; + break; + } + return IntPtr.Zero; + } + + private bool IsOverMaximize(IntPtr lParam) + { + if (_maximize is null) return false; + var x = unchecked((short)(long)lParam); + var y = unchecked((short)((long)lParam >> 16)); + try + { + var point = _maximize.PointFromScreen(new Point(x, y)); + return point.X >= 0 && point.Y >= 0 && point.X < _maximize.ActualWidth && point.Y < _maximize.ActualHeight; + } + catch (InvalidOperationException) + { + return false; + } + } +} diff --git a/src/Titano.Ui/Controls/Toasts.cs b/src/Titano.Ui/Controls/Toasts.cs new file mode 100644 index 00000000..19f1da3e --- /dev/null +++ b/src/Titano.Ui/Controls/Toasts.cs @@ -0,0 +1,79 @@ +using System.Collections.ObjectModel; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Threading; +using Titano.Ui.Mvvm; + +namespace Titano.Ui.Controls; + +/// One in-window notification (DESIGN §4: 420 px, accent left edge, one action, 8 s, hover pauses). +public sealed class Toast : ObservableObject +{ + public required string Title { get; init; } + public string? Message { get; init; } + public string? ActionText { get; init; } + public ICommand? ActionCommand { get; init; } + public string? ActionToolTip { get; init; } + public TimeSpan Lifetime { get; init; } = TimeSpan.FromSeconds(8); +} + +/// Bottom-right stack of s with auto-dismiss. +public class ToastHost : ItemsControl +{ + private readonly Dictionary _timers = []; + + static ToastHost() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(ToastHost), new FrameworkPropertyMetadata(typeof(ToastHost))); + } + + public ToastHost() + { + ItemsSource = Toasts; + CommandBindings.Add(new CommandBinding(DismissCommand, (_, e) => + { + if (e.Parameter is Toast t) Dismiss(t); + })); + } + + public static RoutedCommand DismissCommand { get; } = new(nameof(DismissCommand), typeof(ToastHost)); + + public ObservableCollection Toasts { get; } = []; + + public void Show(Toast toast) + { + Toasts.Add(toast); + while (Toasts.Count > 3) Dismiss(Toasts[0]); + var timer = new DispatcherTimer { Interval = toast.Lifetime }; + timer.Tick += (_, _) => Dismiss(toast); + _timers[toast] = timer; + timer.Start(); + } + + /// Pauses or resumes the dismissal timer (hover pauses). + public void SetPaused(Toast toast, bool paused) + { + if (!_timers.TryGetValue(toast, out var timer)) return; + if (paused) timer.Stop(); + else timer.Start(); + } + + public void Dismiss(Toast toast) + { + if (_timers.Remove(toast, out var timer)) timer.Stop(); + Toasts.Remove(toast); + } + + protected override void OnPreviewMouseMove(MouseEventArgs e) + { + base.OnPreviewMouseMove(e); + foreach (var t in Toasts.ToList()) SetPaused(t, true); + } + + protected override void OnMouseLeave(MouseEventArgs e) + { + base.OnMouseLeave(e); + foreach (var t in Toasts.ToList()) SetPaused(t, false); + } +} diff --git a/src/Titano.Ui/Icons/Icons.xaml b/src/Titano.Ui/Icons/Icons.xaml new file mode 100644 index 00000000..96d567b8 --- /dev/null +++ b/src/Titano.Ui/Icons/Icons.xaml @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.Ui/Interop/NativeMethods.cs b/src/Titano.Ui/Interop/NativeMethods.cs new file mode 100644 index 00000000..68aea192 --- /dev/null +++ b/src/Titano.Ui/Interop/NativeMethods.cs @@ -0,0 +1,45 @@ +using System.Runtime.InteropServices; + +namespace Titano.Ui.Interop; + +/// The few Win32/DWM calls the shared UI needs (window chrome and theme). +internal static partial class NativeMethods +{ + public const int WM_NCHITTEST = 0x0084; + public const int WM_NCMOUSEMOVE = 0x00A0; + public const int WM_NCLBUTTONDOWN = 0x00A1; + public const int WM_NCLBUTTONUP = 0x00A2; + public const int WM_NCMOUSELEAVE = 0x02A2; + public const int WM_GETMINMAXINFO = 0x0024; + public const int HTMAXBUTTON = 9; + + public const int DWMWA_USE_IMMERSIVE_DARK_MODE_OLD = 19; + public const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20; + public const int DWMWA_WINDOW_CORNER_PREFERENCE = 33; + public const int DWMWA_BORDER_COLOR = 34; + public const int DWMWA_CAPTION_COLOR = 35; + + [LibraryImport("dwmapi.dll")] + public static partial int DwmSetWindowAttribute(IntPtr hwnd, int attribute, ref int value, int size); + + /// Sets a 32-bit DWM attribute; false when the OS does not support it. + public static bool TrySetDwm(IntPtr hwnd, int attribute, int value) + { + if (hwnd == IntPtr.Zero || !OperatingSystem.IsWindows()) return false; + try + { + return DwmSetWindowAttribute(hwnd, attribute, ref value, sizeof(int)) == 0; + } + catch (DllNotFoundException) + { + return false; + } + catch (EntryPointNotFoundException) + { + return false; + } + } + + /// COLORREF (0x00BBGGRR) from RGB bytes. + public static int ColorRef(byte r, byte g, byte b) => r | g << 8 | b << 16; +} diff --git a/src/Titano.Ui/Localization/LocExtension.cs b/src/Titano.Ui/Localization/LocExtension.cs new file mode 100644 index 00000000..5d7af581 --- /dev/null +++ b/src/Titano.Ui/Localization/LocExtension.cs @@ -0,0 +1,49 @@ +using System.ComponentModel; +using System.Windows.Data; +using System.Windows.Markup; +using Titano.Core.Localization; + +namespace Titano.Ui.Localization; + +/// +/// XAML access to the string catalog: Text="{l:Loc Library.Filter.Year}". The value is a binding, so +/// changing updates the whole UI without restart (BRIEF §16). +/// +[MarkupExtensionReturnType(typeof(string))] +public sealed class LocExtension : MarkupExtension +{ + public LocExtension() + { + } + + public LocExtension(string key) => Key = key; + + [ConstructorArgument("key")] + public string Key { get; set; } = string.Empty; + + /// Optional format applied to the localized string (e.g. "{0}…"). + public string? StringFormat { get; set; } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + var binding = new Binding("[" + Key + "]") + { + Source = LocSource.Instance, + Mode = BindingMode.OneWay, + StringFormat = StringFormat, + }; + return binding.ProvideValue(serviceProvider); + } +} + +/// Indexer source for bindings; raises a refresh on culture change. +public sealed class LocSource : INotifyPropertyChanged +{ + private LocSource() => Loc.CultureChanged += (_, _) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]")); + + public static LocSource Instance { get; } = new(); + + public event PropertyChangedEventHandler? PropertyChanged; + + public string this[string key] => Loc.L(key); +} diff --git a/src/Titano.Ui/Mvvm/ObservableObject.cs b/src/Titano.Ui/Mvvm/ObservableObject.cs new file mode 100644 index 00000000..3257d5fb --- /dev/null +++ b/src/Titano.Ui/Mvvm/ObservableObject.cs @@ -0,0 +1,39 @@ +using System.ComponentModel; +using System.Runtime.CompilerServices; +using Titano.Core.Localization; + +namespace Titano.Ui.Mvvm; + +/// Minimal INotifyPropertyChanged base. +public abstract class ObservableObject : INotifyPropertyChanged +{ + public event PropertyChangedEventHandler? PropertyChanged; + + protected bool Set(ref T field, T value, [CallerMemberName] string? propertyName = null) + { + if (EqualityComparer.Default.Equals(field, value)) return false; + field = value; + OnPropertyChanged(propertyName); + return true; + } + + protected void OnPropertyChanged([CallerMemberName] string? propertyName = null) => + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + + /// Signals that every property changed (used after a culture switch). + protected void OnAllPropertiesChanged() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(string.Empty)); +} + +/// View model whose computed, localized texts refresh when the UI language changes. +public abstract class LocalizedViewModel : ObservableObject, IDisposable +{ + protected LocalizedViewModel() => Loc.CultureChanged += OnCultureChanged; + + public virtual void Dispose() + { + Loc.CultureChanged -= OnCultureChanged; + GC.SuppressFinalize(this); + } + + private void OnCultureChanged(object? sender, EventArgs e) => OnAllPropertiesChanged(); +} diff --git a/src/Titano.Ui/Mvvm/RelayCommand.cs b/src/Titano.Ui/Mvvm/RelayCommand.cs new file mode 100644 index 00000000..ba45ffbb --- /dev/null +++ b/src/Titano.Ui/Mvvm/RelayCommand.cs @@ -0,0 +1,70 @@ +using System.Windows.Input; + +namespace Titano.Ui.Mvvm; + +/// Synchronous command with optional can-execute predicate. +public sealed class RelayCommand(Action execute, Func? canExecute = null) : ICommand +{ + public RelayCommand(Action execute, Func? canExecute = null) + : this(_ => execute(), canExecute is null ? null : _ => canExecute()) + { + } + + public event EventHandler? CanExecuteChanged + { + add => CommandManager.RequerySuggested += value; + remove => CommandManager.RequerySuggested -= value; + } + + public bool CanExecute(object? parameter) => canExecute?.Invoke(parameter) ?? true; + + public void Execute(object? parameter) => execute(parameter); +} + +/// Asynchronous command that disables itself while running and reports failures through . +public sealed class AsyncRelayCommand(Func execute, Func? canExecute = null) : ICommand +{ + private CancellationTokenSource? _cts; + + public AsyncRelayCommand(Func execute, Func? canExecute = null) + : this((_, _) => execute(), canExecute is null ? null : _ => canExecute()) + { + } + + public event EventHandler? CanExecuteChanged; + + /// Raised on the UI thread when the command throws (other than cancellation). + public static event Action? Failed; + + public bool IsRunning => _cts is not null; + + public bool CanExecute(object? parameter) => !IsRunning && (canExecute?.Invoke(parameter) ?? true); + + public async void Execute(object? parameter) + { + if (!CanExecute(parameter)) return; + _cts = new CancellationTokenSource(); + RaiseCanExecuteChanged(); + try + { + await execute(parameter, _cts.Token); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + Failed?.Invoke(ex); + } + finally + { + _cts.Dispose(); + _cts = null; + RaiseCanExecuteChanged(); + } + } + + public void Cancel() => _cts?.Cancel(); + + public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty); +} diff --git a/src/Titano.Ui/Themes/Controls.xaml b/src/Titano.Ui/Themes/Controls.xaml new file mode 100644 index 00000000..aabdc7bc --- /dev/null +++ b/src/Titano.Ui/Themes/Controls.xaml @@ -0,0 +1,1391 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.Ui/Themes/Tokens.Dark.xaml b/src/Titano.Ui/Themes/Tokens.Dark.xaml new file mode 100644 index 00000000..849678cc --- /dev/null +++ b/src/Titano.Ui/Themes/Tokens.Dark.xaml @@ -0,0 +1,70 @@ + + + #1F1F23 + #1A1A1E + #26262C + #2F3038 + #383943 + #2A2B32 + #3E404A + #535663 + #F2F3F5 + #A9AEB9 + #7B818E + #4CC2FF + #6FCFFF + #3BA9E0 + #0B1B24 + #404CC2FF + #1F4CC2FF + #F5A524 + #35C48F + #E8B339 + #F0625D + #5AD1C8 + #F2F3F5 + #1A1A1A + #99000000 + #3E404A + #141417 + #1FE8B339 + #1FF0625D + #1F35C48F + #26F5A524 + #C42B1C + #66000000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.Ui/Themes/Tokens.Light.xaml b/src/Titano.Ui/Themes/Tokens.Light.xaml new file mode 100644 index 00000000..fa38b096 --- /dev/null +++ b/src/Titano.Ui/Themes/Tokens.Light.xaml @@ -0,0 +1,70 @@ + + + #F3F3F3 + #FFFFFF + #FFFFFF + #FFFFFF + #F5F5F5 + #EBEBEB + #E5E5E5 + #D1D1D1 + #1A1A1A + #616161 + #9E9E9E + #0067C0 + #1975C5 + #005AA8 + #FFFFFF + #E8F1FA + #F0F6FC + #E08A1E + #0F7B4F + #9A6700 + #C42B1C + #1A9E95 + #1A1A1A + #F2F3F5 + #66000000 + #E0E0E0 + #E9E9EC + #FFF4CE + #FDE7E9 + #DFF6DD + #FFF1DE + #C42B1C + #33000000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Titano.Ui/Themes/Typography.xaml b/src/Titano.Ui/Themes/Typography.xaml new file mode 100644 index 00000000..2a9a3f3f --- /dev/null +++ b/src/Titano.Ui/Themes/Typography.xaml @@ -0,0 +1,85 @@ + + + Segoe UI Variable Text, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic, Leelawadee UI, Nirmala UI, Tahoma + Segoe UI Variable Display, Segoe UI, Microsoft YaHei UI, Yu Gothic UI, Malgun Gothic + Cascadia Mono, Consolas + + 18 + 16 + 14 + 13 + 12 + 11 + + 4 + 8 + 12 + 16 + 20 + + 6 + 8 + 12 + 12 + + 32 + 28 + 38 + 34 + 40 + 56 + 30 + 128 + 48 + 320 + 200 + 116 + 180 + + + + + + + + + + + + diff --git a/src/Titano.Ui/Theming/ThemeManager.cs b/src/Titano.Ui/Theming/ThemeManager.cs new file mode 100644 index 00000000..085ddd4e --- /dev/null +++ b/src/Titano.Ui/Theming/ThemeManager.cs @@ -0,0 +1,112 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Interop; +using System.Windows.Media; +using Microsoft.Win32; +using Titano.Ui.Interop; + +namespace Titano.Ui.Theming; + +public enum AppTheme +{ + System, + Dark, + Light, +} + +/// +/// Loads the Titano design system into an application and switches between the dark and light token sets +/// at run time (DESIGN.md §1: dark is the client default, light follows the OS when System is chosen). +/// +public static class ThemeManager +{ + private const string Base = "pack://application:,,,/Titano.Ui;component/"; + private static ResourceDictionary? _tokens; + private static Application? _app; + private static bool _initialized; + + public static AppTheme Requested { get; private set; } = AppTheme.Dark; + + public static bool IsDark { get; private set; } + + public static event EventHandler? Changed; + + /// Merges typography, tokens, icons and control styles into . + public static void Initialize(Application app, AppTheme theme) + { + _app = app; + var merged = app.Resources.MergedDictionaries; + // Controls.xaml merges Typography.xaml and Icons.xaml itself so its StaticResources resolve at load. + _tokens = Load(TokensFor(Resolve(theme))); + merged.Insert(0, _tokens); + merged.Insert(1, Load("Themes/Controls.xaml")); + + ToolTipService.InitialShowDelayProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(400)); + ToolTipService.BetweenShowDelayProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(100)); + ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(20000)); + + SystemEvents.UserPreferenceChanged += (_, e) => + { + if (e.Category == UserPreferenceCategory.General && Requested == AppTheme.System) + app.Dispatcher.BeginInvoke(() => Apply(AppTheme.System)); + }; + Apply(theme); + } + + public static void Apply(AppTheme theme) + { + if (_app is null || _tokens is null) throw new InvalidOperationException("ThemeManager.Initialize first."); + Requested = theme; + var dark = Resolve(theme); + if (dark != IsDark || !_initialized) + { + var merged = _app.Resources.MergedDictionaries; + var index = merged.IndexOf(_tokens); + _tokens = Load(TokensFor(dark)); + merged[index] = _tokens; + IsDark = dark; + _initialized = true; + } + foreach (Window w in _app.Windows) ApplyChrome(w); + Changed?.Invoke(null, EventArgs.Empty); + } + + /// True when Windows apps are set to dark mode. + public static bool SystemPrefersDark() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"); + return key?.GetValue("AppsUseLightTheme") is not int light || light == 0; + } + catch (System.Security.SecurityException) + { + return true; + } + } + + /// Colours the DWM frame (border/caption) to match the current tokens. + public static void ApplyChrome(Window window) + { + var hwnd = new WindowInteropHelper(window).Handle; + if (hwnd == IntPtr.Zero) return; + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_USE_IMMERSIVE_DARK_MODE, IsDark ? 1 : 0); + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_USE_IMMERSIVE_DARK_MODE_OLD, IsDark ? 1 : 0); + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_WINDOW_CORNER_PREFERENCE, 2); + if (_app?.TryFindResource("Color.Chrome") is Color chrome) + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_CAPTION_COLOR, NativeMethods.ColorRef(chrome.R, chrome.G, chrome.B)); + if (_app?.TryFindResource("Color.Stroke") is Color stroke) + NativeMethods.TrySetDwm(hwnd, NativeMethods.DWMWA_BORDER_COLOR, NativeMethods.ColorRef(stroke.R, stroke.G, stroke.B)); + } + + private static bool Resolve(AppTheme theme) => theme switch + { + AppTheme.Dark => true, + AppTheme.Light => false, + _ => SystemPrefersDark(), + }; + + private static string TokensFor(bool dark) => dark ? "Themes/Tokens.Dark.xaml" : "Themes/Tokens.Light.xaml"; + + private static ResourceDictionary Load(string path) => new() { Source = new Uri(Base + path, UriKind.Absolute) }; +} diff --git a/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs b/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs new file mode 100644 index 00000000..e942c6eb --- /dev/null +++ b/tests/Titano.Server.Tests/Hosting/SystemEndpointTests.cs @@ -0,0 +1,126 @@ +using System.Net; +using System.Net.Http.Json; +using System.Security.Cryptography.X509Certificates; +using Titano.Protocol; +using Titano.Testing; + +namespace Titano.Server.Tests.Hosting; + +[Category("server")] +public sealed class SystemEndpointTests(TestContext context) +{ + [Test] + public async Task HealthReportsOk() + { + await using var server = await TestServer.StartAsync(context); + var health = await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus); + Assert.Equal("ok", Assert.NotNull(health).Status); + Assert.Equal("ok", health.Checks["archive"]); + } + + [Test] + public async Task ServerInfoCarriesFingerprintAndApiHeader() + { + await using var server = await TestServer.StartAsync(context); + using var response = await server.Client.GetAsync("/api/v1/server/info"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("1", response.Headers.GetValues(ApiVersion.Header).Single()); + var info = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ServerInfo); + Assert.Equal(1, Assert.NotNull(info).ApiVersion); + Assert.Equal(95, Assert.NotNull(info.TlsFingerprint).Length); // 32 bytes as XX: pairs + } + + [Test] + public async Task HttpsServesTheAdvertisedCertificate() + { + await using var server = await TestServer.StartAsync(context); + var info = await server.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo); + string? seen = null; + using var handler = new HttpClientHandler + { + ServerCertificateCustomValidationCallback = (_, cert, _, _) => + { + seen = cert is null ? null : string.Join(':', cert.GetCertHash(System.Security.Cryptography.HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture))); + return true; + }, + }; + using var https = new HttpClient(handler) { BaseAddress = Assert.NotNull(server.HttpsBase) }; + using var response = await https.GetAsync("/health"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(Assert.NotNull(info).TlsFingerprint, seen); + } + + [Test] + public async Task CertificateIsReusedAcrossRestarts() + { + var root = context.CreateTempDirectory("restart"); + string? first; + await using (var a = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data"))) + first = (await a.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint; + await using var b = await TestServer.StartAsync(context, o => o.DataPath = Path.Combine(root, "data")); + var second = (await b.Client.GetFromJsonAsync("/api/v1/server/info", ProtocolJson.Default.ServerInfo))!.TlsFingerprint; + Assert.Equal(first, second); + } + + [Test] + public async Task UnknownApiRouteReturnsJsonError() + { + await using var server = await TestServer.StartAsync(context); + using var response = await server.Client.GetAsync("/api/v1/does-not-exist"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + var error = await response.Content.ReadFromJsonAsync(ProtocolJson.Default.ApiError); + Assert.Equal("not_found", Assert.NotNull(error).Code); + } + + [Test] + public async Task AdminPanelIsServedWithEtags() + { + await using var server = await TestServer.StartAsync(context); + using var redirect = await new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = server.HttpBase }.GetAsync("/admin"); + Assert.Equal(HttpStatusCode.Redirect, redirect.StatusCode); + using var page = await server.Client.GetAsync("/admin/"); + Assert.Equal(HttpStatusCode.OK, page.StatusCode); + Assert.Contains("app.js", await page.Content.ReadAsStringAsync()); + var etag = page.Headers.ETag; + using var request = new HttpRequestMessage(HttpMethod.Get, "/admin/"); + request.Headers.IfNoneMatch.Add(Assert.NotNull(etag)); + using var cached = await server.Client.SendAsync(request); + Assert.Equal(HttpStatusCode.NotModified, cached.StatusCode); + } + + [Test] + public async Task I18nEndpointFallsBackToEnglish() + { + await using var server = await TestServer.StartAsync(context); + var it = await server.Client.GetFromJsonAsync("/api/v1/i18n/it-IT", ProtocolJson.Default.DictionaryStringString); + Assert.Equal("Accedi", Assert.NotNull(it)["Admin.Login.SignIn"]); + var unknown = await server.Client.GetFromJsonAsync("/api/v1/i18n/xx", ProtocolJson.Default.DictionaryStringString); + Assert.Equal("Sign in", Assert.NotNull(unknown)["Admin.Login.SignIn"]); + } + + [Test] + public void LinuxRefusesSqlite() + { + if (OperatingSystem.IsWindows()) TestContext.Skip("SQLite is allowed on Windows"); + var options = new Titano.Server.Configuration.ServerOptions { Database = Titano.Server.Configuration.DatabaseKind.Sqlite }; + Assert.Throws(options.Validate); + } + + [Test] + public void EnvironmentOverridesDefaults() + { + var root = context.CreateTempDirectory("env"); + var env = new Dictionary + { + ["TITANO_DATA_PATH"] = root, + ["TITANO_HTTP_PORT"] = "9090", + ["TITANO_TLS_MODE"] = "proxy", + ["TITANO_DB"] = "postgres", + ["TITANO_SERVER_NAME"] = "Studio NAS", + }; + var options = Titano.Server.Configuration.ServerOptions.Load(env); + Assert.Equal(9090, options.HttpPort); + Assert.Equal(Titano.Server.Configuration.TlsMode.Proxy, options.TlsMode); + Assert.Equal("Studio NAS", options.ServerName); + } +} diff --git a/tests/Titano.Server.Tests/TestServer.cs b/tests/Titano.Server.Tests/TestServer.cs new file mode 100644 index 00000000..2e099360 --- /dev/null +++ b/tests/Titano.Server.Tests/TestServer.cs @@ -0,0 +1,61 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; +using Microsoft.Extensions.DependencyInjection; +using Titano.Server.Configuration; +using Titano.Server.Hosting; +using Titano.Testing; + +namespace Titano.Server.Tests; + +/// In-process Kestrel on ephemeral ports with temporary archive/data folders (BRIEF §20.1). +public sealed class TestServer : IAsyncDisposable +{ + private readonly WebApplication _app; + + private TestServer(WebApplication app, ServerOptions options, Uri http, Uri? https) + { + _app = app; + Options = options; + HttpBase = http; + HttpsBase = https; + Client = new HttpClient { BaseAddress = http, Timeout = TimeSpan.FromSeconds(30) }; + } + + public ServerOptions Options { get; } + public Uri HttpBase { get; } + public Uri? HttpsBase { get; } + public HttpClient Client { get; } + public IServiceProvider Services => _app.Services; + + public static async Task StartAsync(TestContext context, Action? configure = null) + { + var root = context.CreateTempDirectory("server"); + var options = new ServerOptions + { + DataPath = Path.Combine(root, "data"), + ArchivePath = Path.Combine(root, "archive"), + HttpPort = 0, + HttpsPort = 0, + TlsMode = TlsMode.Auto, + Database = DatabaseKind.Sqlite, + }; + Directory.CreateDirectory(options.ArchivePath); + configure?.Invoke(options); + var app = ServerHost.Build(options, []); + await app.StartAsync(context.Cancellation); + var addresses = app.Services.GetRequiredService().Features.Get()!.Addresses + .Select(a => new Uri(a.Replace("[::]", "127.0.0.1", StringComparison.Ordinal).Replace("0.0.0.0", "127.0.0.1", StringComparison.Ordinal))) + .ToList(); + var http = addresses.First(a => a.Scheme == "http"); + var https = addresses.FirstOrDefault(a => a.Scheme == "https"); + return new TestServer(app, options, http, https); + } + + public async ValueTask DisposeAsync() + { + Client.Dispose(); + await _app.StopAsync(); + await _app.DisposeAsync(); + } +} diff --git a/tests/Titano.Testing/Assert.cs b/tests/Titano.Testing/Assert.cs index 8530989f..9982419f 100644 --- a/tests/Titano.Testing/Assert.cs +++ b/tests/Titano.Testing/Assert.cs @@ -7,12 +7,12 @@ namespace Titano.Testing; /// Assertions with messages that state expected and actual values. public static class Assert { - public static void True(bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) + public static void True([System.Diagnostics.CodeAnalysis.DoesNotReturnIf(false)] bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) { if (!condition) Fail(message ?? $"Expected true: {expression}"); } - public static void False(bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) + public static void False([System.Diagnostics.CodeAnalysis.DoesNotReturnIf(true)] bool condition, string? message = null, [CallerArgumentExpression(nameof(condition))] string? expression = null) { if (condition) Fail(message ?? $"Expected false: {expression}"); } @@ -22,13 +22,13 @@ public static class Assert if (value is not null) Fail($"Expected null: {expression} was {Format(value)}"); } - public static T NotNull(T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class + public static T NotNull([System.Diagnostics.CodeAnalysis.NotNull] T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class { if (value is null) Fail($"Expected non-null: {expression}"); return value!; } - public static T NotNull(T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : struct + public static T NotNull([System.Diagnostics.CodeAnalysis.NotNull] T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : struct { if (value is null) Fail($"Expected non-null: {expression}"); return value!.Value; diff --git a/tests/Titano.Testing/ConsoleReporter.cs b/tests/Titano.Testing/ConsoleReporter.cs index d9828784..41101711 100644 --- a/tests/Titano.Testing/ConsoleReporter.cs +++ b/tests/Titano.Testing/ConsoleReporter.cs @@ -13,6 +13,8 @@ internal sealed class ConsoleReporter(bool verbose) : IDisposable switch (r.Outcome) { case TestOutcome.Failed: + if (GitHubActions) + Console.WriteLine($"::error title=Test failed::{Escape(r.Test.FullName)}: {Escape(r.Message ?? "failed")}"); Write(ConsoleColor.Red, "FAIL "); Console.WriteLine($"{r.Test.FullName} ({Ms(r.Duration)})"); Console.WriteLine(" " + r.Message); @@ -50,6 +52,11 @@ internal sealed class ConsoleReporter(bool verbose) : IDisposable public void Dispose() => Console.Out.Flush(); + private static bool GitHubActions { get; } = Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true"; + + /// Workflow-command escaping (https://docs.github.com/actions/reference/workflow-commands). + private static string Escape(string s) => s.Replace("%", "%25", StringComparison.Ordinal).Replace("\r", "%0D", StringComparison.Ordinal).Replace("\n", "%0A", StringComparison.Ordinal); + private static string Ms(TimeSpan t) => t.TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture) + " ms"; private static string Indent(string s) => string.Join(Environment.NewLine, s.TrimEnd().Split('\n').Select(l => " " + l.TrimEnd('\r'))); diff --git a/tests/Titano.Testing/TestRunner.cs b/tests/Titano.Testing/TestRunner.cs index 1745aad5..813b5f9e 100644 --- a/tests/Titano.Testing/TestRunner.cs +++ b/tests/Titano.Testing/TestRunner.cs @@ -43,8 +43,10 @@ public static class TestRunner } if (selected.Count == 0) { - Console.Error.WriteLine("No tests matched."); - return 2; + // An empty project is not a failure; a filter that matches nothing is a usage error. + var filtered = options.HasFilters; + Console.Error.WriteLine(filtered ? "No tests matched." : "No tests discovered."); + return filtered ? 2 : 0; } var stopwatch = Stopwatch.StartNew(); @@ -284,6 +286,7 @@ public static class TestRunner public int Parallelism { get; private set; } = Math.Max(1, Environment.ProcessorCount); public bool List { get; private set; } public bool Verbose { get; private set; } + public bool HasFilters => Filters.Count > 0 || Excludes.Count > 0; public static Options Parse(string[] args) {