diff --git a/.forgejo/workflows/build-catalog-lite.yml b/.forgejo/workflows/build-catalog-lite.yml deleted file mode 100644 index 8bf031a..0000000 --- a/.forgejo/workflows/build-catalog-lite.yml +++ /dev/null @@ -1,206 +0,0 @@ -name: Build Catalog Lite - -on: - workflow_dispatch: - inputs: - expiration_date: - description: Catalog Lite expiration date, yyyy-MM-dd - required: true - default: '2026-12-31' - type: string - -env: - DOTNET_VERSION: 10.0.x - PROJECT_PATH: CatalogLite/CatalogLite.csproj - CATALOG_LITE_EXPIRATION_DATE: ${{ inputs.expiration_date }} - -jobs: - build: - runs-on: docker - strategy: - fail-fast: false - matrix: - include: - - runtime: win-x64 - artifact_name: catalog-lite-win-x64 - executable_name: CatalogLite.exe - - runtime: linux-x64 - artifact_name: catalog-lite-linux-x64 - executable_name: CatalogLite - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: ${{ env.DOTNET_VERSION }} - - - name: Validate expiration date - run: | - set -eu - case "${CATALOG_LITE_EXPIRATION_DATE}" in - ????-??-??) ;; - *) - echo "expiration_date must use yyyy-MM-dd format" - exit 1 - ;; - esac - - - name: Restore - run: dotnet restore "${{ env.PROJECT_PATH }}" -r "${{ matrix.runtime }}" --configfile NuGet.Config - - - name: Publish Catalog Lite - env: - PUBLISH_DIR: artifacts/publish/${{ matrix.runtime }} - run: | - set -eu - dotnet publish "${{ env.PROJECT_PATH }}" \ - -c Release \ - -r "${{ matrix.runtime }}" \ - --self-contained false \ - --no-restore \ - -p:CatalogLiteExpirationDate="${CATALOG_LITE_EXPIRATION_DATE}" \ - -p:PublishSingleFile=true \ - -p:SelfContained=false \ - -p:IncludeNativeLibrariesForSelfExtract=true \ - -p:PublishTrimmed=false \ - -p:PublishReadyToRun=false \ - -p:DebugType=embedded \ - -o "${PUBLISH_DIR}" - - - name: Validate published files - env: - PUBLISH_DIR: artifacts/publish/${{ matrix.runtime }} - run: | - set -eu - executable="${PUBLISH_DIR}/${{ matrix.executable_name }}" - if [ ! -f "${executable}" ]; then - echo "Catalog Lite executable was not produced: ${executable}" - exit 1 - fi - - loose_library_count="$(find "${PUBLISH_DIR}" -maxdepth 1 -type f \( -iname '*.dll' -o -name '*.so' -o -name '*.dylib' \) | wc -l | tr -d ' ')" - if [ "${loose_library_count}" -ne 0 ]; then - echo "Catalog Lite publish must not contain loose native or managed libraries:" - find "${PUBLISH_DIR}" -maxdepth 1 -type f \( -iname '*.dll' -o -name '*.so' -o -name '*.dylib' \) -print - exit 1 - fi - - extra_file_count="$(find "${PUBLISH_DIR}" -maxdepth 1 -type f ! -name "${{ matrix.executable_name }}" | wc -l | tr -d ' ')" - if [ "${extra_file_count}" -ne 0 ]; then - echo "Catalog Lite publish artifact must contain only ${{ matrix.executable_name }}:" - find "${PUBLISH_DIR}" -maxdepth 1 -type f ! -name "${{ matrix.executable_name }}" -print - exit 1 - fi - - - name: Upload publish artifact - uses: actions/upload-artifact@v3 - with: - name: ${{ matrix.artifact_name }} - path: artifacts/publish/${{ matrix.runtime }}/${{ matrix.executable_name }} - if-no-files-found: error - - release: - needs: build - runs-on: docker - env: - FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} - - steps: - - name: Download Windows artifact - uses: actions/download-artifact@v3 - with: - name: catalog-lite-win-x64 - path: artifacts/release/win-x64 - - - name: Validate release token - run: | - set -eu - if [ -z "${FORGEJO_TOKEN}" ]; then - echo "secrets.FORGEJO_TOKEN is required for Catalog Lite releases" - exit 1 - fi - - - name: Create or update release - run: | - set -eu - api_base="${FORGEJO_SERVER_URL%/}/api/v1/repos/${FORGEJO_REPOSITORY}" - tag="catalog-lite-${CATALOG_LITE_EXPIRATION_DATE}" - name="Catalog Lite ${CATALOG_LITE_EXPIRATION_DATE}" - commit="${FORGEJO_SHA:-${GITHUB_SHA:-}}" - create_payload="$(printf '{"tag_name":"%s","target_commitish":"%s","name":"%s","body":"Catalog Lite\\n\\nScadenza build: %s","draft":false,"prerelease":false}' "${tag}" "${commit}" "${name}" "${CATALOG_LITE_EXPIRATION_DATE}")" - update_payload="$(printf '{"body":"Catalog Lite\\n\\nScadenza build: %s"}' "${CATALOG_LITE_EXPIRATION_DATE}")" - - http_code="$(curl -sS -o release.json -w '%{http_code}' \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - "${api_base}/releases/tags/${tag}")" - - if [ "${http_code}" = "200" ]; then - release_id="$(sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p' release.json | head -n1)" - curl -fsS \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - -H "Content-Type: application/json" \ - -X PATCH \ - -d "${update_payload}" \ - "${api_base}/releases/${release_id}" \ - -o release.json - elif [ "${http_code}" = "404" ]; then - curl -fsS \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - -H "Content-Type: application/json" \ - -X POST \ - -d "${create_payload}" \ - "${api_base}/releases" \ - -o release.json - release_id="$(sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p' release.json | head -n1)" - else - echo "Unexpected response while loading release for tag ${tag}: ${http_code}" - cat release.json - exit 1 - fi - - if [ -z "${release_id}" ]; then - echo "Unable to resolve Forgejo release id" - cat release.json - exit 1 - fi - - echo "RELEASE_ID=${release_id}" >> "${GITHUB_ENV}" - - - name: Upload release assets - run: | - set -eu - api_base="${FORGEJO_SERVER_URL%/}/api/v1/repos/${FORGEJO_REPOSITORY}" - - windows_exe="$(find artifacts/release/win-x64 -maxdepth 1 -type f -iname '*.exe' | head -n1)" - - if [ -z "${windows_exe}" ]; then - echo "No Windows executable found in downloaded artifact" - exit 1 - fi - - curl -fsS \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - "${api_base}/releases/${RELEASE_ID}/assets" \ - -o assets.json - - for asset_id in $(tr '{' '\n' < assets.json | sed -n 's/.*"id":\([0-9][0-9]*\).*"name":"[^"]*".*/\1/p'); do - curl -fsS \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - -X DELETE \ - "${api_base}/releases/${RELEASE_ID}/assets/${asset_id}" - done - - upload_asset() { - asset_path="$1" - asset_name="$2" - curl -fsS \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - -H "Content-Type: application/octet-stream" \ - --data-binary @"${asset_path}" \ - "${api_base}/releases/${RELEASE_ID}/assets?name=${asset_name}" - } - - upload_asset "${windows_exe}" "CatalogLite-${CATALOG_LITE_EXPIRATION_DATE}.exe" diff --git a/.forgejo/workflows/build-windows-avalonia.yml b/.forgejo/workflows/build-windows-avalonia.yml deleted file mode 100644 index c418d92..0000000 --- a/.forgejo/workflows/build-windows-avalonia.yml +++ /dev/null @@ -1,107 +0,0 @@ -name: Build Windows Avalonia - -on: - push: - branches: - - master - - develop - paths: - - '.forgejo/workflows/build-windows-avalonia.yml' - - 'Catalog.Communication/**' - - 'GitVersion.yml' - - 'NuGet.Config' - - 'MaddoShared/**' - - 'imagecatalog/**' - workflow_dispatch: - -env: - DOTNET_VERSION: 10.0.x - PROJECT_PATH: imagecatalog/ImageCatalog 2.csproj - PUBLISH_DIR: artifacts/publish/win-x64 - ARTIFACT_NAME: imagecatalog-windows-avalonia - NUGET_SOURCE_NAME: Nuget-Forgejo-AIFotoONLUS - NUGET_SOURCE_URL: ${{ vars.AIFOTOONLUS_NUGET_SOURCE_URL || format('{0}/api/packages/{1}/nuget/index.json', github.server_url, vars.AIFOTOONLUS_PACKAGE_OWNER || github.repository_owner) }} - -jobs: - build: - runs-on: docker - env: - FORGEJO_PACKAGE_USERNAME: ${{ secrets.FORGEJO_PACKAGE_USERNAME }} - FORGEJO_PACKAGE_TOKEN: ${{ secrets.FORGEJO_PACKAGE_TOKEN }} - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: ${{ env.DOTNET_VERSION }} - - - name: Validate NuGet secrets - run: | - set -eu - if [ -z "${FORGEJO_PACKAGE_USERNAME}" ]; then - echo "secrets.FORGEJO_PACKAGE_USERNAME is required" - exit 1 - fi - if [ -z "${FORGEJO_PACKAGE_TOKEN}" ]; then - echo "secrets.FORGEJO_PACKAGE_TOKEN is required" - exit 1 - fi - - - name: Configure private NuGet source - run: | - set -eu - temp_config="${RUNNER_TEMP}/nuget.config" - cp NuGet.Config "${temp_config}" - - dotnet nuget update source "${{ env.NUGET_SOURCE_NAME }}" \ - --source "${{ env.NUGET_SOURCE_URL }}" \ - --username "${FORGEJO_PACKAGE_USERNAME}" \ - --password "${FORGEJO_PACKAGE_TOKEN}" \ - --store-password-in-clear-text \ - --configfile "${temp_config}" - - echo "NUGET_CONFIG_PATH=${temp_config}" >> "${GITHUB_ENV}" - - - name: Restore - run: dotnet restore "${{ env.PROJECT_PATH }}" -r win-x64 --configfile "${NUGET_CONFIG_PATH}" - - - name: Publish Windows Avalonia build - run: | - set -eu - dotnet publish "${{ env.PROJECT_PATH }}" \ - -c Release \ - -r win-x64 \ - --self-contained true \ - --no-restore \ - -p:AvaloniaWindowsCrossPublish=true \ - -p:PublishSingleFile=true \ - -p:PublishTrimmed=false \ - -p:PublishReadyToRun=false \ - -o "${{ env.PUBLISH_DIR }}" - - - name: Validate published executable - run: | - set -eu - exe_count="$(find "${{ env.PUBLISH_DIR }}" -maxdepth 1 -type f -iname '*.exe' | wc -l | tr -d ' ')" - if [ "${exe_count}" -eq 0 ]; then - echo "No Windows executable produced in ${{ env.PUBLISH_DIR }}" - exit 1 - fi - - legacy_renderer_count="$(find "${{ env.PUBLISH_DIR }}" -maxdepth 1 -type f \( -iname 'Microsoft.Windows.Compatibility.dll' -o -iname 'System.Private.Windows.GdiPlus.dll' \) | wc -l | tr -d ' ')" - if [ "${legacy_renderer_count}" -ne 0 ]; then - echo "Legacy GDI compatibility assemblies must not be published:" - find "${{ env.PUBLISH_DIR }}" -maxdepth 1 -type f \( -iname 'Microsoft.Windows.Compatibility.dll' -o -iname 'System.Private.Windows.GdiPlus.dll' \) -print - exit 1 - fi - - - name: Upload publish artifact - uses: actions/upload-artifact@v3 - with: - name: ${{ env.ARTIFACT_NAME }} - path: ${{ env.PUBLISH_DIR }} - if-no-files-found: error - diff --git a/.forgejo/workflows/release-windows-avalonia.yml b/.forgejo/workflows/release-windows-avalonia.yml deleted file mode 100644 index ca7c521..0000000 --- a/.forgejo/workflows/release-windows-avalonia.yml +++ /dev/null @@ -1,174 +0,0 @@ -name: Release Windows Avalonia - -on: - push: - tags: - - '*' - -env: - DOTNET_VERSION: 10.0.x - PROJECT_PATH: imagecatalog/ImageCatalog 2.csproj - PUBLISH_DIR: artifacts/publish/win-x64 - ARTIFACT_NAME: imagecatalog-windows-avalonia - NUGET_SOURCE_NAME: Nuget-Forgejo-AIFotoONLUS - NUGET_SOURCE_URL: ${{ vars.AIFOTOONLUS_NUGET_SOURCE_URL || format('{0}/api/packages/{1}/nuget/index.json', forgejo.server_url, vars.AIFOTOONLUS_PACKAGE_OWNER || forgejo.repository_owner) }} - -jobs: - build: - runs-on: docker - env: - FORGEJO_PACKAGE_USERNAME: ${{ secrets.FORGEJO_PACKAGE_USERNAME }} - FORGEJO_PACKAGE_TOKEN: ${{ secrets.FORGEJO_PACKAGE_TOKEN }} - - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Setup .NET - uses: actions/setup-dotnet@v4 - with: - dotnet-version: ${{ env.DOTNET_VERSION }} - - - name: Validate NuGet secrets - run: | - set -eu - if [ -z "${FORGEJO_PACKAGE_USERNAME}" ]; then - echo "secrets.FORGEJO_PACKAGE_USERNAME is required" - exit 1 - fi - if [ -z "${FORGEJO_PACKAGE_TOKEN}" ]; then - echo "secrets.FORGEJO_PACKAGE_TOKEN is required" - exit 1 - fi - - - name: Configure private NuGet source - run: | - set -eu - temp_config="${RUNNER_TEMP}/nuget.config" - cp NuGet.Config "${temp_config}" - - dotnet nuget update source "${{ env.NUGET_SOURCE_NAME }}" \ - --source "${{ env.NUGET_SOURCE_URL }}" \ - --username "${FORGEJO_PACKAGE_USERNAME}" \ - --password "${FORGEJO_PACKAGE_TOKEN}" \ - --store-password-in-clear-text \ - --configfile "${temp_config}" - - echo "NUGET_CONFIG_PATH=${temp_config}" >> "${GITHUB_ENV}" - - - name: Restore - run: dotnet restore "${{ env.PROJECT_PATH }}" -r win-x64 --configfile "${NUGET_CONFIG_PATH}" - - - name: Publish Windows Avalonia build - run: | - set -eu - dotnet publish "${{ env.PROJECT_PATH }}" \ - -c Release \ - -r win-x64 \ - --self-contained true \ - --no-restore \ - -p:AvaloniaWindowsCrossPublish=true \ - -p:PublishSingleFile=true \ - -p:PublishTrimmed=false \ - -p:PublishReadyToRun=false \ - -o "${{ env.PUBLISH_DIR }}" - - - name: Validate published executable - run: | - set -eu - exe_count="$(find "${{ env.PUBLISH_DIR }}" -maxdepth 1 -type f -iname '*.exe' | wc -l | tr -d ' ')" - if [ "${exe_count}" -eq 0 ]; then - echo "No Windows executable produced in ${{ env.PUBLISH_DIR }}" - exit 1 - fi - - legacy_renderer_count="$(find "${{ env.PUBLISH_DIR }}" -maxdepth 1 -type f \( -iname 'Microsoft.Windows.Compatibility.dll' -o -iname 'System.Private.Windows.GdiPlus.dll' \) | wc -l | tr -d ' ')" - if [ "${legacy_renderer_count}" -ne 0 ]; then - echo "Legacy GDI compatibility assemblies must not be published:" - find "${{ env.PUBLISH_DIR }}" -maxdepth 1 -type f \( -iname 'Microsoft.Windows.Compatibility.dll' -o -iname 'System.Private.Windows.GdiPlus.dll' \) -print - exit 1 - fi - - - name: Upload publish artifact - uses: actions/upload-artifact@v3 - with: - name: ${{ env.ARTIFACT_NAME }} - path: ${{ env.PUBLISH_DIR }} - if-no-files-found: error - - release: - needs: build - runs-on: docker - env: - FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN }} - - steps: - - name: Download publish artifact - uses: actions/download-artifact@v3 - with: - name: ${{ env.ARTIFACT_NAME }} - path: artifacts/release - - - name: Validate release token - run: | - set -eu - if [ -z "${FORGEJO_TOKEN}" ]; then - echo "secrets.FORGEJO_TOKEN is required for tagged releases" - exit 1 - fi - - - name: Create or reuse release - run: | - set -eu - api_base="${FORGEJO_SERVER_URL%/}/api/v1/repos/${FORGEJO_REPOSITORY}" - tag="${FORGEJO_REF_NAME}" - - http_code="$(curl -sS -o release.json -w '%{http_code}' \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - "${api_base}/releases/tags/${tag}")" - - if [ "${http_code}" = "200" ]; then - release_id="$(sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p' release.json | head -n1)" - elif [ "${http_code}" = "404" ]; then - payload="$(printf '{"tag_name":"%s","name":"%s","draft":false,"prerelease":false}' "${tag}" "${tag}")" - curl -fsS \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - -H "Content-Type: application/json" \ - -X POST \ - -d "${payload}" \ - "${api_base}/releases" \ - -o release.json - release_id="$(sed -n 's/.*"id":\([0-9][0-9]*\).*/\1/p' release.json | head -n1)" - else - echo "Unexpected response while loading release for tag ${tag}: ${http_code}" - cat release.json - exit 1 - fi - - if [ -z "${release_id}" ]; then - echo "Unable to resolve Forgejo release id" - cat release.json - exit 1 - fi - - echo "RELEASE_ID=${release_id}" >> "${GITHUB_ENV}" - - - name: Upload executable to release - run: | - set -eu - api_base="${FORGEJO_SERVER_URL%/}/api/v1/repos/${FORGEJO_REPOSITORY}" - executable_path="$(find artifacts/release -maxdepth 1 -type f -iname '*.exe' | head -n1)" - - if [ -z "${executable_path}" ]; then - echo "No executable found in downloaded artifact" - exit 1 - fi - - short_sha="$(printf '%s' "${FORGEJO_SHA}" | cut -c1-12)" - asset_name="ImageCatalog-avalonia-win-x64-${FORGEJO_REF_NAME}-${short_sha}.exe" - - curl -fsS \ - -H "Authorization: token ${FORGEJO_TOKEN}" \ - -H "Content-Type: application/octet-stream" \ - --data-binary @"${executable_path}" \ - "${api_base}/releases/${RELEASE_ID}/assets?name=${asset_name}" \ No newline at end of file diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md deleted file mode 100644 index 8431a6c..0000000 --- a/.github/copilot-instructions.md +++ /dev/null @@ -1,81 +0,0 @@ -# Copilot Instructions - -## Build & Test Commands - -```powershell -# Build -dotnet build Catalog.slnx - -# Run all tests -dotnet test MaddoShared.Tests - -# Run a single test -dotnet test MaddoShared.Tests --filter "FullyQualifiedName~MethodName" - -# Benchmarks (modes: quick | all | parallel | chunks | sizes | stress) -.\run-benchmarks.ps1 quick - -# Publish release build (self-contained Windows EXE) -dotnet publish "imagecatalog\ImageCatalog 2.csproj" -c Release -r win-x64 --self-contained -``` - -## Architecture - -This is an Avalonia image cataloging application targeting .NET 10.0-windows. - -### Projects - -| Project | Purpose | -|---------|---------| -| **imagecatalog** | Main desktop application — Avalonia with Fluent theme (`AvaloniaMainWindow`) | -| **MaddoShared** | Shared image processing library (the core) | -| **MaddoShared.Tests** | Unit tests for MaddoShared | -| **MaddoShared.Benchmarks** | BenchmarkDotNet performance benchmarks | -| **WPFCatalog** | Alternate WPF UI (secondary) | -| **ImageCatalogCS / ImageCatalogParallel** | Legacy/experimental variants | -| **CatalogLib / CatalogLibVb / CatalogVbLib** | Legacy VB.NET libraries | - -The main app launches Avalonia directly. Dialog events (`SelectSourceFolderRequested`, etc.) are subscribed in `AvaloniaMainWindow` code-behind. `DataModel.UiInvoker` must be set by the active UI to enable cross-thread UI updates (Avalonia sets this to `Dispatcher.UIThread.Invoke`). - -### Core Flow - -1. User configures paths/settings in the UI (`DataModel.cs` — MVVM ViewModel) -2. `ProcessImagesCommand` triggers `ImageCreationService` -3. `ImageCreationService` processes files in parallel chunks, with configurable concurrency and batch size (GC flush between chunks) -4. Each file is handled by the ImageSharp `IImageCreator` implementation -5. Output: resized/watermarked/overlaid images written to a destination folder hierarchy - -### Key Abstractions (MaddoShared) - -- **`IImageCreator`** — single async method to process one image; implemented by `ImageCreatorImageSharp` (SixLabors.ImageSharp) -- **`ImageCreationService`** — parallel orchestrator; uses `AsyncEnumerator` with chunking; loads logo once, clones per thread for thread safety -- **`ImageState`** — per-file processing context (input path, EXIF orientation, thumbnail sizes, overlays, logo, rotation) -- **`PicSettings`** — 50+ property configuration model (dimensions, fonts, colors, JPEG quality, watermark, logo positioning) -- **`FileHelperSharp`** — recursive file enumeration with folder-per-N-files mapping and counter formatting - -## Conventions - -### C# Style -- File-scoped namespaces everywhere: `namespace MaddoShared;` -- Nullable reference types enabled (`enable`) -- Implicit usings enabled -- `ConfigureAwait(false)` on all `await` calls in library code - -### Dependency Injection -- Constructor injection throughout; loggers typed as `ILogger` -- Main app wires services in `Program.cs` via `IServiceCollection` - -### Testing -- MSTest with `[TestClass]` / `[TestMethod]` -- FluentAssertions for assertions -- Moq for mocking -- Factory helper pattern in tests: `CreateService(Action configure = null)` methods for flexible test setup - -### Async / Parallelism -- All image I/O is `async Task` -- `ImageCreationService` uses configurable `MaxDegreeOfParallelism` and `ChunkSize`; explicit `GC.Collect()` between chunks to manage memory under batch load - -### Versioning & CI -- Semantic versioning via **GitVersion** (mode: `ContinuousDelivery`, current base: `3.2.0`) -- GitLab CI pipeline: builds → single-file self-contained EXE → GitLab Release -- Private NuGet packages scoped to `AIFotoONLUS.*` prefix, routed to the GitLab package registry (see `NuGet.Config`) diff --git a/.gitignore b/.gitignore index 7c86da2..432b9b3 100644 --- a/.gitignore +++ b/.gitignore @@ -255,6 +255,3 @@ paket-files/ # JetBrains Rider .idea/ *.sln.iml -.vscode/settings.json -tmp/** -TestArtifacts/** \ No newline at end of file diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 04a76b7..5ba6ff4 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,156 +4,62 @@ stages: # Only create pipelines automatically when a Git tag is pushed. # Otherwise the pipeline must be started manually (pipeline "Run" / dispatch equivalent). -# workflow: -# rules: -# - if: '$CI_COMMIT_TAG' -# when: always -# - if: '$CI_PIPELINE_SOURCE == "web"' -# when: always -# - when: never +workflow: + rules: + - if: '$CI_COMMIT_TAG' + when: always + - if: '$CI_PIPELINE_SOURCE == "web"' + when: always + - when: never variables: DOTNET_CLI_TELEMETRY_OPTOUT: "1" DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1" BUILD_CONFIG: "Release" - # NOTE: This project uses repository variables for NuGet auth because secrets - # (masked/protected variables) may not be available on your GitLab plan. - # Replace the placeholders below with values in the repository, or override - # them in your project CI/CD variables when available. - # - NUGET_USERNAME : username (can be any value when using a PAT) - # - NUGET_PASSWORD : personal access token or project deploy token - NUGET_USERNAME: "REPLACE_WITH_USERNAME" - NUGET_PASSWORD: "REPLACE_WITH_TOKEN" # Build job for Windows runner (shell executor). Remove 'image' so the runner uses the host environment. build_windows: stage: build tags: - - saas-windows-medium-amd64 + - shared-windows script: - - | - powershell -NoProfile -Command { - $needsInstall = -not (dotnet --list-sdks 2>$null | Select-String '^10\.') - if ($needsInstall) { - Write-Host 'Installing .NET 10 SDK using dotnet-install.ps1' - Invoke-WebRequest 'https://dot.net/v1/dotnet-install.ps1' -OutFile dotnet-install.ps1 -UseBasicParsing - .\dotnet-install.ps1 -Channel 10.0 -InstallDir $env:USERPROFILE\.dotnet - $dotnetExe = Join-Path $env:USERPROFILE '.dotnet\dotnet.exe' - } else { - Write-Host '.NET 10 SDK already present on PATH' - $dotnetExe = 'dotnet' - } - - # Configure private NuGet source from GitLab Packages using CI_JOB_TOKEN - # Fallback to repository variables NUGET_USERNAME/NUGET_PASSWORD for shared runners - $nugetUrl = 'https://gitlab.com/api/v4/projects/79509532/packages/nuget/index.json' - $authMode = $null - if ($env:CI_JOB_TOKEN) { - Write-Host 'Configuring private NuGet source Nuget-GitLab-AIFotoONLUS using CI_JOB_TOKEN...' - try { & $dotnetExe nuget remove source Nuget-GitLab-AIFotoONLUS } catch {} - & $dotnetExe nuget add source $nugetUrl --name Nuget-GitLab-AIFotoONLUS --username gitlab-ci-token --password $env:CI_JOB_TOKEN --store-password-in-clear-text - $authMode = 'JobToken' - } elseif ($env:NUGET_USERNAME -and $env:NUGET_PASSWORD) { - Write-Host 'Configuring private NuGet source Nuget-GitLab-AIFotoONLUS using NUGET_USERNAME/NUGET_PASSWORD...' - try { & $dotnetExe nuget remove source Nuget-GitLab-AIFotoONLUS } catch {} - & $dotnetExe nuget add source $nugetUrl --name Nuget-GitLab-AIFotoONLUS --username $env:NUGET_USERNAME --password $env:NUGET_PASSWORD --store-password-in-clear-text - $authMode = 'UserCreds' - } else { - Write-Host 'No credentials available; skipping private NuGet source configuration.' - } - - & $dotnetExe --info - # Diagnostic: verify GitLab NuGet feed and package visibility using configured auth - if ($authMode) { - Write-Host 'Checking GitLab NuGet feed index and project packages for AIFotoONLUS.Core using auth mode:' $authMode - try { - if ($authMode -eq 'JobToken') { - $headers = @{ 'JOB-TOKEN' = $env:CI_JOB_TOKEN } - } else { - $pair = "$env:NUGET_USERNAME:$env:NUGET_PASSWORD" - $b64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($pair)) - $headers = @{ Authorization = "Basic $b64" } - } - Invoke-RestMethod -Uri $nugetUrl -Headers $headers -Method Get | ConvertTo-Json | Write-Host - } catch { Write-Host "Failed to fetch feed index: $_" } - try { - $pkgApi = "https://gitlab.com/api/v4/projects/79509532/packages?package_name=AIFotoONLUS.Core" - Invoke-RestMethod -Uri $pkgApi -Headers $headers -Method Get | ConvertTo-Json | Write-Host - } catch { Write-Host "Failed to query project packages API: $_" } - } else { - Write-Host 'Skipping feed diagnostics because no auth configured.' - } - & $dotnetExe restore - & $dotnetExe build "imagecatalog\ImageCatalog 2.csproj" -c $env:BUILD_CONFIG -v minimal - # Produce a single-file, ready-to-run publish so downstream jobs only need the EXE. - try { - & $dotnetExe publish "imagecatalog\ImageCatalog 2.csproj" -c $env:BUILD_CONFIG -r win-x64 --self-contained true -p:PublishSingleFile=true -p:PublishTrimmed=false -p:PublishReadyToRun=true -o "imagecatalog\bin\$env:BUILD_CONFIG\net10.0-windows\publish" -v minimal - $publishDir = "imagecatalog\bin\$env:BUILD_CONFIG\net10.0-windows\publish" - $legacyRendererFiles = Get-ChildItem $publishDir -File | Where-Object { $_.Name -in @('Microsoft.Windows.Compatibility.dll', 'System.Private.Windows.GdiPlus.dll') } - if ($legacyRendererFiles) { - Write-Host 'Legacy GDI compatibility assemblies must not be published:' - $legacyRendererFiles | ForEach-Object { Write-Host $_.FullName } - exit 1 - } - } catch { - Write-Host "dotnet publish failed: $_" - throw - } - } + - dotnet --info + - dotnet restore + - dotnet build "imagecatalog\ImageCatalog 2.csproj" -c $BUILD_CONFIG -v minimal artifacts: paths: - - "imagecatalog/bin/$BUILD_CONFIG/net10.0-windows/publish/**" + - "**/bin/$BUILD_CONFIG/net10.0-windows/**" expire_in: 1 hour -# Publish and create GitLab Release when building a tag. +# Publish and create GitLab Release when building a tag. This job expects a Windows runner with PowerShell and curl available. publish_release: stage: publish - image: mcr.microsoft.com/dotnet/sdk:10.0 - variables: - GIT_DEPTH: 0 + tags: + - shared-windows needs: - - job: build_windows - artifacts: true - script: | - set -euo pipefail - dotnet --info - export PATH="$PATH:$HOME/.dotnet/tools" - echo "Installing minver-cli" - dotnet tool install --global minver-cli --version 7.0.0 - # Ensure we have full git history and tags for MinVer to compute an accurate version - git fetch --prune --unshallow || true - git fetch --tags || true - echo "Computing version with minver-cli" - version=$(minver 2>/dev/null | tail -n1 || true) - if [ -z "$version" ]; then echo "minver failed to produce a version"; exit 1; fi - echo "Using version: $version" - export VERSION="$version" - # find the single-file exe from the publish output - file=$(find imagecatalog/bin -type f -iname '*.exe' -print | head -n1 || true) - if [ -z "$file" ]; then file=$(find imagecatalog -type f -iname '*.exe' -print | head -n1 || true); fi - if [ -z "$file" ]; then echo "No artifact EXE found to attach"; exit 1; fi - echo "Uploading artifact: $file" - uploadResp=$(curl --silent --show-error --header "JOB-TOKEN:$CI_JOB_TOKEN" --form "file=@$file" "$CI_API_V4_URL/projects/$CI_PROJECT_ID/uploads") - assetPath=$(echo "$uploadResp" | sed -n 's/.*"url":"\([^\"]*\)".*/\1/p') - if [ -z "$assetPath" ]; then echo "Upload failed: $uploadResp"; exit 1; fi - assetUrl="$CI_SERVER_URL$assetPath" - echo "Uploaded asset url: $assetUrl" - basename=$(basename "$file") - export RELEASE_ASSET_URL="$assetUrl" - export ASSET_BASENAME="$basename" + - build_windows + script: + # Publish the app + - dotnet publish "imagecatalog\ImageCatalog 2.csproj" -c $BUILD_CONFIG -r win-x64 --self-contained false -o publish + - echo "Published to $(pwd)\\publish" + # Find first file in publish folder + - $file = Get-ChildItem -Path publish -File | Select-Object -First 1; Write-Host "Uploading $($file.FullName)" + # Upload to GitLab project uploads API to get a public URL for the artifact + - $uploadUrl = "$env:CI_API_V4_URL/projects/$env:CI_PROJECT_ID/uploads" + - $formData = "file=@$($file.FullName)" + - $uploadResp = curl --silent --show-error --header "JOB-TOKEN:$env:CI_JOB_TOKEN" --form $formData $uploadUrl + - $uploadJson = $uploadResp | ConvertFrom-Json + - $assetUrl = "$env:CI_SERVER_URL$($uploadJson.url)" + - 'Write-Host "Uploaded asset url: $assetUrl"' + # Create the release using uploads URL + - $body = @{ name = $env:CI_COMMIT_TAG; tag_name = $env:CI_COMMIT_TAG; description = "Automated release from CI"; assets = @{ links = @(@{ name = "$($file.Name)"; url = $assetUrl }) } } | ConvertTo-Json -Depth 10 + - Invoke-RestMethod -Method Post -Uri "$env:CI_API_V4_URL/projects/$env:CI_PROJECT_ID/releases" -Headers @{ "JOB-TOKEN" = $env:CI_JOB_TOKEN } -Body $body -ContentType "application/json" artifacts: + paths: + - publish/* expire_in: 1 day - release: - tag_name: "$VERSION" - name: "Release $VERSION" - description: "Automated release from CI (version $VERSION)" - assets: - links: - - name: "$ASSET_BASENAME" - url: "$RELEASE_ASSET_URL" -# only: -# - tags + only: + - tags -# Notes for runner setup: The job now runs on the public .NET SDK image and downloads artifacts from the -# `build_windows` job via `needs`. It reads the `minversion` file produced by the build artifacts and -# uses that value as the release tag. +# Notes for runner setup: Ensure a GitLab Windows runner with tag 'windows' is registered and has .NET 10 SDK installed. +# Use the shell executor on the Windows machine so the job runs in the host PowerShell environment diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index afbb38c..0000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "name": "ImageCatalog Avalonia", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build ImageCatalog Avalonia", - "program": "${workspaceFolder:Catalog}/imagecatalog/bin/Debug/net10.0-windows/win-x64/ImageCatalog.exe", - "args": [], - "cwd": "${workspaceFolder:Catalog}/imagecatalog", - "stopAtEntry": false, - "console": "internalConsole" - }, - { - "name": "CatalogLite Avalonia", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build CatalogLite Avalonia", - "program": "${workspaceFolder:Catalog}/CatalogLite/bin/Debug/net10.0/CatalogLite.exe", - "args": [], - "cwd": "${workspaceFolder:Catalog}/CatalogLite", - "stopAtEntry": false, - "console": "internalConsole" - } - ] -} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json deleted file mode 100644 index 791bec6..0000000 --- a/.vscode/tasks.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "version": "2.0.0", - "tasks": [ - { - "label": "build ImageCatalog Avalonia", - "type": "process", - "command": "dotnet", - "args": [ - "build", - "${workspaceFolder:Catalog}/imagecatalog/ImageCatalog 2.csproj", - "--configuration", - "Debug" - ], - "problemMatcher": "$msCompile", - "group": "build" - }, - { - "label": "build CatalogLite Avalonia", - "type": "process", - "command": "dotnet", - "args": [ - "build", - "${workspaceFolder:Catalog}/CatalogLite/CatalogLite.csproj", - "--configuration", - "Debug" - ], - "problemMatcher": "$msCompile", - "group": "build" - } - ] -} \ No newline at end of file diff --git a/Catalog.Communication/Abstractions/IRaceUploadCommunicationClient.cs b/Catalog.Communication/Abstractions/IRaceUploadCommunicationClient.cs deleted file mode 100644 index 26d1b76..0000000 --- a/Catalog.Communication/Abstractions/IRaceUploadCommunicationClient.cs +++ /dev/null @@ -1,40 +0,0 @@ -using Catalog.Communication.Models; - -namespace Catalog.Communication.Abstractions; - -public interface IRaceUploadCommunicationClient -{ - Task LoginAdminAsync(AdminLoginRequest request, CancellationToken cancellationToken = default); - - Task LogoutAdminAsync(CancellationToken cancellationToken = default); - - Task UploadRaceImageAsync(RaceImageUploadRequest request, CancellationToken cancellationToken = default); - - Task RemoveRaceImageAsync(RaceImageRemoveRequest request, CancellationToken cancellationToken = default); - - Task UploadRaceFileAsync(RaceFileUploadRequest request, CancellationToken cancellationToken = default); - - Task SaveRaceAsync(RaceSaveRequest request, CancellationToken cancellationToken = default); - - Task CreateRacePointsAsync(long raceId, CancellationToken cancellationToken = default); - - Task IndexRacePointAsync(long pointId, CancellationToken cancellationToken = default); - - Task GetRaceDetailAsync(long raceId, CancellationToken cancellationToken = default); - - Task UploadFileToReceiverAsync(ReceiveFileUploadRequest request, CancellationToken cancellationToken = default); - - Task ExecuteGaraCommandAsync(IReadOnlyDictionary formFields, CancellationToken cancellationToken = default); - - Task ExecuteAdminPhotoCommandAsync(AdminPhotoEndpoint endpoint, IReadOnlyDictionary formFields, CancellationToken cancellationToken = default); - - Task ExecutePublicLogonAsync(IReadOnlyDictionary formFields, CancellationToken cancellationToken = default); - - Task ExecuteUsersAsync(HttpMethod method, IReadOnlyDictionary? formFields = null, CancellationToken cancellationToken = default); - - Task ExecuteFoto2Async(HttpMethod method, IReadOnlyDictionary? formFields = null, CancellationToken cancellationToken = default); - - Task DownloadThumbnailAsync(string filename, long? idFoto = null, CancellationToken cancellationToken = default); - - Task DownloadOriginalAsync(string filename, long? idFoto = null, CancellationToken cancellationToken = default); -} diff --git a/Catalog.Communication/Catalog.Communication.csproj b/Catalog.Communication/Catalog.Communication.csproj deleted file mode 100644 index 8b3c8df..0000000 --- a/Catalog.Communication/Catalog.Communication.csproj +++ /dev/null @@ -1,17 +0,0 @@ - - - - net10.0 - Library - enable - enable - - - - - - - - - - diff --git a/Catalog.Communication/CatalogCommunicationOptions.cs b/Catalog.Communication/CatalogCommunicationOptions.cs deleted file mode 100644 index 6044d2e..0000000 --- a/Catalog.Communication/CatalogCommunicationOptions.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Catalog.Communication; - -public sealed class CatalogCommunicationOptions -{ - public required Uri BaseUri { get; set; } - - public string AdminPageBasePath { get; set; } = "admin/pg"; - - public string ReceiveFilePath { get; set; } = "ReceiveFile.abl"; - - public TimeSpan RequestTimeout { get; set; } = TimeSpan.FromSeconds(30); - - public int RetryCount { get; set; } = 2; - - public TimeSpan RetryBaseDelay { get; set; } = TimeSpan.FromMilliseconds(250); -} diff --git a/Catalog.Communication/DependencyInjection/CatalogCommunicationServiceCollectionExtensions.cs b/Catalog.Communication/DependencyInjection/CatalogCommunicationServiceCollectionExtensions.cs deleted file mode 100644 index bb5a5b1..0000000 --- a/Catalog.Communication/DependencyInjection/CatalogCommunicationServiceCollectionExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Net; -using Catalog.Communication.Abstractions; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.Extensions.Options; - -namespace Catalog.Communication.DependencyInjection; - -public static class CatalogCommunicationServiceCollectionExtensions -{ - public static IServiceCollection AddCatalogCommunication(this IServiceCollection services, Action configure) - { - ArgumentNullException.ThrowIfNull(services); - ArgumentNullException.ThrowIfNull(configure); - - services - .AddOptions() - .Configure(configure) - .Validate(o => o.BaseUri is not null, "CatalogCommunicationOptions.BaseUri is required.") - .Validate(o => !string.IsNullOrWhiteSpace(o.AdminPageBasePath), "AdminPageBasePath is required.") - .Validate(o => !string.IsNullOrWhiteSpace(o.ReceiveFilePath), "ReceiveFilePath is required.") - .Validate(o => o.RequestTimeout > TimeSpan.Zero, "RequestTimeout must be greater than zero.") - .Validate(o => o.RetryCount >= 0 && o.RetryCount <= 10, "RetryCount must be between 0 and 10.") - .Validate(o => o.RetryBaseDelay > TimeSpan.Zero, "RetryBaseDelay must be greater than zero."); - - services.TryAddSingleton(); - - // Create the HttpClient only when the communication client is requested. - // This avoids constructing the DefaultHttpClientFactory (and its background cleanup timer) - // if the race-upload feature is never used. - services.AddTransient(sp => - { - var options = sp.GetRequiredService>().Value; - var logger = sp.GetService>() ?? NullLogger.Instance; - var cookieContainer = sp.GetRequiredService(); - - var handler = new HttpClientHandler - { - UseCookies = true, - CookieContainer = cookieContainer, - AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli, - }; - - var httpClient = new HttpClient(handler, disposeHandler: true) - { - BaseAddress = options.BaseUri, - Timeout = options.RequestTimeout, - }; - - return new RaceUploadCommunicationClient(httpClient, sp.GetRequiredService>(), logger); - }); - - return services; - } -} diff --git a/Catalog.Communication/Models/AdminLoginRequest.cs b/Catalog.Communication/Models/AdminLoginRequest.cs deleted file mode 100644 index 170faf4..0000000 --- a/Catalog.Communication/Models/AdminLoginRequest.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Catalog.Communication.Models; - -public sealed class AdminLoginRequest -{ - public required string Login { get; init; } - - public required string Password { get; init; } - - public string Command { get; init; } = "check"; -} diff --git a/Catalog.Communication/Models/AdminPhotoEndpoint.cs b/Catalog.Communication/Models/AdminPhotoEndpoint.cs deleted file mode 100644 index b1aad98..0000000 --- a/Catalog.Communication/Models/AdminPhotoEndpoint.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Catalog.Communication.Models; - -public enum AdminPhotoEndpoint -{ - Foto = 0, - TipoGara = 1, - LogFoto = 2, -} diff --git a/Catalog.Communication/Models/MediaFileResponse.cs b/Catalog.Communication/Models/MediaFileResponse.cs deleted file mode 100644 index 2bdfecd..0000000 --- a/Catalog.Communication/Models/MediaFileResponse.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System.Net; - -namespace Catalog.Communication.Models; - -public sealed class MediaFileResponse -{ - public required HttpStatusCode StatusCode { get; init; } - - public required byte[] Content { get; init; } - - public string? ContentType { get; init; } - - public string? FileName { get; init; } - - public required IReadOnlyDictionary> Headers { get; init; } -} diff --git a/Catalog.Communication/Models/RaceFileUploadRequest.cs b/Catalog.Communication/Models/RaceFileUploadRequest.cs deleted file mode 100644 index 83cfb3b..0000000 --- a/Catalog.Communication/Models/RaceFileUploadRequest.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Catalog.Communication.Models; - -public sealed class RaceFileUploadRequest -{ - public int? CodFile { get; init; } - - public long? Id { get; init; } - - public required string FileName { get; init; } - - public required Stream FileStream { get; init; } - - public string FormFieldName { get; init; } = "fileName"; - - public string? ContentType { get; init; } -} diff --git a/Catalog.Communication/Models/RaceImageRemoveRequest.cs b/Catalog.Communication/Models/RaceImageRemoveRequest.cs deleted file mode 100644 index 0e9698a..0000000 --- a/Catalog.Communication/Models/RaceImageRemoveRequest.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace Catalog.Communication.Models; - -public sealed class RaceImageRemoveRequest -{ - public required long Id { get; init; } - - public required int CodImage { get; init; } - - public int? TotImgNumber { get; init; } -} diff --git a/Catalog.Communication/Models/RaceImageUploadRequest.cs b/Catalog.Communication/Models/RaceImageUploadRequest.cs deleted file mode 100644 index ee049f1..0000000 --- a/Catalog.Communication/Models/RaceImageUploadRequest.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Catalog.Communication.Models; - -public sealed class RaceImageUploadRequest -{ - public required long Id { get; init; } - - public required int CodImage { get; init; } - - public int? TotImgNumber { get; init; } - - public required string FileName { get; init; } - - public required Stream FileStream { get; init; } - - public string FormFieldName { get; init; } = "imgFile"; - - public string? ContentType { get; init; } -} diff --git a/Catalog.Communication/Models/RaceSaveRequest.cs b/Catalog.Communication/Models/RaceSaveRequest.cs deleted file mode 100644 index 88293a6..0000000 --- a/Catalog.Communication/Models/RaceSaveRequest.cs +++ /dev/null @@ -1,26 +0,0 @@ -namespace Catalog.Communication.Models; - -public sealed class RaceSaveRequest -{ - public long IdGara { get; init; } - - public required string Description { get; init; } - - public required DateOnly StartDate { get; init; } - - public DateOnly? EndDate { get; init; } - - public required long TipoGaraId { get; init; } - - public int EventoInLinea { get; init; } - - public int TipoIndicizzazione { get; init; } - - public int FreeEvent { get; init; } - - public string? PathBase { get; init; } - - public string? Localita { get; init; } - - public long? CodGara { get; init; } -} diff --git a/Catalog.Communication/Models/RawEndpointResponse.cs b/Catalog.Communication/Models/RawEndpointResponse.cs deleted file mode 100644 index 0f0f36a..0000000 --- a/Catalog.Communication/Models/RawEndpointResponse.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Net; - -namespace Catalog.Communication.Models; - -public sealed class RawEndpointResponse -{ - public required HttpStatusCode StatusCode { get; init; } - - public required string Body { get; init; } - - public required IReadOnlyDictionary> Headers { get; init; } -} diff --git a/Catalog.Communication/Models/ReceiveFileUploadRequest.cs b/Catalog.Communication/Models/ReceiveFileUploadRequest.cs deleted file mode 100644 index 07b0b85..0000000 --- a/Catalog.Communication/Models/ReceiveFileUploadRequest.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace Catalog.Communication.Models; - -public sealed class ReceiveFileUploadRequest -{ - public required string FileName { get; init; } - - public required Stream FileStream { get; init; } - - public required string DestinationPath { get; init; } - - public bool OverwriteRemoteFile { get; init; } - - public int? BufferSize { get; init; } - - public string? ContentType { get; init; } -} diff --git a/Catalog.Communication/Models/UploadFileResponse.cs b/Catalog.Communication/Models/UploadFileResponse.cs deleted file mode 100644 index e68e400..0000000 --- a/Catalog.Communication/Models/UploadFileResponse.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Catalog.Communication.Models; - -public sealed class UploadFileResponse -{ - [JsonPropertyName("result")] - public bool Result { get; init; } - - [JsonPropertyName("message")] - public string Message { get; init; } = string.Empty; - - [JsonPropertyName("fileName")] - public string FileName { get; init; } = string.Empty; - - [JsonPropertyName("fileNameLink")] - public string FileNameLink { get; init; } = string.Empty; -} diff --git a/Catalog.Communication/Models/UploadImageResponse.cs b/Catalog.Communication/Models/UploadImageResponse.cs deleted file mode 100644 index 5ecc353..0000000 --- a/Catalog.Communication/Models/UploadImageResponse.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Text.Json.Serialization; - -namespace Catalog.Communication.Models; - -public sealed class UploadImageResponse -{ - [JsonPropertyName("result")] - public bool Result { get; init; } - - [JsonPropertyName("message")] - public string Message { get; init; } = string.Empty; - - [JsonPropertyName("imgPath")] - public string ImgPath { get; init; } = string.Empty; -} diff --git a/Catalog.Communication/RaceUploadCommunicationClient.cs b/Catalog.Communication/RaceUploadCommunicationClient.cs deleted file mode 100644 index 9657dfe..0000000 --- a/Catalog.Communication/RaceUploadCommunicationClient.cs +++ /dev/null @@ -1,622 +0,0 @@ -using System.Net; -using System.Net.Http.Headers; -using System.Text; -using System.Text.Json; -using System.Globalization; -using Catalog.Communication.Abstractions; -using Catalog.Communication.Models; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; - -namespace Catalog.Communication; - -public sealed class RaceUploadCommunicationClient : IRaceUploadCommunicationClient, IDisposable -{ - private const string AdminMenuPath = "admin/menu/Menu4.abl"; - private const string PublicLogonPath = "Logon.abl"; - private const string UsersPath = "Users.abl"; - private const string Foto2Path = "Foto2.abl"; - private const string ThumbnailPath = "foto"; - private const string OriginalPath = "fotoOriginali"; - - private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) - { - PropertyNameCaseInsensitive = true, - }; - - private readonly HttpClient _httpClient; - private readonly ILogger _logger; - private readonly IOptions _options; - private bool _disposed; - - public RaceUploadCommunicationClient( - HttpClient httpClient, - IOptions options, - ILogger logger) - { - _httpClient = httpClient; - _options = options; - _logger = logger; - } - - public void Dispose() - { - if (_disposed) - { - return; - } - - _httpClient.Dispose(); - _disposed = true; - GC.SuppressFinalize(this); - } - - public Task LoginAdminAsync(AdminLoginRequest request, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(request); - - var formFields = new Dictionary - { - ["login"] = request.Login, - ["pwd"] = request.Password, - ["cmdIU"] = request.Command, - }; - - return PostFormAsync(AdminMenuPath, formFields, "admin-login", cancellationToken); - } - - public Task LogoutAdminAsync(CancellationToken cancellationToken = default) - { - var formFields = new Dictionary - { - ["cmdIU"] = "login", - }; - - return PostFormAsync(AdminMenuPath, formFields, "admin-logout", cancellationToken); - } - - public Task UploadRaceImageAsync(RaceImageUploadRequest request, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(request); - - return PostMultipartAndParseUploadAsync( - GetAdminPagePath("Gara"), - "gara-upload-image", - request.FileStream, - request.FileName, - request.FormFieldName, - request.ContentType, - static fields => - { - fields["cmd"] = "loadImg"; - }, - new Dictionary - { - ["id"] = request.Id.ToString(System.Globalization.CultureInfo.InvariantCulture), - ["codImage"] = request.CodImage.ToString(System.Globalization.CultureInfo.InvariantCulture), - ["totImgNumber"] = request.TotImgNumber?.ToString(System.Globalization.CultureInfo.InvariantCulture), - }, - cancellationToken); - } - - public Task RemoveRaceImageAsync(RaceImageRemoveRequest request, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(request); - - var fields = new Dictionary - { - ["cmd"] = "removeImg", - ["id"] = request.Id.ToString(System.Globalization.CultureInfo.InvariantCulture), - ["codImage"] = request.CodImage.ToString(System.Globalization.CultureInfo.InvariantCulture), - ["totImgNumber"] = request.TotImgNumber?.ToString(System.Globalization.CultureInfo.InvariantCulture), - }; - - return PostFormAndParseUploadAsync(GetAdminPagePath("Gara"), fields, "gara-remove-image", cancellationToken); - } - - public Task UploadRaceFileAsync(RaceFileUploadRequest request, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(request); - - return PostMultipartAndParseUploadAsync( - GetAdminPagePath("Gara"), - "gara-upload-file", - request.FileStream, - request.FileName, - request.FormFieldName, - request.ContentType, - static fields => - { - fields["cmd"] = "saveFile"; - }, - new Dictionary - { - ["codFile"] = request.CodFile?.ToString(System.Globalization.CultureInfo.InvariantCulture), - ["id"] = request.Id?.ToString(System.Globalization.CultureInfo.InvariantCulture), - }, - cancellationToken); - } - - public Task SaveRaceAsync(RaceSaveRequest request, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(request); - - var formFields = new Dictionary - { - ["cmd"] = "asq", - ["act"] = "save", - ["id_gara"] = request.IdGara.ToString(CultureInfo.InvariantCulture), - ["descrizione"] = request.Description, - ["dataGaraInizio"] = request.StartDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), - ["dataGaraFine"] = (request.EndDate ?? request.StartDate).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture), - ["id_tipoGara"] = request.TipoGaraId.ToString(CultureInfo.InvariantCulture), - ["flgEventoInLinea"] = request.EventoInLinea.ToString(CultureInfo.InvariantCulture), - ["flgTipoIndex"] = request.TipoIndicizzazione.ToString(CultureInfo.InvariantCulture), - ["flgFree"] = request.FreeEvent.ToString(CultureInfo.InvariantCulture), - ["pathBase"] = request.PathBase, - ["localita"] = request.Localita, - ["codGara"] = request.CodGara?.ToString(CultureInfo.InvariantCulture), - }; - - return PostFormAsync(GetAdminPagePath("Gara"), formFields, "gara-save", cancellationToken); - } - - public Task CreateRacePointsAsync(long raceId, CancellationToken cancellationToken = default) - { - var formFields = new Dictionary - { - ["cmd"] = "creaPuntiFoto", - ["id_gara"] = raceId.ToString(CultureInfo.InvariantCulture), - }; - - return PostFormAsync(GetAdminPagePath("Gara"), formFields, "gara-create-points", cancellationToken); - } - - public Task IndexRacePointAsync(long pointId, CancellationToken cancellationToken = default) - { - var formFields = new Dictionary - { - ["cmd"] = "indexFoto", - ["id_puntoFotoIdx"] = pointId.ToString(CultureInfo.InvariantCulture), - }; - - return PostFormAsync(GetAdminPagePath("Gara"), formFields, "gara-index-point", cancellationToken); - } - - public Task GetRaceDetailAsync(long raceId, CancellationToken cancellationToken = default) - { - var formFields = new Dictionary - { - ["cmd"] = "search", - ["id_gara"] = raceId.ToString(CultureInfo.InvariantCulture), - }; - - return PostFormAsync(GetAdminPagePath("Gara"), formFields, "gara-detail", cancellationToken); - } - - public async Task UploadFileToReceiverAsync(ReceiveFileUploadRequest request, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(request); - ArgumentException.ThrowIfNullOrWhiteSpace(request.FileName); - ArgumentException.ThrowIfNullOrWhiteSpace(request.DestinationPath); - ArgumentNullException.ThrowIfNull(request.FileStream); - - var payload = await ReadAllBytesAsync(request.FileStream, cancellationToken).ConfigureAwait(false); - var query = new Dictionary - { - ["name"] = request.FileName, - ["path"] = request.DestinationPath, - ["overwriteRemoteFile"] = request.OverwriteRemoteFile ? "true" : "false", - ["bs"] = request.BufferSize?.ToString(CultureInfo.InvariantCulture), - }; - - var path = AppendQuery(GetReceiveFilePath(), query); - - return await ExecuteWithResilienceAsync( - () => - { - var byteContent = new ByteArrayContent(payload); - byteContent.Headers.ContentType = new MediaTypeHeaderValue(request.ContentType ?? "application/octet-stream"); - - return new HttpRequestMessage(HttpMethod.Post, path) - { - Content = byteContent, - }; - }, - ToRawResponseAsync, - "receiver-upload", - cancellationToken).ConfigureAwait(false); - } - - public Task ExecuteGaraCommandAsync(IReadOnlyDictionary formFields, CancellationToken cancellationToken = default) - { - return PostFormAsync(GetAdminPagePath("Gara"), formFields, "gara-command", cancellationToken); - } - - public Task ExecuteAdminPhotoCommandAsync(AdminPhotoEndpoint endpoint, IReadOnlyDictionary formFields, CancellationToken cancellationToken = default) - { - var path = endpoint switch - { - AdminPhotoEndpoint.Foto => GetAdminPagePath("Foto"), - AdminPhotoEndpoint.TipoGara => GetAdminPagePath("TipoGara"), - AdminPhotoEndpoint.LogFoto => GetAdminPagePath("LogFoto"), - _ => throw new ArgumentOutOfRangeException(nameof(endpoint), endpoint, "Unsupported endpoint."), - }; - - return PostFormAsync(path, formFields, $"photo-admin-{endpoint}", cancellationToken); - } - - public Task ExecutePublicLogonAsync(IReadOnlyDictionary formFields, CancellationToken cancellationToken = default) - { - return PostFormAsync(PublicLogonPath, formFields, "public-logon", cancellationToken); - } - - public Task ExecuteUsersAsync(HttpMethod method, IReadOnlyDictionary? formFields = null, CancellationToken cancellationToken = default) - { - return SendCommandAsync(method, UsersPath, formFields, "public-users", cancellationToken); - } - - public Task ExecuteFoto2Async(HttpMethod method, IReadOnlyDictionary? formFields = null, CancellationToken cancellationToken = default) - { - return SendCommandAsync(method, Foto2Path, formFields, "public-foto2", cancellationToken); - } - - public Task DownloadThumbnailAsync(string filename, long? idFoto = null, CancellationToken cancellationToken = default) - { - ArgumentException.ThrowIfNullOrWhiteSpace(filename); - return DownloadFileAsync(ThumbnailPath, filename, idFoto, "media-thumbnail", cancellationToken); - } - - public Task DownloadOriginalAsync(string filename, long? idFoto = null, CancellationToken cancellationToken = default) - { - ArgumentException.ThrowIfNullOrWhiteSpace(filename); - return DownloadFileAsync(OriginalPath, filename, idFoto, "media-original", cancellationToken); - } - - private Task SendCommandAsync(HttpMethod method, string path, IReadOnlyDictionary? formFields, string operationName, CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(method); - - if (method == HttpMethod.Get) - { - var relativePath = AppendQuery(path, formFields); - return GetAsync(relativePath, operationName, cancellationToken); - } - - if (method == HttpMethod.Post) - { - return PostFormAsync(path, formFields ?? new Dictionary(), operationName, cancellationToken); - } - - throw new NotSupportedException($"Only GET and POST are supported. Requested method: {method}."); - } - - private Task GetAsync(string relativePath, string operationName, CancellationToken cancellationToken) - { - return ExecuteWithResilienceAsync( - () => new HttpRequestMessage(HttpMethod.Get, relativePath), - ToRawResponseAsync, - operationName, - cancellationToken); - } - - private Task PostFormAsync(string relativePath, IReadOnlyDictionary formFields, string operationName, CancellationToken cancellationToken) - { - return ExecuteWithResilienceAsync( - () => - { - var request = new HttpRequestMessage(HttpMethod.Post, relativePath) - { - Content = BuildFormContent(formFields), - }; - - return request; - }, - ToRawResponseAsync, - operationName, - cancellationToken); - } - - private Task PostFormAndParseUploadAsync(string relativePath, IReadOnlyDictionary formFields, string operationName, CancellationToken cancellationToken) - { - return ExecuteWithResilienceAsync( - () => - { - var request = new HttpRequestMessage(HttpMethod.Post, relativePath) - { - Content = BuildFormContent(formFields), - }; - - return request; - }, - async (response, token) => - { - var raw = await ToRawResponseAsync(response, token).ConfigureAwait(false); - return ParseSingleItemArray(raw.Body); - }, - operationName, - cancellationToken); - } - - private async Task PostMultipartAndParseUploadAsync( - string relativePath, - string operationName, - Stream fileStream, - string fileName, - string formFieldName, - string? contentType, - Action> configureRequiredFields, - IReadOnlyDictionary optionalFields, - CancellationToken cancellationToken) - { - ArgumentNullException.ThrowIfNull(fileStream); - ArgumentException.ThrowIfNullOrWhiteSpace(fileName); - ArgumentException.ThrowIfNullOrWhiteSpace(formFieldName); - - var payload = await ReadAllBytesAsync(fileStream, cancellationToken).ConfigureAwait(false); - - return await ExecuteWithResilienceAsync( - () => - { - var multipart = new MultipartFormDataContent(); - var fields = new Dictionary(); - configureRequiredFields(fields); - - foreach (var field in fields) - { - if (string.IsNullOrWhiteSpace(field.Value)) - { - continue; - } - - multipart.Add(new StringContent(field.Value, Encoding.UTF8), field.Key); - } - - foreach (var field in optionalFields) - { - if (string.IsNullOrWhiteSpace(field.Value)) - { - continue; - } - - multipart.Add(new StringContent(field.Value, Encoding.UTF8), field.Key); - } - - var fileContent = new ByteArrayContent(payload); - fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType ?? "application/octet-stream"); - multipart.Add(fileContent, formFieldName, fileName); - - return new HttpRequestMessage(HttpMethod.Post, relativePath) - { - Content = multipart, - }; - }, - async (response, token) => - { - var raw = await ToRawResponseAsync(response, token).ConfigureAwait(false); - return ParseSingleItemArray(raw.Body); - }, - operationName, - cancellationToken).ConfigureAwait(false); - } - - private Task DownloadFileAsync(string basePath, string filename, long? idFoto, string operationName, CancellationToken cancellationToken) - { - var escapedFileName = Uri.EscapeDataString(filename); - var relativePath = idFoto.HasValue - ? $"{basePath}/{escapedFileName}?id_foto={idFoto.Value.ToString(System.Globalization.CultureInfo.InvariantCulture)}" - : $"{basePath}/{escapedFileName}"; - - return ExecuteWithResilienceAsync( - () => new HttpRequestMessage(HttpMethod.Get, relativePath), - async (response, token) => - { - var content = await response.Content.ReadAsByteArrayAsync(token).ConfigureAwait(false); - return new MediaFileResponse - { - StatusCode = response.StatusCode, - Content = content, - ContentType = response.Content.Headers.ContentType?.MediaType, - FileName = response.Content.Headers.ContentDisposition?.FileNameStar ?? response.Content.Headers.ContentDisposition?.FileName, - Headers = BuildHeaders(response), - }; - }, - operationName, - cancellationToken); - } - - private async Task ExecuteWithResilienceAsync( - Func requestFactory, - Func> responseFactory, - string operationName, - CancellationToken cancellationToken) - { - var options = _options.Value; - Exception? lastException = null; - - for (var attempt = 0; attempt <= options.RetryCount; attempt++) - { - using var request = requestFactory(); - using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - timeoutCts.CancelAfter(options.RequestTimeout); - - HttpResponseMessage? response = null; - - try - { - response = await _httpClient - .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeoutCts.Token) - .ConfigureAwait(false); - - if (IsRetryableStatusCode(response.StatusCode) && attempt < options.RetryCount) - { - _logger.LogWarning( - "Operation {OperationName} received retryable status code {StatusCode} at attempt {Attempt}/{MaxAttempts}.", - operationName, - (int)response.StatusCode, - attempt + 1, - options.RetryCount + 1); - - await DelayBeforeRetryAsync(options, attempt, cancellationToken).ConfigureAwait(false); - continue; - } - - return await responseFactory(response, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested) - { - lastException = ex; - - if (attempt < options.RetryCount) - { - _logger.LogWarning(ex, "Operation {OperationName} timed out at attempt {Attempt}/{MaxAttempts}.", operationName, attempt + 1, options.RetryCount + 1); - await DelayBeforeRetryAsync(options, attempt, cancellationToken).ConfigureAwait(false); - continue; - } - - _logger.LogError(ex, "Operation {OperationName} timed out after {MaxAttempts} attempts.", operationName, options.RetryCount + 1); - throw; - } - catch (HttpRequestException ex) - { - lastException = ex; - - if (attempt < options.RetryCount) - { - _logger.LogWarning(ex, "Operation {OperationName} failed with transient HTTP error at attempt {Attempt}/{MaxAttempts}.", operationName, attempt + 1, options.RetryCount + 1); - await DelayBeforeRetryAsync(options, attempt, cancellationToken).ConfigureAwait(false); - continue; - } - - _logger.LogError(ex, "Operation {OperationName} failed with HTTP error after {MaxAttempts} attempts.", operationName, options.RetryCount + 1); - throw; - } - catch (Exception ex) - { - _logger.LogError(ex, "Operation {OperationName} failed with unexpected error at attempt {Attempt}/{MaxAttempts}.", operationName, attempt + 1, options.RetryCount + 1); - throw; - } - finally - { - response?.Dispose(); - } - } - - throw new HttpRequestException($"Operation '{operationName}' failed after {options.RetryCount + 1} attempts.", lastException); - } - - private static bool IsRetryableStatusCode(HttpStatusCode statusCode) - { - return statusCode is HttpStatusCode.RequestTimeout - or HttpStatusCode.TooManyRequests - or HttpStatusCode.BadGateway - or HttpStatusCode.ServiceUnavailable - or HttpStatusCode.GatewayTimeout - or HttpStatusCode.InternalServerError; - } - - private static async Task DelayBeforeRetryAsync(CatalogCommunicationOptions options, int attempt, CancellationToken cancellationToken) - { - var delay = TimeSpan.FromMilliseconds(options.RetryBaseDelay.TotalMilliseconds * Math.Pow(2, attempt)); - await Task.Delay(delay, cancellationToken).ConfigureAwait(false); - } - - private static FormUrlEncodedContent BuildFormContent(IReadOnlyDictionary formFields) - { - var pairs = formFields - .Where(kvp => !string.IsNullOrWhiteSpace(kvp.Value)) - .Select(kvp => new KeyValuePair(kvp.Key, kvp.Value!)); - - return new FormUrlEncodedContent(pairs); - } - - private static string AppendQuery(string path, IReadOnlyDictionary? query) - { - if (query is null || query.Count == 0) - { - return path; - } - - var encodedPairs = query - .Where(kvp => !string.IsNullOrWhiteSpace(kvp.Value)) - .Select(kvp => $"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value!)}") - .ToArray(); - - if (encodedPairs.Length == 0) - { - return path; - } - - var separator = path.Contains('?', StringComparison.Ordinal) ? "&" : "?"; - return string.Concat(path, separator, string.Join("&", encodedPairs)); - } - - private static async Task ToRawResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken) - { - var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - - return new RawEndpointResponse - { - StatusCode = response.StatusCode, - Body = body, - Headers = BuildHeaders(response), - }; - } - - private static IReadOnlyDictionary> BuildHeaders(HttpResponseMessage response) - { - var headers = new Dictionary>(StringComparer.OrdinalIgnoreCase); - - foreach (var header in response.Headers) - { - headers[header.Key] = header.Value.ToArray(); - } - - foreach (var header in response.Content.Headers) - { - headers[header.Key] = header.Value.ToArray(); - } - - return headers; - } - - private static TUpload? ParseSingleItemArray(string json) - { - if (string.IsNullOrWhiteSpace(json)) - { - return default; - } - - var items = JsonSerializer.Deserialize>(json, JsonOptions); - return items is { Count: > 0 } ? items[0] : default; - } - - private static async Task ReadAllBytesAsync(Stream stream, CancellationToken cancellationToken) - { - if (stream.CanSeek) - { - stream.Position = 0; - } - - using var memoryStream = new MemoryStream(); - await stream.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false); - return memoryStream.ToArray(); - } - - private string GetAdminPagePath(string pageName) - { - var basePath = _options.Value.AdminPageBasePath.Trim('/'); - return $"{basePath}/{pageName}.abl"; - } - - private string GetReceiveFilePath() - { - var value = _options.Value.ReceiveFilePath; - if (string.IsNullOrWhiteSpace(value)) - { - return "ReceiveFile.abl"; - } - - return value.Trim(); - } -} diff --git a/Catalog.code-workspace b/Catalog.code-workspace deleted file mode 100644 index 93418a7..0000000 --- a/Catalog.code-workspace +++ /dev/null @@ -1,17 +0,0 @@ -{ - "folders": [ - { - "path": "." - }, - { - "path": "../AIFotoONLUS" - }, - { - "path": "../../various/regalamiunsorriso" - } - ], - "settings": { - "commentTranslate.hover.enabled": false, - "github.copilot.chat.otel.dbSpanExporter.enabled": true - } -} \ No newline at end of file diff --git a/Catalog.sln b/Catalog.sln new file mode 100644 index 0000000..a5fd6f7 --- /dev/null +++ b/Catalog.sln @@ -0,0 +1,87 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 18 +VisualStudioVersion = 18.2.11415.280 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ImageCatalog 2", "imagecatalog\ImageCatalog 2.csproj", "{3F1E23DB-435E-0590-1EF5-735E898DBA3C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Libraries", "Libraries", "{A3D50937-74F6-4DC8-8D89-B534B484C0F9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MaddoShared", "MaddoShared\MaddoShared.csproj", "{AEBFE9E3-277C-4A7B-8448-145D1B11998B}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{5F0BEF23-B1EA-4100-A772-DC455D40B1C1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MaddoShared.Tests", "MaddoShared.Tests\MaddoShared.Tests.csproj", "{59952BE8-20B4-4BF2-9367-705F41395265}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MaddoShared.Benchmarks", "MaddoShared.Benchmarks\MaddoShared.Benchmarks.csproj", "{07499348-8C15-4DCC-8316-4AD121A43C38}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x64.ActiveCfg = Debug|Any CPU + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x64.Build.0 = Debug|Any CPU + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x86.ActiveCfg = Debug|x86 + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Debug|x86.Build.0 = Debug|x86 + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Release|Any CPU.Build.0 = Release|Any CPU + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Release|x64.ActiveCfg = Release|x64 + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Release|x64.Build.0 = Release|x64 + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Release|x86.ActiveCfg = Release|x86 + {3F1E23DB-435E-0590-1EF5-735E898DBA3C}.Release|x86.Build.0 = Release|x86 + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Debug|x64.ActiveCfg = Debug|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Debug|x64.Build.0 = Debug|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Debug|x86.ActiveCfg = Debug|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Debug|x86.Build.0 = Debug|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Release|Any CPU.Build.0 = Release|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Release|x64.ActiveCfg = Release|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Release|x64.Build.0 = Release|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Release|x86.ActiveCfg = Release|Any CPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B}.Release|x86.Build.0 = Release|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Debug|Any CPU.Build.0 = Debug|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Debug|x64.ActiveCfg = Debug|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Debug|x64.Build.0 = Debug|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Debug|x86.ActiveCfg = Debug|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Debug|x86.Build.0 = Debug|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Release|Any CPU.ActiveCfg = Release|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Release|Any CPU.Build.0 = Release|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Release|x64.ActiveCfg = Release|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Release|x64.Build.0 = Release|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Release|x86.ActiveCfg = Release|Any CPU + {59952BE8-20B4-4BF2-9367-705F41395265}.Release|x86.Build.0 = Release|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Debug|Any CPU.Build.0 = Debug|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Debug|x64.ActiveCfg = Debug|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Debug|x64.Build.0 = Debug|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Debug|x86.ActiveCfg = Debug|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Debug|x86.Build.0 = Debug|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Release|Any CPU.ActiveCfg = Release|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Release|Any CPU.Build.0 = Release|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Release|x64.ActiveCfg = Release|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Release|x64.Build.0 = Release|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Release|x86.ActiveCfg = Release|Any CPU + {07499348-8C15-4DCC-8316-4AD121A43C38}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {AEBFE9E3-277C-4A7B-8448-145D1B11998B} = {A3D50937-74F6-4DC8-8D89-B534B484C0F9} + {59952BE8-20B4-4BF2-9367-705F41395265} = {5F0BEF23-B1EA-4100-A772-DC455D40B1C1} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {0E3ABC63-8601-4DAC-AFEA-33F3E8E36757} + EndGlobalSection +EndGlobal diff --git a/Catalog.slnx b/Catalog.slnx deleted file mode 100644 index e3c90bb..0000000 --- a/Catalog.slnx +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/CatalogLib/CatalogLib.csproj b/CatalogLib/CatalogLib.csproj new file mode 100644 index 0000000..631add3 --- /dev/null +++ b/CatalogLib/CatalogLib.csproj @@ -0,0 +1,196 @@ + + + + + Debug + AnyCPU + {D27ACCF2-80FC-4DE8-AEB8-351FF076E6D5} + Library + Properties + CatalogLib + CatalogLib + v4.8 + 512 + SAK + SAK + SAK + SAK + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + + + + ..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll + + + ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + True + + + ..\packages\SixLabors.Core.1.0.0-beta0002\lib\netstandard1.1\SixLabors.Core.dll + + + ..\packages\SixLabors.Fonts.1.0.0-beta0001\lib\netstandard1.3\SixLabors.Fonts.dll + + + ..\packages\SixLabors.ImageSharp.1.0.0-beta0001\lib\netstandard1.3\SixLabors.ImageSharp.dll + + + ..\packages\SixLabors.ImageSharp.Drawing.1.0.0-beta0001\lib\netstandard1.1\SixLabors.ImageSharp.Drawing.dll + + + ..\packages\SixLabors.Shapes.1.0.0-beta0001\lib\netstandard1.1\SixLabors.Shapes.dll + + + ..\packages\SixLabors.Shapes.Text.1.0.0-beta0001\lib\netstandard1.1\SixLabors.Shapes.Text.dll + + + + ..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll + + + ..\packages\System.Buffers.4.4.0\lib\netstandard1.1\System.Buffers.dll + + + ..\packages\System.Collections.Immutable.1.4.0\lib\portable-net45+win8+wp8+wpa81\System.Collections.Immutable.dll + + + + ..\packages\System.Console.4.3.0\lib\net46\System.Console.dll + + + + ..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll + + + + ..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll + + + ..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll + + + + ..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll + + + ..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll + + + ..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll + + + ..\packages\System.Memory.4.4.0-preview2-25405-01\lib\netstandard1.0\System.Memory.dll + + + ..\packages\System.Net.Http.4.3.0\lib\net46\System.Net.Http.dll + + + ..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll + + + + ..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.4.0\lib\netstandard1.0\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll + + + ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net46\System.Security.Cryptography.Algorithms.dll + + + ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll + + + ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll + + + ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net46\System.Security.Cryptography.X509Certificates.dll + + + ..\packages\System.ValueTuple.4.4.0\lib\netstandard1.0\System.ValueTuple.dll + + + + + + + + ..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll + + + + + + + + + + + + + + + + {44465926-240d-473f-90b8-786ba4384406} + CatalogVbLib + + + {e93daae6-4aa9-4a45-afb6-58209b3ad3c9} + MaddoLibrary.Base.NET46 + + + + + + + + + + + + + \ No newline at end of file diff --git a/CatalogLib/Class1.cs b/CatalogLib/Class1.cs new file mode 100644 index 0000000..a63356c --- /dev/null +++ b/CatalogLib/Class1.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CatalogLib +{ + public class Class1 + { + } +} diff --git a/CatalogLib/Enums.cs b/CatalogLib/Enums.cs new file mode 100644 index 0000000..831a7c4 --- /dev/null +++ b/CatalogLib/Enums.cs @@ -0,0 +1,41 @@ +namespace CatalogLib +{ + public enum Positions + { + Alto, + Centro, + Basso + } + + public enum Alignments + { + Sinistra, + Centro, + Destra + } + + public enum ResizeModes + { + Bicubic, + Box, + CatmullRom, + Hermite, + Lanczos2, + Lanczos3, + Lanczos5, + Lanczos8, + MitchellNetravali, + NearestNeighbor, + Robidoux, + Spline, + Triangle, + Welch + + } + + public enum ResizeDimensions + { + LatoLungo, + LatoCorto + } +} \ No newline at end of file diff --git a/CatalogLib/IImageProcessor.cs b/CatalogLib/IImageProcessor.cs new file mode 100644 index 0000000..fc08d94 --- /dev/null +++ b/CatalogLib/IImageProcessor.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CatalogLib +{ + public interface IImageProcessor + { + void Start(FileInfo workFile); + } +} diff --git a/CatalogLib/ImageCreator.cs b/CatalogLib/ImageCreator.cs new file mode 100644 index 0000000..869544b --- /dev/null +++ b/CatalogLib/ImageCreator.cs @@ -0,0 +1,618 @@ +using System; +using System.Collections.Generic; +using System.Drawing.Drawing2D; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Drawing; +using System.Drawing.Imaging; +using CatalogVbLib; + +namespace CatalogLib +{ + public class ImageCreator + { + + #region Variabili + + private SinglePicData _singlePicData; + private PicSettings _picSettings; + + private Rotazione _rotation; + + //private bool FotoRuotaADestra = false; + + //private bool FotoRuotaASinistra = false; + private string TempMinText = ""; + //Private crFont1 As Font + + private string _NomeFileChild; + private DirectoryInfo _SourceDir; + private DirectoryInfo _DestDirStart; + + private DirectoryInfo _DestDir; + + private FileInfo _workFile; + private string testoFirma; + private string testoFirmaV; + private int alphaScelta; + private int _dimensioneStandard; + private int _dimensioneStandardMiniatura; + private DateTime dataFoto; + private DateTime dataPartenzaI; + private string testoOrario; + private string testoFirmaPiccola; + private Size thumbSizeSmall; + private Size thumbSizeBig; + private string nomeFileSmall; + private string nomeFileBig; + + private string nomeFileBig2; + private float yPosFromBottom; + private float yPosFromBottom1; + private float yPosFromBottom2; + private float yPosFromBottom3; + private float yPosFromBottom4; + + public string NomeFileChild + { + get { return _NomeFileChild; } + set { _NomeFileChild = value; } + } + + public DirectoryInfo DestDirStart + { + get { return _DestDirStart; } + set { _DestDirStart = value; } + } + + public DirectoryInfo SourceDir + { + get { return _SourceDir; } + set { _SourceDir = value; } + } + + public DirectoryInfo DestDir + { + get { return _DestDir; } + set { _DestDir = value; } + } + + public FileInfo WorkFile + { + get { return _workFile; } + set { _workFile = value; } + } + + #endregion + + //public ImageCreator(string nomeFileChild, DirectoryInfo sourceDir, DirectoryInfo destDir, DirectoryInfo destDirStart) + //{ + // this.NomeFileChild = nomeFileChild; + // SourceDir = sourceDir; + // DestDir = destDir; + // DestDirStart = destDirStart; + // WorkFile = new FileInfo(nomeFileChild); + //} + + //public ImageCreator(string nomeFileChild, DirectoryInfo sourceDir, DirectoryInfo destDir) + //{ + // NomeFileChild = nomeFileChild; + // DestDir = destDir; + //} + + //public ImageCreator(FileInfo file, DirectoryInfo destination) + //{ + // WorkFile = file; + // DestDir = destination; + //} + + public ImageCreator(SinglePicData picData, PicSettings picSettings) + { + + } + + /// + /// Elabora l'immagine + /// + /// Non ne ho idea. ToDo: capire a che serve + public void CreaImmagineThread(string info) + { + + //CatalogLib.PicSettings ps = new CatalogLib.PicSettings(); + + PreparaVariabili(); + + // Workfile deve essere impostato esternamente. ToDo: passarlo come parametro così da potere riutilizzare la classe senza eliminarla e ricrearla + Image g = Image.FromFile(WorkFile.FullName); + + ImpostaTestoExtra(g); + + // Rotazione immagine in base ai dati EXIF + Rotation(ref g); + + // Impostazione del formato + // todo: mettere una selezione più specifica invece di assumere jpg + ImageFormat currentFormat = g.RawFormat; + if (_picSettings.UsaForzaJpg) + { + currentFormat = ImageFormat.Jpeg; + } + + PrepareThumbnailSize(g); + + // big image resolution + var imgOutputBig = new Bitmap(g, thumbSizeBig.Width, thumbSizeBig.Height); + imgOutputBig.SetResolution(g.HorizontalResolution, g.VerticalResolution); + + + if (_picSettings.CreaMiniature) + { + + CreaMiniature(g, imgOutputBig, currentFormat); + } + + + + + + + } + + + private void Rotation(ref System.Drawing.Image g) + { + //FotoRuotaADestra = false; + //FotoRuotaASinistra = false; + _rotation = Rotazione.Normale; + + if (_picSettings.GeneraleRotazioneAutomatica) + { + // ci sono dati exif + if (g.PropertyIdList.Length > 0) + { + ExifReader DatiExif = new ExifReader((Bitmap)g); + + switch (DatiExif.Orientation) + { + case ExifReader.Orientations.BottomLeft: + + break; + case ExifReader.Orientations.BottomRight: + + break; + case ExifReader.Orientations.LeftTop: + + break; + case ExifReader.Orientations.LftBottom: + //FotoRuotaASinistra = true; + _rotation = Rotazione.Sinistra; + break; + case ExifReader.Orientations.RightBottom: + + break; + case ExifReader.Orientations.RightTop: + + break; + case ExifReader.Orientations.TopLeft: + + break; + case ExifReader.Orientations.TopRight: + + break; + } + } + } + + if (_rotation == Rotazione.Sinistra) + { + g.RotateFlip(RotateFlipType.Rotate270FlipNone); + }else + if (_rotation == Rotazione.Destra) + { + g.RotateFlip(RotateFlipType.Rotate90FlipNone); + } + // todo: capire quando va ruotato a destra + } + + /// + /// Aggiunge orario e tempo gara + /// + /// + private void ImpostaTestoExtra(Image g) + { + if (_picSettings.UsaOrarioTestoApplicare || + _picSettings.UsaTempoGaraTestoApplicare || + _picSettings.UsaOrarioMiniatura || + _picSettings.TestoMin || + _picSettings.AggTempoGaraMin || + _picSettings.AggNumTempMin) + { + if (g.PropertyIdList.Length > 0) //ci sono dati exif + { + var datiExix = new ExifReader((Bitmap)g); + dataFoto = datiExix.DateTimeOriginal; + testoFirma = _picSettings.TestoFirmaStart; + testoFirmaV = _picSettings.TestoFirmaStartV; + + if (dataFoto.Year != 1) + { + testoFirmaPiccola = dataFoto.ToShortDateString(); + if (_picSettings.UsaOrarioTestoApplicare) + { + testoFirma = $"{testoFirma} {dataFoto.ToShortDateString()} {dataFoto.ToLongDateString()}"; + testoFirmaV = $"{testoFirmaV} {dataFoto.ToShortDateString()} {dataFoto.ToLongDateString()}"; + //testoFirma = string.Concat(testoFirma, " ", dataFoto.ToShortDateString(), " ", dataFoto.ToLongDateString()); + //testoFirmaV = string.Concat(testoFirmaV, " ", dataFoto.ToShortDateString(), " ", dataFoto.ToLongDateString()); + + } + if (_picSettings.UsaTempoGaraTestoApplicare) + { + //TimeSpan orario = dataPartenzaI - dataFoto; + + string orarioString = (dataPartenzaI - dataFoto).ToString(@"hh\:mm\:ss"); + + testoFirma = $"{testoFirma} {testoOrario} {orarioString}"; + testoFirmaV = $"{testoFirmaV} {testoOrario} {orarioString}"; + + //testoFirma = string.Concat(testoFirma, " ", testoOrario, orario.ToString(@"hh\:mm\:ss")); + //testoFirmaV = string.Concat(testoFirmaV, " ", testoOrario, orario.ToString(@"hh\:mm\:ss")); + } + } + } + } + else + { + testoFirma = _picSettings.TestoFirmaStart; + testoFirmaV = _picSettings.TestoFirmaStartV; + } + } + + /// + /// Preparazione delle variabili a valori di default e caricamento da impostazioni + /// + private void PreparaVariabili() + { + alphaScelta = (int)(255 * (100 - _picSettings.Trasparenza) / 100); + testoFirma = string.Empty; + testoFirmaV = string.Empty; + dataPartenzaI = _picSettings.DataPartenza; + testoOrario = _picSettings.TestoOrario; + if (testoOrario.Length > 0) + { + testoOrario += " "; + } + testoFirmaPiccola = string.Empty; + thumbSizeSmall = new Size(); + thumbSizeBig = new Size(); + nomeFileSmall = string.Empty; + nomeFileBig2 = string.Empty; + nomeFileBig = string.Empty; + _dimensioneStandard = _picSettings.DimStandard; + _dimensioneStandardMiniatura = _picSettings.DimStandardMiniatura; + + nomeFileSmall = _picSettings.Suffisso + WorkFile.Name; + nomeFileBig = WorkFile.Name; + } + + private void PrepareThumbnailSize(Image g) + { + if (g.Width > g.Height) + { + thumbSizeSmall = NewthumbSize(g.Width, g.Height, CatalogVbLib.PicSettings.LarghezzaSmall, "Larghezza"); + //Size sizeOrig = new Size(g.Width, g.Height); + //thumbSizeBig = sizeOrig; + + thumbSizeBig = new Size(g.Width, g.Height); + } + else + { + thumbSizeSmall = NewthumbSize(g.Width, g.Height, CatalogVbLib.PicSettings.AltezzaSmall, "Altezza"); + + thumbSizeBig = new Size(g.Width, g.Height); + } + } + + private void CreaMiniature(Image g, Bitmap imgOutputBig, ImageFormat thisFormat) + { +// CatalogLib.PicSettings ps = new PicSettings(); + + if (_picSettings.TestoMin) + { + testoFirmaPiccola = nomeFileBig; + } + else if (_picSettings.AggNumTempMin) + { + testoFirmaPiccola = nomeFileBig + " "; + } + + Font crFont1; + Font crFont2; + SizeF crSize1 = new SizeF(); + SizeF crSize2 = new SizeF(); + + if (_picSettings.CreaMiniature) + { + if (!_picSettings.AggiungiScritteMiniature) + { + if (string.Equals(_picSettings.DirectorySorgente, _picSettings.DirectoryDestinazione, StringComparison.CurrentCultureIgnoreCase)) + { + nomeFileSmall = nomeFileSmall.Substring(0, nomeFileSmall.Length - 4) + _picSettings.Codice + + nomeFileSmall.Substring(nomeFileSmall.Length - 4); + } + + if (_picSettings.UsaOrarioMiniatura || + _picSettings.TestoMin || + _picSettings.AggTempoGaraMin || + _picSettings.AggNumTempMin) + { + if (!string.IsNullOrWhiteSpace(testoFirmaPiccola)) + { + Bitmap imgOutputSmall = (Bitmap)imgOutputBig.Clone(); + + Graphics grPhoto1 = Graphics.FromImage(imgOutputSmall); + grPhoto1.SmoothingMode = SmoothingMode.HighSpeed; //Todo: permettere di cambiare questo parametro + + int larghezzaStandard1; + + _dimensioneStandardMiniatura = 50; + bool grassetto = _picSettings.Grassetto; + crFont1 = new Font(_picSettings.IlFont, _dimensioneStandardMiniatura, grassetto ? FontStyle.Bold : FontStyle.Regular); + crFont2 = new Font(_picSettings.IlFont, _dimensioneStandard, grassetto ? FontStyle.Bold : FontStyle.Regular); + + crSize1 = grPhoto1.MeasureString(testoFirmaPiccola, crFont1); + crSize2 = grPhoto1.MeasureString(testoFirma, crFont1); + + larghezzaStandard1 = (int)crSize1.Width; + + if (crSize1.Width > g.Width) + { + int conta = _dimensioneStandardMiniatura; + do + { + if (conta > 20) + { + conta -= 5; + } + else + { + conta -= 1; + } + + crFont1 = new Font(_picSettings.IlFont, conta, grassetto ? FontStyle.Bold : FontStyle.Regular); + crSize1 = grPhoto1.MeasureString(testoFirmaPiccola, crFont1); + + if (crSize1.Width < g.Width) + { + larghezzaStandard1 = (int)crSize1.Width; + break; + } + + } while (conta > 5); + _dimensioneStandardMiniatura = conta; + + } + + switch (_picSettings.TextPosition.ToString().ToUpper()) + { + case "ALTO": + yPosFromBottom1 = _picSettings.Margine; + yPosFromBottom4 = _picSettings.MargVert; + break; + + case "BASSO": + yPosFromBottom1 = + (float) + (g.Height - crSize1.Height - (g.Height * CatalogVbLib.PicSettings.Margine / 100)); + yPosFromBottom4 = (float)(g.Height - crSize1.Height - (g.Height * CatalogVbLib.PicSettings.MargVert / 100)); + break; + } + + + float xCenterOfImg1 = Single.NaN; + + StringFormat strFormat1 = new StringFormat(); + + switch (_picSettings.Allineamento.ToUpper()) + { + case "SINISTRA": + xCenterOfImg1 = CatalogVbLib.PicSettings.Margine + (larghezzaStandard1 / 2); + if ((larghezzaStandard1 / 2) > (g.Width / 2) - CatalogVbLib.PicSettings.Margine) + { + xCenterOfImg1 = g.Width / 2; + } + break; + + case "CENTRO": + xCenterOfImg1 = (g.Width / 2); + break; + + case "DESTRA": + xCenterOfImg1 = (g.Width - CatalogVbLib.PicSettings.Margine - (larghezzaStandard1 / 2)); + if ((larghezzaStandard1 / 2) > (g.Width / 2) - CatalogVbLib.PicSettings.Margine) + { + xCenterOfImg1 = g.Width / 2; + } + break; + + } + + strFormat1.Alignment = StringAlignment.Center; + + SolidBrush semiTransBrush21 = new SolidBrush(Color.FromArgb(alphaScelta, 0, 0, 0)); + SolidBrush semiTransBrush1 = new SolidBrush(Color.FromArgb(alphaScelta, CatalogVbLib.PicSettings.fontColoreRGB)); + + _dimensioneStandardMiniatura = CatalogVbLib.PicSettings.DimMin; + + if (_picSettings.Grassetto) + { + crFont1 = new Font(_picSettings.IlFont, _dimensioneStandardMiniatura, FontStyle.Bold); + } + else + { + crFont1 = new Font(_picSettings.IlFont, _dimensioneStandardMiniatura); + } + + if (_picSettings.TestoMin) + { + grPhoto1.DrawString(nomeFileBig, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), strFormat1); + grPhoto1.DrawString(nomeFileBig, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), strFormat1); + } + else if (_picSettings.AggTempoGaraMin & _picSettings.UsaTempoGaraTestoApplicare) + { + //TimeSpan orario = (dataPartenzaI - dataFoto) * 10000000; //todo + TimeSpan orario = dataPartenzaI - dataFoto; //todo controllare se torna la roba giusta + + string tempStr = ""; + + + + tempStr += Environment.NewLine + testoOrario + orario.Hours.ToString("00") + ":" + + orario.Minutes.ToString("00") + ":" + orario.Seconds.ToString("00"); //todo: usare una stringa formato per sta boiata + + grPhoto1.DrawString(tempStr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1)); + grPhoto1.DrawString(tempStr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), strFormat1); + } + else if (_picSettings.AggNumTempMin) //todo semplificare la logica di sti eif + { + TimeSpan orario = dataPartenzaI - dataFoto; //todo controllare se torna la roba giusta + string tempStr = ""; + tempStr += nomeFileBig + Environment.NewLine + testoOrario + orario.Hours.ToString("00") + ":" + + orario.Minutes.ToString("00") + ":" + orario.Seconds.ToString("00"); //todo: usare una stringa formato per sta boiata + + grPhoto1.DrawString(tempStr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1)); + grPhoto1.DrawString(tempStr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), strFormat1); + } + else + { + grPhoto1.DrawString(testoFirmaPiccola, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), strFormat1); + grPhoto1.DrawString(testoFirmaPiccola, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), strFormat1); + } + + + //Salva miniatura + + imgOutputSmall.Save(Path.Combine(DestDir.FullName, "Temp_" + nomeFileSmall), thisFormat); + float width = 0; + float height = 0; + //float scale = Math.Min(width/imgOutputSmall.Width, height/imgOutputSmall.Height); + using (var bmp = new Bitmap(thumbSizeSmall.Width, thumbSizeSmall.Height)) + { + using (var graph = Graphics.FromImage(bmp)) + { + // uncomment for higher quality output + //graph.InterpolationMode = InterpolationMode.High; + //graph.CompositingQuality = CompositingQuality.HighQuality; + //graph.SmoothingMode = SmoothingMode.AntiAlias; + + graph.DrawImage(imgOutputSmall, new Rectangle(0, 0, (int)width, (int)height)); + + bmp.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + } + } + //var bmp = new Bitmap(thumbSizeSmall.Width, thumbSizeSmall.Height); + //var graph = Graphics.FromImage(bmp); + + + +// 10 down vote accepted + + +//Target parameters: + +//float width = 1024; +//float height = 768; +//var brush = new SolidBrush(Color.Black); + +//Your original file: + +//var image = new Bitmap(file); + +//Target sizing (scale factor): + +//float scale = Math.Min(width / image.Width, height / image.Height); + +//The resize including brushing canvas first: + +//var bmp = new Bitmap((int)width, (int)height); +//var graph = Graphics.FromImage(bmp); + +//// uncomment for higher quality output +////graph.InterpolationMode = InterpolationMode.High; +////graph.CompositingQuality = CompositingQuality.HighQuality; +////graph.SmoothingMode = SmoothingMode.AntiAlias; + +//var scaleWidth = (int)(image.Width * scale); +//var scaleHeight = (int)(image.Height * scale); + +//graph.FillRectangle(brush, new RectangleF(0, 0, width, height)); +//graph.DrawImage(image, new Rectangle(((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight)); + + + + //imgOutputSmall.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + + + //Image g2 = Image.FromFile(Path.Combine(DestDir.FullName, "Temp_" + nomeFileSmall)); + //Bitmap imgOutputSmall2 = new Bitmap(g2, thumbSizeSmall.Width, thumbSizeSmall.Height); + //imgOutputSmall2.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + + + + } + } + + + } + } + + + + } + + + + /// + /// Calculate the Size of the New image + /// + /// Larghezza + /// Altezza + /// + /// + /// + /// + private Size NewthumbSize(int currentwidth, int currentheight, int MaxPixel, string TipoSize) + { + // e + //*** Larghezza, Altezza, Auto + + double tempMultiplier = 0; + + if (TipoSize.ToUpper() == "Larghezza".ToUpper()) + { + tempMultiplier = MaxPixel / currentwidth; + } + else if (TipoSize.ToUpper() == "Altezza".ToUpper()) + { + tempMultiplier = MaxPixel / currentheight; + } + else + { + // portrait + if (currentheight > currentwidth) + { + tempMultiplier = MaxPixel / currentheight; + } + else + { + tempMultiplier = MaxPixel / currentwidth; + } + } + + Size NewSize = new Size(Convert.ToInt32(currentwidth * tempMultiplier), Convert.ToInt32(currentheight * tempMultiplier)); + + return NewSize; + } + } +} diff --git a/CatalogLib/ImageCreator2.cs b/CatalogLib/ImageCreator2.cs new file mode 100644 index 0000000..c10607d --- /dev/null +++ b/CatalogLib/ImageCreator2.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using CatalogVbLib; + +namespace CatalogLib +{ + public class ImageCreator2 : IImageProcessor + { + private PicSettings _picSettings = PicSettings.Instance; + + private FileInfo _workFile; + + private Image _workingImage; + + private Rotazione _rotation; + + private ImageFormat _currentFormat; + + private Size _newImageSize; + + private Bitmap _outputImage; + + private DirectoryInfo _destDir; + + private string _nomeFileBig; + + public void Start(FileInfo workFile) + { + _workFile = workFile; + + _workingImage = Image.FromFile(workFile.FullName); + + _destDir = new DirectoryInfo(_picSettings.DirectoryDestinazione); + _nomeFileBig = _workFile.Name; + + CalculateImageSize(); + + ElaborazioneTesto(); + + ElaborazioneRotazione(); + + SetImageFormat(); + + + FinalElaboration(); + + //CreaMiniature + } + + private void FinalElaboration() + { + _outputImage = new Bitmap(_workingImage, _newImageSize.Width, _newImageSize.Height); + _outputImage.SetResolution(_workingImage.HorizontalResolution, _workingImage.VerticalResolution); + + + SavePic(_outputImage, Path.Combine(_destDir.FullName, _nomeFileBig)); + } + + private void SavePic(Bitmap imageToSave, string fileName) + { + var selectedEncoder = GetEncoder(_currentFormat); + var encoder = System.Drawing.Imaging.Encoder.Quality; + var encoderParameters = new EncoderParameters(1); + + + if (Equals(_currentFormat, ImageFormat.Jpeg)) + { + var encoderParameter = new EncoderParameter(encoder, _picSettings.CompressioneJpeg); + encoderParameters.Param[0] = encoderParameter; + } + + imageToSave.Save(fileName, selectedEncoder,encoderParameters); + imageToSave.Dispose(); + } + + private ImageCodecInfo GetEncoder(ImageFormat format) + { + var codecs = ImageCodecInfo.GetImageDecoders(); + + return codecs.FirstOrDefault(c => c.FormatID == format.Guid); + } + + private void ElaborazioneTesto() + { + if (_picSettings.EnableText) + { + // todo: elaborazione testo + } + } + + private void CalculateImageSize() + { + _newImageSize = new Size(_workingImage.Width, _workingImage.Height); + } + + private void ElaborazioneRotazione() + { + + _rotation = Rotazione.Normale; + + if (_picSettings.GeneraleRotazioneAutomatica) + { + // ci sono dati exif + if (_workingImage.PropertyIdList.Length > 0) + { + ExifReader DatiExif = new ExifReader((Bitmap)_workingImage); + + switch (DatiExif.Orientation) + { + case ExifReader.Orientations.BottomLeft: + + break; + case ExifReader.Orientations.BottomRight: + + break; + case ExifReader.Orientations.LeftTop: + + break; + case ExifReader.Orientations.LftBottom: + //FotoRuotaASinistra = true; + _rotation = Rotazione.Sinistra; + break; + case ExifReader.Orientations.RightBottom: + + break; + case ExifReader.Orientations.RightTop: + + break; + case ExifReader.Orientations.TopLeft: + + break; + case ExifReader.Orientations.TopRight: + + break; + } + } + } + + if (_rotation == Rotazione.Sinistra) + { + _workingImage.RotateFlip(RotateFlipType.Rotate270FlipNone); + } + else + if (_rotation == Rotazione.Destra) + { + _workingImage.RotateFlip(RotateFlipType.Rotate90FlipNone); + } + } + + private void SetImageFormat() + { + _currentFormat = _workingImage.RawFormat; + if (_picSettings.GeneraleForzaJPG) + { + _currentFormat = ImageFormat.Jpeg; + } + } + + } +} diff --git a/CatalogLib/ImgSharpCreator.cs b/CatalogLib/ImgSharpCreator.cs new file mode 100644 index 0000000..aa053a6 --- /dev/null +++ b/CatalogLib/ImgSharpCreator.cs @@ -0,0 +1,549 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Numerics; +using System.Threading.Tasks; +using MaddoLibrary.Base.Log; +using SixLabors.Fonts; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Drawing; +using SixLabors.ImageSharp.Formats.Jpeg; +using SixLabors.ImageSharp.MetaData.Profiles.Exif; +using SixLabors.ImageSharp.Processing; +using SixLabors.Primitives; +using Font = SixLabors.Fonts.Font; +using FontFamily = SixLabors.Fonts.FontFamily; +using FontStyle = SixLabors.Fonts.FontStyle; +using Rgba32 = SixLabors.ImageSharp.Rgba32; +using Image = SixLabors.ImageSharp.Image; + +namespace CatalogLib +{ + public class ImgSharpCreator : IImageProcessor + { + private Image _logo; + public ImgSharpCreator() + { + if (!PicSettings.Instance.EnableLogo) return; + if (string.IsNullOrWhiteSpace(PicSettings.Instance.LogoPath)) return; + if (!File.Exists(PicSettings.Instance.LogoPath)) return; + + _logo = Image.Load(PicSettings.Instance.LogoPath); + + } + private FileInfo _currentFile; + public void Start(FileInfo workFile) + { + + Stopwatch s = new Stopwatch(); + s.Start(); + + _currentFile = workFile; + + + + using (Image image = Image.Load(workFile.FullName)/* new Image(workFile.FullName)*/) + { + MaddoLogger.Log("Loaded Image: {0}", workFile.FullName); + //image.Rotate(-90); + bool isRotated; + + var orientation = image.MetaData.ExifProfile.GetValue(ExifTag.Orientation); + if ((ushort)orientation.Value != 1) + { + isRotated = true; + } + else + { + isRotated = false; + } + + if (PicSettings.Instance.FotoRidimensiona) + { + Resize(image); + } + + + if (PicSettings.Instance.GeneraleRotazioneAutomatica) + { + image.Mutate(img => img.AutoOrient()); + MaddoLogger.Log("Rotated Image: {0}", workFile.FullName); + //image.AutoOrient(); + + //var exif = image.MetaData.ExifProfile; + //if (exif != null) + //{ + // var o = exif.GetValue(ExifTag.Orientation); + // if (o != null) + // { + // var v = (ushort)o.Value; + + + + // switch (v) + // { + + + // //1 = Horizontal(normal) + // //2 = Mirror horizontal + // //3 = Rotate 180 + // //4 = Mirror vertical + // //5 = Mirror horizontal and rotate 270 CW + // //6 = Rotate 90 CW + // //7 = Mirror horizontal and rotate 90 CW + // //8 = Rotate 270 CW + // case 1: + // break; + // case 2: + // image.Flip(FlipType.Horizontal); + // break; + // case 3: + // //image.Rotate(180f); + + // //image.Rotate(90); + // image.Rotate(RotateType.Rotate180); + // break; + // case 4: + // image.Flip(FlipType.Vertical); + // break; + // case 5: + // image.RotateFlip(RotateType.Rotate270, FlipType.Horizontal); + // break; + // case 6: + // image.Rotate(RotateType.Rotate90); + // break; + // case 7: + // image.RotateFlip(RotateType.Rotate90, FlipType.Horizontal); + // break; + // case 8: + // //image.Rotate(-90); + // image.Rotate(RotateType.Rotate270); + + // image.MetaData.ExifProfile.SetValue(ExifTag.Orientation, new ExifValue(exif.GetValue(ExifTag.Orientation)).Value = (ushort)1); + // break; + + + // } + // } + //} + + } + + if (PicSettings.Instance.EnableText) + { + //SetTextTest(image); + SetExtraText(image, isRotated); + + + MaddoLogger.Log("Drawn text on Image: {0}", workFile.FullName); + } + + //JpegDecoder j = new JpegDecoder(); + var va = Vector.IsHardwareAccelerated; + + MaddoLogger.Log("Hardware Accelerated: {0}", va); + //image.Resize(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza); + + //image.Resize(2240, 2240); + //var fff = FontCollection.SystemFonts.Find(PicSettings.Instance.NomeFont); + //var font = new Font(fff, (float)PicSettings.Instance.DimensioneFont, FontStyle.Regular); + //image.DrawText("sssssssssssssssssssssssssssssssssssssssssssssss", font, Color.Black, new Vector2(200, 200)); + image.Save(Path.Combine(PicSettings.Instance.DirectoryDestinazione, workFile.Name), new JpegEncoder() { Quality = PicSettings.Instance.CompressioneJpeg }); + //image.Resize(200, 200).Save(""); + + MaddoLogger.Log("Saved Image: {0} to: {1}", workFile.FullName, Path.Combine(PicSettings.Instance.DirectoryDestinazione, workFile.Name)); + } + s.Stop(); + MaddoLogger.Log("Time Taken for {0}: {1}", workFile.FullName, s.Elapsed); + } + + private void Resize(Image image) + { + IResampler resampler; + switch (PicSettings.Instance.ResizeMode) + { + case ResizeModes.Bicubic: + resampler = new BicubicResampler(); + break; + case ResizeModes.Box: + resampler = new BoxResampler(); + break; + case ResizeModes.CatmullRom: + resampler = new CatmullRomResampler(); + break; + case ResizeModes.Hermite: + resampler = new HermiteResampler(); + break; + case ResizeModes.Lanczos2: + resampler = new Lanczos2Resampler(); + break; + case ResizeModes.Lanczos3: + resampler = new Lanczos3Resampler(); + break; + case ResizeModes.Lanczos5: + resampler = new Lanczos5Resampler(); + break; + case ResizeModes.Lanczos8: + resampler = new Lanczos8Resampler(); + break; + case ResizeModes.MitchellNetravali: + resampler = new MitchellNetravaliResampler(); + break; + case ResizeModes.NearestNeighbor: + resampler = new NearestNeighborResampler(); + break; + case ResizeModes.Robidoux: + resampler = new RobidouxResampler(); + break; + case ResizeModes.Spline: + resampler = new SplineResampler(); + break; + case ResizeModes.Triangle: + resampler = new TriangleResampler(); + break; + case ResizeModes.Welch: + resampler = new WelchResampler(); + break; + default: + throw new ArgumentOutOfRangeException(); + } + // todo calcolare ridimensionamento + var size = new Size(PicSettings.Instance.FotoLarghezza, PicSettings.Instance.FotoAltezza); + if (PicSettings.Instance.FotoMantieniDimensioni) + { + size = ResizeImage(image, size, PicSettings.Instance.ResizeDimension); + image.Mutate(x => x.Resize((size.Width), (size.Height), resampler)); + + //Width Formula: + //original height / original width * new width = new height + //Height Formula: + //orignal width / orignal height * new height = new width + } + else + { + + image.Mutate(x => x.Resize(PicSettings.Instance.FotoAltezza, PicSettings.Instance.FotoLarghezza, resampler)); + } + + } + + private Size ResizeImage(Image image, Size size, ResizeDimensions side) + { + switch (side) + { + case ResizeDimensions.LatoLungo: + size = GetResizeDimensions(new Size(image.Width, image.Height), size, image.Width > image.Height); + break; + case ResizeDimensions.LatoCorto: + size = GetResizeDimensions(new Size(image.Width, image.Height), size, image.Width <= image.Height); + break; + default: + throw new ArgumentOutOfRangeException(); + } + return size; + } + + private Size GetResizeDimensions(Size originalSize, Size newSize, bool adjustHeight) + { + return adjustHeight ? new Size(newSize.Width, originalSize.Height / originalSize.Width * newSize.Height) : new Size(originalSize.Width / originalSize.Height * newSize.Height, newSize.Height); + } + + private void SetTextTest(Image image) + { + string text = "test test test test test testtest test test test test test test"; + Font font = new Font(SystemFonts.Find("verdana"), 300, FontStyle.Regular); + image.Mutate(x => x.DrawText(text, font, Rgba32.Yellow, new PointF(2760, 3295.54932f), new TextGraphicsOptions() + { + HorizontalAlignment = HorizontalAlignment.Center + })); + } + + private void SetExtraText(Image image, bool isRotated) + { + if (string.IsNullOrWhiteSpace(PicSettings.Instance.TestoApplicareOrizzontale)) + { + Debug.WriteLine($"{_currentFile.Name} No text"); + return; + } + + string text; + if (isRotated) + { + if (PicSettings.Instance.TestoApplicareOrizzontale.Contains("$_")) + { + text = PicSettings.Instance.TestoApplicareOrizzontale.Replace("$_", "\r\n"); + } + else + { + text = PicSettings.Instance.TestoApplicareOrizzontale.Replace("$_", ""); + } + + } + else + { + text = PicSettings.Instance.TestoApplicareOrizzontale.Replace("$_", ""); + } + + + var fo = SixLabors.Fonts.SystemFonts.Find(PicSettings.Instance.NomeFont); + + + //var fff = FontCollection.SystemFonts.Find(PicSettings.Instance.NomeFont); + //var fff = FontCollection.SystemFonts.Find("Segoe Print"); + + Font font; + + if (!PicSettings.Instance.Grassetto) + { + font = new Font(fo, (float)PicSettings.Instance.DimensioneFont, FontStyle.Regular); + } + else + { + font = new Font(fo, (float)PicSettings.Instance.DimensioneFont, FontStyle.Bold); + } + // todo corsivo + + + + //var font = new Font(fff, 8f, FontStyle.Regular); + + + //Color c = Color.FromHex(FlipRgbString(PicSettings.Instance.ColoreTestoRGB)); + Rgba32 g = Rgba32.FromHex(FlipRgbString(PicSettings.Instance.ColoreTestoRGB)); + + Rgba32 gBack = Rgba32.Black; // todo alpha + //TextMeasurer measurer = new TextMeasurer(); + + //var size = measurer.MeasureText(PicSettings.Instance.TestoApplicareOrizzontale, font, 72); + //float scalingFactor = Math.Min(image.Width / size.Width, image.Height / size.Height); + //Font scaledFont = new Font(font, scalingFactor * font.Size); + + //image.DrawText(PicSettings.Instance.TestoApplicareOrizzontale, scaledFont, g, new Vector2(0, 0)); + + Vector2 center = new Vector2(image.Width / 2, image.Height / 2); //center horizontally, 10px down + + var size = TextMeasurer.Measure(text, new RendererOptions(font)); + + var larghezzaStandard = size.Width; + var dimensioneStandard = (int)Math.Round(PicSettings.Instance.DimensioneFont); + if (size.Width > image.Width) + { + var c = dimensioneStandard; + do + { + if (c > 20) + { + c -= 5; + } + else + { + c -= 1; + } + + if (PicSettings.Instance.Grassetto) + { + font = new Font(fo, c, FontStyle.Bold); + } + else + { + font = new Font(fo, c, FontStyle.Regular); + } + size = TextMeasurer.Measure(text, + new RendererOptions(font)); + if (size.Width < image.Width) + { + larghezzaStandard = (int)Math.Round(size.Width); + break; + } + if (c <= 5) + { + break; + } + } while (dimensioneStandard == c); + } + + float yPosFromBottom = 0; + + switch (PicSettings.Instance.TextPosition) + { + case Positions.Alto: + yPosFromBottom = PicSettings.Instance.Margine; + break; + case Positions.Basso: + yPosFromBottom = image.Height - size.Height - (image.Height * PicSettings.Instance.Margine / 100); + break; + } + + float xCenterofImg = 0; + + // stringformat + + switch (PicSettings.Instance.TextAlignment) + { + case Alignments.Sinistra: + xCenterofImg = PicSettings.Instance.Margine + (larghezzaStandard / 2); + if ((larghezzaStandard / 2) > (image.Width / 2) - PicSettings.Instance.Margine) + { + xCenterofImg = image.Width / 2; + } + break; + case Alignments.Centro: + xCenterofImg = image.Width / 2; + break; + case Alignments.Destra: + xCenterofImg = image.Width - PicSettings.Instance.Margine - larghezzaStandard / 2; + + if (larghezzaStandard / 2 > image.Width / 2 - PicSettings.Instance.Margine) + { + xCenterofImg = image.Width / 2; + } + + break; + } + // stringformat alignment center + + if (PicSettings.Instance.Grassetto) + { + font = new Font(fo, dimensioneStandard, FontStyle.Bold); + } + else + { + font = new Font(fo, dimensioneStandard, FontStyle.Regular); + } + + image.Mutate(x => x.DrawText(text, font, gBack, new PointF((float)Math.Round(xCenterofImg + 1), (float)Math.Round(yPosFromBottom + 1)), new TextGraphicsOptions() + { + HorizontalAlignment = HorizontalAlignment.Center + })); + + image.Mutate(x => x.DrawText(text, font, g, new PointF((float)Math.Round(xCenterofImg), (float)Math.Round(yPosFromBottom)), new TextGraphicsOptions() + { + HorizontalAlignment = HorizontalAlignment.Center + })); + + return; + + + float scalingFactor = Math.Min(image.Width / size.Width, image.Height / size.Height); + Font scaledFont = new Font(font, scalingFactor * font.Size); + + image.Mutate(x => + x.DrawText(PicSettings.Instance.TestoApplicareOrizzontale, scaledFont, g, center, + new TextGraphicsOptions(true) + { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Bottom + })); + //image.DrawText(PicSettings.Instance.TestoApplicareOrizzontale, scaledFont, g, center, new TextGraphicsOptions(true) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom }); + + + } + + private void AddLogo(Image image) + { + //if (string.IsNullOrWhiteSpace(PicSettings.Instance.LogoPath)) return; + //if (!File.Exists(PicSettings.Instance.LogoPath)) return; + //using (Image logo = Image.Load(PicSettings.Instance.LogoPath)) + //{ + // Size size = new Size(); + // Point location = new Point(); + // image.Mutate(x => x.DrawImage(logo, size, location, new GraphicsOptions() + // { + + // })); + + //} + + Size size = new Size(); + Point location = new Point(); + + if (_logo != null) + { + var width = PicSettings.Instance.LogoWidth; + var height = PicSettings.Instance.LogoHeight; + var heightFactor = _logo.Height / height; + var widthFactor = _logo.Width / width; + var newLogoSize = new Size(); + + newLogoSize = GetResizeDimensions(new Size(_logo.Width, _logo.Height), new Size(width, height), PicSettings.Instance.LogoResizeSide.Equals(ResizeDimensions.LatoCorto)); + //todo riguardare perché non torna cosa ho fatto + + int margineUsato = 0; + int margineL; + bool inPercentualeL; + + inPercentualeL = PicSettings.Instance.LogoMargin.EndsWith("%"); + if (inPercentualeL) + { + margineL = int.Parse(PicSettings.Instance.LogoMargin.Replace("%", "")); + } + else + { + margineL = int.Parse(PicSettings.Instance.LogoMargin); + } + + switch (PicSettings.Instance.LogoPosition) + { + case Positions.Alto: + break; + case Positions.Centro: + break; + case Positions.Basso: + break; + default: + throw new ArgumentOutOfRangeException(); + } + + switch (PicSettings.Instance.LogoAlignment) + { + case Alignments.Sinistra: + location.X = margineUsato; + break; + case Alignments.Centro: + //location.X = image.Width - + break; + case Alignments.Destra: + break; + default: + throw new ArgumentOutOfRangeException(); + } + image.Mutate(x => x.DrawImage(_logo, size, location, new GraphicsOptions())); + + + + + } + + } + + private void WriteTextFixed(Image image) + { + var fo = SixLabors.Fonts.SystemFonts.Find("Microsoft Sans Serif"); + var font = new Font(fo, 8, FontStyle.Regular); + Rgba32 g = Rgba32.FromHex("#FF00FFFF"); + Vector2 center = new Vector2(image.Width / 2, image.Height / 2); + var size = TextMeasurer.Measure("Test test test test test", new RendererOptions(font)); + float scalingFactor = Math.Min(image.Width / size.Width, image.Height / size.Height); + Font scaledFont = new Font(font, scalingFactor * font.Size); + image.Mutate(x => x.DrawText("Test test test test test", scaledFont, g, center, new TextGraphicsOptions(true) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom })); + } + + private string FlipRgbString(string originalString) + { + string s; + if (originalString.Length == 7) + { + s = string.Concat("#", originalString.Substring(1, 6)); + } + else + { + s = string.Concat("#", originalString.Substring(3, 6), originalString.Substring(1, 2)); + } + + + return s; + } + } +} diff --git a/CatalogLib/PicSettings.cs b/CatalogLib/PicSettings.cs new file mode 100644 index 0000000..795b004 --- /dev/null +++ b/CatalogLib/PicSettings.cs @@ -0,0 +1,548 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MaddoLibrary.Base.Log; +using Newtonsoft.Json; + +namespace CatalogLib +{ + public class PicSettings + { + private static PicSettings _instance = new PicSettings(); + + public static PicSettings Instance + { + get { return _instance; } + } + + private Dictionary _settingsDict = new Dictionary(); + + public PicSettings() + { + SetDefaults(); + } + + public string SerializeSettings() + { + return JsonConvert.SerializeObject(_settingsDict); + } + + public void DeserializeSettings(string serializedData) + { + _settingsDict = JsonConvert.DeserializeObject>(serializedData); + + + } + + public void SetBase(string key, object value) + { + if (_settingsDict.ContainsKey(key)) + { + _settingsDict[key] = value; + } + else + { + _settingsDict.Add(key, value); + } + } + + public void SetString(string key, string value) + { + SetBase(key, value); + } + + public void SetInt(string key, int value) + { + SetBase(key, value); + } + + public void SetBool(string key, bool value) + { + SetBase(key, value); + } + + public void SetDouble(string key, double value) + { + SetBase(key, value); + } + + public void SetFloat(string key, float value) + { + SetBase(key, value); + } + + public void Set(string key, T value) + { + SetBase(key, value); + } + + public bool Exists(string key) + { + return _settingsDict.ContainsKey(key); + } + + public int GetInt(string key, int defaultValue = 0) + { + if (!_settingsDict.ContainsKey(key)) + { + SetInt(key, defaultValue); + } + + if (_settingsDict[key] is int) return (int)_settingsDict[key]; + Debug.WriteLine($"Error while parsing {key}"); + //return defaultValue; + + int r; + + if (int.TryParse(_settingsDict[key].ToString(), out r)) + { + SetInt(key, r); + + } + else + { + SetInt(key, defaultValue); + } + return (int)_settingsDict[key]; + //return (int) _settingsDict[key]; + + //return _settingsDict.ContainsKey(key) ? (int)_settingsDict[key] : defaultValue; + } + + public double GetDouble(string key, double defaultValue = 0) + { + if (!_settingsDict.ContainsKey(key)) + { + SetDouble(key, defaultValue); + // setdouble default + } + + if (_settingsDict[key] is double) return (double)_settingsDict[key]; + Debug.WriteLine($"Error while parsing {key}"); + + double d; + if (double.TryParse(_settingsDict[key].ToString(), out d)) + { + SetDouble(key, d); + // setdouble key r + } + else + { + SetDouble(key, defaultValue); + //setdouble defaultvalue + } + return (double)_settingsDict[key]; + } + + public float GetFloat(string key, float defaultValue = 0) + { + if (!_settingsDict.ContainsKey(key)) + { + SetFloat(key, defaultValue); + } + + if (_settingsDict[key] is float f) return f; + MaddoLogger.LogError("Error while parsing {0}", key); + + float fl = 0; + SetFloat(key, float.TryParse(_settingsDict[key].ToString(), out f) ? fl : defaultValue); + return (float)_settingsDict[key]; + } + + + + public T Get(string key, T defaultValue) + { + if (!_settingsDict.ContainsKey(key)) + { + Set(key, defaultValue); + // setdouble default + } + + return (T)_settingsDict[key]; + } + + + + + public string GetString(string key, string defaultValue = "") + { + if (!_settingsDict.ContainsKey(key)) + { + SetString(key, defaultValue); + } + return (string)_settingsDict[key]; + + //return _settingsDict.ContainsKey(key) ? (string)_settingsDict[key] : defaultValue; + } + + public bool GetBool(string key, bool defaultValue = false) + { + if (!_settingsDict.ContainsKey(key)) + { + SetBool(key, defaultValue); + return defaultValue; + } + return (bool)_settingsDict[key]; + + + + //return _settingsDict.ContainsKey(key) && (bool)_settingsDict[key]; + } + + + public object GetObject(string key, object defaultValue = null) + { + if (!_settingsDict.ContainsKey(key)) + { + Set(key, defaultValue); + return defaultValue; + } + return _settingsDict[key]; + + //return _settingsDict.ContainsKey(key) ? _settingsDict[key] : defaultValue; + } + + public T GetEnum(string name, T defaultValue) + { + return (T)Enum.Parse(typeof(T), GetString(name, defaultValue.ToString())); + } + + public void SetDefaults() + { + + } + + public bool DirAggiornaSottoDirectory + { + get => this.GetBool("DirAggiornaSottoDirectory", true); + set => this.SetBool("DirAggiornaSottoDirectory", value); + } + + public bool Grassetto + { + get { return GetBool("Grassetto"); } + set { SetBool("Grassetto", value); } + } + + public string IlFont //todo + { + get { return GetString(""); } + set { } + } + + public bool TestoMin //todo + { + get { return false; } + set { } + } + + public bool AggTempoGaraMin //todo + { + get { return false; } + set { } + } + + public bool UsaTempoGaraTestoApplicare //todo + { + get { return false; } + set { } + } + + public bool AggNumTempMin //todo + { + get { return false; } + set { } + } + + public bool CreaMiniature //todo + { + get { return false; } + set { } + } + + public bool AggiungiScritteMiniature + { + get { return false; } + set { } + } + + public string Suffisso + { + get { return string.Empty; } + set { } + } + + public string Codice + { + get { return null; } + set { } + } + + public int Trasparenza + { + get { return 0; } + } + + + + public DateTime DataPartenza { get; set; } + public string TestoOrario { get; internal set; } + public int DimStandard { get; internal set; } + public int DimStandardMiniatura { get; internal set; } + public bool UsaOrarioTestoApplicare { get; set; } + public bool UsaOrarioMiniatura { get; set; } + public string TestoFirmaStart { get; set; } + public string TestoFirmaStartV { get; set; } + public bool UsaForzaJpg { get; set; } + + public string DirectorySorgente + { + get { return GetString("DirSorgente"); } + set { SetString("DirSorgente", value); } + } + + public string DirectoryDestinazione + { + get { return GetString("DirDestinazione"); } + set { SetString("DirDestinazione", value); } + } + + public int Margine + { + get => GetInt("Margin", 1); + set => SetInt("Margin", value); + } + public float MargVert { get; set; } + public string Allineamento { get; set; } + + public bool GeneraleForzaJPG + { + get { return GetBool("GeneraleForzaJPG", true); } + set { SetBool("GeneraleForzaJPG", value); } + } + + public bool GeneraleRotazioneAutomatica + { + get { return GetBool("GeneraleRotazioneAutomatica", true); } + set { SetBool("GeneraleRotazioneAutomatica", value); } + } + + public bool GeneraleSovrascriviFile + { + get { return GetBool("GeneraleSovrascriviFile"); } + set { SetBool("GeneraleSovrascriviFile", value); } + } + + public bool SubdirCreaSottoCartelle + { + get { return GetBool("SubdirCreaSottoCartelle"); } + set { SetBool("SubdirCreaSottoCartelle", value); } + } + + public int SubdirIntervalloFile + { + get { return GetInt("SubdirIntervalloFile", 99); } + set { SetInt("SubdirIntervalloFile", value); } + } + + public string SubdirSuffisso + { + get { return GetString("SubdirSuffisso"); } + set { SetString("SubdirSuffisso", value); } + } + + public int SubdirCifreContatore + { + get { return GetInt("SubdirCifreContatore", 2); } + set { SetInt("SubdirCifreContatore", value); } + } + + public bool SubdirNumerazioneProgressiva + { + get { return GetBool("SubdirNumerazioneProgressiva", true); } + set { SetBool("SubdirNumerazioneProgressiva", value); } + } + + public bool SubdirNumerazioneFiles + { + get { return GetBool("SubdirNumerazioneFiles", false); } + set { SetBool("SubdirNumerazioneFiles", value); } + } + + public int FotoAltezza + { + get { return GetInt("FotoAltezza", 2240); } + set { SetInt("FotoAltezza", value); } + } + + public int FotoLarghezza + { + get { return GetInt("FotoLarghezza", 2240); } + set { SetInt("FotoLarghezza", value); } + } + + public int CompressioneJpeg + { + get { return GetInt("CompressioneJpeg", 85); } + set { SetInt("CompressioneJpeg", value); } + } + + public bool FotoMantieniDimensioni + { + get { return GetBool("FotoMantieniDimensioni", true); } + set { SetBool("FotoMantieniDimensioni", value); } + } + + public string FotoSuffisso + { + get { return GetString("FotoSuffisso"); } + set { SetString("FotoSuffisso", value); } + } + + + public bool EnableThumbnails + { + get { return GetBool("EnableThumbnails", false); } + set { SetBool("EnableThumbnails", value); } + } + public bool EnableLogo + { + get { return GetBool("EnableLogo", false); } + set { SetBool("EnableLogo", value); } + } + + #region Text + + public bool EnableText + { + get { return GetBool("EnableText", false); } + set { SetBool("EnableText", value); } + } + + public string NomeFont + { + get { return GetString("nomeFont", "Verdana"); } + set { SetString("nomeFont", value); } + } + + public double DimensioneFont + { + get { return Get("dimensioneFont", 1); } + set { SetDouble("dimensioneFont", value); } + } + + public string TestoApplicareOrizzontale + { + get + { + return Get("TestoApplicareOrizzontale", ""); + } + set + { + Set("TestoApplicareOrizzontale", value); + } + } + + public string ColoreTestoRGB + { + get { return GetString("coloreTestoRGB", "#000000"); } + set + { + Set("coloreTestoRGB", value); + + } + } + + public bool FotoRidimensiona + { + get => GetBool("FotoRidimensiona", false); + set => Set("FotoRidimensiona", value); + } + + public Positions TextPosition + { + get => GetEnum("TextPosition", Positions.Alto); //(Positions)Enum.Parse(typeof(Positions), GetString("TextPosition", Positions.Alto.ToString())); + set => SetString("TextPosition", value.ToString()); + } + + public Alignments TextAlignment + { + get => GetEnum("TextAlignment", Alignments.Centro); + set => SetString("TextAlignment", value.ToString()); + } + + public bool Threading + { + get => GetBool("Threading", true); + set => SetBool("Threading", value); + } + + public ResizeModes ResizeMode + { + get => GetEnum("ResizeMode", ResizeModes.Bicubic); + set => SetString("ResizeMode", value.ToString()); + } + + public ResizeDimensions ResizeDimension + { + get => GetEnum("ResizeDimension", CatalogLib.ResizeDimensions.LatoCorto); + set => SetString("ResizeDimension", value.ToString()); + } + + public string LogoPath + { + get => GetString("LogoPath"); + set => SetString("LogoPath", value); + } + + public int LogoWidth + { + get => GetInt("LogoWidth"); + set => SetInt("LogoWidth", value); + } + + public int LogoHeight + { + get => GetInt("LogoHeight"); + set => SetInt("LogoHeight", value); + } + + public string LogoMargin + { + get => GetString("LogoMargin"); + set => SetString("LogoMargin", value); + } + + public Positions LogoPosition + { + get => GetEnum("LogoPositions", Positions.Alto); + set => SetString("LogoPositions", value.ToString()); + } + + public Alignments LogoAlignment + { + get => GetEnum("LogoAlignments", Alignments.Centro); + set => SetString("LogoAlignments", value.ToString()); + } + + public ResizeDimensions LogoResizeSide + { + get => GetEnum("LogoResizeMode", ResizeDimensions.LatoCorto); + set => SetString("LogoResizeMode", value.ToString()); + } + + #endregion + + #region Enums + + + + #endregion + } +} \ No newline at end of file diff --git a/CatalogLib/Properties/AssemblyInfo.cs b/CatalogLib/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9d7f332 --- /dev/null +++ b/CatalogLib/Properties/AssemblyInfo.cs @@ -0,0 +1,38 @@ +using System; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("CatalogLib")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CatalogLib")] +[assembly: AssemblyCopyright("Copyright © 2013")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7bb8e6ce-72c8-4b36-a166-a62ed446d4e9")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: CLSCompliant(true)] \ No newline at end of file diff --git a/CatalogLib/SinglePicData.cs b/CatalogLib/SinglePicData.cs new file mode 100644 index 0000000..fb392c5 --- /dev/null +++ b/CatalogLib/SinglePicData.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CatalogLib +{ + public enum Rotazione + { + Normale, + Destra, + Sinistra, + Sottosopra + } + + public class SinglePicData + { + + + } +} diff --git a/CatalogLib/app.config b/CatalogLib/app.config new file mode 100644 index 0000000..f007515 --- /dev/null +++ b/CatalogLib/app.config @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CatalogLib/packages.config b/CatalogLib/packages.config new file mode 100644 index 0000000..86dfa50 --- /dev/null +++ b/CatalogLib/packages.config @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CatalogLib/stylecop.json b/CatalogLib/stylecop.json new file mode 100644 index 0000000..c67c0db --- /dev/null +++ b/CatalogLib/stylecop.json @@ -0,0 +1,15 @@ +{ + "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", + "settings": + { + "orderingRules": + { + "usingDirectivesPlacement": "outsideNamespace" + }, + "documentationRules": + { + "xmlHeader": false, + "copyrightText": "Copyright (c) Six Labors and contributors.\nLicensed under the Apache License, Version 2.0." + } + } +} \ No newline at end of file diff --git a/CatalogLibVb/CatalogLibVb.csproj b/CatalogLibVb/CatalogLibVb.csproj new file mode 100644 index 0000000..8d292d6 --- /dev/null +++ b/CatalogLibVb/CatalogLibVb.csproj @@ -0,0 +1,57 @@ + + + + + Debug + AnyCPU + {B3352D87-BF9F-4F7A-9162-007492DA76E4} + Library + Properties + CatalogLibVb + CatalogLibVb + v4.5 + 512 + SAK + SAK + SAK + SAK + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/CatalogLibVb/Class1.cs b/CatalogLibVb/Class1.cs new file mode 100644 index 0000000..16254ce --- /dev/null +++ b/CatalogLibVb/Class1.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace CatalogLibVb +{ + public class Class1 + { + } +} diff --git a/CatalogLibVb/Properties/AssemblyInfo.cs b/CatalogLibVb/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0ec915f --- /dev/null +++ b/CatalogLibVb/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Le informazioni generali relative a un assembly sono controllate dal seguente +// set di attributi. Per modificare le informazioni associate a un assembly +// occorre quindi modificare i valori di questi attributi. +[assembly: AssemblyTitle("CatalogLibVb")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("CatalogLibVb")] +[assembly: AssemblyCopyright("Copyright © 2014")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili +// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da +// COM, impostare su true l'attributo ComVisible per tale tipo. +[assembly: ComVisible(false)] + +// Se il progetto viene esposto a COM, il GUID che segue verrà utilizzato per creare l'ID della libreria dei tipi +[assembly: Guid("367f3879-584c-4780-8ad0-dc84d2e77928")] + +// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: +// +// Numero di versione principale +// Numero di versione secondario +// Numero build +// Revisione +// +// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build +// utilizzando l'asterisco (*) come descritto di seguito: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/CatalogLite/App.axaml b/CatalogLite/App.axaml deleted file mode 100644 index 7b4ec8a..0000000 --- a/CatalogLite/App.axaml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - #F4F6F8 - #FFFFFF - #D4DAE2 - #1F7A5A - - - #20242A - #2A3038 - #46505C - #4FB286 - - - - - - - - - - - - - - \ No newline at end of file diff --git a/CatalogLite/App.axaml.cs b/CatalogLite/App.axaml.cs deleted file mode 100644 index 64f294b..0000000 --- a/CatalogLite/App.axaml.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Avalonia.Controls.ApplicationLifetimes; -using Avalonia.Markup.Xaml; -using Microsoft.Extensions.DependencyInjection; - -namespace CatalogLite; - -public partial class App : Avalonia.Application -{ - public override void Initialize() => AvaloniaXamlLoader.Load(this); - - public override void OnFrameworkInitializationCompleted() - { - if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) - { - if (ExpirationGuard.IsExpired(out var expirationDate)) - { - var expiredWindow = new ExpiredWindow(expirationDate); - expiredWindow.Closed += (_, _) => desktop.Shutdown(); - desktop.MainWindow = expiredWindow; - } - else - { - desktop.MainWindow = Program.ServiceProvider.GetRequiredService(); - } - } - - base.OnFrameworkInitializationCompleted(); - } -} \ No newline at end of file diff --git a/CatalogLite/Assets/Config.xml b/CatalogLite/Assets/Config.xml deleted file mode 100644 index 9b0fa7d..0000000 --- a/CatalogLite/Assets/Config.xml +++ /dev/null @@ -1,227 +0,0 @@ - - - - MiniatureModalita - Text - - - DirSorgente - - - - DirDestinazione - - - - MiniatureCrea - True - - - MiniatureSuffisso - tn_ - - - MiniatureAltezza - 350 - - - MiniatureLarghezza - 350 - - - FontDimensioneMiniatura - 20 - - - CompressioneJpegMiniatura - 60 - - - MiniatureAddOrario - False - - - NomeMiniatura - False - - - MiniatureAddScritta - True - - - TempoSmall - False - - - NumTempoSmall - False - - - FotoCodice - - - - FotoAltezza - 2560 - - - FotoLarghezza - 2560 - - - FotoDimOriginali - False - - - CompressioneJpeg - 90 - - - FontDimensione - 50 - - - FontNome - Verdana - - - FontBold - True - - - ColoreTestoRGB - #FA7B0A - - - TestoTesto - - - - TestoVerticale - - - - TestoTrasparente - 0 - - - TestoMargine - 8 - - - TestoPosizione - Basso - - - TestoAllineamento - Centro - - - GrandezzaVerticale - 18 - - - MargineVerticale - 6 - - - MarchioAltezza - 250 - - - MarchioLarghezza - 250 - - - MarchioMargine - 130 - - - MarchioAllOrizzontale - Destra - - - MarchioAllVerticale - Alto - - - MarchioTrasparenza - 100 - - - MarchioAggiungi - True - - - ColoreTrasparente - #FFFFFF - - - UsaColoreTrasparente - True - - - ImageLibrary - ImageSharp - - - GeneraleForzaJpg - True - - - GeneraleRotazioneAutomatica - True - - - DirSottoDirectory - True - - - TempoGara - False - - - Orario - False - - - EtichettaOrario - - - - DataFoto - False - - - NumeroFoto - False - - - GeneraleSovrascriviFile - False - - - DirDividiNumFile - 300 - - - DirDividiSuffisso - - - - DirDividiNumCifre - 2 - - - ChunkSize - 0 - - - ThreadsCount - 0 - - - DataPartenza - 17/02/2026 09:35:25 - - \ No newline at end of file diff --git a/CatalogLite/Assets/Logo_RUS_ETS_tricolore_OK.png b/CatalogLite/Assets/Logo_RUS_ETS_tricolore_OK.png deleted file mode 100644 index 1d4d8bf..0000000 Binary files a/CatalogLite/Assets/Logo_RUS_ETS_tricolore_OK.png and /dev/null differ diff --git a/CatalogLite/Assets/testConfig.xml b/CatalogLite/Assets/testConfig.xml deleted file mode 100644 index cf735d0..0000000 --- a/CatalogLite/Assets/testConfig.xml +++ /dev/null @@ -1,336 +0,0 @@ - - - - MiniatureModalita - RaceTime - - - MiniatureCrea - True - - - MiniatureSuffisso - tn_ - - - MiniatureAltezza - 350 - - - MiniatureLarghezza - 350 - - - FontDimensioneMiniatura - 48 - - - CompressioneJpegMiniatura - 25 - - - MiniatureAddOrario - False - - - NomeMiniatura - False - - - MiniatureAddScritta - False - - - TempoSmall - True - - - NumTempoSmall - False - - - FotoCodice - - - - FotoAltezza - 2560 - - - FotoLarghezza - 2560 - - - FotoDimOriginali - False - - - CompressioneJpeg - 90 - - - FontDimensione - 22 - - - FontNome - Verdana - - - FontBold - True - - - ColoreTestoRGB - #FEC005 - - - TestoTesto - MARATONINA DI VINCI -1 FEBBRAIO 2026 - - - TestoVerticale - MARATONINA DI VINCI -1 FEBBRAIO 2026 - - - TestoTrasparente - 0 - - - TestoMargine - 8 - - - TestoPosizione - Basso - - - TestoAllineamento - Centro - - - GrandezzaVerticale - 18 - - - MargineVerticale - 6 - - - MarchioFile - K:\various\catalogtest\Logo.jpg - - - MarchioAltezza - 470 - - - MarchioLarghezza - 470 - - - MarchioMargine - 350 - - - MarchioAllOrizzontale - Destra - - - MarchioAllVerticale - Alto - - - MarchioTrasparenza - 100 - - - MarchioAggiungi - True - - - ColoreTrasparente - #FFFFFF - - - UsaColoreTrasparente - True - - - ImageLibrary - System.Graphics - - - GeneraleForzaJpg - True - - - GeneraleRotazioneAutomatica - True - - - DirSottoDirectory - True - - - TempoGara - True - - - Orario - False - - - EtichettaOrario - TEMPO : - - - DataFoto - False - - - NumeroFoto - False - - - GeneraleSovrascriviFile - True - - - DirDividiNumFile - 300 - - - DirDividiSuffisso - - - - DirDividiNumCifre - 2 - - - ChunkSize - 200 - - - ThreadsCount - 10 - - - DataPartenza - 01/02/2026 20:30:48 - - - AI_EstraiNumeri - True - - - AI_CartellaModelli - K:\vs\AIFotoONLUS\models\\ - - - AI_PercorsoCsv - K:\various\catalogtest\aioutput\test2.csv - - - AI_UsaGpuNumeri - True - - - AI_IncludiThumbnailNumeri - False - - - AI_LivelloCaricoNumeri - 3 - - - AI_FaceExecutablePath - K:\various\regalamiunsorriso\bin\Face_Recognition_Windows\ - - - AI_FaceOutputFolderPath - K:\various\catalogtest\aioutput\ - - - AI_FaceRecursive - True - - - AI_FaceIncludeThumbnails - False - - - AI_FaceParallelism - 3 - - - AI_FaceMinSize - 35 - - - AI_FaceUpsample - False - - - AI_FaceMatcherExecutablePath - K:\various\regalamiunsorriso\bin\Face_Recognition_Windows\face_matcher.exe - - - AI_FaceMatcherTolerance - 0,75 - - - RaceUpload_Login - - - - RaceUpload_Password - - - - RaceUpload_Description - - - - RaceUpload_TipoGaraId - 1 - - - RaceUpload_StartDate - 12/03/2026 00:00:00 - - - RaceUpload_EndDate - 12/03/2026 00:00:00 - - - RaceUpload_PathBase - - - - RaceUpload_Localita - - - - RaceUpload_EventoInLinea - 0 - - - RaceUpload_TipoIndex - 1 - - - RaceUpload_FreeEvent - 0 - - - RaceUpload_LastRaceId - - - - RaceUpload_RemoteProcessedBasePath - - - \ No newline at end of file diff --git a/CatalogLite/AsyncCommand.cs b/CatalogLite/AsyncCommand.cs deleted file mode 100644 index d030d67..0000000 --- a/CatalogLite/AsyncCommand.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Avalonia.Threading; -using System.Windows.Input; - -namespace CatalogLite; - -public sealed class AsyncCommand : ICommand -{ - private readonly Func _execute; - private readonly Func? _canExecute; - private bool _isExecuting; - - public AsyncCommand(Func execute, Func? canExecute = null) - { - _execute = execute ?? throw new ArgumentNullException(nameof(execute)); - _canExecute = canExecute; - } - - public event EventHandler? CanExecuteChanged; - - public bool CanExecute(object? parameter) => !_isExecuting && (_canExecute?.Invoke() ?? true); - - public async void Execute(object? parameter) - { - if (!CanExecute(parameter)) - { - return; - } - - try - { - _isExecuting = true; - RaiseCanExecuteChanged(); - await _execute().ConfigureAwait(false); - } - finally - { - _isExecuting = false; - RaiseCanExecuteChanged(); - } - } - - public void RaiseCanExecuteChanged() - { - if (Dispatcher.UIThread.CheckAccess()) - { - CanExecuteChanged?.Invoke(this, EventArgs.Empty); - return; - } - - Dispatcher.UIThread.Post(() => CanExecuteChanged?.Invoke(this, EventArgs.Empty)); - } -} \ No newline at end of file diff --git a/CatalogLite/CatalogConfigurationLoader.cs b/CatalogLite/CatalogConfigurationLoader.cs deleted file mode 100644 index a4e4a02..0000000 --- a/CatalogLite/CatalogConfigurationLoader.cs +++ /dev/null @@ -1,321 +0,0 @@ -using System.Globalization; -using System.Reflection; -using System.Xml.Linq; -using MaddoShared; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; - -namespace CatalogLite; - -public sealed class CatalogConfigurationLoader -{ - private const string EmbeddedConfigResourceName = "CatalogLite.Assets.Config.xml"; - private const string EmbeddedLogoResourceName = "CatalogLite.Assets.Logo_RUS_ETS_tricolore_OK.png"; - - public CatalogLiteConfiguration Load(string filePath, PicSettings picSettings) - { - if (string.IsNullOrWhiteSpace(filePath)) - { - throw new ArgumentException("Percorso configurazione non valido.", nameof(filePath)); - } - - if (!File.Exists(filePath)) - { - throw new FileNotFoundException("File configurazione non trovato.", filePath); - } - - var values = ConfigurationValues.Load(filePath); - ApplyPicSettings(values, picSettings); - - var sourcePath = LiteCatalogViewModel.NormalizeDirectoryPath(values.GetString("DirSorgente")); - var destinationPath = LiteCatalogViewModel.NormalizeDirectoryPath(values.GetString("DirDestinazione")); - - picSettings.DirectorySorgente = sourcePath; - picSettings.DirectoryDestinazione = destinationPath; - picSettings.DestDir = string.IsNullOrWhiteSpace(destinationPath) - ? new DirectoryInfo(Environment.CurrentDirectory) - : new DirectoryInfo(destinationPath); - - return new CatalogLiteConfiguration - { - FilePath = filePath, - SourcePath = sourcePath, - DestinationPath = destinationPath, - Options = BuildOptions(values, sourcePath, destinationPath) - }; - } - - public CatalogLiteConfiguration LoadEmbedded(PicSettings picSettings) - { - using var configStream = OpenEmbeddedResource(EmbeddedConfigResourceName); - var values = ConfigurationValues.Load(configStream); - ApplyPicSettings(values, picSettings); - picSettings.LogoData = ReadAllBytes(OpenEmbeddedResource(EmbeddedLogoResourceName)); - picSettings.LogoNomeFile = string.Empty; - - var sourcePath = LiteCatalogViewModel.NormalizeDirectoryPath(values.GetString("DirSorgente")); - var destinationPath = LiteCatalogViewModel.NormalizeDirectoryPath(values.GetString("DirDestinazione")); - - picSettings.DirectorySorgente = sourcePath; - picSettings.DirectoryDestinazione = destinationPath; - picSettings.DestDir = string.IsNullOrWhiteSpace(destinationPath) - ? new DirectoryInfo(Environment.CurrentDirectory) - : new DirectoryInfo(destinationPath); - - return new CatalogLiteConfiguration - { - FilePath = "Configurazione incorporata", - SourcePath = sourcePath, - DestinationPath = destinationPath, - Options = BuildOptions(values, sourcePath, destinationPath) - }; - } - - public static ImageCreationService.Options CloneOptions(ImageCreationService.Options options, string sourcePath, string destinationPath) - { - return new ImageCreationService.Options - { - AggiornaSottodirectory = options.AggiornaSottodirectory, - CreaSottocartelle = options.CreaSottocartelle, - FilePerCartella = options.FilePerCartella, - SuffissoCartelle = options.SuffissoCartelle, - CifreContatore = options.CifreContatore, - NumerazioneType = options.NumerazioneType, - SourcePath = sourcePath, - DestinationPath = destinationPath, - MaxThreads = Math.Max(1, options.MaxThreads), - ChunksSize = options.ChunksSize, - LinearExecution = options.LinearExecution - }; - } - - private static void ApplyPicSettings(ConfigurationValues values, PicSettings settings) - { - settings.DirectorySorgente = values.GetString("DirSorgente"); - settings.DirectoryDestinazione = values.GetString("DirDestinazione"); - settings.TestoFirmaStart = values.GetString("TestoTesto"); - settings.TestoFirmaStartV = values.GetString("TestoVerticale"); - settings.DataPartenza = values.GetDateTime("DataPartenza", DateTime.Now); - settings.TestoOrario = values.GetString("EtichettaOrario"); - settings.DimStandard = values.GetInt("FontDimensione", 20); - settings.DimStandardMiniatura = values.GetInt("FontDimensioneMiniatura", 50); - settings.NomeData = values.GetBool("DataFoto"); - settings.TestoNome = values.GetBool("NumeroFoto"); - settings.UsaOrarioMiniatura = IsThumbnailMode(values, "Time") || values.GetBool("MiniatureAddOrario"); - settings.UsaOrarioTestoApplicare = values.GetBool("Orario"); - settings.UsaTempoGaraTestoApplicare = values.GetBool("TempoGara"); - settings.UsaRotazioneAutomatica = values.GetBool("GeneraleRotazioneAutomatica"); - settings.UsaForzaJpg = values.GetBool("GeneraleForzaJpg"); - settings.LarghezzaSmall = values.GetInt("MiniatureLarghezza", 350); - settings.AltezzaSmall = values.GetInt("MiniatureAltezza", 350); - settings.CreaMiniature = values.GetBool("MiniatureCrea", true); - settings.AggiungiScritteMiniature = IsThumbnailMode(values, "Text") || values.GetBool("MiniatureAddScritta"); - settings.Suffisso = values.GetString("MiniatureSuffisso", "tn_"); - settings.Codice = values.GetString("FotoCodice"); - settings.Trasparenza = values.GetInt("TestoTrasparente", 0); - settings.IlFont = values.GetString("FontNome", "Arial"); - settings.Grassetto = values.GetBool("FontBold"); - settings.Posizione = values.GetString("TestoPosizione", "Basso"); - settings.Allineamento = values.GetString("TestoAllineamento", "Centro"); - settings.Margine = values.GetInt("TestoMargine", 8); - settings.LogoAltezza = values.GetInt("MarchioAltezza", 430); - settings.LogoLarghezza = values.GetInt("MarchioLarghezza", 430); - settings.FontColoreRGB = ParseColor(values.GetString("ColoreTestoRGB", "Yellow"), new Rgba32(255, 255, 0, 255)); - settings.LogoAggiungi = values.GetBool("MarchioAggiungi"); - settings.LogoNomeFile = values.GetString("MarchioFile"); - settings.LogoTrasparenza = values.GetInt("MarchioTrasparenza", 100).ToString(CultureInfo.InvariantCulture); - settings.LogoMargine = values.GetString("MarchioMargine", "0"); - settings.LogoPosizioneH = values.GetString("MarchioAllOrizzontale", "Destra"); - settings.LogoPosizioneV = values.GetString("MarchioAllVerticale", "Basso"); - settings.TransparentColor = values.GetString("ColoreTrasparente", "#FFFFFF"); - settings.UseTransparentColor = values.GetBool("UsaColoreTrasparente"); - settings.FotoGrandeDimOrigina = values.GetBool("FotoDimOriginali"); - settings.AltezzaBig = values.GetInt("FotoAltezza", 2240); - settings.LarghezzaBig = values.GetInt("FotoLarghezza", 2240); - settings.DimVert = values.GetInt("GrandezzaVerticale", 20); - settings.MargVert = values.GetInt("MargineVerticale", 6); - settings.TestoMin = IsThumbnailMode(values, "FileName") || values.GetBool("NomeMiniatura"); - settings.DimMin = values.GetInt("FontDimensioneMiniatura", 50); - settings.SecretDefault = false; - settings.SecretBig = false; - settings.SecretSmall = false; - settings.SecretPathSmall = string.Empty; - settings.SecretPathBig = string.Empty; - settings.AggTempoGaraMin = IsThumbnailMode(values, "RaceTime") || values.GetBool("TempoSmall"); - settings.AggNumTempMin = IsThumbnailMode(values, "FileNameAndTime") || values.GetBool("NumTempoSmall"); - settings.JpegQuality = values.GetLong("CompressioneJpeg", 85); - settings.JpegQualityMin = values.GetLong("CompressioneJpegMiniatura", 30); - settings.FotoRuotaADestra = false; - settings.FotoRuotaASinistra = false; - settings.TempMinText = string.Empty; - settings.OverwriteFiles = values.GetBool("GeneraleSovrascriviFile"); - } - - private static ImageCreationService.Options BuildOptions(ConfigurationValues values, string sourcePath, string destinationPath) - { - var threads = values.GetInt("ThreadsCount", Environment.ProcessorCount); - if (threads <= 0) - { - threads = Environment.ProcessorCount; - } - - return new ImageCreationService.Options - { - AggiornaSottodirectory = values.GetBool("DirSottoDirectory"), - CreaSottocartelle = values.GetBool("DirCreaSottocartelle", values.GetBool("CreateSubfolders")), - FilePerCartella = Math.Max(1, values.GetInt("DirDividiNumFile", 99)), - SuffissoCartelle = values.GetString("DirDividiSuffisso"), - CifreContatore = Math.Max(1, values.GetInt("DirDividiNumCifre", 2)), - NumerazioneType = values.GetBool("DirNumerazioneProgressiva", true) ? NumerazioneType.Progressiva : NumerazioneType.Files, - SourcePath = sourcePath, - DestinationPath = destinationPath, - MaxThreads = Math.Max(1, threads), - ChunksSize = Math.Max(0, values.GetInt("ChunkSize", 0)), - LinearExecution = values.GetBool("UseSequentialProcessing") - }; - } - - private static bool IsThumbnailMode(ConfigurationValues values, string mode) - { - return string.Equals(values.GetString("MiniatureModalita"), mode, StringComparison.OrdinalIgnoreCase); - } - - private static Stream OpenEmbeddedResource(string resourceName) - { - var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName); - return stream ?? throw new InvalidOperationException($"Risorsa incorporata non trovata: {resourceName}"); - } - - private static byte[] ReadAllBytes(Stream stream) - { - using (stream) - { - using var memoryStream = new MemoryStream(); - stream.CopyTo(memoryStream); - return memoryStream.ToArray(); - } - } - - private static Rgba32 ParseColor(string value, Rgba32 fallback) - { - if (string.IsNullOrWhiteSpace(value)) - { - return fallback; - } - - var normalized = value.Trim(); - try - { - if (normalized.StartsWith('#') && normalized.Length == 7) - { - return new Rgba32( - Convert.ToByte(normalized[1..3], 16), - Convert.ToByte(normalized[3..5], 16), - Convert.ToByte(normalized[5..7], 16), - 255); - } - - if (normalized.Length == 6 && normalized.All(Uri.IsHexDigit)) - { - normalized = "#" + normalized; - } - - return Color.Parse(normalized).ToPixel(); - } - catch - { - return fallback; - } - } - - private sealed class ConfigurationValues - { - private readonly Dictionary _values; - - private ConfigurationValues(Dictionary values) - { - _values = values; - } - - public static ConfigurationValues Load(string filePath) - { - using var stream = File.OpenRead(filePath); - return Load(stream); - } - - public static ConfigurationValues Load(Stream stream) - { - var document = XDocument.Load(stream); - var values = document - .Descendants("Setup") - .Where(element => element.Element("Nome") is not null) - .GroupBy(element => element.Element("Nome")!.Value, StringComparer.OrdinalIgnoreCase) - .ToDictionary( - group => group.Key, - group => group.Last().Element("Valore")?.Value ?? string.Empty, - StringComparer.OrdinalIgnoreCase); - - if (values.Count == 0) - { - values = document.Root? - .Descendants() - .Where(element => !element.HasElements) - .GroupBy(element => element.Name.LocalName, StringComparer.OrdinalIgnoreCase) - .ToDictionary(group => group.Key, group => group.Last().Value, StringComparer.OrdinalIgnoreCase) - ?? new Dictionary(StringComparer.OrdinalIgnoreCase); - } - - return new ConfigurationValues(values); - } - - public string GetString(string name, string defaultValue = "") - { - return _values.TryGetValue(name, out var value) && !string.IsNullOrWhiteSpace(value) - ? value.Trim() - : defaultValue; - } - - public bool GetBool(string name, bool defaultValue = false) - { - var value = GetString(name); - if (string.IsNullOrWhiteSpace(value)) - { - return defaultValue; - } - - return value.Trim().ToUpperInvariant() switch - { - "TRUE" or "OK" or "SI" or "SÌ" or "1" or "YES" or "VERO" => true, - "FALSE" or "NO" or "0" or "FALSO" => false, - _ => defaultValue - }; - } - - public int GetInt(string name, int defaultValue = 0) - { - return int.TryParse(GetString(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) - ? value - : defaultValue; - } - - public long GetLong(string name, long defaultValue = 0) - { - return long.TryParse(GetString(name), NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) - ? value - : defaultValue; - } - - public DateTime GetDateTime(string name, DateTime defaultValue) - { - var value = GetString(name); - if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var invariantDate)) - { - return invariantDate; - } - - return DateTime.TryParse(value, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out var localDate) - ? localDate - : defaultValue; - } - } -} \ No newline at end of file diff --git a/CatalogLite/CatalogLite.csproj b/CatalogLite/CatalogLite.csproj deleted file mode 100644 index be2b0bc..0000000 --- a/CatalogLite/CatalogLite.csproj +++ /dev/null @@ -1,81 +0,0 @@ - - - net10.0 - Exe - enable - enable - CatalogLite - CatalogLite - false - 2026-12-31 - true - false - true - true - false - false - embedded - - - - WinExe - - - - - - - - - - - - - - - - - - - - - - - - - - - - <_CatalogLiteExpirationDateIsIso>$([System.Text.RegularExpressions.Regex]::IsMatch('$(CatalogLiteExpirationDate)', '^\d{4}-\d{2}-\d{2}$')) - - - - - - - - - - - <_CatalogLiteForbiddenReference Include="@(ReferencePath)" Condition="$([System.String]::Copy('%(FileName)').StartsWith('AIFotoONLUS')) Or '%(FileName)' == 'Catalog.Communication' Or '%(FileName)' == 'Microsoft.Windows.Compatibility' Or '%(FileName)' == 'System.Drawing.Common' Or '%(FileName)' == 'System.Private.Windows.GdiPlus' Or '%(FileName)' == 'System.Windows.Extensions'" /> - - - - - - - <_CatalogLiteSidecarFile Include="$(PublishDir)**\*.dll.config;$(PublishDir)**\*.pdb" /> - - - - - - - <_CatalogLiteLooseNativeFile Include="$(PublishDir)**\*.dll;$(PublishDir)**\*.so;$(PublishDir)**\*.dylib" /> - - - - \ No newline at end of file diff --git a/CatalogLite/CatalogLiteConfiguration.cs b/CatalogLite/CatalogLiteConfiguration.cs deleted file mode 100644 index 87569e7..0000000 --- a/CatalogLite/CatalogLiteConfiguration.cs +++ /dev/null @@ -1,11 +0,0 @@ -using MaddoShared; - -namespace CatalogLite; - -public sealed class CatalogLiteConfiguration -{ - public required string FilePath { get; init; } - public required string SourcePath { get; init; } - public required string DestinationPath { get; init; } - public required ImageCreationService.Options Options { get; init; } -} \ No newline at end of file diff --git a/CatalogLite/ExpirationGuard.cs b/CatalogLite/ExpirationGuard.cs deleted file mode 100644 index b800cf2..0000000 --- a/CatalogLite/ExpirationGuard.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Globalization; -using System.Reflection; - -namespace CatalogLite; - -internal static class ExpirationGuard -{ - private const string GeneratedMetadataKey = "CatalogLiteGeneratedExpirationDate"; - private const string MetadataKey = "CatalogLiteExpirationDate"; - - public static bool IsExpired(out DateOnly? expirationDate) - { - expirationDate = TryReadExpirationDate(); - return expirationDate is null || DateOnly.FromDateTime(DateTime.Now) > expirationDate.Value; - } - - private static DateOnly? TryReadExpirationDate() - { - if (TryParseDate(BuildExpiration.ExpirationDate, out var generatedDate)) - { - return generatedDate; - } - - var metadata = typeof(Program).Assembly.GetCustomAttributes(); - var metadataValue = metadata.FirstOrDefault(attribute => string.Equals(attribute.Key, GeneratedMetadataKey, StringComparison.Ordinal))?.Value - ?? metadata.FirstOrDefault(attribute => string.Equals(attribute.Key, MetadataKey, StringComparison.Ordinal))?.Value; - - return TryParseDate(metadataValue, out var metadataDate) - ? metadataDate - : null; - } - - private static bool TryParseDate(string? value, out DateOnly date) - { - var trimmedValue = value?.Trim(); - return DateOnly.TryParseExact(trimmedValue, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date) - || DateOnly.TryParse(trimmedValue, CultureInfo.CurrentCulture, DateTimeStyles.None, out date); - } -} \ No newline at end of file diff --git a/CatalogLite/ExpiredWindow.cs b/CatalogLite/ExpiredWindow.cs deleted file mode 100644 index c5b84f1..0000000 --- a/CatalogLite/ExpiredWindow.cs +++ /dev/null @@ -1,52 +0,0 @@ -using Avalonia.Controls; -using Avalonia.Layout; - -namespace CatalogLite; - -internal sealed class ExpiredWindow : Window -{ - public ExpiredWindow(DateOnly? expirationDate) - { - Title = "Catalog Lite"; - Width = 430; - Height = 190; - CanResize = false; - WindowStartupLocation = WindowStartupLocation.CenterScreen; - - var message = expirationDate is null - ? "L'applicazione è scaduta e non può essere utilizzata." - : $"L'applicazione è scaduta il {expirationDate:dd/MM/yyyy} e non può essere utilizzata."; - - var closeButton = new Button - { - Content = "Chiudi", - HorizontalAlignment = HorizontalAlignment.Right, - MinWidth = 96 - }; - closeButton.Click += (_, _) => Close(); - - Content = new Border - { - Padding = new Avalonia.Thickness(22), - Child = new StackPanel - { - Spacing = 14, - Children = - { - new TextBlock - { - Text = "Applicazione scaduta", - FontSize = 18, - FontWeight = Avalonia.Media.FontWeight.SemiBold - }, - new TextBlock - { - Text = message, - TextWrapping = Avalonia.Media.TextWrapping.Wrap - }, - closeButton - } - } - }; - } -} \ No newline at end of file diff --git a/CatalogLite/ImageProcessingCoordinator.cs b/CatalogLite/ImageProcessingCoordinator.cs deleted file mode 100644 index dcf78d7..0000000 --- a/CatalogLite/ImageProcessingCoordinator.cs +++ /dev/null @@ -1,95 +0,0 @@ -using System.Collections.Concurrent; -using System.Diagnostics; -using MaddoShared; -using Microsoft.Extensions.Logging; - -namespace CatalogLite; - -public readonly record struct ImageProcessedUpdate(string Status, int Total, int Processed); - -public sealed class ImageProcessingRunResult -{ - public required string FinalSpeedCounter { get; init; } -} - -public sealed class ImageProcessingCoordinator -{ - private readonly ImageCreationService _imageCreationService; - private readonly ILogger _logger; - - public ImageProcessingCoordinator(ImageCreationService imageCreationService, ILogger logger) - { - _imageCreationService = imageCreationService; - _logger = logger; - } - - public async Task RunAsync( - ImageCreationService.Options options, - CancellationToken token, - Action onImageProcessed, - Action onSpeedUpdated) - { - var results = new ConcurrentBag(); - var recentDiffs = new Queue(); - const int recentWindowSize = 5; - - var currentAmount = 0; - var previousAmount = 0; - var processedAtomic = 0; - var speedWatch = Stopwatch.StartNew(); - - using var speedTimer = new System.Threading.Timer(_ => - { - try - { - previousAmount = currentAmount; - currentAmount = Volatile.Read(ref processedAtomic); - var diff = Math.Max(0, currentAmount - previousAmount); - - lock (recentDiffs) - { - recentDiffs.Enqueue(diff); - if (recentDiffs.Count > recentWindowSize) - { - recentDiffs.Dequeue(); - } - } - - double recentAverage; - lock (recentDiffs) - { - recentAverage = recentDiffs.Count == 0 ? 0.0 : recentDiffs.Average(); - } - - var total = Volatile.Read(ref processedAtomic); - var overall = speedWatch.Elapsed.TotalSeconds > 0 ? total / speedWatch.Elapsed.TotalSeconds : 0.0; - var elapsed = speedWatch.Elapsed; - var elapsedText = $"{(int)elapsed.TotalHours}h {elapsed.Minutes}m {elapsed.Seconds}s"; - - onSpeedUpdated($"{recentAverage:0.00} f/s (media: {overall:0.00} f/s) - {elapsedText}{Environment.NewLine}media: {recentAverage * 60.0:0.00} f/m"); - } - catch (Exception ex) - { - _logger.LogDebug(ex, "Errore durante l'aggiornamento della velocità"); - } - }, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); - - EventHandler> onImageProcessedInternal = (_, args) => - { - var processed = Interlocked.Increment(ref processedAtomic); - onImageProcessed(new ImageProcessedUpdate(args.Item1, args.Item2, processed)); - }; - - await _imageCreationService.CreaCatalogoParallel(options, results, onImageProcessedInternal, token).ConfigureAwait(false); - - speedWatch.Stop(); - var finalProcessed = Volatile.Read(ref processedAtomic); - var finalAverage = speedWatch.Elapsed.TotalSeconds > 0 ? finalProcessed / speedWatch.Elapsed.TotalSeconds : 0.0; - var finalElapsed = speedWatch.Elapsed; - - return new ImageProcessingRunResult - { - FinalSpeedCounter = $"{(int)finalElapsed.TotalHours}h {finalElapsed.Minutes}m {finalElapsed.Seconds}s{Environment.NewLine}media: {finalAverage:0.00} f/s{Environment.NewLine}media: {finalAverage * 60.0:0.00} f/m" - }; - } -} \ No newline at end of file diff --git a/CatalogLite/LiteCatalogViewModel.cs b/CatalogLite/LiteCatalogViewModel.cs deleted file mode 100644 index 92106aa..0000000 --- a/CatalogLite/LiteCatalogViewModel.cs +++ /dev/null @@ -1,359 +0,0 @@ -using MaddoShared; -using Microsoft.Extensions.Logging; - -namespace CatalogLite; - -public sealed class LiteCatalogViewModel : ViewModelBase -{ - private readonly CatalogConfigurationLoader _configurationLoader; - private readonly PicSettings _picSettings; - private readonly ImageCreationService _imageCreationService; - private readonly ImageProcessingCoordinator _imageProcessingCoordinator; - private readonly ILogger _logger; - private CatalogLiteConfiguration? _configuration; - private CancellationTokenSource? _processingTokenSource; - private string _configurationPath = string.Empty; - private string _sourcePath = string.Empty; - private string _destinationPath = string.Empty; - private string _processingStatus = "Caricamento configurazione incorporata..."; - private string _speedCounter = "-"; - private int _processedImagesCount; - private int _totalImagesCount; - private int _progressBarValue; - private int _progressBarMaximum = 100; - private bool _isProcessing; - - public LiteCatalogViewModel( - CatalogConfigurationLoader configurationLoader, - PicSettings picSettings, - ImageCreationService imageCreationService, - ImageProcessingCoordinator imageProcessingCoordinator, - ILogger logger) - { - _configurationLoader = configurationLoader; - _picSettings = picSettings; - _imageCreationService = imageCreationService; - _imageProcessingCoordinator = imageProcessingCoordinator; - _logger = logger; - - SelectSourceFolderCommand = new AsyncCommand(RequestSourceFolderAsync, () => !IsProcessing); - SelectDestinationFolderCommand = new AsyncCommand(RequestDestinationFolderAsync, () => !IsProcessing); - StartProcessingCommand = new AsyncCommand(StartProcessingAsync, CanStartProcessing); - StopProcessingCommand = new AsyncCommand(StopProcessingAsync, () => IsProcessing); - } - - public event EventHandler? SelectSourceFolderRequested; - public event EventHandler? SelectDestinationFolderRequested; - public event EventHandler? ShowMessageRequested; - - public Action? UiInvoker { get; set; } - - public AsyncCommand SelectSourceFolderCommand { get; } - public AsyncCommand SelectDestinationFolderCommand { get; } - public AsyncCommand StartProcessingCommand { get; } - public AsyncCommand StopProcessingCommand { get; } - - public string ConfigurationPath - { - get => _configurationPath; - private set - { - _configurationPath = value; - NotifyPropertyChanged(); - } - } - - public string SourcePath - { - get => _sourcePath; - set - { - _sourcePath = NormalizeDirectoryPath(value); - NotifyPropertyChanged(); - RaiseCommandStates(); - } - } - - public string HorizontalText - { - get => _picSettings.TestoFirmaStart ?? string.Empty; - set - { - _picSettings.TestoFirmaStart = value ?? string.Empty; - NotifyPropertyChanged(); - } - } - - public string VerticalText - { - get => _picSettings.TestoFirmaStartV ?? string.Empty; - set - { - _picSettings.TestoFirmaStartV = value ?? string.Empty; - NotifyPropertyChanged(); - } - } - - public string DestinationPath - { - get => _destinationPath; - set - { - _destinationPath = NormalizeDirectoryPath(value); - NotifyPropertyChanged(); - RaiseCommandStates(); - } - } - - public string ProcessingStatus - { - get => _processingStatus; - private set - { - _processingStatus = value; - NotifyPropertyChanged(); - } - } - - public string SpeedCounter - { - get => _speedCounter; - private set - { - _speedCounter = value; - NotifyPropertyChanged(); - } - } - - public int ProcessedImagesCount - { - get => _processedImagesCount; - private set - { - _processedImagesCount = value; - NotifyPropertyChanged(); - } - } - - public int TotalImagesCount - { - get => _totalImagesCount; - private set - { - _totalImagesCount = value; - NotifyPropertyChanged(); - } - } - - public int ProgressBarValue - { - get => _progressBarValue; - private set - { - _progressBarValue = value; - NotifyPropertyChanged(); - } - } - - public int ProgressBarMaximum - { - get => _progressBarMaximum; - private set - { - _progressBarMaximum = Math.Max(1, value); - NotifyPropertyChanged(); - } - } - - public bool IsProcessing - { - get => _isProcessing; - private set - { - _isProcessing = value; - NotifyPropertyChanged(); - RaiseCommandStates(); - } - } - - public void LoadEmbeddedConfiguration() - { - try - { - var configuration = _configurationLoader.LoadEmbedded(_picSettings); - - _configuration = configuration; - ConfigurationPath = configuration.FilePath; - SourcePath = configuration.SourcePath; - DestinationPath = configuration.DestinationPath; - NotifyPropertyChanged(nameof(HorizontalText)); - NotifyPropertyChanged(nameof(VerticalText)); - ResetProgress("Configurazione incorporata caricata."); - } - catch (Exception ex) - { - _logger.LogError(ex, "Errore durante il caricamento della configurazione incorporata"); - ProcessingStatus = "Errore caricamento configurazione incorporata."; - ShowMessage("Configurazione", $"Impossibile caricare la configurazione incorporata: {ex.GetBaseException().Message}"); - } - } - - public static string NormalizeDirectoryPath(string? path) - { - if (string.IsNullOrWhiteSpace(path)) - { - return string.Empty; - } - - var trimmed = path.Trim().TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - return trimmed + Path.DirectorySeparatorChar; - } - - private Task RequestSourceFolderAsync() - { - SelectSourceFolderRequested?.Invoke(this, EventArgs.Empty); - return Task.CompletedTask; - } - - private Task RequestDestinationFolderAsync() - { - SelectDestinationFolderRequested?.Invoke(this, EventArgs.Empty); - return Task.CompletedTask; - } - - private bool CanStartProcessing() - { - return !IsProcessing - && _configuration is not null - && !string.IsNullOrWhiteSpace(SourcePath) - && !string.IsNullOrWhiteSpace(DestinationPath); - } - - private async Task StartProcessingAsync() - { - if (_configuration is null) - { - ShowMessage("Configurazione", "La configurazione incorporata non e' disponibile."); - return; - } - - if (!Directory.Exists(SourcePath)) - { - ShowMessage("Sorgente", "La cartella sorgente non esiste."); - return; - } - - try - { - Directory.CreateDirectory(DestinationPath); - } - catch (Exception ex) - { - ShowMessage("Destinazione", $"Impossibile usare la cartella destinazione: {ex.GetBaseException().Message}"); - return; - } - - _processingTokenSource?.Dispose(); - _processingTokenSource = new CancellationTokenSource(); - var token = _processingTokenSource.Token; - - var options = CatalogConfigurationLoader.CloneOptions(_configuration.Options, SourcePath, DestinationPath); - _picSettings.DirectorySorgente = SourcePath; - _picSettings.DirectoryDestinazione = DestinationPath; - _picSettings.DestDir = new DirectoryInfo(DestinationPath); - - IsProcessing = true; - ResetProgress("Analisi immagini..."); - - try - { - var total = await Task.Run(() => _imageCreationService.GetFilesToProcessPublic(options).Count, token).ConfigureAwait(false); - RunOnUiThread(() => - { - TotalImagesCount = total; - ProgressBarMaximum = Math.Max(1, total); - ProcessingStatus = total == 0 ? "Nessuna immagine trovata." : "Elaborazione in corso..."; - }); - - if (total == 0) - { - return; - } - - var result = await _imageProcessingCoordinator.RunAsync( - options, - token, - update => RunOnUiThread(() => - { - ProcessedImagesCount = update.Processed; - TotalImagesCount = update.Total; - ProgressBarMaximum = update.Total; - ProgressBarValue = update.Processed; - ProcessingStatus = update.Status; - }), - speed => RunOnUiThread(() => SpeedCounter = speed)).ConfigureAwait(false); - - RunOnUiThread(() => - { - SpeedCounter = result.FinalSpeedCounter; - ProcessingStatus = "Finito."; - }); - } - catch (OperationCanceledException) - { - RunOnUiThread(() => ProcessingStatus = "Operazione annullata."); - } - catch (Exception ex) - { - _logger.LogError(ex, "Errore durante l'elaborazione"); - RunOnUiThread(() => ProcessingStatus = $"Errore: {ex.GetBaseException().Message}"); - } - finally - { - _processingTokenSource?.Dispose(); - _processingTokenSource = null; - RunOnUiThread(() => IsProcessing = false); - } - } - - private Task StopProcessingAsync() - { - _processingTokenSource?.Cancel(); - ProcessingStatus = "Arresto in corso..."; - return Task.CompletedTask; - } - - private void ResetProgress(string status) - { - ProcessingStatus = status; - ProcessedImagesCount = 0; - TotalImagesCount = 0; - ProgressBarValue = 0; - ProgressBarMaximum = 100; - SpeedCounter = "-"; - } - - private void RunOnUiThread(Action action) - { - if (UiInvoker is null) - { - action(); - return; - } - - UiInvoker(action); - } - - private void ShowMessage(string title, string message) - { - RunOnUiThread(() => ShowMessageRequested?.Invoke(this, new LiteMessageEventArgs(title, message))); - } - - private void RaiseCommandStates() - { - SelectSourceFolderCommand.RaiseCanExecuteChanged(); - SelectDestinationFolderCommand.RaiseCanExecuteChanged(); - StartProcessingCommand.RaiseCanExecuteChanged(); - StopProcessingCommand.RaiseCanExecuteChanged(); - } -} \ No newline at end of file diff --git a/CatalogLite/LiteMessageEventArgs.cs b/CatalogLite/LiteMessageEventArgs.cs deleted file mode 100644 index 230c787..0000000 --- a/CatalogLite/LiteMessageEventArgs.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace CatalogLite; - -public sealed class LiteMessageEventArgs : EventArgs -{ - public LiteMessageEventArgs(string title, string message) - { - Title = title; - Message = message; - } - - public string Title { get; } - public string Message { get; } -} \ No newline at end of file diff --git a/CatalogLite/MainWindow.axaml b/CatalogLite/MainWindow.axaml deleted file mode 100644 index 2b80313..0000000 --- a/CatalogLite/MainWindow.axaml +++ /dev/null @@ -1,103 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/CatalogLite/MainWindow.axaml.cs b/CatalogLite/MainWindow.axaml.cs deleted file mode 100644 index 26ec9e8..0000000 --- a/CatalogLite/MainWindow.axaml.cs +++ /dev/null @@ -1,99 +0,0 @@ -using Avalonia.Controls; -using Avalonia.Platform.Storage; -using Avalonia.Threading; -using Microsoft.Extensions.DependencyInjection; - -namespace CatalogLite; - -public partial class MainWindow : Window -{ - private readonly LiteCatalogViewModel _viewModel; - - public MainWindow() - : this(Program.ServiceProvider.GetRequiredService()) - { - } - - public MainWindow(LiteCatalogViewModel viewModel) - { - InitializeComponent(); - - _viewModel = viewModel; - DataContext = _viewModel; - _viewModel.UiInvoker = action => Dispatcher.UIThread.Invoke(action); - _viewModel.SelectSourceFolderRequested += OnSelectSourceFolderRequested; - _viewModel.SelectDestinationFolderRequested += OnSelectDestinationFolderRequested; - _viewModel.ShowMessageRequested += OnShowMessageRequested; - _viewModel.LoadEmbeddedConfiguration(); - } - - private async void OnSelectSourceFolderRequested(object? sender, EventArgs e) - { - var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions - { - Title = "Seleziona cartella sorgente" - }); - - if (folders.Count > 0) - { - _viewModel.SourcePath = LiteCatalogViewModel.NormalizeDirectoryPath(folders[0].Path.LocalPath); - } - } - - private async void OnSelectDestinationFolderRequested(object? sender, EventArgs e) - { - var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions - { - Title = "Seleziona cartella destinazione" - }); - - if (folders.Count > 0) - { - _viewModel.DestinationPath = LiteCatalogViewModel.NormalizeDirectoryPath(folders[0].Path.LocalPath); - } - } - - private async void OnShowMessageRequested(object? sender, LiteMessageEventArgs e) - { - await ShowMessageDialogAsync(e.Title, e.Message); - } - - private async Task ShowMessageDialogAsync(string title, string message) - { - var closeButton = new Button - { - Content = "OK", - HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right, - MinWidth = 92 - }; - - var dialog = new Window - { - Title = title, - Width = 420, - Height = 180, - CanResize = false, - WindowStartupLocation = WindowStartupLocation.CenterOwner, - Content = new Border - { - Padding = new Avalonia.Thickness(20), - Child = new StackPanel - { - Spacing = 14, - Children = - { - new TextBlock - { - Text = message, - TextWrapping = Avalonia.Media.TextWrapping.Wrap - }, - closeButton - } - } - } - }; - - closeButton.Click += (_, _) => dialog.Close(); - await dialog.ShowDialog(this); - } -} \ No newline at end of file diff --git a/CatalogLite/Program.cs b/CatalogLite/Program.cs deleted file mode 100644 index ab18009..0000000 --- a/CatalogLite/Program.cs +++ /dev/null @@ -1,45 +0,0 @@ -using Avalonia; -using MaddoShared; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; - -namespace CatalogLite; - -internal static class Program -{ - public static IServiceProvider ServiceProvider { get; private set; } = default!; - - [STAThread] - public static int Main(string[] args) - { - var services = new ServiceCollection(); - ConfigureServices(services); - ServiceProvider = services.BuildServiceProvider(); - - BuildAvaloniaApp().StartWithClassicDesktopLifetime(args ?? []); - return 0; - } - - public static AppBuilder BuildAvaloniaApp() - => AppBuilder.Configure() - .UsePlatformDetect() - .LogToTrace(); - - private static void ConfigureServices(IServiceCollection services) - { - services.AddSingleton(); - services.AddSingleton(); - services.AddTransient(); - services.AddTransient(sp => sp.GetRequiredService()); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - - services.AddLogging(builder => - { - builder.AddConsole(); - builder.SetMinimumLevel(LogLevel.Information); - }); - } -} \ No newline at end of file diff --git a/CatalogLite/ViewModelBase.cs b/CatalogLite/ViewModelBase.cs deleted file mode 100644 index 7d0647a..0000000 --- a/CatalogLite/ViewModelBase.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.ComponentModel; -using System.Runtime.CompilerServices; - -namespace CatalogLite; - -public abstract class ViewModelBase : INotifyPropertyChanged -{ - public event PropertyChangedEventHandler? PropertyChanged; - - protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } -} \ No newline at end of file diff --git a/CatalogVbLib/CatalogVbLib.vbproj b/CatalogVbLib/CatalogVbLib.vbproj new file mode 100644 index 0000000..dd7243d --- /dev/null +++ b/CatalogVbLib/CatalogVbLib.vbproj @@ -0,0 +1,44 @@ + + + net9.0-windows + Library + false + true + + + embedded + + + embedded + + + + True + Application.myapp + True + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + + + + + + + + \ No newline at end of file diff --git a/CatalogVbLib/ExifReader.vb b/CatalogVbLib/ExifReader.vb new file mode 100644 index 0000000..15a19bd --- /dev/null +++ b/CatalogVbLib/ExifReader.vb @@ -0,0 +1,1068 @@ +'''----------------------------------------------------------------------------- +''' +''' Utility class for reading EXIF data from images. Provides abstraction +''' for most common data and generic utilities for work with all other. +''' +''' +''' Copyright (c) Michal A. Valášek - Altair Communications, 2003 +''' Copmany: http://software.altaircom.net * support@altaircom.net +''' Private: http://www.rider.cz * developer@rider.cz +''' This is free software licensed under GNU Lesser General Public License +''' +''' +''' [altair] 10.9.2003 Created +''' +'''----------------------------------------------------------------------------- +Public Class ExifReader + Implements IDisposable + + Private Image As System.Drawing.Bitmap + + '''----------------------------------------------------------------------------- + ''' + ''' Contains possible values of EXIF tag names (ID) + ''' + ''' See GdiPlusImaging.h + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Enum TagNames + ExifIFD = &H8769 + GpsIFD = &H8825 + NewSubfileType = &HFE + SubfileType = &HFF + ImageWidth = &H100 + ImageHeight = &H101 + BitsPerSample = &H102 + Compression = &H103 + PhotometricInterp = &H106 + ThreshHolding = &H107 + CellWidth = &H108 + CellHeight = &H109 + FillOrder = &H10A + DocumentName = &H10D + ImageDescription = &H10E + EquipMake = &H10F + EquipModel = &H110 + StripOffsets = &H111 + Orientation = &H112 + SamplesPerPixel = &H115 + RowsPerStrip = &H116 + StripBytesCount = &H117 + MinSampleValue = &H118 + MaxSampleValue = &H119 + XResolution = &H11A + YResolution = &H11B + PlanarConfig = &H11C + PageName = &H11D + XPosition = &H11E + YPosition = &H11F + FreeOffset = &H120 + FreeByteCounts = &H121 + GrayResponseUnit = &H122 + GrayResponseCurve = &H123 + T4Option = &H124 + T6Option = &H125 + ResolutionUnit = &H128 + PageNumber = &H129 + TransferFuncition = &H12D + SoftwareUsed = &H131 + DateTime = &H132 + Artist = &H13B + HostComputer = &H13C + Predictor = &H13D + WhitePoint = &H13E + PrimaryChromaticities = &H13F + ColorMap = &H140 + HalftoneHints = &H141 + TileWidth = &H142 + TileLength = &H143 + TileOffset = &H144 + TileByteCounts = &H145 + InkSet = &H14C + InkNames = &H14D + NumberOfInks = &H14E + DotRange = &H150 + TargetPrinter = &H151 + ExtraSamples = &H152 + SampleFormat = &H153 + SMinSampleValue = &H154 + SMaxSampleValue = &H155 + TransferRange = &H156 + JPEGProc = &H200 + JPEGInterFormat = &H201 + JPEGInterLength = &H202 + JPEGRestartInterval = &H203 + JPEGLosslessPredictors = &H205 + JPEGPointTransforms = &H206 + JPEGQTables = &H207 + JPEGDCTables = &H208 + JPEGACTables = &H209 + YCbCrCoefficients = &H211 + YCbCrSubsampling = &H212 + YCbCrPositioning = &H213 + REFBlackWhite = &H214 + ICCProfile = &H8773 + Gamma = &H301 + ICCProfileDescriptor = &H302 + SRGBRenderingIntent = &H303 + ImageTitle = &H320 + Copyright = &H8298 + ResolutionXUnit = &H5001 + ResolutionYUnit = &H5002 + ResolutionXLengthUnit = &H5003 + ResolutionYLengthUnit = &H5004 + PrintFlags = &H5005 + PrintFlagsVersion = &H5006 + PrintFlagsCrop = &H5007 + PrintFlagsBleedWidth = &H5008 + PrintFlagsBleedWidthScale = &H5009 + HalftoneLPI = &H500A + HalftoneLPIUnit = &H500B + HalftoneDegree = &H500C + HalftoneShape = &H500D + HalftoneMisc = &H500E + HalftoneScreen = &H500F + JPEGQuality = &H5010 + GridSize = &H5011 + ThumbnailFormat = &H5012 + ThumbnailWidth = &H5013 + ThumbnailHeight = &H5014 + ThumbnailColorDepth = &H5015 + ThumbnailPlanes = &H5016 + ThumbnailRawBytes = &H5017 + ThumbnailSize = &H5018 + ThumbnailCompressedSize = &H5019 + ColorTransferFunction = &H501A + ThumbnailData = &H501B + ThumbnailImageWidth = &H5020 + ThumbnailImageHeight = &H502 + ThumbnailBitsPerSample = &H5022 + ThumbnailCompression = &H5023 + ThumbnailPhotometricInterp = &H5024 + ThumbnailImageDescription = &H5025 + ThumbnailEquipMake = &H5026 + ThumbnailEquipModel = &H5027 + ThumbnailStripOffsets = &H5028 + ThumbnailOrientation = &H5029 + ThumbnailSamplesPerPixel = &H502A + ThumbnailRowsPerStrip = &H502B + ThumbnailStripBytesCount = &H502C + ThumbnailResolutionX = &H502D + ThumbnailResolutionY = &H502E + ThumbnailPlanarConfig = &H502F + ThumbnailResolutionUnit = &H5030 + ThumbnailTransferFunction = &H5031 + ThumbnailSoftwareUsed = &H5032 + ThumbnailDateTime = &H5033 + ThumbnailArtist = &H5034 + ThumbnailWhitePoint = &H5035 + ThumbnailPrimaryChromaticities = &H5036 + ThumbnailYCbCrCoefficients = &H5037 + ThumbnailYCbCrSubsampling = &H5038 + ThumbnailYCbCrPositioning = &H5039 + ThumbnailRefBlackWhite = &H503A + ThumbnailCopyRight = &H503B + LuminanceTable = &H5090 + ChrominanceTable = &H5091 + FrameDelay = &H5100 + LoopCount = &H5101 + PixelUnit = &H5110 + PixelPerUnitX = &H5111 + PixelPerUnitY = &H5112 + PaletteHistogram = &H5113 + ExifExposureTime = &H829A + ExifFNumber = &H829D + ExifExposureProg = &H8822 + ExifSpectralSense = &H8824 + ExifISOSpeed = &H8827 + ExifOECF = &H8828 + ExifVer = &H9000 + ExifDTOrig = &H9003 + ExifDTDigitized = &H9004 + ExifCompConfig = &H9101 + ExifCompBPP = &H9102 + ExifShutterSpeed = &H9201 + ExifAperture = &H9202 + ExifBrightness = &H9203 + ExifExposureBias = &H9204 + ExifMaxAperture = &H9205 + ExifSubjectDist = &H9206 + ExifMeteringMode = &H9207 + ExifLightSource = &H9208 + ExifFlash = &H9209 + ExifFocalLength = &H920A + ExifMakerNote = &H927C + ExifUserComment = &H9286 + ExifDTSubsec = &H9290 + ExifDTOrigSS = &H9291 + ExifDTDigSS = &H9292 + ExifFPXVer = &HA000 + ExifColorSpace = &HA001 + ExifPixXDim = &HA002 + ExifPixYDim = &HA003 + ExifRelatedWav = &HA004 + ExifInterop = &HA005 + ExifFlashEnergy = &HA20B + ExifSpatialFR = &HA20C + ExifFocalXRes = &HA20E + ExifFocalYRes = &HA20F + ExifFocalResUnit = &HA210 + ExifSubjectLoc = &HA214 + ExifExposureIndex = &HA215 + ExifSensingMethod = &HA217 + ExifFileSource = &HA300 + ExifSceneType = &HA301 + ExifCfaPattern = &HA302 + GpsVer = &H0 + GpsLatitudeRef = &H1 + GpsLatitude = &H2 + GpsLongitudeRef = &H3 + GpsLongitude = &H4 + GpsAltitudeRef = &H5 + GpsAltitude = &H6 + GpsGpsTime = &H7 + GpsGpsSatellites = &H8 + GpsGpsStatus = &H9 + GpsGpsMeasureMode = &HA + GpsGpsDop = &HB + GpsSpeedRef = &HC + GpsSpeed = &HD + GpsTrackRef = &HE + GpsTrack = &HF + GpsImgDirRef = &H10 + GpsImgDir = &H11 + GpsMapDatum = &H12 + GpsDestLatRef = &H13 + GpsDestLat = &H14 + GpsDestLongRef = &H15 + GpsDestLong = &H16 + GpsDestBearRef = &H17 + GpsDestBear = &H18 + GpsDestDistRef = &H19 + GpsDestDist = &H1A + End Enum + + '''----------------------------------------------------------------------------- + ''' + ''' Real position of 0th row and column of picture + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Enum Orientations + TopLeft = 1 + TopRight = 2 + BottomRight = 3 + BottomLeft = 4 + LeftTop = 5 + RightTop = 6 + RightBottom = 7 + LftBottom = 8 + End Enum + + '''----------------------------------------------------------------------------- + ''' + ''' Exposure programs + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Enum ExposurePrograms + Manual = 1 + Normal = 2 + AperturePriority = 3 + ShutterPriority = 4 + Creative = 5 + Action = 6 + Portrait = 7 + Landscape = 8 + End Enum + + '''----------------------------------------------------------------------------- + ''' + ''' Exposure metering modes + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Enum ExposureMeteringModes + Unknown = 0 + Average = 1 + CenterWeightedAverage = 2 + Spot = 3 + MultiSpot = 4 + MultiSegment = 5 + [Partial] = 6 + Other = 255 + End Enum + + '''----------------------------------------------------------------------------- + ''' + ''' Flash activity modes + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Enum FlashModes + NotFired = 0 + Fired = 1 + FiredButNoStrobeReturned = 5 + FiredAndStrobeReturned = 7 + End Enum + + '''----------------------------------------------------------------------------- + ''' + ''' Possible light sources (white balance) + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Enum LightSources + Unknown = 0 + Daylight = 1 + Fluorescent = 2 + Tungsten = 3 + Flash = 10 + StandardLightA = 17 + StandardLightB = 18 + StandardLightC = 19 + D55 = 20 + D65 = 21 + D75 = 22 + Other = 255 + End Enum + + '''----------------------------------------------------------------------------- + ''' + ''' Represents rational which is type of some Exif properties + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Structure Rational + Dim Numerator As Int32 + Dim Denominator As Int32 + + '''----------------------------------------------------------------------------- + ''' + ''' Converts rational to string representation + ''' + ''' Optional, default "/". String to be used as delimiter of components. + ''' String representation of the rational. + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Shadows Function ToString(Optional ByVal Delimiter As String = "/") As String + Return Numerator & Delimiter & Denominator + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Converts rational to double precision real number + ''' + ''' The rational as double precision real number. + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Function ToDouble() As Double + Return Numerator / Denominator + End Function + End Structure + + '''----------------------------------------------------------------------------- + ''' + ''' Initializes new instance of this class. + ''' + ''' Bitmap to read exif information from + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Sub New(ByVal Bitmap As System.Drawing.Bitmap) + If Bitmap Is Nothing Then Throw New ArgumentNullException("Bitmap") + Me.Image = Bitmap + End Sub + + '''----------------------------------------------------------------------------- + ''' + ''' Returns all available data in formatted string form + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Overrides Function ToString() As String + Dim SB As New System.Text.StringBuilder + + SB.Append("Image:") + SB.Append("\n\tDimensions: " & Me.Width & " x " & Me.Height & " px") + SB.Append("\n\tResolution: " & Me.ResolutionX & " x " & Me.ResolutionY & " dpi") + SB.Append("\n\tOrientation: " & [Enum].GetName(GetType(Orientations), Me.Orientation)) + SB.Append("\n\tTitle: " & Me.Title) + SB.Append("\n\tDescription: " & Me.Description) + SB.Append("\n\tCopyright: " & Me.Copyright) + SB.Append("\nEquipment:") + SB.Append("\n\tMaker: " & Me.EquipmentMaker) + SB.Append("\n\tModel: " & Me.EquipmentModel) + SB.Append("\n\tSoftware: " & Me.Software) + SB.Append("\nDate and time:") + SB.Append("\n\tGeneral: " & Me.DateTimeLastModified.ToString()) + SB.Append("\n\tOriginal: " & Me.DateTimeOriginal.ToString()) + SB.Append("\n\tDigitized: " & Me.DateTimeDigitized.ToString()) + SB.Append("\nShooting conditions:") + SB.Append("\n\tExposure time: " & Me.ExposureTime.ToString("N4") & " s") + SB.Append("\n\tExposure program: " & [Enum].GetName(GetType(ExposurePrograms), Me.ExposureProgram)) + SB.Append("\n\tExposure mode: " & [Enum].GetName(GetType(ExposureMeteringModes), Me.ExposureMeteringMode)) + SB.Append("\n\tAperture: F" & Me.Aperture.ToString("N2")) + SB.Append("\n\tISO sensitivity: " & Me.ISO) + SB.Append("\n\tSubject distance: " & Me.SubjectDistance.ToString("N2") & " m") + SB.Append("\n\tFocal length: " & Me.FocalLength) + SB.Append("\n\tFlash: " & [Enum].GetName(GetType(FlashModes), Me.FlashMode)) + SB.Append("\n\tLight source (WB): " & [Enum].GetName(GetType(LightSources), Me.LightSource)) + SB.Append("\n\nCopyright (c) Michal A. Valasek - Altair Communications, 2003") + SB.Append("\nhttp://software.altaircom.net * support@altaircom.net") + + SB.Replace("\n", vbCrLf) + SB.Replace("\t", vbTab) + Return SB.ToString() + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Brand of equipment (EXIF EquipMake) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property EquipmentMaker() As String + Get + Return Me.GetPropertyString(TagNames.EquipMake) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Model of equipment (EXIF EquipModel) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property EquipmentModel() As String + Get + Return Me.GetPropertyString(TagNames.EquipModel) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Software used for processing (EXIF Software) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property Software() As String + Get + Return Me.GetPropertyString(TagNames.SoftwareUsed) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Orientation of image (position of row 0, column 0) (EXIF Orientation) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property Orientation() As Orientations + Get + Dim X As Int32 = Me.GetPropertyInt16(TagNames.Orientation) + + If Not [Enum].IsDefined(GetType(Orientations), X) Then + Return Orientations.TopLeft + Else + Return CType([Enum].Parse(GetType(Orientations), [Enum].GetName(GetType(Orientations), X)), Orientations) + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Time when image was last modified (EXIF DateTime). + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property DateTimeLastModified() As DateTime + Get + Try + Return DateTime.ParseExact(Me.GetPropertyString(TagNames.DateTime), "yyyy\:MM\:dd HH\:mm\:ss", Nothing) + Catch ex As Exception + Return DateTime.MinValue + End Try + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Time when image was taken (EXIF DateTimeOriginal). + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property DateTimeOriginal() As DateTime + Get + Try + Return DateTime.ParseExact(Me.GetPropertyString(TagNames.ExifDTOrig), "yyyy\:MM\:dd HH\:mm\:ss", Nothing) + Catch ex As Exception + Return DateTime.MinValue + End Try + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Time when image was digitized (EXIF DateTimeDigitized). + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property DateTimeDigitized() As DateTime + Get + Try + Return DateTime.ParseExact(Me.GetPropertyString(TagNames.ExifDTDigitized), "yyyy\:MM\:dd HH\:mm\:ss", Nothing) + Catch ex As Exception + Return DateTime.MinValue + End Try + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Image width + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property Width() As Int16 + Get + Return Me.GetPropertyInt16(TagNames.ImageWidth) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Image height + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property Height() As Int16 + Get + Return Me.GetPropertyInt16(TagNames.ImageHeight) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' X resolution in dpi (EXIF XResolution/ResolutionUnit) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property ResolutionX() As Double + Get + Dim R As Double = Me.GetPropertyRational(TagNames.XResolution).ToDouble() + + If Me.GetPropertyInt16(TagNames.ResolutionUnit) = 3 Then + '-- resolution is in points/cm + Return R * 2.54 + Else + '-- resolution is in points/inch + Return R + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Y resolution in dpi (EXIF YResolution/ResolutionUnit) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property ResolutionY() As Double + Get + Dim R As Double = Me.GetPropertyRational(TagNames.YResolution).ToDouble() + + If Me.GetPropertyInt16(TagNames.ResolutionUnit) = 3 Then + '-- resolution is in points/cm + Return R * 2.54 + Else + '-- resolution is in points/inch + Return R + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Image title (EXIF ImageTitle) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property Title() As String + Get + Return Me.GetPropertyString(TagNames.ImageTitle) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Image description (EXIF ImageDescription) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property Description() As String + Get + Return Me.GetPropertyString(TagNames.ImageDescription) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Image copyright (EXIF Copyright) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property Copyright() As String + Get + Return Me.GetPropertyString(TagNames.Copyright) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Exposure time in seconds (EXIF ExifExposureTime/ExifShutterSpeed) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property ExposureTime() As Double + Get + If Me.IsPropertyDefined(TagNames.ExifExposureTime) Then + '-- Exposure time is explicitly specified + Return Me.GetPropertyRational(TagNames.ExifExposureTime).ToDouble + ElseIf Me.IsPropertyDefined(TagNames.ExifShutterSpeed) Then + '-- Compute exposure time from shutter speed + Return 1 / (2 ^ Me.GetPropertyRational(TagNames.ExifShutterSpeed).ToDouble) + Else + '-- Can't figure out + Return 0 + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Aperture value as F number (EXIF ExifFNumber/ExifApertureValue) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property Aperture() As Double + Get + If Me.IsPropertyDefined(TagNames.ExifFNumber) Then + Return Me.GetPropertyRational(TagNames.ExifFNumber).ToDouble() + ElseIf Me.IsPropertyDefined(TagNames.ExifAperture) Then + Return System.Math.Sqrt(2) ^ Me.GetPropertyRational(TagNames.ExifAperture).ToDouble() + Else + Return 0 + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Exposure program used (EXIF ExifExposureProg) + ''' + ''' + ''' If not specified, returns Normal (2) + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property ExposureProgram() As ExposurePrograms + Get + Dim X As Int32 = Me.GetPropertyInt16(TagNames.ExifExposureProg) + + If [Enum].IsDefined(GetType(ExposurePrograms), X) Then + Return CType([Enum].Parse(GetType(ExposurePrograms), [Enum].GetName(GetType(ExposurePrograms), X)), ExposurePrograms) + Else + Return ExposurePrograms.Normal + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' ISO sensitivity + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property ISO() As Int16 + Get + Return Me.GetPropertyInt16(TagNames.ExifISOSpeed) + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Subject distance in meters (EXIF SubjectDistance) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property SubjectDistance() As Double + Get + Return Me.GetPropertyRational(TagNames.ExifSubjectDist).ToDouble() + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Exposure method metering mode used (EXIF MeteringMode) + ''' + ''' + ''' If not specified, returns Unknown (0) + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property ExposureMeteringMode() As ExposureMeteringModes + Get + Dim X As Int32 = Me.GetPropertyInt16(TagNames.ExifMeteringMode) + + If [Enum].IsDefined(GetType(ExposureMeteringModes), X) Then + Return CType([Enum].Parse(GetType(ExposureMeteringModes), [Enum].GetName(GetType(ExposureMeteringModes), X)), ExposureMeteringModes) + Else + Return ExposureMeteringModes.Unknown + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Focal length of lenses in mm (EXIF FocalLength) + ''' + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property FocalLength() As Double + Get + Return Me.GetPropertyRational(TagNames.ExifFocalLength).ToDouble + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Flash mode (EXIF Flash) + ''' + ''' + ''' If not present, value NotFired (0) is returned + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property FlashMode() As FlashModes + Get + Dim X As Int32 = Me.GetPropertyInt16(TagNames.ExifFlash) + + If [Enum].IsDefined(GetType(FlashModes), X) Then + Return CType([Enum].Parse(GetType(FlashModes), [Enum].GetName(GetType(FlashModes), X)), FlashModes) + Else + Return FlashModes.NotFired + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Light source / white balance (EXIF LightSource) + ''' + ''' + ''' If not specified, returns Unknown (0). + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public ReadOnly Property LightSource() As LightSources + Get + Dim X As Int32 = Me.GetPropertyInt16(TagNames.ExifLightSource) + + If [Enum].IsDefined(GetType(LightSources), X) Then + Return CType([Enum].Parse(GetType(LightSources), [Enum].GetName(GetType(LightSources), X)), LightSources) + Else + Return LightSources.Unknown + End If + End Get + End Property + + '''----------------------------------------------------------------------------- + ''' + ''' Checks if current image has specified certain property + ''' + ''' + ''' True if image has specified property, False otherwise. + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Function IsPropertyDefined(ByVal PID As Int32) As Boolean + Return CBool([Array].IndexOf(Me.Image.PropertyIdList, PID) > -1) + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Gets specified Int32 property + ''' + ''' Property ID + ''' Optional, default 0. Default value returned if property is not present. + ''' Value of property or DefaultValue if property is not present. + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Function GetPropertyInt32(ByVal PID As Int32, Optional ByVal DefaultValue As Int32 = 0) As Int32 + If Me.IsPropertyDefined(PID) Then + Return GetInt32(Me.Image.GetPropertyItem(PID).Value) + Else + Return DefaultValue + End If + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Gets specified Int16 property + ''' + ''' Property ID + ''' Optional, default 0. Default value returned if property is not present. + ''' Value of property or DefaultValue if property is not present. + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Function GetPropertyInt16(ByVal PID As Int32, Optional ByVal DefaultValue As Int16 = 0) As Int16 + If Me.IsPropertyDefined(PID) Then + Return GetInt16(Me.Image.GetPropertyItem(PID).Value) + Else + Return DefaultValue + End If + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Gets specified string property + ''' + ''' Property ID + ''' Optional, default String.Empty. Default value returned if property is not present. + ''' + ''' Value of property or DefaultValue if property is not present. + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Function GetPropertyString(ByVal PID As Int32, Optional ByVal DefaultValue As String = "") As String + If Me.IsPropertyDefined(PID) Then + Return GetString(Me.Image.GetPropertyItem(PID).Value) + Else + Return DefaultValue + End If + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Gets specified rational property + ''' + ''' Property ID + ''' + ''' Value of property or 0/1 if not present. + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Function GetPropertyRational(ByVal PID As Int32) As Rational + If Me.IsPropertyDefined(PID) Then + Return GetRational(Me.Image.GetPropertyItem(PID).Value) + Else + Dim R As Rational + R.Numerator = 0 + R.Denominator = 1 + Return R + End If + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Reads Int32 from EXIF bytearray. + ''' + ''' EXIF bytearray to process + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Shared Function GetInt32(ByVal B As Byte()) As Int32 + If B.Length < 4 Then Throw New ArgumentException("Data too short (4 bytes expected)", "B") + Return B(3) << 24 Or B(2) << 16 Or B(1) << 8 Or B(0) + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Reads Int16 from EXIF bytearray. + ''' + ''' EXIF bytearray to process + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Shared Function GetInt16(ByVal B As Byte()) As Int16 + If B.Length < 2 Then Throw New ArgumentException("Data too short (2 bytes expected)", "B") + Return B(1) << 8 Or B(0) + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Reads string from EXIF bytearray. + ''' + ''' EXIF bytearray to process + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Shared Function GetString(ByVal B As Byte()) As String + Dim R As String = System.Text.Encoding.ASCII.GetString(B) + If R.EndsWith(vbNullChar) Then R = R.Substring(0, R.Length - 1) + Return R + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Reads rational from EXIF bytearray. + ''' + ''' EXIF bytearray to process + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Shared Function GetRational(ByVal B As Byte()) As Rational + Dim R As New Rational, N(3), D(3) As Byte + Array.Copy(B, 0, N, 0, 4) + Array.Copy(B, 4, D, 0, 4) + R.Denominator = GetInt32(D) + R.Numerator = GetInt32(N) + Return R + End Function + + '''----------------------------------------------------------------------------- + ''' + ''' Disposes unmanaged resources of this class + ''' + ''' + ''' + ''' [altair] 10.9.2003 Created + ''' + '''----------------------------------------------------------------------------- + Public Sub Dispose() Implements System.IDisposable.Dispose + Me.Image.Dispose() + End Sub +End Class diff --git a/CatalogVbLib/My Project/Application.Designer.vb b/CatalogVbLib/My Project/Application.Designer.vb new file mode 100644 index 0000000..88dd01c --- /dev/null +++ b/CatalogVbLib/My Project/Application.Designer.vb @@ -0,0 +1,13 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + diff --git a/CatalogVbLib/My Project/Application.myapp b/CatalogVbLib/My Project/Application.myapp new file mode 100644 index 0000000..758895d --- /dev/null +++ b/CatalogVbLib/My Project/Application.myapp @@ -0,0 +1,10 @@ + + + false + false + 0 + true + 0 + 1 + true + diff --git a/CatalogVbLib/My Project/AssemblyInfo.vb b/CatalogVbLib/My Project/AssemblyInfo.vb new file mode 100644 index 0000000..4d58ddf --- /dev/null +++ b/CatalogVbLib/My Project/AssemblyInfo.vb @@ -0,0 +1,9 @@ +Imports System +Imports System.Reflection +Imports System.Runtime.InteropServices + + + + +'Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi + diff --git a/CatalogVbLib/My Project/Resources.Designer.vb b/CatalogVbLib/My Project/Resources.Designer.vb new file mode 100644 index 0000000..176c107 --- /dev/null +++ b/CatalogVbLib/My Project/Resources.Designer.vb @@ -0,0 +1,63 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + +Imports System + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + ''' + ''' A strongly-typed resource class, for looking up localized strings, etc. + ''' + _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + ''' + ''' Returns the cached ResourceManager instance used by this class. + ''' + _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("CatalogVbLib.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + ''' + ''' Overrides the current thread's CurrentUICulture property for all + ''' resource lookups using this strongly typed resource class. + ''' + _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/CatalogVbLib/My Project/Resources.resx b/CatalogVbLib/My Project/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/CatalogVbLib/My Project/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/CatalogVbLib/My Project/Settings.Designer.vb b/CatalogVbLib/My Project/Settings.Designer.vb new file mode 100644 index 0000000..9abf647 --- /dev/null +++ b/CatalogVbLib/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' +' This code was generated by a tool. +' Runtime Version:4.0.30319.42000 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + _ + Friend Module MySettingsProperty + + _ + Friend ReadOnly Property Settings() As Global.CatalogVbLib.My.MySettings + Get + Return Global.CatalogVbLib.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/CatalogVbLib/My Project/Settings.settings b/CatalogVbLib/My Project/Settings.settings new file mode 100644 index 0000000..85b890b --- /dev/null +++ b/CatalogVbLib/My Project/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/CatalogVbLib/PicSettings.vb b/CatalogVbLib/PicSettings.vb new file mode 100644 index 0000000..42a0da7 --- /dev/null +++ b/CatalogVbLib/PicSettings.vb @@ -0,0 +1,606 @@ +Imports System.IO +Imports System.Drawing.Drawing2D +Imports System.Drawing.Imaging +Imports System.Windows.Forms +Imports System.Drawing + +Public Module PicSettings + + Private _DirectorySorgente As String + Private _DirectoryDestinazione As String + + Private _DimVert As Integer + Private _MargVert As Integer + + + Private _DimStandard As Integer + Private _DimStandardMiniatura As Integer + + Private _NomeData As Boolean + Private _TestoNome As Boolean + Private _UsaOrarioMiniatura As Boolean + Private _UsaOrarioTestoApplicare As Boolean + Private _UsaTempoGaraTestoApplicare As Boolean + Private _TestoFirmaStart As String + Private _TestoFirmaStartV As String + Private _DataPartenza As DateTime + Private _TestoOrario As String + + Private _UsaRotazioneAutomatica As Boolean + Private _UsaForzaJpg As Boolean + + Private _LarghezzaSmall As Integer + Private _AltezzaSmall As Integer + + Private _CreaMiniature As Boolean + Private _AggiungiScritteMiniature As Boolean + Private _AggTempoGaraMin As Boolean + Private _AggNumTempMin As Boolean + + Private _Suffisso As String + Private _Codice As String + + Private _Trasparenza As Integer + Private _IlFont As String + Private _Grassetto As Boolean + + Private _Posizione As String + Private _Allineamento As String + Private _Margine As Integer + + Private _LogoAltezza As Integer + Private _LogoLarghezza As Integer + + Private _fontColoreRGB As System.Drawing.Color + + Private _LogoAggiungi As Boolean + Private _LogoNomeFile As String + Private _LogoTrasparenza As String + Private _LogoMargine As String + Private _LogoPosizioneH As String + Private _LogoPosizioneV As String + + Private _FotoGrandeDimOrigina As Boolean + Private _AltezzaBig As Integer + Private _LarghezzaBig As Integer + Private _DestDir As DirectoryInfo + Private _DimMin As Integer + + Private _TestoMin As Boolean + + Private _SecretDefault As Boolean + Private _SecretBig As Boolean + Private _SecretSmall As Boolean + + Private _SecretPathSmall As String + Private _SecretPathBig As String + + Private _jpegQuality As Long + Private _jpegQualityMin As Long + + Private FotoRuotaADestra As Boolean = False + Private FotoRuotaASinistra As Boolean = False + + Private TempMinText As String = "" + + Private _mainForm As Form + + 'Private progressBar As System.Windows.Forms.ProgressBar + + + + Public Property mainForm() As Form + Get + Return _mainForm + End Get + Set(ByVal value As Form) + _mainForm = value + End Set + End Property + + Public Property DirectorySorgente() As String + Get + Return _DirectorySorgente + End Get + Set(ByVal value As String) + _DirectorySorgente = value + End Set + End Property + + Public Property DirectoryDestinazione() As String + Get + Return _DirectoryDestinazione + End Get + Set(ByVal value As String) + _DirectoryDestinazione = value + End Set + End Property + + Public Property TestoFirmaStart() As String + Get + Return _TestoFirmaStart + End Get + Set(ByVal value As String) + _TestoFirmaStart = value + End Set + End Property + + Public Property TestoFirmaStartV() As String + Get + Return _TestoFirmaStartV + End Get + + Set(ByVal value As String) + _TestoFirmaStartV = value + End Set + End Property + + Public Property DataPartenza() As DateTime + Get + Return _DataPartenza + End Get + Set(ByVal value As DateTime) + _DataPartenza = value + End Set + End Property + + Public Property TestoOrario() As String + Get + Return _TestoOrario + End Get + Set(ByVal value As String) + _TestoOrario = value + End Set + End Property + + Public Property DimStandard() As Integer + Get + Return _DimStandard + End Get + Set(ByVal value As Integer) + _DimStandard = value + End Set + End Property + + Public Property DimStandardMiniatura() As Integer + Get + Return _DimStandardMiniatura + End Get + Set(ByVal value As Integer) + _DimStandardMiniatura = value + End Set + End Property + + Public Property NomeData() As Boolean + Get + Return _NomeData + End Get + Set(ByVal value As Boolean) + _NomeData = value + End Set + End Property + + Public Property TestoNome() As Boolean + Get + Return _TestoNome + End Get + Set(ByVal value As Boolean) + _TestoNome = value + End Set + End Property + + Public Property UsaOrarioMiniatura() As Boolean + Get + Return _UsaOrarioMiniatura + End Get + Set(ByVal value As Boolean) + _UsaOrarioMiniatura = value + End Set + End Property + + Public Property UsaOrarioTestoApplicare() As Boolean + Get + Return _UsaOrarioTestoApplicare + End Get + Set(ByVal value As Boolean) + _UsaOrarioTestoApplicare = value + End Set + End Property + + Public Property UsaTempoGaraTestoApplicare() As Boolean + Get + Return _UsaTempoGaraTestoApplicare + End Get + Set(ByVal value As Boolean) + _UsaTempoGaraTestoApplicare = value + End Set + End Property + + Public Property UsaRotazioneAutomatica() As Boolean + Get + Return _UsaRotazioneAutomatica + End Get + Set(ByVal value As Boolean) + _UsaRotazioneAutomatica = value + End Set + End Property + + Public Property UsaForzaJpg() As Boolean + Get + Return _UsaForzaJpg + End Get + Set(ByVal value As Boolean) + _UsaForzaJpg = value + End Set + End Property + + + + Public Property LarghezzaSmall() As Integer + Get + Return _LarghezzaSmall + End Get + Set(ByVal value As Integer) + _LarghezzaSmall = value + End Set + End Property + + Public Property AltezzaSmall() As Integer + Get + Return _AltezzaSmall + End Get + Set(ByVal value As Integer) + _AltezzaSmall = value + End Set + End Property + + + Public Property CreaMiniature() As Boolean + Get + Return _CreaMiniature + End Get + Set(ByVal value As Boolean) + _CreaMiniature = value + End Set + End Property + + Public Property AggiungiScritteMiniature() As Boolean + Get + Return _AggiungiScritteMiniature + End Get + Set(ByVal value As Boolean) + _AggiungiScritteMiniature = value + End Set + End Property + + + Public Property Suffisso() As String + Get + Return _Suffisso + End Get + Set(ByVal value As String) + _Suffisso = value + End Set + End Property + + Public Property Codice() As String + Get + Return _Codice + End Get + Set(ByVal value As String) + _Codice = value + End Set + End Property + + + Public Property Trasparenza() As Integer + Get + Return _Trasparenza + End Get + Set(ByVal value As Integer) + _Trasparenza = value + End Set + End Property + + Public Property IlFont() As String + Get + Return _IlFont + End Get + Set(ByVal value As String) + _IlFont = value + End Set + End Property + + Public Property Grassetto() As Boolean + Get + Return _Grassetto + End Get + Set(ByVal value As Boolean) + _Grassetto = value + End Set + End Property + + Public Property Posizione() As String + Get + Return _Posizione + End Get + Set(ByVal value As String) + _Posizione = value + End Set + End Property + + Public Property Allineamento() As String + Get + Return _Allineamento + End Get + Set(ByVal value As String) + _Allineamento = value + End Set + End Property + + Public Property Margine() As Integer + Get + Return _Margine + End Get + Set(ByVal value As Integer) + _Margine = value + End Set + End Property + + Public Property LogoAltezza() As Integer + Get + Return _LogoAltezza + End Get + Set(ByVal value As Integer) + _LogoAltezza = value + End Set + End Property + + Public Property LogoLarghezza() As Integer + Get + Return _LogoLarghezza + End Get + Set(ByVal value As Integer) + _LogoLarghezza = value + End Set + End Property + + Public Property fontColoreRGB() As Color + Get + Return _fontColoreRGB + End Get + Set(ByVal value As Color) + _fontColoreRGB = value + End Set + End Property + + Public Property LogoAggiungi() As Boolean + Get + Return _LogoAggiungi + End Get + Set(ByVal value As Boolean) + _LogoAggiungi = value + End Set + End Property + + Public Property LogoNomeFile() As String + Get + Return _LogoNomeFile + End Get + Set(ByVal value As String) + _LogoNomeFile = value + End Set + End Property + + Public Property LogoTrasparenza() As String + Get + Return _LogoTrasparenza + End Get + Set(ByVal value As String) + _LogoTrasparenza = value + End Set + End Property + + Public Property LogoMargine() As String + Get + Return _LogoMargine + End Get + Set(ByVal value As String) + _LogoMargine = value + End Set + End Property + + Public Property LogoPosizioneH() As String + Get + Return _LogoPosizioneH + End Get + Set(ByVal value As String) + _LogoPosizioneH = value + End Set + End Property + + Public Property LogoPosizioneV() As String + Get + Return _LogoPosizioneV + End Get + Set(ByVal value As String) + _LogoPosizioneV = value + End Set + End Property + + Public Property FotoGrandeDimOrigina() As Boolean + Get + Return _FotoGrandeDimOrigina + End Get + Set(ByVal value As Boolean) + _FotoGrandeDimOrigina = value + End Set + End Property + + Public Property AltezzaBig() As Integer + Get + Return _AltezzaBig + End Get + Set(ByVal value As Integer) + _AltezzaBig = value + End Set + End Property + + Public Property LarghezzaBig() As Integer + Get + Return _LarghezzaBig + End Get + Set(ByVal value As Integer) + _LarghezzaBig = value + End Set + End Property + + Public Property DestDir() As DirectoryInfo + Get + Return _DestDir + End Get + Set(ByVal value As DirectoryInfo) + _DestDir = value + End Set + End Property + + Public Property DimVert() As Integer + Get + Return _DimVert + + End Get + Set(ByVal value As Integer) + _DimVert = value + + End Set + End Property + + Public Property MargVert() As Integer + Get + Return _MargVert + + End Get + Set(ByVal value As Integer) + _MargVert = value + End Set + End Property + + Public Property TestoMin() As Boolean + Get + Return _TestoMin + + End Get + Set(ByVal value As Boolean) + _TestoMin = value + + End Set + End Property + + Public Property DimMin() As Integer + Get + Return _DimMin + + End Get + Set(ByVal value As Integer) + _DimMin = value + + End Set + End Property + + Public Property SecretDefault() As Boolean + Get + Return _SecretDefault + + End Get + Set(ByVal value As Boolean) + _SecretDefault = value + + End Set + End Property + + Public Property SecretBig() As Boolean + Get + Return _SecretBig + + End Get + Set(ByVal value As Boolean) + _SecretBig = value + + End Set + End Property + + Public Property SecretSmall() As Boolean + Get + Return _SecretSmall + + End Get + Set(ByVal value As Boolean) + _SecretSmall = value + + End Set + End Property + + Public Property SecretPathSmall() As String + Get + Return _SecretPathSmall + + End Get + Set(ByVal value As String) + _SecretPathSmall = value + + End Set + End Property + + Public Property SecretPathBig() As String + Get + Return _SecretPathBig + + End Get + Set(ByVal value As String) + _SecretPathBig = value + + End Set + End Property + + Public Property AggTempoGaraMin() As Boolean + Get + Return _AggTempoGaraMin + + End Get + Set(ByVal value As Boolean) + _AggTempoGaraMin = value + + End Set + End Property + + Public Property AggNumTempMin() As Boolean + Get + Return _AggNumTempMin + + End Get + Set(ByVal value As Boolean) + _AggNumTempMin = value + + End Set + End Property + + Public Property jpegQuality() As Long + Get + Return _jpegQuality + End Get + Set(ByVal value As Long) + _jpegQuality = value + End Set + + End Property + + Public Property jpegQualityMin() As Long + Get + Return _jpegQualityMin + End Get + Set(ByVal value As Long) + _jpegQualityMin = value + End Set + + End Property +End Module diff --git a/ImageCatalogCS/AboutForm.Designer.cs b/ImageCatalogCS/AboutForm.Designer.cs new file mode 100644 index 0000000..01cd505 --- /dev/null +++ b/ImageCatalogCS/AboutForm.Designer.cs @@ -0,0 +1,101 @@ +namespace ImageCatalogCS +{ + partial class AboutForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutForm)); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.button1 = new System.Windows.Forms.Button(); + this.pictureBox1 = new System.Windows.Forms.PictureBox(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); + this.SuspendLayout(); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 213); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(75, 13); + this.label1.TabIndex = 0; + this.label1.Text = "Image Catalog"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(350, 213); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(66, 13); + this.label2.TabIndex = 1; + this.label2.Text = "Versione 3.0"; + // + // button1 + // + this.button1.Location = new System.Drawing.Point(176, 239); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 2; + this.button1.Text = "Chiudi"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // pictureBox1 + // + this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); + this.pictureBox1.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.InitialImage"))); + this.pictureBox1.Location = new System.Drawing.Point(15, 13); + this.pictureBox1.Name = "pictureBox1"; + this.pictureBox1.Size = new System.Drawing.Size(401, 197); + this.pictureBox1.TabIndex = 3; + this.pictureBox1.TabStop = false; + // + // AboutForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(433, 274); + this.Controls.Add(this.pictureBox1); + this.Controls.Add(this.button1); + this.Controls.Add(this.label2); + this.Controls.Add(this.label1); + this.Name = "AboutForm"; + this.Text = "AboutForm"; + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Button button1; + private System.Windows.Forms.PictureBox pictureBox1; + } +} \ No newline at end of file diff --git a/ImageCatalogCS/AboutForm.cs b/ImageCatalogCS/AboutForm.cs new file mode 100644 index 0000000..80e20f9 --- /dev/null +++ b/ImageCatalogCS/AboutForm.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ImageCatalogCS +{ + public partial class AboutForm : Form + { + public AboutForm() + { + InitializeComponent(); + } + + private void button1_Click(object sender, EventArgs e) + { + this.Close(); + } + } +} diff --git a/ImageCatalogCS/AboutForm.resx b/ImageCatalogCS/AboutForm.resx new file mode 100644 index 0000000..02a449f --- /dev/null +++ b/ImageCatalogCS/AboutForm.resx @@ -0,0 +1,229 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + iVBORw0KGgoAAAANSUhEUgAAAZ4AAADQCAIAAAC4O5DwAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAS + cwAAEnMBjCK5BwAAC05JREFUeF7t2sGBG0cORmEn4PPmooCUxO7FGTgaJ+NgtE0OKZMeTTdQDVQBf7/v + 4svuDLsK9boo6bcfACCHtAEQRNoACCJtAASRNgCCSBsAQaQNgCDSBkAQaQMgiLQBEETaAAgibQAEkTYA + gkgbAEGkDYAg0gZAEGkDIIi0ARBE2gAIIm0ABJE2AIJIGwBBpA2AINIGQBBpAyCItAEQRNoACCJtAASR + NgCCSBsAQaQNgCDSBkAQaQMgiLQBEETaAAgibQAEkTYAgkgbAEGkDYAg0pbqr++/Dfn259+PnwBhjEci + 0hZndFBtvv/1+DXoifGYi7SdkzuvX+Gt3QTjsQ5pG/H3n98eU7QaL+uCGI8KSJtHnZn9NxJXAONRCWkz + qTu0b/gmsgbjUdDKtB0PRIG9aDK1r1asmvsPlUSO2cXGo8WRfViXNsNQLL5GNxzbF3MX74Jpu+Z4HG90 + lZ1dlTbLXCwsW+7YHm5+2F+sTVvCa6UtvWr7q7N0PAy/vMberkmbZTSWrU/Y4OxyTtWJDzUlb9dJ25zx + 2Hj2beZ4lD68L1akzfTOm3IgP5k2tzeD+z9yZUgftWukbep4bEYWacJ4WJZh/f7OT5tt6ReUbfbc3px6 + TOcQpy6pftpWjMdmfNcSx8O0Fqt3eHbabOs9fVVGXnUxAh7Vfujy1lU7bevGY3N2pTLGo+gxfjM5bbZl + nrwkSwd3E3Odsk5wzuVNOG3G8fjP478ZAvYsejxsPy9n2Gymps24vFPXwzS4vz/+myTumNuOYcICq6bN + tKDf/vff5Jdj0GpFjkfFw/xmYtqMb7+ZM2/5SN//sJ7az7toPvChD234reGLLJk203hsm25++BITEjUe + Bc/zm2lpMy7EzJU43uNtFE2fe/9DW8Y3+rGPP3bsbzQf0adlE29mGo9NxwkJGY+CR/rVrLRZR3/aMhzu + i3VuTZ/YMAWf3+hnHa554K9US5txPCz/y6oTEjAe1l2Pn22DOWkz7NuHWWtwtCfPz2Gf8ENHPyrlrB/9 + 0rD11kqbdTw2rSfk9HhYt33Fbk9Jm3nuw07avv3P87INsWU4+GlZ229+2jPMW/y0YtiNPAvWf0LOjYd5 + 3ycd7RcT0na0+z/Nmfb9j/P+GaKrsP/z8nZ/9/eGLLt5xJ/mbLafZzw2EhNyZjyKne4X+WkzD/2UZ9/d + iX9/gv1tG5mzM0N0iuu5B5h3+Wn6pJt4l0llQk6Mx/4SvJp8cctOm/3BC876iQ3/QvxRKEIkbV5MSN0j + npw2+8RXHPWEN+jujyRt3TAhG3vbpn7+1LQVfWYzBteMtH12nQmx7/7Ebc9MW/ey7T/A0CbtLwlp64YJ + +eDY/mmPkJi2io/rEz9mu2vS+bSTtl+40IQUPOx5aetftqNn8A/a/s8ruwwGjt3+oJE2JuTJMQCTtj4r + bfuvs3d1N+zoKXyf/OCntT7sV00bE/JUrm1JadMom+E57B8+8EcV5E7bh9bPfMeEPFVrW07aPINe+/V9 + 3GjT5z/+Mc1P+WDafur79EzIk2cGJjxLStp0ymYauaOHsCxH9WU4cjZtH1quAhPyYFqIp/y2ZaRNqWwb + 8+N83i3z/7V72YLSdtdvLZiQD7XalpA2z5S3GGPXjo1oH7bQtN1N+MISiAn5UKpt8WlzDXmTCc4d3V7H + +Nei03bTaV2YkLtKhz88bYpl26SNrsCN7SYjbZtGq8OE3BQ6/tFpcz1ar2OdcXo7XUx2JaVt02hImBBn + 4FMfLjhtwmXbBL+Y2z3/jry0bS57uW84IXXaFpu2Qs3OEnWGWz7811LT1uuMX3xCytxuQtPmK1vbS8vp + V7PSde0hOW3N1uzKE1ImAqFp881373vL6FkWu609paet33G/6oRUqUBk2nzPJHF18TyyaNQ+TEhbz5G5 + 3oQ4r6xpDx2Ytot8Hf21rydY7EG/8Hz+naeNqF/jw3+dCfFtdNrTB6bN90TSdxh87dyfQ13jRdFbkWtb + XNoufWmDz4kbHO/E8py7m7SjcWkrcg1FE8N1o23VOa9tSS0IS1uRWyj6GP1qymuxuhLXtrC0cWmD39jV + jekprsS1LSptXNowYuzmxvgUV+HaFpW2EldQNDR0cWN+ahNKW4kbKFoaaRsDVFuFHgSlzTmeTCb+Qdvk + eP+cIePatiZtfJ/Ai5G2MUKlFQhCTNoqRBptjfxdAte20gp8jVuSNsYSb0baxuuxsgJFIG0oYOArKWmr + zPuyStjNmLQVuH6is4G0MUSVXTVtvHDxbuAbKWmrjLQBd3wjFbM+CaQNFZA2Mc4NTbiDkzZUQNrEkDbg + hrSJIW3ADWkTsz4JpA0V+NPG35CWRtqAG9KmhX+yC9wM/Ls23o+VOTc0owgxaSvwIOiMtIkhbcAN30fF + OIuQ8Z6KSRt/2IYzuLSpKRAE0ob1uLSp8e1oym4GpY1vpFfyc7eDXlH+svFyrK1CD4LSVqHSyPLl5sbs + I2WTU+CP2sLSVuFZEMOxlxFtGygbr8biKtx0otLmfBjSVtGKyDjfiXeUrbgSF52wtPmehuEsaX7bBn4j + w1NeiRiEpY1rm4LJd6iRsDE69ZVoQVzauLYpGGnb4GYO/SrK1kCNFMSljWubhMHgeOdz6L624ZXYQI0S + BKaNa5uG0epYt3Qwnne8EBvwbXDalgamrcoj4aQz7dl8WbjhZj7xOmzBtc95exqZtirPhLNORygDA9ND + lRtOaNq4tskoFzfC1oVrdBIjEJo2X9sY1tJKxY1ZaaNMA2LT5nsurm21+S7hiRiURjyvxNQ3VnDaytxG + EaLA1Y0LWyt1AhCdtjrRRoi1VzcmpJlCX9vC0+ZqG9e2DlbVjenop9Dpj08bbVM0O29c11qqdPYT0uZ5 + Pia4kVl5433XlWdC0nc5I220TVhu36haZ57ZyD/4KWnztI1h7ig8cLziBNQ69jlpo20XcTpxJE1HsUOf + lDbHYzLcKoydY8M1OV5zU64zWWmjbcCVVCtbXtocj0rbgObKlS0xbbStiN19EF76qz73EgUPe2LaHF9K + GbRU+3Onufi7s8e8RSt41FPTRtvK2N8JteW/1tMWYD7oE/89RG7a7PdUxi3b0fRNHLpURyOn8pyVVCxb + dtrsT03b0h2+Z/qf+sNpI2wJap7x9LTRtkqON6Pv2T/+hsCIZTB/M5s8WvlpMz86gzeDZTf65c3w/mS8 + cpQ93hPSZr+48W1hCtMwtimB7WgxWkmsZZu/AVPSVvj5L8q4IcX7xitzOeMWrBikOWkrvQQXZX3dlCyD + NWpMVC7jPiyZoFlpE7kniLEXosjO2Ht8x3UtVe0zPS1t5oVgHOfy5O1mxaA6i3bHSzJb8QM9MW3WU0Tb + pvPm7SG3HoMf6oYRmqD6aZ6aNmPned+uMHIz+mx4kk+E7B1Zm8O0YSuP8ty0GQ8QbVslpm+rULVpbIOy + dENmp81Ye4Z0oYZ942U4V4dDPD9ttnVhVldrEjgGZT7TaCy/naxImy1uXNxKqFs4BmQRy0gUeOOsSZsp + boxuJXUSx1ysZTi6Ja7Sq9JmWSG+a5RkuXLHYxhqMLziimzVurRZzggv6OJyM8f2l9PoQrIybVA0Wjuu + ZQhF2gAIIm0ABJE2AIJIGwBBpA2AINIGQBBpAyCItAEQRNoACCJtAASRNgCCSBsAQaQNgCDSBkAQaQMg + iLQBEETaAAgibQAEkTYAgkgbAEGkDYAg0gZAEGkDIIi0ARBE2gAIIm0ABJE2AIJIGwBBpA2AINIGQBBp + AyCItAEQRNoACCJtAASRNgCCSBsAQaQNgCDSBkAQaQMgiLQBEETaAAgibQAEkTYAgkgbAEGkDYAg0gZA + EGkDIIi0ARBE2gAIIm0ABJE2AIJIGwA5P378HyuEmb0husDDAAAAAElFTkSuQmCC + + + + + iVBORw0KGgoAAAANSUhEUgAAAZ4AAADQCAIAAAC4O5DwAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAS + cwAAEnMBjCK5BwAAC05JREFUeF7t2sGBG0cORmEn4PPmooCUxO7FGTgaJ+NgtE0OKZMeTTdQDVQBf7/v + 4svuDLsK9boo6bcfACCHtAEQRNoACCJtAASRNgCCSBsAQaQNgCDSBkAQaQMgiLQBEETaAAgibQAEkTYA + gkgbAEGkDYAg0gZAEGkDIIi0ARBE2gAIIm0ABJE2AIJIGwBBpA2AINIGQBBpAyCItAEQRNoACCJtAASR + NgCCSBsAQaQNgCDSBkAQaQMgiLQBEETaAAgibQAEkTYAgkgbAEGkDYAg0pbqr++/Dfn259+PnwBhjEci + 0hZndFBtvv/1+DXoifGYi7SdkzuvX+Gt3QTjsQ5pG/H3n98eU7QaL+uCGI8KSJtHnZn9NxJXAONRCWkz + qTu0b/gmsgbjUdDKtB0PRIG9aDK1r1asmvsPlUSO2cXGo8WRfViXNsNQLL5GNxzbF3MX74Jpu+Z4HG90 + lZ1dlTbLXCwsW+7YHm5+2F+sTVvCa6UtvWr7q7N0PAy/vMberkmbZTSWrU/Y4OxyTtWJDzUlb9dJ25zx + 2Hj2beZ4lD68L1akzfTOm3IgP5k2tzeD+z9yZUgftWukbep4bEYWacJ4WJZh/f7OT5tt6ReUbfbc3px6 + TOcQpy6pftpWjMdmfNcSx8O0Fqt3eHbabOs9fVVGXnUxAh7Vfujy1lU7bevGY3N2pTLGo+gxfjM5bbZl + nrwkSwd3E3Odsk5wzuVNOG3G8fjP478ZAvYsejxsPy9n2Gymps24vFPXwzS4vz/+myTumNuOYcICq6bN + tKDf/vff5Jdj0GpFjkfFw/xmYtqMb7+ZM2/5SN//sJ7az7toPvChD234reGLLJk203hsm25++BITEjUe + Bc/zm2lpMy7EzJU43uNtFE2fe/9DW8Y3+rGPP3bsbzQf0adlE29mGo9NxwkJGY+CR/rVrLRZR3/aMhzu + i3VuTZ/YMAWf3+hnHa554K9US5txPCz/y6oTEjAe1l2Pn22DOWkz7NuHWWtwtCfPz2Gf8ENHPyrlrB/9 + 0rD11kqbdTw2rSfk9HhYt33Fbk9Jm3nuw07avv3P87INsWU4+GlZ229+2jPMW/y0YtiNPAvWf0LOjYd5 + 3ycd7RcT0na0+z/Nmfb9j/P+GaKrsP/z8nZ/9/eGLLt5xJ/mbLafZzw2EhNyZjyKne4X+WkzD/2UZ9/d + iX9/gv1tG5mzM0N0iuu5B5h3+Wn6pJt4l0llQk6Mx/4SvJp8cctOm/3BC876iQ3/QvxRKEIkbV5MSN0j + npw2+8RXHPWEN+jujyRt3TAhG3vbpn7+1LQVfWYzBteMtH12nQmx7/7Ebc9MW/ey7T/A0CbtLwlp64YJ + +eDY/mmPkJi2io/rEz9mu2vS+bSTtl+40IQUPOx5aetftqNn8A/a/s8ruwwGjt3+oJE2JuTJMQCTtj4r + bfuvs3d1N+zoKXyf/OCntT7sV00bE/JUrm1JadMom+E57B8+8EcV5E7bh9bPfMeEPFVrW07aPINe+/V9 + 3GjT5z/+Mc1P+WDafur79EzIk2cGJjxLStp0ymYauaOHsCxH9WU4cjZtH1quAhPyYFqIp/y2ZaRNqWwb + 8+N83i3z/7V72YLSdtdvLZiQD7XalpA2z5S3GGPXjo1oH7bQtN1N+MISiAn5UKpt8WlzDXmTCc4d3V7H + +Nei03bTaV2YkLtKhz88bYpl26SNrsCN7SYjbZtGq8OE3BQ6/tFpcz1ar2OdcXo7XUx2JaVt02hImBBn + 4FMfLjhtwmXbBL+Y2z3/jry0bS57uW84IXXaFpu2Qs3OEnWGWz7811LT1uuMX3xCytxuQtPmK1vbS8vp + V7PSde0hOW3N1uzKE1ImAqFp881373vL6FkWu609paet33G/6oRUqUBk2nzPJHF18TyyaNQ+TEhbz5G5 + 3oQ4r6xpDx2Ytot8Hf21rydY7EG/8Hz+naeNqF/jw3+dCfFtdNrTB6bN90TSdxh87dyfQ13jRdFbkWtb + XNoufWmDz4kbHO/E8py7m7SjcWkrcg1FE8N1o23VOa9tSS0IS1uRWyj6GP1qymuxuhLXtrC0cWmD39jV + jekprsS1LSptXNowYuzmxvgUV+HaFpW2EldQNDR0cWN+ahNKW4kbKFoaaRsDVFuFHgSlzTmeTCb+Qdvk + eP+cIePatiZtfJ/Ai5G2MUKlFQhCTNoqRBptjfxdAte20gp8jVuSNsYSb0baxuuxsgJFIG0oYOArKWmr + zPuyStjNmLQVuH6is4G0MUSVXTVtvHDxbuAbKWmrjLQBd3wjFbM+CaQNFZA2Mc4NTbiDkzZUQNrEkDbg + hrSJIW3ADWkTsz4JpA0V+NPG35CWRtqAG9KmhX+yC9wM/Ls23o+VOTc0owgxaSvwIOiMtIkhbcAN30fF + OIuQ8Z6KSRt/2IYzuLSpKRAE0ob1uLSp8e1oym4GpY1vpFfyc7eDXlH+svFyrK1CD4LSVqHSyPLl5sbs + I2WTU+CP2sLSVuFZEMOxlxFtGygbr8biKtx0otLmfBjSVtGKyDjfiXeUrbgSF52wtPmehuEsaX7bBn4j + w1NeiRiEpY1rm4LJd6iRsDE69ZVoQVzauLYpGGnb4GYO/SrK1kCNFMSljWubhMHgeOdz6L624ZXYQI0S + BKaNa5uG0epYt3Qwnne8EBvwbXDalgamrcoj4aQz7dl8WbjhZj7xOmzBtc95exqZtirPhLNORygDA9ND + lRtOaNq4tskoFzfC1oVrdBIjEJo2X9sY1tJKxY1ZaaNMA2LT5nsurm21+S7hiRiURjyvxNQ3VnDaytxG + EaLA1Y0LWyt1AhCdtjrRRoi1VzcmpJlCX9vC0+ZqG9e2DlbVjenop9Dpj08bbVM0O29c11qqdPYT0uZ5 + Pia4kVl5433XlWdC0nc5I220TVhu36haZ57ZyD/4KWnztI1h7ig8cLziBNQ69jlpo20XcTpxJE1HsUOf + lDbHYzLcKoydY8M1OV5zU64zWWmjbcCVVCtbXtocj0rbgObKlS0xbbStiN19EF76qz73EgUPe2LaHF9K + GbRU+3Onufi7s8e8RSt41FPTRtvK2N8JteW/1tMWYD7oE/89RG7a7PdUxi3b0fRNHLpURyOn8pyVVCxb + dtrsT03b0h2+Z/qf+sNpI2wJap7x9LTRtkqON6Pv2T/+hsCIZTB/M5s8WvlpMz86gzeDZTf65c3w/mS8 + cpQ93hPSZr+48W1hCtMwtimB7WgxWkmsZZu/AVPSVvj5L8q4IcX7xitzOeMWrBikOWkrvQQXZX3dlCyD + NWpMVC7jPiyZoFlpE7kniLEXosjO2Ht8x3UtVe0zPS1t5oVgHOfy5O1mxaA6i3bHSzJb8QM9MW3WU0Tb + pvPm7SG3HoMf6oYRmqD6aZ6aNmPned+uMHIz+mx4kk+E7B1Zm8O0YSuP8ty0GQ8QbVslpm+rULVpbIOy + dENmp81Ye4Z0oYZ942U4V4dDPD9ttnVhVldrEjgGZT7TaCy/naxImy1uXNxKqFs4BmQRy0gUeOOsSZsp + boxuJXUSx1ysZTi6Ja7Sq9JmWSG+a5RkuXLHYxhqMLziimzVurRZzggv6OJyM8f2l9PoQrIybVA0Wjuu + ZQhF2gAIIm0ABJE2AIJIGwBBpA2AINIGQBBpAyCItAEQRNoACCJtAASRNgCCSBsAQaQNgCDSBkAQaQMg + iLQBEETaAAgibQAEkTYAgkgbAEGkDYAg0gZAEGkDIIi0ARBE2gAIIm0ABJE2AIJIGwBBpA2AINIGQBBp + AyCItAEQRNoACCJtAASRNgCCSBsAQaQNgCDSBkAQaQMgiLQBEETaAAgibQAEkTYAgkgbAEGkDYAg0gZA + EGkDIIi0ARBE2gAIIm0ABJE2AIJIGwA5P378HyuEmb0husDDAAAAAElFTkSuQmCC + + + \ No newline at end of file diff --git a/ImageCatalogCS/App.config b/ImageCatalogCS/App.config new file mode 100644 index 0000000..4bfa005 --- /dev/null +++ b/ImageCatalogCS/App.config @@ -0,0 +1,6 @@ + + + + + + diff --git a/ImageCatalogCS/CreaImmagineSeparateThread.cs b/ImageCatalogCS/CreaImmagineSeparateThread.cs new file mode 100644 index 0000000..4444736 --- /dev/null +++ b/ImageCatalogCS/CreaImmagineSeparateThread.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ImageCatalogCS +{ + class CreaImmagineSeparateThread + { + } +} diff --git a/ImageCatalogCS/ExifReader.cs b/ImageCatalogCS/ExifReader.cs new file mode 100644 index 0000000..9f801be --- /dev/null +++ b/ImageCatalogCS/ExifReader.cs @@ -0,0 +1,1166 @@ +using Microsoft.VisualBasic; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +///----------------------------------------------------------------------------- +/// +/// Utility class for reading EXIF data from images. Provides abstraction +/// for most common data and generic utilities for work with all other. +/// +/// +/// Copyright (c) Michal A. Valášek - Altair Communications, 2003 +/// Copmany: http://software.altaircom.net * support@altaircom.net +/// Private: http://www.rider.cz * developer@rider.cz +/// This is free software licensed under GNU Lesser General Public License +/// +/// +/// [altair] 10.9.2003 Created +/// +///----------------------------------------------------------------------------- +public class ExifReader : IDisposable +{ + + + private System.Drawing.Bitmap Image; + ///----------------------------------------------------------------------------- + /// + /// Contains possible values of EXIF tag names (ID) + /// + /// See GdiPlusImaging.h + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public enum TagNames + { + ExifIFD = 0x8769, + GpsIFD = 0x8825, + NewSubfileType = 0xfe, + SubfileType = 0xff, + ImageWidth = 0x100, + ImageHeight = 0x101, + BitsPerSample = 0x102, + Compression = 0x103, + PhotometricInterp = 0x106, + ThreshHolding = 0x107, + CellWidth = 0x108, + CellHeight = 0x109, + FillOrder = 0x10a, + DocumentName = 0x10d, + ImageDescription = 0x10e, + EquipMake = 0x10f, + EquipModel = 0x110, + StripOffsets = 0x111, + Orientation = 0x112, + SamplesPerPixel = 0x115, + RowsPerStrip = 0x116, + StripBytesCount = 0x117, + MinSampleValue = 0x118, + MaxSampleValue = 0x119, + XResolution = 0x11a, + YResolution = 0x11b, + PlanarConfig = 0x11c, + PageName = 0x11d, + XPosition = 0x11e, + YPosition = 0x11f, + FreeOffset = 0x120, + FreeByteCounts = 0x121, + GrayResponseUnit = 0x122, + GrayResponseCurve = 0x123, + T4Option = 0x124, + T6Option = 0x125, + ResolutionUnit = 0x128, + PageNumber = 0x129, + TransferFuncition = 0x12d, + SoftwareUsed = 0x131, + DateTime = 0x132, + Artist = 0x13b, + HostComputer = 0x13c, + Predictor = 0x13d, + WhitePoint = 0x13e, + PrimaryChromaticities = 0x13f, + ColorMap = 0x140, + HalftoneHints = 0x141, + TileWidth = 0x142, + TileLength = 0x143, + TileOffset = 0x144, + TileByteCounts = 0x145, + InkSet = 0x14c, + InkNames = 0x14d, + NumberOfInks = 0x14e, + DotRange = 0x150, + TargetPrinter = 0x151, + ExtraSamples = 0x152, + SampleFormat = 0x153, + SMinSampleValue = 0x154, + SMaxSampleValue = 0x155, + TransferRange = 0x156, + JPEGProc = 0x200, + JPEGInterFormat = 0x201, + JPEGInterLength = 0x202, + JPEGRestartInterval = 0x203, + JPEGLosslessPredictors = 0x205, + JPEGPointTransforms = 0x206, + JPEGQTables = 0x207, + JPEGDCTables = 0x208, + JPEGACTables = 0x209, + YCbCrCoefficients = 0x211, + YCbCrSubsampling = 0x212, + YCbCrPositioning = 0x213, + REFBlackWhite = 0x214, + ICCProfile = 0x8773, + Gamma = 0x301, + ICCProfileDescriptor = 0x302, + SRGBRenderingIntent = 0x303, + ImageTitle = 0x320, + Copyright = 0x8298, + ResolutionXUnit = 0x5001, + ResolutionYUnit = 0x5002, + ResolutionXLengthUnit = 0x5003, + ResolutionYLengthUnit = 0x5004, + PrintFlags = 0x5005, + PrintFlagsVersion = 0x5006, + PrintFlagsCrop = 0x5007, + PrintFlagsBleedWidth = 0x5008, + PrintFlagsBleedWidthScale = 0x5009, + HalftoneLPI = 0x500a, + HalftoneLPIUnit = 0x500b, + HalftoneDegree = 0x500c, + HalftoneShape = 0x500d, + HalftoneMisc = 0x500e, + HalftoneScreen = 0x500f, + JPEGQuality = 0x5010, + GridSize = 0x5011, + ThumbnailFormat = 0x5012, + ThumbnailWidth = 0x5013, + ThumbnailHeight = 0x5014, + ThumbnailColorDepth = 0x5015, + ThumbnailPlanes = 0x5016, + ThumbnailRawBytes = 0x5017, + ThumbnailSize = 0x5018, + ThumbnailCompressedSize = 0x5019, + ColorTransferFunction = 0x501a, + ThumbnailData = 0x501b, + ThumbnailImageWidth = 0x5020, + ThumbnailImageHeight = 0x502, + ThumbnailBitsPerSample = 0x5022, + ThumbnailCompression = 0x5023, + ThumbnailPhotometricInterp = 0x5024, + ThumbnailImageDescription = 0x5025, + ThumbnailEquipMake = 0x5026, + ThumbnailEquipModel = 0x5027, + ThumbnailStripOffsets = 0x5028, + ThumbnailOrientation = 0x5029, + ThumbnailSamplesPerPixel = 0x502a, + ThumbnailRowsPerStrip = 0x502b, + ThumbnailStripBytesCount = 0x502c, + ThumbnailResolutionX = 0x502d, + ThumbnailResolutionY = 0x502e, + ThumbnailPlanarConfig = 0x502f, + ThumbnailResolutionUnit = 0x5030, + ThumbnailTransferFunction = 0x5031, + ThumbnailSoftwareUsed = 0x5032, + ThumbnailDateTime = 0x5033, + ThumbnailArtist = 0x5034, + ThumbnailWhitePoint = 0x5035, + ThumbnailPrimaryChromaticities = 0x5036, + ThumbnailYCbCrCoefficients = 0x5037, + ThumbnailYCbCrSubsampling = 0x5038, + ThumbnailYCbCrPositioning = 0x5039, + ThumbnailRefBlackWhite = 0x503a, + ThumbnailCopyRight = 0x503b, + LuminanceTable = 0x5090, + ChrominanceTable = 0x5091, + FrameDelay = 0x5100, + LoopCount = 0x5101, + PixelUnit = 0x5110, + PixelPerUnitX = 0x5111, + PixelPerUnitY = 0x5112, + PaletteHistogram = 0x5113, + ExifExposureTime = 0x829a, + ExifFNumber = 0x829d, + ExifExposureProg = 0x8822, + ExifSpectralSense = 0x8824, + ExifISOSpeed = 0x8827, + ExifOECF = 0x8828, + ExifVer = 0x9000, + ExifDTOrig = 0x9003, + ExifDTDigitized = 0x9004, + ExifCompConfig = 0x9101, + ExifCompBPP = 0x9102, + ExifShutterSpeed = 0x9201, + ExifAperture = 0x9202, + ExifBrightness = 0x9203, + ExifExposureBias = 0x9204, + ExifMaxAperture = 0x9205, + ExifSubjectDist = 0x9206, + ExifMeteringMode = 0x9207, + ExifLightSource = 0x9208, + ExifFlash = 0x9209, + ExifFocalLength = 0x920a, + ExifMakerNote = 0x927c, + ExifUserComment = 0x9286, + ExifDTSubsec = 0x9290, + ExifDTOrigSS = 0x9291, + ExifDTDigSS = 0x9292, + ExifFPXVer = 0xa000, + ExifColorSpace = 0xa001, + ExifPixXDim = 0xa002, + ExifPixYDim = 0xa003, + ExifRelatedWav = 0xa004, + ExifInterop = 0xa005, + ExifFlashEnergy = 0xa20b, + ExifSpatialFR = 0xa20c, + ExifFocalXRes = 0xa20e, + ExifFocalYRes = 0xa20f, + ExifFocalResUnit = 0xa210, + ExifSubjectLoc = 0xa214, + ExifExposureIndex = 0xa215, + ExifSensingMethod = 0xa217, + ExifFileSource = 0xa300, + ExifSceneType = 0xa301, + ExifCfaPattern = 0xa302, + GpsVer = 0x0, + GpsLatitudeRef = 0x1, + GpsLatitude = 0x2, + GpsLongitudeRef = 0x3, + GpsLongitude = 0x4, + GpsAltitudeRef = 0x5, + GpsAltitude = 0x6, + GpsGpsTime = 0x7, + GpsGpsSatellites = 0x8, + GpsGpsStatus = 0x9, + GpsGpsMeasureMode = 0xa, + GpsGpsDop = 0xb, + GpsSpeedRef = 0xc, + GpsSpeed = 0xd, + GpsTrackRef = 0xe, + GpsTrack = 0xf, + GpsImgDirRef = 0x10, + GpsImgDir = 0x11, + GpsMapDatum = 0x12, + GpsDestLatRef = 0x13, + GpsDestLat = 0x14, + GpsDestLongRef = 0x15, + GpsDestLong = 0x16, + GpsDestBearRef = 0x17, + GpsDestBear = 0x18, + GpsDestDistRef = 0x19, + GpsDestDist = 0x1a + } + + ///----------------------------------------------------------------------------- + /// + /// Real position of 0th row and column of picture + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public enum Orientations + { + TopLeft = 1, + TopRight = 2, + BottomRight = 3, + BottomLeft = 4, + LeftTop = 5, + RightTop = 6, + RightBottom = 7, + LftBottom = 8 + } + + ///----------------------------------------------------------------------------- + /// + /// Exposure programs + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public enum ExposurePrograms + { + Manual = 1, + Normal = 2, + AperturePriority = 3, + ShutterPriority = 4, + Creative = 5, + Action = 6, + Portrait = 7, + Landscape = 8 + } + + ///----------------------------------------------------------------------------- + /// + /// Exposure metering modes + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public enum ExposureMeteringModes + { + Unknown = 0, + Average = 1, + CenterWeightedAverage = 2, + Spot = 3, + MultiSpot = 4, + MultiSegment = 5, + Partial = 6, + Other = 255 + } + + ///----------------------------------------------------------------------------- + /// + /// Flash activity modes + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public enum FlashModes + { + NotFired = 0, + Fired = 1, + FiredButNoStrobeReturned = 5, + FiredAndStrobeReturned = 7 + } + + ///----------------------------------------------------------------------------- + /// + /// Possible light sources (white balance) + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public enum LightSources + { + Unknown = 0, + Daylight = 1, + Fluorescent = 2, + Tungsten = 3, + Flash = 10, + StandardLightA = 17, + StandardLightB = 18, + StandardLightC = 19, + D55 = 20, + D65 = 21, + D75 = 22, + Other = 255 + } + + ///----------------------------------------------------------------------------- + /// + /// Represents rational which is type of some Exif properties + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public struct Rational + { + public Int32 Numerator; + + public Int32 Denominator; + ///----------------------------------------------------------------------------- + /// + /// Converts rational to string representation + /// + /// Optional, default "/". String to be used as delimiter of components. + /// String representation of the rational. + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public new string ToString(string Delimiter = "/") + { + return Numerator + Delimiter + Denominator; + } + + ///----------------------------------------------------------------------------- + /// + /// Converts rational to double precision real number + /// + /// The rational as double precision real number. + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public double ToDouble() + { + return Numerator / Denominator; + } + } + + ///----------------------------------------------------------------------------- + /// + /// Initializes new instance of this class. + /// + /// Bitmap to read exif information from + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public ExifReader(System.Drawing.Bitmap Bitmap) + { + if (Bitmap == null) + throw new ArgumentNullException("Bitmap"); + this.Image = Bitmap; + } + + ///----------------------------------------------------------------------------- + /// + /// Returns all available data in formatted string form + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public override string ToString() + { + System.Text.StringBuilder SB = new System.Text.StringBuilder(); + + SB.Append("Image:"); + SB.Append("\\n\\tDimensions: " + this.Width + " x " + this.Height + " px"); + SB.Append("\\n\\tResolution: " + this.ResolutionX + " x " + this.ResolutionY + " dpi"); + SB.Append("\\n\\tOrientation: " + Enum.GetName(typeof(Orientations), this.Orientation)); + SB.Append("\\n\\tTitle: " + this.Title); + SB.Append("\\n\\tDescription: " + this.Description); + SB.Append("\\n\\tCopyright: " + this.Copyright); + SB.Append("\\nEquipment:"); + SB.Append("\\n\\tMaker: " + this.EquipmentMaker); + SB.Append("\\n\\tModel: " + this.EquipmentModel); + SB.Append("\\n\\tSoftware: " + this.Software); + SB.Append("\\nDate and time:"); + SB.Append("\\n\\tGeneral: " + this.DateTimeLastModified.ToString()); + SB.Append("\\n\\tOriginal: " + this.DateTimeOriginal.ToString()); + SB.Append("\\n\\tDigitized: " + this.DateTimeDigitized.ToString()); + SB.Append("\\nShooting conditions:"); + SB.Append("\\n\\tExposure time: " + this.ExposureTime.ToString("N4") + " s"); + SB.Append("\\n\\tExposure program: " + Enum.GetName(typeof(ExposurePrograms), this.ExposureProgram)); + SB.Append("\\n\\tExposure mode: " + Enum.GetName(typeof(ExposureMeteringModes), this.ExposureMeteringMode)); + SB.Append("\\n\\tAperture: F" + this.Aperture.ToString("N2")); + SB.Append("\\n\\tISO sensitivity: " + this.ISO); + SB.Append("\\n\\tSubject distance: " + this.SubjectDistance.ToString("N2") + " m"); + SB.Append("\\n\\tFocal length: " + this.FocalLength); + SB.Append("\\n\\tFlash: " + Enum.GetName(typeof(FlashModes), this.FlashMode)); + SB.Append("\\n\\tLight source (WB): " + Enum.GetName(typeof(LightSources), this.LightSource)); + SB.Append("\\n\\nCopyright (c) Michal A. Valasek - Altair Communications, 2003"); + SB.Append("\\nhttp://software.altaircom.net * support@altaircom.net"); + + SB.Replace("\\n", System.Environment.NewLine); + SB.Replace("\\t", "\t"); + return SB.ToString(); + } + + ///----------------------------------------------------------------------------- + /// + /// Brand of equipment (EXIF EquipMake) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public string EquipmentMaker + { + get { return this.GetPropertyString((int)TagNames.EquipMake); } + } + + ///----------------------------------------------------------------------------- + /// + /// Model of equipment (EXIF EquipModel) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public string EquipmentModel + { + get { return this.GetPropertyString((int)TagNames.EquipModel); } + } + + ///----------------------------------------------------------------------------- + /// + /// Software used for processing (EXIF Software) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public string Software + { + get { return this.GetPropertyString((int)TagNames.SoftwareUsed); } + } + + ///----------------------------------------------------------------------------- + /// + /// Orientation of image (position of row 0, column 0) (EXIF Orientation) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public Orientations Orientation + { + get + { + Int32 X = this.GetPropertyInt16((int)TagNames.Orientation); + + if (!Enum.IsDefined(typeof(Orientations), X)) + { + return Orientations.TopLeft; + } + else + { + return (Orientations)Enum.Parse(typeof(Orientations), Enum.GetName(typeof(Orientations), X)); + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Time when image was last modified (EXIF DateTime). + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public DateTime DateTimeLastModified + { + get + { + try + { + return DateTime.ParseExact(this.GetPropertyString((int)TagNames.DateTime), "yyyy\\:MM\\:dd HH\\:mm\\:ss", null); + } + catch (Exception ex) + { + return DateTime.MinValue; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Time when image was taken (EXIF DateTimeOriginal). + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public DateTime DateTimeOriginal + { + get + { + try + { + return DateTime.ParseExact(this.GetPropertyString((int)TagNames.ExifDTOrig), "yyyy\\:MM\\:dd HH\\:mm\\:ss", null); + } + catch (Exception ex) + { + return DateTime.MinValue; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Time when image was digitized (EXIF DateTimeDigitized). + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public DateTime DateTimeDigitized + { + get + { + try + { + return DateTime.ParseExact(this.GetPropertyString((int)TagNames.ExifDTDigitized), "yyyy\\:MM\\:dd HH\\:mm\\:ss", null); + } + catch (Exception ex) + { + return DateTime.MinValue; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Image width + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public Int16 Width + { + get { return this.GetPropertyInt16((int)TagNames.ImageWidth); } + } + + ///----------------------------------------------------------------------------- + /// + /// Image height + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public Int16 Height + { + get { return this.GetPropertyInt16((int)TagNames.ImageHeight); } + } + + ///----------------------------------------------------------------------------- + /// + /// X resolution in dpi (EXIF XResolution/ResolutionUnit) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public double ResolutionX + { + get + { + double R = this.GetPropertyRational((int)TagNames.XResolution).ToDouble(); + + if (this.GetPropertyInt16((int)TagNames.ResolutionUnit) == 3) + { + //-- resolution is in points/cm + return R * 2.54; + } + else + { + //-- resolution is in points/inch + return R; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Y resolution in dpi (EXIF YResolution/ResolutionUnit) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public double ResolutionY + { + get + { + double R = this.GetPropertyRational((int)TagNames.YResolution).ToDouble(); + + if (this.GetPropertyInt16((int)TagNames.ResolutionUnit) == 3) + { + //-- resolution is in points/cm + return R * 2.54; + } + else + { + //-- resolution is in points/inch + return R; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Image title (EXIF ImageTitle) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public string Title + { + get { return this.GetPropertyString((int)TagNames.ImageTitle); } + } + + ///----------------------------------------------------------------------------- + /// + /// Image description (EXIF ImageDescription) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public string Description + { + get { return this.GetPropertyString((int)TagNames.ImageDescription); } + } + + ///----------------------------------------------------------------------------- + /// + /// Image copyright (EXIF Copyright) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public string Copyright + { + get { return this.GetPropertyString((int)TagNames.Copyright); } + } + + ///----------------------------------------------------------------------------- + /// + /// Exposure time in seconds (EXIF ExifExposureTime/ExifShutterSpeed) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public double ExposureTime + { + get + { + if (this.IsPropertyDefined((int)TagNames.ExifExposureTime)) + { + //-- Exposure time is explicitly specified + return this.GetPropertyRational((int)TagNames.ExifExposureTime).ToDouble(); + } + else if (this.IsPropertyDefined((int)TagNames.ExifShutterSpeed)) + { + //-- Compute exposure time from shutter speed + return 1 / (Math.Pow(2, this.GetPropertyRational((int)TagNames.ExifShutterSpeed).ToDouble())); + } + else + { + //-- Can't figure out + return 0; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Aperture value as F number (EXIF ExifFNumber/ExifApertureValue) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public double Aperture + { + get + { + if (this.IsPropertyDefined((int)TagNames.ExifFNumber)) + { + return this.GetPropertyRational((int)TagNames.ExifFNumber).ToDouble(); + } + else if (this.IsPropertyDefined((int)TagNames.ExifAperture)) + { + return Math.Pow(System.Math.Sqrt(2), this.GetPropertyRational((int)TagNames.ExifAperture).ToDouble()); + } + else + { + return 0; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Exposure program used (EXIF ExifExposureProg) + /// + /// + /// If not specified, returns Normal (2) + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public ExposurePrograms ExposureProgram + { + get + { + Int32 X = this.GetPropertyInt16((int)TagNames.ExifExposureProg); + + if (Enum.IsDefined(typeof(ExposurePrograms), X)) + { + return (ExposurePrograms)Enum.Parse(typeof(ExposurePrograms), Enum.GetName(typeof(ExposurePrograms), X)); + } + else + { + return ExposurePrograms.Normal; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// ISO sensitivity + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public Int16 ISO + { + get { return this.GetPropertyInt16((int)TagNames.ExifISOSpeed); } + } + + ///----------------------------------------------------------------------------- + /// + /// Subject distance in meters (EXIF SubjectDistance) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public double SubjectDistance + { + get { return this.GetPropertyRational((int)TagNames.ExifSubjectDist).ToDouble(); } + } + + ///----------------------------------------------------------------------------- + /// + /// Exposure method metering mode used (EXIF MeteringMode) + /// + /// + /// If not specified, returns Unknown (0) + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public ExposureMeteringModes ExposureMeteringMode + { + get + { + Int32 X = this.GetPropertyInt16((int)TagNames.ExifMeteringMode); + + if (Enum.IsDefined(typeof(ExposureMeteringModes), X)) + { + return (ExposureMeteringModes)Enum.Parse(typeof(ExposureMeteringModes), Enum.GetName(typeof(ExposureMeteringModes), X)); + } + else + { + return ExposureMeteringModes.Unknown; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Focal length of lenses in mm (EXIF FocalLength) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public double FocalLength + { + get { return this.GetPropertyRational((int)TagNames.ExifFocalLength).ToDouble(); } + } + + ///----------------------------------------------------------------------------- + /// + /// Flash mode (EXIF Flash) + /// + /// + /// If not present, value NotFired (0) is returned + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public FlashModes FlashMode + { + get + { + Int32 X = this.GetPropertyInt16((int)TagNames.ExifFlash); + + if (Enum.IsDefined(typeof(FlashModes), X)) + { + return (FlashModes)Enum.Parse(typeof(FlashModes), Enum.GetName(typeof(FlashModes), X)); + } + else + { + return FlashModes.NotFired; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Light source / white balance (EXIF LightSource) + /// + /// + /// If not specified, returns Unknown (0). + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public LightSources LightSource + { + get + { + Int32 X = this.GetPropertyInt16((int)TagNames.ExifLightSource); + + if (Enum.IsDefined(typeof(LightSources), X)) + { + return (LightSources)Enum.Parse(typeof(LightSources), Enum.GetName(typeof(LightSources), X)); + } + else + { + return LightSources.Unknown; + } + } + } + + ///----------------------------------------------------------------------------- + /// + /// Checks if current image has specified certain property + /// + /// + /// True if image has specified property, False otherwise. + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public bool IsPropertyDefined(Int32 PID) + { + return Convert.ToBoolean(Array.IndexOf(this.Image.PropertyIdList, PID) > -1); + } + + ///----------------------------------------------------------------------------- + /// + /// Gets specified Int32 property + /// + /// Property ID + /// Optional, default 0. Default value returned if property is not present. + /// Value of property or DefaultValue if property is not present. + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public Int32 GetPropertyInt32(Int32 PID, Int32 DefaultValue = 0) + { + if (this.IsPropertyDefined(PID)) + { + return GetInt32(this.Image.GetPropertyItem(PID).Value); + } + else + { + return DefaultValue; + } + } + + ///----------------------------------------------------------------------------- + /// + /// Gets specified Int16 property + /// + /// Property ID + /// Optional, default 0. Default value returned if property is not present. + /// Value of property or DefaultValue if property is not present. + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public Int16 GetPropertyInt16(Int32 PID, Int16 DefaultValue = 0) + { + if (this.IsPropertyDefined(PID)) + { + return GetInt16(this.Image.GetPropertyItem(PID).Value); + } + else + { + return DefaultValue; + } + } + + ///----------------------------------------------------------------------------- + /// + /// Gets specified string property + /// + /// Property ID + /// Optional, default String.Empty. Default value returned if property is not present. + /// + /// Value of property or DefaultValue if property is not present. + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public string GetPropertyString(Int32 PID, string DefaultValue = "") + { + if (this.IsPropertyDefined(PID)) + { + return GetString(this.Image.GetPropertyItem(PID).Value); + } + else + { + return DefaultValue; + } + } + + ///----------------------------------------------------------------------------- + /// + /// Gets specified rational property + /// + /// Property ID + /// + /// Value of property or 0/1 if not present. + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public Rational GetPropertyRational(Int32 PID) + { + if (this.IsPropertyDefined(PID)) + { + return GetRational(this.Image.GetPropertyItem(PID).Value); + } + else + { + Rational R = default(Rational); + R.Numerator = 0; + R.Denominator = 1; + return R; + } + } + + ///----------------------------------------------------------------------------- + /// + /// Reads Int32 from EXIF bytearray. + /// + /// EXIF bytearray to process + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public static Int32 GetInt32(byte[] B) + { + if (B.Length < 4) + throw new ArgumentException("Data too short (4 bytes expected)", "B"); + return B[3] << 24 | B[2] << 16 | B[1] << 8 | B[0]; + } + + ///----------------------------------------------------------------------------- + /// + /// Reads Int16 from EXIF bytearray. + /// + /// EXIF bytearray to process + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public static Int16 GetInt16(byte[] B) + { + if (B.Length < 2) + throw new ArgumentException("Data too short (2 bytes expected)", "B"); + return Convert.ToInt16(B[1] << 8 | B[0]); + } + + ///----------------------------------------------------------------------------- + /// + /// Reads string from EXIF bytearray. + /// + /// EXIF bytearray to process + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public static string GetString(byte[] B) + { + string R = System.Text.Encoding.ASCII.GetString(B); + if (R.EndsWith(string.Empty)) + R = R.Substring(0, R.Length - 1); + return R; + } + + ///----------------------------------------------------------------------------- + /// + /// Reads rational from EXIF bytearray. + /// + /// EXIF bytearray to process + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public static Rational GetRational(byte[] B) + { + Rational R = new Rational(); + byte[] N = new byte[4]; + byte[] D = new byte[4]; + Array.Copy(B, 0, N, 0, 4); + Array.Copy(B, 4, D, 0, 4); + R.Denominator = GetInt32(D); + R.Numerator = GetInt32(N); + return R; + } + + ///----------------------------------------------------------------------------- + /// + /// Disposes unmanaged resources of this class + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + ///----------------------------------------------------------------------------- + public void Dispose() + { + this.Image.Dispose(); + } +} \ No newline at end of file diff --git a/ImageCatalogCS/FileHelper.cs b/ImageCatalogCS/FileHelper.cs new file mode 100644 index 0000000..0e68384 --- /dev/null +++ b/ImageCatalogCS/FileHelper.cs @@ -0,0 +1,173 @@ +using Microsoft.VisualBasic; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.IO; + +public class FileHelper +{ + //Private dirSourceDest As Dictionary(Of FileInfo, DirectoryInfo) + private int filesPerFolder; + private string suffix; + private int counterSize; + private int numerationType; + private string filter; + private bool separateFiles; + + private string extensions = "*.jpg,*.png,*.gif"; + + public enum numerazione + { + Progressiva, + Files + } + /// + /// Preparazione per la separazione + /// + /// + /// + /// + /// + /// + public FileHelper(int filesPerFolder, string suffix, int counterSize, int numerationType) + { + this.filesPerFolder = filesPerFolder; + this.suffix = suffix; + this.counterSize = counterSize; + this.numerationType = numerationType; + this.separateFiles = true; + } + + /// + /// nessuna separazione + /// + /// + public FileHelper() + { + this.separateFiles = false; + } + + + public Dictionary GetFilesRecursive(DirectoryInfo root, DirectoryInfo destRoot, string filter) + { + Dictionary dirSourceDest = new Dictionary(); + List result = new List(); + + //Dim stack As New Stack(Of DirectoryInfo) + Stack> stack = new Stack>(); + + + this.filter = filter; + KeyValuePair pair = new KeyValuePair(); + + + //stack.Push(root) + stack.Push(new KeyValuePair(root, destRoot)); + + while ((stack.Count > 0)) + { + KeyValuePair curDirKV = stack.Pop(); + //curDirKP = stack.Pop() + DirectoryInfo dir = curDirKV.Key; + DirectoryInfo dDir = curDirKV.Value; + try + { + //result.AddRange(dir.GetFiles(filter, SearchOption.TopDirectoryOnly)) + // dividere file qui + if (filesPerFolder > 0 & separateFiles) + { + appendDictionary(dirSourceDest, dividiFilesInDir(dir, dDir)); + } + else + { + appendDictionary(dirSourceDest, getAllFilesInDir(dir, dDir)); + } + + + + foreach (DirectoryInfo subDirectory in dir.GetDirectories()) + { + stack.Push(new KeyValuePair(subDirectory, new DirectoryInfo(Path.Combine(dDir.FullName, subDirectory.Name)))); + + } + + } + catch (Exception ex) + { + } + } + + return dirSourceDest; + } + + public Dictionary appendDictionary(Dictionary dictA, Dictionary dictB) + { + foreach (KeyValuePair pair in dictB) + { + dictA.Add(pair.Key, pair.Value); + } + return dictA; + } + + public Dictionary getAllFilesInDir(DirectoryInfo dir, DirectoryInfo dirDest) + { + Dictionary dict = new Dictionary(); + foreach (FileInfo File in dir.GetFiles(filter)) + { + dict.Add(File, new DirectoryInfo(Path.Combine(dirDest.FullName, File.Name))); + + } + return dict; + } + + private Dictionary dividiFilesInDir(DirectoryInfo dir, DirectoryInfo dirDest) + { + int filesCount = dir.GetFiles(filter).Length; + int contaFilePerDir = 0; + int contaDirPerDir = 0; + string tempText = string.Empty; + Dictionary foldersDict = new Dictionary(); + + DirectoryInfo destDir = null; + destDir = new DirectoryInfo(Path.Combine(dirDest.FullName)); + + foreach (FileInfo file in dir.GetFiles(filter)) + { + contaFilePerDir += 1; + + if (contaFilePerDir == (contaDirPerDir * filesPerFolder) + 1) + { + contaDirPerDir += 1; + + if (numerazione.Progressiva.Equals(numerationType)) + { + tempText = contaDirPerDir.ToString(); + } + else + { + tempText = (contaDirPerDir * filesPerFolder).ToString(); + } + int i = 0; + for (i = 1; i <= (counterSize - tempText.Length); i++) + { + tempText = "0" + tempText; + } + destDir = new DirectoryInfo(Path.Combine(dirDest.FullName, suffix + tempText)); + + + + } + + if (!destDir.Exists) + { + destDir.Create(); + } + + foldersDict.Add(file, destDir); + } + + return foldersDict; + } +} \ No newline at end of file diff --git a/ImageCatalogCS/ImageCatalog 3.csproj b/ImageCatalogCS/ImageCatalog 3.csproj new file mode 100644 index 0000000..ef71c58 --- /dev/null +++ b/ImageCatalogCS/ImageCatalog 3.csproj @@ -0,0 +1,132 @@ + + + + + Debug + AnyCPU + {D11ED7B0-93E8-4F38-A142-EED72D7EE8B5} + WinExe + Properties + ImageCatalogCS + ImageCatalogCS + v4.8 + 512 + SAK + SAK + SAK + SAK + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + prompt + MinimumRecommendedRules.ruleset + true + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + prompt + MinimumRecommendedRules.ruleset + true + + + + + + + + + + + + + + + + + Form + + + AboutForm.cs + + + + + + + Form + + + MainForm.cs + + + + + + + + + AboutForm.cs + + + MainForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + \ No newline at end of file diff --git a/ImageCatalogCS/ImageCreator.cs b/ImageCatalogCS/ImageCreator.cs new file mode 100644 index 0000000..3c03533 --- /dev/null +++ b/ImageCatalogCS/ImageCreator.cs @@ -0,0 +1,1057 @@ +using Microsoft.VisualBasic; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.IO; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Drawing; +using ImageCatalogCS; +using System.Windows.Forms; +//using System.Drawing; +//Imports System.Threading + +public class ImageCreator +{ + #region "dichiarazioni" + + + private bool FotoRuotaADestra = false; + + private bool FotoRuotaASinistra = false; + private string TempMinText = ""; + //Private crFont1 As Font + + private string _NomeFileChild; + private DirectoryInfo _SourceDir; + private DirectoryInfo _DestDirStart; + + private DirectoryInfo _DestDir; + + private FileInfo _workFile; + private string testoFirma; + private string testoFirmaV; + private int alphaScelta; + private int DimensioneStandard; + private int DimensioneStandardMiniatura; + private DateTime dataFoto; + private DateTime dataPartenzaI; + private string testoOrario; + private string testoFirmaPiccola; + private Size thumbSizeSmall; + private Size thumbSizeBig; + private string nomeFileSmall; + private string nomeFileBig; + + private string nomeFileBig2; + private float yPosFromBottom; + private float yPosFromBottom1; + private float yPosFromBottom2; + private float yPosFromBottom3; + + private float yPosFromBottom4; + + #endregion + public ImageCreator() + { + } + + public ImageCreator(string nomeFileChild, DirectoryInfo sourceDir, DirectoryInfo destDir, DirectoryInfo destDirStart) + { + this._NomeFileChild = nomeFileChild; + this._SourceDir = sourceDir; + this._DestDir = destDir; + this._DestDirStart = destDirStart; + this._workFile = new FileInfo(nomeFileChild); + } + + public ImageCreator(string nomeFileChild, DirectoryInfo sourceDir, DirectoryInfo destDir) + { + this._NomeFileChild = nomeFileChild; + this._DestDir = destDir; + } + + public ImageCreator(FileInfo file, DirectoryInfo destination) + { + this._workFile = file; + this._DestDir = destination; + + } + + + + public void CreaImmagineThread(string Info) + { + + try + { + preparaVariabili(); + //Dim g As System.Drawing.Image = System.Drawing.Image.FromFile(Path.Combine(SourceDir.FullName, NomeFileChild)) + System.Drawing.Image g = System.Drawing.Image.FromFile(WorkFile.FullName); + + // Imposta testo extra + impostaTestoExtra(g); + + // Ruota l'immagine in base ai dati EXIF + Rotation(ref g); + + // Forza jpeg se è selezionata l'opzione + System.Drawing.Imaging.ImageFormat thisFormat = g.RawFormat; + if (PicSettings.UsaForzaJpg == true) + thisFormat = System.Drawing.Imaging.ImageFormat.Jpeg; + + prepareThumbnailSize(g); + + Bitmap imgOutputBig = new Bitmap(g, thumbSizeBig.Width, thumbSizeBig.Height); + imgOutputBig.SetResolution(g.HorizontalResolution, g.VerticalResolution); + + // Crea le miniature + creaMiniature(g, imgOutputBig, thisFormat); + + aggiungiTesto(g, imgOutputBig); + + aggiungiLogo(imgOutputBig); + + salvaFoto(imgOutputBig, thumbSizeBig, nomeFileBig, nomeFileSmall, thumbSizeSmall, thisFormat); + + g.Dispose(); + + GC.Collect(); + + //PicSettings.mainForm.stepProgressBar(); + + + } + catch (Exception ex) + { + + MessageBox.Show(ex.Message); + + + } + + + + } + + + private void Rotation(ref System.Drawing.Image g) + { + FotoRuotaADestra = false; + FotoRuotaASinistra = false; + + if (PicSettings.UsaRotazioneAutomatica) + { + // ci sono dati exif + if (g.PropertyIdList.Length > 0) + { + ExifReader DatiExif = new ExifReader((Bitmap)g); + + switch (DatiExif.Orientation) + { + case ExifReader.Orientations.BottomLeft: + + break; + case ExifReader.Orientations.BottomRight: + + break; + case ExifReader.Orientations.LeftTop: + + break; + case ExifReader.Orientations.LftBottom: + FotoRuotaASinistra = true; + break; + case ExifReader.Orientations.RightBottom: + + break; + case ExifReader.Orientations.RightTop: + + break; + case ExifReader.Orientations.TopLeft: + + break; + case ExifReader.Orientations.TopRight: + + break; + } + } + } + + if (FotoRuotaASinistra == true) + { + g.RotateFlip(RotateFlipType.Rotate270FlipNone); + } + if (FotoRuotaADestra == true) + { + g.RotateFlip(RotateFlipType.Rotate90FlipNone); + } + + + + } + /// + /// Aggiunge Orario, tempo gara e altri + /// + /// Image + /// + private void impostaTestoExtra(Image g) + { + + if (PicSettings.UsaOrarioTestoApplicare | PicSettings.UsaTempoGaraTestoApplicare | PicSettings.UsaOrarioMiniatura | PicSettings.TestoMin | PicSettings.AggTempoGaraMin | PicSettings.AggNumTempMin) + { + // ci sono dati exif + if (g.PropertyIdList.Length > 0) + { + ExifReader DatiExif = new ExifReader((Bitmap)g); + dataFoto = DatiExif.DateTimeOriginal; + testoFirma = PicSettings.TestoFirmaStart; + testoFirmaV = PicSettings.TestoFirmaStartV; + + if (dataFoto.Year != 1) + { + testoFirmaPiccola = dataFoto.ToShortTimeString(); + if (PicSettings.UsaOrarioTestoApplicare == true) + { + testoFirma += " " + dataFoto.ToShortDateString() + " " + dataFoto.ToLongTimeString(); + testoFirmaV += " " + dataFoto.ToShortDateString() + " " + dataFoto.ToLongTimeString(); + } + if (PicSettings.UsaTempoGaraTestoApplicare == true) + { + TimeSpan Orario = dataFoto.Subtract(dataPartenzaI); + + + //TimeSpan Orario = new TimeSpan( DateAndTime.DateDiff(DateInterval.Second, dataPartenzaI, dataFoto) * 10000000); + testoFirma += " " + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + testoFirmaV += " " + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + } + } + + } + } + else + { + testoFirma = PicSettings.TestoFirmaStart; + testoFirmaV = PicSettings.TestoFirmaStartV; + + } + } + + /// + /// Prepara diverse variabili azzerandole, elaborandole e prendendole dalle impostazioni + /// + /// + private void preparaVariabili() + { + alphaScelta = Convert.ToInt32((255 * (100 - PicSettings.Trasparenza) / 100)); + testoFirma = ""; + testoFirmaV = ""; + dataPartenzaI = PicSettings.DataPartenza; + testoOrario = PicSettings.TestoOrario; + if (testoOrario.Length > 0) + testoOrario += " "; + testoFirmaPiccola = ""; + thumbSizeSmall = new Size(); + thumbSizeBig = new Size(); + nomeFileSmall = ""; + nomeFileBig2 = ""; + nomeFileBig = ""; + DimensioneStandard = PicSettings.dimStandard; + DimensioneStandardMiniatura = PicSettings.dimStandardMiniatura; + //nomeFileSmall = Suffisso & NomeFileChild + //nomeFileBig = NomeFileChild + nomeFileSmall = PicSettings.Suffisso + WorkFile.Name; + nomeFileBig = WorkFile.Name; + } + + private void prepareThumbnailSize(Image g) + { + if (g.Width > g.Height) + { + thumbSizeSmall = NewthumbSize(g.Width, g.Height, PicSettings.LarghezzaSmall, "Larghezza"); + Size SizeOrig = new Size(g.Width, g.Height); + thumbSizeBig = SizeOrig; + } + else + { + thumbSizeSmall = NewthumbSize(g.Width, g.Height, PicSettings.AltezzaSmall, "Altezza"); + Size SizeOrig = new Size(g.Width, g.Height); + thumbSizeBig = SizeOrig; + } + } + + private void creaMiniature(Image g, Bitmap imgOutputBig, ImageFormat thisFormat) + { + if (PicSettings.TestoMin) + { + testoFirmaPiccola = nomeFileBig; + } + else if (PicSettings.AggNumTempMin) + { + testoFirmaPiccola = nomeFileBig + " "; + } + //Dim yPosFromBottom4 As Single + + Font crFont1 = null; + Font crFont2 = null; + SizeF crSize1 = new SizeF(); + SizeF crSize2 = new SizeF(); + + if (PicSettings.CreaMiniature == true) + { + if (PicSettings.AggiungiScritteMiniature == false) + { + if (string.Equals(PicSettings.directorySorgente.ToUpper(), + PicSettings.directoryDestinazione.ToUpper())) + { + nomeFileSmall = nomeFileSmall.Substring(0, nomeFileSmall.Length - 4) + PicSettings.Codice + nomeFileSmall.Substring(nomeFileSmall.Length - 4); + } + + if (PicSettings.UsaOrarioMiniatura | PicSettings.TestoMin | PicSettings.AggTempoGaraMin | PicSettings.AggNumTempMin) + { + if (testoFirmaPiccola.Length > 0) + { + Bitmap imgOutputSmall = default(Bitmap); + imgOutputSmall = (Bitmap)imgOutputBig.Clone(); + + Graphics grPhoto1 = default(Graphics); + grPhoto1 = Graphics.FromImage(imgOutputSmall); + grPhoto1.SmoothingMode = SmoothingMode.AntiAlias; + + int LarghezzaStandard1 = 0; + //quick fix + DimensioneStandardMiniatura = 50; + if (PicSettings.Grassetto == true) + { + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura, FontStyle.Bold); + crFont2 = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + } + else + { + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura); + crFont2 = new Font(PicSettings.IlFont, DimensioneStandard); + } + + crSize1 = grPhoto1.MeasureString(testoFirmaPiccola, crFont1); + crSize2 = grPhoto1.MeasureString(testoFirma, crFont1); + LarghezzaStandard1 = Convert.ToInt32(crSize1.Width); + + if (crSize1.Width > Convert.ToSingle(g.Width)) + { + int Conta = DimensioneStandardMiniatura; + do + { + if (Conta > 20) + { + Conta -= 5; + } + else + { + Conta -= 1; + } + if (PicSettings.Grassetto == true) + { + crFont1 = new Font(PicSettings.IlFont, Conta, FontStyle.Bold); + } + else + { + crFont1 = new Font(PicSettings.IlFont, Conta); + } + crSize1 = grPhoto1.MeasureString(testoFirmaPiccola, crFont1); + if (crSize1.Width < Convert.ToSingle(g.Width)) + { + LarghezzaStandard1 = Convert.ToInt32(crSize1.Width); + break; // TODO: might not be correct. Was : Exit Do + } + if (Conta <= 5) + break; // TODO: might not be correct. Was : Exit Do + } while (true); + DimensioneStandardMiniatura = Conta; + } + + switch (PicSettings.Posizione.ToUpper()) + { + case "ALTO": + yPosFromBottom1 = (PicSettings.Margine); + yPosFromBottom4 = (PicSettings.margVert); + + break; + case "BASSO": + yPosFromBottom1 = Convert.ToSingle((g.Height - crSize1.Height - (g.Height * PicSettings.Margine / 100))); + yPosFromBottom4 = Convert.ToSingle((g.Height - crSize1.Height - (g.Height * PicSettings.margVert / 100))); + + break; + } + + float xCenterOfImg1 = 0; + + StringFormat StrFormat1 = new StringFormat(); + switch (PicSettings.Allineamento.ToUpper()) + { + case "SINISTRA": + xCenterOfImg1 = Convert.ToSingle((PicSettings.Margine + (LarghezzaStandard1 / 2))); + + if ((LarghezzaStandard1 / 2) > (g.Width / 2) - PicSettings.Margine) + { + xCenterOfImg1 = Convert.ToSingle((g.Width / 2)); + } + + break; + + case "CENTRO": + xCenterOfImg1 = Convert.ToSingle((g.Width / 2)); + + break; + + case "DESTRA": + xCenterOfImg1 = Convert.ToSingle((g.Width - PicSettings.Margine - (LarghezzaStandard1 / 2))); + + if ((LarghezzaStandard1 / 2) > (g.Width / 2) - PicSettings.Margine) + { + xCenterOfImg1 = Convert.ToSingle((g.Width / 2)); + } + + break; + + } + StrFormat1.Alignment = StringAlignment.Center; + + SolidBrush semiTransBrush21 = new SolidBrush(Color.FromArgb(alphaScelta, 0, 0, 0)); + SolidBrush semiTransBrush1 = new SolidBrush(Color.FromArgb(alphaScelta, PicSettings.fontColoreRGB)); + + //quick fix + DimensioneStandardMiniatura = PicSettings.DimMin; + + if (PicSettings.Grassetto == true) + { + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura, FontStyle.Bold); + } + else + { + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura); + } + //asdgadfhdfhjgfsjgfjygfdhsdafa + if (PicSettings.TestoMin) + { + grPhoto1.DrawString(nomeFileBig, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(nomeFileBig, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + else if (PicSettings.AggTempoGaraMin & PicSettings.UsaTempoGaraTestoApplicare) + { + //TimeSpan Orario = new TimeSpan(DateAndTime.DateDiff(DateInterval.Second, dataPartenzaI, dataFoto) * 10000000); + TimeSpan Orario = dataFoto.Subtract(dataPartenzaI); + string tempstr = ""; + + + tempstr += Environment.NewLine + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + + + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + + } + else if (PicSettings.AggNumTempMin) + { + TimeSpan Orario = dataFoto.Subtract(dataPartenzaI); + //TimeSpan Orario = new TimeSpan(DateAndTime.DateDiff(DateInterval.Second, dataPartenzaI, dataFoto) * 10000000); + string tempstr = ""; + tempstr += nomeFileBig; + + tempstr += Environment.NewLine + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + + + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + + + } + else + { + grPhoto1.DrawString(testoFirmaPiccola, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(testoFirmaPiccola, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + + // Salva la miniatura + imgOutputSmall.Save(Path.Combine(DestDir.FullName, "Temp_" + nomeFileSmall), thisFormat); + System.Drawing.Image g2 = System.Drawing.Image.FromFile(Path.Combine(DestDir.FullName, "Temp_" + nomeFileSmall)); + Bitmap imgOutputSmall2 = new Bitmap(g2, thumbSizeSmall.Width, thumbSizeSmall.Height); + imgOutputSmall2.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + + imgOutputSmall2.Dispose(); + imgOutputSmall.Dispose(); + g2.Dispose(); + File.Delete((Path.Combine(DestDir.FullName, "Temp_" + nomeFileSmall))); + } + else + { + Bitmap imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height); + imgOutputSmall.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + imgOutputSmall.Dispose(); + } + } + else + { + Bitmap imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height); + imgOutputSmall.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + imgOutputSmall.Dispose(); + } + } + } + } + + private void aggiungiTesto(Image g, Bitmap imgOutputBig) + { + Graphics grPhoto = default(Graphics); + grPhoto = Graphics.FromImage(imgOutputBig); + grPhoto.SmoothingMode = SmoothingMode.AntiAlias; + + Font crFont = null; + SizeF crSize = new SizeF(); + int LarghezzaStandard = 0; + + if (PicSettings.Grassetto == true) + { + crFont = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + } + else + { + crFont = new Font(PicSettings.IlFont, DimensioneStandard); + } + crSize = grPhoto.MeasureString(testoFirma, crFont); + LarghezzaStandard = Convert.ToInt32(crSize.Width); + + if (crSize.Width > Convert.ToSingle(g.Width)) + { + int Conta = DimensioneStandard; + do + { + if (Conta > 20) + { + Conta -= 5; + } + else + { + Conta -= 1; + } + if (PicSettings.Grassetto == true) + { + crFont = new Font(PicSettings.IlFont, Conta, FontStyle.Bold); + } + else + { + crFont = new Font(PicSettings.IlFont, Conta); + } + crSize = grPhoto.MeasureString(testoFirma, crFont); + if (crSize.Width < Convert.ToSingle(g.Width)) + { + LarghezzaStandard = Convert.ToInt32(crSize.Width); + break; // TODO: might not be correct. Was : Exit Do + } + if (Conta <= 5) + break; // TODO: might not be correct. Was : Exit Do + } while (true); + DimensioneStandard = Conta; + } + + + switch (PicSettings.Posizione.ToUpper()) + { + case "ALTO": + yPosFromBottom = (PicSettings.Margine); + yPosFromBottom3 = (PicSettings.margVert); + + break; + case "BASSO": + yPosFromBottom = Convert.ToSingle((g.Height - crSize.Height - (g.Height * PicSettings.Margine / 100))); + yPosFromBottom3 = Convert.ToSingle((g.Height - crSize.Height - (g.Height * PicSettings.margVert / 100))); + break; + } + + float xCenterOfImg = 0; + float xCenterOfImg3 = 0; + StringFormat StrFormat = new StringFormat(); + switch (PicSettings.Allineamento.ToUpper()) + { + case "SINISTRA": + xCenterOfImg = Convert.ToSingle((PicSettings.Margine + (LarghezzaStandard / 2))); + xCenterOfImg3 = Convert.ToSingle((PicSettings.margVert + (LarghezzaStandard / 2))); + if ((LarghezzaStandard / 2) > (g.Width / 2) - PicSettings.Margine) + { + xCenterOfImg = Convert.ToSingle((g.Width / 2)); + } + if ((LarghezzaStandard / 2) > (g.Width / 2) - PicSettings.margVert) + { + xCenterOfImg3 = Convert.ToSingle((g.Width / 2)); + } + + break; + case "CENTRO": + xCenterOfImg = Convert.ToSingle((g.Width / 2)); + + break; + case "DESTRA": + xCenterOfImg = Convert.ToSingle((g.Width - PicSettings.Margine - (LarghezzaStandard / 2))); + xCenterOfImg3 = Convert.ToSingle((g.Width - PicSettings.margVert - (LarghezzaStandard / 2))); + if ((LarghezzaStandard / 2) > (g.Width / 2) - PicSettings.Margine) + { + xCenterOfImg = Convert.ToSingle((g.Width / 2)); + } + if ((LarghezzaStandard / 2) > (g.Width / 2) - PicSettings.margVert) + { + xCenterOfImg3 = Convert.ToSingle((g.Width / 2)); + } + + break; + } + StrFormat.Alignment = StringAlignment.Center; + + SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(alphaScelta, 0, 0, 0)); + //Dim semiTransBrush As SolidBrush = New SolidBrush(Color.FromArgb(AlphaScelta, _FontColoreR, _FontColoreG, _FontColoreB)) + SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(alphaScelta, PicSettings.fontColoreRGB)); + + + if (FotoRuotaADestra | FotoRuotaASinistra) + { + if (PicSettings.Grassetto == true) + { + crFont = new Font(PicSettings.IlFont, PicSettings.dimVert, FontStyle.Bold); + } + else + { + crFont = new Font(PicSettings.IlFont, PicSettings.dimVert); + } + + + } + else + { + if (PicSettings.Grassetto == true) + { + crFont = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + } + else + { + crFont = new Font(PicSettings.IlFont, DimensioneStandard); + } + } + + + //qui scrive il testo (nomefilebig) + if (PicSettings.TestoNome) + { + if (PicSettings.NomeData & g.PropertyIdList.Length > 0) + { + ExifReader DatiExif = new ExifReader((Bitmap)g); + dataFoto = DatiExif.DateTimeOriginal; + + grPhoto.DrawString((nomeFileBig + " " + dataFoto.ToShortDateString()), crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString((nomeFileBig + " " + dataFoto.ToShortDateString()), crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + } + else + { + grPhoto.DrawString(nomeFileBig, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString(nomeFileBig, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + + } + } + + if (PicSettings.TestoNome == false) + { + if (FotoRuotaADestra | FotoRuotaASinistra) + { + + if (PicSettings.TestoMin == false) + { + + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom3 + 1), StrFormat); + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom3), StrFormat); + } + + if (PicSettings.TestoMin == true) + { + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom4 + 1), StrFormat); + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom4), StrFormat); + + } + } + else + { + grPhoto.DrawString(testoFirma, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString(testoFirma, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + + + } + } + + if (PicSettings.directorySorgente.ToUpper() == PicSettings.directoryDestinazione.ToUpper()) + { + nomeFileBig2 = nomeFileBig; + nomeFileBig = nomeFileBig.Substring(0, nomeFileBig.Length - 4) + PicSettings.Codice + nomeFileBig.Substring(nomeFileBig.Length - 4); + } + grPhoto.Dispose(); + } + + + + + private void aggiungiLogo(Bitmap imgOutputBig) + { + //imgOutputBig + + if (PicSettings.LogoAggiungi == true & File.Exists(PicSettings.LogoNomeFile)) + { + Image ImmagineLogo = Image.FromFile(PicSettings.LogoNomeFile); + + Color LogoColoreTrasparente = Color.White; + //Dim bmWatermark As Bitmap + + //* Create a Bitmap based on the previously modified photograph Bitmap + //bmWatermark = New Bitmap(imgOutputBig) + //bmWatermark.SetResolution(imgOutputBig.HorizontalResolution, imgOutputBig.VerticalResolution) + + //* Load this Bitmap into a new Graphic Object + Graphics grWatermark = Graphics.FromImage(imgOutputBig); + + //* To achieve a translucent watermark we will apply (2) color manipulations + ImageAttributes imageAttributes = new ImageAttributes(); + + //* The first step replace the background color with one that is transparent (Alpha=0, R=0, G=0, B=0) + ColorMap colorMap = new ColorMap(); + + //* background this will be the color we search for and replace with transparency + colorMap.OldColor = LogoColoreTrasparente; + colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); + + ColorMap[] remapTable = { colorMap }; + imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); + + //* The second color manipulation is used to change the opacity by setting the 3rd row and 3rd column to 0.3f + float[][] colorMatrixElements = { + new float[] { + 1f, + 0f, + 0f, + 0f, + 0f + }, + new float[] { + 0f, + 1f, + 0f, + 0f, + 0f + }, + new float[] { + 0f, + 0f, + 1f, + 0f, + 0f + }, + new float[] { + 0f, + 0f, + 0f, + Convert.ToSingle(PicSettings.LogoTrasparenza) / 100, + 0f + }, + new float[] { + 0f, + 0f, + 0f, + 0f, + 1f + } + }; + ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); + imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); + + int FotoLogoH = PicSettings.LogoAltezza; + int FotoLogoW = PicSettings.LogoLarghezza; + double FattoreAlt = ImmagineLogo.Height / FotoLogoH; + double FattoreLarg = ImmagineLogo.Width / FotoLogoW; + Size NuovaSize = default(Size); + if (FattoreLarg > FattoreAlt) + { + NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoW, "Larghezza"); + } + else + { + NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoH, "Altezza"); + } + + int MargineUsato = 0; + int MargineL = 0; + bool InPercentualeL = false; + if (PicSettings.LogoMargine.EndsWith("%") == true) + { + InPercentualeL = true; + } + else + { + InPercentualeL = false; + } + MargineL = Convert.ToInt32(PicSettings.LogoMargine); + if (InPercentualeL == true) + { + MargineUsato = Convert.ToInt32(imgOutputBig.Height * MargineL / 100); + } + else + { + MargineUsato = MargineL; + } + + int xPosOfWm = 0; + int yPosOfWm = 0; + switch (PicSettings.LogoPosizioneH.ToUpper()) + { + case "SINISTRA": + case "NESSUNA": + xPosOfWm = MargineUsato; + + break; + case "CENTRO": + xPosOfWm = Convert.ToInt32((imgOutputBig.Width - NuovaSize.Width) / 2); + + break; + case "DESTRA": + xPosOfWm = ((imgOutputBig.Width - NuovaSize.Width) - MargineUsato); + break; + } + switch (PicSettings.LogoPosizioneV.ToUpper()) + { + case "ALTO": + case "NESSUNA": + yPosOfWm = MargineUsato; + + break; + case "CENTRO": + yPosOfWm = Convert.ToInt32((imgOutputBig.Height - NuovaSize.Height) / 2); + + break; + case "BASSO": + yPosOfWm = ((imgOutputBig.Height - NuovaSize.Height) - MargineUsato); + break; + } + + grWatermark.DrawImage(ImmagineLogo, new Rectangle(xPosOfWm, yPosOfWm, NuovaSize.Width, NuovaSize.Height), 0, 0, ImmagineLogo.Width, ImmagineLogo.Height, GraphicsUnit.Pixel, imageAttributes); + grWatermark.Dispose(); + } + } + + + + private void salvaFoto(Bitmap imgOutputBig, Size thumbSizeBig, string NomeFileBig, string NomeFileSmall, Size thumbSizeSmall, ImageFormat thisFormat) + { + if (PicSettings.FotoGrandeDimOrigina == false) + { + //attenzione non controlla se è png + //imgOutputBig.Save(Path.Combine(_DestDir.FullName, "Temp_" & NomeFileBig), thisFormat) + if (thisFormat.Equals(ImageFormat.Jpeg)) + { + salvaImmagineCustomQuality(imgOutputBig, Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig), PicSettings.jpegQuality); + } + else + { + imgOutputBig.Save(Path.Combine(_DestDir.FullName, "Temp_" + NomeFileBig), thisFormat); + } + + + System.Drawing.Image g2 = System.Drawing.Image.FromFile(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig)); + if (g2.Width > g2.Height) + { + thumbSizeBig = NewthumbSize(g2.Width, g2.Height, PicSettings.LarghezzaBig, "Larghezza"); + } + else + { + thumbSizeBig = NewthumbSize(g2.Width, g2.Height, PicSettings.AltezzaBig, "Altezza"); + } + Bitmap imgOutputBig2 = new Bitmap(g2, thumbSizeBig.Width, thumbSizeBig.Height); + // + if (thisFormat.Equals(ImageFormat.Jpeg)) + { + salvaImmagineCustomQuality(imgOutputBig2, Path.Combine(DestDir.FullName, NomeFileBig), PicSettings.jpegQuality); + } + else + { + imgOutputBig2.Save(Path.Combine(_DestDir.FullName, NomeFileBig), thisFormat); + } + + imgOutputBig2.Dispose(); + imgOutputBig.Dispose(); + g2.Dispose(); + } + else + { + // + if (thisFormat.Equals(ImageFormat.Jpeg)) + { + salvaImmagineCustomQuality(imgOutputBig, Path.Combine(DestDir.FullName, NomeFileBig), PicSettings.jpegQuality); + } + else + { + imgOutputBig.Save(Path.Combine(_DestDir.FullName, NomeFileBig), thisFormat); + } + + imgOutputBig.Dispose(); + } + + + if (PicSettings.CreaMiniature) + { + if (PicSettings.AggiungiScritteMiniature == true) + { + System.Drawing.Image g1 = null; + if (PicSettings.FotoGrandeDimOrigina == false) + { + g1 = System.Drawing.Image.FromFile(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig)); + } + else + { + g1 = System.Drawing.Image.FromFile(Path.Combine(DestDir.FullName, NomeFileBig)); + } + Bitmap imgOutputSmall = new Bitmap(g1, thumbSizeSmall.Width, thumbSizeSmall.Height); + if (PicSettings.directorySorgente.ToUpper() == PicSettings.directoryDestinazione.ToUpper()) + { + NomeFileSmall = NomeFileSmall.Substring(0, NomeFileSmall.Length - 4) + PicSettings.Codice + NomeFileSmall.Substring(NomeFileSmall.Length - 4); + } + // + if (thisFormat.Equals(ImageFormat.Jpeg)) + { + salvaImmagineCustomQuality(imgOutputSmall, Path.Combine(DestDir.FullName, NomeFileSmall), PicSettings.jpegQualityMin); + } + else + { + imgOutputSmall.Save(Path.Combine(_DestDir.FullName, NomeFileSmall), thisFormat); + } + + imgOutputSmall.Dispose(); + g1.Dispose(); + } + + + + } + + if (File.Exists(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig)) == true) + { + File.Delete(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig)); + } + + + } + + + private void salvaImmagineCustomQuality(Bitmap imageToSave, string nomeFileFinale, long quality) + { + ImageCodecInfo JgpEncoder = GetEncoder(ImageFormat.Jpeg); + Encoder MyEncoder = Encoder.Quality; + + EncoderParameters MyEncoderParameters = new EncoderParameters(1); + + EncoderParameter MyEncoderParameter = new EncoderParameter(MyEncoder, PicSettings.jpegQuality); + MyEncoderParameters.Param[0] = MyEncoderParameter; + imageToSave.Save(nomeFileFinale, JgpEncoder, MyEncoderParameters); + imageToSave.Dispose(); + } + + + + private ImageCodecInfo GetEncoder(ImageFormat format) + { + + ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); + + ImageCodecInfo codec = null; + foreach (ImageCodecInfo codec_loopVariable in codecs) + { + codec = codec_loopVariable; + if (codec.FormatID == format.Guid) + { + return codec; + } + } + return null; + + } + + + + + + + /// + /// Calculate the Size of the New image + /// + /// Larghezza + /// Altezza + /// + /// + /// + /// + private Size NewthumbSize(int currentwidth, int currentheight, int MaxPixel, string TipoSize) + { + // e + //*** Larghezza, Altezza, Auto + + double tempMultiplier = 0; + + if (TipoSize.ToUpper() == "Larghezza".ToUpper()) + { + tempMultiplier = MaxPixel / currentwidth; + } + else if (TipoSize.ToUpper() == "Altezza".ToUpper()) + { + tempMultiplier = MaxPixel / currentheight; + } + else + { + // portrait + if (currentheight > currentwidth) + { + tempMultiplier = MaxPixel / currentheight; + } + else + { + tempMultiplier = MaxPixel / currentwidth; + } + } + + Size NewSize = new Size(Convert.ToInt32(currentwidth * tempMultiplier), Convert.ToInt32(currentheight * tempMultiplier)); + + return NewSize; + } + + public FileInfo WorkFile + { + get { return _workFile; } + set { _workFile = value; } + } + + public DirectoryInfo DestDir + { + get { return _DestDir; } + set { _DestDir = value; } + } + + public DirectoryInfo SourceDir + { + get { return _SourceDir; } + set { _SourceDir = value; } + } + + public DirectoryInfo DestDirStart + { + get { return _DestDirStart; } + set { _DestDirStart = value; } + } + + public string NomeFileChild + { + get { return _NomeFileChild; } + set { _NomeFileChild = value; } + } + + +} \ No newline at end of file diff --git a/ImageCatalogCS/MainForm.Designer.cs b/ImageCatalogCS/MainForm.Designer.cs new file mode 100644 index 0000000..54b8132 --- /dev/null +++ b/ImageCatalogCS/MainForm.Designer.cs @@ -0,0 +1,1794 @@ +namespace ImageCatalogCS +{ + partial class MainForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.ProgressBar1 = new System.Windows.Forms.ProgressBar(); + this.CheckBox22 = new System.Windows.Forms.CheckBox(); + this.Label43 = new System.Windows.Forms.Label(); + this.TabControl1 = new System.Windows.Forms.TabControl(); + this.TabPage5 = new System.Windows.Forms.TabPage(); + this.GroupBox11 = new System.Windows.Forms.GroupBox(); + this.Label8 = new System.Windows.Forms.Label(); + this.TextBox8 = new System.Windows.Forms.TextBox(); + this.Label7 = new System.Windows.Forms.Label(); + this.TextBox7 = new System.Windows.Forms.TextBox(); + this.GroupBox3 = new System.Windows.Forms.GroupBox(); + this.chkAggiornaSottodirectory = new System.Windows.Forms.CheckBox(); + this.Button3 = new System.Windows.Forms.Button(); + this.Button2 = new System.Windows.Forms.Button(); + this.Label1 = new System.Windows.Forms.Label(); + this.Label2 = new System.Windows.Forms.Label(); + this.txtSorgente = new System.Windows.Forms.TextBox(); + this.txtDestinazione = new System.Windows.Forms.TextBox(); + this.GroupBox8 = new System.Windows.Forms.GroupBox(); + this.rdbNumFiles = new System.Windows.Forms.RadioButton(); + this.rdbNumProgressiva = new System.Windows.Forms.RadioButton(); + this.txtCifreContatore = new System.Windows.Forms.TextBox(); + this.Label34 = new System.Windows.Forms.Label(); + this.txtSuffissoCartelle = new System.Windows.Forms.TextBox(); + this.Label33 = new System.Windows.Forms.Label(); + this.Label31 = new System.Windows.Forms.Label(); + this.chkCreaSottocartelle = new System.Windows.Forms.CheckBox(); + this.txtFilePerCartella = new System.Windows.Forms.TextBox(); + this.Label32 = new System.Windows.Forms.Label(); + this.GroupBox7 = new System.Windows.Forms.GroupBox(); + this.chkSovrascriviFile = new System.Windows.Forms.CheckBox(); + this.chkRotazioneAutomatica = new System.Windows.Forms.CheckBox(); + this.chkForzaJpg = new System.Windows.Forms.CheckBox(); + this.TabPage3 = new System.Windows.Forms.TabPage(); + this.CheckBox2 = new System.Windows.Forms.CheckBox(); + this.GroupBox10 = new System.Windows.Forms.GroupBox(); + this.Label42 = new System.Windows.Forms.Label(); + this.Label41 = new System.Windows.Forms.Label(); + this.TextBox31 = new System.Windows.Forms.TextBox(); + this.TextBox30 = new System.Windows.Forms.TextBox(); + this.GroupBox9 = new System.Windows.Forms.GroupBox(); + this.CheckBox17 = new System.Windows.Forms.CheckBox(); + this.CheckBox16 = new System.Windows.Forms.CheckBox(); + this.GroupBox5 = new System.Windows.Forms.GroupBox(); + this.TextBox34 = new System.Windows.Forms.TextBox(); + this.Button8 = new System.Windows.Forms.Button(); + this.Label36 = new System.Windows.Forms.Label(); + this.TextBox25 = new System.Windows.Forms.TextBox(); + this.Label35 = new System.Windows.Forms.Label(); + this.ComboBox3 = new System.Windows.Forms.ComboBox(); + this.TextBox11 = new System.Windows.Forms.TextBox(); + this.Label12 = new System.Windows.Forms.Label(); + this.Label11 = new System.Windows.Forms.Label(); + this.CheckBox3 = new System.Windows.Forms.CheckBox(); + this.GroupBox4 = new System.Windows.Forms.GroupBox(); + this.Label40 = new System.Windows.Forms.Label(); + this.TextBox29 = new System.Windows.Forms.TextBox(); + this.TextBox18 = new System.Windows.Forms.TextBox(); + this.Label26 = new System.Windows.Forms.Label(); + this.DateTimePicker1 = new System.Windows.Forms.DateTimePicker(); + this.CheckBox8 = new System.Windows.Forms.CheckBox(); + this.TextBox9 = new System.Windows.Forms.TextBox(); + this.CheckBox7 = new System.Windows.Forms.CheckBox(); + this.Label4 = new System.Windows.Forms.Label(); + this.TextBox4 = new System.Windows.Forms.TextBox(); + this.Label9 = new System.Windows.Forms.Label(); + this.Label13 = new System.Windows.Forms.Label(); + this.ComboBox1 = new System.Windows.Forms.ComboBox(); + this.ComboBox2 = new System.Windows.Forms.ComboBox(); + this.Label14 = new System.Windows.Forms.Label(); + this.TextBox12 = new System.Windows.Forms.TextBox(); + this.Label15 = new System.Windows.Forms.Label(); + this.TabPage2 = new System.Windows.Forms.TabPage(); + this.GroupBox2 = new System.Windows.Forms.GroupBox(); + this.Label45 = new System.Windows.Forms.Label(); + this.TextBox32 = new System.Windows.Forms.TextBox(); + this.TextBox26 = new System.Windows.Forms.TextBox(); + this.Label37 = new System.Windows.Forms.Label(); + this.Label38 = new System.Windows.Forms.Label(); + this.TextBox27 = new System.Windows.Forms.TextBox(); + this.Label39 = new System.Windows.Forms.Label(); + this.TextBox28 = new System.Windows.Forms.TextBox(); + this.CheckBox15 = new System.Windows.Forms.CheckBox(); + this.TabPage1 = new System.Windows.Forms.TabPage(); + this.GroupBox1 = new System.Windows.Forms.GroupBox(); + this.Label46 = new System.Windows.Forms.Label(); + this.TextBox33 = new System.Windows.Forms.TextBox(); + this.Panel2 = new System.Windows.Forms.Panel(); + this.RadioButton3 = new System.Windows.Forms.RadioButton(); + this.RadioButton7 = new System.Windows.Forms.RadioButton(); + this.RadioButton4 = new System.Windows.Forms.RadioButton(); + this.RadioButton6 = new System.Windows.Forms.RadioButton(); + this.RadioButton5 = new System.Windows.Forms.RadioButton(); + this.Label5 = new System.Windows.Forms.Label(); + this.TextBox5 = new System.Windows.Forms.TextBox(); + this.Label6 = new System.Windows.Forms.Label(); + this.TextBox6 = new System.Windows.Forms.TextBox(); + this.Label3 = new System.Windows.Forms.Label(); + this.TextBox3 = new System.Windows.Forms.TextBox(); + this.CheckBox1 = new System.Windows.Forms.CheckBox(); + this.TabPage4 = new System.Windows.Forms.TabPage(); + this.GroupBox6 = new System.Windows.Forms.GroupBox(); + this.PictureBox2 = new System.Windows.Forms.PictureBox(); + this.PictureBox1 = new System.Windows.Forms.PictureBox(); + this.ComboBox5 = new System.Windows.Forms.ComboBox(); + this.ComboBox4 = new System.Windows.Forms.ComboBox(); + this.TextBox19 = new System.Windows.Forms.TextBox(); + this.Label28 = new System.Windows.Forms.Label(); + this.CheckBox5 = new System.Windows.Forms.CheckBox(); + this.TextBox15 = new System.Windows.Forms.TextBox(); + this.TextBox14 = new System.Windows.Forms.TextBox(); + this.Label25 = new System.Windows.Forms.Label(); + this.TextBox16 = new System.Windows.Forms.TextBox(); + this.Label24 = new System.Windows.Forms.Label(); + this.Label22 = new System.Windows.Forms.Label(); + this.Label23 = new System.Windows.Forms.Label(); + this.Button4 = new System.Windows.Forms.Button(); + this.TextBox10 = new System.Windows.Forms.TextBox(); + this.Label29 = new System.Windows.Forms.Label(); + this.Label30 = new System.Windows.Forms.Label(); + this.PictureBox3 = new System.Windows.Forms.PictureBox(); + this.Label20 = new System.Windows.Forms.Label(); + this.Label19 = new System.Windows.Forms.Label(); + this.Label18 = new System.Windows.Forms.Label(); + this.lblFotoTotaliNum = new System.Windows.Forms.Label(); + this.menuStrip1 = new System.Windows.Forms.MenuStrip(); + this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.caricaImpostazioniToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.salvaImpostazioniToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.creaCatalogoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.esciToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.aiutoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.informazioniToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.groupBox12 = new System.Windows.Forms.GroupBox(); + this.btnStopCreazione = new System.Windows.Forms.Button(); + this.lblLog = new System.Windows.Forms.ListBox(); + this.txtFileInfo = new System.Windows.Forms.TextBox(); + this.panelTesto = new System.Windows.Forms.Panel(); + this.panelMiniature = new System.Windows.Forms.Panel(); + this.TabControl1.SuspendLayout(); + this.TabPage5.SuspendLayout(); + this.GroupBox11.SuspendLayout(); + this.GroupBox3.SuspendLayout(); + this.GroupBox8.SuspendLayout(); + this.GroupBox7.SuspendLayout(); + this.TabPage3.SuspendLayout(); + this.GroupBox10.SuspendLayout(); + this.GroupBox9.SuspendLayout(); + this.GroupBox5.SuspendLayout(); + this.GroupBox4.SuspendLayout(); + this.TabPage2.SuspendLayout(); + this.GroupBox2.SuspendLayout(); + this.TabPage1.SuspendLayout(); + this.GroupBox1.SuspendLayout(); + this.Panel2.SuspendLayout(); + this.TabPage4.SuspendLayout(); + this.GroupBox6.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox2)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox3)).BeginInit(); + this.menuStrip1.SuspendLayout(); + this.groupBox12.SuspendLayout(); + this.panelTesto.SuspendLayout(); + this.panelMiniature.SuspendLayout(); + this.SuspendLayout(); + // + // ProgressBar1 + // + this.ProgressBar1.Location = new System.Drawing.Point(16, 401); + this.ProgressBar1.Name = "ProgressBar1"; + this.ProgressBar1.Size = new System.Drawing.Size(513, 13); + this.ProgressBar1.TabIndex = 81; + // + // CheckBox22 + // + this.CheckBox22.AutoSize = true; + this.CheckBox22.Location = new System.Drawing.Point(6, 365); + this.CheckBox22.Name = "CheckBox22"; + this.CheckBox22.Size = new System.Drawing.Size(104, 17); + this.CheckBox22.TabIndex = 80; + this.CheckBox22.Text = "Arresta il sistema"; + this.CheckBox22.UseVisualStyleBackColor = true; + // + // Label43 + // + this.Label43.AutoSize = true; + this.Label43.Location = new System.Drawing.Point(3, 349); + this.Label43.Name = "Label43"; + this.Label43.Size = new System.Drawing.Size(25, 13); + this.Label43.TabIndex = 79; + this.Label43.Text = "000"; + this.Label43.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // TabControl1 + // + this.TabControl1.Controls.Add(this.TabPage5); + this.TabControl1.Controls.Add(this.TabPage3); + this.TabControl1.Controls.Add(this.TabPage2); + this.TabControl1.Controls.Add(this.TabPage1); + this.TabControl1.Controls.Add(this.TabPage4); + this.TabControl1.Location = new System.Drawing.Point(12, 27); + this.TabControl1.Name = "TabControl1"; + this.TabControl1.SelectedIndex = 0; + this.TabControl1.Size = new System.Drawing.Size(521, 372); + this.TabControl1.TabIndex = 78; + // + // TabPage5 + // + this.TabPage5.Controls.Add(this.GroupBox11); + this.TabPage5.Controls.Add(this.GroupBox3); + this.TabPage5.Controls.Add(this.GroupBox8); + this.TabPage5.Controls.Add(this.GroupBox7); + this.TabPage5.Location = new System.Drawing.Point(4, 22); + this.TabPage5.Name = "TabPage5"; + this.TabPage5.Padding = new System.Windows.Forms.Padding(3); + this.TabPage5.Size = new System.Drawing.Size(513, 346); + this.TabPage5.TabIndex = 4; + this.TabPage5.Text = "Generale"; + this.TabPage5.UseVisualStyleBackColor = true; + // + // GroupBox11 + // + this.GroupBox11.Controls.Add(this.Label8); + this.GroupBox11.Controls.Add(this.TextBox8); + this.GroupBox11.Controls.Add(this.Label7); + this.GroupBox11.Controls.Add(this.TextBox7); + this.GroupBox11.Location = new System.Drawing.Point(7, 209); + this.GroupBox11.Name = "GroupBox11"; + this.GroupBox11.Size = new System.Drawing.Size(191, 132); + this.GroupBox11.TabIndex = 48; + this.GroupBox11.TabStop = false; + this.GroupBox11.Text = "Avanzate (ATTENZIONE)"; + // + // Label8 + // + this.Label8.AutoSize = true; + this.Label8.Location = new System.Drawing.Point(64, 26); + this.Label8.Name = "Label8"; + this.Label8.Size = new System.Drawing.Size(61, 13); + this.Label8.TabIndex = 3; + this.Label8.Text = "Min Thread"; + // + // TextBox8 + // + this.TextBox8.Location = new System.Drawing.Point(7, 20); + this.TextBox8.Name = "TextBox8"; + this.TextBox8.Size = new System.Drawing.Size(47, 20); + this.TextBox8.TabIndex = 2; + this.TextBox8.Text = "5"; + // + // Label7 + // + this.Label7.AutoSize = true; + this.Label7.Location = new System.Drawing.Point(61, 48); + this.Label7.Name = "Label7"; + this.Label7.Size = new System.Drawing.Size(64, 13); + this.Label7.TabIndex = 1; + this.Label7.Text = "Max Thread"; + // + // TextBox7 + // + this.TextBox7.Location = new System.Drawing.Point(7, 46); + this.TextBox7.Name = "TextBox7"; + this.TextBox7.Size = new System.Drawing.Size(47, 20); + this.TextBox7.TabIndex = 0; + this.TextBox7.Text = "15"; + // + // GroupBox3 + // + this.GroupBox3.Controls.Add(this.chkAggiornaSottodirectory); + this.GroupBox3.Controls.Add(this.Button3); + this.GroupBox3.Controls.Add(this.Button2); + this.GroupBox3.Controls.Add(this.Label1); + this.GroupBox3.Controls.Add(this.Label2); + this.GroupBox3.Controls.Add(this.txtSorgente); + this.GroupBox3.Controls.Add(this.txtDestinazione); + this.GroupBox3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox3.Location = new System.Drawing.Point(6, 6); + this.GroupBox3.Name = "GroupBox3"; + this.GroupBox3.Size = new System.Drawing.Size(496, 101); + this.GroupBox3.TabIndex = 35; + this.GroupBox3.TabStop = false; + this.GroupBox3.Text = "Directory"; + // + // chkAggiornaSottodirectory + // + this.chkAggiornaSottodirectory.ForeColor = System.Drawing.Color.Black; + this.chkAggiornaSottodirectory.Location = new System.Drawing.Point(80, 64); + this.chkAggiornaSottodirectory.Name = "chkAggiornaSottodirectory"; + this.chkAggiornaSottodirectory.Size = new System.Drawing.Size(152, 24); + this.chkAggiornaSottodirectory.TabIndex = 25; + this.chkAggiornaSottodirectory.Text = "aggiorna le sottodirectory"; + // + // Button3 + // + this.Button3.Location = new System.Drawing.Point(462, 40); + this.Button3.Name = "Button3"; + this.Button3.Size = new System.Drawing.Size(24, 20); + this.Button3.TabIndex = 6; + this.Button3.Text = "..."; + // + // Button2 + // + this.Button2.Location = new System.Drawing.Point(462, 16); + this.Button2.Name = "Button2"; + this.Button2.Size = new System.Drawing.Size(24, 20); + this.Button2.TabIndex = 5; + this.Button2.Text = "..."; + // + // Label1 + // + this.Label1.AutoSize = true; + this.Label1.ForeColor = System.Drawing.Color.Black; + this.Label1.Location = new System.Drawing.Point(6, 19); + this.Label1.Name = "Label1"; + this.Label1.Size = new System.Drawing.Size(50, 13); + this.Label1.TabIndex = 3; + this.Label1.Text = "Sorgente"; + // + // Label2 + // + this.Label2.AutoSize = true; + this.Label2.ForeColor = System.Drawing.Color.Black; + this.Label2.Location = new System.Drawing.Point(6, 43); + this.Label2.Name = "Label2"; + this.Label2.Size = new System.Drawing.Size(68, 13); + this.Label2.TabIndex = 4; + this.Label2.Text = "Destinazione"; + // + // txtSorgente + // + this.txtSorgente.Location = new System.Drawing.Point(80, 16); + this.txtSorgente.Name = "txtSorgente"; + this.txtSorgente.Size = new System.Drawing.Size(376, 20); + this.txtSorgente.TabIndex = 0; + this.txtSorgente.Text = "TextBox1"; + // + // txtDestinazione + // + this.txtDestinazione.Location = new System.Drawing.Point(80, 40); + this.txtDestinazione.Name = "txtDestinazione"; + this.txtDestinazione.Size = new System.Drawing.Size(376, 20); + this.txtDestinazione.TabIndex = 1; + this.txtDestinazione.Text = "TextBox2"; + // + // GroupBox8 + // + this.GroupBox8.Controls.Add(this.rdbNumFiles); + this.GroupBox8.Controls.Add(this.rdbNumProgressiva); + this.GroupBox8.Controls.Add(this.txtCifreContatore); + this.GroupBox8.Controls.Add(this.Label34); + this.GroupBox8.Controls.Add(this.txtSuffissoCartelle); + this.GroupBox8.Controls.Add(this.Label33); + this.GroupBox8.Controls.Add(this.Label31); + this.GroupBox8.Controls.Add(this.chkCreaSottocartelle); + this.GroupBox8.Controls.Add(this.txtFilePerCartella); + this.GroupBox8.Controls.Add(this.Label32); + this.GroupBox8.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox8.Location = new System.Drawing.Point(204, 113); + this.GroupBox8.Name = "GroupBox8"; + this.GroupBox8.Size = new System.Drawing.Size(192, 152); + this.GroupBox8.TabIndex = 47; + this.GroupBox8.TabStop = false; + this.GroupBox8.Text = "Sottocartelle"; + // + // rdbNumFiles + // + this.rdbNumFiles.ForeColor = System.Drawing.Color.Black; + this.rdbNumFiles.Location = new System.Drawing.Point(32, 128); + this.rdbNumFiles.Name = "rdbNumFiles"; + this.rdbNumFiles.Size = new System.Drawing.Size(136, 16); + this.rdbNumFiles.TabIndex = 38; + this.rdbNumFiles.Text = "Numerazione files"; + // + // rdbNumProgressiva + // + this.rdbNumProgressiva.Checked = true; + this.rdbNumProgressiva.ForeColor = System.Drawing.Color.Black; + this.rdbNumProgressiva.Location = new System.Drawing.Point(32, 112); + this.rdbNumProgressiva.Name = "rdbNumProgressiva"; + this.rdbNumProgressiva.Size = new System.Drawing.Size(152, 16); + this.rdbNumProgressiva.TabIndex = 37; + this.rdbNumProgressiva.TabStop = true; + this.rdbNumProgressiva.Text = "Numerazione progressiva"; + // + // txtCifreContatore + // + this.txtCifreContatore.Location = new System.Drawing.Point(128, 88); + this.txtCifreContatore.Name = "txtCifreContatore"; + this.txtCifreContatore.Size = new System.Drawing.Size(56, 20); + this.txtCifreContatore.TabIndex = 34; + this.txtCifreContatore.Text = "4"; + // + // Label34 + // + this.Label34.ForeColor = System.Drawing.Color.Black; + this.Label34.Location = new System.Drawing.Point(8, 88); + this.Label34.Name = "Label34"; + this.Label34.Size = new System.Drawing.Size(112, 16); + this.Label34.TabIndex = 33; + this.Label34.Text = "Num. cifre contatore"; + this.Label34.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // txtSuffissoCartelle + // + this.txtSuffissoCartelle.Location = new System.Drawing.Point(56, 64); + this.txtSuffissoCartelle.Name = "txtSuffissoCartelle"; + this.txtSuffissoCartelle.Size = new System.Drawing.Size(128, 20); + this.txtSuffissoCartelle.TabIndex = 32; + this.txtSuffissoCartelle.Text = "TextBox20"; + // + // Label33 + // + this.Label33.ForeColor = System.Drawing.Color.Black; + this.Label33.Location = new System.Drawing.Point(6, 67); + this.Label33.Name = "Label33"; + this.Label33.Size = new System.Drawing.Size(48, 16); + this.Label33.TabIndex = 31; + this.Label33.Text = "Suffisso"; + // + // Label31 + // + this.Label31.ForeColor = System.Drawing.Color.Black; + this.Label31.Location = new System.Drawing.Point(24, 40); + this.Label31.Name = "Label31"; + this.Label31.Size = new System.Drawing.Size(32, 16); + this.Label31.TabIndex = 30; + this.Label31.Text = "ogni"; + // + // chkCreaSottocartelle + // + this.chkCreaSottocartelle.ForeColor = System.Drawing.Color.Black; + this.chkCreaSottocartelle.Location = new System.Drawing.Point(56, 16); + this.chkCreaSottocartelle.Name = "chkCreaSottocartelle"; + this.chkCreaSottocartelle.Size = new System.Drawing.Size(112, 16); + this.chkCreaSottocartelle.TabIndex = 29; + this.chkCreaSottocartelle.Text = "crea sottocartelle"; + // + // txtFilePerCartella + // + this.txtFilePerCartella.Location = new System.Drawing.Point(56, 40); + this.txtFilePerCartella.Name = "txtFilePerCartella"; + this.txtFilePerCartella.Size = new System.Drawing.Size(64, 20); + this.txtFilePerCartella.TabIndex = 27; + this.txtFilePerCartella.Text = "99"; + // + // Label32 + // + this.Label32.ForeColor = System.Drawing.Color.Black; + this.Label32.Location = new System.Drawing.Point(128, 40); + this.Label32.Name = "Label32"; + this.Label32.Size = new System.Drawing.Size(24, 16); + this.Label32.TabIndex = 28; + this.Label32.Text = "file"; + // + // GroupBox7 + // + this.GroupBox7.Controls.Add(this.chkSovrascriviFile); + this.GroupBox7.Controls.Add(this.chkRotazioneAutomatica); + this.GroupBox7.Controls.Add(this.chkForzaJpg); + this.GroupBox7.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox7.Location = new System.Drawing.Point(6, 113); + this.GroupBox7.Name = "GroupBox7"; + this.GroupBox7.Size = new System.Drawing.Size(192, 88); + this.GroupBox7.TabIndex = 45; + this.GroupBox7.TabStop = false; + this.GroupBox7.Text = "Generale"; + // + // chkSovrascriviFile + // + this.chkSovrascriviFile.AutoSize = true; + this.chkSovrascriviFile.Location = new System.Drawing.Point(16, 61); + this.chkSovrascriviFile.Name = "chkSovrascriviFile"; + this.chkSovrascriviFile.Size = new System.Drawing.Size(94, 17); + this.chkSovrascriviFile.TabIndex = 2; + this.chkSovrascriviFile.Text = "Sovrascrivi file"; + this.chkSovrascriviFile.UseVisualStyleBackColor = true; + // + // chkRotazioneAutomatica + // + this.chkRotazioneAutomatica.ForeColor = System.Drawing.Color.Black; + this.chkRotazioneAutomatica.Location = new System.Drawing.Point(16, 39); + this.chkRotazioneAutomatica.Name = "chkRotazioneAutomatica"; + this.chkRotazioneAutomatica.Size = new System.Drawing.Size(136, 16); + this.chkRotazioneAutomatica.TabIndex = 1; + this.chkRotazioneAutomatica.Text = "Rotazione automatica"; + // + // chkForzaJpg + // + this.chkForzaJpg.Checked = true; + this.chkForzaJpg.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkForzaJpg.ForeColor = System.Drawing.Color.Black; + this.chkForzaJpg.Location = new System.Drawing.Point(16, 18); + this.chkForzaJpg.Name = "chkForzaJpg"; + this.chkForzaJpg.Size = new System.Drawing.Size(80, 16); + this.chkForzaJpg.TabIndex = 0; + this.chkForzaJpg.Text = "Forza Jpg"; + // + // TabPage3 + // + this.TabPage3.Controls.Add(this.panelTesto); + this.TabPage3.Controls.Add(this.CheckBox2); + this.TabPage3.Location = new System.Drawing.Point(4, 22); + this.TabPage3.Name = "TabPage3"; + this.TabPage3.Padding = new System.Windows.Forms.Padding(3); + this.TabPage3.Size = new System.Drawing.Size(513, 346); + this.TabPage3.TabIndex = 2; + this.TabPage3.Text = "Testo"; + this.TabPage3.UseVisualStyleBackColor = true; + // + // CheckBox2 + // + this.CheckBox2.AutoSize = true; + this.CheckBox2.Location = new System.Drawing.Point(7, 8); + this.CheckBox2.Name = "CheckBox2"; + this.CheckBox2.Size = new System.Drawing.Size(93, 17); + this.CheckBox2.TabIndex = 40; + this.CheckBox2.Text = "Aggiungi testo"; + this.CheckBox2.UseVisualStyleBackColor = true; + this.CheckBox2.CheckedChanged += new System.EventHandler(this.CheckBox2_CheckedChanged); + // + // GroupBox10 + // + this.GroupBox10.Controls.Add(this.Label42); + this.GroupBox10.Controls.Add(this.Label41); + this.GroupBox10.Controls.Add(this.TextBox31); + this.GroupBox10.Controls.Add(this.TextBox30); + this.GroupBox10.Location = new System.Drawing.Point(313, 50); + this.GroupBox10.Name = "GroupBox10"; + this.GroupBox10.Size = new System.Drawing.Size(186, 73); + this.GroupBox10.TabIndex = 39; + this.GroupBox10.TabStop = false; + this.GroupBox10.Text = "Testo foto verticali"; + // + // Label42 + // + this.Label42.AutoSize = true; + this.Label42.Location = new System.Drawing.Point(7, 46); + this.Label42.Name = "Label42"; + this.Label42.Size = new System.Drawing.Size(45, 13); + this.Label42.TabIndex = 3; + this.Label42.Text = "Margine"; + // + // Label41 + // + this.Label41.AutoSize = true; + this.Label41.Location = new System.Drawing.Point(7, 25); + this.Label41.Name = "Label41"; + this.Label41.Size = new System.Drawing.Size(108, 13); + this.Label41.TabIndex = 2; + this.Label41.Text = "Dimensione Carattere"; + // + // TextBox31 + // + this.TextBox31.Location = new System.Drawing.Point(131, 46); + this.TextBox31.Name = "TextBox31"; + this.TextBox31.Size = new System.Drawing.Size(39, 20); + this.TextBox31.TabIndex = 1; + // + // TextBox30 + // + this.TextBox30.Location = new System.Drawing.Point(131, 22); + this.TextBox30.Name = "TextBox30"; + this.TextBox30.Size = new System.Drawing.Size(39, 20); + this.TextBox30.TabIndex = 0; + // + // GroupBox9 + // + this.GroupBox9.Controls.Add(this.CheckBox17); + this.GroupBox9.Controls.Add(this.CheckBox16); + this.GroupBox9.Location = new System.Drawing.Point(313, 3); + this.GroupBox9.Name = "GroupBox9"; + this.GroupBox9.Size = new System.Drawing.Size(186, 45); + this.GroupBox9.TabIndex = 38; + this.GroupBox9.TabStop = false; + this.GroupBox9.Text = "Slide show"; + // + // CheckBox17 + // + this.CheckBox17.AutoSize = true; + this.CheckBox17.Location = new System.Drawing.Point(96, 18); + this.CheckBox17.Name = "CheckBox17"; + this.CheckBox17.Size = new System.Drawing.Size(84, 17); + this.CheckBox17.TabIndex = 1; + this.CheckBox17.Text = "Numero foto"; + this.CheckBox17.UseVisualStyleBackColor = true; + // + // CheckBox16 + // + this.CheckBox16.AutoSize = true; + this.CheckBox16.Location = new System.Drawing.Point(6, 19); + this.CheckBox16.Name = "CheckBox16"; + this.CheckBox16.Size = new System.Drawing.Size(49, 17); + this.CheckBox16.TabIndex = 0; + this.CheckBox16.Text = "Data"; + this.CheckBox16.UseVisualStyleBackColor = true; + // + // GroupBox5 + // + this.GroupBox5.Controls.Add(this.TextBox34); + this.GroupBox5.Controls.Add(this.Button8); + this.GroupBox5.Controls.Add(this.Label36); + this.GroupBox5.Controls.Add(this.TextBox25); + this.GroupBox5.Controls.Add(this.Label35); + this.GroupBox5.Controls.Add(this.ComboBox3); + this.GroupBox5.Controls.Add(this.TextBox11); + this.GroupBox5.Controls.Add(this.Label12); + this.GroupBox5.Controls.Add(this.Label11); + this.GroupBox5.Controls.Add(this.CheckBox3); + this.GroupBox5.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox5.Location = new System.Drawing.Point(3, 3); + this.GroupBox5.Name = "GroupBox5"; + this.GroupBox5.Size = new System.Drawing.Size(304, 120); + this.GroupBox5.TabIndex = 37; + this.GroupBox5.TabStop = false; + this.GroupBox5.Text = "Carattere"; + // + // TextBox34 + // + this.TextBox34.Location = new System.Drawing.Point(160, 91); + this.TextBox34.Name = "TextBox34"; + this.TextBox34.Size = new System.Drawing.Size(56, 20); + this.TextBox34.TabIndex = 36; + this.TextBox34.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + // + // Button8 + // + this.Button8.ForeColor = System.Drawing.Color.Black; + this.Button8.Location = new System.Drawing.Point(222, 89); + this.Button8.Name = "Button8"; + this.Button8.Size = new System.Drawing.Size(74, 24); + this.Button8.TabIndex = 35; + this.Button8.Text = "Scegli..."; + // + // Label36 + // + this.Label36.ForeColor = System.Drawing.Color.Black; + this.Label36.Location = new System.Drawing.Point(8, 60); + this.Label36.Name = "Label36"; + this.Label36.Size = new System.Drawing.Size(120, 19); + this.Label36.TabIndex = 34; + this.Label36.Text = "Dimensione miniatura"; + this.Label36.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // TextBox25 + // + this.TextBox25.Location = new System.Drawing.Point(160, 59); + this.TextBox25.Name = "TextBox25"; + this.TextBox25.Size = new System.Drawing.Size(56, 20); + this.TextBox25.TabIndex = 33; + this.TextBox25.Text = "TextBox25"; + // + // Label35 + // + this.Label35.ForeColor = System.Drawing.Color.Black; + this.Label35.Location = new System.Drawing.Point(8, 93); + this.Label35.Name = "Label35"; + this.Label35.Size = new System.Drawing.Size(72, 16); + this.Label35.TabIndex = 32; + this.Label35.Text = "Colore RGB"; + this.Label35.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // ComboBox3 + // + this.ComboBox3.Location = new System.Drawing.Point(96, 8); + this.ComboBox3.Name = "ComboBox3"; + this.ComboBox3.Size = new System.Drawing.Size(120, 21); + this.ComboBox3.TabIndex = 28; + this.ComboBox3.Text = "ComboBox3"; + // + // TextBox11 + // + this.TextBox11.Location = new System.Drawing.Point(160, 35); + this.TextBox11.Name = "TextBox11"; + this.TextBox11.Size = new System.Drawing.Size(56, 20); + this.TextBox11.TabIndex = 27; + this.TextBox11.Text = "TextBox11"; + // + // Label12 + // + this.Label12.AutoSize = true; + this.Label12.ForeColor = System.Drawing.Color.Black; + this.Label12.Location = new System.Drawing.Point(8, 38); + this.Label12.Name = "Label12"; + this.Label12.Size = new System.Drawing.Size(62, 13); + this.Label12.TabIndex = 26; + this.Label12.Text = "Dimensione"; + this.Label12.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Label11 + // + this.Label11.AutoSize = true; + this.Label11.ForeColor = System.Drawing.Color.Black; + this.Label11.Location = new System.Drawing.Point(56, 8); + this.Label11.Name = "Label11"; + this.Label11.Size = new System.Drawing.Size(28, 13); + this.Label11.TabIndex = 22; + this.Label11.Text = "Font"; + // + // CheckBox3 + // + this.CheckBox3.ForeColor = System.Drawing.Color.Black; + this.CheckBox3.Location = new System.Drawing.Point(224, 8); + this.CheckBox3.Name = "CheckBox3"; + this.CheckBox3.Size = new System.Drawing.Size(72, 24); + this.CheckBox3.TabIndex = 24; + this.CheckBox3.Text = "Grassetto"; + // + // GroupBox4 + // + this.GroupBox4.Controls.Add(this.Label40); + this.GroupBox4.Controls.Add(this.TextBox29); + this.GroupBox4.Controls.Add(this.TextBox18); + this.GroupBox4.Controls.Add(this.Label26); + this.GroupBox4.Controls.Add(this.DateTimePicker1); + this.GroupBox4.Controls.Add(this.CheckBox8); + this.GroupBox4.Controls.Add(this.TextBox9); + this.GroupBox4.Controls.Add(this.CheckBox7); + this.GroupBox4.Controls.Add(this.Label4); + this.GroupBox4.Controls.Add(this.TextBox4); + this.GroupBox4.Controls.Add(this.Label9); + this.GroupBox4.Controls.Add(this.Label13); + this.GroupBox4.Controls.Add(this.ComboBox1); + this.GroupBox4.Controls.Add(this.ComboBox2); + this.GroupBox4.Controls.Add(this.Label14); + this.GroupBox4.Controls.Add(this.TextBox12); + this.GroupBox4.Controls.Add(this.Label15); + this.GroupBox4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox4.Location = new System.Drawing.Point(3, 129); + this.GroupBox4.Name = "GroupBox4"; + this.GroupBox4.Size = new System.Drawing.Size(496, 171); + this.GroupBox4.TabIndex = 36; + this.GroupBox4.TabStop = false; + this.GroupBox4.Text = "Testo da applicare"; + // + // Label40 + // + this.Label40.AutoSize = true; + this.Label40.Location = new System.Drawing.Point(8, 52); + this.Label40.Name = "Label40"; + this.Label40.Size = new System.Drawing.Size(48, 13); + this.Label40.TabIndex = 40; + this.Label40.Text = "Verticale"; + // + // TextBox29 + // + this.TextBox29.Location = new System.Drawing.Point(72, 49); + this.TextBox29.Multiline = true; + this.TextBox29.Name = "TextBox29"; + this.TextBox29.Size = new System.Drawing.Size(408, 44); + this.TextBox29.TabIndex = 39; + // + // TextBox18 + // + this.TextBox18.Location = new System.Drawing.Point(232, 147); + this.TextBox18.Name = "TextBox18"; + this.TextBox18.Size = new System.Drawing.Size(100, 20); + this.TextBox18.TabIndex = 38; + // + // Label26 + // + this.Label26.AutoSize = true; + this.Label26.ForeColor = System.Drawing.Color.Black; + this.Label26.Location = new System.Drawing.Point(344, 147); + this.Label26.Name = "Label26"; + this.Label26.Size = new System.Drawing.Size(48, 13); + this.Label26.TabIndex = 37; + this.Label26.Text = "partenza"; + // + // DateTimePicker1 + // + this.DateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Time; + this.DateTimePicker1.Location = new System.Drawing.Point(392, 147); + this.DateTimePicker1.Name = "DateTimePicker1"; + this.DateTimePicker1.Size = new System.Drawing.Size(88, 20); + this.DateTimePicker1.TabIndex = 36; + // + // CheckBox8 + // + this.CheckBox8.ForeColor = System.Drawing.Color.Black; + this.CheckBox8.Location = new System.Drawing.Point(72, 147); + this.CheckBox8.Name = "CheckBox8"; + this.CheckBox8.Size = new System.Drawing.Size(56, 16); + this.CheckBox8.TabIndex = 35; + this.CheckBox8.Text = "Orario"; + // + // TextBox9 + // + this.TextBox9.Location = new System.Drawing.Point(120, 99); + this.TextBox9.Name = "TextBox9"; + this.TextBox9.Size = new System.Drawing.Size(56, 20); + this.TextBox9.TabIndex = 20; + this.TextBox9.Text = "TextBox9"; + // + // CheckBox7 + // + this.CheckBox7.ForeColor = System.Drawing.Color.Black; + this.CheckBox7.Location = new System.Drawing.Point(136, 147); + this.CheckBox7.Name = "CheckBox7"; + this.CheckBox7.Size = new System.Drawing.Size(88, 16); + this.CheckBox7.TabIndex = 34; + this.CheckBox7.Text = "Tempo gara"; + // + // Label4 + // + this.Label4.AutoSize = true; + this.Label4.ForeColor = System.Drawing.Color.Black; + this.Label4.Location = new System.Drawing.Point(8, 24); + this.Label4.Name = "Label4"; + this.Label4.Size = new System.Drawing.Size(59, 13); + this.Label4.TabIndex = 9; + this.Label4.Text = "Orizzontale"; + // + // TextBox4 + // + this.TextBox4.Location = new System.Drawing.Point(72, 24); + this.TextBox4.Name = "TextBox4"; + this.TextBox4.Size = new System.Drawing.Size(408, 20); + this.TextBox4.TabIndex = 8; + this.TextBox4.Text = "TextBox4"; + // + // Label9 + // + this.Label9.AutoSize = true; + this.Label9.ForeColor = System.Drawing.Color.Black; + this.Label9.Location = new System.Drawing.Point(8, 99); + this.Label9.Name = "Label9"; + this.Label9.Size = new System.Drawing.Size(110, 13); + this.Label9.TabIndex = 19; + this.Label9.Text = "Trasparenza (0-100%)"; + // + // Label13 + // + this.Label13.AutoSize = true; + this.Label13.ForeColor = System.Drawing.Color.Black; + this.Label13.Location = new System.Drawing.Point(16, 123); + this.Label13.Name = "Label13"; + this.Label13.Size = new System.Drawing.Size(52, 13); + this.Label13.TabIndex = 29; + this.Label13.Text = "Posizione"; + // + // ComboBox1 + // + this.ComboBox1.Location = new System.Drawing.Point(72, 123); + this.ComboBox1.Name = "ComboBox1"; + this.ComboBox1.Size = new System.Drawing.Size(104, 21); + this.ComboBox1.TabIndex = 28; + this.ComboBox1.Text = "ComboBox1"; + // + // ComboBox2 + // + this.ComboBox2.Location = new System.Drawing.Point(376, 123); + this.ComboBox2.Name = "ComboBox2"; + this.ComboBox2.Size = new System.Drawing.Size(104, 21); + this.ComboBox2.TabIndex = 31; + this.ComboBox2.Text = "ComboBox2"; + // + // Label14 + // + this.Label14.AutoSize = true; + this.Label14.ForeColor = System.Drawing.Color.Black; + this.Label14.Location = new System.Drawing.Point(304, 123); + this.Label14.Name = "Label14"; + this.Label14.Size = new System.Drawing.Size(67, 13); + this.Label14.TabIndex = 30; + this.Label14.Text = "Allineamento"; + // + // TextBox12 + // + this.TextBox12.Location = new System.Drawing.Point(376, 99); + this.TextBox12.Name = "TextBox12"; + this.TextBox12.Size = new System.Drawing.Size(104, 20); + this.TextBox12.TabIndex = 33; + this.TextBox12.Text = "TextBox12"; + // + // Label15 + // + this.Label15.AutoSize = true; + this.Label15.ForeColor = System.Drawing.Color.Black; + this.Label15.Location = new System.Drawing.Point(296, 99); + this.Label15.Name = "Label15"; + this.Label15.Size = new System.Drawing.Size(75, 13); + this.Label15.TabIndex = 32; + this.Label15.Text = "Margine (pixel)"; + // + // TabPage2 + // + this.TabPage2.Controls.Add(this.GroupBox2); + this.TabPage2.Location = new System.Drawing.Point(4, 22); + this.TabPage2.Name = "TabPage2"; + this.TabPage2.Padding = new System.Windows.Forms.Padding(3); + this.TabPage2.Size = new System.Drawing.Size(513, 351); + this.TabPage2.TabIndex = 5; + this.TabPage2.Text = "Foto"; + this.TabPage2.UseVisualStyleBackColor = true; + // + // GroupBox2 + // + this.GroupBox2.Controls.Add(this.Label45); + this.GroupBox2.Controls.Add(this.TextBox32); + this.GroupBox2.Controls.Add(this.TextBox26); + this.GroupBox2.Controls.Add(this.Label37); + this.GroupBox2.Controls.Add(this.Label38); + this.GroupBox2.Controls.Add(this.TextBox27); + this.GroupBox2.Controls.Add(this.Label39); + this.GroupBox2.Controls.Add(this.TextBox28); + this.GroupBox2.Controls.Add(this.CheckBox15); + this.GroupBox2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox2.Location = new System.Drawing.Point(3, 6); + this.GroupBox2.Name = "GroupBox2"; + this.GroupBox2.Size = new System.Drawing.Size(304, 156); + this.GroupBox2.TabIndex = 36; + this.GroupBox2.TabStop = false; + this.GroupBox2.Text = "Foto grande"; + // + // Label45 + // + this.Label45.AutoSize = true; + this.Label45.Location = new System.Drawing.Point(11, 86); + this.Label45.Name = "Label45"; + this.Label45.Size = new System.Drawing.Size(40, 13); + this.Label45.TabIndex = 22; + this.Label45.Text = "Qualità"; + // + // TextBox32 + // + this.TextBox32.Location = new System.Drawing.Point(72, 80); + this.TextBox32.Name = "TextBox32"; + this.TextBox32.Size = new System.Drawing.Size(72, 20); + this.TextBox32.TabIndex = 21; + this.TextBox32.Text = "100"; + // + // TextBox26 + // + this.TextBox26.Location = new System.Drawing.Point(224, 48); + this.TextBox26.Name = "TextBox26"; + this.TextBox26.Size = new System.Drawing.Size(56, 20); + this.TextBox26.TabIndex = 20; + this.TextBox26.Text = "TextBox26"; + // + // Label37 + // + this.Label37.ForeColor = System.Drawing.Color.Black; + this.Label37.Location = new System.Drawing.Point(168, 48); + this.Label37.Name = "Label37"; + this.Label37.Size = new System.Drawing.Size(48, 16); + this.Label37.TabIndex = 19; + this.Label37.Text = "Suffisso"; + this.Label37.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // Label38 + // + this.Label38.AutoSize = true; + this.Label38.ForeColor = System.Drawing.Color.Black; + this.Label38.Location = new System.Drawing.Point(24, 24); + this.Label38.Name = "Label38"; + this.Label38.Size = new System.Drawing.Size(41, 13); + this.Label38.TabIndex = 16; + this.Label38.Text = "Altezza"; + // + // TextBox27 + // + this.TextBox27.Location = new System.Drawing.Point(72, 24); + this.TextBox27.Name = "TextBox27"; + this.TextBox27.Size = new System.Drawing.Size(72, 20); + this.TextBox27.TabIndex = 14; + this.TextBox27.Text = "TextBox27"; + // + // Label39 + // + this.Label39.AutoSize = true; + this.Label39.ForeColor = System.Drawing.Color.Black; + this.Label39.Location = new System.Drawing.Point(8, 48); + this.Label39.Name = "Label39"; + this.Label39.Size = new System.Drawing.Size(56, 13); + this.Label39.TabIndex = 17; + this.Label39.Text = "Larghezza"; + // + // TextBox28 + // + this.TextBox28.Location = new System.Drawing.Point(72, 48); + this.TextBox28.Name = "TextBox28"; + this.TextBox28.Size = new System.Drawing.Size(72, 20); + this.TextBox28.TabIndex = 15; + this.TextBox28.Text = "TextBox28"; + // + // CheckBox15 + // + this.CheckBox15.Checked = true; + this.CheckBox15.CheckState = System.Windows.Forms.CheckState.Checked; + this.CheckBox15.ForeColor = System.Drawing.Color.Black; + this.CheckBox15.Location = new System.Drawing.Point(168, 16); + this.CheckBox15.Name = "CheckBox15"; + this.CheckBox15.Size = new System.Drawing.Size(120, 32); + this.CheckBox15.TabIndex = 18; + this.CheckBox15.Text = "Mantieni dimensioni originali"; + // + // TabPage1 + // + this.TabPage1.Controls.Add(this.panelMiniature); + this.TabPage1.Controls.Add(this.CheckBox1); + this.TabPage1.Location = new System.Drawing.Point(4, 22); + this.TabPage1.Name = "TabPage1"; + this.TabPage1.Padding = new System.Windows.Forms.Padding(3); + this.TabPage1.Size = new System.Drawing.Size(513, 346); + this.TabPage1.TabIndex = 0; + this.TabPage1.Text = "Miniature"; + this.TabPage1.UseVisualStyleBackColor = true; + // + // GroupBox1 + // + this.GroupBox1.Controls.Add(this.Label46); + this.GroupBox1.Controls.Add(this.TextBox33); + this.GroupBox1.Controls.Add(this.Panel2); + this.GroupBox1.Controls.Add(this.Label5); + this.GroupBox1.Controls.Add(this.TextBox5); + this.GroupBox1.Controls.Add(this.Label6); + this.GroupBox1.Controls.Add(this.TextBox6); + this.GroupBox1.Controls.Add(this.Label3); + this.GroupBox1.Controls.Add(this.TextBox3); + this.GroupBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox1.Location = new System.Drawing.Point(3, 3); + this.GroupBox1.Name = "GroupBox1"; + this.GroupBox1.Size = new System.Drawing.Size(350, 210); + this.GroupBox1.TabIndex = 25; + this.GroupBox1.TabStop = false; + this.GroupBox1.Text = "Miniature"; + // + // Label46 + // + this.Label46.AutoSize = true; + this.Label46.Location = new System.Drawing.Point(198, 43); + this.Label46.Name = "Label46"; + this.Label46.Size = new System.Drawing.Size(40, 13); + this.Label46.TabIndex = 21; + this.Label46.Text = "Qualità"; + // + // TextBox33 + // + this.TextBox33.Location = new System.Drawing.Point(244, 40); + this.TextBox33.Name = "TextBox33"; + this.TextBox33.Size = new System.Drawing.Size(100, 20); + this.TextBox33.TabIndex = 20; + // + // Panel2 + // + this.Panel2.Controls.Add(this.RadioButton3); + this.Panel2.Controls.Add(this.RadioButton7); + this.Panel2.Controls.Add(this.RadioButton4); + this.Panel2.Controls.Add(this.RadioButton6); + this.Panel2.Controls.Add(this.RadioButton5); + this.Panel2.Location = new System.Drawing.Point(56, 114); + this.Panel2.Name = "Panel2"; + this.Panel2.Size = new System.Drawing.Size(235, 90); + this.Panel2.TabIndex = 19; + // + // RadioButton3 + // + this.RadioButton3.AutoSize = true; + this.RadioButton3.Location = new System.Drawing.Point(15, 16); + this.RadioButton3.Name = "RadioButton3"; + this.RadioButton3.Size = new System.Drawing.Size(99, 17); + this.RadioButton3.TabIndex = 14; + this.RadioButton3.TabStop = true; + this.RadioButton3.Text = "Aggiungi Scritta"; + this.RadioButton3.UseVisualStyleBackColor = true; + // + // RadioButton7 + // + this.RadioButton7.AutoSize = true; + this.RadioButton7.Location = new System.Drawing.Point(129, 40); + this.RadioButton7.Name = "RadioButton7"; + this.RadioButton7.Size = new System.Drawing.Size(95, 17); + this.RadioButton7.TabIndex = 18; + this.RadioButton7.TabStop = true; + this.RadioButton7.Text = "numero+tempo"; + this.RadioButton7.UseVisualStyleBackColor = true; + // + // RadioButton4 + // + this.RadioButton4.AutoSize = true; + this.RadioButton4.Location = new System.Drawing.Point(15, 40); + this.RadioButton4.Name = "RadioButton4"; + this.RadioButton4.Size = new System.Drawing.Size(95, 17); + this.RadioButton4.TabIndex = 15; + this.RadioButton4.TabStop = true; + this.RadioButton4.Text = "Aggiungi orario"; + this.RadioButton4.UseVisualStyleBackColor = true; + // + // RadioButton6 + // + this.RadioButton6.AutoSize = true; + this.RadioButton6.Location = new System.Drawing.Point(129, 16); + this.RadioButton6.Name = "RadioButton6"; + this.RadioButton6.Size = new System.Drawing.Size(83, 17); + this.RadioButton6.TabIndex = 17; + this.RadioButton6.TabStop = true; + this.RadioButton6.Text = "Numero foto"; + this.RadioButton6.UseVisualStyleBackColor = true; + // + // RadioButton5 + // + this.RadioButton5.AutoSize = true; + this.RadioButton5.Location = new System.Drawing.Point(15, 65); + this.RadioButton5.Name = "RadioButton5"; + this.RadioButton5.Size = new System.Drawing.Size(84, 17); + this.RadioButton5.TabIndex = 16; + this.RadioButton5.TabStop = true; + this.RadioButton5.Text = "Tempo Gara"; + this.RadioButton5.UseVisualStyleBackColor = true; + // + // Label5 + // + this.Label5.AutoSize = true; + this.Label5.ForeColor = System.Drawing.Color.Black; + this.Label5.Location = new System.Drawing.Point(24, 88); + this.Label5.Name = "Label5"; + this.Label5.Size = new System.Drawing.Size(41, 13); + this.Label5.TabIndex = 12; + this.Label5.Text = "Altezza"; + // + // TextBox5 + // + this.TextBox5.Location = new System.Drawing.Point(72, 64); + this.TextBox5.Name = "TextBox5"; + this.TextBox5.Size = new System.Drawing.Size(88, 20); + this.TextBox5.TabIndex = 10; + this.TextBox5.Text = "TextBox5"; + // + // Label6 + // + this.Label6.AutoSize = true; + this.Label6.ForeColor = System.Drawing.Color.Black; + this.Label6.Location = new System.Drawing.Point(8, 64); + this.Label6.Name = "Label6"; + this.Label6.Size = new System.Drawing.Size(56, 13); + this.Label6.TabIndex = 13; + this.Label6.Text = "Larghezza"; + // + // TextBox6 + // + this.TextBox6.Location = new System.Drawing.Point(72, 88); + this.TextBox6.Name = "TextBox6"; + this.TextBox6.Size = new System.Drawing.Size(88, 20); + this.TextBox6.TabIndex = 11; + this.TextBox6.Text = "TextBox6"; + // + // Label3 + // + this.Label3.AutoSize = true; + this.Label3.ForeColor = System.Drawing.Color.Black; + this.Label3.Location = new System.Drawing.Point(24, 40); + this.Label3.Name = "Label3"; + this.Label3.Size = new System.Drawing.Size(44, 13); + this.Label3.TabIndex = 7; + this.Label3.Text = "Suffisso"; + // + // TextBox3 + // + this.TextBox3.Location = new System.Drawing.Point(72, 40); + this.TextBox3.Name = "TextBox3"; + this.TextBox3.Size = new System.Drawing.Size(88, 20); + this.TextBox3.TabIndex = 6; + this.TextBox3.Text = "TextBox3"; + // + // CheckBox1 + // + this.CheckBox1.ForeColor = System.Drawing.Color.Black; + this.CheckBox1.Location = new System.Drawing.Point(6, 7); + this.CheckBox1.Name = "CheckBox1"; + this.CheckBox1.Size = new System.Drawing.Size(104, 24); + this.CheckBox1.TabIndex = 5; + this.CheckBox1.Text = "Crea miniature"; + this.CheckBox1.CheckedChanged += new System.EventHandler(this.CheckBox1_CheckedChanged); + // + // TabPage4 + // + this.TabPage4.Controls.Add(this.GroupBox6); + this.TabPage4.Location = new System.Drawing.Point(4, 22); + this.TabPage4.Name = "TabPage4"; + this.TabPage4.Padding = new System.Windows.Forms.Padding(3); + this.TabPage4.Size = new System.Drawing.Size(513, 351); + this.TabPage4.TabIndex = 3; + this.TabPage4.Text = "Logo"; + this.TabPage4.UseVisualStyleBackColor = true; + // + // GroupBox6 + // + this.GroupBox6.Controls.Add(this.PictureBox2); + this.GroupBox6.Controls.Add(this.PictureBox1); + this.GroupBox6.Controls.Add(this.ComboBox5); + this.GroupBox6.Controls.Add(this.ComboBox4); + this.GroupBox6.Controls.Add(this.TextBox19); + this.GroupBox6.Controls.Add(this.Label28); + this.GroupBox6.Controls.Add(this.CheckBox5); + this.GroupBox6.Controls.Add(this.TextBox15); + this.GroupBox6.Controls.Add(this.TextBox14); + this.GroupBox6.Controls.Add(this.Label25); + this.GroupBox6.Controls.Add(this.TextBox16); + this.GroupBox6.Controls.Add(this.Label24); + this.GroupBox6.Controls.Add(this.Label22); + this.GroupBox6.Controls.Add(this.Label23); + this.GroupBox6.Controls.Add(this.Button4); + this.GroupBox6.Controls.Add(this.TextBox10); + this.GroupBox6.Controls.Add(this.Label29); + this.GroupBox6.Controls.Add(this.Label30); + this.GroupBox6.Controls.Add(this.PictureBox3); + this.GroupBox6.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox6.Location = new System.Drawing.Point(6, 6); + this.GroupBox6.Name = "GroupBox6"; + this.GroupBox6.Size = new System.Drawing.Size(496, 224); + this.GroupBox6.TabIndex = 42; + this.GroupBox6.TabStop = false; + this.GroupBox6.Text = "Logo"; + // + // PictureBox2 + // + this.PictureBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.PictureBox2.Location = new System.Drawing.Point(144, 192); + this.PictureBox2.Name = "PictureBox2"; + this.PictureBox2.Size = new System.Drawing.Size(24, 24); + this.PictureBox2.TabIndex = 44; + this.PictureBox2.TabStop = false; + this.PictureBox2.Visible = false; + // + // PictureBox1 + // + this.PictureBox1.Cursor = System.Windows.Forms.Cursors.Cross; + this.PictureBox1.Location = new System.Drawing.Point(256, 56); + this.PictureBox1.Name = "PictureBox1"; + this.PictureBox1.Size = new System.Drawing.Size(224, 160); + this.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.PictureBox1.TabIndex = 43; + this.PictureBox1.TabStop = false; + // + // ComboBox5 + // + this.ComboBox5.Location = new System.Drawing.Point(144, 168); + this.ComboBox5.Name = "ComboBox5"; + this.ComboBox5.Size = new System.Drawing.Size(96, 21); + this.ComboBox5.TabIndex = 42; + this.ComboBox5.Text = "ComboBox5"; + // + // ComboBox4 + // + this.ComboBox4.Location = new System.Drawing.Point(144, 144); + this.ComboBox4.Name = "ComboBox4"; + this.ComboBox4.Size = new System.Drawing.Size(96, 21); + this.ComboBox4.TabIndex = 41; + this.ComboBox4.Text = "ComboBox4"; + // + // TextBox19 + // + this.TextBox19.Location = new System.Drawing.Point(144, 96); + this.TextBox19.Name = "TextBox19"; + this.TextBox19.Size = new System.Drawing.Size(96, 20); + this.TextBox19.TabIndex = 40; + this.TextBox19.Text = "TextBox19"; + // + // Label28 + // + this.Label28.ForeColor = System.Drawing.Color.Black; + this.Label28.Location = new System.Drawing.Point(17, 97); + this.Label28.Name = "Label28"; + this.Label28.Size = new System.Drawing.Size(120, 16); + this.Label28.TabIndex = 39; + this.Label28.Text = "Trasparenza (0-100%)"; + this.Label28.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // CheckBox5 + // + this.CheckBox5.ForeColor = System.Drawing.Color.Black; + this.CheckBox5.Location = new System.Drawing.Point(0, 26); + this.CheckBox5.Name = "CheckBox5"; + this.CheckBox5.Size = new System.Drawing.Size(72, 20); + this.CheckBox5.TabIndex = 38; + this.CheckBox5.Text = "Aggiungi"; + // + // TextBox15 + // + this.TextBox15.Location = new System.Drawing.Point(144, 72); + this.TextBox15.Name = "TextBox15"; + this.TextBox15.Size = new System.Drawing.Size(96, 20); + this.TextBox15.TabIndex = 19; + this.TextBox15.Text = "TextBox15"; + // + // TextBox14 + // + this.TextBox14.Location = new System.Drawing.Point(144, 48); + this.TextBox14.Name = "TextBox14"; + this.TextBox14.Size = new System.Drawing.Size(96, 20); + this.TextBox14.TabIndex = 18; + this.TextBox14.Text = "TextBox14"; + // + // Label25 + // + this.Label25.AutoSize = true; + this.Label25.ForeColor = System.Drawing.Color.Black; + this.Label25.Location = new System.Drawing.Point(17, 168); + this.Label25.Name = "Label25"; + this.Label25.Size = new System.Drawing.Size(95, 13); + this.Label25.TabIndex = 36; + this.Label25.Text = "Posizione verticale"; + this.Label25.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // TextBox16 + // + this.TextBox16.Location = new System.Drawing.Point(144, 120); + this.TextBox16.Name = "TextBox16"; + this.TextBox16.Size = new System.Drawing.Size(96, 20); + this.TextBox16.TabIndex = 35; + this.TextBox16.Text = "TextBox16"; + // + // Label24 + // + this.Label24.AutoSize = true; + this.Label24.ForeColor = System.Drawing.Color.Black; + this.Label24.Location = new System.Drawing.Point(19, 123); + this.Label24.Name = "Label24"; + this.Label24.Size = new System.Drawing.Size(88, 13); + this.Label24.TabIndex = 34; + this.Label24.Text = "Margine (pixel/%)"; + this.Label24.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Label22 + // + this.Label22.AutoSize = true; + this.Label22.ForeColor = System.Drawing.Color.Black; + this.Label22.Location = new System.Drawing.Point(19, 51); + this.Label22.Name = "Label22"; + this.Label22.Size = new System.Drawing.Size(41, 13); + this.Label22.TabIndex = 20; + this.Label22.Text = "Altezza"; + this.Label22.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Label23 + // + this.Label23.AutoSize = true; + this.Label23.ForeColor = System.Drawing.Color.Black; + this.Label23.Location = new System.Drawing.Point(19, 75); + this.Label23.Name = "Label23"; + this.Label23.Size = new System.Drawing.Size(56, 13); + this.Label23.TabIndex = 21; + this.Label23.Text = "Larghezza"; + this.Label23.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Button4 + // + this.Button4.Location = new System.Drawing.Point(464, 24); + this.Button4.Name = "Button4"; + this.Button4.Size = new System.Drawing.Size(24, 20); + this.Button4.TabIndex = 8; + this.Button4.Text = "..."; + // + // TextBox10 + // + this.TextBox10.Location = new System.Drawing.Point(144, 24); + this.TextBox10.Name = "TextBox10"; + this.TextBox10.Size = new System.Drawing.Size(312, 20); + this.TextBox10.TabIndex = 6; + this.TextBox10.Text = "TextBox10"; + // + // Label29 + // + this.Label29.AutoSize = true; + this.Label29.ForeColor = System.Drawing.Color.Black; + this.Label29.Location = new System.Drawing.Point(17, 147); + this.Label29.Name = "Label29"; + this.Label29.Size = new System.Drawing.Size(105, 13); + this.Label29.TabIndex = 36; + this.Label29.Text = "Posizione orizzontale"; + this.Label29.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Label30 + // + this.Label30.AutoSize = true; + this.Label30.ForeColor = System.Drawing.Color.Black; + this.Label30.Location = new System.Drawing.Point(19, 203); + this.Label30.Name = "Label30"; + this.Label30.Size = new System.Drawing.Size(93, 13); + this.Label30.TabIndex = 36; + this.Label30.Text = "Colore trasparente"; + this.Label30.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.Label30.Visible = false; + // + // PictureBox3 + // + this.PictureBox3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.PictureBox3.Location = new System.Drawing.Point(216, 192); + this.PictureBox3.Name = "PictureBox3"; + this.PictureBox3.Size = new System.Drawing.Size(24, 24); + this.PictureBox3.TabIndex = 44; + this.PictureBox3.TabStop = false; + this.PictureBox3.Visible = false; + // + // Label20 + // + this.Label20.AutoSize = true; + this.Label20.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Label20.Location = new System.Drawing.Point(6, 301); + this.Label20.Name = "Label20"; + this.Label20.Size = new System.Drawing.Size(104, 16); + this.Label20.TabIndex = 74; + this.Label20.Text = "foto generate:"; + // + // Label19 + // + this.Label19.AutoSize = true; + this.Label19.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Label19.Location = new System.Drawing.Point(6, 282); + this.Label19.Name = "Label19"; + this.Label19.Size = new System.Drawing.Size(80, 16); + this.Label19.TabIndex = 73; + this.Label19.Text = "foto totali: "; + // + // Label18 + // + this.Label18.AutoSize = true; + this.Label18.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Label18.Location = new System.Drawing.Point(110, 301); + this.Label18.Name = "Label18"; + this.Label18.Size = new System.Drawing.Size(19, 20); + this.Label18.TabIndex = 72; + this.Label18.Text = "0"; + // + // lblFotoTotaliNum + // + this.lblFotoTotaliNum.AutoSize = true; + this.lblFotoTotaliNum.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblFotoTotaliNum.Location = new System.Drawing.Point(110, 282); + this.lblFotoTotaliNum.Name = "lblFotoTotaliNum"; + this.lblFotoTotaliNum.Size = new System.Drawing.Size(19, 20); + this.lblFotoTotaliNum.TabIndex = 71; + this.lblFotoTotaliNum.Text = "0"; + // + // menuStrip1 + // + this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.fileToolStripMenuItem, + this.aiutoToolStripMenuItem}); + this.menuStrip1.Location = new System.Drawing.Point(0, 0); + this.menuStrip1.Name = "menuStrip1"; + this.menuStrip1.Size = new System.Drawing.Size(756, 24); + this.menuStrip1.TabIndex = 82; + this.menuStrip1.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.caricaImpostazioniToolStripMenuItem, + this.salvaImpostazioniToolStripMenuItem, + this.creaCatalogoToolStripMenuItem, + this.esciToolStripMenuItem}); + this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); + this.fileToolStripMenuItem.Text = "File"; + // + // caricaImpostazioniToolStripMenuItem + // + this.caricaImpostazioniToolStripMenuItem.Name = "caricaImpostazioniToolStripMenuItem"; + this.caricaImpostazioniToolStripMenuItem.Size = new System.Drawing.Size(187, 22); + this.caricaImpostazioniToolStripMenuItem.Text = "Carica impostazioni..."; + this.caricaImpostazioniToolStripMenuItem.Click += new System.EventHandler(this.caricaImpostazioniToolStripMenuItem_Click); + // + // salvaImpostazioniToolStripMenuItem + // + this.salvaImpostazioniToolStripMenuItem.Name = "salvaImpostazioniToolStripMenuItem"; + this.salvaImpostazioniToolStripMenuItem.Size = new System.Drawing.Size(187, 22); + this.salvaImpostazioniToolStripMenuItem.Text = "Salva impostazioni..."; + // + // creaCatalogoToolStripMenuItem + // + this.creaCatalogoToolStripMenuItem.Name = "creaCatalogoToolStripMenuItem"; + this.creaCatalogoToolStripMenuItem.Size = new System.Drawing.Size(187, 22); + this.creaCatalogoToolStripMenuItem.Text = "Crea catalogo"; + // + // esciToolStripMenuItem + // + this.esciToolStripMenuItem.Name = "esciToolStripMenuItem"; + this.esciToolStripMenuItem.Size = new System.Drawing.Size(187, 22); + this.esciToolStripMenuItem.Text = "Esci"; + // + // aiutoToolStripMenuItem + // + this.aiutoToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.informazioniToolStripMenuItem}); + this.aiutoToolStripMenuItem.Name = "aiutoToolStripMenuItem"; + this.aiutoToolStripMenuItem.Size = new System.Drawing.Size(48, 20); + this.aiutoToolStripMenuItem.Text = "Aiuto"; + // + // informazioniToolStripMenuItem + // + this.informazioniToolStripMenuItem.Name = "informazioniToolStripMenuItem"; + this.informazioniToolStripMenuItem.Size = new System.Drawing.Size(152, 22); + this.informazioniToolStripMenuItem.Text = "Informazioni"; + this.informazioniToolStripMenuItem.Click += new System.EventHandler(this.informazioniToolStripMenuItem_Click); + // + // groupBox12 + // + this.groupBox12.Controls.Add(this.txtFileInfo); + this.groupBox12.Controls.Add(this.lblLog); + this.groupBox12.Controls.Add(this.btnStopCreazione); + this.groupBox12.Controls.Add(this.lblFotoTotaliNum); + this.groupBox12.Controls.Add(this.CheckBox22); + this.groupBox12.Controls.Add(this.Label18); + this.groupBox12.Controls.Add(this.Label43); + this.groupBox12.Controls.Add(this.Label19); + this.groupBox12.Controls.Add(this.Label20); + this.groupBox12.Location = new System.Drawing.Point(539, 27); + this.groupBox12.Name = "groupBox12"; + this.groupBox12.Size = new System.Drawing.Size(204, 387); + this.groupBox12.TabIndex = 83; + this.groupBox12.TabStop = false; + this.groupBox12.Text = "Statistiche"; + // + // btnStopCreazione + // + this.btnStopCreazione.Location = new System.Drawing.Point(6, 20); + this.btnStopCreazione.Name = "btnStopCreazione"; + this.btnStopCreazione.Size = new System.Drawing.Size(192, 40); + this.btnStopCreazione.TabIndex = 82; + this.btnStopCreazione.Text = "STOP CREAZIONE"; + this.btnStopCreazione.UseVisualStyleBackColor = true; + this.btnStopCreazione.Click += new System.EventHandler(this.btnStopCreazione_Click); + // + // lblLog + // + this.lblLog.FormattingEnabled = true; + this.lblLog.Location = new System.Drawing.Point(6, 68); + this.lblLog.Name = "lblLog"; + this.lblLog.Size = new System.Drawing.Size(192, 95); + this.lblLog.TabIndex = 83; + // + // txtFileInfo + // + this.txtFileInfo.Enabled = false; + this.txtFileInfo.Location = new System.Drawing.Point(6, 170); + this.txtFileInfo.Multiline = true; + this.txtFileInfo.Name = "txtFileInfo"; + this.txtFileInfo.Size = new System.Drawing.Size(192, 109); + this.txtFileInfo.TabIndex = 84; + // + // panelTesto + // + this.panelTesto.Controls.Add(this.GroupBox5); + this.panelTesto.Controls.Add(this.GroupBox10); + this.panelTesto.Controls.Add(this.GroupBox9); + this.panelTesto.Controls.Add(this.GroupBox4); + this.panelTesto.Location = new System.Drawing.Point(3, 28); + this.panelTesto.Name = "panelTesto"; + this.panelTesto.Size = new System.Drawing.Size(504, 312); + this.panelTesto.TabIndex = 85; + // + // panelMiniature + // + this.panelMiniature.Controls.Add(this.GroupBox1); + this.panelMiniature.Location = new System.Drawing.Point(6, 36); + this.panelMiniature.Name = "panelMiniature"; + this.panelMiniature.Size = new System.Drawing.Size(501, 304); + this.panelMiniature.TabIndex = 27; + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(756, 427); + this.Controls.Add(this.groupBox12); + this.Controls.Add(this.TabControl1); + this.Controls.Add(this.menuStrip1); + this.Controls.Add(this.ProgressBar1); + this.MainMenuStrip = this.menuStrip1; + this.Name = "MainForm"; + this.Text = "Form1"; + this.Load += new System.EventHandler(this.Form1_Load); + this.TabControl1.ResumeLayout(false); + this.TabPage5.ResumeLayout(false); + this.GroupBox11.ResumeLayout(false); + this.GroupBox11.PerformLayout(); + this.GroupBox3.ResumeLayout(false); + this.GroupBox3.PerformLayout(); + this.GroupBox8.ResumeLayout(false); + this.GroupBox8.PerformLayout(); + this.GroupBox7.ResumeLayout(false); + this.GroupBox7.PerformLayout(); + this.TabPage3.ResumeLayout(false); + this.TabPage3.PerformLayout(); + this.GroupBox10.ResumeLayout(false); + this.GroupBox10.PerformLayout(); + this.GroupBox9.ResumeLayout(false); + this.GroupBox9.PerformLayout(); + this.GroupBox5.ResumeLayout(false); + this.GroupBox5.PerformLayout(); + this.GroupBox4.ResumeLayout(false); + this.GroupBox4.PerformLayout(); + this.TabPage2.ResumeLayout(false); + this.GroupBox2.ResumeLayout(false); + this.GroupBox2.PerformLayout(); + this.TabPage1.ResumeLayout(false); + this.GroupBox1.ResumeLayout(false); + this.GroupBox1.PerformLayout(); + this.Panel2.ResumeLayout(false); + this.Panel2.PerformLayout(); + this.TabPage4.ResumeLayout(false); + this.GroupBox6.ResumeLayout(false); + this.GroupBox6.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox2)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox3)).EndInit(); + this.menuStrip1.ResumeLayout(false); + this.menuStrip1.PerformLayout(); + this.groupBox12.ResumeLayout(false); + this.groupBox12.PerformLayout(); + this.panelTesto.ResumeLayout(false); + this.panelMiniature.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + internal System.Windows.Forms.ProgressBar ProgressBar1; + internal System.Windows.Forms.CheckBox CheckBox22; + internal System.Windows.Forms.Label Label43; + internal System.Windows.Forms.TabControl TabControl1; + internal System.Windows.Forms.TabPage TabPage5; + internal System.Windows.Forms.GroupBox GroupBox11; + internal System.Windows.Forms.Label Label8; + internal System.Windows.Forms.TextBox TextBox8; + internal System.Windows.Forms.Label Label7; + internal System.Windows.Forms.TextBox TextBox7; + internal System.Windows.Forms.GroupBox GroupBox3; + internal System.Windows.Forms.CheckBox chkAggiornaSottodirectory; + internal System.Windows.Forms.Button Button3; + internal System.Windows.Forms.Button Button2; + internal System.Windows.Forms.Label Label1; + internal System.Windows.Forms.Label Label2; + internal System.Windows.Forms.TextBox txtSorgente; + internal System.Windows.Forms.TextBox txtDestinazione; + internal System.Windows.Forms.GroupBox GroupBox8; + internal System.Windows.Forms.RadioButton rdbNumFiles; + internal System.Windows.Forms.RadioButton rdbNumProgressiva; + internal System.Windows.Forms.TextBox txtCifreContatore; + internal System.Windows.Forms.Label Label34; + internal System.Windows.Forms.TextBox txtSuffissoCartelle; + internal System.Windows.Forms.Label Label33; + internal System.Windows.Forms.Label Label31; + internal System.Windows.Forms.CheckBox chkCreaSottocartelle; + internal System.Windows.Forms.TextBox txtFilePerCartella; + internal System.Windows.Forms.Label Label32; + internal System.Windows.Forms.GroupBox GroupBox7; + internal System.Windows.Forms.CheckBox chkSovrascriviFile; + internal System.Windows.Forms.CheckBox chkRotazioneAutomatica; + internal System.Windows.Forms.CheckBox chkForzaJpg; + internal System.Windows.Forms.TabPage TabPage3; + internal System.Windows.Forms.CheckBox CheckBox2; + internal System.Windows.Forms.GroupBox GroupBox10; + internal System.Windows.Forms.Label Label42; + internal System.Windows.Forms.Label Label41; + internal System.Windows.Forms.TextBox TextBox31; + internal System.Windows.Forms.TextBox TextBox30; + internal System.Windows.Forms.GroupBox GroupBox9; + internal System.Windows.Forms.CheckBox CheckBox17; + internal System.Windows.Forms.CheckBox CheckBox16; + internal System.Windows.Forms.GroupBox GroupBox5; + internal System.Windows.Forms.TextBox TextBox34; + internal System.Windows.Forms.Button Button8; + internal System.Windows.Forms.Label Label36; + internal System.Windows.Forms.TextBox TextBox25; + internal System.Windows.Forms.Label Label35; + internal System.Windows.Forms.ComboBox ComboBox3; + internal System.Windows.Forms.TextBox TextBox11; + internal System.Windows.Forms.Label Label12; + internal System.Windows.Forms.Label Label11; + internal System.Windows.Forms.CheckBox CheckBox3; + internal System.Windows.Forms.GroupBox GroupBox4; + internal System.Windows.Forms.Label Label40; + internal System.Windows.Forms.TextBox TextBox29; + internal System.Windows.Forms.TextBox TextBox18; + internal System.Windows.Forms.Label Label26; + internal System.Windows.Forms.DateTimePicker DateTimePicker1; + internal System.Windows.Forms.CheckBox CheckBox8; + internal System.Windows.Forms.TextBox TextBox9; + internal System.Windows.Forms.CheckBox CheckBox7; + internal System.Windows.Forms.Label Label4; + internal System.Windows.Forms.TextBox TextBox4; + internal System.Windows.Forms.Label Label9; + internal System.Windows.Forms.Label Label13; + internal System.Windows.Forms.ComboBox ComboBox1; + internal System.Windows.Forms.ComboBox ComboBox2; + internal System.Windows.Forms.Label Label14; + internal System.Windows.Forms.TextBox TextBox12; + internal System.Windows.Forms.Label Label15; + internal System.Windows.Forms.TabPage TabPage2; + internal System.Windows.Forms.GroupBox GroupBox2; + internal System.Windows.Forms.Label Label45; + internal System.Windows.Forms.TextBox TextBox32; + internal System.Windows.Forms.TextBox TextBox26; + internal System.Windows.Forms.Label Label37; + internal System.Windows.Forms.Label Label38; + internal System.Windows.Forms.TextBox TextBox27; + internal System.Windows.Forms.Label Label39; + internal System.Windows.Forms.TextBox TextBox28; + internal System.Windows.Forms.CheckBox CheckBox15; + internal System.Windows.Forms.TabPage TabPage1; + internal System.Windows.Forms.GroupBox GroupBox1; + internal System.Windows.Forms.Label Label46; + internal System.Windows.Forms.TextBox TextBox33; + internal System.Windows.Forms.Panel Panel2; + internal System.Windows.Forms.RadioButton RadioButton3; + internal System.Windows.Forms.RadioButton RadioButton7; + internal System.Windows.Forms.RadioButton RadioButton4; + internal System.Windows.Forms.RadioButton RadioButton6; + internal System.Windows.Forms.RadioButton RadioButton5; + internal System.Windows.Forms.Label Label5; + internal System.Windows.Forms.TextBox TextBox5; + internal System.Windows.Forms.Label Label6; + internal System.Windows.Forms.TextBox TextBox6; + internal System.Windows.Forms.Label Label3; + internal System.Windows.Forms.TextBox TextBox3; + internal System.Windows.Forms.CheckBox CheckBox1; + internal System.Windows.Forms.TabPage TabPage4; + internal System.Windows.Forms.GroupBox GroupBox6; + internal System.Windows.Forms.PictureBox PictureBox2; + internal System.Windows.Forms.PictureBox PictureBox1; + internal System.Windows.Forms.ComboBox ComboBox5; + internal System.Windows.Forms.ComboBox ComboBox4; + internal System.Windows.Forms.TextBox TextBox19; + internal System.Windows.Forms.Label Label28; + internal System.Windows.Forms.CheckBox CheckBox5; + internal System.Windows.Forms.TextBox TextBox15; + internal System.Windows.Forms.TextBox TextBox14; + internal System.Windows.Forms.Label Label25; + internal System.Windows.Forms.TextBox TextBox16; + internal System.Windows.Forms.Label Label24; + internal System.Windows.Forms.Label Label22; + internal System.Windows.Forms.Label Label23; + internal System.Windows.Forms.Button Button4; + internal System.Windows.Forms.TextBox TextBox10; + internal System.Windows.Forms.Label Label29; + internal System.Windows.Forms.Label Label30; + internal System.Windows.Forms.PictureBox PictureBox3; + internal System.Windows.Forms.Label Label20; + internal System.Windows.Forms.Label Label19; + internal System.Windows.Forms.Label Label18; + internal System.Windows.Forms.Label lblFotoTotaliNum; + private System.Windows.Forms.MenuStrip menuStrip1; + private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem caricaImpostazioniToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem salvaImpostazioniToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem creaCatalogoToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem aiutoToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem informazioniToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem esciToolStripMenuItem; + private System.Windows.Forms.GroupBox groupBox12; + private System.Windows.Forms.Button btnStopCreazione; + private System.Windows.Forms.ListBox lblLog; + private System.Windows.Forms.TextBox txtFileInfo; + private System.Windows.Forms.Panel panelTesto; + private System.Windows.Forms.Panel panelMiniature; + + } +} + diff --git a/ImageCatalogCS/MainForm.cs b/ImageCatalogCS/MainForm.cs new file mode 100644 index 0000000..c11509f --- /dev/null +++ b/ImageCatalogCS/MainForm.cs @@ -0,0 +1,548 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.IO; +using System.Drawing.Text; +using System.Threading; + +public delegate void XyThreadAdd(string Info); + +namespace ImageCatalogCS +{ + public partial class MainForm : Form + { + private bool stopAttivo; + private bool waterSelectColor = false; + + //pool + private XYThreadPool myPool = new XYThreadPool(); + + private int contaImmaginiThread; + + private int maxThreads = 15; + private int minThreads = 5; + + public MainForm() + { + InitializeComponent(); + } + + private void setDefaults() + { + txtSorgente.Text = ""; + txtDestinazione.Text = ""; + TextBox3.Text = "tn_"; + TextBox4.Text = ""; + TextBox5.Text = "350"; + TextBox6.Text = "350"; + TextBox27.Text = "2240"; + TextBox28.Text = "2240"; + TextBox9.Text = "0"; + TextBox11.Text = "20"; + TextBox12.Text = "8"; + //TextBox13.Text = "" + TextBox10.Text = ""; + TextBox14.Text = "430"; + TextBox15.Text = "430"; + TextBox16.Text = "290"; + txtFilePerCartella.Text = "99"; + TextBox19.Text = "100"; + txtSuffissoCartelle.Text = ""; + txtCifreContatore.Text = "2"; + TextBox25.Text = "50"; + TextBox26.Text = ""; + TextBox7.Text = Convert.ToString(15); + TextBox8.Text = Convert.ToString(5); + TextBox34.Text = "Yellow"; + TextBox30.Text = "20"; + TextBox31.Text = "6"; + TextBox32.Text = "85"; + TextBox33.Text = "30"; + + + ComboBox1.Items.Add("Alto"); + ComboBox1.Items.Add("Basso"); + ComboBox1.SelectedIndex = 1; + + ComboBox2.Items.Add("Sinistra"); + ComboBox2.Items.Add("Centro"); + ComboBox2.Items.Add("Destra"); + ComboBox2.SelectedIndex = 1; + + // Create a obejct of InstalledFontCollection + InstalledFontCollection InstalledFonts = new InstalledFontCollection(); + // Gets the array of FontFamily objects associated with this FontCollection. + FontFamily[] fontfamilies = InstalledFonts.Families; + + // Populates font combobox with the font name + + foreach (FontFamily fontFamily in fontfamilies) + { + ComboBox3.Items.Add(fontFamily.Name); + } + + ComboBox3.Text = ComboBox3.Items[0].ToString(); + + ComboBox4.Items.Add("Sinistra"); + ComboBox4.Items.Add("Centro"); + ComboBox4.Items.Add("Destra"); + ComboBox4.SelectedIndex = 2; + + ComboBox5.Items.Add("Alto"); + ComboBox5.Items.Add("Centro"); + ComboBox5.Items.Add("Basso"); + ComboBox5.SelectedIndex = 2; + } + + private void Form1_Load(object sender, EventArgs e) + { + Application.EnableVisualStyles(); + setDefaults(); + } + + private void btnCreaCatalogo_Click(object sender, EventArgs e) + { + DateTime timestart; + DateTime timeStop; + + timestart = DateTime.Now; + + txtFileInfo.Text = string.Empty; + lblFotoTotaliNum.Text = "0"; + Label18.Text = "0"; + Label43.Text = "-s"; + + maxThreads = Convert.ToInt32(TextBox7.Text); + minThreads = Convert.ToInt32(TextBox18.Text); + + //setPicSettings(txtSorgente.Text, txtDestinazione.Text); + makeSettingsFromForm(); + ProgressBar1.Minimum = 0; + ProgressBar1.Step = 1; + ProgressBar1.Value = 0; + + System.Threading.Thread t1 = new System.Threading.Thread(creaCatalogoThread); + + + } + + private void creaCatalogoThread() +{ + System.DateTime timeStart = DateTime.Now; + myPool.StopThreadPool(); + myPool.StartThreadPool(minThreads, maxThreads); + contaImmaginiThread = 0; + + //creaImmaginiWithThreadMod(txtSorgente.Text, txtDestinazione.Text) + //creaimmaginiWithThreadDict(txtSorgente.Text, txtDestinazione.Text); + ThreadPoolWorkItem ThAttivo = null; + //int i = 0; + + // fine + + +} + + private int getNumerazione() + { + int numerazione = 0; + if (rdbNumProgressiva.Checked) + { + numerazione = (int)FileHelper.numerazione.Progressiva; + } + else + { + numerazione = (int)FileHelper.numerazione.Files; + } + return numerazione; + } + + private void creaimmaginiWithThreadDict(string SourcePath, string DestPath) +{ + Dictionary dirSourceDest = new Dictionary(); + + if (chkAggiornaSottodirectory.Checked & chkCreaSottocartelle.Checked) { + FileHelper helper = new FileHelper(Convert.ToInt32(txtFilePerCartella.Text), txtSuffissoCartelle.Text, Convert.ToInt32(txtCifreContatore.Text), getNumerazione()); + //getfilesrecursive + dirSourceDest = helper.GetFilesRecursive(new DirectoryInfo(SourcePath), new DirectoryInfo(DestPath), "*.jpg"); + + } else if (chkAggiornaSottodirectory.Checked & !chkCreaSottocartelle.Checked) { + + } + //else if () + + //= getDirsDict(SourcePath, DestPath) + + KeyValuePair pair = default(KeyValuePair); + + foreach (KeyValuePair pair_loopVariable in dirSourceDest) { + pair = pair_loopVariable; + //setLabel10Text("File: " + pair.Key.Name); + string b = (Convert.ToInt32(Label18.Text) + 1).ToString(); + + ImageCreator ClsCreaImmagine = new ImageCreator(pair.Key, pair.Value); + contaImmaginiThread += 1; + myPool.InsertWorkItem(pair.Key.Name, new XyThreadAdd(ClsCreaImmagine.CreaImmagineThread), new object[1] { pair.Key.Name }, true); + + } + +} + + private Dictionary makeSettingsFromForm() + { + Dictionary settingsDict = new Dictionary(); + settingsDict.Add("sourceDirRoot", new DirectoryInfo(txtSorgente.Text)); + settingsDict.Add("destDirRoot", new DirectoryInfo(txtDestinazione.Text)); + + settingsDict.Add("DirDividiDestinazione", chkCreaSottocartelle.Checked); + settingsDict.Add("DirDividiNumFile", txtFilePerCartella.Text); + settingsDict.Add("DirDividiSuffisso", txtSuffissoCartelle.Text); + settingsDict.Add("DirDividiNumCifre", txtCifreContatore.Text); + + settingsDict.Add("DirDividiTipoNumerazione", rdbNumProgressiva.Checked ? "Progressiva" : "Files"); + + // if (rdbNumProgressiva.Checked) + // settingsDict.Add("DirDividiTipoNumerazione", "Progressiva"); + //else + // settingsDict.Add("DirDividiTipoNumerazione", "Files"); + + // Checkbox + settingsDict.Add("creaMiniature", CheckBox1.Checked); + settingsDict.Add("aggiungiTesto", CheckBox2.Checked); + settingsDict.Add("grassetto", CheckBox3.Checked); + settingsDict.Add("logoAggiungi", CheckBox5.Checked); + settingsDict.Add("usaOrarioTestoApplicare", CheckBox8.Checked); + //settingsDict.Add("usaOrarioMiniatura", CheckBox12.Checked); + settingsDict.Add("fotoGrandeDimOrigina", CheckBox15.Checked); + + settingsDict.Add("dimStandard", Convert.ToInt32(TextBox11.Text)); + settingsDict.Add("dimStandardMiniatura", Convert.ToInt32(TextBox25.Text)); + + + + + settingsDict.Add("usaRotazioneAutomatica", chkRotazioneAutomatica.Checked); + settingsDict.Add("usaForzaJpg", chkForzaJpg.Checked); + + settingsDict.Add("testoNome", CheckBox17.Checked); + settingsDict.Add("nomeData", CheckBox16.Checked); + + settingsDict.Add("testoFirmaStart", TextBox4.Text); + settingsDict.Add("testoFirmaStartV", TextBox29.Text); + + settingsDict.Add("dataPartenza", DateTimePicker1.Value); + settingsDict.Add("testoOrario", TextBox18.Text); + + settingsDict.Add("altezzaSmall", Convert.ToInt32(TextBox6.Text)); + settingsDict.Add("larghezzaSmall", Convert.ToInt32(TextBox5.Text)); + + + settingsDict.Add("aggiungiScritteMiniature", RadioButton3.Checked); + settingsDict.Add("aggTempoGaraMin", RadioButton5.Checked); + settingsDict.Add("aggNumTempMin", RadioButton7.Checked); + + settingsDict.Add("dimVert", Convert.ToUInt32(TextBox30.Text)); + settingsDict.Add("margVert", Convert.ToInt32(TextBox31.Text)); + + settingsDict.Add("suffisso", TextBox3.Text); + settingsDict.Add("trasparenza", Convert.ToInt32(TextBox9.Text)); + settingsDict.Add("ilFont", ComboBox3.SelectedItem.ToString()); + + + settingsDict.Add("posizione", ComboBox1.SelectedItem.ToString()); + settingsDict.Add("allineamento", ComboBox2.SelectedItem.ToString()); + settingsDict.Add("margine", Convert.ToInt32(TextBox12.Text)); + + settingsDict.Add("logoAltezza", Convert.ToInt32(TextBox14.Text)); + settingsDict.Add("logoLarghezza", Convert.ToInt32(TextBox15.Text)); + + settingsDict.Add("fontColoreRGB", ColorTranslator.FromHtml(TextBox34.Text)); + + + settingsDict.Add("logoNomeFile", TextBox10.Text); + settingsDict.Add("logoTrasparenza", TextBox19.Text); + settingsDict.Add("logoMargine", TextBox16.Text); + settingsDict.Add("logoPosizioneH", ComboBox4.Text); + settingsDict.Add("logoPosizioneV", ComboBox5.Text); + + + settingsDict.Add("altezzaBig", Convert.ToInt32(TextBox27.Text)); + settingsDict.Add("larghezzaBig", Convert.ToInt32(TextBox28.Text)); + settingsDict.Add("dimMin", Convert.ToInt32(TextBox25.Text)); + + settingsDict.Add("testoMin", RadioButton6.Checked); + + settingsDict.Add("jpegQuality", Convert.ToInt32(TextBox32.Text)); + settingsDict.Add("jpegQualityMin", Convert.ToInt32(TextBox33.Text)); + + return settingsDict; + } + + private void setPicSettings(string SourcePath, string DestPath) + { + DirectoryInfo SourceDir = new DirectoryInfo(SourcePath); + DirectoryInfo DestDirStart = new DirectoryInfo(DestPath); + DirectoryInfo DestDir = null; + + PicSettings.directorySorgente = txtSorgente.Text; + PicSettings.directoryDestinazione = txtDestinazione.Text; + + + PicSettings.dimStandard = Convert.ToInt32(TextBox11.Text); + PicSettings.dimStandardMiniatura = Convert.ToInt32(TextBox25.Text); + + //PicSettings.UsaOrarioMiniatura = CheckBox12.Checked; + PicSettings.UsaOrarioTestoApplicare = CheckBox8.Checked; + PicSettings.UsaTempoGaraTestoApplicare = CheckBox7.Checked; + + PicSettings.UsaRotazioneAutomatica = chkRotazioneAutomatica.Checked; + PicSettings.UsaForzaJpg = chkForzaJpg.Checked; + + if (CheckBox17.Checked) + { + PicSettings.TestoNome = true; + } + else + { + PicSettings.TestoNome = false; + + } + + if (CheckBox16.Checked) + { + PicSettings.NomeData = true; + } + else + { + PicSettings.NomeData = false; + } + PicSettings.TestoFirmaStart = TextBox4.Text; + PicSettings.TestoFirmaStartV = TextBox29.Text; + + PicSettings.DataPartenza = DateTimePicker1.Value; + PicSettings.TestoOrario = TextBox18.Text; + + PicSettings.AltezzaSmall = Convert.ToInt32(TextBox6.Text); + PicSettings.LarghezzaSmall = Convert.ToInt32(TextBox5.Text); + + PicSettings.CreaMiniature = CheckBox1.Checked; + PicSettings.AggiungiScritteMiniature = RadioButton3.Checked; + PicSettings.AggTempoGaraMin = RadioButton5.Checked; + PicSettings.AggNumTempMin = RadioButton7.Checked; + + + PicSettings.dimVert = Convert.ToInt32(TextBox30.Text); + PicSettings.margVert = Convert.ToInt32(TextBox31.Text); + + //PicSettings.NomeFileChild = childFile.Name + PicSettings.Suffisso = TextBox3.Text; + //PicSettings.Codice = TextBox13.Text + + PicSettings.Trasparenza = Convert.ToInt32(TextBox9.Text); + PicSettings.IlFont = ComboBox3.SelectedItem.ToString(); + PicSettings.Grassetto = CheckBox3.Checked; + + PicSettings.Posizione = ComboBox1.SelectedItem.ToString(); + PicSettings.Allineamento = ComboBox2.SelectedItem.ToString(); + PicSettings.Margine = Convert.ToInt32(TextBox12.Text); + + PicSettings.LogoAltezza = Convert.ToInt32(TextBox14.Text); + PicSettings.LogoLarghezza = Convert.ToInt32(TextBox15.Text); + + PicSettings.fontColoreRGB = ColorTranslator.FromHtml(TextBox34.Text); + + PicSettings.LogoAggiungi = CheckBox5.Checked; + PicSettings.LogoNomeFile = TextBox10.Text; + PicSettings.LogoTrasparenza = TextBox19.Text; + PicSettings.LogoMargine = TextBox16.Text; + PicSettings.LogoPosizioneH = ComboBox4.Text; + PicSettings.LogoPosizioneV = ComboBox5.Text; + + PicSettings.FotoGrandeDimOrigina = CheckBox15.Checked; + PicSettings.AltezzaBig = Convert.ToInt32(TextBox27.Text); + PicSettings.LarghezzaBig = Convert.ToInt32(TextBox28.Text); + PicSettings.DimMin = Convert.ToInt32(TextBox25.Text); + + PicSettings.TestoMin = RadioButton6.Checked; + + PicSettings.jpegQuality = Convert.ToInt64(TextBox32.Text); + PicSettings.jpegQualityMin = Convert.ToInt64(TextBox33.Text); + + PicSettings.mainForm = this; + + + } + + private void makeSettingsFromFile() + { + OpenFileDialog openFileDialog = new OpenFileDialog(); + openFileDialog.Filter = "Setup (*.xml)|*.xml|All valid files (*.*)|*.*"; + openFileDialog.FilterIndex = 0; + openFileDialog.RestoreDirectory = true; + + Dictionary settingsDict = new Dictionary(StringComparer.OrdinalIgnoreCase); + + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + XMLSettings xmlSettings = new XMLSettings(openFileDialog.FileName); + settingsDict = xmlSettings.getParametriDict(); + + + settingsDict = bindSettings(settingsDict); + setLogoMiniature(); + this.Text = string.Format("Image Catalog - {0}", openFileDialog.FileName); + + + } + } + + private void setLogoMiniature() + { + if (File.Exists(TextBox10.Text)) + { + + PictureBox1.Image = Image.FromFile(TextBox10.Text); + if (PictureBox1.Image.Height >= PictureBox1.Image.Width) + { + PictureBox1.Height = 160; + PictureBox1.Width = Convert.ToInt32(160 * PictureBox1.Image.Width / PictureBox1.Image.Height); + } + else + { + PictureBox1.Width = 224; + PictureBox1.Height = Convert.ToInt32(224 * PictureBox1.Image.Height / PictureBox1.Image.Width); + } + } + } + + private Dictionary bindSettings(Dictionary dict) + { + + txtSorgente.Text = dict["dirSorgente"].ToString(); + txtDestinazione.Text = dict["dirDestinazione"].ToString(); + chkAggiornaSottodirectory.Checked = Convert.ToBoolean(dict["DirSottoDirectory"]); + + chkCreaSottocartelle.Checked = Convert.ToBoolean(dict["dirDividiDestinazione"]); + txtFilePerCartella.Text = dict["dirDividiNumFile"].ToString(); + txtSuffissoCartelle.Text = dict["dirDividiSuffisso"].ToString(); + txtCifreContatore.Text = dict["dirDividiNumCifre"].ToString(); + + if (dict["dirDividiTipoNumerazione"].ToString().ToUpper() == "PROGRESSIVA") + rdbNumProgressiva.Checked = true; + else + rdbNumFiles.Checked = true; + + CheckBox1.Checked = Convert.ToBoolean(dict["miniatureCrea"]); + TextBox3.Text = dict["miniatureSuffisso"].ToString(); + TextBox5.Text = dict["miniatureAltezza"].ToString(); + TextBox6.Text = dict["miniatureLarghezza"].ToString(); + RadioButton3.Checked = Convert.ToBoolean(dict["miniatureAddScritta"]); + RadioButton4.Checked = Convert.ToBoolean(dict["miniatureAddOrario"]); + + TextBox27.Text = dict["fotoAltezza"].ToString(); + TextBox28.Text = dict["fotoLarghezza"].ToString(); + + TextBox11.Text = dict["fontDimensione"].ToString(); + TextBox25.Text = dict["fontDimensioneMiniatura"].ToString(); + CheckBox3.Checked = Convert.ToBoolean(dict["fontBold"]); + ComboBox3.Text = dict["fontNome"].ToString(); + + TextBox4.Text = dict["testoTesto"].ToString(); + TextBox9.Text = dict["testoTrasparente"].ToString(); + TextBox12.Text = dict["testoMargine"].ToString(); + ComboBox1.Text = dict["testoPosizione"].ToString(); + ComboBox2.Text = dict["testoAllineamento"].ToString(); + + TextBox10.Text = dict["marchioFile"].ToString(); + TextBox14.Text = dict["marchioAltezza"].ToString(); + TextBox15.Text = dict["marchioLarghezza"].ToString(); + TextBox16.Text = dict["marchioMargine"].ToString(); + ComboBox4.Text = dict["marchioAllOrizzontale"].ToString(); + ComboBox5.Text = dict["marchioAllVerticale"].ToString(); + TextBox19.Text = dict["marchioTrasparenza"].ToString(); + CheckBox5.Checked = Convert.ToBoolean(dict["MarchioAggiungi"]); + + CheckBox7.Checked = Convert.ToBoolean(dict["tempoGara"]); + CheckBox8.Checked = Convert.ToBoolean(dict["orario"]); + TextBox18.Text = dict["etichettaOrario"].ToString(); + + chkForzaJpg.Checked = Convert.ToBoolean(dict["generaleForzaJpg"]); + chkRotazioneAutomatica.Checked = Convert.ToBoolean(dict["generaleRotazioneAutomatica"]); + + TextBox30.Text = dict["grandezzaVerticale"].ToString(); + TextBox31.Text = dict["margineVerticale"].ToString(); + CheckBox15.Checked = Convert.ToBoolean(dict["dimensioniOriginali"]); + TextBox29.Text = dict["testoVerticale"].ToString(); + RadioButton6.Checked = Convert.ToBoolean(dict["nomeMiniatura"]); + CheckBox16.Checked = Convert.ToBoolean(dict["dataFoto"]); + CheckBox17.Checked = Convert.ToBoolean(dict["numeroFoto"]); + + + RadioButton5.Checked = Convert.ToBoolean(dict["tempoSmall"]); + RadioButton7.Checked = Convert.ToBoolean(dict["numTempoSmall"]); + + TextBox32.Text = dict["compressioneJpeg"].ToString(); + TextBox33.Text = dict["compressioneJpegMiniatura"].ToString(); + + TextBox34.Text = dict["coloreTestoRGB"].ToString(); + + + + return dict; + } + + + + + private void caricaImpostazioniToolStripMenuItem_Click(object sender, EventArgs e) + { + makeSettingsFromFile(); + } + + private void btnStopCreazione_Click(object sender, EventArgs e) + { + + } + + private void informazioniToolStripMenuItem_Click(object sender, EventArgs e) + { + AboutForm about = new AboutForm(); + about.Show(); + } + + private void CheckBox2_CheckedChanged(object sender, EventArgs e) + { + if (CheckBox2.Checked) + panelTesto.Enabled = true; + else + panelTesto.Enabled = false; + } + + private void CheckBox1_CheckedChanged(object sender, EventArgs e) + { + if (CheckBox1.Checked) + panelMiniature.Enabled = true; + else + panelMiniature.Enabled = false; + } + + + + + + + + + + + + + + } +} diff --git a/ImageCatalogCS/MainForm.resx b/ImageCatalogCS/MainForm.resx new file mode 100644 index 0000000..d5494e3 --- /dev/null +++ b/ImageCatalogCS/MainForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 17, 17 + + \ No newline at end of file diff --git a/ImageCatalogCS/PicSettings.cs b/ImageCatalogCS/PicSettings.cs new file mode 100644 index 0000000..9f930c8 --- /dev/null +++ b/ImageCatalogCS/PicSettings.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ImageCatalogCS +{ + static class PicSettings + { + // Root + public static string directorySorgente { get; set; } + public static string directoryDestinazione { get; set; } + + public static int dimVert { get; set; } + public static int margVert { get; set; } + + public static int dimStandard { get; set; } + public static int dimStandardMiniatura { get; set; } + + public static bool NomeData { get; set; } + public static bool TestoNome { get; set; } + public static bool UsaOrarioMiniatura { get; set; } + public static bool UsaOrarioTestoApplicare { get; set; } + public static bool UsaTempoGaraTestoApplicare { get; set; } + public static string TestoFirmaStart { get; set; } + public static string TestoFirmaStartV { get; set; } + public static DateTime DataPartenza { get; set; } + + public static string TestoOrario { get; set; } + public static bool UsaRotazioneAutomatica { get; set; } + + public static bool UsaForzaJpg { get; set; } + public static int LarghezzaSmall { get; set; } + + public static int AltezzaSmall { get; set; } + public static bool CreaMiniature { get; set; } + public static bool AggiungiScritteMiniature { get; set; } + public static bool AggTempoGaraMin { get; set; } + + public static bool AggNumTempMin { get; set; } + public static string Suffisso { get; set; } + + public static string Codice { get; set; } + public static int Trasparenza { get; set; } + public static string IlFont { get; set; } + + public static bool Grassetto { get; set; } + public static string Posizione { get; set; } + public static string Allineamento { get; set; } + + public static int Margine { get; set; } + public static int LogoAltezza { get; set; } + + public static int LogoLarghezza { get; set; } + + public static Color fontColoreRGB { get; set; } + public static bool LogoAggiungi { get; set; } + public static string LogoNomeFile { get; set; } + public static string LogoTrasparenza { get; set; } + public static string LogoMargine { get; set; } + public static string LogoPosizioneH { get; set; } + + public static string LogoPosizioneV { get; set; } + public static bool FotoGrandeDimOrigina { get; set; } + public static int AltezzaBig { get; set; } + public static int LarghezzaBig { get; set; } + public static DirectoryInfo DestDir { get; set; } + + public static int DimMin { get; set; } + + public static bool TestoMin { get; set; } + public static bool SecretDefault { get; set; } + public static bool SecretBig { get; set; } + + public static bool SecretSmall { get; set; } + public static string SecretPathSmall { get; set; } + + public static string SecretPathBig { get; set; } + public static long jpegQuality { get; set; } + + public static long jpegQualityMin { get; set; } + public static bool FotoRuotaADestra { get; set; } // Default False + + public static bool FotoRuotaASinistra { get; set; } // Default False + + public static string TempMinText { get; set; } // Default "" + public static MainForm mainForm { get; set; } + } +} diff --git a/ImageCatalogCS/Program.cs b/ImageCatalogCS/Program.cs new file mode 100644 index 0000000..9c2ec36 --- /dev/null +++ b/ImageCatalogCS/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ImageCatalogCS +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/ImageCatalogCS/Properties/AssemblyInfo.cs b/ImageCatalogCS/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..97f38c2 --- /dev/null +++ b/ImageCatalogCS/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ImageCatalogCS")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ImageCatalogCS")] +[assembly: AssemblyCopyright("Copyright © 2012")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("00b0a7a5-0de0-48e6-b0c9-ec214aa338dd")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ImageCatalogCS/Properties/Resources.Designer.cs b/ImageCatalogCS/Properties/Resources.Designer.cs new file mode 100644 index 0000000..6af1fd8 --- /dev/null +++ b/ImageCatalogCS/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ImageCatalogCS.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ImageCatalogCS.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/ImageCatalogCS/Properties/Resources.resx b/ImageCatalogCS/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/ImageCatalogCS/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ImageCatalogCS/Properties/Settings.Designer.cs b/ImageCatalogCS/Properties/Settings.Designer.cs new file mode 100644 index 0000000..0e29f59 --- /dev/null +++ b/ImageCatalogCS/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ImageCatalogCS.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.11.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/ImageCatalogCS/Properties/Settings.settings b/ImageCatalogCS/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/ImageCatalogCS/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/ImageCatalogCS/Temperature.cs b/ImageCatalogCS/Temperature.cs new file mode 100644 index 0000000..a56ed82 --- /dev/null +++ b/ImageCatalogCS/Temperature.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Management; + + + +namespace ImageCatalogCS +{ + public class Temperature + { + public double CurrentValue { get; set; } + public string InstanceName { get; set; } + public static List Temperatures + { + get + { + List result = new List(); + ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature"); + foreach (ManagementObject obj in searcher.Get()) + { + Double temp = Convert.ToDouble(obj["CurrentTemperature"].ToString()); + temp = (temp - 2732) / 10.0; + result.Add(new Temperature { CurrentValue = temp, InstanceName = obj["InstanceName"].ToString() }); + } + return result; + + } + } + } +} diff --git a/ImageCatalogCS/XMLSettings.cs b/ImageCatalogCS/XMLSettings.cs new file mode 100644 index 0000000..2443542 --- /dev/null +++ b/ImageCatalogCS/XMLSettings.cs @@ -0,0 +1,208 @@ +using Microsoft.VisualBasic; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.IO; + +public class XMLSettings +{ + + + private DataSet _ElencoParametri; + + private string _NomeFileSetup; + public XMLSettings(string FileSetup) + { + _ElencoParametri = new DataSet(); + _NomeFileSetup = FileSetup; + + if (!string.IsNullOrEmpty(FileSetup)) + { + CaricaParametriSetup(); + } + } + + public XMLSettings() + { + _ElencoParametri = new DataSet(); + _NomeFileSetup = ""; + } + + public void CaricaParametriSetup() + { + _ElencoParametri = LeggiXmlDataSet("Setup", _NomeFileSetup, "Nome"); + } + + public void SalvaParametriSetup() + { + if (System.IO.File.Exists(_NomeFileSetup) == true) + { + File.Delete(_NomeFileSetup); + } + _ElencoParametri.WriteXml(_NomeFileSetup); + } + + public Dictionary getParametriDict() + { + CaricaParametriSetup(); + Dictionary dictParam = new Dictionary(StringComparer.OrdinalIgnoreCase); + + //DataRow[] LElenco = _ElencoParametri.Tables["Setup"].Select("Nome='" + NomeParametro + "'"); + //DataTable table = _ElencoParametri.Tables["Setup"]; + + foreach (DataRow row in _ElencoParametri.Tables["Setup"].Rows) + { + dictParam.Add(row["Nome"].ToString(), row["Valore"]); + } + + return dictParam; + } + + public string LeggiParametroString(string NomeParametro) + { + string Risposta = ""; + + try + { + DataRow[] LElenco = _ElencoParametri.Tables["Setup"].Select("Nome='" + NomeParametro + "'"); + + DataRow LaRiga = null; + foreach (DataRow LaRiga_loopVariable in LElenco) + { + LaRiga = LaRiga_loopVariable; + Risposta = LaRiga["Valore"].ToString(); + } + } + catch + { + Risposta = ""; + } + + return Risposta; + } + + public bool LeggiParametroBoolean(string NomeParametro) + { + string Risposta = ""; + + try + { + DataRow[] LElenco = _ElencoParametri.Tables["Setup"].Select("Nome='" + NomeParametro + "'"); + + DataRow LaRiga = null; + foreach (DataRow LaRiga_loopVariable in LElenco) + { + LaRiga = LaRiga_loopVariable; + Risposta = LaRiga["Valore"].ToString(); + } + } + catch + { + Risposta = ""; + } + + switch (Risposta.ToUpper()) + { + case "TRUE": + case "OK": + case "SI": + case "1": + case "YES": + case "VERO": + return true; + default: + return false; + } + } + + public void AggiornaParametro(string NomeParametro, object ValoreParametro) + { + try + { + if (_ElencoParametri.Tables["Setup"] == null) + { + DataTable TabellaTmp = new DataTable("Setup"); + DataRow RigaTmp = null; + + DataColumn LaColonna = null; + LaColonna = TabellaTmp.Columns.Add("Nome", System.Type.GetType("System.String")); + LaColonna = TabellaTmp.Columns.Add("Valore", System.Type.GetType("System.String")); + + //* Aggiunge alla tabella tutte le righe + RigaTmp = TabellaTmp.NewRow(); + RigaTmp["Nome"] = NomeParametro; + RigaTmp["Valore"] = ValoreParametro; + TabellaTmp.Rows.Add(RigaTmp); + + _ElencoParametri.Tables.Add(TabellaTmp); + } + else + { + DataRow[] LElenco = _ElencoParametri.Tables["Setup"].Select("Nome='" + NomeParametro + "'"); + + if (LElenco.Length == 0) + { + DataRow LaRiga = null; + LaRiga = _ElencoParametri.Tables["Setup"].NewRow(); + LaRiga["Nome"] = NomeParametro; + LaRiga["Valore"] = ValoreParametro; + _ElencoParametri.Tables["Setup"].Rows.Add(LaRiga); + } + else + { + LElenco[0]["Valore"] = ValoreParametro; + } + } + + } + catch + { + } + } + + + private DataTable LeggiXmlDataTable(string NomeTabella, string NomeFileXml, string NomeColonnaChiave = "") + { + //* Crea e Legge il dataset dal file xml + System.Data.DataSet DataSetXml = new System.Data.DataSet(); + DataSetXml.ReadXml(NomeFileXml); + + //* Aggiunge il campo chiave + if (!string.IsNullOrEmpty(NomeColonnaChiave)) + { + DataSetXml.Tables[NomeTabella].Constraints.Add(NomeColonnaChiave, DataSetXml.Tables[NomeTabella].Columns[NomeColonnaChiave], true); + } + + //* Restituisce la risposta + return DataSetXml.Tables[NomeTabella]; + } + + private static DataSet LeggiXmlDataSet(string NomeTabella, string NomeFileXml, string NomeColonnaChiave = "") + { + //* Crea e Legge il dataset dal file xml + DataSet DataSetXml = new DataSet(); + DataSetXml.ReadXml(NomeFileXml); + + //* Aggiunge il campo chiave + if (!string.IsNullOrEmpty(NomeColonnaChiave)) + { + DataSetXml.Tables[NomeTabella].Constraints.Add(NomeColonnaChiave, DataSetXml.Tables[NomeTabella].Columns[NomeColonnaChiave], true); + } + + //* Restituisce la risposta + return DataSetXml; + } + + + + + public string NomeFileSetup + { + get { return _NomeFileSetup; } + set { _NomeFileSetup = value; } + } + + +} \ No newline at end of file diff --git a/ImageCatalogCS/XYThreadPool.cs b/ImageCatalogCS/XYThreadPool.cs new file mode 100644 index 0000000..005b30c --- /dev/null +++ b/ImageCatalogCS/XYThreadPool.cs @@ -0,0 +1,251 @@ +using Microsoft.VisualBasic; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; + +using System.Threading; + +public delegate void ThreadErrorHandlerDelegate(ThreadPoolWorkItem oWorkItem, Exception oError); + +public class ThreadPoolWorkItem +{ + public bool m_bStoreOutput = false; + public string m_sName = ""; + public Delegate m_pMethod = null; + public object[] m_pInput = null; + public object m_oOutput = null; + public Exception m_oException = null; + public ThreadPoolWorkItem() + { + } + public ThreadPoolWorkItem(string sName, Delegate pMethod, object[] pInput, bool bStoreOutput) + { + m_sName = sName; + m_pMethod = pMethod; + m_pInput = pInput; + m_bStoreOutput = bStoreOutput; + } +} + +public class XYThreadPool +{ + private Hashtable m_htThreads = new Hashtable(256); + private int m_nMinThreadCount = 5; + private int m_nMaxThreadCount = 10; + private int m_nShutdownPause = 200; + private int m_nServerPause = 25; + private bool m_bContinue = false; + private static Exception m_oException = null; + private Queue m_qInput = new Queue(1024); + private Queue m_qOutput = new Queue(1024); + private Delegate m_delegateThreadErrorHandler = new ThreadErrorHandlerDelegate(OnThreadError); + private void ThreadProc() + { + while (m_bContinue) + { + object obj = null; + Monitor.Enter(this); + if (m_qInput.Count > 0) + obj = m_qInput.Dequeue(); + Monitor.Exit(this); + if (obj == null) + { + bool bQuit = false; + Monitor.Enter(this); + if (m_htThreads.Count > m_nMinThreadCount) + { + m_htThreads.Remove(Thread.CurrentThread.Name); + bQuit = true; + } + Monitor.Exit(this); + if (bQuit) + return; + Thread.Sleep(10 * m_nServerPause); + } + else + { + ThreadPoolWorkItem oWorkItem = (ThreadPoolWorkItem)obj; + //oWorkItem.m_oOutput = oWorkItem.m_pMethod.DynamicInvoke(oWorkItem.m_pInput) + try + { + oWorkItem.m_oOutput = oWorkItem.m_pMethod.DynamicInvoke(oWorkItem.m_pInput); + } + catch (Exception oBug) + { + if ((m_delegateThreadErrorHandler != null)) + { + try + { + object[] pInput = { + oWorkItem, + oBug + }; + m_delegateThreadErrorHandler.DynamicInvoke(pInput); + } + catch + { + } + } + } + if (oWorkItem.m_bStoreOutput) + { + Monitor.Enter(m_qOutput); + m_qOutput.Enqueue(oWorkItem); + Monitor.Exit(m_qOutput); + } + Thread.Sleep(m_nServerPause); + } + } + } + private static void OnThreadError(ThreadPoolWorkItem oWorkItem, Exception oError) + { + if (oWorkItem == null) + { + m_oException = oError; + } + else + { + oWorkItem.m_oException = oError; + } + } + public void SetThreadErrorHandler(ThreadErrorHandlerDelegate pMethod) + { + Monitor.Enter(this); + m_delegateThreadErrorHandler = pMethod; + Monitor.Exit(this); + } + public void SetServerPause(int nMilliseconds) + { + Monitor.Enter(this); + if (nMilliseconds > 9 & nMilliseconds < 101) + m_nServerPause = nMilliseconds; + Monitor.Exit(this); + } + public void SetShutdownPause(int nMilliseconds) + { + Monitor.Enter(this); + m_nShutdownPause = nMilliseconds; + Monitor.Exit(this); + } + public Exception GetException() + { + return m_oException; + } + public void InsertWorkItem(ThreadPoolWorkItem oWorkItem) + { + try + { + Monitor.Enter(this); + m_qInput.Enqueue(oWorkItem); + if (m_bContinue && m_qInput.Count > m_htThreads.Count && m_htThreads.Count < m_nMaxThreadCount) + { + Thread th = new Thread(ThreadProc); + th.Name = Guid.NewGuid().ToString(); + m_htThreads.Add(th.Name, th); + th.Start(); + } + } + catch (Exception oBug) + { + m_oException = oBug; + } + finally + { + Monitor.Exit(this); + } + } + public void InsertWorkItem(string sName, Delegate pMethod, object[] pArgs, bool bStoreOutput) + { + InsertWorkItem(new ThreadPoolWorkItem(sName, pMethod, pArgs, bStoreOutput)); + } + public ThreadPoolWorkItem ExtractWorkItem() + { + object oWorkItem = null; + Monitor.Enter(m_qOutput); + if (m_qOutput.Count > 0) + oWorkItem = m_qOutput.Dequeue(); + Monitor.Exit(m_qOutput); + if (oWorkItem == null) + return null; + return (ThreadPoolWorkItem)oWorkItem; + } + public bool StartThreadPool(int nMinThreadCount = 5, int nMaxThreadCount = 10) + { + try + { + Monitor.Enter(this); + if (m_bContinue == false) + { + m_bContinue = true; + if (nMinThreadCount > 0) + { + m_nMinThreadCount = nMinThreadCount; + } + if (nMaxThreadCount > m_nMinThreadCount) + { + m_nMaxThreadCount = nMaxThreadCount; + } + else + { + m_nMaxThreadCount = 2 * m_nMinThreadCount; + } + int i = 0; + for (i = 1; i <= m_nMinThreadCount; i++) + { + Thread th = new Thread(ThreadProc); + th.Name = Guid.NewGuid().ToString(); + m_htThreads.Add(th.Name, th); + th.Start(); + } + } + return true; + } + catch (Exception oBug) + { + m_bContinue = false; + m_oException = oBug; + return false; + } + finally + { + Monitor.Exit(this); + } + } + public void StopThreadPool() + { + Monitor.Enter(this); + m_bContinue = false; + Thread.Sleep(Math.Max(200, m_nShutdownPause)); + if ((m_nShutdownPause > 0)) + { + IDictionaryEnumerator dict = m_htThreads.GetEnumerator(); + while (dict.MoveNext()) + { + Thread th = (Thread)dict.Value; + if (th.IsAlive) + { + try + { + th.Abort(); + } + catch + { + } + } + } + } + m_htThreads.Clear(); + m_qInput.Clear(); + // m_qOutput.Clear() + Monitor.Exit(this); + } + public int GetThreadCount() + { + Monitor.Enter(this); + int nCount = m_htThreads.Count; + Monitor.Exit(this); + return nCount; + } +} \ No newline at end of file diff --git a/ImageCatalogParallel/App.config b/ImageCatalogParallel/App.config new file mode 100644 index 0000000..193aecc --- /dev/null +++ b/ImageCatalogParallel/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ImageCatalogParallel/Form1.Designer.cs b/ImageCatalogParallel/Form1.Designer.cs new file mode 100644 index 0000000..d598f89 --- /dev/null +++ b/ImageCatalogParallel/Form1.Designer.cs @@ -0,0 +1,1809 @@ + +namespace ImageCatalogParallel +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.TabPage1 = new System.Windows.Forms.TabPage(); + this.Panel1 = new System.Windows.Forms.Panel(); + this.CheckBox18 = new System.Windows.Forms.CheckBox(); + this.CheckBox4 = new System.Windows.Forms.CheckBox(); + this.CheckBox12 = new System.Windows.Forms.CheckBox(); + this.GroupBox1 = new System.Windows.Forms.GroupBox(); + this.Label46 = new System.Windows.Forms.Label(); + this.TextBox33 = new System.Windows.Forms.TextBox(); + this.Panel2 = new System.Windows.Forms.Panel(); + this.RadioButton3 = new System.Windows.Forms.RadioButton(); + this.RadioButton7 = new System.Windows.Forms.RadioButton(); + this.RadioButton4 = new System.Windows.Forms.RadioButton(); + this.RadioButton6 = new System.Windows.Forms.RadioButton(); + this.RadioButton5 = new System.Windows.Forms.RadioButton(); + this.Label5 = new System.Windows.Forms.Label(); + this.TextBox5 = new System.Windows.Forms.TextBox(); + this.Label6 = new System.Windows.Forms.Label(); + this.TextBox6 = new System.Windows.Forms.TextBox(); + this.Label3 = new System.Windows.Forms.Label(); + this.TextBox3 = new System.Windows.Forms.TextBox(); + this.CheckBox1 = new System.Windows.Forms.CheckBox(); + this.Label37 = new System.Windows.Forms.Label(); + this.Label38 = new System.Windows.Forms.Label(); + this.Label45 = new System.Windows.Forms.Label(); + this.TextBox32 = new System.Windows.Forms.TextBox(); + this.TextBox26 = new System.Windows.Forms.TextBox(); + this.TextBox27 = new System.Windows.Forms.TextBox(); + this.Label39 = new System.Windows.Forms.Label(); + this.CheckBox15 = new System.Windows.Forms.CheckBox(); + this.Label40 = new System.Windows.Forms.Label(); + this.TextBox29 = new System.Windows.Forms.TextBox(); + this.TextBox18 = new System.Windows.Forms.TextBox(); + this.Label26 = new System.Windows.Forms.Label(); + this.DateTimePicker1 = new System.Windows.Forms.DateTimePicker(); + this.CheckBox8 = new System.Windows.Forms.CheckBox(); + this.TextBox9 = new System.Windows.Forms.TextBox(); + this.CheckBox7 = new System.Windows.Forms.CheckBox(); + this.Label4 = new System.Windows.Forms.Label(); + this.TextBox4 = new System.Windows.Forms.TextBox(); + this.Label9 = new System.Windows.Forms.Label(); + this.TextBox28 = new System.Windows.Forms.TextBox(); + this.TabPage2 = new System.Windows.Forms.TabPage(); + this.GroupBox2 = new System.Windows.Forms.GroupBox(); + this.Label27 = new System.Windows.Forms.Label(); + this.Button7 = new System.Windows.Forms.Button(); + this.Button5 = new System.Windows.Forms.Button(); + this.PictureBox2 = new System.Windows.Forms.PictureBox(); + this.PictureBox1 = new System.Windows.Forms.PictureBox(); + this.ComboBox5 = new System.Windows.Forms.ComboBox(); + this.ComboBox4 = new System.Windows.Forms.ComboBox(); + this.Label19 = new System.Windows.Forms.Label(); + this.Label18 = new System.Windows.Forms.Label(); + this.lblFotoTotaliNum = new System.Windows.Forms.Label(); + this.Label10 = new System.Windows.Forms.Label(); + this.TextBox19 = new System.Windows.Forms.TextBox(); + this.Label28 = new System.Windows.Forms.Label(); + this.CheckBox5 = new System.Windows.Forms.CheckBox(); + this.TextBox15 = new System.Windows.Forms.TextBox(); + this.TextBox14 = new System.Windows.Forms.TextBox(); + this.Label25 = new System.Windows.Forms.Label(); + this.TextBox16 = new System.Windows.Forms.TextBox(); + this.btnCreaCatalogoAsync = new System.Windows.Forms.Button(); + this.Label20 = new System.Windows.Forms.Label(); + this.btnCreaCatalogo = new System.Windows.Forms.Button(); + this.Label24 = new System.Windows.Forms.Label(); + this.Label22 = new System.Windows.Forms.Label(); + this.Label23 = new System.Windows.Forms.Label(); + this.TextBox10 = new System.Windows.Forms.TextBox(); + this.Label29 = new System.Windows.Forms.Label(); + this.Label30 = new System.Windows.Forms.Label(); + this.PictureBox3 = new System.Windows.Forms.PictureBox(); + this.GroupBox6 = new System.Windows.Forms.GroupBox(); + this.Button4 = new System.Windows.Forms.Button(); + this.TabPage4 = new System.Windows.Forms.TabPage(); + this.Label13 = new System.Windows.Forms.Label(); + this.rdbNumFiles = new System.Windows.Forms.RadioButton(); + this.rdbNumProgressiva = new System.Windows.Forms.RadioButton(); + this.txtCifreContatore = new System.Windows.Forms.TextBox(); + this.Label34 = new System.Windows.Forms.Label(); + this.txtSuffissoCartelle = new System.Windows.Forms.TextBox(); + this.Label33 = new System.Windows.Forms.Label(); + this.Label31 = new System.Windows.Forms.Label(); + this.txtFilePerCartella = new System.Windows.Forms.TextBox(); + this.GroupBox8 = new System.Windows.Forms.GroupBox(); + this.chkCreaSottocartelle = new System.Windows.Forms.CheckBox(); + this.Label32 = new System.Windows.Forms.Label(); + this.chkAggiornaSottodirectory = new System.Windows.Forms.CheckBox(); + this.GroupBox3 = new System.Windows.Forms.GroupBox(); + this.Button3 = new System.Windows.Forms.Button(); + this.Button2 = new System.Windows.Forms.Button(); + this.Label1 = new System.Windows.Forms.Label(); + this.Label2 = new System.Windows.Forms.Label(); + this.txtSorgente = new System.Windows.Forms.TextBox(); + this.txtDestinazione = new System.Windows.Forms.TextBox(); + this.ProgressBar1 = new System.Windows.Forms.ProgressBar(); + this.CheckBox22 = new System.Windows.Forms.CheckBox(); + this.Label43 = new System.Windows.Forms.Label(); + this.TabControl1 = new System.Windows.Forms.TabControl(); + this.TabPage5 = new System.Windows.Forms.TabPage(); + this.GroupBox11 = new System.Windows.Forms.GroupBox(); + this.Panel3 = new System.Windows.Forms.Panel(); + this.rdbNuovoMetodo = new System.Windows.Forms.RadioButton(); + this.rdbVecchioMetodo = new System.Windows.Forms.RadioButton(); + this.Label8 = new System.Windows.Forms.Label(); + this.TextBox8 = new System.Windows.Forms.TextBox(); + this.Label7 = new System.Windows.Forms.Label(); + this.TextBox7 = new System.Windows.Forms.TextBox(); + this.GroupBox7 = new System.Windows.Forms.GroupBox(); + this.chkSovrascriviFile = new System.Windows.Forms.CheckBox(); + this.chkRotazioneAutomatica = new System.Windows.Forms.CheckBox(); + this.chkForzaJpg = new System.Windows.Forms.CheckBox(); + this.TabPage3 = new System.Windows.Forms.TabPage(); + this.CheckBox2 = new System.Windows.Forms.CheckBox(); + this.GroupBox10 = new System.Windows.Forms.GroupBox(); + this.Label42 = new System.Windows.Forms.Label(); + this.Label41 = new System.Windows.Forms.Label(); + this.TextBox31 = new System.Windows.Forms.TextBox(); + this.TextBox30 = new System.Windows.Forms.TextBox(); + this.GroupBox9 = new System.Windows.Forms.GroupBox(); + this.CheckBox17 = new System.Windows.Forms.CheckBox(); + this.CheckBox16 = new System.Windows.Forms.CheckBox(); + this.GroupBox5 = new System.Windows.Forms.GroupBox(); + this.TextBox34 = new System.Windows.Forms.TextBox(); + this.Button8 = new System.Windows.Forms.Button(); + this.Label36 = new System.Windows.Forms.Label(); + this.TextBox25 = new System.Windows.Forms.TextBox(); + this.Label35 = new System.Windows.Forms.Label(); + this.ComboBox3 = new System.Windows.Forms.ComboBox(); + this.TextBox11 = new System.Windows.Forms.TextBox(); + this.Label12 = new System.Windows.Forms.Label(); + this.Label11 = new System.Windows.Forms.Label(); + this.CheckBox3 = new System.Windows.Forms.CheckBox(); + this.GroupBox4 = new System.Windows.Forms.GroupBox(); + this.ComboBox1 = new System.Windows.Forms.ComboBox(); + this.ComboBox2 = new System.Windows.Forms.ComboBox(); + this.Label14 = new System.Windows.Forms.Label(); + this.TextBox12 = new System.Windows.Forms.TextBox(); + this.Label15 = new System.Windows.Forms.Label(); + this.Button6 = new System.Windows.Forms.Button(); + this.TabPage1.SuspendLayout(); + this.Panel1.SuspendLayout(); + this.GroupBox1.SuspendLayout(); + this.Panel2.SuspendLayout(); + this.TabPage2.SuspendLayout(); + this.GroupBox2.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox2)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox3)).BeginInit(); + this.GroupBox6.SuspendLayout(); + this.TabPage4.SuspendLayout(); + this.GroupBox8.SuspendLayout(); + this.GroupBox3.SuspendLayout(); + this.TabControl1.SuspendLayout(); + this.TabPage5.SuspendLayout(); + this.GroupBox11.SuspendLayout(); + this.Panel3.SuspendLayout(); + this.GroupBox7.SuspendLayout(); + this.TabPage3.SuspendLayout(); + this.GroupBox10.SuspendLayout(); + this.GroupBox9.SuspendLayout(); + this.GroupBox5.SuspendLayout(); + this.GroupBox4.SuspendLayout(); + this.SuspendLayout(); + // + // TabPage1 + // + this.TabPage1.Controls.Add(this.Panel1); + this.TabPage1.Controls.Add(this.GroupBox1); + this.TabPage1.Location = new System.Drawing.Point(4, 22); + this.TabPage1.Name = "TabPage1"; + this.TabPage1.Padding = new System.Windows.Forms.Padding(3); + this.TabPage1.Size = new System.Drawing.Size(513, 351); + this.TabPage1.TabIndex = 0; + this.TabPage1.Text = "Miniature"; + this.TabPage1.UseVisualStyleBackColor = true; + // + // Panel1 + // + this.Panel1.Controls.Add(this.CheckBox18); + this.Panel1.Controls.Add(this.CheckBox4); + this.Panel1.Controls.Add(this.CheckBox12); + this.Panel1.Location = new System.Drawing.Point(52, 236); + this.Panel1.Name = "Panel1"; + this.Panel1.Size = new System.Drawing.Size(304, 73); + this.Panel1.TabIndex = 26; + this.Panel1.Visible = false; + // + // CheckBox18 + // + this.CheckBox18.AutoSize = true; + this.CheckBox18.Location = new System.Drawing.Point(140, 3); + this.CheckBox18.Name = "CheckBox18"; + this.CheckBox18.Size = new System.Drawing.Size(84, 17); + this.CheckBox18.TabIndex = 36; + this.CheckBox18.Text = "Numero foto"; + this.CheckBox18.UseVisualStyleBackColor = true; + // + // CheckBox4 + // + this.CheckBox4.ForeColor = System.Drawing.Color.Black; + this.CheckBox4.Location = new System.Drawing.Point(10, 3); + this.CheckBox4.Name = "CheckBox4"; + this.CheckBox4.Size = new System.Drawing.Size(104, 17); + this.CheckBox4.TabIndex = 34; + this.CheckBox4.Text = "Aggiungi scritta"; + // + // CheckBox12 + // + this.CheckBox12.ForeColor = System.Drawing.Color.Black; + this.CheckBox12.Location = new System.Drawing.Point(10, 19); + this.CheckBox12.Name = "CheckBox12"; + this.CheckBox12.Size = new System.Drawing.Size(104, 21); + this.CheckBox12.TabIndex = 35; + this.CheckBox12.Text = "Aggiungi orario"; + // + // GroupBox1 + // + this.GroupBox1.Controls.Add(this.Label46); + this.GroupBox1.Controls.Add(this.TextBox33); + this.GroupBox1.Controls.Add(this.Panel2); + this.GroupBox1.Controls.Add(this.Label5); + this.GroupBox1.Controls.Add(this.TextBox5); + this.GroupBox1.Controls.Add(this.Label6); + this.GroupBox1.Controls.Add(this.TextBox6); + this.GroupBox1.Controls.Add(this.Label3); + this.GroupBox1.Controls.Add(this.TextBox3); + this.GroupBox1.Controls.Add(this.CheckBox1); + this.GroupBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox1.Location = new System.Drawing.Point(6, 5); + this.GroupBox1.Name = "GroupBox1"; + this.GroupBox1.Size = new System.Drawing.Size(350, 210); + this.GroupBox1.TabIndex = 25; + this.GroupBox1.TabStop = false; + this.GroupBox1.Text = "Miniature"; + // + // Label46 + // + this.Label46.AutoSize = true; + this.Label46.Location = new System.Drawing.Point(198, 43); + this.Label46.Name = "Label46"; + this.Label46.Size = new System.Drawing.Size(40, 13); + this.Label46.TabIndex = 21; + this.Label46.Text = "Qualità"; + // + // TextBox33 + // + this.TextBox33.Location = new System.Drawing.Point(244, 40); + this.TextBox33.Name = "TextBox33"; + this.TextBox33.Size = new System.Drawing.Size(100, 20); + this.TextBox33.TabIndex = 20; + // + // Panel2 + // + this.Panel2.Controls.Add(this.RadioButton3); + this.Panel2.Controls.Add(this.RadioButton7); + this.Panel2.Controls.Add(this.RadioButton4); + this.Panel2.Controls.Add(this.RadioButton6); + this.Panel2.Controls.Add(this.RadioButton5); + this.Panel2.Location = new System.Drawing.Point(56, 114); + this.Panel2.Name = "Panel2"; + this.Panel2.Size = new System.Drawing.Size(235, 90); + this.Panel2.TabIndex = 19; + // + // RadioButton3 + // + this.RadioButton3.AutoSize = true; + this.RadioButton3.Location = new System.Drawing.Point(15, 16); + this.RadioButton3.Name = "RadioButton3"; + this.RadioButton3.Size = new System.Drawing.Size(99, 17); + this.RadioButton3.TabIndex = 14; + this.RadioButton3.TabStop = true; + this.RadioButton3.Text = "Aggiungi Scritta"; + this.RadioButton3.UseVisualStyleBackColor = true; + // + // RadioButton7 + // + this.RadioButton7.AutoSize = true; + this.RadioButton7.Location = new System.Drawing.Point(129, 40); + this.RadioButton7.Name = "RadioButton7"; + this.RadioButton7.Size = new System.Drawing.Size(95, 17); + this.RadioButton7.TabIndex = 18; + this.RadioButton7.TabStop = true; + this.RadioButton7.Text = "numero+tempo"; + this.RadioButton7.UseVisualStyleBackColor = true; + // + // RadioButton4 + // + this.RadioButton4.AutoSize = true; + this.RadioButton4.Location = new System.Drawing.Point(15, 40); + this.RadioButton4.Name = "RadioButton4"; + this.RadioButton4.Size = new System.Drawing.Size(95, 17); + this.RadioButton4.TabIndex = 15; + this.RadioButton4.TabStop = true; + this.RadioButton4.Text = "Aggiungi orario"; + this.RadioButton4.UseVisualStyleBackColor = true; + // + // RadioButton6 + // + this.RadioButton6.AutoSize = true; + this.RadioButton6.Location = new System.Drawing.Point(129, 16); + this.RadioButton6.Name = "RadioButton6"; + this.RadioButton6.Size = new System.Drawing.Size(83, 17); + this.RadioButton6.TabIndex = 17; + this.RadioButton6.TabStop = true; + this.RadioButton6.Text = "Numero foto"; + this.RadioButton6.UseVisualStyleBackColor = true; + // + // RadioButton5 + // + this.RadioButton5.AutoSize = true; + this.RadioButton5.Location = new System.Drawing.Point(15, 65); + this.RadioButton5.Name = "RadioButton5"; + this.RadioButton5.Size = new System.Drawing.Size(84, 17); + this.RadioButton5.TabIndex = 16; + this.RadioButton5.TabStop = true; + this.RadioButton5.Text = "Tempo Gara"; + this.RadioButton5.UseVisualStyleBackColor = true; + // + // Label5 + // + this.Label5.AutoSize = true; + this.Label5.ForeColor = System.Drawing.Color.Black; + this.Label5.Location = new System.Drawing.Point(24, 88); + this.Label5.Name = "Label5"; + this.Label5.Size = new System.Drawing.Size(41, 13); + this.Label5.TabIndex = 12; + this.Label5.Text = "Altezza"; + // + // TextBox5 + // + this.TextBox5.Location = new System.Drawing.Point(72, 64); + this.TextBox5.Name = "TextBox5"; + this.TextBox5.Size = new System.Drawing.Size(88, 20); + this.TextBox5.TabIndex = 10; + this.TextBox5.Text = "TextBox5"; + // + // Label6 + // + this.Label6.AutoSize = true; + this.Label6.ForeColor = System.Drawing.Color.Black; + this.Label6.Location = new System.Drawing.Point(8, 64); + this.Label6.Name = "Label6"; + this.Label6.Size = new System.Drawing.Size(56, 13); + this.Label6.TabIndex = 13; + this.Label6.Text = "Larghezza"; + // + // TextBox6 + // + this.TextBox6.Location = new System.Drawing.Point(72, 88); + this.TextBox6.Name = "TextBox6"; + this.TextBox6.Size = new System.Drawing.Size(88, 20); + this.TextBox6.TabIndex = 11; + this.TextBox6.Text = "TextBox6"; + // + // Label3 + // + this.Label3.AutoSize = true; + this.Label3.ForeColor = System.Drawing.Color.Black; + this.Label3.Location = new System.Drawing.Point(24, 40); + this.Label3.Name = "Label3"; + this.Label3.Size = new System.Drawing.Size(44, 13); + this.Label3.TabIndex = 7; + this.Label3.Text = "Suffisso"; + // + // TextBox3 + // + this.TextBox3.Location = new System.Drawing.Point(72, 40); + this.TextBox3.Name = "TextBox3"; + this.TextBox3.Size = new System.Drawing.Size(88, 20); + this.TextBox3.TabIndex = 6; + this.TextBox3.Text = "TextBox3"; + // + // CheckBox1 + // + this.CheckBox1.ForeColor = System.Drawing.Color.Black; + this.CheckBox1.Location = new System.Drawing.Point(72, 16); + this.CheckBox1.Name = "CheckBox1"; + this.CheckBox1.Size = new System.Drawing.Size(104, 24); + this.CheckBox1.TabIndex = 5; + this.CheckBox1.Text = "Crea miniature"; + // + // Label37 + // + this.Label37.ForeColor = System.Drawing.Color.Black; + this.Label37.Location = new System.Drawing.Point(168, 48); + this.Label37.Name = "Label37"; + this.Label37.Size = new System.Drawing.Size(48, 16); + this.Label37.TabIndex = 19; + this.Label37.Text = "Suffisso"; + this.Label37.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // Label38 + // + this.Label38.AutoSize = true; + this.Label38.ForeColor = System.Drawing.Color.Black; + this.Label38.Location = new System.Drawing.Point(24, 24); + this.Label38.Name = "Label38"; + this.Label38.Size = new System.Drawing.Size(41, 13); + this.Label38.TabIndex = 16; + this.Label38.Text = "Altezza"; + // + // Label45 + // + this.Label45.AutoSize = true; + this.Label45.Location = new System.Drawing.Point(11, 86); + this.Label45.Name = "Label45"; + this.Label45.Size = new System.Drawing.Size(40, 13); + this.Label45.TabIndex = 22; + this.Label45.Text = "Qualità"; + // + // TextBox32 + // + this.TextBox32.Location = new System.Drawing.Point(72, 80); + this.TextBox32.Name = "TextBox32"; + this.TextBox32.Size = new System.Drawing.Size(72, 20); + this.TextBox32.TabIndex = 21; + this.TextBox32.Text = "100"; + // + // TextBox26 + // + this.TextBox26.Location = new System.Drawing.Point(224, 48); + this.TextBox26.Name = "TextBox26"; + this.TextBox26.Size = new System.Drawing.Size(56, 20); + this.TextBox26.TabIndex = 20; + this.TextBox26.Text = "TextBox26"; + // + // TextBox27 + // + this.TextBox27.Location = new System.Drawing.Point(72, 24); + this.TextBox27.Name = "TextBox27"; + this.TextBox27.Size = new System.Drawing.Size(72, 20); + this.TextBox27.TabIndex = 14; + this.TextBox27.Text = "TextBox27"; + // + // Label39 + // + this.Label39.AutoSize = true; + this.Label39.ForeColor = System.Drawing.Color.Black; + this.Label39.Location = new System.Drawing.Point(8, 48); + this.Label39.Name = "Label39"; + this.Label39.Size = new System.Drawing.Size(56, 13); + this.Label39.TabIndex = 17; + this.Label39.Text = "Larghezza"; + // + // CheckBox15 + // + this.CheckBox15.Checked = true; + this.CheckBox15.CheckState = System.Windows.Forms.CheckState.Checked; + this.CheckBox15.ForeColor = System.Drawing.Color.Black; + this.CheckBox15.Location = new System.Drawing.Point(168, 16); + this.CheckBox15.Name = "CheckBox15"; + this.CheckBox15.Size = new System.Drawing.Size(120, 32); + this.CheckBox15.TabIndex = 18; + this.CheckBox15.Text = "Mantieni dimensioni originali"; + // + // Label40 + // + this.Label40.AutoSize = true; + this.Label40.Location = new System.Drawing.Point(8, 52); + this.Label40.Name = "Label40"; + this.Label40.Size = new System.Drawing.Size(48, 13); + this.Label40.TabIndex = 40; + this.Label40.Text = "Verticale"; + // + // TextBox29 + // + this.TextBox29.Location = new System.Drawing.Point(72, 49); + this.TextBox29.Multiline = true; + this.TextBox29.Name = "TextBox29"; + this.TextBox29.Size = new System.Drawing.Size(408, 44); + this.TextBox29.TabIndex = 39; + // + // TextBox18 + // + this.TextBox18.Location = new System.Drawing.Point(232, 156); + this.TextBox18.Name = "TextBox18"; + this.TextBox18.Size = new System.Drawing.Size(100, 20); + this.TextBox18.TabIndex = 38; + // + // Label26 + // + this.Label26.AutoSize = true; + this.Label26.ForeColor = System.Drawing.Color.Black; + this.Label26.Location = new System.Drawing.Point(344, 156); + this.Label26.Name = "Label26"; + this.Label26.Size = new System.Drawing.Size(48, 13); + this.Label26.TabIndex = 37; + this.Label26.Text = "partenza"; + // + // DateTimePicker1 + // + this.DateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Time; + this.DateTimePicker1.Location = new System.Drawing.Point(392, 156); + this.DateTimePicker1.Name = "DateTimePicker1"; + this.DateTimePicker1.Size = new System.Drawing.Size(88, 20); + this.DateTimePicker1.TabIndex = 36; + // + // CheckBox8 + // + this.CheckBox8.ForeColor = System.Drawing.Color.Black; + this.CheckBox8.Location = new System.Drawing.Point(72, 156); + this.CheckBox8.Name = "CheckBox8"; + this.CheckBox8.Size = new System.Drawing.Size(56, 16); + this.CheckBox8.TabIndex = 35; + this.CheckBox8.Text = "Orario"; + // + // TextBox9 + // + this.TextBox9.Location = new System.Drawing.Point(120, 108); + this.TextBox9.Name = "TextBox9"; + this.TextBox9.Size = new System.Drawing.Size(56, 20); + this.TextBox9.TabIndex = 20; + this.TextBox9.Text = "TextBox9"; + // + // CheckBox7 + // + this.CheckBox7.ForeColor = System.Drawing.Color.Black; + this.CheckBox7.Location = new System.Drawing.Point(136, 156); + this.CheckBox7.Name = "CheckBox7"; + this.CheckBox7.Size = new System.Drawing.Size(88, 16); + this.CheckBox7.TabIndex = 34; + this.CheckBox7.Text = "Tempo gara"; + // + // Label4 + // + this.Label4.AutoSize = true; + this.Label4.ForeColor = System.Drawing.Color.Black; + this.Label4.Location = new System.Drawing.Point(8, 24); + this.Label4.Name = "Label4"; + this.Label4.Size = new System.Drawing.Size(59, 13); + this.Label4.TabIndex = 9; + this.Label4.Text = "Orizzontale"; + // + // TextBox4 + // + this.TextBox4.Location = new System.Drawing.Point(72, 24); + this.TextBox4.Name = "TextBox4"; + this.TextBox4.Size = new System.Drawing.Size(408, 20); + this.TextBox4.TabIndex = 8; + this.TextBox4.Text = "TextBox4"; + // + // Label9 + // + this.Label9.AutoSize = true; + this.Label9.ForeColor = System.Drawing.Color.Black; + this.Label9.Location = new System.Drawing.Point(8, 108); + this.Label9.Name = "Label9"; + this.Label9.Size = new System.Drawing.Size(110, 13); + this.Label9.TabIndex = 19; + this.Label9.Text = "Trasparenza (0-100%)"; + // + // TextBox28 + // + this.TextBox28.Location = new System.Drawing.Point(72, 48); + this.TextBox28.Name = "TextBox28"; + this.TextBox28.Size = new System.Drawing.Size(72, 20); + this.TextBox28.TabIndex = 15; + this.TextBox28.Text = "TextBox28"; + // + // TabPage2 + // + this.TabPage2.Controls.Add(this.GroupBox2); + this.TabPage2.Location = new System.Drawing.Point(4, 22); + this.TabPage2.Name = "TabPage2"; + this.TabPage2.Padding = new System.Windows.Forms.Padding(3); + this.TabPage2.Size = new System.Drawing.Size(513, 351); + this.TabPage2.TabIndex = 5; + this.TabPage2.Text = "Foto"; + this.TabPage2.UseVisualStyleBackColor = true; + // + // GroupBox2 + // + this.GroupBox2.Controls.Add(this.Label45); + this.GroupBox2.Controls.Add(this.TextBox32); + this.GroupBox2.Controls.Add(this.TextBox26); + this.GroupBox2.Controls.Add(this.Label37); + this.GroupBox2.Controls.Add(this.Label38); + this.GroupBox2.Controls.Add(this.TextBox27); + this.GroupBox2.Controls.Add(this.Label39); + this.GroupBox2.Controls.Add(this.TextBox28); + this.GroupBox2.Controls.Add(this.CheckBox15); + this.GroupBox2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox2.Location = new System.Drawing.Point(3, 6); + this.GroupBox2.Name = "GroupBox2"; + this.GroupBox2.Size = new System.Drawing.Size(304, 156); + this.GroupBox2.TabIndex = 36; + this.GroupBox2.TabStop = false; + this.GroupBox2.Text = "Foto grande"; + // + // Label27 + // + this.Label27.Location = new System.Drawing.Point(591, 378); + this.Label27.Name = "Label27"; + this.Label27.Size = new System.Drawing.Size(145, 20); + this.Label27.TabIndex = 78; + this.Label27.Text = "Versione 2.2 2021"; + this.Label27.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // Button7 + // + this.Button7.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Button7.Location = new System.Drawing.Point(539, 120); + this.Button7.Name = "Button7"; + this.Button7.Size = new System.Drawing.Size(197, 40); + this.Button7.TabIndex = 77; + this.Button7.Text = "stop creazione"; + // + // Button5 + // + this.Button5.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Button5.Location = new System.Drawing.Point(539, 43); + this.Button5.Name = "Button5"; + this.Button5.Size = new System.Drawing.Size(197, 32); + this.Button5.TabIndex = 76; + this.Button5.Text = "Salva impostazioni"; + // + // PictureBox2 + // + this.PictureBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.PictureBox2.Location = new System.Drawing.Point(144, 192); + this.PictureBox2.Name = "PictureBox2"; + this.PictureBox2.Size = new System.Drawing.Size(24, 24); + this.PictureBox2.TabIndex = 44; + this.PictureBox2.TabStop = false; + this.PictureBox2.Visible = false; + // + // PictureBox1 + // + this.PictureBox1.Cursor = System.Windows.Forms.Cursors.Cross; + this.PictureBox1.Location = new System.Drawing.Point(256, 56); + this.PictureBox1.Name = "PictureBox1"; + this.PictureBox1.Size = new System.Drawing.Size(224, 160); + this.PictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.PictureBox1.TabIndex = 43; + this.PictureBox1.TabStop = false; + // + // ComboBox5 + // + this.ComboBox5.Location = new System.Drawing.Point(144, 168); + this.ComboBox5.Name = "ComboBox5"; + this.ComboBox5.Size = new System.Drawing.Size(96, 21); + this.ComboBox5.TabIndex = 42; + this.ComboBox5.Text = "ComboBox5"; + // + // ComboBox4 + // + this.ComboBox4.Location = new System.Drawing.Point(144, 144); + this.ComboBox4.Name = "ComboBox4"; + this.ComboBox4.Size = new System.Drawing.Size(96, 21); + this.ComboBox4.TabIndex = 41; + this.ComboBox4.Text = "ComboBox4"; + // + // Label19 + // + this.Label19.AutoSize = true; + this.Label19.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Label19.Location = new System.Drawing.Point(544, 275); + this.Label19.Name = "Label19"; + this.Label19.Size = new System.Drawing.Size(80, 16); + this.Label19.TabIndex = 74; + this.Label19.Text = "foto totali: "; + // + // Label18 + // + this.Label18.AutoSize = true; + this.Label18.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Label18.Location = new System.Drawing.Point(648, 294); + this.Label18.Name = "Label18"; + this.Label18.Size = new System.Drawing.Size(19, 20); + this.Label18.TabIndex = 73; + this.Label18.Text = "0"; + // + // lblFotoTotaliNum + // + this.lblFotoTotaliNum.AutoSize = true; + this.lblFotoTotaliNum.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.lblFotoTotaliNum.Location = new System.Drawing.Point(648, 275); + this.lblFotoTotaliNum.Name = "lblFotoTotaliNum"; + this.lblFotoTotaliNum.Size = new System.Drawing.Size(19, 20); + this.lblFotoTotaliNum.TabIndex = 72; + this.lblFotoTotaliNum.Text = "0"; + // + // Label10 + // + this.Label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Label10.Location = new System.Drawing.Point(539, 163); + this.Label10.Name = "Label10"; + this.Label10.Size = new System.Drawing.Size(197, 72); + this.Label10.TabIndex = 71; + this.Label10.Text = "file"; + // + // TextBox19 + // + this.TextBox19.Location = new System.Drawing.Point(144, 96); + this.TextBox19.Name = "TextBox19"; + this.TextBox19.Size = new System.Drawing.Size(96, 20); + this.TextBox19.TabIndex = 40; + this.TextBox19.Text = "TextBox19"; + // + // Label28 + // + this.Label28.ForeColor = System.Drawing.Color.Black; + this.Label28.Location = new System.Drawing.Point(17, 97); + this.Label28.Name = "Label28"; + this.Label28.Size = new System.Drawing.Size(120, 16); + this.Label28.TabIndex = 39; + this.Label28.Text = "Trasparenza (0-100%)"; + this.Label28.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // CheckBox5 + // + this.CheckBox5.ForeColor = System.Drawing.Color.Black; + this.CheckBox5.Location = new System.Drawing.Point(0, 26); + this.CheckBox5.Name = "CheckBox5"; + this.CheckBox5.Size = new System.Drawing.Size(72, 20); + this.CheckBox5.TabIndex = 38; + this.CheckBox5.Text = "Aggiungi"; + // + // TextBox15 + // + this.TextBox15.Location = new System.Drawing.Point(144, 72); + this.TextBox15.Name = "TextBox15"; + this.TextBox15.Size = new System.Drawing.Size(96, 20); + this.TextBox15.TabIndex = 19; + this.TextBox15.Text = "TextBox15"; + // + // TextBox14 + // + this.TextBox14.Location = new System.Drawing.Point(144, 48); + this.TextBox14.Name = "TextBox14"; + this.TextBox14.Size = new System.Drawing.Size(96, 20); + this.TextBox14.TabIndex = 18; + this.TextBox14.Text = "TextBox14"; + // + // Label25 + // + this.Label25.AutoSize = true; + this.Label25.ForeColor = System.Drawing.Color.Black; + this.Label25.Location = new System.Drawing.Point(17, 168); + this.Label25.Name = "Label25"; + this.Label25.Size = new System.Drawing.Size(95, 13); + this.Label25.TabIndex = 36; + this.Label25.Text = "Posizione verticale"; + this.Label25.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // TextBox16 + // + this.TextBox16.Location = new System.Drawing.Point(144, 120); + this.TextBox16.Name = "TextBox16"; + this.TextBox16.Size = new System.Drawing.Size(96, 20); + this.TextBox16.TabIndex = 35; + this.TextBox16.Text = "TextBox16"; + // + // btnCreaCatalogoAsync + // + this.btnCreaCatalogoAsync.Location = new System.Drawing.Point(647, 78); + this.btnCreaCatalogoAsync.Name = "btnCreaCatalogoAsync"; + this.btnCreaCatalogoAsync.Size = new System.Drawing.Size(89, 38); + this.btnCreaCatalogoAsync.TabIndex = 83; + this.btnCreaCatalogoAsync.Text = "Crea 2"; + this.btnCreaCatalogoAsync.UseVisualStyleBackColor = true; + // + // Label20 + // + this.Label20.AutoSize = true; + this.Label20.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Label20.Location = new System.Drawing.Point(544, 294); + this.Label20.Name = "Label20"; + this.Label20.Size = new System.Drawing.Size(104, 16); + this.Label20.TabIndex = 75; + this.Label20.Text = "foto generate:"; + // + // btnCreaCatalogo + // + this.btnCreaCatalogo.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.btnCreaCatalogo.Location = new System.Drawing.Point(539, 77); + this.btnCreaCatalogo.Name = "btnCreaCatalogo"; + this.btnCreaCatalogo.Size = new System.Drawing.Size(107, 39); + this.btnCreaCatalogo.TabIndex = 69; + this.btnCreaCatalogo.Text = "crea catalogo"; + // + // Label24 + // + this.Label24.AutoSize = true; + this.Label24.ForeColor = System.Drawing.Color.Black; + this.Label24.Location = new System.Drawing.Point(19, 123); + this.Label24.Name = "Label24"; + this.Label24.Size = new System.Drawing.Size(88, 13); + this.Label24.TabIndex = 34; + this.Label24.Text = "Margine (pixel/%)"; + this.Label24.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Label22 + // + this.Label22.AutoSize = true; + this.Label22.ForeColor = System.Drawing.Color.Black; + this.Label22.Location = new System.Drawing.Point(19, 51); + this.Label22.Name = "Label22"; + this.Label22.Size = new System.Drawing.Size(41, 13); + this.Label22.TabIndex = 20; + this.Label22.Text = "Altezza"; + this.Label22.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Label23 + // + this.Label23.AutoSize = true; + this.Label23.ForeColor = System.Drawing.Color.Black; + this.Label23.Location = new System.Drawing.Point(19, 75); + this.Label23.Name = "Label23"; + this.Label23.Size = new System.Drawing.Size(56, 13); + this.Label23.TabIndex = 21; + this.Label23.Text = "Larghezza"; + this.Label23.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // TextBox10 + // + this.TextBox10.Location = new System.Drawing.Point(144, 24); + this.TextBox10.Name = "TextBox10"; + this.TextBox10.Size = new System.Drawing.Size(312, 20); + this.TextBox10.TabIndex = 6; + this.TextBox10.Text = "TextBox10"; + // + // Label29 + // + this.Label29.AutoSize = true; + this.Label29.ForeColor = System.Drawing.Color.Black; + this.Label29.Location = new System.Drawing.Point(17, 147); + this.Label29.Name = "Label29"; + this.Label29.Size = new System.Drawing.Size(105, 13); + this.Label29.TabIndex = 36; + this.Label29.Text = "Posizione orizzontale"; + this.Label29.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Label30 + // + this.Label30.AutoSize = true; + this.Label30.ForeColor = System.Drawing.Color.Black; + this.Label30.Location = new System.Drawing.Point(19, 203); + this.Label30.Name = "Label30"; + this.Label30.Size = new System.Drawing.Size(93, 13); + this.Label30.TabIndex = 36; + this.Label30.Text = "Colore trasparente"; + this.Label30.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + this.Label30.Visible = false; + // + // PictureBox3 + // + this.PictureBox3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.PictureBox3.Location = new System.Drawing.Point(216, 192); + this.PictureBox3.Name = "PictureBox3"; + this.PictureBox3.Size = new System.Drawing.Size(24, 24); + this.PictureBox3.TabIndex = 44; + this.PictureBox3.TabStop = false; + this.PictureBox3.Visible = false; + // + // GroupBox6 + // + this.GroupBox6.Controls.Add(this.PictureBox2); + this.GroupBox6.Controls.Add(this.PictureBox1); + this.GroupBox6.Controls.Add(this.ComboBox5); + this.GroupBox6.Controls.Add(this.ComboBox4); + this.GroupBox6.Controls.Add(this.TextBox19); + this.GroupBox6.Controls.Add(this.Label28); + this.GroupBox6.Controls.Add(this.CheckBox5); + this.GroupBox6.Controls.Add(this.TextBox15); + this.GroupBox6.Controls.Add(this.TextBox14); + this.GroupBox6.Controls.Add(this.Label25); + this.GroupBox6.Controls.Add(this.TextBox16); + this.GroupBox6.Controls.Add(this.Label24); + this.GroupBox6.Controls.Add(this.Label22); + this.GroupBox6.Controls.Add(this.Label23); + this.GroupBox6.Controls.Add(this.Button4); + this.GroupBox6.Controls.Add(this.TextBox10); + this.GroupBox6.Controls.Add(this.Label29); + this.GroupBox6.Controls.Add(this.Label30); + this.GroupBox6.Controls.Add(this.PictureBox3); + this.GroupBox6.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox6.Location = new System.Drawing.Point(6, 6); + this.GroupBox6.Name = "GroupBox6"; + this.GroupBox6.Size = new System.Drawing.Size(496, 224); + this.GroupBox6.TabIndex = 42; + this.GroupBox6.TabStop = false; + this.GroupBox6.Text = "Logo"; + // + // Button4 + // + this.Button4.Location = new System.Drawing.Point(464, 24); + this.Button4.Name = "Button4"; + this.Button4.Size = new System.Drawing.Size(24, 20); + this.Button4.TabIndex = 8; + this.Button4.Text = "..."; + // + // TabPage4 + // + this.TabPage4.Controls.Add(this.GroupBox6); + this.TabPage4.Location = new System.Drawing.Point(4, 22); + this.TabPage4.Name = "TabPage4"; + this.TabPage4.Padding = new System.Windows.Forms.Padding(3); + this.TabPage4.Size = new System.Drawing.Size(513, 351); + this.TabPage4.TabIndex = 3; + this.TabPage4.Text = "Logo"; + this.TabPage4.UseVisualStyleBackColor = true; + // + // Label13 + // + this.Label13.AutoSize = true; + this.Label13.ForeColor = System.Drawing.Color.Black; + this.Label13.Location = new System.Drawing.Point(16, 132); + this.Label13.Name = "Label13"; + this.Label13.Size = new System.Drawing.Size(52, 13); + this.Label13.TabIndex = 29; + this.Label13.Text = "Posizione"; + // + // rdbNumFiles + // + this.rdbNumFiles.ForeColor = System.Drawing.Color.Black; + this.rdbNumFiles.Location = new System.Drawing.Point(32, 128); + this.rdbNumFiles.Name = "rdbNumFiles"; + this.rdbNumFiles.Size = new System.Drawing.Size(136, 16); + this.rdbNumFiles.TabIndex = 38; + this.rdbNumFiles.Text = "Numerazione files"; + // + // rdbNumProgressiva + // + this.rdbNumProgressiva.Checked = true; + this.rdbNumProgressiva.ForeColor = System.Drawing.Color.Black; + this.rdbNumProgressiva.Location = new System.Drawing.Point(32, 112); + this.rdbNumProgressiva.Name = "rdbNumProgressiva"; + this.rdbNumProgressiva.Size = new System.Drawing.Size(152, 16); + this.rdbNumProgressiva.TabIndex = 37; + this.rdbNumProgressiva.TabStop = true; + this.rdbNumProgressiva.Text = "Numerazione progressiva"; + // + // txtCifreContatore + // + this.txtCifreContatore.Location = new System.Drawing.Point(128, 88); + this.txtCifreContatore.Name = "txtCifreContatore"; + this.txtCifreContatore.Size = new System.Drawing.Size(56, 20); + this.txtCifreContatore.TabIndex = 34; + this.txtCifreContatore.Text = "4"; + // + // Label34 + // + this.Label34.ForeColor = System.Drawing.Color.Black; + this.Label34.Location = new System.Drawing.Point(8, 88); + this.Label34.Name = "Label34"; + this.Label34.Size = new System.Drawing.Size(112, 16); + this.Label34.TabIndex = 33; + this.Label34.Text = "Num. cifre contatore"; + this.Label34.TextAlign = System.Drawing.ContentAlignment.MiddleRight; + // + // txtSuffissoCartelle + // + this.txtSuffissoCartelle.Location = new System.Drawing.Point(56, 64); + this.txtSuffissoCartelle.Name = "txtSuffissoCartelle"; + this.txtSuffissoCartelle.Size = new System.Drawing.Size(128, 20); + this.txtSuffissoCartelle.TabIndex = 32; + this.txtSuffissoCartelle.Text = "TextBox20"; + // + // Label33 + // + this.Label33.ForeColor = System.Drawing.Color.Black; + this.Label33.Location = new System.Drawing.Point(6, 67); + this.Label33.Name = "Label33"; + this.Label33.Size = new System.Drawing.Size(48, 16); + this.Label33.TabIndex = 31; + this.Label33.Text = "Suffisso"; + // + // Label31 + // + this.Label31.ForeColor = System.Drawing.Color.Black; + this.Label31.Location = new System.Drawing.Point(24, 40); + this.Label31.Name = "Label31"; + this.Label31.Size = new System.Drawing.Size(32, 16); + this.Label31.TabIndex = 30; + this.Label31.Text = "ogni"; + // + // txtFilePerCartella + // + this.txtFilePerCartella.Location = new System.Drawing.Point(56, 40); + this.txtFilePerCartella.Name = "txtFilePerCartella"; + this.txtFilePerCartella.Size = new System.Drawing.Size(64, 20); + this.txtFilePerCartella.TabIndex = 27; + this.txtFilePerCartella.Text = "99"; + // + // GroupBox8 + // + this.GroupBox8.Controls.Add(this.rdbNumFiles); + this.GroupBox8.Controls.Add(this.rdbNumProgressiva); + this.GroupBox8.Controls.Add(this.txtCifreContatore); + this.GroupBox8.Controls.Add(this.Label34); + this.GroupBox8.Controls.Add(this.txtSuffissoCartelle); + this.GroupBox8.Controls.Add(this.Label33); + this.GroupBox8.Controls.Add(this.Label31); + this.GroupBox8.Controls.Add(this.chkCreaSottocartelle); + this.GroupBox8.Controls.Add(this.txtFilePerCartella); + this.GroupBox8.Controls.Add(this.Label32); + this.GroupBox8.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox8.Location = new System.Drawing.Point(204, 113); + this.GroupBox8.Name = "GroupBox8"; + this.GroupBox8.Size = new System.Drawing.Size(192, 152); + this.GroupBox8.TabIndex = 47; + this.GroupBox8.TabStop = false; + this.GroupBox8.Text = "Sottocartelle"; + // + // chkCreaSottocartelle + // + this.chkCreaSottocartelle.ForeColor = System.Drawing.Color.Black; + this.chkCreaSottocartelle.Location = new System.Drawing.Point(56, 16); + this.chkCreaSottocartelle.Name = "chkCreaSottocartelle"; + this.chkCreaSottocartelle.Size = new System.Drawing.Size(112, 16); + this.chkCreaSottocartelle.TabIndex = 29; + this.chkCreaSottocartelle.Text = "crea sottocartelle"; + // + // Label32 + // + this.Label32.ForeColor = System.Drawing.Color.Black; + this.Label32.Location = new System.Drawing.Point(128, 40); + this.Label32.Name = "Label32"; + this.Label32.Size = new System.Drawing.Size(24, 16); + this.Label32.TabIndex = 28; + this.Label32.Text = "file"; + // + // chkAggiornaSottodirectory + // + this.chkAggiornaSottodirectory.ForeColor = System.Drawing.Color.Black; + this.chkAggiornaSottodirectory.Location = new System.Drawing.Point(80, 64); + this.chkAggiornaSottodirectory.Name = "chkAggiornaSottodirectory"; + this.chkAggiornaSottodirectory.Size = new System.Drawing.Size(152, 24); + this.chkAggiornaSottodirectory.TabIndex = 25; + this.chkAggiornaSottodirectory.Text = "aggiorna le sottodirectory"; + // + // GroupBox3 + // + this.GroupBox3.Controls.Add(this.chkAggiornaSottodirectory); + this.GroupBox3.Controls.Add(this.Button3); + this.GroupBox3.Controls.Add(this.Button2); + this.GroupBox3.Controls.Add(this.Label1); + this.GroupBox3.Controls.Add(this.Label2); + this.GroupBox3.Controls.Add(this.txtSorgente); + this.GroupBox3.Controls.Add(this.txtDestinazione); + this.GroupBox3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox3.Location = new System.Drawing.Point(6, 6); + this.GroupBox3.Name = "GroupBox3"; + this.GroupBox3.Size = new System.Drawing.Size(496, 101); + this.GroupBox3.TabIndex = 35; + this.GroupBox3.TabStop = false; + this.GroupBox3.Text = "Directory"; + // + // Button3 + // + this.Button3.Location = new System.Drawing.Point(462, 40); + this.Button3.Name = "Button3"; + this.Button3.Size = new System.Drawing.Size(24, 20); + this.Button3.TabIndex = 6; + this.Button3.Text = "..."; + // + // Button2 + // + this.Button2.Location = new System.Drawing.Point(462, 16); + this.Button2.Name = "Button2"; + this.Button2.Size = new System.Drawing.Size(24, 20); + this.Button2.TabIndex = 5; + this.Button2.Text = "..."; + // + // Label1 + // + this.Label1.AutoSize = true; + this.Label1.ForeColor = System.Drawing.Color.Black; + this.Label1.Location = new System.Drawing.Point(6, 19); + this.Label1.Name = "Label1"; + this.Label1.Size = new System.Drawing.Size(50, 13); + this.Label1.TabIndex = 3; + this.Label1.Text = "Sorgente"; + // + // Label2 + // + this.Label2.AutoSize = true; + this.Label2.ForeColor = System.Drawing.Color.Black; + this.Label2.Location = new System.Drawing.Point(6, 43); + this.Label2.Name = "Label2"; + this.Label2.Size = new System.Drawing.Size(68, 13); + this.Label2.TabIndex = 4; + this.Label2.Text = "Destinazione"; + // + // txtSorgente + // + this.txtSorgente.Location = new System.Drawing.Point(80, 16); + this.txtSorgente.Name = "txtSorgente"; + this.txtSorgente.Size = new System.Drawing.Size(376, 20); + this.txtSorgente.TabIndex = 0; + this.txtSorgente.Text = "TextBox1"; + // + // txtDestinazione + // + this.txtDestinazione.Location = new System.Drawing.Point(80, 40); + this.txtDestinazione.Name = "txtDestinazione"; + this.txtDestinazione.Size = new System.Drawing.Size(376, 20); + this.txtDestinazione.TabIndex = 1; + this.txtDestinazione.Text = "TextBox2"; + // + // ProgressBar1 + // + this.ProgressBar1.Location = new System.Drawing.Point(539, 243); + this.ProgressBar1.Name = "ProgressBar1"; + this.ProgressBar1.Size = new System.Drawing.Size(197, 23); + this.ProgressBar1.TabIndex = 82; + // + // CheckBox22 + // + this.CheckBox22.AutoSize = true; + this.CheckBox22.Location = new System.Drawing.Point(544, 358); + this.CheckBox22.Name = "CheckBox22"; + this.CheckBox22.Size = new System.Drawing.Size(104, 17); + this.CheckBox22.TabIndex = 81; + this.CheckBox22.Text = "Arresta il sistema"; + this.CheckBox22.UseVisualStyleBackColor = true; + // + // Label43 + // + this.Label43.AutoSize = true; + this.Label43.Location = new System.Drawing.Point(541, 342); + this.Label43.Name = "Label43"; + this.Label43.Size = new System.Drawing.Size(25, 13); + this.Label43.TabIndex = 80; + this.Label43.Text = "000"; + this.Label43.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // TabControl1 + // + this.TabControl1.Controls.Add(this.TabPage5); + this.TabControl1.Controls.Add(this.TabPage3); + this.TabControl1.Controls.Add(this.TabPage2); + this.TabControl1.Controls.Add(this.TabPage1); + this.TabControl1.Controls.Add(this.TabPage4); + this.TabControl1.Location = new System.Drawing.Point(12, 12); + this.TabControl1.Name = "TabControl1"; + this.TabControl1.SelectedIndex = 0; + this.TabControl1.Size = new System.Drawing.Size(526, 377); + this.TabControl1.TabIndex = 79; + // + // TabPage5 + // + this.TabPage5.Controls.Add(this.GroupBox11); + this.TabPage5.Controls.Add(this.GroupBox3); + this.TabPage5.Controls.Add(this.GroupBox8); + this.TabPage5.Controls.Add(this.GroupBox7); + this.TabPage5.Location = new System.Drawing.Point(4, 22); + this.TabPage5.Name = "TabPage5"; + this.TabPage5.Padding = new System.Windows.Forms.Padding(3); + this.TabPage5.Size = new System.Drawing.Size(518, 351); + this.TabPage5.TabIndex = 4; + this.TabPage5.Text = "Generale"; + this.TabPage5.UseVisualStyleBackColor = true; + // + // GroupBox11 + // + this.GroupBox11.Controls.Add(this.Panel3); + this.GroupBox11.Controls.Add(this.Label8); + this.GroupBox11.Controls.Add(this.TextBox8); + this.GroupBox11.Controls.Add(this.Label7); + this.GroupBox11.Controls.Add(this.TextBox7); + this.GroupBox11.Location = new System.Drawing.Point(7, 209); + this.GroupBox11.Name = "GroupBox11"; + this.GroupBox11.Size = new System.Drawing.Size(191, 132); + this.GroupBox11.TabIndex = 48; + this.GroupBox11.TabStop = false; + this.GroupBox11.Text = "Avanzate (ATTENZIONE)"; + // + // Panel3 + // + this.Panel3.Controls.Add(this.rdbNuovoMetodo); + this.Panel3.Controls.Add(this.rdbVecchioMetodo); + this.Panel3.Location = new System.Drawing.Point(7, 73); + this.Panel3.Name = "Panel3"; + this.Panel3.Size = new System.Drawing.Size(178, 53); + this.Panel3.TabIndex = 4; + // + // rdbNuovoMetodo + // + this.rdbNuovoMetodo.AutoSize = true; + this.rdbNuovoMetodo.Checked = true; + this.rdbNuovoMetodo.Location = new System.Drawing.Point(8, 28); + this.rdbNuovoMetodo.Name = "rdbNuovoMetodo"; + this.rdbNuovoMetodo.Size = new System.Drawing.Size(95, 17); + this.rdbNuovoMetodo.TabIndex = 1; + this.rdbNuovoMetodo.TabStop = true; + this.rdbNuovoMetodo.Text = "Nuovo metodo"; + this.rdbNuovoMetodo.UseVisualStyleBackColor = true; + // + // rdbVecchioMetodo + // + this.rdbVecchioMetodo.AutoSize = true; + this.rdbVecchioMetodo.Location = new System.Drawing.Point(8, 4); + this.rdbVecchioMetodo.Name = "rdbVecchioMetodo"; + this.rdbVecchioMetodo.Size = new System.Drawing.Size(102, 17); + this.rdbVecchioMetodo.TabIndex = 0; + this.rdbVecchioMetodo.Text = "Vecchio metodo"; + this.rdbVecchioMetodo.UseVisualStyleBackColor = true; + // + // Label8 + // + this.Label8.AutoSize = true; + this.Label8.Location = new System.Drawing.Point(64, 26); + this.Label8.Name = "Label8"; + this.Label8.Size = new System.Drawing.Size(111, 13); + this.Label8.TabIndex = 3; + this.Label8.Text = "Chunk Size (0 = MAX)"; + // + // TextBox8 + // + this.TextBox8.Location = new System.Drawing.Point(7, 20); + this.TextBox8.Name = "TextBox8"; + this.TextBox8.Size = new System.Drawing.Size(47, 20); + this.TextBox8.TabIndex = 2; + this.TextBox8.Text = "0"; + // + // Label7 + // + this.Label7.AutoSize = true; + this.Label7.Location = new System.Drawing.Point(61, 48); + this.Label7.Name = "Label7"; + this.Label7.Size = new System.Drawing.Size(108, 13); + this.Label7.TabIndex = 1; + this.Label7.Text = "Threads (0 = CPU *2)"; + // + // TextBox7 + // + this.TextBox7.Location = new System.Drawing.Point(7, 46); + this.TextBox7.Name = "TextBox7"; + this.TextBox7.Size = new System.Drawing.Size(47, 20); + this.TextBox7.TabIndex = 0; + this.TextBox7.Text = "0"; + // + // GroupBox7 + // + this.GroupBox7.Controls.Add(this.chkSovrascriviFile); + this.GroupBox7.Controls.Add(this.chkRotazioneAutomatica); + this.GroupBox7.Controls.Add(this.chkForzaJpg); + this.GroupBox7.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox7.Location = new System.Drawing.Point(6, 113); + this.GroupBox7.Name = "GroupBox7"; + this.GroupBox7.Size = new System.Drawing.Size(192, 88); + this.GroupBox7.TabIndex = 45; + this.GroupBox7.TabStop = false; + this.GroupBox7.Text = "Generale"; + // + // chkSovrascriviFile + // + this.chkSovrascriviFile.AutoSize = true; + this.chkSovrascriviFile.Location = new System.Drawing.Point(16, 61); + this.chkSovrascriviFile.Name = "chkSovrascriviFile"; + this.chkSovrascriviFile.Size = new System.Drawing.Size(94, 17); + this.chkSovrascriviFile.TabIndex = 2; + this.chkSovrascriviFile.Text = "Sovrascrivi file"; + this.chkSovrascriviFile.UseVisualStyleBackColor = true; + // + // chkRotazioneAutomatica + // + this.chkRotazioneAutomatica.ForeColor = System.Drawing.Color.Black; + this.chkRotazioneAutomatica.Location = new System.Drawing.Point(16, 39); + this.chkRotazioneAutomatica.Name = "chkRotazioneAutomatica"; + this.chkRotazioneAutomatica.Size = new System.Drawing.Size(136, 16); + this.chkRotazioneAutomatica.TabIndex = 1; + this.chkRotazioneAutomatica.Text = "Rotazione automatica"; + // + // chkForzaJpg + // + this.chkForzaJpg.Checked = true; + this.chkForzaJpg.CheckState = System.Windows.Forms.CheckState.Checked; + this.chkForzaJpg.ForeColor = System.Drawing.Color.Black; + this.chkForzaJpg.Location = new System.Drawing.Point(16, 18); + this.chkForzaJpg.Name = "chkForzaJpg"; + this.chkForzaJpg.Size = new System.Drawing.Size(80, 16); + this.chkForzaJpg.TabIndex = 0; + this.chkForzaJpg.Text = "Forza Jpg"; + // + // TabPage3 + // + this.TabPage3.Controls.Add(this.CheckBox2); + this.TabPage3.Controls.Add(this.GroupBox10); + this.TabPage3.Controls.Add(this.GroupBox9); + this.TabPage3.Controls.Add(this.GroupBox5); + this.TabPage3.Controls.Add(this.GroupBox4); + this.TabPage3.Location = new System.Drawing.Point(4, 22); + this.TabPage3.Name = "TabPage3"; + this.TabPage3.Padding = new System.Windows.Forms.Padding(3); + this.TabPage3.Size = new System.Drawing.Size(513, 351); + this.TabPage3.TabIndex = 2; + this.TabPage3.Text = "Testo"; + this.TabPage3.UseVisualStyleBackColor = true; + // + // CheckBox2 + // + this.CheckBox2.AutoSize = true; + this.CheckBox2.Location = new System.Drawing.Point(7, 8); + this.CheckBox2.Name = "CheckBox2"; + this.CheckBox2.Size = new System.Drawing.Size(93, 17); + this.CheckBox2.TabIndex = 40; + this.CheckBox2.Text = "Aggiungi testo"; + this.CheckBox2.UseVisualStyleBackColor = true; + // + // GroupBox10 + // + this.GroupBox10.Controls.Add(this.Label42); + this.GroupBox10.Controls.Add(this.Label41); + this.GroupBox10.Controls.Add(this.TextBox31); + this.GroupBox10.Controls.Add(this.TextBox30); + this.GroupBox10.Location = new System.Drawing.Point(316, 78); + this.GroupBox10.Name = "GroupBox10"; + this.GroupBox10.Size = new System.Drawing.Size(186, 73); + this.GroupBox10.TabIndex = 39; + this.GroupBox10.TabStop = false; + this.GroupBox10.Text = "Testo foto verticali"; + // + // Label42 + // + this.Label42.AutoSize = true; + this.Label42.Location = new System.Drawing.Point(7, 46); + this.Label42.Name = "Label42"; + this.Label42.Size = new System.Drawing.Size(45, 13); + this.Label42.TabIndex = 3; + this.Label42.Text = "Margine"; + // + // Label41 + // + this.Label41.AutoSize = true; + this.Label41.Location = new System.Drawing.Point(7, 25); + this.Label41.Name = "Label41"; + this.Label41.Size = new System.Drawing.Size(108, 13); + this.Label41.TabIndex = 2; + this.Label41.Text = "Dimensione Carattere"; + // + // TextBox31 + // + this.TextBox31.Location = new System.Drawing.Point(131, 46); + this.TextBox31.Name = "TextBox31"; + this.TextBox31.Size = new System.Drawing.Size(39, 20); + this.TextBox31.TabIndex = 1; + // + // TextBox30 + // + this.TextBox30.Location = new System.Drawing.Point(131, 22); + this.TextBox30.Name = "TextBox30"; + this.TextBox30.Size = new System.Drawing.Size(39, 20); + this.TextBox30.TabIndex = 0; + // + // GroupBox9 + // + this.GroupBox9.Controls.Add(this.CheckBox17); + this.GroupBox9.Controls.Add(this.CheckBox16); + this.GroupBox9.Location = new System.Drawing.Point(316, 31); + this.GroupBox9.Name = "GroupBox9"; + this.GroupBox9.Size = new System.Drawing.Size(186, 45); + this.GroupBox9.TabIndex = 38; + this.GroupBox9.TabStop = false; + this.GroupBox9.Text = "Slide show"; + // + // CheckBox17 + // + this.CheckBox17.AutoSize = true; + this.CheckBox17.Location = new System.Drawing.Point(96, 18); + this.CheckBox17.Name = "CheckBox17"; + this.CheckBox17.Size = new System.Drawing.Size(84, 17); + this.CheckBox17.TabIndex = 1; + this.CheckBox17.Text = "Numero foto"; + this.CheckBox17.UseVisualStyleBackColor = true; + // + // CheckBox16 + // + this.CheckBox16.AutoSize = true; + this.CheckBox16.Location = new System.Drawing.Point(6, 19); + this.CheckBox16.Name = "CheckBox16"; + this.CheckBox16.Size = new System.Drawing.Size(49, 17); + this.CheckBox16.TabIndex = 0; + this.CheckBox16.Text = "Data"; + this.CheckBox16.UseVisualStyleBackColor = true; + // + // GroupBox5 + // + this.GroupBox5.Controls.Add(this.TextBox34); + this.GroupBox5.Controls.Add(this.Button8); + this.GroupBox5.Controls.Add(this.Label36); + this.GroupBox5.Controls.Add(this.TextBox25); + this.GroupBox5.Controls.Add(this.Label35); + this.GroupBox5.Controls.Add(this.ComboBox3); + this.GroupBox5.Controls.Add(this.TextBox11); + this.GroupBox5.Controls.Add(this.Label12); + this.GroupBox5.Controls.Add(this.Label11); + this.GroupBox5.Controls.Add(this.CheckBox3); + this.GroupBox5.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox5.Location = new System.Drawing.Point(6, 31); + this.GroupBox5.Name = "GroupBox5"; + this.GroupBox5.Size = new System.Drawing.Size(304, 120); + this.GroupBox5.TabIndex = 37; + this.GroupBox5.TabStop = false; + this.GroupBox5.Text = "Carattere"; + // + // TextBox34 + // + this.TextBox34.Location = new System.Drawing.Point(160, 91); + this.TextBox34.Name = "TextBox34"; + this.TextBox34.Size = new System.Drawing.Size(56, 20); + this.TextBox34.TabIndex = 36; + this.TextBox34.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + // + // Button8 + // + this.Button8.ForeColor = System.Drawing.Color.Black; + this.Button8.Location = new System.Drawing.Point(222, 89); + this.Button8.Name = "Button8"; + this.Button8.Size = new System.Drawing.Size(74, 24); + this.Button8.TabIndex = 35; + this.Button8.Text = "Scegli..."; + // + // Label36 + // + this.Label36.ForeColor = System.Drawing.Color.Black; + this.Label36.Location = new System.Drawing.Point(8, 60); + this.Label36.Name = "Label36"; + this.Label36.Size = new System.Drawing.Size(120, 19); + this.Label36.TabIndex = 34; + this.Label36.Text = "Dimensione miniatura"; + this.Label36.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // TextBox25 + // + this.TextBox25.Location = new System.Drawing.Point(160, 59); + this.TextBox25.Name = "TextBox25"; + this.TextBox25.Size = new System.Drawing.Size(56, 20); + this.TextBox25.TabIndex = 33; + this.TextBox25.Text = "TextBox25"; + // + // Label35 + // + this.Label35.ForeColor = System.Drawing.Color.Black; + this.Label35.Location = new System.Drawing.Point(8, 93); + this.Label35.Name = "Label35"; + this.Label35.Size = new System.Drawing.Size(72, 16); + this.Label35.TabIndex = 32; + this.Label35.Text = "Colore RGB"; + this.Label35.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // ComboBox3 + // + this.ComboBox3.Location = new System.Drawing.Point(96, 8); + this.ComboBox3.Name = "ComboBox3"; + this.ComboBox3.Size = new System.Drawing.Size(120, 21); + this.ComboBox3.TabIndex = 28; + this.ComboBox3.Text = "ComboBox3"; + // + // TextBox11 + // + this.TextBox11.Location = new System.Drawing.Point(160, 35); + this.TextBox11.Name = "TextBox11"; + this.TextBox11.Size = new System.Drawing.Size(56, 20); + this.TextBox11.TabIndex = 27; + this.TextBox11.Text = "TextBox11"; + // + // Label12 + // + this.Label12.AutoSize = true; + this.Label12.ForeColor = System.Drawing.Color.Black; + this.Label12.Location = new System.Drawing.Point(8, 38); + this.Label12.Name = "Label12"; + this.Label12.Size = new System.Drawing.Size(62, 13); + this.Label12.TabIndex = 26; + this.Label12.Text = "Dimensione"; + this.Label12.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // Label11 + // + this.Label11.AutoSize = true; + this.Label11.ForeColor = System.Drawing.Color.Black; + this.Label11.Location = new System.Drawing.Point(56, 8); + this.Label11.Name = "Label11"; + this.Label11.Size = new System.Drawing.Size(28, 13); + this.Label11.TabIndex = 22; + this.Label11.Text = "Font"; + // + // CheckBox3 + // + this.CheckBox3.ForeColor = System.Drawing.Color.Black; + this.CheckBox3.Location = new System.Drawing.Point(224, 8); + this.CheckBox3.Name = "CheckBox3"; + this.CheckBox3.Size = new System.Drawing.Size(72, 24); + this.CheckBox3.TabIndex = 24; + this.CheckBox3.Text = "Grassetto"; + // + // GroupBox4 + // + this.GroupBox4.Controls.Add(this.Label40); + this.GroupBox4.Controls.Add(this.TextBox29); + this.GroupBox4.Controls.Add(this.TextBox18); + this.GroupBox4.Controls.Add(this.Label26); + this.GroupBox4.Controls.Add(this.DateTimePicker1); + this.GroupBox4.Controls.Add(this.CheckBox8); + this.GroupBox4.Controls.Add(this.TextBox9); + this.GroupBox4.Controls.Add(this.CheckBox7); + this.GroupBox4.Controls.Add(this.Label4); + this.GroupBox4.Controls.Add(this.TextBox4); + this.GroupBox4.Controls.Add(this.Label9); + this.GroupBox4.Controls.Add(this.Label13); + this.GroupBox4.Controls.Add(this.ComboBox1); + this.GroupBox4.Controls.Add(this.ComboBox2); + this.GroupBox4.Controls.Add(this.Label14); + this.GroupBox4.Controls.Add(this.TextBox12); + this.GroupBox4.Controls.Add(this.Label15); + this.GroupBox4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(192))))); + this.GroupBox4.Location = new System.Drawing.Point(6, 157); + this.GroupBox4.Name = "GroupBox4"; + this.GroupBox4.Size = new System.Drawing.Size(496, 186); + this.GroupBox4.TabIndex = 36; + this.GroupBox4.TabStop = false; + this.GroupBox4.Text = "Testo da applicare"; + // + // ComboBox1 + // + this.ComboBox1.Location = new System.Drawing.Point(72, 132); + this.ComboBox1.Name = "ComboBox1"; + this.ComboBox1.Size = new System.Drawing.Size(104, 21); + this.ComboBox1.TabIndex = 28; + this.ComboBox1.Text = "ComboBox1"; + // + // ComboBox2 + // + this.ComboBox2.Location = new System.Drawing.Point(376, 132); + this.ComboBox2.Name = "ComboBox2"; + this.ComboBox2.Size = new System.Drawing.Size(104, 21); + this.ComboBox2.TabIndex = 31; + this.ComboBox2.Text = "ComboBox2"; + // + // Label14 + // + this.Label14.AutoSize = true; + this.Label14.ForeColor = System.Drawing.Color.Black; + this.Label14.Location = new System.Drawing.Point(304, 132); + this.Label14.Name = "Label14"; + this.Label14.Size = new System.Drawing.Size(67, 13); + this.Label14.TabIndex = 30; + this.Label14.Text = "Allineamento"; + // + // TextBox12 + // + this.TextBox12.Location = new System.Drawing.Point(376, 108); + this.TextBox12.Name = "TextBox12"; + this.TextBox12.Size = new System.Drawing.Size(104, 20); + this.TextBox12.TabIndex = 33; + this.TextBox12.Text = "TextBox12"; + // + // Label15 + // + this.Label15.AutoSize = true; + this.Label15.ForeColor = System.Drawing.Color.Black; + this.Label15.Location = new System.Drawing.Point(296, 108); + this.Label15.Name = "Label15"; + this.Label15.Size = new System.Drawing.Size(75, 13); + this.Label15.TabIndex = 32; + this.Label15.Text = "Margine (pixel)"; + // + // Button6 + // + this.Button6.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Button6.Location = new System.Drawing.Point(539, 12); + this.Button6.Name = "Button6"; + this.Button6.Size = new System.Drawing.Size(197, 32); + this.Button6.TabIndex = 70; + this.Button6.Text = "Carica impostazioni"; + // + // Form1 + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.Label27); + this.Controls.Add(this.Button7); + this.Controls.Add(this.Button5); + this.Controls.Add(this.Label19); + this.Controls.Add(this.Label18); + this.Controls.Add(this.lblFotoTotaliNum); + this.Controls.Add(this.Label10); + this.Controls.Add(this.btnCreaCatalogoAsync); + this.Controls.Add(this.Label20); + this.Controls.Add(this.btnCreaCatalogo); + this.Controls.Add(this.ProgressBar1); + this.Controls.Add(this.CheckBox22); + this.Controls.Add(this.Label43); + this.Controls.Add(this.TabControl1); + this.Controls.Add(this.Button6); + this.Name = "Form1"; + this.Text = "Form1"; + this.TabPage1.ResumeLayout(false); + this.Panel1.ResumeLayout(false); + this.Panel1.PerformLayout(); + this.GroupBox1.ResumeLayout(false); + this.GroupBox1.PerformLayout(); + this.Panel2.ResumeLayout(false); + this.Panel2.PerformLayout(); + this.TabPage2.ResumeLayout(false); + this.GroupBox2.ResumeLayout(false); + this.GroupBox2.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox2)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.PictureBox3)).EndInit(); + this.GroupBox6.ResumeLayout(false); + this.GroupBox6.PerformLayout(); + this.TabPage4.ResumeLayout(false); + this.GroupBox8.ResumeLayout(false); + this.GroupBox8.PerformLayout(); + this.GroupBox3.ResumeLayout(false); + this.GroupBox3.PerformLayout(); + this.TabControl1.ResumeLayout(false); + this.TabPage5.ResumeLayout(false); + this.GroupBox11.ResumeLayout(false); + this.GroupBox11.PerformLayout(); + this.Panel3.ResumeLayout(false); + this.Panel3.PerformLayout(); + this.GroupBox7.ResumeLayout(false); + this.GroupBox7.PerformLayout(); + this.TabPage3.ResumeLayout(false); + this.TabPage3.PerformLayout(); + this.GroupBox10.ResumeLayout(false); + this.GroupBox10.PerformLayout(); + this.GroupBox9.ResumeLayout(false); + this.GroupBox9.PerformLayout(); + this.GroupBox5.ResumeLayout(false); + this.GroupBox5.PerformLayout(); + this.GroupBox4.ResumeLayout(false); + this.GroupBox4.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + internal System.Windows.Forms.TabPage TabPage1; + internal System.Windows.Forms.Panel Panel1; + internal System.Windows.Forms.CheckBox CheckBox18; + internal System.Windows.Forms.CheckBox CheckBox4; + internal System.Windows.Forms.CheckBox CheckBox12; + internal System.Windows.Forms.GroupBox GroupBox1; + internal System.Windows.Forms.Label Label46; + internal System.Windows.Forms.TextBox TextBox33; + internal System.Windows.Forms.Panel Panel2; + internal System.Windows.Forms.RadioButton RadioButton3; + internal System.Windows.Forms.RadioButton RadioButton7; + internal System.Windows.Forms.RadioButton RadioButton4; + internal System.Windows.Forms.RadioButton RadioButton6; + internal System.Windows.Forms.RadioButton RadioButton5; + internal System.Windows.Forms.Label Label5; + internal System.Windows.Forms.TextBox TextBox5; + internal System.Windows.Forms.Label Label6; + internal System.Windows.Forms.TextBox TextBox6; + internal System.Windows.Forms.Label Label3; + internal System.Windows.Forms.TextBox TextBox3; + internal System.Windows.Forms.CheckBox CheckBox1; + internal System.Windows.Forms.Label Label37; + internal System.Windows.Forms.Label Label38; + internal System.Windows.Forms.Label Label45; + internal System.Windows.Forms.TextBox TextBox32; + internal System.Windows.Forms.TextBox TextBox26; + internal System.Windows.Forms.TextBox TextBox27; + internal System.Windows.Forms.Label Label39; + internal System.Windows.Forms.CheckBox CheckBox15; + internal System.Windows.Forms.Label Label40; + internal System.Windows.Forms.TextBox TextBox29; + internal System.Windows.Forms.TextBox TextBox18; + internal System.Windows.Forms.Label Label26; + internal System.Windows.Forms.DateTimePicker DateTimePicker1; + internal System.Windows.Forms.CheckBox CheckBox8; + internal System.Windows.Forms.TextBox TextBox9; + internal System.Windows.Forms.CheckBox CheckBox7; + internal System.Windows.Forms.Label Label4; + internal System.Windows.Forms.TextBox TextBox4; + internal System.Windows.Forms.Label Label9; + internal System.Windows.Forms.TextBox TextBox28; + internal System.Windows.Forms.TabPage TabPage2; + internal System.Windows.Forms.GroupBox GroupBox2; + internal System.Windows.Forms.Label Label27; + internal System.Windows.Forms.Button Button7; + internal System.Windows.Forms.Button Button5; + internal System.Windows.Forms.PictureBox PictureBox2; + internal System.Windows.Forms.PictureBox PictureBox1; + internal System.Windows.Forms.ComboBox ComboBox5; + internal System.Windows.Forms.ComboBox ComboBox4; + internal System.Windows.Forms.Label Label19; + internal System.Windows.Forms.Label Label18; + internal System.Windows.Forms.Label lblFotoTotaliNum; + internal System.Windows.Forms.Label Label10; + internal System.Windows.Forms.TextBox TextBox19; + internal System.Windows.Forms.Label Label28; + internal System.Windows.Forms.CheckBox CheckBox5; + internal System.Windows.Forms.TextBox TextBox15; + internal System.Windows.Forms.TextBox TextBox14; + internal System.Windows.Forms.Label Label25; + internal System.Windows.Forms.TextBox TextBox16; + internal System.Windows.Forms.Button btnCreaCatalogoAsync; + internal System.Windows.Forms.Label Label20; + internal System.Windows.Forms.Button btnCreaCatalogo; + internal System.Windows.Forms.Label Label24; + internal System.Windows.Forms.Label Label22; + internal System.Windows.Forms.Label Label23; + internal System.Windows.Forms.TextBox TextBox10; + internal System.Windows.Forms.Label Label29; + internal System.Windows.Forms.Label Label30; + internal System.Windows.Forms.PictureBox PictureBox3; + internal System.Windows.Forms.GroupBox GroupBox6; + internal System.Windows.Forms.Button Button4; + internal System.Windows.Forms.TabPage TabPage4; + internal System.Windows.Forms.Label Label13; + internal System.Windows.Forms.RadioButton rdbNumFiles; + internal System.Windows.Forms.RadioButton rdbNumProgressiva; + internal System.Windows.Forms.TextBox txtCifreContatore; + internal System.Windows.Forms.Label Label34; + internal System.Windows.Forms.TextBox txtSuffissoCartelle; + internal System.Windows.Forms.Label Label33; + internal System.Windows.Forms.Label Label31; + internal System.Windows.Forms.TextBox txtFilePerCartella; + internal System.Windows.Forms.GroupBox GroupBox8; + internal System.Windows.Forms.CheckBox chkCreaSottocartelle; + internal System.Windows.Forms.Label Label32; + internal System.Windows.Forms.CheckBox chkAggiornaSottodirectory; + internal System.Windows.Forms.GroupBox GroupBox3; + internal System.Windows.Forms.Button Button3; + internal System.Windows.Forms.Button Button2; + internal System.Windows.Forms.Label Label1; + internal System.Windows.Forms.Label Label2; + internal System.Windows.Forms.TextBox txtSorgente; + internal System.Windows.Forms.TextBox txtDestinazione; + internal System.Windows.Forms.ProgressBar ProgressBar1; + internal System.Windows.Forms.CheckBox CheckBox22; + internal System.Windows.Forms.Label Label43; + internal System.Windows.Forms.TabControl TabControl1; + internal System.Windows.Forms.TabPage TabPage5; + internal System.Windows.Forms.GroupBox GroupBox11; + internal System.Windows.Forms.Panel Panel3; + internal System.Windows.Forms.RadioButton rdbNuovoMetodo; + internal System.Windows.Forms.RadioButton rdbVecchioMetodo; + internal System.Windows.Forms.Label Label8; + internal System.Windows.Forms.TextBox TextBox8; + internal System.Windows.Forms.Label Label7; + internal System.Windows.Forms.TextBox TextBox7; + internal System.Windows.Forms.GroupBox GroupBox7; + internal System.Windows.Forms.CheckBox chkSovrascriviFile; + internal System.Windows.Forms.CheckBox chkRotazioneAutomatica; + internal System.Windows.Forms.CheckBox chkForzaJpg; + internal System.Windows.Forms.TabPage TabPage3; + internal System.Windows.Forms.CheckBox CheckBox2; + internal System.Windows.Forms.GroupBox GroupBox10; + internal System.Windows.Forms.Label Label42; + internal System.Windows.Forms.Label Label41; + internal System.Windows.Forms.TextBox TextBox31; + internal System.Windows.Forms.TextBox TextBox30; + internal System.Windows.Forms.GroupBox GroupBox9; + internal System.Windows.Forms.CheckBox CheckBox17; + internal System.Windows.Forms.CheckBox CheckBox16; + internal System.Windows.Forms.GroupBox GroupBox5; + internal System.Windows.Forms.TextBox TextBox34; + internal System.Windows.Forms.Button Button8; + internal System.Windows.Forms.Label Label36; + internal System.Windows.Forms.TextBox TextBox25; + internal System.Windows.Forms.Label Label35; + internal System.Windows.Forms.ComboBox ComboBox3; + internal System.Windows.Forms.TextBox TextBox11; + internal System.Windows.Forms.Label Label12; + internal System.Windows.Forms.Label Label11; + internal System.Windows.Forms.CheckBox CheckBox3; + internal System.Windows.Forms.GroupBox GroupBox4; + internal System.Windows.Forms.ComboBox ComboBox1; + internal System.Windows.Forms.ComboBox ComboBox2; + internal System.Windows.Forms.Label Label14; + internal System.Windows.Forms.TextBox TextBox12; + internal System.Windows.Forms.Label Label15; + internal System.Windows.Forms.Button Button6; + } +} + diff --git a/ImageCatalogParallel/Form1.cs b/ImageCatalogParallel/Form1.cs new file mode 100644 index 0000000..458f104 --- /dev/null +++ b/ImageCatalogParallel/Form1.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ImageCatalogParallel +{ + public partial class Form1 : Form + { + public Form1() + { + InitializeComponent(); + } + } +} diff --git a/ImageCatalogParallel/Form1.resx b/ImageCatalogParallel/Form1.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/ImageCatalogParallel/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 newline at end of file diff --git a/ImageCatalogParallel/ImageCatalogParallel.csproj b/ImageCatalogParallel/ImageCatalogParallel.csproj new file mode 100644 index 0000000..b507943 --- /dev/null +++ b/ImageCatalogParallel/ImageCatalogParallel.csproj @@ -0,0 +1,83 @@ + + + + + Debug + AnyCPU + {0F42DA5C-2788-48BD-BACA-01625C3CFFBB} + WinExe + ImageCatalogParallel + ImageCatalogParallel + v4.8 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + Form1.cs + + + + + Form1.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/ImageCatalogParallel/Program.cs b/ImageCatalogParallel/Program.cs new file mode 100644 index 0000000..0a1fd3d --- /dev/null +++ b/ImageCatalogParallel/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ImageCatalogParallel +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Form1()); + } + } +} diff --git a/ImageCatalogParallel/Properties/AssemblyInfo.cs b/ImageCatalogParallel/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..757c842 --- /dev/null +++ b/ImageCatalogParallel/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ImageCatalogParallel")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ImageCatalogParallel")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("0f42da5c-2788-48bd-baca-01625c3cffbb")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/ImageCatalogParallel/Properties/Resources.Designer.cs b/ImageCatalogParallel/Properties/Resources.Designer.cs new file mode 100644 index 0000000..a23847e --- /dev/null +++ b/ImageCatalogParallel/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace ImageCatalogParallel.Properties +{ + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ImageCatalogParallel.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/ImageCatalogParallel/Properties/Resources.resx b/ImageCatalogParallel/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/ImageCatalogParallel/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/ImageCatalogParallel/Properties/Settings.Designer.cs b/ImageCatalogParallel/Properties/Settings.Designer.cs new file mode 100644 index 0000000..28069fb --- /dev/null +++ b/ImageCatalogParallel/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace ImageCatalogParallel.Properties +{ + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/ImageCatalogParallel/Properties/Settings.settings b/ImageCatalogParallel/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/ImageCatalogParallel/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/MaddoLibrary b/MaddoLibrary new file mode 160000 index 0000000..5987cc2 --- /dev/null +++ b/MaddoLibrary @@ -0,0 +1 @@ +Subproject commit 5987cc26521d839bf81bdaab19d101488294da19 diff --git a/MaddoShared.Benchmarks/ChunkSizeBenchmarks.cs b/MaddoShared.Benchmarks/ChunkSizeBenchmarks.cs index 390799d..8ea126f 100644 --- a/MaddoShared.Benchmarks/ChunkSizeBenchmarks.cs +++ b/MaddoShared.Benchmarks/ChunkSizeBenchmarks.cs @@ -22,7 +22,7 @@ public class ChunkSizeBenchmarks { private string _sourceDirectory; private string _destinationDirectory; - private ImageCreationService _imageCreationStuff; + private ImageCreationStuff _imageCreationStuff; private PicSettings _picSettings; [Params(100)] @@ -49,8 +49,8 @@ public class ChunkSizeBenchmarks builder.SetMinimumLevel(LogLevel.Warning); }); - var logger = loggerFactory.CreateLogger(); - var imageCreatorLogger = loggerFactory.CreateLogger(); + var logger = loggerFactory.CreateLogger(); + var imageCreatorLogger = loggerFactory.CreateLogger(); _picSettings = new PicSettings { @@ -75,8 +75,8 @@ public class ChunkSizeBenchmarks Trasparenza = 100 }; - var imageCreatorService = new ImageCreatorImageSharp(_picSettings, imageCreatorLogger); - _imageCreationStuff = new ImageCreationService(logger, _picSettings, imageCreatorService); + var imageCreatorService = new ImageCreatorSharp(_picSettings, imageCreatorLogger); + _imageCreationStuff = new ImageCreationStuff(logger, _picSettings, imageCreatorService); } [GlobalCleanup] @@ -109,7 +109,7 @@ public class ChunkSizeBenchmarks [Benchmark] public async Task ProcessWithVariableChunkSize() { - var options = new ImageCreationService.Options + var options = new ImageCreationStuff.Options { SourcePath = _sourceDirectory, DestinationPath = _destinationDirectory, diff --git a/MaddoShared.Benchmarks/Helpers/TestImageGenerator.cs b/MaddoShared.Benchmarks/Helpers/TestImageGenerator.cs index 5630655..34f44b5 100644 --- a/MaddoShared.Benchmarks/Helpers/TestImageGenerator.cs +++ b/MaddoShared.Benchmarks/Helpers/TestImageGenerator.cs @@ -1,32 +1,40 @@ using System; +using System.Diagnostics.CodeAnalysis; +using System.Drawing; +using System.Drawing.Imaging; using System.IO; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats.Jpeg; -using SixLabors.ImageSharp.PixelFormats; namespace MaddoShared.Benchmarks.Helpers; /// -/// Helper class to generate test images for benchmarking. +/// Helper class to generate test images for benchmarking /// +[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility")] public static class TestImageGenerator { + /// + /// Generates a set of test JPEG images in the specified directory + /// + /// Directory where images will be created + /// Number of images to generate + /// Width of each image + /// Height of each image + /// Whether to create images in subfolders public static void GenerateTestImages( - string outputDirectory, - int imageCount, - int width = 4000, + string outputDirectory, + int imageCount, + int width = 4000, int height = 3000, bool includeSubfolders = false) { Directory.CreateDirectory(outputDirectory); - var random = new Random(42); - var encoder = new JpegEncoder { Quality = 85 }; + var random = new Random(42); // Fixed seed for reproducibility - for (var i = 0; i < imageCount; i++) + for (int i = 0; i < imageCount; i++) { var targetDir = outputDirectory; - + if (includeSubfolders && i % 10 == 0) { targetDir = Path.Combine(outputDirectory, $"Subfolder_{i / 10}"); @@ -34,17 +42,48 @@ public static class TestImageGenerator } var filePath = Path.Combine(targetDir, $"test_image_{i:D5}.jpg"); + + // Skip if already exists if (File.Exists(filePath)) - { continue; + + using var bitmap = new Bitmap(width, height); + using var graphics = Graphics.FromImage(bitmap); + + // Fill with a random color background + var bgColor = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)); + graphics.Clear(bgColor); + + // Draw some random shapes to make it more realistic + for (int j = 0; j < 20; j++) + { + var color = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256)); + var brush = new SolidBrush(color); + var x = random.Next(width); + var y = random.Next(height); + var w = random.Next(200, 800); + var h = random.Next(200, 800); + graphics.FillEllipse(brush, x, y, w, h); } - using var image = new Image(width, height, RandomColor(random)); - AddBenchmarkTexture(image, random); - image.Save(filePath, encoder); + // Add some text + using var font = new Font("Arial", 48, FontStyle.Bold); + var text = $"Test Image {i}"; + var textBrush = new SolidBrush(Color.White); + graphics.DrawString(text, font, textBrush, new PointF(100, 100)); + + // Save as JPEG with standard quality + var encoder = GetEncoder(ImageFormat.Jpeg); + var encoderParameters = new EncoderParameters(1); + encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 85L); + + bitmap.Save(filePath, encoder, encoderParameters); } } + /// + /// Cleans up generated test images + /// public static void CleanupTestImages(string directory) { if (Directory.Exists(directory)) @@ -53,38 +92,16 @@ public static class TestImageGenerator } } - private static void AddBenchmarkTexture(Image image, Random random) + private static ImageCodecInfo GetEncoder(ImageFormat format) { - image.ProcessPixelRows(accessor => + var codecs = ImageCodecInfo.GetImageEncoders(); + foreach (var codec in codecs) { - for (var shape = 0; shape < 20; shape++) + if (codec.FormatID == format.Guid) { - var color = RandomColor(random); - var startX = random.Next(image.Width); - var startY = random.Next(image.Height); - var width = random.Next(200, Math.Min(800, image.Width) + 1); - var height = random.Next(200, Math.Min(800, image.Height) + 1); - var endX = Math.Min(accessor.Width, startX + width); - var endY = Math.Min(accessor.Height, startY + height); - - for (var y = startY; y < endY; y++) - { - var row = accessor.GetRowSpan(y); - for (var x = startX; x < endX; x++) - { - row[x] = color; - } - } + return codec; } - }); - } - - private static Rgba32 RandomColor(Random random) - { - return new Rgba32( - (byte)random.Next(256), - (byte)random.Next(256), - (byte)random.Next(256), - 255); + } + return null; } } diff --git a/MaddoShared.Benchmarks/ImageProcessingBenchmarks.cs b/MaddoShared.Benchmarks/ImageProcessingBenchmarks.cs index 49f86d0..0ed6069 100644 --- a/MaddoShared.Benchmarks/ImageProcessingBenchmarks.cs +++ b/MaddoShared.Benchmarks/ImageProcessingBenchmarks.cs @@ -22,10 +22,10 @@ public class ImageProcessingBenchmarks { private string _sourceDirectory; private string _destinationDirectory; - private ImageCreationService _imageCreationStuff; + private ImageCreationStuff _imageCreationStuff; private PicSettings _picSettings; - private ILogger _logger; - private ILogger _imageCreatorLogger; + private ILogger _logger; + private ILogger _imageCreatorLogger; [Params(10, 50, 100)] public int ImageCount { get; set; } @@ -54,8 +54,8 @@ public class ImageProcessingBenchmarks builder.SetMinimumLevel(LogLevel.Warning); // Reduce noise during benchmarks }); - _logger = loggerFactory.CreateLogger(); - _imageCreatorLogger = loggerFactory.CreateLogger(); + _logger = loggerFactory.CreateLogger(); + _imageCreatorLogger = loggerFactory.CreateLogger(); // Setup PicSettings with default values _picSettings = new PicSettings @@ -81,8 +81,8 @@ public class ImageProcessingBenchmarks Trasparenza = 100 }; - var imageCreatorService = new ImageCreatorImageSharp(_picSettings, _imageCreatorLogger); - _imageCreationStuff = new ImageCreationService(_logger, _picSettings, imageCreatorService); + var imageCreatorService = new ImageCreatorSharp(_picSettings, _imageCreatorLogger); + _imageCreationStuff = new ImageCreationStuff(_logger, _picSettings, imageCreatorService); } [GlobalCleanup] @@ -117,7 +117,7 @@ public class ImageProcessingBenchmarks [Benchmark(Description = "Process images in parallel with chunking")] public async Task ProcessImagesParallelWithChunks() { - var options = new ImageCreationService.Options + var options = new ImageCreationStuff.Options { SourcePath = _sourceDirectory, DestinationPath = _destinationDirectory, @@ -139,7 +139,7 @@ public class ImageProcessingBenchmarks [Benchmark(Description = "Process images in parallel without chunking")] public async Task ProcessImagesParallelWithoutChunks() { - var options = new ImageCreationService.Options + var options = new ImageCreationStuff.Options { SourcePath = _sourceDirectory, DestinationPath = _destinationDirectory, @@ -161,7 +161,7 @@ public class ImageProcessingBenchmarks [Benchmark(Description = "Process images linearly")] public async Task ProcessImagesLinear() { - var options = new ImageCreationService.Options + var options = new ImageCreationStuff.Options { SourcePath = _sourceDirectory, DestinationPath = _destinationDirectory, diff --git a/MaddoShared.Benchmarks/ImageSizeBenchmarks.cs b/MaddoShared.Benchmarks/ImageSizeBenchmarks.cs index b190f8d..fe42fcc 100644 --- a/MaddoShared.Benchmarks/ImageSizeBenchmarks.cs +++ b/MaddoShared.Benchmarks/ImageSizeBenchmarks.cs @@ -22,7 +22,7 @@ public class ImageSizeBenchmarks { private string _sourceDirectory; private string _destinationDirectory; - private ImageCreationService _imageCreationStuff; + private ImageCreationStuff _imageCreationStuff; private PicSettings _picSettings; [Params(50)] @@ -58,8 +58,8 @@ public class ImageSizeBenchmarks builder.SetMinimumLevel(LogLevel.Warning); }); - var logger = loggerFactory.CreateLogger(); - var imageCreatorLogger = loggerFactory.CreateLogger(); + var logger = loggerFactory.CreateLogger(); + var imageCreatorLogger = loggerFactory.CreateLogger(); _picSettings = new PicSettings { @@ -84,8 +84,8 @@ public class ImageSizeBenchmarks Trasparenza = 100 }; - var imageCreatorService = new ImageCreatorImageSharp(_picSettings, imageCreatorLogger); - _imageCreationStuff = new ImageCreationService(logger, _picSettings, imageCreatorService); + var imageCreatorService = new ImageCreatorSharp(_picSettings, imageCreatorLogger); + _imageCreationStuff = new ImageCreationStuff(logger, _picSettings, imageCreatorService); } private static (int width, int height) GetDimensions(ImageSize size) @@ -130,7 +130,7 @@ public class ImageSizeBenchmarks [Benchmark] public async Task ProcessDifferentImageSizes() { - var options = new ImageCreationService.Options + var options = new ImageCreationStuff.Options { SourcePath = _sourceDirectory, DestinationPath = _destinationDirectory, diff --git a/MaddoShared.Benchmarks/MaddoShared.Benchmarks.csproj b/MaddoShared.Benchmarks/MaddoShared.Benchmarks.csproj index f68e319..b712ff3 100644 --- a/MaddoShared.Benchmarks/MaddoShared.Benchmarks.csproj +++ b/MaddoShared.Benchmarks/MaddoShared.Benchmarks.csproj @@ -2,14 +2,16 @@ Exe - net10.0 + net10.0-windows x64 + true + true - - + + diff --git a/MaddoShared.Benchmarks/StressTestBenchmark.cs b/MaddoShared.Benchmarks/StressTestBenchmark.cs index 32d1723..4d626ae 100644 --- a/MaddoShared.Benchmarks/StressTestBenchmark.cs +++ b/MaddoShared.Benchmarks/StressTestBenchmark.cs @@ -22,7 +22,7 @@ public class StressTestBenchmark { private string _sourceDirectory; private string _destinationDirectory; - private ImageCreationService _imageCreationStuff; + private ImageCreationStuff _imageCreationStuff; private PicSettings _picSettings; [Params(500, 1000)] @@ -40,7 +40,7 @@ public class StressTestBenchmark Console.WriteLine($"[STRESS TEST] Generating {ImageCount} test images..."); Console.WriteLine("This may take several minutes depending on your hardware."); - + // Use smaller images for stress test to save space and time TestImageGenerator.GenerateTestImages(_sourceDirectory, ImageCount, width: 1920, height: 1080); @@ -49,8 +49,8 @@ public class StressTestBenchmark builder.SetMinimumLevel(LogLevel.Warning); }); - var logger = loggerFactory.CreateLogger(); - var imageCreatorLogger = loggerFactory.CreateLogger(); + var logger = loggerFactory.CreateLogger(); + var imageCreatorLogger = loggerFactory.CreateLogger(); _picSettings = new PicSettings { @@ -75,8 +75,8 @@ public class StressTestBenchmark Trasparenza = 100 }; - var imageCreatorService = new ImageCreatorImageSharp(_picSettings, imageCreatorLogger); - _imageCreationStuff = new ImageCreationService(logger, _picSettings, imageCreatorService); + var imageCreatorService = new ImageCreatorSharp(_picSettings, imageCreatorLogger); + _imageCreationStuff = new ImageCreationStuff(logger, _picSettings, imageCreatorService); Console.WriteLine($"[STRESS TEST] Setup complete. Ready to process {ImageCount} images."); } @@ -113,7 +113,7 @@ public class StressTestBenchmark [Benchmark(Description = "Stress test with optimal settings")] public async Task StressTestOptimalSettings() { - var options = new ImageCreationService.Options + var options = new ImageCreationStuff.Options { SourcePath = _sourceDirectory, DestinationPath = _destinationDirectory, @@ -130,12 +130,12 @@ public class StressTestBenchmark var results = new ConcurrentBag(); var startTime = DateTime.Now; - + await _imageCreationStuff.ProcessImagesParallel(options, results, null, CancellationToken.None); - + var duration = DateTime.Now - startTime; var throughput = ImageCount / duration.TotalSeconds; - + Console.WriteLine($"[STRESS TEST] Processed {results.Count}/{ImageCount} images in {duration.TotalSeconds:F2}s"); Console.WriteLine($"[STRESS TEST] Throughput: {throughput:F2} images/second"); } @@ -143,7 +143,7 @@ public class StressTestBenchmark [Benchmark(Description = "Stress test with aggressive memory management")] public async Task StressTestAggressiveMemoryManagement() { - var options = new ImageCreationService.Options + var options = new ImageCreationStuff.Options { SourcePath = _sourceDirectory, DestinationPath = _destinationDirectory, @@ -160,12 +160,12 @@ public class StressTestBenchmark var results = new ConcurrentBag(); var startTime = DateTime.Now; - + await _imageCreationStuff.ProcessImagesParallel(options, results, null, CancellationToken.None); - + var duration = DateTime.Now - startTime; var throughput = ImageCount / duration.TotalSeconds; - + Console.WriteLine($"[STRESS TEST] Processed {results.Count}/{ImageCount} images in {duration.TotalSeconds:F2}s"); Console.WriteLine($"[STRESS TEST] Throughput: {throughput:F2} images/second"); } diff --git a/MaddoShared.ImageSharpTests/Helpers/CreatorFactory.cs b/MaddoShared.ImageSharpTests/Helpers/CreatorFactory.cs deleted file mode 100644 index cb25390..0000000 --- a/MaddoShared.ImageSharpTests/Helpers/CreatorFactory.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.IO; -using Microsoft.Extensions.Logging.Abstractions; -using SixLabors.ImageSharp.PixelFormats; - -namespace MaddoShared.ImageSharpTests.Helpers -{ - public static class CreatorFactory - { - public static MaddoShared.PicSettings CreateDefaultPicSettings() - { - return new MaddoShared.PicSettings - { - DimStandard = 48, - DimStandardMiniatura = 12, - LarghezzaSmall = 150, - AltezzaSmall = 150, - LarghezzaBig = 800, - AltezzaBig = 600, - Trasparenza = 0, - IlFont = "Arial", - Grassetto = false, - Posizione = "CENTRO", - Allineamento = "CENTRO", - Margine = 10, - MargVert = 10, - TestoMin = false, - AggNumTempMin = false, - CreaMiniature = false, - LogoAggiungi = false, - LogoAltezza = 100, - LogoLarghezza = 100, - LogoMargine = "0", - JpegQuality = 90, - JpegQualityMin = 75, - }; - } - - public static MaddoShared.ImageCreatorImageSharp CreateImageCreator(MaddoShared.PicSettings settings) - { - var logger = NullLogger.Instance; - return new MaddoShared.ImageCreatorImageSharp(settings, logger); - } - } -} diff --git a/MaddoShared.ImageSharpTests/Helpers/PixelInspector.cs b/MaddoShared.ImageSharpTests/Helpers/PixelInspector.cs deleted file mode 100644 index 5642ec7..0000000 --- a/MaddoShared.ImageSharpTests/Helpers/PixelInspector.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; - -namespace MaddoShared.ImageSharpTests.Helpers -{ - public static class PixelInspector - { - public static int CountNonBackgroundPixels(string path, int x, int y, int width, int height, Rgba32 background, int tolerance = 0) - { - using var img = SixLabors.ImageSharp.Image.Load(path); - var bx = Math.Max(0, x); - var by = Math.Max(0, y); - var bw = Math.Min(width, img.Width - bx); - var bh = Math.Min(height, img.Height - by); - if (bw <= 0 || bh <= 0) return 0; - - int count = 0; - img.ProcessPixelRows(accessor => - { - for (int yy = by; yy < by + bh; yy++) - { - var row = accessor.GetRowSpan(yy); - for (int xx = bx; xx < bx + bw; xx++) - { - var p = row[xx]; - if (!IsApproximatelyEqual(p, background, tolerance)) count++; - } - } - }); - - return count; - } - - private static bool IsApproximatelyEqual(Rgba32 a, Rgba32 b, int tol) - { - return Math.Abs(a.R - b.R) <= tol && Math.Abs(a.G - b.G) <= tol && Math.Abs(a.B - b.B) <= tol && Math.Abs(a.A - b.A) <= tol; - } - } -} diff --git a/MaddoShared.ImageSharpTests/Helpers/TempWorkspace.cs b/MaddoShared.ImageSharpTests/Helpers/TempWorkspace.cs deleted file mode 100644 index fba6bd8..0000000 --- a/MaddoShared.ImageSharpTests/Helpers/TempWorkspace.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.IO; - -namespace MaddoShared.ImageSharpTests.Helpers -{ - public sealed class TempWorkspace : IDisposable - { - public DirectoryInfo Root { get; } - public DirectoryInfo SourceDir { get; } - public DirectoryInfo DestDir { get; } - - public TempWorkspace() - { - var root = Path.Combine(Path.GetTempPath(), "MaddoShared.ImageSharpTests", Guid.NewGuid().ToString("N")); - Root = Directory.CreateDirectory(root); - SourceDir = Directory.CreateDirectory(Path.Combine(Root.FullName, "Source")); - DestDir = Directory.CreateDirectory(Path.Combine(Root.FullName, "Dest")); - } - - public void Dispose() - { - try - { - if (Root.Exists) - Root.Delete(true); - } - catch - { - // best-effort cleanup - } - } - } -} diff --git a/MaddoShared.ImageSharpTests/Helpers/TestImageFactory.cs b/MaddoShared.ImageSharpTests/Helpers/TestImageFactory.cs deleted file mode 100644 index 4f15dd8..0000000 --- a/MaddoShared.ImageSharpTests/Helpers/TestImageFactory.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.IO; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.PixelFormats; -using SixLabors.ImageSharp.Processing; -using SixLabors.ImageSharp.Formats.Jpeg; -using SixLabors.ImageSharp.Metadata.Profiles.Exif; - -namespace MaddoShared.ImageSharpTests.Helpers -{ - public static class TestImageFactory - { - public static string CreateSolidJpeg(string directory, string fileName, int width, int height, Rgba32 color) - { - Directory.CreateDirectory(directory); - var path = Path.Combine(directory, fileName); - using var img = new Image(width, height, color); - var encoder = new JpegEncoder { Quality = 90 }; - img.Save(path, encoder); - return path; - } - - public static string CreateSolidPng(string directory, string fileName, int width, int height, Rgba32 color) - { - Directory.CreateDirectory(directory); - var path = Path.Combine(directory, fileName); - using var img = new Image(width, height, color); - img.SaveAsPng(path); - return path; - } - - public static string CreateJpegWithExifOrientation(string directory, string fileName, int width, int height, Rgba32 color, ushort orientation) - { - Directory.CreateDirectory(directory); - var path = Path.Combine(directory, fileName); - using var img = new Image(width, height, color); - // Add EXIF orientation - var profile = new ExifProfile(); - profile.SetValue(ExifTag.Orientation, orientation); - img.Metadata.ExifProfile = profile; - var encoder = new JpegEncoder { Quality = 90 }; - img.Save(path, encoder); - return path; - } - } -} diff --git a/MaddoShared.ImageSharpTests/MaddoShared.ImageSharpTests.csproj b/MaddoShared.ImageSharpTests/MaddoShared.ImageSharpTests.csproj deleted file mode 100644 index 9d7d59a..0000000 --- a/MaddoShared.ImageSharpTests/MaddoShared.ImageSharpTests.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - net10.0 - latest - enable - enable - false - - - - - - - - - - - - - - - - - - - diff --git a/MaddoShared.ImageSharpTests/Tests/ImageResizingTests.cs b/MaddoShared.ImageSharpTests/Tests/ImageResizingTests.cs deleted file mode 100644 index de10120..0000000 --- a/MaddoShared.ImageSharpTests/Tests/ImageResizingTests.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System.IO; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats.Jpeg; -using SixLabors.ImageSharp.Metadata.Profiles.Exif; -using SixLabors.ImageSharp.PixelFormats; -using MaddoShared.ImageSharpTests.Helpers; -using Shouldly; - -namespace MaddoShared.ImageSharpTests.Tests -{ - [TestClass] - public class ImageResizingTests - { - [TestMethod] - public async Task BigImageResizesRespectSettings() - { - using var ws = new TempWorkspace(); - - // create a large input image - var inputPath = TestImageFactory.CreateSolidJpeg(ws.SourceDir.FullName, "input.jpg", 1600, 1200, new Rgba32(200, 200, 200, 255)); - - var pic = CreatorFactory.CreateDefaultPicSettings(); - pic.LarghezzaBig = 800; - pic.AltezzaBig = 600; - pic.CreaMiniature = false; - - var svc = CreatorFactory.CreateImageCreator(pic); - - var state = new MaddoShared.ImageState - { - WorkFile = new FileInfo(inputPath), - DestDir = ws.DestDir, - SourceDir = ws.SourceDir - }; - - await svc.CreateImageAsync(state, null); - - var outPath = Path.Combine(ws.DestDir.FullName, state.NomeFileBig); - using var outImg = SixLabors.ImageSharp.Image.Load(outPath); - - outImg.Width.ShouldBe(800); - outImg.Height.ShouldBe(600); - } - - [TestMethod] - public async Task RemoveExifData_StripsExifProfileWhenEnabledAndPreservesItWhenDisabled() - { - using var ws = new TempWorkspace(); - var preserveInputPath = CreateJpegWithExifMake(ws.SourceDir.FullName, "preserve.jpg"); - var stripInputPath = CreateJpegWithExifMake(ws.SourceDir.FullName, "strip.jpg"); - - var preserveSettings = CreatorFactory.CreateDefaultPicSettings(); - preserveSettings.RemoveExifData = false; - var preserveCreator = CreatorFactory.CreateImageCreator(preserveSettings); - var preserveState = new MaddoShared.ImageState - { - WorkFile = new FileInfo(preserveInputPath), - DestDir = ws.DestDir - }; - await preserveCreator.CreateImageAsync(preserveState, null); - - var stripSettings = CreatorFactory.CreateDefaultPicSettings(); - stripSettings.RemoveExifData = true; - stripSettings.CreaMiniature = true; - var stripCreator = CreatorFactory.CreateImageCreator(stripSettings); - var stripState = new MaddoShared.ImageState - { - WorkFile = new FileInfo(stripInputPath), - DestDir = ws.DestDir - }; - await stripCreator.CreateImageAsync(stripState, null); - - using var preservedOutput = Image.Load(Path.Combine(ws.DestDir.FullName, preserveState.NomeFileBig)); - var preservedExif = preservedOutput.Metadata.ExifProfile; - preservedExif.ShouldNotBeNull(); - preservedExif.TryGetValue(ExifTag.Make, out var make).ShouldBeTrue(); - make!.Value.ShouldBe("Test camera"); - - using var strippedOutput = Image.Load(Path.Combine(ws.DestDir.FullName, stripState.NomeFileBig)); - strippedOutput.Metadata.ExifProfile.ShouldBeNull(); - - using var strippedThumbnail = Image.Load(Path.Combine(ws.DestDir.FullName, stripState.NomeFileSmall)); - strippedThumbnail.Metadata.ExifProfile.ShouldBeNull(); - } - - private static string CreateJpegWithExifMake(string directory, string fileName) - { - var path = TestImageFactory.CreateSolidJpeg(directory, fileName, 160, 120, new Rgba32(200, 200, 200, 255)); - using var image = Image.Load(path); - var exifProfile = new ExifProfile(); - exifProfile.SetValue(ExifTag.Make, "Test camera"); - image.Metadata.ExifProfile = exifProfile; - image.Save(path, new JpegEncoder { Quality = 90 }); - return path; - } - } -} diff --git a/MaddoShared.ImageSharpTests/Tests/TextPositioningTests.cs b/MaddoShared.ImageSharpTests/Tests/TextPositioningTests.cs deleted file mode 100644 index c93460e..0000000 --- a/MaddoShared.ImageSharpTests/Tests/TextPositioningTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System.IO; -using System.Threading.Tasks; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using SixLabors.ImageSharp.PixelFormats; -using MaddoShared.ImageSharpTests.Helpers; -using Shouldly; - -namespace MaddoShared.ImageSharpTests.Tests -{ - [TestClass] - public class TextPositioningTests - { - [TestMethod] - public async Task TextAtBottom_IncreasesNonBackgroundPixelCountInBottomBand() - { - using var ws = new TempWorkspace(); - - // create white background input - var inputPath = TestImageFactory.CreateSolidJpeg(ws.SourceDir.FullName, "input.jpg", 800, 600, new Rgba32(255, 255, 255, 255)); - - var pic = CreatorFactory.CreateDefaultPicSettings(); - pic.Posizione = "BASSO"; - pic.DimStandard = 48; // big text - pic.TestoFirmaStart = "SAMPLE TEXT"; - pic.CreaMiniature = false; - - var svc = CreatorFactory.CreateImageCreator(pic); - - var state = new MaddoShared.ImageState - { - WorkFile = new FileInfo(inputPath), - DestDir = ws.DestDir, - SourceDir = ws.SourceDir - }; - - await svc.CreateImageAsync(state, null); - - var outPath = Path.Combine(ws.DestDir.FullName, state.NomeFileBig); - - // bottom band (lower 25% of image) - var bottomY = (int)(600 * 0.75); - var bottomCount = PixelInspector.CountNonBackgroundPixels(outPath, 0, bottomY, 800, 600 - bottomY, new Rgba32(255, 255, 255, 255), tolerance: 10); - - // top band (upper 25%) - var topCount = PixelInspector.CountNonBackgroundPixels(outPath, 0, 0, 800, (int)(600 * 0.25), new Rgba32(255, 255, 255, 255), tolerance: 10); - - (bottomCount > 50).ShouldBeTrue($"Expected text pixels in bottom band, found {bottomCount}"); - (bottomCount > topCount).ShouldBeTrue("Expected more non-background pixels at bottom than top"); - } - } -} diff --git a/MaddoShared.Tests/DataModelCharacterizationTests.cs b/MaddoShared.Tests/DataModelCharacterizationTests.cs deleted file mode 100644 index 6e8c82c..0000000 --- a/MaddoShared.Tests/DataModelCharacterizationTests.cs +++ /dev/null @@ -1,462 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; -using ImageCatalog_2; -using ImageCatalog_2.Services; -using MaddoShared; -using Microsoft.Extensions.Logging; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NSubstitute; -using Shouldly; - -namespace MaddoShared.Tests; - -[TestClass] -public class DataModelCharacterizationTests -{ - [TestMethod] - public void SelectSourceFolderCommand_RaisesEvent() - { - var model = CreateModel(); - var raised = false; - model.SelectSourceFolderRequested += (_, _) => raised = true; - - model.SelectSourceFolderCommand.Execute(null); - - raised.ShouldBeTrue(); - } - - [TestMethod] - public async Task SaveSettingsToFileAsync_DelegatesToSettingsService() - { - var settingsService = Substitute.For(); - settingsService - .SaveSettingsAsync(Arg.Any(), Arg.Any()) - .Returns(Task.CompletedTask); - - var model = CreateModel(settingsService: settingsService); - - await model.SaveSettingsToFileAsync("settings.xml"); - - await settingsService.Received(1) - .SaveSettingsAsync("settings.xml", model); - } - - [TestMethod] - public async Task LoadSettingsFromFileAsync_DelegatesToSettingsService() - { - var settingsService = Substitute.For(); - settingsService - .LoadSettingsAsync(Arg.Any(), Arg.Any()) - .Returns(Task.CompletedTask); - - var model = CreateModel(settingsService: settingsService); - - await model.LoadSettingsFromFileAsync("settings.xml"); - - await settingsService.Received(1) - .LoadSettingsAsync("settings.xml", model); - } - - [TestMethod] - public void ThumbnailOptionIndex_UpdatesAuthoritativeThumbnailState() - { - var model = CreateModel(); - - model.ThumbnailOptionIndex = (int)DataModel.ThumbnailOptionEnum.RaceTime; - - model.ThumbnailOption.ShouldBe(DataModel.ThumbnailOptionEnum.RaceTime); - model.AddRaceTimeToThumbnails.ShouldBeTrue(); - model.ThumbnailMode.ShouldBe("RaceTime"); - } - - [TestMethod] - public void ProcessingChildChange_RaisesDataModelPropertyChanged() - { - var model = CreateModel(); - string? changed = null; - model.PropertyChanged += (_, args) => changed = args.PropertyName; - - model.Processing.SpeedCounter = "12.00 f/s"; - - changed.ShouldBe(nameof(DataModel.SpeedCounter)); - model.SpeedCounter.ShouldBe("12.00 f/s"); - } - - [TestMethod] - public void PathsNormalize_UpdatesFlattenedSourceAndDestination() - { - var model = CreateModel(); - model.SourcePath = "\"C:/input\""; - model.DestinationPath = "C:/output"; - - model.Paths.NormalizePaths(); - - model.SourcePath.ShouldBe($"C:{System.IO.Path.DirectorySeparatorChar}input{System.IO.Path.DirectorySeparatorChar}"); - model.DestinationPath.ShouldBe($"C:{System.IO.Path.DirectorySeparatorChar}output{System.IO.Path.DirectorySeparatorChar}"); - } - - [TestMethod] - public void DestinationPathChange_UpdatesAiCsvFileNameToMatchFinalFolderSegment() - { - var model = CreateModel(); - model.CsvOutputPath = @"K:\various\catalogtest\aioutput\test2.csv"; - - model.DestinationPath = @"K:\various\catalogtest\Dest\03.KM_8_A\"; - - model.CsvOutputPath.ShouldBe(@"K:\various\catalogtest\aioutput\03.KM_8_A.csv"); - } - - [TestMethod] - public async Task ConfirmAiCsvOverwriteIfNeededAsync_CanCancelWhenCsvAlreadyExists() - { - using var tempDirectory = new TemporaryDirectory(); - var csvPath = Path.Combine(tempDirectory.Path, "existing.csv"); - File.WriteAllText(csvPath, "existing"); - - var model = CreateModel(); - model.CsvOutputPath = csvPath; - - string? requestedTitle = null; - string? requestedMessage = null; - model.ConfirmAiCsvOverwriteAsync = (title, message) => - { - requestedTitle = title; - requestedMessage = message; - return Task.FromResult(false); - }; - - var shouldContinue = await model.ConfirmAiCsvOverwriteIfNeededAsync(); - - shouldContinue.ShouldBeFalse(); - requestedTitle.ShouldBe("File CSV gia esistente"); - requestedMessage.ShouldNotBeNull(); - requestedMessage.ShouldContain("Vuoi sovrascriverlo?"); - requestedMessage.ShouldContain(csvPath); - } - - [TestMethod] - public void AiChildChange_RaisesDataModelPropertyChanged() - { - var model = CreateModel(); - string? changed = null; - model.PropertyChanged += (_, args) => changed = args.PropertyName; - - model.Ai.ModelsFolderPath = "K:/models"; - - changed.ShouldBe(nameof(DataModel.ModelsFolderPath)); - model.ModelsFolderPath.ShouldBe("K:/models"); - } - - [TestMethod] - public void NumberAiGpuChildChange_RaisesDataModelPropertyChanged() - { - var model = CreateModel(); - string? changed = null; - model.PropertyChanged += (_, args) => changed = args.PropertyName; - - model.Ai.UseNumberAiGpu = true; - - changed.ShouldBe(nameof(DataModel.UseNumberAiGpu)); - model.UseNumberAiGpu.ShouldBeTrue(); - } - - [TestMethod] - public void NumberAiThumbnails_DefaultsOffAndRaisesDataModelPropertyChanged() - { - var model = CreateModel(); - model.IncludeNumberAiThumbnails.ShouldBeFalse(); - - string? changed = null; - model.PropertyChanged += (_, args) => changed = args.PropertyName; - - model.Ai.IncludeNumberAiThumbnails = true; - - changed.ShouldBe(nameof(DataModel.IncludeNumberAiThumbnails)); - model.IncludeNumberAiThumbnails.ShouldBeTrue(); - } - - [TestMethod] - public void NumberAiWorkload_DefaultsToThreeAndClampsToFive() - { - var model = CreateModel(); - model.NumberAiWorkloadLevel.ShouldBe(3); - - string? changed = null; - model.PropertyChanged += (_, args) => changed = args.PropertyName; - - model.NumberAiWorkloadLevel = 99; - - changed.ShouldBe(nameof(DataModel.NumberAiWorkloadLevel)); - model.NumberAiWorkloadLevel.ShouldBe(3); - - model.Ai.NumberAiWorkloadLevel = 5; - model.NumberAiWorkloadLevel.ShouldBe(5); - } - - [TestMethod] - public void CommandLineOperationRunner_DetectsHeadlessRequest() - { - CommandLineOperationRunner.IsHeadlessRequest(["--config", "settings.xml", "--operation", "number-ai"]).ShouldBeTrue(); - CommandLineOperationRunner.IsHeadlessRequest(["--config=settings.xml", "--operation=number-ai"]).ShouldBeTrue(); - CommandLineOperationRunner.IsHeadlessRequest([]).ShouldBeFalse(); - } - - [TestMethod] - public void RaceUploadChildChange_RaisesDataModelPropertyChanged() - { - var model = CreateModel(); - string? changed = null; - model.PropertyChanged += (_, args) => changed = args.PropertyName; - - model.RaceUpload.ApiLogin = "admin"; - - changed.ShouldBe(nameof(DataModel.ApiLogin)); - model.ApiLogin.ShouldBe("admin"); - } - - [TestMethod] - public void VisualChildChange_RaisesDataModelPropertyChanged() - { - var model = CreateModel(); - string? changed = null; - model.PropertyChanged += (_, args) => changed = args.PropertyName; - - model.Visual.FontSize = 42; - - changed.ShouldBe(nameof(DataModel.FontSize)); - model.FontSize.ShouldBe(42); - } - - [TestMethod] - public void FaceExecutableFolder_EnablesGpuToggleWhenBothVariantsExist() - { - using var root = new TemporaryDirectory(); - CreateFaceEncoderExecutable(root.Path, "cpu"); - CreateFaceEncoderExecutable(root.Path, "gpu"); - - var model = CreateModel(); - - model.FaceExecutablePath = root.Path; - - model.FaceGpuOptionEnabled.ShouldBeTrue(); - model.UseFaceGpu.ShouldBeFalse(); - } - - [TestMethod] - public void UseFaceGpu_UpdatesUpsampleWhenUsingRecommendedDefault() - { - using var root = new TemporaryDirectory(); - CreateFaceEncoderExecutable(root.Path, "cpu"); - CreateFaceEncoderExecutable(root.Path, "gpu"); - - var model = CreateModel(); - model.FaceExecutablePath = root.Path; - model.FaceUpsample.ShouldBeTrue(); - - model.UseFaceGpu = true; - - model.FaceUpsample.ShouldBeFalse(); - } - - [TestMethod] - public void ResolveConfiguredFaceEncoderExecutablePath_UsesFolderLayoutFromPowerShellScript() - { - using var root = new TemporaryDirectory(); - var cpuExecutable = CreateFaceEncoderExecutable(root.Path, "cpu"); - var gpuExecutable = CreateFaceEncoderExecutable(root.Path, "gpu"); - - DataModel.ResolveConfiguredFaceEncoderExecutablePath(root.Path, useGpu: false).ShouldBe(cpuExecutable); - DataModel.ResolveConfiguredFaceEncoderExecutablePath(root.Path, useGpu: true).ShouldBe(gpuExecutable); - } - - [TestMethod] - public void BuildFaceEncoderOutputPaths_UsesTimestampAndSanitizedFolderName() - { - var timestamp = new DateTime(2026, 5, 9, 14, 30, 45); - var output = DataModel.BuildFaceEncoderOutputPaths( - @"C:\out", - @"C:\images\04 APRILE: gara?", - timestamp); - - output.OutputFilePath.ShouldBe(@"C:\out\face_encodings_20260509_143045_04_APRILE_gara.pkl"); - output.LogFilePath.ShouldBe(@"C:\out\encoder_log_20260509_143045_04_APRILE_gara.txt"); - } - - [TestMethod] - public void FaceUploadPath_ValidatesExpectedRelativePathShape() - { - DataModel.IsValidFaceUploadPath("2026/05.MAGGIO/EMPOLI").ShouldBeTrue(); - DataModel.IsValidFaceUploadPath("2026/5.MAGGIO/EMPOLI").ShouldBeFalse(); - DataModel.IsValidFaceUploadPath("2026/00.MAGGIO/EMPOLI").ShouldBeFalse(); - DataModel.IsValidFaceUploadPath("2026/13.MAGGIO/EMPOLI").ShouldBeFalse(); - DataModel.IsValidFaceUploadPath("2026/05.MAGGIO").ShouldBeFalse(); - - DataModel.CombineRemoteUploadPath("/mnt/da1/foto/", "2026/05.MAGGIO/EMPOLI") - .ShouldBe("/mnt/da1/foto/2026/05.MAGGIO/EMPOLI"); - } - - [TestMethod] - public void FaceUploadCommand_IsEnabledOnlyForValidUploadPath() - { - var model = CreateModel(); - - model.UploadFaceEncoderOutputCommand.CanExecute(null).ShouldBeFalse(); - - model.FaceUploadPath = "2026/05.MAGGIO/EMPOLI"; - model.UploadFaceEncoderOutputCommand.CanExecute(null).ShouldBeTrue(); - - model.FaceUploadPath = "2026/5.MAGGIO/EMPOLI"; - model.UploadFaceEncoderOutputCommand.CanExecute(null).ShouldBeFalse(); - } - - [TestMethod] - public void FaceSshPreferences_AreStoredInUserPreferences() - { - using var tempDirectory = new TemporaryDirectory(); - var preferencesFile = Path.Combine(tempDirectory.Path, "userprefs.xml"); - var preferenceService = new PickerPreferenceService(new ImageCatalog.ParametriSetup(preferencesFile)); - - var model = CreateModel(pickerPreferenceService: preferenceService); - model.FaceSshUsername = "ssh-user"; - model.FaceSshPassword = "ssh-password"; - model.FaceSshAddress = "upload.example.org"; - model.FaceSshPort = "2222"; - model.FaceSshPathA = "/mnt/da1/foto/"; - model.FaceSshPathB = "/mnt/nas12/foto/"; - model.FaceUploadDryRun = true; - - var reloadedPreferenceService = new PickerPreferenceService(new ImageCatalog.ParametriSetup(preferencesFile)); - var reloaded = CreateModel(pickerPreferenceService: reloadedPreferenceService); - - reloaded.FaceSshUsername.ShouldBe("ssh-user"); - reloaded.FaceSshPassword.ShouldBe("ssh-password"); - reloaded.FaceSshAddress.ShouldBe("upload.example.org"); - reloaded.FaceSshPort.ShouldBe("2222"); - reloaded.FaceSshPathA.ShouldBe("/mnt/da1/foto/"); - reloaded.FaceSshPathB.ShouldBe("/mnt/nas12/foto/"); - reloaded.FaceUploadDryRun.ShouldBeTrue(); - } - - [TestMethod] - public void ResolveLatestFaceUploadSourceFile_UsesLatestPklForCurrentRace() - { - using var tempDirectory = new TemporaryDirectory(); - var outputFolder = Path.Combine(tempDirectory.Path, "out"); - var currentRaceFolder = Path.Combine(tempDirectory.Path, "04 APRILE gara"); - Directory.CreateDirectory(outputFolder); - Directory.CreateDirectory(currentRaceFolder); - - var olderCurrentRace = Path.Combine(outputFolder, "face_encodings_20260509_143045_04_APRILE_gara.pkl"); - var newerCurrentRace = Path.Combine(outputFolder, "face_encodings_20260509_153045_04_APRILE_gara.pkl"); - var otherRace = Path.Combine(outputFolder, "face_encodings_20260509_163045_05_MAGGIO_gara.pkl"); - - File.WriteAllText(olderCurrentRace, "old"); - File.WriteAllText(newerCurrentRace, "new"); - File.WriteAllText(otherRace, "other"); - - File.SetLastWriteTimeUtc(olderCurrentRace, new DateTime(2026, 5, 9, 14, 30, 45, DateTimeKind.Utc)); - File.SetLastWriteTimeUtc(newerCurrentRace, new DateTime(2026, 5, 9, 15, 30, 45, DateTimeKind.Utc)); - File.SetLastWriteTimeUtc(otherRace, new DateTime(2026, 5, 9, 16, 30, 45, DateTimeKind.Utc)); - - var selected = DataModel.ResolveLatestFaceUploadSourceFile(outputFolder, currentRaceFolder); - - selected.ShouldBe(newerCurrentRace); - } - - [TestMethod] - public async Task SettingsService_PersistsFaceUploadPathButNotSshPreferences() - { - using var tempDirectory = new TemporaryDirectory(); - var settingsFile = Path.Combine(tempDirectory.Path, "settings.xml"); - var userPreferencesFile = Path.Combine(tempDirectory.Path, "userprefs.xml"); - var preferenceService = new PickerPreferenceService(new ImageCatalog.ParametriSetup(userPreferencesFile)); - var settingsService = new SettingsService( - new ImageCatalog.ParametriSetup(Path.Combine(tempDirectory.Path, "unused.xml")), - Substitute.For>()); - var model = CreateModel(settingsService: settingsService, pickerPreferenceService: preferenceService); - - model.FaceUploadPath = "2026/05.MAGGIO/EMPOLI"; - model.FaceSshUsername = "ssh-user"; - - await settingsService.SaveSettingsAsync(settingsFile, model); - - var xml = File.ReadAllText(settingsFile); - xml.ShouldContain("AI_FaceUploadPath"); - xml.ShouldContain("2026/05.MAGGIO/EMPOLI"); - xml.ShouldNotContain("AI_FaceUploadDryRun"); - xml.ShouldNotContain("FaceAI.Ssh"); - xml.ShouldNotContain("ssh-user"); - - var loaded = CreateModel(settingsService: settingsService); - await settingsService.LoadSettingsAsync(settingsFile, loaded); - loaded.FaceUploadPath.ShouldBe("2026/05.MAGGIO/EMPOLI"); - } - - private static DataModel CreateModel( - ISettingsService? settingsService = null, - ITestService? testService = null, - PickerPreferenceService? pickerPreferenceService = null) - { - var mapper = Substitute.For(); - var picSettings = new PicSettings(); - - var imageCreator = Substitute.For(); - imageCreator - .CreateImageAsync(Arg.Any(), Arg.Any()) - .Returns(Task.CompletedTask); - - var imageCreationService = new ImageCreationService( - Substitute.For>(), - picSettings, - imageCreator); - - var imageProcessingCoordinator = new ImageProcessingCoordinator( - imageCreationService, - Substitute.For>()); - - var aiExtractionService = new AiExtractionService( - Substitute.For>()); - - return new DataModel( - testService ?? Substitute.For(), - settingsService ?? Substitute.For(), - imageCreationService, - aiExtractionService, - imageProcessingCoordinator, - picSettings, - mapper, - Substitute.For>(), - versionProvider: null, - pickerPreferenceService: pickerPreferenceService); - } - - private static string CreateFaceEncoderExecutable(string rootPath, string variant) - { - var variantDirectory = Path.Combine(rootPath, $"face_encoder_{variant}"); - Directory.CreateDirectory(variantDirectory); - - var executablePath = Path.Combine(variantDirectory, $"face_encoder_{variant}.exe"); - File.WriteAllText(executablePath, "stub"); - return executablePath; - } - - private sealed class TemporaryDirectory : IDisposable - { - public TemporaryDirectory() - { - Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()); - Directory.CreateDirectory(Path); - } - - public string Path { get; } - - public void Dispose() - { - if (Directory.Exists(Path)) - { - Directory.Delete(Path, recursive: true); - } - } - } -} diff --git a/MaddoShared.Tests/ImageCreatorSharpTests.cs b/MaddoShared.Tests/ImageCreatorSharpTests.cs index 546a7de..d053452 100644 --- a/MaddoShared.Tests/ImageCreatorSharpTests.cs +++ b/MaddoShared.Tests/ImageCreatorSharpTests.cs @@ -1,63 +1,232 @@ +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; using System.Reflection; -using MaddoShared; using Microsoft.VisualStudio.TestTools.UnitTesting; -using Shouldly; -using SixLabors.ImageSharp; +using Microsoft.Extensions.Logging; +using Moq; +using FluentAssertions; +using MaddoShared; -namespace MaddoShared.Tests; - -[TestClass] -public class ImageCreatorSharpTests +namespace MaddoShared.Tests { - [TestMethod] - public void CalculateThumbnailSize_Larghezza_UsesWidthScaling() + [TestClass] + public class ImageCreatorSharpTests { - var size = CalculateThumbnailSize(400, 200, 200, "Larghezza"); - - size.Width.ShouldBe(200); - size.Height.ShouldBe(100); - } - - [TestMethod] - public void CalculateThumbnailSize_Altezza_UsesHeightScaling() - { - var size = CalculateThumbnailSize(200, 400, 200, "Altezza"); - - size.Width.ShouldBe(100); - size.Height.ShouldBe(200); - } - - [TestMethod] - public void FindBestFontSize_ConstrainsTextToBounds() - { - const string text = "A very long text that will not fit at the requested size"; - var method = typeof(ImageCreatorImageSharp).GetMethod( - "FindBestFontSize", - BindingFlags.NonPublic | BindingFlags.Static); - - method.ShouldNotBeNull(); - - var size = (float)method.Invoke(null, new object[] + private ImageCreatorSharp CreateService(Action customize = null) { - text, - "Arial", - 40, - 50f, - 20f, - 6 - })!; + var settings = new PicSettings + { + DimStandard = 20, + DimStandardMiniatura = 10, + LarghezzaSmall = 100, + AltezzaSmall = 100, + LarghezzaBig = 800, + AltezzaBig = 600, + Trasparenza = 50, + IlFont = "Arial", + Grassetto = false, + Posizione = "CENTRO", + Allineamento = "CENTRO", + Margine = 10, + MargVert = 10, + TestoMin = false, + AggNumTempMin = false + }; - size.ShouldBeInRange(6f, 40f); - (size * text.Length * 0.6f <= 50f || size <= 6f).ShouldBeTrue(); - } + customize?.Invoke(settings); - private static Size CalculateThumbnailSize(int width, int height, int maxPixel, string sizeMode) - { - var method = typeof(ImageCreatorImageSharp).GetMethod( - "CalculateThumbnailSize", - BindingFlags.NonPublic | BindingFlags.Static); + var logger = new Mock>().Object; + return new ImageCreatorSharp(settings, logger); + } - method.ShouldNotBeNull(); - return (Size)method.Invoke(null, new object[] { width, height, maxPixel, sizeMode })!; + [TestMethod] + public void CalculateThumbnailSize_Larghezza_UsesWidthScaling() + { + var svc = CreateService(); + var mi = svc.GetType().GetMethod("CalculateThumbnailSize", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Should().NotBeNull(); + + var size = (Size)mi.Invoke(svc, new object[] { 400, 200, 200, "Larghezza" }); + + size.Width.Should().Be(200); + size.Height.Should().Be(100); + } + + [TestMethod] + public void CalculateThumbnailSize_Altezza_UsesHeightScaling() + { + var svc = CreateService(); + var mi = svc.GetType().GetMethod("CalculateThumbnailSize", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Should().NotBeNull(); + + var size = (Size)mi.Invoke(svc, new object[] { 200, 400, 200, "Altezza" }); + + size.Width.Should().Be(100); + size.Height.Should().Be(200); + } + + [TestMethod] + public void IsSameDirectory_IsCaseInsensitive() + { + var svc = CreateService(); + var mi = svc.GetType().GetMethod("IsSameDirectory", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Should().NotBeNull(); + + bool same = (bool)mi.Invoke(svc, new object[] { @"C:\Temp", @"c:\temp" }); + same.Should().BeTrue(); + + bool notSame = (bool)mi.Invoke(svc, new object[] { @"C:\TempA", @"c:\temp" }); + notSame.Should().BeFalse(); + } + + [TestMethod] + public void UpdateFilenameWithCode_InsertsCodeBeforeExtension() + { + var svc = CreateService(s => s.Codice = "_X"); + var mi = svc.GetType().GetMethod("UpdateFilenameWithCode", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Should().NotBeNull(); + + var state = new ImageState { NomeFileSmall = "photo123.jpg" }; + mi.Invoke(svc, new object[] { state }); + + state.NomeFileSmall.Should().Be("photo123_X.jpg"); + } + + [DataTestMethod] + [DataRow("SINISTRA")] + [DataRow("CENTRO")] + [DataRow("DESTRA")] + public void CalculateHorizontalAlignment_RespectsAlignment(string alignment) + { + var svc = CreateService(s => { s.Allineamento = alignment; s.Margine = 20; }); + + var mi = svc.GetType().GetMethod("CalculateHorizontalAlignment", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Should().NotBeNull(); + + var center = (float)mi.Invoke(svc, new object[] { 800, 100f }); + + if (alignment == "SINISTRA") + center.Should().BeInRange(0f, 400f, "Expected left alignment range"); + if (alignment == "DESTRA") + center.Should().BeInRange(400f, 800f, "Expected right alignment range"); + if (alignment == "CENTRO") + center.Should().BeApproximately(800 / 2f, 0.0001f); + } + + [TestMethod] + public void SetVerticalPosition_AltoAndBasso_SetExpectedValues() + { + var svc = CreateService(s => s.Posizione = "ALTO"); + var mi = svc.GetType().GetMethod("SetVerticalPosition", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Should().NotBeNull(); + + var state = new ImageState(); + + // ALTO + mi.Invoke(svc, new object[] { 500, 20f, state }); + state.YPosFromBottom1.Should().Be(10f); + state.YPosFromBottom4.Should().Be(10f); + + // BASSO + state = new ImageState(); + svc = CreateService(s => { s.Posizione = "BASSO"; s.Margine = 10; s.MargVert = 5; }); + mi = svc.GetType().GetMethod("SetVerticalPosition", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Invoke(svc, new object[] { 200, 20f, state }); + + var expected1 = (float)(200 - 20 - (200 * 10 / 100.0)); + var expected4 = (float)(200 - 20 - (200 * 5 / 100.0)); + state.YPosFromBottom1.Should().BeApproximately(expected1, 0.001f); + state.YPosFromBottom4.Should().BeApproximately(expected4, 0.001f); + } + + [TestMethod] + public void FormatTimeText_WithAndWithoutFileName_ProducesExpectedStrings() + { + var svc = CreateService(); + var mi = svc.GetType().GetMethod("FormatTimeText", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Should().NotBeNull(); + + var state = new ImageState + { + NomeFileBig = "file.jpg", + TestoOrario = "T:", + DataPartenzaI = new DateTime(2024, 01, 01, 12, 0, 0), + DataFoto = new DateTime(2024, 01, 01, 11, 59, 0) + }; + var withoutName = (string)mi.Invoke(svc, new object[] { state, false }); + withoutName.Should().StartWith(Environment.NewLine); + withoutName.Should().Contain("T:"); + + var withName = (string)mi.Invoke(svc, new object[] { state, true }); + withName.Should().Contain("file.jpg"); + withName.Should().Contain("T:"); + withName.Should().Contain(Environment.NewLine); + } + + [TestMethod] + public void PrepareSignatureText_SetsSmallSignature_AccordingFlags() + { + var svc = CreateService(); + var miPrep = svc.GetType().GetMethod("PrepareSignatureText", BindingFlags.NonPublic | BindingFlags.Instance); + miPrep.Should().NotBeNull(); + + var state = new ImageState { NomeFileBig = "bigname.jpg" }; + + svc = CreateService(s => s.TestoMin = true); + miPrep.Invoke(svc, new object[] { state }); + state.TestoFirmaPiccola.Should().Be("bigname.jpg"); + + state.TestoFirmaPiccola = ""; + svc = CreateService(s => { s.TestoMin = false; s.AggNumTempMin = true; }); + miPrep.Invoke(svc, new object[] { state }); + state.TestoFirmaPiccola.Should().Be("bigname.jpg "); + } + + [TestMethod] + public void ShouldRenderText_ReturnsCorrectFlag() + { + var svc = CreateService(s => { s.UsaOrarioMiniatura = false; s.TestoMin = false; s.AggTempoGaraMin = false; s.AggNumTempMin = false; }); + var mi = svc.GetType().GetMethod("ShouldRenderText", BindingFlags.NonPublic | BindingFlags.Instance); + mi.Should().NotBeNull(); + + var res = (bool)mi.Invoke(svc, Array.Empty()); + res.Should().BeFalse(); + + svc = CreateService(s => s.TestoMin = true); + mi = svc.GetType().GetMethod("ShouldRenderText", BindingFlags.NonPublic | BindingFlags.Instance); + res = (bool)mi.Invoke(svc, Array.Empty()); + res.Should().BeTrue(); + } + + [TestMethod] + public void FindBestFontSize_And_AdjustFontToFitWidth_ModifySizes() + { + var svc = CreateService(s => { s.IlFont = "Arial"; s.DimStandardMiniatura = 30; }); + + using var bmp = new Bitmap(400, 100); + using var g = Graphics.FromImage(bmp); + + var miFind = svc.GetType().GetMethod("FindBestFontSize", BindingFlags.NonPublic | BindingFlags.Instance); + miFind.Should().NotBeNull(); + + int best = (int)miFind.Invoke(svc, new object[] { g, "A very long text that won't fit", "Arial", 40, false, 50, 5 }); + best.Should().BeInRange(5, 40); + + var miAdjust = svc.GetType().GetMethod("AdjustFontToFitWidth", BindingFlags.NonPublic | BindingFlags.Instance); + miAdjust.Should().NotBeNull(); + + var imageState = new ImageState { DimensioneStandardMiniatura = 30, TestoFirmaPiccola = "A very long test string" }; + var initialFont = new Font("Arial", imageState.DimensioneStandardMiniatura); + var textSize = g.MeasureString(imageState.TestoFirmaPiccola, initialFont); + + object[] parameters = new object[] { g, 50, imageState, textSize }; + miAdjust.Invoke(svc, parameters); + + var updatedSize = (SizeF)parameters[3]; + imageState.DimensioneStandardMiniatura.Should().BeLessThanOrEqualTo(30); + (updatedSize.Width <= 50 || imageState.DimensioneStandardMiniatura <= 5).Should().BeTrue(); + } } } diff --git a/MaddoShared.Tests/MaddoShared.Tests.csproj b/MaddoShared.Tests/MaddoShared.Tests.csproj index 0060244..b2f98b7 100644 --- a/MaddoShared.Tests/MaddoShared.Tests.csproj +++ b/MaddoShared.Tests/MaddoShared.Tests.csproj @@ -15,13 +15,13 @@ - - - + + + + - diff --git a/MaddoShared.Tests/PickerPreferenceServiceTests.cs b/MaddoShared.Tests/PickerPreferenceServiceTests.cs deleted file mode 100644 index f0fe3d0..0000000 --- a/MaddoShared.Tests/PickerPreferenceServiceTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.IO; -using ImageCatalog; -using ImageCatalog_2.Services; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Shouldly; - -namespace MaddoShared.Tests; - -[TestClass] -public class PickerPreferenceServiceTests -{ - [TestMethod] - public void RememberValue_PersistsExactFilePath() - { - using var tempDirectory = new TemporaryDirectory(); - var preferencesFile = Path.Combine(tempDirectory.Path, "userprefs.xml"); - var service = new PickerPreferenceService(new ParametriSetup(preferencesFile)); - var settingsFile = Path.Combine(tempDirectory.Path, "nested", "settings.xml"); - - service.RememberValue(PickerPreferenceKeys.LastSettingsFile, settingsFile); - - service.GetRememberedValue(PickerPreferenceKeys.LastSettingsFile).ShouldBe(settingsFile); - } - - [TestMethod] - public void ForgetValue_RemovesStoredPreference() - { - using var tempDirectory = new TemporaryDirectory(); - var preferencesFile = Path.Combine(tempDirectory.Path, "userprefs.xml"); - var service = new PickerPreferenceService(new ParametriSetup(preferencesFile)); - - service.RememberValue(PickerPreferenceKeys.LastSettingsFile, Path.Combine(tempDirectory.Path, "settings.xml")); - - service.ForgetValue(PickerPreferenceKeys.LastSettingsFile); - - service.GetRememberedValue(PickerPreferenceKeys.LastSettingsFile).ShouldBeNull(); - } - - private sealed class TemporaryDirectory : IDisposable - { - public TemporaryDirectory() - { - Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()); - Directory.CreateDirectory(Path); - } - - public string Path { get; } - - public void Dispose() - { - if (Directory.Exists(Path)) - { - Directory.Delete(Path, recursive: true); - } - } - } -} \ No newline at end of file diff --git a/MaddoShared.Tests/Test1.cs b/MaddoShared.Tests/Test1.cs index d8dc33b..cd00c92 100644 --- a/MaddoShared.Tests/Test1.cs +++ b/MaddoShared.Tests/Test1.cs @@ -1,69 +1,11 @@ -using ImageCatalog_2.Services; -using ImageCatalog_2.Models; -using Shouldly; -using System.Text; - -namespace MaddoShared.Tests; - -[TestClass] -public sealed class AiExtractionServiceCsvTests +namespace MaddoShared.Tests { - [TestMethod] - public void WriteCsvOutput_UsesLegacyCompatibleQuotingAndSkipsEmptyResults() + [TestClass] + public sealed class Test1 { - using var tempDir = new TempDirectory(); - var csvPath = Path.Combine(tempDir.Path, "ocr.csv"); - - AiExtractionService.WriteCsvOutput( - csvPath, - [ - new AiResultItem { Path = @"C:\images\IMG_7146.JPG", Text = "43" }, - new AiResultItem { Path = @"C:\images\IMG_7207.JPG", Text = "43,84,61" }, - new AiResultItem { Path = @"C:\images\IMG_7208.JPG", Text = string.Empty }, - new AiResultItem { Path = @"C:\images\IMG_7209.JPG", Text = " " }, - new AiResultItem { Path = @"C:\images\IMG_7210.JPG", Text = "a\"b,c" } - ]); - - var csv = File.ReadAllText(csvPath, Encoding.UTF8); - - csv.ShouldBe("filename,text\r" - + "IMG_7146.JPG,43\r" - + "IMG_7207.JPG,\"43,84,61\"\r" - + "IMG_7210.JPG,\"a\"\"b,c\"\r"); - } - - [TestMethod] - public void WriteCsvOutput_WritesUtf8WithoutBom() - { - using var tempDir = new TempDirectory(); - var csvPath = Path.Combine(tempDir.Path, "ocr.csv"); - - AiExtractionService.WriteCsvOutput( - csvPath, - [new AiResultItem { Path = @"C:\images\IMG_7146.JPG", Text = "43" }]); - - var bytes = File.ReadAllBytes(csvPath); - - bytes[.."filename,text\r".Length].ShouldBe(Encoding.ASCII.GetBytes("filename,text\r")); - bytes[..3].ShouldNotBe(new byte[] { 0xEF, 0xBB, 0xBF }); - } - - private sealed class TempDirectory : IDisposable - { - public TempDirectory() + [TestMethod] + public void TestMethod1() { - Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName()); - Directory.CreateDirectory(Path); - } - - public string Path { get; } - - public void Dispose() - { - if (Directory.Exists(Path)) - { - Directory.Delete(Path, recursive: true); - } } } } diff --git a/MaddoShared.backup/FileData.cs b/MaddoShared.backup/FileData.cs new file mode 100644 index 0000000..37bd735 --- /dev/null +++ b/MaddoShared.backup/FileData.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MaddoShared +{ + public class FileData + { + /// + /// Il file originale + /// + public FileInfo File { get; set; } + /// + /// La cartella di destinazione + /// + public DirectoryInfo Directory { get; set; } + + public FileData(FileInfo newFile, DirectoryInfo newDirectory) + { + this.File = newFile; + this.Directory = newDirectory; + } + } +} diff --git a/MaddoShared.backup/FileHelperSharp.cs b/MaddoShared.backup/FileHelperSharp.cs new file mode 100644 index 0000000..905999e --- /dev/null +++ b/MaddoShared.backup/FileHelperSharp.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MaddoShared +{ + public class FileHelperOptions + { + public bool SeparateFiles { get; set; } + public NumerazioneType NumerationType { get; set; } + public int CounterSize { get; set; } + public string Suffix { get; set; } + public int FilesPerFolder { get; set; } + } + public enum NumerazioneType + { + Progressiva, + Files + } + public class FileHelperSharp + { + + public List GetFilesRecursive(DirectoryInfo root, DirectoryInfo destRoot, string filter, FileHelperOptions options) + { + ConcurrentDictionary dirSourceDest = new ConcurrentDictionary(); + List result = new List(); + + // Dim stack As New Stack(Of DirectoryInfo) + Stack> stack = new Stack>(); + + + + KeyValuePair pair = new KeyValuePair(); + + + // stack.Push(root) + stack.Push(new KeyValuePair(root, destRoot)); + + while ((stack.Count > 0)) + { + KeyValuePair curDirKV = stack.Pop(); + // curDirKP = stack.Pop() + DirectoryInfo dir = curDirKV.Key; + DirectoryInfo dDir = curDirKV.Value; + try + { + // result.AddRange(dir.GetFiles(filter, SearchOption.TopDirectoryOnly)) + // dividere file qui + if (options.FilesPerFolder > 0 & options.SeparateFiles) + AppendDictionaryConcurrent(dirSourceDest, DividiFilesInDirConcurrent(dir, dDir, options, filter)); + else + AppendDictionaryConcurrent(dirSourceDest, DividiFilesInDirConcurrent(dir, dDir, options, filter)); + + foreach (DirectoryInfo subDirectory in dir.GetDirectories()) + stack.Push(new KeyValuePair(subDirectory, new DirectoryInfo(Path.Combine(dDir.FullName, subDirectory.Name)))); + } + catch (Exception ex) + { + // TODO ERROR + } + } + + List resultData = new List(); + resultData.AddRange(from p in dirSourceDest + select new FileData(p.Key, p.Value)); + return resultData; + } + + public ConcurrentDictionary AppendDictionaryConcurrent(ConcurrentDictionary dictA, ConcurrentDictionary dictB) + { + foreach (KeyValuePair pair in dictB) + dictA.TryAdd(pair.Key, pair.Value); + return dictA; + } + + + private ConcurrentDictionary DividiFilesInDirConcurrent(DirectoryInfo dir, DirectoryInfo dirDest, FileHelperOptions options, string filter) + { + //int filesCount = dir.GetFiles(Filter).Length; + int contaFilePerDir = 0; + int contaDirPerDir = 0; + string tempText;// = string.Empty; + ConcurrentDictionary foldersDict = new ConcurrentDictionary(); + + DirectoryInfo destDir; + destDir = new DirectoryInfo(Path.Combine(dirDest.FullName)); + foreach (FileInfo file in dir.GetFiles(filter)) + { + contaFilePerDir += 1; + + if (contaFilePerDir == (contaDirPerDir * options.FilesPerFolder) + 1) + { + contaDirPerDir += 1; + + tempText = options.NumerationType == NumerazioneType.Progressiva ? contaDirPerDir.ToString() : (contaDirPerDir * options.FilesPerFolder).ToString(); + int i; + for (i = 1; i <= (options.CounterSize - tempText.Length); i++) + tempText = "0" + tempText; + destDir = new DirectoryInfo(Path.Combine(dirDest.FullName, options.Suffix + tempText)); + } + + if (!destDir.Exists) + destDir.Create(); + + foldersDict.TryAdd(file, destDir); + } + + return foldersDict; + } + + } +} diff --git a/MaddoShared.backup/ImageCreationStuff.cs b/MaddoShared.backup/ImageCreationStuff.cs new file mode 100644 index 0000000..439f3dc --- /dev/null +++ b/MaddoShared.backup/ImageCreationStuff.cs @@ -0,0 +1,194 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using CatalogVbLib; +using Dasync.Collections; + +namespace MaddoShared +{ + public class ImageCreationStuff + { + public class Options + { + public bool AggiornaSottodirectory { get; set; } + public bool CreaSottocartelle { get; set; } + + public int FilePerCartella { get; set; } + public string SuffissoCartelle { get; set; } + public int CifreContatore { get; set; } + public NumerazioneType NumerazioneType { get; set; } + public string SourcePath { get; set; } + public string DestinationPath { get; set; } + + public int MaxThreads { get; set; } + public int ChunksSize { get; set; } + public bool LinearExecution { get; set; } + } + + public async Task CreaCatalogoParallel(Options options, ConcurrentBag results, EventHandler> updateEvent, CancellationToken cancellationToken = default(CancellationToken)) + { + var stopwatch = new Stopwatch(); + stopwatch.Start(); + // todo immagini counter + //todo set label + await CreaImmaginiParallel(options, results, updateEvent, cancellationToken); + + // todo set finito label + stopwatch.Stop(); + + return $"{stopwatch.Elapsed.Hours}h {stopwatch.Elapsed.Minutes}m ${stopwatch.Elapsed.Seconds}s ({stopwatch.Elapsed.TotalSeconds}s)"; + + + } + + public async Task CreaImmaginiParallel(Options options, ConcurrentBag results, EventHandler> updateEvent, CancellationToken cancellationToken = default(CancellationToken)) + { + var dataToProcess = new List(); + if (options.AggiornaSottodirectory && options.CreaSottocartelle) + { + var helper = new FileHelperSharp(); + dataToProcess = helper.GetFilesRecursive(new DirectoryInfo(options.SourcePath), new DirectoryInfo(options.DestinationPath), + "*.jpg", new FileHelperOptions() + { + FilesPerFolder = options.FilePerCartella, + Suffix = options.SuffissoCartelle, + CounterSize = options.CifreContatore, + NumerationType = options.NumerazioneType + }); + } + else if (!options.CreaSottocartelle) + { + var files = Directory.EnumerateFiles(options.SourcePath, "*.jpg", + options.AggiornaSottodirectory + ? SearchOption.AllDirectories + : SearchOption.TopDirectoryOnly); + + dataToProcess = files.Select(x => + { + var fInfo = new FileInfo(x); + var filePath = fInfo.DirectoryName; + var trimmedSourcePath = options.SourcePath.TrimEnd('\\'); + var newFilePath = fInfo.FullName.Replace(trimmedSourcePath, "").TrimStart('\\'); + newFilePath = Path.Combine(options.DestinationPath, newFilePath); + + var destFolderPath = new FileInfo(newFilePath).DirectoryName; + var destFolderInfo = new DirectoryInfo(destFolderPath); + destFolderInfo.EnsureDirectoryExists(); + + return new FileData(fInfo, new DirectoryInfo(new FileInfo(newFilePath).DirectoryName)); + }).ToList(); + + //// TODO + //dataToProcess = + // (from f in Directory.EnumerateFiles(options.SourcePath, "*.jpg", + // options.AggiornaSottodirectory + // ? SearchOption.AllDirectories + // : SearchOption.TopDirectoryOnly) + // select new FileData(new FileInfo(f), + // new DirectoryInfo(options.DestinationPath.PathCombine( + // new FileInfo(f).DirectoryName.Replace(options.SourcePath.TrimEnd(new char[] {'\\'}), "") + // ) + // ) + // ) + // ) + // .ToList(); + } + + var threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads; + var scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, threads) + .ConcurrentScheduler; + + //var allTasks = new List(); + var test = from d in dataToProcess + select Task.Factory.StartNew(async () => + { + await new ImageCreatorSharp(d.File, d.Directory).CreaImmagineThread(d.File.Name); + + //var imgC = new ImageCreatorSharp(d.File, d.Directory); + //imgC.CreaImmagineThread(d.File.Name); + //imgC = null; + }, CancellationToken.None, TaskCreationOptions.None, scheduler); + + //int count = 0; + + if (options.LinearExecution) + { + foreach (var task in test) + { + await task; + } + } + else + { + if (options.ChunksSize == 0) + { + + + //var opts = new ParallelOptions() { MaxDegreeOfParallelism = threads, CancellationToken = cancellationToken, TaskScheduler = scheduler}; + await dataToProcess.ParallelForEachAsync(async fileData => + { + await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread(fileData.File.Name); + results.Add(fileData.File.Name); + //count = Interlocked.Increment(ref count); + try + { + updateEvent?.Invoke(this, new Tuple(fileData.File.Name, dataToProcess.Count) ); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + + }, maxDegreeOfParallelism: threads, false, cancellationToken); + + + } + else + { + + var asdf = SplitList(dataToProcess.ToList(), options.ChunksSize).ToList(); + + + foreach (var sdaf in asdf) + { + await sdaf.ParallelForEachAsync(async fileData => + { + await new ImageCreatorSharp(fileData.File, fileData.Directory).CreaImmagineThread(fileData.File.Name); + results.Add(fileData.File.Name); + //count = Interlocked.Increment(ref count); + try + { + updateEvent?.Invoke(this, new Tuple(fileData.File.Name, dataToProcess.Count)); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + }, maxDegreeOfParallelism: threads, false, cancellationToken); + } + + + + } + } + + + } + + public static IEnumerable> SplitList(List bigList, int nSize = 3) + { + for (int i = 0; i < bigList.Count; i += nSize) + { + yield return bigList.GetRange(i, Math.Min(nSize, bigList.Count - i)); + } + } + } +} diff --git a/MaddoShared.backup/ImageCreatorSharp.cs b/MaddoShared.backup/ImageCreatorSharp.cs new file mode 100644 index 0000000..13f0d8e --- /dev/null +++ b/MaddoShared.backup/ImageCreatorSharp.cs @@ -0,0 +1,1021 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Security; +using System.Text; +using System.Threading.Tasks; +using Microsoft.VisualBasic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Windows.Forms; +using CatalogVbLib; +using SixLabors.ImageSharp.Metadata.Profiles.Exif; + +// Imports System.Threading + +public class ImageCreatorSharp +{ + private bool FotoRuotaADestra = false; + private bool FotoRuotaASinistra = false; + + private string TempMinText = ""; + // Private crFont1 As Font + private string _NomeFileChild; + + private DirectoryInfo _SourceDir; + private DirectoryInfo _DestDirStart; + private DirectoryInfo _DestDir; + + private FileInfo _workFile; + + private string testoFirma; + private string testoFirmaV; + private int alphaScelta; + private int DimensioneStandard; + private int DimensioneStandardMiniatura; + private DateTime dataFoto; + private DateTime dataPartenzaI; + private string testoOrario; + private string testoFirmaPiccola; + private Size thumbSizeSmall; + private Size thumbSizeBig; + private string nomeFileSmall; + private string nomeFileBig; + private string nomeFileBig2; + + private float yPosFromBottom; + private float yPosFromBottom1; + private float yPosFromBottom2; + private float yPosFromBottom3; + private float yPosFromBottom4; + + private ExifReader.Orientations _orientation; + private DateTime? _creationDate; + + public ImageCreatorSharp() + { + } + + public ImageCreatorSharp(string nomeFileChild, DirectoryInfo sourceDir, DirectoryInfo destDir, DirectoryInfo destDirStart) + { + this.NomeFileChild = nomeFileChild; + this.SourceDir = sourceDir; + this.DestDir = destDir; + this.DestDirStart = destDirStart; + this.WorkFile = new FileInfo(nomeFileChild); + } + + public ImageCreatorSharp(string nomeFileChild, DirectoryInfo sourceDir, DirectoryInfo destDir) + { + this.NomeFileChild = nomeFileChild; + this.DestDir = destDir; + } + + public ImageCreatorSharp(FileInfo file, DirectoryInfo destination) + { + this.WorkFile = file; + this.DestDir = destination; + } + + public async Task CreaImmagineThread(string Info) + { + try + { + await Task.Run(() => + { + Console.WriteLine($"File: {WorkFile} Dest: {DestDir}"); + preparaVariabili(); + ExtractExif(); + // Dim g As System.Drawing.Image = System.Drawing.Image.FromFile(Path.Combine(SourceDir.FullName, NomeFileChild)) + using (Image g = Image.FromFile(WorkFile.FullName)) + { + + // Dim g As System.Drawing.Image = System.Drawing.Image.FromFile(WorkFile.FullName) + + // Imposta testo extra + impostaTestoExtra(g); + + // Ruota l'immagine in base ai dati EXIF + Rotation(g); + + // Forza jpeg se è selezionata l'opzione + System.Drawing.Imaging.ImageFormat thisFormat = g.RawFormat; + if (PicSettings.UsaForzaJpg == true) + thisFormat = System.Drawing.Imaging.ImageFormat.Jpeg; + + prepareThumbnailSize(g); + + using (Bitmap imgOutputBig = new Bitmap(g, thumbSizeBig.Width, thumbSizeBig.Height)) + { + //Bitmap imgOutputBig = new Bitmap(g, thumbSizeBig.Width, thumbSizeBig.Height); + imgOutputBig.SetResolution(g.HorizontalResolution, g.VerticalResolution); + + // Crea le miniature + creaMiniature(g, imgOutputBig, thisFormat); + + AggiungiTesto(g, imgOutputBig); + + aggiungiLogo(imgOutputBig); + + SalvaFoto(imgOutputBig, thumbSizeBig, nomeFileBig, nomeFileSmall, thumbSizeSmall, thisFormat); + } + + + } + }); + + // g.Dispose() + + //GC.Collect(); + } + + // PicSettings.mainForm.stepProgressBar() + + catch (Exception ex) + { + var e = ex.Demystify(); + Console.WriteLine(e); + Console.WriteLine(e.Message); + Console.WriteLine(e.StackTrace); + } + } + + private void ExtractExif() + { + using (var img = SixLabors.ImageSharp.Image.Load(_workFile.FullName)) + { + ExifReader.Orientations finalOrientation; + var rotation = img.Metadata?.ExifProfile?.GetValue(ExifTag.Orientation); + if (rotation == null) + { + finalOrientation = ExifReader.Orientations.TopLeft; + } + else + { + finalOrientation = (ExifReader.Orientations)rotation.Value; + } + + _orientation = finalOrientation; + + var creation = img.Metadata?.ExifProfile?.GetValue(ExifTag.DateTime); + if (creation != null) + { + var succ = DateTime.TryParse(creation.Value, out var crDate); + if (succ) + { + _creationDate = crDate; + } + else + { + _creationDate = null; + } + } + else + { + _creationDate = null; + } + + + } + } + + private void Rotation(System.Drawing.Image g) + { + FotoRuotaADestra = false; + FotoRuotaASinistra = false; + + if (PicSettings.UsaRotazioneAutomatica == true) + { + if (g.PropertyIdList.Length > 0) + { + + + //ExifReader DatiExif = new ExifReader((Bitmap)g); + + switch (_orientation /*DatiExif.Orientation*/) + { + case ExifReader.Orientations.BottomLeft: + case ExifReader.Orientations.BottomRight: + case ExifReader.Orientations.LeftTop: + case ExifReader.Orientations.LftBottom: + FotoRuotaASinistra = true; + break; + case ExifReader.Orientations.RightBottom: + case ExifReader.Orientations.RightTop: + case ExifReader.Orientations.TopLeft: + case ExifReader.Orientations.TopRight: + break; + + } + } + } + + if (FotoRuotaASinistra == true) + g.RotateFlip(RotateFlipType.Rotate270FlipNone); + if (FotoRuotaADestra == true) + g.RotateFlip(RotateFlipType.Rotate90FlipNone); + } + /// + /// ''' Aggiunge Orario, tempo gara e altri + /// ''' + /// ''' Image + /// ''' + private void impostaTestoExtra(Image g) + { + if (PicSettings.UsaOrarioTestoApplicare | PicSettings.UsaTempoGaraTestoApplicare | PicSettings.UsaOrarioMiniatura | PicSettings.TestoMin | PicSettings.AggTempoGaraMin | PicSettings.AggNumTempMin) + { + if (g.PropertyIdList.Length > 0) + { + //ExifReader DatiExif = new ExifReader((Bitmap)g); + dataFoto = _creationDate ?? DateTime.Now; //DatiExif.DateTimeOriginal; + testoFirma = PicSettings.TestoFirmaStart; + testoFirmaV = PicSettings.TestoFirmaStartV; + + if (dataFoto.Year != 1) + { + testoFirmaPiccola = dataFoto.ToShortTimeString(); + if (PicSettings.UsaOrarioTestoApplicare == true) + { + testoFirma += " " + dataFoto.ToShortDateString() + " " + dataFoto.ToLongTimeString(); + testoFirmaV += " " + dataFoto.ToShortDateString() + " " + dataFoto.ToLongTimeString(); + } + if (PicSettings.UsaTempoGaraTestoApplicare == true) + { + + var diff = dataPartenzaI - dataFoto; + var diffA = diff.TotalSeconds * 10000000; + + TimeSpan Orario = new TimeSpan(0, 0, 0, (int)diffA); + testoFirma += " " + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + testoFirmaV += " " + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + } + } + } + } + else + { + testoFirma = PicSettings.TestoFirmaStart; + testoFirmaV = PicSettings.TestoFirmaStartV; + } + } + + /// + /// ''' Prepara diverse variabili azzerandole, elaborandole e prendendole dalle impostazioni + /// ''' + /// ''' + private void preparaVariabili() + { + alphaScelta = System.Convert.ToInt32((255 * (100 - PicSettings.Trasparenza) / (double)100)); + testoFirma = ""; + testoFirmaV = ""; + dataPartenzaI = PicSettings.DataPartenza; + testoOrario = PicSettings.TestoOrario; + if (testoOrario.Length > 0) + testoOrario += " "; + testoFirmaPiccola = ""; + thumbSizeSmall = new Size(); + thumbSizeBig = new Size(); + nomeFileSmall = ""; + nomeFileBig2 = ""; + nomeFileBig = ""; + DimensioneStandard = PicSettings.DimStandard; + DimensioneStandardMiniatura = PicSettings.DimStandardMiniatura; + // nomeFileSmall = Suffisso & NomeFileChild + // nomeFileBig = NomeFileChild + nomeFileSmall = PicSettings.Suffisso + WorkFile.Name; + nomeFileBig = WorkFile.Name; + } + + private void prepareThumbnailSize(Image g) + { + if (g.Width > g.Height) + { + thumbSizeSmall = NewthumbSize(g.Width, g.Height, PicSettings.LarghezzaSmall, "Larghezza"); + Size SizeOrig = new Size(g.Width, g.Height); + thumbSizeBig = SizeOrig; + } + else + { + thumbSizeSmall = NewthumbSize(g.Width, g.Height, PicSettings.AltezzaSmall, "Altezza"); + Size SizeOrig = new Size(g.Width, g.Height); + thumbSizeBig = SizeOrig; + } + } + + private void creaMiniature(Image g, Bitmap imgOutputBig, ImageFormat thisFormat) + { + if (PicSettings.TestoMin) + testoFirmaPiccola = nomeFileBig; + else if (PicSettings.AggNumTempMin) + testoFirmaPiccola = nomeFileBig + " "; + // Dim yPosFromBottom4 As Single + + Font crFont1 = null/* TODO Change to default(_) if this is not a reference type */; + Font crFont2 = null/* TODO Change to default(_) if this is not a reference type */; + SizeF crSize1 = new SizeF(); + SizeF crSize2 = new SizeF(); + + if (PicSettings.CreaMiniature == true) + { + if (PicSettings.AggiungiScritteMiniature == false) + { + if (string.Equals(PicSettings.DirectorySorgente, PicSettings.DirectoryDestinazione, StringComparison.OrdinalIgnoreCase)) + nomeFileSmall = nomeFileSmall.Substring(0, nomeFileSmall.Length - 4) + PicSettings.Codice + nomeFileSmall.Substring(nomeFileSmall.Length - 4); + if (PicSettings.UsaOrarioMiniatura | PicSettings.TestoMin | PicSettings.AggTempoGaraMin | PicSettings.AggNumTempMin) + { + if (testoFirmaPiccola.Length > 0) + { + using (var imgOutputSmall = (Bitmap)imgOutputBig.Clone()) + { + Graphics grPhoto1; + grPhoto1 = Graphics.FromImage(imgOutputSmall); + grPhoto1.SmoothingMode = SmoothingMode.AntiAlias; + + int LarghezzaStandard1; + // quick fix + DimensioneStandardMiniatura = 50; + if (PicSettings.Grassetto == true) + { + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura, FontStyle.Bold); + crFont2 = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + } + else + { + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura); + crFont2 = new Font(PicSettings.IlFont, DimensioneStandard); + } + + crSize1 = grPhoto1.MeasureString(testoFirmaPiccola, crFont1); + crSize2 = grPhoto1.MeasureString(testoFirma, crFont1); + LarghezzaStandard1 = System.Convert.ToInt32(crSize1.Width); + + if (crSize1.Width > System.Convert.ToSingle(g.Width)) + { + int Conta = DimensioneStandardMiniatura; + do + { + if (Conta > 20) + Conta -= 5; + else + Conta -= 1; + if (PicSettings.Grassetto == true) + crFont1 = new Font(PicSettings.IlFont, Conta, FontStyle.Bold); + else + crFont1 = new Font(PicSettings.IlFont, Conta); + crSize1 = grPhoto1.MeasureString(testoFirmaPiccola, crFont1); + if (crSize1.Width < System.Convert.ToSingle(g.Width)) + { + LarghezzaStandard1 = System.Convert.ToInt32(crSize1.Width); + break; + } + + if (Conta <= 5) + break; + } + while (true); + DimensioneStandardMiniatura = Conta; + } + + switch (PicSettings.Posizione.ToUpper()) + { + case "ALTO": + { + yPosFromBottom1 = (PicSettings.Margine); + yPosFromBottom4 = (PicSettings.MargVert); + break; + } + + case "BASSO": + { + yPosFromBottom1 = System.Convert.ToSingle((g.Height - crSize1.Height - (g.Height * PicSettings.Margine / (double)100))); + yPosFromBottom4 = System.Convert.ToSingle((g.Height - crSize1.Height - (g.Height * PicSettings.MargVert / (double)100))); + break; + } + } + + float xCenterOfImg1 = 0; + + StringFormat StrFormat1 = new StringFormat(); + switch (PicSettings.Allineamento.ToUpper()) + { + case "SINISTRA": + { + xCenterOfImg1 = System.Convert.ToSingle((PicSettings.Margine + (LarghezzaStandard1 / (double)2))); + + if ((LarghezzaStandard1 / (double)2) > (g.Width / (double)2) - PicSettings.Margine) + xCenterOfImg1 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "CENTRO": + { + xCenterOfImg1 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "DESTRA": + { + xCenterOfImg1 = System.Convert.ToSingle((g.Width - PicSettings.Margine - (LarghezzaStandard1 / (double)2))); + + if ((LarghezzaStandard1 / (double)2) > (g.Width / (double)2) - PicSettings.Margine) + xCenterOfImg1 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + } + StrFormat1.Alignment = StringAlignment.Center; + + SolidBrush semiTransBrush21 = new SolidBrush(Color.FromArgb(alphaScelta, 0, 0, 0)); + SolidBrush semiTransBrush1 = new SolidBrush(Color.FromArgb(alphaScelta, PicSettings.fontColoreRGB)); + + // quick fix + DimensioneStandardMiniatura = PicSettings.DimMin; + + if (PicSettings.Grassetto == true) + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura, FontStyle.Bold); + else + crFont1 = new Font(PicSettings.IlFont, DimensioneStandardMiniatura); + // asdgadfhdfhjgfsjgfjygfdhsdafa + if (PicSettings.TestoMin) + { + grPhoto1.DrawString(nomeFileBig, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(nomeFileBig, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + else if (PicSettings.AggTempoGaraMin & PicSettings.UsaTempoGaraTestoApplicare) + { + var diff = dataPartenzaI - dataFoto; + var diffA = diff.TotalSeconds * 10000000; + + TimeSpan Orario = new TimeSpan(0, 0, (int)diffA);/* new TimeSpan(DateTime.DateDiff(DateInterval.Second, dataPartenzaI, dataFoto) * 10000000);*/ + string tempstr = ""; + + + tempstr += Environment.NewLine + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + + + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + else if (PicSettings.AggNumTempMin) + { + var diff = dataPartenzaI - dataFoto; + var diffA = diff.TotalSeconds * 10000000; + TimeSpan Orario = new TimeSpan(0, 0, (int)diffA); + string tempstr = ""; + tempstr += nomeFileBig; + + tempstr += Environment.NewLine + testoOrario + Orario.Hours.ToString("00") + ":" + Orario.Minutes.ToString("00") + ":" + Orario.Seconds.ToString("00"); + + + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(tempstr, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + else + { + grPhoto1.DrawString(testoFirmaPiccola, crFont1, semiTransBrush21, new PointF(xCenterOfImg1 + 1, yPosFromBottom1 + 1), StrFormat1); + grPhoto1.DrawString(testoFirmaPiccola, crFont1, semiTransBrush1, new PointF(xCenterOfImg1, yPosFromBottom1), StrFormat1); + } + + // Salva la miniatura + //using (var g22 = Image.FromHbitmap(imgOutputSmall)) + + + using (var imgOutputSmall2 = new Bitmap(imgOutputSmall, thumbSizeSmall.Width, thumbSizeSmall.Height)) + { + imgOutputSmall2.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + + //imgOutputSmall2.Dispose(); + } + + //imgOutputSmall.Dispose(); + } + + + //File.Delete(Path.Combine(DestDir.FullName, "Temp_" + nomeFileSmall)); + //FileSystem.Kill(); + } + else + { + using (Bitmap imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height)) + { + imgOutputSmall.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + //imgOutputSmall.Dispose(); + } + } + } + else + { + using (Bitmap imgOutputSmall = new Bitmap(g, thumbSizeSmall.Width, thumbSizeSmall.Height)) + { + imgOutputSmall.Save(Path.Combine(DestDir.FullName, nomeFileSmall), thisFormat); + //imgOutputSmall.Dispose(); + } + } + } + } + + crFont1?.Dispose(); + crFont2?.Dispose(); + } + + private void AggiungiTesto(Image g, Bitmap imgOutputBig) + { + using (var grPhoto = Graphics.FromImage(imgOutputBig)) + { + grPhoto.SmoothingMode = SmoothingMode.AntiAlias; + + Font crFont = null/* TODO Change to default(_) if this is not a reference type */; + SizeF crSize = new SizeF(); + int LarghezzaStandard; + + if (PicSettings.Grassetto == true) + crFont = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + else + crFont = new Font(PicSettings.IlFont, DimensioneStandard); + crSize = grPhoto.MeasureString(testoFirma, crFont); + LarghezzaStandard = System.Convert.ToInt32(crSize.Width); + + if (crSize.Width > System.Convert.ToSingle(g.Width)) + { + int Conta = DimensioneStandard; + do + { + if (Conta > 20) + Conta -= 5; + else + Conta -= 1; + if (PicSettings.Grassetto == true) + crFont = new Font(PicSettings.IlFont, Conta, FontStyle.Bold); + else + crFont = new Font(PicSettings.IlFont, Conta); + crSize = grPhoto.MeasureString(testoFirma, crFont); + if (crSize.Width < System.Convert.ToSingle(g.Width)) + { + LarghezzaStandard = System.Convert.ToInt32(crSize.Width); + break; + } + + if (Conta <= 5) + break; + } + while (true); + DimensioneStandard = Conta; + } + + + switch (PicSettings.Posizione.ToUpper()) + { + case "ALTO": + { + yPosFromBottom = (PicSettings.Margine); + yPosFromBottom3 = (PicSettings.MargVert); + break; + } + + case "BASSO": + { + yPosFromBottom = System.Convert.ToSingle((g.Height - crSize.Height - (g.Height * PicSettings.Margine / (double)100))); + yPosFromBottom3 = System.Convert.ToSingle((g.Height - crSize.Height - (g.Height * PicSettings.MargVert / (double)100))); + break; + } + } + + float xCenterOfImg = 0; + float xCenterOfImg3 = 0; + StringFormat StrFormat = new StringFormat(); + switch (PicSettings.Allineamento.ToUpper()) + { + case "SINISTRA": + { + xCenterOfImg = System.Convert.ToSingle((PicSettings.Margine + (LarghezzaStandard / (double)2))); + xCenterOfImg3 = System.Convert.ToSingle((PicSettings.MargVert + (LarghezzaStandard / (double)2))); + if ((LarghezzaStandard / (double)2) > (g.Width / (double)2) - PicSettings.Margine) + xCenterOfImg = System.Convert.ToSingle((g.Width / (double)2)); + if ((LarghezzaStandard / (double)2) > (g.Width / (double)2) - PicSettings.MargVert) + xCenterOfImg3 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "CENTRO": + { + xCenterOfImg = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "DESTRA": + { + xCenterOfImg = System.Convert.ToSingle((g.Width - PicSettings.Margine - (LarghezzaStandard / (double)2))); + xCenterOfImg3 = System.Convert.ToSingle((g.Width - PicSettings.MargVert - (LarghezzaStandard / (double)2))); + if ((LarghezzaStandard / (double)2) > (g.Width / (double)2) - PicSettings.Margine) + xCenterOfImg = System.Convert.ToSingle((g.Width / (double)2)); + if ((LarghezzaStandard / (double)2) > (g.Width / (double)2) - PicSettings.MargVert) + xCenterOfImg3 = System.Convert.ToSingle((g.Width / (double)2)); + break; + } + } + StrFormat.Alignment = StringAlignment.Center; + + SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(alphaScelta, 0, 0, 0)); + // Dim semiTransBrush As SolidBrush = New SolidBrush(Color.FromArgb(AlphaScelta, _FontColoreR, _FontColoreG, _FontColoreB)) + SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(alphaScelta, PicSettings.fontColoreRGB)); + + if (FotoRuotaADestra | FotoRuotaASinistra) + { + if (PicSettings.Grassetto == true) + crFont = new Font(PicSettings.IlFont, PicSettings.DimVert, FontStyle.Bold); + else + crFont = new Font(PicSettings.IlFont, PicSettings.DimVert); + } + else if (PicSettings.Grassetto == true) + crFont = new Font(PicSettings.IlFont, DimensioneStandard, FontStyle.Bold); + else + crFont = new Font(PicSettings.IlFont, DimensioneStandard); + + + // qui scrive il testo (nomefilebig) + if (PicSettings.TestoNome) + { + if (PicSettings.NomeData & g.PropertyIdList.Length > 0) + { + //ExifReader DatiExif = new ExifReader((Bitmap)g); + dataFoto = _creationDate ?? DateTime.Now; //DatiExif.DateTimeOriginal; + + grPhoto.DrawString((nomeFileBig + " " + dataFoto.ToShortDateString()), crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString((nomeFileBig + " " + dataFoto.ToShortDateString()), crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + } + else + { + grPhoto.DrawString(nomeFileBig, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString(nomeFileBig, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + } + } + + if (PicSettings.TestoNome == false) + { + if (FotoRuotaADestra | FotoRuotaASinistra) + { + if (PicSettings.TestoMin == false) + { + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom3 + 1), StrFormat); + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom3), StrFormat); + } + if (PicSettings.TestoMin == true) + { + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom4 + 1), StrFormat); + grPhoto.DrawString(testoFirmaV, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom4), StrFormat); + } + } + else + { + grPhoto.DrawString(testoFirma, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); + grPhoto.DrawString(testoFirma, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); + } + } + + if (string.Equals(PicSettings.DirectorySorgente, PicSettings.DirectoryDestinazione, StringComparison.OrdinalIgnoreCase)) + { + nomeFileBig2 = nomeFileBig; + nomeFileBig = nomeFileBig.Substring(0, nomeFileBig.Length - 4) + PicSettings.Codice + nomeFileBig.Substring(nomeFileBig.Length - 4); + } + //grPhoto.Dispose(); + + crFont?.Dispose(); + } + + + } + + + + + private void aggiungiLogo(Bitmap imgOutputBig) + { + // imgOutputBig + if (PicSettings.LogoAggiungi == true & File.Exists(PicSettings.LogoNomeFile)) + { + Image ImmagineLogo = Image.FromFile(PicSettings.LogoNomeFile); + + Color LogoColoreTrasparente = Color.White; + // Dim bmWatermark As Bitmap + + // * Create a Bitmap based on the previously modified photograph Bitmap + // bmWatermark = New Bitmap(imgOutputBig) + // bmWatermark.SetResolution(imgOutputBig.HorizontalResolution, imgOutputBig.VerticalResolution) + + // * Load this Bitmap into a new Graphic Object + using (Graphics grWatermark = Graphics.FromImage(imgOutputBig)) + { + ImageAttributes imageAttributes = new ImageAttributes(); + + // * The first step replace the background color with one that is transparent (Alpha=0, R=0, G=0, B=0) + ColorMap colorMap = new ColorMap(); + + // * background this will be the color we search for and replace with transparency + colorMap.OldColor = LogoColoreTrasparente; + colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); + + ColorMap[] remapTable = new[] { colorMap }; + imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); + + // * The second color manipulation is used to change the opacity by setting the 3rd row and 3rd column to 0.3f + float[][] colorMatrixElements = new[] { new float[] { 1.0F, 0.0F, 0.0F, 0.0F, 0.0F }, new float[] { 0.0F, 1.0F, 0.0F, 0.0F, 0.0F }, new float[] { 0.0F, 0.0F, 1.0F, 0.0F, 0.0F }, new float[] { 0.0F, 0.0F, 0.0F, System.Convert.ToSingle(PicSettings.LogoTrasparenza) / 100F, 0.0F }, new float[] { 0.0F, 0.0F, 0.0F, 0.0F, 1.0F } }; + ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); + imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); + + int FotoLogoH = PicSettings.LogoAltezza; + int FotoLogoW = PicSettings.LogoLarghezza; + double FattoreAlt = ImmagineLogo.Height / (double)FotoLogoH; + double FattoreLarg = ImmagineLogo.Width / (double)FotoLogoW; + Size NuovaSize; + if (FattoreLarg > FattoreAlt) + NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoW, "Larghezza"); + else + NuovaSize = NewthumbSize(ImmagineLogo.Width, ImmagineLogo.Height, FotoLogoH, "Altezza"); + + int MargineUsato; + int MargineL; + bool InPercentualeL; + if (PicSettings.LogoMargine.EndsWith("%") == true) + InPercentualeL = true; + else + InPercentualeL = false; + MargineL = System.Convert.ToInt32(PicSettings.LogoMargine); + if (InPercentualeL == true) + MargineUsato = System.Convert.ToInt32(imgOutputBig.Height * MargineL / (double)100); + else + MargineUsato = MargineL; + + int xPosOfWm = 0; + int yPosOfWm = 0; + switch (PicSettings.LogoPosizioneH.ToUpper()) + { + case "SINISTRA": + case "NESSUNA": + { + xPosOfWm = MargineUsato; + break; + } + + case "CENTRO": + { + xPosOfWm = System.Convert.ToInt32((imgOutputBig.Width - NuovaSize.Width) / (double)2); + break; + } + + case "DESTRA": + { + xPosOfWm = ((imgOutputBig.Width - NuovaSize.Width) - MargineUsato); + break; + } + } + switch (PicSettings.LogoPosizioneV.ToUpper()) + { + case "ALTO": + case "NESSUNA": + { + yPosOfWm = MargineUsato; + break; + } + + case "CENTRO": + { + yPosOfWm = System.Convert.ToInt32((imgOutputBig.Height - NuovaSize.Height) / (double)2); + break; + } + + case "BASSO": + { + yPosOfWm = ((imgOutputBig.Height - NuovaSize.Height) - MargineUsato); + break; + } + } + + grWatermark.DrawImage(ImmagineLogo, new Rectangle(xPosOfWm, yPosOfWm, NuovaSize.Width, NuovaSize.Height), 0, 0, ImmagineLogo.Width, ImmagineLogo.Height, GraphicsUnit.Pixel, imageAttributes); + //grWatermark.Dispose(); + } + } + } + + + private void SalvaFoto(Bitmap imgOutputBig, Size thumbSizeBig, string NomeFileBig, string NomeFileSmall, Size thumbSizeSmall, ImageFormat thisFormat) + { + using (var image1Stream = new MemoryStream()) + { + + + + if (PicSettings.FotoGrandeDimOrigina == false) + { + // attenzione non controlla se è png + // imgOutputBig.Save(Path.Combine(_DestDir.FullName, "Temp_" & NomeFileBig), thisFormat) + if (thisFormat.Equals(ImageFormat.Jpeg)) + { + MakeImageCustomQuality(imgOutputBig, image1Stream); + } + //SalvaImmagineCustomQuality(imgOutputBig, Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig), PicSettings.jpegQuality); + else + { + imgOutputBig.Save(image1Stream, thisFormat); + } + //imgOutputBig.Save(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig), thisFormat); + image1Stream.Seek(0, SeekOrigin.Begin); + using (var g2 = Image.FromStream(image1Stream)) + { + thumbSizeBig = g2.Width > g2.Height ? NewthumbSize(g2.Width, g2.Height, PicSettings.LarghezzaBig, "Larghezza") : NewthumbSize(g2.Width, g2.Height, PicSettings.AltezzaBig, "Altezza"); + using (Bitmap imgOutputBig2 = new Bitmap(g2, thumbSizeBig.Width, thumbSizeBig.Height)) + { + if (thisFormat.Equals(ImageFormat.Jpeg)) + SalvaImmagineCustomQuality(imgOutputBig2, Path.Combine(DestDir.FullName, NomeFileBig), PicSettings.jpegQuality); + else + imgOutputBig2.Save(Path.Combine(DestDir.FullName, NomeFileBig), thisFormat); + + //imgOutputBig2.Dispose(); + } + } + + //imgOutputBig.Dispose(); + //g2.Dispose(); + } + else + { + // + if (thisFormat.Equals(ImageFormat.Jpeg)) + SalvaImmagineCustomQuality(imgOutputBig, Path.Combine(DestDir.FullName, NomeFileBig), PicSettings.jpegQuality); + else + imgOutputBig.Save(Path.Combine(DestDir.FullName, NomeFileBig), thisFormat); + + //imgOutputBig.Dispose(); + } + image1Stream.Seek(0, SeekOrigin.Begin); + + if (PicSettings.CreaMiniature) + { + if (PicSettings.AggiungiScritteMiniature) + { + using (System.Drawing.Image g1 = PicSettings.FotoGrandeDimOrigina ? (Image)imgOutputBig.Clone() : Image.FromStream(image1Stream)) + { + //if (PicSettings.FotoGrandeDimOrigina == false) + // g1 = Image.FromStream(image1Stream); + ////g1 = System.Drawing.Image.FromFile(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig)); + //else + // g1 = (Image)imgOutputBig.Clone(); + //g1 = System.Drawing.Image.FromFile(Path.Combine(DestDir.FullName, NomeFileBig)); + using (Bitmap imgOutputSmall = new Bitmap(g1, thumbSizeSmall.Width, thumbSizeSmall.Height)) + { + if (string.Equals(PicSettings.DirectorySorgente, PicSettings.DirectoryDestinazione, StringComparison.OrdinalIgnoreCase)) + NomeFileSmall = NomeFileSmall.Substring(0, NomeFileSmall.Length - 4) + PicSettings.Codice + NomeFileSmall.Substring(NomeFileSmall.Length - 4); + // + if (thisFormat.Equals(ImageFormat.Jpeg)) + SalvaImmagineCustomQuality(imgOutputSmall, Path.Combine(DestDir.FullName, NomeFileSmall), PicSettings.jpegQualityMin); + else + imgOutputSmall.Save(Path.Combine(_DestDir.FullName, NomeFileSmall), thisFormat); + + //imgOutputSmall.Dispose(); + } + + //g1.Dispose(); + } + } + } + + //if (File.Exists(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig))) + // File.Delete(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig)); + + } + } + + private void SalvaImmagineCustomQuality(Bitmap imageToSave, string nomeFileFinale, long quality) + { + ImageCodecInfo JgpEncoder = GetEncoder(ImageFormat.Jpeg); + System.Drawing.Imaging.Encoder MyEncoder = System.Drawing.Imaging.Encoder.Quality; + + EncoderParameters MyEncoderParameters = new EncoderParameters(1); + + EncoderParameter MyEncoderParameter = new EncoderParameter(MyEncoder, PicSettings.jpegQuality); + MyEncoderParameters.Param[0] = MyEncoderParameter; + imageToSave.Save(nomeFileFinale, JgpEncoder, MyEncoderParameters); + //imageToSave.Dispose(); + } + + private void MakeImageCustomQuality(Bitmap imageToSave, Stream destinationStream) + { + ImageCodecInfo JgpEncoder = GetEncoder(ImageFormat.Jpeg); + System.Drawing.Imaging.Encoder MyEncoder = System.Drawing.Imaging.Encoder.Quality; + + EncoderParameters MyEncoderParameters = new EncoderParameters(1); + + EncoderParameter MyEncoderParameter = new EncoderParameter(MyEncoder, PicSettings.jpegQuality); + MyEncoderParameters.Param[0] = MyEncoderParameter; + destinationStream.Seek(0, SeekOrigin.Begin); + imageToSave.Save(destinationStream, JgpEncoder, MyEncoderParameters); + //imageToSave.Dispose(); + } + + + private ImageCodecInfo GetEncoder(ImageFormat format) + { + ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); + + + foreach (var codec in codecs) + { + if (codec.FormatID == format.Guid) + return codec; + } + return null/* TODO Change to default(_) if this is not a reference type */; + } + + + + + + + /// + /// ''' Calculate the Size of the New image + /// ''' + /// ''' Larghezza + /// ''' Altezza + /// ''' + /// ''' + /// ''' + /// ''' + private Size NewthumbSize(int currentwidth, int currentheight, int MaxPixel, string TipoSize) + { + // e + // *** Larghezza, Altezza, Auto + + double tempMultiplier; + + if (TipoSize.ToUpper() == "Larghezza".ToUpper()) + tempMultiplier = MaxPixel / (double)currentwidth; + else if (TipoSize.ToUpper() == "Altezza".ToUpper()) + tempMultiplier = MaxPixel / (double)currentheight; + else if (currentheight > currentwidth) + tempMultiplier = MaxPixel / (double)currentheight; + else + tempMultiplier = MaxPixel / (double)currentwidth; + + Size NewSize = new Size(System.Convert.ToInt32(currentwidth * tempMultiplier), System.Convert.ToInt32(currentheight * tempMultiplier)); + + return NewSize; + } + + public FileInfo WorkFile + { + get + { + return _workFile; + } + set + { + _workFile = value; + } + } + + public DirectoryInfo DestDir + { + get => _DestDir; + set => _DestDir = value; + } + + public DirectoryInfo SourceDir + { + get + { + return _SourceDir; + } + set + { + _SourceDir = value; + } + } + + public DirectoryInfo DestDirStart + { + get + { + return _DestDirStart; + } + set + { + _DestDirStart = value; + } + } + + public string NomeFileChild + { + get + { + return _NomeFileChild; + } + set + { + _NomeFileChild = value; + } + } +} diff --git a/MaddoShared.backup/MaddoShared.csproj b/MaddoShared.backup/MaddoShared.csproj new file mode 100644 index 0000000..03c762e --- /dev/null +++ b/MaddoShared.backup/MaddoShared.csproj @@ -0,0 +1,101 @@ + + + + + Debug + AnyCPU + {AEBFE9E3-277C-4A7B-8448-145D1B11998B} + Library + Properties + MaddoShared + MaddoShared + v4.7.2 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\AsyncEnumerator.4.0.2\lib\net461\AsyncEnumerable.dll + + + ..\packages\Ben.Demystifier.0.3.0\lib\net45\Ben.Demystifier.dll + + + ..\packages\Microsoft.Bcl.AsyncInterfaces.5.0.0\lib\net461\Microsoft.Bcl.AsyncInterfaces.dll + + + ..\packages\SixLabors.ImageSharp.1.0.3\lib\net472\SixLabors.ImageSharp.dll + + + + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + ..\packages\System.Collections.Immutable.5.0.0\lib\net461\System.Collections.Immutable.dll + + + + + ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll + + + + ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + ..\packages\System.Reflection.Metadata.5.0.0\lib\net461\System.Reflection.Metadata.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.5.0.0\lib\net45\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + + + + + + + + ..\packages\Z.ExtensionMethods.2.1.1\lib\net45\Z.ExtensionMethods.dll + + + + + + + + + + + + + {44465926-240d-473f-90b8-786ba4384406} + CatalogVbLib + + + + + + + + \ No newline at end of file diff --git a/MaddoShared.backup/Properties/AssemblyInfo.cs b/MaddoShared.backup/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..52a601e --- /dev/null +++ b/MaddoShared.backup/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MaddoShared")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MaddoShared")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("aebfe9e3-277c-4a7b-8448-145d1b11998b")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MaddoShared.backup/ThreadingHelper.cs b/MaddoShared.backup/ThreadingHelper.cs new file mode 100644 index 0000000..f0ce4db --- /dev/null +++ b/MaddoShared.backup/ThreadingHelper.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MaddoShared +{ + public static class ThreadingHelper + { + /// + /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel. + /// NOTE: If one of the given tasks has already been started, an exception will be thrown. + /// + /// The tasks to run. + /// The maximum number of tasks to run in parallel. + /// The cancellation token. + public static void StartAndWaitAllThrottled(IEnumerable tasksToRun, int maxTasksToRunInParallel, CancellationToken cancellationToken = new CancellationToken()) + { + StartAndWaitAllThrottled(tasksToRun, maxTasksToRunInParallel, -1, cancellationToken); + } + + /// + /// Starts the given tasks and waits for them to complete. This will run, at most, the specified number of tasks in parallel. + /// NOTE: If one of the given tasks has already been started, an exception will be thrown. + /// + /// The tasks to run. + /// The maximum number of tasks to run in parallel. + /// The maximum milliseconds we should allow the max tasks to run in parallel before allowing another task to start. Specify -1 to wait indefinitely. + /// The cancellation token. + public static void StartAndWaitAllThrottled(IEnumerable tasksToRun, int maxTasksToRunInParallel, int timeoutInMilliseconds, CancellationToken cancellationToken = new CancellationToken()) + { + // Convert to a list of tasks so that we don't enumerate over it multiple times needlessly. + var tasks = tasksToRun.ToList(); + + using (var throttler = new SemaphoreSlim(maxTasksToRunInParallel)) + { + var postTaskTasks = new List(); + + // Have each task notify the throttler when it completes so that it decrements the number of tasks currently running. + tasks.ForEach(t => postTaskTasks.Add(t.ContinueWith(tsk => throttler.Release()))); + + // Start running each task. + foreach (var task in tasks) + { + // Increment the number of tasks currently running and wait if too many are running. + throttler.Wait(timeoutInMilliseconds, cancellationToken); + + cancellationToken.ThrowIfCancellationRequested(); + task.Start(); + } + + // Wait for all of the provided tasks to complete. + // We wait on the list of "post" tasks instead of the original tasks, otherwise there is a potential race condition where the throttler's using block is exited before some Tasks have had their "post" action completed, which references the throttler, resulting in an exception due to accessing a disposed object. + Task.WaitAll(postTaskTasks.ToArray(), cancellationToken); + } + } + } +} diff --git a/MaddoShared.backup/app.config b/MaddoShared.backup/app.config new file mode 100644 index 0000000..8d59e6b --- /dev/null +++ b/MaddoShared.backup/app.config @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MaddoShared.backup/packages.config b/MaddoShared.backup/packages.config new file mode 100644 index 0000000..e229a26 --- /dev/null +++ b/MaddoShared.backup/packages.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/MaddoShared.backup/upgrade.backup b/MaddoShared.backup/upgrade.backup new file mode 100644 index 0000000..3d26f1f --- /dev/null +++ b/MaddoShared.backup/upgrade.backup @@ -0,0 +1 @@ +Backup created at 1615021651 (06/03/2021 09:07:31 +00:00) \ No newline at end of file diff --git a/MaddoShared/IImageCreator.cs b/MaddoShared/IImageCreator.cs index 4aa89c7..6fd85a5 100644 --- a/MaddoShared/IImageCreator.cs +++ b/MaddoShared/IImageCreator.cs @@ -1,8 +1,9 @@ +using System.Drawing; using System.Threading.Tasks; namespace MaddoShared; public interface IImageCreator { - Task CreateImageAsync(ImageState imgState, byte[]? logoData); + Task CreateImageAsync(ImageState imgState, Image logo); } diff --git a/MaddoShared/ImageCreationStuff.cs b/MaddoShared/ImageCreationStuff.cs index 9622b7d..b688f3a 100644 --- a/MaddoShared/ImageCreationStuff.cs +++ b/MaddoShared/ImageCreationStuff.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Drawing; using System.IO; using System.Linq; using System.Text; @@ -13,8 +14,9 @@ using Microsoft.Extensions.Logging; namespace MaddoShared { - public class ImageCreationService( - ILogger logger, + [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility")] + public class ImageCreationStuff( + ILogger logger, PicSettings picSettings, IImageCreator imageCreatorService) { @@ -70,15 +72,19 @@ namespace MaddoShared // int threads = options.MaxThreads == 0 ? Environment.ProcessorCount * 2 : options.MaxThreads; int threads = options.MaxThreads; - // Load logo once as raw bytes (cross-platform). byte[] is safe to share across threads. - byte[]? logoBytes = picSettings.LogoData; - if (logoBytes is null && picSettings.LogoAggiungi && File.Exists(picSettings.LogoNomeFile)) + Bitmap logoBmp = null; + // Load Logo (short-circuit) + if (picSettings.LogoAggiungi && File.Exists(picSettings.LogoNomeFile)) { - logoBytes = File.ReadAllBytes(picSettings.LogoNomeFile); + logoBmp = new Bitmap(picSettings.LogoNomeFile); } Func processFile = async fileData => { + Bitmap logoCopy = logoBmp is null + ? null + : logoBmp.Clone(new Rectangle(0, 0, logoBmp.Width, logoBmp.Height), logoBmp.PixelFormat); + var imgState = new ImageState { WorkFile = fileData.File, @@ -87,7 +93,8 @@ namespace MaddoShared try { - await imageCreatorService.CreateImageAsync(imgState, logoBytes); + // Ensure CreateImageAsync can accept a null logoCopy value. + await imageCreatorService.CreateImageAsync(imgState, logoCopy); results.Add(fileData.File.Name); @@ -103,7 +110,8 @@ namespace MaddoShared } finally { - // nothing to dispose — byte[] is managed + // Dispose the clone if it was created + logoCopy?.Dispose(); } }; @@ -131,6 +139,14 @@ namespace MaddoShared } } + try + { + logoBmp?.Dispose(); + } + catch (Exception e) + { + logger.LogError(e, "Error in disposing the logo"); + } } private List GetFilesToProcess(Options options) diff --git a/MaddoShared/ImageCreatorImageSharp.cs b/MaddoShared/ImageCreatorAlternate.cs similarity index 74% rename from MaddoShared/ImageCreatorImageSharp.cs rename to MaddoShared/ImageCreatorAlternate.cs index a0c96a0..8ddfbec 100644 --- a/MaddoShared/ImageCreatorImageSharp.cs +++ b/MaddoShared/ImageCreatorAlternate.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Threading.Tasks; +// System.Drawing not required for ImageSharp-based drawing in this class using Microsoft.Extensions.Logging; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; @@ -16,29 +17,33 @@ using SixLabors.ImageSharp.Drawing; namespace MaddoShared; /// -/// Image creator implemented with SixLabors.ImageSharp for loading, EXIF orientation, -/// resizing, text/logo drawing, and saving. +/// Image creator implemented using SixLabors.ImageSharp for core image operations. +/// This implementation focuses on loading, EXIF-orientation, resizing and saving. +/// It intentionally implements a minimal subset of the original functionality to +/// provide a safe and testable replacement. Additional features (text/logo drawing) +/// can be added later using ImageSharp.Drawing.Common and SixLabors.Fonts. /// -public class ImageCreatorImageSharp : IImageCreator +public class ImageCreatorAlternate : IImageCreator { private readonly PicSettings _picSettings; - private readonly ILogger _logger; + private readonly ILogger _logger; - public ImageCreatorImageSharp(PicSettings picSettings, ILogger logger) + public ImageCreatorAlternate(PicSettings picSettings, ILogger logger) { _picSettings = picSettings ?? throw new ArgumentNullException(nameof(picSettings)); _logger = logger; } - public async Task CreateImageAsync(ImageState imgState, byte[]? logoData) + public async Task CreateImageAsync(ImageState imgState, System.Drawing.Image logo) { ArgumentNullException.ThrowIfNull(imgState); + // Minimal preparation of names and settings normally done by ImageCreatorSharp.PrepareVariables PrepareVariablesMinimal(imgState); try { - _logger.LogInformation("[ImageSharp] Processing {File} -> {Dest}", imgState.WorkFile?.FullName, imgState.DestDir?.FullName); + _logger.LogInformation("[Alternate] Processing {File} -> {Dest}", imgState.WorkFile?.FullName, imgState.DestDir?.FullName); using var fs = File.OpenRead(imgState.WorkFile.FullName); @@ -49,11 +54,11 @@ public class ImageCreatorImageSharp : IImageCreator ExtractExif(img, imgState); // Apply orientation - // Set rotation flags and apply orientation so downstream logic can - // use imgState.FotoRuotaADestra / FotoRuotaASinistra to decide which - // text to draw (horizontal vs vertical). ApplyExifOrientation(img, imgState); + // Determine output format + var forceJpg = _picSettings.UsaForzaJpg; + // Compute big size var bigSize = ComputeBigSize(img.Width, img.Height); @@ -63,10 +68,10 @@ public class ImageCreatorImageSharp : IImageCreator // Ensure destination exists imgState.DestDir?.Create(); - var fileNameBig = System.IO.Path.Combine(imgState.DestDir.FullName, imgState.NomeFileBig); + var fileNameBig = System.IO.Path.Combine(imgState.DestDir.FullName, imgState.NomeFileBig); // Draw overlays (text/logo) onto big image using ImageSharp and save - await DrawAndSaveAsync(imgBig, fileNameBig, imgState, logoData, _picSettings.JpegQuality, isThumbnail: false).ConfigureAwait(false); + await DrawAndSaveWithGdiAsync(imgBig, fileNameBig, imgState, logo, _picSettings.JpegQuality, isThumbnail: false).ConfigureAwait(false); // Create thumbnail if requested if (_picSettings.CreaMiniature) @@ -77,16 +82,20 @@ public class ImageCreatorImageSharp : IImageCreator var fileNameSmall = System.IO.Path.Combine(imgState.DestDir.FullName, imgState.NomeFileSmall); // Draw overlays and save thumbnail via ImageSharp - await DrawAndSaveAsync(imgSmall, fileNameSmall, imgState, logoData, _picSettings.JpegQualityMin, isThumbnail: true).ConfigureAwait(false); + await DrawAndSaveWithGdiAsync(imgSmall, fileNameSmall, imgState, logo, _picSettings.JpegQualityMin, isThumbnail: true).ConfigureAwait(false); } } catch (Exception ex) { - _logger.LogError(ex, "[ImageSharp] Error processing image {File}", imgState.WorkFile?.Name); + _logger.LogError(ex, "[Alternate] Error processing image {File}", imgState.WorkFile?.Name); throw; } } + + + // Thumbnail overlays are rendered by the GDI+ pass in DrawAndSaveWithGdiAsync to match original rendering. + private static SixLabors.ImageSharp.Formats.IImageEncoder GetEncoderForExtension(string ext, long quality) { quality = Math.Clamp(quality, 1, 100); @@ -98,33 +107,16 @@ public class ImageCreatorImageSharp : IImageCreator }; } - private async Task DrawAndSaveAsync(Image imgSharp, string outputPath, ImageState imgState, byte[]? logoData, long quality, bool isThumbnail) + private async Task DrawAndSaveWithGdiAsync(Image imgSharp, string outputPath, ImageState imgState, System.Drawing.Image logo, long quality, bool isThumbnail) { // Use ImageSharp drawing APIs to render text and logos and save using ImageSharp encoders. // Clone editable image so we don't mutate the original reference unexpectedly. using var working = imgSharp.Clone(); - // Ensure the EXIF orientation tag is not present on the working image so - // the final saved file has correct upright pixels and won't be - // re-oriented by EXIF-aware viewers. - try - { - working.Metadata?.ExifProfile?.RemoveValue(ExifTag.Orientation); - } - catch (Exception ex) - { - _logger?.LogDebug(ex, "[ImageSharp] Failed to clear EXIF orientation on working image"); - } - - if (_picSettings.RemoveExifData) - { - working.Metadata.ExifProfile = null; - } - // Ensure DataFoto is set (extracted earlier) so time-based text is available imgState.DataFoto = imgState.CreationDate ?? DateTime.Now; - // Ensure thumbnail text is prepared before drawing. + // Ensure thumbnail text is prepared similarly to ImageCreatorSharp logic if (isThumbnail) { if (string.IsNullOrEmpty(imgState.TestoFirmaPiccola)) @@ -140,11 +132,8 @@ public class ImageCreatorImageSharp : IImageCreator } } - // Prepare text. For rotated (vertical) photos prefer the vertical text - // variant coming from the viewmodel/settings (TestoFirmaStartV). - var text = isThumbnail - ? imgState.TestoFirmaPiccola - : ((imgState.FotoRuotaADestra || imgState.FotoRuotaASinistra) ? imgState.TestoFirmaV : imgState.TestoFirma); + // Prepare text + var text = isThumbnail ? imgState.TestoFirmaPiccola : imgState.TestoFirma; if (string.IsNullOrEmpty(text) && _picSettings.TestoNome) text = imgState.NomeFileBig; @@ -178,33 +167,19 @@ public class ImageCreatorImageSharp : IImageCreator } var shadowColor = SixLabors.ImageSharp.Color.FromRgba(0, 0, 0, (byte)imgState.AlphaScelta); - // Find best font size so text fits image width (allow 95% width) and not exceed ~15% height var maxTextWidth = working.Width * 0.95f; var maxTextHeight = working.Height * 0.15f; - // Support multi-line text: measure using the longest line when choosing font size - var normalizedText = text.Replace("\r", string.Empty); - var lines = normalizedText.Split(new[] { '\n' }, StringSplitOptions.None); - var longestLine = lines.OrderByDescending(l => l.Length).FirstOrDefault() ?? string.Empty; - - // Use a line spacing factor when computing allowed font size so multi-line - // text is sized to fit vertically. The existing FindBestFontSize helper - // approximates single-line height; to account for multiple lines pass a - // reduced maxHeight to that helper. - var lineSpacing = 1.1f; // small extra spacing between lines - var adjustedMaxHeight = Math.Max(6f, maxTextHeight / (lines.Length * lineSpacing)); - - var chosenSize = FindBestFontSize(longestLine, font.Name, Math.Max(6, baseSize), maxTextWidth, adjustedMaxHeight); + var chosenSize = FindBestFontSize(text, font.Name, Math.Max(6, baseSize), maxTextWidth, maxTextHeight); // Use final font var finalFont = SixLabors.Fonts.SystemFonts.CreateFont(font.Name, chosenSize); if (!isThumbnail) imgState.DimensioneStandard = (int)Math.Round(chosenSize); // Approximate measured size since TextMeasurer/RendererOptions may not be available in this Fonts version - var approxWidth = finalFont.Size * longestLine.Length * 0.6f; - // Account for multiple lines: height = font size * lineCount * lineSpacing - var approxHeight = finalFont.Size * lines.Length * lineSpacing; + var approxWidth = finalFont.Size * text.Length * 0.6f; + var approxHeight = finalFont.Size * 1.0f; // Compute horizontal position based on alignment float xCenterOfImg; @@ -253,38 +228,22 @@ public class ImageCreatorImageSharp : IImageCreator originX = Math.Max(0, Math.Min(originX, working.Width - approxWidth)); originY = Math.Max(0, Math.Min(originY, working.Height - approxHeight)); - // Draw shadow then text; handle multiple lines - var lineHeight = finalFont.Size * lineSpacing; + // Draw shadow then text working.Mutate(ctx => { - for (int i = 0; i < lines.Length; i++) - { - var line = lines[i]; - var y = originY + i * lineHeight; - // Ensure we're drawing inside the canvas vertically - if (y + finalFont.Size < 0 || y > working.Height) continue; - - // Center each line individually so multi-line (vertical) text is justified to center - var approxWidthLine = finalFont.Size * (line?.Length ?? 0) * 0.6f; - if (approxWidthLine > working.Width) - approxWidthLine = working.Width * 0.95f; - - var x = xCenterOfImg - (approxWidthLine / 2f); - x = Math.Max(0, Math.Min(x, working.Width - approxWidthLine)); - - ctx.DrawText(line, finalFont, shadowColor, new SixLabors.ImageSharp.PointF(x + 1, y + 1)); - ctx.DrawText(line, finalFont, textColor, new SixLabors.ImageSharp.PointF(x, y)); - } + ctx.DrawText(text, finalFont, shadowColor, new SixLabors.ImageSharp.PointF(originX + 1, originY + 1)); + ctx.DrawText(text, finalFont, textColor, new SixLabors.ImageSharp.PointF(originX, originY)); }); } - // Draw logos only on full-size images. - if (logoData != null && logoData.Length > 0 && _picSettings.LogoAggiungi && !isThumbnail) + // Draw logo if provided + if (logo != null && _picSettings.LogoAggiungi) { try { Image logoImg = null; + // Prefer configured file if present, otherwise use the provided System.Drawing.Image instance if (!string.IsNullOrEmpty(_picSettings.LogoNomeFile) && File.Exists(_picSettings.LogoNomeFile)) { using var logoStream = File.OpenRead(_picSettings.LogoNomeFile); @@ -292,7 +251,10 @@ public class ImageCreatorImageSharp : IImageCreator } else { - using var ms = new MemoryStream(logoData); + // Convert System.Drawing.Image to ImageSharp by saving to PNG in-memory to preserve alpha + await using var ms = new MemoryStream(); + logo.Save(ms, System.Drawing.Imaging.ImageFormat.Png); + ms.Seek(0, SeekOrigin.Begin); logoImg = await SixLabors.ImageSharp.Image.LoadAsync(ms).ConfigureAwait(false); } @@ -406,7 +368,7 @@ public class ImageCreatorImageSharp : IImageCreator } catch (Exception ex) { - _logger.LogError(ex, "[ImageSharp] Invalid transparent color setting {Color}", _picSettings.TransparentColor); + _logger.LogError(ex, "[Alternate] Invalid transparent color setting {Color}", _picSettings.TransparentColor); } } @@ -421,7 +383,7 @@ public class ImageCreatorImageSharp : IImageCreator } catch (Exception ex) { - _logger.LogError(ex, "[ImageSharp] Error drawing logo"); + _logger.LogError(ex, "[Alternate] Error drawing logo in ImageSharp pass"); } } @@ -436,6 +398,8 @@ public class ImageCreatorImageSharp : IImageCreator await working.SaveAsync(outStream, encoder).ConfigureAwait(false); } + // Removed GDI encoder helper; ImageSharp encoders are used instead. + private void PrepareVariablesMinimal(ImageState imgState) { imgState.NomeFileBig = imgState.WorkFile.Name; @@ -444,13 +408,11 @@ public class ImageCreatorImageSharp : IImageCreator imgState.DimensioneStandardMiniatura = _picSettings.DimStandardMiniatura; // basic text / transparency defaults used by drawing routines + // AlphaScelta mirrors ImageCreatorSharp behavior: compute from PicSettings.Trasparenza (0-100) imgState.AlphaScelta = Convert.ToInt32((255 * (100 - _picSettings.Trasparenza) / (double)100)); // Set minimal text fields so text drawing has fallback values imgState.TestoFirma ??= _picSettings.TestoFirmaStart ?? string.Empty; - // Ensure vertical text is populated from settings so callers can - // select the proper variant when drawing vertical photos. - imgState.TestoFirmaV ??= _picSettings.TestoFirmaStartV ?? string.Empty; imgState.TestoFirmaPiccola ??= string.Empty; imgState.DataPartenzaI = _picSettings.DataPartenza; imgState.TestoOrario = _picSettings.TestoOrario ?? string.Empty; @@ -506,29 +468,7 @@ public class ImageCreatorImageSharp : IImageCreator private void ApplyExifOrientation(Image img, ImageState imgState) { - // Set rotation flags on the state so other code can pick the correct text variant. - imgState.FotoRuotaADestra = false; - imgState.FotoRuotaASinistra = false; - - if (_picSettings.UsaRotazioneAutomatica) - { - switch (imgState.Orientation) - { - case Orientations.BottomLeft: - case Orientations.BottomRight: - case Orientations.LeftTop: - case Orientations.LftBottom: - imgState.FotoRuotaASinistra = true; - break; - case Orientations.RightBottom: - case Orientations.RightTop: - case Orientations.TopLeft: - case Orientations.TopRight: - // no-op - break; - } - } - + // Common EXIF orientations: 1=TopLeft, 3=BottomRight (rotate 180), 6=RightTop (rotate 90 CW), 8=LeftBottom (rotate 270 CW) switch (imgState.Orientation) { case Orientations.RightTop: // 6 @@ -543,22 +483,9 @@ public class ImageCreatorImageSharp : IImageCreator default: break; } - - // After applying the pixel rotation, remove the EXIF orientation tag so - // viewers do not re-apply the rotation. Leaving the tag causes some - // viewers to display the image in the wrong (original) orientation. - try - { - img.Metadata?.ExifProfile?.RemoveValue(ExifTag.Orientation); - } - catch (Exception ex) - { - // Non-fatal: log and continue - _logger?.LogDebug(ex, "[ImageSharp] Could not clear EXIF orientation tag"); - } } - private Size ComputeBigSize(int width, int height) + private System.Drawing.Size ComputeBigSize(int width, int height) { // If original large size option requested, return original // otherwise compute based on width/height limits from settings @@ -567,14 +494,16 @@ public class ImageCreatorImageSharp : IImageCreator : CalculateThumbnailSize(width, height, _picSettings.AltezzaBig, "Altezza"); } - private Size ComputeSmallSize(int width, int height) + private System.Drawing.Size ComputeSmallSize(int width, int height) { return width > height ? CalculateThumbnailSize(width, height, _picSettings.LarghezzaSmall, "Larghezza") : CalculateThumbnailSize(width, height, _picSettings.AltezzaSmall, "Altezza"); } - private static Size CalculateThumbnailSize(int currentwidth, int currentheight, int maxPixel, string tipoSize) + // Helper to access PicSettings values via instance _picSettings + + private static System.Drawing.Size CalculateThumbnailSize(int currentwidth, int currentheight, int maxPixel, string tipoSize) { double tempMultiplier; if (string.Equals(tipoSize, "Larghezza", StringComparison.OrdinalIgnoreCase)) @@ -586,7 +515,7 @@ public class ImageCreatorImageSharp : IImageCreator else tempMultiplier = maxPixel / (double)currentwidth; - var newSize = new Size(Convert.ToInt32(currentwidth * tempMultiplier), Convert.ToInt32(currentheight * tempMultiplier)); + var newSize = new System.Drawing.Size(Convert.ToInt32(currentwidth * tempMultiplier), Convert.ToInt32(currentheight * tempMultiplier)); return newSize; } diff --git a/MaddoShared/ImageCreatorMapper.cs b/MaddoShared/ImageCreatorMapper.cs new file mode 100644 index 0000000..8ee07cf --- /dev/null +++ b/MaddoShared/ImageCreatorMapper.cs @@ -0,0 +1,49 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; + +namespace MaddoShared; + +/// +/// Dynamically resolves the concrete IImageCreator implementation at call time +/// based on current PicSettings.ImageCreatorProvider. +/// +public class ImageCreatorMapper : IImageCreator +{ + private readonly IServiceProvider _sp; + private readonly PicSettings _settings; + private readonly ILogger _logger; + + public ImageCreatorMapper(IServiceProvider sp, PicSettings settings, ILogger logger) + { + _sp = sp ?? throw new ArgumentNullException(nameof(sp)); + _settings = settings ?? throw new ArgumentNullException(nameof(settings)); + _logger = logger; + } + + public Task CreateImageAsync(ImageState imgState, System.Drawing.Image logo) + { + var provider = (_settings.ImageCreatorProvider ?? "Sharp").Trim(); + _logger?.LogDebug("Resolving IImageCreator for provider '{Provider}'", provider); + + return provider.Equals("ALTERNATE", StringComparison.OrdinalIgnoreCase) + ? ResolveAndCall(imgState, logo) + : ResolveAndCall(imgState, logo); + } + + private Task ResolveAndCall(ImageState imgState, System.Drawing.Image logo) where T : IImageCreator + { + // Resolve the concrete implementation and forward the call + var impl = (IImageCreator)_sp.GetService(typeof(T)); + if (impl is null) + { + _logger?.LogWarning("Requested image creator {Type} is not registered. Falling back to ImageCreatorSharp.", typeof(T).Name); + impl = (IImageCreator)_sp.GetService(typeof(ImageCreatorSharp)); + } + + if (impl is null) + throw new InvalidOperationException("No IImageCreator implementation is registered."); + + return impl.CreateImageAsync(imgState, logo); + } +} diff --git a/MaddoShared/ImageCreatorSharp.cs b/MaddoShared/ImageCreatorSharp.cs new file mode 100644 index 0000000..b430a36 --- /dev/null +++ b/MaddoShared/ImageCreatorSharp.cs @@ -0,0 +1,863 @@ +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.Globalization; +using System.IO; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using SixLabors.ImageSharp.Metadata.Profiles.Exif; + +// Imports System.Threading + +namespace MaddoShared; + +[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility")] +public class ImageCreatorSharp(PicSettings picSettings, ILogger logger) : IImageCreator +{ + public async Task CreateImageAsync(ImageState imgState, Image logo) + { + try + { + await Task.Run(() => + { + logger.LogInformation("File: {FileInfo} Dest: {DirectoryInfo}", imgState.WorkFile, imgState.DestDir); + PrepareVariables(imgState); + ExtractExif(imgState); + + using var g = Image.FromFile(imgState.WorkFile.FullName); + + // Set extra text + SetExtraText(g, imgState); + + // Rotate image according to EXIF + ApplyRotation(g, imgState); + + // Force jpeg if option selected + var thisFormat = g.RawFormat; + if (picSettings.UsaForzaJpg) + thisFormat = ImageFormat.Jpeg; + + PrepareThumbnailSize(g, imgState); + + using var imgOutputBig = new Bitmap(g, imgState.ThumbSizeBig.Width, imgState.ThumbSizeBig.Height); + + imgOutputBig.SetResolution(g.HorizontalResolution, g.VerticalResolution); + + // Create thumbnails + CreateThumbnails(g, imgState, imgOutputBig, thisFormat); + + AddText(g, imgState, imgOutputBig); + + AddLogo(imgOutputBig, logo); + + SavePhoto(imgOutputBig, imgState, thisFormat); + }).ConfigureAwait(false); + } + + catch (Exception ex) + { + var e = ex.Demystify(); + logger.LogError(e, "Error in processing photo {WorkFileName}", imgState.WorkFile.Name); + } + } + + private void ExtractExif(ImageState imgState) + { + using var img = SixLabors.ImageSharp.Image.Load(imgState.WorkFile.FullName); + imgState.Orientation = Orientations.TopLeft; + + IExifValue rotation = null; + + var exifProfile = img.Metadata?.ExifProfile; + var found = exifProfile != null && exifProfile.TryGetValue(ExifTag.Orientation, out rotation); + + if (found) + { + var intOrientation = rotation.Value.ToInt32(); + imgState.Orientation = (Orientations)intOrientation; + } + + IExifValue date = null; + var creationFound = exifProfile != null && exifProfile.TryGetValue(ExifTag.DateTimeOriginal, out date); + if (creationFound) + { + var succ = DateTime.TryParseExact(date.Value, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture, + DateTimeStyles.None, out var crDate); + if (succ) + { + imgState.CreationDate = crDate; + } + else + { + imgState.CreationDate = null; + } + } + else + { + imgState.CreationDate = null; + } + } + + private void ApplyRotation(Image g, ImageState imgState) + { + imgState.FotoRuotaADestra = false; + imgState.FotoRuotaASinistra = false; + + if (picSettings.UsaRotazioneAutomatica && g.PropertyIdList.Length > 0) + { + switch (imgState.Orientation) + { + case Orientations.BottomLeft: + case Orientations.BottomRight: + case Orientations.LeftTop: + case Orientations.LftBottom: + imgState.FotoRuotaASinistra = true; + break; + case Orientations.RightBottom: + case Orientations.RightTop: + case Orientations.TopLeft: + case Orientations.TopRight: + break; + } + } + + if (imgState.FotoRuotaASinistra) + g.RotateFlip(RotateFlipType.Rotate270FlipNone); + if (imgState.FotoRuotaADestra) + g.RotateFlip(RotateFlipType.Rotate90FlipNone); + } + + /// + /// ''' Aggiunge Orario, tempo gara e altri + /// ''' + /// ''' Image + /// + /// ''' + private void SetExtraText(Image g, ImageState imgState) + { + if (picSettings.UsaOrarioTestoApplicare || picSettings.UsaTempoGaraTestoApplicare || + picSettings.UsaOrarioMiniatura || picSettings.TestoMin || picSettings.AggTempoGaraMin || + picSettings.AggNumTempMin) + { + if (g.PropertyIdList.Length <= 0) return; + imgState.DataFoto = imgState.CreationDate ?? DateTime.Now; + imgState.TestoFirma = picSettings.TestoFirmaStart; + imgState.TestoFirmaV = picSettings.TestoFirmaStartV; + + if (imgState.DataFoto.Year == 1) return; + imgState.TestoFirmaPiccola = imgState.DataFoto.ToShortTimeString(); + if (picSettings.UsaOrarioTestoApplicare) + { + imgState.TestoFirma += + $" {imgState.DataFoto.ToShortDateString()} {imgState.DataFoto.ToLongTimeString()}"; + imgState.TestoFirmaV += + $" {imgState.DataFoto.ToShortDateString()} {imgState.DataFoto.ToLongTimeString()}"; + } + + if (!picSettings.UsaTempoGaraTestoApplicare) return; + var diff = imgState.DataFoto - imgState.DataPartenzaI; + imgState.TestoFirma += $" {imgState.TestoOrario}{diff.Hours:00}:{diff.Minutes:00}:{diff.Seconds:00}"; + imgState.TestoFirmaV += $" {imgState.TestoOrario}{diff.Hours:00}:{diff.Minutes:00}:{diff.Seconds:00}"; + } + else + { + imgState.TestoFirma = picSettings.TestoFirmaStart; + imgState.TestoFirmaV = picSettings.TestoFirmaStartV; + } + } + + /// + /// ''' Prepara diverse variabili azzerandole, elaborandole e prendendole dalle impostazioni + /// ''' + /// ''' + private void PrepareVariables(ImageState imgState) + { + imgState.AlphaScelta = System.Convert.ToInt32((255 * (100 - picSettings.Trasparenza) / (double)100)); + imgState.TestoFirma = ""; + imgState.TestoFirmaV = ""; + imgState.DataPartenzaI = picSettings.DataPartenza; + imgState.TestoOrario = picSettings.TestoOrario; + if (imgState.TestoOrario.Length > 0) + imgState.TestoOrario += " "; + imgState.TestoFirmaPiccola = ""; + imgState.ThumbSizeSmall = new Size(); + imgState.ThumbSizeBig = new Size(); + imgState.NomeFileSmall = ""; + imgState.NomeFileBig2 = ""; + imgState.NomeFileBig = ""; + imgState.DimensioneStandard = picSettings.DimStandard; + imgState.DimensioneStandardMiniatura = picSettings.DimStandardMiniatura; + // nomeFileSmall = Suffisso & NomeFileChild + // nomeFileBig = NomeFileChild + imgState.NomeFileSmall = picSettings.Suffisso + imgState.WorkFile.Name; + imgState.NomeFileBig = imgState.WorkFile.Name; + // Sanitize file names to avoid invalid characters causing IO errors + imgState.NomeFileSmall = SanitizeFileName(imgState.NomeFileSmall); + imgState.NomeFileBig = SanitizeFileName(imgState.NomeFileBig); + } + + private static string SanitizeFileName(string fileName) + { + if (string.IsNullOrEmpty(fileName)) return fileName; + var invalid = Path.GetInvalidFileNameChars(); + var sb = new System.Text.StringBuilder(fileName.Length); + foreach (var ch in fileName) + { + sb.Append(Array.IndexOf(invalid, ch) >= 0 ? '_' : ch); + } + return sb.ToString(); + } + + private void PrepareThumbnailSize(Image g, ImageState imgState) + { + if (g.Width > g.Height) + { + imgState.ThumbSizeSmall = CalculateThumbnailSize(g.Width, g.Height, picSettings.LarghezzaSmall, "Larghezza"); + var sizeOrig = new Size(g.Width, g.Height); + imgState.ThumbSizeBig = sizeOrig; + } + else + { + imgState.ThumbSizeSmall = CalculateThumbnailSize(g.Width, g.Height, picSettings.AltezzaSmall, "Altezza"); + var sizeOrig = new Size(g.Width, g.Height); + imgState.ThumbSizeBig = sizeOrig; + } + } + + private void CreateThumbnails(Image sourceImage, ImageState imgState, Bitmap imgOutputBig, ImageFormat format) + { + // Only skip thumbnail generation when the global "create thumbnails" flag is false. + // Whether thumbnails include text is handled by ShouldRenderText/CreateThumbnailWithText + if (!picSettings.CreaMiniature) + return; + + PrepareSignatureText(imgState); + + if (IsSameDirectory(picSettings.DirectorySorgente, picSettings.DirectoryDestinazione)) + UpdateFilenameWithCode(imgState); + + if (ShouldRenderText()) + CreateThumbnailWithText(sourceImage, imgState, imgOutputBig, format); + else + CreateSimpleThumbnail(sourceImage, imgState, format); + } + + private void PrepareSignatureText(ImageState imgState) + { + if (picSettings.TestoMin) + imgState.TestoFirmaPiccola = imgState.NomeFileBig; + else if (picSettings.AggNumTempMin) + imgState.TestoFirmaPiccola = imgState.NomeFileBig + " "; + } + + private bool IsSameDirectory(string dir1, string dir2) => + string.Equals(dir1, dir2, StringComparison.OrdinalIgnoreCase); + + private void UpdateFilenameWithCode(ImageState imgState) + { + var name = imgState.NomeFileSmall; + imgState.NomeFileSmall = name[..^4] + picSettings.Codice + name[^4..]; + } + + private bool ShouldRenderText() => + picSettings.UsaOrarioMiniatura || picSettings.TestoMin || picSettings.AggTempoGaraMin || + picSettings.AggNumTempMin; + + private void CreateSimpleThumbnail(Image image, ImageState imgState, ImageFormat format) + { + using var thumbnail = new Bitmap(image, imgState.ThumbSizeSmall.Width, imgState.ThumbSizeSmall.Height); + thumbnail.Save(Path.Combine(imgState.DestDir.FullName, imgState.NomeFileSmall), format); + } + + private void CreateThumbnailWithText(Image image, ImageState imgState, Bitmap sourceBitmap, ImageFormat format) + { + if (imgState.TestoFirmaPiccola.Length == 0) + { + CreateSimpleThumbnail(image, imgState, format); + return; + } + + using var imgOutputSmall = (Bitmap)sourceBitmap.Clone(); + using var graphics = Graphics.FromImage(imgOutputSmall); + graphics.SmoothingMode = SmoothingMode.AntiAlias; + + // Use the user's configured font size directly + using var font1 = CreateFont(picSettings.IlFont, imgState.DimensioneStandardMiniatura, picSettings.Grassetto); + var textSize = graphics.MeasureString(imgState.TestoFirmaPiccola, font1); + + // Adjust font if it's too large for the image dimensions + // Keep text height under 15% of image height to ensure proper spacing when resized + // This leaves room for margins and prevents clipping + int tempFontSize = imgState.DimensioneStandardMiniatura; + float maxTextHeight = image.Height * 0.15f; + + while ((textSize.Width > image.Width * 0.95f || textSize.Height > maxTextHeight) && tempFontSize > 5) + { + tempFontSize = (tempFontSize > 20) ? tempFontSize - 5 : tempFontSize - 1; + using var tempFont = CreateFont(picSettings.IlFont, tempFontSize, picSettings.Grassetto); + textSize = graphics.MeasureString(imgState.TestoFirmaPiccola, tempFont); + } + + // Re-measure text with the final font size for accurate positioning + using var finalFont = CreateFont(picSettings.IlFont, tempFontSize, picSettings.Grassetto); + var finalTextSize = graphics.MeasureString(imgState.TestoFirmaPiccola, finalFont); + + SetVerticalPosition(image.Height, finalTextSize.Height, imgState); + + float xCenter = CalculateHorizontalAlignment(image.Width, finalTextSize.Width); + using var stringFormat = new StringFormat(); + stringFormat.Alignment = StringAlignment.Center; + + using var shadowBrush = new SolidBrush(Color.FromArgb(imgState.AlphaScelta, 0, 0, 0)); + using var textBrush = new SolidBrush(Color.FromArgb(imgState.AlphaScelta, picSettings.FontColoreRGB)); + + DrawText(graphics, imgState, xCenter, stringFormat, shadowBrush, textBrush, finalFont); + + using var finalThumb = + new Bitmap(imgOutputSmall, imgState.ThumbSizeSmall.Width, imgState.ThumbSizeSmall.Height); + finalThumb.Save(Path.Combine(imgState.DestDir.FullName, imgState.NomeFileSmall), format); + } + + private Font CreateFont(string fontName, int size, bool bold) => + new Font(fontName, size, bold ? FontStyle.Bold : FontStyle.Regular); + + private int FindBestFontSize(Graphics g, string text, string fontName, int maxSize, bool bold, int maxWidth, int minSize = 5) + { + if (maxSize <= minSize) return Math.Max(minSize, maxSize); + + int low = minSize; + int high = Math.Max(minSize, maxSize); + int best = minSize; + + while (low <= high) + { + int mid = (low + high) / 2; + using var testFont = CreateFont(fontName, mid, bold); + var measured = g.MeasureString(text, testFont); + if (measured.Width <= maxWidth) + { + best = mid; + low = mid + 1; // try larger + } + else + { + high = mid - 1; // too big + } + } + + return best; + } + + + private void AddText(Image g, ImageState imgState, Bitmap imgOutputBig) + { + using var grPhoto = Graphics.FromImage(imgOutputBig); + grPhoto.SmoothingMode = SmoothingMode.AntiAlias; + + // Determine best base font size using a binary search (faster than decremental loop) + int availableWidth = (int)g.Width; + int targetBaseSize = imgState.DimensioneStandard > 0 ? imgState.DimensioneStandard : picSettings.DimStandard; + int bestBaseSize = FindBestFontSize(grPhoto, imgState.TestoFirma ?? string.Empty, picSettings.IlFont, targetBaseSize, picSettings.Grassetto, availableWidth); + imgState.DimensioneStandard = bestBaseSize; + + // Decide final drawing size (use DimVert if rotated) + int drawSize = (imgState.FotoRuotaADestra || imgState.FotoRuotaASinistra) ? picSettings.DimVert : imgState.DimensioneStandard; + + using var drawFont = CreateFont(picSettings.IlFont, drawSize, picSettings.Grassetto); + var crSize = grPhoto.MeasureString(imgState.TestoFirma ?? string.Empty, drawFont); + var larghezzaStandard = Convert.ToInt32(crSize.Width); + + // Vertical positions + switch (picSettings.Posizione.ToUpper()) + { + case "ALTO": + { + imgState.YPosFromBottom = picSettings.Margine; + imgState.YPosFromBottom3 = picSettings.MargVert; + break; + } + + case "BASSO": + { + imgState.YPosFromBottom = + Convert.ToSingle((g.Height - crSize.Height - (g.Height * picSettings.Margine / 100.0))); + imgState.YPosFromBottom3 = + Convert.ToSingle((g.Height - crSize.Height - (g.Height * picSettings.MargVert / 100.0))); + break; + } + } + + float xCenterOfImg = 0; + using var strFormat = new StringFormat(); + switch (picSettings.Allineamento.ToUpper()) + { + case "SINISTRA": + { + xCenterOfImg = Convert.ToSingle((picSettings.Margine + (larghezzaStandard / (double)2))); + if ((larghezzaStandard / (double)2) > (g.Width / (double)2) - picSettings.Margine) + xCenterOfImg = Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "CENTRO": + { + xCenterOfImg = Convert.ToSingle((g.Width / (double)2)); + break; + } + + case "DESTRA": + { + xCenterOfImg = + Convert.ToSingle((g.Width - picSettings.Margine - (larghezzaStandard / (double)2))); + if ((larghezzaStandard / (double)2) > (g.Width / (double)2) - picSettings.Margine) + xCenterOfImg = Convert.ToSingle((g.Width / (double)2)); + break; + } + } + + strFormat.Alignment = StringAlignment.Center; + + using var semiTransBrush2 = new SolidBrush(Color.FromArgb(imgState.AlphaScelta, 0, 0, 0)); + using var semiTransBrush = new SolidBrush(Color.FromArgb(imgState.AlphaScelta, picSettings.FontColoreRGB)); + + // write text (NomeFileBig) + if (picSettings.TestoNome) + { + if (picSettings.NomeData && g.PropertyIdList.Length > 0) + { + imgState.DataFoto = imgState.CreationDate ?? DateTime.Now; + + grPhoto.DrawString((imgState.NomeFileBig + " " + imgState.DataFoto.ToShortDateString()), drawFont, + semiTransBrush2, new PointF(xCenterOfImg + 1, imgState.YPosFromBottom + 1), strFormat); + grPhoto.DrawString((imgState.NomeFileBig + " " + imgState.DataFoto.ToShortDateString()), drawFont, + semiTransBrush, new PointF(xCenterOfImg, imgState.YPosFromBottom), strFormat); + } + else + { + grPhoto.DrawString(imgState.NomeFileBig, drawFont, semiTransBrush2, + new PointF(xCenterOfImg + 1, imgState.YPosFromBottom + 1), strFormat); + grPhoto.DrawString(imgState.NomeFileBig, drawFont, semiTransBrush, + new PointF(xCenterOfImg, imgState.YPosFromBottom), strFormat); + } + } + else + { + if (imgState.FotoRuotaADestra || imgState.FotoRuotaASinistra) + { + if (!picSettings.TestoMin) + { + grPhoto.DrawString(imgState.TestoFirmaV, drawFont, semiTransBrush2, + new PointF(xCenterOfImg + 1, imgState.YPosFromBottom3 + 1), strFormat); + grPhoto.DrawString(imgState.TestoFirmaV, drawFont, semiTransBrush, + new PointF(xCenterOfImg, imgState.YPosFromBottom3), strFormat); + } + + if (picSettings.TestoMin) + { + grPhoto.DrawString(imgState.TestoFirmaV, drawFont, semiTransBrush2, + new PointF(xCenterOfImg + 1, imgState.YPosFromBottom4 + 1), strFormat); + grPhoto.DrawString(imgState.TestoFirmaV, drawFont, semiTransBrush, + new PointF(xCenterOfImg, imgState.YPosFromBottom4), strFormat); + } + } + else + { + grPhoto.DrawString(imgState.TestoFirma, drawFont, semiTransBrush2, + new PointF(xCenterOfImg + 1, imgState.YPosFromBottom + 1), strFormat); + grPhoto.DrawString(imgState.TestoFirma, drawFont, semiTransBrush, + new PointF(xCenterOfImg, imgState.YPosFromBottom), strFormat); + } + } + + if (string.Equals(picSettings.DirectorySorgente, picSettings.DirectoryDestinazione, + StringComparison.OrdinalIgnoreCase)) + { + imgState.NomeFileBig2 = imgState.NomeFileBig; + imgState.NomeFileBig = $"{imgState.NomeFileBig[..^4]}{picSettings.Codice}{imgState.NomeFileBig[^4..]}"; + } + } + + private void AddLogo(Bitmap imgOutputBig, Image logo) + { + // Skip if no logo provided + if (logo is null) return; + + // Load check (use short-circuit &&) + if (!(picSettings.LogoAggiungi && File.Exists(picSettings.LogoNomeFile))) return; + + // Decide whether to apply a color-key transparency remap or rely on existing image alpha. + // If UseTransparentColor is true, parse the configured TransparentColor and remap it to fully transparent. + using var grWatermark = Graphics.FromImage(imgOutputBig); + using ImageAttributes imageAttributes = new ImageAttributes(); + + if (picSettings.UseTransparentColor) + { + Color keyColor = Color.White; + try + { + if (!string.IsNullOrWhiteSpace(picSettings.TransparentColor)) + { + // ColorTranslator accepts both "#RRGGBB" and "RRGGBB" + keyColor = ColorTranslator.FromHtml(picSettings.TransparentColor); + } + } + catch + { + keyColor = Color.White; + } + + var colorMap = new ColorMap + { + // background: the color we search for and replace with transparency + OldColor = keyColor, + NewColor = Color.FromArgb(0, 0, 0, 0) + }; + + var remapTable = new[] { colorMap }; + imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); + } + + // * The second color manipulation is used to change the opacity by setting the 3rd row and 3rd column to 0.3f + // Parse transparency safely (default to 100 if parsing fails) + if (!int.TryParse(picSettings.LogoTrasparenza, out var logoTransparencyValue)) + { + logoTransparencyValue = 100; + } + + var colorMatrixElements = new[] + { + new[] { 1.0F, 0.0F, 0.0F, 0.0F, 0.0F }, new[] { 0.0F, 1.0F, 0.0F, 0.0F, 0.0F }, + new[] { 0.0F, 0.0F, 1.0F, 0.0F, 0.0F }, + new[] { 0.0F, 0.0F, 0.0F, System.Convert.ToSingle(logoTransparencyValue) / 100F, 0.0F }, + new[] { 0.0F, 0.0F, 0.0F, 0.0F, 1.0F } + }; + var wmColorMatrix = new ColorMatrix(colorMatrixElements); + imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); + + var fotoLogoH = picSettings.LogoAltezza; + var fotoLogoW = picSettings.LogoLarghezza; + var fattoreAlt = logo.Height / (double)fotoLogoH; + var fattoreLarg = logo.Width / (double)fotoLogoW; + var nuovaSize = fattoreLarg > fattoreAlt + ? CalculateThumbnailSize(logo.Width, logo.Height, fotoLogoW, "Larghezza") + : CalculateThumbnailSize(logo.Width, logo.Height, fotoLogoH, "Altezza"); + + // Guard against null/empty LogoMargine and percentage parsing + var logoMargineStr = picSettings.LogoMargine ?? string.Empty; + var inPercentualeL = logoMargineStr.EndsWith('%'); + var margineL = 0; + if (inPercentualeL) + { + var trimmed = logoMargineStr.TrimEnd('%'); + if (!int.TryParse(trimmed, out margineL)) margineL = 0; + } + else + { + if (!int.TryParse(logoMargineStr, out margineL)) margineL = 0; + } + var margineUsato = + inPercentualeL ? System.Convert.ToInt32(imgOutputBig.Height * margineL / (double)100) : margineL; + + int xPosOfWm = 0; + int yPosOfWm = 0; + var logoH = (picSettings.LogoPosizioneH ?? "NESSUNA").ToUpperInvariant(); + var logoV = (picSettings.LogoPosizioneV ?? "NESSUNA").ToUpperInvariant(); + switch (logoH) + { + case "SINISTRA": + case "NESSUNA": + { + xPosOfWm = margineUsato; + break; + } + + case "CENTRO": + { + xPosOfWm = System.Convert.ToInt32((imgOutputBig.Width - nuovaSize.Width) / (double)2); + break; + } + + case "DESTRA": + { + xPosOfWm = ((imgOutputBig.Width - nuovaSize.Width) - margineUsato); + break; + } + } + + switch (logoV) + { + case "ALTO": + case "NESSUNA": + { + yPosOfWm = margineUsato; + break; + } + + case "CENTRO": + { + yPosOfWm = System.Convert.ToInt32((imgOutputBig.Height - nuovaSize.Height) / (double)2); + break; + } + + case "BASSO": + { + yPosOfWm = ((imgOutputBig.Height - nuovaSize.Height) - margineUsato); + break; + } + } + + grWatermark.DrawImage(logo, new Rectangle(xPosOfWm, yPosOfWm, nuovaSize.Width, nuovaSize.Height), 0, 0, + logo.Width, logo.Height, GraphicsUnit.Pixel, imageAttributes); + //grWatermark.Dispose(); + } + + + private void SavePhoto(Bitmap imgOutputBig, ImageState imgState, ImageFormat thisFormat) + { + var fileName = Path.Combine(imgState.DestDir.FullName, imgState.NomeFileBig); + + using var image1Stream = new MemoryStream(); + if (picSettings.FotoGrandeDimOrigina == false) + { + // attenzione non controlla se è png + // imgOutputBig.Save(Path.Combine(_DestDir.FullName, "Temp_" & NomeFileBig), thisFormat) + if (thisFormat.Equals(ImageFormat.Jpeg)) + { + MakeImageCustomQuality(imgOutputBig, image1Stream, picSettings.JpegQuality); + } + //SalvaImmagineCustomQuality(imgOutputBig, Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig), _picSettings.jpegQuality); + else + { + imgOutputBig.Save(image1Stream, thisFormat); + } + + //imgOutputBig.Save(Path.Combine(DestDir.FullName, "Temp_" + NomeFileBig), thisFormat); + image1Stream.Seek(0, SeekOrigin.Begin); + using var g2 = Image.FromStream(image1Stream); + imgState.ThumbSizeBig = g2.Width > g2.Height + ? CalculateThumbnailSize(g2.Width, g2.Height, picSettings.LarghezzaBig, "Larghezza") + : CalculateThumbnailSize(g2.Width, g2.Height, picSettings.AltezzaBig, "Altezza"); + using var imgOutputBig2 = new Bitmap(g2, imgState.ThumbSizeBig.Width, imgState.ThumbSizeBig.Height); + + if (!picSettings.OverwriteFiles && File.Exists(fileName)) + { + logger.LogInformation("Saltata foto {FileName}, esiste", fileName); + } + else + { + if (thisFormat.Equals(ImageFormat.Jpeg)) + SaveImageCustomQuality(imgOutputBig2, fileName, picSettings.JpegQuality); + else + imgOutputBig2.Save(fileName, thisFormat); + } + } + else + { + if (!picSettings.OverwriteFiles && File.Exists(fileName)) + { + logger.LogInformation("Saltata foto {FileName}, esiste", fileName); + } + else + { + if (thisFormat.Equals(ImageFormat.Jpeg)) + SaveImageCustomQuality(imgOutputBig, fileName, picSettings.JpegQuality); + else + imgOutputBig.Save(fileName, thisFormat); + } + } + + image1Stream.Seek(0, SeekOrigin.Begin); + + if (!picSettings.CreaMiniature) return; + if (!picSettings.AggiungiScritteMiniature) return; + + using var g1 = picSettings.FotoGrandeDimOrigina ? (Image)imgOutputBig.Clone() : Image.FromStream(image1Stream); + + using var imgOutputSmall = new Bitmap(g1, imgState.ThumbSizeSmall.Width, imgState.ThumbSizeSmall.Height); + + if (string.Equals(picSettings.DirectorySorgente, picSettings.DirectoryDestinazione, + StringComparison.OrdinalIgnoreCase)) + imgState.NomeFileSmall = imgState.NomeFileSmall.Substring(0, imgState.NomeFileSmall.Length - 4) + + picSettings.Codice + + imgState.NomeFileSmall.Substring(imgState.NomeFileSmall.Length - 4); + + var tnFileName = Path.Combine(imgState.DestDir.FullName, imgState.NomeFileSmall); + + if (!picSettings.OverwriteFiles && File.Exists(tnFileName)) + { + logger.LogInformation("Saltata miniatura foto {TnFileName}, esiste", tnFileName); + } + else + { + if (thisFormat.Equals(ImageFormat.Jpeg)) + SaveImageCustomQuality(imgOutputSmall, tnFileName, picSettings.JpegQualityMin); + else + imgOutputSmall.Save(tnFileName, thisFormat); + } + } + + private void SaveImageCustomQuality(Bitmap imageToSave, string nomeFileFinale, long quality) + { + var jgpEncoder = GetEncoder(ImageFormat.Jpeg); + var myEncoder = System.Drawing.Imaging.Encoder.Quality; + + using var myEncoderParameters = new EncoderParameters(1); + + var myEncoderParameter = new EncoderParameter(myEncoder, quality); + myEncoderParameters.Param[0] = myEncoderParameter; + imageToSave.Save(nomeFileFinale, jgpEncoder, myEncoderParameters); + //imageToSave.Dispose(); + } + + private void MakeImageCustomQuality(Bitmap imageToSave, Stream destinationStream, long quality) + { + var jgpEncoder = GetEncoder(ImageFormat.Jpeg); + var myEncoder = System.Drawing.Imaging.Encoder.Quality; + + using var myEncoderParameters = new EncoderParameters(1); + + var myEncoderParameter = new EncoderParameter(myEncoder, quality); + myEncoderParameters.Param[0] = myEncoderParameter; + destinationStream.Seek(0, SeekOrigin.Begin); + imageToSave.Save(destinationStream, jgpEncoder, myEncoderParameters); + //imageToSave.Dispose(); + } + + private ImageCodecInfo GetEncoder(ImageFormat format) + { + var codecs = ImageCodecInfo.GetImageDecoders(); + + foreach (var codec in codecs) + { + if (codec.FormatID == format.Guid) + return codec; + } + + return null /* TODO Change to default(_) if this is not a reference type */; + } + + /// + /// ''' Calculate the Size of the New image + /// ''' + /// ''' Larghezza + /// ''' Altezza + /// ''' + /// ''' + /// ''' + /// ''' + private Size CalculateThumbnailSize(int currentwidth, int currentheight, int maxPixel, string tipoSize) + { + // e + // *** Larghezza, Altezza, Auto + + double tempMultiplier; + + if (tipoSize.ToUpper() == "Larghezza".ToUpper()) + tempMultiplier = maxPixel / (double)currentwidth; + else if (tipoSize.ToUpper() == "Altezza".ToUpper()) + tempMultiplier = maxPixel / (double)currentheight; + else if (currentheight > currentwidth) + tempMultiplier = maxPixel / (double)currentheight; + else + tempMultiplier = maxPixel / (double)currentwidth; + + var newSize = new Size(System.Convert.ToInt32(currentwidth * tempMultiplier), + System.Convert.ToInt32(currentheight * tempMultiplier)); + + return newSize; + } + + private void SetVerticalPosition(int imgHeight, float textHeight, ImageState imgState) + { + // Use 1% of image height as minimum margin, or 10px, whichever is larger + float minMargin = Math.Max(10f, imgHeight * 0.01f); + + switch (picSettings.Posizione.ToUpper()) + { + case "ALTO": + imgState.YPosFromBottom1 = Math.Max(minMargin, picSettings.Margine); + imgState.YPosFromBottom4 = Math.Max(minMargin, picSettings.MargVert); + break; + + case "BASSO": + var bottomMargin1 = (float)(imgHeight * picSettings.Margine / 100.0); + var bottomMargin4 = (float)(imgHeight * picSettings.MargVert / 100.0); + + // Position from bottom: bottom edge of text at desired margin from bottom + // Y = imageHeight - textHeight - bottomMargin + var desiredY1 = imgHeight - textHeight - bottomMargin1; + var desiredY4 = imgHeight - textHeight - bottomMargin4; + + // Ensure text stays completely within bounds: + // - Top edge must be >= minMargin (not clipped at top) + // - Bottom edge must be <= imgHeight - minMargin (not clipped at bottom) + var maxAllowedY1 = imgHeight - textHeight - minMargin; // Maximum Y to keep bottom margin + var maxAllowedY4 = imgHeight - textHeight - minMargin; + + imgState.YPosFromBottom1 = Math.Max(minMargin, Math.Min(desiredY1, maxAllowedY1)); + imgState.YPosFromBottom4 = Math.Max(minMargin, Math.Min(desiredY4, maxAllowedY4)); + break; + + case "CENTRO": + default: + // Center the text vertically + var centeredY = (imgHeight - textHeight) / 2f; + // Clamp to ensure margins are respected + imgState.YPosFromBottom1 = Math.Max(minMargin, Math.Min(centeredY, imgHeight - textHeight - minMargin)); + imgState.YPosFromBottom4 = imgState.YPosFromBottom1; + break; + } + } + + private float CalculateHorizontalAlignment(int imgWidth, float textWidth) + { + double halfWidth = textWidth / 2.0; + + return picSettings.Allineamento.ToUpper() switch + { + "SINISTRA" => (float)Math.Min(picSettings.Margine + halfWidth, imgWidth / 2.0), + "DESTRA" => (float)Math.Max(imgWidth - picSettings.Margine - halfWidth, imgWidth / 2.0), + _ => imgWidth / 2.0f, // CENTRO or default + }; + } + + private void DrawText(Graphics g, ImageState imgState, float x, StringFormat format, + Brush shadowBrush, Brush textBrush, Font font) + { + string content = imgState.TestoFirmaPiccola; + + if (picSettings.TestoMin) + { + content = imgState.NomeFileBig; + } + else if (picSettings.AggTempoGaraMin && picSettings.UsaTempoGaraTestoApplicare) + { + content = FormatTimeText(imgState, includeFileName: false); + } + else if (picSettings.AggNumTempMin) + { + content = FormatTimeText(imgState, includeFileName: true); + } + + var offset = new PointF(x + 1, imgState.YPosFromBottom1 + 1); + var actual = new PointF(x, imgState.YPosFromBottom1); + + g.DrawString(content, font, shadowBrush, offset, format); + g.DrawString(content, font, textBrush, actual, format); + } + + private string FormatTimeText(ImageState imgState, bool includeFileName) + { + var diff = imgState.DataPartenzaI - imgState.DataFoto; + var ticks = (long)(diff.TotalSeconds * 10000000); + var time = new TimeSpan(ticks); + + var formatted = $"{imgState.TestoOrario}{time:hh\\:mm\\:ss}"; + return includeFileName + ? $"{imgState.NomeFileBig}{Environment.NewLine}{formatted}" + : Environment.NewLine + formatted; + } +} diff --git a/MaddoShared/ImageState.cs b/MaddoShared/ImageState.cs index e80094c..0090ecb 100644 --- a/MaddoShared/ImageState.cs +++ b/MaddoShared/ImageState.cs @@ -1,4 +1,5 @@ using System; +using System.Drawing; using System.IO; namespace MaddoShared; @@ -27,16 +28,18 @@ public class ImageState public DateTime DataPartenzaI { get; set; } public string TestoOrario { get; set; } public string TestoFirmaPiccola { get; set; } - public string NomeFileSmall { get; set; } - public string NomeFileBig { get; set; } - public string NomeFileBig2 { get; set; } + public Size ThumbSizeSmall { get; set; } + public Size ThumbSizeBig { get; set; } + public string NomeFileSmall{ get; set; } + public string NomeFileBig{ get; set; } + public string NomeFileBig2{ get; set; } - public float YPosFromBottom { get; set; } - public float YPosFromBottom1 { get; set; } - public float YPosFromBottom2 { get; set; } - public float YPosFromBottom3 { get; set; } - public float YPosFromBottom4 { get; set; } + public float YPosFromBottom{ get; set; } + public float YPosFromBottom1{ get; set; } + public float YPosFromBottom2{ get; set; } + public float YPosFromBottom3{ get; set; } + public float YPosFromBottom4{ get; set; } - public Orientations Orientation { get; set; } - public DateTime? CreationDate { get; set; } + public Orientations Orientation{ get; set; } + public DateTime? CreationDate{ get; set; } } \ No newline at end of file diff --git a/MaddoShared/MaddoShared.csproj b/MaddoShared/MaddoShared.csproj index 6d0ee05..2bd6b04 100644 --- a/MaddoShared/MaddoShared.csproj +++ b/MaddoShared/MaddoShared.csproj @@ -1,10 +1,10 @@  - net10.0 + net10.0-windows Library - enable - enable false + true + true x64 @@ -29,5 +29,6 @@ all + \ No newline at end of file diff --git a/MaddoShared/PicSettings.cs b/MaddoShared/PicSettings.cs index 883ff37..6729bf6 100644 --- a/MaddoShared/PicSettings.cs +++ b/MaddoShared/PicSettings.cs @@ -1,6 +1,7 @@ using System; +using System.Drawing; using System.IO; -using SixLabors.ImageSharp.PixelFormats; +using System.Windows.Forms; namespace MaddoShared; @@ -10,7 +11,6 @@ public class PicSettings public string DirectoryDestinazione { get; set; } public string TestoFirmaStart { get; set; } public string TestoFirmaStartV { get; set; } - public byte[]? LogoData { get; set; } public DateTime DataPartenza { get; set; } public string TestoOrario { get; set; } public int DimStandard { get; set; } @@ -22,7 +22,6 @@ public class PicSettings public bool UsaTempoGaraTestoApplicare { get; set; } public bool UsaRotazioneAutomatica { get; set; } public bool UsaForzaJpg { get; set; } - public bool RemoveExifData { get; set; } public int LarghezzaSmall { get; set; } public int AltezzaSmall { get; set; } public bool CreaMiniature { get; set; } @@ -37,7 +36,7 @@ public class PicSettings public int Margine { get; set; } public int LogoAltezza { get; set; } public int LogoLarghezza { get; set; } - public Rgba32 FontColoreRGB { get; set; } = new(255, 255, 0, 255); + public Color FontColoreRGB { get; set; } public bool LogoAggiungi { get; set; } // Initialize logo-related strings to safe defaults to avoid null reference issues public string LogoNomeFile { get; set; } = string.Empty; @@ -83,4 +82,6 @@ public class PicSettings public bool FotoRuotaASinistra { get; set; } = false; public string TempMinText { get; set; } = string.Empty; public bool OverwriteFiles { get; set; } = false; + // Which image creator to use: "Sharp" for current implementation, "Alternate" for alternate library + public string ImageCreatorProvider { get; set; } = "Sharp"; } \ No newline at end of file diff --git a/MaddoShared/Properties/AssemblyInfo.cs b/MaddoShared/Properties/AssemblyInfo.cs index 6af8d79..52a601e 100644 --- a/MaddoShared/Properties/AssemblyInfo.cs +++ b/MaddoShared/Properties/AssemblyInfo.cs @@ -8,10 +8,10 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("MaddoShared")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Maddo")] +[assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MaddoShared")] -[assembly: AssemblyCopyright("Copyright © 2021-2026")] -[assembly: AssemblyTrademark("Maddo")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible diff --git a/NuGet.Config b/NuGet.Config deleted file mode 100644 index e0e2d2b..0000000 --- a/NuGet.Config +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/README.md b/README.md index dd8716f..aa5f0de 100644 --- a/README.md +++ b/README.md @@ -1,13 +1 @@ Catalog 3 - -## Catalog Lite - -`CatalogLite/CatalogLite.csproj` is a minimal Avalonia frontend for processing images from a saved XML configuration. It references `MaddoShared`, uses only the ImageSharp processor, and exposes only XML loading, source/destination folder selection, start/stop, and progress. - -The build embeds an expiration date from the `CatalogLiteExpirationDate` MSBuild property: - -```powershell -dotnet publish CatalogLite/CatalogLite.csproj -c Release -r win-x64 --self-contained false -p:PublishSingleFile=true -p:CatalogLiteExpirationDate=2026-12-31 -``` - -The separate Forgejo workflow is `.forgejo/workflows/build-catalog-lite.yml`; run it manually and set `expiration_date` in `yyyy-MM-dd` format. diff --git a/WPFCatalog/App.config b/WPFCatalog/App.config new file mode 100644 index 0000000..ca0daff --- /dev/null +++ b/WPFCatalog/App.config @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WPFCatalog/App.xaml b/WPFCatalog/App.xaml new file mode 100644 index 0000000..9388e68 --- /dev/null +++ b/WPFCatalog/App.xaml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/WPFCatalog/App.xaml.cs b/WPFCatalog/App.xaml.cs new file mode 100644 index 0000000..ac50df1 --- /dev/null +++ b/WPFCatalog/App.xaml.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace WPFCatalog +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + } +} diff --git a/WPFCatalog/Controls/GeneralSettingsControl.xaml b/WPFCatalog/Controls/GeneralSettingsControl.xaml new file mode 100644 index 0000000..bfa637d --- /dev/null +++ b/WPFCatalog/Controls/GeneralSettingsControl.xaml @@ -0,0 +1,186 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WPFCatalog/Controls/GeneralSettingsControl.xaml.cs b/WPFCatalog/Controls/GeneralSettingsControl.xaml.cs new file mode 100644 index 0000000..af3e0aa --- /dev/null +++ b/WPFCatalog/Controls/GeneralSettingsControl.xaml.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace WPFCatalog.Controls +{ + /// + /// Interaction logic for GeneralSettingsControl.xaml + /// + public partial class GeneralSettingsControl : UserControl + { + public GeneralSettingsControl() + { + InitializeComponent(); + } + } +} diff --git a/WPFCatalog/Controls/TextSettingsControl.xaml b/WPFCatalog/Controls/TextSettingsControl.xaml new file mode 100644 index 0000000..7d7ac19 --- /dev/null +++ b/WPFCatalog/Controls/TextSettingsControl.xaml @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WPFCatalog/Controls/TextSettingsControl.xaml.cs b/WPFCatalog/Controls/TextSettingsControl.xaml.cs new file mode 100644 index 0000000..2c29c51 --- /dev/null +++ b/WPFCatalog/Controls/TextSettingsControl.xaml.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace WPFCatalog.Controls +{ + /// + /// Interaction logic for TextSettingsControl.xaml + /// + public partial class TextSettingsControl : UserControl + { + public TextSettingsControl() + { + InitializeComponent(); + } + } +} diff --git a/WPFCatalog/Converters/FontFamilyStringConverter.cs b/WPFCatalog/Converters/FontFamilyStringConverter.cs new file mode 100644 index 0000000..66a103e --- /dev/null +++ b/WPFCatalog/Converters/FontFamilyStringConverter.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Data; +using System.Windows.Media; + +namespace WPFCatalog +{ + public class FontFamilyStringConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + FontFamily fontfamily = new FontFamily("Verdana"); + if (value != null) + { + fontfamily = new FontFamily(value.ToString()); + } + return fontfamily; + + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} diff --git a/WPFCatalog/Converters/MaddoColorConverter.cs b/WPFCatalog/Converters/MaddoColorConverter.cs new file mode 100644 index 0000000..2248484 --- /dev/null +++ b/WPFCatalog/Converters/MaddoColorConverter.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; +using System.Windows.Media; + +namespace WPFCatalog +{ + public class MaddoColorConverter : IValueConverter + { + private static readonly DependencyObject _dummy = new DependencyObject(); + + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + Color color = Colors.Black; + + if (value != null && value != DependencyProperty.UnsetValue && value is string && !String.IsNullOrWhiteSpace((string)value)) + { + string c = (string)value; + object convertedColor = null; + try + { + convertedColor = ColorConverter.ConvertFromString(c); + } + catch (Exception ex) + { + if (!DesignerProperties.GetIsInDesignMode(_dummy)) + { + throw new FormatException($"String {c} does not represent a valid color", ex); + } + } + if (convertedColor != null) + { + color = (Color)convertedColor; + } + } + + return color; + + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value != null) + { + Color color = (Color)value; + Debug.WriteLine(color.ToString()); + return color.ToString(); + } + return string.Empty; + } + } +} diff --git a/WPFCatalog/Icons/camera-photo-5.png b/WPFCatalog/Icons/camera-photo-5.png new file mode 100644 index 0000000..1e54dea Binary files /dev/null and b/WPFCatalog/Icons/camera-photo-5.png differ diff --git a/WPFCatalog/Icons/document-open-6.png b/WPFCatalog/Icons/document-open-6.png new file mode 100644 index 0000000..fe03b7f Binary files /dev/null and b/WPFCatalog/Icons/document-open-6.png differ diff --git a/WPFCatalog/Icons/document-open-folder.png b/WPFCatalog/Icons/document-open-folder.png new file mode 100644 index 0000000..98b8a94 Binary files /dev/null and b/WPFCatalog/Icons/document-open-folder.png differ diff --git a/WPFCatalog/Icons/face-smile-2.png b/WPFCatalog/Icons/face-smile-2.png new file mode 100644 index 0000000..24ce7a5 Binary files /dev/null and b/WPFCatalog/Icons/face-smile-2.png differ diff --git a/WPFCatalog/Icons/format-justify-left-2.png b/WPFCatalog/Icons/format-justify-left-2.png new file mode 100644 index 0000000..d6abc05 Binary files /dev/null and b/WPFCatalog/Icons/format-justify-left-2.png differ diff --git a/WPFCatalog/Icons/photo.png b/WPFCatalog/Icons/photo.png new file mode 100644 index 0000000..0b2e201 Binary files /dev/null and b/WPFCatalog/Icons/photo.png differ diff --git a/WPFCatalog/Icons/picture.png b/WPFCatalog/Icons/picture.png new file mode 100644 index 0000000..b773744 Binary files /dev/null and b/WPFCatalog/Icons/picture.png differ diff --git a/WPFCatalog/MainWindow.xaml b/WPFCatalog/MainWindow.xaml new file mode 100644 index 0000000..c7cd8fe --- /dev/null +++ b/WPFCatalog/MainWindow.xaml @@ -0,0 +1,203 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - diff --git a/imagecatalog/AvaloniaMainWindow.axaml.cs b/imagecatalog/AvaloniaMainWindow.axaml.cs deleted file mode 100644 index 20e5fb2..0000000 --- a/imagecatalog/AvaloniaMainWindow.axaml.cs +++ /dev/null @@ -1,382 +0,0 @@ -using Avalonia; -using Avalonia.Controls; -using Avalonia.Interactivity; -using Avalonia.Layout; -using Avalonia.Platform.Storage; -using Avalonia.Styling; -using Avalonia.Threading; -using ImageCatalog_2.Services; -using Microsoft.Extensions.DependencyInjection; -using System.ComponentModel; -using System.IO; - -namespace ImageCatalog_2; - -public partial class AvaloniaMainWindow : Window -{ - private readonly DataModel _model; - private readonly PickerPreferenceService _pickerPreferenceService; - private bool _isDarkTheme; - private bool _startupSettingsRestoreAttempted; - - public AvaloniaMainWindow() - : this(Program.ServiceProvider.GetRequiredService()) - { - } - - public AvaloniaMainWindow(DataModel model) - { - InitializeComponent(); - - _model = model; - _pickerPreferenceService = Program.ServiceProvider.GetRequiredService(); - DataContext = _model; - - Opened += async (_, _) => - { - SyncThemeStateFromCurrentTheme(); - await TryLoadLastSettingsOnStartupAsync(); - }; - Closing += AvaloniaMainWindow_Closing; - - // Let DataModel marshal callbacks onto Avalonia UI thread. - _model.UiInvoker = action => Dispatcher.UIThread.Invoke(action); - _model.ConfirmAiCsvOverwriteAsync = ShowConfirmationDialogAsync; - - _model.SelectSourceFolderRequested += async (_, _) => - { - var suggestedStartLocation = await _pickerPreferenceService.TryGetStartFolderAsync(StorageProvider, PickerPreferenceKeys.SourceFolder, _model.SourcePath); - var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions - { - Title = "Seleziona cartella sorgente", - SuggestedStartLocation = suggestedStartLocation - }); - - if (folders.Count > 0) - { - _model.SourcePath = folders[0].Path.LocalPath + Path.DirectorySeparatorChar; - _pickerPreferenceService.RememberPath(PickerPreferenceKeys.SourceFolder, _model.SourcePath); - } - }; - - _model.SelectDestinationFolderRequested += async (_, _) => - { - var suggestedStartLocation = await _pickerPreferenceService.TryGetStartFolderAsync(StorageProvider, PickerPreferenceKeys.DestinationFolder, _model.DestinationPath); - var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions - { - Title = "Seleziona cartella destinazione", - SuggestedStartLocation = suggestedStartLocation - }); - - if (folders.Count > 0) - { - _model.DestinationPath = folders[0].Path.LocalPath + Path.DirectorySeparatorChar; - _pickerPreferenceService.RememberPath(PickerPreferenceKeys.DestinationFolder, _model.DestinationPath); - } - }; - - _model.SelectLogoFileRequested += async (_, _) => - { - var suggestedStartLocation = await _pickerPreferenceService.TryGetStartFolderAsync(StorageProvider, PickerPreferenceKeys.LogoFile, _model.LogoFile); - var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions - { - Title = "Seleziona logo", - SuggestedStartLocation = suggestedStartLocation, - FileTypeFilter = - [ - new FilePickerFileType("Immagini") { Patterns = ["*.jpg", "*.jpeg", "*.png", "*.bmp", "*.gif"] } - ] - }); - - if (files.Count > 0) - { - _model.LogoFile = files[0].Path.LocalPath; - _pickerPreferenceService.RememberPath(PickerPreferenceKeys.LogoFile, _model.LogoFile); - } - }; - - _model.SelectModelsFolderRequested += async (_, _) => - { - var suggestedStartLocation = await _pickerPreferenceService.TryGetStartFolderAsync(StorageProvider, PickerPreferenceKeys.ModelsFolder, _model.ModelsFolderPath); - var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions - { - Title = "Seleziona cartella modelli", - SuggestedStartLocation = suggestedStartLocation - }); - - if (folders.Count > 0) - { - _model.ModelsFolderPath = folders[0].Path.LocalPath + Path.DirectorySeparatorChar; - _pickerPreferenceService.RememberPath(PickerPreferenceKeys.ModelsFolder, _model.ModelsFolderPath); - } - }; - - _model.SelectCsvOutputRequested += async (_, _) => - { - var suggestedStartLocation = await _pickerPreferenceService.TryGetStartFolderAsync(StorageProvider, PickerPreferenceKeys.CsvOutput, _model.CsvOutputPath); - var file = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions - { - Title = "Salva CSV", - DefaultExtension = "csv", - FileTypeChoices = [new FilePickerFileType("CSV") { Patterns = ["*.csv"] }], - SuggestedStartLocation = suggestedStartLocation - }); - - if (file is not null) - { - _model.CsvOutputPath = file.Path.LocalPath; - _pickerPreferenceService.RememberPath(PickerPreferenceKeys.CsvOutput, _model.CsvOutputPath); - } - }; - - _model.SaveSettingsRequested += async (_, _) => - { - var suggestedStartLocation = await _pickerPreferenceService.TryGetStartFolderAsync(StorageProvider, PickerPreferenceKeys.SettingsFile); - var file = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions - { - Title = "Salva impostazioni", - DefaultExtension = "xml", - FileTypeChoices = [new FilePickerFileType("Setup") { Patterns = ["*.xml"] }], - SuggestedStartLocation = suggestedStartLocation - }); - - if (file is not null) - { - await _model.SaveSettingsToFileAsync(file.Path.LocalPath); - _pickerPreferenceService.RememberPath(PickerPreferenceKeys.SettingsFile, file.Path.LocalPath); - _pickerPreferenceService.RememberValue(PickerPreferenceKeys.LastSettingsFile, file.Path.LocalPath); - } - }; - - _model.LoadSettingsRequested += async (_, _) => - { - var suggestedStartLocation = await _pickerPreferenceService.TryGetStartFolderAsync(StorageProvider, PickerPreferenceKeys.SettingsFile); - var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions - { - Title = "Carica impostazioni", - FileTypeFilter = [new FilePickerFileType("Setup") { Patterns = ["*.xml"] }], - SuggestedStartLocation = suggestedStartLocation - }); - - if (files.Count > 0) - { - await _model.LoadSettingsFromFileAsync(files[0].Path.LocalPath); - _pickerPreferenceService.RememberPath(PickerPreferenceKeys.SettingsFile, files[0].Path.LocalPath); - _pickerPreferenceService.RememberValue(PickerPreferenceKeys.LastSettingsFile, files[0].Path.LocalPath); - } - }; - - _model.SelectColorRequested += (_, _) => - { - // Color is set by typing hex directly in the TextBox. - }; - - _model.SelectTransparentColorRequested += (_, _) => - { - // Color is set by typing hex directly in the TextBox. - }; - - _model.ShowMessageRequested += async (_, args) => - { - await ShowMessageDialogAsync(args.Item1, args.Item2); - }; - } - - private bool _isStoppingFaceEncoderForClose; - - private async Task TryLoadLastSettingsOnStartupAsync() - { - if (_startupSettingsRestoreAttempted) - { - return; - } - - _startupSettingsRestoreAttempted = true; - - var lastSettingsFile = _pickerPreferenceService.GetRememberedValue(PickerPreferenceKeys.LastSettingsFile); - if (string.IsNullOrWhiteSpace(lastSettingsFile)) - { - return; - } - - if (!File.Exists(lastSettingsFile)) - { - _pickerPreferenceService.ForgetValue(PickerPreferenceKeys.LastSettingsFile); - return; - } - - try - { - await _model.LoadSettingsFromFileAsync(lastSettingsFile); - _pickerPreferenceService.RememberPath(PickerPreferenceKeys.SettingsFile, lastSettingsFile); - } - catch (Exception ex) - { - await ShowMessageDialogAsync("Impostazioni", $"Impossibile caricare il file impostazioni automatico:\n{ex.GetBaseException().Message}"); - } - } - - private async void AvaloniaMainWindow_Closing(object? sender, CancelEventArgs e) - { - if (_isStoppingFaceEncoderForClose || (!_model.IsFaceEncoderRunning && !_model.IsFaceMatcherRunning)) - { - return; - } - - e.Cancel = true; - _isStoppingFaceEncoderForClose = true; - - try - { - if (_model.IsFaceMatcherRunning) - { - await _model.StopFaceMatcherAsync("Arresto face matcher in chiusura...", waitForExit: true); - } - - if (_model.IsFaceEncoderRunning) - { - await _model.StopFaceEncoderAsync("Arresto face encoder in chiusura...", waitForExit: true); - } - } - finally - { - _isStoppingFaceEncoderForClose = false; - Close(); - } - } - - private void ToggleTheme_Click(object? sender, RoutedEventArgs e) - { - _isDarkTheme = !_isDarkTheme; - - if (Avalonia.Application.Current is not null) - { - Avalonia.Application.Current.RequestedThemeVariant = _isDarkTheme ? ThemeVariant.Dark : ThemeVariant.Light; - } - - UpdateThemeToggleButtonContent(); - } - - private void SyncThemeStateFromCurrentTheme() - { - _isDarkTheme = ActualThemeVariant == ThemeVariant.Dark; - UpdateThemeToggleButtonContent(); - } - - private void UpdateThemeToggleButtonContent() - { - _ = this.FindControl("ThemeToggleButton"); - } - - private async Task ShowMessageDialogAsync(string title, string message) - { - var dialog = new Window - { - Title = title, - Width = 960, - Height = 560, - CanResize = false, - WindowStartupLocation = WindowStartupLocation.CenterOwner, - SizeToContent = SizeToContent.Manual - }; - - dialog.Content = BuildMessageDialogContent(message, () => dialog.Close()); - - await dialog.ShowDialog(this); - } - - private async Task ShowConfirmationDialogAsync(string title, string message) - { - var dialog = new Window - { - Title = title, - Width = 520, - CanResize = false, - WindowStartupLocation = WindowStartupLocation.CenterOwner, - SizeToContent = SizeToContent.Height - }; - - dialog.Content = BuildConfirmationDialogContent( - message, - () => dialog.Close(true), - () => dialog.Close(false)); - - return await dialog.ShowDialog(this); - } - - private static Control BuildMessageDialogContent(string message, Action closeDialog) - { - var layout = new StackPanel - { - Margin = new Thickness(16), - Spacing = 12 - }; - - layout.Children.Add(new ScrollViewer - { - Height = 460, - HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, - VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, - Content = new TextBlock - { - Text = message, - TextWrapping = Avalonia.Media.TextWrapping.Wrap, - FontFamily = new Avalonia.Media.FontFamily("Cascadia Mono, Consolas, monospace") - } - }); - - var closeButton = new Button - { - Content = "OK", - MinWidth = 88, - HorizontalAlignment = HorizontalAlignment.Right - }; - - closeButton.Click += (_, _) => closeDialog(); - - layout.Children.Add(closeButton); - return layout; - } - - private static Control BuildConfirmationDialogContent(string message, Action confirmDialog, Action cancelDialog) - { - var layout = new StackPanel - { - Margin = new Thickness(16), - Spacing = 12 - }; - - layout.Children.Add(new TextBlock - { - Text = message, - TextWrapping = Avalonia.Media.TextWrapping.Wrap, - MaxWidth = 460 - }); - - var buttons = new StackPanel - { - Orientation = Orientation.Horizontal, - HorizontalAlignment = HorizontalAlignment.Right, - Spacing = 8 - }; - - var cancelButton = new Button - { - Content = "Annulla", - MinWidth = 96 - }; - cancelButton.Click += (_, _) => cancelDialog(); - - var confirmButton = new Button - { - Content = "Sovrascrivi", - MinWidth = 96 - }; - confirmButton.Click += (_, _) => confirmDialog(); - - buttons.Children.Add(cancelButton); - buttons.Children.Add(confirmButton); - layout.Children.Add(buttons); - return layout; - } -} diff --git a/imagecatalog/AvaloniaViews/AiTabView.axaml b/imagecatalog/AvaloniaViews/AiTabView.axaml deleted file mode 100644 index 5026497..0000000 --- a/imagecatalog/AvaloniaViews/AiTabView.axaml +++ /dev/null @@ -1,102 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/imagecatalog/AvaloniaViews/AiTabView.axaml.cs b/imagecatalog/AvaloniaViews/AiTabView.axaml.cs deleted file mode 100644 index f56e327..0000000 --- a/imagecatalog/AvaloniaViews/AiTabView.axaml.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Avalonia.Controls; -namespace ImageCatalog_2.AvaloniaViews; - -public partial class AiTabView : Avalonia.Controls.UserControl -{ - public AiTabView() - { - InitializeComponent(); - } -} diff --git a/imagecatalog/AvaloniaViews/FaceAiTabView.axaml b/imagecatalog/AvaloniaViews/FaceAiTabView.axaml deleted file mode 100644 index 4564e7d..0000000 --- a/imagecatalog/AvaloniaViews/FaceAiTabView.axaml +++ /dev/null @@ -1,329 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/imagecatalog/AvaloniaViews/FaceAiTabView.axaml.cs b/imagecatalog/AvaloniaViews/FaceAiTabView.axaml.cs deleted file mode 100644 index 0fbe36b..0000000 --- a/imagecatalog/AvaloniaViews/FaceAiTabView.axaml.cs +++ /dev/null @@ -1,325 +0,0 @@ -using Avalonia.Controls; -using Avalonia.Interactivity; -using Avalonia.Input; -using Avalonia.Layout; -using Avalonia.Media; -using Avalonia.Media.Imaging; -using Avalonia.Threading; -using ImageCatalog_2.Models; -using ImageCatalog_2.Services; -using System; -using System.ComponentModel; -using System.IO; -using System.Text; -using System.Threading.Tasks; - -namespace ImageCatalog_2.AvaloniaViews; - -public partial class FaceAiTabView : Avalonia.Controls.UserControl -{ - private INotifyPropertyChanged? _faceAiPropertySource; - - public FaceAiTabView() - { - InitializeComponent(); - DataContextChanged += OnDataContextChanged; - } - - private void OnDataContextChanged(object? sender, EventArgs e) - { - if (_faceAiPropertySource is not null) - { - _faceAiPropertySource.PropertyChanged -= OnFaceAiPropertyChanged; - } - - _faceAiPropertySource = DataContext as INotifyPropertyChanged; - if (_faceAiPropertySource is not null) - { - _faceAiPropertySource.PropertyChanged += OnFaceAiPropertyChanged; - } - } - - private void OnFaceAiPropertyChanged(object? sender, PropertyChangedEventArgs e) - { - if (string.Equals(e.PropertyName, nameof(DataModel.FaceCommandOutput), StringComparison.Ordinal)) - { - ScrollOutputTextBoxToEnd("FaceOutputTextBox"); - return; - } - - if (string.Equals(e.PropertyName, nameof(DataModel.FaceMatcherCommandOutput), StringComparison.Ordinal)) - { - ScrollOutputTextBoxToEnd("FaceMatcherOutputTextBox"); - } - } - - private void ScrollOutputTextBoxToEnd(string controlName) - { - var outputBox = this.FindControl(controlName); - if (outputBox is null) - { - return; - } - - Dispatcher.UIThread.Post(() => - { - var textLength = outputBox.Text?.Length ?? 0; - outputBox.CaretIndex = textLength; - }); - } - - private async void OpenFaceMatcherPreview_Click(object? sender, RoutedEventArgs e) - { - if (sender is not Button { Tag: FaceMatcherResultItem item }) - { - return; - } - - await OpenFaceMatcherPreviewAsync(item); - } - - private async Task OpenFaceMatcherPreviewAsync(FaceMatcherResultItem item) - { - var owner = TopLevel.GetTopLevel(this) as Window; - var dialog = BuildFaceMatcherPreviewDialog(item); - if (owner is not null) - { - await dialog.ShowDialog(owner); - return; - } - - dialog.Show(); - } - - private async void FaceMatcherResults_DoubleTapped(object? sender, TappedEventArgs e) - { - if (sender is not Avalonia.Controls.DataGrid { SelectedItem: FaceMatcherResultItem item }) - { - return; - } - - await OpenFaceMatcherPreviewAsync(item); - } - - private Window BuildFaceMatcherPreviewDialog(FaceMatcherResultItem item) - { - var dialog = new Window - { - Title = $"Preview match: {item.PhotoId}", - Width = 1180, - Height = 900, - WindowStartupLocation = WindowStartupLocation.CenterOwner - }; - - Bitmap? bitmap = null; - var dimensionText = "n/d"; - if (!string.IsNullOrWhiteSpace(item.ResolvedImagePath) && File.Exists(item.ResolvedImagePath)) - { - try - { - bitmap = new Bitmap(item.ResolvedImagePath); - dimensionText = $"{bitmap.PixelSize.Width} x {bitmap.PixelSize.Height}px"; - } - catch - { - bitmap = null; - } - } - - var fileInfo = !string.IsNullOrWhiteSpace(item.ResolvedImagePath) && File.Exists(item.ResolvedImagePath) - ? new FileInfo(item.ResolvedImagePath) - : null; - - var debugBuilder = new StringBuilder(); - debugBuilder.AppendLine($"File matcher: {item.PhotoId}"); - debugBuilder.AppendLine($"Score: {item.ScoreDisplay}"); - debugBuilder.AppendLine($"Path risolto: {item.ResolvedImagePath}"); - debugBuilder.AppendLine($"Candidati trovati in destinazione: {item.CandidateCount}"); - debugBuilder.AppendLine($"Dimensioni immagine: {dimensionText}"); - if (fileInfo is not null) - { - debugBuilder.AppendLine($"Dimensione file: {fileInfo.Length / 1024.0:F1} KB"); - debugBuilder.AppendLine($"Ultima modifica: {fileInfo.LastWriteTime:yyyy-MM-dd HH:mm:ss}"); - } - - debugBuilder.AppendLine($"Immagine ricerca: {item.SearchImagePath}"); - debugBuilder.AppendLine($"CSV risultati: {item.CsvPath}"); - debugBuilder.AppendLine($"Log matcher: {item.LogPath}"); - if (!string.IsNullOrWhiteSpace(item.DebugSummary)) - { - debugBuilder.AppendLine($"Dettagli riga: {item.DebugSummary}"); - } - - if (!string.IsNullOrWhiteSpace(item.RawRow)) - { - debugBuilder.AppendLine($"Raw CSV: {item.RawRow}"); - } - - var layout = new Grid - { - Margin = new Avalonia.Thickness(16), - RowDefinitions = new RowDefinitions("Auto,*,Auto") - }; - - var header = new StackPanel { Spacing = 6 }; - header.Children.Add(new TextBlock - { - Text = item.PhotoId, - FontWeight = FontWeight.Bold, - FontSize = 18 - }); - header.Children.Add(new TextBlock - { - Text = string.IsNullOrWhiteSpace(item.ScoreDisplay) - ? "Score: n/d" - : $"Score: {item.ScoreDisplay}%", - FontWeight = FontWeight.SemiBold, - Opacity = 0.9 - }); - header.Children.Add(new TextBlock - { - Text = string.IsNullOrWhiteSpace(item.ResolvedImagePath) - ? "Nessun file immagine risolto nella cartella Destinazione." - : item.ResolvedImagePath, - TextWrapping = TextWrapping.Wrap, - Opacity = 0.8 - }); - layout.Children.Add(header); - - var contentGrid = new Grid - { - Margin = new Avalonia.Thickness(0, 12, 0, 12), - RowDefinitions = new RowDefinitions("Auto,*,Auto") - }; - Grid.SetRow(contentGrid, 1); - - var zoomLevel = 1.0; - var zoomText = new TextBlock - { - Text = "100%", - VerticalAlignment = VerticalAlignment.Center, - MinWidth = 52, - TextAlignment = TextAlignment.Center - }; - - var imageControl = bitmap is null - ? null - : new Image - { - Source = bitmap, - Stretch = Stretch.None, - HorizontalAlignment = HorizontalAlignment.Left, - VerticalAlignment = VerticalAlignment.Top, - RenderTransform = new ScaleTransform(1, 1) - }; - - void UpdateZoom(double delta) - { - if (imageControl is null) - { - return; - } - - zoomLevel = Math.Clamp(zoomLevel + delta, 0.1, 8.0); - imageControl.RenderTransform = new ScaleTransform(zoomLevel, zoomLevel); - zoomText.Text = $"{zoomLevel * 100:0}%"; - } - - var toolbar = new StackPanel - { - Orientation = Orientation.Horizontal, - Spacing = 8, - Margin = new Avalonia.Thickness(0, 0, 0, 12) - }; - - var zoomOutButton = new Button { Content = "Zoom -", MinWidth = 80, IsEnabled = imageControl is not null }; - zoomOutButton.Click += (_, _) => UpdateZoom(-0.1); - toolbar.Children.Add(zoomOutButton); - - var zoomInButton = new Button { Content = "Zoom +", MinWidth = 80, IsEnabled = imageControl is not null }; - zoomInButton.Click += (_, _) => UpdateZoom(0.1); - toolbar.Children.Add(zoomInButton); - - var resetZoomButton = new Button { Content = "100%", MinWidth = 72, IsEnabled = imageControl is not null }; - resetZoomButton.Click += (_, _) => - { - if (imageControl is null) - { - return; - } - - zoomLevel = 1.0; - imageControl.RenderTransform = new ScaleTransform(1, 1); - zoomText.Text = "100%"; - }; - toolbar.Children.Add(resetZoomButton); - toolbar.Children.Add(zoomText); - contentGrid.Children.Add(toolbar); - - var previewBorder = new Border - { - BorderBrush = Brushes.Gray, - BorderThickness = new Avalonia.Thickness(1), - Padding = new Avalonia.Thickness(8), - Child = new ScrollViewer - { - HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, - VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto, - Content = bitmap is null - ? new TextBlock - { - Text = "Anteprima non disponibile", - HorizontalAlignment = HorizontalAlignment.Center, - VerticalAlignment = VerticalAlignment.Center - } - : imageControl - } - }; - Grid.SetRow(previewBorder, 1); - contentGrid.Children.Add(previewBorder); - - var debugBox = new TextBox - { - Text = debugBuilder.ToString(), - IsReadOnly = true, - AcceptsReturn = true, - TextWrapping = TextWrapping.Wrap, - FontFamily = new FontFamily("Cascadia Mono, Consolas, monospace"), - MinHeight = 180, - Margin = new Avalonia.Thickness(0, 12, 0, 0) - }; - Grid.SetRow(debugBox, 2); - contentGrid.Children.Add(debugBox); - - layout.Children.Add(contentGrid); - - var footer = new StackPanel - { - Orientation = Orientation.Horizontal, - HorizontalAlignment = HorizontalAlignment.Right, - Spacing = 8 - }; - Grid.SetRow(footer, 2); - - var openFileButton = new Button { Content = "Apri file" }; - openFileButton.Click += (_, _) => PathShellService.OpenInExplorer(item.ResolvedImagePath); - footer.Children.Add(openFileButton); - - var openFolderButton = new Button { Content = "Apri cartella" }; - openFolderButton.Click += (_, _) => - { - var directory = Path.GetDirectoryName(item.ResolvedImagePath); - PathShellService.OpenInExplorer(string.IsNullOrWhiteSpace(directory) ? item.ResolvedImagePath : directory); - }; - footer.Children.Add(openFolderButton); - - var closeButton = new Button { Content = "Chiudi", MinWidth = 88 }; - closeButton.Click += (_, _) => dialog.Close(); - footer.Children.Add(closeButton); - - layout.Children.Add(footer); - dialog.Content = layout; - return dialog; - } - -} diff --git a/imagecatalog/AvaloniaViews/GeneralTabView.axaml b/imagecatalog/AvaloniaViews/GeneralTabView.axaml deleted file mode 100644 index f99fead..0000000 --- a/imagecatalog/AvaloniaViews/GeneralTabView.axaml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/imagecatalog/AvaloniaViews/GeneralTabView.axaml.cs b/imagecatalog/AvaloniaViews/GeneralTabView.axaml.cs deleted file mode 100644 index 9670c2a..0000000 --- a/imagecatalog/AvaloniaViews/GeneralTabView.axaml.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Avalonia.Controls; -namespace ImageCatalog_2.AvaloniaViews; - -public partial class GeneralTabView : Avalonia.Controls.UserControl -{ - public GeneralTabView() - { - InitializeComponent(); - } -} diff --git a/imagecatalog/AvaloniaViews/LogoTabView.axaml b/imagecatalog/AvaloniaViews/LogoTabView.axaml deleted file mode 100644 index 275f059..0000000 --- a/imagecatalog/AvaloniaViews/LogoTabView.axaml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/imagecatalog/Controls/PathPickerField.axaml.cs b/imagecatalog/Controls/PathPickerField.axaml.cs deleted file mode 100644 index 6ec2538..0000000 --- a/imagecatalog/Controls/PathPickerField.axaml.cs +++ /dev/null @@ -1,285 +0,0 @@ -using Avalonia; -using Avalonia.Controls; -using Avalonia.Data; -using Avalonia.Platform.Storage; -using ImageCatalog_2.Services; -using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace ImageCatalog_2.Controls; - -public partial class PathPickerField : UserControl -{ - private readonly PickerPreferenceService _pickerPreferenceService; - - public static readonly StyledProperty LabelProperty = - AvaloniaProperty.Register(nameof(Label), string.Empty); - - public static readonly StyledProperty TextProperty = - AvaloniaProperty.Register(nameof(Text), string.Empty, defaultBindingMode: BindingMode.TwoWay); - - public static readonly StyledProperty WatermarkProperty = - AvaloniaProperty.Register(nameof(Watermark), string.Empty); - - public static readonly StyledProperty PreferenceKeyProperty = - AvaloniaProperty.Register(nameof(PreferenceKey), string.Empty); - - public static readonly StyledProperty PickerTitleProperty = - AvaloniaProperty.Register(nameof(PickerTitle), string.Empty); - - public static readonly StyledProperty FileTypeNameProperty = - AvaloniaProperty.Register(nameof(FileTypeName), string.Empty); - - public static readonly StyledProperty FilePatternsProperty = - AvaloniaProperty.Register(nameof(FilePatterns), string.Empty); - - public static readonly StyledProperty DefaultExtensionProperty = - AvaloniaProperty.Register(nameof(DefaultExtension), string.Empty); - - public static readonly StyledProperty PickerModeProperty = - AvaloniaProperty.Register(nameof(PickerMode), PathPickerSelectionMode.Folder); - - public static readonly StyledProperty IsTextReadOnlyProperty = - AvaloniaProperty.Register(nameof(IsTextReadOnly), false); - - public static readonly StyledProperty ShowPickerButtonProperty = - AvaloniaProperty.Register(nameof(ShowPickerButton), true); - - public static readonly StyledProperty AppendDirectorySeparatorProperty = - AvaloniaProperty.Register(nameof(AppendDirectorySeparator), false); - - public PathPickerField() - { - _pickerPreferenceService = Program.ServiceProvider.GetRequiredService(); - InitializeComponent(); - } - - public string Label - { - get => GetValue(LabelProperty); - set => SetValue(LabelProperty, value); - } - - public string Text - { - get => GetValue(TextProperty); - set => SetValue(TextProperty, value); - } - - public string Watermark - { - get => GetValue(WatermarkProperty); - set => SetValue(WatermarkProperty, value); - } - - public string PreferenceKey - { - get => GetValue(PreferenceKeyProperty); - set => SetValue(PreferenceKeyProperty, value); - } - - public string PickerTitle - { - get => GetValue(PickerTitleProperty); - set => SetValue(PickerTitleProperty, value); - } - - public string FileTypeName - { - get => GetValue(FileTypeNameProperty); - set => SetValue(FileTypeNameProperty, value); - } - - public string FilePatterns - { - get => GetValue(FilePatternsProperty); - set => SetValue(FilePatternsProperty, value); - } - - public string DefaultExtension - { - get => GetValue(DefaultExtensionProperty); - set => SetValue(DefaultExtensionProperty, value); - } - - public PathPickerSelectionMode PickerMode - { - get => GetValue(PickerModeProperty); - set => SetValue(PickerModeProperty, value); - } - - public bool IsTextReadOnly - { - get => GetValue(IsTextReadOnlyProperty); - set => SetValue(IsTextReadOnlyProperty, value); - } - - public bool ShowPickerButton - { - get => GetValue(ShowPickerButtonProperty); - set => SetValue(ShowPickerButtonProperty, value); - } - - public bool AppendDirectorySeparator - { - get => GetValue(AppendDirectorySeparatorProperty); - set => SetValue(AppendDirectorySeparatorProperty, value); - } - - private async void PickPath_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) - { - var topLevel = TopLevel.GetTopLevel(this); - var storageProvider = topLevel?.StorageProvider; - if (storageProvider is null) - { - return; - } - - var selectedPath = await PickPathAsync(storageProvider); - if (string.IsNullOrWhiteSpace(selectedPath)) - { - return; - } - - Text = selectedPath; - - if (!string.IsNullOrWhiteSpace(PreferenceKey)) - { - _pickerPreferenceService.RememberPath(PreferenceKey, selectedPath); - } - } - - private void OpenPath_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) - { - PathShellService.OpenInExplorer(Text); - } - - private async Task PickPathAsync(IStorageProvider storageProvider) - { - var suggestedStartLocation = await TryGetSuggestedStartLocationAsync(storageProvider); - var pickerTitle = ResolvePickerTitle(); - - switch (PickerMode) - { - case PathPickerSelectionMode.Folder: - { - var folders = await storageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions - { - Title = pickerTitle, - SuggestedStartLocation = suggestedStartLocation - }); - - return folders.Count == 0 - ? null - : NormalizeSelectedPath(folders[0].Path.LocalPath); - } - case PathPickerSelectionMode.OpenFile: - { - var files = await storageProvider.OpenFilePickerAsync(new FilePickerOpenOptions - { - Title = pickerTitle, - SuggestedStartLocation = suggestedStartLocation, - FileTypeFilter = BuildFileTypes() - }); - - return files.Count == 0 - ? null - : files[0].Path.LocalPath; - } - case PathPickerSelectionMode.SaveFile: - { - var file = await storageProvider.SaveFilePickerAsync(new FilePickerSaveOptions - { - Title = pickerTitle, - SuggestedStartLocation = suggestedStartLocation, - DefaultExtension = NormalizeDefaultExtension(DefaultExtension), - FileTypeChoices = BuildFileTypes() - }); - - return file?.Path.LocalPath; - } - default: - return null; - } - } - - private async Task TryGetSuggestedStartLocationAsync(IStorageProvider storageProvider) - { - if (string.IsNullOrWhiteSpace(PreferenceKey)) - { - return null; - } - - return await _pickerPreferenceService.TryGetStartFolderAsync(storageProvider, PreferenceKey, Text); - } - - private IReadOnlyList BuildFileTypes() - { - var patterns = (FilePatterns ?? string.Empty) - .Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - - if (patterns.Length == 0) - { - return Array.Empty(); - } - - var fileTypeName = string.IsNullOrWhiteSpace(FileTypeName) - ? "File" - : FileTypeName.Trim(); - - return - [ - new FilePickerFileType(fileTypeName) - { - Patterns = patterns.ToList() - } - ]; - } - - private string ResolvePickerTitle() - { - if (!string.IsNullOrWhiteSpace(PickerTitle)) - { - return PickerTitle; - } - - var cleanedLabel = string.IsNullOrWhiteSpace(Label) - ? "percorso" - : Label.Trim().TrimEnd(':'); - - return PickerMode == PathPickerSelectionMode.SaveFile - ? $"Salva {cleanedLabel.ToLowerInvariant()}" - : $"Seleziona {cleanedLabel.ToLowerInvariant()}"; - } - - private string NormalizeSelectedPath(string selectedPath) - { - if (PickerMode != PathPickerSelectionMode.Folder || !AppendDirectorySeparator) - { - return selectedPath; - } - - if (string.IsNullOrWhiteSpace(selectedPath)) - { - return string.Empty; - } - - return selectedPath.EndsWith(Path.DirectorySeparatorChar) - || selectedPath.EndsWith(Path.AltDirectorySeparatorChar) - ? selectedPath - : selectedPath + Path.DirectorySeparatorChar; - } - - private static string NormalizeDefaultExtension(string extension) - { - if (string.IsNullOrWhiteSpace(extension)) - { - return string.Empty; - } - - return extension.Trim().TrimStart('.'); - } -} \ No newline at end of file diff --git a/imagecatalog/Controls/PathPickerSelectionMode.cs b/imagecatalog/Controls/PathPickerSelectionMode.cs deleted file mode 100644 index 27d456e..0000000 --- a/imagecatalog/Controls/PathPickerSelectionMode.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ImageCatalog_2.Controls; - -public enum PathPickerSelectionMode -{ - Folder, - OpenFile, - SaveFile -} \ No newline at end of file diff --git a/imagecatalog/Converters/FilePathToBitmapConverter.cs b/imagecatalog/Converters/FilePathToBitmapConverter.cs deleted file mode 100644 index 614897d..0000000 --- a/imagecatalog/Converters/FilePathToBitmapConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Globalization; -using Avalonia.Data.Converters; -using Avalonia.Media.Imaging; - -namespace ImageCatalog_2.Converters; - -public sealed class FilePathToBitmapConverter : IValueConverter -{ - public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) - { - if (value is not string path || string.IsNullOrWhiteSpace(path)) - { - return null; - } - - try - { - return new Bitmap(path); - } - catch - { - return null; - } - } - - public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) - { - throw new NotSupportedException(); - } -} diff --git a/imagecatalog/DataModel.cs b/imagecatalog/DataModel.cs index fe2c1cd..cafff8c 100644 --- a/imagecatalog/DataModel.cs +++ b/imagecatalog/DataModel.cs @@ -1,25 +1,20 @@ using ImageCatalog_2.Commands; -using ImageCatalog_2.Models; using ImageCatalog_2.Services; -using ImageCatalog_2.ViewModels; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; -using System.IO; +using System.Drawing.Text; using System.Linq; using System.Text; -using System.Globalization; using System.Threading; using System.Threading.Tasks; +using System.Windows.Forms; using System.Windows.Input; -using AIFotoONLUS.Core; -using System.Text.RegularExpressions; using AutoMapper; using MaddoShared; using Microsoft.Extensions.Logging; -using System.Collections.ObjectModel; -using SixLabors.Fonts; namespace ImageCatalog_2 { @@ -38,83 +33,27 @@ namespace ImageCatalog_2 public ICommand SelectTransparentColorCommand { get; } public ICommand SelectModelsFolderCommand { get; } public ICommand SelectCsvOutputCommand { get; } - public ICommand StartAiCommand { get; } - public ICommand StartFaceEncoderCommand { get; } - public ICommand StopFaceEncoderCommand { get; } - public ICommand UploadFaceEncoderOutputCommand { get; } - public ICommand StartFaceMatcherCommand { get; } - public ICommand StopFaceMatcherCommand { get; } private readonly ITestService _service; private readonly ILogger _logger; private readonly ISettingsService _settingsService; - private readonly ImageCreationService _imageCreationService; - private readonly IAiExtractionService _aiExtractionService; - private readonly IImageProcessingCoordinator _imageProcessingCoordinator; - private readonly PickerPreferenceService? _pickerPreferenceService; - private readonly ProcessingStateViewModel _processing; - private readonly PathSettingsViewModel _paths; - private readonly AiSettingsViewModel _ai; - private readonly RaceUploadSettingsViewModel _raceUpload; - private readonly VisualSettingsViewModel _visual; + private readonly ImageCreationStuff _imageCreationService; private readonly PicSettings _picSettings; private readonly IMapper _mapper; - private readonly AsyncCommand _startFaceEncoderCommand; - private readonly AsyncCommand _stopFaceEncoderCommand; - private readonly AsyncCommand _uploadFaceEncoderOutputCommand; - private readonly AsyncCommand _startFaceMatcherCommand; - private readonly AsyncCommand _stopFaceMatcherCommand; - private readonly object _faceEncoderProcessLock = new(); - private readonly object _faceMatcherProcessLock = new(); - private Process? _faceEncoderProcess; - private Process? _faceMatcherProcess; - private CancellationTokenSource? _faceEncoderWatcherTokenSource; - private Task? _faceEncoderWatcherTask; - private CancellationTokenSource? _faceEncoderLogWatcherTokenSource; - private Task? _faceEncoderLogWatcherTask; - private CancellationTokenSource? _faceMatcherWatcherTokenSource; - private Task? _faceMatcherWatcherTask; - private CancellationTokenSource? _faceMatcherLogWatcherTokenSource; - private Task? _faceMatcherLogWatcherTask; - private bool _hasStartedFaceEncoderInSession; - private bool _hasStartedFaceMatcherInSession; - private bool _isLoadingFaceSshUserPreferences; - private string _lastFaceEncoderOutputFilePath = string.Empty; - private int _numberAiGpuRefreshVersion; - private volatile bool _numberAiGpuValidationPending; - - private sealed record ParsedFaceMatcherRow(string PhotoId, double? Score, string RawRow, string DebugSummary); - - private const string AiCsvOverwriteDialogTitle = "File CSV gia esistente"; - private static readonly Regex FaceUploadPathRegex = new(@"^\d{4}/(?:0[1-9]|1[0-2])\.[^/\\]+/[^/\\]+$", RegexOptions.Compiled | RegexOptions.CultureInvariant); // ComboBox collections public List AvailableFonts { get; } public List VerticalPositions { get; } = new() { "Alto", "Centro", "Basso" }; public List HorizontalAlignments { get; } = new() { "Sinistra", "Centro", "Destra" }; - [CLSCompliant(false)] - public DataModel(ITestService testService, ISettingsService settingsService, - ImageCreationService imageCreationService, IAiExtractionService aiExtractionService, IImageProcessingCoordinator imageProcessingCoordinator, PicSettings picSettings, - IMapper mapper, ILogger logger, MaddoShared.IVersionProvider? versionProvider = null, PickerPreferenceService? pickerPreferenceService = null) + public DataModel(ITestService testService, ISettingsService settingsService, + ImageCreationStuff imageCreationService, PicSettings picSettings, + IMapper mapper, ILogger logger, MaddoShared.IVersionProvider? versionProvider = null) { _service = testService; _logger = logger; _settingsService = settingsService; _imageCreationService = imageCreationService; - _aiExtractionService = aiExtractionService; - _imageProcessingCoordinator = imageProcessingCoordinator; - _pickerPreferenceService = pickerPreferenceService; - _processing = new ProcessingStateViewModel(); - _processing.PropertyChanged += OnProcessingPropertyChanged; - _paths = new PathSettingsViewModel(); - _paths.PropertyChanged += OnPathsPropertyChanged; - _ai = new AiSettingsViewModel(); - _ai.PropertyChanged += OnAiPropertyChanged; - _raceUpload = new RaceUploadSettingsViewModel(); - _raceUpload.PropertyChanged += OnRaceUploadPropertyChanged; - _visual = new VisualSettingsViewModel(); - _visual.PropertyChanged += OnVisualPropertyChanged; _picSettings = picSettings; _mapper = mapper; // Populate AppVersion from version provider when available @@ -126,18 +65,7 @@ namespace ImageCatalog_2 ProcessImagesCommand = new AsyncCommand(ProcessImages); SelectModelsFolderCommand = new RelayCommand(SelectModelsFolder); SelectCsvOutputCommand = new RelayCommand(SelectCsvOutput); - StartAiCommand = new AsyncCommand(StartAiAsync); - _startFaceEncoderCommand = new AsyncCommand(RunFaceEncoderAsync, CanRunFaceEncoder); - _stopFaceEncoderCommand = new AsyncCommand(() => StopFaceEncoderAsync("Arresto richiesto dall'utente."), CanStopFaceEncoder); - _uploadFaceEncoderOutputCommand = new AsyncCommand(UploadFaceEncoderOutputAsync, CanUploadFaceEncoderOutput); - _startFaceMatcherCommand = new AsyncCommand(RunFaceMatcherAsync, CanRunFaceMatcher); - _stopFaceMatcherCommand = new AsyncCommand(() => StopFaceMatcherAsync("Arresto richiesto dall'utente."), CanStopFaceMatcher); - StartFaceEncoderCommand = _startFaceEncoderCommand; - StopFaceEncoderCommand = _stopFaceEncoderCommand; - UploadFaceEncoderOutputCommand = _uploadFaceEncoderOutputCommand; - StartFaceMatcherCommand = _startFaceMatcherCommand; - StopFaceMatcherCommand = _stopFaceMatcherCommand; - + SelectSourceFolderCommand = new RelayCommand(SelectSourceFolder); SelectDestinationFolderCommand = new RelayCommand(SelectDestinationFolder); SelectLogoFileCommand = new RelayCommand(SelectLogoFile); @@ -148,500 +76,186 @@ namespace ImageCatalog_2 // Load available fonts AvailableFonts = LoadAvailableFonts(); - LoadFaceSshUserPreferences(); - QueueRefreshNumberAiGpuCapabilities(); - RefreshFaceExecutableCapabilities(); } - private async Task StartAiAsync() + private async Task RunAiExtractionAsync(CancellationToken token) { - if (!await ConfirmAiCsvOverwriteIfNeededAsync().ConfigureAwait(false)) + // Simple stub: scan source folder for supported images and either call AIFotoONLUS.Core + // or simulate results. Write CSV output and populate PreviewResults. + if (string.IsNullOrWhiteSpace(SourcePath) || !System.IO.Directory.Exists(SourcePath)) { - await InvokeOnUiThreadAsync(() => NumberAiStatsSummary = "OCR annullato.").ConfigureAwait(false); + _logger.LogWarning("Source path invalid for AI extraction: {SourcePath}", SourcePath); return; } - MainToken = new CancellationTokenSource(); + var imageFiles = System.IO.Directory.EnumerateFiles(SourcePath, "*.*", System.IO.SearchOption.TopDirectoryOnly) + .Where(f => f.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) + || f.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) + || f.EndsWith(".png", StringComparison.OrdinalIgnoreCase) + || f.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) + || f.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)) + .ToList(); + + if (imageFiles.Count == 0) + { + _logger.LogInformation("No image files found for AI extraction in {SourcePath}", SourcePath); + return; + } + + // Clear preview + await InvokeOnUiThreadAsync(() => { PreviewResults.Clear(); }); + + // Try to locate AIFotoONLUS.Core types via reflection to avoid hard reference at compile time + Type? aiProcessorType = null; + object? aiProcessor = null; + try { - await RunAiExtractionCoreAsync(MainToken.Token, useDestination: true, recursive: true).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - await InvokeOnUiThreadAsync(() => NumberAiStatsSummary = "OCR annullato.").ConfigureAwait(false); + var assembly = AppDomain.CurrentDomain.GetAssemblies() + .FirstOrDefault(a => a.GetName().Name?.Equals("AIFotoONLUS.Core", StringComparison.OrdinalIgnoreCase) == true); + if (assembly != null) + { + aiProcessorType = assembly.GetType("AIFotoONLUS.Core.AiProcessor"); + if (aiProcessorType != null) + { + // Create instance assuming parameterless ctor + aiProcessor = Activator.CreateInstance(aiProcessorType); + } + } } catch (Exception ex) { - _logger.LogError(ex, "AI extraction failed"); - if (UseNumberAiGpu) - { - QueueRefreshNumberAiGpuCapabilities(); - } - - await InvokeOnUiThreadAsync(() => NumberAiStatsSummary = $"Errore OCR: {ex.GetBaseException().Message}").ConfigureAwait(false); - - await ShowErrorMessageAsync("Errore AI", ex.GetBaseException().Message).ConfigureAwait(false); - } - finally - { - MainToken = null; - } - } - - private async Task RunAiExtractionCoreAsync(CancellationToken token, bool useDestination = false, bool recursive = false, bool failOnInvalidPath = false) - { - var searchRoot = useDestination ? DestinationPath : SourcePath; - if (string.IsNullOrWhiteSpace(searchRoot) || !System.IO.Directory.Exists(searchRoot)) - { - _logger.LogWarning("AI extraction path invalid: {Path}", searchRoot); - if (failOnInvalidPath) - { - throw new DirectoryNotFoundException($"AI extraction path invalid: {searchRoot}"); - } - - return; + _logger.LogDebug(ex, "AIFotoONLUS.Core not available or failed to load via reflection"); } - await InvokeOnUiThreadAsync(() => - { - PreviewResults.Clear(); - AiProgress = 0; - NumberAiStatsSummary = BuildNumberAiIdleSummary(); - }).ConfigureAwait(false); + var results = new List(); - var summary = await _aiExtractionService.RunAsync( - new AiExtractionRequest + foreach (var file in imageFiles) + { + token.ThrowIfCancellationRequested(); + + string extracted = string.Empty; + + if (aiProcessorType is not null && aiProcessor is not null) { - SearchRoot = searchRoot, - Recursive = recursive, - IncludeThumbnails = IncludeNumberAiThumbnails, - ModelsFolderPath = ModelsFolderPath, - UseGpu = UseNumberAiGpu, - WorkloadLevel = NumberAiWorkloadLevel, - CsvOutputPath = CsvOutputPath - }, - token, - result => InvokeOnUiThreadAsync(() => - { - if (!string.IsNullOrWhiteSpace(result.Text)) + try { - PreviewResults.Add(result); + // Preferred method name: ExtractNumbersFromImage(string imagePath) + var method = aiProcessorType.GetMethod("ExtractNumbersFromImage") ?? aiProcessorType.GetMethod("ExtractTextFromImage"); + if (method is not null) + { + var value = method.Invoke(aiProcessor, new object[] { file }); + if (value != null) + extracted = value.ToString() ?? string.Empty; + } + else + { + // No expected method found, fallback to simulated result + extracted = SimulateExtraction(file); + } } - }), - progress => InvokeOnUiThreadAsync(() => + catch (Exception ex) + { + _logger.LogWarning(ex, "Error invoking AI processor for {File}", file); + extracted = SimulateExtraction(file); + } + } + else { - AiProgress = progress.PercentComplete; - NumberAiStatsSummary = BuildNumberAiProgressSummary(progress); - })).ConfigureAwait(false); + // Simulate extraction when library not available + extracted = SimulateExtraction(file); + } - await InvokeOnUiThreadAsync(() => + var res = new AiResult { Path = file, Text = extracted }; + results.Add(res); + + await InvokeOnUiThreadAsync(() => PreviewResults.Add(res)); + } + + // Write CSV if requested + if (!string.IsNullOrWhiteSpace(CsvOutputPath)) { - AiProgress = summary.TotalFiles > 0 ? 100 : 0; - NumberAiStatsSummary = BuildNumberAiCompletionSummary(summary); - }).ConfigureAwait(false); + try + { + var dir = System.IO.Path.GetDirectoryName(CsvOutputPath) ?? string.Empty; + if (!string.IsNullOrWhiteSpace(dir) && !System.IO.Directory.Exists(dir)) + { + System.IO.Directory.CreateDirectory(dir); + } + + using var sw = new System.IO.StreamWriter(CsvOutputPath, false, System.Text.Encoding.UTF8); + sw.WriteLine("Path,Text"); + foreach (var r in results) + { + var safeText = (r.Text ?? string.Empty).Replace("\"", "\"\""); + sw.WriteLine($"\"{r.Path}\",\"{safeText}\""); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to write CSV to {CsvOutputPath}", CsvOutputPath); + } + } } - /// - /// Optional UI-thread invoker set by the active UI layer. - /// - public Action? UiInvoker { get; set; } + private string SimulateExtraction(string file) + { + // Cheap heuristic: return filename digits + var name = System.IO.Path.GetFileNameWithoutExtension(file); + var digits = new string(name.Where(char.IsDigit).ToArray()); + if (string.IsNullOrEmpty(digits)) return ""; + return digits; + } private Task InvokeOnUiThreadAsync(Action action) { + // Use SynchronizationContext via Task to ensure UI thread update return Task.Run(() => { - if (UiInvoker != null) - UiInvoker(action); - else - action(); + System.Windows.Application.Current?.Dispatcher.Invoke(action); }); } - public AiSettingsViewModel Ai => _ai; - public RaceUploadSettingsViewModel RaceUpload => _raceUpload; - // AI properties + private bool _extractNumbers; public bool ExtractNumbers { - get => _ai.ExtractNumbers; - set => _ai.ExtractNumbers = value; + get => _extractNumbers; + set { _extractNumbers = value; NotifyPropertyChanged(); } } + private string _modelsFolderPath = string.Empty; public string ModelsFolderPath { - get => _ai.ModelsFolderPath; - set - { - _ai.ModelsFolderPath = value; - QueueRefreshNumberAiGpuCapabilities(); - } + get => _modelsFolderPath; + set { _modelsFolderPath = value; NotifyPropertyChanged(); } } + private string _csvOutputPath = string.Empty; public string CsvOutputPath { - get => _ai.CsvOutputPath; - set => _ai.CsvOutputPath = value; - } - - public Func>? ConfirmAiCsvOverwriteAsync { get; set; } - - public bool UseNumberAiGpu - { - get => _ai.UseNumberAiGpu; - set => SetUseNumberAiGpu(value); - } - - public bool NumberAiGpuOptionEnabled - { - get => _ai.NumberAiGpuOptionEnabled; - private set => _ai.NumberAiGpuOptionEnabled = value; - } - - public bool IncludeNumberAiThumbnails - { - get => _ai.IncludeNumberAiThumbnails; - set => _ai.IncludeNumberAiThumbnails = value; - } - - public IReadOnlyList NumberAiWorkloadOptions { get; } = [1, 2, 3, 4, 5]; - - public int NumberAiWorkloadLevel - { - get => _ai.NumberAiWorkloadLevel; - set => _ai.NumberAiWorkloadLevel = NormalizeNumberAiWorkloadLevel(value); - } - - public string NumberAiStatsSummary - { - get => _ai.NumberAiStatsSummary; - private set => _ai.NumberAiStatsSummary = value; - } - - public string FaceExecutablePath - { - get => _ai.FaceExecutablePath; - set - { - var normalizedValue = value ?? string.Empty; - if (string.Equals(_ai.FaceExecutablePath, normalizedValue, StringComparison.Ordinal)) - { - RefreshFaceExecutableCapabilities(); - return; - } - - _ai.FaceExecutablePath = normalizedValue; - RefreshFaceExecutableCapabilities(); - } - } - - public string FaceOutputFolderPath - { - get => _ai.FaceOutputFolderPath; - set => _ai.FaceOutputFolderPath = value; - } - - public string FaceUploadPath - { - get => _ai.FaceUploadPath; - set - { - _ai.FaceUploadPath = value?.Trim() ?? string.Empty; - NotifyPropertyChanged(nameof(IsFaceUploadPathValid)); - UpdateFaceUploadCommandStates(); - } - } - - public bool FaceUploadDryRun - { - get => _ai.FaceUploadDryRun; - set => SetFaceSshPreferenceBoolValue(PickerPreferenceKeys.FaceUploadDryRun, normalizedValue => _ai.FaceUploadDryRun = normalizedValue, value); - } - - public bool IsFaceUploadPathValid => IsValidFaceUploadPath(FaceUploadPath); - - public string FaceSshUsername - { - get => _ai.FaceSshUsername; - set => SetFaceSshPreferenceValue(PickerPreferenceKeys.FaceSshUsername, normalizedValue => _ai.FaceSshUsername = normalizedValue, value?.Trim() ?? string.Empty); - } - - public string FaceSshPassword - { - get => _ai.FaceSshPassword; - set => SetFaceSshPreferenceValue(PickerPreferenceKeys.FaceSshPassword, normalizedValue => _ai.FaceSshPassword = normalizedValue, value ?? string.Empty); - } - - public string FaceSshAddress - { - get => _ai.FaceSshAddress; - set => SetFaceSshPreferenceValue(PickerPreferenceKeys.FaceSshAddress, normalizedValue => _ai.FaceSshAddress = normalizedValue, value?.Trim() ?? string.Empty); - } - - public string FaceSshPort - { - get => _ai.FaceSshPort; - set => SetFaceSshPreferenceValue(PickerPreferenceKeys.FaceSshPort, normalizedValue => _ai.FaceSshPort = normalizedValue, value?.Trim() ?? string.Empty); - } - - public string FaceSshPathA - { - get => _ai.FaceSshPathA; - set => SetFaceSshPreferenceValue(PickerPreferenceKeys.FaceSshPathA, normalizedValue => _ai.FaceSshPathA = normalizedValue, value?.Trim() ?? string.Empty); - } - - public string FaceSshPathB - { - get => _ai.FaceSshPathB; - set => SetFaceSshPreferenceValue(PickerPreferenceKeys.FaceSshPathB, normalizedValue => _ai.FaceSshPathB = normalizedValue, value?.Trim() ?? string.Empty); - } - - public bool IsFaceUploadRunning - { - get => _ai.IsFaceUploadRunning; - private set => _ai.IsFaceUploadRunning = value; - } - - public bool FaceRecursive - { - get => _ai.FaceRecursive; - set => _ai.FaceRecursive = value; - } - - public bool FaceIncludeThumbnails - { - get => _ai.FaceIncludeThumbnails; - set => _ai.FaceIncludeThumbnails = value; - } - - public IReadOnlyList FaceParallelismOptions { get; } = [1, 2, 3, 4, 5]; - - public int FaceParallelism - { - get => _ai.FaceParallelism; - set => _ai.FaceParallelism = value; - } - - public int FaceMinSize - { - get => _ai.FaceMinSize; - set => _ai.FaceMinSize = value; - } - - public bool FaceUpsample - { - get => _ai.FaceUpsample; - set => _ai.FaceUpsample = value; - } - - public bool FaceGpuOptionEnabled => _ai.FaceGpuOptionEnabled; - - public bool UseFaceGpu - { - get => _ai.UseFaceGpu; - set => SetUseFaceGpu(value); - } - - public bool IsFaceEncoderRunning - { - get => _ai.IsFaceEncoderRunning; - private set => _ai.IsFaceEncoderRunning = value; - } - - public string FaceStatusMessage - { - get => _ai.FaceStatusMessage; - private set => _ai.FaceStatusMessage = value; - } - - public string FaceCommandOutput - { - get => _ai.FaceCommandOutput; - private set => _ai.FaceCommandOutput = value; - } - - public string FaceMatcherExecutablePath - { - get => _ai.FaceMatcherExecutablePath; - set => _ai.FaceMatcherExecutablePath = value ?? string.Empty; - } - - public string FaceMatcherEncodingsPath - { - get => _ai.FaceMatcherEncodingsPath; - set => _ai.FaceMatcherEncodingsPath = value ?? string.Empty; - } - - public string FaceMatcherOutputPath - { - get => _ai.FaceMatcherOutputPath; - set => _ai.FaceMatcherOutputPath = value ?? string.Empty; - } - - public string FaceMatcherLogPath - { - get => _ai.FaceMatcherLogPath; - set => _ai.FaceMatcherLogPath = value ?? string.Empty; - } - - public double FaceMatcherTolerance - { - get => _ai.FaceMatcherTolerance; - set => _ai.FaceMatcherTolerance = NormalizeFaceMatcherTolerance(value); - } - - public string FaceMatcherSelectedImagePath - { - get => _ai.FaceMatcherSelectedImagePath; - set => _ai.FaceMatcherSelectedImagePath = value ?? string.Empty; - } - - public bool IsFaceMatcherRunning - { - get => _ai.IsFaceMatcherRunning; - private set => _ai.IsFaceMatcherRunning = value; - } - - public string FaceMatcherStatusMessage - { - get => _ai.FaceMatcherStatusMessage; - private set => _ai.FaceMatcherStatusMessage = value; - } - - public string FaceMatcherCommandOutput - { - get => _ai.FaceMatcherCommandOutput; - private set => _ai.FaceMatcherCommandOutput = value; - } - - public System.Collections.ObjectModel.ObservableCollection FaceMatcherResults => _ai.FaceMatcherResults; - - // Race upload settings - public string ApiLogin - { - get => _raceUpload.ApiLogin; - set => _raceUpload.ApiLogin = value; - } - - public string ApiPassword - { - get => _raceUpload.ApiPassword; - set => _raceUpload.ApiPassword = value; - } - - public string ApiRaceDescription - { - get => _raceUpload.ApiRaceDescription; - set => _raceUpload.ApiRaceDescription = value; - } - - public string ApiRaceTypeId - { - get => _raceUpload.ApiRaceTypeId; - set => _raceUpload.ApiRaceTypeId = value; - } - - public DateTime ApiRaceStartDate - { - get => _raceUpload.ApiRaceStartDate; - set => _raceUpload.ApiRaceStartDate = value; - } - - public DateTime ApiRaceEndDate - { - get => _raceUpload.ApiRaceEndDate; - set => _raceUpload.ApiRaceEndDate = value; - } - - public string ApiPathBase - { - get => _raceUpload.ApiPathBase; - set => _raceUpload.ApiPathBase = value; - } - - public string ApiLocalita - { - get => _raceUpload.ApiLocalita; - set => _raceUpload.ApiLocalita = value; - } - - public int ApiEventoInLineaIndex - { - get => _raceUpload.ApiEventoInLineaIndex; - set => _raceUpload.ApiEventoInLineaIndex = value; - } - - public int ApiTipoIndexValue - { - get => _raceUpload.ApiTipoIndexValue; - set => _raceUpload.ApiTipoIndexValue = value; - } - - public int ApiFreeEventIndex - { - get => _raceUpload.ApiFreeEventIndex; - set => _raceUpload.ApiFreeEventIndex = value; - } - - public string ApiRaceId - { - get => _raceUpload.ApiRaceId; - set => _raceUpload.ApiRaceId = value; - } - - public string ApiRemoteProcessedBasePath - { - get => _raceUpload.ApiRemoteProcessedBasePath; - set => _raceUpload.ApiRemoteProcessedBasePath = value; + get => _csvOutputPath; + set { _csvOutputPath = value; NotifyPropertyChanged(); } } // Preview results for DataGrid - public System.Collections.ObjectModel.ObservableCollection PreviewResults => _ai.PreviewResults; + private System.Collections.ObjectModel.ObservableCollection _previewResults = new(); + public System.Collections.ObjectModel.ObservableCollection PreviewResults => _previewResults; - public double AiProgress + public class AiResult { - get => _ai.AiProgress; - set => _ai.AiProgress = value; - } - - private string BuildNumberAiIdleSummary() - { - var workerCount = ResolveNumberAiWorkerCount(UseNumberAiGpu, NumberAiWorkloadLevel); - var unit = UseNumberAiGpu ? "batch" : "worker"; - return $"In attesa. Carico {NumberAiWorkloadLevel}/5, {workerCount} {unit}, 0.00 img/s."; - } - - private static string BuildNumberAiProgressSummary(AiExtractionProgressUpdate progress) - { - var unit = progress.UseGpu ? "batch" : "worker"; - return $"{progress.ProcessedFiles}/{progress.TotalFiles} immagini, media {progress.AverageImagesPerSecond:F2} img/s, carico {progress.WorkloadLevel}/5, {progress.WorkerCount} {unit}."; - } - - private static string BuildNumberAiCompletionSummary(AiExtractionRunSummary summary) - { - if (summary.TotalFiles == 0) - { - return "Nessuna immagine trovata per OCR."; - } - - var unit = summary.UseGpu ? "batch" : "worker"; - return $"Completato: {summary.ProcessedFiles}/{summary.TotalFiles} immagini, media finale {summary.AverageImagesPerSecond:F2} img/s, errori {summary.FailedFiles}, carico {summary.WorkloadLevel}/5, {summary.WorkerCount} {unit}."; + public string Path { get; set; } = string.Empty; + public string Text { get; set; } = string.Empty; } private List LoadAvailableFonts() { - try + var fonts = new List(); + using (var installedFonts = new InstalledFontCollection()) { - return SystemFonts.Collection.Families - .Select(f => f.Name) - .Where(name => !string.IsNullOrWhiteSpace(name)) - .Distinct(StringComparer.OrdinalIgnoreCase) - .OrderBy(name => name, StringComparer.CurrentCultureIgnoreCase) - .ToList(); - } - catch - { - return new List(); + fonts.AddRange(installedFonts.Families.Select(f => f.Name)); } + return fonts; } private CancellationTokenSource? _mainToken; @@ -656,34 +270,64 @@ namespace ImageCatalog_2 } } + private string _sourcePath; + public string SourcePath { - get => _paths.SourcePath; - set => _paths.SourcePath = value; + get => _sourcePath; + set + { + _sourcePath = value; + NotifyPropertyChanged(); + } } + private string _destinationPath; + public string DestinationPath { - get => _paths.DestinationPath; - set => _paths.DestinationPath = value; + get => _destinationPath; + set + { + _destinationPath = value; + NotifyPropertyChanged(); + } } + private string _horizontalText; + public string HorizontalText { - get => _visual.HorizontalText; - set => _visual.HorizontalText = value; + get => _horizontalText; + set + { + _horizontalText = value; + NotifyPropertyChanged(); + } } + private string _verticalText; + public string VerticalText { - get => _visual.VerticalText; - set => _visual.VerticalText = value; + get => _verticalText; + set + { + _verticalText = value; + NotifyPropertyChanged(); + } } + private bool _overwriteImages; + public bool OverwriteImages { - get => _visual.OverwriteImages; - set => _visual.OverwriteImages = value; + get => _overwriteImages; + set + { + _overwriteImages = value; + NotifyPropertyChanged(); + } } private bool _uiEnabled = true; @@ -701,78 +345,16 @@ namespace ImageCatalog_2 public bool UiDisabled => !_uiEnabled; - public ProcessingStateViewModel Processing => _processing; - public PathSettingsViewModel Paths => _paths; - public VisualSettingsViewModel Visual => _visual; - - private void OnProcessingPropertyChanged(object? sender, PropertyChangedEventArgs e) - { - if (string.IsNullOrWhiteSpace(e.PropertyName)) - { - return; - } - - // Keep existing DataModel bindings working while state lives in child viewmodel. - NotifyPropertyChanged(e.PropertyName); - } - - private void OnPathsPropertyChanged(object? sender, PropertyChangedEventArgs e) - { - if (string.IsNullOrWhiteSpace(e.PropertyName)) - { - return; - } - - if (string.Equals(e.PropertyName, nameof(PathSettingsViewModel.DestinationPath), StringComparison.Ordinal)) - { - UpdateAiCsvOutputPathForDestination(); - } - - NotifyPropertyChanged(e.PropertyName); - } - - private void OnAiPropertyChanged(object? sender, PropertyChangedEventArgs e) - { - if (string.IsNullOrWhiteSpace(e.PropertyName)) - { - return; - } - - NotifyPropertyChanged(e.PropertyName); - if (string.Equals(e.PropertyName, nameof(AiSettingsViewModel.FaceUploadPath), StringComparison.Ordinal)) - { - NotifyPropertyChanged(nameof(IsFaceUploadPathValid)); - } - - UpdateFaceEncoderCommandStates(); - UpdateFaceUploadCommandStates(); - UpdateFaceMatcherCommandStates(); - } - - private void OnRaceUploadPropertyChanged(object? sender, PropertyChangedEventArgs e) - { - if (string.IsNullOrWhiteSpace(e.PropertyName)) - { - return; - } - - NotifyPropertyChanged(e.PropertyName); - } - - private void OnVisualPropertyChanged(object? sender, PropertyChangedEventArgs e) - { - if (string.IsNullOrWhiteSpace(e.PropertyName)) - { - return; - } - - NotifyPropertyChanged(e.PropertyName); - } + private string _speedCounter = "-"; public string SpeedCounter { - get => _processing.SpeedCounter; - set => _processing.SpeedCounter = value; + get => _speedCounter; + set + { + _speedCounter = value; + NotifyPropertyChanged(); + } } private int _chunkSize; @@ -800,122 +382,261 @@ namespace ImageCatalog_2 } // Thumbnail settings + private string _thumbnailPrefix = "tn_"; public string ThumbnailPrefix { - get => _visual.ThumbnailPrefix; - set => _visual.ThumbnailPrefix = value; + get => _thumbnailPrefix; + set + { + _thumbnailPrefix = value; + NotifyPropertyChanged(); + } } + private int _thumbnailHeight = 350; public int ThumbnailHeight { - get => _visual.ThumbnailHeight; - set => _visual.ThumbnailHeight = value; + get => _thumbnailHeight; + set + { + _thumbnailHeight = value; + NotifyPropertyChanged(); + } } + private int _thumbnailWidth = 350; public int ThumbnailWidth { - get => _visual.ThumbnailWidth; - set => _visual.ThumbnailWidth = value; + get => _thumbnailWidth; + set + { + _thumbnailWidth = value; + NotifyPropertyChanged(); + } } // Big photo settings + private int _photoBigHeight = 2240; public int PhotoBigHeight { - get => _visual.PhotoBigHeight; - set => _visual.PhotoBigHeight = value; + get => _photoBigHeight; + set + { + _photoBigHeight = value; + NotifyPropertyChanged(); + } } + private int _photoBigWidth = 2240; public int PhotoBigWidth { - get => _visual.PhotoBigWidth; - set => _visual.PhotoBigWidth = value; + get => _photoBigWidth; + set + { + _photoBigWidth = value; + NotifyPropertyChanged(); + } } // Font settings + private int _fontSize = 20; public int FontSize { - get => _visual.FontSize; - set => _visual.FontSize = value; + get => _fontSize; + set + { + _fontSize = value; + NotifyPropertyChanged(); + } } + private int _fontSizeThumbnail = 50; public int FontSizeThumbnail { - get => _visual.FontSizeThumbnail; - set => _visual.FontSizeThumbnail = value; + get => _fontSizeThumbnail; + set + { + _fontSizeThumbnail = value; + NotifyPropertyChanged(); + } } + private string _fontName = "Arial"; public string FontName { - get => _visual.FontName; - set => _visual.FontName = value; + get => _fontName; + set + { + _fontName = value; + NotifyPropertyChanged(); + } } + private bool _fontBold = false; public bool FontBold { - get => _visual.FontBold; - set => _visual.FontBold = value; + get => _fontBold; + set + { + _fontBold = value; + NotifyPropertyChanged(); + } } // Text settings + private int _textTransparency = 0; public int TextTransparency { - get => _visual.TextTransparency; - set => _visual.TextTransparency = value; + get => _textTransparency; + set + { + _textTransparency = value; + NotifyPropertyChanged(); + } } + private int _textMargin = 8; public int TextMargin { - get => _visual.TextMargin; - set => _visual.TextMargin = value; + get => _textMargin; + set + { + _textMargin = value; + NotifyPropertyChanged(); + } } + private string _textColorRGB = "Yellow"; public string TextColorRGB { - get => _visual.TextColorRGB; - set => _visual.TextColorRGB = value; + get => _textColorRGB; + set + { + _textColorRGB = value; + NotifyPropertyChanged(); + } } + private string _transparentColor = "#FFFFFF"; public string TransparentColor { - get => _visual.TransparentColor; - set => _visual.TransparentColor = value; + get => _transparentColor; + set + { + _transparentColor = value; + NotifyPropertyChanged(); + } } + private bool _useTransparentColor; public bool UseTransparentColor { - get => _visual.UseTransparentColor; - set => _visual.UseTransparentColor = value; + get => _useTransparentColor; + set + { + _useTransparentColor = value; + NotifyPropertyChanged(); + } } // Logo/Watermark settings + private string _logoFile = ""; public string LogoFile { - get => _visual.LogoFile; - set => _visual.LogoFile = value; + get => _logoFile; + set + { + _logoFile = value; + NotifyPropertyChanged(); + } } + private int _logoHeight = 430; public int LogoHeight { - get => _visual.LogoHeight; - set => _visual.LogoHeight = value; + get => _logoHeight; + set + { + _logoHeight = value; + NotifyPropertyChanged(); + } } + private int _logoWidth = 430; public int LogoWidth { - get => _visual.LogoWidth; - set => _visual.LogoWidth = value; + get => _logoWidth; + set + { + _logoWidth = value; + NotifyPropertyChanged(); + } } + private int _logoMargin = 290; public int LogoMargin { - get => _visual.LogoMargin; - set => _visual.LogoMargin = value; + get => _logoMargin; + set + { + _logoMargin = value; + NotifyPropertyChanged(); + } } + private int _logoTransparency = 100; public int LogoTransparency { - get => _visual.LogoTransparency; - set => _visual.LogoTransparency = value; + get => _logoTransparency; + set + { + _logoTransparency = value; + NotifyPropertyChanged(); + } + } + + // Image library selection (UI radio buttons bind to the boolean helpers) + private string _imageLibrary = "System.Graphics"; + + /// + /// The selected image processing library. Possible values: "System.Graphics" or "ImageSharp". + /// This value is mirrored into PicSettings.ImageCreatorProvider so the runtime mapper picks the implementation. + /// + public string ImageLibrary + { + get => _imageLibrary; + set + { + if (_imageLibrary == value) return; + _imageLibrary = value; + // Reflect selection into PicSettings so mapper can resolve at runtime + _picSettings.ImageCreatorProvider = string.Equals(value, "ImageSharp", StringComparison.OrdinalIgnoreCase) + ? "ALTERNATE" + : "Sharp"; + NotifyPropertyChanged(); + NotifyPropertyChanged(nameof(UseSystemGraphics)); + NotifyPropertyChanged(nameof(UseImageSharp)); + } + } + + public bool UseSystemGraphics + { + get => string.Equals(ImageLibrary, "System.Graphics", StringComparison.OrdinalIgnoreCase); + set + { + if (value) ImageLibrary = "System.Graphics"; + NotifyPropertyChanged(); + } + } + + public bool UseImageSharp + { + get => string.Equals(ImageLibrary, "ImageSharp", StringComparison.OrdinalIgnoreCase); + set + { + if (value) ImageLibrary = "ImageSharp"; + NotifyPropertyChanged(); + } } // Folder division settings @@ -953,29 +674,49 @@ namespace ImageCatalog_2 } // Vertical text settings + private int _verticalTextSize = 20; public int VerticalTextSize { - get => _visual.VerticalTextSize; - set => _visual.VerticalTextSize = value; + get => _verticalTextSize; + set + { + _verticalTextSize = value; + NotifyPropertyChanged(); + } } + private int _verticalTextMargin = 6; public int VerticalTextMargin { - get => _visual.VerticalTextMargin; - set => _visual.VerticalTextMargin = value; + get => _verticalTextMargin; + set + { + _verticalTextMargin = value; + NotifyPropertyChanged(); + } } // JPEG compression settings + private int _jpegQuality = 85; public int JpegQuality { - get => _visual.JpegQuality; - set => _visual.JpegQuality = value; + get => _jpegQuality; + set + { + _jpegQuality = value; + NotifyPropertyChanged(); + } } + private int _jpegQualityThumbnail = 30; public int JpegQualityThumbnail { - get => _visual.JpegQualityThumbnail; - set => _visual.JpegQualityThumbnail = value; + get => _jpegQualityThumbnail; + set + { + _jpegQualityThumbnail = value; + NotifyPropertyChanged(); + } } // CheckBox settings @@ -1012,17 +753,6 @@ namespace ImageCatalog_2 } } - private bool _removeExifData; - public bool RemoveExifData - { - get => _removeExifData; - set - { - _removeExifData = value; - NotifyPropertyChanged(); - } - } - private bool _updateSubdirectories; public bool UpdateSubdirectories { @@ -1067,16 +797,26 @@ namespace ImageCatalog_2 } } + private bool _addLogo; public bool AddLogo { - get => _visual.AddLogo; - set => _visual.AddLogo = value; + get => _addLogo; + set + { + _addLogo = value; + NotifyPropertyChanged(); + } } + private bool _keepOriginalDimensions; public bool KeepOriginalDimensions { - get => _visual.KeepOriginalDimensions; - set => _visual.KeepOriginalDimensions = value; + get => _keepOriginalDimensions; + set + { + _keepOriginalDimensions = value; + NotifyPropertyChanged(); + } } private bool _showDate; @@ -1414,36 +1154,73 @@ namespace ImageCatalog_2 } // Image processing progress and status + private string _processingStatus = ""; public string ProcessingStatus { - get => _processing.ProcessingStatus; - set => _processing.ProcessingStatus = value; + get => _processingStatus; + set + { + _processingStatus = value; + NotifyPropertyChanged(); + } } + private int _processedImagesCount = 0; public int ProcessedImagesCount { - get => _processing.ProcessedImagesCount; - set => _processing.ProcessedImagesCount = value; + get => _processedImagesCount; + set + { + _processedImagesCount = value; + NotifyPropertyChanged(); + } } + private int _totalImagesCount = 0; public int TotalImagesCount { - get => _processing.TotalImagesCount; - set => _processing.TotalImagesCount = value; + get => _totalImagesCount; + set + { + _totalImagesCount = value; + NotifyPropertyChanged(); + } } + private int _progressBarValue = 0; public int ProgressBarValue { - get => _processing.ProgressBarValue; - set => _processing.ProgressBarValue = value; + get => _progressBarValue; + set + { + _progressBarValue = value; + NotifyPropertyChanged(); + } } + private int _progressBarMaximum = 100; public int ProgressBarMaximum { - get => _processing.ProgressBarMaximum; - set => _processing.ProgressBarMaximum = value; + get => _progressBarMaximum; + set + { + _progressBarMaximum = value; + NotifyPropertyChanged(); + } } + private ConcurrentBag _results = new(); + private int _currentAmount = 0; + private int _previousAmount = 0; + // Atomic counter for processed images — avoids expensive ConcurrentBag.Count enumerations + private int _processedAtomic = 0; + private System.Threading.Timer? _speedTimer; + // Stopwatch used to compute run-wide averages + private Stopwatch? _speedWatch; + // Recent diffs queue to smooth short-term fluctuations + private readonly Queue _recentDiffs = new(); + private int _recentWindowSize = 5; // average over last 5 samples (~5s) + private void Test(object parameter) { Debug.WriteLine("Yep"); @@ -1455,7 +1232,7 @@ namespace ImageCatalog_2 Debug.WriteLine("Yep c"); } - public async Task ProcessImages() + private async Task ProcessImages() { _logger.LogInformation("Avvio elaborazione..."); UiEnabled = false; @@ -1464,12 +1241,17 @@ namespace ImageCatalog_2 MainToken = new CancellationTokenSource(); var token = MainToken.Token; - // Normalize paths - _paths.NormalizePaths(); - + // Fix paths + FixPaths(); + // Reset counters - _processing.ResetForRun(); - + ProcessingStatus = "Elaborazione in corso..."; + TotalImagesCount = 0; + ProcessedImagesCount = 0; + SpeedCounter = "-f/s"; + ProgressBarValue = 0; + ProgressBarMaximum = 100; + // Update PicSettings from DataModel using AutoMapper _mapper.Map(this, _picSettings); // Explicitly ensure thumbnail-related flags are applied to PicSettings @@ -1490,8 +1272,8 @@ namespace ImageCatalog_2 { // Best-effort; do not fail processing on mapping issues } - - var imageCreationOptions = new ImageCreationService.Options + + var imageCreationOptions = new ImageCreationStuff.Options { AggiornaSottodirectory = UpdateSubdirectories, CreaSottocartelle = CreateSubfolders, @@ -1508,20 +1290,61 @@ namespace ImageCatalog_2 try { - var runResult = await _imageProcessingCoordinator.RunAsync( - new ImageProcessingRunRequest { Options = imageCreationOptions }, - token, - update => - { - ProcessedImagesCount = update.Processed; - TotalImagesCount = update.Total; - ProgressBarMaximum = update.Total; - ProgressBarValue = update.Processed; - ProcessingStatus = update.Status; - }, - speed => { SpeedCounter = speed; }).ConfigureAwait(false); + _results = new ConcurrentBag(); + _currentAmount = 0; + _previousAmount = 0; + _processedAtomic = 0; + + // Start speed timer (sample every second using lightweight atomic reads) + _speedWatch = Stopwatch.StartNew(); + _recentDiffs.Clear(); + _speedTimer = new System.Threading.Timer(UpdateSpeedCounter, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1)); - SpeedCounter = runResult.FinalSpeedCounter; + var time = await _imageCreationService.CreaCatalogoParallel( + imageCreationOptions, + _results, + OnImageProcessed, + token); + + // AI integration stub: if ExtractNumbers is enabled, simulate or invoke OCR processing + if (ExtractNumbers) + { + try + { + await RunAiExtractionAsync(token); + } + catch (OperationCanceledException) + { + _logger.LogInformation("AI extraction canceled"); + } + catch (Exception ex) + { + _logger.LogError(ex, "AI extraction failed"); + } + } + + // Compute final averages and show only averages (do not show raw seconds) + var finalProcessed = System.Threading.Volatile.Read(ref _processedAtomic); + double overallAvg = 0.0; + double overallPerMin = 0.0; + if (_speedWatch is not null && _speedWatch.Elapsed.TotalSeconds > 0.0) + { + overallAvg = finalProcessed / _speedWatch.Elapsed.TotalSeconds; + overallPerMin = overallAvg * 60.0; + } + + // Compute elapsed time as h m s and show final averages (no raw seconds parentheses) + var finalElapsed = _speedWatch?.Elapsed ?? TimeSpan.Zero; + int fh = (int)finalElapsed.TotalHours; + int fm = finalElapsed.Minutes; + int fs = finalElapsed.Seconds; + + SpeedCounter = $"{fh}h {fm}m {fs}s{Environment.NewLine}media: {overallAvg:0.00} f/s{Environment.NewLine}media: {overallPerMin:0.00} f/m"; + + _speedTimer?.Dispose(); + _speedTimer = null; + _speedWatch?.Stop(); + _speedWatch = null; } catch (OperationCanceledException) { @@ -1536,21 +1359,104 @@ namespace ImageCatalog_2 { MainToken?.Dispose(); MainToken = null; + _speedTimer?.Dispose(); + _speedTimer = null; } ProcessingStatus = "Finito"; UiEnabled = true; } - public async Task RunNumberAiAsync(CancellationToken token) + private void UpdateSpeedCounter(object? state) { - await RunAiExtractionCoreAsync(token, useDestination: true, recursive: true, failOnInvalidPath: true).ConfigureAwait(false); + try + { + _previousAmount = _currentAmount; + // Read the atomic counter without enumerating the ConcurrentBag + _currentAmount = System.Threading.Volatile.Read(ref _processedAtomic); + int diff = _currentAmount - _previousAmount; + + // Protect against negative or spurious diffs + if (diff < 0) diff = 0; + + // Maintain a small sliding window of recent diffs to smooth the display + lock (_recentDiffs) + { + _recentDiffs.Enqueue(diff); + if (_recentDiffs.Count > _recentWindowSize) + _recentDiffs.Dequeue(); + } + + double avgRecent; + lock (_recentDiffs) + { + avgRecent = _recentDiffs.Count == 0 ? 0.0 : _recentDiffs.Average(); + } + + // Compute overall average (since start) if we have a stopwatch + double overall = 0.0; + if (_speedWatch is not null && _speedWatch.Elapsed.TotalSeconds >= 1) + { + var elapsedSeconds = _speedWatch.Elapsed.TotalSeconds; + var total = System.Threading.Volatile.Read(ref _processedAtomic); + overall = elapsedSeconds > 0 ? total / elapsedSeconds : 0.0; + } + + // Recent per-minute estimate + var recentPerMin = avgRecent * 60.0; + var overallPerMin = overall * 60.0; + + // Build a two-line display plus elapsed time: first line shows f/s with overall media and elapsed time, + // second line shows recent photos per minute (media) + var elapsed = _speedWatch?.Elapsed ?? TimeSpan.Zero; + int hours = (int)elapsed.TotalHours; + int minutes = elapsed.Minutes; + int seconds = elapsed.Seconds; + var elapsedStr = $"{hours}h {minutes}m {seconds}s"; + + SpeedCounter = $"{avgRecent:0.00} f/s (media: {overall:0.00} f/s) - {elapsedStr}{Environment.NewLine}media: {recentPerMin:0.00} f/m"; + } + catch + { + // Swallow unlikely errors from timing/queue operations but keep UI responsive + } } - public async Task RunFaceAiAsync(CancellationToken token) + private void OnImageProcessed(object? sender, Tuple args) { - using var registration = token.Register(() => _ = StopFaceEncoderAsync("Arresto face encoder richiesto dalla CLI.", waitForExit: true)); - await RunFaceEncoderAsync().ConfigureAwait(false); + // Increment atomic processed counter once and use its value for all UI updates + var processed = System.Threading.Interlocked.Increment(ref _processedAtomic); + ProcessedImagesCount = processed; + TotalImagesCount = args.Item2; + ProgressBarMaximum = args.Item2; + ProgressBarValue = processed; + ProcessingStatus = args.Item1; + } + + private void FixPaths() + { + SourcePath = FixPath(SourcePath); + DestinationPath = FixPath(DestinationPath); + } + + private string FixPath(string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + return string.Empty; + } + + // Trim leading/trailing quotes + path = path.Trim().Trim('"'); + + // Normalize directory separators + path = path.Replace('/', System.IO.Path.DirectorySeparatorChar) + .Replace('\\', System.IO.Path.DirectorySeparatorChar); + + // Remove trailing separators then add one back + path = path.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar; + + return path; } private async Task CancelOperation() @@ -1581,2292 +1487,19 @@ namespace ImageCatalog_2 } } - public async Task StopFaceEncoderAsync(string reason, bool waitForExit = true) - { - var trackedProcess = GetTrackedFaceEncoderProcess(); - var ownsProcess = false; - var process = trackedProcess; - - if (process is null) - { - process = FindConfiguredFaceEncoderProcess(); - ownsProcess = process is not null; - } - - if (process is null) - { - await InvokeOnUiThreadAsync(() => - { - IsFaceEncoderRunning = false; - FaceStatusMessage = "Face encoder non in esecuzione."; - }).ConfigureAwait(false); - return; - } - - try - { - await InvokeOnUiThreadAsync(() => FaceStatusMessage = reason).ConfigureAwait(false); - - var gracefulStopRequested = TryRequestFaceEncoderStop(process); - if (waitForExit) - { - var exited = await WaitForProcessExitAsync(process, TimeSpan.FromSeconds(5)).ConfigureAwait(false); - if (!exited) - { - try - { - process.Kill(entireProcessTree: true); - exited = await WaitForProcessExitAsync(process, TimeSpan.FromSeconds(5)).ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Unable to terminate face encoder process {ProcessId}", process.Id); - } - } - - await InvokeOnUiThreadAsync(() => - { - IsFaceEncoderRunning = !exited && IsProcessAlive(process); - FaceStatusMessage = exited - ? "Face encoder arrestato." - : gracefulStopRequested - ? "Segnale di arresto inviato al face encoder." - : "Arresto forzato del face encoder richiesto."; - }).ConfigureAwait(false); - } - } - finally - { - if (ownsProcess) - { - process.Dispose(); - } - } - } - - private bool CanRunFaceEncoder() - { - return !IsFaceEncoderRunning; - } - - private bool CanStopFaceEncoder() - { - return IsFaceEncoderRunning; - } - - private void UpdateFaceEncoderCommandStates() - { - _startFaceEncoderCommand?.RaiseCanExecuteChanged(); - _stopFaceEncoderCommand?.RaiseCanExecuteChanged(); - } - - private void UpdateFaceUploadCommandStates() - { - _uploadFaceEncoderOutputCommand?.RaiseCanExecuteChanged(); - } - - private void UpdateFaceMatcherCommandStates() - { - _startFaceMatcherCommand?.RaiseCanExecuteChanged(); - _stopFaceMatcherCommand?.RaiseCanExecuteChanged(); - } - - private async Task RunFaceEncoderAsync() - { - if (IsFaceEncoderRunning) - { - FaceStatusMessage = "Face encoder gia in esecuzione."; - return; - } - - var executableRootPath = NormalizeFilePathArgument(FaceExecutablePath); - var outputFolderPath = NormalizeDirectoryPathArgument(FaceOutputFolderPath); - var imagesFolder = NormalizeDirectoryPathArgument(DestinationPath); - var executablePath = ResolveConfiguredFaceEncoderExecutablePath(executableRootPath, UseFaceGpu); - - if (string.IsNullOrWhiteSpace(executableRootPath)) - { - FaceStatusMessage = "Percorso cartella face encoder non valido."; - return; - } - - if (string.IsNullOrWhiteSpace(executablePath) || !File.Exists(executablePath)) - { - FaceStatusMessage = UseFaceGpu - ? "Impossibile trovare face_encoder_gpu.exe nella cartella selezionata." - : "Impossibile trovare face_encoder_cpu.exe nella cartella selezionata."; - return; - } - - if (string.IsNullOrWhiteSpace(imagesFolder) || !Directory.Exists(imagesFolder)) - { - FaceStatusMessage = "Cartella Destinazione non valida."; - return; - } - - if (string.IsNullOrWhiteSpace(outputFolderPath)) - { - FaceStatusMessage = "Inserisci la cartella di output per encodings e log."; - return; - } - - try - { - Directory.CreateDirectory(outputFolderPath); - } - catch (Exception ex) - { - _logger.LogError(ex, "Unable to create face output directory: {OutputFolderPath}", outputFolderPath); - FaceStatusMessage = "Impossibile creare la cartella di output."; - return; - } - - var parallelism = NormalizeFaceParallelism(FaceParallelism); - var minSize = NormalizeFaceMinSize(FaceMinSize); - var outputFiles = BuildFaceEncoderOutputPaths(outputFolderPath, imagesFolder, DateTime.Now); - _lastFaceEncoderOutputFilePath = outputFiles.OutputFilePath; - - FaceExecutablePath = executableRootPath; - FaceOutputFolderPath = outputFolderPath; - FaceCommandOutput = string.Empty; - FaceStatusMessage = "Esecuzione face encoder in corso..."; - - var transcriptLines = new StringBuilder(); - var outputLines = new StringBuilder(); - var errorLines = new StringBuilder(); - - try - { - var processStartInfo = new ProcessStartInfo - { - FileName = executablePath, - WorkingDirectory = Path.GetDirectoryName(executablePath) ?? Environment.CurrentDirectory, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true, - RedirectStandardInput = false, - CreateNoWindow = false, - }; - - processStartInfo.ArgumentList.Add("--images"); - processStartInfo.ArgumentList.Add(imagesFolder); - processStartInfo.ArgumentList.Add("--out"); - processStartInfo.ArgumentList.Add(outputFiles.OutputFilePath); - processStartInfo.ArgumentList.Add("--log"); - processStartInfo.ArgumentList.Add(outputFiles.LogFilePath); - - if (FaceRecursive) - { - processStartInfo.ArgumentList.Add("--recursive"); - } - - if (FaceIncludeThumbnails) - { - processStartInfo.ArgumentList.Add("--include-tn"); - } - - processStartInfo.ArgumentList.Add(UseFaceGpu ? "--multiprocess" : "--multicore"); - processStartInfo.ArgumentList.Add(parallelism.ToString()); - processStartInfo.ArgumentList.Add("--min-size"); - processStartInfo.ArgumentList.Add(minSize.ToString()); - - if (FaceUpsample) - { - processStartInfo.ArgumentList.Add("--upsample"); - } - - using var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; - process.OutputDataReceived += (_, args) => AppendFaceProcessOutput(outputLines, transcriptLines, args.Data, isError: false); - process.ErrorDataReceived += (_, args) => AppendFaceProcessOutput(errorLines, transcriptLines, args.Data, isError: true); - process.Exited += (_, _) => - { - _ = InvokeOnUiThreadAsync(() => - { - if (!ComputeIsFaceEncoderRunning()) - { - IsFaceEncoderRunning = false; - } - }); - }; - - if (!process.Start()) - { - throw new InvalidOperationException("Avvio face encoder fallito."); - } - - _hasStartedFaceEncoderInSession = true; - EnsureFaceEncoderWatcherStarted(); - TrackFaceEncoderProcess(process); - await InvokeOnUiThreadAsync(() => IsFaceEncoderRunning = true).ConfigureAwait(false); - - if (UseFaceGpu) - { - StartFaceEncoderLogWatcher(outputFiles.LogFilePath, outputLines, transcriptLines); - } - - process.BeginOutputReadLine(); - process.BeginErrorReadLine(); - await process.WaitForExitAsync().ConfigureAwait(false); - - var summary = BuildFaceEncoderSummary(process.ExitCode, processStartInfo, outputFiles.OutputFilePath, outputFiles.LogFilePath, outputLines, errorLines); - await InvokeOnUiThreadAsync(() => - { - FaceCommandOutput = string.IsNullOrWhiteSpace(FaceCommandOutput) - ? summary - : $"{FaceCommandOutput.TrimEnd()}\n\n{summary}"; - FaceStatusMessage = process.ExitCode == 0 - ? "Face encoder completato." - : $"Face encoder terminato con errore (code {process.ExitCode})."; - }).ConfigureAwait(false); - } - catch (Exception ex) - { - Console.Error.WriteLine(ex); - _logger.LogError(ex, "Face encoder execution failed."); - await InvokeOnUiThreadAsync(() => - { - FaceCommandOutput = ex.ToString(); - FaceStatusMessage = "Errore durante esecuzione face encoder."; - }).ConfigureAwait(false); - } - finally - { - await StopFaceEncoderLogWatcherAsync().ConfigureAwait(false); - ClearTrackedFaceEncoderProcess(); - await InvokeOnUiThreadAsync(() => IsFaceEncoderRunning = ComputeIsFaceEncoderRunning()).ConfigureAwait(false); - } - } - - private bool CanRunFaceMatcher() - { - return !IsFaceMatcherRunning; - } - - private bool CanUploadFaceEncoderOutput() - { - return IsFaceUploadPathValid && !IsFaceUploadRunning; - } - - private async Task UploadFaceEncoderOutputAsync() - { - if (!IsValidFaceUploadPath(FaceUploadPath)) - { - FaceStatusMessage = "Percorso upload non valido."; - return; - } - - if (!TryBuildFaceUploadRequest(out var request, out var validationMessage)) - { - FaceStatusMessage = validationMessage; - await ShowErrorMessageAsync("Upload Face AI", validationMessage).ConfigureAwait(false); - return; - } - - IsFaceUploadRunning = true; - UpdateFaceUploadCommandStates(); - FaceStatusMessage = "Upload face encoder in corso..."; - - try - { - if (FaceUploadDryRun) - { - var preview = BuildFaceUploadDryRunPreview(request); - await ShowMessageAsync("Upload Face AI (dry run)", preview).ConfigureAwait(false); - await InvokeOnUiThreadAsync(() => FaceStatusMessage = "Dry run: comando mostrato nel popup.").ConfigureAwait(false); - return; - } - - var result = await RunFaceUploadPowerShellAsync(request).ConfigureAwait(false); - await InvokeOnUiThreadAsync(() => - { - FaceCommandOutput = string.IsNullOrWhiteSpace(FaceCommandOutput) - ? result - : $"{FaceCommandOutput.TrimEnd()}\n\n{result}"; - FaceStatusMessage = "Upload completato."; - }).ConfigureAwait(false); - } - catch (Exception ex) - { - var message = ex.GetBaseException().Message; - _logger.LogError(ex, "Face encoder upload failed."); - await InvokeOnUiThreadAsync(() => FaceStatusMessage = "Errore durante upload face encoder.").ConfigureAwait(false); - await ShowErrorMessageAsync("Upload Face AI", message).ConfigureAwait(false); - } - finally - { - await InvokeOnUiThreadAsync(() => - { - IsFaceUploadRunning = false; - UpdateFaceUploadCommandStates(); - }).ConfigureAwait(false); - } - } - - private bool CanStopFaceMatcher() - { - return IsFaceMatcherRunning; - } - - private async Task RunFaceMatcherAsync() - { - if (IsFaceMatcherRunning) - { - FaceMatcherStatusMessage = "Face matcher gia in esecuzione."; - return; - } - - var executablePath = ResolveConfiguredFaceMatcherExecutablePath(NormalizeFilePathArgument(FaceMatcherExecutablePath), NormalizeFilePathArgument(FaceExecutablePath)); - if (string.IsNullOrWhiteSpace(executablePath) || !File.Exists(executablePath)) - { - FaceMatcherStatusMessage = "Percorso face_matcher.exe non valido."; - return; - } - - var searchImagePath = NormalizeFilePathArgument(FaceMatcherSelectedImagePath); - if (string.IsNullOrWhiteSpace(searchImagePath) || !File.Exists(searchImagePath)) - { - FaceMatcherStatusMessage = "Seleziona un'immagine valida per il match."; - return; - } - - var encodingsPath = ResolveConfiguredFaceMatcherEncodingsPath(NormalizeFilePathArgument(FaceMatcherEncodingsPath), NormalizeDirectoryPathArgument(FaceOutputFolderPath)); - if (string.IsNullOrWhiteSpace(encodingsPath) || !File.Exists(encodingsPath)) - { - FaceMatcherStatusMessage = "File encodings .pkl non trovato."; - return; - } - - var fallbackOutputRoot = ResolveFaceMatcherFallbackOutputRoot(NormalizeFilePathArgument(FaceMatcherOutputPath), NormalizeFilePathArgument(FaceMatcherLogPath), NormalizeDirectoryPathArgument(FaceOutputFolderPath), executablePath); - var outputPaths = ResolveFaceMatcherOutputPaths(FaceMatcherOutputPath, FaceMatcherLogPath, fallbackOutputRoot, searchImagePath, DateTime.Now); - - try - { - Directory.CreateDirectory(Path.GetDirectoryName(outputPaths.CsvPath) ?? fallbackOutputRoot); - Directory.CreateDirectory(Path.GetDirectoryName(outputPaths.LogPath) ?? fallbackOutputRoot); - } - catch (Exception ex) - { - _logger.LogError(ex, "Unable to create face matcher output directory."); - FaceMatcherStatusMessage = "Impossibile creare cartelle output/log del matcher."; - return; - } - - var tolerance = NormalizeFaceMatcherTolerance(FaceMatcherTolerance); - FaceMatcherExecutablePath = executablePath; - FaceMatcherEncodingsPath = encodingsPath; - FaceMatcherOutputPath = outputPaths.CsvPath; - FaceMatcherLogPath = outputPaths.LogPath; - - await InvokeOnUiThreadAsync(() => - { - FaceMatcherResults.Clear(); - FaceMatcherCommandOutput = string.Empty; - FaceMatcherStatusMessage = "Esecuzione face matcher in corso..."; - }).ConfigureAwait(false); - - var transcriptLines = new StringBuilder(); - var outputLines = new StringBuilder(); - var errorLines = new StringBuilder(); - - try - { - var processStartInfo = new ProcessStartInfo - { - FileName = executablePath, - WorkingDirectory = Path.GetDirectoryName(executablePath) ?? Environment.CurrentDirectory, - UseShellExecute = false, - RedirectStandardOutput = false, - RedirectStandardError = false, - RedirectStandardInput = false, - CreateNoWindow = true, - }; - - processStartInfo.Environment["PYTHONUTF8"] = "1"; - processStartInfo.Environment["PYTHONIOENCODING"] = "utf-8"; - - processStartInfo.ArgumentList.Add("--image"); - processStartInfo.ArgumentList.Add(searchImagePath); - processStartInfo.ArgumentList.Add("--encodings"); - processStartInfo.ArgumentList.Add(encodingsPath); - processStartInfo.ArgumentList.Add("--out"); - processStartInfo.ArgumentList.Add(outputPaths.CsvPath); - processStartInfo.ArgumentList.Add("--log"); - processStartInfo.ArgumentList.Add(outputPaths.LogPath); - processStartInfo.ArgumentList.Add("--tolerance"); - processStartInfo.ArgumentList.Add(tolerance.ToString("0.##", CultureInfo.InvariantCulture)); - - using var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; - process.Exited += (_, _) => - { - _ = InvokeOnUiThreadAsync(() => - { - if (!ComputeIsFaceMatcherRunning()) - { - IsFaceMatcherRunning = false; - } - }); - }; - - if (!process.Start()) - { - throw new InvalidOperationException("Avvio face matcher fallito."); - } - - _hasStartedFaceMatcherInSession = true; - EnsureFaceMatcherWatcherStarted(); - TrackFaceMatcherProcess(process); - await InvokeOnUiThreadAsync(() => IsFaceMatcherRunning = true).ConfigureAwait(false); - - StartFaceMatcherLogWatcher(outputPaths.LogPath, outputLines, transcriptLines); - await process.WaitForExitAsync().ConfigureAwait(false); - - var isNoFacesRun = process.ExitCode == 1 && await LogIndicatesNoFacesAsync(outputPaths.LogPath).ConfigureAwait(false); - if (process.ExitCode == 0 || isNoFacesRun) - { - var parsedRows = await ParseFaceMatcherCsvAsync(outputPaths.CsvPath, outputPaths.LogPath).ConfigureAwait(false); - var resolvedPaths = ResolveDestinationImagesByFileName(DestinationPath, parsedRows.Select(row => row.PhotoId)); - await InvokeOnUiThreadAsync(() => - { - FaceMatcherResults.Clear(); - foreach (var row in parsedRows) - { - resolvedPaths.TryGetValue(row.PhotoId, out var candidates); - candidates ??= []; - - FaceMatcherResults.Add(new FaceMatcherResultItem - { - PhotoId = row.PhotoId, - Score = row.Score, - ResolvedImagePath = candidates.FirstOrDefault() ?? string.Empty, - CandidateCount = candidates.Count, - RawRow = row.RawRow, - DebugSummary = row.DebugSummary, - SearchImagePath = searchImagePath, - CsvPath = outputPaths.CsvPath, - LogPath = outputPaths.LogPath - }); - } - }).ConfigureAwait(false); - } - - var summary = BuildFaceMatcherSummary(process.ExitCode, processStartInfo, outputPaths.CsvPath, outputPaths.LogPath, outputLines, errorLines, FaceMatcherResults.Count); - await InvokeOnUiThreadAsync(() => - { - FaceMatcherCommandOutput = string.IsNullOrWhiteSpace(FaceMatcherCommandOutput) - ? summary - : $"{FaceMatcherCommandOutput.TrimEnd()}\n\n{summary}"; - FaceMatcherStatusMessage = process.ExitCode switch - { - 0 when FaceMatcherResults.Count > 0 => $"Face matcher completato: {FaceMatcherResults.Count} match.", - 0 => "Face matcher completato senza match.", - 1 when isNoFacesRun => "Face matcher completato: nessun volto rilevato nell'immagine di ricerca.", - _ => $"Face matcher terminato con errore (code {process.ExitCode})." - }; - }).ConfigureAwait(false); - } - catch (Exception ex) - { - Console.Error.WriteLine(ex); - _logger.LogError(ex, "Face matcher execution failed."); - await InvokeOnUiThreadAsync(() => - { - FaceMatcherCommandOutput = ex.ToString(); - FaceMatcherStatusMessage = "Errore durante esecuzione face matcher."; - }).ConfigureAwait(false); - } - finally - { - await StopFaceMatcherLogWatcherAsync().ConfigureAwait(false); - ClearTrackedFaceMatcherProcess(); - await InvokeOnUiThreadAsync(() => IsFaceMatcherRunning = ComputeIsFaceMatcherRunning()).ConfigureAwait(false); - } - } - - public async Task StopFaceMatcherAsync(string reason, bool waitForExit = true) - { - var trackedProcess = GetTrackedFaceMatcherProcess(); - Process? process = null; - - if (trackedProcess is not null) - { - process = trackedProcess; - } - else if (_hasStartedFaceMatcherInSession) - { - process = FindConfiguredFaceMatcherProcess(); - } - - if (process is null) - { - await StopFaceMatcherLogWatcherAsync().ConfigureAwait(false); - await InvokeOnUiThreadAsync(() => - { - IsFaceMatcherRunning = false; - FaceMatcherStatusMessage = "Face matcher non in esecuzione."; - }).ConfigureAwait(false); - return; - } - - using (process) - { - var gracefulStopRequested = TryRequestFaceMatcherStop(process); - var exited = !IsProcessAlive(process); - - if (!exited && waitForExit) - { - exited = await WaitForProcessExitAsync(process, TimeSpan.FromSeconds(5)).ConfigureAwait(false); - } - - if (!exited) - { - try - { - process.Kill(entireProcessTree: true); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Unable to terminate face matcher process {ProcessId}", process.Id); - } - } - - await StopFaceMatcherLogWatcherAsync().ConfigureAwait(false); - ClearTrackedFaceMatcherProcess(); - await InvokeOnUiThreadAsync(() => - { - IsFaceMatcherRunning = !exited && IsProcessAlive(process); - FaceMatcherStatusMessage = exited - ? "Face matcher arrestato." - : gracefulStopRequested - ? "Segnale di arresto inviato al face matcher." - : "Arresto forzato del face matcher richiesto."; - }).ConfigureAwait(false); - } - } - - private async Task WatchFaceEncoderProcessAsync(CancellationToken token) - { - using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)); - - try - { - while (await timer.WaitForNextTickAsync(token).ConfigureAwait(false)) - { - if (!_hasStartedFaceEncoderInSession) - { - continue; - } - - var isRunning = ComputeIsFaceEncoderRunning(); - if (isRunning != IsFaceEncoderRunning) - { - await InvokeOnUiThreadAsync(() => IsFaceEncoderRunning = isRunning).ConfigureAwait(false); - } - } - } - catch (OperationCanceledException) - { - // App shutdown. - } - } - - private async Task WatchFaceMatcherProcessAsync(CancellationToken token) - { - using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1)); - - try - { - while (await timer.WaitForNextTickAsync(token).ConfigureAwait(false)) - { - if (!_hasStartedFaceMatcherInSession) - { - continue; - } - - var isRunning = ComputeIsFaceMatcherRunning(); - if (isRunning != IsFaceMatcherRunning) - { - await InvokeOnUiThreadAsync(() => IsFaceMatcherRunning = isRunning).ConfigureAwait(false); - } - } - } - catch (OperationCanceledException) - { - // App shutdown. - } - } - - private void EnsureFaceEncoderWatcherStarted() - { - if (_faceEncoderWatcherTask is not null) - { - return; - } - - _faceEncoderWatcherTokenSource = new CancellationTokenSource(); - _faceEncoderWatcherTask = WatchFaceEncoderProcessAsync(_faceEncoderWatcherTokenSource.Token); - } - - private void EnsureFaceMatcherWatcherStarted() - { - if (_faceMatcherWatcherTask is not null) - { - return; - } - - _faceMatcherWatcherTokenSource = new CancellationTokenSource(); - _faceMatcherWatcherTask = WatchFaceMatcherProcessAsync(_faceMatcherWatcherTokenSource.Token); - } - - private void StartFaceEncoderLogWatcher(string logFilePath, StringBuilder outputLines, StringBuilder transcriptLines) - { - _faceEncoderLogWatcherTokenSource?.Cancel(); - _faceEncoderLogWatcherTokenSource?.Dispose(); - - _faceEncoderLogWatcherTokenSource = new CancellationTokenSource(); - _faceEncoderLogWatcherTask = WatchFaceEncoderLogFileAsync(logFilePath, outputLines, transcriptLines, _faceEncoderLogWatcherTokenSource.Token); - } - - private void StartFaceMatcherLogWatcher(string logFilePath, StringBuilder outputLines, StringBuilder transcriptLines) - { - _faceMatcherLogWatcherTokenSource?.Cancel(); - _faceMatcherLogWatcherTokenSource?.Dispose(); - - _faceMatcherLogWatcherTokenSource = new CancellationTokenSource(); - _faceMatcherLogWatcherTask = WatchFaceMatcherLogFileAsync(logFilePath, outputLines, transcriptLines, _faceMatcherLogWatcherTokenSource.Token); - } - - private async Task StopFaceEncoderLogWatcherAsync() - { - var tokenSource = _faceEncoderLogWatcherTokenSource; - var task = _faceEncoderLogWatcherTask; - - _faceEncoderLogWatcherTokenSource = null; - _faceEncoderLogWatcherTask = null; - - if (tokenSource is null) - { - return; - } - - try - { - await tokenSource.CancelAsync().ConfigureAwait(false); - if (task is not null) - { - await task.ConfigureAwait(false); - } - } - catch (OperationCanceledException) - { - // Expected when shutting down the watcher. - } - finally - { - tokenSource.Dispose(); - } - } - - private async Task StopFaceMatcherLogWatcherAsync() - { - var tokenSource = _faceMatcherLogWatcherTokenSource; - var task = _faceMatcherLogWatcherTask; - - _faceMatcherLogWatcherTokenSource = null; - _faceMatcherLogWatcherTask = null; - - if (tokenSource is null) - { - return; - } - - try - { - await tokenSource.CancelAsync().ConfigureAwait(false); - if (task is not null) - { - await task.ConfigureAwait(false); - } - } - catch (OperationCanceledException) - { - // Expected when shutting down the watcher. - } - finally - { - tokenSource.Dispose(); - } - } - - private async Task WatchFaceEncoderLogFileAsync(string logFilePath, StringBuilder outputLines, StringBuilder transcriptLines, CancellationToken token) - { - long filePosition = 0; - - while (!token.IsCancellationRequested) - { - try - { - if (File.Exists(logFilePath)) - { - using var stream = new FileStream(logFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - if (filePosition > stream.Length) - { - filePosition = 0; - } - - stream.Seek(filePosition, SeekOrigin.Begin); - using var reader = new StreamReader(stream); - while (!reader.EndOfStream) - { - var line = await reader.ReadLineAsync(token).ConfigureAwait(false); - AppendFaceProcessOutput(outputLines, transcriptLines, line, isError: false); - } - - filePosition = stream.Position; - } - } - catch (OperationCanceledException) - { - throw; - } - catch (IOException) - { - // Retry on the next polling interval while the encoder is still writing. - } - catch (UnauthorizedAccessException) - { - // Retry on the next polling interval if the log file is transiently locked. - } - - await Task.Delay(TimeSpan.FromMilliseconds(250), token).ConfigureAwait(false); - } - } - - private async Task WatchFaceMatcherLogFileAsync(string logFilePath, StringBuilder outputLines, StringBuilder transcriptLines, CancellationToken token) - { - long filePosition = 0; - - while (!token.IsCancellationRequested) - { - try - { - if (File.Exists(logFilePath)) - { - using var stream = new FileStream(logFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - if (filePosition > stream.Length) - { - filePosition = 0; - } - - stream.Seek(filePosition, SeekOrigin.Begin); - using var reader = new StreamReader(stream); - while (!reader.EndOfStream) - { - var line = await reader.ReadLineAsync(token).ConfigureAwait(false); - AppendFaceMatcherProcessOutput(outputLines, transcriptLines, line, isError: false); - } - - filePosition = stream.Position; - } - } - catch (OperationCanceledException) - { - throw; - } - catch (IOException) - { - // Retry while the matcher is still writing. - } - catch (UnauthorizedAccessException) - { - // Retry if the file is transiently locked. - } - - await Task.Delay(TimeSpan.FromMilliseconds(250), token).ConfigureAwait(false); - } - } - - private void RefreshFaceExecutableCapabilities() - { - var executableRoot = NormalizeFilePathArgument(_ai.FaceExecutablePath); - var hasCpu = !string.IsNullOrWhiteSpace(ResolveConfiguredFaceEncoderExecutablePath(executableRoot, useGpu: false)); - var hasGpu = !string.IsNullOrWhiteSpace(ResolveConfiguredFaceEncoderExecutablePath(executableRoot, useGpu: true)); - - _ai.FaceGpuOptionEnabled = hasCpu && hasGpu; - - if (hasGpu && !hasCpu) - { - _ai.UseFaceGpu = true; - } - else if (!hasGpu) - { - _ai.UseFaceGpu = false; - } - } - - private void QueueRefreshNumberAiGpuCapabilities() - { - if (!TryBuildNumberAiModelConfiguration(out var configuration)) - { - _numberAiGpuValidationPending = false; - NumberAiGpuOptionEnabled = false; - _ai.UseNumberAiGpu = false; - return; - } - - _numberAiGpuValidationPending = true; - var requestVersion = Interlocked.Increment(ref _numberAiGpuRefreshVersion); - _ = RefreshNumberAiGpuCapabilitiesAsync(configuration, requestVersion); - } - - private async Task RefreshNumberAiGpuCapabilitiesAsync(ModelConfiguration configuration, int requestVersion) - { - try - { - var gpuAvailable = await Task.Run(() => - NumberRecognitionEngine.TryValidateGpuRuntime(configuration, _logger, out _)).ConfigureAwait(false); - - if (requestVersion != Volatile.Read(ref _numberAiGpuRefreshVersion)) - { - return; - } - - await InvokeOnUiThreadAsync(() => - { - if (requestVersion != Volatile.Read(ref _numberAiGpuRefreshVersion)) - { - return; - } - - _numberAiGpuValidationPending = false; - NumberAiGpuOptionEnabled = gpuAvailable; - if (!gpuAvailable) - { - _ai.UseNumberAiGpu = false; - } - }).ConfigureAwait(false); - } - catch (Exception ex) - { - if (requestVersion != Volatile.Read(ref _numberAiGpuRefreshVersion)) - { - return; - } - - _logger.LogWarning(ex, "Failed to refresh OCR GPU capabilities."); - - await InvokeOnUiThreadAsync(() => - { - if (requestVersion != Volatile.Read(ref _numberAiGpuRefreshVersion)) - { - return; - } - - _numberAiGpuValidationPending = false; - NumberAiGpuOptionEnabled = false; - _ai.UseNumberAiGpu = false; - }).ConfigureAwait(false); - } - } - - private void SetUseNumberAiGpu(bool value) - { - if (!value) - { - _ai.UseNumberAiGpu = false; - return; - } - - if (NumberAiGpuOptionEnabled || _numberAiGpuValidationPending) - { - _ai.UseNumberAiGpu = true; - return; - } - - _ai.UseNumberAiGpu = false; - } - - private bool TryBuildNumberAiModelConfiguration(out ModelConfiguration configuration) - { - configuration = null!; - - if (string.IsNullOrWhiteSpace(ModelsFolderPath)) - { - return false; - } - - var modelsRoot = Path.GetFullPath(ModelsFolderPath.Trim().Trim('"')); - if (!Directory.Exists(modelsRoot)) - { - return false; - } - - configuration = new ModelConfiguration - { - DetectionCfg = Path.Combine(modelsRoot, "detection.cfg"), - DetectionWeights = Path.Combine(modelsRoot, "detection.weights"), - RecognitionCfg = Path.Combine(modelsRoot, "recognition.cfg"), - RecognitionWeights = Path.Combine(modelsRoot, "recognition.weights"), - UseGpu = true - }; - - return File.Exists(configuration.DetectionCfg) - && File.Exists(configuration.DetectionWeights) - && File.Exists(configuration.RecognitionCfg) - && File.Exists(configuration.RecognitionWeights); - } - - private Task ShowMessageAsync(string title, string message) - { - return InvokeOnUiThreadAsync(() => - { - ShowMessageRequested?.Invoke(this, Tuple.Create(title, message, 0)); - }); - } - - private Task ShowErrorMessageAsync(string title, string message) - { - return ShowMessageAsync(title, message); - } - - internal async Task ConfirmAiCsvOverwriteIfNeededAsync() - { - var csvOutputPath = NormalizeFilePathArgument(CsvOutputPath); - if (string.IsNullOrWhiteSpace(csvOutputPath) || !File.Exists(csvOutputPath)) - { - return true; - } - - var confirmOverwrite = ConfirmAiCsvOverwriteAsync; - if (confirmOverwrite is null) - { - return true; - } - - var message = $"Il file CSV esiste gia:\n{csvOutputPath}\n\nVuoi sovrascriverlo? Se scegli Annulla l'operazione OCR non verra avviata."; - return await confirmOverwrite(AiCsvOverwriteDialogTitle, message).ConfigureAwait(false); - } - - internal void UpdateAiCsvOutputPathForDestination() - { - var updatedPath = BuildAiCsvOutputPathForDestination(CsvOutputPath, DestinationPath); - if (string.Equals(updatedPath, CsvOutputPath, StringComparison.Ordinal)) - { - return; - } - - CsvOutputPath = updatedPath; - } - - internal static string BuildAiCsvOutputPathForDestination(string currentCsvOutputPath, string destinationPath) - { - var normalizedCsvPath = NormalizeFilePathArgument(currentCsvOutputPath); - if (string.IsNullOrWhiteSpace(normalizedCsvPath)) - { - return currentCsvOutputPath; - } - - var directory = Path.GetDirectoryName(normalizedCsvPath); - var destinationFolderName = GetDestinationFolderName(destinationPath); - if (string.IsNullOrWhiteSpace(destinationFolderName)) - { - return normalizedCsvPath; - } - - var extension = Path.GetExtension(normalizedCsvPath); - if (string.IsNullOrWhiteSpace(extension)) - { - extension = ".csv"; - } - - var safeFileName = SanitizeFileName(destinationFolderName) + extension; - return string.IsNullOrWhiteSpace(directory) - ? safeFileName - : Path.Combine(directory, safeFileName); - } - - private static string GetDestinationFolderName(string destinationPath) - { - var normalizedDestinationPath = NormalizeDirectoryPathArgument(destinationPath); - if (string.IsNullOrWhiteSpace(normalizedDestinationPath)) - { - return string.Empty; - } - - var trimmedPath = normalizedDestinationPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - if (string.IsNullOrWhiteSpace(trimmedPath)) - { - return string.Empty; - } - - var rootPath = Path.GetPathRoot(trimmedPath)?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - if (!string.IsNullOrWhiteSpace(rootPath) - && string.Equals(trimmedPath, rootPath, StringComparison.OrdinalIgnoreCase)) - { - return string.Empty; - } - - return Path.GetFileName(trimmedPath); - } - - private static string SanitizeFileName(string value) - { - if (string.IsNullOrWhiteSpace(value)) - { - return string.Empty; - } - - var invalidFileNameChars = Path.GetInvalidFileNameChars(); - var builder = new StringBuilder(value.Length); - foreach (var character in value) - { - builder.Append(Array.IndexOf(invalidFileNameChars, character) >= 0 ? '_' : character); - } - - return builder.ToString(); - } - - private void SetUseFaceGpu(bool value) - { - var currentValue = _ai.UseFaceGpu; - if (!FaceGpuOptionEnabled) - { - return; - } - - if (currentValue == value) - { - return; - } - - _ai.UseFaceGpu = value; - - var previousRecommendedUpsample = GetRecommendedFaceUpsample(currentValue); - if (_ai.FaceUpsample == previousRecommendedUpsample) - { - _ai.FaceUpsample = GetRecommendedFaceUpsample(value); - } - } - - private void TrackFaceEncoderProcess(Process process) - { - lock (_faceEncoderProcessLock) - { - _faceEncoderProcess = process; - } - } - - private void TrackFaceMatcherProcess(Process process) - { - lock (_faceMatcherProcessLock) - { - _faceMatcherProcess = process; - } - } - - private void ClearTrackedFaceEncoderProcess() - { - lock (_faceEncoderProcessLock) - { - if (_faceEncoderProcess is not null && _faceEncoderProcess.HasExited) - { - _faceEncoderProcess = null; - return; - } - - _faceEncoderProcess = null; - } - } - - private void ClearTrackedFaceMatcherProcess() - { - lock (_faceMatcherProcessLock) - { - if (_faceMatcherProcess is not null && _faceMatcherProcess.HasExited) - { - _faceMatcherProcess = null; - return; - } - - _faceMatcherProcess = null; - } - } - - private Process? GetTrackedFaceEncoderProcess() - { - lock (_faceEncoderProcessLock) - { - if (_faceEncoderProcess is null) - { - return null; - } - - if (_faceEncoderProcess.HasExited) - { - _faceEncoderProcess = null; - return null; - } - - return _faceEncoderProcess; - } - } - - private Process? GetTrackedFaceMatcherProcess() - { - lock (_faceMatcherProcessLock) - { - if (_faceMatcherProcess is null) - { - return null; - } - - if (_faceMatcherProcess.HasExited) - { - _faceMatcherProcess = null; - return null; - } - - return _faceMatcherProcess; - } - } - - private Process? FindConfiguredFaceEncoderProcess() - { - var configuredExecutablePath = ResolveConfiguredFaceEncoderExecutablePath(FaceExecutablePath, UseFaceGpu); - if (string.IsNullOrWhiteSpace(configuredExecutablePath)) - { - return null; - } - - var processName = Path.GetFileNameWithoutExtension(configuredExecutablePath); - foreach (var process in Process.GetProcessesByName(processName)) - { - if (!IsProcessAlive(process)) - { - process.Dispose(); - continue; - } - - if (IsMatchingProcessPath(process, configuredExecutablePath)) - { - return process; - } - - process.Dispose(); - } - - return null; - } - - private Process? FindConfiguredFaceMatcherProcess() - { - var configuredExecutablePath = ResolveConfiguredFaceMatcherExecutablePath(FaceMatcherExecutablePath, FaceExecutablePath); - if (string.IsNullOrWhiteSpace(configuredExecutablePath)) - { - return null; - } - - var processName = Path.GetFileNameWithoutExtension(configuredExecutablePath); - foreach (var process in Process.GetProcessesByName(processName)) - { - if (!IsProcessAlive(process)) - { - process.Dispose(); - continue; - } - - if (IsMatchingProcessPath(process, configuredExecutablePath)) - { - return process; - } - - process.Dispose(); - } - - return null; - } - - private bool ComputeIsFaceEncoderRunning() - { - var trackedProcess = GetTrackedFaceEncoderProcess(); - if (trackedProcess is not null) - { - return true; - } - - if (!_hasStartedFaceEncoderInSession) - { - return false; - } - - using var discoveredProcess = FindConfiguredFaceEncoderProcess(); - return discoveredProcess is not null; - } - - private bool ComputeIsFaceMatcherRunning() - { - var trackedProcess = GetTrackedFaceMatcherProcess(); - if (trackedProcess is not null) - { - return true; - } - - if (!_hasStartedFaceMatcherInSession) - { - return false; - } - - using var discoveredProcess = FindConfiguredFaceMatcherProcess(); - return discoveredProcess is not null; - } - - private static bool IsProcessAlive(Process process) - { - try - { - return !process.HasExited; - } - catch - { - return false; - } - } - - private static bool IsMatchingProcessPath(Process process, string configuredExecutablePath) - { - try - { - var processPath = process.MainModule?.FileName; - return !string.IsNullOrWhiteSpace(processPath) - && string.Equals(Path.GetFullPath(processPath), Path.GetFullPath(configuredExecutablePath), StringComparison.OrdinalIgnoreCase); - } - catch - { - return false; - } - } - - private bool TryRequestFaceEncoderStop(Process process) - { - if (!IsProcessAlive(process)) - { - return true; - } - -#if WINDOWS - if (Program.TrySendConsoleInterrupt(process.Id)) - { - return true; - } -#endif - - try - { - return process.CloseMainWindow(); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Unable to request graceful stop for face encoder process {ProcessId}", process.Id); - return false; - } - } - - private bool TryRequestFaceMatcherStop(Process process) - { - if (!IsProcessAlive(process)) - { - return true; - } - -#if WINDOWS - if (Program.TrySendConsoleInterrupt(process.Id)) - { - return true; - } -#endif - - try - { - return process.CloseMainWindow(); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Unable to request graceful stop for face matcher process {ProcessId}", process.Id); - return false; - } - } - - private static async Task WaitForProcessExitAsync(Process process, TimeSpan timeout) - { - if (!IsProcessAlive(process)) - { - return true; - } - - using var cancellationTokenSource = new CancellationTokenSource(timeout); - try - { - await process.WaitForExitAsync(cancellationTokenSource.Token).ConfigureAwait(false); - return true; - } - catch (OperationCanceledException) - { - return !IsProcessAlive(process); - } - } - - private void AppendFaceProcessOutput(StringBuilder builder, StringBuilder transcriptBuilder, string? line, bool isError) - { - if (string.IsNullOrWhiteSpace(line)) - { - return; - } - - lock (builder) - { - builder.AppendLine(line); - } - - if (isError) - { - Console.Error.WriteLine(line); - } - else - { - Console.WriteLine(line); - } - - string transcript; - lock (transcriptBuilder) - { - if (isError) - { - transcriptBuilder.Append("[stderr] "); - } - - transcriptBuilder.AppendLine(line); - transcript = transcriptBuilder.ToString(); - } - - _ = InvokeOnUiThreadAsync(() => FaceCommandOutput = transcript); - } - - private void AppendFaceMatcherProcessOutput(StringBuilder builder, StringBuilder transcriptBuilder, string? line, bool isError) - { - if (string.IsNullOrWhiteSpace(line)) - { - return; - } - - lock (builder) - { - builder.AppendLine(line); - } - - if (isError) - { - Console.Error.WriteLine(line); - } - else - { - Console.WriteLine(line); - } - - string transcript; - lock (transcriptBuilder) - { - if (isError) - { - transcriptBuilder.Append("[stderr] "); - } - - transcriptBuilder.AppendLine(line); - transcript = transcriptBuilder.ToString(); - } - - _ = InvokeOnUiThreadAsync(() => FaceMatcherCommandOutput = transcript); - } - - internal static string? ResolveConfiguredFaceMatcherExecutablePath(string configuredPath, string fallbackEncoderPath) - { - foreach (var candidate in EnumerateFaceMatcherExecutableCandidates(configuredPath, fallbackEncoderPath)) - { - if (File.Exists(candidate)) - { - return candidate; - } - } - - return null; - } - - internal static string? ResolveConfiguredFaceMatcherEncodingsPath(string configuredPath, string fallbackOutputFolderPath) - { - var normalizedPath = NormalizeFilePathArgument(configuredPath); - if (File.Exists(normalizedPath)) - { - return normalizedPath; - } - - if (Directory.Exists(normalizedPath)) - { - var fromDirectory = new DirectoryInfo(normalizedPath) - .EnumerateFiles("*.pkl", SearchOption.TopDirectoryOnly) - .OrderByDescending(file => file.LastWriteTimeUtc) - .FirstOrDefault(); - if (fromDirectory is not null) - { - return fromDirectory.FullName; - } - } - - var fallbackOutputFolder = NormalizeDirectoryPathArgument(fallbackOutputFolderPath); - if (Directory.Exists(fallbackOutputFolder)) - { - var latest = new DirectoryInfo(fallbackOutputFolder) - .EnumerateFiles("*.pkl", SearchOption.TopDirectoryOnly) - .OrderByDescending(file => file.LastWriteTimeUtc) - .FirstOrDefault(); - return latest?.FullName; - } - - return null; - } - - internal static string? ResolveConfiguredFaceEncoderExecutablePath(string configuredPath, bool useGpu) - { - var variant = useGpu ? "gpu" : "cpu"; - foreach (var candidate in EnumerateFaceEncoderExecutableCandidates(configuredPath, variant)) - { - if (File.Exists(candidate)) - { - return candidate; - } - } - - return null; - } - - internal static (string OutputFilePath, string LogFilePath) BuildFaceEncoderOutputPaths(string outputFolderPath, string imagesFolderPath, DateTime timestamp) - { - var safeRaceName = BuildSafeFaceEncoderRaceName(imagesFolderPath); - var timestampToken = timestamp.ToString("yyyyMMdd_HHmmss"); - - return ( - Path.Combine(outputFolderPath, $"face_encodings_{timestampToken}_{safeRaceName}.pkl"), - Path.Combine(outputFolderPath, $"encoder_log_{timestampToken}_{safeRaceName}.txt")); - } - - internal static bool IsValidFaceUploadPath(string value) - { - return FaceUploadPathRegex.IsMatch((value ?? string.Empty).Trim()); - } - - internal static string CombineRemoteUploadPath(string basePath, string relativePath) - { - var normalizedBasePath = (basePath ?? string.Empty).Trim().Replace('\\', '/').TrimEnd('/'); - var normalizedRelativePath = (relativePath ?? string.Empty).Trim().Replace('\\', '/').Trim('/'); - - return string.IsNullOrWhiteSpace(normalizedBasePath) - ? normalizedRelativePath - : string.IsNullOrWhiteSpace(normalizedRelativePath) - ? normalizedBasePath - : $"{normalizedBasePath}/{normalizedRelativePath}"; - } - - private void LoadFaceSshUserPreferences() - { - if (_pickerPreferenceService is null) - { - return; - } - - _isLoadingFaceSshUserPreferences = true; - try - { - _ai.FaceSshUsername = _pickerPreferenceService.GetRememberedValue(PickerPreferenceKeys.FaceSshUsername) ?? string.Empty; - _ai.FaceSshPassword = _pickerPreferenceService.GetRememberedRawValue(PickerPreferenceKeys.FaceSshPassword) ?? string.Empty; - _ai.FaceSshAddress = _pickerPreferenceService.GetRememberedValue(PickerPreferenceKeys.FaceSshAddress) ?? string.Empty; - _ai.FaceSshPort = _pickerPreferenceService.GetRememberedValue(PickerPreferenceKeys.FaceSshPort) ?? "22"; - _ai.FaceSshPathA = _pickerPreferenceService.GetRememberedValue(PickerPreferenceKeys.FaceSshPathA) ?? string.Empty; - _ai.FaceSshPathB = _pickerPreferenceService.GetRememberedValue(PickerPreferenceKeys.FaceSshPathB) ?? string.Empty; - _ai.FaceUploadDryRun = TryGetRememberedBoolPreference(PickerPreferenceKeys.FaceUploadDryRun); - } - finally - { - _isLoadingFaceSshUserPreferences = false; - } - } - - private void SetFaceSshPreferenceValue(string preferenceKey, Action setValue, string value) - { - setValue(value); - if (_isLoadingFaceSshUserPreferences) - { - return; - } - - _pickerPreferenceService?.RememberRawValue(preferenceKey, value); - } - - private void SetFaceSshPreferenceBoolValue(string preferenceKey, Action setValue, bool value) - { - setValue(value); - if (_isLoadingFaceSshUserPreferences) - { - return; - } - - _pickerPreferenceService?.RememberRawValue(preferenceKey, value ? bool.TrueString : bool.FalseString); - } - - private bool TryGetRememberedBoolPreference(string preferenceKey) - { - var rawValue = _pickerPreferenceService?.GetRememberedRawValue(preferenceKey); - return bool.TryParse(rawValue, out var parsed) && parsed; - } - - private bool TryBuildFaceUploadRequest(out FaceUploadRequest request, out string validationMessage) - { - request = null!; - validationMessage = string.Empty; - - var sourceFilePath = ResolveFaceEncoderUploadSourceFile(); - if (string.IsNullOrWhiteSpace(sourceFilePath) || !File.Exists(sourceFilePath)) - { - validationMessage = "File .pkl face encoder non trovato nella cartella output."; - return false; - } - - var username = FaceSshUsername.Trim(); - var password = FaceSshPassword; - var serverAddress = FaceSshAddress.Trim(); - if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(serverAddress)) - { - validationMessage = "Inserisci username e indirizzo SSH."; - return false; - } - - if (!int.TryParse(FaceSshPort.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var port) || port is < 1 or > 65535) - { - validationMessage = "Porta SSH non valida."; - return false; - } - - var remoteBasePaths = new[] { FaceSshPathA, FaceSshPathB } - .Select(path => path.Trim()) - .Where(path => !string.IsNullOrWhiteSpace(path)) - .ToArray(); - if (remoteBasePaths.Length != 2) - { - validationMessage = "Inserisci path SSH A e path SSH B."; - return false; - } - - var relativeUploadPath = FaceUploadPath.Trim(); - var remoteDirectories = remoteBasePaths - .Select(path => CombineRemoteUploadPath(path, relativeUploadPath)) - .ToArray(); - - request = new FaceUploadRequest(sourceFilePath, username, password, serverAddress, port, remoteDirectories); - return true; - } - - private string? ResolveFaceEncoderUploadSourceFile() - { - var outputFolderPath = NormalizeDirectoryPathArgument(FaceOutputFolderPath); - if (!Directory.Exists(outputFolderPath)) - { - return null; - } - - return ResolveLatestFaceUploadSourceFile(outputFolderPath, NormalizeDirectoryPathArgument(DestinationPath)); - } - - internal static string? ResolveLatestFaceUploadSourceFile(string outputFolderPath, string imagesFolderPath) - { - var normalizedOutputFolderPath = NormalizeDirectoryPathArgument(outputFolderPath); - if (!Directory.Exists(normalizedOutputFolderPath)) - { - return null; - } - - var safeRaceName = BuildSafeFaceEncoderRaceName(NormalizeDirectoryPathArgument(imagesFolderPath)); - var racePattern = $"face_encodings_*_{safeRaceName}.pkl"; - - return new DirectoryInfo(normalizedOutputFolderPath) - .EnumerateFiles(racePattern, SearchOption.TopDirectoryOnly) - .OrderByDescending(file => file.LastWriteTimeUtc) - .ThenByDescending(file => file.Name, StringComparer.OrdinalIgnoreCase) - .FirstOrDefault() - ?.FullName; - } - - private async Task RunFaceUploadPowerShellAsync(FaceUploadRequest request) - { - var commandLine = BuildFaceUploadPowerShellCommand(request); - - var processStartInfo = CreateFaceUploadProcessStartInfo(commandLine); - - using var process = new Process { StartInfo = processStartInfo }; - - if (!process.Start()) - { - throw new InvalidOperationException("Avvio PowerShell per upload fallito."); - } - - await process.WaitForExitAsync().ConfigureAwait(false); - - if (process.ExitCode != 0) - { - throw new InvalidOperationException($"Upload fallito (exit code {process.ExitCode}). Verifica autenticazione SSH o inserisci la password nel terminale se richiesta."); - } - - var summary = new StringBuilder(); - summary.AppendLine("Upload Face AI completato."); - summary.AppendLine($"Command: {commandLine}"); - summary.AppendLine($"File: {request.LocalPath}"); - foreach (var remoteDirectory in request.RemoteDirectories) - { - summary.AppendLine($"Destinazione: {remoteDirectory}"); - } - - return summary.ToString(); - } - - private static ProcessStartInfo CreateFaceUploadProcessStartInfo(string commandLine) - { - var processStartInfo = new ProcessStartInfo - { - FileName = ResolvePowerShellExecutable(), - UseShellExecute = false, - RedirectStandardOutput = false, - RedirectStandardError = false, - RedirectStandardInput = false, - CreateNoWindow = false - }; - - processStartInfo.ArgumentList.Add("-NoProfile"); - processStartInfo.ArgumentList.Add("-ExecutionPolicy"); - processStartInfo.ArgumentList.Add("Bypass"); - processStartInfo.ArgumentList.Add("-Command"); - processStartInfo.ArgumentList.Add(commandLine); - - return processStartInfo; - } - - private static string BuildFaceUploadDryRunPreview(FaceUploadRequest request) - { - return BuildFaceUploadPowerShellCommand(request); - } - - private static string BuildFaceUploadPowerShellCommand(FaceUploadRequest request) - { - var fileName = Path.GetFileName(request.LocalPath); - var copyCommands = request.RemoteDirectories - .Select(remoteDirectory => BuildFaceUploadCopyCommand(request, CombineRemoteUploadPath(remoteDirectory, fileName))) - .ToArray(); - - return string.Join("; ", copyCommands); - } - - private static string ResolvePowerShellExecutable() - { - return OperatingSystem.IsWindows() ? "powershell.exe" : "pwsh"; - } - - private static string BuildFaceUploadCopyCommand(FaceUploadRequest request, string remoteFilePath) - { - return BuildScpCommand(request, remoteFilePath); - } - - private static string BuildScpCommand(FaceUploadRequest request, string remoteFilePath) - { - var remoteTarget = $"{request.UserName}@{request.ServerAddress}:{QuoteScpRemotePath(remoteFilePath)}"; - return $"scp -P {request.Port.ToString(CultureInfo.InvariantCulture)} {QuotePowerShellString(request.LocalPath)} {QuotePowerShellString(remoteTarget)}"; - } - - private static string QuotePowerShellString(string value) - { - return $"'{(value ?? string.Empty).Replace("'", "''", StringComparison.Ordinal)}'"; - } - - private static string QuoteScpRemotePath(string value) - { - return "'" + (value ?? string.Empty).Replace("'", "'\\''", StringComparison.Ordinal) + "'"; - } - - private sealed record FaceUploadRequest( - string LocalPath, - string UserName, - string Password, - string ServerAddress, - int Port, - IReadOnlyList RemoteDirectories); - - internal static string BuildSafeFaceEncoderRaceName(string imagesFolderPath) - { - var raceName = new DirectoryInfo(imagesFolderPath).Name; - if (string.IsNullOrWhiteSpace(raceName)) - { - return "race"; - } - - var invalidChars = Path.GetInvalidFileNameChars(); - var builder = new StringBuilder(raceName.Length); - var previousWasSeparator = false; - - foreach (var currentChar in raceName) - { - if (char.IsWhiteSpace(currentChar) || invalidChars.Contains(currentChar)) - { - if (!previousWasSeparator) - { - builder.Append('_'); - previousWasSeparator = true; - } - - continue; - } - - builder.Append(currentChar); - previousWasSeparator = false; - } - - return builder.ToString().Trim('_') switch - { - "" => "race", - var sanitized => sanitized - }; - } - - internal static (string CsvPath, string LogPath) ResolveFaceMatcherOutputPaths(string configuredCsvPath, string configuredLogPath, string fallbackRootPath, string imagePath, DateTime timestamp) - { - var baseName = BuildSafeFaceMatcherImageName(imagePath); - var timestampToken = timestamp.ToString("yyyyMMdd_HHmmss"); - var csvPath = ResolveFaceMatcherOutputFilePath(configuredCsvPath, fallbackRootPath, $"result_{timestampToken}_{baseName}.csv"); - var logPath = ResolveFaceMatcherOutputFilePath(configuredLogPath, fallbackRootPath, $"matcher_log_{timestampToken}_{baseName}.txt"); - return (csvPath, logPath); - } - - internal static string BuildSafeFaceMatcherImageName(string imagePath) - { - var fileName = Path.GetFileNameWithoutExtension(imagePath); - if (string.IsNullOrWhiteSpace(fileName)) - { - return "image"; - } - - var invalidChars = Path.GetInvalidFileNameChars(); - var builder = new StringBuilder(fileName.Length); - foreach (var currentChar in fileName) - { - builder.Append(invalidChars.Contains(currentChar) || char.IsWhiteSpace(currentChar) ? '_' : currentChar); - } - - return builder.ToString().Trim('_') switch - { - "" => "image", - var sanitized => sanitized - }; - } - - private static IEnumerable EnumerateFaceEncoderExecutableCandidates(string configuredPath, string variant) - { - var normalizedPath = NormalizeFilePathArgument(configuredPath); - if (string.IsNullOrWhiteSpace(normalizedPath)) - { - yield break; - } - - var executableName = $"face_encoder_{variant}.exe"; - - if (File.Exists(normalizedPath)) - { - var fileDirectory = Path.GetDirectoryName(normalizedPath); - if (!string.IsNullOrWhiteSpace(fileDirectory)) - { - yield return Path.Combine(fileDirectory, executableName); - - var parentDirectory = Directory.GetParent(fileDirectory)?.FullName; - if (!string.IsNullOrWhiteSpace(parentDirectory)) - { - yield return Path.Combine(parentDirectory, $"face_encoder_{variant}", executableName); - } - } - - yield return normalizedPath; - yield break; - } - - yield return Path.Combine(normalizedPath, executableName); - yield return Path.Combine(normalizedPath, $"face_encoder_{variant}", executableName); - - var leafName = Path.GetFileName(normalizedPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); - if (leafName.Equals("face_encoder_cpu", StringComparison.OrdinalIgnoreCase) - || leafName.Equals("face_encoder_gpu", StringComparison.OrdinalIgnoreCase)) - { - var parentDirectory = Directory.GetParent(normalizedPath)?.FullName; - if (!string.IsNullOrWhiteSpace(parentDirectory)) - { - yield return Path.Combine(parentDirectory, $"face_encoder_{variant}", executableName); - } - } - } - - private static IEnumerable EnumerateFaceMatcherExecutableCandidates(string configuredPath, string fallbackEncoderPath) - { - var normalizedPath = NormalizeFilePathArgument(configuredPath); - if (!string.IsNullOrWhiteSpace(normalizedPath)) - { - if (File.Exists(normalizedPath)) - { - yield return normalizedPath; - } - - yield return Path.Combine(normalizedPath, "face_matcher.exe"); - } - - var fallbackPath = NormalizeFilePathArgument(fallbackEncoderPath); - if (!string.IsNullOrWhiteSpace(fallbackPath)) - { - if (File.Exists(fallbackPath)) - { - var fileDirectory = Path.GetDirectoryName(fallbackPath); - if (!string.IsNullOrWhiteSpace(fileDirectory)) - { - yield return Path.Combine(fileDirectory, "face_matcher.exe"); - } - } - - yield return Path.Combine(fallbackPath, "face_matcher.exe"); - } - } - - private static int NormalizeFaceParallelism(int value) - { - return value is >= 1 and <= 5 ? value : 3; - } - - private static double NormalizeFaceMatcherTolerance(double value) - { - if (double.IsNaN(value) || double.IsInfinity(value)) - { - return 0.5; - } - - return Math.Clamp(Math.Round(value, 2), 0.35, 0.75); - } - - private static int NormalizeNumberAiWorkloadLevel(int value) - { - return value is >= 1 and <= 5 ? value : 3; - } - - private static int ResolveNumberAiWorkerCount(bool useGpu, int workloadLevel) - { - var normalized = NormalizeNumberAiWorkloadLevel(workloadLevel); - var maxWorkers = Math.Max(1, Environment.ProcessorCount); - var requestedWorkers = useGpu - ? normalized switch - { - 1 => 4, - 2 => 8, - 3 => 16, - 4 => 24, - _ => 32 - } - : normalized switch - { - 1 => 1, - 2 => 2, - 3 => 3, - 4 => 4, - _ => 5 - }; - - return useGpu ? requestedWorkers : Math.Min(requestedWorkers, maxWorkers); - } - - private static int NormalizeFaceMinSize(int value) - { - return value > 0 ? value : 35; - } - - private static bool GetRecommendedFaceUpsample(bool useGpu) - { - return !useGpu; - } - - private static string BuildFaceEncoderSummary( - int exitCode, - ProcessStartInfo processStartInfo, - string outputFilePath, - string logFilePath, - StringBuilder outputLines, - StringBuilder errorLines) - { - var summary = new StringBuilder(); - summary.AppendLine($"Exit code: {exitCode}"); - summary.AppendLine($"Command: {processStartInfo.FileName} {string.Join(" ", processStartInfo.ArgumentList)}"); - summary.AppendLine($"Output file: {outputFilePath}"); - summary.AppendLine($"Log file: {logFilePath}"); - - lock (outputLines) - { - if (outputLines.Length > 0) - { - summary.AppendLine(); - summary.AppendLine("STDOUT:"); - summary.Append(outputLines); - } - } - - lock (errorLines) - { - if (errorLines.Length > 0) - { - summary.AppendLine(); - summary.AppendLine("STDERR:"); - summary.Append(errorLines); - } - } - - return summary.ToString(); - } - - private static string BuildFaceMatcherSummary( - int exitCode, - ProcessStartInfo processStartInfo, - string csvPath, - string logFilePath, - StringBuilder outputLines, - StringBuilder errorLines, - int matchCount) - { - var summary = new StringBuilder(); - summary.AppendLine($"Exit code: {exitCode}"); - summary.AppendLine($"Command: {processStartInfo.FileName} {string.Join(" ", processStartInfo.ArgumentList)}"); - summary.AppendLine($"Result CSV: {csvPath}"); - summary.AppendLine($"Log file: {logFilePath}"); - summary.AppendLine($"Match count: {matchCount}"); - - lock (outputLines) - { - if (outputLines.Length > 0) - { - summary.AppendLine(); - summary.AppendLine("STDOUT:"); - summary.Append(outputLines); - } - } - - lock (errorLines) - { - if (errorLines.Length > 0) - { - summary.AppendLine(); - summary.AppendLine("STDERR:"); - summary.Append(errorLines); - } - } - - return summary.ToString(); - } - - private static string ResolveFaceMatcherFallbackOutputRoot(string configuredCsvPath, string configuredLogPath, string faceOutputFolderPath, string executablePath) - { - foreach (var candidate in new[] { NormalizeFilePathArgument(configuredCsvPath), NormalizeFilePathArgument(configuredLogPath), NormalizeDirectoryPathArgument(faceOutputFolderPath) }) - { - if (string.IsNullOrWhiteSpace(candidate)) - { - continue; - } - - if (Directory.Exists(candidate)) - { - return candidate; - } - - var directory = Path.GetDirectoryName(candidate); - if (!string.IsNullOrWhiteSpace(directory)) - { - return directory; - } - } - - return Path.Combine(Path.GetDirectoryName(executablePath) ?? Environment.CurrentDirectory, "output"); - } - - private static string ResolveFaceMatcherOutputFilePath(string configuredPath, string fallbackRootPath, string defaultFileName) - { - var normalized = NormalizeFilePathArgument(configuredPath); - if (string.IsNullOrWhiteSpace(normalized)) - { - return Path.Combine(fallbackRootPath, defaultFileName); - } - - if (Directory.Exists(normalized) || string.IsNullOrWhiteSpace(Path.GetExtension(normalized))) - { - return Path.Combine(normalized, defaultFileName); - } - - return normalized; - } - - private async Task LogIndicatesNoFacesAsync(string logPath) - { - try - { - if (!File.Exists(logPath)) - { - return false; - } - - var content = await File.ReadAllTextAsync(logPath).ConfigureAwait(false); - return content.Contains("nessun volt", StringComparison.OrdinalIgnoreCase) - || content.Contains("no face", StringComparison.OrdinalIgnoreCase) - || content.Contains("0 faces", StringComparison.OrdinalIgnoreCase); - } - catch - { - return false; - } - } - - private static async Task> ParseFaceMatcherCsvAsync(string csvPath, string logPath) - { - var parsedRows = new List(); - if (!File.Exists(csvPath)) - { - return parsedRows; - } - - var logScores = await ParseFaceMatcherScoresFromLogAsync(logPath).ConfigureAwait(false); - - var lines = await File.ReadAllLinesAsync(csvPath).ConfigureAwait(false); - var meaningfulLines = lines.Where(line => !string.IsNullOrWhiteSpace(line)).ToArray(); - if (meaningfulLines.Length == 0) - { - return parsedRows; - } - - string[]? headers = null; - var firstCells = ParseCsvLine(meaningfulLines[0]); - var hasHeader = firstCells.Any(cell => cell.Contains("file", StringComparison.OrdinalIgnoreCase) - || cell.Contains("image", StringComparison.OrdinalIgnoreCase) - || cell.Contains("score", StringComparison.OrdinalIgnoreCase) - || cell.Contains("distance", StringComparison.OrdinalIgnoreCase) - || cell.Contains("confidence", StringComparison.OrdinalIgnoreCase)); - - var startIndex = 0; - if (hasHeader) - { - headers = firstCells; - startIndex = 1; - } - - for (var index = startIndex; index < meaningfulLines.Length; index++) - { - var rawLine = meaningfulLines[index].Trim(); - var cells = ParseCsvLine(rawLine); - if (cells.Length == 0 || string.IsNullOrWhiteSpace(cells[0])) - { - continue; - } - - var photoId = Path.GetFileName(cells[0]); - double? score = null; - for (var cellIndex = 1; cellIndex < cells.Length; cellIndex++) - { - if (double.TryParse(cells[cellIndex], NumberStyles.Float, CultureInfo.InvariantCulture, out var parsedScore)) - { - score = parsedScore; - break; - } - } - - if (!score.HasValue && logScores.TryGetValue(photoId, out var logScore)) - { - score = logScore; - } - - var debugParts = new List(); - for (var cellIndex = 1; cellIndex < cells.Length; cellIndex++) - { - var cellValue = cells[cellIndex]; - if (string.IsNullOrWhiteSpace(cellValue)) - { - continue; - } - - var header = headers is not null && cellIndex < headers.Length - ? headers[cellIndex] - : $"col{cellIndex + 1}"; - debugParts.Add($"{header}: {cellValue}"); - } - - if (score.HasValue) - { - debugParts.Add($"score: {score.Value.ToString("0.###", CultureInfo.InvariantCulture)}"); - } - - parsedRows.Add(new ParsedFaceMatcherRow(photoId, score, rawLine, string.Join(" | ", debugParts))); - } - - return parsedRows; - } - - private static async Task> ParseFaceMatcherScoresFromLogAsync(string logPath) - { - var scores = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (!File.Exists(logPath)) - { - return scores; - } - - var lines = await File.ReadAllLinesAsync(logPath).ConfigureAwait(false); - foreach (var line in lines) - { - if (string.IsNullOrWhiteSpace(line)) - { - continue; - } - - var match = Regex.Match( - line, - @"in\s+(?.+?)\s+-\s+\[Somiglianza:\s*(?[0-9]+(?:[\.,][0-9]+)?)%\]", - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - - if (!match.Success) - { - continue; - } - - var pathValue = match.Groups["path"].Value.Trim(); - var photoId = Path.GetFileName(pathValue); - if (string.IsNullOrWhiteSpace(photoId)) - { - continue; - } - - var scoreText = match.Groups["score"].Value.Replace(',', '.'); - if (!double.TryParse(scoreText, NumberStyles.Float, CultureInfo.InvariantCulture, out var score)) - { - continue; - } - - if (!scores.TryGetValue(photoId, out var existingScore) || score > existingScore) - { - scores[photoId] = score; - } - } - - return scores; - } - - private static string[] ParseCsvLine(string line) - { - var values = new List(); - var current = new StringBuilder(); - var insideQuotes = false; - - foreach (var currentChar in line) - { - if (currentChar == '"') - { - insideQuotes = !insideQuotes; - continue; - } - - if (currentChar == ',' && !insideQuotes) - { - values.Add(current.ToString().Trim()); - current.Clear(); - continue; - } - - current.Append(currentChar); - } - - values.Add(current.ToString().Trim()); - return values.ToArray(); - } - - private static Dictionary> ResolveDestinationImagesByFileName(string destinationRoot, IEnumerable fileNames) - { - var result = new Dictionary>(StringComparer.OrdinalIgnoreCase); - var normalizedRoot = NormalizeDirectoryPathArgument(destinationRoot); - if (string.IsNullOrWhiteSpace(normalizedRoot) || !Directory.Exists(normalizedRoot)) - { - return result; - } - - var requestedNames = new HashSet(fileNames.Where(name => !string.IsNullOrWhiteSpace(name)).Select(name => Path.GetFileName(name)), StringComparer.OrdinalIgnoreCase); - if (requestedNames.Count == 0) - { - return result; - } - - foreach (var path in Directory.EnumerateFiles(normalizedRoot, "*", SearchOption.AllDirectories)) - { - var fileName = Path.GetFileName(path); - if (!requestedNames.Contains(fileName)) - { - continue; - } - - if (!result.TryGetValue(fileName, out var list)) - { - list = new List(); - result[fileName] = list; - } - - list.Add(path); - } - - return result; - } - - private static string NormalizeDirectoryPathArgument(string value) - { - if (string.IsNullOrWhiteSpace(value)) - { - return string.Empty; - } - - var normalized = value.Trim().Trim('"'); - var root = Path.GetPathRoot(normalized); - if (!string.IsNullOrEmpty(root) && normalized.Length > root.Length) - { - normalized = normalized.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - } - - return normalized; - } - - private static string NormalizeFilePathArgument(string value) - { - if (string.IsNullOrWhiteSpace(value)) - { - return string.Empty; - } - - return value.Trim().Trim('"'); - } - // Note: These commands will trigger events that the View will handle to show dialogs // since dialogs require UI context - public event EventHandler? SelectSourceFolderRequested; - public event EventHandler? SelectDestinationFolderRequested; - public event EventHandler? SelectLogoFileRequested; - public event EventHandler? SelectModelsFolderRequested; - public event EventHandler? SelectCsvOutputRequested; - public event EventHandler? SaveSettingsRequested; - public event EventHandler? LoadSettingsRequested; - public event EventHandler? SelectColorRequested; + public event EventHandler SelectSourceFolderRequested; + public event EventHandler SelectDestinationFolderRequested; + public event EventHandler SelectLogoFileRequested; + public event EventHandler SelectModelsFolderRequested; + public event EventHandler SelectCsvOutputRequested; + public event EventHandler SaveSettingsRequested; + public event EventHandler LoadSettingsRequested; + public event EventHandler SelectColorRequested; // Request that the View shows a message to the user (message, caption, icon) - public event EventHandler>? ShowMessageRequested; - public event EventHandler? SelectTransparentColorRequested; + public event EventHandler> ShowMessageRequested; + public event EventHandler SelectTransparentColorRequested; private void SelectSourceFolder(object parameter) { @@ -3895,12 +1528,12 @@ namespace ImageCatalog_2 private void SaveSettings(object parameter) { - SaveSettingsRequested?.Invoke(this, string.Empty); + SaveSettingsRequested?.Invoke(this, null); } private void LoadSettings(object parameter) { - LoadSettingsRequested?.Invoke(this, string.Empty); + LoadSettingsRequested?.Invoke(this, null); } private void SelectColor(object parameter) diff --git a/imagecatalog/ExifReader.cs b/imagecatalog/ExifReader.cs new file mode 100644 index 0000000..97005ca --- /dev/null +++ b/imagecatalog/ExifReader.cs @@ -0,0 +1,1190 @@ +/// ----------------------------------------------------------------------------- +/// +/// Utility class for reading EXIF data from images. Provides abstraction +/// for most common data and generic utilities for work with all other. +/// +/// +/// Copyright (c) Michal A. Valášek - Altair Communications, 2003 +/// Copmany: http://software.altaircom.net * support@altaircom.net +/// Private: http://www.rider.cz * developer@rider.cz +/// This is free software licensed under GNU Lesser General Public License +/// +/// +/// [altair] 10.9.2003 Created +/// +/// ----------------------------------------------------------------------------- +using System; +using System.Drawing; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; + +namespace ImageCatalog +{ + public class ExifReader : IDisposable + { + private Bitmap Image; + + /// ----------------------------------------------------------------------------- + /// + /// Contains possible values of EXIF tag names (ID) + /// + /// See GdiPlusImaging.h + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public enum TagNames + { + ExifIFD = 0x8769, + GpsIFD = 0x8825, + NewSubfileType = 0xFE, + SubfileType = 0xFF, + ImageWidth = 0x100, + ImageHeight = 0x101, + BitsPerSample = 0x102, + Compression = 0x103, + PhotometricInterp = 0x106, + ThreshHolding = 0x107, + CellWidth = 0x108, + CellHeight = 0x109, + FillOrder = 0x10A, + DocumentName = 0x10D, + ImageDescription = 0x10E, + EquipMake = 0x10F, + EquipModel = 0x110, + StripOffsets = 0x111, + Orientation = 0x112, + SamplesPerPixel = 0x115, + RowsPerStrip = 0x116, + StripBytesCount = 0x117, + MinSampleValue = 0x118, + MaxSampleValue = 0x119, + XResolution = 0x11A, + YResolution = 0x11B, + PlanarConfig = 0x11C, + PageName = 0x11D, + XPosition = 0x11E, + YPosition = 0x11F, + FreeOffset = 0x120, + FreeByteCounts = 0x121, + GrayResponseUnit = 0x122, + GrayResponseCurve = 0x123, + T4Option = 0x124, + T6Option = 0x125, + ResolutionUnit = 0x128, + PageNumber = 0x129, + TransferFuncition = 0x12D, + SoftwareUsed = 0x131, + DateTime = 0x132, + Artist = 0x13B, + HostComputer = 0x13C, + Predictor = 0x13D, + WhitePoint = 0x13E, + PrimaryChromaticities = 0x13F, + ColorMap = 0x140, + HalftoneHints = 0x141, + TileWidth = 0x142, + TileLength = 0x143, + TileOffset = 0x144, + TileByteCounts = 0x145, + InkSet = 0x14C, + InkNames = 0x14D, + NumberOfInks = 0x14E, + DotRange = 0x150, + TargetPrinter = 0x151, + ExtraSamples = 0x152, + SampleFormat = 0x153, + SMinSampleValue = 0x154, + SMaxSampleValue = 0x155, + TransferRange = 0x156, + JPEGProc = 0x200, + JPEGInterFormat = 0x201, + JPEGInterLength = 0x202, + JPEGRestartInterval = 0x203, + JPEGLosslessPredictors = 0x205, + JPEGPointTransforms = 0x206, + JPEGQTables = 0x207, + JPEGDCTables = 0x208, + JPEGACTables = 0x209, + YCbCrCoefficients = 0x211, + YCbCrSubsampling = 0x212, + YCbCrPositioning = 0x213, + REFBlackWhite = 0x214, + ICCProfile = 0x8773, + Gamma = 0x301, + ICCProfileDescriptor = 0x302, + SRGBRenderingIntent = 0x303, + ImageTitle = 0x320, + Copyright = 0x8298, + ResolutionXUnit = 0x5001, + ResolutionYUnit = 0x5002, + ResolutionXLengthUnit = 0x5003, + ResolutionYLengthUnit = 0x5004, + PrintFlags = 0x5005, + PrintFlagsVersion = 0x5006, + PrintFlagsCrop = 0x5007, + PrintFlagsBleedWidth = 0x5008, + PrintFlagsBleedWidthScale = 0x5009, + HalftoneLPI = 0x500A, + HalftoneLPIUnit = 0x500B, + HalftoneDegree = 0x500C, + HalftoneShape = 0x500D, + HalftoneMisc = 0x500E, + HalftoneScreen = 0x500F, + JPEGQuality = 0x5010, + GridSize = 0x5011, + ThumbnailFormat = 0x5012, + ThumbnailWidth = 0x5013, + ThumbnailHeight = 0x5014, + ThumbnailColorDepth = 0x5015, + ThumbnailPlanes = 0x5016, + ThumbnailRawBytes = 0x5017, + ThumbnailSize = 0x5018, + ThumbnailCompressedSize = 0x5019, + ColorTransferFunction = 0x501A, + ThumbnailData = 0x501B, + ThumbnailImageWidth = 0x5020, + ThumbnailImageHeight = 0x502, + ThumbnailBitsPerSample = 0x5022, + ThumbnailCompression = 0x5023, + ThumbnailPhotometricInterp = 0x5024, + ThumbnailImageDescription = 0x5025, + ThumbnailEquipMake = 0x5026, + ThumbnailEquipModel = 0x5027, + ThumbnailStripOffsets = 0x5028, + ThumbnailOrientation = 0x5029, + ThumbnailSamplesPerPixel = 0x502A, + ThumbnailRowsPerStrip = 0x502B, + ThumbnailStripBytesCount = 0x502C, + ThumbnailResolutionX = 0x502D, + ThumbnailResolutionY = 0x502E, + ThumbnailPlanarConfig = 0x502F, + ThumbnailResolutionUnit = 0x5030, + ThumbnailTransferFunction = 0x5031, + ThumbnailSoftwareUsed = 0x5032, + ThumbnailDateTime = 0x5033, + ThumbnailArtist = 0x5034, + ThumbnailWhitePoint = 0x5035, + ThumbnailPrimaryChromaticities = 0x5036, + ThumbnailYCbCrCoefficients = 0x5037, + ThumbnailYCbCrSubsampling = 0x5038, + ThumbnailYCbCrPositioning = 0x5039, + ThumbnailRefBlackWhite = 0x503A, + ThumbnailCopyRight = 0x503B, + LuminanceTable = 0x5090, + ChrominanceTable = 0x5091, + FrameDelay = 0x5100, + LoopCount = 0x5101, + PixelUnit = 0x5110, + PixelPerUnitX = 0x5111, + PixelPerUnitY = 0x5112, + PaletteHistogram = 0x5113, + ExifExposureTime = 0x829A, + ExifFNumber = 0x829D, + ExifExposureProg = 0x8822, + ExifSpectralSense = 0x8824, + ExifISOSpeed = 0x8827, + ExifOECF = 0x8828, + ExifVer = 0x9000, + ExifDTOrig = 0x9003, + ExifDTDigitized = 0x9004, + ExifCompConfig = 0x9101, + ExifCompBPP = 0x9102, + ExifShutterSpeed = 0x9201, + ExifAperture = 0x9202, + ExifBrightness = 0x9203, + ExifExposureBias = 0x9204, + ExifMaxAperture = 0x9205, + ExifSubjectDist = 0x9206, + ExifMeteringMode = 0x9207, + ExifLightSource = 0x9208, + ExifFlash = 0x9209, + ExifFocalLength = 0x920A, + ExifMakerNote = 0x927C, + ExifUserComment = 0x9286, + ExifDTSubsec = 0x9290, + ExifDTOrigSS = 0x9291, + ExifDTDigSS = 0x9292, + ExifFPXVer = 0xA000, + ExifColorSpace = 0xA001, + ExifPixXDim = 0xA002, + ExifPixYDim = 0xA003, + ExifRelatedWav = 0xA004, + ExifInterop = 0xA005, + ExifFlashEnergy = 0xA20B, + ExifSpatialFR = 0xA20C, + ExifFocalXRes = 0xA20E, + ExifFocalYRes = 0xA20F, + ExifFocalResUnit = 0xA210, + ExifSubjectLoc = 0xA214, + ExifExposureIndex = 0xA215, + ExifSensingMethod = 0xA217, + ExifFileSource = 0xA300, + ExifSceneType = 0xA301, + ExifCfaPattern = 0xA302, + GpsVer = 0x0, + GpsLatitudeRef = 0x1, + GpsLatitude = 0x2, + GpsLongitudeRef = 0x3, + GpsLongitude = 0x4, + GpsAltitudeRef = 0x5, + GpsAltitude = 0x6, + GpsGpsTime = 0x7, + GpsGpsSatellites = 0x8, + GpsGpsStatus = 0x9, + GpsGpsMeasureMode = 0xA, + GpsGpsDop = 0xB, + GpsSpeedRef = 0xC, + GpsSpeed = 0xD, + GpsTrackRef = 0xE, + GpsTrack = 0xF, + GpsImgDirRef = 0x10, + GpsImgDir = 0x11, + GpsMapDatum = 0x12, + GpsDestLatRef = 0x13, + GpsDestLat = 0x14, + GpsDestLongRef = 0x15, + GpsDestLong = 0x16, + GpsDestBearRef = 0x17, + GpsDestBear = 0x18, + GpsDestDistRef = 0x19, + GpsDestDist = 0x1A + } + + /// ----------------------------------------------------------------------------- + /// + /// Real position of 0th row and column of picture + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public enum Orientations + { + TopLeft = 1, + TopRight = 2, + BottomRight = 3, + BottomLeft = 4, + LeftTop = 5, + RightTop = 6, + RightBottom = 7, + LftBottom = 8 + } + + /// ----------------------------------------------------------------------------- + /// + /// Exposure programs + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public enum ExposurePrograms + { + Manual = 1, + Normal = 2, + AperturePriority = 3, + ShutterPriority = 4, + Creative = 5, + Action = 6, + Portrait = 7, + Landscape = 8 + } + + /// ----------------------------------------------------------------------------- + /// + /// Exposure metering modes + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public enum ExposureMeteringModes + { + Unknown = 0, + Average = 1, + CenterWeightedAverage = 2, + Spot = 3, + MultiSpot = 4, + MultiSegment = 5, + Partial = 6, + Other = 255 + } + + /// ----------------------------------------------------------------------------- + /// + /// Flash activity modes + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public enum FlashModes + { + NotFired = 0, + Fired = 1, + FiredButNoStrobeReturned = 5, + FiredAndStrobeReturned = 7 + } + + /// ----------------------------------------------------------------------------- + /// + /// Possible light sources (white balance) + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public enum LightSources + { + Unknown = 0, + Daylight = 1, + Fluorescent = 2, + Tungsten = 3, + Flash = 10, + StandardLightA = 17, + StandardLightB = 18, + StandardLightC = 19, + D55 = 20, + D65 = 21, + D75 = 22, + Other = 255 + } + + /// ----------------------------------------------------------------------------- + /// + /// Represents rational which is type of some Exif properties + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public struct Rational + { + public int Numerator; + public int Denominator; + + /// ----------------------------------------------------------------------------- + /// + /// Converts rational to string representation + /// + /// Optional, default "/". String to be used as delimiter of components. + /// String representation of the rational. + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public new string ToString(string Delimiter = "/") + { + return Numerator + Delimiter + Denominator; + } + + /// ----------------------------------------------------------------------------- + /// + /// Converts rational to double precision real number + /// + /// The rational as double precision real number. + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public double ToDouble() + { + return Numerator / (double)Denominator; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Initializes new instance of this class. + /// + /// Bitmap to read exif information from + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public ExifReader(Bitmap Bitmap) + { + if (Bitmap is null) + throw new ArgumentNullException("Bitmap"); + Image = Bitmap; + } + + /// ----------------------------------------------------------------------------- + /// + /// Returns all available data in formatted string form + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public override string ToString() + { + var SB = new System.Text.StringBuilder(); + SB.Append("Image:"); + SB.Append(@"\n\tDimensions: " + Width + " x " + Height + " px"); + SB.Append(@"\n\tResolution: " + ResolutionX + " x " + ResolutionY + " dpi"); + SB.Append(@"\n\tOrientation: " + Enum.GetName(typeof(Orientations), Orientation)); + SB.Append(@"\n\tTitle: " + Title); + SB.Append(@"\n\tDescription: " + Description); + SB.Append(@"\n\tCopyright: " + Copyright); + SB.Append(@"\nEquipment:"); + SB.Append(@"\n\tMaker: " + EquipmentMaker); + SB.Append(@"\n\tModel: " + EquipmentModel); + SB.Append(@"\n\tSoftware: " + Software); + SB.Append(@"\nDate and time:"); + SB.Append(@"\n\tGeneral: " + DateTimeLastModified.ToString()); + SB.Append(@"\n\tOriginal: " + DateTimeOriginal.ToString()); + SB.Append(@"\n\tDigitized: " + DateTimeDigitized.ToString()); + SB.Append(@"\nShooting conditions:"); + SB.Append(@"\n\tExposure time: " + ExposureTime.ToString("N4") + " s"); + SB.Append(@"\n\tExposure program: " + Enum.GetName(typeof(ExposurePrograms), ExposureProgram)); + SB.Append(@"\n\tExposure mode: " + Enum.GetName(typeof(ExposureMeteringModes), ExposureMeteringMode)); + SB.Append(@"\n\tAperture: F" + Aperture.ToString("N2")); + SB.Append(@"\n\tISO sensitivity: " + ISO); + SB.Append(@"\n\tSubject distance: " + SubjectDistance.ToString("N2") + " m"); + SB.Append(@"\n\tFocal length: " + FocalLength); + SB.Append(@"\n\tFlash: " + Enum.GetName(typeof(FlashModes), FlashMode)); + SB.Append(@"\n\tLight source (WB): " + Enum.GetName(typeof(LightSources), LightSource)); + SB.Append(@"\n\nCopyright (c) Michal A. Valasek - Altair Communications, 2003"); + SB.Append(@"\nhttp://software.altaircom.net * support@altaircom.net"); + SB.Replace(@"\n", Constants.vbCrLf); + SB.Replace(@"\t", Constants.vbTab); + return SB.ToString(); + } + + /// ----------------------------------------------------------------------------- + /// + /// Brand of equipment (EXIF EquipMake) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public string EquipmentMaker + { + get + { + return GetPropertyString((int)TagNames.EquipMake); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Model of equipment (EXIF EquipModel) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public string EquipmentModel + { + get + { + return GetPropertyString((int)TagNames.EquipModel); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Software used for processing (EXIF Software) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public string Software + { + get + { + return GetPropertyString((int)TagNames.SoftwareUsed); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Orientation of image (position of row 0, column 0) (EXIF Orientation) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public Orientations Orientation + { + get + { + int X = GetPropertyInt16((int)TagNames.Orientation); + if (!Enum.IsDefined(typeof(Orientations), X)) + { + return Orientations.TopLeft; + } + else + { + return (Orientations)Conversions.ToInteger(Enum.Parse(typeof(Orientations), Enum.GetName(typeof(Orientations), X))); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Time when image was last modified (EXIF DateTime). + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public DateTime DateTimeLastModified + { + get + { + try + { + return DateTime.ParseExact(GetPropertyString((int)TagNames.DateTime), @"yyyy\:MM\:dd HH\:mm\:ss", null); + } + catch (Exception ex) + { + return DateTime.MinValue; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Time when image was taken (EXIF DateTimeOriginal). + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public DateTime DateTimeOriginal + { + get + { + try + { + return DateTime.ParseExact(GetPropertyString((int)TagNames.ExifDTOrig), @"yyyy\:MM\:dd HH\:mm\:ss", null); + } + catch (Exception ex) + { + return DateTime.MinValue; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Time when image was digitized (EXIF DateTimeDigitized). + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public DateTime DateTimeDigitized + { + get + { + try + { + return DateTime.ParseExact(GetPropertyString((int)TagNames.ExifDTDigitized), @"yyyy\:MM\:dd HH\:mm\:ss", null); + } + catch (Exception ex) + { + return DateTime.MinValue; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Image width + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public short Width + { + get + { + return GetPropertyInt16((int)TagNames.ImageWidth); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Image height + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public short Height + { + get + { + return GetPropertyInt16((int)TagNames.ImageHeight); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// X resolution in dpi (EXIF XResolution/ResolutionUnit) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public double ResolutionX + { + get + { + double R = GetPropertyRational((int)TagNames.XResolution).ToDouble(); + if (GetPropertyInt16((int)TagNames.ResolutionUnit) == 3) + { + // -- resolution is in points/cm + return R * 2.54d; + } + else + { + // -- resolution is in points/inch + return R; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Y resolution in dpi (EXIF YResolution/ResolutionUnit) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public double ResolutionY + { + get + { + double R = GetPropertyRational((int)TagNames.YResolution).ToDouble(); + if (GetPropertyInt16((int)TagNames.ResolutionUnit) == 3) + { + // -- resolution is in points/cm + return R * 2.54d; + } + else + { + // -- resolution is in points/inch + return R; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Image title (EXIF ImageTitle) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public string Title + { + get + { + return GetPropertyString((int)TagNames.ImageTitle); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Image description (EXIF ImageDescription) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public string Description + { + get + { + return GetPropertyString((int)TagNames.ImageDescription); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Image copyright (EXIF Copyright) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public string Copyright + { + get + { + return GetPropertyString((int)TagNames.Copyright); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Exposure time in seconds (EXIF ExifExposureTime/ExifShutterSpeed) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public double ExposureTime + { + get + { + if (IsPropertyDefined((int)TagNames.ExifExposureTime)) + { + // -- Exposure time is explicitly specified + return GetPropertyRational((int)TagNames.ExifExposureTime).ToDouble(); + } + else if (IsPropertyDefined((int)TagNames.ExifShutterSpeed)) + { + // -- Compute exposure time from shutter speed + return 1d / Math.Pow(2d, GetPropertyRational((int)TagNames.ExifShutterSpeed).ToDouble()); + } + else + { + // -- Can't figure out + return 0d; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Aperture value as F number (EXIF ExifFNumber/ExifApertureValue) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public double Aperture + { + get + { + if (IsPropertyDefined((int)TagNames.ExifFNumber)) + { + return GetPropertyRational((int)TagNames.ExifFNumber).ToDouble(); + } + else if (IsPropertyDefined((int)TagNames.ExifAperture)) + { + return Math.Pow(Math.Sqrt(2d), GetPropertyRational((int)TagNames.ExifAperture).ToDouble()); + } + else + { + return 0d; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Exposure program used (EXIF ExifExposureProg) + /// + /// + /// If not specified, returns Normal (2) + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public ExposurePrograms ExposureProgram + { + get + { + int X = GetPropertyInt16((int)TagNames.ExifExposureProg); + if (Enum.IsDefined(typeof(ExposurePrograms), X)) + { + return (ExposurePrograms)Conversions.ToInteger(Enum.Parse(typeof(ExposurePrograms), Enum.GetName(typeof(ExposurePrograms), X))); + } + else + { + return ExposurePrograms.Normal; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// ISO sensitivity + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public short ISO + { + get + { + return GetPropertyInt16((int)TagNames.ExifISOSpeed); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Subject distance in meters (EXIF SubjectDistance) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public double SubjectDistance + { + get + { + return GetPropertyRational((int)TagNames.ExifSubjectDist).ToDouble(); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Exposure method metering mode used (EXIF MeteringMode) + /// + /// + /// If not specified, returns Unknown (0) + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public ExposureMeteringModes ExposureMeteringMode + { + get + { + int X = GetPropertyInt16((int)TagNames.ExifMeteringMode); + if (Enum.IsDefined(typeof(ExposureMeteringModes), X)) + { + return (ExposureMeteringModes)Conversions.ToInteger(Enum.Parse(typeof(ExposureMeteringModes), Enum.GetName(typeof(ExposureMeteringModes), X))); + } + else + { + return ExposureMeteringModes.Unknown; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Focal length of lenses in mm (EXIF FocalLength) + /// + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public double FocalLength + { + get + { + return GetPropertyRational((int)TagNames.ExifFocalLength).ToDouble(); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Flash mode (EXIF Flash) + /// + /// + /// If not present, value NotFired (0) is returned + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public FlashModes FlashMode + { + get + { + int X = GetPropertyInt16((int)TagNames.ExifFlash); + if (Enum.IsDefined(typeof(FlashModes), X)) + { + return (FlashModes)Conversions.ToInteger(Enum.Parse(typeof(FlashModes), Enum.GetName(typeof(FlashModes), X))); + } + else + { + return FlashModes.NotFired; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Light source / white balance (EXIF LightSource) + /// + /// + /// If not specified, returns Unknown (0). + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public LightSources LightSource + { + get + { + int X = GetPropertyInt16((int)TagNames.ExifLightSource); + if (Enum.IsDefined(typeof(LightSources), X)) + { + return (LightSources)Conversions.ToInteger(Enum.Parse(typeof(LightSources), Enum.GetName(typeof(LightSources), X))); + } + else + { + return LightSources.Unknown; + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Checks if current image has specified certain property + /// + /// + /// True if image has specified property, False otherwise. + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public bool IsPropertyDefined(int PID) + { + return Array.IndexOf(Image.PropertyIdList, PID) > -1; + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets specified Int32 property + /// + /// Property ID + /// Optional, default 0. Default value returned if property is not present. + /// Value of property or DefaultValue if property is not present. + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public int GetPropertyInt32(int PID, int DefaultValue = 0) + { + if (IsPropertyDefined(PID)) + { + return GetInt32(Image.GetPropertyItem(PID).Value); + } + else + { + return DefaultValue; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets specified Int16 property + /// + /// Property ID + /// Optional, default 0. Default value returned if property is not present. + /// Value of property or DefaultValue if property is not present. + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public short GetPropertyInt16(int PID, short DefaultValue = 0) + { + if (IsPropertyDefined(PID)) + { + return GetInt16(Image.GetPropertyItem(PID).Value); + } + else + { + return DefaultValue; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets specified string property + /// + /// Property ID + /// Optional, default String.Empty. Default value returned if property is not present. + /// + /// Value of property or DefaultValue if property is not present. + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public string GetPropertyString(int PID, string DefaultValue = "") + { + if (IsPropertyDefined(PID)) + { + return GetString(Image.GetPropertyItem(PID).Value); + } + else + { + return DefaultValue; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets specified rational property + /// + /// Property ID + /// + /// Value of property or 0/1 if not present. + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public Rational GetPropertyRational(int PID) + { + if (IsPropertyDefined(PID)) + { + return GetRational(Image.GetPropertyItem(PID).Value); + } + else + { + Rational R; + R.Numerator = 0; + R.Denominator = 1; + return R; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Reads Int32 from EXIF bytearray. + /// + /// EXIF bytearray to process + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public static int GetInt32(byte[] B) + { + if (B.Length < 4) + throw new ArgumentException("Data too short (4 bytes expected)", "B"); + return B[3] << 24 | B[2] << 16 | B[1] << 8 | B[0]; + } + + /// ----------------------------------------------------------------------------- + /// + /// Reads Int16 from EXIF bytearray. + /// + /// EXIF bytearray to process + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public static short GetInt16(byte[] B) + { + if (B.Length < 2) + throw new ArgumentException("Data too short (2 bytes expected)", "B"); + return (short)(B[1] << 8 | B[0]); + } + + /// ----------------------------------------------------------------------------- + /// + /// Reads string from EXIF bytearray. + /// + /// EXIF bytearray to process + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public static string GetString(byte[] B) + { + string R = System.Text.Encoding.ASCII.GetString(B); + if (R.EndsWith(Constants.vbNullChar)) + R = R.Substring(0, R.Length - 1); + return R; + } + + /// ----------------------------------------------------------------------------- + /// + /// Reads rational from EXIF bytearray. + /// + /// EXIF bytearray to process + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public static Rational GetRational(byte[] B) + { + var R = new Rational(); + byte[] N = new byte[4], D = new byte[4]; + Array.Copy(B, 0, N, 0, 4); + Array.Copy(B, 4, D, 0, 4); + R.Denominator = GetInt32(D); + R.Numerator = GetInt32(N); + return R; + } + + /// ----------------------------------------------------------------------------- + /// + /// Disposes unmanaged resources of this class + /// + /// + /// + /// [altair] 10.9.2003 Created + /// + /// ----------------------------------------------------------------------------- + public void Dispose() + { + Image.Dispose(); + } + } +} \ No newline at end of file diff --git a/imagecatalog/ImageCatalog 2 - Backup.csproj b/imagecatalog/ImageCatalog 2 - Backup.csproj new file mode 100644 index 0000000..c77aca9 --- /dev/null +++ b/imagecatalog/ImageCatalog 2 - Backup.csproj @@ -0,0 +1,59 @@ + + + WinExe + net8.0-windows + enable + enable + true + False + 3.0.0.0 + 3.0.0.0 + 3.0.0-alpha.63+Branch.develop.Sha.39a9baf5c618d8d79c75b89e2d5c4020939697f2 + 3.0.0-alpha0063 + + + true + + + embedded + + + embedded + + + + MyApplicationCodeGenerator + Application.Designer.cs + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + + + + + + + + + + + + + all + + + All + + + + + True + True + Settings.settings + + + + \ No newline at end of file diff --git a/imagecatalog/ImageCatalog 2.csproj b/imagecatalog/ImageCatalog 2.csproj index c7bb517..3744a5c 100644 --- a/imagecatalog/ImageCatalog 2.csproj +++ b/imagecatalog/ImageCatalog 2.csproj @@ -1,44 +1,26 @@  + WinExe + net10.0-windows enable enable + true + true False - false + 3.1.2.0 + 3.1.2.0 + 3.1.2 + 3.1.2 ImageCatalog default - false - true - false - - - - net10.0-windows - WinExe - win-x64 Logo.ico - - net10.0 - Exe - - - WinExe - win-x64 - true - true - true - false - false + + win-x64 - true - - true - - - $([System.IO.Path]::GetFullPath('$(MSBuildThisFileDirectory)..\..\AIFotoONLUS\src\AIFotoONLUS.Core\bin\$(Configuration)\net10.0')) embedded @@ -46,17 +28,6 @@ embedded - - - - - - - - - - - SettingsSingleFileGenerator @@ -64,30 +35,31 @@ - - - + - - - - - - - - - - - - + + + + + + + + + all - + + + + $(Version) + $(Version) + $(Version) + True @@ -95,6 +67,11 @@ Settings.settings + + + MainForm.cs + + @@ -156,22 +133,4 @@ - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/imagecatalog/ImageCatalog 2.vbproj b/imagecatalog/ImageCatalog 2.vbproj new file mode 100644 index 0000000..b8cc359 --- /dev/null +++ b/imagecatalog/ImageCatalog 2.vbproj @@ -0,0 +1,347 @@ + + + + Local + 9.0.30729 + 2.0 + {8D3AA2B0-8F06-4A61-9CAD-B920EB1A8E9C} + Debug + AnyCPU + + + + + ImageCatalog + + + None + JScript + Grid + IE50 + false + WinExe + Binary + On + On + ImageCatalog + ImageCatalog.My.MyApplication + + + WindowsForms + 3.5 + + + v4.7.2 + true + My Project\app.manifest + + + SAK + SAK + SAK + SAK + + + http://localhost/ImageCatalog/ + true + Web + true + Foreground + 7 + Days + false + false + true + 0 + 1.8.0.%2a + false + true + + + bin\ + ImageCatalog.xml + 285212672 + + + + + true + true + true + false + false + false + false + 1 + 42016,42017,42018,42019,42032,42353,42354,42355 + full + AnyCPU + AllRules.ruleset + false + + + bin\ + ImageCatalog.xml + 285212672 + + + + + false + true + false + true + false + false + false + 1 + 42016,42017,42018,42019,42032,42353,42354,42355 + none + AnyCPU + AllRules.ruleset + false + + + true + true + true + bin\x64\Debug\ + 285212672 + ImageCatalog.xml + 1 + 42016,42017,42018,42019,42032,42353,42354,42355 + full + x64 + AllRules.ruleset + false + + + true + bin\x64\Release\ + 285212672 + ImageCatalog.xml + true + 1 + 42016,42017,42018,42019,42032,42353,42354,42355 + x64 + AllRules.ruleset + false + + + true + true + true + bin\x86\Debug\ + 285212672 + ImageCatalog.xml + 1 + 42016,42017,42018,42019,42032,42353,42354,42355 + full + x86 + bin\ImageCatalog.exe.CodeAnalysisLog.xml + true + GlobalSuppressions.vb + AllRules.ruleset + ;F:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets + true + ;F:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules + true + false + false + + + true + bin\x86\Release\ + 285212672 + ImageCatalog.xml + true + 1 + 42016,42017,42018,42019,42032,42353,42354,42355 + x86 + bin\ImageCatalog.exe.CodeAnalysisLog.xml + true + GlobalSuppressions.vb + AllRules.ruleset + ;F:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets + true + ;F:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules + true + false + + + + ..\packages\Ben.Demystifier.0.3.0\lib\net45\Ben.Demystifier.dll + + + + System + + + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + ..\packages\System.Collections.Immutable.5.0.0\lib\net461\System.Collections.Immutable.dll + + + 3.5 + True + + + System.Data + True + + + System.Drawing + True + + + ..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll + + + + ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + ..\packages\System.Reflection.Metadata.5.0.0\lib\net461\System.Reflection.Metadata.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + System.Windows.Forms + + + System.XML + + + + + + + + + + + + + + + Code + + + + + + Code + + + Form + + + + MainForm.vb + + + Form + + + + True + Application.myapp + + + True + True + Settings.settings + + + + + Code + + + Code + + + Form1.vb + Designer + + + MainForm.vb + + + MyApplicationCodeGenerator + Application.Designer.vb + + + + + + My + SettingsSingleFileGenerator + Settings.Designer.vb + + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 2.0 %28x86%29 + false + + + False + .NET Framework 3.0 %28x86%29 + false + + + False + .NET Framework 3.5 + true + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + + + + {44465926-240d-473f-90b8-786ba4384406} + CatalogVbLib + + + {aebfe9e3-277c-4a7b-8448-145d1b11998b} + MaddoShared + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/imagecatalog/Logo.png b/imagecatalog/Logo.png deleted file mode 100644 index 849b093..0000000 Binary files a/imagecatalog/Logo.png and /dev/null differ diff --git a/imagecatalog/MainForm.Designer.cs b/imagecatalog/MainForm.Designer.cs new file mode 100644 index 0000000..4584822 --- /dev/null +++ b/imagecatalog/MainForm.Designer.cs @@ -0,0 +1,2244 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.Runtime.CompilerServices; +using System.Windows.Forms; +using Microsoft.VisualBasic.CompilerServices; + +namespace ImageCatalog +{ + [DesignerGenerated()] + public partial class MainForm : Form + { + + // Form overrides dispose to clean up the component list. + [DebuggerNonUserCode()] + protected override void Dispose(bool disposing) + { + try + { + if (disposing && components is object) + { + components.Dispose(); + } + } + finally + { + base.Dispose(disposing); + } + } + + // Required by the Windows Form Designer + private System.ComponentModel.IContainer components; + + // NOTE: The following procedure is required by the Windows Form Designer + // It can be modified using the Windows Form Designer. + // Do not modify it using the code editor. + [DebuggerStepThrough()] + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + ProgressBar1 = new ProgressBar(); + CheckBox22 = new CheckBox(); + bindingSource1 = new BindingSource(components); + dataModelBindingSource = new BindingSource(components); + Label43 = new Label(); + TabControl1 = new TabControl(); + TabPage5 = new TabPage(); + groupBox12 = new GroupBox(); + rdbLibrary2 = new RadioButton(); + rdbLibrary1 = new RadioButton(); + GroupBox11 = new GroupBox(); + numericUpDown2 = new NumericUpDown(); + numericUpDown1 = new NumericUpDown(); + Panel3 = new Panel(); + rdbNuovoMetodo = new RadioButton(); + rdbVecchioMetodo = new RadioButton(); + Label8 = new Label(); + Label7 = new Label(); + GroupBox3 = new GroupBox(); + btnOpenDestFolder = new Button(); + btnOpenSourceFolder = new Button(); + chkAggiornaSottodirectory = new CheckBox(); + _Button3 = new Button(); + _Button2 = new Button(); + Label1 = new Label(); + Label2 = new Label(); + txtSorgente = new TextBox(); + txtDestinazione = new TextBox(); + GroupBox8 = new GroupBox(); + rdbNumFiles = new RadioButton(); + rdbNumProgressiva = new RadioButton(); + txtCifreContatore = new TextBox(); + Label34 = new Label(); + txtSuffissoCartelle = new TextBox(); + Label33 = new Label(); + Label31 = new Label(); + chkCreaSottocartelle = new CheckBox(); + txtFilePerCartella = new TextBox(); + Label32 = new Label(); + GroupBox7 = new GroupBox(); + chkSovrascriviFile = new CheckBox(); + chkRotazioneAutomatica = new CheckBox(); + chkForzaJpg = new CheckBox(); + TabPage3 = new TabPage(); + GroupBox10 = new GroupBox(); + Label42 = new Label(); + Label41 = new Label(); + TextBox31 = new TextBox(); + TextBox30 = new TextBox(); + GroupBox9 = new GroupBox(); + CheckBox17 = new CheckBox(); + CheckBox16 = new CheckBox(); + GroupBox5 = new GroupBox(); + TextBox34 = new TextBox(); + _Button8 = new Button(); + Label36 = new Label(); + TextBox25 = new TextBox(); + Label35 = new Label(); + ComboBox3 = new ComboBox(); + TextBox11 = new TextBox(); + Label12 = new Label(); + Label11 = new Label(); + CheckBox3 = new CheckBox(); + GroupBox4 = new GroupBox(); + Label40 = new Label(); + TextBox29 = new TextBox(); + TextBox18 = new TextBox(); + Label26 = new Label(); + DateTimePicker1 = new DateTimePicker(); + CheckBox8 = new CheckBox(); + TextBox9 = new TextBox(); + CheckBox7 = new CheckBox(); + Label4 = new Label(); + TextBox4 = new TextBox(); + Label9 = new Label(); + Label13 = new Label(); + ComboBox1 = new ComboBox(); + ComboBox2 = new ComboBox(); + Label14 = new Label(); + TextBox12 = new TextBox(); + Label15 = new Label(); + TabPage2 = new TabPage(); + GroupBox2 = new GroupBox(); + Label45 = new Label(); + TextBox32 = new TextBox(); + TextBox26 = new TextBox(); + Label37 = new Label(); + Label38 = new Label(); + TextBox27 = new TextBox(); + Label39 = new Label(); + TextBox28 = new TextBox(); + CheckBox15 = new CheckBox(); + TabPage1 = new TabPage(); + Panel1 = new Panel(); + _CheckBox18 = new CheckBox(); + _CheckBox4 = new CheckBox(); + _CheckBox12 = new CheckBox(); + GroupBox1 = new GroupBox(); + Label46 = new Label(); + TextBox33 = new TextBox(); + Label5 = new Label(); + TextBox5 = new TextBox(); + Label6 = new Label(); + TextBox6 = new TextBox(); + Label3 = new Label(); + TextBox3 = new TextBox(); + CheckBox1 = new CheckBox(); + comboThumbnailOption = new ComboBox(); + TabPage4 = new TabPage(); + GroupBox6 = new GroupBox(); + chkUseTransparentColor = new CheckBox(); + btnSetTransparency = new Button(); + _PictureBox1 = new PictureBox(); + ComboBox5 = new ComboBox(); + ComboBox4 = new ComboBox(); + TextBox19 = new TextBox(); + Label28 = new Label(); + CheckBox5 = new CheckBox(); + TextBox15 = new TextBox(); + TextBox14 = new TextBox(); + Label25 = new Label(); + TextBox16 = new TextBox(); + Label24 = new Label(); + Label22 = new Label(); + Label23 = new Label(); + _Button4 = new Button(); + TextBox10 = new TextBox(); + Label29 = new Label(); + PictureBox3 = new PictureBox(); + versionLabel = new Label(); + _Button7 = new Button(); + _Button5 = new Button(); + Label20 = new Label(); + Label19 = new Label(); + Label18 = new Label(); + lblFotoTotaliNum = new Label(); + Label10 = new Label(); + _Button6 = new Button(); + _btnCreaCatalogoAsync = new Button(); + timer1 = new System.Windows.Forms.Timer(components); + dataModelBindingSource1 = new BindingSource(components); + colorDialog1 = new ColorDialog(); + label16 = new Label(); + ((System.ComponentModel.ISupportInitialize)bindingSource1).BeginInit(); + ((System.ComponentModel.ISupportInitialize)dataModelBindingSource).BeginInit(); + TabControl1.SuspendLayout(); + TabPage5.SuspendLayout(); + groupBox12.SuspendLayout(); + GroupBox11.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)numericUpDown2).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDown1).BeginInit(); + Panel3.SuspendLayout(); + GroupBox3.SuspendLayout(); + GroupBox8.SuspendLayout(); + GroupBox7.SuspendLayout(); + TabPage3.SuspendLayout(); + GroupBox10.SuspendLayout(); + GroupBox9.SuspendLayout(); + GroupBox5.SuspendLayout(); + GroupBox4.SuspendLayout(); + TabPage2.SuspendLayout(); + GroupBox2.SuspendLayout(); + TabPage1.SuspendLayout(); + Panel1.SuspendLayout(); + GroupBox1.SuspendLayout(); + TabPage4.SuspendLayout(); + GroupBox6.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)_PictureBox1).BeginInit(); + ((System.ComponentModel.ISupportInitialize)PictureBox3).BeginInit(); + ((System.ComponentModel.ISupportInitialize)dataModelBindingSource1).BeginInit(); + SuspendLayout(); + // + // ProgressBar1 + // + ProgressBar1.Location = new Point(1078, 561); + ProgressBar1.Margin = new Padding(6, 8, 6, 8); + ProgressBar1.Name = "ProgressBar1"; + ProgressBar1.Size = new Size(384, 52); + ProgressBar1.TabIndex = 67; + // + // CheckBox22 + // + CheckBox22.AutoSize = true; + CheckBox22.DataBindings.Add(new Binding("Checked", bindingSource1, "ShutdownSystem", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox22.Location = new Point(1078, 827); + CheckBox22.Margin = new Padding(6, 8, 6, 8); + CheckBox22.Name = "CheckBox22"; + CheckBox22.Size = new Size(197, 34); + CheckBox22.TabIndex = 65; + CheckBox22.Text = "Arresta il sistema"; + CheckBox22.UseVisualStyleBackColor = true; + // + // bindingSource1 + // + bindingSource1.DataSource = dataModelBindingSource; + // + // dataModelBindingSource + // + dataModelBindingSource.DataSource = typeof(ImageCatalog_2.DataModel); + // + // Label43 + // + Label43.AutoSize = true; + Label43.DataBindings.Add(new Binding("Text", bindingSource1, "SpeedCounter", true)); + Label43.Location = new Point(1074, 725); + Label43.Margin = new Padding(6, 0, 6, 0); + Label43.Name = "Label43"; + Label43.Size = new Size(46, 30); + Label43.TabIndex = 64; + Label43.Text = "000"; + Label43.TextAlign = ContentAlignment.MiddleLeft; + // + // TabControl1 + // + TabControl1.Controls.Add(TabPage5); + TabControl1.Controls.Add(TabPage3); + TabControl1.Controls.Add(TabPage2); + TabControl1.Controls.Add(TabPage1); + TabControl1.Controls.Add(TabPage4); + TabControl1.DataBindings.Add(new Binding("Enabled", bindingSource1, "UiEnabled", true)); + TabControl1.Location = new Point(24, 22); + TabControl1.Margin = new Padding(6, 8, 6, 8); + TabControl1.Name = "TabControl1"; + TabControl1.SelectedIndex = 0; + TabControl1.Size = new Size(1042, 870); + TabControl1.TabIndex = 63; + // + // TabPage5 + // + TabPage5.Controls.Add(groupBox12); + TabPage5.Controls.Add(GroupBox11); + TabPage5.Controls.Add(GroupBox3); + TabPage5.Controls.Add(GroupBox8); + TabPage5.Controls.Add(GroupBox7); + TabPage5.Location = new Point(4, 39); + TabPage5.Margin = new Padding(6, 8, 6, 8); + TabPage5.Name = "TabPage5"; + TabPage5.Padding = new Padding(6, 8, 6, 8); + TabPage5.Size = new Size(1034, 827); + TabPage5.TabIndex = 4; + TabPage5.Text = "Generale"; + TabPage5.UseVisualStyleBackColor = true; + // + // groupBox12 + // + groupBox12.Controls.Add(rdbLibrary2); + groupBox12.Controls.Add(rdbLibrary1); + groupBox12.Location = new Point(405, 625); + groupBox12.Name = "groupBox12"; + groupBox12.Size = new Size(350, 175); + groupBox12.TabIndex = 49; + groupBox12.TabStop = false; + groupBox12.Text = "Libreria Manipolazione Grafica"; + // + // rdbLibrary2 + // + rdbLibrary2.AutoSize = true; + rdbLibrary2.DataBindings.Add(new Binding("Checked", bindingSource1, "UseImageSharp", true, DataSourceUpdateMode.OnPropertyChanged)); + rdbLibrary2.Location = new Point(12, 77); + rdbLibrary2.Name = "rdbLibrary2"; + rdbLibrary2.Size = new Size(149, 34); + rdbLibrary2.TabIndex = 1; + rdbLibrary2.TabStop = true; + rdbLibrary2.Text = "ImageSharp"; + rdbLibrary2.UseVisualStyleBackColor = true; + // + // rdbLibrary1 + // + rdbLibrary1.AutoSize = true; + rdbLibrary1.DataBindings.Add(new Binding("Checked", bindingSource1, "UseSystemGraphics", true, DataSourceUpdateMode.OnPropertyChanged)); + rdbLibrary1.Location = new Point(12, 37); + rdbLibrary1.Name = "rdbLibrary1"; + rdbLibrary1.Size = new Size(188, 34); + rdbLibrary1.TabIndex = 0; + rdbLibrary1.TabStop = true; + rdbLibrary1.Text = "System.Graphics"; + rdbLibrary1.UseVisualStyleBackColor = true; + // + // GroupBox11 + // + GroupBox11.Controls.Add(numericUpDown2); + GroupBox11.Controls.Add(numericUpDown1); + GroupBox11.Controls.Add(Panel3); + GroupBox11.Controls.Add(Label8); + GroupBox11.Controls.Add(Label7); + GroupBox11.Location = new Point(14, 483); + GroupBox11.Margin = new Padding(6, 8, 6, 8); + GroupBox11.Name = "GroupBox11"; + GroupBox11.Padding = new Padding(6, 8, 6, 8); + GroupBox11.Size = new Size(382, 305); + GroupBox11.TabIndex = 48; + GroupBox11.TabStop = false; + GroupBox11.Text = "Avanzate (ATTENZIONE)"; + // + // numericUpDown2 + // + numericUpDown2.DataBindings.Add(new Binding("Value", bindingSource1, "ThreadsCount", true, DataSourceUpdateMode.OnPropertyChanged)); + numericUpDown2.Location = new Point(14, 111); + numericUpDown2.Maximum = new decimal(new int[] { 10000, 0, 0, 0 }); + numericUpDown2.Name = "numericUpDown2"; + numericUpDown2.Size = new Size(105, 35); + numericUpDown2.TabIndex = 52; + // + // numericUpDown1 + // + numericUpDown1.DataBindings.Add(new Binding("Value", bindingSource1, "ChunkSize", true, DataSourceUpdateMode.OnPropertyChanged)); + numericUpDown1.Location = new Point(14, 58); + numericUpDown1.Maximum = new decimal(new int[] { 10000, 0, 0, 0 }); + numericUpDown1.Name = "numericUpDown1"; + numericUpDown1.Size = new Size(105, 35); + numericUpDown1.TabIndex = 51; + // + // Panel3 + // + Panel3.Controls.Add(rdbNuovoMetodo); + Panel3.Controls.Add(rdbVecchioMetodo); + Panel3.Location = new Point(14, 168); + Panel3.Margin = new Padding(6, 8, 6, 8); + Panel3.Name = "Panel3"; + Panel3.Size = new Size(355, 123); + Panel3.TabIndex = 4; + // + // rdbNuovoMetodo + // + rdbNuovoMetodo.AutoSize = true; + rdbNuovoMetodo.Checked = true; + rdbNuovoMetodo.DataBindings.Add(new Binding("Checked", bindingSource1, "UseParallelProcessing", true, DataSourceUpdateMode.OnPropertyChanged)); + rdbNuovoMetodo.Location = new Point(17, 65); + rdbNuovoMetodo.Margin = new Padding(6, 8, 6, 8); + rdbNuovoMetodo.Name = "rdbNuovoMetodo"; + rdbNuovoMetodo.Size = new Size(116, 34); + rdbNuovoMetodo.TabIndex = 1; + rdbNuovoMetodo.TabStop = true; + rdbNuovoMetodo.Text = "Parallelo"; + rdbNuovoMetodo.UseVisualStyleBackColor = true; + // + // rdbVecchioMetodo + // + rdbVecchioMetodo.AutoSize = true; + rdbVecchioMetodo.DataBindings.Add(new Binding("Checked", bindingSource1, "UseSequentialProcessing", true, DataSourceUpdateMode.OnPropertyChanged)); + rdbVecchioMetodo.Location = new Point(17, 9); + rdbVecchioMetodo.Margin = new Padding(6, 8, 6, 8); + rdbVecchioMetodo.Name = "rdbVecchioMetodo"; + rdbVecchioMetodo.Size = new Size(105, 34); + rdbVecchioMetodo.TabIndex = 0; + rdbVecchioMetodo.Text = "Lineare"; + rdbVecchioMetodo.UseVisualStyleBackColor = true; + // + // Label8 + // + Label8.AutoSize = true; + Label8.Location = new Point(127, 60); + Label8.Margin = new Padding(6, 0, 6, 0); + Label8.Name = "Label8"; + Label8.Size = new Size(215, 30); + Label8.TabIndex = 3; + Label8.Text = "Chunk Size (0 = MAX)"; + // + // Label7 + // + Label7.AutoSize = true; + Label7.Location = new Point(127, 112); + Label7.Margin = new Padding(6, 0, 6, 0); + Label7.Name = "Label7"; + Label7.Size = new Size(186, 30); + Label7.TabIndex = 1; + Label7.Text = "Threads (0 = Auto)"; + // + // GroupBox3 + // + GroupBox3.Controls.Add(btnOpenDestFolder); + GroupBox3.Controls.Add(btnOpenSourceFolder); + GroupBox3.Controls.Add(chkAggiornaSottodirectory); + GroupBox3.Controls.Add(_Button3); + GroupBox3.Controls.Add(_Button2); + GroupBox3.Controls.Add(Label1); + GroupBox3.Controls.Add(Label2); + GroupBox3.Controls.Add(txtSorgente); + GroupBox3.Controls.Add(txtDestinazione); + GroupBox3.ForeColor = Color.FromArgb(0, 0, 192); + GroupBox3.Location = new Point(12, 13); + GroupBox3.Margin = new Padding(6, 8, 6, 8); + GroupBox3.Name = "GroupBox3"; + GroupBox3.Padding = new Padding(6, 8, 6, 8); + GroupBox3.Size = new Size(991, 232); + GroupBox3.TabIndex = 35; + GroupBox3.TabStop = false; + GroupBox3.Text = "Directory"; + // + // btnOpenDestFolder + // + btnOpenDestFolder.Location = new Point(939, 97); + btnOpenDestFolder.Margin = new Padding(6, 8, 6, 8); + btnOpenDestFolder.Name = "btnOpenDestFolder"; + btnOpenDestFolder.Size = new Size(48, 35); + btnOpenDestFolder.TabIndex = 27; + btnOpenDestFolder.Text = "Apri"; + // + // btnOpenSourceFolder + // + btnOpenSourceFolder.Location = new Point(939, 38); + btnOpenSourceFolder.Margin = new Padding(6, 8, 6, 8); + btnOpenSourceFolder.Name = "btnOpenSourceFolder"; + btnOpenSourceFolder.Size = new Size(48, 35); + btnOpenSourceFolder.TabIndex = 26; + btnOpenSourceFolder.Text = "Apri"; + // + // chkAggiornaSottodirectory + // + chkAggiornaSottodirectory.DataBindings.Add(new Binding("Checked", bindingSource1, "UpdateSubdirectories", true, DataSourceUpdateMode.OnPropertyChanged)); + chkAggiornaSottodirectory.ForeColor = Color.Black; + chkAggiornaSottodirectory.Location = new Point(161, 147); + chkAggiornaSottodirectory.Margin = new Padding(6, 8, 6, 8); + chkAggiornaSottodirectory.Name = "chkAggiornaSottodirectory"; + chkAggiornaSottodirectory.Size = new Size(475, 55); + chkAggiornaSottodirectory.TabIndex = 25; + chkAggiornaSottodirectory.Text = "aggiorna le sottodirectory"; + // + // _Button3 + // + _Button3.Location = new Point(879, 96); + _Button3.Margin = new Padding(6, 8, 6, 8); + _Button3.Name = "_Button3"; + _Button3.Size = new Size(48, 36); + _Button3.TabIndex = 6; + _Button3.Text = "..."; + // + // _Button2 + // + _Button2.Location = new Point(879, 38); + _Button2.Margin = new Padding(6, 8, 6, 8); + _Button2.Name = "_Button2"; + _Button2.Size = new Size(48, 35); + _Button2.TabIndex = 5; + _Button2.Text = "..."; + // + // Label1 + // + Label1.AutoSize = true; + Label1.ForeColor = Color.Black; + Label1.Location = new Point(12, 43); + Label1.Margin = new Padding(6, 0, 6, 0); + Label1.Name = "Label1"; + Label1.Size = new Size(96, 30); + Label1.TabIndex = 3; + Label1.Text = "Sorgente"; + // + // Label2 + // + Label2.AutoSize = true; + Label2.ForeColor = Color.Black; + Label2.Location = new Point(12, 96); + Label2.Margin = new Padding(6, 0, 6, 0); + Label2.Name = "Label2"; + Label2.Size = new Size(133, 30); + Label2.TabIndex = 4; + Label2.Text = "Destinazione"; + // + // txtSorgente + // + txtSorgente.DataBindings.Add(new Binding("Text", bindingSource1, "SourcePath", true, DataSourceUpdateMode.OnPropertyChanged)); + txtSorgente.Location = new Point(161, 38); + txtSorgente.Margin = new Padding(6, 8, 6, 8); + txtSorgente.Name = "txtSorgente"; + txtSorgente.Size = new Size(706, 35); + txtSorgente.TabIndex = 0; + // + // txtDestinazione + // + txtDestinazione.DataBindings.Add(new Binding("Text", bindingSource1, "DestinationPath", true, DataSourceUpdateMode.OnPropertyChanged)); + txtDestinazione.Location = new Point(161, 93); + txtDestinazione.Margin = new Padding(6, 8, 6, 8); + txtDestinazione.Name = "txtDestinazione"; + txtDestinazione.Size = new Size(706, 35); + txtDestinazione.TabIndex = 1; + txtDestinazione.Text = "TextBox2"; + // + // GroupBox8 + // + GroupBox8.Controls.Add(rdbNumFiles); + GroupBox8.Controls.Add(rdbNumProgressiva); + GroupBox8.Controls.Add(txtCifreContatore); + GroupBox8.Controls.Add(Label34); + GroupBox8.Controls.Add(txtSuffissoCartelle); + GroupBox8.Controls.Add(Label33); + GroupBox8.Controls.Add(Label31); + GroupBox8.Controls.Add(chkCreaSottocartelle); + GroupBox8.Controls.Add(txtFilePerCartella); + GroupBox8.Controls.Add(Label32); + GroupBox8.ForeColor = Color.FromArgb(0, 0, 192); + GroupBox8.Location = new Point(408, 261); + GroupBox8.Margin = new Padding(6, 8, 6, 8); + GroupBox8.Name = "GroupBox8"; + GroupBox8.Padding = new Padding(6, 8, 6, 8); + GroupBox8.Size = new Size(384, 351); + GroupBox8.TabIndex = 47; + GroupBox8.TabStop = false; + GroupBox8.Text = "Sottocartelle"; + // + // rdbNumFiles + // + rdbNumFiles.DataBindings.Add(new Binding("Checked", bindingSource1, "UseFileNumbering", true, DataSourceUpdateMode.OnPropertyChanged)); + rdbNumFiles.ForeColor = Color.Black; + rdbNumFiles.Location = new Point(65, 295); + rdbNumFiles.Margin = new Padding(6, 8, 6, 8); + rdbNumFiles.Name = "rdbNumFiles"; + rdbNumFiles.Size = new Size(271, 38); + rdbNumFiles.TabIndex = 38; + rdbNumFiles.Text = "Numerazione files"; + // + // rdbNumProgressiva + // + rdbNumProgressiva.Checked = true; + rdbNumProgressiva.DataBindings.Add(new Binding("Checked", bindingSource1, "UseProgressiveNumbering", true, DataSourceUpdateMode.OnPropertyChanged)); + rdbNumProgressiva.ForeColor = Color.Black; + rdbNumProgressiva.Location = new Point(65, 258); + rdbNumProgressiva.Margin = new Padding(6, 8, 6, 8); + rdbNumProgressiva.Name = "rdbNumProgressiva"; + rdbNumProgressiva.Size = new Size(305, 38); + rdbNumProgressiva.TabIndex = 37; + rdbNumProgressiva.TabStop = true; + rdbNumProgressiva.Text = "Numerazione progressiva"; + // + // txtCifreContatore + // + txtCifreContatore.DataBindings.Add(new Binding("Text", bindingSource1, "CounterDigits", true, DataSourceUpdateMode.OnPropertyChanged)); + txtCifreContatore.Location = new Point(257, 202); + txtCifreContatore.Margin = new Padding(6, 8, 6, 8); + txtCifreContatore.Name = "txtCifreContatore"; + txtCifreContatore.Size = new Size(107, 35); + txtCifreContatore.TabIndex = 34; + txtCifreContatore.Text = "4"; + // + // Label34 + // + Label34.ForeColor = Color.Black; + Label34.Location = new Point(17, 202); + Label34.Margin = new Padding(6, 0, 6, 0); + Label34.Name = "Label34"; + Label34.Size = new Size(223, 38); + Label34.TabIndex = 33; + Label34.Text = "Num. cifre contatore"; + Label34.TextAlign = ContentAlignment.MiddleRight; + // + // txtSuffissoCartelle + // + txtSuffissoCartelle.DataBindings.Add(new Binding("Text", bindingSource1, "FolderSuffix", true, DataSourceUpdateMode.OnPropertyChanged)); + txtSuffissoCartelle.Location = new Point(113, 147); + txtSuffissoCartelle.Margin = new Padding(6, 8, 6, 8); + txtSuffissoCartelle.Name = "txtSuffissoCartelle"; + txtSuffissoCartelle.Size = new Size(251, 35); + txtSuffissoCartelle.TabIndex = 32; + txtSuffissoCartelle.Text = "TextBox20"; + // + // Label33 + // + Label33.ForeColor = Color.Black; + Label33.Location = new Point(12, 155); + Label33.Margin = new Padding(6, 0, 6, 0); + Label33.Name = "Label33"; + Label33.Size = new Size(96, 38); + Label33.TabIndex = 31; + Label33.Text = "Suffisso"; + // + // Label31 + // + Label31.ForeColor = Color.Black; + Label31.Location = new Point(48, 93); + Label31.Margin = new Padding(6, 0, 6, 0); + Label31.Name = "Label31"; + Label31.Size = new Size(65, 38); + Label31.TabIndex = 30; + Label31.Text = "ogni"; + // + // chkCreaSottocartelle + // + chkCreaSottocartelle.DataBindings.Add(new Binding("Checked", bindingSource1, "CreateSubfolders", true, DataSourceUpdateMode.OnPropertyChanged)); + chkCreaSottocartelle.ForeColor = Color.Black; + chkCreaSottocartelle.Location = new Point(113, 38); + chkCreaSottocartelle.Margin = new Padding(6, 8, 6, 8); + chkCreaSottocartelle.Name = "chkCreaSottocartelle"; + chkCreaSottocartelle.Size = new Size(223, 38); + chkCreaSottocartelle.TabIndex = 29; + chkCreaSottocartelle.Text = "crea sottocartelle"; + // + // txtFilePerCartella + // + txtFilePerCartella.DataBindings.Add(new Binding("Text", bindingSource1, "FilesPerFolder", true, DataSourceUpdateMode.OnPropertyChanged)); + txtFilePerCartella.Location = new Point(113, 93); + txtFilePerCartella.Margin = new Padding(6, 8, 6, 8); + txtFilePerCartella.Name = "txtFilePerCartella"; + txtFilePerCartella.Size = new Size(124, 35); + txtFilePerCartella.TabIndex = 27; + txtFilePerCartella.Text = "99"; + // + // Label32 + // + Label32.ForeColor = Color.Black; + Label32.Location = new Point(257, 93); + Label32.Margin = new Padding(6, 0, 6, 0); + Label32.Name = "Label32"; + Label32.Size = new Size(48, 38); + Label32.TabIndex = 28; + Label32.Text = "file"; + // + // GroupBox7 + // + GroupBox7.Controls.Add(chkSovrascriviFile); + GroupBox7.Controls.Add(chkRotazioneAutomatica); + GroupBox7.Controls.Add(chkForzaJpg); + GroupBox7.ForeColor = Color.FromArgb(0, 0, 192); + GroupBox7.Location = new Point(12, 261); + GroupBox7.Margin = new Padding(6, 8, 6, 8); + GroupBox7.Name = "GroupBox7"; + GroupBox7.Padding = new Padding(6, 8, 6, 8); + GroupBox7.Size = new Size(384, 202); + GroupBox7.TabIndex = 45; + GroupBox7.TabStop = false; + GroupBox7.Text = "Generale"; + // + // chkSovrascriviFile + // + chkSovrascriviFile.AutoSize = true; + chkSovrascriviFile.DataBindings.Add(new Binding("Checked", bindingSource1, "OverwriteImages", true, DataSourceUpdateMode.OnPropertyChanged)); + chkSovrascriviFile.Location = new Point(31, 141); + chkSovrascriviFile.Margin = new Padding(6, 8, 6, 8); + chkSovrascriviFile.Name = "chkSovrascriviFile"; + chkSovrascriviFile.Size = new Size(170, 34); + chkSovrascriviFile.TabIndex = 2; + chkSovrascriviFile.Text = "Sovrascrivi file"; + chkSovrascriviFile.UseVisualStyleBackColor = true; + // + // chkRotazioneAutomatica + // + chkRotazioneAutomatica.DataBindings.Add(new Binding("Checked", bindingSource1, "AutomaticRotation", true, DataSourceUpdateMode.OnPropertyChanged)); + chkRotazioneAutomatica.ForeColor = Color.Black; + chkRotazioneAutomatica.Location = new Point(31, 90); + chkRotazioneAutomatica.Margin = new Padding(6, 8, 6, 8); + chkRotazioneAutomatica.Name = "chkRotazioneAutomatica"; + chkRotazioneAutomatica.Size = new Size(271, 38); + chkRotazioneAutomatica.TabIndex = 1; + chkRotazioneAutomatica.Text = "Rotazione automatica"; + // + // chkForzaJpg + // + chkForzaJpg.Checked = true; + chkForzaJpg.CheckState = CheckState.Checked; + chkForzaJpg.DataBindings.Add(new Binding("Checked", bindingSource1, "ForceJpeg", true, DataSourceUpdateMode.OnPropertyChanged)); + chkForzaJpg.ForeColor = Color.Black; + chkForzaJpg.Location = new Point(31, 42); + chkForzaJpg.Margin = new Padding(6, 8, 6, 8); + chkForzaJpg.Name = "chkForzaJpg"; + chkForzaJpg.Size = new Size(161, 38); + chkForzaJpg.TabIndex = 0; + chkForzaJpg.Text = "Forza Jpg"; + // + // TabPage3 + // + TabPage3.Controls.Add(GroupBox10); + TabPage3.Controls.Add(GroupBox9); + TabPage3.Controls.Add(GroupBox5); + TabPage3.Controls.Add(GroupBox4); + TabPage3.Location = new Point(4, 39); + TabPage3.Margin = new Padding(6, 8, 6, 8); + TabPage3.Name = "TabPage3"; + TabPage3.Padding = new Padding(6, 8, 6, 8); + TabPage3.Size = new Size(1034, 827); + TabPage3.TabIndex = 2; + TabPage3.Text = "Testo"; + TabPage3.UseVisualStyleBackColor = true; + // + // GroupBox10 + // + GroupBox10.Controls.Add(Label42); + GroupBox10.Controls.Add(Label41); + GroupBox10.Controls.Add(TextBox31); + GroupBox10.Controls.Add(TextBox30); + GroupBox10.Location = new Point(631, 180); + GroupBox10.Margin = new Padding(6, 8, 6, 8); + GroupBox10.Name = "GroupBox10"; + GroupBox10.Padding = new Padding(6, 8, 6, 8); + GroupBox10.Size = new Size(372, 168); + GroupBox10.TabIndex = 39; + GroupBox10.TabStop = false; + GroupBox10.Text = "Testo foto verticali"; + // + // Label42 + // + Label42.AutoSize = true; + Label42.Location = new Point(14, 107); + Label42.Margin = new Padding(6, 0, 6, 0); + Label42.Name = "Label42"; + Label42.Size = new Size(90, 30); + Label42.TabIndex = 3; + Label42.Text = "Margine"; + // + // Label41 + // + Label41.AutoSize = true; + Label41.Location = new Point(14, 57); + Label41.Margin = new Padding(6, 0, 6, 0); + Label41.Name = "Label41"; + Label41.Size = new Size(214, 30); + Label41.TabIndex = 2; + Label41.Text = "Dimensione Carattere"; + // + // TextBox31 + // + TextBox31.DataBindings.Add(new Binding("Text", bindingSource1, "VerticalTextMargin", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox31.Location = new Point(262, 107); + TextBox31.Margin = new Padding(6, 8, 6, 8); + TextBox31.Name = "TextBox31"; + TextBox31.Size = new Size(74, 35); + TextBox31.TabIndex = 1; + // + // TextBox30 + // + TextBox30.DataBindings.Add(new Binding("Text", bindingSource1, "VerticalTextSize", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox30.Location = new Point(262, 51); + TextBox30.Margin = new Padding(6, 8, 6, 8); + TextBox30.Name = "TextBox30"; + TextBox30.Size = new Size(74, 35); + TextBox30.TabIndex = 0; + // + // GroupBox9 + // + GroupBox9.Controls.Add(CheckBox17); + GroupBox9.Controls.Add(CheckBox16); + GroupBox9.Location = new Point(631, 72); + GroupBox9.Margin = new Padding(6, 8, 6, 8); + GroupBox9.Name = "GroupBox9"; + GroupBox9.Padding = new Padding(6, 8, 6, 8); + GroupBox9.Size = new Size(372, 103); + GroupBox9.TabIndex = 38; + GroupBox9.TabStop = false; + GroupBox9.Text = "Slide show"; + // + // CheckBox17 + // + CheckBox17.AutoSize = true; + CheckBox17.DataBindings.Add(new Binding("Checked", bindingSource1, "ShowPhotoNumber", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox17.Location = new Point(192, 42); + CheckBox17.Margin = new Padding(6, 8, 6, 8); + CheckBox17.Name = "CheckBox17"; + CheckBox17.Size = new Size(159, 34); + CheckBox17.TabIndex = 1; + CheckBox17.Text = "Numero foto"; + CheckBox17.UseVisualStyleBackColor = true; + // + // CheckBox16 + // + CheckBox16.AutoSize = true; + CheckBox16.DataBindings.Add(new Binding("Checked", bindingSource1, "ShowDate", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox16.Location = new Point(12, 43); + CheckBox16.Margin = new Padding(6, 8, 6, 8); + CheckBox16.Name = "CheckBox16"; + CheckBox16.Size = new Size(83, 34); + CheckBox16.TabIndex = 0; + CheckBox16.Text = "Data"; + CheckBox16.UseVisualStyleBackColor = true; + // + // GroupBox5 + // + GroupBox5.Controls.Add(TextBox34); + GroupBox5.Controls.Add(_Button8); + GroupBox5.Controls.Add(Label36); + GroupBox5.Controls.Add(TextBox25); + GroupBox5.Controls.Add(Label35); + GroupBox5.Controls.Add(ComboBox3); + GroupBox5.Controls.Add(TextBox11); + GroupBox5.Controls.Add(Label12); + GroupBox5.Controls.Add(Label11); + GroupBox5.Controls.Add(CheckBox3); + GroupBox5.ForeColor = Color.FromArgb(0, 0, 192); + GroupBox5.Location = new Point(12, 72); + GroupBox5.Margin = new Padding(6, 8, 6, 8); + GroupBox5.Name = "GroupBox5"; + GroupBox5.Padding = new Padding(6, 8, 6, 8); + GroupBox5.Size = new Size(607, 278); + GroupBox5.TabIndex = 37; + GroupBox5.TabStop = false; + GroupBox5.Text = "Carattere"; + // + // TextBox34 + // + TextBox34.DataBindings.Add(new Binding("Text", bindingSource1, "TextColorRGB", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox34.Location = new Point(319, 210); + TextBox34.Margin = new Padding(6, 8, 6, 8); + TextBox34.Name = "TextBox34"; + TextBox34.Size = new Size(107, 35); + TextBox34.TabIndex = 36; + TextBox34.TextAlign = HorizontalAlignment.Right; + // + // _Button8 + // + _Button8.ForeColor = Color.Black; + _Button8.Location = new Point(444, 205); + _Button8.Margin = new Padding(6, 8, 6, 8); + _Button8.Name = "_Button8"; + _Button8.Size = new Size(149, 55); + _Button8.TabIndex = 35; + _Button8.Text = "Scegli..."; + // + // Label36 + // + Label36.ForeColor = Color.Black; + Label36.Location = new Point(17, 138); + Label36.Margin = new Padding(6, 0, 6, 0); + Label36.Name = "Label36"; + Label36.Size = new Size(240, 43); + Label36.TabIndex = 34; + Label36.Text = "Dimensione miniatura"; + Label36.TextAlign = ContentAlignment.MiddleLeft; + // + // TextBox25 + // + TextBox25.DataBindings.Add(new Binding("Text", bindingSource1, "FontSizeThumbnail", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox25.Location = new Point(319, 137); + TextBox25.Margin = new Padding(6, 8, 6, 8); + TextBox25.Name = "TextBox25"; + TextBox25.Size = new Size(107, 35); + TextBox25.TabIndex = 33; + TextBox25.Text = "TextBox25"; + // + // Label35 + // + Label35.ForeColor = Color.Black; + Label35.Location = new Point(17, 215); + Label35.Margin = new Padding(6, 0, 6, 0); + Label35.Name = "Label35"; + Label35.Size = new Size(144, 38); + Label35.TabIndex = 32; + Label35.Text = "Colore RGB"; + Label35.TextAlign = ContentAlignment.MiddleLeft; + // + // ComboBox3 + // + ComboBox3.DataBindings.Add(new Binding("Text", bindingSource1, "FontName", true, DataSourceUpdateMode.OnPropertyChanged)); + ComboBox3.Location = new Point(192, 18); + ComboBox3.Margin = new Padding(6, 8, 6, 8); + ComboBox3.Name = "ComboBox3"; + ComboBox3.Size = new Size(237, 38); + ComboBox3.TabIndex = 28; + ComboBox3.Text = "ComboBox3"; + // + // TextBox11 + // + TextBox11.DataBindings.Add(new Binding("Text", bindingSource1, "FontSize", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox11.Location = new Point(319, 81); + TextBox11.Margin = new Padding(6, 8, 6, 8); + TextBox11.Name = "TextBox11"; + TextBox11.Size = new Size(107, 35); + TextBox11.TabIndex = 27; + TextBox11.Text = "TextBox11"; + // + // Label12 + // + Label12.AutoSize = true; + Label12.ForeColor = Color.Black; + Label12.Location = new Point(17, 87); + Label12.Margin = new Padding(6, 0, 6, 0); + Label12.Name = "Label12"; + Label12.Size = new Size(123, 30); + Label12.TabIndex = 26; + Label12.Text = "Dimensione"; + Label12.TextAlign = ContentAlignment.MiddleLeft; + // + // Label11 + // + Label11.AutoSize = true; + Label11.ForeColor = Color.Black; + Label11.Location = new Point(113, 18); + Label11.Margin = new Padding(6, 0, 6, 0); + Label11.Name = "Label11"; + Label11.Size = new Size(54, 30); + Label11.TabIndex = 22; + Label11.Text = "Font"; + // + // CheckBox3 + // + CheckBox3.DataBindings.Add(new Binding("Checked", bindingSource1, "FontBold", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox3.ForeColor = Color.Black; + CheckBox3.Location = new Point(449, 18); + CheckBox3.Margin = new Padding(6, 8, 6, 8); + CheckBox3.Name = "CheckBox3"; + CheckBox3.Size = new Size(144, 55); + CheckBox3.TabIndex = 24; + CheckBox3.Text = "Grassetto"; + // + // GroupBox4 + // + GroupBox4.Controls.Add(Label40); + GroupBox4.Controls.Add(TextBox29); + GroupBox4.Controls.Add(TextBox18); + GroupBox4.Controls.Add(Label26); + GroupBox4.Controls.Add(DateTimePicker1); + GroupBox4.Controls.Add(CheckBox8); + GroupBox4.Controls.Add(TextBox9); + GroupBox4.Controls.Add(CheckBox7); + GroupBox4.Controls.Add(Label4); + GroupBox4.Controls.Add(TextBox4); + GroupBox4.Controls.Add(Label9); + GroupBox4.Controls.Add(Label13); + GroupBox4.Controls.Add(ComboBox1); + GroupBox4.Controls.Add(ComboBox2); + GroupBox4.Controls.Add(Label14); + GroupBox4.Controls.Add(TextBox12); + GroupBox4.Controls.Add(Label15); + GroupBox4.ForeColor = Color.FromArgb(0, 0, 192); + GroupBox4.Location = new Point(12, 363); + GroupBox4.Margin = new Padding(6, 8, 6, 8); + GroupBox4.Name = "GroupBox4"; + GroupBox4.Padding = new Padding(6, 8, 6, 8); + GroupBox4.Size = new Size(991, 429); + GroupBox4.TabIndex = 36; + GroupBox4.TabStop = false; + GroupBox4.Text = "Testo da applicare"; + // + // Label40 + // + Label40.AutoSize = true; + Label40.Location = new Point(17, 120); + Label40.Margin = new Padding(6, 0, 6, 0); + Label40.Name = "Label40"; + Label40.Size = new Size(92, 30); + Label40.TabIndex = 40; + Label40.Text = "Verticale"; + // + // TextBox29 + // + TextBox29.DataBindings.Add(new Binding("Text", bindingSource1, "VerticalText", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox29.Location = new Point(144, 112); + TextBox29.Margin = new Padding(6, 8, 6, 8); + TextBox29.Multiline = true; + TextBox29.Name = "TextBox29"; + TextBox29.Size = new Size(813, 97); + TextBox29.TabIndex = 39; + // + // TextBox18 + // + TextBox18.DataBindings.Add(new Binding("Text", bindingSource1, "TimeLabel", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox18.Location = new Point(463, 360); + TextBox18.Margin = new Padding(6, 8, 6, 8); + TextBox18.Name = "TextBox18"; + TextBox18.Size = new Size(196, 35); + TextBox18.TabIndex = 38; + // + // Label26 + // + Label26.AutoSize = true; + Label26.ForeColor = Color.Black; + Label26.Location = new Point(689, 360); + Label26.Margin = new Padding(6, 0, 6, 0); + Label26.Name = "Label26"; + Label26.Size = new Size(94, 30); + Label26.TabIndex = 37; + Label26.Text = "partenza"; + // + // DateTimePicker1 + // + DateTimePicker1.DataBindings.Add(new Binding("Value", bindingSource1, "RaceStartDate", true, DataSourceUpdateMode.OnPropertyChanged)); + DateTimePicker1.Format = DateTimePickerFormat.Time; + DateTimePicker1.Location = new Point(785, 360); + DateTimePicker1.Margin = new Padding(6, 8, 6, 8); + DateTimePicker1.Name = "DateTimePicker1"; + DateTimePicker1.Size = new Size(172, 35); + DateTimePicker1.TabIndex = 36; + // + // CheckBox8 + // + CheckBox8.DataBindings.Add(new Binding("Checked", bindingSource1, "AddTime", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox8.ForeColor = Color.Black; + CheckBox8.Location = new Point(144, 360); + CheckBox8.Margin = new Padding(6, 8, 6, 8); + CheckBox8.Name = "CheckBox8"; + CheckBox8.Size = new Size(113, 38); + CheckBox8.TabIndex = 35; + CheckBox8.Text = "Orario"; + // + // TextBox9 + // + TextBox9.DataBindings.Add(new Binding("Text", bindingSource1, "TextTransparency", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox9.Location = new Point(240, 249); + TextBox9.Margin = new Padding(6, 8, 6, 8); + TextBox9.Name = "TextBox9"; + TextBox9.Size = new Size(107, 35); + TextBox9.TabIndex = 20; + TextBox9.Text = "TextBox9"; + // + // CheckBox7 + // + CheckBox7.DataBindings.Add(new Binding("Checked", bindingSource1, "AddRaceTime", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox7.ForeColor = Color.Black; + CheckBox7.Location = new Point(271, 360); + CheckBox7.Margin = new Padding(6, 8, 6, 8); + CheckBox7.Name = "CheckBox7"; + CheckBox7.Size = new Size(175, 38); + CheckBox7.TabIndex = 34; + CheckBox7.Text = "Tempo gara"; + // + // Label4 + // + Label4.AutoSize = true; + Label4.ForeColor = Color.Black; + Label4.Location = new Point(17, 55); + Label4.Margin = new Padding(6, 0, 6, 0); + Label4.Name = "Label4"; + Label4.Size = new Size(119, 30); + Label4.TabIndex = 9; + Label4.Text = "Orizzontale"; + // + // TextBox4 + // + TextBox4.DataBindings.Add(new Binding("Text", bindingSource1, "HorizontalText", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox4.Location = new Point(144, 55); + TextBox4.Margin = new Padding(6, 8, 6, 8); + TextBox4.Name = "TextBox4"; + TextBox4.Size = new Size(813, 35); + TextBox4.TabIndex = 8; + // + // Label9 + // + Label9.AutoSize = true; + Label9.ForeColor = Color.Black; + Label9.Location = new Point(17, 249); + Label9.Margin = new Padding(6, 0, 6, 0); + Label9.Name = "Label9"; + Label9.Size = new Size(210, 30); + Label9.TabIndex = 19; + Label9.Text = "Trasparenza (0-100%)"; + // + // Label13 + // + Label13.AutoSize = true; + Label13.ForeColor = Color.Black; + Label13.Location = new Point(31, 305); + Label13.Margin = new Padding(6, 0, 6, 0); + Label13.Name = "Label13"; + Label13.Size = new Size(100, 30); + Label13.TabIndex = 29; + Label13.Text = "Posizione"; + // + // ComboBox1 + // + ComboBox1.DataBindings.Add(new Binding("Text", bindingSource1, "VerticalPosition", true, DataSourceUpdateMode.OnPropertyChanged)); + ComboBox1.Location = new Point(144, 305); + ComboBox1.Margin = new Padding(6, 8, 6, 8); + ComboBox1.Name = "ComboBox1"; + ComboBox1.Size = new Size(203, 38); + ComboBox1.TabIndex = 28; + ComboBox1.Text = "ComboBox1"; + // + // ComboBox2 + // + ComboBox2.DataBindings.Add(new Binding("Text", bindingSource1, "HorizontalAlignment", true, DataSourceUpdateMode.OnPropertyChanged)); + ComboBox2.Location = new Point(751, 305); + ComboBox2.Margin = new Padding(6, 8, 6, 8); + ComboBox2.Name = "ComboBox2"; + ComboBox2.Size = new Size(203, 38); + ComboBox2.TabIndex = 31; + ComboBox2.Text = "ComboBox2"; + // + // Label14 + // + Label14.AutoSize = true; + Label14.ForeColor = Color.Black; + Label14.Location = new Point(607, 305); + Label14.Margin = new Padding(6, 0, 6, 0); + Label14.Name = "Label14"; + Label14.Size = new Size(136, 30); + Label14.TabIndex = 30; + Label14.Text = "Allineamento"; + // + // TextBox12 + // + TextBox12.DataBindings.Add(new Binding("Text", bindingSource1, "TextMargin", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox12.Location = new Point(751, 249); + TextBox12.Margin = new Padding(6, 8, 6, 8); + TextBox12.Name = "TextBox12"; + TextBox12.Size = new Size(203, 35); + TextBox12.TabIndex = 33; + TextBox12.Text = "TextBox12"; + // + // Label15 + // + Label15.AutoSize = true; + Label15.ForeColor = Color.Black; + Label15.Location = new Point(593, 249); + Label15.Margin = new Padding(6, 0, 6, 0); + Label15.Name = "Label15"; + Label15.Size = new Size(151, 30); + Label15.TabIndex = 32; + Label15.Text = "Margine (pixel)"; + // + // TabPage2 + // + TabPage2.Controls.Add(GroupBox2); + TabPage2.Location = new Point(4, 39); + TabPage2.Margin = new Padding(6, 8, 6, 8); + TabPage2.Name = "TabPage2"; + TabPage2.Padding = new Padding(6, 8, 6, 8); + TabPage2.Size = new Size(1034, 827); + TabPage2.TabIndex = 5; + TabPage2.Text = "Foto"; + TabPage2.UseVisualStyleBackColor = true; + // + // GroupBox2 + // + GroupBox2.Controls.Add(Label45); + GroupBox2.Controls.Add(TextBox32); + GroupBox2.Controls.Add(TextBox26); + GroupBox2.Controls.Add(Label37); + GroupBox2.Controls.Add(Label38); + GroupBox2.Controls.Add(TextBox27); + GroupBox2.Controls.Add(Label39); + GroupBox2.Controls.Add(TextBox28); + GroupBox2.Controls.Add(CheckBox15); + GroupBox2.ForeColor = Color.FromArgb(0, 0, 192); + GroupBox2.Location = new Point(6, 13); + GroupBox2.Margin = new Padding(6, 8, 6, 8); + GroupBox2.Name = "GroupBox2"; + GroupBox2.Padding = new Padding(6, 8, 6, 8); + GroupBox2.Size = new Size(607, 360); + GroupBox2.TabIndex = 36; + GroupBox2.TabStop = false; + GroupBox2.Text = "Foto grande"; + // + // Label45 + // + Label45.AutoSize = true; + Label45.Location = new Point(22, 198); + Label45.Margin = new Padding(6, 0, 6, 0); + Label45.Name = "Label45"; + Label45.Size = new Size(80, 30); + Label45.TabIndex = 22; + Label45.Text = "Qualità"; + // + // TextBox32 + // + TextBox32.DataBindings.Add(new Binding("Text", bindingSource1, "JpegQuality", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox32.Location = new Point(144, 185); + TextBox32.Margin = new Padding(6, 8, 6, 8); + TextBox32.Name = "TextBox32"; + TextBox32.Size = new Size(141, 35); + TextBox32.TabIndex = 21; + TextBox32.Text = "100"; + // + // TextBox26 + // + TextBox26.DataBindings.Add(new Binding("Text", bindingSource1, "BigPhotoSuffix", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox26.Location = new Point(449, 111); + TextBox26.Margin = new Padding(6, 8, 6, 8); + TextBox26.Name = "TextBox26"; + TextBox26.Size = new Size(107, 35); + TextBox26.TabIndex = 20; + // + // Label37 + // + Label37.ForeColor = Color.Black; + Label37.Location = new Point(336, 111); + Label37.Margin = new Padding(6, 0, 6, 0); + Label37.Name = "Label37"; + Label37.Size = new Size(96, 38); + Label37.TabIndex = 19; + Label37.Text = "Suffisso"; + Label37.TextAlign = ContentAlignment.MiddleRight; + // + // Label38 + // + Label38.AutoSize = true; + Label38.ForeColor = Color.Black; + Label38.Location = new Point(48, 55); + Label38.Margin = new Padding(6, 0, 6, 0); + Label38.Name = "Label38"; + Label38.Size = new Size(81, 30); + Label38.TabIndex = 16; + Label38.Text = "Altezza"; + // + // TextBox27 + // + TextBox27.DataBindings.Add(new Binding("Text", bindingSource1, "PhotoBigWidth", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox27.Location = new Point(144, 55); + TextBox27.Margin = new Padding(6, 8, 6, 8); + TextBox27.Name = "TextBox27"; + TextBox27.Size = new Size(141, 35); + TextBox27.TabIndex = 14; + TextBox27.Text = "TextBox27"; + // + // Label39 + // + Label39.AutoSize = true; + Label39.ForeColor = Color.Black; + Label39.Location = new Point(17, 111); + Label39.Margin = new Padding(6, 0, 6, 0); + Label39.Name = "Label39"; + Label39.Size = new Size(107, 30); + Label39.TabIndex = 17; + Label39.Text = "Larghezza"; + // + // TextBox28 + // + TextBox28.DataBindings.Add(new Binding("Text", bindingSource1, "PhotoBigHeight", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox28.Location = new Point(144, 111); + TextBox28.Margin = new Padding(6, 8, 6, 8); + TextBox28.Name = "TextBox28"; + TextBox28.Size = new Size(141, 35); + TextBox28.TabIndex = 15; + TextBox28.Text = "TextBox28"; + // + // CheckBox15 + // + CheckBox15.Checked = true; + CheckBox15.CheckState = CheckState.Checked; + CheckBox15.DataBindings.Add(new Binding("Checked", bindingSource1, "KeepOriginalDimensions", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox15.ForeColor = Color.Black; + CheckBox15.Location = new Point(336, 38); + CheckBox15.Margin = new Padding(6, 8, 6, 8); + CheckBox15.Name = "CheckBox15"; + CheckBox15.Size = new Size(240, 73); + CheckBox15.TabIndex = 18; + CheckBox15.Text = "Mantieni dimensioni originali"; + // + // TabPage1 + // + TabPage1.Controls.Add(Panel1); + TabPage1.Controls.Add(GroupBox1); + TabPage1.Location = new Point(4, 39); + TabPage1.Margin = new Padding(6, 8, 6, 8); + TabPage1.Name = "TabPage1"; + TabPage1.Padding = new Padding(6, 8, 6, 8); + TabPage1.Size = new Size(1034, 827); + TabPage1.TabIndex = 0; + TabPage1.Text = "Miniature"; + TabPage1.UseVisualStyleBackColor = true; + // + // Panel1 + // + Panel1.Controls.Add(_CheckBox18); + Panel1.Controls.Add(_CheckBox4); + Panel1.Controls.Add(_CheckBox12); + Panel1.Location = new Point(103, 545); + Panel1.Margin = new Padding(6, 8, 6, 8); + Panel1.Name = "Panel1"; + Panel1.Size = new Size(607, 168); + Panel1.TabIndex = 26; + Panel1.Visible = false; + // + // _CheckBox18 + // + _CheckBox18.AutoSize = true; + _CheckBox18.Location = new Point(281, 8); + _CheckBox18.Margin = new Padding(6, 8, 6, 8); + _CheckBox18.Name = "_CheckBox18"; + _CheckBox18.Size = new Size(159, 34); + _CheckBox18.TabIndex = 36; + _CheckBox18.Text = "Numero foto"; + _CheckBox18.UseVisualStyleBackColor = true; + // + // _CheckBox4 + // + _CheckBox4.ForeColor = Color.Black; + _CheckBox4.Location = new Point(19, 8); + _CheckBox4.Margin = new Padding(6, 8, 6, 8); + _CheckBox4.Name = "_CheckBox4"; + _CheckBox4.Size = new Size(209, 39); + _CheckBox4.TabIndex = 34; + _CheckBox4.Text = "Aggiungi scritta"; + // + // _CheckBox12 + // + _CheckBox12.ForeColor = Color.Black; + _CheckBox12.Location = new Point(19, 43); + _CheckBox12.Margin = new Padding(6, 8, 6, 8); + _CheckBox12.Name = "_CheckBox12"; + _CheckBox12.Size = new Size(209, 48); + _CheckBox12.TabIndex = 35; + _CheckBox12.Text = "Aggiungi orario"; + // + // GroupBox1 + // + GroupBox1.Controls.Add(label16); + GroupBox1.Controls.Add(Label46); + GroupBox1.Controls.Add(TextBox33); + GroupBox1.Controls.Add(Label5); + GroupBox1.Controls.Add(TextBox5); + GroupBox1.Controls.Add(Label6); + GroupBox1.Controls.Add(TextBox6); + GroupBox1.Controls.Add(Label3); + GroupBox1.Controls.Add(TextBox3); + GroupBox1.Controls.Add(CheckBox1); + GroupBox1.Controls.Add(comboThumbnailOption); + GroupBox1.ForeColor = Color.FromArgb(0, 0, 192); + GroupBox1.Location = new Point(12, 12); + GroupBox1.Margin = new Padding(6, 8, 6, 8); + GroupBox1.Name = "GroupBox1"; + GroupBox1.Padding = new Padding(6, 8, 6, 8); + GroupBox1.Size = new Size(701, 485); + GroupBox1.TabIndex = 25; + GroupBox1.TabStop = false; + GroupBox1.Text = "Miniature"; + // + // Label46 + // + Label46.AutoSize = true; + Label46.Location = new Point(396, 99); + Label46.Margin = new Padding(6, 0, 6, 0); + Label46.Name = "Label46"; + Label46.Size = new Size(80, 30); + Label46.TabIndex = 21; + Label46.Text = "Qualità"; + // + // TextBox33 + // + TextBox33.DataBindings.Add(new Binding("Text", bindingSource1, "JpegQualityThumbnail", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox33.Location = new Point(487, 93); + TextBox33.Margin = new Padding(6, 8, 6, 8); + TextBox33.Name = "TextBox33"; + TextBox33.Size = new Size(196, 35); + TextBox33.TabIndex = 20; + // + // Label5 + // + Label5.AutoSize = true; + Label5.ForeColor = Color.Black; + Label5.Location = new Point(48, 202); + Label5.Margin = new Padding(6, 0, 6, 0); + Label5.Name = "Label5"; + Label5.Size = new Size(81, 30); + Label5.TabIndex = 12; + Label5.Text = "Altezza"; + // + // TextBox5 + // + TextBox5.DataBindings.Add(new Binding("Text", bindingSource1, "ThumbnailWidth", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox5.Location = new Point(144, 147); + TextBox5.Margin = new Padding(6, 8, 6, 8); + TextBox5.Name = "TextBox5"; + TextBox5.Size = new Size(172, 35); + TextBox5.TabIndex = 10; + TextBox5.Text = "TextBox5"; + // + // Label6 + // + Label6.AutoSize = true; + Label6.ForeColor = Color.Black; + Label6.Location = new Point(17, 147); + Label6.Margin = new Padding(6, 0, 6, 0); + Label6.Name = "Label6"; + Label6.Size = new Size(107, 30); + Label6.TabIndex = 13; + Label6.Text = "Larghezza"; + // + // TextBox6 + // + TextBox6.DataBindings.Add(new Binding("Text", bindingSource1, "ThumbnailHeight", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox6.Location = new Point(144, 202); + TextBox6.Margin = new Padding(6, 8, 6, 8); + TextBox6.Name = "TextBox6"; + TextBox6.Size = new Size(172, 35); + TextBox6.TabIndex = 11; + TextBox6.Text = "TextBox6"; + // + // Label3 + // + Label3.AutoSize = true; + Label3.ForeColor = Color.Black; + Label3.Location = new Point(48, 93); + Label3.Margin = new Padding(6, 0, 6, 0); + Label3.Name = "Label3"; + Label3.Size = new Size(85, 30); + Label3.TabIndex = 7; + Label3.Text = "Suffisso"; + // + // TextBox3 + // + TextBox3.DataBindings.Add(new Binding("Text", bindingSource1, "ThumbnailPrefix", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox3.Location = new Point(144, 93); + TextBox3.Margin = new Padding(6, 8, 6, 8); + TextBox3.Name = "TextBox3"; + TextBox3.Size = new Size(172, 35); + TextBox3.TabIndex = 6; + TextBox3.Text = "TextBox3"; + // + // CheckBox1 + // + CheckBox1.DataBindings.Add(new Binding("Checked", bindingSource1, "CreateThumbnails", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox1.ForeColor = Color.Black; + CheckBox1.Location = new Point(144, 38); + CheckBox1.Margin = new Padding(6, 8, 6, 8); + CheckBox1.Name = "CheckBox1"; + CheckBox1.Size = new Size(209, 55); + CheckBox1.TabIndex = 5; + CheckBox1.Text = "Crea miniature"; + // + // comboThumbnailOption + // + comboThumbnailOption.DropDownStyle = ComboBoxStyle.DropDownList; + comboThumbnailOption.Location = new Point(204, 262); + comboThumbnailOption.Margin = new Padding(6, 8, 6, 8); + comboThumbnailOption.Name = "comboThumbnailOption"; + comboThumbnailOption.Size = new Size(470, 38); + comboThumbnailOption.TabIndex = 18; + // + // TabPage4 + // + TabPage4.Controls.Add(GroupBox6); + TabPage4.Location = new Point(4, 39); + TabPage4.Margin = new Padding(6, 8, 6, 8); + TabPage4.Name = "TabPage4"; + TabPage4.Padding = new Padding(6, 8, 6, 8); + TabPage4.Size = new Size(1034, 827); + TabPage4.TabIndex = 3; + TabPage4.Text = "Logo"; + TabPage4.UseVisualStyleBackColor = true; + // + // GroupBox6 + // + GroupBox6.Controls.Add(chkUseTransparentColor); + GroupBox6.Controls.Add(btnSetTransparency); + GroupBox6.Controls.Add(_PictureBox1); + GroupBox6.Controls.Add(ComboBox5); + GroupBox6.Controls.Add(ComboBox4); + GroupBox6.Controls.Add(TextBox19); + GroupBox6.Controls.Add(Label28); + GroupBox6.Controls.Add(CheckBox5); + GroupBox6.Controls.Add(TextBox15); + GroupBox6.Controls.Add(TextBox14); + GroupBox6.Controls.Add(Label25); + GroupBox6.Controls.Add(TextBox16); + GroupBox6.Controls.Add(Label24); + GroupBox6.Controls.Add(Label22); + GroupBox6.Controls.Add(Label23); + GroupBox6.Controls.Add(_Button4); + GroupBox6.Controls.Add(TextBox10); + GroupBox6.Controls.Add(Label29); + GroupBox6.Controls.Add(PictureBox3); + GroupBox6.ForeColor = Color.FromArgb(0, 0, 192); + GroupBox6.Location = new Point(12, 13); + GroupBox6.Margin = new Padding(6, 8, 6, 8); + GroupBox6.Name = "GroupBox6"; + GroupBox6.Padding = new Padding(6, 8, 6, 8); + GroupBox6.Size = new Size(991, 593); + GroupBox6.TabIndex = 42; + GroupBox6.TabStop = false; + GroupBox6.Text = "Logo"; + // + // chkUseTransparentColor + // + chkUseTransparentColor.AutoSize = true; + chkUseTransparentColor.Location = new Point(39, 461); + chkUseTransparentColor.Name = "chkUseTransparentColor"; + chkUseTransparentColor.Size = new Size(210, 34); + chkUseTransparentColor.TabIndex = 46; + chkUseTransparentColor.Text = "Colore trasparente"; + chkUseTransparentColor.UseVisualStyleBackColor = true; + // + // btnSetTransparency + // + btnSetTransparency.Location = new Point(288, 455); + btnSetTransparency.Name = "btnSetTransparency"; + btnSetTransparency.Size = new Size(131, 40); + btnSetTransparency.TabIndex = 45; + btnSetTransparency.Text = "Imposta"; + btnSetTransparency.UseVisualStyleBackColor = true; + // + // _PictureBox1 + // + _PictureBox1.Cursor = Cursors.Cross; + _PictureBox1.Location = new Point(511, 129); + _PictureBox1.Margin = new Padding(6, 8, 6, 8); + _PictureBox1.Name = "_PictureBox1"; + _PictureBox1.Size = new Size(449, 369); + _PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; + _PictureBox1.TabIndex = 43; + _PictureBox1.TabStop = false; + // + // ComboBox5 + // + ComboBox5.DataBindings.Add(new Binding("Text", bindingSource1, "LogoVerticalPosition", true, DataSourceUpdateMode.OnPropertyChanged)); + ComboBox5.Location = new Point(288, 387); + ComboBox5.Margin = new Padding(6, 8, 6, 8); + ComboBox5.Name = "ComboBox5"; + ComboBox5.Size = new Size(189, 38); + ComboBox5.TabIndex = 42; + ComboBox5.Text = "ComboBox5"; + // + // ComboBox4 + // + ComboBox4.DataBindings.Add(new Binding("Text", bindingSource1, "LogoHorizontalPosition", true, DataSourceUpdateMode.OnPropertyChanged)); + ComboBox4.Location = new Point(288, 333); + ComboBox4.Margin = new Padding(6, 8, 6, 8); + ComboBox4.Name = "ComboBox4"; + ComboBox4.Size = new Size(189, 38); + ComboBox4.TabIndex = 41; + ComboBox4.Text = "ComboBox4"; + // + // TextBox19 + // + TextBox19.DataBindings.Add(new Binding("Text", bindingSource1, "LogoTransparency", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox19.Location = new Point(288, 222); + TextBox19.Margin = new Padding(6, 8, 6, 8); + TextBox19.Name = "TextBox19"; + TextBox19.Size = new Size(189, 35); + TextBox19.TabIndex = 40; + TextBox19.Text = "TextBox19"; + // + // Label28 + // + Label28.ForeColor = Color.Black; + Label28.Location = new Point(38, 222); + Label28.Margin = new Padding(6, 0, 6, 0); + Label28.Name = "Label28"; + Label28.Size = new Size(240, 38); + Label28.TabIndex = 39; + Label28.Text = "Trasparenza (0-100%)"; + Label28.TextAlign = ContentAlignment.MiddleLeft; + // + // CheckBox5 + // + CheckBox5.DataBindings.Add(new Binding("Checked", bindingSource1, "AddLogo", true, DataSourceUpdateMode.OnPropertyChanged)); + CheckBox5.ForeColor = Color.Black; + CheckBox5.Location = new Point(12, 56); + CheckBox5.Margin = new Padding(6, 8, 6, 8); + CheckBox5.Name = "CheckBox5"; + CheckBox5.Size = new Size(144, 47); + CheckBox5.TabIndex = 38; + CheckBox5.Text = "Aggiungi"; + // + // TextBox15 + // + TextBox15.DataBindings.Add(new Binding("Text", bindingSource1, "LogoHeight", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox15.Location = new Point(288, 167); + TextBox15.Margin = new Padding(6, 8, 6, 8); + TextBox15.Name = "TextBox15"; + TextBox15.Size = new Size(189, 35); + TextBox15.TabIndex = 19; + TextBox15.Text = "TextBox15"; + // + // TextBox14 + // + TextBox14.DataBindings.Add(new Binding("Text", bindingSource1, "LogoWidth", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox14.Location = new Point(288, 111); + TextBox14.Margin = new Padding(6, 8, 6, 8); + TextBox14.Name = "TextBox14"; + TextBox14.Size = new Size(189, 35); + TextBox14.TabIndex = 18; + TextBox14.Text = "TextBox14"; + // + // Label25 + // + Label25.AutoSize = true; + Label25.ForeColor = Color.Black; + Label25.Location = new Point(39, 390); + Label25.Margin = new Padding(6, 0, 6, 0); + Label25.Name = "Label25"; + Label25.Size = new Size(183, 30); + Label25.TabIndex = 36; + Label25.Text = "Posizione verticale"; + Label25.TextAlign = ContentAlignment.MiddleLeft; + // + // TextBox16 + // + TextBox16.DataBindings.Add(new Binding("Text", bindingSource1, "LogoMargin", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox16.Location = new Point(288, 278); + TextBox16.Margin = new Padding(6, 8, 6, 8); + TextBox16.Name = "TextBox16"; + TextBox16.Size = new Size(189, 35); + TextBox16.TabIndex = 35; + TextBox16.Text = "TextBox16"; + // + // Label24 + // + Label24.AutoSize = true; + Label24.ForeColor = Color.Black; + Label24.Location = new Point(38, 283); + Label24.Margin = new Padding(6, 0, 6, 0); + Label24.Name = "Label24"; + Label24.Size = new Size(176, 30); + Label24.TabIndex = 34; + Label24.Text = "Margine (pixel/%)"; + Label24.TextAlign = ContentAlignment.MiddleLeft; + // + // Label22 + // + Label22.AutoSize = true; + Label22.ForeColor = Color.Black; + Label22.Location = new Point(38, 117); + Label22.Margin = new Padding(6, 0, 6, 0); + Label22.Name = "Label22"; + Label22.Size = new Size(81, 30); + Label22.TabIndex = 20; + Label22.Text = "Altezza"; + Label22.TextAlign = ContentAlignment.MiddleLeft; + // + // Label23 + // + Label23.AutoSize = true; + Label23.ForeColor = Color.Black; + Label23.Location = new Point(38, 172); + Label23.Margin = new Padding(6, 0, 6, 0); + Label23.Name = "Label23"; + Label23.Size = new Size(107, 30); + Label23.TabIndex = 21; + Label23.Text = "Larghezza"; + Label23.TextAlign = ContentAlignment.MiddleLeft; + // + // _Button4 + // + _Button4.Location = new Point(929, 55); + _Button4.Margin = new Padding(6, 8, 6, 8); + _Button4.Name = "_Button4"; + _Button4.Size = new Size(48, 47); + _Button4.TabIndex = 8; + _Button4.Text = "..."; + // + // TextBox10 + // + TextBox10.DataBindings.Add(new Binding("Text", bindingSource1, "LogoFile", true, DataSourceUpdateMode.OnPropertyChanged)); + TextBox10.Location = new Point(288, 55); + TextBox10.Margin = new Padding(6, 8, 6, 8); + TextBox10.Name = "TextBox10"; + TextBox10.Size = new Size(621, 35); + TextBox10.TabIndex = 6; + TextBox10.Text = "TextBox10"; + // + // Label29 + // + Label29.AutoSize = true; + Label29.ForeColor = Color.Black; + Label29.Location = new Point(38, 341); + Label29.Margin = new Padding(6, 0, 6, 0); + Label29.Name = "Label29"; + Label29.Size = new Size(208, 30); + Label29.TabIndex = 36; + Label29.Text = "Posizione orizzontale"; + Label29.TextAlign = ContentAlignment.MiddleLeft; + // + // PictureBox3 + // + PictureBox3.BorderStyle = BorderStyle.FixedSingle; + PictureBox3.Location = new Point(432, 442); + PictureBox3.Margin = new Padding(6, 8, 6, 8); + PictureBox3.Name = "PictureBox3"; + PictureBox3.Size = new Size(45, 53); + PictureBox3.TabIndex = 44; + PictureBox3.TabStop = false; + PictureBox3.Visible = false; + // + // versionLabel + // + versionLabel.DataBindings.Add(new Binding("Text", bindingSource1, "AppVersion", true)); + versionLabel.Location = new Point(1182, 873); + versionLabel.Margin = new Padding(6, 0, 6, 0); + versionLabel.Name = "versionLabel"; + versionLabel.Size = new Size(281, 47); + versionLabel.TabIndex = 62; + versionLabel.Text = "Versione 2.2 2021"; + versionLabel.TextAlign = ContentAlignment.MiddleRight; + // + // _Button7 + // + _Button7.DataBindings.Add(new Binding("Enabled", bindingSource1, "UiDisabled", true, DataSourceUpdateMode.OnPropertyChanged)); + _Button7.DataBindings.Add(new Binding("Command", bindingSource1, "AsyncCancelOperationCommand", true)); + _Button7.Font = new Font("Microsoft Sans Serif", 14.25F, FontStyle.Bold, GraphicsUnit.Point, 0); + _Button7.Location = new Point(1078, 278); + _Button7.Margin = new Padding(6, 8, 6, 8); + _Button7.Name = "_Button7"; + _Button7.Size = new Size(384, 93); + _Button7.TabIndex = 61; + _Button7.Text = "STOP"; + // + // _Button5 + // + _Button5.DataBindings.Add(new Binding("Enabled", bindingSource1, "UiEnabled", true)); + _Button5.Font = new Font("Microsoft Sans Serif", 11F, FontStyle.Bold, GraphicsUnit.Point, 0); + _Button5.Location = new Point(1078, 95); + _Button5.Margin = new Padding(6, 8, 6, 8); + _Button5.Name = "_Button5"; + _Button5.Size = new Size(384, 73); + _Button5.TabIndex = 60; + _Button5.Text = "Salva impostazioni"; + // + // Label20 + // + Label20.AutoSize = true; + Label20.Font = new Font("Microsoft Sans Serif", 9.75F, FontStyle.Bold, GraphicsUnit.Point, 0); + Label20.Location = new Point(1078, 678); + Label20.Margin = new Padding(6, 0, 6, 0); + Label20.Name = "Label20"; + Label20.Size = new Size(175, 29); + Label20.TabIndex = 59; + Label20.Text = "foto generate:"; + // + // Label19 + // + Label19.AutoSize = true; + Label19.Font = new Font("Microsoft Sans Serif", 9.75F, FontStyle.Bold, GraphicsUnit.Point, 0); + Label19.Location = new Point(1078, 635); + Label19.Margin = new Padding(6, 0, 6, 0); + Label19.Name = "Label19"; + Label19.Size = new Size(135, 29); + Label19.TabIndex = 58; + Label19.Text = "foto totali: "; + // + // Label18 + // + Label18.AutoSize = true; + Label18.Font = new Font("Microsoft Sans Serif", 12F, FontStyle.Bold, GraphicsUnit.Point, 0); + Label18.Location = new Point(1286, 678); + Label18.Margin = new Padding(6, 0, 6, 0); + Label18.Name = "Label18"; + Label18.Size = new Size(31, 32); + Label18.TabIndex = 57; + Label18.Text = "0"; + // + // lblFotoTotaliNum + // + lblFotoTotaliNum.AutoSize = true; + lblFotoTotaliNum.Font = new Font("Microsoft Sans Serif", 12F, FontStyle.Bold, GraphicsUnit.Point, 0); + lblFotoTotaliNum.Location = new Point(1286, 635); + lblFotoTotaliNum.Margin = new Padding(6, 0, 6, 0); + lblFotoTotaliNum.Name = "lblFotoTotaliNum"; + lblFotoTotaliNum.Size = new Size(31, 32); + lblFotoTotaliNum.TabIndex = 56; + lblFotoTotaliNum.Text = "0"; + // + // Label10 + // + Label10.Font = new Font("Microsoft Sans Serif", 14.25F, FontStyle.Bold, GraphicsUnit.Point, 0); + Label10.Location = new Point(1078, 377); + Label10.Margin = new Padding(6, 0, 6, 0); + Label10.Name = "Label10"; + Label10.Size = new Size(384, 167); + Label10.TabIndex = 55; + Label10.Text = "file"; + // + // _Button6 + // + _Button6.DataBindings.Add(new Binding("Enabled", bindingSource1, "UiEnabled", true)); + _Button6.Font = new Font("Microsoft Sans Serif", 11F, FontStyle.Bold, GraphicsUnit.Point, 0); + _Button6.Location = new Point(1078, 22); + _Button6.Margin = new Padding(6, 8, 6, 8); + _Button6.Name = "_Button6"; + _Button6.Size = new Size(384, 73); + _Button6.TabIndex = 54; + _Button6.Text = "Carica impostazioni"; + // + // _btnCreaCatalogoAsync + // + _btnCreaCatalogoAsync.DataBindings.Add(new Binding("Enabled", bindingSource1, "UiEnabled", true)); + _btnCreaCatalogoAsync.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Bold, GraphicsUnit.Point, 0); + _btnCreaCatalogoAsync.Location = new Point(1078, 175); + _btnCreaCatalogoAsync.Margin = new Padding(6, 8, 6, 8); + _btnCreaCatalogoAsync.Name = "_btnCreaCatalogoAsync"; + _btnCreaCatalogoAsync.Size = new Size(384, 87); + _btnCreaCatalogoAsync.TabIndex = 68; + _btnCreaCatalogoAsync.Text = "CREA"; + _btnCreaCatalogoAsync.UseVisualStyleBackColor = true; + // + // dataModelBindingSource1 + // + dataModelBindingSource1.DataSource = typeof(ImageCatalog_2.DataModel); + // + // label16 + // + label16.AutoSize = true; + label16.Location = new Point(39, 262); + label16.Name = "label16"; + label16.Size = new Size(156, 30); + label16.TabIndex = 22; + label16.Text = "Testo Miniature"; + // + // MainForm + // + AutoScaleDimensions = new SizeF(12F, 30F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1478, 925); + Controls.Add(_btnCreaCatalogoAsync); + Controls.Add(ProgressBar1); + Controls.Add(CheckBox22); + Controls.Add(Label43); + Controls.Add(TabControl1); + Controls.Add(versionLabel); + Controls.Add(_Button7); + Controls.Add(_Button5); + Controls.Add(Label20); + Controls.Add(Label19); + Controls.Add(Label18); + Controls.Add(lblFotoTotaliNum); + Controls.Add(Label10); + Controls.Add(_Button6); + Margin = new Padding(6, 8, 6, 8); + MaximizeBox = false; + Name = "MainForm"; + Text = "Image Catalog"; + Load += Form1_Load; + ((System.ComponentModel.ISupportInitialize)bindingSource1).EndInit(); + ((System.ComponentModel.ISupportInitialize)dataModelBindingSource).EndInit(); + TabControl1.ResumeLayout(false); + TabPage5.ResumeLayout(false); + groupBox12.ResumeLayout(false); + groupBox12.PerformLayout(); + GroupBox11.ResumeLayout(false); + GroupBox11.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)numericUpDown2).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDown1).EndInit(); + Panel3.ResumeLayout(false); + Panel3.PerformLayout(); + GroupBox3.ResumeLayout(false); + GroupBox3.PerformLayout(); + GroupBox8.ResumeLayout(false); + GroupBox8.PerformLayout(); + GroupBox7.ResumeLayout(false); + GroupBox7.PerformLayout(); + TabPage3.ResumeLayout(false); + GroupBox10.ResumeLayout(false); + GroupBox10.PerformLayout(); + GroupBox9.ResumeLayout(false); + GroupBox9.PerformLayout(); + GroupBox5.ResumeLayout(false); + GroupBox5.PerformLayout(); + GroupBox4.ResumeLayout(false); + GroupBox4.PerformLayout(); + TabPage2.ResumeLayout(false); + GroupBox2.ResumeLayout(false); + GroupBox2.PerformLayout(); + TabPage1.ResumeLayout(false); + Panel1.ResumeLayout(false); + Panel1.PerformLayout(); + GroupBox1.ResumeLayout(false); + GroupBox1.PerformLayout(); + TabPage4.ResumeLayout(false); + GroupBox6.ResumeLayout(false); + GroupBox6.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)_PictureBox1).EndInit(); + ((System.ComponentModel.ISupportInitialize)PictureBox3).EndInit(); + ((System.ComponentModel.ISupportInitialize)dataModelBindingSource1).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + internal ProgressBar ProgressBar1; + internal CheckBox CheckBox22; + internal Label Label43; + internal TabControl TabControl1; + internal TabPage TabPage5; + internal GroupBox GroupBox3; + internal CheckBox chkAggiornaSottodirectory; + private Button _Button3; + + internal Button Button3 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _Button3; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _Button3 = value; + } + } + + private Button _Button2; + + internal Button Button2 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _Button2; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _Button2 = value; + } + } + + internal Label Label1; + internal Label Label2; + internal TextBox txtSorgente; + internal TextBox txtDestinazione; + internal GroupBox GroupBox8; + internal RadioButton rdbNumFiles; + internal RadioButton rdbNumProgressiva; + internal TextBox txtCifreContatore; + internal Label Label34; + internal TextBox txtSuffissoCartelle; + internal Label Label33; + internal Label Label31; + internal CheckBox chkCreaSottocartelle; + internal TextBox txtFilePerCartella; + internal Label Label32; + internal GroupBox GroupBox7; + internal CheckBox chkRotazioneAutomatica; + internal CheckBox chkForzaJpg; + internal TabPage TabPage3; + internal GroupBox GroupBox10; + internal Label Label42; + internal Label Label41; + internal TextBox TextBox31; + internal TextBox TextBox30; + internal Label versionLabel; + internal GroupBox GroupBox9; + internal CheckBox CheckBox17; + internal CheckBox CheckBox16; + internal GroupBox GroupBox5; + internal TextBox TextBox34; + private Button _Button8; + + internal Button Button8 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _Button8; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _Button8 = value; + } + } + + internal Label Label36; + internal TextBox TextBox25; + internal Label Label35; + internal ComboBox ComboBox3; + internal TextBox TextBox11; + internal Label Label12; + internal Label Label11; + internal CheckBox CheckBox3; + internal GroupBox GroupBox4; + internal Label Label40; + internal TextBox TextBox29; + internal TextBox TextBox18; + internal Label Label26; + internal DateTimePicker DateTimePicker1; + internal CheckBox CheckBox8; + internal TextBox TextBox9; + internal CheckBox CheckBox7; + internal Label Label4; + internal TextBox TextBox4; + internal Label Label9; + internal Label Label13; + internal ComboBox ComboBox1; + internal ComboBox ComboBox2; + internal Label Label14; + internal TextBox TextBox12; + internal Label Label15; + internal TabPage TabPage2; + internal GroupBox GroupBox2; + internal Label Label45; + internal TextBox TextBox32; + internal TextBox TextBox26; + internal Label Label37; + internal Label Label38; + internal TextBox TextBox27; + internal Label Label39; + internal TextBox TextBox28; + internal CheckBox CheckBox15; + internal TabPage TabPage1; + internal Panel Panel1; + private CheckBox _CheckBox18; + + internal CheckBox CheckBox18 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _CheckBox18; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _CheckBox18 = value; + } + } + + private CheckBox _CheckBox4; + + internal CheckBox CheckBox4 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _CheckBox4; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _CheckBox4 = value; + } + } + + private CheckBox _CheckBox12; + + internal CheckBox CheckBox12 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _CheckBox12; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _CheckBox12 = value; + } + } + + internal GroupBox GroupBox1; + internal Label Label46; + internal TextBox TextBox33; + private ComboBox comboThumbnailOption; + internal Label Label5; + internal TextBox TextBox5; + internal Label Label6; + internal TextBox TextBox6; + internal Label Label3; + internal TextBox TextBox3; + internal CheckBox CheckBox1; + internal TabPage TabPage4; + internal GroupBox GroupBox6; + private PictureBox _PictureBox1; + + internal PictureBox PictureBox1 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _PictureBox1; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _PictureBox1 = value; + } + } + + internal ComboBox ComboBox5; + internal ComboBox ComboBox4; + internal TextBox TextBox19; + internal Label Label28; + internal CheckBox CheckBox5; + internal TextBox TextBox15; + internal TextBox TextBox14; + internal Label Label25; + internal TextBox TextBox16; + internal Label Label24; + internal Label Label22; + internal Label Label23; + private Button _Button4; + + internal Button Button4 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _Button4; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _Button4 = value; + } + } + + internal TextBox TextBox10; + internal Label Label29; + private Label _Label27; + + internal Label Label27 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _Label27; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _Label27 = value; + } + } + + private Button _Button7; + + private Button _Button5; + + internal Button Button5 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _Button5; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _Button5 = value; + } + } + + internal Label Label20; + internal Label Label19; + internal Label Label18; + internal Label lblFotoTotaliNum; + internal Label Label10; + + //internal Button btnCreaCatalogo + //{ + // [MethodImpl(MethodImplOptions.Synchronized)] + // get + // { + // return _btnCreaCatalogo; + // } + + // [MethodImpl(MethodImplOptions.Synchronized)] + // set + // { + // if (_btnCreaCatalogo != null) + // { + // _btnCreaCatalogo.Click -= btnCreaCatalogo_Click; + // } + + // _btnCreaCatalogo = value; + // if (_btnCreaCatalogo != null) + // { + // _btnCreaCatalogo.Click += btnCreaCatalogo_Click; + // } + // } + //} + + private Button _Button6; + + internal Button Button6 + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _Button6; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _Button6 = value; + } + } + + internal GroupBox GroupBox11; + internal Label Label7; + internal Label Label8; + internal Panel Panel3; + internal RadioButton rdbNuovoMetodo; + internal RadioButton rdbVecchioMetodo; + internal CheckBox chkSovrascriviFile; + private Button _btnCreaCatalogoAsync; + private System.Windows.Forms.Timer timer1; + private BindingSource dataModelBindingSource; + private BindingSource dataModelBindingSource1; + private BindingSource bindingSource1; + private NumericUpDown numericUpDown1; + private NumericUpDown numericUpDown2; + private Button btnOpenDestFolder; + private Button btnOpenSourceFolder; + private GroupBox groupBox12; + private RadioButton rdbLibrary2; + private RadioButton rdbLibrary1; + internal PictureBox PictureBox3; + private ColorDialog colorDialog1; + private Button btnSetTransparency; + private CheckBox chkUseTransparentColor; + private Label label16; + + internal Button btnCreaCatalogoAsync + { + [MethodImpl(MethodImplOptions.Synchronized)] + get + { + return _btnCreaCatalogoAsync; + } + + [MethodImpl(MethodImplOptions.Synchronized)] + set + { + _btnCreaCatalogoAsync = value; + } + } + } +} \ No newline at end of file diff --git a/imagecatalog/MainForm.cs b/imagecatalog/MainForm.cs new file mode 100644 index 0000000..e951bc3 --- /dev/null +++ b/imagecatalog/MainForm.cs @@ -0,0 +1,840 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Text; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using ImageCatalog_2; +using ImageCatalog_2.Commands; +using ImageCatalog_2.Services; +using MaddoShared; +using Microsoft.Extensions.Logging; + +namespace ImageCatalog; + +public partial class MainForm +{ + private readonly DataModel Model; + + private readonly ILogger _logger; + + private readonly ParametriSetup _parametriSetup; + private readonly PicSettings _picSettings; + // Prevent re-entrant updates between UI events and model PropertyChanged handling + private bool _suppressRadioUpdates = false; + private bool _transparentDialogOpen = false; + + public MainForm(DataModel model, ImageCreationStuff imageCreationStuff, PicSettings picSettings, + ParametriSetup parametriSetup, ILogger logger) + { + Model = model; + _parametriSetup = parametriSetup; + _picSettings = picSettings; + _logger = logger; + + _logger.LogDebug("Start"); + + InitializeComponent(); + // Set this form as the control for thread marshalling in the DataModel + Model.SetControl(this); + + // Ensure the designer data bindings have a concrete DataSource immediately so + // that UI controls (radio buttons) reflect the ViewModel state and propagate + // user changes back to the ViewModel. + bindingSource1.DataSource = Model; + + BindControls(); + + // The designer originally bound the radio buttons to boolean helpers on the ViewModel. + // Those two separate bindings can fight with each other. Clear designer bindings and + // wire explicit Click handlers that update the single authoritative property + // `Model.ImageLibrary`. Also keep a PropertyChanged listener to reflect external + // changes back into the radio buttons. + rdbLibrary1.DataBindings.Clear(); + rdbLibrary2.DataBindings.Clear(); + + // Initialize radio state from model + rdbLibrary1.Checked = Model.UseSystemGraphics; + rdbLibrary2.Checked = Model.UseImageSharp; + + // Use Click handlers (not CheckedChanged) to avoid competing binding updates + rdbLibrary1.Click += (_, _) => + { + if (_suppressRadioUpdates) return; + if (Model.ImageLibrary != "System.Graphics") + Model.ImageLibrary = "System.Graphics"; + }; + rdbLibrary2.Click += (_, _) => + { + if (_suppressRadioUpdates) return; + if (Model.ImageLibrary != "ImageSharp") + Model.ImageLibrary = "ImageSharp"; + }; + + // Watch for model changes so we can reflect external updates + Model.PropertyChanged += Model_PropertyChanged; + + // Thumbnail options moved to ComboBox to avoid conflicting bindings with multiple radio buttons + + // Initialize ComboBox with Italian descriptions + comboThumbnailOption.Items.Clear(); + comboThumbnailOption.Items.AddRange(new object[] { + "Nessuna", + "Aggiungi scritta", + "Nome file", + "Aggiungi orario", + "Nome+Orario", + "Tempo gara" + }); + + // Bind to model via helper index property ThumbnailOptionIndex + comboThumbnailOption.DataBindings.Add(new Binding("SelectedIndex", bindingSource1, "ThumbnailOptionIndex", true, DataSourceUpdateMode.OnPropertyChanged)); + + // Save user preferences on form close instead of immediately when dialogs are used + this.FormClosing += MainForm_FormClosing; + + // Wire up 'Open folder in Explorer' buttons + btnOpenSourceFolder.Click += BtnOpenSourceFolder_Click; + btnOpenDestFolder.Click += BtnOpenDestFolder_Click; + + // Show currently selected color in small PictureBox3 + PictureBox3.BackColor = ColorTranslator.FromHtml(Model.TransparentColor); + + // Version label is data-bound to DataModel.AppVersion; DataModel is populated with the version via DI + } + + + + private void RdbLibrary_CheckedChanged(object? sender, EventArgs e) + { + // Keep behavior simple: when a radio button becomes checked, update the ViewModel + // so that the designer binding and PicSettings stay in sync. + if (sender is RadioButton rb && rb.Checked) + { + _logger?.LogDebug("Radio library changed: {RadioName}", rb.Name); + if (rb == rdbLibrary2) + { + Model.ImageLibrary = "ImageSharp"; + } + else if (rb == rdbLibrary1) + { + Model.ImageLibrary = "System.Graphics"; + } + } + } + + private void Model_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (e.PropertyName is null) return; + if (e.PropertyName == nameof(Model.ImageLibrary) || e.PropertyName == nameof(Model.UseImageSharp) || e.PropertyName == nameof(Model.UseSystemGraphics)) + { + _logger?.LogDebug("Model property changed: {Property} => ImageLibrary={ImageLibrary}, PicSettings.Provider={Provider}", e.PropertyName, Model.ImageLibrary, _picSettings.ImageCreatorProvider); + + // Reflect authoritative model value into the radio buttons in a thread-safe, re-entrancy-safe way + try + { + _suppressRadioUpdates = true; + rdbLibrary1.Checked = Model.UseSystemGraphics; + rdbLibrary2.Checked = Model.UseImageSharp; + } + finally + { + _suppressRadioUpdates = false; + } + } + + // Thumbnail mode changes - reflect back to combo box index + if (e.PropertyName == nameof(Model.ThumbnailMode) || + e.PropertyName == nameof(Model.ThumbnailOption) || + e.PropertyName == nameof(Model.ThumbnailOptionIndex)) + { + try + { + _suppressRadioUpdates = true; + comboThumbnailOption.SelectedIndex = Model.ThumbnailOptionIndex; + } + finally + { + _suppressRadioUpdates = false; + } + } + } + + protected void BindControls() + { + // Bind buttons to ViewModel commands using command binding + _btnCreaCatalogoAsync.BindCommand(Model.ProcessImagesCommand); + // Note: `button1` control does not exist in the designer. Use the primary create button only. + _Button2.BindCommand(Model.SelectSourceFolderCommand); + _Button3.BindCommand(Model.SelectDestinationFolderCommand); + _Button4.BindCommand(Model.SelectLogoFileCommand); + _Button5.BindCommand(Model.SaveSettingsCommand); + _Button6.BindCommand(Model.LoadSettingsCommand); + _Button8.BindCommand(Model.SelectColorCommand); + // Bind the transparency chooser button/command + btnSetTransparency.BindCommand(Model.SelectTransparentColorCommand); + + // Subscribe to ViewModel events for UI dialogs (these need UI context) + Model.SelectSourceFolderRequested += OnSelectSourceFolderRequested; + Model.SelectDestinationFolderRequested += OnSelectDestinationFolderRequested; + Model.SelectLogoFileRequested += OnSelectLogoFileRequested; + Model.SaveSettingsRequested += OnSaveSettingsRequested; + Model.LoadSettingsRequested += OnLoadSettingsRequested; + Model.SelectColorRequested += OnSelectColorRequested; + Model.SelectTransparentColorRequested += OnSelectTransparentColorRequested; + // Show message requests (from ViewModel validation) + Model.ShowMessageRequested += OnShowMessageRequested; + } + + private void OnSelectTransparentColorRequested(object? sender, EventArgs e) + { + // Ensure UI thread + if (InvokeRequired) + { + Invoke(new Action(OnSelectTransparentColorRequested), sender, e as EventArgs ?? EventArgs.Empty); + return; + } + // Prevent re-entrancy: if the dialog is already open, ignore subsequent requests + if (_transparentDialogOpen) return; + + _transparentDialogOpen = true; + var dlg = new ColorDialog { AllowFullOpen = true }; + try + { + dlg.Color = ColorTranslator.FromHtml(Model.TransparentColor); + } + catch { } + try + { + if (dlg.ShowDialog() == DialogResult.OK) + { + Model.TransparentColor = ColorTranslator.ToHtml(dlg.Color); + PictureBox3.BackColor = dlg.Color; + + // Update preview if logo exists + if (!string.IsNullOrWhiteSpace(Model.LogoFile) && File.Exists(Model.LogoFile)) + { + UpdateLogoPictureBox(Model.LogoFile); + } + } + } + finally + { + _transparentDialogOpen = false; + } + } + + private void BtnSetTransparency_Click(object? sender, EventArgs e) + { + Model.SelectTransparentColorCommand.Execute(null); + } + + private void OnShowMessageRequested(object? sender, Tuple args) + { + if (args is null) return; + // Ensure call on UI thread + if (InvokeRequired) + { + Invoke(new Action(() => OnShowMessageRequested(sender, args))); + return; + } + + MessageBox.Show(this, args.Item1, args.Item2, MessageBoxButtons.OK, args.Item3); + } + + private void SetDefaults() + { + // Bind ComboBoxes to Model using proper data binding + ComboBox1.DataSource = new List(Model.VerticalPositions); + ComboBox1.DataBindings.Add(new Binding("SelectedItem", bindingSource1, nameof(Model.VerticalPosition), + false, DataSourceUpdateMode.OnPropertyChanged)); + + ComboBox2.DataSource = new List(Model.HorizontalAlignments); + ComboBox2.DataBindings.Add(new Binding("SelectedItem", bindingSource1, nameof(Model.HorizontalAlignment), + false, DataSourceUpdateMode.OnPropertyChanged)); + + ComboBox3.DataSource = new List(Model.AvailableFonts); + ComboBox3.DataBindings.Add(new Binding("SelectedItem", bindingSource1, nameof(Model.FontName), + false, DataSourceUpdateMode.OnPropertyChanged)); + + ComboBox4.DataSource = new List(Model.HorizontalAlignments); + ComboBox4.DataBindings.Add(new Binding("SelectedItem", bindingSource1, nameof(Model.LogoHorizontalPosition), + false, DataSourceUpdateMode.OnPropertyChanged)); + + ComboBox5.DataSource = new List { "Alto", "Centro", "Basso" }; + ComboBox5.DataBindings.Add(new Binding("SelectedItem", bindingSource1, nameof(Model.LogoVerticalPosition), + false, DataSourceUpdateMode.OnPropertyChanged)); + + // Bind progress bar and status labels + ProgressBar1.DataBindings.Add(new Binding("Maximum", bindingSource1, nameof(Model.ProgressBarMaximum), + false, DataSourceUpdateMode.OnPropertyChanged)); + ProgressBar1.DataBindings.Add(new Binding("Value", bindingSource1, nameof(Model.ProgressBarValue), + false, DataSourceUpdateMode.OnPropertyChanged)); + + Label18.DataBindings.Add(new Binding("Text", bindingSource1, nameof(Model.ProcessedImagesCount), + false, DataSourceUpdateMode.OnPropertyChanged)); + lblFotoTotaliNum.DataBindings.Add(new Binding("Text", bindingSource1, nameof(Model.TotalImagesCount), + false, DataSourceUpdateMode.OnPropertyChanged)); + Label10.DataBindings.Add(new Binding("Text", bindingSource1, nameof(Model.ProcessingStatus), + false, DataSourceUpdateMode.OnPropertyChanged)); + + // Bind transparency model properties to UI + chkUseTransparentColor.DataBindings.Add(new Binding("Checked", bindingSource1, nameof(Model.UseTransparentColor), false, DataSourceUpdateMode.OnPropertyChanged)); + // Show currently selected color in PictureBox3 + PictureBox3.Visible = false; + if (!string.IsNullOrWhiteSpace(Model.TransparentColor)) + { + try + { + PictureBox3.BackColor = ColorTranslator.FromHtml(Model.TransparentColor); + PictureBox3.Visible = true; + } + catch + { + PictureBox3.Visible = false; + } + } + + // When logo file changes, update preview + Model.PropertyChanged += (s, e) => + { + if (e.PropertyName == nameof(Model.LogoFile) || e.PropertyName == nameof(Model.UseTransparentColor) || e.PropertyName == nameof(Model.TransparentColor)) + { + if (!string.IsNullOrWhiteSpace(Model.LogoFile) && System.IO.File.Exists(Model.LogoFile)) + { + UpdateLogoPictureBox(Model.LogoFile); + } + } + }; + + // Bind transparent color hex and show color in PictureBox3 + // Bind UseTransparentColor checkbox (designer control named CheckBox5 used for AddLogo earlier, add new binding control exists in designer) + // Use PictureBox3 to display color value + var colorBinding = new Binding("BackColor", bindingSource1, nameof(Model.TransparentColor), true, DataSourceUpdateMode.OnPropertyChanged); + colorBinding.Format += (s, e) => + { + try + { + e.Value = ColorTranslator.FromHtml(e.Value?.ToString() ?? "#FFFFFF"); + } + catch + { + e.Value = Color.White; + } + }; + PictureBox3.DataBindings.Add(colorBinding); + + // Bind checkbox for using color key transparency if such control exists (CheckBox5 was repurposed as AddLogo); create binding if available + try + { + // The designer has CheckBox5 for 'AddLogo'. We'll add a separate binding to a new control named CheckBoxUseTransparentColor if present. + var chk = this.Controls.Find("chkUseTransparentColor", true).FirstOrDefault() as CheckBox; + if (chk != null) + { + chk.DataBindings.Add(new Binding("Checked", bindingSource1, nameof(Model.UseTransparentColor), false, DataSourceUpdateMode.OnPropertyChanged)); + } + } + catch { } + } + + + private void Form1_Load(object sender, EventArgs e) + { + bindingSource1.DataSource = Model; + Application.EnableVisualStyles(); + SetDefaults(); + + _logger.LogInformation("Programma Avviato"); + // If settings were loaded before the form was shown, ensure the logo preview is updated + try + { + if (!string.IsNullOrWhiteSpace(Model.LogoFile) && File.Exists(Model.LogoFile)) + { + UpdateLogoPictureBox(Model.LogoFile); + } + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Failed to load logo during form load"); + } + } + + private string CalcTime(DateTime timeStart, DateTime timeStop, int numFoto) + { + long timediffH, timediffS; + long timediffM; + + TimeSpan timeDiff = timeStop - timeStart; + + timediffM = (int)timeDiff.TotalMinutes; + timediffS = (int)timeDiff.TotalSeconds; + timediffH = (int)timeDiff.TotalHours; + + // timediffM = DateAndTime.DateDiff(DateInterval.Minute, timeStart, timeStop); + // timediffS = DateAndTime.DateDiff(DateInterval.Second, timeStart, timeStop); + // timediffH = DateAndTime.DateDiff(DateInterval.Hour, timeStart, timeStop); + + double fotoSec = numFoto / (double)timediffS; + double fotoMin = numFoto / (double)timediffM; + double fotoOra = numFoto / (double)timediffH; + string s = "S: " + timediffS.ToString() + "; F/s: " + + fotoSec.ToString( + "0.000"); // + " F/m: " + fotoMin.ToString("0.00") + " F/h: " + fotoOra.ToString("0.00") + return s; + } + + private string SelectFolder(string startingFolder) + { + var dialog = new FolderBrowserDialog(); + dialog.InitialDirectory = startingFolder; + if (dialog.ShowDialog() != DialogResult.OK) return string.Empty; + + return FixPath(dialog.SelectedPath); + } + + private string FixPath(string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + return string.Empty; + } + + // Trim leading/trailing quotes + path = path.Trim().Trim('"'); + + // Normalize directory separators + path = path.Replace('/', Path.DirectorySeparatorChar) + .Replace('\\', Path.DirectorySeparatorChar); + + // Remove trailing separators then add one back + path = path.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + + return path; + } + + private void OnSelectSourceFolderRequested(object sender, EventArgs e) + { + // Prefer model value; if empty fall back to last-used value stored in user prefs + var starting = !string.IsNullOrWhiteSpace(Model.SourcePath) + ? Model.SourcePath + : _parametriSetup.LeggiParametroString("LastSourceFolder"); + + var dialogResult = SelectFolder(starting); + if (!string.IsNullOrWhiteSpace(dialogResult)) + { + Model.SourcePath = dialogResult; + _parametriSetup.AggiornaParametro("LastSourceFolder", dialogResult); + _parametriSetup.SalvaParametriSetup(); + } + } + + private void BtnOpenSourceFolder_Click(object? sender, EventArgs e) + { + // Prefer the model value but fall back to the textbox if needed + var path = string.IsNullOrWhiteSpace(Model.SourcePath) ? txtSorgente.Text : Model.SourcePath; + OpenFolder(path); + } + + private void BtnOpenDestFolder_Click(object? sender, EventArgs e) + { + var path = string.IsNullOrWhiteSpace(Model.DestinationPath) ? txtDestinazione.Text : Model.DestinationPath; + OpenFolder(path); + } + + private void OpenFolder(string? path) + { + if (string.IsNullOrWhiteSpace(path)) + { + MessageBox.Show(this, "Folder path is empty.", "Open Folder", MessageBoxButtons.OK, MessageBoxIcon.Warning); + return; + } + + path = path.Trim().Trim('"'); + + try + { + if (File.Exists(path)) + { + // If a file was provided, open its folder and select it + Process.Start("explorer.exe", $"/select,\"{path}\""); + return; + } + + if (Directory.Exists(path)) + { + Process.Start(new ProcessStartInfo + { + FileName = path, + UseShellExecute = true + }); + return; + } + + MessageBox.Show(this, $"Folder does not exist: {path}", "Open Folder", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + catch (Exception ex) + { + _logger?.LogError(ex, "Failed to open folder {Path}", path); + MessageBox.Show(this, $"Failed to open folder: {ex.Message}", "Open Folder", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void OnSelectDestinationFolderRequested(object sender, EventArgs e) + { + var starting = !string.IsNullOrWhiteSpace(Model.DestinationPath) + ? Model.DestinationPath + : _parametriSetup.LeggiParametroString("LastDestinationFolder"); + + var dialogResult = SelectFolder(starting); + if (!string.IsNullOrWhiteSpace(dialogResult)) + { + Model.DestinationPath = dialogResult; + _parametriSetup.AggiornaParametro("LastDestinationFolder", dialogResult); + _parametriSetup.SalvaParametriSetup(); + } + } + + private void OnSelectLogoFileRequested(object sender, EventArgs e) + { + var dialog = new OpenFileDialog(); + dialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp;*.gif"; + if (!string.IsNullOrWhiteSpace(Model.LogoFile)) + { + dialog.FileName = Model.LogoFile; + } + else + { + var lastLogoFolder = _parametriSetup.LeggiParametroString("LastLogoFolder"); + if (!string.IsNullOrWhiteSpace(lastLogoFolder) && Directory.Exists(lastLogoFolder)) + { + dialog.InitialDirectory = lastLogoFolder; + } + } + + if (dialog.ShowDialog() == DialogResult.OK) + { + Model.LogoFile = dialog.FileName; + UpdateLogoPictureBox(Model.LogoFile); + try + { + var folder = Path.GetDirectoryName(dialog.FileName) ?? string.Empty; + if (!string.IsNullOrWhiteSpace(folder)) + { + _parametriSetup.AggiornaParametro("LastLogoFolder", folder); + _parametriSetup.SalvaParametriSetup(); + } + } + catch + { + // ignore preferences save failures + } + } + } + + private async void OnSaveSettingsRequested(object sender, string e) + { + var saveDialog = new SaveFileDialog + { + Filter = "Setup (*.xml)|*.xml|All valid files (*.*)|*.*", + FilterIndex = 0, + RestoreDirectory = true + }; + var lastSettings = _parametriSetup.LeggiParametroString("LastSettingsFolder"); + if (!string.IsNullOrWhiteSpace(lastSettings) && Directory.Exists(lastSettings)) + saveDialog.InitialDirectory = lastSettings; + + if (saveDialog.ShowDialog() != DialogResult.OK) return; + + await Model.SaveSettingsToFileAsync(saveDialog.FileName); + Text = "Image Catalog - " + Path.GetFileName(saveDialog.FileName); + + try + { + var folder = Path.GetDirectoryName(saveDialog.FileName) ?? string.Empty; + if (!string.IsNullOrWhiteSpace(folder)) + { + _parametriSetup.AggiornaParametro("LastSettingsFolder", folder); + _parametriSetup.SalvaParametriSetup(); + } + } + catch + { + // ignore + } + } + + private async void OnLoadSettingsRequested(object sender, string e) + { + var openDialog = new OpenFileDialog + { + Filter = "Setup (*.xml)|*.xml|All valid files (*.*)|*.*", + FilterIndex = 0, + RestoreDirectory = true + }; + + var lastSettings = _parametriSetup.LeggiParametroString("LastSettingsFolder"); + if (!string.IsNullOrWhiteSpace(lastSettings) && Directory.Exists(lastSettings)) + openDialog.InitialDirectory = lastSettings; + + if (openDialog.ShowDialog() != DialogResult.OK) return; + + try + { + await Model.LoadSettingsFromFileAsync(openDialog.FileName); + + // Explicitly ensure UI is enabled after loading + Model.UiEnabled = true; + + // If a logo path was stored in the settings, try to resolve and display it. + // The stored path may be absolute or relative to the settings file location. + try + { + var storedLogo = Model.LogoFile; + // Trim whitespace and surrounding quotes which may be present in saved settings + if (!string.IsNullOrWhiteSpace(storedLogo)) + { + storedLogo = storedLogo.Trim(); + storedLogo = storedLogo.Trim('"'); + } + if (!string.IsNullOrWhiteSpace(storedLogo)) + { + string resolved = storedLogo; + // If not rooted, try to resolve relative to the settings file folder + var settingsFolder = Path.GetDirectoryName(openDialog.FileName) ?? string.Empty; + if (!Path.IsPathRooted(resolved) && !string.IsNullOrWhiteSpace(settingsFolder)) + { + var candidate = Path.Combine(settingsFolder, resolved); + if (File.Exists(candidate)) resolved = candidate; + } + + // If rooted but file doesn't exist, try filename near settings file + if (!File.Exists(resolved) && !string.IsNullOrWhiteSpace(settingsFolder)) + { + var candidate2 = Path.Combine(settingsFolder, Path.GetFileName(resolved)); + if (File.Exists(candidate2)) resolved = candidate2; + } + + if (File.Exists(resolved)) + { + // Update the model so data-bound controls reflect the resolved absolute path + Model.LogoFile = resolved; + UpdateLogoPictureBox(resolved); + } + } + } + catch (Exception ex) + { + _logger.LogDebug(ex, "Error resolving logo path after loading settings"); + } + + Text = "Image Catalog - " + Path.GetFileName(openDialog.FileName); + + try + { + var folder = Path.GetDirectoryName(openDialog.FileName) ?? string.Empty; + if (!string.IsNullOrWhiteSpace(folder)) + { + _parametriSetup.AggiornaParametro("LastSettingsFolder", folder); + _parametriSetup.SalvaParametriSetup(); + } + } + catch + { + // ignore preferences save failures + } + + _logger.LogInformation($"Settings loaded successfully from {openDialog.FileName}"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error loading settings"); + MessageBox.Show($"Error loading settings: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void MainForm_FormClosing(object? sender, FormClosingEventArgs e) + { + try + { + // Persist last-used dialogs paths (user preferences) + // These keys are managed independently from settings files + // and must be saved when the form closes. + _parametriSetup.AggiornaParametro("LastSourceFolder", Model.SourcePath ?? string.Empty); + _parametriSetup.AggiornaParametro("LastDestinationFolder", Model.DestinationPath ?? string.Empty); + _parametriSetup.AggiornaParametro("LastLogoFolder", Path.GetDirectoryName(Model.LogoFile ?? string.Empty) ?? string.Empty); + _parametriSetup.SalvaParametriSetup(); + } + catch (Exception ex) + { + _logger?.LogWarning(ex, "Failed to save user preferences on exit"); + } + } + + private void OnSelectColorRequested(object sender, EventArgs e) + { + var colorDialog = new ColorDialog + { + AllowFullOpen = true + }; + + if (!string.IsNullOrWhiteSpace(Model.TextColorRGB)) + { + try + { + colorDialog.Color = ColorTranslator.FromHtml(Model.TextColorRGB); + } + catch + { + // Invalid color, use default + } + } + + if (colorDialog.ShowDialog() == DialogResult.OK) + { + Model.TextColorRGB = ColorTranslator.ToHtml(colorDialog.Color); + TextBox34.BackColor = colorDialog.Color; + } + } + + private void UpdateLogoPictureBox(string logoPath) + { + try + { + // Load image via System.Drawing for preview so we can use MakeTransparent when requested + using var img = System.Drawing.Image.FromFile(logoPath); + + System.Drawing.Bitmap previewBmp; + // If using color-key transparency and a color is selected, apply MakeTransparent for preview + if (Model.UseTransparentColor && !string.IsNullOrWhiteSpace(Model.TransparentColor)) + { + try + { + var key = ColorTranslator.FromHtml(Model.TransparentColor); + previewBmp = new System.Drawing.Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + using (var g = System.Drawing.Graphics.FromImage(previewBmp)) + { + g.Clear(System.Drawing.Color.Transparent); + g.DrawImage(img, 0, 0, img.Width, img.Height); + } + // Apply exact color-key transparency + previewBmp.MakeTransparent(key); + PictureBox3.BackColor = key; + PictureBox3.Visible = true; + } + catch + { + previewBmp = new System.Drawing.Bitmap(img); + } + } + else + { + previewBmp = new System.Drawing.Bitmap(img); + } + + // Resize preview to fit into PictureBox1 while preserving aspect ratio + // Resize preview to fit into PictureBox1 while preserving aspect ratio + var boxW = PictureBox1.ClientSize.Width > 0 ? PictureBox1.ClientSize.Width : 449; + var boxH = PictureBox1.ClientSize.Height > 0 ? PictureBox1.ClientSize.Height : 369; + var ratio = Math.Min((double)boxW / previewBmp.Width, (double)boxH / previewBmp.Height); + var destW = Math.Max(1, (int)(previewBmp.Width * ratio)); + var destH = Math.Max(1, (int)(previewBmp.Height * ratio)); + var scaled = new System.Drawing.Bitmap(destW, destH, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + using (var g = System.Drawing.Graphics.FromImage(scaled)) + { + g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + g.Clear(System.Drawing.Color.Transparent); + // Center the image in the PictureBox + var offsetX = Math.Max(0, (boxW - destW) / 2); + var offsetY = Math.Max(0, (boxH - destH) / 2); + using var canvas = new System.Drawing.Bitmap(boxW, boxH, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + using (var cg = System.Drawing.Graphics.FromImage(canvas)) + { + cg.Clear(System.Drawing.Color.Transparent); + cg.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; + cg.DrawImage(previewBmp, offsetX, offsetY, destW, destH); + } + g.DrawImage(canvas, 0, 0); + } + + // Set PictureBox1 image (dispose previous) + var old = PictureBox1.Image; + PictureBox1.SizeMode = PictureBoxSizeMode.CenterImage; + PictureBox1.Image = scaled; + old?.Dispose(); + previewBmp.Dispose(); + } + catch + { + // Image loading failed, ignore + } + } + + private void UpdateLogoPreviewWithColorKey(string logoPath, Color keyColor) + { + try + { + using var img = (Bitmap)Image.FromFile(logoPath); + // Create ARGB copy + var bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + using (var g = Graphics.FromImage(bmp)) + { + g.DrawImage(img, 0, 0, img.Width, img.Height); + } + + bmp.MakeTransparent(keyColor); + + // Resize to PictureBox1 size similar to previous logic + Bitmap finalBmp; + if (bmp.Height >= bmp.Width) + { + finalBmp = new Bitmap(bmp, new Size((int)(160 * bmp.Width / (double)bmp.Height), 160)); + } + else + { + finalBmp = new Bitmap(bmp, new Size(160, (int)(160 * bmp.Height / (double)bmp.Width))); + } + + PictureBox1.Image = finalBmp; + } + catch + { + // ignore preview failures + } + } + + private void setLabel18Text(string text) + { + if (Label18.InvokeRequired) + { + Label18.Invoke(new Action(setLabel18Text), text); + } + else + { + Label18.Text = text; + } + } +} + +public class PicInfo +{ + public DirectoryInfo DirSource, DirDest, DirDestStart; + public string NomeImmagine; + + public PicInfo(DirectoryInfo Dir_Source, DirectoryInfo Dir_Dest, DirectoryInfo Dir_DestStart, + string Nome_Immagine) + { + DirSource = Dir_Source; + DirDest = Dir_Dest; + DirDestStart = Dir_DestStart; + NomeImmagine = Nome_Immagine; + } +} \ No newline at end of file diff --git a/imagecatalog/MainForm.resx b/imagecatalog/MainForm.resx new file mode 100644 index 0000000..fa95561 --- /dev/null +++ b/imagecatalog/MainForm.resx @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 586, 17 + + + 120, 17 + + + 17, 17 + + + 349, 17 + + + 802, 17 + + \ No newline at end of file diff --git a/imagecatalog/MainWindow.xaml b/imagecatalog/MainWindow.xaml new file mode 100644 index 0000000..17bda4f --- /dev/null +++ b/imagecatalog/MainWindow.xaml @@ -0,0 +1,322 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +