diff --git a/.github/commit-conventions.instructions.md b/.github/commit-conventions.instructions.md new file mode 100644 index 0000000..72c9f58 --- /dev/null +++ b/.github/commit-conventions.instructions.md @@ -0,0 +1,31 @@ +--- +applyTo: "**" +--- +# Commit Message Conventions + +When generating commit messages, follow this format combining gitmoji emoticons with conventional commits. +Also use a list for the descripton, each description on its own line + +**Format:** ` (scope): ` + +## Gitmoji Reference + +- โœจ `:sparkles:` - New features +- ๐Ÿ› `:bug:` - Bug fixes +- ๐ŸŽจ `:art:` - Code structure/format improvements +- โšก๏ธ `:zap:` - Performance improvements +- ๐Ÿ”ง `:wrench:` - Configuration changes +- ๐Ÿ“ `:memo:` - Documentation +- โœ… `:white_check_mark:` - Tests +- ๐Ÿš€ `:rocket:` - Deployments +- โ™ป๏ธ `:recycle:` - Refactoring +- ๐Ÿ”ฅ `:fire:` - Removing code/files +- ๐Ÿ’„ `:lipstick:` - UI/styling +- ๐Ÿ”’ `:lock:` - Security fixes +- ๐Ÿšจ `:rotating_light:` - Fixing linter warnings +- ๐Ÿ’š `:green_heart:` - CI/CD fixes +- ๐Ÿ“ฆ `:package:` - Dependencies/packages +- ๐Ÿ—๏ธ `:building_construction:` - Architecture changes +- ๐Ÿงช `:test_tube:` - Experimental features +- ๐Ÿฉน `:adhesive_bandage:` - Simple fixes +- ๐Ÿ”€ `:twisted_rightwards_arrows:` - Merging branches diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000..3c7b119 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,429 @@ +# MapWinGIS Development Guidelines + +## Scope and authoritative guidance + +Follow [AGENTS.md](../AGENTS.md) and the detailed standards linked there. +They take precedence over the general guidance below. + +`MapWinGIS.Core` is a C++20 DLL. It must not use COM, ATL, or MFC. +The ActiveX wrapper is not implemented yet. COM/ActiveX guidance below +applies only to that future wrapper and to preserving the MapWinGIS 5 contract. + +## Project Context + +This repository contains the modernized MapWinGIS6 codebase. + +MapWinGIS 5 is the legacy COM/ActiveX library and the behavior reference. +Port its functionality incrementally as modern C++20. Do not transliterate +the legacy implementation. + +When working in this repository, prioritize: + +* Correctness and preservation of existing MapWinGIS behavior. +* API and backwards compatibility where applicable. +* Clear, maintainable modern C++. +* Small, focused changes. +* Understanding existing code before changing it. +* Avoiding unnecessary changes outside the requested scope. + +Do not assume that a modernization task is an opportunity to redesign unrelated functionality. + +--- + +## General Coding Guidelines + +Before changing code: + +1. Understand the responsibility of the relevant class, component, or subsystem. +2. Inspect related declarations, implementations, and call sites when necessary. +3. Consider whether the code is part of the public COM/ActiveX API. +4. Preserve existing behavior unless the task explicitly requests a behavioral change. +5. Identify compatibility implications before changing public APIs. + +When making changes: + +* Keep changes focused on the requested task. +* Prefer simple, readable solutions over unnecessary abstraction. +* Follow the existing architecture unless there is a clear reason to change it. +* Do not introduce dependencies without a clear need. +* Do not perform unrelated refactoring. +* Do not silently change public API behavior. +* Do not remove functionality merely because it appears old or unusual. +* Do not make assumptions about code that are not supported by the source or project context. + +When a requirement is ambiguous, inspect the surrounding code and project conventions before making assumptions. + +--- + +# Documentation Guidelines + +## File-level documentation + +Every new or substantially modified C++ source or header file should have a concise Doxygen-style file header. + +Preferred format: + +```cpp +/** + * @file Map.cpp + * + * @brief Implements the Map class. + * + * Provides functionality for managing map layers and interacting + * with the map rendering system. + */ +``` + +The exact wording must reflect the actual contents of the file. + +Do not blindly copy a generic description or infer functionality solely from the filename. + +### Header files + +For `.h` and `.hpp` files, describe: + +* The main classes, interfaces, structs, enums, or other public types. +* The responsibility of the API declared in the file. +* Important relationships or constraints when relevant. + +### Implementation files + +For `.cpp`, `.cc`, and `.cxx` files, describe: + +* The functionality implemented by the file. +* The main class or component being implemented. +* Important implementation responsibilities when they provide useful context. + +### Length + +Keep file-level documentation concise. + +As a general guideline, 3โ€“10 lines is sufficient for most files. + +A more complex file may need additional context, but do not turn every file into a documentation page. + +Do not document every function in the file from the file header. + +--- + +## Doxygen + +Use Doxygen-compatible syntax where appropriate. + +For file-level documentation, prefer: + +```cpp +/** + * @file FileName.cpp + * + * @brief Short description of the file. + */ +``` + +Use additional Doxygen tags when they provide meaningful documentation. + +Do not add tags merely for completeness. + +In particular, do not automatically add: + +* `@author` +* `@date` +* `@version` +* `@history` + +unless explicitly requested or required by an established project convention. + +--- + +## Public API documentation + +Public APIs should be documented when their purpose or behavior is not obvious. + +For public classes, methods, properties, interfaces, and other API elements, documentation should explain meaningful behavior and contracts rather than simply repeating the name. + +Useful information can include: + +* What the API does. +* Important parameters and return values. +* Preconditions or constraints. +* Ownership and lifetime requirements. +* Exceptions or error behavior. +* Threading requirements. +* COM/ActiveX compatibility considerations. +* Non-obvious behavior that callers need to understand. + +Avoid documentation such as: + +```cpp +// Gets the name. +std::string GetName(); +``` + +when the declaration is already self-explanatory. + +Prefer documentation that adds information: + +```cpp +/** + * @brief Gets the name of the layer. + * + * Returns the name currently exposed through the MapWinGIS API. + * The returned value may be empty if no name has been assigned. + */ +``` + +Only document behavior that is supported by the code or established project requirements. + +--- + +# Comments in Implementations + +Comments should explain information that cannot be understood easily from the code itself. + +Prefer comments that explain: + +* Why code is implemented in a particular way. +* Compatibility requirements. +* Non-obvious algorithms. +* Workarounds. +* Architectural constraints. +* Important assumptions. +* Reasons for seemingly unusual behavior. + +Avoid comments that merely restate the code. + +Prefer: + +```cpp +// Preserve the legacy behavior because existing COM clients +// may depend on this coordinate transformation. +``` + +over: + +```cpp +// Transform the coordinates. +``` + +Do not add comments simply to increase the amount of documentation. + +Do not invent explanations for code whose intent is unclear. + +If the reason for unusual code cannot be established reliably, do not fabricate one. + +--- + +# Change History + +Do not add manual change logs to source files. + +Do not add: + +* `Revision History` +* `Change History` +* `Created by` +* `Author` +* `Last modified` +* Creation dates +* Modification dates +* Date-based change entries + +For example, do not add: + +```text +Revision History: +2020-05-12 John - Added layer support +2024-03-18 Jane - Fixed rendering +2026-10-01 Paul - Modernized implementation +``` + +Git provides this information more reliably through commit history and blame. + +The purpose of source documentation is to explain the code's purpose, behavior, and design โ€” not to maintain a manually updated history. + +--- + +# Historical and Migrated Code + +The new repository is being populated by moving functionality from the legacy MapWinGIS codebase. + +When migrating code: + +* Preserve useful technical comments from the original implementation when they remain relevant. +* Preserve comments explaining compatibility requirements or non-obvious behavior. +* Do not blindly copy obsolete or misleading comments. +* Do not introduce historical changelists into the new code. +* Do not assume that old comments are correct simply because they exist. +* Update documentation when the migrated implementation has materially changed. + +The new repository should document the current implementation rather than reproduce the documentation style of the legacy repository. + +--- + +# COM / ActiveX Compatibility + +MapWinGIS exposes a long-lived COM/ActiveX API. + +When modifying code that is part of the public API: + +* Treat compatibility as an important consideration. +* Avoid changing public interfaces without an explicit requirement. +* Be careful with COM-visible types, interfaces, methods, properties, enums, DISPIDs, and related contracts. +* Consider existing external applications that may depend on legacy behavior. +* Document compatibility constraints when they are important to understanding the implementation. + +Do not claim that a behavior is required for backwards compatibility unless that requirement is known or can reasonably be established from the code or project context. + +--- + +# Modern C++ Guidelines + +Modernize code deliberately rather than mechanically. + +Use C++20 and follow the architecture and conventions in +[docs/CODING-STANDARDS.md](../docs/CODING-STANDARDS.md). + +Examples include: + +* RAII. +* Appropriate smart pointers. +* Scoped enums. +* `constexpr` where appropriate. +* `const` correctness. +* Range-based loops where they improve clarity. +* Standard library facilities instead of unnecessary custom implementations. +* Clear ownership and lifetime semantics. +* Avoiding raw owning pointers. + +However: + +* Do not modernize code merely for stylistic reasons during an unrelated task. +* Do not introduce abstractions without a clear benefit. +* Do not change behavior unintentionally. +* Consider COM/ActiveX ownership and lifetime semantics carefully before replacing existing pointer-based patterns. +* Consider ABI/API compatibility before changing public types or interfaces. + +When migrating a legacy component, preserve externally observable behavior unless the modernization task explicitly calls for a change. + +--- + +# Error Handling + +Follow the error-handling conventions established by the surrounding code and API. + +For COM-facing code, pay particular attention to existing error reporting and HRESULT-related behavior. + +Do not replace an established error-handling mechanism with exceptions or another mechanism without considering its effect on callers and the public API. + +Do not silently swallow errors. + +When changing error handling, make the behavioral implications explicit. + +--- + +# Dependencies + +Prefer existing project dependencies and the C++ standard library. + +Do not add a third-party dependency for functionality that can reasonably be implemented using existing project facilities or the standard library. + +If a new dependency is genuinely necessary: + +* Keep the change focused. +* Explain why it is needed. +* Consider build, deployment, licensing, and compatibility implications. + +--- + +# Generated and Third-party Code + +Do not modify generated code, build output, or third-party/vendor code unless explicitly requested. + +Before editing an unfamiliar file, determine whether it is: + +* Project source code. +* Generated code. +* Third-party code. +* Build output. +* Configuration or tooling. + +When uncertain, inspect the project structure and related configuration rather than guessing. + +--- + +# Scope and Unrelated Changes + +Keep changes focused. + +Unless explicitly requested, do not: + +* Refactor unrelated code. +* Rename unrelated symbols. +* Reformat unrelated files. +* Change line endings unnecessarily. +* Reorder includes without a reason. +* Change build configuration. +* Update dependencies. +* Fix unrelated bugs. +* Modify generated files. +* Rewrite existing documentation unrelated to the task. + +A clean, focused diff is preferred. + +--- + +# Before Making Changes + +For non-trivial changes: + +1. Identify the relevant files. +2. Understand the existing implementation. +3. Identify related declarations and callers where necessary. +4. Determine whether the code is part of the public COM/ActiveX API. +5. Consider compatibility implications. +6. Make the smallest appropriate change. +7. Review the resulting diff for unintended modifications. + +Do not make large speculative changes when a smaller change satisfies the requirement. + +--- + +# After Making Changes + +Review the resulting changes and verify: + +* The requested functionality is implemented correctly. +* Existing behavior is preserved where required. +* Public API compatibility has been considered. +* Documentation accurately describes the current code. +* No invented behavior or assumptions were introduced. +* No unrelated files were modified. +* No unnecessary formatting changes were introduced. +* New comments provide useful information rather than restating code. +* File-level documentation follows the project's Doxygen conventions. + +When possible, build and test the affected code. + +If tests cannot be run, state that clearly rather than implying that the changes were verified. + +--- + +# Communication + +When explaining changes: + +* Be concise and technical. +* Clearly distinguish facts from assumptions. +* Mention important compatibility considerations. +* Identify uncertainty rather than guessing. +* Report relevant files and changes. +* Mention tests/builds that were actually performed. +* Do not claim success for operations that were not verified. + +For larger tasks, summarize: + +1. What was changed. +2. Why it was changed. +3. Which files were affected. +4. What was tested. +5. Any remaining concerns or follow-up work. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..8999b7e --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,65 @@ +name: build + +on: + push: + branches: [main, development] + pull_request: + +jobs: + build: + runs-on: windows-2025 + strategy: + fail-fast: false + matrix: + platform: [x64, Win32] + configuration: [Debug, Release] + + env: + VCPKG_BINARY_SOURCES: clear;x-gha,readwrite + # The runner image does not ship SDK 10.0.28000 yet. + MWG_WINDOWS_SDK: '10.0' + + steps: + - uses: actions/checkout@v4 + + - name: Export GitHub Actions cache variables + uses: actions/github-script@v7 + with: + script: | + core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || ''); + core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || ''); + + - name: Bootstrap vcpkg + shell: pwsh + run: ./build/scripts/bootstrap-vcpkg.ps1 + + - uses: microsoft/setup-msbuild@v2 + + - name: Build + shell: pwsh + run: | + msbuild MapWinGIS6.slnx ` + -p:Configuration=${{ matrix.configuration }} ` + -p:Platform=${{ matrix.platform }} ` + -p:MwgWindowsSdk=$env:MWG_WINDOWS_SDK ` + -m -v:m + + - name: Test + shell: pwsh + run: | + $exe = "bin/${{ matrix.configuration }}/${{ matrix.platform }}/MapWinGIS.Core.Tests.exe" + & $exe --gtest_output="xml:testresults-${{ matrix.platform }}-${{ matrix.configuration }}.xml" + + - name: Upload test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: testresults-${{ matrix.platform }}-${{ matrix.configuration }} + path: testresults-*.xml + + - name: Upload binaries + if: matrix.configuration == 'Release' + uses: actions/upload-artifact@v4 + with: + name: MapWinGIS.Core-${{ matrix.platform }} + path: bin/Release/${{ matrix.platform }}/ diff --git a/.gitignore b/.gitignore index d5a18de..2753665 100644 --- a/.gitignore +++ b/.gitignore @@ -427,3 +427,6 @@ FodyWeavers.xsd *.msix *.msm *.msp + +# vcpkg installed libraries +vcpkg_installed/ diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..884c643 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,5 @@ +{ + "recommendations": [ + "github.vscode-github-actions" + ] +} \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..78c16e7 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,72 @@ +# AGENTS.md + +Instructions for AI coding agents (GitHub Copilot, Claude Code, etc.) working +in this repository. + +## Contents + +- [Mission](#mission) +- [Repository layout](#repository-layout) +- [Build, test, validate](#build-test-validate) +- [Ground rules](#ground-rules) +- [Detailed guidance](#detailed-guidance) + +## Mission + +MapWinGIS6 re-implements MapWinGIS โ€” a 20-year-old open-source MFC/ATL +ActiveX GIS control โ€” as modern C++: + +- **`MapWinGIS.Core.dll`** โ€” the mapping engine as a plain C++ DLL. No COM, + ATL or MFC. Usable and testable on its own. +- **`MapWinGIS.ocx`** โ€” a thin ActiveX/COM wrapper over the core that keeps + the MapWinGIS 5 API. Not started yet. + +[MapWinGIS 5](https://github.com/MapWindow/MapWinGIS) is the reference +implementation and the behavioral ground truth. Port its functionality; do +not transliterate its code. + +## Repository layout + +| Path | Contents | +|---|---| +| `src/MapWinGIS.Core/` | Core engine. Public headers in `include/mapwingis/`, implementation in `src/`, grouped by area (`core`, `gdal`, `vector`, ...) | +| `tests/MapWinGIS.Core.Tests/` | GoogleTest unit tests; shared fixtures in `TestData.h/.cpp` | +| `build/` | Shared MSBuild props, vcpkg overlay triplets, bootstrap scripts | +| `docs/` | Detailed documentation (see table below) | + +## Build, test, validate + +```powershell +pwsh -File build\scripts\bootstrap-vcpkg.ps1 +msbuild MapWinGIS6.slnx -p:Configuration=Debug -p:Platform=x64 -m +bin\Debug\x64\MapWinGIS.Core.Tests.exe +``` + +Every task must leave the tree in this state: `Debug | x64` builds with no +new Level 4 warnings and all tests pass. Full build details, vcpkg features +and switches: [docs/BUILDING.md](docs/BUILDING.md). + +## Ground rules + +1. **Modernize, don't transliterate.** MapWinGIS 5 code is a behavior + reference. Rewrite it as clean C++20 in the style already in this tree. +2. **Core stays pure.** No COM, ATL or MFC in `MapWinGIS.Core`; COM concerns + belong to the future ActiveX layer. +3. **Match existing conventions.** SPDX header, Doxygen file block, `mwg` + namespace, PImpl classes, `[[nodiscard]]`, exceptions with `TryX` + companions. Full list: [docs/CODING-STANDARDS.md](docs/CODING-STANDARDS.md). +4. **Preserve the MapWinGIS 5 contract.** 0-based feature indexes, enum + values pinned to the v5 type library, error semantics. + See [docs/PORTING.md](docs/PORTING.md). +5. **Tests with every feature.** GoogleTest with generated fixtures via + `TestData.h`. Conventions: [docs/TESTING.md](docs/TESTING.md). + +## Detailed guidance + +| Topic | File | +|---|---| +| Build details, vcpkg, switches, troubleshooting | [docs/BUILDING.md](docs/BUILDING.md) | +| Architecture, DLL design, GDAL lifecycle, threading | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | +| Coding style and API conventions | [docs/CODING-STANDARDS.md](docs/CODING-STANDARDS.md) | +| Porting behavior from MapWinGIS 5 | [docs/PORTING.md](docs/PORTING.md) | +| Writing and running tests | [docs/TESTING.md](docs/TESTING.md) | diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..2a67dd2 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,66 @@ + + + + + + + $(MSBuildThisFileDirectory) + 6.0.0 + + + + + v145 + + 10.0.28000.0 + $(MwgWindowsSdk) + + + + + $(MwgRepoRoot)bin\$(Configuration)\$(Platform)\ + $(MwgRepoRoot)obj\$(MSBuildProjectName)\$(Configuration)\$(Platform)\ + + + + + + $(MWG_VCPKG_ROOT) + $(MwgRepoRoot)..\vcpkg + $(VCPKG_ROOT) + + $(MwgVcpkgRoot) + true + true + $(MwgRepoRoot) + $(MwgRepoRoot)vcpkg_installed\ + false + true + true + + x64-windows-v145 + x86-windows-v145 + x64-windows-v145 + + + tests + --overlay-triplets=$(MwgRepoRoot)build\triplets --x-feature=$(MwgVcpkgFeatures.Replace(';',' --x-feature=')) + + + + $(VcpkgInstalledDir)$(VcpkgTriplet)\ + $(MwgVcpkgTripletDir)share\ + $(MwgVcpkgTripletDir)share\ + + + + + + + diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 0000000..d049ac3 --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,42 @@ + + + + + + + true + + + + + + + + + + + + + + + + + + + diff --git a/LICENSE b/LICENSE index cecca9b..a612ad9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,373 @@ -MIT License - -Copyright (c) 2026 MapWindow Open Source GIS - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/MapWinGIS6.runsettings b/MapWinGIS6.runsettings new file mode 100644 index 0000000..28e3e43 --- /dev/null +++ b/MapWinGIS6.runsettings @@ -0,0 +1,6 @@ + + + + true + + \ No newline at end of file diff --git a/MapWinGIS6.slnx b/MapWinGIS6.slnx new file mode 100644 index 0000000..5febc07 --- /dev/null +++ b/MapWinGIS6.slnx @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/README.md b/README.md index 636318f..d7f5b27 100644 --- a/README.md +++ b/README.md @@ -1 +1,79 @@ -# MapWinGIS6 \ No newline at end of file +# MapWinGIS6 + +MapWinGIS6 is the next major version of [MapWinGIS](https://github.com/MapWindow/MapWinGIS), +the open-source mapping engine behind MapWindow. + +MapWinGIS 5 is one large MFC/ATL project that builds `MapWinGIS.ocx`. Version 6 +splits that into two layers: + +- **`MapWinGIS.Core.dll`** โ€” the mapping engine as a normal C++ DLL, with no + COM, ATL or MFC. It can be used and tested on its own. +- **`MapWinGIS.ocx`** โ€” a thin ActiveX/COM wrapper over the core, keeping the + existing API so that current C#, VB.NET, WPF, Delphi and VB6 applications + keep working. + +MapWinGIS 5.x stays available and remains the reference implementation during +the migration. + +## Status + +Early. The core currently includes GDAL setup and OGR-backed vector dataset +and layer access, including feature and field reading and updates. Available +formats depend on the GDAL drivers enabled in the build; tests cover shapefiles +and GeoPackage. The ActiveX layer has not been added yet. + +## Build and test + +### Prerequisites + +- Windows +- Visual Studio 2026 (18.10 or later) with the **Desktop development with C++** workload, including MSVC v145 and Windows SDK 10.0.28000.0 +- Git and PowerShell 7 (`pwsh`) +- About 15 GB of free disk space for dependencies and build outputs + +### First build + +From the repository root, bootstrap vcpkg and build the solution: + +```powershell +pwsh -File build\scripts\bootstrap-vcpkg.ps1 +msbuild MapWinGIS6.slnx -p:Configuration=Debug -p:Platform=x64 -m +``` + +The bootstrap script clones and initializes vcpkg in a sibling `vcpkg` folder +unless an existing vcpkg installation is configured. The first build uses +vcpkg to compile GDAL and its dependencies, so it can take a while; subsequent +builds use the local binary cache. No dependency downloads or environment +configuration are needed by hand. + +Alternatively, after bootstrapping vcpkg, open `MapWinGIS6.slnx` in Visual +Studio and build the `Debug | x64` configuration. + +### Run the C++ tests + +The solution build includes the GoogleTest project by default. After building, +run the test executable from the repository root: + +```powershell +bin\Debug\x64\MapWinGIS.Core.Tests.exe +``` + +You can also run the tests through Visual Studio's Test Explorer. For the +Release configuration, build with `-p:Configuration=Release` and run +`bin\Release\x64\MapWinGIS.Core.Tests.exe`. + +For additional configurations, dependency features, and troubleshooting, see +[docs/BUILDING.md](docs/BUILDING.md). + +## Layout + +| Path | Contents | +|---|---| +| `src/MapWinGIS.Core/` | The core engine. Public headers in `include/mapwingis/` | +| `tests/MapWinGIS.Core.Tests/` | C++ unit tests (GoogleTest) | +| `build/` | Shared MSBuild props, vcpkg triplets and scripts | +| `docs/` | Build, architecture, coding, porting and testing documentation | + +## License + +Mozilla Public License 2.0. See [LICENSE](LICENSE). diff --git a/build/props/MapWinGIS.Cpp.props b/build/props/MapWinGIS.Cpp.props new file mode 100644 index 0000000..82320e9 --- /dev/null +++ b/build/props/MapWinGIS.Cpp.props @@ -0,0 +1,79 @@ + + + + + + + Unicode + true + false + false + false + false + + + + + stdcpp20 + stdc17 + true + true + Level4 + true + ProgramDatabase + Sync + /utf-8 /Zc:__cplusplus /Zc:preprocessor /Zc:throwingNew /bigobj %(AdditionalOptions) + + WIN32_LEAN_AND_MEAN; + NOMINMAX; + _WIN32_WINNT=0x0A00; + WINVER=0x0A00; + NTDDI_VERSION=0x0A00000B; + _CRT_SECURE_NO_WARNINGS; + MWG_VERSION="$(MwgVersion)"; + %(PreprocessorDefinitions) + + + 4251;%(DisableSpecificWarnings) + + + true + Windows + true + true + /HIGHENTROPYVA %(AdditionalOptions) + + + + + + Disabled + MultiThreadedDebugDLL + EnableFastChecks + _DEBUG;%(PreprocessorDefinitions) + + + + + + MaxSpeed + MultiThreadedDLL + true + true + Guard + NDEBUG;%(PreprocessorDefinitions) + + + true + true + + + + + + /fsanitize=address %(AdditionalOptions) + + + + diff --git a/build/scripts/bootstrap-vcpkg.ps1 b/build/scripts/bootstrap-vcpkg.ps1 new file mode 100644 index 0000000..16bfe80 --- /dev/null +++ b/build/scripts/bootstrap-vcpkg.ps1 @@ -0,0 +1,60 @@ +<# +.SYNOPSIS + Makes a vcpkg installation available for building MapWinGIS6. + +.DESCRIPTION + Resolves a vcpkg root in this order: + 1. -VcpkgRoot + 2. the MWG_VCPKG_ROOT environment variable + 3. \..\vcpkg (cloned here by default) + 4. the VCPKG_ROOT environment variable + + Clones and bootstraps vcpkg when needed, and enables the local binary cache. + MSBuild resolves the same locations, so after running this once the solution + builds without further setup. +#> +[CmdletBinding()] +param( + [string] $VcpkgRoot, + [switch] $Update +) + +$ErrorActionPreference = 'Stop' + +$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path + +function Resolve-VcpkgRoot { + if ($VcpkgRoot) { return $VcpkgRoot } + if ($env:MWG_VCPKG_ROOT) { return $env:MWG_VCPKG_ROOT } + + $sibling = Join-Path (Split-Path $repoRoot -Parent) 'vcpkg' + if (Test-Path (Join-Path $sibling '.vcpkg-root')) { return $sibling } + if ($env:VCPKG_ROOT -and (Test-Path (Join-Path $env:VCPKG_ROOT '.vcpkg-root'))) { return $env:VCPKG_ROOT } + + return $sibling +} + +$root = Resolve-VcpkgRoot +Write-Host "vcpkg root: $root" + +if (-not (Test-Path (Join-Path $root '.vcpkg-root'))) { + Write-Host 'Cloning vcpkg...' + git clone https://github.com/microsoft/vcpkg.git $root +} +elseif ($Update) { + Write-Host 'Updating vcpkg...' + git -C $root pull --ff-only +} + +$exe = Join-Path $root 'vcpkg.exe' +if (-not (Test-Path $exe) -or $Update) { + Write-Host 'Bootstrapping vcpkg...' + & (Join-Path $root 'bootstrap-vcpkg.bat') -disableMetrics + if ($LASTEXITCODE -ne 0) { throw "bootstrap-vcpkg.bat failed with exit code $LASTEXITCODE" } +} + +& $exe version + +Write-Host '' +Write-Host 'Done. MapWinGIS6 will find this vcpkg automatically.' +Write-Host 'To use a different location, set MWG_VCPKG_ROOT or pass /p:MwgVcpkgRoot= to MSBuild.' diff --git a/build/triplets/x64-windows-v145.cmake b/build/triplets/x64-windows-v145.cmake new file mode 100644 index 0000000..cc17452 --- /dev/null +++ b/build/triplets/x64-windows-v145.cmake @@ -0,0 +1,7 @@ +set(VCPKG_TARGET_ARCHITECTURE x64) +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE dynamic) + +# Pinned so that the dependencies are built with the same toolset as MapWinGIS6 +# even when an older Visual Studio is also installed. +set(VCPKG_PLATFORM_TOOLSET v145) diff --git a/build/triplets/x86-windows-v145.cmake b/build/triplets/x86-windows-v145.cmake new file mode 100644 index 0000000..cc4d8e5 --- /dev/null +++ b/build/triplets/x86-windows-v145.cmake @@ -0,0 +1,7 @@ +set(VCPKG_TARGET_ARCHITECTURE x86) +set(VCPKG_CRT_LINKAGE dynamic) +set(VCPKG_LIBRARY_LINKAGE dynamic) + +# Pinned so that the dependencies are built with the same toolset as MapWinGIS6 +# even when an older Visual Studio is also installed. +set(VCPKG_PLATFORM_TOOLSET v145) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..85a49f3 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,76 @@ +# Architecture + +## Two layers + +MapWinGIS6 splits the monolithic MapWinGIS 5 control into two layers: + +1. **MapWinGIS.Core.dll** โ€” the mapping engine, a plain C++ DLL. All logic + lives here. No COM, ATL or MFC anywhere in this layer. +2. **MapWinGIS.ocx** โ€” a thin ActiveX/COM wrapper (not started yet). Its only + jobs are to expose the v5 COM API, translate between COM and core types, + and convert core exceptions into MapWinGIS error codes. + +Everything that can be tested must be testable through the core alone. + +## Module design + +- Public API lives in `src/MapWinGIS.Core/include/mapwingis//`, grouped + by area (`core`, `gdal`, `vector`, ...). All of it is in namespace `mwg`. +- Implementation lives in `src/MapWinGIS.Core/src//`, mirroring the + public header names. Shared internals that are not part of the public API go + in `src/internal/`. +- Public classes use the PImpl idiom: a private `Impl` class held in a + `std::unique_ptr _impl`, constructed via + `explicit X(std::unique_ptr)`. Public headers stay free of + third-party includes โ€” GDAL/OGR types never appear in public headers. + Copying is disabled; there is no inheritance in public APIs. +- Exported classes and functions are marked `MWG_CORE_API` + (`mapwingis/core/Api.h`). + +## DLL boundary + +Exceptions cross the `MapWinGIS.Core.dll` boundary (`CoreError` and its +subclasses). This is safe because every binary in the product is built with +one toolset and one CRT (`build/props/MapWinGIS.Cpp.props` disables warning +4251 for exactly that reason). The ActiveX layer is responsible for +translating these exceptions into the MapWinGIS error codes its consumers +expect. + +## Errors + +- Operations that can fail throw `CoreError` (or a subclass such as + `OpenFailed`); see `mapwingis/core/Error.h`. +- Offer a `TryX` companion that returns `nullptr`/`std::optional` instead of + throwing when probing is a normal use case (e.g. `Open`/`TryOpen`). +- `std::optional` reports absent *values* (null cells, missing doubles), not + operational failure. Keep the two distinct. + +## GDAL lifecycle + +- Everything that touches GDAL goes through + `mapwingis/gdal/GdalEnvironment.h`. `GdalEnvironment::Initialize()` is + idempotent and thread-safe; call it before any GDAL use. +- GDAL and PROJ data (`gdal-data`, `proj.db`) are deployed next to + `MapWinGIS.Core.dll` by the build (`Directory.Build.targets`, + `MwgDeployRuntimeData`). Code must point GDAL/PROJ at those locations via + `GdalEnvironment` โ€” never via `GDAL_DATA`/`PROJ_LIB` environment variables. +- Use `GdalEnvironment::QuietScope` to suppress GDAL diagnostics in tests and + in code paths where failure is expected. +- Observe GDAL errors through the thread-local `LastErrorMessage()` / + `SetLogHandler()`. Never write to stderr and never show message boxes from + the core. + +## Threading + +Core objects are not thread-safe unless their documentation explicitly says +otherwise. Even `const` methods may cache state (see `VectorLayer`). The +pattern is: one dataset object per thread, or serialized access. +`GdalEnvironment` initialization is the exception โ€” safe to call from +anywhere. + +## Current state + +The tree is early: GDAL environment setup and vector reading/editing +(`VectorDataset`, `VectorLayer`, backed by OGR) are the first slices. Areas +still to be ported (map control, rendering, raster, tiles, ...) get new +`` folders under both `include/mapwingis/` and `src/`. diff --git a/docs/BUILDING.md b/docs/BUILDING.md new file mode 100644 index 0000000..67fd6ab --- /dev/null +++ b/docs/BUILDING.md @@ -0,0 +1,123 @@ +# Building MapWinGIS6 + +## Prerequisites + +| Requirement | Version | Notes | +|---|---|---| +| Visual Studio 2026 | 18.10 or later | Workload **Desktop development with C++** | +| MSVC toolset | v145 (14.51 or later) | Installed with the workload | +| Windows SDK | 10.0.28000.0 | Override with `/p:MwgWindowsSdk=10.0` to use the newest installed instead | +| Git | any recent version | Needed to clone vcpkg | +| Disk space | about 15 GB | vcpkg sources, build trees and binaries | + +The ActiveX layer is not part of the solution yet. When it arrives it will also +need the **C++ MFC** and **C++ ATL** components. + +## First build + +```powershell +# 1. Get vcpkg. Clones into ..\vcpkg next to this repository by default. +pwsh -File build\scripts\bootstrap-vcpkg.ps1 + +# 2. Build. The first build compiles GDAL and its dependencies from source and +# takes a while; later builds reuse the vcpkg binary cache. +msbuild MapWinGIS6.slnx -p:Configuration=Debug -p:Platform=x64 -m +``` + +Or just open `MapWinGIS6.slnx` in Visual Studio after step 1 and build. + +### Where vcpkg is found + +`Directory.Build.props` and `bootstrap-vcpkg.ps1` look in this order: + +1. `/p:MwgVcpkgRoot=` on the MSBuild command line +2. the `MWG_VCPKG_ROOT` environment variable +3. `..\vcpkg` next to the repository +4. the `VCPKG_ROOT` environment variable + +## Configurations and platforms + +| | | +|---|---| +| Configurations | `Debug` (`/MDd`, `_DEBUG`), `Release` (`/MD`, `/O2`) | +| Platforms | `x64`, `Win32` | +| Triplets | `x64-windows-v145`, `x86-windows-v145` (in `build/triplets`, pinned to v145) | +| Output | `bin\\\` | +| Intermediates | `obj\\\\` | + +Nothing is written outside the repository and no environment variables are +changed. The build does not register anything with COM. + +## Dependencies + +All dependencies come from vcpkg; see `vcpkg.json`. There is no manual SDK +download and no `support\` folder. + +Manifest features: + +| Feature | Contents | When | +|---|---|---| +| (default) | GDAL with the recommended drivers plus the small permissive codecs | Everyday development | +| `tests` | GoogleTest | Enabled by default through `MwgVcpkgFeatures` | +| `full-drivers` | Adds HDF5, NetCDF, KML, SpatiaLite and PostgreSQL to GDAL | Release packages. Much slower to build | + +```powershell +msbuild MapWinGIS6.slnx -p:Platform=x64 -p:Configuration=Release -p:MwgVcpkgFeatures="tests;full-drivers" +``` + +### Runtime data + +vcpkg installs `gdal-data` and `proj.db` under `vcpkg_installed\\share`. +A target in `Directory.Build.targets` copies them into the output folder as +`gdal-data\` and `proj\`, and `GdalEnvironment` points GDAL and PROJ at them. +No `GDAL_DATA` or `PROJ_LIB` environment variable is needed or set. + +### Binary cache + +vcpkg caches built packages in `%LOCALAPPDATA%\vcpkg\archives` by default, so a +rebuild or a second platform is fast. To share a cache across machines, set +`VCPKG_BINARY_SOURCES`, for example: + +```powershell +$env:VCPKG_BINARY_SOURCES = 'clear;files,\\server\share\vcpkg-cache,readwrite' +``` + +## Running the tests + +```powershell +bin\Debug\x64\MapWinGIS.Core.Tests.exe +``` + +Or use Test Explorer in Visual Studio, which picks up the GoogleTest adapter +automatically. + +For CI, write a JUnit-style report: + +```powershell +bin\Release\x64\MapWinGIS.Core.Tests.exe --gtest_output=xml:testresults.xml +``` + +## Extra build switches + +| Property | Default | Effect | +|---|---|---| +| `MwgWindowsSdk` | `10.0.28000.0` | Windows SDK version. `10.0` means "newest installed" | +| `MwgVcpkgRoot` | resolved (see above) | vcpkg location | +| `MwgVcpkgFeatures` | `tests` | Semicolon-separated manifest features | +| `MwgEnableAsan` | `false` | Adds `/fsanitize=address` | +| `MwgDeployRuntimeData` | `true` | Copies `gdal-data` and `proj` to the output folder | + +## Troubleshooting + +**`Invalid triplet: x64-windows-v145`** +vcpkg was run without the overlay triplets. Build through MSBuild, or pass +`--overlay-triplets=build\triplets` when calling vcpkg directly. + +**`gdal-data is missing`, reported by a test** +The dependencies are not installed yet, or `MwgDeployRuntimeData` was turned +off. Rebuild after running the bootstrap script. + +**vcpkg picks the wrong compiler** +The triplets pin `VCPKG_PLATFORM_TOOLSET v145`. If an older Visual Studio is +still selected, check that the VS 2026 C++ workload is installed and delete +`vcpkg_installed\` before rebuilding. diff --git a/docs/CODING-STANDARDS.md b/docs/CODING-STANDARDS.md new file mode 100644 index 0000000..b97d8b6 --- /dev/null +++ b/docs/CODING-STANDARDS.md @@ -0,0 +1,88 @@ +# Coding standards + +The existing sources are the normative examples. This file names the rules so +new code is indistinguishable from existing code. + +## File layout and headers + +- Every source file starts with `// SPDX-License-Identifier: MPL-2.0` + followed by a Doxygen file block: + + ```cpp + /** + * @file VectorDataset.h + * @brief Declares the vector dataset and layer APIs. + * + * (Optional extra paragraphs with behavioral notes.) + */ + ``` + +- Use `#pragma once`; no include guards. +- One class (or a small group of closely related types) per header, with a + matching `.cpp`. +- Public headers include only standard-library and other public MapWinGIS + headers. Third-party headers (GDAL/OGR, Windows internals) belong in the + `.cpp` or in `src/internal/`. + +## Language and toolchain + +- C++20 (`stdcpp20`, C17), conformance mode, `/utf-8`, `/Zc:__cplusplus`, + `/Zc:preprocessor`, `/Zc:throwingNew`. +- Warning level 4 with zero new warnings; SDL checks on. Do not silence + warnings with pragmas in source โ€” fix the code. + +## Formatting + +- 4-space indentation, no tabs; Allman braces; `case` labels indented under + `switch`. +- `namespace mwg { ... }` with contents indented one level. +- Naming: `PascalCase` public methods and types, `_camelCase` private members + (`_impl`, `_dataset`), `kPascalCase` compile-time constants + (`SampleLayer::kFeatureCount`). + +## API shape + +- All public API is in `namespace mwg` and exported with `MWG_CORE_API`. +- PImpl: declare `class Impl;` privately, construct via + `explicit X(std::unique_ptr)`, store as `std::unique_ptr _impl`. + Delete copy constructor and assignment; add move semantics only when there + is a real need. +- Mark every non-void query `[[nodiscard]]`. +- Return `std::optional` for possibly-absent values, `std::unique_ptr` for + owning factory results; take paths as `std::filesystem::path` and read-only + strings as `std::string_view`. +- No output parameters, no raw owning pointers, no `new`/`delete` outside of + PImpl construction. +- Document on the declaration: behavior, thread-safety, performance + characteristics, and exceptions (`\throws`) โ€” in the style of the existing + headers. State "not thread-safe" explicitly whenever it is true. + +## Types + +- `enum class` with an explicit underlying type + (`enum class ShapeType : int`). +- When an enum mirrors a MapWinGIS 5 type-library enum, the numeric values + are pinned and must never be renumbered โ€” the ActiveX layer converts with a + `static_cast`. Note the pinning in the doc comment. +- Small type-safe helpers belong next to the enum + (`constexpr ShapeType BaseShapeType(ShapeType) noexcept`). + +## Errors and validation + +- Throw `CoreError` subclasses (`mapwingis/core/Error.h`) for operational + failure. Messages are plain English and suitable for surfacing through the + ActiveX layer. +- Validate indexes and arguments at the API boundary and throw on violation. +- Never `catch (...)` silently, never show UI, never log to `std::cout` from + the core. Report through `GdalEnvironment` diagnostics or throw. + +## Windows and dependencies + +- The environment defines `NOMINMAX`, `WIN32_LEAN_AND_MEAN` and + `_WIN32_WINNT=0x0A00` globally. Write code that works with them; do not + `#undef` or redefine them. +- The `min`/`max` macros are off: use `std::min`/`std::max`. +- All third-party dependencies come from the vcpkg manifest (`vcpkg.json`). + Never vendor libraries, download SDKs by hand, or add `support/` folders. +- The product is Unicode (`CharacterSet=Unicode`); use wide APIs at the + boundary and convert explicitly. diff --git a/docs/PORTING.md b/docs/PORTING.md new file mode 100644 index 0000000..195f6b7 --- /dev/null +++ b/docs/PORTING.md @@ -0,0 +1,52 @@ +# Porting from MapWinGIS 5 + +[MapWinGIS 5](https://github.com/MapWindow/MapWinGIS) is a single large +MFC/ATL project (the `CMapView` control plus COM classes, with the type +library in `MapWinGIS.odl`). It is the **reference implementation**: when +re-creating a feature, its behavior is the specification. The goal is a +modern rewrite, not a line-by-line translation. + +## What "port" means here + +1. **Study the v5 behavior.** Read the v5 sources for the feature: what the + public API accepts and returns, edge cases, error behavior, units, + coordinate order and defaults. +2. **Design the core API first.** Express it with the current conventions + (PImpl class in `include/mapwingis//`, `std::optional`, exceptions + with `TryX` companions). Resist mirroring v5 class hierarchies and COM + signatures. +3. **Implement in the core and test against the spec.** Add GoogleTest + coverage for the ported behavior, including edge cases and failures. +4. **Leave COM mapping to the ActiveX layer.** Later, the wrapper maps core + types and exceptions onto the v5 COM API and error codes. + +## Behavioral contract to preserve + +The ActiveX layer will be a mechanical translation, so the core must keep the +following true: + +- **Feature/shape indexes are 0-based** and match v5 shape indexes exactly. +- **Enums that correspond to v5 type-library enums keep identical numeric + values** (see `ShapeType`/`FieldType` in `mapwingis/core/Enums.h`). Add the + same pinning note to every new ported enum. +- **Error semantics**: v5 reports failures via error codes and + `LastErrorMessage`-style state; the core throws or returns + `std::optional`, with the same information in the exception message. +- **Formatting**: where v5 formats values for display (e.g. `CellValue` + text), the core keeps the same textual output. + +## Anti-patterns + +- Do not copy the v5 file organization (flat folders, `stdafx.h`, COM maps). +- Do not port MFC containers (`CString`, `CArray`, `CMap`) โ€” use + `std::string`, `std::vector`, `std::map`. +- Do not port GDI rendering or window-message logic into the core. Rendering + gets its own core area designed for it; the COM control merely forwards. +- Do not "improve" behavior silently. Differences from v5 must be deliberate + and recorded in the header's doc comment so the ActiveX implementation and + future maintainers can see the decision. + +## When v5 behavior is unclear or contradictory + +Prefer the behavior the [MapWindow application](https://github.com/MapWindow/MapWindow5) and its existing tests depend +on, and record the decision in the relevant header doc comment. diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..4915835 --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,45 @@ +# Testing + +- Framework: GoogleTest, provided by the vcpkg `tests` feature (enabled by + default through `MwgVcpkgFeatures`). +- Test project: `tests/MapWinGIS.Core.Tests`, built with the solution. +- Shared fixtures and helpers live in `TestData.h/.cpp` (`TempDirectory`, + `MakeSampleShapefile`, `MakeProvincesDataset`, and layer constants). Extend + these instead of writing per-file fixture code. + +## Running + +```powershell +bin\Debug\x64\MapWinGIS.Core.Tests.exe +bin\Release\x64\MapWinGIS.Core.Tests.exe --gtest_output=xml:testresults.xml # CI +``` + +Also runnable from Visual Studio Test Explorer (GoogleTest adapter picks it +up automatically). + +## Conventions + +- One test file per area under test (`VectorDatasetTests.cpp`, + `VectorLayerTests.cpp`, `GdalEnvironmentTests.cpp`). +- Fixture classes go in an anonymous namespace and derive from `testing::Test` + or `testing::TestWithParam` for parameterized cases. Use `protected:` + `SetUp()` and production member naming (`_camelCase`). +- Test names are PascalCase behavior statements: + `ReportsTheDriverAndPath`, `RejectsOutOfRangeFieldIndexes`. Use `TEST_F` + with fixtures, `TEST_P` with parameterized fixtures, and plain `TEST` for + one-off cases. Register parameter values with `INSTANTIATE_TEST_SUITE_P`. +- Prefer `EXPECT_*`; use `ASSERT_*` only when continuing would crash (e.g. + before dereferencing). +- Cast `[[nodiscard]]` returns to `(void)` inside `EXPECT_THROW`. +- Append `<< value` to expectations on strings when the failure output + matters. +- Test files carry the same SPDX and Doxygen header as production files. +- Cover for each feature: happy path, empty/missing input, out-of-range + indexes, null values, non-ASCII paths, write-then-reopen round-trips, and + error cases. +- Test data is generated at runtime inside a `TempDirectory`; do not commit + shapefiles or databases to the repository. +- `MakeProvincesDataset` creates Shapefile and GeoPackage fixtures for layer + tests. Each has four polygons in EPSG:28992, all five field types, null + values, and UTF-8 names. Tests edit their own generated datasets. +- Wrap expected GDAL noise in `GdalEnvironment::QuietScope`. diff --git a/src/MapWinGIS.Core/MapWinGIS.Core.vcxproj b/src/MapWinGIS.Core/MapWinGIS.Core.vcxproj new file mode 100644 index 0000000..7e63345 --- /dev/null +++ b/src/MapWinGIS.Core/MapWinGIS.Core.vcxproj @@ -0,0 +1,67 @@ + + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + + {2B6A9A3B-0C5E-4E6E-9E31-3E8F5A2D1C01} + MapWinGISCore + MapWinGIS.Core + MapWinGIS.Core + + + + + + DynamicLibrary + + + + + + + + + + + $(MSBuildProjectDirectory)\include;$(MSBuildProjectDirectory)\src;%(AdditionalIncludeDirectories) + MWG_CORE_BUILD;%(PreprocessorDefinitions) + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/MapWinGIS.Core/include/mapwingis/core/Api.h b/src/MapWinGIS.Core/include/mapwingis/core/Api.h new file mode 100644 index 0000000..153e978 --- /dev/null +++ b/src/MapWinGIS.Core/include/mapwingis/core/Api.h @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file Api.h + * @brief Defines the DLL import/export attribute for the core API. + * + * Consumers exchange standard-library types across the DLL boundary and must + * use the same toolset and CRT as MapWinGIS.Core.dll. + */ +#pragma once + +/// Export/import attribute for the public MapWinGIS.Core API. +/// +/// The API uses standard library types across the DLL boundary, so consumers +/// must be built with the same toolset and CRT as MapWinGIS.Core.dll. Every +/// binary in the MapWinGIS product satisfies that. +#ifdef MWG_CORE_BUILD +#define MWG_CORE_API __declspec(dllexport) +#else +#define MWG_CORE_API __declspec(dllimport) +#endif diff --git a/src/MapWinGIS.Core/include/mapwingis/core/Enums.h b/src/MapWinGIS.Core/include/mapwingis/core/Enums.h new file mode 100644 index 0000000..bfcd7d2 --- /dev/null +++ b/src/MapWinGIS.Core/include/mapwingis/core/Enums.h @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file Enums.h + * @brief Defines geometry and attribute types used by the core API. + * + * ShapeType and FieldType retain the numeric values of the corresponding + * MapWinGIS 5 enums for conversion by the ActiveX layer. + */ +#pragma once + +namespace mwg +{ + /// Geometry type of a layer or shape. + /// + /// The values are identical to the ShpfileType enum of the MapWinGIS 5 type + /// library, so the ActiveX layer can convert with a static_cast. + enum class ShapeType : int + { + NullShape = 0, + Point = 1, + PolyLine = 3, + Polygon = 5, + MultiPoint = 8, + PointZ = 11, + PolyLineZ = 13, + PolygonZ = 15, + MultiPointZ = 18, + PointM = 21, + PolyLineM = 23, + PolygonM = 25, + MultiPointM = 28, + MultiPatch = 31, + }; + + /// Attribute field type. + /// + /// The values are identical to the FieldType enum of the MapWinGIS 5 type + /// library. + enum class FieldType : int + { + String = 0, + Integer = 1, + Double = 2, + Boolean = 3, + Date = 4, + }; + + /// Drops the Z and M variants, e.g. PolygonZ -> Polygon. + constexpr ShapeType BaseShapeType(const ShapeType type) noexcept + { + switch (type) + { + case ShapeType::PointZ: + case ShapeType::PointM: + return ShapeType::Point; + case ShapeType::PolyLineZ: + case ShapeType::PolyLineM: + return ShapeType::PolyLine; + case ShapeType::PolygonZ: + case ShapeType::PolygonM: + return ShapeType::Polygon; + case ShapeType::MultiPointZ: + case ShapeType::MultiPointM: + return ShapeType::MultiPoint; + default: + return type; + } + } +} diff --git a/src/MapWinGIS.Core/include/mapwingis/core/Error.h b/src/MapWinGIS.Core/include/mapwingis/core/Error.h new file mode 100644 index 0000000..db0e14a --- /dev/null +++ b/src/MapWinGIS.Core/include/mapwingis/core/Error.h @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file Error.h + * @brief Declares exceptions used to report core operation failures. + * + * CoreError is the base exception and OpenFailed represents data source open + * failures. The ActiveX layer translates these exceptions to MapWinGIS errors. + */ +#pragma once + +#include +#include + +#include "mapwingis/core/Api.h" + +namespace mwg +{ + /// Thrown when a core operation fails. + /// + /// Exceptions cross the MapWinGIS.Core.dll boundary; see Api.h for why that + /// is safe here. The ActiveX layer converts them into MapWinGIS error codes. + /// Export constructors individually because MSVC's std::runtime_error is + /// not a DLL-interface base class. + class CoreError : public std::runtime_error + { + public: + MWG_CORE_API explicit CoreError(const std::string& message) + : std::runtime_error(message) + { + } + }; + + /// A file could not be opened, or no driver could read it. + class OpenFailed : public CoreError + { + public: + MWG_CORE_API explicit OpenFailed(const std::string& message) + : CoreError(message) + { + } + }; +} diff --git a/src/MapWinGIS.Core/include/mapwingis/core/Extent.h b/src/MapWinGIS.Core/include/mapwingis/core/Extent.h new file mode 100644 index 0000000..82a4e18 --- /dev/null +++ b/src/MapWinGIS.Core/include/mapwingis/core/Extent.h @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file Extent.h + * @brief Defines an axis-aligned 2D bounding extent. + * + * Extent represents an empty or bounded coordinate region and provides + * containment, intersection, and union operations for core geometry APIs. + */ +#pragma once + +#include +#include + +#include "mapwingis/core/Api.h" + +namespace mwg +{ + /// Axis-aligned bounding box. Default-constructed instances are empty. + struct MWG_CORE_API Extent + { + double xMin = std::numeric_limits::quiet_NaN(); + double yMin = std::numeric_limits::quiet_NaN(); + double xMax = std::numeric_limits::quiet_NaN(); + double yMax = std::numeric_limits::quiet_NaN(); + + constexpr Extent() = default; + + constexpr Extent(const double xMinimum, const double yMinimum, + const double xMaximum, const double yMaximum) noexcept + : xMin(xMinimum), yMin(yMinimum), xMax(xMaximum), yMax(yMaximum) + { + } + + [[nodiscard]] bool IsEmpty() const noexcept + { + return !(xMin <= xMax && yMin <= yMax); + } + + [[nodiscard]] double Width() const noexcept { return IsEmpty() ? 0.0 : xMax - xMin; } + [[nodiscard]] double Height() const noexcept { return IsEmpty() ? 0.0 : yMax - yMin; } + [[nodiscard]] double CenterX() const noexcept { return (xMin + xMax) / 2.0; } + [[nodiscard]] double CenterY() const noexcept { return (yMin + yMax) / 2.0; } + + [[nodiscard]] bool Intersects(const Extent& other) const noexcept + { + if (IsEmpty() || other.IsEmpty()) return false; + return xMin <= other.xMax && xMax >= other.xMin && + yMin <= other.yMax && yMax >= other.yMin; + } + + [[nodiscard]] bool Contains(const double x, const double y) const noexcept + { + return !IsEmpty() && x >= xMin && x <= xMax && y >= yMin && y <= yMax; + } + + [[nodiscard]] Extent Union(const Extent& other) const noexcept + { + if (IsEmpty()) return other; + if (other.IsEmpty()) return *this; + return {std::min(xMin, other.xMin), std::min(yMin, other.yMin), + std::max(xMax, other.xMax), std::max(yMax, other.yMax)}; + } + }; +} diff --git a/src/MapWinGIS.Core/include/mapwingis/gdal/GdalEnvironment.h b/src/MapWinGIS.Core/include/mapwingis/gdal/GdalEnvironment.h new file mode 100644 index 0000000..0b602aa --- /dev/null +++ b/src/MapWinGIS.Core/include/mapwingis/gdal/GdalEnvironment.h @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file GdalEnvironment.h + * @brief Declares process-wide GDAL initialization and diagnostics APIs. + * + * GdalEnvironment configures runtime data paths, registers drivers, and + * exposes version, driver, and error reporting utilities. + */ +#pragma once + +#include +#include +#include +#include + +#include "mapwingis/core/Api.h" + +namespace mwg +{ + enum class LogLevel : int + { + Debug, + Warning, + Error, + }; + + /// Receives GDAL diagnostics. Called on the thread that raised them. + using LogHandler = std::function; + + /// Process-wide GDAL setup. + /// + /// Everything that touches GDAL goes through Initialize() first. It is + /// idempotent and thread-safe, so callers do not have to coordinate. + class MWG_CORE_API GdalEnvironment + { + public: + GdalEnvironment() = delete; + + /// Registers the drivers and points GDAL at the data files deployed + /// beside MapWinGIS.Core.dll. Runs at most once per process. + static void Initialize(); + + /// Same, but with explicit data locations. Only has an effect on the + /// first call. + static void Initialize(const std::filesystem::path& gdalDataDir, + const std::filesystem::path& projDataDir); + + [[nodiscard]] static bool IsInitialized() noexcept; + + /// Installs a handler for GDAL diagnostics. Pass {} to remove it. + static void SetLogHandler(LogHandler handler); + + /// Last GDAL error raised on the calling thread, or "" if there was none. + [[nodiscard]] static std::string LastErrorMessage(); + static void ClearLastError(); + + [[nodiscard]] static std::string GdalVersion(); + [[nodiscard]] static std::string GeosVersion(); + [[nodiscard]] static std::string ProjVersion(); + + [[nodiscard]] static int RasterDriverCount(); + [[nodiscard]] static int VectorDriverCount(); + [[nodiscard]] static bool HasRasterDriver(const std::string& name); + [[nodiscard]] static bool HasVectorDriver(const std::string& name); + + /// Directory the core DLL was loaded from. Runtime data lives here. + [[nodiscard]] static std::filesystem::path ModuleDirectory(); + + /// Suppresses GDAL diagnostics on the calling thread for its lifetime. + /// Uses GDAL's per-thread handler stack, so other threads are unaffected. + /// Construct and destroy on the same thread, in reverse construction + /// order. Restores the previous handler even when an exception unwinds. + class MWG_CORE_API QuietScope + { + public: + QuietScope(); + ~QuietScope(); + QuietScope(const QuietScope&) = delete; + QuietScope& operator=(const QuietScope&) = delete; + }; + }; +} diff --git a/src/MapWinGIS.Core/include/mapwingis/vector/FieldInfo.h b/src/MapWinGIS.Core/include/mapwingis/vector/FieldInfo.h new file mode 100644 index 0000000..df0dec5 --- /dev/null +++ b/src/MapWinGIS.Core/include/mapwingis/vector/FieldInfo.h @@ -0,0 +1,27 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file FieldInfo.h + * @brief Defines metadata for a vector layer attribute field. + * + * FieldInfo stores the field name, MapWinGIS field type, width, and precision + * exposed by the vector dataset API. + */ +#pragma once + +#include + +#include "mapwingis/core/Api.h" +#include "mapwingis/core/Enums.h" + +namespace mwg +{ + /// Definition of one attribute field. + struct MWG_CORE_API FieldInfo + { + std::string name; + FieldType type = FieldType::String; + int width = 0; + int precision = 0; + }; +} diff --git a/src/MapWinGIS.Core/include/mapwingis/vector/VectorDataset.h b/src/MapWinGIS.Core/include/mapwingis/vector/VectorDataset.h new file mode 100644 index 0000000..9376d05 --- /dev/null +++ b/src/MapWinGIS.Core/include/mapwingis/vector/VectorDataset.h @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file VectorDataset.h + * @brief Declares the vector dataset and layer APIs. + * + * Provides OGR-backed access to vector data, including feature attributes, + * geometry, and updates. Feature indexes are 0-based for MapWinGIS 5 + * compatibility; dataset and layer access is not thread-safe. + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "mapwingis/core/Api.h" +#include "mapwingis/core/Enums.h" +#include "mapwingis/core/Extent.h" +#include "mapwingis/vector/FieldInfo.h" + +namespace mwg +{ + class VectorDataset; + + enum class OpenMode : int + { + ReadOnly, + Update, + }; + + /// One vector layer of an open dataset. + /// + /// Layers are owned by their VectorDataset and stay valid for as long as it + /// does. Feature indexes are 0-based, matching MapWinGIS 5 shape indexes. + /// + /// Not thread-safe, not even for the const methods: they cache the most + /// recently read feature, the feature count and the extent. Use one + /// VectorDataset per thread, or serialise access. + /// + /// The first indexed feature access costs one pass over the layer to map + /// indexes onto feature ids. Later accesses are direct lookups. + /// All indexed feature access throws CoreError for an invalid index or a + /// feature that cannot be read. Null attributes and absent geometries + /// still return empty values. + class MWG_CORE_API VectorLayer + { + public: + ~VectorLayer(); + + VectorLayer(const VectorLayer&) = delete; + VectorLayer& operator=(const VectorLayer&) = delete; + + [[nodiscard]] std::string Name() const; + + /// Geometry type, mapped onto the shapefile types MapWinGIS 5 exposes. + [[nodiscard]] ShapeType Type() const; + + /// Exact count. May read the whole layer for formats that don't keep one. + [[nodiscard]] std::int64_t FeatureCount() const; + + [[nodiscard]] Extent GetExtent() const; + + [[nodiscard]] int FieldCount() const; + [[nodiscard]] const std::vector& Fields() const; + [[nodiscard]] const FieldInfo& Field(int index) const; + /// -1 when there is no field with that name (case-insensitive). + [[nodiscard]] int FieldIndex(const std::string& name) const; + + /// Layer projection as WKT, or "" when the layer has none. + [[nodiscard]] std::string ProjectionWkt() const; + + [[nodiscard]] bool IsCellNull(int fieldIndex, std::int64_t featureIndex) const; + /// Attribute formatted as text, which is what MapWinGIS 5 CellValue yields + /// for display purposes. + [[nodiscard]] std::string CellString(int fieldIndex, std::int64_t featureIndex) const; + [[nodiscard]] std::optional CellDouble(int fieldIndex, std::int64_t featureIndex) const; + [[nodiscard]] std::optional CellInteger(int fieldIndex, std::int64_t featureIndex) const; + + /// ISO WKT of the feature geometry, or "" when the feature has none. + [[nodiscard]] std::string GeometryWkt(std::int64_t featureIndex) const; + [[nodiscard]] Extent GeometryExtent(std::int64_t featureIndex) const; + + /// True when the dataset was opened with OpenMode::Update. + [[nodiscard]] bool IsWritable() const; + + /// Attribute and geometry edits. Each writes the feature back + /// immediately; the file is complete once the dataset is closed. + /// \throws CoreError when the dataset is read-only or the index is invalid. + void SetCellString(int fieldIndex, std::int64_t featureIndex, const std::string& value); + void SetCellDouble(int fieldIndex, std::int64_t featureIndex, double value); + void SetCellInteger(int fieldIndex, std::int64_t featureIndex, std::int64_t value); + void SetCellNull(int fieldIndex, std::int64_t featureIndex); + void SetGeometryWkt(std::int64_t featureIndex, const std::string& wkt); + + private: + friend class VectorDataset; + + void ValidateField(int fieldIndex) const; + + class Impl; + explicit VectorLayer(std::unique_ptr impl); + std::unique_ptr _impl; + }; + + /// An open vector data source: a shapefile, a GeoPackage, a database + /// connection, anything OGR can read. + /// + /// Not thread-safe; see VectorLayer. + class MWG_CORE_API VectorDataset + { + public: + ~VectorDataset(); + + VectorDataset(const VectorDataset&) = delete; + VectorDataset& operator=(const VectorDataset&) = delete; + + /// Opens a data source. + /// \throws OpenFailed when no driver can read it, or when update was + /// requested and the driver or file does not allow it. + [[nodiscard]] static std::unique_ptr Open(const std::filesystem::path& path, + OpenMode mode = OpenMode::ReadOnly); + + /// Returns nullptr instead of throwing. + [[nodiscard]] static std::unique_ptr TryOpen(const std::filesystem::path& path, + OpenMode mode = OpenMode::ReadOnly); + + [[nodiscard]] std::string DriverName() const; + [[nodiscard]] std::filesystem::path Path() const; + [[nodiscard]] bool IsWritable() const; + + /// Writes pending changes to disk without closing. Closing the dataset + /// does this as well. + /// \throws CoreError when GDAL cannot flush pending changes. + void Flush(); + + [[nodiscard]] int LayerCount() const; + [[nodiscard]] VectorLayer& Layer(int index) const; + /// nullptr when there is no layer with that name. + [[nodiscard]] VectorLayer* LayerByName(const std::string& name) const; + + private: + class Impl; + explicit VectorDataset(std::unique_ptr impl); + std::unique_ptr _impl; + }; +} diff --git a/src/MapWinGIS.Core/src/gdal/GdalEnvironment.cpp b/src/MapWinGIS.Core/src/gdal/GdalEnvironment.cpp new file mode 100644 index 0000000..211879c --- /dev/null +++ b/src/MapWinGIS.Core/src/gdal/GdalEnvironment.cpp @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file GdalEnvironment.cpp + * @brief Implements process-wide GDAL setup and diagnostic handling. + * + * Configures GDAL and PROJ runtime data, registers drivers, and provides + * thread-safe initialization, version queries, and scoped error suppression. + */ +#include "mapwingis/gdal/GdalEnvironment.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "internal/Utf8.h" + +namespace mwg +{ + using detail::ToUtf8; + + namespace + { + std::once_flag g_initFlag; + bool g_initialized = false; + + std::mutex g_logHandlerMutex; + LogHandler g_logHandler; + + thread_local std::string t_lastError; + + LogLevel ToLogLevel(const CPLErr severity) noexcept + { + switch (severity) + { + case CE_Warning: + return LogLevel::Warning; + case CE_Failure: + case CE_Fatal: + return LogLevel::Error; + default: + return LogLevel::Debug; + } + } + + void CPL_STDCALL ErrorHandler(const CPLErr severity, CPLErrorNum, const char* message) + { + if (message == nullptr) return; + + if (severity == CE_Failure || severity == CE_Fatal) + t_lastError = message; + + LogHandler handler; + { + std::lock_guard lock(g_logHandlerMutex); + handler = g_logHandler; + } + if (handler) handler(ToLogLevel(severity), message); + } + + void DoInitialize(const std::filesystem::path& gdalDataDir, const std::filesystem::path& projDataDir) + { + CPLSetErrorHandler(&ErrorHandler); + + if (!gdalDataDir.empty() && std::filesystem::is_directory(gdalDataDir)) + CPLSetConfigOption("GDAL_DATA", ToUtf8(gdalDataDir).c_str()); + + if (!projDataDir.empty() && std::filesystem::is_directory(projDataDir)) + { + const std::string proj = ToUtf8(projDataDir); + const char* paths[] = {proj.c_str(), nullptr}; + OSRSetPROJSearchPaths(paths); + } + + GDALAllRegister(); + g_initialized = true; + } + + GDALDriverH FindDriver(const std::string& name, const unsigned int kind) + { + GdalEnvironment::Initialize(); + GDALDriverH driver = GDALGetDriverByName(name.c_str()); + if (driver == nullptr) return nullptr; + + const char* value = GDALGetMetadataItem( + driver, kind == GDAL_OF_RASTER ? GDAL_DCAP_RASTER : GDAL_DCAP_VECTOR, nullptr); + return (value != nullptr && CPLTestBool(value)) ? driver : nullptr; + } + + int CountDrivers(const unsigned int kind) + { + GdalEnvironment::Initialize(); + int count = 0; + for (int i = 0; i < GDALGetDriverCount(); ++i) + { + GDALDriverH driver = GDALGetDriver(i); + const char* value = GDALGetMetadataItem( + driver, kind == GDAL_OF_RASTER ? GDAL_DCAP_RASTER : GDAL_DCAP_VECTOR, nullptr); + if (value != nullptr && CPLTestBool(value)) ++count; + } + return count; + } + } + + void GdalEnvironment::Initialize() + { + const std::filesystem::path moduleDir = ModuleDirectory(); + Initialize(moduleDir / "gdal-data", moduleDir / "proj"); + } + + void GdalEnvironment::Initialize(const std::filesystem::path& gdalDataDir, + const std::filesystem::path& projDataDir) + { + std::call_once(g_initFlag, DoInitialize, gdalDataDir, projDataDir); + } + + bool GdalEnvironment::IsInitialized() noexcept + { + return g_initialized; + } + + void GdalEnvironment::SetLogHandler(LogHandler handler) + { + std::lock_guard lock(g_logHandlerMutex); + g_logHandler = std::move(handler); + } + + std::string GdalEnvironment::LastErrorMessage() + { + return t_lastError; + } + + void GdalEnvironment::ClearLastError() + { + t_lastError.clear(); + CPLErrorReset(); + } + + std::string GdalEnvironment::GdalVersion() + { + Initialize(); + const char* version = GDALVersionInfo("RELEASE_NAME"); + return version != nullptr ? version : std::string{}; + } + + std::string GdalEnvironment::GeosVersion() + { + const char* version = GEOSversion(); + return version != nullptr ? version : std::string{}; + } + + std::string GdalEnvironment::ProjVersion() + { + Initialize(); + int major = 0; + int minor = 0; + int patch = 0; + OSRGetPROJVersion(&major, &minor, &patch); + return std::to_string(major) + "." + std::to_string(minor) + "." + std::to_string(patch); + } + + int GdalEnvironment::RasterDriverCount() { return CountDrivers(GDAL_OF_RASTER); } + int GdalEnvironment::VectorDriverCount() { return CountDrivers(GDAL_OF_VECTOR); } + + bool GdalEnvironment::HasRasterDriver(const std::string& name) + { + return FindDriver(name, GDAL_OF_RASTER) != nullptr; + } + + bool GdalEnvironment::HasVectorDriver(const std::string& name) + { + return FindDriver(name, GDAL_OF_VECTOR) != nullptr; + } + + std::filesystem::path GdalEnvironment::ModuleDirectory() + { + HMODULE module = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(&ModuleDirectory), &module)) + { + return {}; + } + + std::wstring buffer(MAX_PATH, L'\0'); + for (;;) + { + const DWORD length = GetModuleFileNameW(module, buffer.data(), static_cast(buffer.size())); + if (length == 0) return {}; + if (length < buffer.size()) + { + buffer.resize(length); + break; + } + buffer.resize(buffer.size() * 2); + } + + return std::filesystem::path(buffer).parent_path(); + } + + GdalEnvironment::QuietScope::QuietScope() + { + GdalEnvironment::Initialize(); + CPLPushErrorHandler(CPLQuietErrorHandler); + } + + GdalEnvironment::QuietScope::~QuietScope() + { + CPLPopErrorHandler(); + } +} diff --git a/src/MapWinGIS.Core/src/internal/Utf8.h b/src/MapWinGIS.Core/src/internal/Utf8.h new file mode 100644 index 0000000..50e87d5 --- /dev/null +++ b/src/MapWinGIS.Core/src/internal/Utf8.h @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file Utf8.h + * @brief Converts filesystem paths to UTF-8 strings for GDAL operations. + * + * Provides the shared internal path conversion used by the core library. + */ +#pragma once + +#include +#include + +namespace mwg::detail +{ + /// GDAL expects UTF-8 paths, so this is the only conversion the core uses. + inline std::string ToUtf8(const std::filesystem::path& path) + { + const std::u8string utf8 = path.u8string(); + return {reinterpret_cast(utf8.data()), utf8.size()}; + } +} diff --git a/src/MapWinGIS.Core/src/vector/VectorDataset.cpp b/src/MapWinGIS.Core/src/vector/VectorDataset.cpp new file mode 100644 index 0000000..5488506 --- /dev/null +++ b/src/MapWinGIS.Core/src/vector/VectorDataset.cpp @@ -0,0 +1,569 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file VectorDataset.cpp + * @brief Implements OGR-backed vector datasets and layers. + * + * Handles feature and field access, geometry and attribute conversion, + * indexed feature lookup, and writable dataset updates. + */ +#include "mapwingis/vector/VectorDataset.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "internal/Utf8.h" +#include "mapwingis/core/Error.h" +#include "mapwingis/gdal/GdalEnvironment.h" + +namespace mwg +{ + using detail::ToUtf8; + + namespace + { + ShapeType ToShapeType(const OGRwkbGeometryType type) + { + const OGRwkbGeometryType flat = wkbFlatten(type); + const bool hasZ = wkbHasZ(type) != FALSE; + const bool hasM = wkbHasM(type) != FALSE; + + auto pick = [hasZ, hasM](const ShapeType plain, const ShapeType z, const ShapeType m) + { + if (hasZ) return z; + if (hasM) return m; + return plain; + }; + + switch (flat) + { + case wkbPoint: + return pick(ShapeType::Point, ShapeType::PointZ, ShapeType::PointM); + case wkbMultiPoint: + return pick(ShapeType::MultiPoint, ShapeType::MultiPointZ, ShapeType::MultiPointM); + case wkbLineString: + case wkbMultiLineString: + case wkbCircularString: + case wkbCompoundCurve: + case wkbMultiCurve: + return pick(ShapeType::PolyLine, ShapeType::PolyLineZ, ShapeType::PolyLineM); + case wkbPolygon: + case wkbMultiPolygon: + case wkbCurvePolygon: + case wkbMultiSurface: + return pick(ShapeType::Polygon, ShapeType::PolygonZ, ShapeType::PolygonM); + default: + return ShapeType::NullShape; + } + } + + FieldInfo ToFieldInfo(const OGRFieldDefn& defn) + { + FieldInfo info; + info.name = defn.GetNameRef() != nullptr ? defn.GetNameRef() : ""; + info.width = defn.GetWidth(); + info.precision = defn.GetPrecision(); + + switch (defn.GetType()) + { + case OFTInteger: + info.type = defn.GetSubType() == OFSTBoolean ? FieldType::Boolean : FieldType::Integer; + break; + case OFTInteger64: + info.type = FieldType::Integer; + break; + case OFTReal: + info.type = FieldType::Double; + break; + case OFTDate: + case OFTDateTime: + case OFTTime: + info.type = FieldType::Date; + break; + default: + info.type = FieldType::String; + break; + } + return info; + } + + bool EqualsIgnoreCase(const std::string& a, const std::string& b) + { + return a.size() == b.size() && + std::equal(a.begin(), a.end(), b.begin(), + [](const unsigned char x, const unsigned char y) + { + return std::tolower(x) == std::tolower(y); + }); + } + } + + // ---------------------------------------------------------------- Layer + + class VectorLayer::Impl + { + public: + Impl(OGRLayer* layer, const bool writable) + : _layer(layer), _writable(writable) + { + if (const OGRFeatureDefn* defn = _layer->GetLayerDefn()) + { + _fields.reserve(static_cast(defn->GetFieldCount())); + for (int i = 0; i < defn->GetFieldCount(); ++i) + _fields.push_back(ToFieldInfo(*defn->GetFieldDefn(i))); + } + } + + /// Borrowed pointer, valid until the next call. Throws when the index is + /// out of range or the feature cannot be read. + /// + /// Callers read several fields of the same feature in a row, so the most + /// recently used feature is kept. Without it, reading five attributes of + /// one feature would mean five reads from the file. + [[nodiscard]] OGRFeature* GetFeature(const std::int64_t index) const + { + if (index < 0) + throw CoreError("Feature index out of range: " + std::to_string(index)); + if (_cachedIndex == index && _cachedFeature) return _cachedFeature.get(); + + EnsureFeatureIds(); + if (std::cmp_greater_equal(index, _featureIds.size())) + throw CoreError("Feature index out of range: " + std::to_string(index)); + + GdalEnvironment::ClearLastError(); + _cachedFeature.reset(_layer->GetFeature(_featureIds[static_cast(index)])); + _cachedIndex = _cachedFeature ? index : -1; + if (!_cachedFeature) + { + std::string message = "Cannot read feature at index " + std::to_string(index); + if (const std::string detail = GdalEnvironment::LastErrorMessage(); !detail.empty()) + message += " (" + detail + ")"; + throw CoreError(message); + } + return _cachedFeature.get(); + } + + [[nodiscard]] OGRFeature* GetFeatureForEdit(const std::int64_t index) const + { + if (!_writable) + throw CoreError("The dataset was not opened for update"); + + return GetFeature(index); + } + + void Save(OGRFeature* feature) const + { + if (_layer->SetFeature(feature) != OGRERR_NONE) + { + std::string message = "Cannot write feature " + std::to_string(feature->GetFID()); + if (const std::string detail = GdalEnvironment::LastErrorMessage(); !detail.empty()) + message += " (" + detail + ")"; + throw CoreError(message); + } + _extent.reset(); + } + + [[nodiscard]] std::int64_t FeatureCount() const + { + if (!_featureCount) + _featureCount = static_cast(_layer->GetFeatureCount(TRUE)); + return *_featureCount; + } + + [[nodiscard]] Extent GetExtent() const + { + if (!_extent) + { + OGREnvelope envelope; + _extent = _layer->GetExtent(&envelope, TRUE) == OGRERR_NONE + ? Extent{envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY} + : Extent{}; + } + return *_extent; + } + + OGRLayer* _layer; + bool _writable; + std::vector _fields; + + private: + /// MapWinGIS addresses features by 0-based index; OGR addresses them by + /// feature id, which is not the same thing: shapefile ids start at 0, + /// GeoPackage ids at 1, and either can have gaps. Building the mapping + /// costs one pass over the layer, so it is deferred until an indexed + /// lookup actually happens, and the pass asks the driver for ids only. + void EnsureFeatureIds() const + { + if (_featureIdsValid) return; + + // Keep expected diagnostics suppressed for the entire scan, not + // just while SetIgnoredFields is configured. + const GdalEnvironment::QuietScope quiet; + const IgnoreAllButIds ignoreScope(*_layer, _fields); + + _featureIds.clear(); + _featureIds.reserve(static_cast(std::max(FeatureCount(), 0))); + + _layer->ResetReading(); + while (const OGRFeatureUniquePtr feature{_layer->GetNextFeature()}) + _featureIds.push_back(feature->GetFID()); + _layer->ResetReading(); + + _featureIdsValid = true; + } + + /// Tells the driver to skip attributes and geometry for the duration of + /// the id scan, and restores the layer afterwards. + class IgnoreAllButIds + { + public: + IgnoreAllButIds(OGRLayer& layer, const std::vector& fields) + : _layer(layer) + { + std::vector ignored; + ignored.reserve(fields.size() + 2); + for (const FieldInfo& field : fields) ignored.push_back(field.name.c_str()); + ignored.push_back("OGR_GEOMETRY"); + ignored.push_back(nullptr); + + _applied = _layer.SetIgnoredFields(ignored.data()) == OGRERR_NONE; + } + + ~IgnoreAllButIds() + { + if (_applied) _layer.SetIgnoredFields(nullptr); + } + + IgnoreAllButIds(const IgnoreAllButIds&) = delete; + IgnoreAllButIds& operator=(const IgnoreAllButIds&) = delete; + + private: + OGRLayer& _layer; + bool _applied = false; + }; + + mutable std::vector _featureIds; + mutable bool _featureIdsValid = false; + mutable OGRFeatureUniquePtr _cachedFeature; + mutable std::int64_t _cachedIndex = -1; + mutable std::optional _featureCount; + mutable std::optional _extent; + }; + + VectorLayer::VectorLayer(std::unique_ptr impl) + : _impl(std::move(impl)) + { + } + + VectorLayer::~VectorLayer() = default; + + std::string VectorLayer::Name() const + { + const char* name = _impl->_layer->GetName(); + return name != nullptr ? name : std::string{}; + } + + ShapeType VectorLayer::Type() const + { + return ToShapeType(_impl->_layer->GetGeomType()); + } + + std::int64_t VectorLayer::FeatureCount() const + { + return _impl->FeatureCount(); + } + + Extent VectorLayer::GetExtent() const + { + return _impl->GetExtent(); + } + + int VectorLayer::FieldCount() const + { + return static_cast(_impl->_fields.size()); + } + + const std::vector& VectorLayer::Fields() const + { + return _impl->_fields; + } + + const FieldInfo& VectorLayer::Field(const int index) const + { + if (index < 0 || index >= FieldCount()) + throw CoreError("Field index out of range: " + std::to_string(index)); + return _impl->_fields[static_cast(index)]; + } + + int VectorLayer::FieldIndex(const std::string& name) const + { + for (std::size_t i = 0; i < _impl->_fields.size(); ++i) + { + if (EqualsIgnoreCase(_impl->_fields[i].name, name)) return static_cast(i); + } + return -1; + } + + std::string VectorLayer::ProjectionWkt() const + { + const OGRSpatialReference* srs = _impl->_layer->GetSpatialRef(); + if (srs == nullptr) return {}; + + char* wkt = nullptr; + if (srs->exportToWkt(&wkt) != OGRERR_NONE || wkt == nullptr) + { + CPLFree(wkt); + return {}; + } + + std::string result(wkt); + CPLFree(wkt); + return result; + } + + bool VectorLayer::IsCellNull(const int fieldIndex, const std::int64_t featureIndex) const + { + ValidateField(fieldIndex); + const OGRFeature* feature = _impl->GetFeature(featureIndex); + return !feature->IsFieldSetAndNotNull(fieldIndex); + } + + std::string VectorLayer::CellString(const int fieldIndex, const std::int64_t featureIndex) const + { + ValidateField(fieldIndex); + const OGRFeature* feature = _impl->GetFeature(featureIndex); + if (!feature->IsFieldSetAndNotNull(fieldIndex)) return {}; + + const char* value = feature->GetFieldAsString(fieldIndex); + return value != nullptr ? value : std::string{}; + } + + std::optional VectorLayer::CellDouble(const int fieldIndex, const std::int64_t featureIndex) const + { + ValidateField(fieldIndex); + const OGRFeature* feature = _impl->GetFeature(featureIndex); + if (!feature->IsFieldSetAndNotNull(fieldIndex)) return std::nullopt; + return feature->GetFieldAsDouble(fieldIndex); + } + + std::optional VectorLayer::CellInteger(const int fieldIndex, const std::int64_t featureIndex) const + { + ValidateField(fieldIndex); + const OGRFeature* feature = _impl->GetFeature(featureIndex); + if (!feature->IsFieldSetAndNotNull(fieldIndex)) return std::nullopt; + return static_cast(feature->GetFieldAsInteger64(fieldIndex)); + } + + std::string VectorLayer::GeometryWkt(const std::int64_t featureIndex) const + { + const OGRFeature* feature = _impl->GetFeature(featureIndex); + + const OGRGeometry* geometry = feature->GetGeometryRef(); + if (geometry == nullptr) return {}; + + char* wkt = nullptr; + if (geometry->exportToWkt(&wkt, wkbVariantIso) != OGRERR_NONE || wkt == nullptr) + { + CPLFree(wkt); + return {}; + } + + std::string result(wkt); + CPLFree(wkt); + return result; + } + + Extent VectorLayer::GeometryExtent(const std::int64_t featureIndex) const + { + const OGRFeature* feature = _impl->GetFeature(featureIndex); + + const OGRGeometry* geometry = feature->GetGeometryRef(); + if (geometry == nullptr || geometry->IsEmpty()) return {}; + + OGREnvelope envelope; + geometry->getEnvelope(&envelope); + return {envelope.MinX, envelope.MinY, envelope.MaxX, envelope.MaxY}; + } + + bool VectorLayer::IsWritable() const + { + return _impl->_writable; + } + + void VectorLayer::ValidateField(const int fieldIndex) const + { + if (fieldIndex < 0 || fieldIndex >= FieldCount()) + throw CoreError("Field index out of range: " + std::to_string(fieldIndex)); + } + + void VectorLayer::SetCellString(const int fieldIndex, const std::int64_t featureIndex, + const std::string& value) + { + ValidateField(fieldIndex); + OGRFeature* feature = _impl->GetFeatureForEdit(featureIndex); + feature->SetField(fieldIndex, value.c_str()); + _impl->Save(feature); + } + + void VectorLayer::SetCellDouble(const int fieldIndex, const std::int64_t featureIndex, + const double value) + { + ValidateField(fieldIndex); + OGRFeature* feature = _impl->GetFeatureForEdit(featureIndex); + feature->SetField(fieldIndex, value); + _impl->Save(feature); + } + + void VectorLayer::SetCellInteger(const int fieldIndex, const std::int64_t featureIndex, + const std::int64_t value) + { + ValidateField(fieldIndex); + OGRFeature* feature = _impl->GetFeatureForEdit(featureIndex); + feature->SetField(fieldIndex, static_cast(value)); + _impl->Save(feature); + } + + void VectorLayer::SetCellNull(const int fieldIndex, const std::int64_t featureIndex) + { + ValidateField(fieldIndex); + OGRFeature* feature = _impl->GetFeatureForEdit(featureIndex); + feature->SetFieldNull(fieldIndex); + _impl->Save(feature); + } + + void VectorLayer::SetGeometryWkt(const std::int64_t featureIndex, const std::string& wkt) + { + OGRFeature* feature = _impl->GetFeatureForEdit(featureIndex); + + OGRGeometry* parsed = nullptr; + const char* text = wkt.c_str(); + if (OGRGeometryFactory::createFromWkt(&text, _impl->_layer->GetSpatialRef(), &parsed) != OGRERR_NONE || + parsed == nullptr) + { + throw CoreError("Cannot parse WKT: " + wkt); + } + + if (feature->SetGeometryDirectly(parsed) != OGRERR_NONE) + throw CoreError("Cannot assign geometry to feature"); + + _impl->Save(feature); + } + + // -------------------------------------------------------------- Dataset + + class VectorDataset::Impl + { + public: + Impl(GDALDatasetUniquePtr dataset, std::filesystem::path path, const bool writable) + : _dataset(std::move(dataset)), _path(std::move(path)), _writable(writable) + { + const int count = _dataset->GetLayerCount(); + _layers.reserve(static_cast(count)); + for (int i = 0; i < count; ++i) + { + OGRLayer* layer = _dataset->GetLayer(i); + _layers.push_back(std::unique_ptr( + new VectorLayer(std::make_unique(layer, writable)))); + } + } + + GDALDatasetUniquePtr _dataset; + std::filesystem::path _path; + bool _writable; + std::vector> _layers; + }; + + VectorDataset::VectorDataset(std::unique_ptr impl) + : _impl(std::move(impl)) + { + } + + VectorDataset::~VectorDataset() = default; + + std::unique_ptr VectorDataset::TryOpen(const std::filesystem::path& path, + const OpenMode mode) + { + GdalEnvironment::Initialize(); + GdalEnvironment::ClearLastError(); + + const bool writable = mode == OpenMode::Update; + const unsigned int flags = + GDAL_OF_VECTOR | GDAL_OF_VERBOSE_ERROR | (writable ? GDAL_OF_UPDATE : GDAL_OF_READONLY); + + GDALDatasetUniquePtr dataset( + GDALDataset::Open(ToUtf8(path).c_str(), flags, nullptr, nullptr, nullptr)); + + if (!dataset) return nullptr; + return std::unique_ptr( + new VectorDataset(std::make_unique(std::move(dataset), path, writable))); + } + + std::unique_ptr VectorDataset::Open(const std::filesystem::path& path, + const OpenMode mode) + { + if (std::unique_ptr dataset = TryOpen(path, mode)) return dataset; + + std::string message = "Cannot open vector data source: " + ToUtf8(path); + if (const std::string detail = GdalEnvironment::LastErrorMessage(); !detail.empty()) + message += " (" + detail + ")"; + throw OpenFailed(message); + } + + bool VectorDataset::IsWritable() const + { + return _impl->_writable; + } + + void VectorDataset::Flush() + { + GdalEnvironment::ClearLastError(); + if (_impl->_dataset->FlushCache(false) != CE_None) + { + std::string message = "Cannot flush vector data source: " + ToUtf8(_impl->_path); + if (const char* detail = CPLGetLastErrorMsg(); detail != nullptr && *detail != '\0') + message += " (" + std::string(detail) + ")"; + throw CoreError(message); + } + } + + std::string VectorDataset::DriverName() const + { + GDALDriver* driver = _impl->_dataset->GetDriver(); + if (driver == nullptr) return {}; + const char* name = driver->GetDescription(); + return name != nullptr ? name : std::string{}; + } + + std::filesystem::path VectorDataset::Path() const + { + return _impl->_path; + } + + int VectorDataset::LayerCount() const + { + return static_cast(_impl->_layers.size()); + } + + VectorLayer& VectorDataset::Layer(const int index) const + { + if (index < 0 || index >= LayerCount()) + throw CoreError("Layer index out of range: " + std::to_string(index)); + return *_impl->_layers[static_cast(index)]; + } + + VectorLayer* VectorDataset::LayerByName(const std::string& name) const + { + for (const std::unique_ptr& layer : _impl->_layers) + { + if (EqualsIgnoreCase(layer->Name(), name)) return layer.get(); + } + return nullptr; + } +} diff --git a/tests/MapWinGIS.Core.Tests/GdalEnvironmentTests.cpp b/tests/MapWinGIS.Core.Tests/GdalEnvironmentTests.cpp new file mode 100644 index 0000000..279b8a3 --- /dev/null +++ b/tests/MapWinGIS.Core.Tests/GdalEnvironmentTests.cpp @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file GdalEnvironmentTests.cpp + * @brief Tests GDAL initialization, drivers, runtime data, and diagnostics. + * + * Verifies environment setup and the logging and error-reporting behavior + * exposed by GdalEnvironment. + */ +#include + +#include +#include + +#include + +#include "mapwingis/gdal/GdalEnvironment.h" + +using namespace mwg; + +namespace +{ + // Lower bounds, not exact counts: the driver set depends on the vcpkg + // manifest feature that was built (core-drivers or full-drivers). + constexpr int kMinimumRasterDrivers = 50; + constexpr int kMinimumVectorDrivers = 30; +} + +TEST(GdalEnvironment, ReportsVersions) +{ + GdalEnvironment::Initialize(); + + EXPECT_FALSE(GdalEnvironment::GdalVersion().empty()); + EXPECT_FALSE(GdalEnvironment::GeosVersion().empty()); + EXPECT_FALSE(GdalEnvironment::ProjVersion().empty()); + + EXPECT_TRUE(GdalEnvironment::GdalVersion().starts_with("3.")); +} + +TEST(GdalEnvironment, InitializeIsIdempotent) +{ + GdalEnvironment::Initialize(); + GdalEnvironment::Initialize(); + EXPECT_TRUE(GdalEnvironment::IsInitialized()); +} + +TEST(GdalEnvironment, RegistersDrivers) +{ + EXPECT_GE(GdalEnvironment::RasterDriverCount(), kMinimumRasterDrivers); + EXPECT_GE(GdalEnvironment::VectorDriverCount(), kMinimumVectorDrivers); +} + +TEST(GdalEnvironment, HasTheDriversMapWinGisDependsOn) +{ + EXPECT_TRUE(GdalEnvironment::HasVectorDriver("ESRI Shapefile")); + EXPECT_TRUE(GdalEnvironment::HasVectorDriver("GPKG")); + EXPECT_TRUE(GdalEnvironment::HasVectorDriver("OpenFileGDB")); + EXPECT_TRUE(GdalEnvironment::HasVectorDriver("GeoJSON")); + EXPECT_TRUE(GdalEnvironment::HasVectorDriver("MapInfo File")); + EXPECT_TRUE(GdalEnvironment::HasVectorDriver("CSV")); + EXPECT_TRUE(GdalEnvironment::HasVectorDriver("DXF")); + + EXPECT_TRUE(GdalEnvironment::HasRasterDriver("GTiff")); + EXPECT_TRUE(GdalEnvironment::HasRasterDriver("MEM")); + EXPECT_TRUE(GdalEnvironment::HasRasterDriver("AAIGrid")); + EXPECT_TRUE(GdalEnvironment::HasRasterDriver("HFA")); + EXPECT_TRUE(GdalEnvironment::HasRasterDriver("VRT")); + EXPECT_TRUE(GdalEnvironment::HasRasterDriver("PNG")); + EXPECT_TRUE(GdalEnvironment::HasRasterDriver("JPEG")); +} + +TEST(GdalEnvironment, DeploysRuntimeDataNextToTheModule) +{ + const std::filesystem::path dir = GdalEnvironment::ModuleDirectory(); + ASSERT_FALSE(dir.empty()); + + EXPECT_TRUE(std::filesystem::is_directory(dir / "gdal-data")) + << "gdal-data is missing from " << dir.string(); + EXPECT_TRUE(std::filesystem::exists(dir / "proj" / "proj.db")) + << "proj.db is missing from " << dir.string(); +} + +TEST(GdalEnvironment, CapturesTheLastError) +{ + GdalEnvironment::Initialize(); + GdalEnvironment::ClearLastError(); + EXPECT_TRUE(GdalEnvironment::LastErrorMessage().empty()); + + CPLError(CE_Failure, CPLE_AppDefined, "%s", "test failure"); + EXPECT_EQ(GdalEnvironment::LastErrorMessage(), "test failure"); + + GdalEnvironment::ClearLastError(); + EXPECT_TRUE(GdalEnvironment::LastErrorMessage().empty()); +} + +TEST(GdalEnvironment, QuietScopeRestoresTheHandler) +{ + GdalEnvironment::Initialize(); + + int seen = 0; + GdalEnvironment::SetLogHandler([&seen](LogLevel, std::string_view) { ++seen; }); + + { + const GdalEnvironment::QuietScope quiet; + CPLError(CE_Warning, CPLE_AppDefined, "%s", "suppressed"); + } + EXPECT_EQ(seen, 0); + + CPLError(CE_Warning, CPLE_AppDefined, "%s", "reported"); + EXPECT_EQ(seen, 1); + + GdalEnvironment::SetLogHandler({}); + GdalEnvironment::ClearLastError(); +} + +TEST(GdalEnvironment, QuietScopeDoesNotSuppressOtherThreads) +{ + GdalEnvironment::Initialize(); + + std::atomic seen{0}; + GdalEnvironment::SetLogHandler([&seen](LogLevel, std::string_view) { ++seen; }); + + { + const GdalEnvironment::QuietScope quiet; + CPLError(CE_Warning, CPLE_AppDefined, "%s", "suppressed"); + std::thread worker([] + { + CPLError(CE_Warning, CPLE_AppDefined, "%s", "reported on another thread"); + }); + worker.join(); + } + + GdalEnvironment::SetLogHandler({}); + EXPECT_EQ(seen.load(), 1); + GdalEnvironment::ClearLastError(); +} diff --git a/tests/MapWinGIS.Core.Tests/Main.cpp b/tests/MapWinGIS.Core.Tests/Main.cpp new file mode 100644 index 0000000..cccde5f --- /dev/null +++ b/tests/MapWinGIS.Core.Tests/Main.cpp @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file Main.cpp + * @brief Provides the GoogleTest entry point for the core test executable. + * + * Defines main locally so the test target does not link GoogleTest's main + * libraries, which are auto-linked by the configured vcpkg setup. + */ +#include + +// Defined here rather than linking gtest_main, so that both gtest_main.lib and +// gmock_main.lib stay out of the link (vcpkg auto-links every library). +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj b/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj new file mode 100644 index 0000000..16df992 --- /dev/null +++ b/tests/MapWinGIS.Core.Tests/MapWinGIS.Core.Tests.vcxproj @@ -0,0 +1,69 @@ + + + + + + Debug + Win32 + + + Debug + x64 + + + Release + Win32 + + + Release + x64 + + + + + {2B6A9A3B-0C5E-4E6E-9E31-3E8F5A2D1C02} + MapWinGISCoreTests + MapWinGIS.Core.Tests + MapWinGIS.Core.Tests + + + + + + Application + + + + + + + + + + + $(MwgRepoRoot)src\MapWinGIS.Core\include;%(AdditionalIncludeDirectories) + + + Console + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/MapWinGIS.Core.Tests/TestData.cpp b/tests/MapWinGIS.Core.Tests/TestData.cpp new file mode 100644 index 0000000..7b743e0 --- /dev/null +++ b/tests/MapWinGIS.Core.Tests/TestData.cpp @@ -0,0 +1,194 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file TestData.cpp + * @brief Implements shared vector test fixture helpers. + * + * Manages temporary directories and creates polygon datasets with attributes, + * null values, and projections for the core tests. + */ +#include "TestData.h" + +#include +#include + +#include +#include + +#include "mapwingis/gdal/GdalEnvironment.h" + +namespace mwg::test +{ + namespace + { + std::string ToUtf8(const std::filesystem::path& path) + { + const std::u8string utf8 = path.u8string(); + return {reinterpret_cast(utf8.data()), utf8.size()}; + } + + std::string RandomName() + { + static std::mt19937_64 engine{std::random_device{}()}; + std::uniform_int_distribution distribution; + return "mwg-test-" + std::to_string(distribution(engine)); + } + } + + TempDirectory::TempDirectory() + : _path(std::filesystem::temp_directory_path() / RandomName()) + { + std::filesystem::create_directories(_path); + } + + TempDirectory::~TempDirectory() + { + std::error_code ignored; + std::filesystem::remove_all(_path, ignored); + } + + std::filesystem::path MakeProvincesDataset(const std::filesystem::path& directory, + const std::string& fileName) + { + GdalEnvironment::Initialize(); + + const std::filesystem::path path = directory / fileName; + const bool shapefile = path.extension() == ".shp"; + if (!shapefile && path.extension() != ".gpkg") + throw std::invalid_argument("Test dataset must have a .shp or .gpkg extension"); + + GDALDriver* driver = GetGDALDriverManager()->GetDriverByName( + shapefile ? "ESRI Shapefile" : "GPKG"); + if (driver == nullptr) throw std::runtime_error("Test dataset driver is not available"); + + GDALDatasetUniquePtr dataset( + driver->Create(ToUtf8(path).c_str(), 0, 0, 0, GDT_Unknown, nullptr)); + if (!dataset) throw std::runtime_error("Cannot create " + ToUtf8(path)); + + OGRSpatialReference srs; + if (srs.importFromEPSG(Provinces::kEpsg) != OGRERR_NONE) + throw std::runtime_error("Cannot create test projection"); + + const char* options[] = {"ENCODING=UTF-8", nullptr}; + OGRLayer* layer = dataset->CreateLayer(Provinces::kLayerName, &srs, wkbPolygon, + shapefile ? options : nullptr); + if (layer == nullptr) throw std::runtime_error("Cannot create layer"); + + OGRFieldDefn idField(Provinces::kIdField, OFTInteger); + OGRFieldDefn nameField(Provinces::kNameField, OFTString); + nameField.SetWidth(32); + OGRFieldDefn areaField(Provinces::kAreaField, OFTReal); + areaField.SetWidth(18); + areaField.SetPrecision(4); + OGRFieldDefn surveyedField(Provinces::kSurveyedField, OFTDate); + OGRFieldDefn activeField(Provinces::kActiveField, OFTInteger); + activeField.SetSubType(OFSTBoolean); + + if (layer->CreateField(&idField) != OGRERR_NONE || + layer->CreateField(&nameField) != OGRERR_NONE || + layer->CreateField(&areaField) != OGRERR_NONE || + layer->CreateField(&surveyedField) != OGRERR_NONE || + layer->CreateField(&activeField) != OGRERR_NONE) + { + throw std::runtime_error("Cannot create fields"); + } + + static constexpr const char* kNames[] = {"Noord", "Oost", Provinces::kNonAsciiName}; + static constexpr int kDates[][3] = {{2020, 1, 15}, {2021, 6, 30}, {2022, 11, 1}}; + + for (int i = 0; i < Provinces::kFeatureCount; ++i) + { + OGRFeatureUniquePtr feature(OGRFeature::CreateFeature(layer->GetLayerDefn())); + feature->SetField(Provinces::kIdField, i + 1); + if (i != Provinces::kNullFeature) + { + feature->SetField(Provinces::kNameField, kNames[i]); + feature->SetField(Provinces::kSurveyedField, + kDates[i][0], kDates[i][1], kDates[i][2]); + } + feature->SetField(Provinces::kAreaField, 1.0); + feature->SetField(Provinces::kActiveField, i == 2 ? 0 : 1); + + const double x = Provinces::kMinX + 1000.0 * i; + OGRLinearRing ring; + ring.addPoint(x, Provinces::kMinY); + ring.addPoint(x + 1000.0, Provinces::kMinY); + ring.addPoint(x + 1000.0, Provinces::kMaxY); + ring.addPoint(x, Provinces::kMaxY); + ring.closeRings(); + + OGRPolygon polygon; + polygon.addRing(&ring); + if (feature->SetGeometry(&polygon) != OGRERR_NONE || + layer->CreateFeature(feature.get()) != OGRERR_NONE) + { + throw std::runtime_error("Cannot write feature " + std::to_string(i)); + } + } + + dataset.reset(); + return path; + } + + std::filesystem::path MakeSampleShapefile(const std::filesystem::path& directory, + const std::string& baseName) + { + GdalEnvironment::Initialize(); + + const std::filesystem::path shp = directory / (baseName + ".shp"); + + GDALDriver* driver = GetGDALDriverManager()->GetDriverByName("ESRI Shapefile"); + if (driver == nullptr) throw std::runtime_error("ESRI Shapefile driver is not available"); + + GDALDatasetUniquePtr dataset( + driver->Create(ToUtf8(shp).c_str(), 0, 0, 0, GDT_Unknown, nullptr)); + if (!dataset) throw std::runtime_error("Cannot create " + ToUtf8(shp)); + + OGRSpatialReference srs; + srs.importFromEPSG(28992); + + OGRLayer* layer = dataset->CreateLayer(baseName.c_str(), &srs, wkbPolygon, nullptr); + if (layer == nullptr) throw std::runtime_error("Cannot create layer"); + + OGRFieldDefn idField(SampleLayer::kIdField, OFTInteger); + OGRFieldDefn nameField(SampleLayer::kNameField, OFTString); + nameField.SetWidth(32); + OGRFieldDefn areaField(SampleLayer::kAreaField, OFTReal); + areaField.SetWidth(18); + areaField.SetPrecision(4); + + if (layer->CreateField(&idField) != OGRERR_NONE || + layer->CreateField(&nameField) != OGRERR_NONE || + layer->CreateField(&areaField) != OGRERR_NONE) + { + throw std::runtime_error("Cannot create fields"); + } + + static constexpr const char* kNames[] = {"first", "second", nullptr}; + + for (int i = 0; i < SampleLayer::kFeatureCount; ++i) + { + OGRFeatureUniquePtr feature(OGRFeature::CreateFeature(layer->GetLayerDefn())); + feature->SetField(SampleLayer::kIdField, i + 1); + if (kNames[i] != nullptr) feature->SetField(SampleLayer::kNameField, kNames[i]); + feature->SetField(SampleLayer::kAreaField, 1.0 + i); + + OGRLinearRing ring; + ring.addPoint(static_cast(i), 0.0); + ring.addPoint(static_cast(i) + 1.0, 0.0); + ring.addPoint(static_cast(i) + 1.0, 1.0); + ring.addPoint(static_cast(i), 1.0); + ring.closeRings(); + + OGRPolygon polygon; + polygon.addRing(&ring); + feature->SetGeometry(&polygon); + + if (layer->CreateFeature(feature.get()) != OGRERR_NONE) + throw std::runtime_error("Cannot write feature " + std::to_string(i)); + } + + dataset.reset(); + return shp; + } +} diff --git a/tests/MapWinGIS.Core.Tests/TestData.h b/tests/MapWinGIS.Core.Tests/TestData.h new file mode 100644 index 0000000..29f4a1b --- /dev/null +++ b/tests/MapWinGIS.Core.Tests/TestData.h @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file TestData.h + * @brief Declares shared vector test data and fixture helpers. + * + * Provides generated dataset metadata, temporary-directory support, and + * helpers for creating Shapefile and GeoPackage fixtures. + */ +#pragma once + +#include +#include + +namespace mwg::test +{ + /// Describes the projected polygon layer written by MakeProvincesDataset(). + struct Provinces + { + static constexpr int kFeatureCount = 4; + static constexpr int kEpsg = 28992; + + static constexpr const char* kLayerName = "provinces"; + static constexpr const char* kIdField = "ID"; + static constexpr const char* kNameField = "NAME"; + static constexpr const char* kAreaField = "AREA_KM2"; + static constexpr const char* kSurveyedField = "SURVEYED"; + static constexpr const char* kActiveField = "ACTIVE"; + + static constexpr double kMinX = 100000.0; + static constexpr double kMinY = 400000.0; + static constexpr double kMaxX = 104000.0; + static constexpr double kMaxY = 401000.0; + + /// Feature 3 has a null NAME and a null SURVEYED. + static constexpr int kNullFeature = 3; + /// UTF-8; feature 2 exercises non-ASCII attribute values. + static constexpr const char* kNonAsciiName = "Frysl\u00e2n"; + }; + + /// Writes four polygons with all five field types, null values, and UTF-8 + /// names. fileName must have a .shp or .gpkg extension. + std::filesystem::path MakeProvincesDataset(const std::filesystem::path& directory, + const std::string& fileName); + + /// Describes the sample layer that MakeSampleShapefile() writes, so tests + /// can assert against it without repeating literals. + struct SampleLayer + { + static constexpr int kFeatureCount = 3; + + static constexpr const char* kIdField = "ID"; + static constexpr const char* kNameField = "NAME"; + static constexpr const char* kAreaField = "AREA"; + + // Feature 0..2: unit squares side by side, y in [0, 1]. + static constexpr double kMinX = 0.0; + static constexpr double kMinY = 0.0; + static constexpr double kMaxX = 3.0; + static constexpr double kMaxY = 1.0; + }; + + /// Creates a directory that is deleted when the object goes out of scope. + class TempDirectory + { + public: + TempDirectory(); + ~TempDirectory(); + + TempDirectory(const TempDirectory&) = delete; + TempDirectory& operator=(const TempDirectory&) = delete; + + [[nodiscard]] const std::filesystem::path& Path() const noexcept { return _path; } + + private: + std::filesystem::path _path; + }; + + /// Writes a 3-feature polygon shapefile in EPSG:28992 with the fields + /// described by SampleLayer, and returns the .shp path. + /// The last feature has a NULL NAME so that null handling is covered. + std::filesystem::path MakeSampleShapefile(const std::filesystem::path& directory, + const std::string& baseName = "sample"); +} diff --git a/tests/MapWinGIS.Core.Tests/VectorDatasetTests.cpp b/tests/MapWinGIS.Core.Tests/VectorDatasetTests.cpp new file mode 100644 index 0000000..01caf89 --- /dev/null +++ b/tests/MapWinGIS.Core.Tests/VectorDatasetTests.cpp @@ -0,0 +1,232 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file VectorDatasetTests.cpp + * @brief Tests vector dataset and layer operations using generated fixtures. + * + * Covers layer metadata, feature attributes and geometry, null values, + * projections, errors, and opening data sources with non-ASCII paths. + */ +#include + +#include + +#include "TestData.h" +#include "mapwingis/core/Error.h" +#include "mapwingis/gdal/GdalEnvironment.h" +#include "mapwingis/vector/VectorDataset.h" + +using namespace mwg; +using namespace mwg::test; + +namespace +{ + class FlushFailureDataset : public GDALDataset + { + public: + explicit FlushFailureDataset(const bool reportError) + : _reportError(reportError) + { + } + + CPLErr FlushCache(bool) override + { + if (_reportError) + CPLError(CE_Failure, CPLE_FileIO, "%s", "Simulated flush failure"); + return CE_Failure; + } + + private: + bool _reportError; + }; + + class VectorDatasetTest : public testing::Test + { + protected: + void SetUp() override + { + _shp = MakeSampleShapefile(_dir.Path()); + _dataset = VectorDataset::Open(_shp); + _layer = &_dataset->Layer(0); + } + + TempDirectory _dir; + std::filesystem::path _shp; + std::unique_ptr _dataset; + VectorLayer* _layer = nullptr; + }; +} + +TEST_F(VectorDatasetTest, ReportsTheDriverAndPath) +{ + EXPECT_EQ(_dataset->DriverName(), "ESRI Shapefile"); + EXPECT_EQ(_dataset->Path(), _shp); +} + +TEST_F(VectorDatasetTest, HasOneLayer) +{ + EXPECT_EQ(_dataset->LayerCount(), 1); + EXPECT_EQ(_layer->Name(), "sample"); + EXPECT_NE(_dataset->LayerByName("SAMPLE"), nullptr); + EXPECT_EQ(_dataset->LayerByName("missing"), nullptr); +} + +TEST_F(VectorDatasetTest, ReportsShapeTypeAndFeatureCount) +{ + EXPECT_EQ(_layer->Type(), ShapeType::Polygon); + EXPECT_EQ(_layer->FeatureCount(), SampleLayer::kFeatureCount); +} + +TEST_F(VectorDatasetTest, ReportsTheLayerExtent) +{ + const Extent extent = _layer->GetExtent(); + ASSERT_FALSE(extent.IsEmpty()); + EXPECT_DOUBLE_EQ(extent.xMin, SampleLayer::kMinX); + EXPECT_DOUBLE_EQ(extent.yMin, SampleLayer::kMinY); + EXPECT_DOUBLE_EQ(extent.xMax, SampleLayer::kMaxX); + EXPECT_DOUBLE_EQ(extent.yMax, SampleLayer::kMaxY); +} + +TEST_F(VectorDatasetTest, ReportsTheFieldDefinitions) +{ + ASSERT_EQ(_layer->FieldCount(), 3); + + EXPECT_EQ(_layer->Field(0).name, SampleLayer::kIdField); + EXPECT_EQ(_layer->Field(0).type, FieldType::Integer); + + EXPECT_EQ(_layer->Field(1).name, SampleLayer::kNameField); + EXPECT_EQ(_layer->Field(1).type, FieldType::String); + EXPECT_EQ(_layer->Field(1).width, 32); + + EXPECT_EQ(_layer->Field(2).name, SampleLayer::kAreaField); + EXPECT_EQ(_layer->Field(2).type, FieldType::Double); + EXPECT_EQ(_layer->Field(2).precision, 4); +} + +TEST_F(VectorDatasetTest, FindsFieldsCaseInsensitively) +{ + EXPECT_EQ(_layer->FieldIndex("name"), 1); + EXPECT_EQ(_layer->FieldIndex("NAME"), 1); + EXPECT_EQ(_layer->FieldIndex("nope"), -1); +} + +TEST_F(VectorDatasetTest, ReadsCellValues) +{ + const int id = _layer->FieldIndex(SampleLayer::kIdField); + const int name = _layer->FieldIndex(SampleLayer::kNameField); + const int area = _layer->FieldIndex(SampleLayer::kAreaField); + + EXPECT_EQ(_layer->CellInteger(id, 0), 1); + EXPECT_EQ(_layer->CellInteger(id, 2), 3); + EXPECT_EQ(_layer->CellString(name, 0), "first"); + EXPECT_EQ(_layer->CellString(name, 1), "second"); + ASSERT_TRUE(_layer->CellDouble(area, 1).has_value()); + EXPECT_DOUBLE_EQ(*_layer->CellDouble(area, 1), 2.0); +} + +TEST_F(VectorDatasetTest, ReportsNullCells) +{ + const int name = _layer->FieldIndex(SampleLayer::kNameField); + + EXPECT_FALSE(_layer->IsCellNull(name, 0)); + EXPECT_TRUE(_layer->IsCellNull(name, 2)); + EXPECT_EQ(_layer->CellString(name, 2), ""); + EXPECT_FALSE(_layer->CellDouble(name, 2).has_value()); +} + +TEST_F(VectorDatasetTest, RejectsOutOfRangeFieldIndexes) +{ + EXPECT_THROW((void)_layer->CellString(-1, 0), CoreError); + EXPECT_THROW((void)_layer->CellString(99, 0), CoreError); + EXPECT_THROW((void)_dataset->Layer(1), CoreError); +} + +TEST_F(VectorDatasetTest, ExportsGeometryAsWkt) +{ + const std::string wkt = _layer->GeometryWkt(0); + EXPECT_TRUE(wkt.starts_with("POLYGON")) << wkt; + EXPECT_NE(wkt.find("0 0"), std::string::npos) << wkt; + + EXPECT_THROW((void)_layer->GeometryWkt(SampleLayer::kFeatureCount), CoreError); +} + +TEST_F(VectorDatasetTest, ReportsPerFeatureExtents) +{ + const Extent extent = _layer->GeometryExtent(1); + ASSERT_FALSE(extent.IsEmpty()); + EXPECT_DOUBLE_EQ(extent.xMin, 1.0); + EXPECT_DOUBLE_EQ(extent.xMax, 2.0); +} + +TEST_F(VectorDatasetTest, ReportsTheProjection) +{ + const std::string wkt = _layer->ProjectionWkt(); + ASSERT_FALSE(wkt.empty()); + EXPECT_NE(wkt.find("Amersfoort"), std::string::npos) << wkt; +} + +TEST(VectorDataset, ReportsMissingFiles) +{ + const TempDirectory dir; + const std::filesystem::path missing = dir.Path() / "does-not-exist.shp"; + + EXPECT_EQ(VectorDataset::TryOpen(missing), nullptr); + EXPECT_THROW((void)VectorDataset::Open(missing), OpenFailed); +} + +TEST(VectorDataset, OpensNonAsciiPaths) +{ + const TempDirectory dir; + const std::filesystem::path shp = MakeSampleShapefile(dir.Path(), "\u0412\u043e\u0437\u0434\u0443\u0445"); + + const std::unique_ptr dataset = VectorDataset::Open(shp); + ASSERT_EQ(dataset->LayerCount(), 1); + EXPECT_EQ(dataset->Layer(0).FeatureCount(), SampleLayer::kFeatureCount); +} + +TEST(VectorDataset, ReportsFlushFailures) +{ + GdalEnvironment::Initialize(); + const auto deregister = [](GDALDriver* driver) + { + GetGDALDriverManager()->DeregisterDriver(driver); + delete driver; + }; + const std::unique_ptr driver{ + std::make_unique().release(), deregister}; + driver->SetDescription("MWGFlushFailure"); + driver->SetMetadataItem(GDAL_DCAP_VECTOR, "YES"); + driver->SetMetadataItem(GDAL_DCAP_OPEN, "YES"); + driver->pfnIdentify = [](GDALOpenInfo* info) + { + return std::string_view(info->pszFilename).starts_with("MWG_FLUSH_FAILURE:") ? TRUE : FALSE; + }; + driver->pfnOpen = [](GDALOpenInfo* info) -> GDALDataset* + { + const std::string_view name(info->pszFilename); + if (!name.starts_with("MWG_FLUSH_FAILURE:")) return nullptr; + return std::make_unique(name.ends_with("detail")).release(); + }; + GetGDALDriverManager()->RegisterDriver(driver.get()); + + const GdalEnvironment::QuietScope quiet; + for (const char* path : {"MWG_FLUSH_FAILURE:detail", "MWG_FLUSH_FAILURE:silent"}) + { + const std::unique_ptr dataset = VectorDataset::Open(path); + CPLError(CE_Failure, CPLE_AppDefined, "%s", "Stale error"); + try + { + dataset->Flush(); + ADD_FAILURE() << "Flush did not report failure"; + } + catch (const CoreError& error) + { + const std::string message(error.what()); + EXPECT_NE(message.find("Cannot flush vector data source:"), std::string::npos) << message; + EXPECT_NE(message.find(path), std::string::npos) << message; + EXPECT_EQ(message.find("Stale error"), std::string::npos) << message; + if (std::string_view(path).ends_with("detail")) + EXPECT_NE(message.find("Simulated flush failure"), std::string::npos) << message; + } + } +} diff --git a/tests/MapWinGIS.Core.Tests/VectorLayerTests.cpp b/tests/MapWinGIS.Core.Tests/VectorLayerTests.cpp new file mode 100644 index 0000000..12b4cc9 --- /dev/null +++ b/tests/MapWinGIS.Core.Tests/VectorLayerTests.cpp @@ -0,0 +1,382 @@ +// SPDX-License-Identifier: MPL-2.0 + +/** + * @file VectorLayerTests.cpp + * @brief Tests vector layer reading and editing with generated fixtures. + * + * Exercises shapefile and GeoPackage behavior for attributes, geometry, + * projections, null values, and persisted edits across both formats. + */ + +#include + +#include +#include + +#include "TestData.h" +#include "mapwingis/core/Error.h" +#include "mapwingis/gdal/GdalEnvironment.h" +#include "mapwingis/vector/VectorDataset.h" + +using namespace mwg; +using namespace mwg::test; + +namespace +{ + /// Runs every case against both the shapefile and the GeoPackage, so the + /// core stays format-agnostic. + class VectorLayerTest : public testing::TestWithParam + { + protected: + void SetUp() override + { + _dataset = VectorDataset::Open(MakeProvincesDataset(_dir.Path(), GetParam())); + _layer = _dataset->LayerByName(Provinces::kLayerName); + ASSERT_NE(_layer, nullptr); + } + + TempDirectory _dir; + std::unique_ptr _dataset; + VectorLayer* _layer = nullptr; + }; +} + +INSTANTIATE_TEST_SUITE_P(Formats, VectorLayerTest, + testing::Values("provinces.shp", "provinces.gpkg"), + [](const testing::TestParamInfo& info) + { + return std::string(info.param).find("gpkg") != std::string::npos + ? "GeoPackage" + : "Shapefile"; + }); + +TEST_P(VectorLayerTest, ReportsTheLayer) +{ + EXPECT_EQ(_layer->Type(), ShapeType::Polygon); + EXPECT_EQ(_layer->FeatureCount(), Provinces::kFeatureCount); +} + +TEST_P(VectorLayerTest, ReportsTheExtent) +{ + const Extent extent = _layer->GetExtent(); + ASSERT_FALSE(extent.IsEmpty()); + EXPECT_DOUBLE_EQ(extent.xMin, Provinces::kMinX); + EXPECT_DOUBLE_EQ(extent.yMin, Provinces::kMinY); + EXPECT_DOUBLE_EQ(extent.xMax, Provinces::kMaxX); + EXPECT_DOUBLE_EQ(extent.yMax, Provinces::kMaxY); +} + +TEST_P(VectorLayerTest, ReportsAllMapWinGisFieldTypes) +{ + EXPECT_EQ(_layer->Field(_layer->FieldIndex(Provinces::kIdField)).type, FieldType::Integer); + EXPECT_EQ(_layer->Field(_layer->FieldIndex(Provinces::kNameField)).type, FieldType::String); + EXPECT_EQ(_layer->Field(_layer->FieldIndex(Provinces::kAreaField)).type, FieldType::Double); + EXPECT_EQ(_layer->Field(_layer->FieldIndex(Provinces::kSurveyedField)).type, FieldType::Date); + EXPECT_EQ(_layer->Field(_layer->FieldIndex(Provinces::kActiveField)).type, FieldType::Boolean); +} + +TEST_P(VectorLayerTest, ReadsAttributes) +{ + const int id = _layer->FieldIndex(Provinces::kIdField); + const int name = _layer->FieldIndex(Provinces::kNameField); + const int area = _layer->FieldIndex(Provinces::kAreaField); + const int active = _layer->FieldIndex(Provinces::kActiveField); + + EXPECT_EQ(_layer->CellInteger(id, 0), 1); + EXPECT_EQ(_layer->CellString(name, 0), "Noord"); + EXPECT_EQ(_layer->CellString(name, 1), "Oost"); + ASSERT_TRUE(_layer->CellDouble(area, 0).has_value()); + EXPECT_DOUBLE_EQ(*_layer->CellDouble(area, 0), 1.0); + EXPECT_EQ(_layer->CellInteger(active, 2), 0); + EXPECT_EQ(_layer->CellInteger(active, 3), 1); +} + +TEST_P(VectorLayerTest, PreservesNonAsciiAttributeValues) +{ + const int name = _layer->FieldIndex(Provinces::kNameField); + EXPECT_EQ(_layer->CellString(name, 2), Provinces::kNonAsciiName); +} + +TEST_P(VectorLayerTest, DistinguishesNullFromEmpty) +{ + const int name = _layer->FieldIndex(Provinces::kNameField); + const int surveyed = _layer->FieldIndex(Provinces::kSurveyedField); + + EXPECT_FALSE(_layer->IsCellNull(name, 0)); + EXPECT_TRUE(_layer->IsCellNull(name, Provinces::kNullFeature)); + EXPECT_TRUE(_layer->IsCellNull(surveyed, Provinces::kNullFeature)); + EXPECT_FALSE(_layer->IsCellNull(surveyed, 0)); +} + +TEST_P(VectorLayerTest, ReadsDatesAsText) +{ + const int surveyed = _layer->FieldIndex(Provinces::kSurveyedField); + EXPECT_EQ(_layer->CellString(surveyed, 0), "2020/01/15"); +} + +TEST_P(VectorLayerTest, ReportsTheProjection) +{ + const std::string wkt = _layer->ProjectionWkt(); + ASSERT_FALSE(wkt.empty()); + EXPECT_NE(wkt.find("Amersfoort"), std::string::npos) << wkt; + EXPECT_NE(wkt.find("28992"), std::string::npos) << wkt; +} + +TEST_P(VectorLayerTest, ReadsGeometry) +{ + const std::string wkt = _layer->GeometryWkt(0); + EXPECT_TRUE(wkt.starts_with("POLYGON")) << wkt; + + const Extent extent = _layer->GeometryExtent(0); + ASSERT_FALSE(extent.IsEmpty()); + EXPECT_DOUBLE_EQ(extent.xMin, 100000.0); + EXPECT_DOUBLE_EQ(extent.xMax, 101000.0); + EXPECT_DOUBLE_EQ(extent.Width() * extent.Height(), 1000000.0); +} + +TEST_P(VectorLayerTest, IsReadOnlyByDefault) +{ + EXPECT_FALSE(_dataset->IsWritable()); + EXPECT_FALSE(_layer->IsWritable()); + + const int name = _layer->FieldIndex(Provinces::kNameField); + EXPECT_THROW(_layer->SetCellString(name, 0, "Zuid"), CoreError); +} + +TEST_P(VectorLayerTest, RejectsOutOfRangeFeatureIndexes) +{ + const int name = _layer->FieldIndex(Provinces::kNameField); + const int area = _layer->FieldIndex(Provinces::kAreaField); + const int id = _layer->FieldIndex(Provinces::kIdField); + + const std::array invalidIndexes{ + -1, _layer->FeatureCount(), std::int64_t{1} << 32, std::numeric_limits::max()}; + for (const std::int64_t index : invalidIndexes) + { + EXPECT_THROW((void)_layer->IsCellNull(name, index), CoreError); + EXPECT_THROW((void)_layer->CellString(name, index), CoreError); + EXPECT_THROW((void)_layer->CellDouble(area, index), CoreError); + EXPECT_THROW((void)_layer->CellInteger(id, index), CoreError); + EXPECT_THROW((void)_layer->GeometryWkt(index), CoreError); + EXPECT_THROW((void)_layer->GeometryExtent(index), CoreError); + } +} + +TEST_P(VectorLayerTest, PreservesNullAttributeResults) +{ + const int name = _layer->FieldIndex(Provinces::kNameField); + EXPECT_TRUE(_layer->IsCellNull(name, Provinces::kNullFeature)); + EXPECT_TRUE(_layer->CellString(name, Provinces::kNullFeature).empty()); + EXPECT_FALSE(_layer->CellDouble(name, Provinces::kNullFeature).has_value()); + EXPECT_FALSE(_layer->CellInteger(name, Provinces::kNullFeature).has_value()); +} + +// ------------------------------------------------------------------ editing + +namespace +{ + class VectorLayerEditTest : public testing::TestWithParam + { + protected: + void SetUp() override + { + _path = MakeProvincesDataset(_dir.Path(), GetParam()); + } + + /// Opens the fixture, hands the layer to `edit`, then closes so the + /// driver flushes everything to disk. + template + void Edit(TEdit edit) + { + std::unique_ptr dataset = VectorDataset::Open(_path, OpenMode::Update); + ASSERT_TRUE(dataset->IsWritable()); + edit(dataset->Layer(0)); + } + + [[nodiscard]] std::unique_ptr Reopen() const + { + return VectorDataset::Open(_path); + } + + TempDirectory _dir; + std::filesystem::path _path; + }; +} + +INSTANTIATE_TEST_SUITE_P(Formats, VectorLayerEditTest, + testing::Values("provinces.shp", "provinces.gpkg"), + [](const testing::TestParamInfo& info) + { + return std::string(info.param).find("gpkg") != std::string::npos + ? "GeoPackage" + : "Shapefile"; + }); + +TEST_P(VectorLayerEditTest, GeneratesEveryPartOfTheDataset) +{ + EXPECT_TRUE(std::filesystem::exists(_path)); + if (_path.extension() == ".shp") + { + for (const char* sidecar : {".shx", ".dbf", ".prj", ".cpg"}) + { + EXPECT_TRUE(std::filesystem::exists(std::filesystem::path(_path).replace_extension(sidecar))) + << sidecar; + } + } +} + +TEST_P(VectorLayerEditTest, PersistsAttributeEdits) +{ + Edit([](VectorLayer& layer) + { + layer.SetCellString(layer.FieldIndex(Provinces::kNameField), 0, "Zuid-Holland"); + layer.SetCellDouble(layer.FieldIndex(Provinces::kAreaField), 0, 42.5); + layer.SetCellInteger(layer.FieldIndex(Provinces::kActiveField), 0, 0); + }); + + const std::unique_ptr dataset = Reopen(); + VectorLayer& layer = dataset->Layer(0); + + EXPECT_EQ(layer.CellString(layer.FieldIndex(Provinces::kNameField), 0), "Zuid-Holland"); + ASSERT_TRUE(layer.CellDouble(layer.FieldIndex(Provinces::kAreaField), 0).has_value()); + EXPECT_DOUBLE_EQ(*layer.CellDouble(layer.FieldIndex(Provinces::kAreaField), 0), 42.5); + EXPECT_EQ(layer.CellInteger(layer.FieldIndex(Provinces::kActiveField), 0), 0); + + EXPECT_EQ(layer.FeatureCount(), Provinces::kFeatureCount); + EXPECT_EQ(layer.CellString(layer.FieldIndex(Provinces::kNameField), 1), "Oost"); +} + +TEST_P(VectorLayerEditTest, FlushesPendingEdits) +{ + const std::unique_ptr dataset = VectorDataset::Open(_path, OpenMode::Update); + VectorLayer& layer = dataset->Layer(0); + layer.SetCellString(layer.FieldIndex(Provinces::kNameField), 0, "Flushed"); + EXPECT_NO_THROW(dataset->Flush()); + + const std::unique_ptr reopened = Reopen(); + EXPECT_EQ(reopened->Layer(0).CellString( + reopened->Layer(0).FieldIndex(Provinces::kNameField), 0), "Flushed"); +} + +TEST_P(VectorLayerEditTest, RejectsOutOfRangeFeatureIndexes) +{ + Edit([](VectorLayer& layer) + { + const int name = layer.FieldIndex(Provinces::kNameField); + const int area = layer.FieldIndex(Provinces::kAreaField); + const int id = layer.FieldIndex(Provinces::kIdField); + const std::array invalidIndexes{ + -1, layer.FeatureCount(), std::int64_t{1} << 32, std::numeric_limits::max()}; + for (const std::int64_t index : invalidIndexes) + { + EXPECT_THROW(layer.SetCellString(name, index, "Invalid"), CoreError); + EXPECT_THROW(layer.SetCellDouble(area, index, 1.0), CoreError); + EXPECT_THROW(layer.SetCellInteger(id, index, 1), CoreError); + EXPECT_THROW(layer.SetCellNull(name, index), CoreError); + EXPECT_THROW(layer.SetGeometryWkt(index, "POLYGON EMPTY"), CoreError); + } + }); +} + +TEST_P(VectorLayerEditTest, PersistsNonAsciiEdits) +{ + Edit([](VectorLayer& layer) + { + layer.SetCellString(layer.FieldIndex(Provinces::kNameField), 0, "Sk\u00e2rsterl\u00e2n"); + }); + + const std::unique_ptr dataset = Reopen(); + EXPECT_EQ(dataset->Layer(0).CellString( + dataset->Layer(0).FieldIndex(Provinces::kNameField), 0), + "Sk\u00e2rsterl\u00e2n"); +} + +TEST_P(VectorLayerEditTest, PersistsNulls) +{ + Edit([](VectorLayer& layer) + { + layer.SetCellNull(layer.FieldIndex(Provinces::kNameField), 0); + layer.SetCellString(layer.FieldIndex(Provinces::kNameField), Provinces::kNullFeature, "Filled"); + }); + + const std::unique_ptr dataset = Reopen(); + VectorLayer& layer = dataset->Layer(0); + const int name = layer.FieldIndex(Provinces::kNameField); + + EXPECT_TRUE(layer.IsCellNull(name, 0)); + EXPECT_FALSE(layer.IsCellNull(name, Provinces::kNullFeature)); + EXPECT_EQ(layer.CellString(name, Provinces::kNullFeature), "Filled"); +} + +TEST_P(VectorLayerEditTest, PersistsGeometryEdits) +{ + static constexpr const char* kMoved = + "POLYGON ((200000 500000, 201000 500000, 201000 501000, 200000 501000, 200000 500000))"; + + Edit([](VectorLayer& layer) { layer.SetGeometryWkt(0, kMoved); }); + + const std::unique_ptr dataset = Reopen(); + const Extent extent = dataset->Layer(0).GeometryExtent(0); + + ASSERT_FALSE(extent.IsEmpty()); + EXPECT_DOUBLE_EQ(extent.xMin, 200000.0); + EXPECT_DOUBLE_EQ(extent.yMax, 501000.0); +} + +TEST_P(VectorLayerEditTest, RejectsInvalidWkt) +{ + const GdalEnvironment::QuietScope quiet; + Edit([](VectorLayer& layer) + { + EXPECT_THROW(layer.SetGeometryWkt(0, "NOT WKT"), CoreError); + }); +} + +TEST_P(VectorLayerEditTest, ReflectsEditsWithoutReopening) +{ + const std::unique_ptr dataset = VectorDataset::Open(_path, OpenMode::Update); + VectorLayer& layer = dataset->Layer(0); + const int name = layer.FieldIndex(Provinces::kNameField); + const int area = layer.FieldIndex(Provinces::kAreaField); + + ASSERT_EQ(layer.CellString(name, 0), "Noord"); + + layer.SetCellString(name, 0, "Changed"); + EXPECT_EQ(layer.CellString(name, 0), "Changed"); + + // Reading a different feature and coming back must not resurrect the old value. + EXPECT_EQ(layer.CellString(name, 1), "Oost"); + EXPECT_EQ(layer.CellString(name, 0), "Changed"); + + layer.SetCellNull(area, 0); + EXPECT_TRUE(layer.IsCellNull(area, 0)); +} + +TEST_P(VectorLayerEditTest, RecomputesTheExtentAfterAGeometryEdit) +{ + static constexpr const char* kMoved = + "POLYGON ((200000 500000, 201000 500000, 201000 501000, 200000 501000, 200000 500000))"; + + const std::unique_ptr dataset = VectorDataset::Open(_path, OpenMode::Update); + VectorLayer& layer = dataset->Layer(0); + + ASSERT_DOUBLE_EQ(layer.GetExtent().xMax, Provinces::kMaxX); + + layer.SetGeometryWkt(0, kMoved); + EXPECT_DOUBLE_EQ(layer.GetExtent().xMax, 201000.0); +} + +TEST_P(VectorLayerEditTest, KeepsGeneratedFixturesIndependent) +{ + Edit([](VectorLayer& layer) + { + layer.SetCellString(layer.FieldIndex(Provinces::kNameField), 0, "Changed"); + }); + + const TempDirectory otherDir; + const std::unique_ptr other = + VectorDataset::Open(MakeProvincesDataset(otherDir.Path(), GetParam())); + EXPECT_EQ(other->Layer(0).CellString( + other->Layer(0).FieldIndex(Provinces::kNameField), 0), + "Noord"); +} diff --git a/vcpkg-configuration.json b/vcpkg-configuration.json new file mode 100644 index 0000000..cadeb73 --- /dev/null +++ b/vcpkg-configuration.json @@ -0,0 +1,6 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg-configuration.schema.json", + "overlay-triplets": [ + "./build/triplets" + ] +} diff --git a/vcpkg.json b/vcpkg.json new file mode 100644 index 0000000..89699f5 --- /dev/null +++ b/vcpkg.json @@ -0,0 +1,54 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg/master/scripts/vcpkg.schema.json", + "name": "mapwingis6", + "version": "6.0.0", + "description": "MapWinGIS 6 mapping engine", + "homepage": "https://github.com/MapWindow/MapWinGIS6", + "license": "MPL-2.0", + "supports": "windows & !uwp", + "dependencies": [ + { + "name": "gdal", + "default-features": false, + "features": [ + "recommended-features", + "gif", + "iconv", + "libxml2", + "lzma", + "openjpeg", + "openssl", + "pcre2", + "webp", + "zstd" + ] + }, + "geos" + ], + "default-features": [], + "features": { + "full-drivers": { + "description": "Driver set used for release packages: adds HDF5, NetCDF, KML, SpatiaLite and PostgreSQL support to GDAL. Slow to build.", + "dependencies": [ + { + "name": "gdal", + "default-features": false, + "features": [ + "hdf5", + "libkml", + "libspatialite", + "netcdf", + "postgresql" + ] + } + ] + }, + "tests": { + "description": "Build the C++ unit tests", + "dependencies": [ + "gtest" + ] + } + }, + "builtin-baseline": "a42757564758c60651ebc616d9b000b7b91249ef" +}