From bcd1b1d0e9f33ab9643f572d3b9807fefc95e20d Mon Sep 17 00:00:00 2001 From: Paul Meems Date: Sun, 15 Nov 2026 21:03:26 +0100 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20feat(activex):=20load=20vector?= =?UTF-8?q?=20datasets=20asynchronously?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add versioned asynchronous vector-load API and shared completion delivery. - Prepare data off-thread, commit on the owner thread, and preserve synchronous loading. - Cover completion, cancellation, failures, and shutdown; update docs and plan. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .ai/memory/architecture/activex.md | 12 +- .../development-review-fix-plan-20261113.md | 8 +- README.md | 8 +- docs/ARCHITECTURE.md | 46 +- docs/PORTING.md | 18 +- docs/TESTING.md | 3 +- docs/gdal-integration.md | 2 + src/MapWinGIS.ActiveX/GdalEventSource.cpp | 56 ++ src/MapWinGIS.ActiveX/GdalEventSource.h | 14 + .../GdalOperationDispatcher.cpp | 118 +++- .../GdalOperationDispatcher.h | 17 + src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl | 31 +- src/MapWinGIS.ActiveX/MapWinGISControl.cpp | 613 +++++++++++++++++- src/MapWinGIS.ActiveX/MapWinGISControl.h | 24 +- .../ActiveXActivationTests.cpp | 237 ++++++- 15 files changed, 1122 insertions(+), 85 deletions(-) diff --git a/.ai/memory/architecture/activex.md b/.ai/memory/architecture/activex.md index 57a4e5d..93c2b9e 100644 --- a/.ai/memory/architecture/activex.md +++ b/.ai/memory/architecture/activex.md @@ -7,14 +7,14 @@ remain in Core. ## Automation contracts -- `IMapWinGISControl`, `IMapWinGISControl2`, `IMapWinGISControl3`, and - `IMapWinGISControl4` are versioned derived interfaces with distinct IIDs. +- `IMapWinGISControl` through `IMapWinGISControl5` are versioned derived + interfaces with distinct IIDs. Do not add vtable members to a published interface or change its IID. Extend the contract with a new derived interface when needed. -- The default control interface is `IMapWinGISControl4`. It adds navigation, - layer count, and stable layer-ID access to `IMapWinGISControl3`. The - independent generic GDAL capability uses `IMapWinGISControlGdal`, and - notifications use the separate `IMapWinGISControlEvents` dispinterface. +- The default control interface is `IMapWinGISControl5`. It adds asynchronous + vector loading to `IMapWinGISControl4`; the independent generic GDAL + capability uses `IMapWinGISControlGdal`, and both operations use the + separate `IMapWinGISControlEvents` dispinterface. - These are new v6 interfaces, not the MapWinGIS 5 type-library contracts. The current control does not claim v5 binary compatibility. - Keep COM conversions and COM error translation at this boundary. Core diff --git a/.github/plans/development-review-fix-plan-20261113.md b/.github/plans/development-review-fix-plan-20261113.md index 155f349..2252ab0 100644 --- a/.github/plans/development-review-fix-plan-20261113.md +++ b/.github/plans/development-review-fix-plan-20261113.md @@ -12,7 +12,7 @@ Implement one phase per run and open one PR per phase, in this order. Check a ph - [x] Phase 6 – Improve COM container compatibility (#6, #20, #24, #27, #37) - [x] Phase 7 – Rebuild render scenes per layer (#7, #34) - [x] Phase 8 – Fix ActiveX rendering edge cases (#21, #26, #35, #38) -- [ ] Phase 9 – Load vector datasets asynchronously (#36) +- [x] Phase 9 – Load vector datasets asynchronously (#36) Finding coverage: every finding is assigned to exactly one phase: @@ -401,3 +401,9 @@ Suggested fix: - GDAL objects created on the worker must not be used concurrently; follow the threading contract documented in Phase 3. After approval, implement it with tests: load completes and fires the event; cancel leaves the map unchanged; a failed open reports error details; destroying the control during a load is safe. + +**Phase 9 result:** Added asynchronous vector loading to `IMapWinGISControl5` at DISPIDs 18-20. The worker prepares the dataset and render scene; the owning apartment commits them before raising the shared `GdalOperationCompleted` event. Cancellation discards the candidate, and the synchronous load methods retain their behavior. + +**Validation:** CMake Debug x64 build and all 430 CTest cases passed; three opt-in cases were skipped. MSBuild Debug x64 built with zero warnings. Its Core suite passed 335 tests with one skip, and its ActiveX suite passed 88 tests with three skips. The existing CMake D9025 command-line warning remains. + +**Limitations:** Interactive registered-control hosting and network-dependent/opt-in rendering tests were not run locally. diff --git a/README.md b/README.md index 8433278..12f77a8 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,10 @@ cancellation events. The core also supports a shared map viewport with pan, center zoom, anchored zoom, and fitting to the visible map or a named layer. These navigation calls -do not depend on a window. `IMapWinGISControl4` exposes this programmatic -navigation and stable layer IDs through ActiveX. The control also supports -left-button drag panning and cursor-anchored mouse-wheel zoom. Resizing keeps -the current map center and resolution. +do not depend on a window. `IMapWinGISControl5` exposes this programmatic +navigation, stable layer IDs, and asynchronous vector loading through ActiveX. +The control also supports left-button drag panning and cursor-anchored +mouse-wheel zoom. Resizing keeps the current map center and resolution. Cached drag frames are reused only for whole-pixel shifts. Scaled and print draws use temporary rendering buffers and keep the screen diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ad85e7d..548051f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -362,10 +362,11 @@ drawing operation is unsupported. The control reports the active backend and the reason for a fallback through `RenderingBackend` and `RenderingStatus`. These rendering properties are on `IMapWinGISControl2`, which derives from `IMapWinGISControl`. `IMapWinGISControl3` adds `ClearLayers` at DISPID 8. -The coclass default is `IMapWinGISControl4`, which derives from -`IMapWinGISControl3`. It adds map navigation, layer count, and stable layer IDs -at DISPIDs 9-17. The earlier interfaces, their DISPIDs, and their IIDs remain -unchanged. +`IMapWinGISControl4` derives from `IMapWinGISControl3` and adds map navigation, +layer count, and stable layer IDs at DISPIDs 9-17. The coclass default is +`IMapWinGISControl5`, which derives from `IMapWinGISControl4` and adds +asynchronous vector loading at DISPIDs 18-20. The earlier interfaces, their +DISPIDs, and their IIDs remain unchanged. OpenGL capability detection checks framebuffer-object entry points, the maximum renderbuffer size, and the maximum viewport dimensions at runtime; targets exceeding either limit use GDI. CPU staging for OpenGL readback is @@ -399,19 +400,23 @@ intentional compatibility gaps and the rationale when interfaces are introduced. The control exposes a small v6 COM surface: Core initialization, vector dataset loading, layer-loaded state, feature count, renderer preference, -active backend and status, plus asynchronous generic GDAL operations with -progress, cancellation, and result reporting. The GDAL API has a new interface -and does not claim MapWinGIS 5 `IGdalUtils` binary compatibility. -At most sixteen operations may be active or awaiting result cleanup. Call -`EndGdalOperation` after completion to release an operation slot. The control -delivers events on its owning apartment thread. Destroying the in-place window -suspends notification delivery without cancelling operations; a subsequent -`WM_SIZE` resumes delivery. Calling `Close` or destroying the control after -the client's final COM reference is released cancels outstanding work and -discards queued notifications. An in-progress event dispatch holds a temporary -COM reference, so releasing the client's reference inside an event does not -destroy the control until dispatch returns. Workers never retain COM references -or wait for event handlers. +active backend and status, plus asynchronous vector loading and generic GDAL +operations. The GDAL API has a new interface and does not claim MapWinGIS 5 +`IGdalUtils` binary compatibility. Both asynchronous capabilities share one +dispatcher and operation limit: at most sixteen operations may be active or +awaiting result cleanup. `GdalOperationCompleted` signals either kind; call +`EndGdalOperation` or `EndLoadVectorDataset`, respectively, to retrieve the +result and release its slot. Completion is delivered on the owning apartment +thread. For vector loads, the control commits the prepared dataset and scene +before raising the completion event. Cancellation discards the candidate and +leaves the live map unchanged. Destroying the in-place window suspends +notification delivery without cancelling operations; a subsequent `WM_SIZE` +resumes delivery. Calling `Close` or destroying the control after the client's +final COM reference is released cancels outstanding work and discards queued +notifications. An in-progress event dispatch holds a temporary COM reference, +so releasing the client's reference inside an event does not destroy the +control until dispatch returns. Workers never retain COM references or wait for +event handlers. `LoadVectorDataset` adds the first vector layer of a dataset on top of the map. Earlier layers stay loaded, so calling it again shows several layers. @@ -420,6 +425,13 @@ returns the stable ID of the new layer, and `GetLayerId` returns a layer ID by its current 0-based position. Call `ClearLayers` before switching or refreshing datasets to avoid duplicate layers. It releases all loaded datasets and clears the feature total, but keeps the view. +`IMapWinGISControl5::BeginLoadVectorDataset` performs the same preparation on +the GDAL worker and returns an operation ID. It uses the existing +`GdalOperationCompleted` event; clients retrieve the result and new layer ID +with `EndLoadVectorDataset`. `CancelLoadVectorDataset` does not block. If +cancellation is accepted before the completion event is delivered, the +candidate is discarded and the map is unchanged. The original synchronous +`LoadVectorDataset` and `LoadVectorDatasetEx` methods keep their behavior. The layer must be polygon-compatible: a dataset whose first layer has another geometry type fails to load and is not added, even if a later layer is polygonal. An empty polygon layer loads but draws nothing. The control reads diff --git a/docs/PORTING.md b/docs/PORTING.md index 5cb0367..4874744 100644 --- a/docs/PORTING.md +++ b/docs/PORTING.md @@ -72,12 +72,18 @@ The initial `MapWinGIS.ocx` exposes a deliberately small v6 automation contract. `IMapWinGISControl` reports Core initialization, loads a vector dataset, and reports whether a layer is loaded and its feature count. `IMapWinGISControl2` adds renderer preference, active backend, and status. -`IMapWinGISControl3` adds `ClearLayers`. `IMapWinGISControl4` derives from it -and is the default automation interface; it adds view navigation, layer count, -`LoadVectorDatasetEx`, and stable layer-ID lookup by 0-based position. Loads -add layers, including duplicate loads of one dataset. Each successful load -requests a fit to the combined map extent, replacing any previous pan or zoom -when the extent is valid and the viewport has a size. +`IMapWinGISControl3` adds `ClearLayers`. `IMapWinGISControl4` adds view +navigation, layer count, `LoadVectorDatasetEx`, and stable layer-ID lookup by +0-based position. `IMapWinGISControl5` derives from it and is the default +automation interface; it adds asynchronous vector loading, cancellation, and +result retrieval. It reuses the `GdalOperationCompleted` event and shares the +dispatcher and operation limit with asynchronous GDAL calls. The worker +prepares a candidate dataset and scene; the control commits them on its owning +apartment before the completion event. Cancelling before completion leaves the +map unchanged. The synchronous load methods retain their existing behavior. +Loads add layers, including duplicate loads of one dataset. Each successful +load requests a fit to the combined map extent, replacing any previous pan or +zoom when the extent is valid and the viewport has a size. Call `ClearLayers` before switching or refreshing datasets. It releases all layers and resets the cached feature total while keeping the viewport. diff --git a/docs/TESTING.md b/docs/TESTING.md index 4074018..ca6d97c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -122,7 +122,8 @@ output folder. CI runs them before the solution build. Builds with Pull requests run both Debug and full-driver Release tests for x64. The native `MapWinGIS.ActiveX.Tests` project covers COM activation, rendering -through GDI and OpenGL, and GDAL progress/completion events. +through GDI and OpenGL, GDAL progress/completion events, and asynchronous +vector loads, including cancellation, failure details, and control destruction. Class-factory tests require no COM registration. They inspect the native control through test-only friend helpers, without changing its COM interfaces. They cover whole-pixel cached pan draws, fractional and oversized offsets, diff --git a/docs/gdal-integration.md b/docs/gdal-integration.md index 3140722..09edf69 100644 --- a/docs/gdal-integration.md +++ b/docs/gdal-integration.md @@ -144,6 +144,8 @@ cancellation, GDAL error code, summary, full diagnostics, callback error code and message, and warnings, and to release the operation slot. An incomplete operation returns `E_PENDING`; an unknown or ended identifier returns `E_INVALIDARG`. +`GdalOperationCompleted` is also reused for asynchronous vector loads exposed +by `IMapWinGISControl5`; retrieve those results with `EndLoadVectorDataset`. `EndGdalOperation` also returns `E_PENDING` while a progress or completion event is being delivered. Call it after the event handler returns. diff --git a/src/MapWinGIS.ActiveX/GdalEventSource.cpp b/src/MapWinGIS.ActiveX/GdalEventSource.cpp index fe50b5a..0c49934 100644 --- a/src/MapWinGIS.ActiveX/GdalEventSource.cpp +++ b/src/MapWinGIS.ActiveX/GdalEventSource.cpp @@ -123,6 +123,36 @@ namespace mwg::activex } } + std::uint64_t GdalEventSource::BeginWork( + GdalOperationDispatcher::WorkCallback work) + { + if (_closing || _dispatchWindow == nullptr || + !_dispatchWindow->IsWindow()) + { + throw std::runtime_error( + "The GDAL event source is not available for new operations."); + } + + _dispatcher.SetWakeCallback( + &GdalEventSource::PostDispatchMessage, + _dispatchWindow.get()); + _dispatcher.SetWorkerFinishedCallback( + &GdalEventSource::UnlockActiveXModule, + nullptr); + ArmRetryTimer(); + _AtlModule.Lock(); + try + { + return _dispatcher.BeginWork(std::move(work), true); + } + catch (...) + { + _AtlModule.Unlock(); + UpdateRetryTimer(); + throw; + } + } + GdalCancelResult GdalEventSource::Cancel( const std::uint64_t operationId) noexcept { @@ -135,6 +165,19 @@ namespace mwg::activex return _dispatcher.GetResult(operationId); } + GdalOperationLookup GdalEventSource::GetResultForDelivery( + const std::uint64_t operationId) const + { + return _dispatcher.GetResultForDelivery(operationId); + } + + void GdalEventSource::UpdateCompletedResult( + const std::uint64_t operationId, + GdalOperationSnapshot result) + { + _dispatcher.UpdateCompletedResult(operationId, std::move(result)); + } + GdalOperationLookup GdalEventSource::End(const std::uint64_t operationId) { GdalOperationLookup result = _dispatcher.End(operationId); @@ -142,6 +185,14 @@ namespace mwg::activex return result; } + void GdalEventSource::SetCompletionCallback( + const CompletionCallback callback, + void* const context) noexcept + { + _completionCallback = callback; + _completionContext = context; + } + void GdalEventSource::RecordCallbackError( const std::uint64_t operationId, const HRESULT result) noexcept @@ -245,6 +296,11 @@ namespace mwg::activex } } 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) diff --git a/src/MapWinGIS.ActiveX/GdalEventSource.h b/src/MapWinGIS.ActiveX/GdalEventSource.h index fc3516f..9ebd2b7 100644 --- a/src/MapWinGIS.ActiveX/GdalEventSource.h +++ b/src/MapWinGIS.ActiveX/GdalEventSource.h @@ -27,6 +27,8 @@ namespace mwg::activex class GdalEventSource final { public: + using CompletionCallback = void(*)(void*, std::uint64_t) noexcept; + GdalEventSource( ATL::CComDynamicUnkArray& sinks, GdalDispatchWindow::Callback callback, @@ -40,10 +42,20 @@ namespace mwg::activex [[nodiscard]] std::uint64_t Begin( std::string algorithmPath, std::vector arguments); + [[nodiscard]] std::uint64_t BeginWork( + GdalOperationDispatcher::WorkCallback work); [[nodiscard]] GdalCancelResult Cancel(std::uint64_t operationId) noexcept; [[nodiscard]] GdalOperationLookup GetResult( std::uint64_t operationId) const; + [[nodiscard]] GdalOperationLookup GetResultForDelivery( + std::uint64_t operationId) const; + void UpdateCompletedResult( + std::uint64_t operationId, + GdalOperationSnapshot result); [[nodiscard]] GdalOperationLookup End(std::uint64_t operationId); + void SetCompletionCallback( + CompletionCallback callback, + void* context) noexcept; void RecordCallbackError( std::uint64_t operationId, HRESULT result) noexcept; @@ -76,6 +88,8 @@ namespace mwg::activex ATL::CComDynamicUnkArray& _sinks; GdalDispatchWindow::Callback _dispatchCallback = nullptr; void* _dispatchContext = nullptr; + CompletionCallback _completionCallback = nullptr; + void* _completionContext = nullptr; std::shared_ptr _dispatchWindow; bool _dispatching = false; bool _dispatchWindowDestroyPending = false; diff --git a/src/MapWinGIS.ActiveX/GdalOperationDispatcher.cpp b/src/MapWinGIS.ActiveX/GdalOperationDispatcher.cpp index 46c45bd..6f7235b 100644 --- a/src/MapWinGIS.ActiveX/GdalOperationDispatcher.cpp +++ b/src/MapWinGIS.ActiveX/GdalOperationDispatcher.cpp @@ -34,6 +34,7 @@ namespace mwg::activex bool completed = false; bool completionPending = false; bool notificationDeliveryInProgress = false; + bool honorCancellationAtCompletion = false; int callbackErrorCode = 0; std::string callbackError; std::optional progress; @@ -241,8 +242,7 @@ namespace mwg::activex void Execute( const std::shared_ptr& state, const std::shared_ptr& operation, - std::string algorithmPath, - std::vector arguments, + GdalOperationDispatcher::WorkCallback work, const GdalOperationDispatcher::WorkerFinishedCallback workerFinishedCallback, void* const workerFinishedContext) noexcept { @@ -270,21 +270,15 @@ namespace mwg::activex } else { - mwg::GdalAlgorithmRunner runner(algorithmPath); - if (runner.ParseCommandLineArgs(arguments) && - runner.ValidateArguments()) + const GdalOperationDispatcher::ProgressCallback progress = + [state, operationId = operation->id]( + const double fraction, + const std::string_view message) { - static_cast(runner.Run( - [state, operationId = operation->id]( - const double progress, - const std::string_view message) - { - QueueProgress(state, operationId, progress, message); - return true; - }, - &operation->cancellation)); - } - result = MakeSnapshot(runner.Result()); + QueueProgress(state, operationId, fraction, message); + return true; + }; + result = work(operation->cancellation, progress); } } catch (const std::exception& exception) @@ -326,6 +320,24 @@ namespace mwg::activex return; } + if (operation->honorCancellationAtCompletion && + operation->cancellation.IsCancellationRequested() && + result.succeeded) + { + result.succeeded = false; + result.cancelled = true; + if (result.summary.empty()) + { + try + { + result.summary = "GDAL operation was cancelled."; + } + catch (...) + { + result.summary.clear(); + } + } + } operation->result = std::move(result); operation->completed = true; if (!state->stopping) @@ -371,6 +383,39 @@ namespace mwg::activex std::string algorithmPath, std::vector arguments) { + return BeginWork( + [algorithmPath = std::move(algorithmPath), + arguments = std::move(arguments)]( + GdalCancellationToken& cancellation, + const ProgressCallback& progress) + { + if (cancellation.IsCancellationRequested()) + { + GdalOperationSnapshot result; + result.cancelled = true; + result.summary = "GDAL operation was cancelled before execution."; + return result; + } + + mwg::GdalAlgorithmRunner runner(algorithmPath); + if (runner.ParseCommandLineArgs(arguments) && + runner.ValidateArguments()) + { + static_cast(runner.Run(progress, &cancellation)); + } + return MakeSnapshot(runner.Result()); + }); + } + + std::uint64_t GdalOperationDispatcher::BeginWork( + WorkCallback work, + const bool honorCancellationAtCompletion) + { + if (!work) + { + throw std::invalid_argument("The GDAL worker callback is empty."); + } + std::shared_ptr operation; std::uint64_t operationId = 0; HMODULE workerModule = nullptr; @@ -393,6 +438,8 @@ namespace mwg::activex operationId = _state->nextId++; } while (operationId == 0 || _state->operations.contains(operationId)); operation->id = operationId; + operation->honorCancellationAtCompletion = + honorCancellationAtCompletion; _state->operations.emplace(operationId, operation); workerFinishedCallback = _state->workerFinishedCallback; workerFinishedContext = _state->workerFinishedContext; @@ -405,8 +452,7 @@ namespace mwg::activex Execute, _state, operation, - std::move(algorithmPath), - std::move(arguments), + std::move(work), workerFinishedCallback, workerFinishedContext); RetainModuleUntilWorkerExit(worker, workerModule); @@ -500,6 +546,42 @@ namespace mwg::activex return {GdalEndResult::Ended, std::move(result)}; } + GdalOperationLookup GdalOperationDispatcher::GetResultForDelivery( + const std::uint64_t operationId) const + { + std::lock_guard lock(_state->mutex); + const auto operation = _state->operations.find(operationId); + if (operation == _state->operations.end()) + { + return {GdalEndResult::NotFound, std::nullopt}; + } + if (!operation->second->completed) + { + return {GdalEndResult::Pending, std::nullopt}; + } + + GdalOperationSnapshot result = operation->second->result; + result.callbackErrorCode = operation->second->callbackErrorCode; + result.callbackError = operation->second->callbackError; + return {GdalEndResult::Ended, std::move(result)}; + } + + void GdalOperationDispatcher::UpdateCompletedResult( + const std::uint64_t operationId, + GdalOperationSnapshot result) + { + std::lock_guard lock(_state->mutex); + const auto operation = _state->operations.find(operationId); + if (operation == _state->operations.end() || + !operation->second->completed) + { + throw std::runtime_error( + "The completed GDAL operation result is not available for update."); + } + + operation->second->result = std::move(result); + } + bool GdalOperationDispatcher::BeginNotificationDelivery( const std::uint64_t operationId) noexcept { diff --git a/src/MapWinGIS.ActiveX/GdalOperationDispatcher.h b/src/MapWinGIS.ActiveX/GdalOperationDispatcher.h index ba94014..f355542 100644 --- a/src/MapWinGIS.ActiveX/GdalOperationDispatcher.h +++ b/src/MapWinGIS.ActiveX/GdalOperationDispatcher.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -90,6 +91,10 @@ namespace mwg::activex using WakeCallback = bool(*)(void*) noexcept; using WorkerFinishedCallback = void(*)(void*) noexcept; + using ProgressCallback = std::function; + using WorkCallback = std::function; static constexpr std::size_t kMaxOutstandingOperations = 16; /// \throws std::bad_alloc when its shared worker state cannot be created. @@ -112,6 +117,11 @@ namespace mwg::activex [[nodiscard]] std::uint64_t Begin( std::string algorithmPath, std::vector arguments); + /// Starts caller-supplied GDAL work on a worker and reports its result. + /// The callback must not access the control or COM objects. + [[nodiscard]] std::uint64_t BeginWork( + WorkCallback work, + bool honorCancellationAtCompletion = false); /// Thread-safe cancellation request; it does not wait for the worker. [[nodiscard]] GdalCancelResult Cancel(std::uint64_t operationId) noexcept; /// Must be called on the owner thread. @@ -119,6 +129,13 @@ namespace mwg::activex /// \throws std::system_error when state locking fails. [[nodiscard]] GdalOperationLookup GetResult( std::uint64_t operationId) const; + /// Reads a result while its owner-thread completion callback is active. + [[nodiscard]] GdalOperationLookup GetResultForDelivery( + std::uint64_t operationId) const; + /// Replaces a completed result before owner-thread notification delivery. + void UpdateCompletedResult( + std::uint64_t operationId, + GdalOperationSnapshot result); /// Must be called on the owner thread. /// \throws std::system_error when state locking fails. [[nodiscard]] GdalOperationLookup End(std::uint64_t operationId); diff --git a/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl b/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl index f0dd283..abaa0e3 100644 --- a/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl +++ b/src/MapWinGIS.ActiveX/MapWinGIS.ActiveX.idl @@ -116,6 +116,35 @@ library MapWinGISActiveXLib HRESULT GetLayerId([in] LONG index, [out, retval] hyper* layerId); }; + [ + object, + dual, + oleautomation, + uuid(4F8CE31A-60D1-4B9D-A4AF-2C80C5F63A91), + pointer_default(unique) + ] + interface IMapWinGISControl5 : IMapWinGISControl4 + { + // The completion notification is GdalOperationCompleted. Call the + // matching End method to retrieve the result and release the slot. + [id(18)] + HRESULT BeginLoadVectorDataset( + [in] BSTR path, + [out, retval] hyper* operationId); + + [id(19)] + HRESULT CancelLoadVectorDataset([in] hyper operationId); + + [id(20)] + HRESULT EndLoadVectorDataset( + [in] hyper operationId, + [out] VARIANT_BOOL* succeeded, + [out] VARIANT_BOOL* cancelled, + [out] hyper* layerId, + [out] BSTR* summary, + [out] BSTR* diagnostics); + }; + // GDAL operations are an independent capability, not a version of the // control's core automation contract. This interface is early-bound only: // SAFEARRAY(BSTR) arguments and hyper operation IDs are not suitable for @@ -176,7 +205,7 @@ library MapWinGISActiveXLib ] coclass MapWinGISControl { - [default] interface IMapWinGISControl4; + [default] interface IMapWinGISControl5; interface IMapWinGISControlGdal; [default, source] dispinterface IMapWinGISControlEvents; }; diff --git a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp index 7c6db2a..ee0ec0e 100644 --- a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp +++ b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp @@ -89,6 +89,56 @@ namespace return S_OK; } + struct PreparedVectorDataset final + { + std::shared_ptr dataset; + mwg::rendering::VectorRenderScene scene; + LONGLONG featureCount = 0; + }; + + [[nodiscard]] PreparedVectorDataset PrepareVectorDataset( + const std::filesystem::path& datasetPath) + { + std::shared_ptr dataset = + mwg::VectorDataset::Open(datasetPath); + if (dataset->LayerCount() == 0) + { + throw mwg::CoreError("Vector dataset contains no layers"); + } + + mwg::Map candidate; + candidate.AddLayer(dataset); + mwg::rendering::MapRenderScene scene = + mwg::rendering::CreateMapRenderScene(candidate); + for (const mwg::rendering::SkippedLayer& skipped : scene.skippedLayers) + { + if (skipped.reason == mwg::rendering::LayerSkipReason::Failed) + { + throw mwg::CoreError(skipped.message); + } + } + + mwg::rendering::VectorRenderScene preparedScene; + if (scene.layers.empty()) + { + preparedScene.sourceFeatureCount = dataset->Layer(0).FeatureCount(); + } + else + { + preparedScene = std::move(scene.layers.front().scene); + } + + if (std::cmp_greater( + preparedScene.sourceFeatureCount, + std::numeric_limits::max())) + { + throw mwg::CoreError("Map feature count is out of range"); + } + const LONGLONG count = + static_cast(preparedScene.sourceFeatureCount); + return {std::move(dataset), std::move(preparedScene), count}; + } + template [[nodiscard]] HRESULT RunViewOperation( Operation&& operation, @@ -153,12 +203,25 @@ namespace } } +struct CMapWinGISControl::VectorLoadState final +{ + std::shared_ptr dataset; + mwg::rendering::VectorRenderScene scene; + LONGLONG featureCount = 0; + LONGLONG layerId = 0; + bool cancelRequestedOnOwner = false; + bool committed = false; +}; + CMapWinGISControl::CMapWinGISControl() : _gdalEvents( m_vec, &CMapWinGISControl::DispatchGdalNotifications, this) { + _gdalEvents.SetCompletionCallback( + &CMapWinGISControl::CompleteVectorLoad, + this); } STDMETHODIMP CMapWinGISControl::Load(IStream* stream) @@ -188,6 +251,7 @@ STDMETHODIMP CMapWinGISControl::InterfaceSupportsErrorInfo(REFIID interfaceId) IsEqualIID(interfaceId, IID_IMapWinGISControl2) || IsEqualIID(interfaceId, IID_IMapWinGISControl3) || IsEqualIID(interfaceId, IID_IMapWinGISControl4) || + IsEqualIID(interfaceId, IID_IMapWinGISControl5) || IsEqualIID(interfaceId, IID_IMapWinGISControlGdal) ? S_OK : S_FALSE; } @@ -265,6 +329,13 @@ STDMETHODIMP CMapWinGISControl::CancelGdalOperation(const LONGLONG operationId) { return SetComErrorInfo("The GDAL operation ID must be positive.", E_INVALIDARG); } + if (_vectorLoadOperations.contains( + static_cast(operationId))) + { + return SetComErrorInfo( + "The operation ID belongs to an asynchronous vector load.", + E_INVALIDARG); + } switch (_gdalEvents.Cancel(static_cast(operationId))) { @@ -298,6 +369,13 @@ STDMETHODIMP CMapWinGISControl::EndGdalOperation( *warnings = nullptr; if (operationId <= 0) return SetComErrorInfo("The GDAL operation ID must be positive.", E_INVALIDARG); + if (_vectorLoadOperations.contains( + static_cast(operationId))) + { + return SetComErrorInfo( + "The operation ID belongs to an asynchronous vector load.", + E_INVALIDARG); + } mwg::activex::GdalOperationLookup ended; try @@ -379,20 +457,33 @@ STDMETHODIMP CMapWinGISControl::LoadVectorDatasetEx( return LoadVectorDatasetImpl(path, layerId, IID_IMapWinGISControl4); } -HRESULT CMapWinGISControl::LoadVectorDatasetImpl( +STDMETHODIMP CMapWinGISControl::BeginLoadVectorDataset( BSTR path, - LONGLONG* layerId, - REFIID sourceIid) + LONGLONG* operationId) { + if (operationId == nullptr) + { + return SetControlComErrorInfo( + "The operation ID output pointer is null.", + IID_IMapWinGISControl5, + E_POINTER); + } + *operationId = 0; if (path == nullptr) { - return SetControlComErrorInfo("The dataset path is null.", sourceIid, E_INVALIDARG); + return SetControlComErrorInfo( + "The dataset path is null.", + IID_IMapWinGISControl5, + E_INVALIDARG); } const UINT pathLength = ::SysStringLen(path); if (pathLength == 0) { - return SetControlComErrorInfo("The dataset path is empty.", sourceIid, E_INVALIDARG); + return SetControlComErrorInfo( + "The dataset path is empty.", + IID_IMapWinGISControl5, + E_INVALIDARG); } try @@ -400,44 +491,511 @@ HRESULT CMapWinGISControl::LoadVectorDatasetImpl( const std::wstring pathText(path, static_cast(pathLength)); if (pathText.find(L'\0') != std::wstring::npos) { - return SetControlComErrorInfo("The dataset path contains an embedded null character.", sourceIid, E_INVALIDARG); + return SetControlComErrorInfo( + "The dataset path contains an embedded null character.", + IID_IMapWinGISControl5, + E_INVALIDARG); } - const std::filesystem::path datasetPath(pathText); - std::shared_ptr dataset = mwg::VectorDataset::Open(datasetPath); - if (dataset->LayerCount() == 0) + const HRESULT windowResult = _gdalEvents.EnsureDispatchWindow(); + if (FAILED(windowResult)) { - throw mwg::CoreError("Vector dataset contains no layers"); + return SetControlComErrorInfo( + "The GDAL notification window could not be created.", + IID_IMapWinGISControl5, + windowResult); } - // Validate before AddLayer can auto-fit or schedule a pending fit. - mwg::Map candidate; - candidate.AddLayer(dataset); - mwg::rendering::MapRenderScene scene = - mwg::rendering::CreateMapRenderScene(candidate); - for (const mwg::rendering::SkippedLayer& skipped : scene.skippedLayers) + auto state = std::make_shared(); + _vectorLoadOperations.reserve(_vectorLoadOperations.size() + 1); + const auto [placeholder, inserted] = + _vectorLoadOperations.emplace(0, state); + if (!inserted) { - if (skipped.reason == mwg::rendering::LayerSkipReason::Failed) + return SetControlComErrorInfo( + "A vector dataset load is already being prepared.", + IID_IMapWinGISControl5, + E_UNEXPECTED); + } + + std::uint64_t id = 0; + try + { + const std::filesystem::path datasetPath(pathText); + id = _gdalEvents.BeginWork( + [state, datasetPath]( + mwg::GdalCancellationToken& cancellation, + const mwg::activex::GdalOperationDispatcher::ProgressCallback&) + { + mwg::activex::GdalOperationSnapshot result; + if (cancellation.IsCancellationRequested()) + { + result.cancelled = true; + result.summary = "Vector dataset loading was cancelled."; + return result; + } + + try + { + PreparedVectorDataset prepared = + PrepareVectorDataset(datasetPath); + if (cancellation.IsCancellationRequested()) + { + result.cancelled = true; + result.summary = + "Vector dataset loading was cancelled."; + return result; + } + + state->dataset = std::move(prepared.dataset); + state->scene = std::move(prepared.scene); + state->featureCount = prepared.featureCount; + result.succeeded = true; + result.summary = "Vector dataset loaded."; + return result; + } + catch (const std::bad_alloc&) + { + throw; + } + catch (const std::exception& exception) + { + result.summary = exception.what(); + result.diagnostics = result.summary; + return result; + } + catch (...) + { + result.summary = + "An unexpected error occurred while loading the vector dataset."; + result.diagnostics = result.summary; + return result; + } + }); + } + catch (...) + { + _vectorLoadOperations.erase(placeholder); + throw; + } + + auto operation = _vectorLoadOperations.extract(placeholder); + operation.key() = id; + _vectorLoadOperations.insert(std::move(operation)); + *operationId = static_cast(id); + return S_OK; + } + catch (const std::bad_alloc&) + { + return SetControlComErrorInfo( + "Out of memory while starting the vector dataset load.", + IID_IMapWinGISControl5, + E_OUTOFMEMORY); + } + catch (const std::exception& exception) + { + return SetControlComErrorInfo( + exception.what(), + IID_IMapWinGISControl5, + E_FAIL); + } + catch (...) + { + return SetControlComErrorInfo( + "An unexpected error occurred while starting the vector dataset load.", + IID_IMapWinGISControl5, + E_UNEXPECTED); + } +} + +STDMETHODIMP CMapWinGISControl::CancelLoadVectorDataset( + const LONGLONG operationId) +{ + if (operationId <= 0) + { + return SetControlComErrorInfo( + "The vector load operation ID must be positive.", + IID_IMapWinGISControl5, + E_INVALIDARG); + } + + const auto found = _vectorLoadOperations.find( + static_cast(operationId)); + if (found == _vectorLoadOperations.end()) + { + return SetControlComErrorInfo( + "The vector load operation ID was not found.", + IID_IMapWinGISControl5, + E_INVALIDARG); + } + switch (_gdalEvents.Cancel(static_cast(operationId))) + { + case mwg::activex::GdalCancelResult::Requested: + return S_OK; + case mwg::activex::GdalCancelResult::Completed: + if (!found->second->committed) + { + try { - throw mwg::CoreError(skipped.message); + const mwg::activex::GdalOperationLookup completed = + _gdalEvents.GetResult( + static_cast(operationId)); + if (completed.status == mwg::activex::GdalEndResult::Ended && + completed.result.has_value() && + completed.result->succeeded && + !completed.result->cancelled) + { + found->second->cancelRequestedOnOwner = true; + return S_OK; + } + } + catch (const std::bad_alloc&) + { + return SetControlComErrorInfo( + "Out of memory while checking the vector load result.", + IID_IMapWinGISControl5, + E_OUTOFMEMORY); + } + catch (...) + { + return SetControlComErrorInfo( + "The vector load result could not be checked.", + IID_IMapWinGISControl5, + E_FAIL); } } - mwg::rendering::VectorRenderScene preparedScene; - if (scene.layers.empty()) + return S_FALSE; + case mwg::activex::GdalCancelResult::AlreadyRequested: + return S_FALSE; + case mwg::activex::GdalCancelResult::NotFound: + default: + return SetControlComErrorInfo( + "The vector load operation ID was not found.", + IID_IMapWinGISControl5, + E_INVALIDARG); + } +} + +STDMETHODIMP CMapWinGISControl::EndLoadVectorDataset( + const LONGLONG operationId, + VARIANT_BOOL* succeeded, + VARIANT_BOOL* cancelled, + LONGLONG* layerId, + BSTR* summary, + BSTR* diagnostics) +{ + if (succeeded == nullptr || cancelled == nullptr || layerId == nullptr || + summary == nullptr || diagnostics == nullptr) + { + return SetControlComErrorInfo( + "One or more vector load result output pointers are null.", + IID_IMapWinGISControl5, + E_POINTER); + } + *succeeded = VARIANT_FALSE; + *cancelled = VARIANT_FALSE; + *layerId = 0; + *summary = nullptr; + *diagnostics = nullptr; + if (operationId <= 0) + { + return SetControlComErrorInfo( + "The vector load operation ID must be positive.", + IID_IMapWinGISControl5, + E_INVALIDARG); + } + + const auto found = _vectorLoadOperations.find( + static_cast(operationId)); + if (found == _vectorLoadOperations.end()) + { + return SetControlComErrorInfo( + "The vector load operation ID was not found.", + IID_IMapWinGISControl5, + E_INVALIDARG); + } + + mwg::activex::GdalOperationLookup ended; + try + { + ended = _gdalEvents.End(static_cast(operationId)); + } + catch (const std::bad_alloc&) + { + return SetControlComErrorInfo( + "Out of memory while retrieving the vector load result.", + IID_IMapWinGISControl5, + E_OUTOFMEMORY); + } + catch (const std::exception& exception) + { + return SetControlComErrorInfo( + exception.what(), + IID_IMapWinGISControl5, + E_FAIL); + } + catch (...) + { + return SetControlComErrorInfo( + "An unexpected error occurred while retrieving the vector load result.", + IID_IMapWinGISControl5, + E_UNEXPECTED); + } + + if (ended.status == mwg::activex::GdalEndResult::Pending) + { + return SetControlComErrorInfo( + "The vector load has not finished or is still delivering events.", + IID_IMapWinGISControl5, + E_PENDING); + } + if (ended.status != mwg::activex::GdalEndResult::Ended || + !ended.result.has_value()) + { + _vectorLoadOperations.erase(found); + return SetControlComErrorInfo( + "The vector load operation ID was not found.", + IID_IMapWinGISControl5, + E_INVALIDARG); + } + + const auto state = found->second; + _vectorLoadOperations.erase(found); + BSTR summaryText = nullptr; + BSTR diagnosticText = nullptr; + HRESULT result = DiagnosticToBstr(ended.result->summary, &summaryText); + if (SUCCEEDED(result)) + { + result = DiagnosticToBstr(ended.result->diagnostics, &diagnosticText); + } + if (FAILED(result)) + { + ::SysFreeString(summaryText); + ::SysFreeString(diagnosticText); + return SetControlComErrorInfo( + "The completed vector load result could not be marshalled to COM.", + IID_IMapWinGISControl5, + result); + } + + *succeeded = ended.result->succeeded ? VARIANT_TRUE : VARIANT_FALSE; + *cancelled = ended.result->cancelled ? VARIANT_TRUE : VARIANT_FALSE; + *layerId = state->committed ? state->layerId : 0; + *summary = summaryText; + *diagnostics = diagnosticText; + return S_OK; +} + +void CMapWinGISControl::CompleteVectorLoad( + void* const context, + const std::uint64_t operationId) noexcept +{ + static_cast(context)->CompleteVectorLoad(operationId); +} + +void CMapWinGISControl::CompleteVectorLoad( + const std::uint64_t operationId) noexcept +{ + const auto found = _vectorLoadOperations.find(operationId); + if (found == _vectorLoadOperations.end()) + { + return; + } + + mwg::activex::GdalOperationSnapshot result; + try + { + const mwg::activex::GdalOperationLookup completed = + _gdalEvents.GetResultForDelivery(operationId); + if (completed.status != mwg::activex::GdalEndResult::Ended || + !completed.result.has_value()) { - preparedScene.sourceFeatureCount = dataset->Layer(0).FeatureCount(); + return; } - else + result = *completed.result; + const auto& state = found->second; + if (state->cancelRequestedOnOwner) { - preparedScene = std::move(scene.layers.front().scene); + result.succeeded = false; + result.cancelled = true; + result.summary = "Vector dataset loading was cancelled."; + result.diagnostics.clear(); + state->dataset.reset(); + state->scene = {}; + state->featureCount = 0; + _gdalEvents.UpdateCompletedResult(operationId, std::move(result)); + return; + } + if (result.cancelled) + { + result.succeeded = false; + result.summary = "Vector dataset loading was cancelled."; + result.diagnostics.clear(); + state->dataset.reset(); + state->scene = {}; + state->featureCount = 0; + _gdalEvents.UpdateCompletedResult(operationId, std::move(result)); + return; + } + if (!result.succeeded) + { + state->dataset.reset(); + state->scene = {}; + state->featureCount = 0; + return; } - const LONGLONG count = static_cast(preparedScene.sourceFeatureCount); - if (count < 0 || count > std::numeric_limits::max() - _featureCount) + + if (state->featureCount > + std::numeric_limits::max() - _featureCount) + { + throw mwg::CoreError("Map feature count is out of range"); + } + const mwg::LayerId id = _view.AddLayer( + std::move(state->dataset), + std::move(state->scene)); + LONGLONG convertedId = 0; + if (FAILED(CopyLayerId(id, &convertedId))) + { + (void)_view.RemoveLayer(id); + throw mwg::CoreError("The layer ID could not be represented as a COM integer."); + } + try + { + (void)_view.FitToMap(); + } + catch (...) + { + (void)_view.RemoveLayer(id); + throw; + } + + _featureCount += state->featureCount; + state->layerId = convertedId; + state->committed = true; + state->featureCount = 0; + InvalidateLayerCache(); + FireViewChange(); + } + catch (const std::bad_alloc&) + { + result.succeeded = false; + result.cancelled = false; + result.summary.clear(); + result.diagnostics.clear(); + try + { + result.summary = "Out of memory while committing the vector dataset."; + result.diagnostics = result.summary; + } + catch (...) + { + } + found->second->dataset.reset(); + found->second->scene = {}; + found->second->featureCount = 0; + try + { + _gdalEvents.UpdateCompletedResult(operationId, std::move(result)); + } + catch (...) + { + ::OutputDebugStringW( + L"MapWinGIS: unable to retain the vector load commit failure.\n"); + } + } + catch (const std::exception& exception) + { + result.succeeded = false; + result.cancelled = false; + try + { + result.summary = exception.what(); + result.diagnostics = result.summary; + } + catch (...) + { + result.summary.clear(); + result.diagnostics.clear(); + } + found->second->dataset.reset(); + found->second->scene = {}; + found->second->featureCount = 0; + try + { + _gdalEvents.UpdateCompletedResult(operationId, std::move(result)); + } + catch (...) + { + ::OutputDebugStringW( + L"MapWinGIS: unable to retain the vector load commit failure.\n"); + } + } + catch (...) + { + result.succeeded = false; + result.cancelled = false; + try + { + result.summary = + "An unexpected error occurred while committing the vector dataset."; + result.diagnostics = result.summary; + } + catch (...) + { + result.summary.clear(); + result.diagnostics.clear(); + } + found->second->dataset.reset(); + found->second->scene = {}; + found->second->featureCount = 0; + try + { + _gdalEvents.UpdateCompletedResult(operationId, std::move(result)); + } + catch (...) + { + ::OutputDebugStringW( + L"MapWinGIS: unable to retain the vector load commit failure.\n"); + } + } +} + +HRESULT CMapWinGISControl::LoadVectorDatasetImpl( + BSTR path, + LONGLONG* layerId, + REFIID sourceIid) +{ + if (path == nullptr) + { + return SetControlComErrorInfo("The dataset path is null.", sourceIid, E_INVALIDARG); + } + + const UINT pathLength = ::SysStringLen(path); + if (pathLength == 0) + { + return SetControlComErrorInfo("The dataset path is empty.", sourceIid, E_INVALIDARG); + } + + try + { + const std::wstring pathText(path, static_cast(pathLength)); + if (pathText.find(L'\0') != std::wstring::npos) + { + return SetControlComErrorInfo("The dataset path contains an embedded null character.", sourceIid, E_INVALIDARG); + } + + // Validate before AddLayer can auto-fit or schedule a pending fit. + PreparedVectorDataset prepared = + PrepareVectorDataset(std::filesystem::path(pathText)); + if (prepared.featureCount > + std::numeric_limits::max() - _featureCount) { throw mwg::CoreError("Map feature count is out of range"); } - const mwg::LayerId id = _view.AddLayer(std::move(dataset), std::move(preparedScene)); + const mwg::LayerId id = _view.AddLayer( + std::move(prepared.dataset), + std::move(prepared.scene)); LONGLONG convertedId = 0; if (layerId != nullptr && FAILED(CopyLayerId(id, &convertedId))) { @@ -455,7 +1013,7 @@ HRESULT CMapWinGISControl::LoadVectorDatasetImpl( throw; } - _featureCount += count; + _featureCount += prepared.featureCount; if (layerId != nullptr) { *layerId = convertedId; @@ -1065,6 +1623,7 @@ STDMETHODIMP CMapWinGISControl::Close(const DWORD saveOption) { CancelMousePan(); _gdalEvents.Close(); + _vectorLoadOperations.clear(); const HRESULT result = ATL::IOleObjectImpl::Close(saveOption); return FAILED(result) ? SetControlComErrorInfo("The ActiveX control could not be closed.", IID_IMapWinGISControl4, result) diff --git a/src/MapWinGIS.ActiveX/MapWinGISControl.h b/src/MapWinGIS.ActiveX/MapWinGISControl.h index accb969..1082c5c 100644 --- a/src/MapWinGIS.ActiveX/MapWinGISControl.h +++ b/src/MapWinGIS.ActiveX/MapWinGISControl.h @@ -14,6 +14,8 @@ #include "resource.h" #include +#include +#include #include #include @@ -56,8 +58,8 @@ class ATL_NO_VTABLE CMapWinGISControl : // Load the default dispatch type information from this OCX, not a // potentially older registered copy of the same type library. public ATL::IDispatchImpl< - IMapWinGISControl4, - &IID_IMapWinGISControl4, + IMapWinGISControl5, + &IID_IMapWinGISControl5, &LIBID_MapWinGISActiveXLib, 0xFFFF, 0xFFFF>, @@ -76,6 +78,7 @@ class ATL_NO_VTABLE CMapWinGISControl : DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CMapWinGISControl) + COM_INTERFACE_ENTRY(IMapWinGISControl5) COM_INTERFACE_ENTRY(IMapWinGISControl4) COM_INTERFACE_ENTRY(IMapWinGISControl3) COM_INTERFACE_ENTRY(IMapWinGISControl2) @@ -86,7 +89,7 @@ class ATL_NO_VTABLE CMapWinGISControl : COM_INTERFACE_ENTRY(IProvideClassInfo2) COM_INTERFACE_ENTRY(IPersistPropertyBag) COM_INTERFACE_ENTRY(IConnectionPointContainer) - COM_INTERFACE_ENTRY2(IDispatch, IMapWinGISControl4) + COM_INTERFACE_ENTRY2(IDispatch, IMapWinGISControl5) COM_INTERFACE_ENTRY(IViewObjectEx) COM_INTERFACE_ENTRY(IViewObject2) COM_INTERFACE_ENTRY(IViewObject) @@ -143,6 +146,15 @@ class ATL_NO_VTABLE CMapWinGISControl : STDMETHOD(ZoomToLayer)(LONGLONG layerId) override; STDMETHOD(get_LayerCount)(LONG* count) override; STDMETHOD(LoadVectorDatasetEx)(BSTR path, LONGLONG* layerId) override; + STDMETHOD(BeginLoadVectorDataset)(BSTR path, LONGLONG* operationId) override; + STDMETHOD(CancelLoadVectorDataset)(LONGLONG operationId) override; + STDMETHOD(EndLoadVectorDataset)( + LONGLONG operationId, + VARIANT_BOOL* succeeded, + VARIANT_BOOL* cancelled, + LONGLONG* layerId, + BSTR* summary, + BSTR* diagnostics) override; STDMETHOD(GetLayerId)(LONG index, LONGLONG* layerId) override; STDMETHOD(BeginGdalOperation)( BSTR algorithmPath, @@ -181,7 +193,10 @@ class ATL_NO_VTABLE CMapWinGISControl : private: friend class mwg::activex::testing::MapWinGISControlTestAccess; + struct VectorLoadState; HRESULT LoadVectorDatasetImpl(BSTR path, LONGLONG* layerId, REFIID sourceIid); + static void CompleteVectorLoad(void* context, std::uint64_t operationId) noexcept; + void CompleteVectorLoad(std::uint64_t operationId) noexcept; /// Resizes the view to a host size, clamped to the supported range, and /// returns true when the frame must be redrawn. @@ -234,6 +249,9 @@ class ATL_NO_VTABLE CMapWinGISControl : bool _layerCacheValid = false; mwg::activex::VectorLayerRenderer _renderer; mwg::activex::GdalEventSource _gdalEvents; + std::unordered_map< + std::uint64_t, + std::shared_ptr> _vectorLoadOperations; POINT _lastPanPoint{}; bool _isPanning = false; }; diff --git a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp index 592b47e..cb35d96 100644 --- a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp @@ -287,6 +287,50 @@ namespace void* _completionContext = nullptr; }; + class GdalEventSubscription final + { + public: + explicit GdalEventSubscription(IUnknown* control) + { + ATL::CComQIPtr connectionPoints(control); + if (connectionPoints == nullptr) + { + _result = E_NOINTERFACE; + return; + } + _result = connectionPoints->FindConnectionPoint( + __uuidof(IMapWinGISControlEvents), + &_connectionPoint); + if (FAILED(_result)) + { + return; + } + + _sink.Attach(new GdalEventSink()); + _result = _connectionPoint->Advise(_sink.Get(), &_cookie); + } + + ~GdalEventSubscription() + { + if (_connectionPoint != nullptr && _cookie != 0) + { + _connectionPoint->Unadvise(_cookie); + } + } + + GdalEventSubscription(const GdalEventSubscription&) = delete; + GdalEventSubscription& operator=(const GdalEventSubscription&) = delete; + + [[nodiscard]] HRESULT Result() const noexcept { return _result; } + [[nodiscard]] GdalEventSink* Sink() const noexcept { return _sink.Get(); } + + private: + ATL::CComPtr _connectionPoint; + ComPtr _sink; + DWORD _cookie = 0; + HRESULT _result = E_FAIL; + }; + class HostedProgressAlgorithm final : public GDALAlgorithm { public: @@ -956,6 +1000,188 @@ TEST_F(ActiveXMapTest, LoadsStackAndClearReleasesTheDatasets) EXPECT_EQ(count, 1); } +TEST_F(ActiveXMapTest, LoadsVectorDatasetAsynchronouslyAndCommitsBeforeCompletionEvent) +{ + ComPtr control; + ASSERT_EQ(_control.As(&control), S_OK); + GdalEventSubscription subscription(control.Get()); + ASSERT_EQ(subscription.Result(), S_OK); + + const std::vector rectangles{{0, 0, 2, 2}, {3, 0, 5, 2}}; + const auto path = mwg::test::MakeRectanglesDataset( + _directory.Path(), + "async-load.gpkg", + rectangles); + LONGLONG operationId = 0; + ASSERT_EQ(control->BeginLoadVectorDataset( + ATL::CComBSTR(path.c_str()), + &operationId), S_OK); + ASSERT_GT(operationId, 0); + + LONG layerCount = -1; + ASSERT_EQ(control->get_LayerCount(&layerCount), S_OK); + EXPECT_EQ(layerCount, 0); + ASSERT_TRUE(PumpUntilGdalCompletion( + *subscription.Sink(), + operationId, + std::chrono::steady_clock::now() + std::chrono::seconds(10))); + EXPECT_TRUE(subscription.Sink()->WasDeliveredOn(std::this_thread::get_id())); + + VARIANT_BOOL succeeded = VARIANT_FALSE; + VARIANT_BOOL cancelled = VARIANT_TRUE; + LONGLONG layerId = 0; + BSTR rawSummary = nullptr; + BSTR rawDiagnostics = nullptr; + ASSERT_EQ(control->EndLoadVectorDataset( + operationId, + &succeeded, + &cancelled, + &layerId, + &rawSummary, + &rawDiagnostics), S_OK); + std::unique_ptr summary( + rawSummary, + &SysFreeString); + std::unique_ptr diagnostics( + rawDiagnostics, + &SysFreeString); + EXPECT_EQ(succeeded, VARIANT_TRUE); + EXPECT_EQ(cancelled, VARIANT_FALSE); + EXPECT_GT(layerId, 0); + ASSERT_NE(summary, nullptr); + EXPECT_NE(std::wstring(summary.get()).find(L"loaded"), std::wstring::npos); + ASSERT_EQ(control->get_LayerCount(&layerCount), S_OK); + EXPECT_EQ(layerCount, 1); + LONGLONG featureCount = 0; + ASSERT_EQ(_control->get_FeatureCount(&featureCount), S_OK); + EXPECT_EQ(featureCount, 2); +} + +TEST_F(ActiveXMapTest, CancellingVectorDatasetLoadLeavesTheMapUnchanged) +{ + ComPtr control; + ASSERT_EQ(_control.As(&control), S_OK); + GdalEventSubscription subscription(control.Get()); + ASSERT_EQ(subscription.Result(), S_OK); + + const std::vector rectangles{{0, 0, 2, 2}}; + const auto path = mwg::test::MakeRectanglesDataset( + _directory.Path(), + "async-cancel.gpkg", + rectangles); + LONGLONG operationId = 0; + ASSERT_EQ(control->BeginLoadVectorDataset( + ATL::CComBSTR(path.c_str()), + &operationId), S_OK); + ASSERT_GT(operationId, 0); + EXPECT_EQ(control->CancelLoadVectorDataset(operationId), S_OK); + ASSERT_TRUE(PumpUntilGdalCompletion( + *subscription.Sink(), + operationId, + std::chrono::steady_clock::now() + std::chrono::seconds(10))); + + VARIANT_BOOL succeeded = VARIANT_TRUE; + VARIANT_BOOL cancelled = VARIANT_FALSE; + LONGLONG layerId = -1; + BSTR summary = nullptr; + BSTR diagnostics = nullptr; + ASSERT_EQ(control->EndLoadVectorDataset( + operationId, + &succeeded, + &cancelled, + &layerId, + &summary, + &diagnostics), S_OK); + ::SysFreeString(summary); + ::SysFreeString(diagnostics); + EXPECT_EQ(succeeded, VARIANT_FALSE); + EXPECT_EQ(cancelled, VARIANT_TRUE); + EXPECT_EQ(layerId, 0); + LONG layerCount = -1; + ASSERT_EQ(control->get_LayerCount(&layerCount), S_OK); + EXPECT_EQ(layerCount, 0); + LONGLONG featureCount = -1; + ASSERT_EQ(_control->get_FeatureCount(&featureCount), S_OK); + EXPECT_EQ(featureCount, 0); +} + +TEST_F(ActiveXMapTest, FailedVectorDatasetLoadReportsThePath) +{ + ComPtr control; + ASSERT_EQ(_control.As(&control), S_OK); + GdalEventSubscription subscription(control.Get()); + ASSERT_EQ(subscription.Result(), S_OK); + const auto path = _directory.Path() / "missing.gpkg"; + const mwg::GdalEnvironment::QuietScope quiet; + + LONGLONG operationId = 0; + ASSERT_EQ(control->BeginLoadVectorDataset( + ATL::CComBSTR(path.c_str()), + &operationId), S_OK); + ASSERT_TRUE(PumpUntilGdalCompletion( + *subscription.Sink(), + operationId, + std::chrono::steady_clock::now() + std::chrono::seconds(10))); + + VARIANT_BOOL succeeded = VARIANT_TRUE; + VARIANT_BOOL cancelled = VARIANT_TRUE; + LONGLONG layerId = -1; + BSTR rawSummary = nullptr; + BSTR rawDiagnostics = nullptr; + ASSERT_EQ(control->EndLoadVectorDataset( + operationId, + &succeeded, + &cancelled, + &layerId, + &rawSummary, + &rawDiagnostics), S_OK); + std::unique_ptr summary( + rawSummary, + &SysFreeString); + std::unique_ptr diagnostics( + rawDiagnostics, + &SysFreeString); + EXPECT_EQ(succeeded, VARIANT_FALSE); + EXPECT_EQ(cancelled, VARIANT_FALSE); + EXPECT_EQ(layerId, 0); + ASSERT_NE(summary, nullptr); + EXPECT_NE(std::wstring(summary.get()).find(path.filename().wstring()), std::wstring::npos); + ASSERT_NE(diagnostics, nullptr); + EXPECT_NE(std::wstring(diagnostics.get()).find(path.filename().wstring()), std::wstring::npos); + LONG layerCount = -1; + ASSERT_EQ(control->get_LayerCount(&layerCount), S_OK); + EXPECT_EQ(layerCount, 0); +} + +TEST_F(ActiveXMapTest, DestroyingControlDuringVectorLoadDoesNotAccessTheControlFromWorker) +{ + using GetClassObject = HRESULT(STDAPICALLTYPE*)(REFCLSID, REFIID, LPVOID*); + const auto getClassObject = reinterpret_cast( + GetProcAddress(_module->Get(), "DllGetClassObject")); + ASSERT_NE(getClassObject, nullptr); + ComPtr factory; + ASSERT_EQ(getClassObject( + __uuidof(MapWinGISControl), + IID_PPV_ARGS(&factory)), S_OK); + ComPtr control; + ASSERT_EQ(factory->CreateInstance( + nullptr, + IID_PPV_ARGS(&control)), S_OK); + + const std::vector rectangles{{0, 0, 2, 2}}; + const auto path = mwg::test::MakeRectanglesDataset( + _directory.Path(), + "async-destroy.gpkg", + rectangles); + LONGLONG operationId = 0; + ASSERT_EQ(control->BeginLoadVectorDataset( + ATL::CComBSTR(path.c_str()), + &operationId), S_OK); + ASSERT_GT(operationId, 0); + control.Reset(); + Sleep(50); +} + TEST_F(ActiveXMapTest, ExposesStableLayerIdsAndMapNavigation) { constexpr int width = 120; @@ -1138,10 +1364,12 @@ TEST_F(ActiveXMapTest, PreservesDispatchIdsAndInterfaceIdentity) ComPtr second; ComPtr third; ComPtr fourth; + ComPtr fifth; ASSERT_EQ(_control.As(&first), S_OK); ASSERT_EQ(_control.As(&second), S_OK); ASSERT_EQ(_control.As(&third), S_OK); ASSERT_EQ(_control.As(&fourth), S_OK); + ASSERT_EQ(_control.As(&fifth), S_OK); ComPtr identity; ASSERT_EQ(fourth.As(&identity), S_OK); ComPtr other; @@ -1153,6 +1381,9 @@ TEST_F(ActiveXMapTest, PreservesDispatchIdsAndInterfaceIdentity) other.Reset(); ASSERT_EQ(third.As(&other), S_OK); EXPECT_EQ(identity.Get(), other.Get()); + other.Reset(); + ASSERT_EQ(fifth.As(&other), S_OK); + EXPECT_EQ(identity.Get(), other.Get()); const IID firstIid{0x1B6D4167, 0xB2D7, 0x4AE4, {0x8F, 0x88, 0x92, 0xC5, 0x75, 0xBF, 0x4A, 0xF7}}; const IID secondIid{0x2C386A29, 0xC378, 0x45C1, {0xB8, 0xD5, 0x56, 0x24, 0x50, 0x0C, 0xCF, 0xF2}}; @@ -1160,6 +1391,8 @@ TEST_F(ActiveXMapTest, PreservesDispatchIdsAndInterfaceIdentity) EXPECT_TRUE(IsEqualIID(__uuidof(IMapWinGISControl), firstIid)); EXPECT_TRUE(IsEqualIID(__uuidof(IMapWinGISControl2), secondIid)); EXPECT_TRUE(IsEqualIID(__uuidof(IMapWinGISControl3), thirdIid)); + const IID fifthIid{0x4F8CE31A, 0x60D1, 0x4B9D, {0xA4, 0xAF, 0x2C, 0x80, 0xC5, 0xF6, 0x3A, 0x91}}; + EXPECT_TRUE(IsEqualIID(__uuidof(IMapWinGISControl5), fifthIid)); ComPtr dispatch; ASSERT_EQ(_control.As(&dispatch), S_OK); @@ -1168,7 +1401,9 @@ TEST_F(ActiveXMapTest, PreservesDispatchIdsAndInterfaceIdentity) {L"LoadVectorDataset", 2}, {L"FitToMap", 9}, {L"ZoomIn", 10}, {L"ZoomOut", 11}, {L"Pan", 12}, {L"ZoomAt", 13}, {L"ZoomToLayer", 14}, {L"LayerCount", 15}, - {L"LoadVectorDatasetEx", 16}, {L"GetLayerId", 17}}; + {L"LoadVectorDatasetEx", 16}, {L"GetLayerId", 17}, + {L"BeginLoadVectorDataset", 18}, {L"CancelLoadVectorDataset", 19}, + {L"EndLoadVectorDataset", 20}}; for (const auto& member : members) { std::wstring name(member.name); From a1f0b70c5fcde15c2eccf1b6fc04badc7849c08b Mon Sep 17 00:00:00 2001 From: Paul Meems Date: Sun, 15 Nov 2026 21:25:29 +0100 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20fix(activex):=20finalize=20a?= =?UTF-8?q?sync=20vector=20loads=20before=20reporting=20completion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Wait for owner-thread finalization before consuming results - Ignore replayed completions after a layer is committed - Verify notification ordering and control destruction with deterministic tests Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/MapWinGIS.ActiveX/MapWinGISControl.cpp | 59 +++- .../ActiveXActivationTests.cpp | 291 +++++++++++++++++- 2 files changed, 345 insertions(+), 5 deletions(-) diff --git a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp index ee0ec0e..ac105fb 100644 --- a/src/MapWinGIS.ActiveX/MapWinGISControl.cpp +++ b/src/MapWinGIS.ActiveX/MapWinGISControl.cpp @@ -25,6 +25,7 @@ #include #include +#include #include #include #include @@ -48,6 +49,9 @@ OBJECT_ENTRY_AUTO(CLSID_MapWinGISControl, CMapWinGISControl) namespace { constexpr double kMouseWheelZoomFactor = 1.2; + using VectorPreparationHook = void(*)(void*, bool) noexcept; + std::atomic g_vectorPreparationHook{nullptr}; + std::atomic g_vectorPreparationContext{nullptr}; using mwg::activex::ComConversion::BstrToUtf8; using mwg::activex::ComConversion::CopyStringArray; @@ -203,6 +207,15 @@ namespace } } +extern "C" __declspec(dllexport) void __cdecl +MapWinGISControlSetVectorPreparationHookForTesting( + void(*const hook)(void*, bool) noexcept, + void* const context) noexcept +{ + g_vectorPreparationContext.store(context, std::memory_order_relaxed); + g_vectorPreparationHook.store(hook, std::memory_order_release); +} + struct CMapWinGISControl::VectorLoadState final { std::shared_ptr dataset; @@ -211,6 +224,7 @@ struct CMapWinGISControl::VectorLoadState final LONGLONG layerId = 0; bool cancelRequestedOnOwner = false; bool committed = false; + bool ownerFinalized = false; }; CMapWinGISControl::CMapWinGISControl() @@ -537,6 +551,28 @@ STDMETHODIMP CMapWinGISControl::BeginLoadVectorDataset( try { + const auto preparationHook = + g_vectorPreparationHook.load(std::memory_order_acquire); + void* const preparationContext = + g_vectorPreparationContext.load(std::memory_order_relaxed); + struct PreparationFinishedNotification final + { + VectorPreparationHook hook; + void* context; + + ~PreparationFinishedNotification() + { + if (hook != nullptr) + { + hook(context, true); + } + } + } preparationFinished{preparationHook, preparationContext}; + if (preparationHook != nullptr) + { + preparationHook(preparationContext, false); + } + PreparedVectorDataset prepared = PrepareVectorDataset(datasetPath); if (cancellation.IsCancellationRequested()) @@ -714,6 +750,13 @@ STDMETHODIMP CMapWinGISControl::EndLoadVectorDataset( IID_IMapWinGISControl5, E_INVALIDARG); } + if (!found->second->ownerFinalized) + { + return SetControlComErrorInfo( + "The vector load has not finished or is still delivering events.", + IID_IMapWinGISControl5, + E_PENDING); + } mwg::activex::GdalOperationLookup ended; try @@ -801,6 +844,21 @@ void CMapWinGISControl::CompleteVectorLoad( { return; } + const auto& state = found->second; + if (state->committed) + { + return; + } + + struct OwnerFinalizationGuard final + { + bool& finalized; + + ~OwnerFinalizationGuard() + { + finalized = true; + } + } ownerFinalization{state->ownerFinalized}; mwg::activex::GdalOperationSnapshot result; try @@ -813,7 +871,6 @@ void CMapWinGISControl::CompleteVectorLoad( return; } result = *completed.result; - const auto& state = found->second; if (state->cancelRequestedOnOwner) { result.succeeded = false; diff --git a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp index cb35d96..14d6664 100644 --- a/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp +++ b/tests/MapWinGIS.ActiveX.Tests/ActiveXActivationTests.cpp @@ -45,6 +45,9 @@ namespace { using Microsoft::WRL::ComPtr; + using VectorPreparationHook = void(*)(void*, bool) noexcept; + using VectorPreparationHookSetter = + void(__cdecl*)(VectorPreparationHook, void*) noexcept; [[nodiscard]] std::string ToUtf8(const std::filesystem::path& path) { @@ -259,6 +262,15 @@ namespace operationId) != _completedOperations.end(); } + [[nodiscard]] std::size_t CompletionCount(const LONGLONG operationId) const + { + std::lock_guard lock(_mutex); + return static_cast(std::count( + _completedOperations.begin(), + _completedOperations.end(), + operationId)); + } + [[nodiscard]] bool HasProgress(const LONGLONG operationId) const { std::lock_guard lock(_mutex); @@ -287,6 +299,137 @@ namespace void* _completionContext = nullptr; }; + struct VectorLoadCompletionObservation final + { + IMapWinGISControl5* control = nullptr; + HRESULT layerCountResult = E_FAIL; + HRESULT featureCountResult = E_FAIL; + LONG layerCount = -1; + LONGLONG featureCount = -1; + + static HRESULT Observe(void* const context, LONGLONG) + { + auto& observation = + *static_cast(context); + observation.layerCountResult = + observation.control->get_LayerCount(&observation.layerCount); + observation.featureCountResult = + observation.control->get_FeatureCount(&observation.featureCount); + return S_OK; + } + }; + + class ScopedEvent final + { + public: + ScopedEvent() noexcept + : _handle(CreateEventW(nullptr, TRUE, FALSE, nullptr)) + { + } + + ~ScopedEvent() + { + if (_handle != nullptr) + { + CloseHandle(_handle); + } + } + + ScopedEvent(const ScopedEvent&) = delete; + ScopedEvent& operator=(const ScopedEvent&) = delete; + + [[nodiscard]] bool IsValid() const noexcept { return _handle != nullptr; } + [[nodiscard]] HANDLE Get() const noexcept { return _handle; } + + [[nodiscard]] bool Signal() const noexcept + { + return _handle != nullptr && SetEvent(_handle) != FALSE; + } + + [[nodiscard]] bool Wait(const DWORD timeout) const noexcept + { + return _handle != nullptr && + WaitForSingleObject(_handle, timeout) == WAIT_OBJECT_0; + } + + private: + HANDLE _handle = nullptr; + }; + + class VectorPreparationBarrier final + { + public: + ~VectorPreparationBarrier() + { + if (_started.Wait(0)) + { + static_cast(_release.Signal()); + static_cast(_finished.Wait(10000)); + } + } + + [[nodiscard]] bool IsValid() const noexcept + { + return _started.IsValid() && _release.IsValid() && _finished.IsValid(); + } + + [[nodiscard]] bool WaitForStart(const DWORD timeout) const noexcept + { + return _started.Wait(timeout); + } + + [[nodiscard]] bool Release() const noexcept { return _release.Signal(); } + + [[nodiscard]] bool WaitForFinish(const DWORD timeout) const noexcept + { + return _finished.Wait(timeout); + } + + [[nodiscard]] DWORD ReleaseWaitResult() const noexcept + { + return _releaseWaitResult.load(std::memory_order_acquire); + } + + static void Notify(void* const context, const bool finished) noexcept + { + auto& barrier = *static_cast(context); + if (finished) + { + static_cast(barrier._finished.Signal()); + return; + } + + static_cast(barrier._started.Signal()); + barrier._releaseWaitResult.store( + WaitForSingleObject(barrier._release.Get(), 10000), + std::memory_order_release); + } + + private: + ScopedEvent _started; + ScopedEvent _release; + ScopedEvent _finished; + std::atomic _releaseWaitResult{WAIT_FAILED}; + }; + + class ScopedVectorPreparationHook final + { + public: + explicit ScopedVectorPreparationHook( + const VectorPreparationHookSetter setter) noexcept + : _setter(setter) + { + } + + ~ScopedVectorPreparationHook() + { + _setter(nullptr, nullptr); + } + + private: + VectorPreparationHookSetter _setter; + }; + class GdalEventSubscription final { public: @@ -625,12 +768,13 @@ namespace return S_OK; } - [[nodiscard]] bool PumpUntilGdalCompletion( + [[nodiscard]] bool PumpUntilGdalCompletionCount( GdalEventSink& sink, const LONGLONG operationId, + const std::size_t expectedCount, const std::chrono::steady_clock::time_point deadline) { - while (!sink.HasCompleted(operationId) && + while (sink.CompletionCount(operationId) < expectedCount && std::chrono::steady_clock::now() < deadline) { MSG message{}; @@ -646,7 +790,40 @@ namespace } Sleep(1); } - return sink.HasCompleted(operationId); + return sink.CompletionCount(operationId) >= expectedCount; + } + + [[nodiscard]] bool PumpUntilGdalCompletion( + GdalEventSink& sink, + const LONGLONG operationId, + const std::chrono::steady_clock::time_point deadline) + { + return PumpUntilGdalCompletionCount(sink, operationId, 1, deadline); + } + + [[nodiscard]] bool WaitForGdalDispatchMessage( + const std::chrono::steady_clock::time_point deadline) + { + MSG message{}; + while (std::chrono::steady_clock::now() < deadline) + { + if (PeekMessageW( + &message, + nullptr, + mwg::activex::kGdalDispatchMessage, + mwg::activex::kGdalDispatchMessage, + PM_NOREMOVE) != FALSE) + { + return true; + } + Sleep(1); + } + return PeekMessageW( + &message, + nullptr, + mwg::activex::kGdalDispatchMessage, + mwg::activex::kGdalDispatchMessage, + PM_NOREMOVE) != FALSE; } class CMapWinGISTestModule final : @@ -1000,12 +1177,77 @@ TEST_F(ActiveXMapTest, LoadsStackAndClearReleasesTheDatasets) EXPECT_EQ(count, 1); } +TEST_F(ActiveXMapTest, EndWaitsForOwnerThreadVectorLoadFinalization) +{ + ComPtr control; + ASSERT_EQ(_control.As(&control), S_OK); + GdalEventSubscription subscription(control.Get()); + ASSERT_EQ(subscription.Result(), S_OK); + + const std::vector rectangles{{0, 0, 2, 2}}; + const auto path = mwg::test::MakeRectanglesDataset( + _directory.Path(), + "async-end-before-dispatch.gpkg", + rectangles); + LONGLONG operationId = 0; + ASSERT_EQ(control->BeginLoadVectorDataset( + ATL::CComBSTR(path.c_str()), + &operationId), S_OK); + ASSERT_GT(operationId, 0); + + ASSERT_TRUE(WaitForGdalDispatchMessage( + std::chrono::steady_clock::now() + std::chrono::seconds(10))); + + 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_PENDING); + EXPECT_EQ(succeeded, VARIANT_FALSE); + EXPECT_EQ(cancelled, VARIANT_FALSE); + EXPECT_EQ(layerId, 0); + EXPECT_EQ(summary, nullptr); + EXPECT_EQ(diagnostics, nullptr); + + ASSERT_TRUE(PumpUntilGdalCompletion( + *subscription.Sink(), + operationId, + std::chrono::steady_clock::now() + std::chrono::seconds(10))); + EXPECT_EQ(control->EndLoadVectorDataset( + operationId, + &succeeded, + &cancelled, + &layerId, + &summary, + &diagnostics), S_OK); + std::unique_ptr summaryText( + summary, + &SysFreeString); + std::unique_ptr diagnosticText( + diagnostics, + &SysFreeString); + EXPECT_EQ(succeeded, VARIANT_TRUE); + EXPECT_EQ(cancelled, VARIANT_FALSE); + EXPECT_GT(layerId, 0); +} + TEST_F(ActiveXMapTest, LoadsVectorDatasetAsynchronouslyAndCommitsBeforeCompletionEvent) { ComPtr control; ASSERT_EQ(_control.As(&control), S_OK); GdalEventSubscription subscription(control.Get()); ASSERT_EQ(subscription.Result(), S_OK); + VectorLoadCompletionObservation observation{control.Get()}; + subscription.Sink()->SetCompletionCallback( + &VectorLoadCompletionObservation::Observe, + &observation); const std::vector rectangles{{0, 0, 2, 2}, {3, 0, 5, 2}}; const auto path = mwg::test::MakeRectanglesDataset( @@ -1026,6 +1268,33 @@ TEST_F(ActiveXMapTest, LoadsVectorDatasetAsynchronouslyAndCommitsBeforeCompletio operationId, std::chrono::steady_clock::now() + std::chrono::seconds(10))); EXPECT_TRUE(subscription.Sink()->WasDeliveredOn(std::this_thread::get_id())); + EXPECT_EQ(observation.layerCountResult, S_OK); + EXPECT_EQ(observation.featureCountResult, S_OK); + EXPECT_EQ(observation.layerCount, 1); + EXPECT_EQ(observation.featureCount, 2); + + ComPtr window; + ASSERT_EQ(control.As(&window), S_OK); + LRESULT windowMessageResult = 0; + ASSERT_TRUE(SUCCEEDED(window->OnWindowMessage( + WM_DESTROY, + 0, + 0, + &windowMessageResult))); + ASSERT_TRUE(SUCCEEDED(window->OnWindowMessage( + WM_CREATE, + 0, + 0, + &windowMessageResult))); + ASSERT_TRUE(PumpUntilGdalCompletionCount( + *subscription.Sink(), + operationId, + 2, + std::chrono::steady_clock::now() + std::chrono::seconds(10))); + EXPECT_EQ(observation.layerCountResult, S_OK); + EXPECT_EQ(observation.featureCountResult, S_OK); + EXPECT_EQ(observation.layerCount, 1); + EXPECT_EQ(observation.featureCount, 2); VARIANT_BOOL succeeded = VARIANT_FALSE; VARIANT_BOOL cancelled = VARIANT_TRUE; @@ -1155,7 +1424,17 @@ TEST_F(ActiveXMapTest, FailedVectorDatasetLoadReportsThePath) TEST_F(ActiveXMapTest, DestroyingControlDuringVectorLoadDoesNotAccessTheControlFromWorker) { + VectorPreparationBarrier barrier; + ASSERT_TRUE(barrier.IsValid()); using GetClassObject = HRESULT(STDAPICALLTYPE*)(REFCLSID, REFIID, LPVOID*); + const auto setPreparationHook = + reinterpret_cast(GetProcAddress( + _module->Get(), + "MapWinGISControlSetVectorPreparationHookForTesting")); + ASSERT_NE(setPreparationHook, nullptr); + ScopedVectorPreparationHook hookReset(setPreparationHook); + setPreparationHook(&VectorPreparationBarrier::Notify, &barrier); + const auto getClassObject = reinterpret_cast( GetProcAddress(_module->Get(), "DllGetClassObject")); ASSERT_NE(getClassObject, nullptr); @@ -1178,8 +1457,12 @@ TEST_F(ActiveXMapTest, DestroyingControlDuringVectorLoadDoesNotAccessTheControlF ATL::CComBSTR(path.c_str()), &operationId), S_OK); ASSERT_GT(operationId, 0); + ASSERT_TRUE(barrier.WaitForStart(10000)); control.Reset(); - Sleep(50); + ASSERT_TRUE(barrier.Release()); + ASSERT_TRUE(barrier.WaitForFinish(10000)); + EXPECT_EQ(barrier.ReleaseWaitResult(), WAIT_OBJECT_0); + setPreparationHook(nullptr, nullptr); } TEST_F(ActiveXMapTest, ExposesStableLayerIdsAndMapNavigation)