From 1356a713d4e283aaf30957d1afbf9858fef0df57 Mon Sep 17 00:00:00 2001 From: Paul Meems Date: Wed, 18 Nov 2026 17:24:52 +0100 Subject: [PATCH 1/2] Share render scenes and harden ActiveX dispatch - Share immutable layer geometry without copying, render polygonal collection members, and skip malformed parts. Reuse GDI buffers and fit print and scaled draws to the live visible extent. - Deliver one GDAL notification batch per message, repost wakes consumed by nested pumps, and keep vector-load state alive through reentrant control closure. Match managed completions by operation ID and normalize null warnings. - Invalidate cached features after writes so reads reflect values stored by the driver. - Make ActiveX test exports optional, protect existing COM registrations during activation checks, and add regression tests and documentation. --- .ai/memory/architecture/activex.md | 15 ++ .ai/memory/architecture/core-library.md | 7 + .ai/memory/lessons/lessons.md | 22 +++ .idea/.gitignore | 6 + CMakeLists.txt | 3 + docs/ARCHITECTURE.md | 17 +- docs/BUILDING.md | 1 + docs/gdal-integration.md | 4 +- .../ActiveXTestHost/GdalOperationClient.cs | 13 +- src/MapWinGIS.ActiveX/CMakeLists.txt | 3 + src/MapWinGIS.ActiveX/ComConversion.cpp | 6 +- src/MapWinGIS.ActiveX/GdalEventSource.cpp | 96 ++++++----- src/MapWinGIS.ActiveX/GdalEventSource.h | 1 + .../GdalOperationDispatcher.cpp | 10 ++ .../GdiVectorLayerRenderer.cpp | 19 ++- .../MapWinGIS.ActiveX.vcxproj | 10 ++ src/MapWinGIS.ActiveX/MapWinGISControl.cpp | 83 +++++++--- .../OpenGlVectorLayerRenderer.cpp | 9 +- .../include/mapwingis/map/MapView.h | 17 +- .../mapwingis/rendering/MapRenderScene.h | 19 ++- .../mapwingis/rendering/VectorRenderScene.h | 12 +- .../include/mapwingis/vector/VectorDataset.h | 5 +- .../src/gdal/GdalAlgorithmRunner.cpp | 10 +- src/MapWinGIS.Core/src/map/MapView.cpp | 18 ++- .../src/rendering/MapRenderScene.cpp | 3 +- .../src/rendering/PolygonTriangulation.cpp | 31 +++- .../src/rendering/VectorRenderScene.cpp | 63 ++++++-- .../src/vector/VectorDataset.cpp | 10 +- .../ActiveXActivationTests.cpp | 152 +++++++++++++++++- .../RenderingBaselineTests.cpp | 8 +- .../VectorLayerRendererTests.cpp | 85 +++++++--- .../Verify-ActiveXActivation.ps1 | 25 ++- .../MapRenderSceneTests.cpp | 20 +-- tests/MapWinGIS.Core.Tests/MapViewTests.cpp | 57 +++++-- tests/MapWinGIS.Core.Tests/TestData.cpp | 2 +- tests/MapWinGIS.Core.Tests/TestData.h | 2 + .../MapWinGIS.Core.Tests/VectorLayerTests.cpp | 21 +++ .../VectorRenderSceneTests.cpp | 45 ++++++ 38 files changed, 749 insertions(+), 181 deletions(-) diff --git a/.ai/memory/architecture/activex.md b/.ai/memory/architecture/activex.md index 93c2b9e..8980fd6 100644 --- a/.ai/memory/architecture/activex.md +++ b/.ai/memory/architecture/activex.md @@ -46,6 +46,21 @@ ActiveX-specific implementation units are also compiled into `MapWinGIS.ActiveX.Impl.lib`, allowing native tests to exercise them without requiring COM activation. +Alternate-size draws (printing, scaled metafiles) fit the live visible extent +into the target size, so they show what the screen shows instead of the +viewport's scale at a different pixel size. + +GDAL notifications are delivered one drained batch per dispatch message. +Notifications queued while sinks run post their own wake, and a wake consumed +by a sink's nested message pump is re-posted after the batch. Do not +reintroduce a drain-until-empty loop: it keeps the STA thread busy for as long +as an operation reports progress. + +Test-only exports such as `MapWinGISControlSetVectorPreparationHookForTesting` +exist only when `MWG_ACTIVEX_TEST_HOOKS` is defined +(`MWG_ENABLE_ACTIVEX_TEST_HOOKS` in CMake, which defaults to `MWG_BUILD_TESTS`; +`MwgEnableActiveXTestHooks` in MSBuild). Tests that need them skip when absent. + ## Current limits The control exposes a deliberately small v6 automation API. It does not expose diff --git a/.ai/memory/architecture/core-library.md b/.ai/memory/architecture/core-library.md index 803dbcf..bb8f6ad 100644 --- a/.ai/memory/architecture/core-library.md +++ b/.ai/memory/architecture/core-library.md @@ -45,6 +45,13 @@ need separate `InvalidateLayerScene` calls after an edit, or one `InvalidateScene` call for the whole map. Invalidating a failed layer also allows retrying its source. Visibility changes alone retain the cached result. +Layer scenes are immutable and shared: `LayerRenderScene::scene` is a +`std::shared_ptr`, so composing a `MapRenderScene` or +handing a prepared scene to `MapView::AddLayer` does not copy geometry. +Renderers must treat a null scene as a failed layer. Scene building skips empty +geometry, renders polygonal members of geometry collections, and counts other +skipped parts in `VectorRenderScene::skippedGeometryCount`. + ## References - [Architecture documentation](../../../docs/ARCHITECTURE.md#module-design) diff --git a/.ai/memory/lessons/lessons.md b/.ai/memory/lessons/lessons.md index 388c64a..24d6db8 100644 --- a/.ai/memory/lessons/lessons.md +++ b/.ai/memory/lessons/lessons.md @@ -112,3 +112,25 @@ back the writes. Other formats retain their driver's stored-extent behavior. See [VectorDataset.cpp](../../../src/MapWinGIS.Core/src/vector/VectorDataset.cpp) and the shrinking and reopening cases in [VectorLayerTests.cpp](../../../tests/MapWinGIS.Core.Tests/VectorLayerTests.cpp). + +## Squash-merging development into main breaks later merges + +**Problem:** After `main` received `development` as one squash commit, a trial +merge of `development` into `main` conflicted in 29 files, although the squash +tree was identical to a commit already on `development`. + +**Cause:** The squash commit is not an ancestor of `development`, so Git sees +both branches adding the same files independently. + +**Resolution:** Verify that `git diff origin/main` is +empty, then record the merge on `development` with +`git merge -s ours origin/main`. Use merge commits, not squash commits, for +`development` to `main` releases. + +## Driver coercion makes cached written values stale + +OGR drivers can coerce a written value; the Shapefile driver truncates a string +to the DBF field width, for example. Core therefore discards its cached feature +after every `SetFeature` write, successful or not, so a later read returns the +stored value instead of the value the caller wrote. See +`VectorLayerEditTest.ReadsBackTheStoredValueAfterTheDriverCoercesAWrite`. diff --git a/.idea/.gitignore b/.idea/.gitignore index f3b42f4..dc3d416 100644 --- a/.idea/.gitignore +++ b/.idea/.gitignore @@ -10,3 +10,9 @@ # Datasource local storage ignored files /dataSources/ /dataSources.local.xml +# Machine- and checkout-specific project files +/*.local.json +/*.local.xml +/misc.xml +/modules.xml +/*.iml diff --git a/CMakeLists.txt b/CMakeLists.txt index a2ad0c1..c9ad615 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,6 +17,9 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") # --- options needed before project() ----------------------------------------- option(MWG_BUILD_TESTS "Build the GoogleTest suite (adds the 'tests' vcpkg feature)" ON) option(MWG_BUILD_ACTIVEX "Build the ActiveX control (requires Windows SDK MIDL and ATL)" ON) +option(MWG_ENABLE_ACTIVEX_TEST_HOOKS + "Export test-only hooks from MapWinGIS.ocx; turn OFF for distributed binaries (MSBuild: MwgEnableActiveXTestHooks)" + ${MWG_BUILD_TESTS}) set(MWG_WINDOWS_SDK "10.0.28000.0" CACHE STRING "Windows SDK version (MSBuild: MwgWindowsSdk). 10.0 means the newest installed SDK") diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 548051f..9111858 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -226,7 +226,8 @@ has no extent or transform of its own. - **Render scene.** `rendering::CreateMapRenderScene` (`mapwingis/rendering/MapRenderScene.h`) copies the polygon geometry of - every visible layer into an owned `MapRenderScene`, bottom layer first. Each + every visible layer into an immutable, shared per-layer scene in a + `MapRenderScene`, bottom layer first. Each layer is converted on its own: hidden layers, layers without polygon geometry, and layers that fail (for example, non-polygon layers) are listed in `skippedLayers` with a reason and do not stop the other layers. @@ -241,8 +242,8 @@ has no extent or transform of its own. assembles it from cached layer scenes on the next call. The `AddLayer` overload that accepts a prepared vector scene transfers that geometry into the current scene without another - traversal. It copies the new geometry into its layer cache before adding - the layer. Existing scene storage stays unchanged when it is current. + traversal. Its layer cache and the assembled scene share that geometry + instead of copying it. Existing scene storage stays unchanged when it is current. It assembles a stale scene before adding the new layer. Every mutator returns whether the frame may have changed, and the host requests a redraw when it does. Edits to source @@ -302,7 +303,9 @@ viewport. For windowless hosts, `SetObjectRects` supplies the live size. `OnDraw` uses a viewport copy sized to the drawing target. Printing, metafile output, and scaled draws do not change the live viewport or its pending fit, and use temporary frame/staging buffers rather than resizing the interactive -screen buffers. +screen buffers. When the target size differs from the live size, the copy is +fitted to the live visible extent, so the target shows the same map area as +the screen at the target's own scale. If no view exists yet, drawing fits only that copy to the visible map extent. Resizing updates the OpenGL viewport and staging buffers without changing ownership of map data. A left-button drag pans the shared `MapView` by the @@ -462,8 +465,10 @@ the map snapshot without rereading visible layers, hidden layers are prepared when first shown, and removing or clearing layers drops only the corresponding cache entries. InvalidateLayerScene rebuilds one layer after source edits; InvalidateScene clears all layer caches. Adding a prepared layer seeds its -cache directly. The public map scene remains an owning snapshot, so assembly -copies cached geometry. The cache and snapshot each own coordinates and meshes. +cache directly. Layer scenes are immutable and shared through +`std::shared_ptr`, so assembling the map snapshot +shares cached coordinates and meshes instead of copying them; peak memory +stays at one copy of each layer's geometry. When a driver cannot provide a fast extent, scene preparation computes bounds during the geometry traversal. It caches those bounds on the vector layer, so a later map fit does not scan the layer again. diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 852cd76..2c4574d 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -264,6 +264,7 @@ bin\Release\x64\MapWinGIS.ActiveX.Tests.exe --gtest_output=xml:activex-testresul | `MwgVcpkgRoot` | resolved (see above) | vcpkg location | | `MwgVcpkgFeatures` | `tests` | Semicolon-separated manifest features | | `MwgEnableAsan` | `false` | Adds `/fsanitize=address` | +| `MwgEnableActiveXTestHooks` | `true` | Exports test-only hooks from `MapWinGIS.ocx`. Set `false` for distributed binaries. CMake: `MWG_ENABLE_ACTIVEX_TEST_HOOKS`, which defaults to `MWG_BUILD_TESTS` | | `MwgDeployRuntimeData` | `true` for Core, `false` otherwise | Copies `gdal-data` and `proj` to the output folder | ## CMake migration diff --git a/docs/gdal-integration.md b/docs/gdal-integration.md index 09edf69..17a74cb 100644 --- a/docs/gdal-integration.md +++ b/docs/gdal-integration.md @@ -138,7 +138,9 @@ Call the interface on its owning COM apartment, which must continue pumping messages while operations are active. A message-only dispatcher delivers `GdalProgress` and `GdalOperationCompleted` events on that thread. Progress is coalesced per operation; -the terminal event is retained. The wrapper permits sixteen outstanding +the terminal event is retained. Each dispatch message delivers one batch of +pending events and then returns to the message loop, so a fast-reporting +operation does not keep the thread inside event delivery. The wrapper permits sixteen outstanding operations. Call `EndGdalOperation` after completion to retrieve success, cancellation, GDAL error code, summary, full diagnostics, callback error code and message, and warnings, and to release the operation slot. An incomplete diff --git a/samples/CSharp/ActiveXTestHost/GdalOperationClient.cs b/samples/CSharp/ActiveXTestHost/GdalOperationClient.cs index 7e60827..1f0617e 100644 --- a/samples/CSharp/ActiveXTestHost/GdalOperationClient.cs +++ b/samples/CSharp/ActiveXTestHost/GdalOperationClient.cs @@ -29,7 +29,7 @@ void EndGdalOperation( [MarshalAs(UnmanagedType.BStr)] out string summary, [MarshalAs(UnmanagedType.BStr)] out string diagnostics, [MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_BSTR)] - out string[] warnings); + out string[]? warnings); } internal sealed record GdalOperationResult( @@ -77,7 +77,6 @@ public static async Task ConvertRasterAsync( TaskCreationOptions.RunContinuationsAsynchronously); var progressEvents = new List(); long operationId = 0; - long completedOperationId = 0; GdalProgressEvent onProgress = (id, fraction, message) => { @@ -89,7 +88,8 @@ public static async Task ConvertRasterAsync( }; GdalCompletedEvent onCompleted = id => { - completedOperationId = id; + // Other operations on the same control also raise this event, so + // only the matching completion may resolve this call. if (id == operationId) { completed.TrySetResult(id); @@ -136,7 +136,7 @@ public static async Task ConvertRasterAsync( control.CancelGdalOperation(operationId); } - await completed.Task.ConfigureAwait(true); + long completedOperationId = await completed.Task.ConfigureAwait(true); control.EndGdalOperation( operationId, out bool succeeded, @@ -146,7 +146,7 @@ public static async Task ConvertRasterAsync( out string callbackError, out string summary, out string diagnostics, - out string[] warnings); + out string[]? warnings); return new GdalOperationResult( operationId, @@ -159,7 +159,8 @@ public static async Task ConvertRasterAsync( callbackError, summary, diagnostics, - warnings); + // The control returns a null array when there are no warnings. + warnings ?? []); } finally { diff --git a/src/MapWinGIS.ActiveX/CMakeLists.txt b/src/MapWinGIS.ActiveX/CMakeLists.txt index eb56bd8..c2b8ad5 100644 --- a/src/MapWinGIS.ActiveX/CMakeLists.txt +++ b/src/MapWinGIS.ActiveX/CMakeLists.txt @@ -85,6 +85,9 @@ target_link_libraries(MapWinGIS.ActiveX PRIVATE ) target_compile_definitions(MapWinGIS.ActiveX PRIVATE "$<$:_ATL_APARTMENT_THREADED>") +if(MWG_ENABLE_ACTIVEX_TEST_HOOKS) + target_compile_definitions(MapWinGIS.ActiveX PRIVATE "$<$:MWG_ACTIVEX_TEST_HOOKS>") +endif() # MSBuild ResourceCompile: /l 0x0409 and the MIDL output directory on the include path. target_compile_options(MapWinGIS.ActiveX PRIVATE "$<$:/l0x0409>") diff --git a/src/MapWinGIS.ActiveX/ComConversion.cpp b/src/MapWinGIS.ActiveX/ComConversion.cpp index f4f8281..da19082 100644 --- a/src/MapWinGIS.ActiveX/ComConversion.cpp +++ b/src/MapWinGIS.ActiveX/ComConversion.cpp @@ -7,6 +7,7 @@ #include "ComConversion.h" #include +#include #include #include @@ -185,10 +186,13 @@ namespace mwg::activex::ComConversion { return result; } + // Own the copy before converting: BstrToUtf8 can throw bad_alloc. + const std::unique_ptr ownedArgument{ + argument, + &::SysFreeString}; std::string converted; result = BstrToUtf8(argument, converted); - ::SysFreeString(argument); if (FAILED(result)) { return result; diff --git a/src/MapWinGIS.ActiveX/GdalEventSource.cpp b/src/MapWinGIS.ActiveX/GdalEventSource.cpp index 0c49934..8a5b844 100644 --- a/src/MapWinGIS.ActiveX/GdalEventSource.cpp +++ b/src/MapWinGIS.ActiveX/GdalEventSource.cpp @@ -239,12 +239,20 @@ namespace mwg::activex LRESULT GdalEventSource::OnDispatch(BOOL& handled) { handled = TRUE; - if (_dispatching || !_dispatcher.IsDispatchActive()) + if (_dispatching) + { + // A sink pumped messages and consumed a wake meant for work queued + // after the current batch was drained. Re-post it once that batch ends. + _redispatchRequested = true; + return 0; + } + if (!_dispatcher.IsDispatchActive()) { return 0; } _dispatching = true; + _redispatchRequested = false; const std::uint64_t generation = _dispatcher.GetGeneration(); struct DispatchGuard final { @@ -260,63 +268,65 @@ namespace mwg::activex } } dispatchGuard{*this}; - while (_dispatcher.GetGeneration() == generation && - _dispatcher.IsDispatchActive()) + // Deliver one batch per message. Notifications queued while the sinks + // run post their own wake message, so the owner thread returns to its + // message loop between batches instead of looping here for as long as + // a fast-reporting operation keeps producing progress. + const auto notifications = _dispatcher.DrainNotifications(); + for (const GdalOperationNotification& notification : notifications) { - const auto notifications = _dispatcher.DrainNotifications(); - if (notifications.empty()) + if (_dispatcher.GetGeneration() != generation || + !_dispatcher.IsDispatchActive()) { break; } + if (!_dispatcher.BeginNotificationDelivery(notification.operationId)) + { + continue; + } - for (const GdalOperationNotification& notification : notifications) + struct NotificationGuard final { - if (_dispatcher.GetGeneration() != generation || - !_dispatcher.IsDispatchActive()) - { - break; - } - if (!_dispatcher.BeginNotificationDelivery(notification.operationId)) - { - continue; - } + GdalOperationDispatcher& dispatcher; + std::uint64_t operationId; + std::uint64_t generation; - struct NotificationGuard final + ~NotificationGuard() { - GdalOperationDispatcher& dispatcher; - std::uint64_t operationId; - std::uint64_t generation; - - ~NotificationGuard() + if (dispatcher.GetGeneration() == generation) { - if (dispatcher.GetGeneration() == generation) - { - dispatcher.EndNotificationDelivery(operationId); - } + dispatcher.EndNotificationDelivery(operationId); } - } notificationGuard{_dispatcher, notification.operationId, generation}; - - if (notification.kind == GdalNotificationKind::Completed && - _completionCallback != nullptr) - { - _completionCallback(_completionContext, notification.operationId); - } - const HRESULT result = - notification.kind == GdalNotificationKind::Progress - ? FireProgress(notification, generation) - : FireCompleted(notification.operationId, generation); - if (FAILED(result) && _dispatcher.GetGeneration() == generation) - { - RecordCallbackError(notification.operationId, result); - } - if (_dispatcher.GetGeneration() != generation) - { - break; } + } notificationGuard{_dispatcher, notification.operationId, generation}; + + if (notification.kind == GdalNotificationKind::Completed && + _completionCallback != nullptr) + { + _completionCallback(_completionContext, notification.operationId); + } + const HRESULT result = + notification.kind == GdalNotificationKind::Progress + ? FireProgress(notification, generation) + : FireCompleted(notification.operationId, generation); + if (FAILED(result) && _dispatcher.GetGeneration() == generation) + { + RecordCallbackError(notification.operationId, result); + } + if (_dispatcher.GetGeneration() != generation) + { + break; } } if (_dispatcher.GetGeneration() == generation) { + if (_redispatchRequested && _dispatchWindow != nullptr && + !_dispatchWindowDestroyPending && _dispatcher.IsDispatchActive() && + !_dispatchWindow->PostWake()) + { + ArmRetryTimer(); + } + _redispatchRequested = false; UpdateRetryTimer(); } return 0; diff --git a/src/MapWinGIS.ActiveX/GdalEventSource.h b/src/MapWinGIS.ActiveX/GdalEventSource.h index 9ebd2b7..455f0d6 100644 --- a/src/MapWinGIS.ActiveX/GdalEventSource.h +++ b/src/MapWinGIS.ActiveX/GdalEventSource.h @@ -92,6 +92,7 @@ namespace mwg::activex void* _completionContext = nullptr; std::shared_ptr _dispatchWindow; bool _dispatching = false; + bool _redispatchRequested = false; bool _dispatchWindowDestroyPending = false; bool _closing = false; }; diff --git a/src/MapWinGIS.ActiveX/GdalOperationDispatcher.cpp b/src/MapWinGIS.ActiveX/GdalOperationDispatcher.cpp index 6f7235b..e449097 100644 --- a/src/MapWinGIS.ActiveX/GdalOperationDispatcher.cpp +++ b/src/MapWinGIS.ActiveX/GdalOperationDispatcher.cpp @@ -621,6 +621,16 @@ namespace mwg::activex { std::vector notifications; std::lock_guard lock(_state->mutex); + // Reserve the whole batch before clearing any pending flag. After this + // point the pushes cannot reallocate and the moves cannot throw, so a + // bad_alloc leaves every notification pending for a later drain. + std::size_t pendingCount = 0; + for (const auto& entry : _state->operations) + { + pendingCount += (entry.second->progress.has_value() ? 1u : 0u) + + (entry.second->completionPending ? 1u : 0u); + } + notifications.reserve(pendingCount); _state->wakePending = false; for (auto& [operationId, operation] : _state->operations) { diff --git a/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp index 9814264..e9d0eb7 100644 --- a/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp +++ b/src/MapWinGIS.ActiveX/GdiVectorLayerRenderer.cpp @@ -161,13 +161,15 @@ namespace mwg::activex const rendering::VectorRenderScene& scene, const ViewTransform& transform, const double originX, - const double originY) + const double originY, + std::vector& points, + std::vector& ringCounts) { for (std::size_t polygonIndex = 0; polygonIndex < scene.polygons.size(); ++polygonIndex) { const rendering::PolygonView polygon = scene.polygons[polygonIndex]; - std::vector points; - std::vector ringCounts; + points.clear(); + ringCounts.clear(); for (std::size_t ringIndex = 0; ringIndex < polygon.size(); ++ringIndex) { const std::span ring = polygon[ringIndex]; @@ -267,16 +269,21 @@ namespace mwg::activex std::size_t drawnLayers = 0; try { + // Reused for every polygon so a frame allocates only when a ring set + // exceeds the largest one seen so far. + std::vector points; + std::vector ringCounts; for (const rendering::LayerRenderScene& layer : scene.layers) { - if (!HasDrawableCoordinates(layer.scene, *transform, originX, originY)) + if (layer.scene == nullptr || + !HasDrawableCoordinates(*layer.scene, *transform, originX, originY)) { _failedLayers.push_back(layer.layerId); continue; } - const HRESULT layerResult = - DrawLayer(deviceContext, layer.scene, *transform, originX, originY); + const HRESULT layerResult = DrawLayer( + deviceContext, *layer.scene, *transform, originX, originY, points, ringCounts); if (layerResult == E_INVALIDARG) { _failedLayers.push_back(layer.layerId); diff --git a/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.vcxproj b/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.vcxproj index 30e1d6d..d142785 100644 --- a/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.vcxproj +++ b/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.vcxproj @@ -45,6 +45,10 @@ + + true + + $(MwgRepoRoot)src\MapWinGIS.Core\include;$(IntDir);%(AdditionalIncludeDirectories) @@ -64,6 +68,12 @@ + + + MWG_ACTIVEX_TEST_HOOKS;%(PreprocessorDefinitions) + + + diff --git a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp index ac105fb..945a55e 100644 --- a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp +++ b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -96,7 +97,7 @@ namespace struct PreparedVectorDataset final { std::shared_ptr dataset; - mwg::rendering::VectorRenderScene scene; + std::shared_ptr scene; LONGLONG featureCount = 0; }; @@ -122,24 +123,32 @@ namespace } } - mwg::rendering::VectorRenderScene preparedScene; + std::shared_ptr preparedScene; if (scene.layers.empty()) { - preparedScene.sourceFeatureCount = dataset->Layer(0).FeatureCount(); + auto emptyScene = std::make_shared(); + emptyScene->sourceFeatureCount = dataset->Layer(0).FeatureCount(); + preparedScene = std::move(emptyScene); } else { + // The candidate map is discarded, so this is the only owner of the + // geometry; MapView stores the same snapshot without copying it. preparedScene = std::move(scene.layers.front().scene); } + if (preparedScene == nullptr) + { + throw mwg::CoreError("Layer render scene is missing"); + } if (std::cmp_greater( - preparedScene.sourceFeatureCount, + preparedScene->sourceFeatureCount, std::numeric_limits::max())) { throw mwg::CoreError("Map feature count is out of range"); } const LONGLONG count = - static_cast(preparedScene.sourceFeatureCount); + static_cast(preparedScene->sourceFeatureCount); return {std::move(dataset), std::move(preparedScene), count}; } @@ -207,6 +216,9 @@ namespace } } +#if defined(MWG_ACTIVEX_TEST_HOOKS) +// Test-only export (MWG_ENABLE_ACTIVEX_TEST_HOOKS / MwgEnableActiveXTestHooks). +// Distributed binaries are built without it, so the hook stays null there. extern "C" __declspec(dllexport) void __cdecl MapWinGISControlSetVectorPreparationHookForTesting( void(*const hook)(void*, bool) noexcept, @@ -215,11 +227,12 @@ MapWinGISControlSetVectorPreparationHookForTesting( g_vectorPreparationContext.store(context, std::memory_order_relaxed); g_vectorPreparationHook.store(hook, std::memory_order_release); } +#endif struct CMapWinGISControl::VectorLoadState final { std::shared_ptr dataset; - mwg::rendering::VectorRenderScene scene; + std::shared_ptr scene; LONGLONG featureCount = 0; LONGLONG layerId = 0; bool cancelRequestedOnOwner = false; @@ -844,7 +857,10 @@ void CMapWinGISControl::CompleteVectorLoad( { return; } - const auto& state = found->second; + // Own the state: FireViewChange and other host callbacks can re-enter the + // control (for example Close or EndLoadVectorDataset) and erase this entry, + // so neither the iterator nor a reference into the map may be used later. + const std::shared_ptr state = found->second; if (state->committed) { return; @@ -947,9 +963,9 @@ void CMapWinGISControl::CompleteVectorLoad( catch (...) { } - found->second->dataset.reset(); - found->second->scene = {}; - found->second->featureCount = 0; + state->dataset.reset(); + state->scene = {}; + state->featureCount = 0; try { _gdalEvents.UpdateCompletedResult(operationId, std::move(result)); @@ -974,9 +990,9 @@ void CMapWinGISControl::CompleteVectorLoad( result.summary.clear(); result.diagnostics.clear(); } - found->second->dataset.reset(); - found->second->scene = {}; - found->second->featureCount = 0; + state->dataset.reset(); + state->scene = {}; + state->featureCount = 0; try { _gdalEvents.UpdateCompletedResult(operationId, std::move(result)); @@ -1002,9 +1018,9 @@ void CMapWinGISControl::CompleteVectorLoad( result.summary.clear(); result.diagnostics.clear(); } - found->second->dataset.reset(); - found->second->scene = {}; - found->second->featureCount = 0; + state->dataset.reset(); + state->scene = {}; + state->featureCount = 0; try { _gdalEvents.UpdateCompletedResult(operationId, std::move(result)); @@ -1128,30 +1144,30 @@ STDMETHODIMP CMapWinGISControl::get_FeatureCount(LONGLONG* count) STDMETHODIMP CMapWinGISControl::get_RenderingBackend(BSTR* backend) { - if (backend == nullptr) return SetControlComErrorInfo("The rendering backend output pointer is null.", IID_IMapWinGISControl4, E_POINTER); + if (backend == nullptr) return SetControlComErrorInfo("The rendering backend output pointer is null.", IID_IMapWinGISControl2, E_POINTER); const HRESULT result = CopyToBstr(BackendName(_renderer.GetActiveBackend()), backend); - return FAILED(result) ? SetControlComErrorInfo("The rendering backend could not be returned.", IID_IMapWinGISControl4, result) : result; + return FAILED(result) ? SetControlComErrorInfo("The rendering backend could not be returned.", IID_IMapWinGISControl2, result) : result; } STDMETHODIMP CMapWinGISControl::get_RenderingStatus(BSTR* status) { - if (status == nullptr) return SetControlComErrorInfo("The rendering status output pointer is null.", IID_IMapWinGISControl4, E_POINTER); + if (status == nullptr) return SetControlComErrorInfo("The rendering status output pointer is null.", IID_IMapWinGISControl2, E_POINTER); const HRESULT result = CopyToBstr(_renderer.GetDiagnostic(), status); - return FAILED(result) ? SetControlComErrorInfo("The rendering status could not be returned.", IID_IMapWinGISControl4, result) : result; + return FAILED(result) ? SetControlComErrorInfo("The rendering status could not be returned.", IID_IMapWinGISControl2, result) : result; } STDMETHODIMP CMapWinGISControl::get_RenderingBackendPreference(BSTR* preference) { - if (preference == nullptr) return SetControlComErrorInfo("The rendering backend preference output pointer is null.", IID_IMapWinGISControl4, E_POINTER); + if (preference == nullptr) return SetControlComErrorInfo("The rendering backend preference output pointer is null.", IID_IMapWinGISControl2, E_POINTER); const HRESULT result = CopyToBstr(PreferenceName(_renderer.GetPreference()), preference); - return FAILED(result) ? SetControlComErrorInfo("The rendering backend preference could not be returned.", IID_IMapWinGISControl4, result) : result; + return FAILED(result) ? SetControlComErrorInfo("The rendering backend preference could not be returned.", IID_IMapWinGISControl2, result) : result; } STDMETHODIMP CMapWinGISControl::put_RenderingBackendPreference(BSTR preference) { if (preference == nullptr) { - return SetControlComErrorInfo("The rendering backend preference is null.", IID_IMapWinGISControl4, E_INVALIDARG); + return SetControlComErrorInfo("The rendering backend preference is null.", IID_IMapWinGISControl2, E_INVALIDARG); } const UINT length = ::SysStringLen(preference); @@ -1181,7 +1197,7 @@ STDMETHODIMP CMapWinGISControl::put_RenderingBackendPreference(BSTR preference) } else { - return SetControlComErrorInfo("The rendering backend preference must be Automatic, OpenGL, or GDI.", IID_IMapWinGISControl4, E_INVALIDARG); + return SetControlComErrorInfo("The rendering backend preference must be Automatic, OpenGL, or GDI.", IID_IMapWinGISControl2, E_INVALIDARG); } if (_renderer.GetPreference() != previousPreference) @@ -1674,6 +1690,12 @@ void CMapWinGISControl::DispatchGdalNotifications(void* const control) noexcept { ::OutputDebugStringA(exception.what()); } + catch (...) + { + // This callback is noexcept; a non-standard exception must not + // terminate the host process. + ::OutputDebugStringW(L"MapWinGIS: unexpected exception while dispatching GDAL notifications.\n"); + } } STDMETHODIMP CMapWinGISControl::Close(const DWORD saveOption) @@ -1935,7 +1957,15 @@ HRESULT CMapWinGISControl::OnDraw(ATL_DRAWINFO& drawInfo) const mwg::rendering::MapRenderScene& scene = _view.Scene(); // Printing and scaled draws use a snapshot, never the live viewport. mwg::Viewport viewport = _view.GetViewport(); + const mwg::Extent liveExtent = viewport.VisibleExtent(); viewport.SetSize(static_cast(width), static_cast(height)); + if (alternateSize && liveExtent.IsValid()) + { + // Scale what the screen shows to the target: a print or a + // larger metafile must not reveal more of the map at screen + // resolution. + (void)viewport.FitExtent(liveExtent); + } if (!viewport.HasView()) { (void)viewport.FitExtent(_view.GetMap().GetExtent(), mwg::MapView::kDefaultPadding); @@ -1965,6 +1995,11 @@ HRESULT CMapWinGISControl::OnDraw(ATL_DRAWINFO& drawInfo) ::OutputDebugStringA(exception.what()); return E_FAIL; } + catch (...) + { + ::OutputDebugStringW(L"MapWinGIS: unexpected exception while drawing the map.\n"); + return E_UNEXPECTED; + } }; if (buffered) diff --git a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp index b40b888..8069407 100644 --- a/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp +++ b/src/MapWinGIS.ActiveX/OpenGlVectorLayerRenderer.cpp @@ -179,7 +179,11 @@ namespace mwg::activex { for (const rendering::LayerRenderScene& layer : scene.layers) { - const rendering::VectorRenderScene& vectorScene = layer.scene; + if (layer.scene == nullptr) + { + return false; + } + const rendering::VectorRenderScene& vectorScene = *layer.scene; if (vectorScene.fillMeshes.size() != vectorScene.polygons.size()) { return false; @@ -714,7 +718,8 @@ namespace mwg::activex for (const rendering::LayerRenderScene& layer : scene.layers) { - const HRESULT layerResult = DrawLayer(layer.scene, *transform); + // IsSupported above rejected null layer scenes. + const HRESULT layerResult = DrawLayer(*layer.scene, *transform); if (FAILED(layerResult)) { _lastFailureReason = L"OpenGL could not allocate its vertex buffers."; diff --git a/src/MapWinGIS.Core/include/mapwingis/map/MapView.h b/src/MapWinGIS.Core/include/mapwingis/map/MapView.h index ce80aed..892fc6d 100644 --- a/src/MapWinGIS.Core/include/mapwingis/map/MapView.h +++ b/src/MapWinGIS.Core/include/mapwingis/map/MapView.h @@ -73,13 +73,22 @@ namespace mwg /// The scene must match the specified source layer without intervening /// edits. An empty scene adds a layer with no drawable geometry. /// Transfers scene ownership and retains the current layers' scenes, - /// rebuilding stale scenes first. The cache owns a separate copy of - /// the new scene. The next Scene() does not reread data. + /// rebuilding stale scenes first. The cache and the assembled scene + /// share one immutable copy of the new geometry. The next Scene() + /// does not reread data. /// Fitting and argument errors are the same as the other AddLayer overload. /// \throws std::bad_alloc when memory runs out. LayerId AddLayer(std::shared_ptr dataset, rendering::VectorRenderScene scene, int layerIndex = 0); + /// Adds a layer with an already prepared, shared snapshot of its + /// geometry, as returned in LayerRenderScene::scene. Behaves like the + /// overload above but stores the given snapshot without copying it. + /// \throws InvalidArgument when scene is null, before the map changes. + LayerId AddLayer(std::shared_ptr dataset, + std::shared_ptr scene, + int layerIndex = 0); + /// Removes a layer; see Map::RemoveLayer. The view is kept. bool RemoveLayer(LayerId id) noexcept; @@ -152,7 +161,9 @@ namespace mwg /// reference stays valid for the lifetime of the MapView; a later /// call that reassembles the scene replaces its contents. Geometry /// for a visible uncached layer is read once; visibility changes reuse - /// its cache. Reassembly copies cached geometry into the map snapshot. + /// its cache. Reassembly shares cached geometry with the map snapshot + /// instead of copying it, so a held LayerRenderScene::scene stays + /// valid after the layer is invalidated or removed. /// Failed layers retain their diagnostics until explicitly invalidated. /// \throws std::bad_alloc when memory runs out. [[nodiscard]] const rendering::MapRenderScene& Scene(); diff --git a/src/MapWinGIS.Core/include/mapwingis/rendering/MapRenderScene.h b/src/MapWinGIS.Core/include/mapwingis/rendering/MapRenderScene.h index ddb2dbe..21cb9a2 100644 --- a/src/MapWinGIS.Core/include/mapwingis/rendering/MapRenderScene.h +++ b/src/MapWinGIS.Core/include/mapwingis/rendering/MapRenderScene.h @@ -4,13 +4,15 @@ * @file MapRenderScene.h * @brief Declares backend-neutral render data for all layers of a map. * - * A map render scene is an owned snapshot of the drawable geometry of a Map, - * in drawing order. It holds no references to the map, its layers, or their - * datasets, and it holds no view state: renderers draw it through a separate - * Viewport, so a view change does not need a new scene. + * A map render scene is a snapshot of the drawable geometry of a Map, in + * drawing order. Layer geometry is immutable and shared through + * reference-counted pointers. The scene holds no references to the map, its + * layers, or their datasets, and it holds no view state: renderers draw it + * through a separate Viewport, so a view change does not need a new scene. */ #pragma once +#include #include #include @@ -20,13 +22,16 @@ namespace mwg::rendering { - /// Owned geometry of one map layer. + /// Geometry of one map layer. struct LayerRenderScene { /// Identity of the map layer the geometry was copied from. LayerId layerId; - /// Polygon geometry in map coordinates; never empty in a MapRenderScene. - VectorRenderScene scene; + /// Immutable polygon geometry in map coordinates; never null or empty + /// in a MapRenderScene. Shared, not copied, between a MapView's layer + /// cache and the scenes it assembles; replace the pointer rather than + /// modifying the geometry. + std::shared_ptr scene; }; /// Why CreateMapRenderScene left a map layer out of the scene. diff --git a/src/MapWinGIS.Core/include/mapwingis/rendering/VectorRenderScene.h b/src/MapWinGIS.Core/include/mapwingis/rendering/VectorRenderScene.h index 1425acf..cb8653b 100644 --- a/src/MapWinGIS.Core/include/mapwingis/rendering/VectorRenderScene.h +++ b/src/MapWinGIS.Core/include/mapwingis/rendering/VectorRenderScene.h @@ -133,6 +133,10 @@ namespace mwg Extent extent; /// Feature count of the layer used to create this scene. std::int64_t sourceFeatureCount = 0; + /// Non-empty geometry parts that were not rendered: non-polygonal + /// geometries or collection members, and polygons without an + /// exterior ring of at least three points. + std::int64_t skippedGeometryCount = 0; PolygonBuffer polygons; /// Triangulated fill meshes prepared once when the scene is /// created, aligned with polygons: fillMeshes[i] belongs to @@ -145,8 +149,12 @@ namespace mwg /// Copies polygon geometry from a layer into backend-neutral scene data. /// - /// Supports Polygon and MultiPolygon layers. Empty geometries are - /// skipped. The returned coordinates remain in the layer's coordinate + /// Supports Polygon, MultiPolygon, and curved polygon layers. Empty + /// geometries are skipped. Polygonal members of geometry collections + /// are rendered; other geometries, and polygons whose exterior ring + /// has fewer than three points, are skipped and counted in + /// skippedGeometryCount. Interior rings with fewer than three points + /// are dropped. The returned coordinates remain in the layer's coordinate /// system; this function does not transform projections. Not /// thread-safe, consistent with the input layer's contract. /// \throws CoreError when the layer is not polygonal or contains no diff --git a/src/MapWinGIS.Core/include/mapwingis/vector/VectorDataset.h b/src/MapWinGIS.Core/include/mapwingis/vector/VectorDataset.h index e8785c3..ec45220 100644 --- a/src/MapWinGIS.Core/include/mapwingis/vector/VectorDataset.h +++ b/src/MapWinGIS.Core/include/mapwingis/vector/VectorDataset.h @@ -144,7 +144,10 @@ namespace mwg [[nodiscard]] static std::unique_ptr Open(const std::filesystem::path& path, OpenMode mode = OpenMode::ReadOnly); - /// Returns nullptr instead of throwing. + /// Opens a data source, returning nullptr when no driver can open it or + /// update access is unavailable. Only that open probe is non-throwing. + /// \throws InvalidArgument when the path cannot be converted to UTF-8. + /// \throws CoreError when GDAL initialization fails. [[nodiscard]] static std::unique_ptr TryOpen(const std::filesystem::path& path, OpenMode mode = OpenMode::ReadOnly); diff --git a/src/MapWinGIS.Core/src/gdal/GdalAlgorithmRunner.cpp b/src/MapWinGIS.Core/src/gdal/GdalAlgorithmRunner.cpp index 6ac17f5..b55629a 100644 --- a/src/MapWinGIS.Core/src/gdal/GdalAlgorithmRunner.cpp +++ b/src/MapWinGIS.Core/src/gdal/GdalAlgorithmRunner.cpp @@ -254,10 +254,12 @@ namespace mwg GdalAlgorithmRunner::~GdalAlgorithmRunner() { - // Destruction only releases the runner's own dataset references - // (through GdalDatasetDeleter) and the GDALAlgorithm, which is - // refcount-only work. It must not wait for operations holding the - // shared GDAL execution lock. + // Destruction releases the runner's own dataset references (through + // GdalDatasetDeleter) and the GDALAlgorithm. Either may close a dataset + // when it holds the last reference; that close runs without the shared + // GDAL execution lock so destruction never waits for, or deadlocks with, + // an operation holding it. Callers must not destroy a runner while + // another thread still uses a dataset only this runner references. _impl.reset(); } diff --git a/src/MapWinGIS.Core/src/map/MapView.cpp b/src/MapWinGIS.Core/src/map/MapView.cpp index 10ae8ad..f2a8484 100644 --- a/src/MapWinGIS.Core/src/map/MapView.cpp +++ b/src/MapWinGIS.Core/src/map/MapView.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -113,8 +114,23 @@ namespace mwg LayerId MapView::AddLayer(std::shared_ptr dataset, rendering::VectorRenderScene scene, const int layerIndex) { + return AddLayer( + std::move(dataset), + std::make_shared(std::move(scene)), + layerIndex); + } + + LayerId MapView::AddLayer(std::shared_ptr dataset, + std::shared_ptr scene, + const int layerIndex) + { + if (scene == nullptr) + { + throw InvalidArgument("Layer scene must not be null"); + } + (void)Scene(); - const bool empty = scene.polygons.empty(); + const bool empty = scene->polygons.empty(); if (empty) { _impl->_scene.skippedLayers.reserve(_impl->_scene.skippedLayers.size() + 1); diff --git a/src/MapWinGIS.Core/src/rendering/MapRenderScene.cpp b/src/MapWinGIS.Core/src/rendering/MapRenderScene.cpp index d100dda..799ef70 100644 --- a/src/MapWinGIS.Core/src/rendering/MapRenderScene.cpp +++ b/src/MapWinGIS.Core/src/rendering/MapRenderScene.cpp @@ -7,6 +7,7 @@ #include "mapwingis/rendering/MapRenderScene.h" #include +#include #include #include @@ -39,7 +40,7 @@ namespace mwg::rendering { return SkippedLayer{layer.Id(), LayerSkipReason::NoGeometry, {}}; } - return LayerRenderScene{layer.Id(), std::move(scene)}; + return LayerRenderScene{layer.Id(), std::make_shared(std::move(scene))}; } MapRenderScene CreateMapRenderScene(const Map& map) diff --git a/src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp b/src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp index 84a0af6..1eea1dd 100644 --- a/src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp +++ b/src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp @@ -11,12 +11,14 @@ #include "mapwingis/rendering/PolygonTriangulation.h" #include +#include #include +#include #include -#include #include #include #include +#include #include #include @@ -89,6 +91,26 @@ namespace mwg::rendering return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y); } + // Exact coordinate equality: triangulation reuses input vertices bit for bit, and + // std::hash hashes 0.0 and -0.0 alike, consistent with operator==. + struct PointHash + { + [[nodiscard]] std::size_t operator()(const Point& point) const noexcept + { + const std::size_t x = std::hash{}(point.x); + const std::size_t y = std::hash{}(point.y); + return x ^ (y + 0x9e3779b97f4a7c15ULL + (x << 6) + (x >> 2)); + } + }; + + struct PointEqual + { + [[nodiscard]] bool operator()(const Point& left, const Point& right) const noexcept + { + return left.x == right.x && left.y == right.y; + } + }; + /// Deduplicates vertices and assembles consistently wound triangles. class MeshBuilder { @@ -115,8 +137,7 @@ namespace mwg::rendering private: [[nodiscard]] std::uint32_t AddVertex(const Point& point) { - const auto key = std::make_pair(point.x, point.y); - const auto found = _vertexLookup.find(key); + const auto found = _vertexLookup.find(point); if (found != _vertexLookup.end()) { return found->second; @@ -130,12 +151,12 @@ namespace mwg::rendering } const auto index = static_cast(_mesh.vertices.size()); _mesh.vertices.push_back(point); - _vertexLookup.emplace(key, index); + _vertexLookup.emplace(point, index); return index; } TriangleMesh _mesh; - std::map, std::uint32_t> _vertexLookup; + std::unordered_map _vertexLookup; }; void AppendTriangle(const OGRPolygon& triangle, MeshBuilder& builder) diff --git a/src/MapWinGIS.Core/src/rendering/VectorRenderScene.cpp b/src/MapWinGIS.Core/src/rendering/VectorRenderScene.cpp index c5cd958..7cd1511 100644 --- a/src/MapWinGIS.Core/src/rendering/VectorRenderScene.cpp +++ b/src/MapWinGIS.Core/src/rendering/VectorRenderScene.cpp @@ -6,6 +6,8 @@ * * Reads vector geometries sequentially and copies supported polygon * coordinates into owned scene data before releasing each feature. + * Unsupported or degenerate parts are skipped and counted rather than + * failing the layer. */ #include "mapwingis/rendering/VectorRenderScene.h" @@ -124,6 +126,10 @@ namespace mwg::rendering void AppendGeometry(const OGRGeometry& geometry) { + if (geometry.IsEmpty()) + { + return; + } switch (wkbFlatten(geometry.getGeometryType())) { case wkbPolygon: @@ -156,38 +162,67 @@ namespace mwg::rendering return; } + case wkbGeometryCollection: + { + const auto& collection = static_cast(geometry); + for (int index = 0; index < collection.getNumGeometries(); ++index) + { + if (const OGRGeometry* member = collection.getGeometryRef(index)) + { + AppendGeometry(*member); + } + } + return; + } + default: - throw CoreError("Vector rendering supports Polygon and MultiPolygon geometries only"); + // A polygon layer can still contain stray points or lines; drop them + // rather than failing the whole layer. + ++_scene.skippedGeometryCount; + return; } } private: - void AppendRing(const OGRLinearRing* source) + [[nodiscard]] static bool IsUsableRing(const OGRLinearRing* ring) { - if (source == nullptr || source->getNumPoints() < 3) - { - return; - } - for (int index = 0; index < source->getNumPoints(); ++index) + return ring != nullptr && ring->getNumPoints() >= 3; + } + + void AppendRing(const OGRLinearRing& source) + { + for (int index = 0; index < source.getNumPoints(); ++index) { - _coordinates.push_back({source->getX(index), source->getY(index)}); + _coordinates.push_back({source.getX(index), source.getY(index)}); } _ringEnds.push_back(_coordinates.size()); } void AppendPolygon(const OGRPolygon& source) { + if (source.IsEmpty()) + { + return; + } + // Without a usable exterior ring, a hole would otherwise become ring 0 and + // be filled as if it were the polygon's exterior. + const OGRLinearRing* exterior = source.getExteriorRing(); + if (!IsUsableRing(exterior)) + { + ++_scene.skippedGeometryCount; + return; + } _coordinates.clear(); _ringEnds.clear(); - AppendRing(source.getExteriorRing()); + AppendRing(*exterior); for (int index = 0; index < source.getNumInteriorRings(); ++index) { - AppendRing(source.getInteriorRing(index)); - } - if (!_ringEnds.empty()) - { - _scene.polygons.AppendPolygon(_coordinates, _ringEnds); + if (const OGRLinearRing* ring = source.getInteriorRing(index); IsUsableRing(ring)) + { + AppendRing(*ring); + } } + _scene.polygons.AppendPolygon(_coordinates, _ringEnds); } VectorRenderScene& _scene; diff --git a/src/MapWinGIS.Core/src/vector/VectorDataset.cpp b/src/MapWinGIS.Core/src/vector/VectorDataset.cpp index 2c2e943..92efccc 100644 --- a/src/MapWinGIS.Core/src/vector/VectorDataset.cpp +++ b/src/MapWinGIS.Core/src/vector/VectorDataset.cpp @@ -212,6 +212,11 @@ namespace mwg { GdalEnvironment::ClearLastError(); const OGRErr result = _layer->SetFeature(feature); + const GIntBig featureId = feature->GetFID(); + // The driver may coerce written values (for example truncate a DBF string), so the + // in-memory feature no longer reflects storage even when the write succeeds. + _cachedFeature.reset(); + _cachedIndex = -1; if (geometryChanged) { _extent.reset(); @@ -219,9 +224,6 @@ namespace mwg } if (result != OGRERR_NONE) { - const GIntBig featureId = feature->GetFID(); - _cachedFeature.reset(); - _cachedIndex = -1; _featureIds.clear(); _featureIdsValid = false; _featureCount.reset(); @@ -250,6 +252,8 @@ namespace mwg if (layerName == nullptr || layerName[0] == '\0') throw CoreError("Cannot recompute stored extent for an unnamed layer"); + // The Shapefile and GPKG drivers treat the remainder of this statement as the + // literal layer name, so it must not be quoted or escaped. const std::string sql = "RECOMPUTE EXTENT ON " + std::string(layerName); const auto releaseResult = [this](OGRLayer* result) { diff --git a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp index 14d6664..6c68f18 100644 --- a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp @@ -575,6 +575,19 @@ namespace return E_FAIL; } + // Simulates a sink that shows UI from a progress event: the nested pump + // consumes dispatch messages posted while the control is still delivering. + HRESULT PumpNestedMessages(void*, LONGLONG) + { + MSG message{}; + while (::PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) + { + ::TranslateMessage(&message); + ::DispatchMessageW(&message); + } + return S_OK; + } + HRESULT FailCompletion(void*, LONGLONG) { return E_FAIL; @@ -1146,6 +1159,18 @@ TEST_F(ActiveXMapTest, InvalidArgumentsSetComErrorInfoForEachAutomationInterface ASSERT_EQ(_control.As(¤t), S_OK); EXPECT_EQ(current->ZoomToLayer(0), E_INVALIDARG); expectDescription(L"Layer ID"); + + // Rendering properties are declared on IMapWinGISControl2, so their error + // information must name that interface for clients that only know it. + ComPtr rendering; + ASSERT_EQ(_control.As(&rendering), S_OK); + EXPECT_EQ(rendering->put_RenderingBackendPreference(ATL::CComBSTR(L"Vulkan")), E_INVALIDARG); + ComPtr renderingError; + ASSERT_EQ(::GetErrorInfo(0, &renderingError), S_OK); + ASSERT_NE(renderingError, nullptr); + GUID source{}; + ASSERT_EQ(renderingError->GetGUID(&source), S_OK); + EXPECT_TRUE(IsEqualGUID(source, __uuidof(IMapWinGISControl2))); } TEST_F(ActiveXMapTest, LoadsStackAndClearReleasesTheDatasets) @@ -1326,6 +1351,82 @@ TEST_F(ActiveXMapTest, LoadsVectorDatasetAsynchronouslyAndCommitsBeforeCompletio EXPECT_EQ(featureCount, 2); } +TEST_F(ActiveXMapTest, ClosingTheControlFromTheLoadCommitViewChangeIsSafe) +{ + class ClosingViewChangeSink final : + public Microsoft::WRL::RuntimeClass, IAdviseSink> + { + public: + explicit ClosingViewChangeSink(IOleObject* object) noexcept : _object(object) {} + void STDMETHODCALLTYPE OnDataChange(FORMATETC*, STGMEDIUM*) override {} + void STDMETHODCALLTYPE OnViewChange(DWORD, LONG) override + { + if (closeResult == S_FALSE) + { + closeResult = _object->Close(OLECLOSE_NOSAVE); + } + } + void STDMETHODCALLTYPE OnRename(IMoniker*) override {} + void STDMETHODCALLTYPE OnSave() override {} + void STDMETHODCALLTYPE OnClose() override {} + HRESULT closeResult = S_FALSE; + + private: + IOleObject* _object; + }; + + ComPtr control; + ASSERT_EQ(_control.As(&control), S_OK); + ComPtr oleObject; + ASSERT_EQ(_control.As(&oleObject), S_OK); + const auto sink = Microsoft::WRL::Make(oleObject.Get()); + ASSERT_NE(sink, nullptr); + ASSERT_EQ(_viewObject->SetAdvise(DVASPECT_CONTENT, 0, sink.Get()), S_OK); + + const auto path = mwg::test::MakeRectanglesDataset( + _directory.Path(), + "async-close-on-commit.gpkg", + std::vector{{0, 0, 2, 2}}); + LONGLONG operationId = 0; + ASSERT_EQ(control->BeginLoadVectorDataset( + ATL::CComBSTR(path.c_str()), + &operationId), S_OK); + + // The commit's FireViewChange re-enters Close, which discards every load + // state; the commit must finish on its own reference to the state. + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (sink->closeResult == S_FALSE && std::chrono::steady_clock::now() < deadline) + { + MSG message{}; + while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE) != FALSE) + { + TranslateMessage(&message); + DispatchMessageW(&message); + } + Sleep(1); + } + ASSERT_EQ(sink->closeResult, S_OK); + ASSERT_EQ(_viewObject->SetAdvise(DVASPECT_CONTENT, 0, nullptr), S_OK); + + VARIANT_BOOL succeeded = VARIANT_TRUE; + VARIANT_BOOL cancelled = VARIANT_TRUE; + LONGLONG layerId = -1; + BSTR summary = nullptr; + BSTR diagnostics = nullptr; + EXPECT_EQ(control->EndLoadVectorDataset( + operationId, + &succeeded, + &cancelled, + &layerId, + &summary, + &diagnostics), E_INVALIDARG); + EXPECT_EQ(summary, nullptr); + EXPECT_EQ(diagnostics, nullptr); + LONG layerCount = 0; + ASSERT_EQ(control->get_LayerCount(&layerCount), S_OK); + EXPECT_EQ(layerCount, 1); +} + TEST_F(ActiveXMapTest, CancellingVectorDatasetLoadLeavesTheMapUnchanged) { ComPtr control; @@ -1431,7 +1532,10 @@ TEST_F(ActiveXMapTest, DestroyingControlDuringVectorLoadDoesNotAccessTheControlF reinterpret_cast(GetProcAddress( _module->Get(), "MapWinGISControlSetVectorPreparationHookForTesting")); - ASSERT_NE(setPreparationHook, nullptr); + if (setPreparationHook == nullptr) + { + GTEST_SKIP() << "MapWinGIS.ocx was built without MWG_ENABLE_ACTIVEX_TEST_HOOKS."; + } ScopedVectorPreparationHook hookReset(setPreparationHook); setPreparationHook(&VectorPreparationBarrier::Notify, &barrier); @@ -1987,6 +2091,37 @@ TEST_F(ActiveXMapTest, AlternateDrawBoundsDoNotChangeTheLiveSizeUsedForFitting) EXPECT_EQ(GetPixel(resized.Get(), moved->x, moved->y), RGB(61, 122, 169)); } +TEST_F(ActiveXMapTest, AlternateSizeDrawsScaleTheLiveVisibleExtent) +{ + ASSERT_EQ(Resize(120, 100), S_OK); + ASSERT_EQ(LoadRectangles({{0, 0, 10, 5}}), S_OK); + mwg::Viewport live(120, 100); + ASSERT_TRUE(live.FitExtent({0, 0, 10, 5}, 12.0)); + mwg::Viewport printed(240, 200); + ASSERT_TRUE(printed.FitExtent(live.VisibleExtent())); + + BitmapSurface surface(240, 200); + ASSERT_TRUE(surface.IsValid()); + ASSERT_EQ(Draw(surface.Get(), 240, 200), S_OK); + + // At the screen resolution the rectangle would cover only the middle of + // a double-size target, leaving its right part unpainted. + for (const mwg::MapPoint point : {mwg::MapPoint{0.5, 2.5}, mwg::MapPoint{9.5, 2.5}}) + { + const auto pixel = mwg::ToPixel(*printed.MapToScreen(point)); + ASSERT_TRUE(pixel.has_value()); + EXPECT_EQ(GetPixel(surface.Get(), pixel->x, pixel->y), RGB(61, 122, 169)) + << point.x << ", " << point.y; + } + const auto outside = mwg::ToPixel(*printed.MapToScreen({-0.5, 2.5})); + ASSERT_TRUE(outside.has_value()); + EXPECT_EQ(GetPixel(surface.Get(), outside->x, outside->y), GetSysColor(COLOR_WINDOW)); + + // The live view keeps its size and scale. + using Access = mwg::activex::testing::MapWinGISControlTestAccess; + EXPECT_DOUBLE_EQ(Access::Resolution(Access::Control(_control.Get())), *live.Resolution()); +} + TEST_F(ActiveXMapTest, ScaledDrawsKeepScreenBuffersAtTheClientSize) { using Access = mwg::activex::testing::MapWinGISControlTestAccess; @@ -2535,6 +2670,21 @@ TEST(ActiveXHosting, ResizesRepaintsAndRecreatesControl) warningResult.warnings.front().find(L"COM test warning"), std::wstring::npos); + eventSink->SetProgressCallback(&PumpNestedMessages, nullptr); + LONGLONG nestedPumpOperationId = 0; + ASSERT_TRUE(SUCCEEDED(StartGdalOperation( + gdalControl, + L"mwg-test-activex progress", + {}, + &nestedPumpOperationId))); + ComGdalResult nestedPumpResult; + ASSERT_TRUE(SUCCEEDED(finishOperation( + nestedPumpOperationId, + nestedPumpResult))); + EXPECT_EQ(nestedPumpResult.succeeded, VARIANT_TRUE); + EXPECT_EQ(nestedPumpResult.callbackErrorCode, 0); + eventSink->SetProgressCallback(nullptr, nullptr); + LONGLONG failureOperationId = 0; ASSERT_TRUE(SUCCEEDED(StartGdalOperation( gdalControl, diff --git a/tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp b/tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp index 4e444e1..979217a 100644 --- a/tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/RenderingBaselineTests.cpp @@ -400,7 +400,7 @@ TEST_F(RenderingBaseline, MeasuresCoreSceneAndBackendCosts) const std::optional memoryAfterScene = PrivateMiB(memoryError); ASSERT_TRUE(memoryAfterScene.has_value()) << "GetProcessMemoryInfo failed: " << memoryError; ASSERT_EQ(scene.layers.size(), 1U); - ASSERT_EQ(scene.layers.front().scene.polygons.size(), static_cast(featureCount)); + ASSERT_EQ(scene.layers.front().scene->polygons.size(), static_cast(featureCount)); DibSurface surface(kTargetWidth, kTargetHeight); ASSERT_TRUE(surface.IsValid()); @@ -489,9 +489,9 @@ TEST_F(RenderingBaseline, MeasuresComplexPolygonCosts) std::size_t meshIndexCount = 0; for (const rendering::LayerRenderScene& layer : scene.layers) { - ASSERT_EQ(layer.scene.fillMeshes.size(), layer.scene.polygons.size()); - polygonCount += layer.scene.polygons.size(); - for (const std::optional& mesh : layer.scene.fillMeshes) + ASSERT_EQ(layer.scene->fillMeshes.size(), layer.scene->polygons.size()); + polygonCount += layer.scene->polygons.size(); + for (const std::optional& mesh : layer.scene->fillMeshes) { ASSERT_TRUE(mesh.has_value()) << "Every complex baseline polygon must triangulate"; diff --git a/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp b/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp index 7b3cec1..90ef80a 100644 --- a/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/VectorLayerRendererTests.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -104,6 +105,7 @@ namespace return { rectangle, 1, + 0, {{{{rectangle.xMin, rectangle.yMin}, {rectangle.xMax, rectangle.yMin}, {rectangle.xMax, rectangle.yMax}, @@ -132,6 +134,23 @@ namespace } } + /// Wraps a layer scene in the shared immutable form held by map scenes. + [[nodiscard]] std::shared_ptr Share( + mwg::rendering::VectorRenderScene scene) + { + return std::make_shared(std::move(scene)); + } + + /// Gives a test fixture a private, editable copy of a layer's geometry; + /// map scenes otherwise share it immutably. + [[nodiscard]] mwg::rendering::VectorRenderScene& Edit(mwg::rendering::LayerRenderScene& layer) + { + auto copy = std::make_shared(*layer.scene); + mwg::rendering::VectorRenderScene& editable = *copy; + layer.scene = std::move(copy); + return editable; + } + /// A map scene with these layers, bottom first, with identities 1, 2, ... /// Every polygon gets its Core triangulation mesh. [[nodiscard]] mwg::rendering::MapRenderScene MakeMapScene( @@ -142,7 +161,7 @@ namespace for (mwg::rendering::VectorRenderScene& layer : layers) { TriangulateScene(layer); - scene.layers.push_back({mwg::LayerId{++id}, std::move(layer)}); + scene.layers.push_back({mwg::LayerId{++id}, Share(std::move(layer))}); } return scene; } @@ -155,7 +174,7 @@ namespace /// Rebuilds the single-polygon fixture with one additional interior ring. void AddInteriorRing(mwg::rendering::MapRenderScene& scene, mwg::rendering::Ring ring) { - auto& buffer = scene.layers.front().scene.polygons; + auto& buffer = Edit(scene.layers.front()).polygons; const auto view = buffer.front(); mwg::rendering::Polygon polygon; for (std::size_t index = 0; index < view.size(); ++index) @@ -288,9 +307,9 @@ TEST(VectorLayerRenderer, OpenGlRendersConcavePolygonWithDuplicateVertex) // Concave corner with a consecutive duplicate vertex; Core // triangulation tolerates the duplicate and produces the fill mesh. mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); - scene.layers.front().scene.polygons = {{{ + Edit(scene.layers.front()).polygons = {{{ {0.0, 0.0}, {10.0, 0.0}, {10.0, 10.0}, {5.0, 5.0}, {5.0, 5.0}, {0.0, 10.0}, {0.0, 0.0}}}}; - TriangulateScene(scene.layers.front().scene); + TriangulateScene(Edit(scene.layers.front())); const mwg::Viewport viewport = FitViewport(bounds); mwg::activex::OpenGlVectorLayerRenderer renderer; @@ -315,7 +334,7 @@ TEST(VectorLayerRenderer, OpenGlRejectsPolygonWithoutFillMesh) // rings remain; OpenGL must decline the frame instead of approximating // the fill so the coordinator falls back to GDI. mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); - scene.layers.front().scene.fillMeshes.front().reset(); + Edit(scene.layers.front()).fillMeshes.front().reset(); mwg::activex::OpenGlVectorLayerRenderer renderer; EXPECT_EQ(renderer.Draw(surface.Get(), bounds, scene, FitViewport(bounds)), S_FALSE); @@ -334,6 +353,7 @@ TEST(VectorLayerRenderer, OpenGlRejectsSelfIntersectingRing) const mwg::rendering::MapRenderScene scene = MakeMapScene({{ mwg::Extent{-3.0, -3.0, 3.0, 3.0}, 0, + 0, {{{{0.0, 3.0}, {2.0, -3.0}, {-3.0, 1.0}, {3.0, 1.0}, {-2.0, -3.0}, {0.0, 3.0}}}}}}); mwg::activex::OpenGlVectorLayerRenderer renderer; @@ -353,7 +373,7 @@ TEST(VectorLayerRenderer, OpenGlRejectsTheFrameWhenAnyLayerHasNoFillMesh) const RECT bounds{0, 0, 120, 100}; mwg::rendering::MapRenderScene scene = MakeTwoLayerScene(); - scene.layers.back().scene.fillMeshes.front().reset(); + Edit(scene.layers.back()).fillMeshes.front().reset(); mwg::activex::OpenGlVectorLayerRenderer renderer; EXPECT_EQ( @@ -373,9 +393,9 @@ TEST(VectorLayerRenderer, FailsWithoutDrawingNonFiniteCoordinates) const RECT bounds{0, 0, 120, 100}; mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); - scene.layers.front().scene.polygons.AppendPolygon( + Edit(scene.layers.front()).polygons.AppendPolygon( {{{1.0, 1.0}, {std::numeric_limits::quiet_NaN(), 5.0}, {9.0, 9.0}, {1.0, 1.0}}}); - TriangulateScene(scene.layers.front().scene); + TriangulateScene(Edit(scene.layers.front())); mwg::activex::VectorLayerRenderer renderer; EXPECT_EQ(renderer.Draw(surface.Get(), bounds, scene, FitViewport(bounds)), E_INVALIDARG); @@ -393,9 +413,9 @@ TEST(VectorLayerRenderer, SkipsOnlyTheLayerThatCannotBeDrawn) ASSERT_NE(FillRect(surface.Get(), &bounds, GetSysColorBrush(COLOR_WINDOW)), 0); mwg::rendering::MapRenderScene scene = MakeTwoLayerScene(); - scene.layers.front().scene.polygons.AppendPolygon( + Edit(scene.layers.front()).polygons.AppendPolygon( {{{0.0, 0.0}, {std::numeric_limits::infinity(), 1.0}, {1.0, 1.0}, {0.0, 0.0}}}); - TriangulateScene(scene.layers.front().scene); + TriangulateScene(Edit(scene.layers.front())); const mwg::Viewport viewport = FitViewport(bounds, kTwoLayerExtent); mwg::activex::VectorLayerRenderer renderer; @@ -411,6 +431,27 @@ TEST(VectorLayerRenderer, SkipsOnlyTheLayerThatCannotBeDrawn) EXPECT_EQ(MapPixel(surface.Get(), viewport, 9.0, 4.0), kFill); } +TEST(VectorLayerRenderer, ReportsALayerWithoutASceneAndDrawsTheOthers) +{ + BitmapSurface surface(200, 120); + ASSERT_TRUE(surface.IsValid()); + const RECT bounds{0, 0, 200, 120}; + ASSERT_NE(FillRect(surface.Get(), &bounds, GetSysColorBrush(COLOR_WINDOW)), 0); + + mwg::rendering::MapRenderScene scene = MakeTwoLayerScene(); + scene.layers.front().scene.reset(); + const mwg::Viewport viewport = FitViewport(bounds, kTwoLayerExtent); + + mwg::activex::VectorLayerRenderer renderer; + ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, viewport), S_OK); + + EXPECT_EQ(renderer.GetActiveBackend(), mwg::activex::VectorRenderBackendKind::Gdi); + ASSERT_EQ(renderer.GetFailedLayers().size(), 1U); + EXPECT_EQ(renderer.GetFailedLayers().front(), mwg::LayerId{1}); + EXPECT_EQ(MapPixel(surface.Get(), viewport, 1.0, 1.0), GetSysColor(COLOR_WINDOW)); + EXPECT_EQ(MapPixel(surface.Get(), viewport, 9.0, 4.0), kFill); +} + TEST(VectorLayerRenderer, OpenGlRendersPolygonWithInteriorRing) { BitmapSurface surface(120, 100); @@ -421,7 +462,7 @@ TEST(VectorLayerRenderer, OpenGlRendersPolygonWithInteriorRing) mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); AddInteriorRing(scene, {{3.0, 3.0}, {3.0, 7.0}, {7.0, 7.0}, {7.0, 3.0}, {3.0, 3.0}}); - TriangulateScene(scene.layers.front().scene); + TriangulateScene(Edit(scene.layers.front())); mwg::activex::VectorLayerRenderer renderer; ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, FitViewport(bounds)), S_OK); @@ -440,7 +481,7 @@ TEST(VectorLayerRenderer, FallsBackToGdiWhenAPolygonHasNoFillMesh) const RECT bounds{0, 0, 120, 100}; mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); - scene.layers.front().scene.fillMeshes.front().reset(); + Edit(scene.layers.front()).fillMeshes.front().reset(); mwg::activex::VectorLayerRenderer renderer; ASSERT_EQ(renderer.Draw(surface.Get(), bounds, scene, FitViewport(bounds)), S_OK); @@ -470,7 +511,7 @@ TEST(VectorLayerRenderer, GdiFallbackRendersConcaveHoledPolygonFromRings) }}; layer.fillMeshes.push_back(std::nullopt); mwg::rendering::MapRenderScene scene; - scene.layers.push_back({mwg::LayerId{1}, std::move(layer)}); + scene.layers.push_back({mwg::LayerId{1}, Share(std::move(layer))}); const mwg::Viewport viewport = FitViewport(bounds); mwg::activex::VectorLayerRenderer renderer; @@ -509,20 +550,20 @@ TEST(VectorLayerRenderer, OpenGlSupportRequiresAMeshForEveryPolygon) // No meshes at all. mwg::rendering::MapRenderScene withoutMeshes = MakeConvexPolygonScene(); - withoutMeshes.layers.front().scene.fillMeshes.clear(); + Edit(withoutMeshes.layers.front()).fillMeshes.clear(); EXPECT_FALSE( mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::IsSceneSupported( withoutMeshes)); // A triangulation failure for one polygon rejects the whole frame. mwg::rendering::MapRenderScene nullMesh = MakeConvexPolygonScene(); - nullMesh.layers.front().scene.fillMeshes.front().reset(); + Edit(nullMesh.layers.front()).fillMeshes.front().reset(); EXPECT_FALSE( mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::IsSceneSupported(nullMesh)); // Non-finite coordinates stay unsupported regardless of the mesh. mwg::rendering::MapRenderScene nonFinite = MakeConvexPolygonScene(); - nonFinite.layers.front().scene.polygons.Coordinates().front().x = + Edit(nonFinite.layers.front()).polygons.Coordinates().front().x = std::numeric_limits::infinity(); EXPECT_FALSE( mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::IsSceneSupported(nonFinite)); @@ -549,7 +590,7 @@ TEST(VectorLayerRenderer, OpenGlSupportsConcaveMultipartAndHoledScenes) // A malformed mesh reference also rejects the scene. mwg::rendering::MapRenderScene broken = scene; - broken.layers.front().scene.fillMeshes.front()->indices.resize(4); + Edit(broken.layers.front()).fillMeshes.front()->indices.resize(4); EXPECT_FALSE( mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::IsSceneSupported(broken)); } @@ -562,9 +603,9 @@ TEST(VectorLayerRenderer, OpenGlRendersLShapedPolygon) const RECT bounds{0, 0, 120, 100}; mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); - scene.layers.front().scene.polygons = {{{ + Edit(scene.layers.front()).polygons = {{{ {0.0, 0.0}, {10.0, 0.0}, {10.0, 4.0}, {4.0, 4.0}, {4.0, 10.0}, {0.0, 10.0}, {0.0, 0.0}}}}; - TriangulateScene(scene.layers.front().scene); + TriangulateScene(Edit(scene.layers.front())); const mwg::Viewport viewport = FitViewport(bounds); mwg::activex::OpenGlVectorLayerRenderer renderer; @@ -590,7 +631,7 @@ TEST(VectorLayerRenderer, OpenGlRendersPolygonWithMultipleInteriorRings) mwg::rendering::MapRenderScene scene = MakeConvexPolygonScene(); AddInteriorRing(scene, {{2.0, 2.0}, {2.0, 4.0}, {4.0, 4.0}, {4.0, 2.0}, {2.0, 2.0}}); AddInteriorRing(scene, {{6.0, 6.0}, {6.0, 8.0}, {8.0, 8.0}, {8.0, 6.0}, {6.0, 6.0}}); - TriangulateScene(scene.layers.front().scene); + TriangulateScene(Edit(scene.layers.front())); const mwg::Viewport viewport = FitViewport(bounds); mwg::activex::OpenGlVectorLayerRenderer renderer; @@ -745,7 +786,7 @@ TEST(VectorLayerRenderer, FlatSceneCopyPreservesPixelsAfterTheOriginalIsReleased auto source = MakeMapScene({ MakeRectangleLayer({1, 1, 9, 9}), MakeRectangleLayer({7, 7, 10, 10})}); AddInteriorRing(source, {{3, 3}, {3, 6}, {6, 6}, {6, 3}, {3, 3}}); - TriangulateScene(source.layers.front().scene); + TriangulateScene(Edit(source.layers.front())); ASSERT_TRUE( mwg::activex::testing::OpenGlVectorLayerRendererTestAccess::IsSceneSupported(source)); ASSERT_NE(FillRect(originalGdi.Get(), &bounds, GetSysColorBrush(COLOR_WINDOW)), 0); @@ -1018,7 +1059,7 @@ TEST(VectorLayerRenderer, GdiSkipsLayerTraversalWhenTheHostClipDoesNotIntersectB const RECT bounds{0, 0, 120, 100}; const mwg::Viewport viewport = FitViewport(bounds); auto scene = MakeConvexPolygonScene(); - scene.layers.front().scene.polygons.Coordinates().front().x = + Edit(scene.layers.front()).polygons.Coordinates().front().x = std::numeric_limits::infinity(); const int saved = SaveDC(surface.Get()); ASSERT_NE(saved, 0); diff --git a/tests/MapWinGIS.ActiveX.Tests/Verify-ActiveXActivation.ps1 b/tests/MapWinGIS.ActiveX.Tests/Verify-ActiveXActivation.ps1 index 6374cd6..273964e 100644 --- a/tests/MapWinGIS.ActiveX.Tests/Verify-ActiveXActivation.ps1 +++ b/tests/MapWinGIS.ActiveX.Tests/Verify-ActiveXActivation.ps1 @@ -35,11 +35,34 @@ $registrationTool = if ($Platform -eq 'x64') { Join-Path $env:SystemRoot 'SysWOW64\regsvr32.exe' } +$idlPath = [System.IO.Path]::GetFullPath( + (Join-Path $PSScriptRoot '..\..\src\MapWinGIS.ActiveX\MapWinGIS.ActiveX.idl')) +if (-not (Test-Path -LiteralPath $idlPath -PathType Leaf)) { + throw "The ActiveX interface definition was not found at '$idlPath'." +} + +# DllRegisterServer also writes the type library and its interfaces, and +# DllUnregisterServer removes them, so every key the control owns is protected. $registrationPaths = @( - 'Software\Classes\CLSID\{2F0AB6FC-F7C0-4E42-A002-A61F9C6F294F}' 'Software\Classes\MapWinGIS6.Control.6' 'Software\Classes\MapWinGIS6.Control' ) +$idlDeclarations = [regex]::Matches( + (Get-Content -LiteralPath $idlPath -Raw), + 'uuid\(([0-9A-Fa-f-]{36})\)[^\]]*\]\s*(library|interface|dispinterface|coclass)\b') +foreach ($declaration in $idlDeclarations) { + $guid = '{' + $declaration.Groups[1].Value.ToUpperInvariant() + '}' + $registrationPaths += switch ($declaration.Groups[2].Value) { + 'library' { "Software\Classes\TypeLib\$guid" } + 'coclass' { "Software\Classes\CLSID\$guid" } + default { "Software\Classes\Interface\$guid" } + } +} +if (-not ($registrationPaths -match '\\TypeLib\\') -or + -not ($registrationPaths -match '\\CLSID\\') -or + -not ($registrationPaths -match '\\Interface\\')) { + throw "Could not read the type library, class, and interface GUIDs from '$idlPath'." +} $testReport = Join-Path ([System.IO.Path]::GetTempPath()) ( "MapWinGIS.ActiveX.Tests.$([guid]::NewGuid().ToString('N')).xml") $existingRegistration = @() diff --git a/tests/MapWinGIS.Core.Tests/MapRenderSceneTests.cpp b/tests/MapWinGIS.Core.Tests/MapRenderSceneTests.cpp index 79e6959..ea1ab4b 100644 --- a/tests/MapWinGIS.Core.Tests/MapRenderSceneTests.cpp +++ b/tests/MapWinGIS.Core.Tests/MapRenderSceneTests.cpp @@ -164,9 +164,9 @@ TEST_F(MapRenderSceneTest, ContainsEveryVisibleLayerInDrawingOrder) EXPECT_EQ(scene.layers[0].layerId, bottom); EXPECT_EQ(scene.layers[1].layerId, middle); EXPECT_EQ(scene.layers[2].layerId, top); - EXPECT_EQ(scene.layers[0].scene.polygons.size(), 1U); - EXPECT_EQ(scene.layers[1].scene.polygons.size(), 2U); - EXPECT_EQ(scene.layers[1].scene.sourceFeatureCount, 2); + EXPECT_EQ(scene.layers[0].scene->polygons.size(), 1U); + EXPECT_EQ(scene.layers[1].scene->polygons.size(), 2U); + EXPECT_EQ(scene.layers[1].scene->sourceFeatureCount, 2); } TEST_F(MapRenderSceneTest, KeepsEachLayersOwnExtentAndCoordinates) @@ -177,10 +177,10 @@ TEST_F(MapRenderSceneTest, KeepsEachLayersOwnExtentAndCoordinates) const rendering::MapRenderScene scene = rendering::CreateMapRenderScene(_map); ASSERT_EQ(scene.layers.size(), 2U); - EXPECT_DOUBLE_EQ(scene.layers[0].scene.extent.xMax, 1.0); - EXPECT_DOUBLE_EQ(scene.layers[1].scene.extent.xMin, 100.0); - EXPECT_DOUBLE_EQ(scene.layers[1].scene.extent.yMax, 60.0); - for (const rendering::Point& point : scene.layers[1].scene.polygons.front().front()) + EXPECT_DOUBLE_EQ(scene.layers[0].scene->extent.xMax, 1.0); + EXPECT_DOUBLE_EQ(scene.layers[1].scene->extent.xMin, 100.0); + EXPECT_DOUBLE_EQ(scene.layers[1].scene->extent.yMax, 60.0); + for (const rendering::Point& point : scene.layers[1].scene->polygons.front().front()) { EXPECT_GE(point.x, 100.0); EXPECT_LE(point.x, 140.0); @@ -287,8 +287,8 @@ TEST_F(MapRenderSceneTest, IsolatesStandardExceptionsButPropagatesAllocationFail EXPECT_EQ(scene.skippedLayers[0].layerId, failed); EXPECT_EQ(scene.skippedLayers[0].reason, rendering::LayerSkipReason::Failed); EXPECT_EQ(scene.skippedLayers[0].message, "Simulated geometry read exception"); - const auto* polygons = scene.layers[0].scene.polygons.Coordinates().data(); - EXPECT_EQ(view.Scene().layers[0].scene.polygons.Coordinates().data(), polygons); + const auto* polygons = scene.layers[0].scene->polygons.Coordinates().data(); + EXPECT_EQ(view.Scene().layers[0].scene->polygons.Coordinates().data(), polygons); view.AddLayer(VectorDataset::Open("MWG_THROWING:allocation")); EXPECT_THROW((void)view.Scene(), std::bad_alloc); @@ -304,5 +304,5 @@ TEST_F(MapRenderSceneTest, SceneIsASnapshotThatOutlivesTheMapLayers) ASSERT_EQ(scene.layers.size(), 1U); EXPECT_EQ(scene.layers[0].layerId, id); - EXPECT_EQ(scene.layers[0].scene.polygons.front().front().size(), 5U); + EXPECT_EQ(scene.layers[0].scene->polygons.front().front().size(), 5U); } diff --git a/tests/MapWinGIS.Core.Tests/MapViewTests.cpp b/tests/MapWinGIS.Core.Tests/MapViewTests.cpp index 108d660..1bdbdcd 100644 --- a/tests/MapWinGIS.Core.Tests/MapViewTests.cpp +++ b/tests/MapWinGIS.Core.Tests/MapViewTests.cpp @@ -306,10 +306,10 @@ TEST_F(MapViewTest, SceneIsReusedUntilTheMapChanges) { _view.AddLayer(OpenRectangles({{0.0, 0.0, 1.0, 1.0}})); const rendering::MapRenderScene& scene = _view.Scene(); - const auto* polygons = scene.layers.front().scene.polygons.Coordinates().data(); + const auto* polygons = scene.layers.front().scene->polygons.Coordinates().data(); ASSERT_TRUE(_view.Resize(300, 200)); - EXPECT_EQ(_view.Scene().layers.front().scene.polygons.Coordinates().data(), polygons); + EXPECT_EQ(_view.Scene().layers.front().scene->polygons.Coordinates().data(), polygons); EXPECT_TRUE(_view.InvalidateScene()); EXPECT_EQ(&_view.Scene(), &scene); @@ -334,8 +334,8 @@ TEST_F(MapViewTest, PreparedLayersRetainTheirGeometryUntilInvalidated) ASSERT_EQ(view.Scene().layers.size(), 2U); EXPECT_EQ(view.Scene().layers[0].layerId, firstId); EXPECT_EQ(view.Scene().layers[1].layerId, secondId); - EXPECT_EQ(view.Scene().layers[0].scene.polygons.Coordinates().data(), firstPolygons); - EXPECT_EQ(view.Scene().layers[1].scene.polygons.Coordinates().data(), secondPolygons); + EXPECT_EQ(view.Scene().layers[0].scene->polygons.Coordinates().data(), firstPolygons); + EXPECT_EQ(view.Scene().layers[1].scene->polygons.Coordinates().data(), secondPolygons); EXPECT_EQ(driver.readCalls, 8); EXPECT_TRUE(view.InvalidateScene()); @@ -343,6 +343,39 @@ TEST_F(MapViewTest, PreparedLayersRetainTheirGeometryUntilInvalidated) EXPECT_EQ(driver.readCalls, 16); } +TEST_F(MapViewTest, SharedPreparedSceneIsStoredWithoutCopyAndOutlivesInvalidation) +{ + const auto dataset = OpenRectangles({{0.0, 0.0, 1.0, 1.0}}); + const auto prepared = std::make_shared( + rendering::CreateVectorRenderScene(*dataset)); + + const LayerId id = _view.AddLayer(dataset, prepared); + ASSERT_EQ(_view.Scene().layers.size(), 1U); + EXPECT_EQ(_view.Scene().layers.front().layerId, id); + EXPECT_EQ(_view.Scene().layers.front().scene, prepared); + + // A renderer holding the assembled layer scene keeps valid geometry after + // the view drops it. + const std::shared_ptr held = + _view.Scene().layers.front().scene; + EXPECT_TRUE(_view.InvalidateScene()); + ASSERT_EQ(_view.Scene().layers.size(), 1U); + EXPECT_NE(_view.Scene().layers.front().scene, held); + EXPECT_TRUE(_view.RemoveLayer(id)); + ASSERT_EQ(held->polygons.size(), 1U); + EXPECT_EQ(held->polygons.front().front().size(), 5U); +} + +TEST_F(MapViewTest, NullPreparedSceneIsRejectedBeforeTheMapChanges) +{ + const auto dataset = OpenRectangles({{0.0, 0.0, 1.0, 1.0}}); + EXPECT_THROW( + (void)_view.AddLayer(dataset, std::shared_ptr{}), + InvalidArgument); + EXPECT_EQ(_view.GetMap().LayerCount(), 0); + EXPECT_FALSE(_view.GetViewport().HasView()); +} + TEST_F(MapViewTest, VisibilityChangesReuseCachedLayerScenes) { VectorReadTestDriver driver; @@ -497,14 +530,14 @@ TEST_F(MapViewTest, AllocationFailurePreservesThePublishedSceneAndAllowsRetry) const LayerId first = view.AddLayer(dataset); const auto& scene = view.Scene(); ASSERT_EQ(scene.layers.size(), 1U); - const auto* coordinates = scene.layers.front().scene.polygons.Coordinates().data(); + const auto* coordinates = scene.layers.front().scene->polygons.Coordinates().data(); const LayerId second = view.AddLayer(dataset); driver.failExtentCapabilityAllocation = true; EXPECT_THROW((void)view.Scene(), std::bad_alloc); ASSERT_EQ(scene.layers.size(), 1U); EXPECT_EQ(scene.layers.front().layerId, first); - EXPECT_EQ(scene.layers.front().scene.polygons.Coordinates().data(), coordinates); + EXPECT_EQ(scene.layers.front().scene->polygons.Coordinates().data(), coordinates); EXPECT_TRUE(scene.skippedLayers.empty()); driver.failExtentCapabilityAllocation = false; @@ -520,7 +553,7 @@ TEST_F(MapViewTest, ComplexSceneMeshesSurviveViewportChanges) const rendering::MapRenderScene& scene = _view.Scene(); ASSERT_EQ(scene.layers.size(), 1U); - const rendering::VectorRenderScene& layerScene = scene.layers.front().scene; + const rendering::VectorRenderScene& layerScene = *scene.layers.front().scene; ASSERT_EQ(layerScene.polygons.size(), 2U); ASSERT_EQ(layerScene.fillMeshes.size(), 2U); // Both the concave component and the holed component are triangulated. @@ -536,8 +569,8 @@ TEST_F(MapViewTest, ComplexSceneMeshesSurviveViewportChanges) // its triangulated meshes stay alive and are not rebuilt. ASSERT_TRUE(_view.Resize(640, 480)); EXPECT_EQ(&_view.Scene(), &scene); - EXPECT_EQ(_view.Scene().layers.front().scene.fillMeshes.data(), meshStorage); - EXPECT_EQ(_view.Scene().layers.front().scene.fillMeshes[1]->vertices.data(), + EXPECT_EQ(_view.Scene().layers.front().scene->fillMeshes.data(), meshStorage); + EXPECT_EQ(_view.Scene().layers.front().scene->fillMeshes[1]->vertices.data(), holedMeshVertices); ASSERT_TRUE(_view.ZoomIn()); @@ -545,7 +578,7 @@ TEST_F(MapViewTest, ComplexSceneMeshesSurviveViewportChanges) ASSERT_TRUE(_view.ZoomAt(ScreenPoint{150.0, 100.0}, 2.0)); ASSERT_TRUE(_view.Pan(1.0, -0.5)); EXPECT_EQ(&_view.Scene(), &scene); - const rendering::VectorRenderScene& navigated = _view.Scene().layers.front().scene; + const rendering::VectorRenderScene& navigated = *_view.Scene().layers.front().scene; EXPECT_EQ(navigated.fillMeshes[1]->vertices.data(), holedMeshVertices); EXPECT_EQ(navigated.fillMeshes[1]->indices.size(), holedMeshIndices); EXPECT_EQ(navigated.polygons[1].size(), holedPolygonRings); @@ -553,7 +586,7 @@ TEST_F(MapViewTest, ComplexSceneMeshesSurviveViewportChanges) // Reassembly keeps the cached meshes and original rings for outlines and GDI. const LayerId second = _view.AddLayer(OpenRectangles({{100.0, 0.0, 110.0, 10.0}})); ASSERT_EQ(_view.Scene().layers.size(), 2U); - const rendering::VectorRenderScene& rebuilt = _view.Scene().layers.front().scene; + const rendering::VectorRenderScene& rebuilt = *_view.Scene().layers.front().scene; ASSERT_EQ(rebuilt.polygons.size(), 2U); ASSERT_EQ(rebuilt.fillMeshes.size(), 2U); EXPECT_TRUE(rebuilt.fillMeshes[0].has_value()); @@ -562,7 +595,7 @@ TEST_F(MapViewTest, ComplexSceneMeshesSurviveViewportChanges) EXPECT_TRUE(_view.RemoveLayer(second)); ASSERT_EQ(_view.Scene().layers.size(), 1U); - EXPECT_TRUE(_view.Scene().layers.front().scene.fillMeshes[1].has_value()); + EXPECT_TRUE(_view.Scene().layers.front().scene->fillMeshes[1].has_value()); } TEST_F(MapViewTest, PreparedEmptyLayerPreservesExistingAndStaleScenes) diff --git a/tests/MapWinGIS.Core.Tests/TestData.cpp b/tests/MapWinGIS.Core.Tests/TestData.cpp index 7803391..e93c39c 100644 --- a/tests/MapWinGIS.Core.Tests/TestData.cpp +++ b/tests/MapWinGIS.Core.Tests/TestData.cpp @@ -338,7 +338,7 @@ namespace mwg::test OGRFieldDefn idField(Provinces::kIdField, OFTInteger); OGRFieldDefn nameField(Provinces::kNameField, OFTString); - nameField.SetWidth(32); + nameField.SetWidth(Provinces::kNameWidth); OGRFieldDefn areaField(Provinces::kAreaField, OFTReal); areaField.SetWidth(18); areaField.SetPrecision(4); diff --git a/tests/MapWinGIS.Core.Tests/TestData.h b/tests/MapWinGIS.Core.Tests/TestData.h index bfc6a94..6995c9c 100644 --- a/tests/MapWinGIS.Core.Tests/TestData.h +++ b/tests/MapWinGIS.Core.Tests/TestData.h @@ -80,6 +80,8 @@ namespace mwg::test static constexpr const char* kLayerName = "provinces"; static constexpr const char* kIdField = "ID"; static constexpr const char* kNameField = "NAME"; + /// Initial declared width of NAME in generated fixtures. + static constexpr int kNameWidth = 32; static constexpr const char* kAreaField = "AREA_KM2"; static constexpr const char* kSurveyedField = "SURVEYED"; static constexpr const char* kActiveField = "ACTIVE"; diff --git a/tests/MapWinGIS.Core.Tests/VectorLayerTests.cpp b/tests/MapWinGIS.Core.Tests/VectorLayerTests.cpp index 3f32445..5dc3500 100644 --- a/tests/MapWinGIS.Core.Tests/VectorLayerTests.cpp +++ b/tests/MapWinGIS.Core.Tests/VectorLayerTests.cpp @@ -421,6 +421,27 @@ TEST_P(VectorLayerEditTest, FlushesPendingEdits) reopened->Layer(0).FieldIndex(Provinces::kNameField), 0), "Flushed"); } +TEST_P(VectorLayerEditTest, ReadsBackTheStoredValueAfterTheDriverCoercesAWrite) +{ + const std::string longName(Provinces::kNameWidth + 300, 'x'); + std::string readBack; + { + const GdalEnvironment::QuietScope quiet; + const std::unique_ptr dataset = VectorDataset::Open(_path, OpenMode::Update); + VectorLayer& layer = dataset->Layer(0); + const int name = layer.FieldIndex(Provinces::kNameField); + layer.SetCellString(name, 0, longName); + readBack = layer.CellString(name, 0); + } + + const std::unique_ptr reopened = Reopen(); + const std::string stored = reopened->Layer(0).CellString( + reopened->Layer(0).FieldIndex(Provinces::kNameField), 0); + EXPECT_EQ(readBack, stored); + if (_path.extension() == ".shp") + EXPECT_EQ(stored.size(), 254U); +} + TEST_P(VectorLayerEditTest, RejectsOutOfRangeFeatureIndexes) { Edit([](VectorLayer& layer) diff --git a/tests/MapWinGIS.Core.Tests/VectorRenderSceneTests.cpp b/tests/MapWinGIS.Core.Tests/VectorRenderSceneTests.cpp index 1e09d18..262a73d 100644 --- a/tests/MapWinGIS.Core.Tests/VectorRenderSceneTests.cpp +++ b/tests/MapWinGIS.Core.Tests/VectorRenderSceneTests.cpp @@ -512,6 +512,51 @@ TEST(VectorRenderScene, LinearizesCurvedPolygonGeometry) EXPECT_GT(scene.polygons.front().front().size(), 5u); } +TEST(VectorRenderScene, RendersPolygonalCollectionMembersAndCountsSkippedParts) +{ + GdalEnvironment::Initialize(); + TempDirectory directory; + std::filesystem::path path; + { + const GdalEnvironment::QuietScope quiet; + path = MakeDimensionalPolygonDataset( + directory.Path(), + "collection.gpkg", + wkbMultiPolygon, + "GEOMETRYCOLLECTION (POLYGON ((0 0, 4 0, 4 4, 0 4, 0 0)), " + "LINESTRING (0 0, 1 1), POINT (2 2))"); + } + const auto dataset = VectorDataset::Open(path); + + const rendering::VectorRenderScene scene = + rendering::CreateVectorRenderScene(dataset->Layer(0)); + + ASSERT_EQ(scene.polygons.size(), 1u); + EXPECT_EQ(scene.polygons.front().front().size(), 5u); + EXPECT_EQ(scene.skippedGeometryCount, 2); +} + +TEST(VectorRenderScene, SkipsPolygonsWithADegenerateExteriorInsteadOfPromotingAHole) +{ + GdalEnvironment::Initialize(); + TempDirectory directory; + const auto path = MakeDimensionalPolygonDataset( + directory.Path(), + "degenerate-exterior.gpkg", + wkbMultiPolygon, + "MULTIPOLYGON (((0 0, 1 1), (1 1, 2 1, 2 2, 1 1)), " + "((10 10, 14 10, 14 14, 10 10)))"); + const auto dataset = VectorDataset::Open(path); + + const rendering::VectorRenderScene scene = + rendering::CreateVectorRenderScene(dataset->Layer(0)); + + ASSERT_EQ(scene.polygons.size(), 1u); + ASSERT_EQ(scene.polygons.front().size(), 1u); + EXPECT_DOUBLE_EQ(scene.polygons.front().front().front().x, 10.0); + EXPECT_EQ(scene.skippedGeometryCount, 1); +} + TEST(VectorRenderScene, RejectsDatasetWithoutLayers) { GdalEnvironment::Initialize(); From 395f14cef0e4160f1a28fd61affde53534ac3892 Mon Sep 17 00:00:00 2001 From: Paul Meems Date: Wed, 18 Nov 2026 17:49:50 +0100 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20fix(rendering):=20keep=20has?= =?UTF-8?q?h=20mixing=20native-width?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Avoid Win32 narrowing in the point hash combiner. - Synchronize nested dispatch coverage and disable timer fallback. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/rendering/PolygonTriangulation.cpp | 4 +- .../ActiveXActivationTests.cpp | 214 +++++++++++++++++- 2 files changed, 209 insertions(+), 9 deletions(-) diff --git a/src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp b/src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp index 1eea1dd..d984b88 100644 --- a/src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp +++ b/src/MapWinGIS.Core/src/rendering/PolygonTriangulation.cpp @@ -99,7 +99,9 @@ namespace mwg::rendering { const std::size_t x = std::hash{}(point.x); const std::size_t y = std::hash{}(point.y); - return x ^ (y + 0x9e3779b97f4a7c15ULL + (x << 6) + (x >> 2)); + constexpr std::size_t mixingConstant = + static_cast(0x9e3779b97f4a7c15ULL); + return x ^ (y + mixingConstant + (x << 6) + (x >> 2)); } }; diff --git a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp index 6c68f18..b2d4e84 100644 --- a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp @@ -36,6 +36,7 @@ #include "MapWinGIS.ActiveX_i.h" #include "MapWinGISControlTestAccess.h" #include "DllInstallScope.h" +#include "GdalDispatchWindow.h" #include "TestData.h" #include "mapwingis/gdal/GdalAlgorithmRunner.h" #include "mapwingis/gdal/GdalEnvironment.h" @@ -271,6 +272,15 @@ namespace operationId)); } + [[nodiscard]] std::size_t ProgressCount(const LONGLONG operationId) const + { + std::lock_guard lock(_mutex); + return static_cast(std::count( + _progressOperations.begin(), + _progressOperations.end(), + operationId)); + } + [[nodiscard]] bool HasProgress(const LONGLONG operationId) const { std::lock_guard lock(_mutex); @@ -356,6 +366,128 @@ namespace HANDLE _handle = nullptr; }; + class NestedDispatchBarrier final + { + public: + ~NestedDispatchBarrier() + { + static_cast(_sinkEntered.Signal()); + static_cast(_wakePosted.Signal()); + static_cast(_allowFinish.Signal()); + if (_started.load(std::memory_order_acquire)) + { + static_cast(_workerFinished.Wait(10000)); + } + } + + void MarkStarted() noexcept + { + _started.store(true, std::memory_order_release); + } + + [[nodiscard]] bool WaitForSinkEntered() const noexcept + { + return _sinkEntered.Wait(10000); + } + + [[nodiscard]] bool WaitForWakePosted() const noexcept + { + return _wakePosted.Wait(10000); + } + + [[nodiscard]] bool WaitForCompletionDelivery() const noexcept + { + return _allowFinish.Wait(10000); + } + + [[nodiscard]] bool SignalSinkEntered() const noexcept + { + return _sinkEntered.Signal(); + } + + [[nodiscard]] bool SignalWakePosted() const noexcept + { + return _wakePosted.Signal(); + } + + [[nodiscard]] bool SignalAllowFinish() const noexcept + { + return _allowFinish.Signal(); + } + + [[nodiscard]] bool SignalWorkerFinished() const noexcept + { + return _workerFinished.Signal(); + } + + void RecordNestedDispatch() noexcept + { + _nestedDispatchCount.fetch_add(1, std::memory_order_relaxed); + } + + [[nodiscard]] int NestedDispatchCount() const noexcept + { + return _nestedDispatchCount.load(std::memory_order_relaxed); + } + + private: + ScopedEvent _sinkEntered; + ScopedEvent _wakePosted; + ScopedEvent _allowFinish; + ScopedEvent _workerFinished; + std::atomic_bool _started{false}; + std::atomic_int _nestedDispatchCount{0}; + }; + + std::atomic nestedDispatchBarrier{nullptr}; + + class HostedNestedDispatchAlgorithm final : public GDALAlgorithm + { + public: + explicit HostedNestedDispatchAlgorithm( + NestedDispatchBarrier* const barrier) + : GDALAlgorithm( + "mwg-test-activex-nested-progress", + "Test nested COM progress dispatch", + ""), + _barrier(barrier) + { + } + + protected: + bool RunImpl(GDALProgressFunc progress, void* userData) override + { + if (_barrier == nullptr || progress == nullptr) + { + return false; + } + + struct FinishSignal final + { + NestedDispatchBarrier& barrier; + ~FinishSignal() + { + static_cast(barrier.SignalWorkerFinished()); + } + } finishSignal{*_barrier}; + + if (progress(0.1, "COM nested progress", userData) == 0 || + !_barrier->WaitForSinkEntered()) + { + return false; + } + if (progress(0.2, "COM nested progress", userData) == 0) + { + return false; + } + static_cast(_barrier->SignalWakePosted()); + return _barrier->WaitForCompletionDelivery(); + } + + private: + NestedDispatchBarrier* _barrier = nullptr; + }; + class VectorPreparationBarrier final { public: @@ -541,6 +673,13 @@ namespace registry.DeclareAlgorithm( {"mwg-test-activex", "progress"}, [] { return std::make_unique(); }); + registry.DeclareAlgorithm( + {"mwg-test-activex", "nested-progress"}, + [] + { + return std::make_unique( + nestedDispatchBarrier.load(std::memory_order_acquire)); + }); registry.DeclareAlgorithm( {"mwg-test-activex", "diagnostics"}, [] { return std::make_unique(); }); @@ -577,15 +716,43 @@ namespace // Simulates a sink that shows UI from a progress event: the nested pump // consumes dispatch messages posted while the control is still delivering. - HRESULT PumpNestedMessages(void*, LONGLONG) + HRESULT PumpNestedMessages(void* const context, LONGLONG) { - MSG message{}; - while (::PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) + auto& barrier = *static_cast(context); + if (barrier.NestedDispatchCount() != 0) + { + return barrier.SignalAllowFinish() ? S_OK : E_FAIL; + } + if (!barrier.SignalSinkEntered()) + { + return E_FAIL; + } + + const auto dispatchWake = [&barrier] { - ::TranslateMessage(&message); + MSG message{}; + if (!::PeekMessageW( + &message, + nullptr, + mwg::activex::kGdalDispatchMessage, + mwg::activex::kGdalDispatchMessage, + PM_REMOVE)) + { + return false; + } ::DispatchMessageW(&message); + barrier.RecordNestedDispatch(); + return true; + }; + + if (!barrier.WaitForWakePosted() || !dispatchWake()) + { + return E_FAIL; } - return S_OK; + while (dispatchWake()) + { + } + return barrier.NestedDispatchCount() == 1 ? S_OK : E_FAIL; } HRESULT FailCompletion(void*, LONGLONG) @@ -2670,20 +2837,51 @@ TEST(ActiveXHosting, ResizesRepaintsAndRecreatesControl) warningResult.warnings.front().find(L"COM test warning"), std::wstring::npos); - eventSink->SetProgressCallback(&PumpNestedMessages, nullptr); + NestedDispatchBarrier nestedBarrier; + struct NestedDispatchCleanup final + { + GdalEventSink& eventSink; + ~NestedDispatchCleanup() + { + eventSink.SetProgressCallback(nullptr, nullptr); + nestedDispatchBarrier.store( + nullptr, + std::memory_order_release); + } + } nestedDispatchCleanup{*eventSink.Get()}; + static_cast(nestedDispatchCleanup); + nestedDispatchBarrier.store( + &nestedBarrier, + std::memory_order_release); + eventSink->SetProgressCallback( + &PumpNestedMessages, + &nestedBarrier); LONGLONG nestedPumpOperationId = 0; ASSERT_TRUE(SUCCEEDED(StartGdalOperation( gdalControl, - L"mwg-test-activex progress", + L"mwg-test-activex nested-progress", {}, &nestedPumpOperationId))); + nestedBarrier.MarkStarted(); + const HWND dispatchWindow = ::FindWindowExW( + HWND_MESSAGE, + nullptr, + L"MapWinGIS6.GdalDispatchWindow", + nullptr); + ASSERT_NE(dispatchWindow, nullptr); + ASSERT_TRUE(::KillTimer( + dispatchWindow, + mwg::activex::kGdalDispatchRetryTimerId)); ComGdalResult nestedPumpResult; ASSERT_TRUE(SUCCEEDED(finishOperation( nestedPumpOperationId, nestedPumpResult))); EXPECT_EQ(nestedPumpResult.succeeded, VARIANT_TRUE); EXPECT_EQ(nestedPumpResult.callbackErrorCode, 0); - eventSink->SetProgressCallback(nullptr, nullptr); + EXPECT_EQ( + eventSink->ProgressCount(nestedPumpOperationId), + 2u); + EXPECT_EQ(nestedBarrier.NestedDispatchCount(), 1); LONGLONG failureOperationId = 0; ASSERT_TRUE(SUCCEEDED(StartGdalOperation(